feat(commands): multi-select ordered command pipeline with step reordering and single-pass composition (AI-05, AI-07)
This commit is contained in:
parent
f49acf0105
commit
10af20a0ad
157 changed files with 29455 additions and 913 deletions
511
apps/desktop/tests/main/services/KeyBindingService.test.ts
Normal file
511
apps/desktop/tests/main/services/KeyBindingService.test.ts
Normal file
|
|
@ -0,0 +1,511 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { globalShortcut, ipcMain, powerMonitor } from 'electron'
|
||||
import { uIOhook, UiohookKey } from 'uiohook-napi'
|
||||
import type { UiohookKeyboardEvent, UiohookMouseEvent } from 'uiohook-napi'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import {
|
||||
MouseButton,
|
||||
VK,
|
||||
createDefaultBindingMap,
|
||||
kb,
|
||||
validateBinding,
|
||||
} from '@d3ro/core/keybinding'
|
||||
import type { KeyBinding, MouseButtonCode } from '@d3ro/core/types'
|
||||
import {
|
||||
configSet,
|
||||
initInMemoryConfig,
|
||||
resetInMemoryConfig,
|
||||
saveKeyBindings,
|
||||
} from '../../../src/main/services/ConfigService'
|
||||
import {
|
||||
getKeyBindingService,
|
||||
uiohookCodeToVk,
|
||||
type KeyBindingTriggerPayload,
|
||||
} from '../../../src/main/services/KeyBindingService'
|
||||
import { registerKeyBindingHandlers } from '../../../src/main/ipc/keybinding-handlers'
|
||||
import { resetGlobalInputHookForTests } from '../../../src/main/services/global-input-hook'
|
||||
|
||||
type HookHandler<T> = (event: T) => void
|
||||
|
||||
function createHookHarness(): {
|
||||
keydown: (event: Partial<UiohookKeyboardEvent> & { keycode: number }) => void
|
||||
keyup: (event: Partial<UiohookKeyboardEvent> & { keycode: number }) => void
|
||||
mousedown: (event: Partial<UiohookMouseEvent> & { button: unknown }) => void
|
||||
mouseup: (event: Partial<UiohookMouseEvent> & { button: unknown }) => void
|
||||
} {
|
||||
const findListener = <T>(eventName: string): HookHandler<T> => {
|
||||
const calls = vi.mocked(uIOhook.on).mock.calls
|
||||
for (let i = calls.length - 1; i >= 0; i -= 1) {
|
||||
const [registeredEvent, listener] = calls[i]
|
||||
if (registeredEvent === eventName && typeof listener === 'function') {
|
||||
return listener as unknown as HookHandler<T>
|
||||
}
|
||||
}
|
||||
throw new Error(`No uIOhook listener registered for "${eventName}"`)
|
||||
}
|
||||
|
||||
return {
|
||||
keydown: (event) => {
|
||||
findListener<UiohookKeyboardEvent>('keydown')({
|
||||
type: 4,
|
||||
time: Date.now(),
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
...event,
|
||||
} as UiohookKeyboardEvent)
|
||||
},
|
||||
keyup: (event) => {
|
||||
findListener<UiohookKeyboardEvent>('keyup')({
|
||||
type: 5,
|
||||
time: Date.now(),
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
...event,
|
||||
} as UiohookKeyboardEvent)
|
||||
},
|
||||
mousedown: (event) => {
|
||||
findListener<UiohookMouseEvent>('mousedown')({
|
||||
type: 7,
|
||||
time: Date.now(),
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
x: 0,
|
||||
y: 0,
|
||||
clicks: 1,
|
||||
...event,
|
||||
} as UiohookMouseEvent)
|
||||
},
|
||||
mouseup: (event) => {
|
||||
findListener<UiohookMouseEvent>('mouseup')({
|
||||
type: 8,
|
||||
time: Date.now(),
|
||||
altKey: false,
|
||||
ctrlKey: false,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
x: 0,
|
||||
y: 0,
|
||||
clicks: 1,
|
||||
...event,
|
||||
} as UiohookMouseEvent)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function mb(
|
||||
code: MouseButtonCode,
|
||||
mods: Partial<Pick<KeyBinding, 'ctrl' | 'alt' | 'shift' | 'meta'>> = {},
|
||||
): KeyBinding {
|
||||
return {
|
||||
device: 'mouse',
|
||||
code,
|
||||
ctrl: mods.ctrl ?? false,
|
||||
alt: mods.alt ?? false,
|
||||
shift: mods.shift ?? false,
|
||||
meta: mods.meta ?? false,
|
||||
}
|
||||
}
|
||||
|
||||
const VK_F8 = VK.F1 + 7
|
||||
const VK_F9 = VK.F1 + 8
|
||||
|
||||
describe('KeyBindingService', () => {
|
||||
const hook = createHookHarness()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetGlobalInputHookForTests()
|
||||
initInMemoryConfig({
|
||||
hotkeyEnabled: true,
|
||||
suggestionEnabled: true,
|
||||
})
|
||||
const service = getKeyBindingService()
|
||||
service.dispose()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
getKeyBindingService().dispose()
|
||||
resetGlobalInputHookForTests()
|
||||
resetInMemoryConfig()
|
||||
})
|
||||
|
||||
describe('keyboard & mouse event handling and lifecycle', () => {
|
||||
it('maps uiohook keycodes to canonical Windows VK codes and returns null for unknown codes', () => {
|
||||
expect(uiohookCodeToVk(UiohookKey.F8)).toBe(VK_F8)
|
||||
expect(uiohookCodeToVk(UiohookKey.AltRight)).toBe(VK.AltRight)
|
||||
expect(uiohookCodeToVk(UiohookKey.A)).toBe(VK.A)
|
||||
expect(uiohookCodeToVk(UiohookKey.Enter)).toBe(VK.Enter)
|
||||
expect(uiohookCodeToVk(999_999)).toBeNull()
|
||||
})
|
||||
|
||||
it('attaches uIOhook listeners on start, triggers keyboard actions, and cleans up on stop', () => {
|
||||
const map = createDefaultBindingMap()
|
||||
map.command = [kb(VK_F9, { ctrl: true })]
|
||||
saveKeyBindings(map)
|
||||
|
||||
const service = getKeyBindingService()
|
||||
const triggered: KeyBindingTriggerPayload[] = []
|
||||
service.on('triggered', (payload) => triggered.push(payload))
|
||||
|
||||
service.loadFromConfig()
|
||||
service.start()
|
||||
expect(service.isRunning).toBe(true)
|
||||
expect(service.registeredBindingCount).toBeGreaterThan(0)
|
||||
|
||||
hook.keydown({ keycode: UiohookKey.F9, ctrlKey: true })
|
||||
hook.keyup({ keycode: UiohookKey.F9, ctrlKey: true })
|
||||
|
||||
expect(triggered).toEqual([
|
||||
expect.objectContaining({
|
||||
actionId: 'command',
|
||||
type: 'pressed',
|
||||
isDoublePress: false,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
actionId: 'command',
|
||||
type: 'released',
|
||||
isDoublePress: false,
|
||||
}),
|
||||
])
|
||||
|
||||
service.stop()
|
||||
expect(service.isRunning).toBe(false)
|
||||
expect(uIOhook.removeListener).toHaveBeenCalledWith('keydown', expect.any(Function))
|
||||
expect(uIOhook.removeListener).toHaveBeenCalledWith('keyup', expect.any(Function))
|
||||
expect(uIOhook.removeListener).toHaveBeenCalledWith('mousedown', expect.any(Function))
|
||||
expect(uIOhook.removeListener).toHaveBeenCalledWith('mouseup', expect.any(Function))
|
||||
})
|
||||
|
||||
it('skips keyboard bindings whose VK has no uiohook mapping (e.g., VK.Pause)', () => {
|
||||
const map = createDefaultBindingMap()
|
||||
for (const key of Object.keys(map) as Array<keyof typeof map>) {
|
||||
map[key] = []
|
||||
}
|
||||
map.command = [kb(VK.Pause)]
|
||||
saveKeyBindings(map)
|
||||
|
||||
const service = getKeyBindingService()
|
||||
service.loadFromConfig()
|
||||
expect(service.registeredBindingCount).toBe(0)
|
||||
})
|
||||
|
||||
it('releases held bindings when powerMonitor emits lock-screen or suspend', () => {
|
||||
const map = createDefaultBindingMap()
|
||||
map.dictation = [kb(VK_F8)]
|
||||
map['hands-free'] = []
|
||||
saveKeyBindings(map)
|
||||
|
||||
const service = getKeyBindingService()
|
||||
const triggered: KeyBindingTriggerPayload[] = []
|
||||
service.on('triggered', (payload) => triggered.push(payload))
|
||||
|
||||
service.loadFromConfig()
|
||||
service.start()
|
||||
|
||||
hook.keydown({ keycode: UiohookKey.F8 })
|
||||
expect(triggered).toHaveLength(1)
|
||||
expect(triggered[0]).toMatchObject({ actionId: 'dictation', type: 'pressed' })
|
||||
|
||||
const lockCall = vi
|
||||
.mocked(powerMonitor.on)
|
||||
.mock.calls.find(([event]) => (event as string) === 'lock-screen')
|
||||
expect(lockCall).toBeDefined()
|
||||
const lockHandler = lockCall?.[1] as (() => void) | undefined
|
||||
lockHandler?.()
|
||||
|
||||
expect(triggered).toHaveLength(2)
|
||||
expect(triggered[1]).toMatchObject({ actionId: 'dictation', type: 'released' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('mouse button binding rules (MB1 rejection, MB2/MB3 modifier requirement, MB4/MB5 free binding)', () => {
|
||||
it('rejects MB1 (Left click) both with and without modifiers in validation and IPC setBindings', async () => {
|
||||
expect(validateBinding(mb(MouseButton.Left))).toEqual({
|
||||
valid: false,
|
||||
reason: 'device-disabled',
|
||||
reasonKey: 'keybinding.disabled.mouseLeft',
|
||||
warningKey: null,
|
||||
})
|
||||
expect(validateBinding(mb(MouseButton.Left, { ctrl: true, alt: true }))).toEqual({
|
||||
valid: false,
|
||||
reason: 'device-disabled',
|
||||
reasonKey: 'keybinding.disabled.mouseLeft',
|
||||
warningKey: null,
|
||||
})
|
||||
|
||||
const handlers = new Map<string, (...args: unknown[]) => unknown>()
|
||||
vi.mocked(ipcMain.handle).mockImplementation((channel, listener) => {
|
||||
handlers.set(channel, listener as (...args: unknown[]) => unknown)
|
||||
})
|
||||
registerKeyBindingHandlers()
|
||||
|
||||
const setBindings = handlers.get(IPC_CHANNELS.KEYBINDING.SET_BINDINGS)!
|
||||
const res = (await setBindings({}, {
|
||||
actionId: 'dictation',
|
||||
bindings: [mb(MouseButton.Left, { ctrl: true })],
|
||||
})) as { success: boolean; error?: { details?: { reason?: string } } }
|
||||
|
||||
expect(res.success).toBe(false)
|
||||
expect(res.error?.details?.reason).toBe('device-disabled')
|
||||
})
|
||||
|
||||
it('requires a modifier for MB2 (Right) and MB3 (Middle), and triggers only when modifier is held', () => {
|
||||
expect(validateBinding(mb(MouseButton.Right))).toMatchObject({
|
||||
valid: false,
|
||||
reason: 'modifier-required',
|
||||
reasonKey: 'keybinding.reject.modifierRequired',
|
||||
})
|
||||
expect(validateBinding(mb(MouseButton.Middle))).toMatchObject({
|
||||
valid: false,
|
||||
reason: 'modifier-required',
|
||||
reasonKey: 'keybinding.reject.modifierRequired',
|
||||
})
|
||||
|
||||
expect(validateBinding(mb(MouseButton.Right, { ctrl: true }))).toMatchObject({
|
||||
valid: true,
|
||||
reason: null,
|
||||
warningKey: 'keybinding.warning.mousePassthrough',
|
||||
})
|
||||
expect(validateBinding(mb(MouseButton.Middle, { alt: true }))).toMatchObject({
|
||||
valid: true,
|
||||
reason: null,
|
||||
warningKey: 'keybinding.warning.mousePassthrough',
|
||||
})
|
||||
|
||||
const map = createDefaultBindingMap()
|
||||
map.command = [mb(MouseButton.Right, { ctrl: true })]
|
||||
map.caption = [mb(MouseButton.Middle, { alt: true })]
|
||||
saveKeyBindings(map)
|
||||
|
||||
const service = getKeyBindingService()
|
||||
const triggered: KeyBindingTriggerPayload[] = []
|
||||
service.on('triggered', (payload) => triggered.push(payload))
|
||||
service.loadFromConfig()
|
||||
service.start()
|
||||
|
||||
// Unmodified MB2 / MB3 must not trigger
|
||||
hook.mousedown({ button: MouseButton.Right })
|
||||
hook.mouseup({ button: MouseButton.Right })
|
||||
hook.mousedown({ button: MouseButton.Middle })
|
||||
hook.mouseup({ button: MouseButton.Middle })
|
||||
expect(triggered).toHaveLength(0)
|
||||
|
||||
// Ctrl+MB2 and Alt+MB3 trigger their respective actions
|
||||
hook.mousedown({ button: MouseButton.Right, ctrlKey: true })
|
||||
hook.mouseup({ button: MouseButton.Right, ctrlKey: true })
|
||||
hook.mousedown({ button: MouseButton.Middle, altKey: true })
|
||||
hook.mouseup({ button: MouseButton.Middle, altKey: true })
|
||||
|
||||
expect(
|
||||
triggered.filter((t) => t.type === 'pressed').map((t) => t.actionId),
|
||||
).toEqual(['command', 'caption'])
|
||||
})
|
||||
|
||||
it('allows free (unmodified) binding for MB4 (Back) and MB5 (Forward) and handles constituent mouseup release', () => {
|
||||
expect(validateBinding(mb(MouseButton.Back))).toMatchObject({
|
||||
valid: true,
|
||||
reason: null,
|
||||
warningKey: 'keybinding.warning.mousePassthrough',
|
||||
})
|
||||
expect(validateBinding(mb(MouseButton.Forward))).toMatchObject({
|
||||
valid: true,
|
||||
reason: null,
|
||||
warningKey: 'keybinding.warning.mousePassthrough',
|
||||
})
|
||||
|
||||
const map = createDefaultBindingMap()
|
||||
map.dictation = [mb(MouseButton.Back)]
|
||||
map['hands-free'] = []
|
||||
map.command = [mb(MouseButton.Forward)]
|
||||
saveKeyBindings(map)
|
||||
|
||||
const service = getKeyBindingService()
|
||||
const triggered: KeyBindingTriggerPayload[] = []
|
||||
service.on('triggered', (payload) => triggered.push(payload))
|
||||
service.loadFromConfig()
|
||||
service.start()
|
||||
|
||||
// Press MB4 unmodified -> hold starts; release MB4 while Alt is held -> constituent button still releases hold!
|
||||
hook.mousedown({ button: MouseButton.Back })
|
||||
hook.mouseup({ button: MouseButton.Back, altKey: true })
|
||||
|
||||
// Press MB5 unmodified -> triggers command
|
||||
hook.mousedown({ button: MouseButton.Forward })
|
||||
hook.mouseup({ button: MouseButton.Forward })
|
||||
|
||||
expect(triggered).toEqual([
|
||||
expect.objectContaining({ actionId: 'dictation', type: 'pressed', isDoublePress: false }),
|
||||
expect.objectContaining({ actionId: 'dictation', type: 'released', isDoublePress: false }),
|
||||
expect.objectContaining({ actionId: 'command', type: 'pressed', isDoublePress: false }),
|
||||
expect.objectContaining({ actionId: 'command', type: 'released', isDoublePress: false }),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('hold-to-talk vs double-press hands-free on shared binding', () => {
|
||||
it('distinguishes single hold (dictation) from rapid double-press (hands-free) on the same key', () => {
|
||||
const sharedBinding = kb(VK_F8)
|
||||
const map = createDefaultBindingMap()
|
||||
map.dictation = [sharedBinding]
|
||||
map['hands-free'] = [sharedBinding]
|
||||
saveKeyBindings(map)
|
||||
|
||||
const service = getKeyBindingService()
|
||||
const triggered: KeyBindingTriggerPayload[] = []
|
||||
service.on('triggered', (payload) => triggered.push(payload))
|
||||
service.loadFromConfig()
|
||||
service.start()
|
||||
|
||||
let now = 1_000
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now)
|
||||
|
||||
try {
|
||||
// 1. Single press & hold (>400ms gap afterwards)
|
||||
hook.keydown({ keycode: UiohookKey.F8, time: now })
|
||||
now += 600
|
||||
hook.keyup({ keycode: UiohookKey.F8, time: now })
|
||||
|
||||
expect(triggered).toEqual([
|
||||
expect.objectContaining({ actionId: 'dictation', type: 'pressed', isDoublePress: false }),
|
||||
expect.objectContaining({ actionId: 'dictation', type: 'released', isDoublePress: false }),
|
||||
])
|
||||
|
||||
triggered.length = 0
|
||||
|
||||
// 2. Wait past double-press window, then double-press within 150ms
|
||||
now += 1_000
|
||||
hook.keydown({ keycode: UiohookKey.F8, time: now })
|
||||
now += 80
|
||||
hook.keyup({ keycode: UiohookKey.F8, time: now })
|
||||
now += 100
|
||||
hook.keydown({ keycode: UiohookKey.F8, time: now })
|
||||
now += 80
|
||||
hook.keyup({ keycode: UiohookKey.F8, time: now })
|
||||
|
||||
expect(triggered).toEqual([
|
||||
expect.objectContaining({ actionId: 'dictation', type: 'pressed', isDoublePress: false }),
|
||||
expect.objectContaining({ actionId: 'dictation', type: 'released', isDoublePress: false }),
|
||||
expect.objectContaining({ actionId: 'hands-free', type: 'pressed', isDoublePress: true }),
|
||||
expect.objectContaining({ actionId: 'hands-free', type: 'released', isDoublePress: true }),
|
||||
])
|
||||
} finally {
|
||||
nowSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('multiple bindings per action', () => {
|
||||
it('triggers the same action from multiple distinct keyboard and mouse bindings independently', () => {
|
||||
const map = createDefaultBindingMap()
|
||||
map.dictation = [kb(VK_F8), mb(MouseButton.Back)]
|
||||
map['hands-free'] = []
|
||||
saveKeyBindings(map)
|
||||
|
||||
const service = getKeyBindingService()
|
||||
const triggered: KeyBindingTriggerPayload[] = []
|
||||
service.on('triggered', (payload) => triggered.push(payload))
|
||||
service.loadFromConfig()
|
||||
service.start()
|
||||
|
||||
hook.keydown({ keycode: UiohookKey.F8 })
|
||||
hook.keyup({ keycode: UiohookKey.F8 })
|
||||
|
||||
hook.mousedown({ button: MouseButton.Back })
|
||||
hook.mouseup({ button: MouseButton.Back })
|
||||
|
||||
expect(triggered).toEqual([
|
||||
expect.objectContaining({
|
||||
actionId: 'dictation',
|
||||
type: 'pressed',
|
||||
binding: expect.objectContaining({ device: 'keyboard', code: VK_F8 }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
actionId: 'dictation',
|
||||
type: 'released',
|
||||
binding: expect.objectContaining({ device: 'keyboard', code: VK_F8 }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
actionId: 'dictation',
|
||||
type: 'pressed',
|
||||
binding: expect.objectContaining({ device: 'mouse', code: MouseButton.Back }),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
actionId: 'dictation',
|
||||
type: 'released',
|
||||
binding: expect.objectContaining({ device: 'mouse', code: MouseButton.Back }),
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('suggestion capture accelerator registration & unregistration', () => {
|
||||
it('registers suggestion accelerators only while suggestion capture is active and suggestionEnabled is true', () => {
|
||||
const service = getKeyBindingService()
|
||||
service.loadFromConfig()
|
||||
service.start()
|
||||
|
||||
// On Windows/Linux, no globalShortcut is registered when suggestion overlay is inactive
|
||||
vi.mocked(globalShortcut.register).mockClear()
|
||||
vi.mocked(globalShortcut.unregister).mockClear()
|
||||
|
||||
service.setSuggestionCaptureActive(true)
|
||||
|
||||
const registeredWhenActive = vi
|
||||
.mocked(globalShortcut.register)
|
||||
.mock.calls.map(([accelerator]) => accelerator)
|
||||
expect(registeredWhenActive).toEqual(
|
||||
expect.arrayContaining([
|
||||
'Control+Alt+Return',
|
||||
'Control+Alt+Space',
|
||||
'Control+Alt+Down',
|
||||
'Control+Alt+Up',
|
||||
'Control+Alt+Backspace',
|
||||
]),
|
||||
)
|
||||
|
||||
// Deactivating suggestion capture unregisters all captured accelerators
|
||||
service.setSuggestionCaptureActive(false)
|
||||
const unregisteredWhenInactive = vi
|
||||
.mocked(globalShortcut.unregister)
|
||||
.mock.calls.map(([accelerator]) => accelerator)
|
||||
expect(unregisteredWhenInactive).toEqual(
|
||||
expect.arrayContaining([
|
||||
'Control+Alt+Return',
|
||||
'Control+Alt+Space',
|
||||
'Control+Alt+Down',
|
||||
'Control+Alt+Up',
|
||||
'Control+Alt+Backspace',
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('releases captured accelerators when suggestionEnabled is turned off and re-registers when turned back on', () => {
|
||||
const service = getKeyBindingService()
|
||||
service.loadFromConfig()
|
||||
service.start()
|
||||
|
||||
service.setSuggestionCaptureActive(true)
|
||||
vi.mocked(globalShortcut.register).mockClear()
|
||||
vi.mocked(globalShortcut.unregister).mockClear()
|
||||
|
||||
// Turning off suggestionEnabled releases captured shortcuts immediately
|
||||
configSet('suggestionEnabled', false)
|
||||
expect(vi.mocked(globalShortcut.unregister)).toHaveBeenCalledWith('Control+Alt+Return')
|
||||
|
||||
vi.mocked(globalShortcut.register).mockClear()
|
||||
|
||||
// Turning suggestionEnabled back on while capture is still wanted re-registers them
|
||||
configSet('suggestionEnabled', true)
|
||||
expect(vi.mocked(globalShortcut.register)).toHaveBeenCalledWith(
|
||||
'Control+Alt+Return',
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -48,11 +48,19 @@ function typingContext(overrides: Partial<TypingContext> = {}): TypingContext {
|
|||
}
|
||||
|
||||
function deps(overrides: Partial<TypoCorrectionDeps> = {}) {
|
||||
const state = { lastKeyAt: 1000 }
|
||||
const replaceBeforeCaret = vi.fn(async () => true)
|
||||
const state = { lastKeyAt: 1000, inputRevision: 1 }
|
||||
const replaceBeforeCaret = vi.fn(async (_count: number, _text: string, _options?: { commitComposition?: boolean }) => true)
|
||||
const base: TypoCorrectionDeps = {
|
||||
replaceBeforeCaret,
|
||||
replaceBeforeCaret: async (count, text, options) => {
|
||||
if (options?.canApply && !options.canApply()) return false
|
||||
options?.beforeApply?.()
|
||||
return options?.commitComposition
|
||||
? replaceBeforeCaret(count, text, { commitComposition: true })
|
||||
: replaceBeforeCaret(count, text)
|
||||
},
|
||||
lastKeyAt: () => state.lastKeyAt,
|
||||
inputRevision: () => state.inputRevision,
|
||||
nativeInputTick: () => 10,
|
||||
expectProgrammaticKeys: vi.fn(),
|
||||
expectProgrammaticInsert: vi.fn(() => () => undefined),
|
||||
foregroundHandle: () => 7,
|
||||
|
|
@ -216,6 +224,48 @@ describe('TypoCorrectionService', () => {
|
|||
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('같은 밀리초의 입력/클릭도 대기한 교정의 삭제 직전에 취소한다', async () => {
|
||||
let ready!: () => void
|
||||
const fake = deps({
|
||||
replaceBeforeCaret: async (_count, _text, options) => {
|
||||
await new Promise<void>((resolve) => { ready = resolve })
|
||||
if (options?.canApply && !options.canApply()) return false
|
||||
options?.beforeApply?.()
|
||||
return true
|
||||
}
|
||||
})
|
||||
const service = new TypoCorrectionService(fake.deps)
|
||||
const corrected = vi.fn()
|
||||
service.on('corrected', corrected)
|
||||
expect(service.handleTypingContext(typingContext({ inputRevision: 1 }))).toBe('correcting')
|
||||
expect(fake.deps.expectProgrammaticKeys).not.toHaveBeenCalled()
|
||||
expect(fake.deps.expectProgrammaticInsert).not.toHaveBeenCalled()
|
||||
fake.state.inputRevision += 1 // lastKeyAt is intentionally unchanged
|
||||
ready()
|
||||
await flush()
|
||||
expect(corrected).not.toHaveBeenCalled()
|
||||
expect(fake.deps.expectProgrammaticInsert).not.toHaveBeenCalled()
|
||||
expect(fake.deps.expectProgrammaticKeys).toHaveBeenLastCalledWith(0)
|
||||
})
|
||||
|
||||
it('JS 훅 도착 전 OS 입력이 바뀌었거나 조회가 불가능하면 자동 교정을 취소한다', async () => {
|
||||
for (const tick of [11, null]) {
|
||||
const fake = deps({ nativeInputTick: () => tick })
|
||||
const service = new TypoCorrectionService(fake.deps)
|
||||
service.handleTypingContext(typingContext({ nativeInputTick: 10 }))
|
||||
await flush()
|
||||
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
|
||||
it('포그라운드 창 확인이 실패해도 이전 창에 있다고 가정하지 않는다', async () => {
|
||||
const fake = deps({ foregroundHandle: () => null })
|
||||
const service = new TypoCorrectionService(fake.deps)
|
||||
service.handleTypingContext(typingContext())
|
||||
await flush()
|
||||
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('같은 구간은 두 번 검사하지 않는다', async () => {
|
||||
const fake = deps({ warmModel: () => 'gemma' })
|
||||
const service = new TypoCorrectionService(fake.deps)
|
||||
|
|
@ -262,6 +312,41 @@ describe('TypoCorrectionService', () => {
|
|||
expect(fake.deps.generate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('콜드 모델이거나 유휴 스냅샷이 와도 커서 끝에서 조합 중인 한글 초성(안ㄴ·안녕ㅎ·오늘 ㅇ)을 지워 글자를 삼키지 않는다', async () => {
|
||||
const fake = deps({ warmModel: () => null })
|
||||
const service = new TypoCorrectionService(fake.deps)
|
||||
|
||||
for (const prefix of ['안ㄴ', '안녕ㅎ', '안녕하ㅅ', '한ㄱ', '글ㅈ', '오늘 ㅇ', '아직 ㄴ']) {
|
||||
expect(
|
||||
service.handleTypingContext(
|
||||
typingContext({
|
||||
prefix,
|
||||
isComposing: false,
|
||||
idleMs: 800,
|
||||
appName: 'chrome.exe'
|
||||
})
|
||||
),
|
||||
prefix
|
||||
).toBe('pass')
|
||||
}
|
||||
await flush()
|
||||
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||
|
||||
// 반면 어절이 공백으로 끝난 뒤 남은 내부 낱자 잡음("그ㅓ런건 ")은 콜드 모델에서도 즉시 정리한다
|
||||
expect(
|
||||
service.handleTypingContext(
|
||||
typingContext({
|
||||
prefix: '그ㅓ런건 ',
|
||||
isComposing: false,
|
||||
idleMs: 800,
|
||||
appName: 'chrome.exe'
|
||||
})
|
||||
)
|
||||
).toBe('correcting')
|
||||
await flush()
|
||||
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('그ㅓ런건 '.length, '그런건 ')
|
||||
})
|
||||
|
||||
it('검사 중 접두가 바뀌면 검사를 버리고 새 문맥은 그대로 넘긴다', async () => {
|
||||
let release: (() => void) | null = null
|
||||
const fake = deps({
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ErrorCode } from '@d3ro/core/errors'
|
||||
import type { History, MeetingSessionRow } from '../../../src/main/db/schema'
|
||||
import type { History, MeetingMemoRow, MeetingSessionRow } from '../../../src/main/db/schema'
|
||||
|
||||
interface MockBuilderOptions {
|
||||
get?: unknown
|
||||
|
|
@ -182,4 +182,48 @@ describe('UnifiedSearchService', () => {
|
|||
expect.objectContaining({ code: ErrorCode.DBQueryFailed }),
|
||||
)
|
||||
})
|
||||
|
||||
it('includes meeting_memos and timed transcript segments in meeting search results', async () => {
|
||||
const memoOnlyMeeting: MeetingSessionRow = {
|
||||
...meeting,
|
||||
id: 'meeting-memo-1',
|
||||
title: '설계 검토 회의',
|
||||
startedAt: 400,
|
||||
createdAt: 400,
|
||||
rawTranscript: '[00:10] 아키텍처 개요 설명',
|
||||
}
|
||||
const memoRow: MeetingMemoRow = {
|
||||
id: 'memo-1',
|
||||
sessionId: 'meeting-memo-1',
|
||||
content: '마이그레이션 체크리스트 확인 필요',
|
||||
timestampMs: 75_000,
|
||||
createdAt: 410,
|
||||
updatedAt: 410,
|
||||
}
|
||||
selectQueue.push(
|
||||
createMockBuilder({ get: { count: 0 } }),
|
||||
createMockBuilder({ all: [] }),
|
||||
createMockBuilder({ get: { count: 0 } }),
|
||||
createMockBuilder({ all: [] }),
|
||||
createMockBuilder({ all: [memoRow] }),
|
||||
createMockBuilder({ all: [memoOnlyMeeting] }),
|
||||
)
|
||||
const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import(
|
||||
'../../../src/main/services/UnifiedSearchService'
|
||||
)
|
||||
resetUnifiedSearchServiceForTests()
|
||||
|
||||
const response = getUnifiedSearchService().search({ query: '체크리스트', limit: 10 })
|
||||
|
||||
expect(response.total).toBe(1)
|
||||
expect(response.results).toEqual([
|
||||
expect.objectContaining({
|
||||
source: 'meeting',
|
||||
id: 'meeting-memo-1',
|
||||
title: '설계 검토 회의',
|
||||
matchedField: 'content',
|
||||
excerpt: '[01:15] 마이그레이션 체크리스트 확인 필요',
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -380,6 +380,29 @@ describe('VoiceModeService', () => {
|
|||
expect(action).toBe('custom')
|
||||
expect(systemPrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('복수 지시문 파이프라인(정리 → 격식체 변환)이 설정되면 단계별로 합성된 시스템 프롬프트를 전달한다', async () => {
|
||||
registerInstruction({
|
||||
id: 'builtin-clean-speech',
|
||||
name: '구어·추임새·중복 정리',
|
||||
prompt: '추임새와 말바꾸기, 중복을 제거하세요.',
|
||||
})
|
||||
registerInstruction({
|
||||
id: 'builtin-formal',
|
||||
name: '격식체 변환',
|
||||
prompt: '정중한 비즈니스 존댓말(-습니다/-합니다)로 변환하세요.',
|
||||
})
|
||||
config.values.defaultLLMAction = 'custom'
|
||||
config.values.activeInstructionId = 'builtin-clean-speech,builtin-formal'
|
||||
|
||||
await runSession()
|
||||
const [text, action, , systemPrompt] = mockLLM.processText.mock.calls[0]
|
||||
|
||||
expect(text).toBe(TRANSCRIPT)
|
||||
expect(action).toBe('custom')
|
||||
expect(systemPrompt).toContain('[1단계: 구어·추임새·중복 정리]')
|
||||
expect(systemPrompt).toContain('[2단계: 격식체 변환]')
|
||||
})
|
||||
})
|
||||
|
||||
// ── 두 번째 진입점: 음성 단축키 ────────────────────────
|
||||
|
|
|
|||
61
apps/desktop/tests/main/services/i18n-locale-parity.test.ts
Normal file
61
apps/desktop/tests/main/services/i18n-locale-parity.test.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// tests/main/services/i18n-locale-parity.test.ts
|
||||
// GAP-I18N-01 / GAP-UX-07 / GAP-LLM-01 회귀 방지 테스트:
|
||||
// 12개 지원 로케일 파일의 키 집합이 마스터(ko.json)와 100% 일치하는지 검증한다.
|
||||
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { LOCALE_META } from '@d3ro/i18n'
|
||||
|
||||
const LOCALES_DIR = path.resolve(__dirname, '../../../../../packages/i18n/src/locales')
|
||||
|
||||
describe('i18n 12개 로케일 키 정합성 (GAP-I18N-01 / GAP-UX-07 / GAP-LLM-01)', () => {
|
||||
const ko = JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, 'ko.json'), 'utf8')) as Record<string, string>
|
||||
const en = JSON.parse(fs.readFileSync(path.join(LOCALES_DIR, 'en.json'), 'utf8')) as Record<string, string>
|
||||
const masterKeys = Object.keys(ko)
|
||||
|
||||
it('마스터(ko.json)와 영어(en.json)의 키 집합이 정확히 일치한다', () => {
|
||||
const missingInEn = masterKeys.filter((k) => !(k in en))
|
||||
const extraInEn = Object.keys(en).filter((k) => !(k in ko))
|
||||
expect(missingInEn).toEqual([])
|
||||
expect(extraInEn).toEqual([])
|
||||
})
|
||||
|
||||
it.each(LOCALE_META.map((m) => m.code))(
|
||||
"로케일 '%s'가 마스터(ko.json)의 모든 키를 빠짐없이 포함한다",
|
||||
(localeCode) => {
|
||||
const filePath = path.join(LOCALES_DIR, `${localeCode}.json`)
|
||||
const data = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Record<string, string>
|
||||
const missing = masterKeys.filter((k) => !(k in data) || typeof data[k] !== 'string' || data[k].length === 0)
|
||||
expect(missing).toEqual([])
|
||||
},
|
||||
)
|
||||
|
||||
it('온보딩 LLM 모델 크기 안내가 기본 모델(gemma4:e4b, 4.0GB)과 일치한다 (GAP-UX-07)', () => {
|
||||
expect(ko['onboarding.llmModelSize']).toContain('4.0GB')
|
||||
expect(en['onboarding.llmModelSize']).toContain('4.0GB')
|
||||
})
|
||||
|
||||
it('번역 대상 언어 설정 키가 정의되어 있다 (GAP-LLM-01)', () => {
|
||||
const requiredKeys = [
|
||||
'settings.targetLanguage',
|
||||
'settings.targetLanguage.desc',
|
||||
'settings.targetLanguage.en',
|
||||
'settings.targetLanguage.ko',
|
||||
'settings.targetLanguage.ja',
|
||||
'settings.targetLanguage.zhCN',
|
||||
'settings.targetLanguage.zhTW',
|
||||
'settings.targetLanguage.es',
|
||||
'settings.targetLanguage.fr',
|
||||
'settings.targetLanguage.de',
|
||||
'settings.targetLanguage.pt',
|
||||
'settings.targetLanguage.vi',
|
||||
'settings.targetLanguage.id',
|
||||
'settings.targetLanguage.ar',
|
||||
]
|
||||
for (const key of requiredKeys) {
|
||||
expect(ko[key]).toBeTruthy()
|
||||
expect(en[key]).toBeTruthy()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
@ -126,12 +126,13 @@ describe('classifyKeyStroke', () => {
|
|||
})
|
||||
|
||||
describe('텍스트 지표', () => {
|
||||
it('단어 수 — 공백 분리 토큰 중 문자/숫자가 있는 것만', () => {
|
||||
it('단어 수 — 공백 분리 토큰 중 문자/숫자가 있는 것만 세며, 비공백 CJK 문장도 분할 집계한다', () => {
|
||||
expect(countWords('')).toBe(0)
|
||||
expect(countWords('hello world')).toBe(2)
|
||||
expect(countWords('안녕하세요 오늘 날씨')).toBe(3)
|
||||
expect(countWords(' , . ! ')).toBe(0)
|
||||
expect(countWords('v1.2 배포 준비')).toBe(3)
|
||||
expect(countWords('今天开会讨论了三件事')).toBeGreaterThanOrEqual(4)
|
||||
})
|
||||
|
||||
it('문장 수 — 종결 부호와 개행', () => {
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ vi.mock('../../../src/main/services/UiaContextService', () => ({
|
|||
})
|
||||
}))
|
||||
vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null }))
|
||||
vi.mock('../../../src/main/utils/win32-input-activity', () => ({ getLastNativeInputTick: () => 123 }))
|
||||
|
||||
import {
|
||||
getInputTelemetryService,
|
||||
|
|
|
|||
|
|
@ -10,12 +10,13 @@ vi.mock('../../../src/main/services/LoggerService', () => ({
|
|||
getLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/global-input-hook', () => ({ acquireGlobalInputHook: () => () => undefined }))
|
||||
// 매핑 없는 키코드(0) = IME 처리 키
|
||||
// 0은 합성 유니코드 키다. IME는 별도의 변환표에 없는 코드를 쓴다.
|
||||
vi.mock('../../../src/main/services/KeyBindingService', () => ({
|
||||
uiohookCodeToVk: (code: number) => (code === 0 ? null : 0x41)
|
||||
uiohookCodeToVk: (code: number) => (code === 0xffff ? null : 0x41)
|
||||
}))
|
||||
vi.mock('../../../src/main/services/UiaContextService', () => ({ getUiaContextService: () => ({}) }))
|
||||
vi.mock('../../../src/main/utils/win32-foreground', () => ({ getForegroundWindowInfo: () => null }))
|
||||
vi.mock('../../../src/main/utils/win32-input-activity', () => ({ getLastNativeInputTick: () => 123 }))
|
||||
|
||||
import {
|
||||
getInputTelemetryService,
|
||||
|
|
@ -37,13 +38,19 @@ describe('IME 글자 키', () => {
|
|||
it('변환표에 없는 키(IME 처리 키)를 수정자 없이 누르면 타이핑으로 본다', () => {
|
||||
const service = getInputTelemetryService() as unknown as Internal
|
||||
expect(service._lastTypedAt).toBe(0)
|
||||
service._handleKeyDown(key(0))
|
||||
service._handleKeyDown(key(0xffff))
|
||||
expect(service._lastTypedAt).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('Ctrl/Alt 와 함께면 단축키다 — 타이핑이 아니다', () => {
|
||||
const service = getInputTelemetryService() as unknown as Internal
|
||||
service._handleKeyDown(key(0, { ctrlKey: true }))
|
||||
service._handleKeyDown(key(0xffff, { ctrlKey: true }))
|
||||
expect(service._lastTypedAt).toBe(0)
|
||||
})
|
||||
|
||||
it('합성 유니코드 패킷은 사용자 타이핑으로 집계하지 않는다', () => {
|
||||
const service = getInputTelemetryService() as unknown as Internal
|
||||
service._handleKeyDown(key(0))
|
||||
expect(service._lastTypedAt).toBe(0)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,216 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { FocusSnapshot } from '@d3ro/core/input-intelligence'
|
||||
import type { ForegroundWindowInfo } from '../../../src/main/utils/win32-foreground'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
snapshot: vi.fn<() => Promise<FocusSnapshot>>(),
|
||||
foreground: vi.fn<() => ForegroundWindowInfo | null>(),
|
||||
nativeInputTick: vi.fn<() => number | null>()
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({ screen: { getPrimaryDisplay: () => ({ scaleFactor: 1 }) } }))
|
||||
vi.mock('uiohook-napi', () => ({ uIOhook: { on: vi.fn(), removeListener: vi.fn() } }))
|
||||
vi.mock('../../../src/main/db', () => ({ getDatabase: vi.fn() }))
|
||||
vi.mock('../../../src/main/services/ConfigService', () => ({
|
||||
configGet: (key: string) => (key === 'inputExcludedApps' ? [] : undefined),
|
||||
configSet: vi.fn()
|
||||
}))
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() })
|
||||
}))
|
||||
vi.mock('../../../src/main/services/global-input-hook', () => ({ acquireGlobalInputHook: () => () => undefined }))
|
||||
vi.mock('../../../src/main/services/KeyBindingService', () => ({ uiohookCodeToVk: (code: number) => code }))
|
||||
vi.mock('../../../src/main/services/UiaContextService', () => ({
|
||||
getUiaContextService: () => ({
|
||||
getSnapshot: mocks.snapshot,
|
||||
isAvailable: () => true,
|
||||
lastReason: null,
|
||||
lastSuccessAt: 0
|
||||
})
|
||||
}))
|
||||
vi.mock('../../../src/main/utils/win32-foreground', () => ({
|
||||
getForegroundWindowInfo: mocks.foreground,
|
||||
isForegroundKoreanIme: () => false
|
||||
}))
|
||||
vi.mock('../../../src/main/utils/win32-input-activity', () => ({ getLastNativeInputTick: mocks.nativeInputTick }))
|
||||
|
||||
import {
|
||||
getInputTelemetryService,
|
||||
resetInputTelemetryServiceForTests,
|
||||
type TypingContext
|
||||
} from '../../../src/main/services/InputTelemetryService'
|
||||
|
||||
interface Internal {
|
||||
_running: boolean
|
||||
_lastKeyAt: number
|
||||
_lastTypedAt: number
|
||||
_lastFocusKey: string
|
||||
_textAtFocus: string
|
||||
_lastContext: TypingContext | null
|
||||
_foreground: { appName: string | null; windowTitle: string | null; hwnd: number | null }
|
||||
_captureTextSnapshot(): Promise<TypingContext | null>
|
||||
_handleKeyDown(event: { keycode: number }): void
|
||||
_handleMouseDown(event: { x: number; y: number; button: number }): void
|
||||
_handleMouseUp(event: { x: number; y: number }): void
|
||||
_handleWheel(event: { rotation: number }): void
|
||||
}
|
||||
|
||||
function snapshot(overrides: Partial<FocusSnapshot> = {}): FocusSnapshot {
|
||||
return {
|
||||
available: true,
|
||||
isPassword: false,
|
||||
isEditable: true,
|
||||
isComposing: false,
|
||||
hasSelection: false,
|
||||
controlType: 'Edit',
|
||||
controlName: '메시지',
|
||||
textSource: 'value',
|
||||
text: '안녕하세요',
|
||||
caretOffset: 5,
|
||||
caretRect: null,
|
||||
elementRect: null,
|
||||
windowTitle: '채팅',
|
||||
appName: 'chrome.exe',
|
||||
processId: 1,
|
||||
capturedAt: Date.now(),
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('입력 중 늦게 도착하는 UIA 스냅샷', () => {
|
||||
let service: ReturnType<typeof getInputTelemetryService>
|
||||
let internal: Internal
|
||||
let publish: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
resetInputTelemetryServiceForTests()
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(10_000)
|
||||
mocks.foreground.mockReset().mockReturnValue(null)
|
||||
mocks.nativeInputTick.mockReset().mockReturnValue(123)
|
||||
mocks.snapshot.mockReset()
|
||||
service = getInputTelemetryService()
|
||||
internal = service as unknown as Internal
|
||||
internal._running = true
|
||||
internal._foreground = { appName: 'chrome.exe', windowTitle: '채팅', hwnd: 42 }
|
||||
internal._lastKeyAt = Date.now()
|
||||
internal._lastTypedAt = Date.now()
|
||||
internal._textAtFocus = '기존 기준선'
|
||||
publish = vi.fn()
|
||||
service.on('typed-context', publish)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
service.dispose()
|
||||
vi.restoreAllMocks()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
function pending() {
|
||||
let resolve!: (value: FocusSnapshot) => void
|
||||
mocks.snapshot.mockImplementationOnce(() => new Promise((done) => { resolve = done }))
|
||||
const request = internal._captureTextSnapshot()
|
||||
return { request, resolve }
|
||||
}
|
||||
|
||||
it('같은 밀리초에 친 새 글자도 감지해 오래된 텍스트를 발행하거나 기준선으로 저장하지 않는다', async () => {
|
||||
const delayed = pending()
|
||||
const at = internal._lastKeyAt
|
||||
internal._handleKeyDown({ keycode: 0x41 })
|
||||
expect(internal._lastKeyAt).toBe(at)
|
||||
delayed.resolve(snapshot())
|
||||
|
||||
expect(await delayed.request).toBeNull()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
expect(internal._lastContext).toBeNull()
|
||||
expect(internal._textAtFocus).toBe('기존 기준선')
|
||||
|
||||
mocks.snapshot.mockResolvedValueOnce(snapshot({ text: '안녕하세요 추가', caretOffset: 8 }))
|
||||
expect((await internal._captureTextSnapshot())?.prefix).toBe('안녕하세요 추가')
|
||||
expect(publish).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['마우스 클릭', (value: Internal) => value._handleMouseDown({ x: 2, y: 3, button: 1 })],
|
||||
['선택 드래그 끝', (value: Internal) => value._handleMouseUp({ x: 2, y: 3 })],
|
||||
['스크롤', (value: Internal) => value._handleWheel({ rotation: 1 })],
|
||||
['합성 유니코드 키', (value: Internal) => value._handleKeyDown({ keycode: 0 })]
|
||||
] as const)('%s 중 도착한 응답은 버린다', async (_name, change) => {
|
||||
const delayed = pending()
|
||||
change(internal)
|
||||
delayed.resolve(snapshot())
|
||||
expect(await delayed.request).toBeNull()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('통계에서 제외한 프로그램 백스페이스도 스냅샷을 무효화한다', async () => {
|
||||
service.expectProgrammaticKeys(1)
|
||||
const delayed = pending()
|
||||
internal._handleKeyDown({ keycode: 0x08 })
|
||||
delayed.resolve(snapshot())
|
||||
expect(await delayed.request).toBeNull()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('키 이벤트 없이 포그라운드 창이 바뀌어도 이전 창의 텍스트를 발행하지 않는다', async () => {
|
||||
const delayed = pending()
|
||||
mocks.foreground.mockReturnValue({
|
||||
hwnd: 99, title: '다른 창', appName: 'notes.exe', processId: 2, appPath: null, bounds: null
|
||||
})
|
||||
delayed.resolve(snapshot())
|
||||
expect(await delayed.request).toBeNull()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('중지 후 재시작해도 이전 세션의 응답을 적용하지 않는다', async () => {
|
||||
const delayed = pending()
|
||||
service.stop()
|
||||
service.start()
|
||||
delayed.resolve(snapshot())
|
||||
expect(await delayed.request).toBeNull()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('마지막 키보다 먼저 캡처된 응답은 버린다', async () => {
|
||||
mocks.snapshot.mockResolvedValueOnce(snapshot({ capturedAt: Date.now() - 1 }))
|
||||
expect(await internal._captureTextSnapshot()).toBeNull()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('메인 스레드에 키 콜백이 아직 도착하지 않아도 네이티브 입력 변화로 취소한다', async () => {
|
||||
const revision = service.inputRevision
|
||||
const delayed = pending()
|
||||
mocks.nativeInputTick.mockReturnValue(124)
|
||||
delayed.resolve(snapshot())
|
||||
expect(service.inputRevision).toBe(revision)
|
||||
expect(await delayed.request).toBeNull()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('네이티브 tick이 감소하거나 래핑되어도 변화로 처리한다', async () => {
|
||||
mocks.nativeInputTick.mockReturnValue(0xffffffff)
|
||||
const delayed = pending()
|
||||
mocks.nativeInputTick.mockReturnValue(0)
|
||||
delayed.resolve(snapshot())
|
||||
expect(await delayed.request).toBeNull()
|
||||
expect(publish).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('Windows에서 네이티브 상태를 못 읽으면 문맥에 null을 명시해 자동 교정이 거절할 수 있게 한다', async () => {
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
mocks.nativeInputTick.mockReturnValue(null)
|
||||
mocks.snapshot.mockResolvedValueOnce(snapshot())
|
||||
expect((await internal._captureTextSnapshot())?.nativeInputTick).toBeNull()
|
||||
})
|
||||
|
||||
it('겹친 타이머들은 UIA 조회와 문맥 발행을 한 번만 한다', async () => {
|
||||
const delayed = pending()
|
||||
const duplicate = internal._captureTextSnapshot()
|
||||
delayed.resolve(snapshot())
|
||||
const [first, second] = await Promise.all([delayed.request, duplicate])
|
||||
expect(first).toBe(second)
|
||||
expect(first?.inputRevision).toBe(service.inputRevision)
|
||||
expect(mocks.snapshot).toHaveBeenCalledTimes(1)
|
||||
expect(publish).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
|
@ -20,6 +20,8 @@ import {
|
|||
renderInstructionPrompt,
|
||||
buildInstructionInvocation,
|
||||
resolveSystemPrompt,
|
||||
resolveTargetLanguage,
|
||||
SUPPORTED_TARGET_LANGUAGES,
|
||||
buildSuggestionPrompt,
|
||||
DEFAULT_TARGET_LANGUAGE,
|
||||
BASE_SYSTEM_PROMPTS,
|
||||
|
|
@ -28,6 +30,7 @@ import {
|
|||
FREE_PROMPT_SYSTEM_PROMPT,
|
||||
} from '../../../src/main/services/llm-prompts'
|
||||
import { buildCaptionRefinePrompt, buildTypoCheckPrompt } from '../../../src/main/services/llm-prompts'
|
||||
import * as ConfigServiceModule from '../../../src/main/services/ConfigService'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
|
@ -153,6 +156,23 @@ describe('resolveSystemPrompt', () => {
|
|||
expect(resolveSystemPrompt('translate')).toContain(`${DEFAULT_TARGET_LANGUAGE}로 번역`)
|
||||
})
|
||||
|
||||
it('ConfigService에 targetLanguage가 설정되어 있으면 명시 인자 생략 시 설정값을 사용한다', () => {
|
||||
const spy = vi.spyOn(ConfigServiceModule, 'getConfigService').mockReturnValue({
|
||||
get: (key: string) => (key === 'targetLanguage' ? 'Japanese' : undefined),
|
||||
} as never)
|
||||
try {
|
||||
expect(resolveTargetLanguage()).toBe('Japanese')
|
||||
expect(resolveTargetLanguage('Spanish')).toBe('Spanish')
|
||||
expect(resolveSystemPrompt('translate')).toContain('Japanese로 번역')
|
||||
expect(
|
||||
renderInstructionPrompt('{{targetLanguage}}로 번역해줘', { text: '안녕' }),
|
||||
).toBe('Japanese로 번역해줘')
|
||||
expect(SUPPORTED_TARGET_LANGUAGES).toContain('Japanese')
|
||||
} finally {
|
||||
spy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
// 수정 대상이 아닌 일반 액션들이 각자의 프롬프트로 해석되는지 잠근다.
|
||||
// 이들이 refine으로 조용히 폴백하면 커스텀 경로와 같은 사고가 난다.
|
||||
it.each(['refine', 'summarize', 'grammar', 'expand'] as const)(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ErrorCode } from '@d3ro/core/errors'
|
||||
import { initInMemoryConfig, resetInMemoryConfig } from '../../../src/main/services/ConfigService'
|
||||
import { configSet, initInMemoryConfig, resetInMemoryConfig } from '../../../src/main/services/ConfigService'
|
||||
import { availableParallelism } from 'node:os'
|
||||
import { inferenceCpuThreads } from '../../../src/main/utils/inference-cpu-budget'
|
||||
import {
|
||||
getLocalLLMService,
|
||||
resetLocalLLMServiceForTests,
|
||||
|
|
@ -44,6 +46,36 @@ describe('LocalLLMService request lifecycle', () => {
|
|||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it.each(['http://127.0.0.1:11434', 'http://192.168.1.2:11434'])(
|
||||
'applies CPU headroom across generate, warm-up streaming and chat only for loopback (%s)', async (serverUrl) => {
|
||||
configSet('ollamaServerUrl', serverUrl)
|
||||
const bodies: Array<{ options: { num_thread?: number }; stream: boolean }> = []
|
||||
vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const body = JSON.parse(String(init?.body)) as (typeof bodies)[number]
|
||||
bodies.push(body)
|
||||
if (!body.stream) return completedGenerateResponse()
|
||||
const frame = String(input).endsWith('/api/chat')
|
||||
? { message: { content: 'ok' }, done: true }
|
||||
: { model: 'gemma4:e4b', response: 'ok', done: true }
|
||||
return new Response(completedStream([JSON.stringify(frame)]), { status: 200 })
|
||||
}))
|
||||
|
||||
const service = getLocalLLMService()
|
||||
await service.generate('hello')
|
||||
for await (const token of service.streamGenerate('hi', { maxTokens: 1 })) void token
|
||||
for await (const token of service.chatStream([{ role: 'user', content: 'hello' }])) void token
|
||||
|
||||
expect(bodies).toHaveLength(3)
|
||||
for (const body of bodies) {
|
||||
if (serverUrl.includes('127.0.0.1')) {
|
||||
expect(body.options.num_thread).toBe(inferenceCpuThreads(availableParallelism()))
|
||||
} else {
|
||||
expect(body.options).not.toHaveProperty('num_thread')
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('sends the bounded default num_predict to chat requests', async () => {
|
||||
const cancel = vi.fn()
|
||||
const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,87 @@
|
|||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { TextInsertService } from '../../../src/main/services/TextInsertService'
|
||||
|
||||
vi.mock('../../../src/main/services/text-insert/electron-clipboard-port', () => ({ electronClipboardPort: {} }))
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() })
|
||||
}))
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void
|
||||
const promise = new Promise<void>((done) => { resolve = done })
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
describe('replacement under delayed input processing', () => {
|
||||
it('does not delete new typing after waiting behind another insertion', async () => {
|
||||
const pending = deferred()
|
||||
const keyboard = {
|
||||
type: vi.fn(() => pending.promise), paste: vi.fn(), backspace: vi.fn(),
|
||||
replaceBeforeCaret: vi.fn(async () => true)
|
||||
}
|
||||
const service = new TextInsertService({ keyboard })
|
||||
let revision = 1
|
||||
const beforeApply = vi.fn()
|
||||
const first = service.insertText('prior insertion', 'keyboard')
|
||||
const correction = service.replaceBeforeCaret(3, 'fixed', 'keyboard', {
|
||||
canApply: () => revision === 1, beforeApply, requireAtomic: true
|
||||
})
|
||||
await Promise.resolve()
|
||||
revision += 1 // physical input or a click while the first insertion is pending
|
||||
pending.resolve()
|
||||
await first
|
||||
expect((await correction).success).toBe(false)
|
||||
expect(keyboard.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||
expect(keyboard.backspace).not.toHaveBeenCalled()
|
||||
expect(beforeApply).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('revalidates after a slow fallback module load before sending any keys', async () => {
|
||||
const loading = deferred()
|
||||
const started = deferred()
|
||||
const keyboard = {
|
||||
type: vi.fn(), paste: vi.fn(), backspace: vi.fn(),
|
||||
preload: vi.fn(() => { started.resolve(); return loading.promise })
|
||||
}
|
||||
const service = new TextInsertService({ keyboard })
|
||||
let current = true
|
||||
const correction = service.replaceBeforeCaret(3, 'fixed', 'keyboard', { canApply: () => current })
|
||||
await started.promise
|
||||
current = false
|
||||
loading.resolve()
|
||||
expect((await correction).success).toBe(false)
|
||||
expect(keyboard.backspace).not.toHaveBeenCalled()
|
||||
expect(keyboard.type).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not use separate backspaces when automatic atomic replacement is unavailable', async () => {
|
||||
const keyboard = {
|
||||
type: vi.fn(), paste: vi.fn(), backspace: vi.fn(),
|
||||
replaceBeforeCaret: vi.fn(async () => false)
|
||||
}
|
||||
const service = new TextInsertService({ keyboard })
|
||||
expect((await service.replaceBeforeCaret(3, 'fixed', 'keyboard', { requireAtomic: true })).success).toBe(false)
|
||||
expect(keyboard.backspace).not.toHaveBeenCalled()
|
||||
expect(keyboard.type).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('registers synthetic keys only when the valid queued replacement actually runs', async () => {
|
||||
const pending = deferred()
|
||||
const order: string[] = []
|
||||
const keyboard = {
|
||||
type: vi.fn(() => pending.promise), paste: vi.fn(), backspace: vi.fn(),
|
||||
replaceBeforeCaret: vi.fn(async () => { order.push('replace'); return true })
|
||||
}
|
||||
const service = new TextInsertService({ keyboard })
|
||||
const first = service.insertText('prior', 'keyboard')
|
||||
const correction = service.replaceBeforeCaret(3, 'fixed', 'keyboard', {
|
||||
canApply: () => true, beforeApply: () => { order.push('register') }, requireAtomic: true
|
||||
})
|
||||
await Promise.resolve()
|
||||
expect(order).toEqual([])
|
||||
pending.resolve()
|
||||
await first
|
||||
expect((await correction).success).toBe(true)
|
||||
expect(order).toEqual(['register', 'replace'])
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { TextInsertService } from '../../../src/main/services/TextInsertService'
|
||||
import { TypoCorrectionService } from '../../../src/main/services/TypoCorrectionService'
|
||||
import type { TypingContext } from '../../../src/main/services/InputTelemetryService'
|
||||
|
||||
vi.mock('../../../src/main/services/text-insert/electron-clipboard-port', () => ({ electronClipboardPort: {} }))
|
||||
vi.mock('../../../src/main/services/ConfigService', () => ({
|
||||
configGet: (key: string) => key === 'typoAutoCorrectEnabled' ? true :
|
||||
key === 'typoAutoCorrectUseModel' ? false : [],
|
||||
configSet: vi.fn()
|
||||
}))
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })
|
||||
}))
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void
|
||||
const promise = new Promise<void>((done) => { resolve = done })
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const state = { text: '오늘 잘 됬어요 ', lastKeyAt: 1_000, revision: 1, nativeTick: 5, hwnd: 7 }
|
||||
const prior = deferred()
|
||||
const replacementDone = deferred()
|
||||
const keyboard = {
|
||||
type: async () => prior.promise,
|
||||
paste: vi.fn(async () => undefined),
|
||||
backspace: vi.fn(async (count: number) => { state.text = state.text.slice(0, -count) }),
|
||||
replaceBeforeCaret: vi.fn(async (count: number, text: string) => {
|
||||
state.text = state.text.slice(0, -count) + text
|
||||
return true
|
||||
})
|
||||
}
|
||||
const insert = new TextInsertService({ keyboard })
|
||||
const typo = new TypoCorrectionService({
|
||||
replaceBeforeCaret: async (count, text, options) => {
|
||||
try { return (await insert.replaceBeforeCaret(count, text, 'keyboard', options)).success }
|
||||
finally { replacementDone.resolve() }
|
||||
},
|
||||
lastKeyAt: () => state.lastKeyAt,
|
||||
inputRevision: () => state.revision,
|
||||
nativeInputTick: () => state.nativeTick,
|
||||
foregroundHandle: () => state.hwnd,
|
||||
expectProgrammaticKeys: vi.fn(),
|
||||
expectProgrammaticInsert: () => () => undefined,
|
||||
recentTexts: () => [],
|
||||
warmModel: () => null,
|
||||
generate: async function* () { yield '없음' }
|
||||
})
|
||||
const context: TypingContext = {
|
||||
prefix: state.text, fullText: state.text, caretOffset: state.text.length,
|
||||
anchor: null, anchorKind: null, isPassword: false, isEditable: true,
|
||||
isComposing: false, hasSelection: false, available: true,
|
||||
appName: 'notepad.exe', windowTitle: 'Fixture', windowHandle: 7,
|
||||
idleMs: 800, capturedAt: 1_800, inputRevision: 1, nativeInputTick: 5,
|
||||
editedSinceFocus: true, typedRecently: true, caretReliable: true
|
||||
}
|
||||
return { state, prior, replacementDone, keyboard, insert, typo, context }
|
||||
}
|
||||
|
||||
describe('real correction services preserve a text sink across delayed queue interleavings', () => {
|
||||
it.each(['delivered-key', 'same-millisecond-key', 'native-event-before-js'] as const)(
|
||||
'preserves the whole next Hangul word when %s arrives while correction waits', async (event) => {
|
||||
const f = fixture()
|
||||
const priorInsertion = f.insert.insertText('', 'keyboard')
|
||||
expect(f.typo.handleTypingContext(f.context)).toBe('correcting')
|
||||
await Promise.resolve()
|
||||
const expected = f.state.text + '안녕하세요 '
|
||||
f.state.text = expected
|
||||
// Isolate each guard: identical millisecond/native ticks must not hide the
|
||||
// revision case, and a native event may precede both JS-side counters.
|
||||
if (event === 'delivered-key') f.state.lastKeyAt += 100
|
||||
if (event === 'same-millisecond-key') f.state.revision += 1
|
||||
if (event === 'native-event-before-js') f.state.nativeTick += 1
|
||||
f.prior.resolve()
|
||||
await priorInsertion
|
||||
await f.replacementDone.promise
|
||||
expect(f.state.text).toBe(expected)
|
||||
expect(f.keyboard.replaceBeforeCaret).not.toHaveBeenCalled()
|
||||
f.typo.dispose()
|
||||
}
|
||||
)
|
||||
|
||||
it('still replaces the intended typo if nothing changed during the same queue wait', async () => {
|
||||
const f = fixture()
|
||||
const priorInsertion = f.insert.insertText('', 'keyboard')
|
||||
expect(f.typo.handleTypingContext(f.context)).toBe('correcting')
|
||||
f.prior.resolve()
|
||||
await priorInsertion
|
||||
await f.replacementDone.promise
|
||||
expect(f.state.text).toBe('오늘 잘 됐어요 ')
|
||||
expect(f.keyboard.replaceBeforeCaret).toHaveBeenCalledOnce()
|
||||
f.typo.dispose()
|
||||
})
|
||||
})
|
||||
|
|
@ -76,9 +76,19 @@ describe('제스처 입력 정규화', () => {
|
|||
expect(resolveGestureMode('command', false)).toBe('dictation')
|
||||
})
|
||||
|
||||
it("'command' 는 dictation 파이프라인 fallback 이라 hold-to-talk 이다", () => {
|
||||
expect(resolveGestureHoldMode('command', false)).toBe(true)
|
||||
it("'command' 는 바인딩의 holdMode(토글 또는 홀드)를 그대로 따른다", () => {
|
||||
expect(resolveGestureHoldMode('command', false)).toBe(false)
|
||||
expect(resolveGestureHoldMode('command', true)).toBe(true)
|
||||
expect(resolveGestureHoldMode('dictation', true)).toBe(true)
|
||||
expect(resolveGestureHoldMode('hands-free', false)).toBe(false)
|
||||
})
|
||||
|
||||
it("holdMode=false 인 'command' 토글은 첫 press 로 시작하고 녹음 중 다음 press 로 정지한다", () => {
|
||||
const commandTogglePress: VoiceGesture = { type: 'press', mode: 'dictation', holdMode: false }
|
||||
const commandToggleRelease: VoiceGesture = { type: 'release', mode: 'dictation', holdMode: false }
|
||||
expect(resolveVoiceIntent(commandTogglePress, 'idle')).toEqual(START_DICTATION)
|
||||
expect(resolveVoiceIntent(commandToggleRelease, 'recording')).toEqual(IGNORE)
|
||||
expect(resolveVoiceIntent(commandTogglePress, 'recording')).toEqual(STOP)
|
||||
expect(resolveVoiceIntent(commandTogglePress, 'processing')).toEqual(IGNORE)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,77 @@
|
|||
import { createRequire } from 'node:module'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const nodeRequire = createRequire(import.meta.url)
|
||||
const koffiPath = nodeRequire.resolve('koffi')
|
||||
const originalKoffi = nodeRequire.cache[koffiPath]
|
||||
const nativeRead = vi.fn<(info: Buffer) => boolean>()
|
||||
const load = vi.fn()
|
||||
let input: typeof import('../../../src/main/utils/win32-input-activity')
|
||||
|
||||
vi.mock('../../../src/main/services/LoggerService', () => ({
|
||||
getLogger: () => ({ warn: vi.fn() })
|
||||
}))
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
nativeRead.mockReset().mockImplementation((info) => {
|
||||
expect(info.length).toBe(8)
|
||||
expect(info.readUInt32LE(0)).toBe(8)
|
||||
info.writeUInt32LE(0xfedcba98, 4)
|
||||
return true
|
||||
})
|
||||
load.mockReset().mockReturnValue({ func: vi.fn(() => nativeRead) })
|
||||
nodeRequire.cache[koffiPath] = {
|
||||
id: koffiPath, filename: koffiPath, loaded: true, exports: { load }
|
||||
} as unknown as NodeModule
|
||||
input = await import('../../../src/main/utils/win32-input-activity')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalKoffi) nodeRequire.cache[koffiPath] = originalKoffi
|
||||
else delete nodeRequire.cache[koffiPath]
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('native input activity token', () => {
|
||||
it('initializes LASTINPUTINFO.cbSize and reads an unsigned DWORD without epoch conversion', () => {
|
||||
expect(input.getLastNativeInputTick()).toBe(0xfedcba98)
|
||||
expect(input.getLastNativeInputTick()).toBe(0xfedcba98)
|
||||
expect(nativeRead).toHaveBeenCalledTimes(2)
|
||||
expect(load).toHaveBeenCalledTimes(1)
|
||||
expect(load).toHaveBeenCalledWith('user32.dll')
|
||||
})
|
||||
|
||||
it('preserves zero after tick wraparound as a valid token', () => {
|
||||
nativeRead.mockImplementation((info) => {
|
||||
info.writeUInt32LE(0, 4)
|
||||
return true
|
||||
})
|
||||
expect(input.getLastNativeInputTick()).toBe(0)
|
||||
})
|
||||
|
||||
it('returns null on native failure instead of treating zeroed memory as an idle token', () => {
|
||||
nativeRead.mockReturnValueOnce(false)
|
||||
expect(input.getLastNativeInputTick()).toBeNull()
|
||||
expect(input.getLastNativeInputTick()).toBe(0xfedcba98)
|
||||
})
|
||||
|
||||
it('does not load a Windows DLL on other platforms', () => {
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')
|
||||
expect(input.getLastNativeInputTick()).toBeNull()
|
||||
expect(load).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails closed and avoids repeated native loads when koffi is unavailable', () => {
|
||||
load.mockImplementation(() => { throw new Error('unavailable') })
|
||||
expect(input.getLastNativeInputTick()).toBeNull()
|
||||
expect(input.getLastNativeInputTick()).toBeNull()
|
||||
expect(load).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('returns null when native invocation throws', () => {
|
||||
nativeRead.mockImplementation(() => { throw new Error('native failure') })
|
||||
expect(input.getLastNativeInputTick()).toBeNull()
|
||||
})
|
||||
})
|
||||
124
apps/desktop/tests/main/services/win32-unicode-input.test.ts
Normal file
124
apps/desktop/tests/main/services/win32-unicode-input.test.ts
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
import { createRequire } from 'node:module'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ErrorCode } from '@d3ro/core/errors'
|
||||
|
||||
const nodeRequire = createRequire(import.meta.url)
|
||||
const koffiPath = nodeRequire.resolve('koffi')
|
||||
const originalKoffi = nodeRequire.cache[koffiPath]
|
||||
const sendInput = vi.fn<(count: number, buffer: Buffer, size: number) => number>()
|
||||
let input: typeof import('../../../src/main/utils/win32-unicode-input')
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.resetModules()
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
sendInput.mockReset().mockImplementation((count) => count)
|
||||
// Production loads koffi with CommonJS require; vi.mock cannot intercept it.
|
||||
// Replace its cache entry before importing so no native library can receive keys.
|
||||
nodeRequire.cache[koffiPath] = {
|
||||
id: koffiPath,
|
||||
filename: koffiPath,
|
||||
loaded: true,
|
||||
exports: {
|
||||
struct: vi.fn((name: string) => name),
|
||||
union: vi.fn((name: string) => name),
|
||||
sizeof: vi.fn(() => 40),
|
||||
offsetof: vi.fn(() => 8),
|
||||
load: vi.fn(() => ({ func: vi.fn(() => sendInput) }))
|
||||
}
|
||||
} as unknown as NodeModule
|
||||
input = await import('../../../src/main/utils/win32-unicode-input')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalKoffi) nodeRequire.cache[koffiPath] = originalKoffi
|
||||
else delete nodeRequire.cache[koffiPath]
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function events(): Array<{ vk: number; scan: number; flags: number }> {
|
||||
const [count, buffer, size] = sendInput.mock.calls[0]
|
||||
expect(size).toBe(40)
|
||||
expect(buffer.length).toBe(count * size)
|
||||
return Array.from({ length: count }, (_, index) => {
|
||||
const base = index * size
|
||||
expect(buffer.readUInt32LE(base)).toBe(1)
|
||||
return {
|
||||
vk: buffer.readUInt16LE(base + 8),
|
||||
scan: buffer.readUInt16LE(base + 10),
|
||||
flags: buffer.readUInt32LE(base + 12)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
describe('Win32 input batches', () => {
|
||||
it('encodes Hangul and both UTF-16 surrogate units as Unicode down/up pairs', () => {
|
||||
expect(input.sendWin32UnicodeText('안😀')).toBe(true)
|
||||
expect(sendInput).toHaveBeenCalledTimes(1)
|
||||
expect(events()).toEqual([
|
||||
{ vk: 0, scan: 0xc548, flags: 4 }, { vk: 0, scan: 0xc548, flags: 6 },
|
||||
{ vk: 0, scan: 0xd83d, flags: 4 }, { vk: 0, scan: 0xd83d, flags: 6 },
|
||||
{ vk: 0, scan: 0xde00, flags: 4 }, { vk: 0, scan: 0xde00, flags: 6 }
|
||||
])
|
||||
})
|
||||
|
||||
it('puts composition commit, requested deletion plus commit space, and replacement in one batch', () => {
|
||||
expect(input.sendWin32UnicodeReplacement(2, '안', { commitComposition: true })).toBe(true)
|
||||
expect(sendInput).toHaveBeenCalledTimes(1)
|
||||
expect(events()).toEqual([
|
||||
{ vk: 0x20, scan: 0, flags: 0 }, { vk: 0x20, scan: 0, flags: 2 },
|
||||
{ vk: 8, scan: 0, flags: 0 }, { vk: 8, scan: 0, flags: 2 },
|
||||
{ vk: 8, scan: 0, flags: 0 }, { vk: 8, scan: 0, flags: 2 },
|
||||
{ vk: 8, scan: 0, flags: 0 }, { vk: 8, scan: 0, flags: 2 },
|
||||
{ vk: 0, scan: 0xc548, flags: 4 }, { vk: 0, scan: 0xc548, flags: 6 }
|
||||
])
|
||||
})
|
||||
|
||||
it('permits fallback only when the native call reports no inserted events', () => {
|
||||
sendInput.mockReturnValue(0)
|
||||
expect(input.sendWin32UnicodeText('hello')).toBe(false)
|
||||
expect(input.sendWin32UnicodeReplacement(2, '안')).toBe(false)
|
||||
})
|
||||
|
||||
it.each([1, 2, 4, 5])('rejects a replacement after %i of 6 events instead of replaying deletions', (sent) => {
|
||||
sendInput.mockReturnValue(sent)
|
||||
expect(() => input.sendWin32UnicodeReplacement(2, '안')).toThrow(`${sent}/6 events; retry blocked`)
|
||||
expect(sendInput).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects partially inserted ordinary text instead of duplicating it', () => {
|
||||
sendInput.mockReturnValue(2)
|
||||
expect(() => input.sendWin32UnicodeText('안녕')).toThrow('2/4 events; retry blocked')
|
||||
expect(sendInput).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('blocks retry when the native result is unknown', () => {
|
||||
sendInput.mockImplementation(() => { throw new Error('native failure') })
|
||||
expect(() => input.sendWin32UnicodeReplacement(2, '안')).toThrow('unknown insertion result')
|
||||
expect(() => input.sendWin32UnicodeText('안')).toThrow('unknown insertion result')
|
||||
expect(sendInput).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('propagates partial insertion through the actual keyboard adapter and service without fallback', async () => {
|
||||
const { NutKeyboardPort } = await import('../../../src/main/services/text-insert/nut-keyboard-port')
|
||||
const { TextInsertService } = await import('../../../src/main/services/TextInsertService')
|
||||
const keyboard = new NutKeyboardPort('win32')
|
||||
const backspace = vi.spyOn(keyboard, 'backspace')
|
||||
const type = vi.spyOn(keyboard, 'type')
|
||||
const service = new TextInsertService({ keyboard, platform: 'win32' })
|
||||
const completed = vi.fn()
|
||||
service.on('insert-completed', completed)
|
||||
sendInput.mockReturnValue(2)
|
||||
|
||||
await expect(service.replaceBeforeCaret(2, '안', 'keyboard')).rejects.toMatchObject({
|
||||
code: ErrorCode.TextInsertKeySimulationFailed
|
||||
})
|
||||
expect(sendInput).toHaveBeenCalledTimes(1)
|
||||
expect(backspace).not.toHaveBeenCalled()
|
||||
expect(type).not.toHaveBeenCalled()
|
||||
expect(completed).not.toHaveBeenCalled()
|
||||
|
||||
sendInput.mockImplementation((count) => count)
|
||||
await expect(service.replaceBeforeCaret(2, '안', 'keyboard')).resolves.toMatchObject({ success: true })
|
||||
expect(completed).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
27
apps/desktop/tests/main/utils/inference-cpu-budget.test.ts
Normal file
27
apps/desktop/tests/main/utils/inference-cpu-budget.test.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import { inferenceCpuThreads, localInferenceCpuOptions } from '../../../src/main/utils/inference-cpu-budget'
|
||||
|
||||
describe('local inference scheduling budget', () => {
|
||||
it.each([[1, 1], [2, 1], [3, 1], [4, 2], [6, 4], [8, 4], [16, 4], [64, 4]])(
|
||||
'leaves foreground headroom on %i available CPUs (%i workers)', (cpus, expected) => {
|
||||
expect(inferenceCpuThreads(cpus)).toBe(expected)
|
||||
}
|
||||
)
|
||||
|
||||
it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])('uses one worker for invalid capacity %s', (cpus) => {
|
||||
expect(inferenceCpuThreads(cpus)).toBe(1)
|
||||
})
|
||||
|
||||
it.each(['http://localhost:11434', 'http://localhost.:11434', 'http://127.0.0.1:11434', 'http://127.0.0.2:11434', 'http://[::1]:11434'])(
|
||||
'bounds the local engine at %s', (url) => {
|
||||
expect(localInferenceCpuOptions(url).num_thread).toBeGreaterThanOrEqual(1)
|
||||
expect(localInferenceCpuOptions(url).num_thread).toBeLessThanOrEqual(4)
|
||||
}
|
||||
)
|
||||
|
||||
it.each(['https://llm.example.com', 'http://192.168.1.2:11434', 'http://localhost.example.com', 'invalid'])(
|
||||
'does not infer a remote engine budget from this PC: %s', (url) => {
|
||||
expect(localInferenceCpuOptions(url)).toEqual({})
|
||||
}
|
||||
)
|
||||
})
|
||||
|
|
@ -32,8 +32,11 @@ import { resetCloudSyncServiceForTests } from '../../src/main/services/CloudSync
|
|||
import { resetTTSPlaybackServiceForTests } from '../../src/main/services/TTSPlaybackService'
|
||||
import { resetMeetingSummaryServiceForTests } from '../../src/main/services/MeetingSummaryService'
|
||||
import { resetLocalLLMServiceForTests } from '../../src/main/services/LocalLLMService'
|
||||
import { resetLocalSTTServiceForTests } from '../../src/main/services/LocalSTTService'
|
||||
import type { IPCResult } from '@d3ro/core/errors'
|
||||
import {
|
||||
LocalSTTService,
|
||||
resetLocalSTTServiceForTests,
|
||||
} from '../../src/main/services/LocalSTTService'
|
||||
import { D3ROError, ErrorCode, type IPCResult } from '@d3ro/core/errors'
|
||||
import type { NewHistory } from '../../src/main/db/schema'
|
||||
|
||||
const ipcHandlers = new Map<string, (...args: unknown[]) => unknown>()
|
||||
|
|
@ -103,6 +106,8 @@ export function resetAllSingletons(): void {
|
|||
|
||||
export function useRedHarness(): void {
|
||||
let testdb: ReturnType<typeof createTestDb> | null = null
|
||||
let initSpy: ReturnType<typeof vi.spyOn> | null = null
|
||||
let ensureSidecarSpy: ReturnType<typeof vi.spyOn> | null = null
|
||||
|
||||
beforeEach(() => {
|
||||
testdb = createTestDb()
|
||||
|
|
@ -110,9 +115,28 @@ export function useRedHarness(): void {
|
|||
initInMemoryConfig()
|
||||
resetAllSingletons()
|
||||
resetIpcHandlers()
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => {
|
||||
throw new TypeError('fetch failed (red harness offline default)')
|
||||
}),
|
||||
)
|
||||
const sidecarDisabledError = (): Promise<never> =>
|
||||
Promise.reject(
|
||||
new D3ROError(
|
||||
ErrorCode.STTSidecarSpawnFailed,
|
||||
'red harness: real Python sidecar spawn is disabled in usecase tests',
|
||||
),
|
||||
)
|
||||
initSpy = vi.spyOn(LocalSTTService.prototype, 'initialize').mockImplementation(sidecarDisabledError)
|
||||
ensureSidecarSpy = vi.spyOn(LocalSTTService.prototype, 'ensureSidecar').mockImplementation(sidecarDisabledError)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
initSpy?.mockRestore()
|
||||
ensureSidecarSpy?.mockRestore()
|
||||
initSpy = null
|
||||
ensureSidecarSpy = null
|
||||
resetAllSingletons()
|
||||
unbindTestDatabase()
|
||||
testdb?.close()
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AdMediationConfig } from '@d3ro/core/types'
|
||||
import { Feature, type AdMediationConfig } from '@d3ro/core/types'
|
||||
import { getAdMediationEngine } from '../../src/main/services/ads/AdMediationEngine'
|
||||
import { getAdSettlementService } from '../../src/main/services/ads/AdSettlementService'
|
||||
import { getLicenseService } from '../../src/main/services/LicenseService'
|
||||
import { EthicalAdsAdapter } from '../../src/main/services/ads/EthicalAdsAdapter'
|
||||
import { CarbonAdsAdapter } from '../../src/main/services/ads/CarbonAdsAdapter'
|
||||
import { PlaywireAdapter } from '../../src/main/services/ads/PlaywireAdapter'
|
||||
|
|
@ -275,3 +276,88 @@ describe('AdSettlementService fail-closed ledger', () => {
|
|||
expect(settlement.getRevenueStats('2026-08')).toEqual(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GAP-ADS-02 rewarded quota integration', () => {
|
||||
const engine = getAdMediationEngine()
|
||||
const knownNetworks = engine.getConfig().networks
|
||||
|
||||
it('grants LicenseService bonus quota on verified rewarded ad completion and blocks replay', async () => {
|
||||
const license = getLicenseService()
|
||||
const baseQuota = license.getUsage(Feature.PREMIUM_LLM)
|
||||
|
||||
engine.setConfig({
|
||||
rewardTokensAmount: 50,
|
||||
rewardCooldownSeconds: 0,
|
||||
networks: knownNetworks.map((n) =>
|
||||
n.id === 'direct_sponsor'
|
||||
? {
|
||||
...n,
|
||||
enabled: true,
|
||||
endpointUrl: 'https://ads.example.com',
|
||||
apiSecret: 'secret',
|
||||
}
|
||||
: { ...n, enabled: false },
|
||||
),
|
||||
})
|
||||
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
bidEcpm: 15,
|
||||
creative: {
|
||||
id: 'rewarded-ad-1',
|
||||
title: 'Rewarded Video',
|
||||
advertiserName: 'D3RO Partner',
|
||||
clickUrl: 'https://example.com/reward',
|
||||
format: 'rewarded_video',
|
||||
rewardTokens: 50,
|
||||
durationSeconds: 15,
|
||||
},
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ ok: true }), { status: 200 }))
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ success: true, tokenReward: 50 }), { status: 200 }),
|
||||
)
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
try {
|
||||
const auction = await engine.runAuction({
|
||||
placement: 'rewarded_video_quota',
|
||||
format: 'rewarded_video',
|
||||
floorEcpm: 4,
|
||||
})
|
||||
expect(auction.winner?.id).toBe('rewarded-ad-1')
|
||||
|
||||
engine.recordImpression({
|
||||
adId: 'rewarded-ad-1',
|
||||
format: 'rewarded_video',
|
||||
network: 'direct_sponsor',
|
||||
earnedEcpm: auction.winningBidEcpm,
|
||||
})
|
||||
|
||||
const claim = await engine.claimReward('rewarded-ad-1', 'direct_sponsor', 'nonce-1')
|
||||
expect(claim.success).toBe(true)
|
||||
expect(claim.tokensAdded).toBe(50)
|
||||
expect(claim.newTotalQuota).toBe(baseQuota.limit + 50)
|
||||
expect(license.getUsage(Feature.PREMIUM_LLM).limit).toBe(baseQuota.limit + 50)
|
||||
|
||||
// Replay with same adId or nonce is rejected
|
||||
const replay = await engine.claimReward('rewarded-ad-1', 'direct_sponsor', 'nonce-1')
|
||||
expect(replay).toEqual({
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
})
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
engine.setConfig({
|
||||
networks: knownNetworks.map((n) => ({ ...n, enabled: false })),
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
|
|||
368
apps/desktop/tests/unit/desktop-ux-gaps.test.ts
Normal file
368
apps/desktop/tests/unit/desktop-ux-gaps.test.ts
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
// apps/desktop/tests/unit/desktop-ux-gaps.test.ts
|
||||
// Unit tests for Desktop UX & Main backlog items:
|
||||
// GAP-UX-06, GAP-KEY-03, GAP-ADS-02, GAP-UX-01, GAP-UX-02, GAP-UX-03
|
||||
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { EventEmitter } from 'events'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import { ErrorCode, ipcError, ipcSuccess } from '@d3ro/core/errors'
|
||||
import { Feature } from '@d3ro/core/types'
|
||||
import { STT_PROVIDERS_META } from '../../src/main/services/stt/STTManager'
|
||||
import { registerAudioHandlers } from '../../src/main/ipc/audio-handlers'
|
||||
import { getAudioCaptureService } from '../../src/main/services/AudioCaptureService'
|
||||
import { getDictionaryService } from '../../src/main/services/DictionaryService'
|
||||
import { getVoiceConversationService } from '../../src/main/services/VoiceConversationService'
|
||||
import { getTTSPlaybackService } from '../../src/main/services/TTSPlaybackService'
|
||||
import { registerVoiceConversationHandlers } from '../../src/main/ipc/voice-conversation-handlers'
|
||||
import { resolveRagAddError } from '../../src/renderer/pages/KnowledgeBasePage'
|
||||
import { getVoiceModeService } from '../../src/main/services/VoiceModeService'
|
||||
import { getLicenseService } from '../../src/main/services/LicenseService'
|
||||
import { getMeetingModeService } from '../../src/main/services/MeetingModeService'
|
||||
import { registerMeetingModeHandlers } from '../../src/main/ipc/meeting-mode-handlers'
|
||||
import { syncNotepadMemo, loadNotepad } from '../../src/renderer/components/meeting/meeting-notepad-storage'
|
||||
import { getHistoryService } from '../../src/main/services/HistoryService'
|
||||
import { registerHistoryHandlers } from '../../src/main/ipc/history-handlers'
|
||||
import { getMemoService } from '../../src/main/services/MemoService'
|
||||
import {
|
||||
MEETING_SUMMARY_PROMPT,
|
||||
extractTranscriptCitations,
|
||||
parseCitationTimestampMs,
|
||||
} from '../../src/main/services/MeetingSummaryService'
|
||||
import { splitTextWithCitations } from '../../src/renderer/components/meeting/MarkdownRenderer'
|
||||
import { getDatabase } from '../../src/main/db'
|
||||
import { meetingSessions } from '../../src/main/db/schema'
|
||||
import { historyInput, invokeIpc, useRedHarness } from '../red/harness'
|
||||
|
||||
useRedHarness()
|
||||
|
||||
describe('GAP-UX-06: Desktop Main Cleanup (sub-items a–f)', () => {
|
||||
it('(a) STT_PROVIDERS_META uses neutral technical descriptions without marketing strings', () => {
|
||||
const bannedTerms = ['100% 완전 오프라인', 'Industry Benchmark', 'Ultra Fast', 'Enterprise Ready', 'K-Language Best']
|
||||
for (const meta of STT_PROVIDERS_META) {
|
||||
for (const banned of bannedTerms) {
|
||||
expect(meta.description).not.toContain(banned)
|
||||
expect(meta.badge ?? '').not.toContain(banned)
|
||||
}
|
||||
expect(meta.description.length).toBeGreaterThan(5)
|
||||
}
|
||||
})
|
||||
|
||||
it('(b) AUDIO.TEST_DEVICE forwards the requested deviceId to AudioCaptureService.acquire', async () => {
|
||||
registerAudioHandlers()
|
||||
const audioService = getAudioCaptureService()
|
||||
const fakeStream = new EventEmitter()
|
||||
const releaseMock = vi.fn().mockResolvedValue(undefined)
|
||||
const acquireSpy = vi.spyOn(audioService, 'acquire').mockResolvedValue({
|
||||
stream: fakeStream,
|
||||
sampleRate: 16000,
|
||||
channels: 1,
|
||||
release: releaseMock,
|
||||
})
|
||||
|
||||
try {
|
||||
const res = await invokeIpc<{ success: boolean }>(IPC_CHANNELS.AUDIO.TEST_DEVICE, {
|
||||
deviceId: 'usb-mic-device-42',
|
||||
durationMs: 50,
|
||||
})
|
||||
expect(res.success).toBe(true)
|
||||
expect(acquireSpy).toHaveBeenCalledWith('usb-mic-device-42')
|
||||
await invokeIpc(IPC_CHANNELS.AUDIO.STOP_TEST)
|
||||
} finally {
|
||||
acquireSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('(c) DictionaryService includes pronunciation in getPromptHints and applyDictionaryCorrections replaces & increments usageCount', () => {
|
||||
const dict = getDictionaryService()
|
||||
const added = dict.add({
|
||||
word: 'D3ROVoice',
|
||||
pronunciation: '디쓰리로보이스, 디쓰리로',
|
||||
category: 'general',
|
||||
})
|
||||
|
||||
const hints = dict.getPromptHints()
|
||||
expect(hints).toContain('D3ROVoice (디쓰리로보이스, 디쓰리로)')
|
||||
|
||||
const corrected = dict.applyDictionaryCorrections('오늘 디쓰리로보이스 테스트를 진행합니다')
|
||||
expect(corrected.text).toBe('오늘 D3ROVoice 테스트를 진행합니다')
|
||||
expect(corrected.matchedIds).toEqual([added.id])
|
||||
|
||||
const page = dict.list({ page: 0, pageSize: 10 })
|
||||
const entry = page.entries.find((e) => e.id === added.id)
|
||||
expect(entry?.usageCount).toBe(1)
|
||||
})
|
||||
|
||||
it('(d) VoiceConversationService.replayMessage speaks assistant message via TTSPlaybackService and is exposed via IPC', async () => {
|
||||
registerVoiceConversationHandlers()
|
||||
const tts = getTTSPlaybackService()
|
||||
const speakSpy = vi.spyOn(tts, 'speakSentences').mockResolvedValue(undefined)
|
||||
|
||||
try {
|
||||
const res = await invokeIpc(IPC_CHANNELS.VOICE_CONVERSATION.REPLAY_MESSAGE ?? 'voiceConversation:replayMessage', {
|
||||
text: '다시 읽어줄 응답입니다.',
|
||||
})
|
||||
expect(res.success).toBe(true)
|
||||
expect(speakSpy).toHaveBeenCalledWith(['다시 읽어줄 응답입니다.'])
|
||||
|
||||
await getVoiceConversationService().replayMessage('직접 호출 테스트')
|
||||
expect(speakSpy).toHaveBeenCalledWith(['직접 호출 테스트'])
|
||||
} finally {
|
||||
speakSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('(e) preload instruction.getAll is typed as CustomInstruction[]', () => {
|
||||
const preloadSrc = fs.readFileSync(
|
||||
path.resolve(__dirname, '../../src/preload/index.ts'),
|
||||
'utf-8',
|
||||
)
|
||||
expect(preloadSrc).toContain('invoke<CustomInstruction[]>(IPC_CHANNELS.INSTRUCTION.GET_ALL)')
|
||||
})
|
||||
|
||||
it('(f) resolveRagAddError checks structured details.cancelled / error code instead of fragile string matching', () => {
|
||||
const cancelledResp = ipcError(ErrorCode.RAGIndexingFailed, 'File selection cancelled', {
|
||||
cancelled: true,
|
||||
reason: 'dialog_cancelled',
|
||||
})
|
||||
expect(resolveRagAddError(cancelledResp)).toBeNull()
|
||||
|
||||
const realErrorResp = ipcError(ErrorCode.RAGIndexingFailed, 'Failed to parse PDF', {
|
||||
cancelled: false,
|
||||
})
|
||||
expect(resolveRagAddError(realErrorResp)).toBe('Failed to parse PDF')
|
||||
|
||||
const okResp = ipcSuccess({
|
||||
id: 'doc-1',
|
||||
title: 'Test',
|
||||
filePath: '/tmp/test.txt',
|
||||
chunkCount: 2,
|
||||
createdAt: Date.now(),
|
||||
})
|
||||
expect(resolveRagAddError(okResp)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('GAP-KEY-03: command Keybinding Action Dedicated Behavior', () => {
|
||||
it('_resolveHoldMode honors specHoldMode for command action and _resolveLlmRoute upgrades none to refine', async () => {
|
||||
const { configSet } = await import('../../src/main/services/ConfigService')
|
||||
configSet('llmBackend', 'online')
|
||||
configSet('defaultLLMAction', 'none')
|
||||
|
||||
const vm = getVoiceModeService()
|
||||
expect(vm._resolveHoldMode('command', false)).toBe(false)
|
||||
expect(vm._resolveHoldMode('command', true)).toBe(true)
|
||||
|
||||
const resolveRoute = (
|
||||
vm as unknown as {
|
||||
_resolveLlmRoute: (
|
||||
overrideId: string | null,
|
||||
actionId?: 'dictation' | 'command' | 'hands-free',
|
||||
) => { kind: string; action?: string; reason?: string }
|
||||
}
|
||||
)._resolveLlmRoute.bind(vm)
|
||||
|
||||
expect(resolveRoute(null, 'dictation')).toEqual({ kind: 'insert-raw', reason: 'none' })
|
||||
expect(resolveRoute(null, 'command')).toEqual({ kind: 'action', action: 'refine' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GAP-ADS-02: LicenseService.grantRewardQuota', () => {
|
||||
it('increments bonus quota for PREMIUM_LLM and deduplicates nonces', () => {
|
||||
const license = getLicenseService()
|
||||
const before = license.getUsage(Feature.PREMIUM_LLM)
|
||||
|
||||
const first = license.grantRewardQuota(50, 'nonce-abc')
|
||||
expect(first.granted).toBe(true)
|
||||
expect(first.tokensAdded).toBe(50)
|
||||
expect(first.bonusQuota).toBe(50)
|
||||
expect(first.newTotalQuota).toBe(before.limit + 50)
|
||||
|
||||
const duplicate = license.grantRewardQuota(50, 'nonce-abc')
|
||||
expect(duplicate.granted).toBe(false)
|
||||
expect(duplicate.tokensAdded).toBe(0)
|
||||
expect(license.getUsage(Feature.PREMIUM_LLM).limit).toBe(before.limit + 50)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GAP-UX-01: Meeting Post-Meeting addMemo & Notepad Sync', () => {
|
||||
it('allows adding a memo to an ended meeting session by meetingId and syncs via syncNotepadMemo', async () => {
|
||||
registerMeetingModeHandlers()
|
||||
const now = Date.now()
|
||||
getDatabase()
|
||||
.insert(meetingSessions)
|
||||
.values({
|
||||
id: 'ended-session-1',
|
||||
title: '종료된 회의',
|
||||
status: 'completed',
|
||||
startedAt: now - 60_000,
|
||||
endedAt: now,
|
||||
durationMs: 60_000,
|
||||
rawTranscript: '[00:10] 안녕하세요',
|
||||
createdAt: now - 60_000,
|
||||
updatedAt: now,
|
||||
})
|
||||
.run()
|
||||
|
||||
const memo = await getMeetingModeService().addMemo('회의 종료 후 추가한 메모', 'ended-session-1')
|
||||
expect(memo.sessionId).toBe('ended-session-1')
|
||||
expect(memo.content).toBe('회의 종료 후 추가한 메모')
|
||||
expect(memo.timestampMs).toBe(60_000)
|
||||
|
||||
const detail = getMeetingModeService().getSession('ended-session-1')
|
||||
expect(detail.memos).toHaveLength(1)
|
||||
expect(detail.memos[0].content).toBe('회의 종료 후 추가한 메모')
|
||||
|
||||
// Test notepad storage + IPC sync helper
|
||||
const fakeStorageMap = new Map<string, string>()
|
||||
const fakeStorage = {
|
||||
getItem: (k: string) => fakeStorageMap.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => {
|
||||
fakeStorageMap.set(k, v)
|
||||
},
|
||||
removeItem: (k: string) => {
|
||||
fakeStorageMap.delete(k)
|
||||
},
|
||||
}
|
||||
|
||||
const synced = await syncNotepadMemo(
|
||||
fakeStorage,
|
||||
'ended-session-1',
|
||||
'노트패드에서 동기화된 메모',
|
||||
{
|
||||
addMemo: (params) =>
|
||||
invokeIpc(IPC_CHANNELS.MEETING_MODE.ADD_MEMO, params),
|
||||
},
|
||||
)
|
||||
expect(loadNotepad(fakeStorage, 'ended-session-1')).toBe('노트패드에서 동기화된 메모')
|
||||
expect(synced?.content).toBe('노트패드에서 동기화된 메모')
|
||||
expect(getMeetingModeService().getSession('ended-session-1').memos).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GAP-UX-02: History SQLite Multi-Filter, Update, and Markdown Export', () => {
|
||||
it('filters HistoryService.getAll in SQLite by mode, isFavorite, tag, search, and beforeCreatedAt', () => {
|
||||
const historySvc = getHistoryService()
|
||||
const memoSvc = getMemoService()
|
||||
|
||||
const e1 = historySvc.create(
|
||||
historyInput({
|
||||
originalText: '알파 프로젝트 일정 논의',
|
||||
mode: 'dictation',
|
||||
isFavorite: true,
|
||||
}),
|
||||
)
|
||||
const e2 = historySvc.create(
|
||||
historyInput({
|
||||
originalText: '알파 프로젝트 번역 테스트',
|
||||
mode: 'translate',
|
||||
isFavorite: true,
|
||||
}),
|
||||
)
|
||||
historySvc.create(
|
||||
historyInput({
|
||||
originalText: '베타 프로젝트 일반 메모',
|
||||
mode: 'dictation',
|
||||
isFavorite: false,
|
||||
}),
|
||||
)
|
||||
|
||||
memoSvc.addTag(e1.id, 'alpha')
|
||||
memoSvc.addTag(e2.id, 'alpha')
|
||||
|
||||
// Object caller with combined filters
|
||||
const filtered = historySvc.getAll({
|
||||
page: 0,
|
||||
pageSize: 10,
|
||||
mode: 'dictation',
|
||||
isFavorite: true,
|
||||
tag: 'alpha',
|
||||
search: '일정',
|
||||
})
|
||||
expect(filtered.total).toBe(1)
|
||||
expect(filtered.entries[0].id).toBe(e1.id)
|
||||
|
||||
// Backward-compatible positional caller (limit, offset, search)
|
||||
const positional = historySvc.getAll(10, 0, '알파')
|
||||
expect(positional.total).toBe(2)
|
||||
})
|
||||
|
||||
it('updates history entry title and text via HistoryService.update and history:update IPC', async () => {
|
||||
registerHistoryHandlers()
|
||||
const historySvc = getHistoryService()
|
||||
const created = historySvc.create(
|
||||
historyInput({
|
||||
originalText: '초기 원문 텍스트',
|
||||
polishedText: '초기 다듬은 텍스트',
|
||||
}),
|
||||
)
|
||||
|
||||
const res = await invokeIpc<{ id: string; title: string | null; polishedText: string | null }>(
|
||||
'history:update',
|
||||
{
|
||||
id: created.id,
|
||||
title: '수정된 제목',
|
||||
polishedText: '수정된 본문 내용입니다',
|
||||
},
|
||||
)
|
||||
expect(res.success).toBe(true)
|
||||
if (res.success) {
|
||||
expect(res.data.title).toBe('수정된 제목')
|
||||
expect(res.data.polishedText).toBe('수정된 본문 내용입니다')
|
||||
}
|
||||
|
||||
const reloaded = historySvc.getById(created.id)
|
||||
expect(reloaded?.title).toBe('수정된 제목')
|
||||
expect(reloaded?.polishedText).toBe('수정된 본문 내용입니다')
|
||||
expect(reloaded?.wordCount).toBe(3)
|
||||
})
|
||||
|
||||
it('exports untagged history records and supports custom savePath in MemoService.exportMarkdown', () => {
|
||||
const historySvc = getHistoryService()
|
||||
historySvc.create(
|
||||
historyInput({
|
||||
title: '태그 없는 메모',
|
||||
originalText: '태그가 없어도 내보내기에 포함됩니다',
|
||||
}),
|
||||
)
|
||||
|
||||
const customPath = path.join(os.tmpdir(), `d3ro-memo-export-test-${Date.now()}.md`)
|
||||
try {
|
||||
const outPath = getMemoService().exportMarkdown({
|
||||
format: 'markdown',
|
||||
savePath: customPath,
|
||||
})
|
||||
expect(outPath).toBe(path.resolve(customPath))
|
||||
const content = fs.readFileSync(outPath, 'utf-8')
|
||||
expect(content).toContain('## Untagged')
|
||||
expect(content).toContain('태그가 없어도 내보내기에 포함됩니다')
|
||||
} finally {
|
||||
if (fs.existsSync(customPath)) fs.unlinkSync(customPath)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('GAP-UX-03: Meeting Summary Transcript Citations', () => {
|
||||
it('parses [MM:SS] and [HH:MM:SS] citations and splits summary text into clickable citation parts', () => {
|
||||
expect(MEETING_SUMMARY_PROMPT).toContain('[MM:SS]')
|
||||
expect(parseCitationTimestampMs('[01:25]')).toBe(85_000)
|
||||
expect(parseCitationTimestampMs('[01:02:03]')).toBe(3_723_000)
|
||||
expect(parseCitationTimestampMs('[invalid]')).toBeNull()
|
||||
|
||||
const sampleMarkdown = `## 요약\n출시 일정을 확정했습니다 [02:15].\n\n## 핵심 결정사항\n- 11월 정식 배포 [05:40]`
|
||||
const citations = extractTranscriptCitations(sampleMarkdown)
|
||||
expect(citations).toEqual([
|
||||
{ label: '[02:15]', timestampMs: 135_000 },
|
||||
{ label: '[05:40]', timestampMs: 340_000 },
|
||||
])
|
||||
|
||||
const parts = splitTextWithCitations('출시 일정을 확정했습니다 [02:15].')
|
||||
expect(parts).toEqual([
|
||||
{ type: 'text', value: '출시 일정을 확정했습니다 ' },
|
||||
{ type: 'citation', label: '[02:15]', timestampMs: 135_000 },
|
||||
{ type: 'text', value: '.' },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
|
@ -9,10 +9,12 @@ import { describe, expect, it } from 'vitest'
|
|||
import {
|
||||
COMMAND_NONE,
|
||||
commandSelection,
|
||||
commandSelections,
|
||||
commandTestRequest,
|
||||
conversationBadge,
|
||||
documentIndexLabelKey,
|
||||
llmActionLabelKey,
|
||||
removeInstructionFromActiveIds,
|
||||
resolveCommandPipeline,
|
||||
withoutHidden,
|
||||
isInstructionInUse,
|
||||
|
|
@ -32,6 +34,21 @@ describe('resolveCommandPipeline', () => {
|
|||
const p = resolveCommandPipeline({ defaultLLMAction: 'custom', activeInstructionId: 'i1' }, list)
|
||||
expect(p).toEqual({ kind: 'instruction', instruction: polish })
|
||||
expect(commandSelection(p)).toBe('i1')
|
||||
expect(commandSelections(p)).toEqual(['i1'])
|
||||
})
|
||||
|
||||
it("'custom' + 복수 지시문('i2,i1')이면 선택한 순서대로 다단계 파이프라인을 구성한다", () => {
|
||||
const p = resolveCommandPipeline({ defaultLLMAction: 'custom', activeInstructionId: 'i2,i1' }, list)
|
||||
expect(p).toEqual({ kind: 'instructions', instructions: [list[1], polish] })
|
||||
expect(commandSelection(p)).toBe('i2,i1')
|
||||
expect(commandSelections(p)).toEqual(['i2', 'i1'])
|
||||
const testReq = commandTestRequest(p, ' 어 오늘 회의 내용 정리 ')
|
||||
expect(testReq.ok).toBe(true)
|
||||
if (testReq.ok) {
|
||||
expect(testReq.params.action).toBe('custom')
|
||||
expect(testReq.params.customPrompt).toContain('[1단계: 요약]')
|
||||
expect(testReq.params.customPrompt).toContain('[2단계: 정중하게]')
|
||||
}
|
||||
})
|
||||
|
||||
it("'custom' 인데 지시문이 지워졌으면 '선택 안 됨'으로 정직하게", () => {
|
||||
|
|
@ -98,8 +115,10 @@ describe('withoutHidden / documentIndexLabelKey', () => {
|
|||
})
|
||||
|
||||
describe('isInstructionInUse — 명령 삭제 확정 시점의 설정으로 판단', () => {
|
||||
it('지운 명령이 아직 선택돼 있을 때만 true', () => {
|
||||
it('지운 명령이 아직 선택돼 있을 때만 true (단일 및 복수 파이프라인 포함)', () => {
|
||||
expect(isInstructionInUse({ defaultLLMAction: 'custom', activeInstructionId: 'x' }, 'x')).toBe(true)
|
||||
expect(isInstructionInUse({ defaultLLMAction: 'custom', activeInstructionId: 'y,x' }, 'x')).toBe(true)
|
||||
expect(removeInstructionFromActiveIds('y,x', 'x')).toEqual(['y'])
|
||||
// 되돌리기 알림 동안 다른 명령을 골랐다 — 덮으면 안 된다
|
||||
expect(isInstructionInUse({ defaultLLMAction: 'custom', activeInstructionId: 'y' }, 'x')).toBe(false)
|
||||
expect(isInstructionInUse({ defaultLLMAction: 'refine', activeInstructionId: 'x' }, 'x')).toBe(false)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue