fix: red-team round 3 hardening across desktop, mobile, core and server

Batch of red-team r3 fixes that were in the working tree before the
2026-09-28 design overhaul, committed as one unit with their tests.

- desktop main: STT timeouts and sidecar, voice recording store, sync
  (credentials, audio, knowledge reindex, push gates), runtime
  provisioner, update policy, AltGr keybindings, voice-command policy,
  dictionary file codec/limits, meeting transcript condensing and a
  local recording ledger so interrupted-session recovery only closes
  meetings this device recorded (a phone's live meeting is left alone).
- mobile: login CSRF via implicit token callbacks rejected, account
  deletion/retention, durable queue retention, knowledge realtime
  without unfiltered DELETE, meeting re-record failure paths, cloud STT
  client, preferences store/resync.
- core: text chunking splits long unbroken transcripts to fit, template
  field policy, dictionary limits, meeting markdown inline handling.
- server: payple webhook policy and cancellation order scope, meeting
  document generation quota, team RPC null-role guard, unified LLM
  quota in-flight accounting, knowledge chunk vector index, meeting
  re-record failure paths (migrations 20260929*).
- ci: portable/runtime feed gates, update-policy schema, Forgejo file
  delete and alias planning.

Four older tests are updated to the new contracts rather than the old
behavior: token-pair auth callbacks are rejected, knowledge realtime no
longer subscribes to DELETE, long transcript lines are split, and
meeting recovery requires the local recording ledger for empty rows.
This commit is contained in:
Yun Chan 2026-09-28 20:45:52 +09:00
parent 2428ede03d
commit ba9ef9741e
161 changed files with 17056 additions and 2379 deletions

View file

@ -86,7 +86,8 @@ export function createDefaultSuggestionServiceDeps(): SuggestionServiceDeps {
return {
repository: createSqliteSuggestionRepository(),
budget: new SuggestionBudget(),
warmth: new ModelWarmTracker(),
// 상주 추정은 로컬 LLM 의 모든 요청(받아쓰기·음성 대화 포함)을 본다.
warmth: new ModelWarmTracker({ residentUntil: (model) => getLocalLLMService().residency?.residentUntil(model) ?? null }),
foreground: {
currentWindowHandle: () => getForegroundWindowInfo()?.hwnd ?? null
},
@ -186,6 +187,8 @@ export class SuggestionService extends EventEmitter {
private _provenance: SuggestionProvenance | null = null
/** 세션을 만든 입력창의 최상위 창 핸들 — 수락 직전 포커스가 그대로인지 확인한다. */
private _windowHandle: number | null = null
/** 이 세션의 이력 행 id — 한 세션은 한 행이다(채우기 후보·수락은 이 행을 갱신한다). */
private _sessionRecordId: string | null = null
/** 요청 예산 (간격 · 분/일 카운트 · 실패 쿨다운) */
private readonly _budget: SuggestionBudget
@ -350,7 +353,24 @@ export class SuggestionService extends EventEmitter {
setEnabled(enabled: boolean): void {
configSet('suggestionEnabled', enabled)
if (!enabled) this.dismiss('disabled')
else void this.warmUp()
// 입력 맥락(수집 동의)이 없으면 제안이 뜰 수 없다 — 모델만 데우지 않는다.
else if (hasInputContextConsent()) void this.warmUp()
this.emit('state-changed', this.getState())
}
/**
* 입력 수집 동의·일시정지가 바뀌었다. 입력 맥락이 끊기면 떠 있는 세션·채우기 루프를 닫고
* 붙잡고 있던 마지막 문맥을 버린다(동의를 철회한 뒤 수동 요청이 옛 접두로 생성하지 않게).
* 다시 켜지면 제안이 켜져 있을 때만 모델을 데운다.
*/
handleInputConsentChanged(): void {
if (!hasInputContextConsent()) {
this.dismiss('disabled')
this._lastContext = null
this._lastRequestedPrefix = ''
} else if (this.isEnabled()) {
void this.warmUp()
}
this.emit('state-changed', this.getState())
}
@ -579,6 +599,7 @@ export class SuggestionService extends EventEmitter {
if (this.isPresentationActive) this.dismiss(reason)
return { ok: false, reason }
}
if (context.caretReliable === false) return { ok: false, reason: 'caret-unknown' }
const prefix = normalizeRequestPrefix(context.prefix)
if (prefix.length < 1) return { ok: false, reason: 'empty-prefix' }
@ -619,6 +640,7 @@ export class SuggestionService extends EventEmitter {
editedSinceFocus: context.editedSinceFocus,
typedRecently: context.typedRecently,
prefix: context.prefix,
caretReliable: context.caretReliable !== false,
idleMs: context.idleMs,
triggerDelayMs: config.triggerDelayMs,
minPrefixChars: config.minPrefixChars,
@ -696,7 +718,11 @@ export class SuggestionService extends EventEmitter {
if (!this._isCurrentFallbackContext(prefix, context, token)) return false
const trimmedPrefix = normalizeSessionPrefix(prefix)
const localMemory = memory ?? this._collectMemoryHints(trimmedPrefix, context.appName)
const entries = buildLocalSuggestionCandidateEntries(trimmedPrefix, localMemory, maxCandidates, maxChars)
// 원문 뒤 공백(단어를 끝냈는가)은 세션 접두 정규화가 지운다 — 최신 원문에서 읽어 넘긴다.
const rawPrefix = this._lastContext?.prefix ?? context.prefix
const entries = buildLocalSuggestionCandidateEntries(trimmedPrefix, localMemory, maxCandidates, maxChars, {
wordFinished: /\s$/u.test(rawPrefix)
})
if (entries.length === 0) return false
this._partialText = ''
@ -795,6 +821,7 @@ export class SuggestionService extends EventEmitter {
// 후보가 오기 전에 빈 화면으로 기다리게 하지 않는다 — 즉시 자리를 잡고
// "생성 중" 을 보여준 뒤 내용으로 채운다. 실측 5초 지연에서 특히 중요하다.
this._candidates = []
this._sessionRecordId = null
this._activeIndex = 0
this._anchor = context.anchor
this._anchorKind = context.anchorKind
@ -904,6 +931,9 @@ export class SuggestionService extends EventEmitter {
if (!timedOut) return
this._lastSkipReason = 'generation-failed'
// warm 이라 믿고 보낸 요청이 시간 초과했다면 모델은 이미 내려갔다(다른 기능의 짧은 keep_alive 등)
// — 다음 멈춤은 같은 콜드 요청을 되풀이하지 말고 워밍업("준비 중")부터 한다.
this._warmth.noteCold(model)
this._noteFailure(`timeout ${timeoutMs}ms`)
if (
this._publishLocalMemory(
@ -1102,13 +1132,10 @@ export class SuggestionService extends EventEmitter {
logger.debug(`제안 후보 추가 ${this._candidates.length}/${SUGGESTION_DEFAULTS.maxCandidatesTotal}`)
this._armVisibleTtl()
this.emit('updated', this.getState())
this._recordSuggestion({
prefix,
text: candidateText,
model,
latencyMs: 0,
candidateCount: this._candidates.length
})
// 채우기 후보는 새 행이 아니다 — 세션 행의 후보 수만 늘린다(지연 0 행이 평균·수락률을 망쳤다).
if (this._sessionRecordId) {
this._repository.updateSessionCandidates?.(this._sessionRecordId, this._candidates.length)
}
return true
} catch (error) {
if (!abort.signal.aborted) {
@ -1320,6 +1347,7 @@ export class SuggestionService extends EventEmitter {
this._generatedForPrefix = ''
this._targetTotal = 0
this._provenance = null
this._sessionRecordId = null
this._lastSkipReason = reason
this._abort?.abort()
this._abort = null
@ -1350,12 +1378,21 @@ export class SuggestionService extends EventEmitter {
logger.info(`제안 수락 무시: 표시 중인 후보 없음 (index=${index ?? 'active'})`)
return { ok: false, reason: 'already-visible' }
}
// 케어렛을 모르는 필드에서 문서 중간을 고친 뒤다 — 후보는 문서 끝의 이어 쓰기라
// 실제 커서(문서 중간)에 붙이면 엉뚱한 곳에 문장이 들어간다.
if (this._lastContext?.caretReliable === false) {
logger.info('제안 수락 거부: 케어렛 위치를 알 수 없고 마지막 편집이 문서 끝이 아니다')
this.dismiss('caret-unknown')
this.emit('state-changed', this.getState())
return { ok: false, reason: 'caret-unknown' }
}
// 후보는 정제 과정에서 앞 공백을 잃는다 — 커서 앞 원문의 마지막 글자를 보고 구분 공백을
// 붙인다(joinSuggestion). 세션을 닫기 전에(dismiss 가 세션 접두를 지운다) 계산한다.
const text = joinSuggestion(this._acceptPrefix(), candidate.text, candidate.joint ?? 'separate')
const appName = this._appName
const windowTitle = this._windowTitle
const targetWindow = this._windowHandle
const sessionRecordId = this._sessionRecordId
// 먼저 창을 닫고 생성을 멈춘다 — 수락은 즉시 반응해야 한다.
this.dismiss('accepted')
@ -1401,7 +1438,13 @@ export class SuggestionService extends EventEmitter {
logger.info(`제안 수락: ${text.length}자 삽입 (method=${method === 'keyboard' ? 'keyboard' : 'clipboard'}, app=${appName ?? '-'})`)
// 이력은 후보 원문으로 기록돼 있다 — 구분 공백이 붙은 삽입 문자열로는 찾지 못한다.
this._repository.markAccepted(candidate.text)
// 세션 행을 알면 그 행을 수락으로 표시한다 — 텍스트로 찾으면 로컬 기억의 2번째 이후 후보는
// 행이 없어 사라지거나 같은 문구의 옛 행(다른 앱·다른 날)이 수락으로 잡혔다.
if (sessionRecordId && this._repository.markSessionAccepted) {
this._repository.markSessionAccepted(sessionRecordId, candidate.text)
} else {
this._repository.markAccepted(candidate.text)
}
// 수락한 문장은 사용자 문체의 확실한 표본이다 (학습 동의 시에만 저장됨).
this._learning.recordAccepted(candidate.text, { appName, windowTitle })
return { ok: true }
@ -1455,7 +1498,8 @@ export class SuggestionService extends EventEmitter {
learnTypedText: configGet('inputLearnTypedText') === true,
appName: this._appName
})
this._repository.record({ ...input, prefix: persistPrefix ? input.prefix : '', appName: this._appName })
const id = this._repository.record({ ...input, prefix: persistPrefix ? input.prefix : '', appName: this._appName })
this._sessionRecordId = typeof id === 'string' ? id : null
}
/** 테스트/진단 — 현재 앱이 제외 대상인지. */
@ -1483,6 +1527,11 @@ function sanitizePartial(raw: string): string {
return lines.slice(0, 2).join(' ').slice(0, SUGGESTION_MAX_OUTPUT_CHARS)
}
/** 입력 텔레메트리가 맥락을 보낼 수 있는 상태인가 (수집 동의 + 일시정지 아님). */
export function hasInputContextConsent(): boolean {
return configGet('inputTelemetryEnabled') === true && configGet('inputTelemetryPaused') !== true
}
let instance: SuggestionService | null = null
export function getSuggestionService(): SuggestionService {