feat(desktop): propose typo fixes inside the suggestion popup and make suggestions snappier
While suggestions are on, typos are no longer replaced silently. The popup shows the fix next to the candidate and applies it only when the candidate is accepted. The per-minute request cap rises from 6 to 20 so suggestions keep appearing after accepting one and continuing to type.
This commit is contained in:
parent
d63854db67
commit
f5ae4c8c04
38 changed files with 1239 additions and 660 deletions
|
|
@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
216
apps/desktop/tests/main/services/suggestion-presence.test.ts
Normal file
216
apps/desktop/tests/main/services/suggestion-presence.test.ts
Normal file
|
|
@ -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> = {}): 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<void>
|
||||
_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)
|
||||
})
|
||||
})
|
||||
|
|
@ -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> = {}): 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<void>
|
||||
_lastContext: TypingContext | null
|
||||
}
|
||||
|
||||
let services: SuggestionService[] = []
|
||||
|
||||
async function visible(context: TypingContext, expectKeys = vi.fn()): Promise<SuggestionService> {
|
||||
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 }))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue