feat: ship Wave 5-6 multi-surface hygiene, optimization, and bug fixes
This commit is contained in:
parent
01ef3293cf
commit
66b6b45ba9
399 changed files with 17828 additions and 11330 deletions
|
|
@ -3,28 +3,12 @@ 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'
|
||||
import { UnityAdsAdapter } from '../../src/main/services/ads/UnityAdsAdapter'
|
||||
import { AppLovinAdapter } from '../../src/main/services/ads/AppLovinAdapter'
|
||||
import { GoogleAdManagerAdapter } from '../../src/main/services/ads/GoogleAdManagerAdapter'
|
||||
import { InMobiAdapter } from '../../src/main/services/ads/InMobiAdapter'
|
||||
import { PubMaticAdapter } from '../../src/main/services/ads/PubMaticAdapter'
|
||||
import { MintegralAdapter } from '../../src/main/services/ads/MintegralAdapter'
|
||||
import { DirectHouseSponsorAdapter } from '../../src/main/services/ads/DirectHouseSponsorAdapter'
|
||||
import { createUnavailableAdAdapters } from '../../src/main/services/ads/UnavailableAdAdapter'
|
||||
|
||||
const adapterCases = [
|
||||
['EthicalAds', new EthicalAdsAdapter()],
|
||||
['Carbon Ads', new CarbonAdsAdapter()],
|
||||
['Playwire', new PlaywireAdapter()],
|
||||
['Unity Ads', new UnityAdsAdapter()],
|
||||
['AppLovin', new AppLovinAdapter()],
|
||||
['Google Ad Manager', new GoogleAdManagerAdapter()],
|
||||
['InMobi', new InMobiAdapter()],
|
||||
['PubMatic', new PubMaticAdapter()],
|
||||
['Mintegral', new MintegralAdapter()],
|
||||
] as const
|
||||
const adapterCases = createUnavailableAdAdapters().map(
|
||||
(adapter) => [adapter.networkName, adapter] as const,
|
||||
)
|
||||
|
||||
describe('desktop ad provider boundaries', () => {
|
||||
it.each(adapterCases)('%s returns no bid until a real provider is integrated', async (_name, adapter) => {
|
||||
|
|
|
|||
500
apps/desktop/tests/unit/renderer-popups-and-helpers.test.ts
Normal file
500
apps/desktop/tests/unit/renderer-popups-and-helpers.test.ts
Normal file
|
|
@ -0,0 +1,500 @@
|
|||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import vm from 'node:vm'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createFakeClock, createSeededRandom } from '@d3ro/core/ports'
|
||||
import { toErrorMessage } from '../../src/renderer/utils/error-message'
|
||||
import { formatElapsed } from '../../src/renderer/components/meeting/meeting-format'
|
||||
import {
|
||||
formatClockTime,
|
||||
formatDayLabel,
|
||||
formatDurationLong,
|
||||
formatNumber,
|
||||
formatRecordingTime,
|
||||
formatRecordingTimeUnit,
|
||||
getDateKey,
|
||||
} from '../../src/renderer/utils/formatters'
|
||||
|
||||
interface FakeClassList {
|
||||
tokens: Set<string>
|
||||
add: (...cls: string[]) => void
|
||||
remove: (...cls: string[]) => void
|
||||
toggle: (cls: string, force?: boolean) => boolean
|
||||
contains: (cls: string) => boolean
|
||||
}
|
||||
|
||||
class FakeElement {
|
||||
id: string
|
||||
tagName: string
|
||||
children: FakeElement[] = []
|
||||
parentNode: FakeElement | null = null
|
||||
attributes = new Map<string, string>()
|
||||
listeners = new Map<string, Array<(event?: unknown) => void>>()
|
||||
style: Record<string, string> = {}
|
||||
hidden = false
|
||||
type = ''
|
||||
scrollTop = 0
|
||||
offsetWidth = 0
|
||||
innerHtmlWrites: string[] = []
|
||||
private _innerHTML = ''
|
||||
private _textContent = ''
|
||||
readonly classList: FakeClassList
|
||||
|
||||
constructor(tagName: string, id = '') {
|
||||
this.tagName = tagName.toUpperCase()
|
||||
this.id = id
|
||||
const tokens = new Set<string>()
|
||||
this.classList = {
|
||||
tokens,
|
||||
add: (...cls: string[]) => {
|
||||
for (const c of cls) tokens.add(c)
|
||||
},
|
||||
remove: (...cls: string[]) => {
|
||||
for (const c of cls) tokens.delete(c)
|
||||
},
|
||||
toggle: (cls: string, force?: boolean) => {
|
||||
const next = force ?? !tokens.has(cls)
|
||||
if (next) tokens.add(cls)
|
||||
else tokens.delete(cls)
|
||||
return next
|
||||
},
|
||||
contains: (cls: string) => tokens.has(cls),
|
||||
}
|
||||
}
|
||||
|
||||
get className(): string {
|
||||
return Array.from(this.classList.tokens).join(' ')
|
||||
}
|
||||
|
||||
set className(val: string) {
|
||||
this.classList.tokens.clear()
|
||||
for (const part of val.split(/\s+/).filter(Boolean)) {
|
||||
this.classList.tokens.add(part)
|
||||
}
|
||||
}
|
||||
|
||||
get firstChild(): FakeElement | null {
|
||||
return this.children[0] ?? null
|
||||
}
|
||||
|
||||
get textContent(): string {
|
||||
if (this.tagName === '#TEXT') return this._textContent
|
||||
return this.children.map((c) => c.textContent).join('')
|
||||
}
|
||||
|
||||
set textContent(val: string) {
|
||||
if (this.tagName === '#TEXT') {
|
||||
this._textContent = val
|
||||
this.children = []
|
||||
return
|
||||
}
|
||||
this._textContent = ''
|
||||
if (val === '') {
|
||||
this.children = []
|
||||
return
|
||||
}
|
||||
const textNode = new FakeElement('#TEXT')
|
||||
textNode._textContent = val
|
||||
this.children = [textNode]
|
||||
}
|
||||
|
||||
get innerHTML(): string {
|
||||
return this._innerHTML
|
||||
}
|
||||
|
||||
set innerHTML(val: string) {
|
||||
this.innerHtmlWrites.push(val)
|
||||
this._innerHTML = val
|
||||
if (val === '') this.children = []
|
||||
}
|
||||
|
||||
appendChild(child: FakeElement): FakeElement {
|
||||
child.parentNode = this
|
||||
this.children.push(child)
|
||||
return child
|
||||
}
|
||||
|
||||
insertBefore(child: FakeElement, refChild: FakeElement | null): FakeElement {
|
||||
child.parentNode = this
|
||||
const idx = refChild ? this.children.indexOf(refChild) : -1
|
||||
if (idx < 0) this.children.push(child)
|
||||
else this.children.splice(idx, 0, child)
|
||||
return child
|
||||
}
|
||||
|
||||
removeChild(child: FakeElement): FakeElement {
|
||||
const idx = this.children.indexOf(child)
|
||||
if (idx >= 0) {
|
||||
this.children.splice(idx, 1)
|
||||
child.parentNode = null
|
||||
}
|
||||
return child
|
||||
}
|
||||
|
||||
setAttribute(name: string, value: string): void {
|
||||
this.attributes.set(name, value)
|
||||
}
|
||||
|
||||
getAttribute(name: string): string | null {
|
||||
return this.attributes.get(name) ?? null
|
||||
}
|
||||
|
||||
removeAttribute(name: string): void {
|
||||
this.attributes.delete(name)
|
||||
}
|
||||
|
||||
addEventListener(type: string, cb: (event?: unknown) => void): void {
|
||||
const list = this.listeners.get(type) ?? []
|
||||
list.push(cb)
|
||||
this.listeners.set(type, list)
|
||||
}
|
||||
|
||||
removeEventListener(type: string, cb: (event?: unknown) => void): void {
|
||||
const list = this.listeners.get(type)
|
||||
if (!list) return
|
||||
const idx = list.indexOf(cb)
|
||||
if (idx >= 0) list.splice(idx, 1)
|
||||
}
|
||||
|
||||
dispatch(type: string, event: unknown = {}): void {
|
||||
for (const cb of this.listeners.get(type) ?? []) cb(event)
|
||||
}
|
||||
|
||||
scrollIntoView(): void {}
|
||||
setPointerCapture(): void {}
|
||||
getBoundingClientRect(): { width: number; height: number } {
|
||||
return { width: 200, height: 80 }
|
||||
}
|
||||
}
|
||||
|
||||
interface PopupSandbox {
|
||||
elements: Map<string, FakeElement>
|
||||
emitIpc: (channel: string, data?: unknown) => void
|
||||
sent: Array<{ channel: string; payload: unknown }>
|
||||
unsubCalls: () => number
|
||||
registeredCount: () => number
|
||||
triggerDocument: (type: string) => void
|
||||
triggerWindow: (type: string) => void
|
||||
flushRaf: () => void
|
||||
pendingRafCount: () => number
|
||||
}
|
||||
|
||||
function loadPopupSandbox(popupName: string, elementIds: readonly string[]): PopupSandbox {
|
||||
const scriptPath = path.resolve(
|
||||
__dirname,
|
||||
'../../src/renderer/popups',
|
||||
popupName,
|
||||
'script.js',
|
||||
)
|
||||
const code = fs.readFileSync(scriptPath, 'utf8')
|
||||
const elements = new Map<string, FakeElement>()
|
||||
for (const id of elementIds) {
|
||||
elements.set(id, new FakeElement('div', id))
|
||||
}
|
||||
|
||||
const ipcHandlers = new Map<string, Array<(data?: unknown) => void>>()
|
||||
const sent: Array<{ channel: string; payload: unknown }> = []
|
||||
let activeSubscriptions = 0
|
||||
let totalUnsubs = 0
|
||||
|
||||
const docListeners = new Map<string, Array<() => void>>()
|
||||
const winListeners = new Map<string, Array<() => void>>()
|
||||
let rafId = 0
|
||||
const rafQueue = new Map<number, () => void>()
|
||||
const fakeClock = createFakeClock(1_700_000_000_000)
|
||||
const seededRandom = createSeededRandom(42)
|
||||
|
||||
const fakeWindow = {
|
||||
addEventListener(type: string, cb: () => void): void {
|
||||
const list = winListeners.get(type) ?? []
|
||||
list.push(cb)
|
||||
winListeners.set(type, list)
|
||||
},
|
||||
removeEventListener(type: string, cb: () => void): void {
|
||||
const list = winListeners.get(type)
|
||||
if (!list) return
|
||||
const idx = list.indexOf(cb)
|
||||
if (idx >= 0) list.splice(idx, 1)
|
||||
},
|
||||
popupAPI: {
|
||||
send(channel: string, payload?: unknown): void {
|
||||
sent.push({ channel, payload })
|
||||
},
|
||||
on(channel: string, cb: (data?: unknown) => void): () => void {
|
||||
activeSubscriptions += 1
|
||||
const list = ipcHandlers.get(channel) ?? []
|
||||
list.push(cb)
|
||||
ipcHandlers.set(channel, list)
|
||||
let removed = false
|
||||
return () => {
|
||||
if (removed) return
|
||||
removed = true
|
||||
activeSubscriptions -= 1
|
||||
totalUnsubs += 1
|
||||
const current = ipcHandlers.get(channel) ?? []
|
||||
const idx = current.indexOf(cb)
|
||||
if (idx >= 0) current.splice(idx, 1)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const FakeDate = class extends Date {
|
||||
constructor(value?: number | string | Date) {
|
||||
super(value === undefined ? fakeClock.now() : (value as number))
|
||||
}
|
||||
static now(): number {
|
||||
return fakeClock.now()
|
||||
}
|
||||
}
|
||||
|
||||
const fakeMath = Object.assign(Object.create(Math), {
|
||||
random: () => seededRandom.next(),
|
||||
})
|
||||
|
||||
const context: Record<string, unknown> = {
|
||||
window: fakeWindow,
|
||||
document: {
|
||||
getElementById: (id: string) => elements.get(id) ?? null,
|
||||
querySelectorAll: () => [],
|
||||
createElement: (tag: string) => new FakeElement(tag),
|
||||
createTextNode: (text: string) => {
|
||||
const node = new FakeElement('#text')
|
||||
node.textContent = text
|
||||
return node
|
||||
},
|
||||
addEventListener(type: string, cb: () => void): void {
|
||||
const list = docListeners.get(type) ?? []
|
||||
list.push(cb)
|
||||
docListeners.set(type, list)
|
||||
},
|
||||
removeEventListener(type: string, cb: () => void): void {
|
||||
const list = docListeners.get(type)
|
||||
if (!list) return
|
||||
const idx = list.indexOf(cb)
|
||||
if (idx >= 0) list.splice(idx, 1)
|
||||
},
|
||||
},
|
||||
Date: FakeDate,
|
||||
Math: fakeMath,
|
||||
Number,
|
||||
String,
|
||||
Array,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
setInterval,
|
||||
clearInterval,
|
||||
requestAnimationFrame(cb: () => void): number {
|
||||
rafId += 1
|
||||
rafQueue.set(rafId, cb)
|
||||
return rafId
|
||||
},
|
||||
cancelAnimationFrame(id: number): void {
|
||||
rafQueue.delete(id)
|
||||
},
|
||||
}
|
||||
|
||||
vm.runInNewContext(code, context, { filename: scriptPath })
|
||||
|
||||
return {
|
||||
elements,
|
||||
sent,
|
||||
unsubCalls: () => totalUnsubs,
|
||||
registeredCount: () => activeSubscriptions,
|
||||
emitIpc(channel: string, data?: unknown): void {
|
||||
for (const cb of [...(ipcHandlers.get(channel) ?? [])]) {
|
||||
cb(data)
|
||||
}
|
||||
},
|
||||
triggerDocument(type: string): void {
|
||||
for (const cb of docListeners.get(type) ?? []) cb()
|
||||
},
|
||||
triggerWindow(type: string): void {
|
||||
for (const cb of winListeners.get(type) ?? []) cb()
|
||||
},
|
||||
flushRaf(): void {
|
||||
const entries = Array.from(rafQueue.entries())
|
||||
rafQueue.clear()
|
||||
for (const [, cb] of entries) cb()
|
||||
},
|
||||
pendingRafCount: () => rafQueue.size,
|
||||
}
|
||||
}
|
||||
|
||||
describe('렌더러 포맷터 및 팝업 스크립트 방어 동작', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('formatters와formatElapsed_비유한수와음수입력시_NaN이나음수문자열을반환하지않는다', () => {
|
||||
expect(formatElapsed(Number.NaN)).toBe('00:00')
|
||||
expect(formatElapsed(-500)).toBe('00:00')
|
||||
expect(formatElapsed(3_665_000)).toBe('1:01:05')
|
||||
|
||||
expect(formatDurationLong(Number.NaN, 'en')).toBe('0 min')
|
||||
expect(formatNumber(Number.NaN)).toBe('0')
|
||||
expect(formatRecordingTime(Number.NaN)).toBe('0')
|
||||
expect(formatRecordingTimeUnit(Number.NaN)).toBe('MIN')
|
||||
expect(getDateKey(Number.NaN)).toBe('')
|
||||
expect(formatClockTime(Number.NaN, 'en')).toBe('')
|
||||
expect(formatDayLabel(Number.NaN, 'en')).toBe('')
|
||||
|
||||
expect(toErrorMessage(new Error('network down'))).toBe('network down')
|
||||
expect(toErrorMessage('plain failure')).toBe('plain failure')
|
||||
})
|
||||
|
||||
it('commandPopup_innerHTML을사용하지않고null페이로드및beforeunload해제를안전하게처리한다', () => {
|
||||
const sandbox = loadPopupSandbox('command-popup', ['container', 'items'])
|
||||
const items = sandbox.elements.get('items')!
|
||||
|
||||
sandbox.emitIpc('command:showItems', {
|
||||
commands: [{ id: '1', name: '<img src=x onerror=alert(1)>', description: '<b>desc</b>' }],
|
||||
activeId: '',
|
||||
})
|
||||
sandbox.emitIpc('command:showItems', null)
|
||||
sandbox.emitIpc('command:keyEvent', null)
|
||||
|
||||
expect(items.innerHtmlWrites).toEqual([])
|
||||
expect(items.children[1]?.textContent).toContain('<img src=x onerror=alert(1)>')
|
||||
|
||||
sandbox.triggerWindow('beforeunload')
|
||||
expect(sandbox.registeredCount()).toBe(0)
|
||||
expect(sandbox.unsubCalls()).toBe(4)
|
||||
})
|
||||
|
||||
it('historyPopup_비유한타임스탬프와null페이로드에서도_NaN을렌더링하지않고언로드시구독을해제한다', () => {
|
||||
const sandbox = loadPopupSandbox('history-popup', ['container', 'items'])
|
||||
const items = sandbox.elements.get('items')!
|
||||
|
||||
sandbox.emitIpc('history:showItems', {
|
||||
entries: [{ id: '1', originalText: '원문', polishedText: '', createdAt: Number.NaN }],
|
||||
})
|
||||
sandbox.emitIpc('history:showItems', null)
|
||||
sandbox.emitIpc('history:keyEvent', null)
|
||||
|
||||
expect(items.innerHtmlWrites).toEqual([])
|
||||
expect(items.children[0]?.textContent.includes('NaN')).toBe(false)
|
||||
|
||||
sandbox.triggerWindow('beforeunload')
|
||||
expect(sandbox.registeredCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('resultPopup_prepare직후hide수신시_측정IPC를보내지않고숨겨진상태mouseleave로타이머가돌지않는다', () => {
|
||||
vi.useFakeTimers({ now: 1_700_000_000_000 })
|
||||
const sandbox = loadPopupSandbox('result-popup', [
|
||||
'container',
|
||||
'result-text',
|
||||
'copy-btn',
|
||||
'copy-icon',
|
||||
'check-icon',
|
||||
'copy-label',
|
||||
'close-btn',
|
||||
])
|
||||
const container = sandbox.elements.get('container')!
|
||||
|
||||
sandbox.emitIpc('result:prepare', { text: '복사할 문장' })
|
||||
sandbox.emitIpc('result:hide')
|
||||
sandbox.flushRaf()
|
||||
sandbox.flushRaf()
|
||||
|
||||
expect(sandbox.sent.filter((item) => item.channel === 'result:measured')).toEqual([])
|
||||
|
||||
container.dispatch('mouseleave')
|
||||
vi.advanceTimersByTime(5000)
|
||||
expect(sandbox.sent.filter((item) => item.channel === 'window:hideResultPopup')).toEqual([])
|
||||
|
||||
sandbox.triggerWindow('beforeunload')
|
||||
expect(sandbox.registeredCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('captionOverlay_hide이후지연페이드타이머가새세션자막을지우지않고언로드시리소스를정리한다', () => {
|
||||
vi.useFakeTimers({ now: 1_700_000_000_000 })
|
||||
const sandbox = loadPopupSandbox('caption-overlay', [
|
||||
'lines',
|
||||
'container',
|
||||
'root',
|
||||
'handle',
|
||||
'handleHint',
|
||||
])
|
||||
const lines = sandbox.elements.get('lines')!
|
||||
|
||||
sandbox.emitIpc('caption:config', { autoClearMs: 1000 })
|
||||
sandbox.emitIpc('caption:segment', { id: 's1', text: '첫 문장', timestamp: 1, isFinal: true })
|
||||
// 1000ms 뒤 fadeAndRemoveLine(500ms 타이머 시작) 진입
|
||||
vi.advanceTimersByTime(1000)
|
||||
// fade-out 도중 hide 후 곧바로 새 자막이 들어와도 이전 fade 타이머는 취소되어야 한다
|
||||
sandbox.emitIpc('caption:hide')
|
||||
expect(lines.children).toHaveLength(0)
|
||||
|
||||
sandbox.emitIpc('caption:segment', { id: 's2', text: '새 세션 문장', timestamp: 2, isFinal: true })
|
||||
sandbox.emitIpc('caption:stateChanged', null)
|
||||
vi.advanceTimersByTime(600)
|
||||
expect(lines.children).toHaveLength(1)
|
||||
expect(lines.children[0]?.textContent).toBe('새 세션 문장')
|
||||
|
||||
sandbox.triggerWindow('beforeunload')
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
expect(sandbox.registeredCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('suggestionOverlay_범위초과activeIndex에서도_유효페이지후보를표시하고언로드시정리한다', () => {
|
||||
vi.useFakeTimers({ now: 1_700_000_000_000 })
|
||||
const sandbox = loadPopupSandbox('suggestion-overlay', [
|
||||
'candidates',
|
||||
'provenance',
|
||||
'progress',
|
||||
'keyHints',
|
||||
'footer',
|
||||
'status',
|
||||
'statusText',
|
||||
'panel',
|
||||
'close',
|
||||
])
|
||||
const candidates = sandbox.elements.get('candidates')!
|
||||
|
||||
sandbox.emitIpc('suggestionPopup:show', {
|
||||
candidates: [{ text: '첫째' }, { text: '둘째' }],
|
||||
activeIndex: 99,
|
||||
generating: true,
|
||||
})
|
||||
|
||||
expect(candidates.children).toHaveLength(2)
|
||||
expect(candidates.children[1]?.classList.contains('active')).toBe(true)
|
||||
|
||||
sandbox.triggerWindow('beforeunload')
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
expect(sandbox.registeredCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('recordingTip_음수레벨클램프와언로드시인터벌및IPC해제를수행한다', () => {
|
||||
vi.useFakeTimers({ now: 1_700_000_000_000 })
|
||||
const sandbox = loadPopupSandbox('recording-tip', [
|
||||
'container',
|
||||
'wave-bars',
|
||||
'duration-text',
|
||||
'status-text',
|
||||
'cancel-hint',
|
||||
'progress',
|
||||
'partial-text',
|
||||
'done-view',
|
||||
'done-text',
|
||||
'error-view',
|
||||
'error-text',
|
||||
'head-row',
|
||||
])
|
||||
|
||||
sandbox.triggerDocument('DOMContentLoaded')
|
||||
sandbox.emitIpc('voice:audioLevel', { level: -2 })
|
||||
sandbox.emitIpc('window:tipStateChanged', { state: 'recording' })
|
||||
vi.advanceTimersByTime(1000)
|
||||
|
||||
const barHeights = sandbox.elements
|
||||
.get('wave-bars')!
|
||||
.children.map((bar) => Number.parseInt(bar.style.height, 10))
|
||||
expect(barHeights.every((h) => Number.isFinite(h) && h >= 2 && h <= 22)).toBe(true)
|
||||
|
||||
sandbox.triggerWindow('beforeunload')
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
expect(sandbox.registeredCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
186
apps/desktop/tests/unit/settings-and-suggestion-helpers.test.ts
Normal file
186
apps/desktop/tests/unit/settings-and-suggestion-helpers.test.ts
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
FALLBACK_OLLAMA_MODELS,
|
||||
RECOMMENDED_OLLAMA_MODEL,
|
||||
clampMicMeterPercent,
|
||||
formatModelSizeGb,
|
||||
listUninstalledFallbackModels,
|
||||
resolveActiveOllamaModel,
|
||||
resolveOllamaStatusSummary
|
||||
} from '../../src/renderer/components/settings/settings-model-helpers'
|
||||
import {
|
||||
applyCorrectionToContext,
|
||||
buildDecisionInputSignature,
|
||||
isDuplicateCandidateText,
|
||||
normalizeSuggestionPolicyConfig,
|
||||
rerankFilledCandidates,
|
||||
resolveTerminalTypingContext,
|
||||
sameCandidateText,
|
||||
toSuggestionCorrectionFromPlan
|
||||
} from '../../src/main/services/suggestion/suggestion-policy-helpers'
|
||||
import type { TypingContext } from '../../src/main/services/InputTelemetryService'
|
||||
|
||||
function createTypingContext(overrides: Partial<TypingContext> = {}): TypingContext {
|
||||
return {
|
||||
available: true,
|
||||
isEditable: true,
|
||||
isPassword: false,
|
||||
isComposing: false,
|
||||
hasSelection: false,
|
||||
editedSinceFocus: true,
|
||||
typedRecently: true,
|
||||
prefix: '회의 안건을 정리했습니다',
|
||||
documentBefore: '회의 안건을 정리했습니다',
|
||||
fullText: '회의 안건을 정리했습니다',
|
||||
appName: 'Notion',
|
||||
windowTitle: '주간 회의록',
|
||||
windowHandle: 101,
|
||||
anchor: null,
|
||||
anchorKind: null,
|
||||
idleMs: 700,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('settings-model-helpers', () => {
|
||||
it('활성모델결정_설정없을때_권장모델을반환한다', () => {
|
||||
expect(resolveActiveOllamaModel(undefined)).toBe(RECOMMENDED_OLLAMA_MODEL)
|
||||
expect(resolveActiveOllamaModel('qwen2.5:7b')).toBe('qwen2.5:7b')
|
||||
})
|
||||
|
||||
it('미설치기본모델목록_설치된모델제외_나머지후보만반환한다', () => {
|
||||
expect(listUninstalledFallbackModels([{ name: 'llama3.2:3b' }])).toEqual(['qwen2.5:3b'])
|
||||
expect(listUninstalledFallbackModels([])).toEqual([...FALLBACK_OLLAMA_MODELS])
|
||||
})
|
||||
|
||||
it('모델크기표시_바이트입력시_소수첫째자리기가바이트를계산한다', () => {
|
||||
const twoPointFiveGb = Math.round(2.5 * 1024 * 1024 * 1024)
|
||||
expect(formatModelSizeGb(twoPointFiveGb)).toBe(2.5)
|
||||
expect(formatModelSizeGb(0)).toBe(0)
|
||||
})
|
||||
|
||||
it('마이크레벨백분율_범위초과및음수_0과100사이정수로고정한다', () => {
|
||||
expect(clampMicMeterPercent(-0.3)).toBe(0)
|
||||
expect(clampMicMeterPercent(0.456)).toBe(46)
|
||||
expect(clampMicMeterPercent(1.8)).toBe(100)
|
||||
})
|
||||
|
||||
it('Ollama상태요약_연결상태별_적절한번역키와인자를반환한다', () => {
|
||||
expect(resolveOllamaStatusSummary(null, 0)).toEqual({ kind: 'checking' })
|
||||
expect(
|
||||
resolveOllamaStatusSummary({ connectionState: 'disconnected', models: [] }, 0)
|
||||
).toEqual({ kind: 'offline' })
|
||||
expect(
|
||||
resolveOllamaStatusSummary({ connectionState: 'connected', serverVersion: '0.6.2', models: [] }, 3)
|
||||
).toEqual({ kind: 'connectedVersion', version: '0.6.2', count: 3 })
|
||||
expect(
|
||||
resolveOllamaStatusSummary({ connectionState: 'connected', models: [] }, 2)
|
||||
).toEqual({ kind: 'connected', count: 2 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('suggestion-policy-helpers', () => {
|
||||
it('오타교정문맥적용_접두끝일치시_prefix와documentBefore끝만교체한다', () => {
|
||||
const context = createTypingContext({
|
||||
prefix: '오늘 회으에서',
|
||||
documentBefore: '제목\n오늘 회으에서'
|
||||
})
|
||||
const updated = applyCorrectionToContext(context, {
|
||||
from: '회으에서',
|
||||
to: '회의에서',
|
||||
edits: [{ start: 0, end: 2, to: '회의' }]
|
||||
})
|
||||
|
||||
expect(updated.prefix).toBe('오늘 회의에서')
|
||||
expect(updated.documentBefore).toBe('제목\n오늘 회의에서')
|
||||
})
|
||||
|
||||
it('후보동일성및중복검사_공백문장부호정규화및접두확장_중복으로판정한다', () => {
|
||||
expect(sameCandidateText('다음 주에 공유드릴게요!', '다음 주에 공유드릴게요.')).toBe(true)
|
||||
expect(
|
||||
isDuplicateCandidateText('다음 주에 공유드릴게요 그리고 검토 부탁드립니다', [
|
||||
{ text: '다음 주에 공유드릴게요', rank: 0 }
|
||||
])
|
||||
).toBe(true)
|
||||
expect(
|
||||
isDuplicateCandidateText('내일 오전에 다시 확인하겠습니다', [
|
||||
{ text: '다음 주에 공유드릴게요', rank: 0 }
|
||||
])
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('채우기후보재정렬_개인화점수높은신규후보_개인후보유지하고모델후보앞으로배치한다', () => {
|
||||
const candidates = [
|
||||
{ text: '먼저', rank: 0, source: 'personal' as const },
|
||||
{ text: '일반적인 안내 문장입니다.', rank: 1 },
|
||||
{ text: '주간 배포 체크리스트 공유드립니다.', rank: 2 }
|
||||
]
|
||||
const reranked = rerankFilledCandidates(candidates, '주간 배포 체크리스트 공유드립니다.', {
|
||||
prefix: '이번 스프린트 마무리하며',
|
||||
continuationHints: ['주간 배포 체크리스트 공유드립니다.'],
|
||||
followUpHints: ['주간 배포 체크리스트 공유드립니다.'],
|
||||
relatedHints: [],
|
||||
phraseHints: ['주간 배포 체크리스트']
|
||||
})
|
||||
|
||||
expect(reranked[0]).toEqual({ text: '먼저', rank: 0, source: 'personal' })
|
||||
expect(reranked[1]).toEqual({ text: '주간 배포 체크리스트 공유드립니다.', rank: 1 })
|
||||
expect(reranked[2]).toEqual({ text: '일반적인 안내 문장입니다.', rank: 2 })
|
||||
})
|
||||
|
||||
it('정책설정정규화_최소지연시간및분당최대요청상한_강제적용한다', () => {
|
||||
const normalized = normalizeSuggestionPolicyConfig({
|
||||
triggerDelayMs: 50,
|
||||
minPrefixChars: 0,
|
||||
maxRequestsPerMinute: 999,
|
||||
dailyBudget: 0,
|
||||
excludedApps: ['1Password.exe']
|
||||
})
|
||||
|
||||
expect(normalized.triggerDelayMs).toBeGreaterThanOrEqual(200)
|
||||
expect(normalized.maxRequestsPerMinute).toBe(30)
|
||||
expect(normalized.excludedApps).toEqual(['1Password.exe'])
|
||||
})
|
||||
|
||||
it('교정계획변환_접두끝불일치시_제외하고일치시상대오프셋으로변환한다', () => {
|
||||
const mismatched = toSuggestionCorrectionFromPlan('다른 문장', {
|
||||
originalText: '회으',
|
||||
insertText: '회의',
|
||||
corrections: [{ start: 10, end: 12, to: '회의' }]
|
||||
})
|
||||
expect(mismatched).toBe(undefined)
|
||||
|
||||
const matched = toSuggestionCorrectionFromPlan('오늘 회으 진행', {
|
||||
originalText: '회으 진행',
|
||||
insertText: '회의 진행',
|
||||
corrections: [{ start: 3, end: 5, to: '회의' }]
|
||||
})
|
||||
expect(matched).toEqual({
|
||||
from: '회으 진행',
|
||||
to: '회의 진행',
|
||||
edits: [{ start: 0, end: 2, to: '회의' }]
|
||||
})
|
||||
})
|
||||
|
||||
it('판단입력서명및터미널문맥_회색추천문구와끝타이핑_정확히구분한다', () => {
|
||||
const context = createTypingContext({ anchor: { x: 10, y: 20, width: 4, height: 18 } })
|
||||
expect(
|
||||
buildDecisionInputSignature(context, { modelAvailable: true, enabled: true })
|
||||
).toBe('true|true|false|false|A|true|true|true|true')
|
||||
|
||||
const emptyStep = resolveTerminalTypingContext(
|
||||
createTypingContext({ appName: 'WindowsTerminal', fullText: 'PS D:\\repo> ' }),
|
||||
{ lastPrompt: null, promptTyped: false }
|
||||
)
|
||||
expect(emptyStep.context.caretReliable).toBe(true)
|
||||
|
||||
const ghostSuggestionStep = resolveTerminalTypingContext(
|
||||
createTypingContext({
|
||||
appName: 'WindowsTerminal',
|
||||
fullText: 'PS D:\\repo> run the entire verification pipeline now'
|
||||
}),
|
||||
emptyStep.nextState
|
||||
)
|
||||
expect(ghostSuggestionStep.context.caretReliable).toBe(false)
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue