d3ro-voice/packages/core/src/recent-writes.ts
Yun Chan 3cac14f668
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Has been cancelled
deploy-site / deploy (push) Has been cancelled
ci / 워크스페이스 빌드 검증 (push) Has been cancelled
ci / 모바일 린트·타입·Jest (push) Has been cancelled
ci / Supabase Edge Functions + Cloudflare Worker (push) Has been cancelled
ci / .NET API 서버 테스트 (push) Has been cancelled
feat(desktop): typo auto-correct and context-aware sentence prediction
Typo auto-correct (INPUT-19)
- TypoCorrectionService + core typo-correction: 2-set Korean layout
  mistypes both ways, always-wrong spellings, near-misses of the user's
  frequent words, optional model check re-validated in core; applied by
  backspace N + paste and cancelled on new keys or window change.

Prediction quality (INPUT-20/21)
- gemma models are sent raw with the user's unfinished sentence pre-filled
  into the model turn, so the model truly continues the text (mid-word
  joins and spacing exact). Other models keep the instruction prompt.
- Context: text before the caret (opening lines and a fact list of names,
  dates, amounts outside the 400-char window), messages just sent in the
  same chat window (memory only, 30 min), personal-graph follow-ups and
  IDF-ranked related sentences with Korean stemming.
- Guards: first sentence only, restated-prefix stripping (also fixes the
  instruction path), repeat drop, no invented dates/names/numbers
  (one retry), plain -다 register, no emoji unless the user uses them,
  search-box keywords. Fill loop mixes instruction prompts for variety.
- Opt-in real-model probe: tests/integration/suggestion-quality.ollama.test.ts

Suggestions now actually show up
- Terminal (Claude Code): caret trust from the input line, not the whole
  screen (status line below the box blocked every keystroke); Korean
  composition counts as typing at the end; a grey placeholder filling the
  empty box at once is not user text.
- Chrome: UIA focus flicker while typing no longer resets "edited".
- KakaoTalk/RichEdit: trailing paragraph mark ignored for edit position
  and stripped so accepted text keeps its separating space.
- While the overlay is visible the suggestion shortcuts are captured so
  Ctrl+Alt+Enter no longer also types a newline; released when hidden.
- nut-js preloaded after boot (first accept waited 4.8 s).
2026-10-03 21:48:28 +09:00

94 lines
3.4 KiB
TypeScript

// packages/core — "이 창에서 조금 전에 쓴 글" 기억 (메모리 전용, 순수 로직).
//
// 왜 필요한가: 채팅·메신저는 보내는 순간 입력칸이 빈다. 그래서 다음 메시지를 쓸 때 커서 앞
// 텍스트에는 방금 보낸 말이 없고, 모델은 대화가 어디까지 왔는지 모른다("ㅇㅋ 그럼 나도 " 만 보고
// 엉뚱한 말을 잇는다). 입력칸이 비워지는 순간 직전 내용을 "보낸 글" 로 잠시 기억했다가 같은 창의
// 다음 제안 문맥에 넣는다.
//
// 저장하지 않는다 — 프로세스 메모리에만, 짧게(기본 30분) 둔다.
export interface RecentWriteMeta {
windowHandle: number | null
appName: string | null
windowTitle: string | null
}
export interface RecentWrite extends RecentWriteMeta {
text: string
at: number
}
export interface RecentWritesOptions {
ttlMs?: number
maxEntries?: number
maxChars?: number
}
const DEFAULT_TTL_MS = 30 * 60_000
const DEFAULT_MAX_ENTRIES = 24
const DEFAULT_MAX_CHARS = 600
function sameWindow(a: RecentWriteMeta, b: RecentWriteMeta): boolean {
if (a.windowHandle !== null && b.windowHandle !== null && a.windowHandle === b.windowHandle) return true
const appA = a.appName?.trim().toLowerCase()
const appB = b.appName?.trim().toLowerCase()
return Boolean(appA) && appA === appB && Boolean(a.windowTitle) && a.windowTitle === b.windowTitle
}
export class RecentWritesBuffer {
private _entries: RecentWrite[] = []
private _fieldKey = ''
private _fieldText = ''
private readonly _ttlMs: number
private readonly _maxEntries: number
private readonly _maxChars: number
constructor(options: RecentWritesOptions = {}) {
this._ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
this._maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES
this._maxChars = options.maxChars ?? DEFAULT_MAX_CHARS
}
/**
* 입력칸 스냅샷을 본다. 같은 칸에서 내용이 있던 칸이 비워지면(보냄) 직전 내용을 기억한다.
*
* 칸이 바뀌면 기준만 다시 잡는다 — 다른 칸으로 옮겨 간 것은 "보냄" 이 아니다.
* 일부만 지운 경우(고쳐 쓰기)도 보냄이 아니다: 남은 글이 없을 때만 기록한다.
*/
observe(fieldKey: string, text: string, meta: RecentWriteMeta, now: number): RecentWrite | null {
if (fieldKey !== this._fieldKey) {
this._fieldKey = fieldKey
this._fieldText = text
return null
}
const previous = this._fieldText.trim()
this._fieldText = text
if (text.trim().length > 0 || previous.length < 2) return null
const entry: RecentWrite = {
...meta,
text: previous.length > this._maxChars ? previous.slice(-this._maxChars) : previous,
at: now
}
this._prune(now)
this._entries.push(entry)
if (this._entries.length > this._maxEntries) this._entries.splice(0, this._entries.length - this._maxEntries)
return entry
}
/** 같은 창에서 조금 전에 쓴 글 (오래된 것부터, 최대 limit 개). */
listFor(meta: RecentWriteMeta, now: number, limit = 4): RecentWrite[] {
this._prune(now)
return this._entries.filter((entry) => sameWindow(entry, meta)).slice(-limit)
}
clear(): void {
this._entries = []
this._fieldKey = ''
this._fieldText = ''
}
private _prune(now: number): void {
this._entries = this._entries.filter((entry) => now - entry.at <= this._ttlMs)
}
}