feat(input): upgrade graph personalization, english morphology detection, and atomic SendInput replacement
This commit is contained in:
parent
52eef21bab
commit
cd4a452148
21 changed files with 1098 additions and 110 deletions
|
|
@ -249,12 +249,13 @@ async function initInputIntelligence(): Promise<void> {
|
|||
typo.on('corrected', () => {
|
||||
if (suggestion.isPresentationActive) suggestion.dismiss('stale')
|
||||
})
|
||||
// 인플레이스 자동 교정(handleTypingContext)은 타이핑과 절대 경합하지 않도록
|
||||
// 0.1ms 결정적 한영·영문오타 엔진(layoutOnly: true, 커서 직전 어절만 교체)만 즉시 실행하고,
|
||||
// 문장 단위 로컬 LLM(Gemma) 오타 교정은 키보드를 건드리지 않는 제안 팝업(propose)에서만 제시한다.
|
||||
// 인플레이스 자동 교정(handleTypingContext)은 커서 직전 꼬리 어절만 원자적(단일 Win32 SendInput)으로 교체한다:
|
||||
// 1단계(25ms 단어 경계 / 650ms 어절 끝): 결정적 한영·영문오타(Araso) 즉시 전환
|
||||
// 2단계(350ms 수상한 어절 경계 / 600ms 유휴): 철자 사전·개인 어휘·자모 잡음 및 로컬 LLM(Gemma) 꼬리 오타 보정
|
||||
// 이미 지나간 문장 앞쪽 오타는 키보드를 건드리지 않는 제안 팝업(propose)에서 제시한다.
|
||||
suggestion.setTypoProposer({ propose: (context, signal, options) => typo.propose(context, signal, options) })
|
||||
telemetry.on('typed-context', (context) => {
|
||||
const verdict = typo.handleTypingContext(context, { layoutOnly: true, trailingWordOnly: true })
|
||||
const verdict = typo.handleTypingContext(context, { trailingWordOnly: true })
|
||||
if (verdict === 'pass') suggestion.handleTypingContext(context)
|
||||
})
|
||||
telemetry.on('state-changed', (state) =>
|
||||
|
|
|
|||
|
|
@ -16,8 +16,10 @@ import {
|
|||
continuationsFrom,
|
||||
extractTerms,
|
||||
jaccard,
|
||||
rankTwoHopGraphTargets,
|
||||
scoreRelatedNodes,
|
||||
splitSentences,
|
||||
stemContinuationsFrom,
|
||||
type GraphContext,
|
||||
type PersonalGraphQuery,
|
||||
type PersonalGraphStats,
|
||||
|
|
@ -40,13 +42,20 @@ export type { PersonalGraphQuery, PersonalGraphStats }
|
|||
const MAINTENANCE_NODE_LIMIT = 300
|
||||
/** 관계 조회에서 최근 노드를 훑는 수. */
|
||||
const TERM_SCAN_LIMIT = 400
|
||||
/** 같은 앱에서 단문 메시지를 연속으로 보낼 때 follows 엣지로 잇는 최대 세션 간격 (10분). */
|
||||
const SESSION_FOLLOWS_WINDOW_MS = 10 * 60_000
|
||||
/** 새 문장을 넣을 때 즉시 shares_terms 엣지를 연결할 최근 노드 수. */
|
||||
const INCREMENTAL_SHARES_SCAN_LIMIT = 40
|
||||
|
||||
class PersonalGraphService {
|
||||
/** 앱별 마지막 학습 문장 — 카카오톡·슬랙 등 단문 메시지 사이의 follows 사슬을 잇는다. */
|
||||
private readonly _lastIndexedByScope = new Map<string, { phrase: string; at: number }>()
|
||||
|
||||
/**
|
||||
* 텍스트를 그래프에 반영한다.
|
||||
*
|
||||
* 문장마다 노드를 upsert 하고, 연속한 문장 쌍을 follows 엣지로, 용어를 충분히
|
||||
* 공유하는 쌍을 shares_terms 엣지로 남긴다.
|
||||
* 문장마다 노드를 upsert 하고, 연속한 문장 쌍(같은 앱의 직전 메시지 포함)을 follows 엣지로,
|
||||
* 용어를 충분히 공유하는 쌍을 shares_terms 엣지로 남긴다.
|
||||
*/
|
||||
indexText(
|
||||
text: string,
|
||||
|
|
@ -56,9 +65,17 @@ class PersonalGraphService {
|
|||
if (sentences.length === 0) return
|
||||
|
||||
const at = meta.at ?? Date.now()
|
||||
const scopeKey = meta.appName?.trim().toLowerCase() || null
|
||||
try {
|
||||
const db = getDatabase()
|
||||
|
||||
const recentExisting = db
|
||||
.select({ phrase: personalPhrases.phrase, terms: personalPhrases.terms })
|
||||
.from(personalPhrases)
|
||||
.orderBy(desc(personalPhrases.lastUsedAt))
|
||||
.limit(INCREMENTAL_SHARES_SCAN_LIMIT)
|
||||
.all()
|
||||
|
||||
for (const sentence of sentences) {
|
||||
const terms = extractTerms(sentence)
|
||||
db.insert(personalPhrases)
|
||||
|
|
@ -82,9 +99,36 @@ class PersonalGraphService {
|
|||
}
|
||||
})
|
||||
.run()
|
||||
|
||||
if (terms.length > 0) {
|
||||
for (const existing of recentExisting) {
|
||||
if (existing.phrase === sentence) continue
|
||||
const existingTerms = parseTerms(existing.terms)
|
||||
if (existingTerms.length === 0) continue
|
||||
if (jaccard(terms, existingTerms) >= SHARES_TERMS_MIN_SIMILARITY) {
|
||||
this._upsertEdge(existing.phrase, sentence, 'shares_terms')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// follows 엣지
|
||||
// 같은 앱에서 직전 세션(10분 이내)에 쓴 문장과 첫 문장을 follows 로 연결
|
||||
if (scopeKey) {
|
||||
const previousInScope = this._lastIndexedByScope.get(scopeKey)
|
||||
if (
|
||||
previousInScope &&
|
||||
previousInScope.phrase !== sentences[0] &&
|
||||
Math.abs(at - previousInScope.at) <= SESSION_FOLLOWS_WINDOW_MS
|
||||
) {
|
||||
this._upsertEdge(previousInScope.phrase, sentences[0], 'follows')
|
||||
}
|
||||
this._lastIndexedByScope.set(scopeKey, {
|
||||
phrase: sentences[sentences.length - 1],
|
||||
at
|
||||
})
|
||||
}
|
||||
|
||||
// follows 엣지 (같은 텍스트 내 인접 문장)
|
||||
for (const edge of buildSequenceEdges(sentences)) {
|
||||
this._upsertEdge(edge.from, edge.to, 'follows')
|
||||
}
|
||||
|
|
@ -135,7 +179,11 @@ class PersonalGraphService {
|
|||
* 3) related — 지금 문장·직전 문장·앞 문맥의 용어를 IDF 로 가중해 고른 관련 문장과,
|
||||
* 그 문장들 뒤에 이어 쓴 문장(follows 1단계 확장).
|
||||
*/
|
||||
retrieveContext(prefix: string, limit = 4, options: { appName?: string | null } = {}): GraphContext {
|
||||
retrieveContext(
|
||||
prefix: string,
|
||||
limit = 4,
|
||||
options: { appName?: string | null; recentWrites?: readonly string[] } = {}
|
||||
): GraphContext {
|
||||
const empty: GraphContext = { continuations: [], related: [], followUps: [] }
|
||||
const normalizedPrefix = prefix.replace(/\s+/gu, ' ').trim()
|
||||
if (normalizedPrefix.length < 2) return empty
|
||||
|
|
@ -143,19 +191,26 @@ class PersonalGraphService {
|
|||
try {
|
||||
const db = getDatabase()
|
||||
const context = analyzeWritingContext(prefix)
|
||||
const recentWriteSentences =
|
||||
options.recentWrites && options.recentWrites.length > 0
|
||||
? splitSentences(options.recentWrites[options.recentWrites.length - 1] ?? '')
|
||||
: []
|
||||
const anchorLastSentence =
|
||||
context.lastSentence ||
|
||||
(recentWriteSentences.length > 0 ? recentWriteSentences[recentWriteSentences.length - 1] : '')
|
||||
const inPrefix = (text: string): boolean => normalizedPrefix.includes(text)
|
||||
|
||||
// (1) 직전 문장 뒤에 이어 쓴 문장
|
||||
const followUps = this._followUpsAfter(context.lastSentence, context.currentSentence ? 2 : 3, inPrefix)
|
||||
// (1) 직전 문장(또는 방금 보낸 채팅 메시지) 뒤에 이어 쓴 문장
|
||||
const followUps = this._followUpsAfter(anchorLastSentence, context.currentSentence ? 2 : 3, inPrefix)
|
||||
|
||||
// (2) 꼬리 이어쓰기 — 지금 문장 안에서만 찾는다 (앞 문장 끝과 섞이지 않게)
|
||||
const tailSource = context.currentSentence || context.lastSentence
|
||||
const continuations = this._continuationsForTail(tailSource)
|
||||
|
||||
// (3) 관련 문장 — IDF 가중 용어 겹침 + follows 1단계 확장
|
||||
// (3) 관련 문장 — IDF 가중 용어 겹침 + 1-hop follows + 2-hop (shares_terms -> follows) 경로 확장
|
||||
const queryTerms = buildQueryTerms([
|
||||
{ text: context.currentSentence, weight: 2 },
|
||||
{ text: context.lastSentence, weight: 1.5 },
|
||||
{ text: anchorLastSentence, weight: 1.5 },
|
||||
{ text: context.earlierText.slice(-200), weight: 1 }
|
||||
])
|
||||
const recentNodes = db
|
||||
|
|
@ -185,22 +240,66 @@ class PersonalGraphService {
|
|||
if (related.length >= limit || related.includes(text) || followUps.includes(text) || inPrefix(text)) return
|
||||
related.push(text)
|
||||
}
|
||||
// 관련 문장의 다음 문장이 관련 문장 자체보다 "이어질 말" 에 가깝다 — 상위 앵커 2개만 확장한다.
|
||||
const anchors = scored.slice(0, 2).map((item) => item.text)
|
||||
const hops = anchors.length
|
||||
// 관련 문장의 다음 문장이 관련 문장 자체보다 "이어질 말" 에 가깝다 — 상위 앵커 확장 + 2-hop 경로 탐색
|
||||
const anchors = scored.slice(0, 3).map((item) => item.text)
|
||||
const firstHopEdges = anchors.length
|
||||
? db
|
||||
.select()
|
||||
.from(phraseEdges)
|
||||
.where(and(inArray(phraseEdges.fromPhrase, anchors), eq(phraseEdges.kind, 'follows')))
|
||||
.where(or(inArray(phraseEdges.fromPhrase, anchors), inArray(phraseEdges.toPhrase, anchors)))
|
||||
.orderBy(desc(phraseEdges.weight))
|
||||
.limit(6)
|
||||
.limit(12)
|
||||
.all()
|
||||
: []
|
||||
const directFollowHops = firstHopEdges.filter(
|
||||
(edge) => edge.kind === 'follows' && anchors.includes(edge.fromPhrase)
|
||||
)
|
||||
const normalizedFirstHop = firstHopEdges.flatMap((edge) => {
|
||||
if (edge.kind === 'follows' && anchors.includes(edge.fromPhrase)) {
|
||||
return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'follows' as const, weight: edge.weight }]
|
||||
}
|
||||
if (edge.kind === 'shares_terms') {
|
||||
if (anchors.includes(edge.fromPhrase)) {
|
||||
return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'shares_terms' as const, weight: edge.weight }]
|
||||
}
|
||||
if (anchors.includes(edge.toPhrase)) {
|
||||
return [{ from: edge.toPhrase, to: edge.fromPhrase, kind: 'shares_terms' as const, weight: edge.weight }]
|
||||
}
|
||||
}
|
||||
return []
|
||||
})
|
||||
const midNodes = [...new Set(normalizedFirstHop.map((edge) => edge.to))]
|
||||
const secondHopFollows = midNodes.length
|
||||
? db
|
||||
.select()
|
||||
.from(phraseEdges)
|
||||
.where(and(inArray(phraseEdges.fromPhrase, midNodes), eq(phraseEdges.kind, 'follows')))
|
||||
.orderBy(desc(phraseEdges.weight))
|
||||
.limit(12)
|
||||
.all()
|
||||
.map((edge) => ({
|
||||
from: edge.fromPhrase,
|
||||
to: edge.toPhrase,
|
||||
kind: 'follows' as const,
|
||||
weight: edge.weight
|
||||
}))
|
||||
: []
|
||||
const twoHopTargets = rankTwoHopGraphTargets({
|
||||
firstHopEdges: normalizedFirstHop,
|
||||
secondHopFollowEdges: secondHopFollows,
|
||||
queryTerms,
|
||||
exclude: (text) => inPrefix(text) || followUps.includes(text),
|
||||
limit: 2
|
||||
})
|
||||
|
||||
for (const item of scored) {
|
||||
push(item.text)
|
||||
const hop = hops.find((edge) => edge.fromPhrase === item.text)
|
||||
const hop = directFollowHops.find((edge) => edge.fromPhrase === item.text)
|
||||
if (hop) push(hop.toPhrase)
|
||||
}
|
||||
for (const target of twoHopTargets) {
|
||||
push(target)
|
||||
}
|
||||
return { continuations, related, followUps }
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
|
|
@ -305,7 +404,16 @@ class PersonalGraphService {
|
|||
)
|
||||
if (found.length > 0) return found
|
||||
}
|
||||
return []
|
||||
|
||||
// 정확한 문자열 꼬리가 어긋나도("회의록을 정리해서" vs "회의록 정리해서") 어간 열이 일치하면 이어쓰기를 뽑는다.
|
||||
const recentPhrases = db
|
||||
.select({ phrase: personalPhrases.phrase })
|
||||
.from(personalPhrases)
|
||||
.orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt))
|
||||
.limit(120)
|
||||
.all()
|
||||
.map((row) => row.phrase)
|
||||
return stemContinuationsFrom(recentPhrases, normalized, 3)
|
||||
}
|
||||
|
||||
/** 용어 공유 엣지를 백필한다 (기존 노드들 사이 관계 보강). */
|
||||
|
|
@ -469,6 +577,7 @@ class PersonalGraphService {
|
|||
|
||||
clearAll(): void {
|
||||
try {
|
||||
this._lastIndexedByScope.clear()
|
||||
const db = getDatabase()
|
||||
db.delete(phraseEdges).run()
|
||||
logger.info('개인 그래프 엣지 전체 삭제')
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ import {
|
|||
type SuggestionStep
|
||||
} from '@d3ro/core/input-intelligence'
|
||||
import { renderRawChatPrompt, rawChatStopSequences } from '@d3ro/core/chat-template'
|
||||
import { buildQueryTerms, splitSentences } from '@d3ro/core/personal-graph'
|
||||
import { buildQueryTerms, scoreCandidatePersonalization, splitSentences } from '@d3ro/core/personal-graph'
|
||||
import { copiesContext } from '@d3ro/core/suggestion-confidence'
|
||||
import { splitFirstWord } from '@d3ro/core/suggestion-text'
|
||||
import { predictPersonalContinuation } from '@d3ro/core/personal-ngram'
|
||||
|
|
@ -1028,14 +1028,22 @@ export class SuggestionService extends EventEmitter {
|
|||
|
||||
private _collectMemoryHints(prefix: string, appName: string | null): LocalMemoryContext {
|
||||
const telemetry = getInputTelemetryService()
|
||||
const graphContext = getPersonalGraphService().retrieveContext(prefix, 4, { appName })
|
||||
const recentWrites = telemetry
|
||||
.listRecentWrites({
|
||||
windowHandle: this._lastContext?.windowHandle ?? null,
|
||||
appName,
|
||||
windowTitle: this._lastContext?.windowTitle ?? null
|
||||
})
|
||||
.map((entry) => entry.text)
|
||||
const graphContext = getPersonalGraphService().retrieveContext(prefix, 4, { appName, recentWrites })
|
||||
const phrases = telemetry.listPhrases(120)
|
||||
// 지금 글과 용어가 겹치는 문구만 — 문맥과 무관한 "자주 쓰는 말" 은 프롬프트를 흐린다.
|
||||
const writing = analyzeWritingContext(prefix)
|
||||
const lastRecentWrite = recentWrites.length > 0 ? recentWrites[recentWrites.length - 1] ?? '' : ''
|
||||
const relevanceTerms = new Set(
|
||||
buildQueryTerms([
|
||||
{ text: writing.currentSentence, weight: 2 },
|
||||
{ text: writing.lastSentence, weight: 1 }
|
||||
{ text: writing.lastSentence || lastRecentWrite, weight: 1 }
|
||||
]).keys()
|
||||
)
|
||||
const phraseHints = selectPhraseHints(phrases, prefix, 5, { appName, relevanceTerms })
|
||||
|
|
@ -1759,6 +1767,32 @@ export class SuggestionService extends EventEmitter {
|
|||
if (token !== this._generationToken || this._isDuplicateCandidate(candidate.text)) return false
|
||||
|
||||
this._candidates.push({ ...candidate, rank: this._candidates.length })
|
||||
if (this._activeIndex === 0 && this._candidates.length >= 2) {
|
||||
const personalContext = {
|
||||
prefix,
|
||||
continuationHints: memory.continuationHints,
|
||||
followUpHints: memory.followUpHints,
|
||||
relatedHints: memory.relatedHints,
|
||||
phraseHints: memory.phraseHints
|
||||
}
|
||||
const newScore = scoreCandidatePersonalization(candidate.text, personalContext)
|
||||
if (newScore >= 1.5) {
|
||||
const personalItems = this._candidates.filter((item) => item.source === 'personal')
|
||||
const modelItems = this._candidates
|
||||
.filter((item) => item.source !== 'personal')
|
||||
.map((item, idx) => ({
|
||||
item,
|
||||
idx,
|
||||
score: scoreCandidatePersonalization(item.text, personalContext)
|
||||
}))
|
||||
.sort((a, b) => (Math.abs(b.score - a.score) >= 0.8 ? b.score - a.score : a.idx - b.idx))
|
||||
.map((entry) => entry.item)
|
||||
this._candidates = [...personalItems, ...modelItems].map((item, index) => ({
|
||||
...item,
|
||||
rank: index
|
||||
}))
|
||||
}
|
||||
}
|
||||
logger.debug(`제안 후보 추가 ${this._candidates.length}/${SUGGESTION_DEFAULTS.maxCandidatesTotal}`)
|
||||
this._armVisibleTtl()
|
||||
this.emit('updated', this.getState())
|
||||
|
|
|
|||
|
|
@ -104,6 +104,24 @@ export class TextInsertService extends EventEmitter {
|
|||
options: { commitComposition?: boolean } = {}
|
||||
): Promise<InsertResult> {
|
||||
const run = this._tail.then(async () => {
|
||||
if (method === 'keyboard' && this._keyboard.replaceBeforeCaret) {
|
||||
const start = performance.now()
|
||||
const handled = await this._keyboard.replaceBeforeCaret(deleteCount, text, options)
|
||||
if (handled) {
|
||||
this.emit('insert-started', { text, method: 'keyboard' })
|
||||
const result: InsertResult = {
|
||||
success: true,
|
||||
method: 'keyboard',
|
||||
textLength: text.length,
|
||||
durationMs: performance.now() - start
|
||||
}
|
||||
this.emit('insert-completed', { result })
|
||||
logger.info(
|
||||
`Text replaced atomically (-${deleteCount} / +${text.length} chars, ${Math.round(result.durationMs)}ms, keyboard)`
|
||||
)
|
||||
return result
|
||||
}
|
||||
}
|
||||
try {
|
||||
let count = deleteCount
|
||||
// 커서 앞 글자가 IME 조합 중이면 먼저 확정한다 (Space → 남은 공백까지 지운다).
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ import {
|
|||
mergeTypoCorrections,
|
||||
parseModelTypoPairs,
|
||||
planTypoReplacement,
|
||||
rebaseTypoReplacementPlan,
|
||||
tokenizeWords,
|
||||
typoRegionStart,
|
||||
validateModelCorrections,
|
||||
|
|
@ -123,7 +124,7 @@ const REVERT_LENGTH_TOLERANCE = 12
|
|||
|
||||
export class TypoCorrectionService extends EventEmitter {
|
||||
private _applying = false
|
||||
private _check: { abort: AbortController; prefix: string; context: TypingContext } | null = null
|
||||
private _check: { abort: AbortController; prefix: string; context: TypingContext; latestKeyAt: number } | null = null
|
||||
/** 마지막으로 결정적·모델 검사를 마친 구간(교정 전·후 모두 포함) — 같은 구간을 되풀이해 묻거나 연쇄 재교정하지 않는다. */
|
||||
private _lastCheckedRegion = ''
|
||||
private _lastPostRegion = ''
|
||||
|
|
@ -170,12 +171,29 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
this._watchRevert(context)
|
||||
if (this._applying) return 'correcting'
|
||||
|
||||
// 진행 중 모델 검사 — 같은 접두면 계속 기다리고, 달라졌으면(더 쳤다) 버린다.
|
||||
// 진행 중 모델 검사 — 같은 접두이거나 짧은 공백·구두점/완결 어절 꼬리만 덧붙었으면 리베이스 대기로 유지하고,
|
||||
// 한창 글자를 치는 중이면(유휴 부족·조합 중) 검사를 버리고 타이핑을 방해하지 않는다.
|
||||
if (this._check) {
|
||||
if (this._check.prefix === context.prefix) {
|
||||
this._check.context = context
|
||||
this._check.latestKeyAt = this._deps.lastKeyAt()
|
||||
return 'checking'
|
||||
}
|
||||
if (context.prefix.startsWith(this._check.prefix)) {
|
||||
const delta = context.prefix.slice(this._check.prefix.length)
|
||||
const canRebaseDelta =
|
||||
delta.length > 0 &&
|
||||
delta.length <= 6 &&
|
||||
(/^[ \t.,!?;:]{1,4}$/u.test(delta) ||
|
||||
(!context.isComposing &&
|
||||
context.idleMs >= LAYOUT_BOUNDARY_MIN_IDLE_MS &&
|
||||
/[ \t.,!?;:]$/u.test(delta)))
|
||||
if (canRebaseDelta) {
|
||||
this._check.context = context
|
||||
this._check.latestKeyAt = this._deps.lastKeyAt()
|
||||
return 'checking'
|
||||
}
|
||||
}
|
||||
this._cancelCheck()
|
||||
}
|
||||
|
||||
|
|
@ -296,7 +314,7 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
|
||||
this._markRegionChecked(region)
|
||||
const abort = new AbortController()
|
||||
this._check = { abort, prefix, context }
|
||||
this._check = { abort, prefix, context, latestKeyAt: keyAtDecision }
|
||||
void this._runModelCheck(model, context, abort, keyAtDecision, ignoredWords, vocabulary.known)
|
||||
return 'checking'
|
||||
}
|
||||
|
|
@ -438,11 +456,20 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
const tailCorrections = mergeTypoCorrections(fromModel, detectJamoNoise(prefix, { ignoredWords })).filter(
|
||||
(c) => prefix.length - c.start <= MAX_MODEL_DELETE_CHARS
|
||||
)
|
||||
const plan = planTypoReplacement(prefix, tailCorrections)
|
||||
if (!plan || plan.deleteCount > MAX_MODEL_DELETE_CHARS) return
|
||||
// 검사하는 사이 사용자가 더 쳤으면 접두가 달라져 위에서 취소됐다. 여기서 한 번 더 키를 본다.
|
||||
const basePlan = planTypoReplacement(prefix, tailCorrections)
|
||||
if (!basePlan) return
|
||||
const activeCheck = this._check?.abort === abort ? this._check : null
|
||||
const targetContext = activeCheck?.context ?? context
|
||||
const targetKeyAt = activeCheck?.latestKeyAt ?? keyAtDecision
|
||||
const rebasedPlan = rebaseTypoReplacementPlan(
|
||||
basePlan,
|
||||
prefix,
|
||||
targetContext.prefix,
|
||||
MAX_MODEL_DELETE_CHARS
|
||||
)
|
||||
if (!rebasedPlan) return
|
||||
this._check = null
|
||||
corrected = await this._apply(plan, context, keyAtDecision)
|
||||
corrected = await this._apply(rebasedPlan, targetContext, targetKeyAt)
|
||||
} catch (error) {
|
||||
if (!abort.signal.aborted) {
|
||||
logger.debug(`모델 오타 검사 실패: ${error instanceof Error ? error.message : String(error)}`)
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
|
||||
import { PersonalNgramModel } from '@d3ro/core/personal-ngram'
|
||||
import { getDatabase } from '../../db'
|
||||
import { typingSamples } from '../../db/schema'
|
||||
import { personalPhrases, typingSamples } from '../../db/schema'
|
||||
import { getLogger } from '../LoggerService'
|
||||
|
||||
const logger = getLogger('PersonalNgramIndex')
|
||||
|
|
@ -37,7 +37,21 @@ export class PersonalNgramIndex {
|
|||
const startedAt = this._now()
|
||||
try {
|
||||
const model = new PersonalNgramModel()
|
||||
for (const row of db.select({ text: typingSamples.text }).from(typingSamples).all()) model.addText(row.text)
|
||||
for (const row of db.select({ text: typingSamples.text }).from(typingSamples).all()) {
|
||||
model.addText(row.text)
|
||||
}
|
||||
try {
|
||||
for (const row of db
|
||||
.select({ phrase: personalPhrases.phrase, count: personalPhrases.count })
|
||||
.from(personalPhrases)
|
||||
.all()) {
|
||||
if (row.count >= 2 && typeof row.phrase === 'string') {
|
||||
model.addText(row.phrase, Math.min(row.count - 1, 3))
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// personal_phrases 테이블이 없는 테스트 목(mock) DB 에서는 typing_samples 만으로 진행한다.
|
||||
}
|
||||
this._model = model
|
||||
this._builtFor = db
|
||||
logger.info(`개인 n-gram 생성: 표본 ${model.textCount}개 (${this._now() - startedAt}ms)`)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
import type { Key as NutKey } from '@nut-tree-fork/nut-js'
|
||||
import { getLogger } from '../LoggerService'
|
||||
import { sendWin32UnicodeText } from '../../utils/win32-unicode-input'
|
||||
import { sendWin32UnicodeReplacement, sendWin32UnicodeText } from '../../utils/win32-unicode-input'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
|
||||
const logger = getLogger('TextInsertService')
|
||||
|
|
@ -22,6 +22,15 @@ export interface KeyboardPort {
|
|||
* 글자가 아니라 낱자가 지워져(여 → ㅇ) 지울 개수가 어긋난다. 호출자는 남은 공백까지 지운다 (선택).
|
||||
*/
|
||||
commitComposition?(): Promise<void>
|
||||
/**
|
||||
* (선택적 IME 조합 확정 Space) + 커서 앞 백스페이스 + 텍스트 타이핑을 단일 원자적(atomic) 호출로 수행한다.
|
||||
* 지원하고 성공했으면 true, 폴백이 필요하면 false 를 돌려준다.
|
||||
*/
|
||||
replaceBeforeCaret?(
|
||||
deleteCount: number,
|
||||
text: string,
|
||||
options?: { commitComposition?: boolean }
|
||||
): Promise<boolean>
|
||||
/** 네이티브 키 모듈을 미리 불러 둔다 — 첫 삽입이 로딩을 기다리지 않게 (선택) */
|
||||
preload?(): Promise<void>
|
||||
}
|
||||
|
|
@ -112,6 +121,21 @@ export class NutKeyboardPort implements KeyboardPort {
|
|||
await nut.native.click(nut.Key.Space)
|
||||
}
|
||||
|
||||
async replaceBeforeCaret(
|
||||
deleteCount: number,
|
||||
text: string,
|
||||
options: { commitComposition?: boolean } = {}
|
||||
): Promise<boolean> {
|
||||
if (
|
||||
this._platform === 'win32' &&
|
||||
this._load === loadNutModule &&
|
||||
sendWin32UnicodeReplacement(deleteCount, text, options)
|
||||
) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** 백스페이스를 count 번 — 키마다 네이티브 keyTap 한 번이다. */
|
||||
async backspace(count: number): Promise<void> {
|
||||
if (count <= 0) return
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ const logger = getLogger('win32-unicode-input')
|
|||
const INPUT_KEYBOARD = 1
|
||||
const KEYEVENTF_KEYUP = 0x0002
|
||||
const KEYEVENTF_UNICODE = 0x0004
|
||||
const VK_BACK = 0x08
|
||||
const VK_SPACE = 0x20
|
||||
|
||||
type SendInputFn = (cInputs: number, pInputs: Buffer, cbSize: number) => number
|
||||
|
||||
|
|
@ -80,6 +82,34 @@ function ensureLoaded(): SendInputFn | null {
|
|||
}
|
||||
}
|
||||
|
||||
function writeVirtualKeyPair(buffer: Buffer, pairIndex: number, vk: number): void {
|
||||
const downBase = pairIndex * 2 * inputStructSize
|
||||
buffer.writeUInt32LE(INPUT_KEYBOARD, downBase)
|
||||
buffer.writeUInt16LE(vk, downBase + unionOffset)
|
||||
buffer.writeUInt16LE(0, downBase + unionOffset + 2)
|
||||
buffer.writeUInt32LE(0, downBase + unionOffset + 4)
|
||||
|
||||
const upBase = (pairIndex * 2 + 1) * inputStructSize
|
||||
buffer.writeUInt32LE(INPUT_KEYBOARD, upBase)
|
||||
buffer.writeUInt16LE(vk, upBase + unionOffset)
|
||||
buffer.writeUInt16LE(0, upBase + unionOffset + 2)
|
||||
buffer.writeUInt32LE(KEYEVENTF_KEYUP, upBase + unionOffset + 4)
|
||||
}
|
||||
|
||||
function writeUnicodeKeyPair(buffer: Buffer, pairIndex: number, codeUnit: number): void {
|
||||
const downBase = pairIndex * 2 * inputStructSize
|
||||
buffer.writeUInt32LE(INPUT_KEYBOARD, downBase)
|
||||
buffer.writeUInt16LE(0, downBase + unionOffset)
|
||||
buffer.writeUInt16LE(codeUnit, downBase + unionOffset + 2)
|
||||
buffer.writeUInt32LE(KEYEVENTF_UNICODE, downBase + unionOffset + 4)
|
||||
|
||||
const upBase = (pairIndex * 2 + 1) * inputStructSize
|
||||
buffer.writeUInt32LE(INPUT_KEYBOARD, upBase)
|
||||
buffer.writeUInt16LE(0, upBase + unionOffset)
|
||||
buffer.writeUInt16LE(codeUnit, upBase + unionOffset + 2)
|
||||
buffer.writeUInt32LE(KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, upBase + unionOffset + 4)
|
||||
}
|
||||
|
||||
/**
|
||||
* UTF-16 문자열을 Windows SendInput(KEYEVENTF_UNICODE) 호출 한 번으로 입력 큐에 넣는다.
|
||||
* 성공 시 true, 지원하지 않거나 실패 시 false 를 반환한다.
|
||||
|
|
@ -95,18 +125,7 @@ export function sendWin32UnicodeText(text: string): boolean {
|
|||
const buffer = Buffer.alloc(totalEvents * inputStructSize)
|
||||
|
||||
for (let i = 0; i < codeUnits; i += 1) {
|
||||
const code = text.charCodeAt(i)
|
||||
const downBase = i * 2 * inputStructSize
|
||||
buffer.writeUInt32LE(INPUT_KEYBOARD, downBase)
|
||||
buffer.writeUInt16LE(0, downBase + unionOffset)
|
||||
buffer.writeUInt16LE(code, downBase + unionOffset + 2)
|
||||
buffer.writeUInt32LE(KEYEVENTF_UNICODE, downBase + unionOffset + 4)
|
||||
|
||||
const upBase = (i * 2 + 1) * inputStructSize
|
||||
buffer.writeUInt32LE(INPUT_KEYBOARD, upBase)
|
||||
buffer.writeUInt16LE(0, upBase + unionOffset)
|
||||
buffer.writeUInt16LE(code, upBase + unionOffset + 2)
|
||||
buffer.writeUInt32LE(KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, upBase + unionOffset + 4)
|
||||
writeUnicodeKeyPair(buffer, i, text.charCodeAt(i))
|
||||
}
|
||||
|
||||
const sent = sendInput(totalEvents, buffer, inputStructSize)
|
||||
|
|
@ -116,3 +135,54 @@ export function sendWin32UnicodeText(text: string): boolean {
|
|||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* (선택적 IME 조합 확정 Space) + 커서 앞 백스페이스 N번 + UTF-16 문자열 입력을
|
||||
* 단 한 번의 Windows SendInput 호출로 원자적(atomic)으로 주입한다.
|
||||
*
|
||||
* Win32 SendInput 규약상 단일 호출 안의 INPUT 배열 사이에 사용자의 물리 키 입력이 끼어들 수 없으므로,
|
||||
* 빠른 타이핑 도중에도 지우기와 다시 쓰기가 경쟁하지 않고 < 0.5ms 안에 끝난다.
|
||||
*/
|
||||
export function sendWin32UnicodeReplacement(
|
||||
deleteCount: number,
|
||||
text: string,
|
||||
options: { commitComposition?: boolean } = {}
|
||||
): boolean {
|
||||
const safeDeleteCount = Math.max(0, Math.trunc(deleteCount))
|
||||
if (safeDeleteCount === 0 && !text) return true
|
||||
const sendInput = ensureLoaded()
|
||||
if (!sendInput || inputStructSize <= 0) return false
|
||||
|
||||
try {
|
||||
const commitSpacePairs = options.commitComposition && safeDeleteCount > 0 ? 1 : 0
|
||||
const backspacePairs = safeDeleteCount + commitSpacePairs
|
||||
const textPairs = text.length
|
||||
const totalPairs = commitSpacePairs + backspacePairs + textPairs
|
||||
const totalEvents = totalPairs * 2
|
||||
if (totalEvents === 0) return true
|
||||
|
||||
const buffer = Buffer.alloc(totalEvents * inputStructSize)
|
||||
let pairCursor = 0
|
||||
|
||||
if (commitSpacePairs > 0) {
|
||||
writeVirtualKeyPair(buffer, pairCursor, VK_SPACE)
|
||||
pairCursor += 1
|
||||
}
|
||||
for (let i = 0; i < backspacePairs; i += 1) {
|
||||
writeVirtualKeyPair(buffer, pairCursor, VK_BACK)
|
||||
pairCursor += 1
|
||||
}
|
||||
for (let i = 0; i < textPairs; i += 1) {
|
||||
writeUnicodeKeyPair(buffer, pairCursor, text.charCodeAt(i))
|
||||
pairCursor += 1
|
||||
}
|
||||
|
||||
const sent = sendInput(totalEvents, buffer, inputStructSize)
|
||||
return sent === totalEvents
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
`SendInput(atomic replacement) 실행 실패: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -141,6 +141,47 @@ describe('TypoCorrectionService', () => {
|
|||
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('ㅡㅁ가둥 '.length, 'markdown ')
|
||||
})
|
||||
|
||||
it('모델 검사 도중 사용자가 구두점·짧은 완결 어절을 덧붙이면 취소하지 않고 새 접두 위로 리베이스해 교정한다', async () => {
|
||||
let release: (() => void) | null = null
|
||||
const generate = vi.fn(async function* () {
|
||||
await new Promise<void>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
yield 'ㅡㅁ가둥 => markdown'
|
||||
})
|
||||
const fake = deps({ warmModel: () => 'gemma4:e4b', generate })
|
||||
const service = new TypoCorrectionService(fake.deps)
|
||||
|
||||
expect(
|
||||
service.handleTypingContext(
|
||||
typingContext({
|
||||
prefix: 'ㅡㅁ가둥',
|
||||
isComposing: false,
|
||||
idleMs: 650,
|
||||
appName: 'Antigravity.exe'
|
||||
})
|
||||
)
|
||||
).toBe('checking')
|
||||
|
||||
// 모델이 응답하기 전에 사용자가 공백을 쳤지만 유휴(40ms) 조건을 만족한 경우 리베이스 대기 유지
|
||||
fake.state.lastKeyAt = 1005
|
||||
expect(
|
||||
service.handleTypingContext(
|
||||
typingContext({
|
||||
prefix: 'ㅡㅁ가둥 ',
|
||||
isComposing: false,
|
||||
idleMs: 40,
|
||||
appName: 'Antigravity.exe'
|
||||
})
|
||||
)
|
||||
).toBe('checking')
|
||||
|
||||
release?.()
|
||||
await flush()
|
||||
await flush()
|
||||
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('ㅡㅁ가둥 '.length, 'markdown ')
|
||||
})
|
||||
|
||||
it('설정으로 끌 수 있다', () => {
|
||||
config.typoAutoCorrectEnabled = false
|
||||
const fake = deps()
|
||||
|
|
|
|||
|
|
@ -74,4 +74,30 @@ describe('PersonalGraphService.retrieveContext', () => {
|
|||
expect(context.related).not.toContain('배포 로그 확인했습니다')
|
||||
expect(context.followUps).not.toContain('배포 로그 확인했습니다')
|
||||
})
|
||||
|
||||
it('같은 앱에서 단문 메시지를 연속으로 보내도 세션 follows 사슬을 잇고 recentWrites 로 복원한다', () => {
|
||||
const graph = getPersonalGraphService()
|
||||
const now = Date.now()
|
||||
graph.indexText('배포 모두 끝났습니다', { source: 'typed', appName: 'Slack.exe', at: now })
|
||||
graph.indexText('모니터링 대시보드 확인 부탁드립니다', {
|
||||
source: 'typed',
|
||||
appName: 'Slack.exe',
|
||||
at: now + 15_000
|
||||
})
|
||||
|
||||
// 채팅창에서 엔터로 전송해 입력칸이 비워진 뒤 다음 메시지를 치기 시작한 상태
|
||||
const context = graph.retrieveContext('지금 ', 4, {
|
||||
appName: 'Slack.exe',
|
||||
recentWrites: ['배포 모두 끝났습니다']
|
||||
})
|
||||
expect(context.followUps).toContain('모니터링 대시보드 확인 부탁드립니다')
|
||||
})
|
||||
|
||||
it('조사가 달라 정확한 부분 문자열이 어긋나도 어간(stem) 연속 일치로 이어쓰기를 찾는다', () => {
|
||||
const graph = getPersonalGraphService()
|
||||
graph.indexText('회의록 정리해서 내일 오전까지 공유드리겠습니다', { source: 'typed' })
|
||||
|
||||
const context = graph.retrieveContext('오늘 회의록을 정리해서')
|
||||
expect(context.continuations).toEqual(['내일 오전까지 공유드리겠습니다'])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue