diff --git a/apps/desktop/src/main/bootstrap.ts b/apps/desktop/src/main/bootstrap.ts index 1500a82..b4416be 100644 --- a/apps/desktop/src/main/bootstrap.ts +++ b/apps/desktop/src/main/bootstrap.ts @@ -235,7 +235,14 @@ async function initInputIntelligence(): Promise { typo.on('corrected', () => { if (suggestion.isPresentationActive) suggestion.dismiss('stale') }) + // 제안이 켜져 있으면 오타를 조용히 고치지 않고 제안 창에 "지운 글자 → 고친 글자" 로 함께 내놓는다 + // (수락할 때만 적용 — 2026-10-17 사용자 요청). 제안이 꺼져 있을 때만 위 자동 교정이 돈다. + suggestion.setTypoProposer({ propose: (context, signal, options) => typo.propose(context, signal, options) }) telemetry.on('typed-context', (context) => { + if (suggestion.isEnabled()) { + suggestion.handleTypingContext(context) + return + } const verdict = typo.handleTypingContext(context) if (verdict === 'pass') suggestion.handleTypingContext(context) }) diff --git a/apps/desktop/src/main/ipc/suggestion-handlers.ts b/apps/desktop/src/main/ipc/suggestion-handlers.ts index 8c91ce0..9c8a9bd 100644 --- a/apps/desktop/src/main/ipc/suggestion-handlers.ts +++ b/apps/desktop/src/main/ipc/suggestion-handlers.ts @@ -58,7 +58,7 @@ export function registerSuggestionHandlers(): void { configSet('suggestionMinPrefixChars', clamp(params.minPrefixChars, 4, 40)) } if (params.maxRequestsPerMinute !== undefined) { - configSet('suggestionMaxRequestsPerMinute', clamp(params.maxRequestsPerMinute, 1, 12)) + configSet('suggestionMaxRequestsPerMinute', clamp(params.maxRequestsPerMinute, 1, 30)) } if (params.dailyBudget !== undefined) { configSet('suggestionDailyBudget', clamp(params.dailyBudget, 1, 100000)) diff --git a/apps/desktop/src/main/services/ConfigService.ts b/apps/desktop/src/main/services/ConfigService.ts index 3b8ce12..2a4241f 100644 --- a/apps/desktop/src/main/services/ConfigService.ts +++ b/apps/desktop/src/main/services/ConfigService.ts @@ -18,7 +18,7 @@ import { getLogger } from './LoggerService' const logger = getLogger('ConfigService') /** 제안/텔레메트리 튜닝 기본값의 현재 개정판. 기본값을 바꾸면 올린다. */ -const SUGGESTION_TUNING_REVISION = 6 +const SUGGESTION_TUNING_REVISION = 7 const INITIAL_SUGGESTION_TUNING = { suggestionTriggerDelayMs: 300, @@ -62,6 +62,12 @@ function migrateSuggestionTuning(activeStore: ElectronStore): void { if (!Number.isFinite(delay) || delay < 500) activeStore.set('suggestionTriggerDelayMs', 600) } + // 분당 6회는 로컬 모델(첫 후보 0.8초)에 너무 빡빡했다 — 고르고 이어 친 뒤 멈추면 rate-limited 로 안 떴다. + if (current < 7) { + const perMinute = Number(raw.suggestionMaxRequestsPerMinute) + if (!Number.isFinite(perMinute) || perMinute < 20) activeStore.set('suggestionMaxRequestsPerMinute', 20) + } + activeStore.set('suggestionTuningRevision', SUGGESTION_TUNING_REVISION) logger.info( `Migrated suggestion tuning values to revision ${SUGGESTION_TUNING_REVISION}` @@ -210,7 +216,7 @@ const CONFIG_DEFAULTS: AppConfig = { // 기본값 정본: packages/core/src/input-intelligence.ts SUGGESTION_DEFAULTS suggestionTriggerDelayMs: 600, suggestionMinPrefixChars: 8, - suggestionMaxRequestsPerMinute: 6, + suggestionMaxRequestsPerMinute: 20, suggestionDailyBudget: 500, suggestionOverlayInteractive: true, suggestionRequestTimeoutMs: 8000, diff --git a/apps/desktop/src/main/services/InputTelemetryService.ts b/apps/desktop/src/main/services/InputTelemetryService.ts index 6ebe228..c791f75 100644 --- a/apps/desktop/src/main/services/InputTelemetryService.ts +++ b/apps/desktop/src/main/services/InputTelemetryService.ts @@ -22,6 +22,7 @@ import { sql, gte, eq, desc, inArray } from 'drizzle-orm' import { INPUT_TELEMETRY_DEFAULTS, SUGGESTION_CONTEXT_MAX_CHARS, + COMPOSING_IDLE_MULTIPLIER, SUGGESTION_DEFAULTS, calculateFrictionInsight, classifyKeyStroke, @@ -637,9 +638,11 @@ class InputTelemetryService extends EventEmitter { // 제안이 영원히 요청되지 않는다(실측: debounce 로그만 반복). 그래서 // 트리거 지연을 넘긴 시점에 한 번 더 스냅샷을 돌려 게이트를 연다. if (this._settleTimer) clearTimeout(this._settleTimer) + // 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔 + // 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측 2026-10-17: "빠릿하지 않다"). const settleDelay = Math.max( - INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 300, - (configGet('suggestionTriggerDelayMs') || 1000) + 400 + INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 50, + Math.ceil((configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) * COMPOSING_IDLE_MULTIPLIER) + 60 ) this._settleTimer = setTimeout(() => { this._settleTimer = null @@ -738,8 +741,9 @@ class InputTelemetryService extends EventEmitter { context.editedSinceFocus = textForFocus !== this._textAtFocus || this._typedIntoFocus // 보내면 비워지는 칸(채팅)의 직전 내용을 "이 창에서 조금 전에 쓴 글" 로 잠시 기억한다. - // 비밀번호·편집 불가·조합 중 칸과 터미널(명령 기록)은 보지 않는다. - if (snapshot.isEditable && !snapshot.isPassword && !snapshot.isComposing && !isTerminalApp(this._foreground.appName)) { + // 비밀번호·편집 불가 칸과 터미널(명령 기록)은 보지 않는다. 조합 중인 칸도 본다 — 한글은 보내기 직전 + // 스냅샷이 거의 늘 조합 중이라, 빼면 보낸 글이 하나도 기억되지 않았다(실측 2026-10-17 에이전트 창 comp=true 연속). + if (snapshot.isEditable && !snapshot.isPassword && !isTerminalApp(this._foreground.appName)) { this._recentWrites.observe( focusKey, snapshot.text, diff --git a/apps/desktop/src/main/services/SuggestionService.ts b/apps/desktop/src/main/services/SuggestionService.ts index 33d7eae..5c940f7 100644 --- a/apps/desktop/src/main/services/SuggestionService.ts +++ b/apps/desktop/src/main/services/SuggestionService.ts @@ -12,6 +12,7 @@ import { EventEmitter } from 'events' import { + COMPOSING_IDLE_MULTIPLIER, SUGGESTION_DEFAULTS, SUGGESTION_MAX_OUTPUT_CHARS, buildLocalSuggestionCandidateEntries, @@ -33,6 +34,7 @@ import { type AnchorKind, type PhysicalRect, type SuggestionCandidate, + type SuggestionCorrection, type SuggestionPolicyInput, type SuggestionProvenance, type SuggestionSkipReason, @@ -76,6 +78,31 @@ export interface SuggestionLearningPort { expectProgrammaticInsert(text: string): () => void /** 수락한 문장을 사용자 문체 표본으로 기록한다 (학습 동의 시에만 저장됨). */ recordAccepted(text: string, meta: { appName: string | null; windowTitle: string | null }): void + /** 곧 보낼 프로그램 키 수(교정 수락의 백스페이스 등) — 입력 통계에서 뺀다. */ + expectProgrammaticKeys?(count: number): void +} + +/** + * 제안과 함께 내놓을 오타 교정을 만드는 포트 (TypoCorrectionService.propose — bootstrap 이 연결한다). + * 커서 앞 원문 끝의 originalText 를 insertText 로 바꾸는 계획을 돌려준다. + */ +export interface SuggestionTypoProposer { + propose( + context: TypingContext, + signal: AbortSignal, + options?: { thorough?: boolean } + ): Promise<{ originalText: string; insertText: string; corrections: Array<{ start: number; end: number; to: string }> } | null> +} + +/** 교정을 적용한 문맥 — 모델에는 고친 글을 보여 주고, 세션 비교는 원문으로 한다. */ +function applyCorrectionToContext(context: TypingContext, correction: SuggestionCorrection): TypingContext { + const replaceTail = (text: string): string => + text.endsWith(correction.from) ? text.slice(0, text.length - correction.from.length) + correction.to : text + return { + ...context, + prefix: replaceTail(context.prefix), + documentBefore: context.documentBefore == null ? context.documentBefore : replaceTail(context.documentBefore) + } } /** 서비스 협력자 — 기본값은 getSuggestionService() 가 연결한다 (DIP). */ @@ -98,6 +125,7 @@ export function createDefaultSuggestionServiceDeps(): SuggestionServiceDeps { }, learning: { expectProgrammaticInsert: (text) => getInputTelemetryService().expectProgrammaticInsert(text), + expectProgrammaticKeys: (count) => getInputTelemetryService().expectProgrammaticKeys(count), recordAccepted: (text, meta) => getInputTelemetryService().recordExternalText(text, { ...meta, source: 'suggestion' }) } @@ -205,6 +233,14 @@ interface ModelRequest { parse(raw: string): { candidate: SuggestionCandidate | null; rejected: string | null } /** 스트리밍 중간 표시용 텍스트 */ partial(raw: string): string + /** + * 빈 출력일 때 다시 보낼 변형 — prefill 끝에 공백을 붙여 "다음 단어부터" 쓰게 한다. + * + * 실측(2026-10-17, gemma4:e4b): "…잠시 쉬면", "…창이 나왔다가" 처럼 공백 없이 문장 중간에서 끝난 + * prefill 은 모델이 곧바로 턴을 닫아 빈 출력이 됐다(첫 후보 18회 중 15회). 끝에 공백 하나를 붙이면 + * 4문장 모두 이어 썼다. 출력 앞에 공백을 되돌려 붙여 해석하므로 이음새는 '띄어 쓰기' 가 된다. + */ + spaced?: ModelRequest } /** @@ -281,6 +317,24 @@ export class SuggestionService extends EventEmitter { private _windowHandle: number | null = null /** 이 세션의 이력 행 id — 한 세션은 한 행이다(채우기 후보·수락은 이 행을 갱신한다). */ private _sessionRecordId: string | null = null + /** 이 세션 후보가 함께 적용하는 오타 교정 */ + private _correction: SuggestionCorrection | null = null + /** 모델에 보여 준 (교정 적용) 문맥 — 채우기 루프가 같은 문맥으로 더 만든다 */ + private _promptContext: TypingContext | null = null + private _typoProposer: SuggestionTypoProposer | null = null + /** 이 세션 첫 후보가 "공백 붙인 prefill" 로 나왔다 — 채우기도 그 변형으로 보낸다 */ + private _spacedPreferred = false + /** + * 첫 후보를 못 만든 접두 — 같은 글로 멈춰 있는 동안 다시 생성하지 않는다. 실패할 때마다 다음 스냅샷이 + * 같은 글로 또 생성해 "생성 중" 창이 1초마다 떴다 꺼졌다(실측 2026-10-17). + */ + private _failedPrefix = '' + /** + * 손을 멈추자마자 먼저 띄운 "생성 중" 자리 — 생성은 아직 시작 전이다. 정책의 "표시 중"(already-visible) + * 에는 넣지 않는다: 넣으면 정작 생성 시점에 이미 떠 있다고 보고 생성하지 않는다. + */ + private _pending = false + private _pendingTimer: NodeJS.Timeout | null = null /** 요청 예산 (간격 · 분/일 카운트 · 실패 쿨다운) */ private readonly _budget: SuggestionBudget @@ -389,7 +443,7 @@ export class SuggestionService extends EventEmitter { modelId: this.resolveModel(), modelAvailable: getLocalLLMService().isAvailable(), visible: this.isVisible, - generating: this._generating, + generating: this._generating || this._pending, warmingUp: this._warmingUp, partialText: this._partialText || null, candidates: [...this._candidates], @@ -411,10 +465,16 @@ export class SuggestionService extends EventEmitter { telemetryEnabled: configGet('inputTelemetryEnabled') === true, overlayInteractive: configGet('suggestionOverlayInteractive') !== false, typoAutoCorrect: configGet('typoAutoCorrectEnabled') !== false, - provenance: this._provenance + provenance: this._provenance, + correction: this._correction } } + /** 제안 창에 오타 교정을 함께 내놓을 포트를 연결한다 (bootstrap). null 이면 교정 없이 제안만 한다. */ + setTypoProposer(proposer: SuggestionTypoProposer | null): void { + this._typoProposer = proposer + } + /** 제안 전용 모델 (설정 없으면 기본 LLM 모델). */ resolveModel(): string | null { const dedicated = configGet('suggestionModelId') @@ -605,9 +665,76 @@ export class SuggestionService extends EventEmitter { // 서버가 없을 때 "준비 중" 은 실제 준비 작업(워밍업 루프)이 돌 때만 보여준다. modelStarting: this._warmUpPromise !== null }) + if (step.action === 'generate' && this._failedPrefix && step.prefix === this._failedPrefix) { + // 방금 이 글로 첫 후보를 못 만들었다 — 더 치기 전까지 같은 생성을 되풀이하지 않는다(창 깜빡임 방지). + this._lastSkipReason = 'unchanged' + this._clearPending(true) + return + } + this._updatePresence(step, context, now) this._executeStep(step, context, config, now) } + /** + * 손을 멈춘 순간(presenceDelayMs) "생성 중" 자리를 먼저 띄운다 — 생성은 트리거 지연 뒤에 시작한다. + * 곧 생성으로 이어질 때만 띄운다(예산·모델 온기·닫기 직후·실패한 같은 글 확인). 다시 치면 거둔다. + */ + private _updatePresence(step: SuggestionStep, context: TypingContext, now: number): void { + if (step.action === 'generate') { + this._clearPending(false) + return + } + const waiting = step.action === 'settle' && (step.reason === 'debounce' || step.reason === 'composing') + if ( + waiting && + context.idleMs >= SUGGESTION_DEFAULTS.presenceDelayMs && + !this.isPresentationActive && + this._willGenerateSoon(context, now) + ) { + if (!this._pending) this._showPending(context) + return + } + this._clearPending(true) + } + + private _willGenerateSoon(context: TypingContext, now: number): boolean { + const model = this.resolveModel() + if (!model || !this._warmth.isWarm(model, now) || this._budget.isCoolingDown(now)) return false + if (now < this._userDismissedUntil) return false + const prefix = normalizeRequestPrefix(context.prefix) + if (prefix === this._failedPrefix || prefix === this._lastRequestedPrefix) return false + const config = this.readPolicyConfig() + const budget = this._budget.snapshot(now) + // 생성은 조금 뒤(트리거 지연)에 시작한다 — 그때까지 흐를 시간을 쳐서 간격을 본다. + const untilGenerate = Math.max(0, config.triggerDelayMs * COMPOSING_IDLE_MULTIPLIER - context.idleMs) + return ( + budget.sinceLastRequestMs + untilGenerate >= SUGGESTION_DEFAULTS.minIntervalMs && + budget.requestsThisMinute < config.maxRequestsPerMinute && + budget.requestsToday < config.dailyBudget + ) + } + + private _showPending(context: TypingContext): void { + this._pending = true + this._anchor = context.anchor + this._anchorKind = context.anchorKind + this._appName = context.appName + if (this._pendingTimer) clearTimeout(this._pendingTimer) + this._pendingTimer = setTimeout(() => this._clearPending(true), SUGGESTION_DEFAULTS.presenceMaxMs) + this._pendingTimer.unref?.() + this.emit('updated', this.getState()) + } + + private _clearPending(notify: boolean): void { + if (this._pendingTimer) { + clearTimeout(this._pendingTimer) + this._pendingTimer = null + } + if (!this._pending) return + this._pending = false + if (notify && !this.isPresentationActive) this.emit('updated', this.getState()) + } + private _executeStep(step: SuggestionStep, context: TypingContext, config: PolicyConfig, now: number): void { switch (step.action) { case 'end-session': @@ -877,9 +1004,9 @@ export class SuggestionService extends EventEmitter { * 미리 넣어 그 글자 바로 뒤부터 쓰게 한다. 모르는 모델이면 예전 지시형 프롬프트를 쓴다. * 두 경로 모두 같은 문맥(문서 첫머리·사실, 이 창의 앞 글, 개인 그래프)을 받는다. * - * `preferInstruct`: 다음 문장 모드의 채우기 후보는 지시형을 섞는다. prefill 은 분포가 뾰족해 - * 온도를 올려도 첫 후보와 같은 문장이 반복됐고, 지시형은 "이미 제안한 문장" 목록을 따라 다른 - * 내용을 낸다(실측). 마저 쓰기 모드에서는 지시형이 새 문장을 시작해 버려 섞지 않는다. + * 채우기 후보도 prefill 로만 만든다. 예전엔 다양성을 위해 다음 문장 모드에서 지시형을 섞었는데, + * 지시형 gemma 는 사용자 글에 "대답" 했다(실측 2026-10-17 이력: "혹시 어떤 기능을 염두에 두고 계신지 + * 설명해 주실 수 있을까요?" — 사용자 신고 "내가 쓴 것에 대한 응답만 나온다"). 후보가 덜 다양한 편이 낫다. */ private _buildModelRequest( model: string, @@ -887,7 +1014,7 @@ export class SuggestionService extends EventEmitter { context: TypingContext, memory: LocalMemoryContext, maxChars: number, - options: { avoidCandidates?: readonly string[]; preferInstruct?: boolean } = {} + options: { avoidCandidates?: readonly string[] } = {} ): ModelRequest { const now = Date.now() const recentWrites = getInputTelemetryService() @@ -919,8 +1046,7 @@ export class SuggestionService extends EventEmitter { assistantPrefix: prompt.assistantPrefix ?? '' }) - const instruct = options.preferInstruct === true && prompt.writing.mode === 'next-sentence' - if (rawPrompt !== null && !instruct) { + if (rawPrompt !== null) { const written = splitSentences(context.documentBefore ?? prefix) const extract = (raw: string) => extractContinuation(raw, { @@ -931,10 +1057,35 @@ export class SuggestionService extends EventEmitter { 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('/')}` } + 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: rawChatStopSequences(model), + 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' } @@ -1029,6 +1180,8 @@ export class SuggestionService extends EventEmitter { this._candidates = entries.map((entry, index) => entry.attachToPrefix ? { text: entry.text, rank: index, joint: 'attach' } : { text: entry.text, rank: index } ) + this._correction = null + this._promptContext = null this._activeIndex = 0 this._anchor = context.anchor this._anchorKind = context.anchorKind @@ -1118,6 +1271,8 @@ export class SuggestionService extends EventEmitter { // 후보가 오기 전에 빈 화면으로 기다리게 하지 않는다 — 즉시 자리를 잡고 // "생성 중" 을 보여준 뒤 내용으로 채운다. 실측 5초 지연에서 특히 중요하다. this._candidates = [] + this._correction = null + this._promptContext = null this._sessionRecordId = null this._activeIndex = 0 this._anchor = context.anchor @@ -1142,19 +1297,35 @@ export class SuggestionService extends EventEmitter { // 개인 그래프 문맥: (1) 과거에 그 꼬리 뒤에 실제로 이어 쓴 문장, // (2) follows/용어공유 관계로 끌어온 관련 문장. - const memory = this._collectMemoryHints(trimmedPrefix, context.appName) - const continuationHints = memory.continuationHints - // 세션의 첫 요청은 딱 1개만 청한다 — 한꺼번에 여러 개를 요청하면 느리다(사용자 - // 요청). 첫 후보를 보여준 뒤 나머지는 채우기 루프가 하나씩 순차로 더 만든다. - const request = this._buildModelRequest(model, trimmedPrefix, context, memory, maxChars) + let memory = this._collectMemoryHints(trimmedPrefix, context.appName) + let spacedPreferred = false + let correction: SuggestionCorrection | null = null + let promptContext = context let parsed: { candidate: SuggestionCandidate | null; rejected: string | null } = { candidate: null, rejected: 'empty' } try { + // 오타가 있으면 고친 글로 이어 쓴다 — 낱자 잡음("안ㄴ뇽", "ㅇ다른")이 섞인 글을 그대로 주면 모델이 + // 그 잡음까지 되풀이했다(실측 이력: "아직 ㅇ" → "아직 ㅇ 기능도…"). 교정은 수락할 때만 적용한다. + correction = await this._proposeCorrection(context, abort.signal) + 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 for (let attempt = 0; attempt < 2; attempt += 1) { - const temperature = attempt === 0 ? SUGGESTION_DEFAULTS.temperature : FILL_TEMPERATURE - const raw = await this._streamModel(request, model, temperature, abort.signal, (partial) => { + const raw = await this._streamModel(active, model, temperature, abort.signal, (partial) => { // 도착하는 대로 오버레이에 흘려보낸다 — 사용자는 "계속 생성되는" 것을 본다. // IPC 과다 방출을 막기 위해 120ms 간격으로만 보낸다. this._partialText = partial @@ -1165,15 +1336,25 @@ export class SuggestionService extends EventEmitter { } }) if (abort.signal.aborted) break - parsed = request.parse(raw) + parsed = active.parse(raw) if (!parsed.candidate) { // 진단: 왜 비었는지 모양만 남긴다(글자 내용은 남기지 않는다) — 실측 2026-10-03 카톡 10회 모두 빈 후보. - logger.debug(`제안 정제 실패: ${describeRawOutput(raw, request.raw)}`) + logger.debug(`제안 정제 실패: ${describeRawOutput(raw, active.raw)}`) + } + 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 } - if (parsed.candidate || !parsed.rejected?.startsWith('unsupported-facts')) break - logger.info(`제안 후보 버림 (${parsed.rejected}) — 한 번 더 뽑는다`) this._partialText = '' } + spacedPreferred = active !== request } catch (error) { if (!abort.signal.aborted) { this._lastSkipReason = 'generation-failed' @@ -1264,6 +1445,7 @@ export class SuggestionService extends EventEmitter { } const first = parsed.candidate + this._failedPrefix = first ? '' : this._lastRequestedPrefix if (!first) { this._lastSkipReason = 'generation-failed' logger.info(`제안 후보가 비어 있음 (모델 출력 정제 후: ${parsed.rejected ?? 'empty'})`) @@ -1290,6 +1472,9 @@ export class SuggestionService extends EventEmitter { this._budget.noteSuccess() this._partialText = '' this._candidates = [{ ...first, rank: 0 }] + this._correction = correction + this._promptContext = promptContext + this._spacedPreferred = spacedPreferred this._activeIndex = 0 this._anchor = context.anchor this._anchorKind = context.anchorKind @@ -1301,7 +1486,7 @@ export class SuggestionService extends EventEmitter { this._lastSkipReason = null this._provenance = { mode: 'local-model', - continuationCount: continuationHints.length, + continuationCount: memory.continuationHints.length, relatedCount: memory.relatedHints.length + memory.followUpHints.length, phraseCount: memory.phraseHints.length, appPhraseCount: memory.appPhraseCount @@ -1327,6 +1512,28 @@ export class SuggestionService extends EventEmitter { } } + /** 이 문맥에 함께 내놓을 오타 교정 — 포트가 없거나 실패하면 교정 없이 간다. */ + private async _proposeCorrection( + context: TypingContext, + signal: AbortSignal, + thorough = false + ): Promise { + if (!this._typoProposer) return null + try { + const plan = await this._typoProposer.propose(context, signal, { thorough }) + if (!plan || !context.prefix.endsWith(plan.originalText)) return null + const base = plan.corrections[0]?.start ?? 0 + return { + from: plan.originalText, + to: plan.insertText, + edits: plan.corrections.map((edit) => ({ start: edit.start - base, end: edit.end - base, to: edit.to })) + } + } catch (error) { + logger.debug(`제안용 오타 교정 실패 — 교정 없이 제안한다: ${error instanceof Error ? error.message : String(error)}`) + return null + } + } + // ── 채우기 루프 (2번째 이후 후보, 최대 12개) ──────────── /** @@ -1337,6 +1544,7 @@ export class SuggestionService extends EventEmitter { * 소비하지 않는다(설계). 시간 초과된 채우기 요청은 조용히 다음으로 넘어간다. */ private async _runFillLoop(token: number, context: TypingContext, maxChars: number): Promise { + await this._proposeLateCorrection(token, context) let consecutiveEmpty = 0 while ( token === this._generationToken && @@ -1354,6 +1562,28 @@ export class SuggestionService extends EventEmitter { } } + /** + * 첫 후보를 보여 준 뒤 모델 오타 검사를 한 번 더 한다 — 낱자 없는 오타("회으에서")는 첫 요청 전에 + * 묻지 않는다(멈출 때마다 0.5~1초 늦어진다). 찾으면 교정 줄을 붙이고, 남은 후보는 고친 글로 잇는다. + */ + private async _proposeLateCorrection(token: number, context: TypingContext): Promise { + if (this._correction || !this._typoProposer) return + const abort = new AbortController() + this._fillAbort = abort + try { + const late = await this._proposeCorrection(context, abort.signal, true) + if (!late || token !== this._generationToken || abort.signal.aborted) return + // 그사이 원문이 바뀌었으면(세션이 끝났으면 토큰이 달라진다) 붙이지 않는다. + if (!this._lastContext || !this._lastContext.prefix.endsWith(late.from)) return + this._correction = late + this._promptContext = applyCorrectionToContext(context, late) + this._armVisibleTtl() + this.emit('updated', this.getState()) + } finally { + if (this._fillAbort === abort) this._fillAbort = null + } + } + /** 채우기 루프 한 스텝 — 후보 1개를 요청해 고유하면 덧붙인다. */ private async _fillOne(token: number, context: TypingContext, maxChars: number): Promise { const model = this.resolveModel() @@ -1371,14 +1601,13 @@ export class SuggestionService extends EventEmitter { // 세션이 고정한 접두를 쓴다 — context.prefix 는 그사이 바뀌었을 수 있지만, // 바뀌었다면 이미 위(handleTypingContext)에서 세션이 dismiss 되어 토큰이 // 달라져 있으므로 이 루프는 다음 체크에서 멈춘다. - const prefix = this._generatedForPrefix + // 교정이 있으면 모델에는 고친 글을 보여 준다 (첫 후보와 같은 문맥). + const promptContext = this._promptContext ?? context + const prefix = normalizeSessionPrefix(promptContext.prefix) const memory = this._collectMemoryHints(prefix, context.appName) const avoidCandidates = this._candidates.map((candidate) => candidate.text) - // 홀수 번째 채우기는 (다음 문장 모드일 때) 지시형으로 — 후보 다양성. - const request = this._buildModelRequest(model, prefix, context, memory, maxChars, { - avoidCandidates, - preferInstruct: this._candidates.length % 2 === 1 - }) + const built = this._buildModelRequest(model, prefix, 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 @@ -1630,7 +1859,8 @@ export class SuggestionService extends EventEmitter { this._userDismissedUntil = Date.now() + SUGGESTION_DEFAULTS.userDismissQuietMs logger.info(`사용자가 제안을 닫음 — ${SUGGESTION_DEFAULTS.userDismissQuietMs}ms 동안 재표시하지 않는다`) } - const wasVisible = this.isPresentationActive + const wasVisible = this.isPresentationActive || this._pending + this._clearPending(false) // 진행 중이던 생성을 무효화한다 (닫았는데 잠시 뒤 결과가 다시 뜨는 것을 막는다). this._generationToken += 1 this._clearVisibleTtl() @@ -1645,6 +1875,8 @@ export class SuggestionService extends EventEmitter { this._targetTotal = 0 this._provenance = null this._sessionRecordId = null + this._correction = null + this._promptContext = null this._lastSkipReason = reason this._abort?.abort() this._abort = null @@ -1685,7 +1917,16 @@ export class SuggestionService extends EventEmitter { } // 후보는 정제 과정에서 앞 공백을 잃는다 — 커서 앞 원문의 마지막 글자를 보고 구분 공백을 // 붙인다(joinSuggestion). 세션을 닫기 전에(dismiss 가 세션 접두를 지운다) 계산한다. - const text = joinSuggestion(this._acceptPrefix(), candidate.text, candidate.joint ?? 'separate') + // 교정이 있으면 커서 앞 오타 구간을 지우고 고친 글 + 후보를 함께 넣는다. 그사이 원문 끝이 달라졌으면 + // (IME 마지막 글자 교체 등) 교정은 버리고 후보만 넣는다 — 엉뚱한 글자를 지우지 않는다. + const acceptPrefix = this._acceptPrefix() + const correction = this._correction && acceptPrefix.endsWith(this._correction.from) ? this._correction : null + const basePrefix = correction + ? acceptPrefix.slice(0, acceptPrefix.length - correction.from.length) + correction.to + : acceptPrefix + const text = (correction?.to ?? '') + joinSuggestion(basePrefix, candidate.text, candidate.joint ?? 'separate') + const deleteCount = correction?.from.length ?? 0 + const composing = this._lastContext?.isComposing === true const appName = this._appName const windowTitle = this._windowTitle const targetWindow = this._windowHandle @@ -1720,11 +1961,18 @@ export class SuggestionService extends EventEmitter { // 삽입 직후의 텍스트 스냅샷 diff 가 이 텍스트를 "타이핑" 으로 다시 학습하지 않도록 알린다. const cancelExpectedInsert = this._learning.expectProgrammaticInsert(text) const method = configGet('insertMethod') + const insertMethod = method === 'keyboard' ? 'keyboard' : 'clipboard' try { - const result = await getTextInsertService().insertText( - text, - method === 'keyboard' ? 'keyboard' : 'clipboard' - ) + if (deleteCount > 0) { + // 확정용 Space(+1)·백스페이스·붙여넣기(Ctrl, V) 키는 사용자 입력 통계에서 뺀다. + this._learning.expectProgrammaticKeys?.(deleteCount + (composing ? 2 : 0) + 2) + } + const result = + deleteCount > 0 + ? await getTextInsertService().replaceBeforeCaret(deleteCount, text, insertMethod, { + commitComposition: composing + }) + : await getTextInsertService().insertText(text, insertMethod) if (!result.success) { cancelExpectedInsert() logger.warn(`제안 삽입 실패 (method=${result.method}, len=${result.textLength})`) @@ -1736,7 +1984,12 @@ export class SuggestionService extends EventEmitter { return { ok: false, reason: 'generation-failed' } } - logger.info(`제안 수락: ${text.length}자 삽입 (method=${method === 'keyboard' ? 'keyboard' : 'clipboard'}, app=${appName ?? '-'})`) + logger.info( + `제안 수락: ${text.length}자 삽입${deleteCount > 0 ? ` (오타 교정 포함, ${deleteCount}자 교체)` : ''} ` + + `(method=${insertMethod}, app=${appName ?? '-'})` + ) + // 수락 뒤 이어 쳐서 멈추면 바로 다음 제안이 떠야 한다 — 방금 세션의 요청 간격에 걸리지 않게 푼다. + this._budget.relaxInterval(Date.now(), SUGGESTION_DEFAULTS.minIntervalMs) // 이력은 후보 원문으로 기록돼 있다 — 구분 공백이 붙은 삽입 문자열로는 찾지 못한다. // 세션 행을 알면 그 행을 수락으로 표시한다 — 텍스트로 찾으면 로컬 기억의 2번째 이후 후보는 // 행이 없어 사라지거나 같은 문구의 옛 행(다른 앱·다른 날)이 수락으로 잡혔다. @@ -1778,7 +2031,7 @@ export class SuggestionService extends EventEmitter { maxRequestsPerMinute: Math.min( configGet('suggestionMaxRequestsPerMinute') || SUGGESTION_DEFAULTS.maxRequestsPerMinute, - 12 + 30 ), dailyBudget: configGet('suggestionDailyBudget') || SUGGESTION_DEFAULTS.dailyBudget, maxCandidates: SUGGESTION_DEFAULTS.maxCandidates, diff --git a/apps/desktop/src/main/services/TextInsertService.ts b/apps/desktop/src/main/services/TextInsertService.ts index 5ef70b2..0207294 100644 --- a/apps/desktop/src/main/services/TextInsertService.ts +++ b/apps/desktop/src/main/services/TextInsertService.ts @@ -97,10 +97,22 @@ export class TextInsertService extends EventEmitter { * 커서를 옮기지 않고 백스페이스로만 지운다 — 앱마다 다른 단어 이동/선택 동작에 기대지 않는다. * 다른 삽입과 같은 직렬화 꼬리를 탄다(클립보드 save/restore 가 엇갈리지 않게). */ - replaceBeforeCaret(deleteCount: number, text: string, method: InsertMethod = 'clipboard'): Promise { + replaceBeforeCaret( + deleteCount: number, + text: string, + method: InsertMethod = 'clipboard', + options: { commitComposition?: boolean } = {} + ): Promise { const run = this._tail.then(async () => { try { - await this._keyboard.backspace(deleteCount) + let count = deleteCount + // 커서 앞 글자가 IME 조합 중이면 먼저 확정한다 (Space → 남은 공백까지 지운다). + if (options.commitComposition && this._keyboard.commitComposition) { + await this._keyboard.commitComposition() + await this._sleep(15) + count += 1 + } + await this._keyboard.backspace(count) } catch (error) { throw error instanceof D3ROError ? error diff --git a/apps/desktop/src/main/services/TypoCorrectionService.ts b/apps/desktop/src/main/services/TypoCorrectionService.ts index 3c9ba47..41b6809 100644 --- a/apps/desktop/src/main/services/TypoCorrectionService.ts +++ b/apps/desktop/src/main/services/TypoCorrectionService.ts @@ -8,6 +8,10 @@ // core validateModelCorrections 로 다시 거른 것만 교체. // 3) 교체는 "커서 앞 N 글자 백스페이스 → 고친 구간 붙여넣기" 한 번이다. // +// 제안이 켜져 있으면 조용히 고치지 않는다 — propose() 가 교정을 만들어 제안 창에 "지운 글자 → 고친 +// 글자" 로 함께 보여 주고, 사용자가 수락할 때만 적용한다(2026-10-17 사용자 요청). 위 자동 교정은 제안이 +// 꺼져 있을 때만 쓴다(bootstrap 배선). +// // 안전장치: 멈춤(유휴 600ms) 뒤에만, 스냅샷 뒤 사용자가 한 키라도 더 쳤으면 취소, 포그라운드 창이 // 바뀌었으면 취소, 터미널·에디터·제외 앱·비밀번호·선택·조합 중에는 하지 않는다. 사용자가 교정을 // 되돌리면 그 단어는 무시 목록에 올려 다시 고치지 않는다. @@ -21,8 +25,11 @@ import { TYPO_MIN_IDLE_MS, TYPO_REVERT_WINDOW_MS, buildVocabulary, + detectJamoNoise, detectTypoRevert, detectTypos, + hasSuspiciousTypo, + mergeTypoCorrections, parseModelTypoPairs, planTypoReplacement, tokenizeWords, @@ -46,6 +53,8 @@ const MODEL_CHECK_TIMEOUT_MS = 2500 const MODEL_CHECK_MAX_TOKENS = 48 /** 개인 어휘 캐시 수명 */ const VOCABULARY_TTL_MS = 60_000 +/** 제안용 모델 검사 응답 제한 — 제안 첫 후보가 그만큼 늦어진다. */ +const PROPOSAL_CHECK_TIMEOUT_MS = 1500 /** 모델 검사 최소 구간 길이 (글자) */ const MODEL_CHECK_MIN_CHARS = 6 @@ -182,6 +191,69 @@ export class TypoCorrectionService extends EventEmitter { return 'checking' } + /** + * 제안 창에 함께 내놓을 교정을 만든다 — 적용하지 않는다. + * + * 결정적 규칙(한영 전환·늘 틀린 철자·개인 어휘·낱자 잡음)은 늘 보고, 모델은 구간이 수상할 때 + * (낱자가 섞인 한글 단어·드문 음절)만 묻는다 — 멈출 때마다 묻으면 제안이 그만큼 늦는다. + * 사용자가 고르는 제안이라 자동 교정보다 넓게 본다: 학습 제외 앱(에이전트 창 등)도 보되, + * 명령을 치는 터미널과 사용자 제외 앱은 뺀다. + * + * `thorough`: 수상한 흔적이 없어도 끝난 단어가 둘 이상이면 모델에 묻는다 — 첫 후보를 보여 준 뒤 + * 백그라운드에서 쓴다("회으에서", "괜찬으세요" 처럼 낱자 없는 오타는 수상함 판정에 걸리지 않는다). + */ + async propose( + context: TypingContext, + signal: AbortSignal, + options: { thorough?: boolean } = {} + ): Promise { + if (!this.isEnabled()) return null + if (!context.available || !context.isEditable || context.isPassword || context.hasSelection) return null + if (isTerminalApp(context.appName)) return null + if (context.appName && isAppExcluded(context.appName, configGet('inputExcludedApps'))) return null + + const prefix = context.prefix + const region = prefix.slice(typoRegionStart(prefix)) + if (!region.trim()) return null + + const ignoredWords = configGet('typoIgnoredWords') ?? [] + const vocabulary = this._loadVocabulary() + const deterministic = mergeTypoCorrections( + detectTypos(prefix, { includeTrailingToken: true, ignoredWords, vocabulary: vocabulary.latin }), + detectJamoNoise(prefix, { ignoredWords }) + ) + + let fromModel: TypoCorrection[] = [] + const model = configGet('typoAutoCorrectUseModel') !== false ? this._deps.warmModel() : null + const worthAsking = hasSuspiciousTypo(region) || (options.thorough === true && this._worthModelCheck(region)) + if (model && worthAsking) { + const abort = new AbortController() + const forward = (): void => abort.abort() + signal.addEventListener('abort', forward, { once: true }) + const timer = setTimeout(() => abort.abort(), PROPOSAL_CHECK_TIMEOUT_MS) + timer.unref?.() + try { + fromModel = await this._askModel(model, prefix, abort.signal, ignoredWords, vocabulary.known) + } catch (error) { + if (!abort.signal.aborted) { + logger.debug(`제안용 오타 검사 실패: ${error instanceof Error ? error.message : String(error)}`) + } + } finally { + clearTimeout(timer) + signal.removeEventListener('abort', forward) + } + } + if (signal.aborted) return null + + // 모델이 같은 단어를 더 잘 고쳤으면(안ㄴ뇽 → 안녕) 낱자 지우기(안뇽)보다 앞선다. + const plan = planTypoReplacement(prefix, mergeTypoCorrections(fromModel, deterministic)) + if (plan) { + const sources = [...new Set(plan.corrections.map((correction) => correction.source))].join(',') + logger.info(`제안에 오타 교정 ${plan.corrections.length}건 포함 (${sources}, app=${context.appName ?? '-'})`) + } + return plan + } + /** 설정에서 끌 때·종료할 때 */ dispose(): void { this._cancelCheck() @@ -242,26 +314,8 @@ export class TypoCorrectionService extends EventEmitter { let corrected = false try { const prefix = context.prefix - const region = prefix.slice(typoRegionStart(prefix)) - const writing = analyzeWritingContext(prefix.slice(0, typoRegionStart(prefix))) - const { systemPrompt, text } = buildTypoCheckPrompt({ - sentence: region, - previous: [writing.earlierText, writing.lastSentence, writing.currentSentence].filter(Boolean).join(' ') - }) - let raw = '' - for await (const chunk of this._deps.generate(text, { - model, - systemPrompt, - maxTokens: MODEL_CHECK_MAX_TOKENS, - signal: abort.signal - })) { - if (abort.signal.aborted) break - raw += chunk - if (raw.length > 400) break - } + const corrections = await this._askModel(model, prefix, abort.signal, ignoredWords, knownWords) if (abort.signal.aborted || this._check?.abort !== abort) return - - const corrections = validateModelCorrections(prefix, parseModelTypoPairs(raw), { ignoredWords, knownWords }) const plan = planTypoReplacement(prefix, corrections) if (!plan) return // 검사하는 사이 사용자가 더 쳤으면 접두가 달라져 위에서 취소됐다. 여기서 한 번 더 키를 본다. @@ -281,6 +335,30 @@ export class TypoCorrectionService extends EventEmitter { } } + /** 지금 문장의 오타를 모델에 묻고, core 규칙으로 다시 거른 교정만 돌려준다. */ + private async _askModel( + model: string, + prefix: string, + signal: AbortSignal, + ignoredWords: readonly string[], + knownWords: ReadonlySet + ): Promise { + const region = prefix.slice(typoRegionStart(prefix)) + const writing = analyzeWritingContext(prefix.slice(0, typoRegionStart(prefix))) + const { systemPrompt, text } = buildTypoCheckPrompt({ + sentence: region, + previous: [writing.earlierText, writing.lastSentence, writing.currentSentence].filter(Boolean).join(' ') + }) + let raw = '' + for await (const chunk of this._deps.generate(text, { model, systemPrompt, maxTokens: MODEL_CHECK_MAX_TOKENS, signal })) { + if (signal.aborted) break + raw += chunk + if (raw.length > 400) break + } + if (signal.aborted) return [] + return validateModelCorrections(prefix, parseModelTypoPairs(raw), { ignoredWords, knownWords }) + } + private _cancelCheck(): void { if (!this._check) return this._check.abort.abort() diff --git a/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts b/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts index 07676d7..22bf20e 100644 --- a/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts +++ b/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts @@ -16,6 +16,11 @@ export interface KeyboardPort { type(text: string): Promise /** 커서 앞 글자를 count 번 지운다 (오타 교정) */ backspace(count: number): Promise + /** + * IME 가 조합 중인 글자를 확정시키고 공백 하나를 남긴다 (실제 Space 키) — 조합 중에 백스페이스를 보내면 + * 글자가 아니라 낱자가 지워져(여 → ㅇ) 지울 개수가 어긋난다. 호출자는 남은 공백까지 지운다 (선택). + */ + commitComposition?(): Promise /** 네이티브 키 모듈을 미리 불러 둔다 — 첫 삽입이 로딩을 기다리지 않게 (선택) */ preload?(): Promise } @@ -98,6 +103,11 @@ export class NutKeyboardPort implements KeyboardPort { await nut.native.type(text) } + async commitComposition(): Promise { + const nut = await this._ensureNut() + await nut.native.click(nut.Key.Space) + } + /** 백스페이스를 count 번 — 키마다 네이티브 keyTap 한 번이다. */ async backspace(count: number): Promise { if (count <= 0) return diff --git a/apps/desktop/src/main/windows/WindowManager.ts b/apps/desktop/src/main/windows/WindowManager.ts index 2ea7bb3..e6af338 100644 --- a/apps/desktop/src/main/windows/WindowManager.ts +++ b/apps/desktop/src/main/windows/WindowManager.ts @@ -5,7 +5,7 @@ import { app, BrowserWindow, screen, ipcMain, Menu, clipboard } from 'electron' import { join } from 'path' import { is } from '@electron-toolkit/utils' import { WINDOW_SIZE } from '@d3ro/core/constants' -import type { AnchorKind, PhysicalRect } from '@d3ro/core/input-intelligence' +import type { AnchorKind, PhysicalRect, SuggestionCorrection } from '@d3ro/core/input-intelligence' import { fitAnchoredPanel, placeAnchoredPanel, @@ -108,6 +108,7 @@ function getPopupI18nStrings(): Record { // 키 힌트 줄 (동작 낱말 — 실제 키는 사용자 바인딩에서 매번 계산해 붙인다) suggestionHintMoveLabel: t('popup.suggestion.hintMove'), suggestionHintAcceptLabel: t('popup.suggestion.hintAccept'), + suggestionCorrectionLabel: t('popup.suggestion.correctionLabel'), suggestionHintCloseLabel: t('popup.suggestion.hintDismiss'), suggestionHintGeneratingMore: t('popup.suggestion.hintGeneratingMore'), } @@ -845,6 +846,8 @@ interface SuggestionOverlayContent { /** 스트리밍 중 부분 텍스트 */ partialText?: string | null provenance?: SuggestionOverlayProvenance | null + /** 후보와 함께 적용되는 오타 교정 — 팝업이 "지운 글자 → 고친 글자" 줄을 그린다 */ + correction?: SuggestionCorrection | null } /** 현재 세션의 배치(최대 높이 기준) — 내용이 바뀌면 이 자리에서 높이만 맞춘다. */ @@ -872,7 +875,8 @@ function fitSuggestionOverlay(win: BrowserWindow, content: SuggestionOverlayCont activeIndex: content.activeIndex, generating: content.generating === true, warmingUp: content.warmingUp === true, - hasPartialText: !!content.partialText + hasPartialText: !!content.partialText, + hasCorrection: !!content.correction }) ) const previous = suggestionOverlayBounds @@ -921,6 +925,7 @@ export function showSuggestionOverlay( partialText: payload.partialText ?? null, appName: payload.appName, provenance: payload.provenance ?? null, + correction: payload.correction ?? null, _i18n: getPopupI18nStrings(), _keyHints: buildSuggestionKeyHints() })) diff --git a/apps/desktop/src/main/windows/suggestion-overlay-geometry.ts b/apps/desktop/src/main/windows/suggestion-overlay-geometry.ts index 3fba2c1..7042f18 100644 --- a/apps/desktop/src/main/windows/suggestion-overlay-geometry.ts +++ b/apps/desktop/src/main/windows/suggestion-overlay-geometry.ts @@ -18,14 +18,16 @@ const PANEL_PADDING = 6 // .suggestion-panel padding const STATUS_HEIGHT = 32 // .status height const ITEM_HEIGHT = 44 // .suggestion-item height const ITEM_GAP = 2 // .candidates gap +/** .correction: height 26 + margin-bottom 2, 그리고 뒤 후보와의 .candidates gap 2 */ +const CORRECTION_HEIGHT = 26 + 2 + ITEM_GAP /** .footer: margin-top 6 + border-top 1 + padding-top 6 + 행 14 + gap 5 + 키 안내 16 + padding-bottom 2 */ const FOOTER_HEIGHT = 6 + 1 + 6 + 14 + 5 + 16 + 2 const CHROME_HEIGHT = 2 * (ROOT_PADDING + PANEL_BORDER + PANEL_PADDING) -/** 한 페이지(3개) + 진행률/키 안내 — 가장 큰 패널이자 창 최대 높이 (= 208). */ +/** 교정 줄 + 한 페이지(3개) + 진행률/키 안내 — 가장 큰 패널이자 창 최대 높이 (= 238). */ export const SUGGESTION_OVERLAY_MAX_HEIGHT = - CHROME_HEIGHT + PAGE_SIZE * ITEM_HEIGHT + (PAGE_SIZE - 1) * ITEM_GAP + FOOTER_HEIGHT + CHROME_HEIGHT + CORRECTION_HEIGHT + PAGE_SIZE * ITEM_HEIGHT + (PAGE_SIZE - 1) * ITEM_GAP + FOOTER_HEIGHT export interface SuggestionPanelLayoutInput { candidateCount: number @@ -34,6 +36,8 @@ export interface SuggestionPanelLayoutInput { warmingUp: boolean /** 스트리밍 중인 부분 텍스트가 있는가 */ hasPartialText: boolean + /** 오타 교정 줄이 보이는가 (후보가 있을 때만 그린다) */ + hasCorrection?: boolean } /** 지금 그려지는 패널(+root 패딩) 높이 — script.js render() 와 같은 규칙으로 센다. */ @@ -55,6 +59,7 @@ export function suggestionPanelHeight(input: SuggestionPanelLayoutInput): number (busy ? STATUS_HEIGHT : 0) + items * ITEM_HEIGHT + Math.max(0, items - 1) * ITEM_GAP + + (count > 0 && input.hasCorrection ? CORRECTION_HEIGHT : 0) + (count > 0 ? FOOTER_HEIGHT : 0) return Math.min(height, SUGGESTION_OVERLAY_MAX_HEIGHT) } diff --git a/apps/desktop/src/main/windows/suggestion-overlay-presenter.ts b/apps/desktop/src/main/windows/suggestion-overlay-presenter.ts index 54ced22..2fb365d 100644 --- a/apps/desktop/src/main/windows/suggestion-overlay-presenter.ts +++ b/apps/desktop/src/main/windows/suggestion-overlay-presenter.ts @@ -18,7 +18,7 @@ import { /** 오버레이 내용 — show 와 update 가 같이 쓴다 */ export type SuggestionOverlayContentPayload = Pick< SuggestionState, - 'candidates' | 'activeIndex' | 'targetTotal' | 'generating' | 'warmingUp' | 'partialText' | 'provenance' + 'candidates' | 'activeIndex' | 'targetTotal' | 'generating' | 'warmingUp' | 'partialText' | 'provenance' | 'correction' > /** 새로 띄울 때만 필요한 배치 정보를 더한 payload */ @@ -38,6 +38,7 @@ export function toSuggestionOverlayContent(state: SuggestionState): SuggestionOv warmingUp: state.warmingUp, partialText: state.partialText, provenance: state.provenance, + correction: state.correction, } } diff --git a/apps/desktop/src/renderer/popups/suggestion-overlay/script.js b/apps/desktop/src/renderer/popups/suggestion-overlay/script.js index 874609c..7ba6f76 100644 --- a/apps/desktop/src/renderer/popups/suggestion-overlay/script.js +++ b/apps/desktop/src/renderer/popups/suggestion-overlay/script.js @@ -35,6 +35,8 @@ var provenance = null var i18nStrings = {} var keyHints = null + /** 후보와 함께 적용되는 오타 교정 { from, to, edits:[{start,end,to}] } */ + var correction = null var generatingSince = 0 var tickTimer = null @@ -70,6 +72,8 @@ return } + if (correction) candidatesContainer.appendChild(buildCorrectionRow(correction)) + var page = Math.floor(activeIndex / PAGE_SIZE) var pageStart = page * PAGE_SIZE var pageEnd = Math.min(pageStart + PAGE_SIZE, candidates.length) @@ -105,9 +109,45 @@ body.textContent = text item.appendChild(num) item.appendChild(body) + // 교정이 있으면 후보 앞에 고친 글 끝부분을 강조해 붙인다 — "이렇게 고친 뒤 이어진다" 를 보여 준다. + if (correction && tag === 'button') { + var lead = document.createElement('span') + lead.className = 'corrected' + var tail = correction.to.replace(/\s+$/, '') + lead.textContent = (tail.length > 18 ? '…' + tail.slice(-18) : tail) + ' ' + body.insertBefore(lead, body.firstChild) + } return item } + /** "고침 | 지운 글자 → 고친 글자" 한 줄 — 바뀐 단어만 보여 준다. */ + function buildCorrectionRow(value) { + var row = document.createElement('div') + row.className = 'correction' + var label = document.createElement('span') + label.className = 'correction-label' + label.textContent = i18nStrings.suggestionCorrectionLabel || '' + row.appendChild(label) + var diff = document.createElement('span') + diff.className = 'correction-diff' + var edits = value.edits && value.edits.length ? value.edits : [{ start: 0, end: value.from.length, to: value.to }] + for (var i = 0; i < edits.length; i++) { + if (i > 0) diff.appendChild(document.createTextNode(', ')) + var removed = document.createElement('del') + removed.textContent = value.from.slice(edits[i].start, edits[i].end).trim() || '␣' + var arrow = document.createElement('span') + arrow.className = 'correction-arrow' + arrow.textContent = '→' + var added = document.createElement('ins') + added.textContent = edits[i].to || '∅' + diff.appendChild(removed) + diff.appendChild(arrow) + diff.appendChild(added) + } + row.appendChild(diff) + return row + } + function renderProgress() { if (!progressContainer) return progressContainer.textContent = '' @@ -211,6 +251,7 @@ if (payload.warmingUp !== undefined) warmingUp = payload.warmingUp === true if (payload.partialText !== undefined) partialText = payload.partialText || null if (payload.provenance !== undefined) provenance = payload.provenance || null + if (payload.correction !== undefined) correction = payload.correction || null } function startTick() { @@ -254,6 +295,7 @@ warmingUp = false partialText = null provenance = null + correction = null candidates = [] activeIndex = 0 targetTotal = 0 diff --git a/apps/desktop/src/renderer/popups/suggestion-overlay/style.css b/apps/desktop/src/renderer/popups/suggestion-overlay/style.css index e9a4b3c..effd3b8 100644 --- a/apps/desktop/src/renderer/popups/suggestion-overlay/style.css +++ b/apps/desktop/src/renderer/popups/suggestion-overlay/style.css @@ -299,3 +299,55 @@ kbd { line-height: 1; min-width: 0; } + +/* ── 오타 교정 (후보와 함께 적용된다) — 지운 글자는 취소선, 고친 글자는 강조. 높이 26px 고정 ── */ +.correction { + display: flex; + align-items: center; + gap: 6px; + height: 26px; + margin-bottom: 2px; + padding: 0 28px 0 8px; + overflow: hidden; + white-space: nowrap; + font-size: 12px; + color: var(--d3-text-secondary); +} + +.correction-label { + flex: 0 0 auto; + padding: 1px 6px; + border-radius: 4px; + background: var(--d3-accent-dim); + color: var(--d3-accent-main); + font-size: 11px; + font-weight: 600; +} + +.correction-diff { + overflow: hidden; + text-overflow: ellipsis; +} + +.correction del { + color: var(--d3-status-danger); + text-decoration: line-through; + opacity: 0.85; +} + +.correction ins { + color: var(--d3-accent-main); + text-decoration: none; + font-weight: 600; +} + +.correction-arrow { + margin: 0 3px; + opacity: 0.7; +} + +/* 후보 앞에 붙는 고친 글 — 이 글자들로 바뀐 뒤 후보가 이어진다는 표시 */ +.suggestion-text .corrected { + color: var(--d3-accent-main); + font-weight: 600; +} diff --git a/apps/desktop/tests/main/ipc/suggestion-handlers.test.ts b/apps/desktop/tests/main/ipc/suggestion-handlers.test.ts index 07c461c..e0c2f29 100644 --- a/apps/desktop/tests/main/ipc/suggestion-handlers.test.ts +++ b/apps/desktop/tests/main/ipc/suggestion-handlers.test.ts @@ -54,13 +54,13 @@ describe('SUGGESTION.SET_CONFIG', () => { expect(configSet).not.toHaveBeenCalledWith('suggestionEnabled', true) }) - it('분당 요청 상한을 12로 강제한다', async () => { + it('분당 요청 상한을 30으로 강제한다', async () => { const handler = handlers.get(IPC_CHANNELS.SUGGESTION.SET_CONFIG) if (!handler) throw new Error('suggestion config handler was not registered') await handler({}, { maxRequestsPerMinute: 99 }) - expect(configSet).toHaveBeenCalledWith('suggestionMaxRequestsPerMinute', 12) + expect(configSet).toHaveBeenCalledWith('suggestionMaxRequestsPerMinute', 30) }) }) diff --git a/apps/desktop/tests/main/services/ConfigService.test.ts b/apps/desktop/tests/main/services/ConfigService.test.ts index 40702c7..d2af843 100644 --- a/apps/desktop/tests/main/services/ConfigService.test.ts +++ b/apps/desktop/tests/main/services/ConfigService.test.ts @@ -48,9 +48,9 @@ describe('ConfigService suggestion tuning migration', () => { ) await initConfigService() - expect(configGet('suggestionTuningRevision')).toBe(6) + expect(configGet('suggestionTuningRevision')).toBe(7) expect(configGet('suggestionTriggerDelayMs')).toBe(600) - expect(configGet('suggestionMaxRequestsPerMinute')).toBe(6) + expect(configGet('suggestionMaxRequestsPerMinute')).toBe(20) expect(configGet('suggestionMinPrefixChars')).toBe(17) expect(configGet('suggestionDailyBudget')).toBe(777) expect(configGet('suggestionRequestTimeoutMs')).toBe(23000) @@ -114,7 +114,7 @@ describe('ConfigService suggestion tuning migration', () => { // 옮기지 않는 액션은 그대로 남는다. expect(bindings['suggestion-next']).toEqual(OLD_NEXT) expect(bindings['suggestion-prev']).toEqual(OLD_PREV) - expect(configGet('suggestionTuningRevision')).toBe(6) + expect(configGet('suggestionTuningRevision')).toBe(7) resetInMemoryConfig() }) @@ -176,7 +176,7 @@ describe('ConfigService suggestion tuning migration', () => { '../../../src/main/services/ConfigService' ) await initConfigService() - expect(configGet('suggestionTuningRevision')).toBe(6) + expect(configGet('suggestionTuningRevision')).toBe(7) expect(configGet('suggestionTriggerDelayMs')).toBe(expected) resetInMemoryConfig() vi.doUnmock('electron-store') diff --git a/apps/desktop/tests/main/services/TypoCorrectionService.test.ts b/apps/desktop/tests/main/services/TypoCorrectionService.test.ts index f1c2fc2..9a52054 100644 --- a/apps/desktop/tests/main/services/TypoCorrectionService.test.ts +++ b/apps/desktop/tests/main/services/TypoCorrectionService.test.ts @@ -263,3 +263,59 @@ describe('TypoCorrectionService', () => { expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('dkssudgktpdy'.length, '안녕하세요') }) }) + +describe('TypoCorrectionService.propose — 제안 창에 함께 내놓을 교정 (적용하지 않음)', () => { + beforeEach(() => { + config.typoAutoCorrectEnabled = true + config.typoAutoCorrectUseModel = true + config.typoIgnoredWords = [] + config.inputExcludedApps = [] + }) + + it('수상한 구간이면 모델에 묻고, 고친 계획만 돌려준다 — 대상 앱에는 아무것도 보내지 않는다', async () => { + const generate = vi.fn(async function* () { + yield '안ㄴ뇽하세여 => 안녕하세요' + }) + const fake = deps({ warmModel: () => 'gemma4:e4b', generate }) + const service = new TypoCorrectionService(fake.deps) + + const plan = await service.propose( + typingContext({ prefix: '안ㄴ뇽하세여.?', appName: 'Agent Switchboard.exe' }), + new AbortController().signal + ) + + expect(plan?.insertText).toBe('안녕하세요.?') + expect(plan?.originalText).toBe('안ㄴ뇽하세여.?') + expect(generate).toHaveBeenCalledTimes(1) + expect(fake.replaceBeforeCaret).not.toHaveBeenCalled() + }) + + it('수상하지 않으면 모델에 묻지 않는다 (제안이 늦어지지 않게)', async () => { + const generate = vi.fn(async function* () { + yield '없음' + }) + const service = new TypoCorrectionService(deps({ warmModel: () => 'gemma4:e4b', generate }).deps) + + const plan = await service.propose(typingContext({ prefix: '오늘 회의 자료 공유드립니다 ' }), new AbortController().signal) + + expect(plan).toBeNull() + expect(generate).not.toHaveBeenCalled() + }) + + it('모델이 없어도 낱자 잡음은 결정적으로 지운다', async () => { + const service = new TypoCorrectionService(deps().deps) + const plan = await service.propose(typingContext({ prefix: '그ㅓ런건 전혀 ' }), new AbortController().signal) + expect(plan?.insertText).toBe('그런건 전혀 ') + }) + + it('터미널·제외 앱·꺼진 설정에서는 내놓지 않는다', async () => { + const service = new TypoCorrectionService(deps().deps) + const signal = new AbortController().signal + expect(await service.propose(typingContext({ prefix: '그ㅓ런건 ', appName: 'WindowsTerminal.exe' }), signal)).toBeNull() + config.inputExcludedApps = ['slack'] + expect(await service.propose(typingContext({ prefix: '그ㅓ런건 ' }), signal)).toBeNull() + config.inputExcludedApps = [] + config.typoAutoCorrectEnabled = false + expect(await service.propose(typingContext({ prefix: '그ㅓ런건 ' }), signal)).toBeNull() + }) +}) diff --git a/apps/desktop/tests/main/services/input-intelligence.test.ts b/apps/desktop/tests/main/services/input-intelligence.test.ts index d1ffc0b..4853ef7 100644 --- a/apps/desktop/tests/main/services/input-intelligence.test.ts +++ b/apps/desktop/tests/main/services/input-intelligence.test.ts @@ -581,8 +581,8 @@ describe('개인 문구', () => { describe('기본값 (실측 근거)', () => { it('자동 제안의 요청 상한은 보수적 기본 정책을 지킨다', () => { expect(SUGGESTION_DEFAULTS.triggerDelayMs).toBe(600) - expect(SUGGESTION_DEFAULTS.minIntervalMs).toBe(5000) - expect(SUGGESTION_DEFAULTS.maxRequestsPerMinute).toBe(6) + expect(SUGGESTION_DEFAULTS.minIntervalMs).toBe(1200) + expect(SUGGESTION_DEFAULTS.maxRequestsPerMinute).toBe(20) expect(SUGGESTION_DEFAULTS.dailyBudget).toBe(500) expect(SUGGESTION_DEFAULTS.maxCandidates).toBe(3) expect(SUGGESTION_DEFAULTS.maxOutputTokens).toBe(64) diff --git a/apps/desktop/tests/main/services/suggestion-presence.test.ts b/apps/desktop/tests/main/services/suggestion-presence.test.ts new file mode 100644 index 0000000..8d7c286 --- /dev/null +++ b/apps/desktop/tests/main/services/suggestion-presence.test.ts @@ -0,0 +1,216 @@ +// 제안 창 반응성 — 빈 출력 재시도, 실패한 같은 글 재생성 방지, 멈추자마자 "생성 중" 자리 (2026-10-17) +// +// 실측: 문장 중간에서 공백 없이 끝난 prefill 은 gemma 가 곧바로 턴을 닫아 빈 출력이 됐고(18회 중 15회), 빈 출력마다 +// 창을 닫은 뒤 같은 글로 1초마다 다시 생성해 "떴다 꺼졌다" 를 반복했다. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const config = vi.hoisted(() => ({ + suggestionEnabled: true as boolean, + suggestionModelId: 'gemma4:e4b' as string | null, + llmModelId: 'gemma4:e4b' as string | null, + inputExcludedApps: [] as string[], + suggestionTriggerDelayMs: 600, + suggestionMinPrefixChars: 4, + suggestionMaxRequestsPerMinute: 20, + suggestionDailyBudget: 500, + suggestionRequestTimeoutMs: 8000, + inputLearnTypedText: false, + inputTelemetryEnabled: false, + suggestionOverlayInteractive: true, + insertMethod: 'clipboard' +})) +const harness = vi.hoisted(() => ({ + streamGenerate: vi.fn(), + insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })), + replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({ + success: true, + method: 'clipboard', + textLength: text.length + })) +})) + +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: keyof typeof config) => config[key]), + configSet: vi.fn() +})) +vi.mock('../../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) +})) +vi.mock('../../../src/main/services/LocalLLMService', () => ({ + getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate }) +})) +vi.mock('../../../src/main/services/InputTelemetryService', () => ({ + getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] }) +})) +vi.mock('../../../src/main/services/PersonalGraphService', () => ({ + getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) }) +})) +vi.mock('../../../src/main/services/TextInsertService', () => ({ + getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) +})) +vi.mock('../../../src/main/services/modifier-state', () => ({ waitForModifiersReleased: async () => true })) +vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) +vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) +vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) + +import { + SuggestionService, + type SuggestionServiceDeps +} from '../../../src/main/services/SuggestionService' +import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget' +import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker' +import type { TypingContext } from '../../../src/main/services/InputTelemetryService' + +const PREFIX = '지금 테스트 해보는데 잠시 쉬면' + +function typingContext(overrides: Partial = {}): TypingContext { + const prefix = overrides.prefix ?? PREFIX + return { + prefix, + fullText: prefix, + caretOffset: prefix.length, + documentBefore: prefix, + anchor: { x: 10, y: 10, width: 2, height: 16 }, + anchorKind: 'caret', + isPassword: false, + isEditable: true, + isComposing: false, + hasSelection: false, + available: true, + appName: 'notepad.exe', + windowTitle: 'notes', + windowHandle: null, + idleMs: 2000, + capturedAt: Date.now(), + editedSinceFocus: true, + typedRecently: true, + ...overrides + } +} + +function deps(): SuggestionServiceDeps { + const warmth = new ModelWarmTracker() + warmth.noteWarm('gemma4:e4b', Date.now() + 600_000) + return { + repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) }, + budget: new SuggestionBudget(), + warmth, + foreground: { currentWindowHandle: () => null }, + learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: vi.fn() } + } +} + +interface Internal { + _generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise + _lastContext: TypingContext | null + _lastRequestAt: number +} + +let services: SuggestionService[] = [] +function create(): SuggestionService { + const service = new SuggestionService(deps()) + services.push(service) + return service +} + +beforeEach(() => { + harness.streamGenerate.mockReset() +}) + +afterEach(() => { + for (const service of services) service.dispose() + services = [] + vi.useRealTimers() +}) + +describe('빈 출력 재시도', () => { + it('모델이 곧바로 턴을 닫으면 prefill 끝에 공백을 붙여 한 번 더 뽑고, 띄어 쓴 후보로 쓴다', async () => { + harness.streamGenerate.mockImplementation(async function* (prompt: string) { + yield prompt.endsWith(' ') ? '렉 걸리는 느낌이 있어.' : '' + }) + const service = create() + ;(service as unknown as Internal)._lastContext = typingContext() + await (service as unknown as Internal)._generate(PREFIX, typingContext(), 3, 160) + + const prompts = harness.streamGenerate.mock.calls.map(([prompt]) => String(prompt)) + expect(prompts[0].endsWith(PREFIX)).toBe(true) + expect(prompts[1].endsWith(`${PREFIX} `)).toBe(true) + expect(service.getState().candidates[0]).toEqual({ text: '렉 걸리는 느낌이 있어.', rank: 0 }) + // 채우기도 공백 붙인 변형으로 보낸다 + await vi.waitFor(() => expect(harness.streamGenerate.mock.calls.length).toBeGreaterThan(2)) + expect(String(harness.streamGenerate.mock.calls[2][0]).endsWith(`${PREFIX} `)).toBe(true) + }) + + it('끝내 비면 창을 닫고, 같은 글로 멈춰 있는 동안 다시 생성하지 않는다 (더 치면 다시 한다)', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield '' + }) + const service = create() + const context = typingContext() + service.handleTypingContext(context) + await vi.waitFor(() => expect(harness.streamGenerate).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(service.getState().generating).toBe(false)) + + // 같은 글의 다음 스냅샷들 — 1.2초 간격이 지나도 다시 생성하지 않는다 + vi.useFakeTimers({ now: Date.now() + 5000 }) + service.handleTypingContext({ ...context, idleMs: 7000 }) + service.handleTypingContext({ ...context, idleMs: 8000 }) + expect(harness.streamGenerate).toHaveBeenCalledTimes(2) + expect(service.getState().generating).toBe(false) + vi.useRealTimers() + + harness.streamGenerate.mockImplementation(async function* () { + yield ' 다음 문장.' + }) + // 실제로는 더 치는 데 시간이 걸린다 — 요청 간격(1.2초)이 지난 것으로 둔다 + ;(service as unknown as Internal)._lastRequestAt = Date.now() - 5000 + const longer = `${PREFIX} 그리고` + service.handleTypingContext(typingContext({ prefix: longer, documentBefore: longer, fullText: longer, caretOffset: longer.length })) + await vi.waitFor(() => expect(service.getState().candidates.length).toBeGreaterThan(0)) + }) +}) + +describe('멈추자마자 "생성 중" 자리', () => { + it('트리거 지연 전이라도 presenceDelayMs 가 지나면 생성 중으로 보이고, 생성은 아직 시작하지 않는다', () => { + const service = create() + const updates: boolean[] = [] + service.on('updated', (state) => updates.push(state.generating)) + + service.handleTypingContext(typingContext({ idleMs: 400 })) + + expect(service.getState().generating).toBe(true) + expect(service.getState().anchor).not.toBeNull() + expect(harness.streamGenerate).not.toHaveBeenCalled() + expect(updates).toEqual([true]) + // 정책상 "표시 중" 은 아니다 — 생성 시점에 already-visible 로 막히면 안 된다 + expect(service.isPresentationActive).toBe(false) + }) + + it('다시 치기 시작하면 조용히 거두고, 트리거 지연이 지나면 생성으로 이어진다', async () => { + harness.streamGenerate.mockImplementation(async function* () { + yield ' 이어지는 문장.' + }) + const service = create() + service.handleTypingContext(typingContext({ idleMs: 400 })) + expect(service.getState().generating).toBe(true) + + const typed = `${PREFIX}고` + service.handleTypingContext(typingContext({ prefix: typed, documentBefore: typed, fullText: typed, caretOffset: typed.length, idleMs: 80 })) + expect(service.getState().generating).toBe(false) + + service.handleTypingContext(typingContext({ prefix: typed, documentBefore: typed, fullText: typed, caretOffset: typed.length, idleMs: 400 })) + expect(service.getState().generating).toBe(true) + service.handleTypingContext(typingContext({ prefix: typed, documentBefore: typed, fullText: typed, caretOffset: typed.length, idleMs: 800 })) + await vi.waitFor(() => expect(service.getState().candidates.length).toBeGreaterThan(0)) + }) + + it('생성으로 이어지지 않으면 presenceMaxMs 뒤 스스로 거둔다', () => { + vi.useFakeTimers() + const service = create() + service.handleTypingContext(typingContext({ idleMs: 400 })) + expect(service.getState().generating).toBe(true) + vi.advanceTimersByTime(3100) + expect(service.getState().generating).toBe(false) + }) +}) diff --git a/apps/desktop/tests/main/services/suggestion-typo-correction.test.ts b/apps/desktop/tests/main/services/suggestion-typo-correction.test.ts new file mode 100644 index 0000000..47d9c4e --- /dev/null +++ b/apps/desktop/tests/main/services/suggestion-typo-correction.test.ts @@ -0,0 +1,242 @@ +// 제안 창에 오타 교정을 함께 내놓기 (2026-10-17 사용자 요청) +// +// "안ㄴ뇽하세여.?" 를 치고 멈추면 조용히 고치지 않고, 제안 창에 "지운 글자 → 고친 글자" 를 보여 주며 +// 모델에는 고친 글로 이어 쓰게 한다. 수락하면 오타 구간을 지우고 고친 글 + 후보를 한 번에 넣는다. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const config = vi.hoisted(() => ({ + suggestionEnabled: true as boolean, + suggestionModelId: 'gemma4:e4b' as string | null, + llmModelId: 'gemma4:e4b' as string | null, + inputExcludedApps: [] as string[], + suggestionTriggerDelayMs: 600, + suggestionMinPrefixChars: 4, + suggestionMaxRequestsPerMinute: 20, + suggestionDailyBudget: 500, + suggestionRequestTimeoutMs: 8000, + inputLearnTypedText: false, + inputTelemetryEnabled: false, + suggestionOverlayInteractive: true, + insertMethod: 'clipboard' +})) +const harness = vi.hoisted(() => ({ + streamGenerate: vi.fn(), + insertText: vi.fn(async (text: string) => ({ success: true, method: 'clipboard', textLength: text.length })), + replaceBeforeCaret: vi.fn(async (_count: number, text: string) => ({ + success: true, + method: 'clipboard', + textLength: text.length + })) +})) + +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: keyof typeof config) => config[key]), + configSet: vi.fn() +})) +vi.mock('../../../src/main/services/LoggerService', () => ({ + getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }) +})) +vi.mock('../../../src/main/services/LocalLLMService', () => ({ + getLocalLLMService: () => ({ isAvailable: () => true, streamGenerate: harness.streamGenerate }) +})) +vi.mock('../../../src/main/services/InputTelemetryService', () => ({ + getInputTelemetryService: () => ({ listPhrases: () => [], listRecentWrites: () => [] }) +})) +vi.mock('../../../src/main/services/PersonalGraphService', () => ({ + getPersonalGraphService: () => ({ retrieveContext: () => ({ continuations: [], related: [] }) }) +})) +vi.mock('../../../src/main/services/TextInsertService', () => ({ + getTextInsertService: () => ({ insertText: harness.insertText, replaceBeforeCaret: harness.replaceBeforeCaret }) +})) +vi.mock('../../../src/main/services/modifier-state', () => ({ waitForModifiersReleased: async () => true })) +vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null })) +vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() })) +vi.mock('../../../src/main/db/schema', () => ({ suggestions: {} })) + +import { + SuggestionService, + type SuggestionServiceDeps, + type SuggestionTypoProposer +} from '../../../src/main/services/SuggestionService' +import { SuggestionBudget } from '../../../src/main/services/suggestion/SuggestionBudget' +import { ModelWarmTracker } from '../../../src/main/services/suggestion/ModelWarmTracker' +import type { TypingContext } from '../../../src/main/services/InputTelemetryService' + +const TYPO = '안ㄴ뇽하세여.?' + +function typingContext(overrides: Partial = {}): TypingContext { + const prefix = overrides.prefix ?? TYPO + return { + prefix, + fullText: prefix, + caretOffset: prefix.length, + documentBefore: prefix, + anchor: null, + anchorKind: null, + isPassword: false, + isEditable: true, + isComposing: false, + hasSelection: false, + available: true, + appName: 'Agent Switchboard.exe', + windowTitle: 'Agent Switchboard', + windowHandle: null, + idleMs: 2000, + capturedAt: Date.now(), + editedSinceFocus: true, + typedRecently: true, + ...overrides + } +} + +const proposer: SuggestionTypoProposer = { + propose: vi.fn(async () => ({ + originalText: TYPO, + insertText: '안녕하세요.?', + corrections: [{ start: 0, end: 6, to: '안녕하세요' }] + })) +} + +function deps(expectKeys = vi.fn()): SuggestionServiceDeps { + const warmth = new ModelWarmTracker() + warmth.noteWarm('gemma4:e4b', Date.now() + 600_000) + return { + repository: { record: vi.fn(), markAccepted: vi.fn(), list: vi.fn(() => []) }, + budget: new SuggestionBudget(), + warmth, + foreground: { currentWindowHandle: () => null }, + learning: { expectProgrammaticInsert: vi.fn(() => vi.fn()), recordAccepted: vi.fn(), expectProgrammaticKeys: expectKeys } + } +} + +interface Internal { + _generate(prefix: string, context: TypingContext, maxCandidates: number, maxChars: number): Promise + _lastContext: TypingContext | null +} + +let services: SuggestionService[] = [] + +async function visible(context: TypingContext, expectKeys = vi.fn()): Promise { + const service = new SuggestionService(deps(expectKeys)) + services.push(service) + service.setTypoProposer(proposer) + const internal = service as unknown as Internal + internal._lastContext = context + await internal._generate(context.prefix, context, 3, 160) + return service +} + +beforeEach(() => { + harness.streamGenerate.mockReset() + harness.streamGenerate.mockImplementation(async function* () { + yield ' 오늘 회의 자료 공유드립니다.' + }) + harness.insertText.mockClear() + harness.replaceBeforeCaret.mockClear() +}) + +afterEach(() => { + for (const service of services) service.dispose() + services = [] +}) + +describe('제안 + 오타 교정', () => { + it('모델에는 고친 글을 보여 주고, 세션 상태에 교정(지운 글자 → 고친 글자)을 싣는다', async () => { + const service = await visible(typingContext()) + + const prompt = String(harness.streamGenerate.mock.calls[0][0]) + expect(prompt).toContain('안녕하세요.?') + expect(prompt).not.toContain('안ㄴ뇽') + const state = service.getState() + expect(state.candidates[0]?.text).toBe('오늘 회의 자료 공유드립니다.') + expect(state.correction).toEqual({ from: TYPO, to: '안녕하세요.?', edits: [{ start: 0, end: 6, to: '안녕하세요' }] }) + }) + + it('수락하면 오타 구간을 지우고 고친 글 + 후보를 한 번에 넣는다', async () => { + const expectKeys = vi.fn() + const service = await visible(typingContext(), expectKeys) + + const result = await service.accept() + + expect(result).toEqual({ ok: true }) + expect(harness.insertText).not.toHaveBeenCalled() + expect(harness.replaceBeforeCaret).toHaveBeenCalledWith(TYPO.length, '안녕하세요.? 오늘 회의 자료 공유드립니다.', 'clipboard', { + commitComposition: false + }) + // 백스페이스 8 + Ctrl,V 2 + expect(expectKeys).toHaveBeenCalledWith(TYPO.length + 2) + }) + + it('커서 앞 글자가 조합 중이면 먼저 확정하고 지운다', async () => { + const context = typingContext({ isComposing: true }) + const service = await visible(context) + + await service.accept() + + expect(harness.replaceBeforeCaret).toHaveBeenCalledWith(TYPO.length, expect.any(String), 'clipboard', { + commitComposition: true + }) + }) + + it('수락 직전 원문 끝이 교정 원문과 다르면 교정은 버리고 후보만 넣는다', async () => { + const service = await visible(typingContext()) + // 같은 세션으로 보이되(마지막 글자만 바뀜) 끝이 더 이상 교정 원문이 아니다. + ;(service as unknown as Internal)._lastContext = typingContext({ prefix: '안ㄴ뇽하세여.!' }) + + await service.accept() + + expect(harness.replaceBeforeCaret).not.toHaveBeenCalled() + expect(harness.insertText).toHaveBeenCalledWith(' 오늘 회의 자료 공유드립니다.', 'clipboard') + }) + + it('교정 포트가 없거나 교정이 없으면 예전처럼 후보만 넣는다', async () => { + const service = new SuggestionService(deps()) + services.push(service) + const context = typingContext({ prefix: '오늘 회의에서 논의한 내용을 정리해서', documentBefore: null }) + ;(service as unknown as Internal)._lastContext = context + await (service as unknown as Internal)._generate(context.prefix, context, 3, 160) + + expect(service.getState().correction).toBeNull() + await service.accept() + expect(harness.insertText).toHaveBeenCalledTimes(1) + expect(harness.replaceBeforeCaret).not.toHaveBeenCalled() + }) + + it('낱자 없는 오타는 첫 후보를 늦추지 않고, 첫 후보 뒤 정밀 검사로 교정 줄을 붙인다', async () => { + const PREFIX = '오늘 회으에서 나온 얘기를 정리하면 ' + const late: SuggestionTypoProposer = { + propose: vi.fn(async (_context, _signal, options) => + options?.thorough + ? { originalText: '회으에서 나온 얘기를 정리하면 ', insertText: '회의에서 나온 얘기를 정리하면 ', corrections: [{ start: 3, end: 7, to: '회의에서' }] } + : null + ) + } + const service = new SuggestionService(deps()) + services.push(service) + service.setTypoProposer(late) + const context = typingContext({ prefix: PREFIX, documentBefore: PREFIX }) + ;(service as unknown as Internal)._lastContext = context + await (service as unknown as Internal)._generate(PREFIX, context, 3, 160) + + // 첫 요청 전 검사는 정밀 검사가 아니었다 + expect(late.propose).toHaveBeenNthCalledWith(1, expect.anything(), expect.anything(), { thorough: false }) + await vi.waitFor(() => expect(service.getState().correction?.to).toBe('회의에서 나온 얘기를 정리하면 ')) + expect(service.getState().correction?.edits).toEqual([{ start: 0, end: 4, to: '회의에서' }]) + }) + + it('채우기 후보도 prefill 로만 만든다 — 지시형(대답하는 말투)을 섞지 않는다', async () => { + let call = 0 + harness.streamGenerate.mockImplementation(async function* () { + call += 1 + yield ` ${'가나다라마바사'.charAt(call)}로 이어 쓴다.` + }) + const service = await visible(typingContext()) + + await vi.waitFor(() => expect(service.getState().generating).toBe(false)) + expect(harness.streamGenerate.mock.calls.length).toBeGreaterThan(2) + for (const [, options] of harness.streamGenerate.mock.calls) { + expect(options).toEqual(expect.objectContaining({ raw: true })) + } + }) +}) 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 3b230c7..db58598 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 @@ -339,7 +339,7 @@ describe('suggestionPanelHeight — style.css 고정 치수와 같은 규칙', ( '../../../src/main/windows/suggestion-overlay-geometry' ) const base = { candidateCount: 0, activeIndex: 0, generating: false, warmingUp: false, hasPartialText: false } - expect(SUGGESTION_OVERLAY_MAX_HEIGHT).toBe(208) + expect(SUGGESTION_OVERLAY_MAX_HEIGHT).toBe(238) expect(suggestionPanelHeight({ ...base, warmingUp: true })).toBe(54) expect(suggestionPanelHeight({ ...base, generating: true })).toBe(54) expect(suggestionPanelHeight({ ...base, generating: true, hasPartialText: true })).toBe(98) @@ -349,6 +349,9 @@ describe('suggestionPanelHeight — style.css 고정 치수와 같은 규칙', ( // 두 번째 페이지에 후보 1개 expect(suggestionPanelHeight({ ...base, candidateCount: 4, activeIndex: 3 })).toBe(116) expect(suggestionPanelHeight({ ...base, candidateCount: 12, activeIndex: 5 })).toBe(208) + // 오타 교정 줄은 후보가 있을 때만 30px 를 더한다 + expect(suggestionPanelHeight({ ...base, candidateCount: 3, hasCorrection: true })).toBe(238) + expect(suggestionPanelHeight({ ...base, generating: true, hasCorrection: true })).toBe(54) }) }) diff --git a/docs/map/10-feature-catalog.md b/docs/map/10-feature-catalog.md index 0700a3f..fef0bf9 100644 --- a/docs/map/10-feature-catalog.md +++ b/docs/map/10-feature-catalog.md @@ -185,7 +185,8 @@ end-to-end behaviour has **not been verified by typing in a real app** (`11` GAP | INPUT-18 | Shortcut Safety Audit | [~] | [-] | [-] | [-] | Settings UI applies core `auditKeyBindingMap` to surface invalid/conflict issues while hold/double-press exceptions remain unchanged. | | INPUT-19 | Typo auto-correct while typing | [~] | [-] | [-] | [-] | **2026-10-03.** `TypoCorrectionService` (main, singleton + EventEmitter) runs on each `typed-context` before `SuggestionService`. Only after a pause (`TYPO_MIN_IDLE_MS` 600 ms), only in the 120-char/last-line region before the caret, only in fields the user just edited (`editedSinceFocus` + `typedRecently`); never in password/selection/IME-composing/caret-unknown fields, terminals, code editors (`shouldLearnFromApp`) or user-excluded apps. Layer 1 (core `typo-correction.ts`, pure): 2-set Korean layout mistypes both ways (`dkssudgktpdy`→`안녕하세요`, `솓`→`the`; conversion must compose fully into KS X 1001 common syllables — `hangul-common-syllables.ts`), always-wrong spellings (됬→됐, ㄹ께→ㄹ게, 몇일→며칠, teh→the, dont→don't …), and 1-edit near-misses of the user's frequent English words. Layer 2: if the suggestion model is already warm, a 2.5 s / 48-token sentence check (`buildTypoCheckPrompt`, `틀린말 => 고친말`) whose output is re-validated by `validateModelCorrections` (whole-eojeol or stem match, jamo-level edit distance, no spacing/case/word swaps, no abbreviation expansion like 넘→너무, user's repeated words exempt). Apply = backspace N + paste the corrected span (`TextInsertService.replaceBeforeCaret`, serialized with other inserts); cancelled if any key arrived after the decision or the foreground window changed. Programmatic keys are excluded from input stats. Reverting a fix within 30 s puts the word in `typoIgnoredWords`. While the model check runs the suggestion is deferred (`settled`) so it is generated from the corrected text and the two requests never race on the same model. Toggle: Settings → Input (`typoAutoCorrectEnabled`, default on; `typoAutoCorrectUseModel`). Logs record counts/sources only, never the words. Evidence: core 478 tests, desktop `TypoCorrectionService.test.ts` 14; real `gemma4:e4b` probe ≈0.5–0.8 s per check, 0 false fixes on slang/proper-noun samples. Not yet verified by typing in a real external app (GAP-INPUT-08). | | INPUT-20 | Context-aware suggestion prompt & graph retrieval | [~] | [-] | [-] | [-] | **2026-10-03.** Prompt (`buildSuggestionPrompt`) now splits the prefix with core `writing-context.ts` into earlier text / last sentence / unfinished current sentence and states the mode (finish this sentence vs. write the next one), language and Korean register (formal/polite/casual); adds the text after the caret (no overlap) and fixes dropped characters that had leaked into the old prompt ("[지금까지 텍스트]", "사용자가 언어"). Graph (`PersonalGraphService.retrieveContext`): `followUps` = what the user actually wrote after the same (or near-identical) last sentence via `follows` edges; continuations fall back from 14- to 10- to 7-char word-boundary tails; related sentences ranked by IDF-weighted term overlap (`scoreRelatedNodes`) with same-app/recency boosts plus a one-hop `follows` expansion. Korean terms are stemmed (`stemTerm`: particles and common 하다 endings) so "회의에서"/"회의는" match; stored old terms are re-stemmed at query time. Phrase hints for the prompt keep only phrases sharing terms with the current text (or same app); unfiltered phrases remain for the no-model local-memory fallback. Evidence: `personal-graph-context.test.ts` (real SQLite) 5, `llm-prompts.test.ts` +5, core `writing-context.test.ts` 8; real `gemma4:e4b` probe keeps register and follows graph hints (~0.55 s). | -| INPUT-21 | Prefill continuation + document/conversation context for suggestions | [~] | [-] | [-] | [-] | **2026-10-03.** For models whose chat template we know (gemma 4 `<\|turn>`, gemma 2/3 ``; core `chat-template.ts`), the suggestion request is sent `raw` with the user's own unfinished sentence (or last sentence) pre-filled into the model turn, so the model literally continues the text: mid-word joins (`회의실`+`에서`) and spacing come out exact (`extractContinuation` keeps joint `attach`/`separate`; trailing space is not pre-filled — it destabilised output — and an attach after a finished word is rejected). Ollama's chat-API prefill was measured and rejected (drops the leading space, closes the turn: `검토해 보시`→`부탁드립니다.`). Other models keep the instruction prompt. Context added to both paths: whole text before the caret (`TypingContext.documentBefore`, ≤6000 chars; null for document-like/terminal/password) → opening lines outside the 1,200-char window and a fact list (names+titles, attendee lines, dates, times, amounts, versions, acronyms, quoted terms — `analyzeDocumentContext`); **same-window messages the user just sent** (chat boxes empty on send — `RecentWritesBuffer`, memory only, 30 min, cleared when input observation stops, terminals excluded); search-box detection (keywords, not sentences); plain `-다` register split from casual `-어`; no emoji unless the user uses them. Output guards: first sentence/line only, stream cut as soon as it ends, restated-prefix stripping (also fixes the instruction path, where `CI는 통과했고…` was inserted after `CI는`), repeat-of-written-sentence drop, and **unsupported-fact rejection** (`findUnsupportedFacts`: dates/numbers/names+titles/lone Latin identifiers absent from document, window title, recent messages and personal hints) with one retry for the first candidate. Fill loop: temperature 1.0; in next-sentence mode every other fill uses the instruction prompt (prefill alone repeated the first candidate). Evidence: real `gemma4:e4b` probe `tests/integration/suggestion-quality.ollama.test.ts` (15 scenarios, opt-in `D3RO_SUGGESTION_PROBE=1`) — first-candidate warnings 0/15 vs 1/15 for the old path (old path invented a launch date instead of the 11월 15일 stated 1,200 chars earlier), mean ≈0.68 s both; core `suggestion-continuation.test.ts` 25, `llm-prompts.test.ts` +7. Not yet verified by typing in a real app (GAP-INPUT-09). | +| INPUT-21 | Prefill continuation + document/conversation context for suggestions | [~] | [-] | [-] | [-] | **2026-10-03.** For models whose chat template we know (gemma 4 `<\|turn>`, gemma 2/3 ``; core `chat-template.ts`), the suggestion request is sent `raw` with the user's own unfinished sentence (or last sentence) pre-filled into the model turn, so the model literally continues the text: mid-word joins (`회의실`+`에서`) and spacing come out exact (`extractContinuation` keeps joint `attach`/`separate`; trailing space is not pre-filled — it destabilised output — and an attach after a finished word is rejected). Ollama's chat-API prefill was measured and rejected (drops the leading space, closes the turn: `검토해 보시`→`부탁드립니다.`). Other models keep the instruction prompt. Context added to both paths: whole text before the caret (`TypingContext.documentBefore`, ≤6000 chars; null for document-like/terminal/password) → opening lines outside the 1,200-char window and a fact list (names+titles, attendee lines, dates, times, amounts, versions, acronyms, quoted terms — `analyzeDocumentContext`); **same-window messages the user just sent** (chat boxes empty on send — `RecentWritesBuffer`, memory only, 30 min, cleared when input observation stops, terminals excluded); search-box detection (keywords, not sentences); plain `-다` register split from casual `-어`; no emoji unless the user uses them. Output guards: first sentence/line only, stream cut as soon as it ends, restated-prefix stripping (also fixes the instruction path, where `CI는 통과했고…` was inserted after `CI는`), repeat-of-written-sentence drop, and **unsupported-fact rejection** (`findUnsupportedFacts`: dates/numbers/names+titles/lone Latin identifiers absent from document, window title, recent messages and personal hints) with one retry for the first candidate. Fill loop: temperature 1.0, prefill only (the 2026-10-17 change removed the alternating instruction prompt — see INPUT-22). Evidence: real `gemma4:e4b` probe `tests/integration/suggestion-quality.ollama.test.ts` (15 scenarios, opt-in `D3RO_SUGGESTION_PROBE=1`) — first-candidate warnings 0/15 vs 1/15 for the old path (old path invented a launch date instead of the 11월 15일 stated 1,200 chars earlier), mean ≈0.68 s both; core `suggestion-continuation.test.ts` 25, `llm-prompts.test.ts` +7. Not yet verified by typing in a real app (GAP-INPUT-09). | +| INPUT-22 | Typo fixes proposed inside the suggestion popup + snappier suggestions | [~] | [-] | [-] | [-] | **2026-10-17.** While suggestions are on, typos are no longer replaced silently: `TypoCorrectionService.propose()` builds a plan without applying it and `SuggestionService` shows it in the popup as a `오타 고침` row (`del` struck-through original → `ins` fix) with the corrected tail prefixed to every candidate; the model continues from the corrected text. Accept = backspace the typo span + paste fix + candidate in one `replaceBeforeCaret` (if the caret char is still IME-composing, a real Space commits it first and is deleted too); if the text before the caret no longer ends with the typo span, only the candidate is inserted. Silent auto-correct (INPUT-19) still runs when suggestions are off. New core rule `detectJamoNoise`: a lone stray jamo inside/before Hangul syllables (`그ㅓ런`, `ㅇ다른`, `가쓴ㄷ거`) or a lone jamo word mid-sentence is removed; `ㅋㅋ`/`ㅠㅠ`/trailing `ㅎ`/first-word `ㅇ` are kept. Model typo check runs before the first candidate only when `hasSuspiciousTypo` (stray jamo, rare syllable); otherwise once in the background after the first candidate (`thorough`, ≥2 words) and the row is attached late. Proposals also work in learning-excluded apps (agent windows) but not terminals/excluded apps. Responsiveness: `minIntervalMs` 5000→1200, per-minute cap 6→20 (config migration rev 7, IPC clamp 30), composing idle ×1.5→×1.2, settle snapshot fires right after the required idle (≈780 ms instead of 1 s), accept relaxes the interval so the next pause after Space suggests again, visible TTL 20→45 s. Fill loop no longer mixes instruction prompts (instruction-path gemma *answered* the user: "설명해 주실 수 있을까요?"). **Round 2 (same day, live test: "panel should appear the moment I pause; it still closes mid-generation / flashes"):** 15 of 18 first requests returned an empty model output — a prefill ending mid-sentence with no trailing space (`…잠시 쉬면`) makes gemma close its turn at once; each empty result closed the panel and the next snapshot regenerated the same text ~1 s later (flash loop). Fixes: empty raw output → one retry with a trailing space appended to the prefill (`ModelRequest.spaced`, output re-parsed with a leading space so the joint is separate; probe: 4/4 sentences continue; fills reuse the spaced variant); a prefix whose first request failed is not regenerated until the text changes (`_failedPrefix`); a lone trailing jamo is removed with the *following* space so the text still ends "word + space"; snapshot debounce 700→380 ms and a "생성 중" placeholder (`presenceDelayMs` 350, self-clears after `presenceMaxMs` 3 s or when typing resumes, only when a request will follow — warm model, budget, not dismissed, not a failed prefix) shown before generation starts; it is not counted as "visible" by the policy. Tests: `suggestion-presence.test.ts` 5. Recent same-window writes are observed even while IME-composing (Korean chat boxes are almost always composing, so sent messages were never remembered). Diagnosis (installed v1.9.0 log + history DB, 1,122 suggestions / 11 accepted): v1.9.0 predates INPUT-19/21 and cleared a visible popup once `typedRecently` expired 8 s after the last key — ≈ the time the 12-candidate fill takes ("closes by itself when all candidates are done"). Evidence: real `gemma4:e4b` — `안ㄴ뇽하세여.?`→`안녕하세요.?` (1.1 s), `회으에서`→`회의에서`, `괜찬으세요`→`괜찮으세요`, `ㅇ다른`/`그ㅓ런` (0.8 s); desktop `suggestion-typo-correction.test.ts` 7, `TypoCorrectionService.test.ts` +4, core `typo-correction.test.ts` +4; desktop 2556 pass (2 known caption-env failures). Real-app check pending (GAP-INPUT-10). | --- diff --git a/packages/core/__tests__/typo-correction.test.ts b/packages/core/__tests__/typo-correction.test.ts index d949c19..6d820be 100644 --- a/packages/core/__tests__/typo-correction.test.ts +++ b/packages/core/__tests__/typo-correction.test.ts @@ -5,16 +5,20 @@ import { describe, expect, it } from 'vitest' import { buildVocabulary, detectHangulTypedLatin, + detectJamoNoise, detectLatinTypedHangul, detectTypoRevert, detectTypos, fixByVocabulary, fixKnownMisspelling, + hasSuspiciousTypo, + mergeTypoCorrections, hangulToLatin, isPlausibleTypoFix, latinToHangul, parseModelTypoPairs, planTypoReplacement, + validateModelCorrections, typoRegionStart, validateModelCorrections } from '../src/typo-correction' @@ -221,3 +225,33 @@ describe('되돌리기 감지', () => { expect(detectTypoRevert('그건 됐다 그리고', { from: '됬다', to: '됐다', tailLength: 4 })).toBe(false) }) }) + +describe('낱자 잡음 (2026-10-17 실측 입력)', () => { + const fixed = (text: string): string | null => planTypoReplacement(text, detectJamoNoise(text))?.insertText ?? null + + it('음절 사이·앞에 끼어든 낱자 하나를 지운다', () => { + expect(fixed('그ㅓ런건 전혀')).toBe('그런건 전혀') + expect(fixed('내 가쓴ㄷ거에 대한')).toBe('가쓴거에 대한') + expect(fixed('파츠가 ㅇ다른 UI')).toBe('다른 UI') + expect(fixed('안ㄴ뇽하세여.?')).toBe('안뇽하세여.?') + }) + + it('문장 중간에 홀로 남은 낱자는 뒤 공백과 함께 지운다 — 끝의 낱자를 지워도 "아직 " 이 남는다', () => { + expect(fixed('실망스럽고 ㅇ ㅇ이전 까지')).toBe('이전 까지') + expect(fixed('아직 ㅇ')).toBe('') + expect(planTypoReplacement('아직 ㅇ', detectJamoNoise('아직 ㅇ'))?.deleteCount).toBe(1) + }) + + it('의도한 낱자(ㅋㅋ·ㅠㅠ·끝의 감정 낱자·첫머리 대답)는 두고, 수상하다고 보지도 않는다', () => { + for (const text of ['ㅋㅋ 좋아', '좋아ㅋㅋ', '고마워ㅎ', '미안ㅠ', 'ㅇ 알겠어', 'ㅇㅋ 그럼']) { + expect(detectJamoNoise(text)).toEqual([]) + expect(hasSuspiciousTypo(text)).toBe(false) + } + }) + + it('모델 교정이 같은 단어의 낱자 지우기보다 앞선다', () => { + const text = '안ㄴ뇽하세여.?' + const model = validateModelCorrections(text, [{ from: '안ㄴ뇽하세여', to: '안녕하세요' }]) + expect(planTypoReplacement(text, mergeTypoCorrections(model, detectJamoNoise(text)))?.insertText).toBe('안녕하세요.?') + }) +}) diff --git a/packages/core/src/input-intelligence.ts b/packages/core/src/input-intelligence.ts index 8e5b2a5..09c1c00 100644 --- a/packages/core/src/input-intelligence.ts +++ b/packages/core/src/input-intelligence.ts @@ -1212,6 +1212,18 @@ export interface SuggestionCandidate { joint?: SuggestionJoint } +/** + * 제안과 함께 내놓는 오타 교정 — 커서 앞 원문 끝의 `from` 을 `to` 로 바꾼 뒤 후보를 잇는다. + * + * 조용히 고치지 않고 제안 창에 "지운 글자 → 고친 글자" 로 보여 주며, 수락할 때만 적용한다. + * `edits` 는 `from` 안의 위치(표시용)다 — 바뀐 단어만 강조하고 나머지는 그대로 보인다. + */ +export interface SuggestionCorrection { + from: string + to: string + edits: Array<{ start: number; end: number; to: string }> +} + /** 현재 제안이 어느 로컬 근거에서 나왔는지 보여 주는 비식별 설명. */ export interface SuggestionProvenance { mode: 'local-model' | 'local-memory' @@ -1267,6 +1279,8 @@ export interface SuggestionState { typoAutoCorrect: boolean /** 후보를 만든 로컬 근거의 수량만 노출한다. */ provenance: SuggestionProvenance | null + /** 이 세션의 후보가 함께 적용하는 오타 교정 (없으면 null) */ + correction: SuggestionCorrection | null } /** 제안 기본값 — 인라인 컴플리션 실측 중앙값 기준. */ @@ -1286,14 +1300,28 @@ export const SUGGESTION_DEFAULTS = { * 보수적이다. */ minPrefixChars: 8, - minIntervalMs: 5000, + /** + * 요청 사이 최소 간격. + * + * 원래 5초였다 — 로컬 모델 첫 후보가 0.8초 안팎인데 5초·분당 6회에 막혀, 제안을 고르고 이어 친 뒤 + * 다시 멈추면 rate-limited 로 아무것도 안 떴다(실측 2026-10-17: "나올 때도 있고 안 나올 때도"). + * 치는 동안 진행 중 요청은 취소·환불되므로 간격은 짧아도 된다. + */ + minIntervalMs: 1200, + /** + * 손을 멈춘 뒤 "생성 중" 자리를 먼저 띄우는 시점 (ms). 생성은 triggerDelayMs(조합 중이면 배수) 뒤에 + * 시작하고, 그 전에 다시 치면 조용히 거둔다 — 반응은 빠르게, 모델 호출은 지금처럼 보수적으로. + */ + presenceDelayMs: 350, + /** 먼저 띄운 자리가 생성으로 이어지지 않으면 이 시간 뒤 스스로 거둔다 (ms) */ + presenceMaxMs: 3000, /** * 멈춤 판단의 하한. 이보다 짧으면 글자 사이의 순간 멈춤에도 생성이 시작돼, * 치는 도중 창이 떴다 사라지기를 반복한다(실측 2026-09-27: 100ms 설정에서 * 5~6초마다 생성→소멸 반복). */ minTriggerDelayMs: 500, - maxRequestsPerMinute: 6, + maxRequestsPerMinute: 20, dailyBudget: 500, /** 로컬 기억 경로(폴백)에서 한 번에 만드는 후보 수 — 채우기 루프가 없다. */ maxCandidates: 3, @@ -1320,7 +1348,7 @@ export const SUGGESTION_DEFAULTS = { * 오버레이는 "다음 문맥" 이 와야 지워지는데, 타이핑을 멈추면 문맥이 오지 않아 * 창이 무한정 남는다(실측 신고: 아무것도 안 치는데 제안창이 떠 있음). */ - visibleTtlMs: 20000, + visibleTtlMs: 45000, /** * 요청 시작 후 이 시간이 지나면 결과를 폐기한다. * @@ -1353,7 +1381,7 @@ export const SUGGESTION_DEFAULTS = { * * 조합 중에는 손을 멈춘 것으로 보이려면 기본 지연의 이 배수만큼 조용해야 한다. */ -export const COMPOSING_IDLE_MULTIPLIER = 1.5 +export const COMPOSING_IDLE_MULTIPLIER = 1.2 /** * 접두가 이만큼 더 자라면 재생성한다. @@ -1382,8 +1410,14 @@ export const INPUT_TELEMETRY_DEFAULTS = { activeWindowSampleMinIntervalMs: 1000, /** 마지막 입력 후 이 시간이 지나면 활성 시간 누적을 멈춘다 */ activeIdleTimeoutMs: 60000, - /** 텍스트 스냅샷(학습/컨텍스트) 디바운스 */ - textSnapshotDebounceMs: 700, + /** + * 텍스트 스냅샷(학습/컨텍스트) 디바운스. + * + * 700ms 였다 — 제안 창은 이 스냅샷이 와야 뜨므로, 잠깐 쉬어도 창이 늦게 떴다("UI 가 빠릿하게, 잠시 + * 쉬면 나와야" — 2026-10-17). 이 시점에 "생성 중" 자리를 먼저 띄우고(presenceDelayMs), 생성은 + * 트리거 지연 뒤에 시작한다. + */ + textSnapshotDebounceMs: 380, /** 백그라운드 샘플 주기 (ms) — 타이핑이 이어져도 관측을 멈추지 않는다 */ sampleIntervalMs: 800, /** 마지막 입력이 이 시간 안에 있었으면 주기 샘플을 돌린다 (ms) */ diff --git a/packages/core/src/typo-correction.ts b/packages/core/src/typo-correction.ts index cbb7cd7..ad08b11 100644 --- a/packages/core/src/typo-correction.ts +++ b/packages/core/src/typo-correction.ts @@ -16,7 +16,7 @@ import { isCommonHangulSyllable } from './hangul-common-syllables' // 타입 // ============================================================ -export type TypoSource = 'layout' | 'dictionary' | 'vocabulary' | 'model' +export type TypoSource = 'layout' | 'dictionary' | 'vocabulary' | 'model' | 'jamo' /** 접두(커서 앞 텍스트) 안의 교정 하나. start/end 는 접두 문자열 오프셋(UTF-16)이다. */ export interface TypoCorrection { @@ -591,6 +591,87 @@ export function detectTypos(prefix: string, options: TypoDetectOptions = {}): Ty return out } +// ============================================================ +// 자모 잡음 (낱자가 음절 사이에 끼어든 오타) +// ============================================================ + +/** 호환 자모 (ㄱ–ㅣ) — 조합되지 못하고 남은 낱자 */ +const COMPAT_JAMO = /^[\u3131-\u3163]$/u +/** 일부러 붙이는 감정 낱자 (고마워ㅎ, 좋아ㅋ, 미안ㅠ) — 낱자 하나여도 오타가 아니다 */ +const EMOTIVE_JAMO = new Set(['ㅋ', 'ㅎ', 'ㅠ', 'ㅜ']) + +/** + * 음절 사이·앞에 끼어든 낱자 하나를 지우는 교정을 찾는다. + * + * 실측(2026-10-17, 사용자 입력 원문): "안ㄴ뇽", "그ㅓ런", "가쓴ㄷ거", "ㅇ다른", "실망스럽고 ㅇ ㅇ이전". + * 빠르게 치다 조합이 깨지면 낱자가 남는다. 낱자 둘 이상(ㅋㅋ, ㅠㅠ, ㅇㅋ)과 끝에 붙인 감정 낱자는 + * 의도한 표현이라 두고, 단어 하나가 통째로 낱자 하나인 것(문장 중간의 "ㅇ")은 앞 공백과 함께 지운다. + * 결정적 규칙은 "지우기" 만 한다 — "안ㄴ뇽 → 안녕" 처럼 글자를 바꿔야 하는 것은 모델 검사 몫이다. + */ +export function detectJamoNoise(prefix: string, options: { ignoredWords?: readonly string[] } = {}): TypoCorrection[] { + const regionStart = typoRegionStart(prefix) + const tokens = tokenizeWords(prefix).filter((token) => token.start >= regionStart) + const out: TypoCorrection[] = [] + tokens.forEach((token, index) => { + if (isIgnored(token.text, options.ignoredWords)) return + const chars = Array.from(token.text) + if (chars.length === 1 && COMPAT_JAMO.test(chars[0])) { + // 글 첫 단어인 "ㅇ"(응)·"ㄱ"(고) 는 대답이다 — 앞에 한글 단어가 있을 때만 잡음으로 본다. + const previous = tokens[index - 1] + if (!previous || !HANGUL_SYLLABLE.test(previous.text) || EMOTIVE_JAMO.has(chars[0])) return + // 뒤 공백과 함께 지운다 — 앞 공백을 지우면 끝에 남은 낱자("있고 ㅇ")가 "있고" 가 되어, 모델이 끝난 + // 단어에 글자를 붙이려 하거나 곧바로 턴을 닫았다(실측 2026-10-17: 교정이 붙은 첫 후보 4번 모두 빈 출력). + const end = /[ \t]/u.test(prefix[token.end] ?? '') ? token.end + 1 : token.end + out.push({ start: token.start, end, from: prefix.slice(token.start, end), to: '', source: 'jamo' }) + return + } + if (!HANGUL_SYLLABLE.test(token.text)) return + let changed = false + const kept = chars.filter((char, position) => { + if (!COMPAT_JAMO.test(char)) return true + const lone = !COMPAT_JAMO.test(chars[position - 1] ?? '') && !COMPAT_JAMO.test(chars[position + 1] ?? '') + if (!lone) return true + if (position === chars.length - 1 && EMOTIVE_JAMO.has(char)) return true + changed = true + return false + }) + if (!changed) return + const to = kept.join('') + if (!HANGUL_SYLLABLE.test(to)) return + out.push({ start: token.start, end: token.end, from: token.text, to, source: 'jamo' }) + }) + return out +} + +/** + * 모델에 오타 검사를 맡길 만큼 수상한 구간인가 — 낱자가 섞인 한글 단어, 드문 음절, 결정적 탐지 결과. + * + * 제안 창에 교정을 함께 내놓을 때 멈출 때마다 모델 검사(0.5초)를 하면 제안이 그만큼 늦는다. + * 수상한 흔적이 있을 때만 묻는다. + */ +export function hasSuspiciousTypo(region: string): boolean { + if (detectJamoNoise(region).length > 0) return true + return tokenizeWords(region).some((token) => + Array.from(token.text).some((char) => HANGUL_SYLLABLE.test(char) && !isCommonHangulSyllable(char)) + ) +} + +/** + * 같은 구간에 대한 교정을 합친다 — 앞 목록이 우선이고, 겹치는 뒤 목록 항목은 버린다. + * (모델이 "안ㄴ뇽 → 안녕" 을 냈으면 같은 단어의 "낱자 지우기" 는 쓰지 않는다) + */ +export function mergeTypoCorrections( + primary: readonly TypoCorrection[], + secondary: readonly TypoCorrection[] +): TypoCorrection[] { + const out = [...primary] + for (const candidate of secondary) { + if (out.some((existing) => candidate.start < existing.end && existing.start < candidate.end)) continue + out.push(candidate) + } + return out.sort((a, b) => a.start - b.start) +} + // ============================================================ // 모델 교정 검증 // ============================================================ diff --git a/packages/i18n/src/locales/de.json b/packages/i18n/src/locales/de.json index ddc9cfa..c31c7ac 100644 --- a/packages/i18n/src/locales/de.json +++ b/packages/i18n/src/locales/de.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "Ausschlüsse gespeichert.", "input.feedback.cleared": "Erfasste Daten gelöscht.", "popup.suggestion.hintAccept": "Übernehmen", + "popup.suggestion.correctionLabel": "Korrigiert", "popup.suggestion.hintNext": "Weiter", "popup.suggestion.hintDismiss": "Schließen", "popup.suggestion.hintMove": "Bewegen", diff --git a/packages/i18n/src/locales/en.json b/packages/i18n/src/locales/en.json index f67c5d6..ea543bc 100644 --- a/packages/i18n/src/locales/en.json +++ b/packages/i18n/src/locales/en.json @@ -1778,6 +1778,7 @@ "input.feedback.excludedSaved": "Exclusions saved.", "input.feedback.cleared": "Collected data deleted.", "popup.suggestion.hintAccept": "Accept", + "popup.suggestion.correctionLabel": "Fixed", "popup.suggestion.hintNext": "Next", "popup.suggestion.hintDismiss": "Dismiss", "popup.suggestion.hintMove": "Move", diff --git a/packages/i18n/src/locales/es.json b/packages/i18n/src/locales/es.json index 55da20e..520512a 100644 --- a/packages/i18n/src/locales/es.json +++ b/packages/i18n/src/locales/es.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "Exclusiones guardadas.", "input.feedback.cleared": "Datos recopilados eliminados.", "popup.suggestion.hintAccept": "Aceptar", + "popup.suggestion.correctionLabel": "Corregido", "popup.suggestion.hintNext": "Siguiente", "popup.suggestion.hintDismiss": "Descartar", "popup.suggestion.hintMove": "Mover", diff --git a/packages/i18n/src/locales/fr.json b/packages/i18n/src/locales/fr.json index da5f4e7..6e2103a 100644 --- a/packages/i18n/src/locales/fr.json +++ b/packages/i18n/src/locales/fr.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "Exclusions enregistrées.", "input.feedback.cleared": "Données collectées supprimées.", "popup.suggestion.hintAccept": "Accepter", + "popup.suggestion.correctionLabel": "Corrigé", "popup.suggestion.hintNext": "Suivant", "popup.suggestion.hintDismiss": "Fermer", "popup.suggestion.hintMove": "Déplacer", diff --git a/packages/i18n/src/locales/ja.json b/packages/i18n/src/locales/ja.json index 9696f7c..4b45d63 100644 --- a/packages/i18n/src/locales/ja.json +++ b/packages/i18n/src/locales/ja.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "除外リストを保存しました。", "input.feedback.cleared": "収集したデータを削除しました。", "popup.suggestion.hintAccept": "承認", + "popup.suggestion.correctionLabel": "誤字修正", "popup.suggestion.hintNext": "次へ", "popup.suggestion.hintDismiss": "閉じる", "popup.suggestion.hintMove": "移動", diff --git a/packages/i18n/src/locales/ko.json b/packages/i18n/src/locales/ko.json index 4b2c393..b6cfbce 100644 --- a/packages/i18n/src/locales/ko.json +++ b/packages/i18n/src/locales/ko.json @@ -1785,6 +1785,7 @@ "input.feedback.excludedSaved": "제외 목록을 저장했습니다.", "input.feedback.cleared": "수집된 데이터를 삭제했습니다.", "popup.suggestion.hintAccept": "수락", + "popup.suggestion.correctionLabel": "오타 고침", "popup.suggestion.hintNext": "다음", "popup.suggestion.hintDismiss": "닫기", "popup.suggestion.hintMove": "이동", diff --git a/packages/i18n/src/locales/pt.json b/packages/i18n/src/locales/pt.json index 3f78d80..e48fa9f 100644 --- a/packages/i18n/src/locales/pt.json +++ b/packages/i18n/src/locales/pt.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "Exclusões salvas.", "input.feedback.cleared": "Dados coletados excluídos.", "popup.suggestion.hintAccept": "Aceitar", + "popup.suggestion.correctionLabel": "Corrigido", "popup.suggestion.hintNext": "Próxima", "popup.suggestion.hintDismiss": "Descartar", "popup.suggestion.hintMove": "Mover", diff --git a/packages/i18n/src/locales/ru.json b/packages/i18n/src/locales/ru.json index 49e4a24..3a9f12f 100644 --- a/packages/i18n/src/locales/ru.json +++ b/packages/i18n/src/locales/ru.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "Исключения сохранены.", "input.feedback.cleared": "Собранные данные удалены.", "popup.suggestion.hintAccept": "Принять", + "popup.suggestion.correctionLabel": "Исправлено", "popup.suggestion.hintNext": "Далее", "popup.suggestion.hintDismiss": "Закрыть", "popup.suggestion.hintMove": "Перемещение", diff --git a/packages/i18n/src/locales/th.json b/packages/i18n/src/locales/th.json index 84bcc9f..2b364ec 100644 --- a/packages/i18n/src/locales/th.json +++ b/packages/i18n/src/locales/th.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "บันทึกรายการยกเว้นแล้ว", "input.feedback.cleared": "ลบข้อมูลที่เก็บไว้แล้ว", "popup.suggestion.hintAccept": "ยอมรับ", + "popup.suggestion.correctionLabel": "แก้คำผิด", "popup.suggestion.hintNext": "ถัดไป", "popup.suggestion.hintDismiss": "ปิด", "popup.suggestion.hintMove": "ย้าย", diff --git a/packages/i18n/src/locales/vi.json b/packages/i18n/src/locales/vi.json index 61e4c7e..e7655cb 100644 --- a/packages/i18n/src/locales/vi.json +++ b/packages/i18n/src/locales/vi.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "Đã lưu danh sách loại trừ.", "input.feedback.cleared": "Đã xóa dữ liệu thu thập.", "popup.suggestion.hintAccept": "Chấp nhận", + "popup.suggestion.correctionLabel": "Đã sửa", "popup.suggestion.hintNext": "Tiếp", "popup.suggestion.hintDismiss": "Đóng", "popup.suggestion.hintMove": "Di chuyển", diff --git a/packages/i18n/src/locales/zh-TW.json b/packages/i18n/src/locales/zh-TW.json index 91e2c31..04e2b93 100644 --- a/packages/i18n/src/locales/zh-TW.json +++ b/packages/i18n/src/locales/zh-TW.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "已儲存排除清單。", "input.feedback.cleared": "已刪除收集的資料。", "popup.suggestion.hintAccept": "接受", + "popup.suggestion.correctionLabel": "已更正", "popup.suggestion.hintNext": "下一個", "popup.suggestion.hintDismiss": "關閉", "popup.suggestion.hintMove": "移動", diff --git a/packages/i18n/src/locales/zh.json b/packages/i18n/src/locales/zh.json index 4faad5e..0b5a1af 100644 --- a/packages/i18n/src/locales/zh.json +++ b/packages/i18n/src/locales/zh.json @@ -363,6 +363,7 @@ "input.feedback.excludedSaved": "已保存排除列表。", "input.feedback.cleared": "已删除收集的数据。", "popup.suggestion.hintAccept": "接受", + "popup.suggestion.correctionLabel": "已纠错", "popup.suggestion.hintNext": "下一个", "popup.suggestion.hintDismiss": "关闭", "popup.suggestion.hintMove": "移动", diff --git a/scripts/ci/publish-gitlab-release.mjs b/scripts/ci/publish-gitlab-release.mjs deleted file mode 100644 index bc01143..0000000 --- a/scripts/ci/publish-gitlab-release.mjs +++ /dev/null @@ -1,259 +0,0 @@ -// scripts/ci/publish-gitlab-release.mjs -// 태그 파이프라인의 release 스테이지에서 실행: -// 1) package-windows / package-macos artifacts를 GitLab Generic Package Registry에 업로드 -// - 버전별 경로: packages/generic/d3ro-voice// -// - latest 경로: packages/generic/d3ro-voice/latest/ (electron-updater feed) -// 2) GitLab Release 생성 + asset 링크 연결 -// -// agent-switchboard-client의 publish-gitlab-release.mjs 패턴을 D3RO에 맞게 단순화. -// (Ed25519 update-policy 서명 체계는 후속 단계 — 현재는 latest.yml 기반) -// -// 필요 env: CI_API_V4_URL, CI_PROJECT_ID, CI_JOB_TOKEN, CI_COMMIT_TAG - -import { createReadStream, readFileSync } from "node:fs"; -import { readFile, readdir, stat } from "node:fs/promises"; -import { timingSafeEqual } from "node:crypto"; -import { basename, join } from "node:path"; -import process from "node:process"; -import { fileURLToPath, URL } from "node:url"; - -const apiUrl = required("CI_API_V4_URL").replace(/\/+$/, ""); -const projectId = required("CI_PROJECT_ID"); -const jobToken = required("CI_JOB_TOKEN"); -const tag = required("CI_COMMIT_TAG"); -const version = tag.replace(/^v/, ""); -const packageName = "d3ro-voice"; - -if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version)) { - throw new Error(`Unsupported release tag: ${tag}`); -} - -const productVersion = JSON.parse( - await readFile(fileURLToPath(new URL("../../release/product-version.json", import.meta.url)), "utf8"), -); -if (tag !== `v${productVersion.version}` || !/^\d+\.\d+\.\d+$/.test(version)) { - throw new Error(`Release tag ${tag} does not match stable product version v${productVersion.version}.`); -} - -// electron-builder output: apps/desktop/release// -const releaseDirectory = fileURLToPath(new URL(`../../apps/desktop/release/${version}/`, import.meta.url)); - -// 업로드 대상 수집 — 설치파일 + 업데이터 메타데이터만 (unpacked 디렉토리 제외) -const ASSET_PATTERN = /(\.exe|\.dmg|\.zip|\.blockmap|^(latest|alpha|beta)(-mac|-linux)?\.yml)$/; - -const files = []; -for (const name of await readdir(releaseDirectory)) { - if (!ASSET_PATTERN.test(name)) continue; - const path = join(releaseDirectory, name); - if ((await stat(path)).isFile()) files.push({ name, path }); -} - -if (files.length === 0) { - throw new Error(`No release assets found in ${releaseDirectory}`); -} - -const hasWindows = files.some((file) => file.name.endsWith(".exe")); -if (!hasWindows) { - throw new Error(`Windows installer is missing for ${tag}.`); -} -// latest.yml은 자동 업데이트 feed의 핵심 — 없으면 electron-builder publish 설정 회귀 -if (!files.some((file) => file.name === "latest.yml")) { - throw new Error( - `latest.yml is missing for ${tag} — check electron-builder.yml publish config.`, - ); -} -const hasMac = files.some((file) => file.name.endsWith(".dmg")); -if (!hasMac) { - // mac runner 미등록/실패 시에도 Windows 단독 릴리스는 진행 (경고만) - process.stdout.write(`WARNING: macOS artifacts missing for ${tag} — Windows-only release.\n`); -} - -const packageBaseUrl = `${apiUrl}/projects/${encodeURIComponent(projectId)}/packages/generic/${packageName}/${version}`; -const latestPackageBaseUrl = `${apiUrl}/projects/${encodeURIComponent(projectId)}/packages/generic/${packageName}/latest`; - -const links = []; -const sortedFiles = files.sort((a, b) => a.name.localeCompare(b.name)); - -// 1) 버전별 패키지 업로드 -for (const file of sortedFiles) { - const registryName = safeAssetName(file.name); - const uploadUrl = `${packageBaseUrl}/${encodeURIComponent(registryName)}`; - await uploadFile(file, uploadUrl, "versioned package"); - links.push({ - name: file.name, - url: uploadUrl, - direct_asset_path: `/${registryName}`, - link_type: isUpdateMetadata(file.name) ? "other" : "package", - }); -} - -// 2) latest 패키지 갱신. 설치파일과 blockmap을 먼저 올리고, update metadata를 -// 마지막에 게시한다. 기존 latest를 선삭제하지 않으므로 배포 중에도 이전 -// 설치본이 404를 받지 않는다. 중복 업로드가 금지된 인스턴스라면 metadata -// 전환 전에 실패해 기존 feed가 그대로 보존된다. -const latestFiles = [...sortedFiles].sort((a, b) => { - const metadataOrder = Number(isUpdateMetadata(a.name)) - Number(isUpdateMetadata(b.name)); - return metadataOrder || a.name.localeCompare(b.name); -}); -for (const file of latestFiles) { - const registryName = safeAssetName(file.name); - await uploadFile(file, `${latestPackageBaseUrl}/${encodeURIComponent(registryName)}`, "latest package"); -} - -for (const file of latestFiles.filter((candidate) => isYamlUpdateMetadata(candidate.name))) { - validateUpdateMetadataReferences(file, latestFiles); -} -for (const file of latestFiles.filter((candidate) => isUpdateMetadata(candidate.name))) { - await verifyPublicLatestFile(file, latestPackageBaseUrl); -} - -// 3) GitLab Release 생성 또는 재시도 시 안전하게 갱신 -const description = await buildDescription(); -const releaseUrl = `${apiUrl}/projects/${encodeURIComponent(projectId)}/releases`; -await upsertRelease(releaseUrl, description, links); - -process.stdout.write(`Created ${tag} with ${links.length} release assets.\n`); - -// ── 헬퍼 ──────────────────────────────────────────────────── - -function required(name) { - const value = process.env[name]?.trim(); - if (!value) throw new Error(`${name} is required.`); - return value; -} - -function safeAssetName(name) { - return basename(name).replace(/[^A-Za-z0-9._-]+/g, "-"); -} - -function isUpdateMetadata(name) { - return /(?:\.blockmap$|^(?:latest|alpha|beta)(?:-mac|-linux)?\.yml$)/.test(name); -} - -function isYamlUpdateMetadata(name) { - return /^(?:latest|alpha|beta)(?:-mac|-linux)?\.yml$/.test(name); -} - -async function buildDescription() { - const changelog = await readFile( - fileURLToPath(new URL("../../CHANGELOG.md", import.meta.url)), - "utf8", - ); - const section = extractChangelogSection(changelog, version); - if (!section) throw new Error(`CHANGELOG.md is missing a ${version} release section.`); - return section; -} - -function extractChangelogSection(changelog, targetVersion) { - const lines = changelog.split("\n"); - // 버전 뒤 경계 필수 — "0.1.0"이 "0.1.0-alpha" 섹션에 오매칭되지 않게 - const escaped = targetVersion.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const headerPattern = new RegExp(`^##\\s+\\[?v?${escaped}(?:\\]|\\s|$)`); - const start = lines.findIndex((line) => headerPattern.test(line)); - if (start === -1) return null; - let end = lines.length; - for (let i = start + 1; i < lines.length; i++) { - if (/^##\s+/.test(lines[i])) { - end = i; - break; - } - } - return lines.slice(start, end).join("\n").trim(); -} - -async function uploadFile(file, uploadUrl, target) { - process.stdout.write(`Uploading ${file.name} to ${target}...\n`); - const response = await globalThis.fetch(uploadUrl, { - method: "PUT", - headers: { "JOB-TOKEN": jobToken }, - body: createReadStream(file.path), - duplex: "half", - }); - if (!response.ok) { - throw new Error(`${target} upload failed for ${file.name}: HTTP ${response.status} ${await response.text()}`); - } -} - -function validateUpdateMetadataReferences(metadataFile, uploadedFiles) { - const text = readFileSyncUtf8(metadataFile.path); - const uploadedNames = new Set(uploadedFiles.map((file) => safeAssetName(file.name))); - const references = [...text.matchAll(/^\s*(?:-\s+url:|path:)\s*["']?([^"'\r\n]+?)["']?\s*$/gm)] - .map((match) => basename(match[1].trim())); - if (references.length === 0) { - throw new Error(`${metadataFile.name} does not reference a release artifact.`); - } - for (const reference of references) { - if (!uploadedNames.has(reference)) { - throw new Error(`${metadataFile.name} references missing release artifact ${reference}.`); - } - } -} - -function readFileSyncUtf8(path) { - return readFileSync(path, "utf8"); -} - -async function verifyPublicLatestFile(file, packageBaseUrl) { - const publicUrl = `${packageBaseUrl}/${encodeURIComponent(safeAssetName(file.name))}?release=${encodeURIComponent(tag)}`; - const response = await globalThis.fetch(publicUrl, { cache: "no-store" }); - if (!response.ok) { - throw new Error(`Public updater verification failed for ${file.name}: HTTP ${response.status}`); - } - const expected = await readFile(file.path); - const actual = Buffer.from(await response.arrayBuffer()); - if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) { - throw new Error(`Public updater verification returned stale or altered ${file.name}.`); - } - process.stdout.write(`Verified public latest metadata ${file.name}.\n`); -} - -async function upsertRelease(releaseUrl, description, desiredLinks) { - const headers = { "JOB-TOKEN": jobToken, "Content-Type": "application/json" }; - const existingUrl = `${releaseUrl}/${encodeURIComponent(tag)}`; - const existingResponse = await globalThis.fetch(existingUrl, { headers }); - - if (existingResponse.status === 404) { - const createResponse = await globalThis.fetch(releaseUrl, { - method: "POST", - headers, - body: JSON.stringify({ - name: `D3RO Voice ${tag}`, - tag_name: tag, - description, - assets: { links: desiredLinks }, - }), - }); - if (!createResponse.ok) { - throw new Error(`Release creation failed: HTTP ${createResponse.status} ${await createResponse.text()}`); - } - return; - } - - if (!existingResponse.ok) { - throw new Error(`Release lookup failed: HTTP ${existingResponse.status} ${await existingResponse.text()}`); - } - - const existing = await existingResponse.json(); - const updateResponse = await globalThis.fetch(existingUrl, { - method: "PUT", - headers, - body: JSON.stringify({ name: `D3RO Voice ${tag}`, description }), - }); - if (!updateResponse.ok) { - throw new Error(`Release update failed: HTTP ${updateResponse.status} ${await updateResponse.text()}`); - } - - const existingLinks = Array.isArray(existing?.assets?.links) ? existing.assets.links : []; - for (const desired of desiredLinks) { - const match = existingLinks.find((link) => link?.name === desired.name); - const linksBase = `${existingUrl}/assets/links`; - const response = await globalThis.fetch(match ? `${linksBase}/${encodeURIComponent(match.id)}` : linksBase, { - method: match ? "PUT" : "POST", - headers, - body: JSON.stringify(desired), - }); - if (!response.ok) { - throw new Error(`Release link upsert failed for ${desired.name}: HTTP ${response.status} ${await response.text()}`); - } - } -} diff --git a/scripts/ci/publish-updater-release.mjs b/scripts/ci/publish-updater-release.mjs deleted file mode 100644 index 558eee4..0000000 --- a/scripts/ci/publish-updater-release.mjs +++ /dev/null @@ -1,316 +0,0 @@ -// scripts/ci/publish-updater-release.mjs -// 자동 업데이트 채널(latest)에 디스크톱 설치본을 게시한다. -// -// 전제: 설치본이 Cloudflare 업로드 한도(100MiB) 아래여야 한다. 그래서 로컬 AI -// 런타임(사이드카/ffmpeg)은 설치본에 넣지 않고, 앱이 처음 필요할 때 -// `runtime-latest`에서 내려받는다(RuntimeProvisioner, `npm run release:portable`가 게시). -// -// 정책 예외(명시): -// - 이 채널은 일반적으로 Authenticode 서명을 요구한다. 서명 인증서가 준비되기 전까지 -// 업데이트를 전달할 수 없어, **무서명 빌드를 명시적 승인(--ack-unsigned)으로만** 게시한다. -// - 검증되지 않은 서명을 조용히 게시하지 않는다: 승인 플래그가 없으면 즉시 실패한다. -// -// 사용: -// npm run build --workspace=@d3ro/desktop -// node scripts/ci/publish-updater-release.mjs --build --ack-unsigned -// node scripts/ci/publish-updater-release.mjs --check # 게시 예정만 확인 - -import credentialHelpers from '../lib/credentials.cjs' -import { spawnSync } from 'node:child_process' -import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs' -import { readFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { - RUNTIME_MIN_VERSION_SOURCE, - WINDOWS_X64_TARGET, - assertRuntimeFeedCompatible, - parseRuntimeMinVersions, -} from './lib/runtime-feed-gate.mjs' -import { assertValidUpdatePolicy } from './lib/update-policy-schema.mjs' - -const { forgejoAuthorization } = credentialHelpers - -const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..') -const desktopDir = join(root, 'apps', 'desktop') -const args = process.argv.slice(2) -const check = args.includes('--check') -const ackUnsigned = args.includes('--ack-unsigned') -const build = args.includes('--build') - -const FEED = 'https://git.chanpaca.net/api/packages/yunchan/generic/d3ro-voice' -/** Cloudflare 업로드 본문 한도 (실측: 110MiB → 413) */ -const MAX_UPLOAD_BYTES = 100 * 1024 * 1024 - -const version = JSON.parse( - readFileSync(join(root, 'release', 'product-version.json'), 'utf8'), -).version -const releaseDir = join(desktopDir, 'release', version) - -if (build) { - const appDir = join(releaseDir, 'win-unpacked') - - // 1) 먼저 unpacked 트리빌드한다. - console.log('[updater] electron-builder --dir (앱 전용 — 런타임 제외)') - const result = spawnSync( - 'npx', - [ - 'electron-builder', - '--win', - 'dir', - '--x64', - '--config', - 'electron-builder.yml', - '--publish', - 'never', - '-c.win.forceCodeSigning=false', - '-c.npmRebuild=false', - ], - { cwd: desktopDir, stdio: 'inherit', shell: process.platform === 'win32' }, - ) - if (result.status !== 0) { - console.error(`[updater] 빌드 실패 (exit ${result.status ?? 'null'})`) - process.exit(result.status ?? 1) - } - - // 2) 네이티브 모듈 ABI 보장 + 검증 (호스트 Node ABI가 섞이면 이 시작조차 못 한다) - runNodeScript('scripts/ci/fix-native-abi.mjs', ['--dir', appDir]) - runNodeScript('scripts/ci/verify-native-abi.mjs', ['--dir', appDir]) - - // electron-updater 설정 파일을 보장한다(없으면 자동 업데이트가 동작하지 않는다) - runNodeScript('scripts/ci/write-app-update-yml.mjs', ['--dir', appDir]) - - // 3) 검증된 트리에서 설치본 생성 (--prepackaged = 재빌드 없이 그대로 패키징) - console.log('[updater] electron-builder --prepackaged (NSIS x64)') - const packageResult = spawnSync( - 'npx', - [ - 'electron-builder', - '--prepackaged', - appDir, - '--win', - 'nsis', - '--x64', - '--config', - 'electron-builder.yml', - '--publish', - 'never', - '-c.win.forceCodeSigning=false', - '-c.npmRebuild=false', - ], - { cwd: desktopDir, stdio: 'inherit', shell: process.platform === 'win32' }, - ) - if (packageResult.status !== 0) { - console.error(`[updater] 설치본 생성 실패 (exit ${packageResult.status ?? 'null'})`) - process.exit(packageResult.status ?? 1) - } -} - -/** 이 스크립트와 같은 Node로 CI 스크립트를 실행한다 */ -function runNodeScript(relativePath, scriptArgs) { - console.log(`[updater] $ node ${relativePath} ${scriptArgs.join(' ')}`) - const result = spawnSync(process.execPath, [join(root, relativePath), ...scriptArgs], { - cwd: root, - stdio: 'inherit', - }) - if (result.status !== 0) { - console.error(`[updater] ${relativePath} 실패 (exit ${result.status ?? 'null'})`) - process.exit(result.status ?? 1) - } -} - -const metadataPath = join(releaseDir, 'latest.yml') -if (!existsSync(metadataPath)) { - console.error( - `[updater] latest.yml이 없습니다: ${metadataPath}\n --build로 먼저 빌드하세요.`, - ) - process.exit(1) -} - -const candidates = readdirSync(releaseDir).filter( - (name) => /\.exe$/.test(name) && !/__uninstaller|apponly/i.test(name), -) -const installer = candidates.find((name) => name.includes('Setup')) ?? candidates[0] -if (!installer) { - console.error(`[updater] 설치본을 찾을 수 없습니다: ${releaseDir}`) - process.exit(1) -} - -const installerPath = join(releaseDir, installer) -const blockmapPath = `${installerPath}.blockmap` -const policyPath = join(root, 'release', 'update-policy.json') - -// 원격 정책은 오타 하나로 킬 스위치·staged rollout 이 조용히 꺼질 수 있다 — 올리기 전에 엄격히 검증한다. -if (existsSync(policyPath)) { - try { - assertValidUpdatePolicy(readFileSync(policyPath), 'release/update-policy.json') - } catch (error) { - console.error(`[updater] ${error instanceof Error ? error.message : String(error)}`) - process.exit(1) - } -} - -const payloads = [ - { name: installer, path: installerPath, type: 'application/octet-stream' }, - { name: `${installer}.blockmap`, path: blockmapPath, type: 'application/octet-stream' }, - { name: 'latest.yml', path: metadataPath, type: 'text/yaml' }, - { name: 'update-policy.json', path: policyPath, type: 'application/json' }, -].filter((payload) => existsSync(payload.path)) - -const installerSize = statSync(installerPath).size -console.log( - [ - `[updater] 버전 ${version}`, - ` 설치본 : ${installer} (${(installerSize / 1048576).toFixed(1)}MiB)`, - ` 한도 : ${(MAX_UPLOAD_BYTES / 1048576).toFixed(0)}MiB (Cloudflare 업로드 본문 한도)`, - ].join('\n'), -) - -if (installerSize > MAX_UPLOAD_BYTES) { - console.error( - [ - '[updater] 설치본이 업로드 한도를 넘습니다 — 게시할 수 없습니다.', - ' 런타임(사이드카/ffmpeg)을 설치본에 다시 넣지 않았는지 확인하세요:', - ' `apps/desktop/electron-builder.yml`의 extraResources / files / asarUnpack.', - ].join('\n'), - ) - process.exit(1) -} - -// 설치본에 app-update.yml이 없으면 electron-updater가 설정을 읽지 못해 자동 업데이트가 죽는다. -const packagedUpdateConfig = join(releaseDir, 'win-unpacked', 'resources', 'app-update.yml') -if (!existsSync(packagedUpdateConfig)) { - console.error('[updater] app-update.yml 누락 — write-app-update-yml.mjs를 먼저 실행하세요.') - process.exit(1) -} - -const metadata = readFileSync(metadataPath, 'utf8') -if (!metadata.includes(`version: ${version}`)) { - console.error('[updater] latest.yml의 버전이 product-version.json과 다릅니다.') - process.exit(1) -} - -const targets = [`${FEED}/${version}`, `${FEED}/latest`] - -// 앱이 요구하는 런타임(RUNTIME_MIN_VERSION)을 runtime-latest 가 아직 제공하지 못하면, 이 설치본으로 -// 업데이트한 사용자는 로컬 STT 엔진을 쓸 수 없다. latest.yml 을 올리기 전에 fail-closed 로 확인한다. -try { - const runtime = await assertRuntimeFeedCompatible({ - url: `${FEED}/runtime-latest/runtime.json`, - fetchImpl: (url, init) => fetch(url, init), - minVersions: parseRuntimeMinVersions(readFileSync(join(root, RUNTIME_MIN_VERSION_SOURCE), 'utf8')), - target: WINDOWS_X64_TARGET, - }) - console.log(`[updater] runtime-latest ${runtime.version} 이 이 빌드의 최소 런타임 요구를 만족합니다.`) -} catch (error) { - console.error(`[updater] ${error instanceof Error ? error.message : String(error)}`) - process.exit(1) -} - -if (check) { - console.log('[updater] (check) 게시 예정:') - for (const target of targets) { - for (const payload of payloads) { - console.log(` PUT ${target}/${payload.name} (${statSync(payload.path).size} bytes)`) - } - } - process.exit(0) -} - -if (!ackUnsigned) { - console.error( - [ - '[updater] 무서명 빌드를 stable 채널에 게시하려면 명시적 승인이 필요합니다.', - ' 서명 인증서가 준비되면 이 플래그 없이 게시하세요(권장).', - ' 승인: --ack-unsigned', - ].join('\n'), - ) - process.exit(1) -} - -const authorization = forgejoAuthorization() - -/** - * 원격 파일이 로컬 바이트와 같은지 판단한다. - * Forgejo generic registry는 HEAD를 405로 거부하고 해시도 주지 않으므로, - * Range GET으로 크기를 본 뒤 1MiB 이하는 실제 바이트까지 비교한다. - * (크기만 비교하면 버전 문자열만 바뀐 latest.yml 같은 메타데이터를 놓친다 — 실측 사고.) - */ -async function remoteIsIdentical(url, body, fetchImpl) { - const probe = await fetchImpl(url, { headers: { Range: 'bytes=0-0' } }).catch(() => null) - if (!probe?.ok) return false - const contentRange = probe.headers.get('content-range') - const remoteSize = contentRange ? Number(contentRange.split('/')[1]) : NaN - if (!Number.isFinite(remoteSize) || remoteSize !== body.length) return false - if (body.length > 1024 * 1024) return true - const full = await fetchImpl(url).catch(() => null) - if (!full?.ok) return false - const remoteBytes = Buffer.from(await full.arrayBuffer()) - return remoteBytes.length === body.length && remoteBytes.equals(body) -} - -async function forgejoFetch(url, init = {}) { - return fetch(url, { - ...init, - headers: { Authorization: authorization, ...(init.headers ?? {}) }, - }) -} - -console.log( - [ - '[updater] 경고: 무서명 설치본을 stable(latest) 채널에 게시합니다.', - ' - electron-updater는 app-update.yml에 publisherName이 없으면 서명 검증을 건너뛰므로', - ' 설치 자체는 정상 동작합니다.', - ' - 인증서가 준비되면 이 버전보다 높은 버전으로 서명 게시하여 대체하세요.', - ].join('\n'), -) - -for (const target of targets) { - for (const payload of payloads) { - const url = `${target}/${encodeURIComponent(payload.name)}` - const body = await readFile(payload.path) - - // Forgejo generic registry는 HEAD를 405로 거부하고 해시도 주지 않는다. - // 크기만 비교하면 버전 문자열만 바뀐 latest.yml을 "동일"로 오판한다 — 내용까지 비교한다. - if (await remoteIsIdentical(url, body, forgejoFetch)) { - console.log(`[updater] 이미 동일한 파일이 있습니다(건너): ${url}`) - continue - } - - // 메타데이터는 최신을 가리켜야 하므로 기존 파일을 지우고 쓴다(PUT은 409를 돌려준다). - const existing = await forgejoFetch(url, { headers: { Range: 'bytes=0-0' } }).catch(() => null) - if (existing?.ok) { - await forgejoFetch(url, { method: 'DELETE' }).catch(() => null) - } - - const response = await forgejoFetch(url, { - method: 'PUT', - headers: { 'Content-Type': payload.type }, - body, - }) - if (!response.ok) { - const hint = - response.status === 409 - ? ' (409: 같은 경로에 다른 내용이 이미 있음 — 게시된 버전을 덮어쓰지 않습니다)' - : response.status === 413 - ? ' (413: Cloudflare 업로드 한도 초과 — 런타임 분리 확인)' - : '' - console.error( - `[updater] 업로드 실패 (HTTP ${response.status}): ${target}/${payload.name}${hint}`, - ) - process.exit(1) - } - console.log(`[updater] uploaded ${target}/${payload.name}`) - } -} - -console.log( - [ - '', - `[updater] 게시 완료: ${version}`, - ` 피드 : ${FEED}/latest`, - ` 메타 : ${FEED}/latest/latest.yml`, - ' 기존 설치본(canonical feed 사용)은 다음 업데이트 확인 때 이 버전을 받습니다.', - ' legacy GitLab mirror를 보는 1.0.x 이하 설치는 1회 수동 설치가 필요합니다.', - ].join('\n'), -) \ No newline at end of file