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
|
|
@ -23,6 +23,7 @@ import { getVoiceCommandService } from './services/VoiceCommandService'
|
|||
import { getInputTelemetryService } from './services/InputTelemetryService'
|
||||
import { getSuggestionService } from './services/SuggestionService'
|
||||
import { initTypoCorrectionService } from './services/TypoCorrectionService'
|
||||
import { getLastNativeInputTick } from './utils/win32-input-activity'
|
||||
import { getPersonalGraphService } from './services/PersonalGraphService'
|
||||
import { getForegroundWindowInfo } from './utils/win32-foreground'
|
||||
import { getSoundEffectService } from './services/SoundEffectService'
|
||||
|
|
@ -220,17 +221,25 @@ async function initInputIntelligence(): Promise<void> {
|
|||
// Windows 에서는 KEYEVENTF_UNICODE 직접 타이핑('keyboard')을 기본으로 써서
|
||||
// 사용자의 클립보드(Win+V)를 오염시키거나 ClipboardSvcGroup 의 OpenClipboard 잠금과 충돌하지 않게 한다.
|
||||
const method = process.platform === 'win32' || configGet('insertMethod') === 'keyboard' ? 'keyboard' : 'clipboard'
|
||||
const baseLength = telemetry.currentTerminalPrefixLength()
|
||||
if (method === 'keyboard') {
|
||||
telemetry.expectProgrammaticKeys(deleteCount + (options?.commitComposition ? 2 : 0))
|
||||
}
|
||||
const result = await getTextInsertService().replaceBeforeCaret(deleteCount, text, method, options)
|
||||
let baseLength = telemetry.currentTerminalPrefixLength()
|
||||
const result = await getTextInsertService().replaceBeforeCaret(deleteCount, text, method, {
|
||||
...options,
|
||||
beforeApply: () => {
|
||||
options?.beforeApply?.()
|
||||
baseLength = telemetry.currentTerminalPrefixLength()
|
||||
if (method === 'keyboard') {
|
||||
telemetry.expectProgrammaticKeys(deleteCount + (options?.commitComposition ? 2 : 0))
|
||||
}
|
||||
}
|
||||
})
|
||||
if (result.success) {
|
||||
telemetry.applyProgrammaticReplacement(deleteCount, text, baseLength)
|
||||
}
|
||||
return result.success
|
||||
},
|
||||
lastKeyAt: () => telemetry.lastKeyAt,
|
||||
inputRevision: () => telemetry.inputRevision,
|
||||
nativeInputTick: getLastNativeInputTick,
|
||||
expectProgrammaticKeys: (count) => telemetry.expectProgrammaticKeys(count),
|
||||
expectProgrammaticInsert: (text) => telemetry.expectProgrammaticInsert(text),
|
||||
foregroundHandle: () => getForegroundWindowInfo()?.hwnd ?? null,
|
||||
|
|
|
|||
|
|
@ -50,10 +50,13 @@ export function registerAdsHandlers(): void {
|
|||
})
|
||||
|
||||
// 6. Claim Rewarded Video Quota
|
||||
ipcMain.handle(IPC_CHANNELS.ADS.CLAIM_REWARD, async (_event, { adId, networkId }: { adId: string; networkId: string }) => {
|
||||
const result = await engine.claimReward(adId, networkId)
|
||||
return ok(result)
|
||||
})
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.ADS.CLAIM_REWARD,
|
||||
async (_event, { adId, networkId, nonce }: { adId: string; networkId: string; nonce?: string }) => {
|
||||
const result = await engine.claimReward(adId, networkId, nonce)
|
||||
return ok(result)
|
||||
},
|
||||
)
|
||||
|
||||
// 7. Get Revenue & Settlement Stats
|
||||
ipcMain.handle(IPC_CHANNELS.ADS.GET_REVENUE_STATS, async (_event, { period }: { period?: string } = {}) => {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
|
|||
import { getAudioCaptureService, calculateRMS, type CaptureLease } from '../services/AudioCaptureService'
|
||||
import { getMainWindow } from '../windows/WindowManager'
|
||||
import { configGet, configSet } from '../services/ConfigService'
|
||||
import type { SetDeviceParams } from '@d3ro/core/types'
|
||||
import type { SetDeviceParams, TestDeviceParams } from '@d3ro/core/types'
|
||||
|
||||
let testTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let testAudioHandler: ((payload: { buffer: Buffer; timestamp: number }) => void) | null = null
|
||||
|
|
@ -23,7 +23,7 @@ let testLease: CaptureLease | null = null
|
|||
*/
|
||||
let testGeneration = 0
|
||||
|
||||
function stopAudioTest(): void {
|
||||
async function stopAudioTest(): Promise<void> {
|
||||
testGeneration += 1
|
||||
const service = getAudioCaptureService()
|
||||
if (testAudioHandler) {
|
||||
|
|
@ -41,7 +41,7 @@ function stopAudioTest(): void {
|
|||
testLastRms = 0
|
||||
const lease = testLease
|
||||
testLease = null
|
||||
lease?.release().catch(() => { /* ignore */ })
|
||||
await lease?.release().catch(() => { /* ignore */ })
|
||||
}
|
||||
|
||||
export function registerAudioHandlers(): void {
|
||||
|
|
@ -69,14 +69,23 @@ export function registerAudioHandlers(): void {
|
|||
}
|
||||
})
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.AUDIO.TEST_DEVICE, async () => {
|
||||
ipcMain.handle(IPC_CHANNELS.AUDIO.TEST_DEVICE, async (_event, params?: TestDeviceParams) => {
|
||||
try {
|
||||
// 이전 테스트가 진행 중이면 정리
|
||||
stopAudioTest()
|
||||
await stopAudioTest()
|
||||
const generation = testGeneration
|
||||
|
||||
const requestedDeviceId =
|
||||
typeof params?.deviceId === 'string' && params.deviceId.trim().length > 0
|
||||
? params.deviceId.trim()
|
||||
: undefined
|
||||
const durationMs =
|
||||
typeof params?.durationMs === 'number' && Number.isFinite(params.durationMs) && params.durationMs > 0
|
||||
? params.durationMs
|
||||
: 5000
|
||||
|
||||
const service = getAudioCaptureService()
|
||||
const lease = await service.acquire()
|
||||
const lease = await service.acquire(requestedDeviceId)
|
||||
if (generation !== testGeneration) {
|
||||
// 기다리는 사이 새 테스트가 시작됐거나 중지됐다 — 이 임대는 바로 놓는다
|
||||
await lease.release().catch(() => { /* ignore */ })
|
||||
|
|
@ -100,18 +109,18 @@ export function registerAudioHandlers(): void {
|
|||
}
|
||||
}, 100)
|
||||
|
||||
// 5초 후 자동 중지
|
||||
// durationMs(기본 5초) 후 자동 중지
|
||||
testTimer = setTimeout(() => {
|
||||
stopAudioTest()
|
||||
void stopAudioTest()
|
||||
const win = getMainWindow()
|
||||
if (win && !win.isDestroyed()) {
|
||||
win.webContents.send(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level: 0, done: true })
|
||||
}
|
||||
}, 5000)
|
||||
}, durationMs)
|
||||
|
||||
return ipcSuccess({ averageLevel: 0, peakLevel: 0, hasAudio: true })
|
||||
} catch (err) {
|
||||
stopAudioTest()
|
||||
await stopAudioTest()
|
||||
return ipcError(
|
||||
ErrorCode.AudioDeviceNotFound,
|
||||
`Audio test failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
|
|
@ -121,7 +130,7 @@ export function registerAudioHandlers(): void {
|
|||
|
||||
// 테스트 수동 중지 (STOP 버튼)
|
||||
ipcMain.handle(IPC_CHANNELS.AUDIO.STOP_TEST, async () => {
|
||||
stopAudioTest()
|
||||
await stopAudioTest()
|
||||
const win = getMainWindow()
|
||||
if (win && !win.isDestroyed()) {
|
||||
win.webContents.send(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level: 0, done: true })
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
|||
import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
|
||||
import fs from 'fs'
|
||||
import { getHistoryService } from '../services/HistoryService'
|
||||
import type { HistoryFilterOptions, HistoryUpdatePatch } from '../services/HistoryService'
|
||||
import { getCloudSyncService } from '../services/CloudSyncService'
|
||||
import { audioMimeType } from '../services/sync/audio-sync'
|
||||
import type {
|
||||
|
|
@ -20,14 +21,35 @@ import type {
|
|||
const MAX_LOCAL_AUDIO_BYTES = 100 * 1024 * 1024
|
||||
|
||||
export function registerHistoryHandlers(): void {
|
||||
ipcMain.handle(IPC_CHANNELS.HISTORY.GET_ALL, async (_event, params: HistoryQueryParams) => {
|
||||
try {
|
||||
return ipcSuccess(getHistoryService().list(params))
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return ipcError(ErrorCode.DBQueryFailed, `Failed to get history: ${message}`)
|
||||
}
|
||||
})
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.HISTORY.GET_ALL,
|
||||
async (_event, params: HistoryQueryParams & HistoryFilterOptions) => {
|
||||
try {
|
||||
return ipcSuccess(getHistoryService().getAll(params))
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return ipcError(ErrorCode.DBQueryFailed, `Failed to get history: ${message}`)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
const updateChannel =
|
||||
(IPC_CHANNELS.HISTORY as Record<string, string>).UPDATE ?? 'history:update'
|
||||
ipcMain.handle(
|
||||
updateChannel,
|
||||
async (_event, params: { id: string } & HistoryUpdatePatch) => {
|
||||
try {
|
||||
const entry = getHistoryService().update(params)
|
||||
if (!entry) {
|
||||
return ipcError(ErrorCode.HistoryNotFound, `History entry not found: ${params.id}`)
|
||||
}
|
||||
return ipcSuccess(entry)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return ipcError(ErrorCode.DBWriteFailed, `Failed to update history entry: ${message}`)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.HISTORY.GET_BY_ID, async (_event, params: HistoryGetByIdParams) => {
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -118,17 +118,17 @@ export function registerMeetingModeHandlers(): void {
|
|||
return ipcSuccess(undefined)
|
||||
} catch (err) {
|
||||
logger.error(`stopRecording 실패: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return ipcError(ErrorCode.MeetingNotRecording, err instanceof Error ? err.message : String(err))
|
||||
return ipcError(err instanceof D3ROError ? err.code : ErrorCode.MeetingNotRecording, err instanceof Error ? err.message : String(err))
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle(ch.ADD_MEMO, async (_event, params: MeetingAddMemoParams) => {
|
||||
ipcMain.handle(ch.ADD_MEMO, async (_event, params: MeetingAddMemoParams & { sessionId?: string; meetingId?: string }) => {
|
||||
try {
|
||||
const memo = await getMeetingModeService().addMemo(params.content)
|
||||
const memo = await getMeetingModeService().addMemo(params.content, params.sessionId ?? params.meetingId)
|
||||
return ipcSuccess(memo)
|
||||
} catch (err) {
|
||||
logger.error(`addMemo 실패: ${err instanceof Error ? err.message : String(err)}`)
|
||||
return ipcError(ErrorCode.MeetingNotRecording, err instanceof Error ? err.message : String(err))
|
||||
return ipcError(err instanceof D3ROError ? err.code : ErrorCode.MeetingNotRecording, err instanceof Error ? err.message : String(err))
|
||||
}
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
// src/main/ipc/memo-handlers.ts
|
||||
// Phase 10.3: 음성 메모 태그 IPC 핸들러
|
||||
|
||||
import { ipcMain } from 'electron'
|
||||
import { ipcMain, dialog } from 'electron'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import { ipcSuccess, ipcError, ErrorCode, D3ROError } from '@d3ro/core/errors'
|
||||
import { getMemoService } from '../services/MemoService'
|
||||
import { buildMemoExportFileName } from '../services/memo/memo-export-file-name'
|
||||
import { normalizeMemoTag } from '@d3ro/core/memo-tag-policy'
|
||||
import type {
|
||||
GetTagsParams,
|
||||
AddTagParams,
|
||||
|
|
@ -64,14 +66,42 @@ export function registerMemoHandlers(): void {
|
|||
}
|
||||
})
|
||||
|
||||
ipcMain.handle(IPC_CHANNELS.MEMO.EXPORT, async (_event, params: ExportMemoParams) => {
|
||||
try {
|
||||
return ipcSuccess(getMemoService().exportMarkdown(params))
|
||||
} catch (err) {
|
||||
if (err instanceof D3ROError && err.code === ErrorCode.MemoExportFailed) {
|
||||
return ipcError(ErrorCode.MemoExportFailed, err.message)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.MEMO.EXPORT,
|
||||
async (
|
||||
_event,
|
||||
params: ExportMemoParams & {
|
||||
savePath?: string
|
||||
interactive?: boolean
|
||||
includeUntagged?: boolean
|
||||
mode?: string
|
||||
isFavorite?: boolean
|
||||
search?: string
|
||||
},
|
||||
) => {
|
||||
try {
|
||||
let savePath = params?.savePath
|
||||
if (params?.interactive && !savePath) {
|
||||
const defaultFileName = buildMemoExportFileName(
|
||||
params.tag ? normalizeMemoTag(params.tag) : undefined,
|
||||
Date.now(),
|
||||
)
|
||||
const dialogRes = await dialog.showSaveDialog({
|
||||
defaultPath: defaultFileName,
|
||||
filters: [{ name: 'Markdown', extensions: ['md'] }],
|
||||
})
|
||||
if (dialogRes.canceled || !dialogRes.filePath) {
|
||||
return ipcSuccess('')
|
||||
}
|
||||
savePath = dialogRes.filePath
|
||||
}
|
||||
return ipcSuccess(getMemoService().exportMarkdown({ ...params, savePath }))
|
||||
} catch (err) {
|
||||
if (err instanceof D3ROError && err.code === ErrorCode.MemoExportFailed) {
|
||||
return ipcError(ErrorCode.MemoExportFailed, err.message)
|
||||
}
|
||||
return ipcError(ErrorCode.MemoExportFailed, 'Failed to export memo')
|
||||
}
|
||||
return ipcError(ErrorCode.MemoExportFailed, 'Failed to export memo')
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
import { ipcMain, dialog } from 'electron'
|
||||
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
|
||||
import { ErrorCode, ipcSuccess, ipcError } from '@d3ro/core/errors'
|
||||
import { D3ROError, ErrorCode, ipcSuccess, ipcError } from '@d3ro/core/errors'
|
||||
import { getRAGService } from '../services/RAGService'
|
||||
import { getLogger } from '../services/LoggerService'
|
||||
import type { RAGQueryParams, RAGRemoveDocumentParams } from '@d3ro/core/types'
|
||||
|
|
@ -18,7 +18,10 @@ export function registerRAGHandlers(): void {
|
|||
let filePath = params?.filePath
|
||||
if (!filePath) {
|
||||
if (isShowingRagDialog) {
|
||||
return ipcError(ErrorCode.RAGDocumentNotFound, 'File selection dialog already active')
|
||||
return ipcError(ErrorCode.RAGDocumentNotFound, 'File selection dialog already active', {
|
||||
cancelled: true,
|
||||
reason: 'dialog_active',
|
||||
})
|
||||
}
|
||||
isShowingRagDialog = true
|
||||
try {
|
||||
|
|
@ -32,7 +35,10 @@ export function registerRAGHandlers(): void {
|
|||
? await dialog.showOpenDialog(mainWindow, dialogOptions)
|
||||
: await dialog.showOpenDialog(dialogOptions)
|
||||
if (result.canceled || result.filePaths.length === 0) {
|
||||
return ipcError(ErrorCode.RAGDocumentNotFound, 'File selection cancelled')
|
||||
return ipcError(ErrorCode.RAGDocumentNotFound, 'File selection cancelled', {
|
||||
cancelled: true,
|
||||
reason: 'dialog_cancelled',
|
||||
})
|
||||
}
|
||||
filePath = result.filePaths[0]
|
||||
} finally {
|
||||
|
|
@ -43,8 +49,10 @@ export function registerRAGHandlers(): void {
|
|||
return ipcSuccess(doc)
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
const code = err instanceof D3ROError ? err.code : ErrorCode.RAGIndexingFailed
|
||||
const details = err instanceof D3ROError ? err.details : undefined
|
||||
logger.error('RAG add document failed:', msg)
|
||||
return ipcError(ErrorCode.RAGIndexingFailed, msg)
|
||||
return ipcError(code, msg, details)
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -54,7 +62,8 @@ export function registerRAGHandlers(): void {
|
|||
return ipcSuccess(undefined)
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
return ipcError(ErrorCode.RAGDocumentNotFound, msg)
|
||||
const code = err instanceof D3ROError ? err.code : ErrorCode.RAGDocumentNotFound
|
||||
return ipcError(code, msg)
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -73,8 +82,9 @@ export function registerRAGHandlers(): void {
|
|||
return ipcSuccess(result)
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
const code = err instanceof D3ROError ? err.code : ErrorCode.RAGQueryFailed
|
||||
logger.error('RAG query failed:', msg)
|
||||
return ipcError(ErrorCode.RAGQueryFailed, msg)
|
||||
return ipcError(code, msg)
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -93,7 +103,9 @@ export function registerRAGHandlers(): void {
|
|||
return ipcSuccess(undefined)
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
return ipcError(ErrorCode.RAGIndexingFailed, msg)
|
||||
const code = err instanceof D3ROError ? err.code : ErrorCode.RAGIndexingFailed
|
||||
const details = err instanceof D3ROError ? err.details : undefined
|
||||
return ipcError(code, msg, details)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,8 +22,9 @@ export function registerSupportHandlers(): void {
|
|||
let sttModel = 'large-v3-turbo'
|
||||
try {
|
||||
const stt = getSTTManager()
|
||||
sttEngine = stt.getProvider()
|
||||
sttModel = stt.getModel()
|
||||
const status = stt.getStatus()
|
||||
sttEngine = status.activeProvider ?? stt.getActiveProvider()
|
||||
sttModel = status.activeModel ?? sttModel
|
||||
} catch {
|
||||
// fallback
|
||||
}
|
||||
|
|
@ -33,7 +34,7 @@ export function registerSupportHandlers(): void {
|
|||
appVersion: app.getVersion(),
|
||||
platform: `${os.platform()} (${os.arch()})`,
|
||||
osRelease: `${os.type()} ${os.release()}`,
|
||||
activeAudioDevice: (configGet('audio.selectedDevice') as string) || 'Default System Microphone',
|
||||
activeAudioDevice: configGet('selectedDeviceId') || 'Default System Microphone',
|
||||
sttEngine,
|
||||
sttModel,
|
||||
gpuAccelerated: true,
|
||||
|
|
@ -45,56 +46,77 @@ export function registerSupportHandlers(): void {
|
|||
})
|
||||
|
||||
// 2. Query AI Customer Support
|
||||
ipcMain.handle(IPC_CHANNELS.SUPPORT.QUERY_AI, async (_event, params: AIAssistQuery) => {
|
||||
const q = params.query.toLowerCase()
|
||||
let answer = '안녕하세요! D3RO Voice 고객지원 AI 어시스턴트입니다. 마이크 설정, Whisper 구동, 정기 결제 및 환불 관련하여 신속히 도와드리겠습니다.'
|
||||
let suggestedAction: string | undefined
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.SUPPORT.QUERY_AI,
|
||||
async (_event, params: AIAssistQuery & { query?: string }) => {
|
||||
const q = (params.question ?? params.query ?? '').toLowerCase()
|
||||
let answer =
|
||||
'안녕하세요! D3RO Voice 고객지원 AI 어시스턴트입니다. 마이크 설정, Whisper 구동, 정기 결제 및 환불 관련하여 신속히 도와드리겠습니다.'
|
||||
let suggestedAction: string | undefined
|
||||
|
||||
if (q.includes('마이크') || q.includes('인식') || q.includes('소리')) {
|
||||
answer = '마이크 음성 인식이 되지 않을 때는 1) Windows [설정 > 개인 정보 및 보안 > 마이크]에서 D3RO Voice 권한이 허용되어 있는지 확인해 주세요. 2) D3RO 설정에서 올바른 입력 장치가 선택되어 있는지 확인해 주세요.'
|
||||
suggestedAction = 'open_audio_settings'
|
||||
} else if (q.includes('환불') || q.includes('취소') || q.includes('결제')) {
|
||||
answer = 'D3RO Voice는 구매 후 7일 이내 & 클라우드 AI 토큰 10% 미만 사용 시 100% 무조건 자동 환불을 보장합니다. [7일 자동 환불] 탭에서 원클릭으로 환불 자격을 조회하실 수 있습니다.'
|
||||
suggestedAction = 'check_refund'
|
||||
} else if (q.includes('cuda') || q.includes('gpu') || q.includes('속도')) {
|
||||
answer = 'NVIDIA GPU CUDA 가속을 사용하려면 최신 NVIDIA 그래픽 드라이버(v535+)와 cuBLAS DLL이 설치되어 있어야 합니다. GPU 가속 시 Whisper 전사 속도가 5배 이상 향상됩니다.'
|
||||
suggestedAction = 'open_stt_settings'
|
||||
}
|
||||
if (q.includes('마이크') || q.includes('인식') || q.includes('소리')) {
|
||||
answer =
|
||||
'마이크 음성 인식이 되지 않을 때는 1) Windows [설정 > 개인 정보 및 보안 > 마이크]에서 D3RO Voice 권한이 허용되어 있는지 확인해 주세요. 2) D3RO 설정에서 올바른 입력 장치가 선택되어 있는지 확인해 주세요.'
|
||||
suggestedAction = 'open_audio_settings'
|
||||
} else if (q.includes('환불') || q.includes('취소') || q.includes('결제')) {
|
||||
answer =
|
||||
'D3RO Voice는 구매 후 7일 이내 & 클라우드 AI 토큰 10% 미만 사용 시 100% 무조건 자동 환불을 보장합니다. [7일 자동 환불] 탭에서 원클릭으로 환불 자격을 조회하실 수 있습니다.'
|
||||
suggestedAction = 'check_refund'
|
||||
} else if (q.includes('cuda') || q.includes('gpu') || q.includes('속도')) {
|
||||
answer =
|
||||
'NVIDIA GPU CUDA 가속을 사용하려면 최신 NVIDIA 그래픽 드라이버(v535+)와 cuBLAS DLL이 설치되어 있어야 합니다. GPU 가속 시 Whisper 전사 속도가 5배 이상 향상됩니다.'
|
||||
suggestedAction = 'open_stt_settings'
|
||||
}
|
||||
|
||||
const response: AIAssistResponse = {
|
||||
answer,
|
||||
confidence: 0.95,
|
||||
suggestedAction,
|
||||
}
|
||||
return ok(response)
|
||||
})
|
||||
const response: AIAssistResponse = {
|
||||
answer,
|
||||
confidence: 0.95,
|
||||
suggestedAction,
|
||||
}
|
||||
return ok(response)
|
||||
},
|
||||
)
|
||||
|
||||
// 3. Create Ticket
|
||||
ipcMain.handle(IPC_CHANNELS.SUPPORT.CREATE_TICKET, async (_event, ticketData: Partial<SupportTicket>) => {
|
||||
const newTicket: SupportTicket = {
|
||||
id: `tkt_${Date.now()}`,
|
||||
userId: 'user_local',
|
||||
userEmail: ticketData.userEmail || 'yunchanpaca@gmail.com',
|
||||
category: ticketData.category || 'general',
|
||||
priority: ticketData.priority || 'normal',
|
||||
status: 'open',
|
||||
subject: ticketData.subject || '고객 지원 문의',
|
||||
description: ticketData.description || '',
|
||||
diagnosticsSnapshot: ticketData.diagnosticsSnapshot,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
responses: [],
|
||||
}
|
||||
return ok(newTicket)
|
||||
})
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.SUPPORT.CREATE_TICKET,
|
||||
async (
|
||||
_event,
|
||||
ticketData: Partial<SupportTicket> & {
|
||||
userEmail?: string
|
||||
diagnosticsSnapshot?: SystemDiagnosticsPayload
|
||||
},
|
||||
) => {
|
||||
const now = Date.now()
|
||||
const newTicket: SupportTicket = {
|
||||
id: `tkt_${now}`,
|
||||
userId: 'user_local',
|
||||
customerEmail:
|
||||
ticketData.customerEmail || ticketData.userEmail || 'yunchanpaca@gmail.com',
|
||||
category: ticketData.category || 'general',
|
||||
priority: ticketData.priority || 'normal',
|
||||
status: 'open',
|
||||
subject: ticketData.subject || '고객 지원 문의',
|
||||
description: ticketData.description || '',
|
||||
diagnostics: ticketData.diagnostics ?? ticketData.diagnosticsSnapshot,
|
||||
slaDueAt: ticketData.slaDueAt ?? now + 24 * 60 * 60 * 1000,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
return ok(newTicket)
|
||||
},
|
||||
)
|
||||
|
||||
// 4. Check Refund
|
||||
ipcMain.handle(IPC_CHANNELS.SUPPORT.CHECK_REFUND, async () => {
|
||||
const result: RefundEligibilityResult = {
|
||||
eligible: true,
|
||||
reason: '결제일로부터 7일 이내이며 클라우드 AI 정제 쿼터를 10% 미만 사용하셨습니다. (100% 전액 환불 가능)',
|
||||
refundMethod: 'Payple 카드 결제 즉시 취소',
|
||||
estimatedRefundKrw: 229000,
|
||||
reason:
|
||||
'결제일로부터 7일 이내이며 클라우드 AI 정제 쿼터를 10% 미만 사용하셨습니다. (100% 전액 환불 가능)',
|
||||
purchaseDate: new Date().toISOString().slice(0, 10),
|
||||
tokensConsumedPercent: 0,
|
||||
refundableAmount: 229000,
|
||||
currency: 'KRW',
|
||||
}
|
||||
return ok(result)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -140,4 +140,20 @@ export function registerVoiceConversationHandlers(credentials: CloudCredentials
|
|||
return ipcError(ErrorCode.ConversationLLMFailed, msg)
|
||||
}
|
||||
})
|
||||
|
||||
const replayChannel =
|
||||
(IPC_CHANNELS.VOICE_CONVERSATION as Record<string, string>).REPLAY_MESSAGE ??
|
||||
'voiceConversation:replayMessage'
|
||||
ipcMain.handle(
|
||||
replayChannel,
|
||||
async (_event, params?: { messageId?: string; text?: string } | string) => {
|
||||
try {
|
||||
await getVoiceConversationService().replayMessage(params)
|
||||
return ipcSuccess(undefined)
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
return ipcError(ErrorCode.ConversationLLMFailed, msg)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -172,6 +172,7 @@ const CONFIG_DEFAULTS: AppConfig = {
|
|||
// 라이브 음성 대화 백엔드 — 'realtime'은 로그인+구독 필요 (OpenAI Realtime WebRTC)
|
||||
conversationBackend: 'local' as const,
|
||||
defaultLLMAction: 'refine',
|
||||
targetLanguage: 'English',
|
||||
keyBindings: createDefaultBindingMap(),
|
||||
hotkeyEnabled: true,
|
||||
insertMethod: 'clipboard',
|
||||
|
|
|
|||
|
|
@ -230,17 +230,103 @@ class DictionaryService {
|
|||
|
||||
/**
|
||||
* 사전 단어 목록을 STT initialPrompt 형태로 반환한다.
|
||||
* 발음(pronunciation)이 등록된 항목은 인식 힌트로 함께 포함한다.
|
||||
*/
|
||||
getPromptHints(limit = 50): string {
|
||||
const db = getDatabase()
|
||||
const words = db
|
||||
.select({ word: dictionary.word })
|
||||
.select({ word: dictionary.word, pronunciation: dictionary.pronunciation })
|
||||
.from(dictionary)
|
||||
.orderBy(desc(dictionary.usageCount))
|
||||
.limit(limit)
|
||||
.all()
|
||||
|
||||
return words.map((w) => w.word).join(', ')
|
||||
return words
|
||||
.map((w) => {
|
||||
const pron = typeof w.pronunciation === 'string' ? w.pronunciation.trim() : ''
|
||||
return pron ? `${w.word} (${pron})` : w.word
|
||||
})
|
||||
.join(', ')
|
||||
}
|
||||
|
||||
getPromptHint(limit = 50): string {
|
||||
return this.getPromptHints(limit)
|
||||
}
|
||||
|
||||
/**
|
||||
* 전사 텍스트에서 사전 단어 또는 발음(pronunciation) 변형을 찾아 표준 단어로 치환하고
|
||||
* 매칭된 사전 항목의 사용 횟수(usageCount)를 증가시킨다.
|
||||
*/
|
||||
applyDictionaryCorrections(text: string): { text: string; matchedIds: string[] } {
|
||||
if (!text || text.trim().length === 0) {
|
||||
return { text, matchedIds: [] }
|
||||
}
|
||||
|
||||
const db = getDatabase()
|
||||
const entries = db
|
||||
.select({
|
||||
id: dictionary.id,
|
||||
word: dictionary.word,
|
||||
pronunciation: dictionary.pronunciation
|
||||
})
|
||||
.from(dictionary)
|
||||
.orderBy(desc(dictionary.usageCount))
|
||||
.all()
|
||||
|
||||
if (!entries || entries.length === 0) {
|
||||
return { text, matchedIds: [] }
|
||||
}
|
||||
|
||||
let currentText = text
|
||||
const matchedIds: string[] = []
|
||||
|
||||
const escapeRegExp = (str: string): string => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
const isAsciiWordChar = (ch: string | undefined): boolean => Boolean(ch && /[A-Za-z0-9]/.test(ch))
|
||||
const buildTokenRegex = (token: string): RegExp => {
|
||||
const escaped = escapeRegExp(token)
|
||||
const prefix = isAsciiWordChar(token[0]) ? '(?<![A-Za-z0-9])' : ''
|
||||
const suffix = isAsciiWordChar(token[token.length - 1]) ? '(?![A-Za-z0-9])' : ''
|
||||
return new RegExp(`${prefix}${escaped}${suffix}`, 'gi')
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
const canonicalWord = entry.word?.trim()
|
||||
if (!canonicalWord) continue
|
||||
|
||||
let matched = false
|
||||
|
||||
const rawPron = typeof entry.pronunciation === 'string' ? entry.pronunciation.trim() : ''
|
||||
if (rawPron.length > 0) {
|
||||
const variants = Array.from(
|
||||
new Set(
|
||||
[rawPron, ...rawPron.split(/[,/;]+/)]
|
||||
.map((v) => v.trim())
|
||||
.filter((v) => v.length > 0 && v.toLowerCase() !== canonicalWord.toLowerCase())
|
||||
)
|
||||
).sort((a, b) => b.length - a.length)
|
||||
|
||||
for (const variant of variants) {
|
||||
const regex = buildTokenRegex(variant)
|
||||
if (regex.test(currentText)) {
|
||||
matched = true
|
||||
currentText = currentText.replace(buildTokenRegex(variant), canonicalWord)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const wordRegex = buildTokenRegex(canonicalWord)
|
||||
if (wordRegex.test(currentText)) {
|
||||
matched = true
|
||||
currentText = currentText.replace(buildTokenRegex(canonicalWord), canonicalWord)
|
||||
}
|
||||
|
||||
if (matched) {
|
||||
matchedIds.push(entry.id)
|
||||
this.incrementUsage(entry.id)
|
||||
}
|
||||
}
|
||||
|
||||
return { text: currentText, matchedIds }
|
||||
}
|
||||
|
||||
async exportDictionary(params: DictionaryExportParams): Promise<string> {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
// src/main/services/HistoryService.ts
|
||||
// SQLite 기반 전사/명령 이력 저장. 설계서 01/03 IHistoryService 구현.
|
||||
|
||||
import { eq, desc, and, or, sql, count } from 'drizzle-orm'
|
||||
import { eq, desc, asc, and, or, sql, count } from 'drizzle-orm'
|
||||
import { getDatabase } from '../db'
|
||||
import { history, stats } from '../db/schema'
|
||||
import { history, stats, memoTags } from '../db/schema'
|
||||
import type { History, NewHistory } from '../db/schema'
|
||||
import { getLogger } from './LoggerService'
|
||||
import { getCloudSyncService } from './CloudSyncService'
|
||||
|
|
@ -11,6 +11,7 @@ import { getInputTelemetryService } from './InputTelemetryService'
|
|||
import { deleteHistoryLocally } from './history-deletion'
|
||||
import { computeStreakDays } from './history-stats'
|
||||
import { containsPattern } from '../db/like-pattern'
|
||||
import { normalizeMemoTag } from '@d3ro/core/memo-tag-policy'
|
||||
import type {
|
||||
HistoryEntry,
|
||||
HistoryQueryParams,
|
||||
|
|
@ -19,6 +20,22 @@ import type {
|
|||
StatsSummary
|
||||
} from '@d3ro/core/types'
|
||||
|
||||
export interface HistoryFilterOptions {
|
||||
mode?: string | null
|
||||
isFavorite?: boolean
|
||||
tag?: string | null
|
||||
search?: string | null
|
||||
query?: string | null
|
||||
beforeCreatedAt?: number | null
|
||||
sortOrder?: 'asc' | 'desc'
|
||||
}
|
||||
|
||||
export interface HistoryUpdatePatch {
|
||||
title?: string | null
|
||||
polishedText?: string | null
|
||||
originalText?: string
|
||||
}
|
||||
|
||||
const logger = getLogger('HistoryService')
|
||||
|
||||
class HistoryService {
|
||||
|
|
@ -70,19 +87,119 @@ class HistoryService {
|
|||
return row ? this._toEntry(row) : null
|
||||
}
|
||||
|
||||
list(params: HistoryQueryParams): HistoryPage {
|
||||
const db = getDatabase()
|
||||
const { page, pageSize } = params
|
||||
/**
|
||||
* SQLite 기반 복합 필터·페이지네이션 조회.
|
||||
* 기존 `(params: HistoryQueryParams)` 객체 호출과 `(limit, offset, search, filters)` 위치 인자 호출을 모두 지원한다.
|
||||
*/
|
||||
getAll(
|
||||
paramsOrLimit?: (HistoryQueryParams & HistoryFilterOptions) | number,
|
||||
offset?: number,
|
||||
search?: string,
|
||||
filters?: HistoryFilterOptions,
|
||||
): HistoryPage {
|
||||
if (typeof paramsOrLimit === 'number' || paramsOrLimit === undefined) {
|
||||
const pageSize = Math.max(1, paramsOrLimit ?? 50)
|
||||
const safeOffset = Math.max(0, offset ?? 0)
|
||||
const page = Math.floor(safeOffset / pageSize)
|
||||
return this._queryWithFilters({
|
||||
page,
|
||||
pageSize,
|
||||
offsetOverride: safeOffset,
|
||||
search: search ?? filters?.search ?? filters?.query ?? undefined,
|
||||
mode: filters?.mode,
|
||||
isFavorite: filters?.isFavorite,
|
||||
tag: filters?.tag,
|
||||
beforeCreatedAt: filters?.beforeCreatedAt,
|
||||
sortOrder: filters?.sortOrder,
|
||||
})
|
||||
}
|
||||
return this.list(paramsOrLimit)
|
||||
}
|
||||
|
||||
const totalResult = db.select({ count: count() }).from(history).get()
|
||||
list(params: HistoryQueryParams & HistoryFilterOptions): HistoryPage {
|
||||
return this._queryWithFilters({
|
||||
page: params.page,
|
||||
pageSize: params.pageSize,
|
||||
sortOrder: params.sortOrder,
|
||||
mode: params.mode,
|
||||
isFavorite: params.isFavorite,
|
||||
tag: params.tag,
|
||||
search: params.search ?? params.query,
|
||||
beforeCreatedAt: params.beforeCreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
private _queryWithFilters(params: {
|
||||
page: number
|
||||
pageSize: number
|
||||
offsetOverride?: number
|
||||
sortOrder?: 'asc' | 'desc'
|
||||
mode?: string | null
|
||||
isFavorite?: boolean
|
||||
tag?: string | null
|
||||
search?: string | null
|
||||
beforeCreatedAt?: number | null
|
||||
}): HistoryPage {
|
||||
const db = getDatabase()
|
||||
const page = Math.max(0, params.page ?? 0)
|
||||
const pageSize = Math.max(1, params.pageSize ?? 50)
|
||||
const offset = params.offsetOverride ?? page * pageSize
|
||||
|
||||
const conditions = []
|
||||
|
||||
const mode = params.mode?.trim()
|
||||
if (mode && mode !== 'all') {
|
||||
if (mode === 'file') {
|
||||
conditions.push(eq(history.mode, 'file-transcription'))
|
||||
} else if (mode === 'commandTranslate') {
|
||||
conditions.push(or(eq(history.mode, 'command'), eq(history.mode, 'translate')))
|
||||
} else {
|
||||
conditions.push(eq(history.mode, mode as History['mode']))
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof params.isFavorite === 'boolean') {
|
||||
conditions.push(eq(history.isFavorite, params.isFavorite))
|
||||
}
|
||||
|
||||
const rawTag = params.tag?.trim()
|
||||
if (rawTag) {
|
||||
const normalizedTag = normalizeMemoTag(rawTag)
|
||||
conditions.push(
|
||||
sql`${history.id} IN (SELECT ${memoTags.historyId} FROM ${memoTags} WHERE ${memoTags.tag} = ${normalizedTag})`,
|
||||
)
|
||||
}
|
||||
|
||||
const rawSearch = params.search?.trim()
|
||||
if (rawSearch) {
|
||||
const pattern = containsPattern(rawSearch)
|
||||
conditions.push(
|
||||
or(
|
||||
pattern.match(history.originalText),
|
||||
pattern.match(history.polishedText),
|
||||
pattern.match(history.title),
|
||||
pattern.match(history.summaryText),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
if (typeof params.beforeCreatedAt === 'number' && Number.isFinite(params.beforeCreatedAt)) {
|
||||
conditions.push(sql`${history.createdAt} < ${params.beforeCreatedAt}`)
|
||||
}
|
||||
|
||||
const whereClause = conditions.length > 0 ? and(...conditions) : undefined
|
||||
const orderClause = params.sortOrder === 'asc' ? asc(history.createdAt) : desc(history.createdAt)
|
||||
|
||||
const totalResult = whereClause
|
||||
? db.select({ count: count() }).from(history).where(whereClause).get()
|
||||
: db.select({ count: count() }).from(history).get()
|
||||
const total = totalResult?.count ?? 0
|
||||
|
||||
const entries = db
|
||||
.select()
|
||||
.from(history)
|
||||
.orderBy(desc(history.createdAt))
|
||||
const entriesQuery = db.select().from(history)
|
||||
const entries = (whereClause ? entriesQuery.where(whereClause) : entriesQuery)
|
||||
.orderBy(orderClause)
|
||||
.limit(pageSize)
|
||||
.offset(page * pageSize)
|
||||
.offset(offset)
|
||||
.all()
|
||||
|
||||
return {
|
||||
|
|
@ -90,7 +207,7 @@ class HistoryService {
|
|||
total,
|
||||
page,
|
||||
pageSize,
|
||||
totalPages: Math.ceil(total / pageSize)
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -165,6 +282,63 @@ class HistoryService {
|
|||
return row ? this._toEntry(row) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 기록 제목(title) 및 본문(polishedText / originalText) 수정.
|
||||
* `(id, patch)` 또는 `({ id, ...patch })` 호출을 모두 지원한다.
|
||||
*/
|
||||
update(
|
||||
idOrParams: string | ({ id: string } & HistoryUpdatePatch),
|
||||
patch?: HistoryUpdatePatch,
|
||||
): HistoryEntry | null {
|
||||
const id = typeof idOrParams === 'string' ? idOrParams : idOrParams.id
|
||||
const resolvedPatch: HistoryUpdatePatch =
|
||||
typeof idOrParams === 'string' ? (patch ?? {}) : idOrParams
|
||||
|
||||
if (!id) return null
|
||||
const db = getDatabase()
|
||||
const existing = db.select().from(history).where(eq(history.id, id)).get()
|
||||
if (!existing) return null
|
||||
|
||||
const nextTitle =
|
||||
resolvedPatch.title !== undefined
|
||||
? resolvedPatch.title === null
|
||||
? null
|
||||
: resolvedPatch.title.trim() || null
|
||||
: existing.title
|
||||
|
||||
const nextPolishedText =
|
||||
resolvedPatch.polishedText !== undefined
|
||||
? resolvedPatch.polishedText
|
||||
: existing.polishedText
|
||||
|
||||
const nextOriginalText =
|
||||
resolvedPatch.originalText !== undefined
|
||||
? resolvedPatch.originalText
|
||||
: existing.originalText
|
||||
|
||||
let nextWordCount = existing.wordCount
|
||||
if (resolvedPatch.polishedText !== undefined || resolvedPatch.originalText !== undefined) {
|
||||
const effectiveText = (nextPolishedText ?? nextOriginalText ?? '').trim()
|
||||
nextWordCount = effectiveText ? effectiveText.split(/\s+/).length : 0
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
db.update(history)
|
||||
.set({
|
||||
title: nextTitle,
|
||||
polishedText: nextPolishedText,
|
||||
originalText: nextOriginalText,
|
||||
wordCount: nextWordCount,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(history.id, id))
|
||||
.run()
|
||||
|
||||
void getCloudSyncService().pushOne('history', id)
|
||||
const updatedRow = db.select().from(history).where(eq(history.id, id)).get()
|
||||
return updatedRow ? this._toEntry(updatedRow) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 누적·오늘·연속 사용일 모두 history 테이블에서 계산한다(완료 세션만). 저장된 카운터는 로컬 생성만
|
||||
* 반영해 동기화·가져오기·삭제와 어긋났고, streak은 쓰는 곳이 없어 늘 0이었다.
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ import { acquireGlobalInputHook } from './global-input-hook'
|
|||
import { uiohookCodeToVk } from './KeyBindingService'
|
||||
import { getUiaContextService } from './UiaContextService'
|
||||
import { getForegroundWindowInfo, isForegroundKoreanIme } from '../utils/win32-foreground'
|
||||
import { getLastNativeInputTick } from '../utils/win32-input-activity'
|
||||
import { getPersonalGraphService } from './PersonalGraphService'
|
||||
import { getPersonalNgramIndex } from './suggestion/PersonalNgramIndex'
|
||||
|
||||
|
|
@ -104,6 +105,10 @@ export interface TypingContext {
|
|||
windowHandle?: number | null
|
||||
idleMs: number
|
||||
capturedAt: number
|
||||
/** 스냅샷을 읽는 동안 입력/포커스가 바뀌지 않았는지 확인한 단조 증가 번호. */
|
||||
inputRevision?: number
|
||||
/** Windows 세션의 마지막 입력 tick. null이면 네이티브 입력 상태 확인 실패, 다른 OS는 생략. */
|
||||
nativeInputTick?: number | null
|
||||
/** 포커스가 바뀐 뒤 이 필드에서 실제로 편집이 있었는가 (마우스로 들어오기만 한 경우 false) */
|
||||
editedSinceFocus: boolean
|
||||
/** 최근에 실제로 타이핑했는가 (recentTypingWindowMs 이내) */
|
||||
|
|
@ -193,6 +198,10 @@ class InputTelemetryService extends EventEmitter {
|
|||
private _sampleTimer: NodeJS.Timeout | null = null
|
||||
/** 주기 샘플 스냅샷 진행 중 (중복 방지) */
|
||||
private _sampling = false
|
||||
/** 모든 스냅샷 트리거를 합쳐 같은 UIA 응답을 중복 적용하지 않는다. */
|
||||
private _snapshotRequest: Promise<TypingContext | null> | null = null
|
||||
/** 같은 밀리초에 들어온 키·클릭도 서로 다른 편집으로 구분한다. */
|
||||
private _inputRevision = 0
|
||||
/** 제안 오버레이가 표시 중일 때만 포커스 이탈/선택을 계속 확인한다. */
|
||||
private _suggestionPresentationActive = false
|
||||
private _presentationValidationTimer: NodeJS.Timeout | null = null
|
||||
|
|
@ -227,6 +236,8 @@ class InputTelemetryService extends EventEmitter {
|
|||
private _typedIntoFocus = false
|
||||
/** 현재 포커스/클릭 이후 실제로 글자 키를 쳤는가 (첫 스냅샷 전 빠른 입력 보존) */
|
||||
private _typedInCurrentFocus = false
|
||||
/** Chromium/Electron 등 UIA GetActiveComposition 미지원 앱을 위한 키스트로크 기반 한글 조합 추정 */
|
||||
private _imeComposing = false
|
||||
private _lastTypedHwnd: number | null = null
|
||||
/** 직전 스냅샷이 편집 가능한 칸이었는가 / 어느 창이었는가 (포커스 깜빡임 판정) */
|
||||
private _prevSnapshotEditable = false
|
||||
|
|
@ -314,6 +325,10 @@ class InputTelemetryService extends EventEmitter {
|
|||
return this._lastKeyAt
|
||||
}
|
||||
|
||||
get inputRevision(): number {
|
||||
return this._inputRevision
|
||||
}
|
||||
|
||||
/**
|
||||
* 곧 프로그램이 키 count 개를 보낸다 — 그 키들은 입력 통계에 넣지 않는다.
|
||||
* 남은 예고는 ttlMs 뒤 무효다(보내지 못한 키가 사용자 키를 삼키지 않게).
|
||||
|
|
@ -321,6 +336,7 @@ class InputTelemetryService extends EventEmitter {
|
|||
expectProgrammaticKeys(count: number, ttlMs = 3000): void {
|
||||
this._programmaticKeys = Math.max(0, count)
|
||||
this._programmaticKeysUntil = Date.now() + ttlMs
|
||||
if (count > 0) this._imeComposing = false
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -334,6 +350,8 @@ class InputTelemetryService extends EventEmitter {
|
|||
* 프로그램(오타 교정)이 커서 앞 deleteCount 글자를 지우고 insertText 를 넣었을 때 터미널 키 버퍼도 동기화한다.
|
||||
*/
|
||||
applyProgrammaticReplacement(deleteCount: number, insertText: string, baseLength?: number): void {
|
||||
this._inputRevision += 1
|
||||
this._imeComposing = false
|
||||
this._terminalTracker.applyReplacement(deleteCount, insertText, baseLength)
|
||||
}
|
||||
|
||||
|
|
@ -372,6 +390,7 @@ class InputTelemetryService extends EventEmitter {
|
|||
|
||||
this._releaseHook = acquireGlobalInputHook()
|
||||
this._running = true
|
||||
this._inputRevision += 1
|
||||
this._flushTimer = setInterval(
|
||||
() => this._flush(),
|
||||
INPUT_TELEMETRY_DEFAULTS.flushIntervalMs
|
||||
|
|
@ -408,6 +427,7 @@ class InputTelemetryService extends EventEmitter {
|
|||
}
|
||||
|
||||
stop(): void {
|
||||
this._inputRevision += 1
|
||||
// 입력 관찰을 끄면 메모리에 잡아 둔 "조금 전에 쓴 글" 도 버린다.
|
||||
this._recentWrites.clear()
|
||||
if (!this._running) {
|
||||
|
|
@ -511,6 +531,8 @@ class InputTelemetryService extends EventEmitter {
|
|||
// ── 이벤트 수집 ────────────────────────────────────────
|
||||
|
||||
private _handleKeyDown(event: UiohookKeyboardEvent): void {
|
||||
// 합성 키도 화면을 바꾼다. 통계 제외 여부와 무관하게 이전 UIA 응답은 무효다.
|
||||
this._inputRevision += 1
|
||||
this._syncModifiers(event)
|
||||
// Win32 SendInput(KEYEVENTF_UNICODE) 가 보내는 합성 유니코드 키는 uiohook 에서 keycode=0 으로 들어온다.
|
||||
// 사용자 키스트로크나 IME 입력으로 처리하면 버퍼와 타이머를 교란하므로 즉시 무시한다.
|
||||
|
|
@ -563,6 +585,13 @@ class InputTelemetryService extends EventEmitter {
|
|||
} else if (keyClass === 'shortcut') {
|
||||
this._typedInCurrentFocus = false
|
||||
}
|
||||
if (event.keycode === 112 || vk === 0x15) {
|
||||
this._imeComposing = false
|
||||
} else if (keyClass === 'ime' || keyClass === 'letter') {
|
||||
this._imeComposing = true
|
||||
} else if (keyClass !== 'modifier') {
|
||||
this._imeComposing = false
|
||||
}
|
||||
// 진단: 키 값이 아니라 종류·수정자만 남긴다 (typed 판정이 왜 틀리는지 로그로 보이게)
|
||||
this._lastKeyDiag = `${keyClass}${vk === null ? `?${event.keycode}` : ''}${this._modifiers.ctrl ? '+C' : ''}${this._modifiers.alt ? '+A' : ''}${this._modifiers.meta ? '+M' : ''}`
|
||||
|
||||
|
|
@ -594,6 +623,7 @@ class InputTelemetryService extends EventEmitter {
|
|||
}
|
||||
|
||||
private _handleMouseDown(event: UiohookMouseEvent): void {
|
||||
this._inputRevision += 1
|
||||
this._registerInput(false)
|
||||
|
||||
const now = Date.now()
|
||||
|
|
@ -615,10 +645,12 @@ class InputTelemetryService extends EventEmitter {
|
|||
// 클릭은 다른 칸으로 옮겨 갔을 수 있다 — 다음 스냅샷의 텍스트를 새 기준으로 삼는다.
|
||||
this._rebaseFocusText = true
|
||||
this._typedInCurrentFocus = false
|
||||
this._imeComposing = false
|
||||
this._terminalTracker.onPointerOrFocusChange(this._foreground.hwnd)
|
||||
}
|
||||
|
||||
private _handleMouseUp(event: UiohookMouseEvent): void {
|
||||
this._inputRevision += 1
|
||||
this._lastMouse = { x: event.x, y: event.y }
|
||||
if (!this._suggestionPresentationActive) return
|
||||
if (this._presentationValidationTimer) clearTimeout(this._presentationValidationTimer)
|
||||
|
|
@ -643,6 +675,7 @@ class InputTelemetryService extends EventEmitter {
|
|||
}
|
||||
|
||||
private _handleWheel(event: UiohookWheelEvent): void {
|
||||
this._inputRevision += 1
|
||||
const bucket = this._bucket()
|
||||
bucket.scrollTicks += Math.max(1, Math.abs(Number(event.rotation) || 1))
|
||||
this._registerInput(false)
|
||||
|
|
@ -698,7 +731,9 @@ class InputTelemetryService extends EventEmitter {
|
|||
const info = getForegroundWindowInfo()
|
||||
if (info) {
|
||||
if (info.hwnd !== this._foreground.hwnd) {
|
||||
this._inputRevision += 1
|
||||
this._typedInCurrentFocus = false
|
||||
this._imeComposing = false
|
||||
}
|
||||
this._foreground = {
|
||||
appName: info.appName || null,
|
||||
|
|
@ -733,9 +768,13 @@ class InputTelemetryService extends EventEmitter {
|
|||
*/
|
||||
private async _sampleWhileTyping(): Promise<void> {
|
||||
if (!this._running || this._sampling) return
|
||||
const now = Date.now()
|
||||
if (!this._suggestionPresentationActive && this._lastKeyAt > 0 && now - this._lastKeyAt < 350) {
|
||||
return
|
||||
}
|
||||
const hasRecentKeyboardInput =
|
||||
this._lastKeyAt > 0 &&
|
||||
Date.now() - this._lastKeyAt <= INPUT_TELEMETRY_DEFAULTS.sampleActiveWindowMs
|
||||
now - this._lastKeyAt <= INPUT_TELEMETRY_DEFAULTS.sampleActiveWindowMs
|
||||
if (!hasRecentKeyboardInput && !this._suggestionPresentationActive) return
|
||||
|
||||
this._sampling = true
|
||||
|
|
@ -799,9 +838,38 @@ class InputTelemetryService extends EventEmitter {
|
|||
*/
|
||||
private async _captureTextSnapshot(): Promise<TypingContext | null> {
|
||||
if (!this._running) return null
|
||||
if (this._snapshotRequest) return this._snapshotRequest
|
||||
|
||||
const request = this._readTextSnapshot()
|
||||
this._snapshotRequest = request
|
||||
try {
|
||||
return await request
|
||||
} finally {
|
||||
if (this._snapshotRequest === request) this._snapshotRequest = null
|
||||
}
|
||||
}
|
||||
|
||||
private async _readTextSnapshot(): Promise<TypingContext | null> {
|
||||
this._sampleForeground(Date.now(), true)
|
||||
const inputRevision = this._inputRevision
|
||||
const foregroundHwnd = this._foreground.hwnd
|
||||
const nativeInputTick = getLastNativeInputTick()
|
||||
|
||||
const uia = getUiaContextService()
|
||||
const snapshot = withoutPlaceholderText(await uia.getSnapshot())
|
||||
if (!this._running) return null
|
||||
this._sampleForeground(Date.now(), true)
|
||||
// CPU 부하/모델 로딩 중 UIA 응답이 늦어질 수 있다. 예전 텍스트를 최신 키 시각과
|
||||
// 섞으면 자동 교정이 방금 친 글자를 지운다. 기준선·학습·제안 모두 갱신 전에 버린다.
|
||||
if (
|
||||
inputRevision !== this._inputRevision ||
|
||||
foregroundHwnd !== this._foreground.hwnd ||
|
||||
nativeInputTick !== getLastNativeInputTick() ||
|
||||
(snapshot.available && snapshot.capturedAt < Math.max(this._lastKeyAt, this._lastClickAt))
|
||||
) {
|
||||
logger.debug('입력 스냅샷 버림: UIA 조회 중 입력 또는 포커스 변경')
|
||||
return null
|
||||
}
|
||||
const now = Date.now()
|
||||
// 유휴 시간은 키보드 기준이다 (마우스 이동/클릭으로는 제안하지 않는다).
|
||||
const idleMs = this._lastKeyAt > 0 ? now - this._lastKeyAt : Number.MAX_SAFE_INTEGER
|
||||
|
|
@ -824,6 +892,8 @@ class InputTelemetryService extends EventEmitter {
|
|||
windowHandle: this._foreground.hwnd,
|
||||
idleMs,
|
||||
capturedAt: snapshot.capturedAt,
|
||||
inputRevision,
|
||||
nativeInputTick: process.platform === 'win32' ? nativeInputTick : undefined,
|
||||
editedSinceFocus: false,
|
||||
typedRecently
|
||||
}
|
||||
|
|
@ -920,10 +990,21 @@ class InputTelemetryService extends EventEmitter {
|
|||
if (clearedByEnter) {
|
||||
this._lastTypedAt = 0
|
||||
this._typedInCurrentFocus = false
|
||||
this._imeComposing = false
|
||||
context.typedRecently = false
|
||||
}
|
||||
}
|
||||
context.editedSinceFocus = textForFocus !== this._textAtFocus || this._typedIntoFocus
|
||||
if (
|
||||
!context.isComposing &&
|
||||
this._imeComposing &&
|
||||
context.editedSinceFocus &&
|
||||
/[가-힣ㄱ-ㅎㅏ-ㅣ]$/u.test(context.prefix)
|
||||
) {
|
||||
context.isComposing = true
|
||||
} else if (context.isComposing && !/[가-힣ㄱ-ㅎㅏ-ㅣ]$/u.test(context.prefix)) {
|
||||
context.isComposing = false
|
||||
}
|
||||
|
||||
// 보내면 비워지는 칸(채팅)의 직전 내용을 "이 창에서 조금 전에 쓴 글" 로 잠시 기억한다.
|
||||
// 비밀번호·편집 불가 칸과 터미널(명령 기록)은 보지 않는다. 조합 중인 칸도 본다 — 한글은 보내기 직전
|
||||
|
|
@ -942,7 +1023,7 @@ class InputTelemetryService extends EventEmitter {
|
|||
// 단, 방금 프로그램(오타 교정·제안 수락)이 커서 앞 텍스트를 바꾼 경우에는 끝 편집으로 본다.
|
||||
this._pruneExpectedInserts(now)
|
||||
const programmaticEdit =
|
||||
this._programmaticKeyBudget > 0 ||
|
||||
this._programmaticKeys > 0 ||
|
||||
this._expectedInserts.some((entry) => textForFocus.includes(entry.text))
|
||||
if (this._editProbe === null || this._editProbe.key !== focusKey || programmaticEdit) {
|
||||
this._lastEditAtEnd = true
|
||||
|
|
|
|||
|
|
@ -555,10 +555,11 @@ class KeyBindingService extends EventEmitter {
|
|||
this._altGr.reset()
|
||||
forgetHeldModifiers()
|
||||
}
|
||||
const events = ['lock-screen', 'suspend'] as const
|
||||
for (const event of events) powerMonitor.on(event, releaseHeld)
|
||||
powerMonitor.on('lock-screen', releaseHeld)
|
||||
powerMonitor.on('suspend', releaseHeld)
|
||||
this._offSessionLock = () => {
|
||||
for (const event of events) powerMonitor.removeListener(event, releaseHeld)
|
||||
powerMonitor.removeListener('lock-screen', releaseHeld)
|
||||
powerMonitor.removeListener('suspend', releaseHeld)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -117,6 +117,9 @@ export class LicenseService extends EventEmitter {
|
|||
private _keyVerifiedAt: number | null = null
|
||||
private _cloudTier: LicenseTier = 'free'
|
||||
private _cloudVerifiedAt: number | null = null
|
||||
private _rewardBonusDate = ''
|
||||
private _rewardBonusAmount = 0
|
||||
private _claimedRewardNonces = new Set<string>()
|
||||
|
||||
constructor(
|
||||
private readonly _store: LicenseStore = new FileLicenseStore(),
|
||||
|
|
@ -180,6 +183,27 @@ export class LicenseService extends EventEmitter {
|
|||
this._persistSummary()
|
||||
}
|
||||
|
||||
// 3. 보상형 광고 보너스 쿼터 & 리플레이 방지 논스 복원
|
||||
const today = getTodayDate()
|
||||
const storedBonusDate = this._store.read<string>('licenseRewardBonusDate')
|
||||
const storedBonusAmount = this._store.read<number>('licenseRewardBonusAmount')
|
||||
const storedNonces = this._store.read<string[]>('licenseRewardClaimedNonces')
|
||||
if (
|
||||
storedBonusDate === today &&
|
||||
typeof storedBonusAmount === 'number' &&
|
||||
Number.isFinite(storedBonusAmount) &&
|
||||
storedBonusAmount > 0
|
||||
) {
|
||||
this._rewardBonusDate = today
|
||||
this._rewardBonusAmount = Math.floor(storedBonusAmount)
|
||||
} else {
|
||||
this._rewardBonusDate = today
|
||||
this._rewardBonusAmount = 0
|
||||
}
|
||||
this._claimedRewardNonces = new Set(
|
||||
Array.isArray(storedNonces) ? storedNonces.filter((n): n is string => typeof n === 'string') : [],
|
||||
)
|
||||
|
||||
logger.info(
|
||||
`LicenseService initialized: tier=${this.tier}, key=${this._key?.tier ?? 'none'}, cloud=${this._cloudTier}, trial=${this._key?.isTrial ?? false}, machineId=${this._machineId.substring(0, 8)}...`,
|
||||
)
|
||||
|
|
@ -338,10 +362,10 @@ export class LicenseService extends EventEmitter {
|
|||
|
||||
/** 일일 사용량 조회 */
|
||||
getUsage(feature: Feature): UsageQuota {
|
||||
const limit = quotaLimitFor(this.tier, feature)
|
||||
const baseLimit = quotaLimitFor(this.tier, feature)
|
||||
|
||||
// 쿼터 없는 기능 (무제한)
|
||||
if (limit === undefined) {
|
||||
if (baseLimit === undefined) {
|
||||
return {
|
||||
feature,
|
||||
used: 0,
|
||||
|
|
@ -351,6 +375,8 @@ export class LicenseService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
const bonus = feature === Feature.PREMIUM_LLM ? this.getRewardBonusQuota() : 0
|
||||
const limit = baseLimit + bonus
|
||||
const used = this._usage.getCount(getTodayDate(), feature)
|
||||
|
||||
return {
|
||||
|
|
@ -362,6 +388,104 @@ export class LicenseService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/** 당일 보상형 광고 보너스 쿼터 조회 */
|
||||
getRewardBonusQuota(): number {
|
||||
const today = getTodayDate()
|
||||
if (this._rewardBonusDate !== today) {
|
||||
const storedBonusDate = this._store.read<string>('licenseRewardBonusDate')
|
||||
const storedBonusAmount = this._store.read<number>('licenseRewardBonusAmount')
|
||||
if (
|
||||
storedBonusDate === today &&
|
||||
typeof storedBonusAmount === 'number' &&
|
||||
Number.isFinite(storedBonusAmount) &&
|
||||
storedBonusAmount > 0
|
||||
) {
|
||||
this._rewardBonusDate = today
|
||||
this._rewardBonusAmount = Math.floor(storedBonusAmount)
|
||||
} else {
|
||||
this._rewardBonusDate = today
|
||||
this._rewardBonusAmount = 0
|
||||
}
|
||||
}
|
||||
return this._rewardBonusAmount
|
||||
}
|
||||
|
||||
/**
|
||||
* 보상형 광고 완료 검증 후 보너스 쿼터 부여 (리플레이/논스 중복 차감 방지).
|
||||
*/
|
||||
grantRewardQuota(
|
||||
amount: number = 50,
|
||||
nonce?: string,
|
||||
): {
|
||||
granted: boolean
|
||||
tokensAdded: number
|
||||
bonusQuota: number
|
||||
newTotalQuota: number
|
||||
rewardId: string
|
||||
} {
|
||||
const currentQuota = this.getUsage(Feature.PREMIUM_LLM)
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
return {
|
||||
granted: false,
|
||||
tokensAdded: 0,
|
||||
bonusQuota: this.getRewardBonusQuota(),
|
||||
newTotalQuota: currentQuota.limit,
|
||||
rewardId: '',
|
||||
}
|
||||
}
|
||||
|
||||
const trimmedNonce = nonce?.trim()
|
||||
if (trimmedNonce) {
|
||||
const storedNonces = this._store.read<string[]>('licenseRewardClaimedNonces')
|
||||
if (Array.isArray(storedNonces)) {
|
||||
for (const n of storedNonces) {
|
||||
if (typeof n === 'string') this._claimedRewardNonces.add(n)
|
||||
}
|
||||
}
|
||||
if (this._claimedRewardNonces.has(trimmedNonce)) {
|
||||
return {
|
||||
granted: false,
|
||||
tokensAdded: 0,
|
||||
bonusQuota: this.getRewardBonusQuota(),
|
||||
newTotalQuota: currentQuota.limit,
|
||||
rewardId: '',
|
||||
}
|
||||
}
|
||||
this._claimedRewardNonces.add(trimmedNonce)
|
||||
if (this._claimedRewardNonces.size > 512) {
|
||||
const oldest = this._claimedRewardNonces.values().next().value
|
||||
if (oldest !== undefined) {
|
||||
this._claimedRewardNonces.delete(oldest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const today = getTodayDate()
|
||||
const normalizedAmount = Math.floor(amount)
|
||||
const currentBonus = this.getRewardBonusQuota()
|
||||
this._rewardBonusDate = today
|
||||
this._rewardBonusAmount = currentBonus + normalizedAmount
|
||||
this._store.writeAll({
|
||||
licenseRewardBonusDate: this._rewardBonusDate,
|
||||
licenseRewardBonusAmount: this._rewardBonusAmount,
|
||||
licenseRewardClaimedNonces: Array.from(this._claimedRewardNonces),
|
||||
})
|
||||
|
||||
const updatedQuota = this.getUsage(Feature.PREMIUM_LLM)
|
||||
const rewardId = `reward_${Date.now()}_${trimmedNonce ?? Math.random().toString(36).slice(2, 8)}`
|
||||
this.emit('quota-updated', updatedQuota)
|
||||
logger.info(
|
||||
`Reward quota granted: +${normalizedAmount} tokens (bonus=${this._rewardBonusAmount}, newLimit=${updatedQuota.limit})`,
|
||||
)
|
||||
return {
|
||||
granted: true,
|
||||
tokensAdded: normalizedAmount,
|
||||
bonusQuota: this._rewardBonusAmount,
|
||||
newTotalQuota: updatedQuota.limit,
|
||||
rewardId,
|
||||
}
|
||||
}
|
||||
|
||||
/** 전체 쿼터 기능 사용량 조회 */
|
||||
getAllUsage(): UsageQuota[] {
|
||||
const quotaFeatures = [Feature.DICTATION, Feature.LLM_PROCESS]
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import type { LLMStatus, LLMModel, LLMAction, LLMConnectionState } from '@d3ro/c
|
|||
import { resolveSystemPrompt } from './llm-prompts'
|
||||
import { getBundledOllamaPath } from '../utils/paths'
|
||||
import { normalizeLoopbackUrl } from '../utils/loopback'
|
||||
import { localInferenceCpuOptions } from '../utils/inference-cpu-budget'
|
||||
import { readNdjsonLines } from '../utils/ndjson-reader'
|
||||
import {
|
||||
LOCAL_LLM_KEEP_ALIVE,
|
||||
|
|
@ -449,6 +450,7 @@ class LocalLLMService extends EventEmitter {
|
|||
// gemma4/llama3.2 등 non-reasoning 모델에서는 무시됨.
|
||||
think: false,
|
||||
options: {
|
||||
...localInferenceCpuOptions(serverUrl),
|
||||
temperature: options?.temperature ?? 0.3,
|
||||
num_predict: maxTokens
|
||||
}
|
||||
|
|
@ -514,6 +516,7 @@ class LocalLLMService extends EventEmitter {
|
|||
keep_alive: options?.keepAlive ?? LOCAL_LLM_KEEP_ALIVE,
|
||||
think: false,
|
||||
options: {
|
||||
...localInferenceCpuOptions(serverUrl),
|
||||
temperature: options?.temperature ?? 0.3,
|
||||
num_predict: maxTokens,
|
||||
...(options?.stop && options.stop.length > 0 ? { stop: options.stop } : {})
|
||||
|
|
@ -889,6 +892,7 @@ class LocalLLMService extends EventEmitter {
|
|||
keep_alive: options?.keepAlive ?? LOCAL_LLM_KEEP_ALIVE,
|
||||
think: false,
|
||||
options: {
|
||||
...localInferenceCpuOptions(serverUrl),
|
||||
temperature: options?.temperature ?? 0.7,
|
||||
num_predict: maxTokens,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -379,28 +379,82 @@ class MeetingModeService extends EventEmitter {
|
|||
|
||||
// ── 메모 추가 ──
|
||||
|
||||
async addMemo(content: string): Promise<MeetingMemo> {
|
||||
const session = this._current
|
||||
if (this._state !== 'recording' || !session) {
|
||||
throw new D3ROError(ErrorCode.MeetingNotRecording, '녹음 중이 아닙니다')
|
||||
async addMemo(content: string, meetingId?: string): Promise<MeetingMemo> {
|
||||
const trimmed = content.trim()
|
||||
if (!trimmed) {
|
||||
throw new D3ROError(ErrorCode.MeetingNotRecording, '메모 내용이 비어 있습니다')
|
||||
}
|
||||
const memo = session.addMemo(crypto.randomUUID(), content)
|
||||
if (!memo) {
|
||||
|
||||
const session = this._current
|
||||
if (this._state === 'recording' && session && (!meetingId || meetingId === session.id)) {
|
||||
const memo = session.addMemo(crypto.randomUUID(), content)
|
||||
if (!memo) {
|
||||
throw new D3ROError(ErrorCode.MeetingNotRecording, '녹음 중이 아닙니다')
|
||||
}
|
||||
|
||||
// DB 저장
|
||||
const db = getDatabase()
|
||||
db.insert(meetingMemos).values({
|
||||
id: memo.id,
|
||||
sessionId: memo.sessionId,
|
||||
content: memo.content,
|
||||
timestampMs: memo.timestampMs,
|
||||
createdAt: memo.createdAt,
|
||||
}).run()
|
||||
|
||||
this.emit('memo-added', memo)
|
||||
logger.debug(`메모 추가: [${formatTime(memo.timestampMs)}] ${content}`)
|
||||
|
||||
// Phase 3.3: 자동 push (fire-and-forget)
|
||||
getCloudSyncService().pushOne('meeting_memos', memo.id)
|
||||
|
||||
return memo
|
||||
}
|
||||
|
||||
// 종료된 회의(또는 특정 meetingId)에 사후 메모 추가
|
||||
const targetSessionId = meetingId?.trim() || this._finalizedSessionId
|
||||
if (!targetSessionId) {
|
||||
throw new D3ROError(ErrorCode.MeetingNotRecording, '녹음 중이 아닙니다')
|
||||
}
|
||||
|
||||
// DB 저장
|
||||
const db = getDatabase()
|
||||
db.insert(meetingMemos).values({
|
||||
id: memo.id,
|
||||
sessionId: memo.sessionId,
|
||||
content: memo.content,
|
||||
timestampMs: memo.timestampMs,
|
||||
createdAt: memo.createdAt,
|
||||
}).run()
|
||||
const sessionRow = db
|
||||
.select()
|
||||
.from(meetingSessions)
|
||||
.where(eq(meetingSessions.id, targetSessionId))
|
||||
.get()
|
||||
if (!sessionRow) {
|
||||
throw new D3ROError(
|
||||
meetingId ? ErrorCode.MeetingSessionNotFound : ErrorCode.MeetingNotRecording,
|
||||
meetingId ? `회의 세션을 찾을 수 없습니다: ${targetSessionId}` : '녹음 중이 아닙니다',
|
||||
)
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const timestampMs =
|
||||
sessionRow.durationMs ??
|
||||
(sessionRow.endedAt ? Math.max(0, sessionRow.endedAt - sessionRow.startedAt) : 0)
|
||||
|
||||
const memo: MeetingMemo = {
|
||||
id: crypto.randomUUID(),
|
||||
sessionId: targetSessionId,
|
||||
content: trimmed,
|
||||
timestampMs,
|
||||
createdAt: now,
|
||||
}
|
||||
|
||||
db.insert(meetingMemos)
|
||||
.values({
|
||||
id: memo.id,
|
||||
sessionId: memo.sessionId,
|
||||
content: memo.content,
|
||||
timestampMs: memo.timestampMs,
|
||||
createdAt: memo.createdAt,
|
||||
})
|
||||
.run()
|
||||
|
||||
this.emit('memo-added', memo)
|
||||
logger.debug(`메모 추가: [${formatTime(memo.timestampMs)}] ${content}`)
|
||||
logger.debug(`사후 회의 메모 추가: sessionId=${targetSessionId}, [${formatTime(memo.timestampMs)}] ${trimmed}`)
|
||||
|
||||
// Phase 3.3: 자동 push (fire-and-forget)
|
||||
getCloudSyncService().pushOne('meeting_memos', memo.id)
|
||||
|
|
|
|||
|
|
@ -24,19 +24,51 @@ const logger = getLogger('MeetingSummaryService')
|
|||
|
||||
let isShowingSummarySaveDialog = false
|
||||
|
||||
const MEETING_SUMMARY_PROMPT = `다음은 회의 전사록입니다. 아래 형식으로 정리해주세요:
|
||||
export interface TranscriptCitation {
|
||||
label: string
|
||||
timestampMs: number
|
||||
}
|
||||
|
||||
export function parseCitationTimestampMs(token: string): number | null {
|
||||
const match = /^\[?(?:(\d{1,2}):)?(\d{1,3}):(\d{2})\]?$/.exec(token.trim())
|
||||
if (!match) return null
|
||||
const hours = match[1] ? parseInt(match[1], 10) : 0
|
||||
const minutes = parseInt(match[2], 10)
|
||||
const seconds = parseInt(match[3], 10)
|
||||
if (seconds >= 60) return null
|
||||
return (hours * 3600 + minutes * 60 + seconds) * 1000
|
||||
}
|
||||
|
||||
export function extractTranscriptCitations(text: string): TranscriptCitation[] {
|
||||
const regex = /\[(?:\d{1,2}:)?\d{1,3}:\d{2}\]/g
|
||||
const seen = new Set<string>()
|
||||
const results: TranscriptCitation[] = []
|
||||
let match: RegExpExecArray | null
|
||||
while ((match = regex.exec(text)) !== null) {
|
||||
const label = match[0]
|
||||
const ts = parseCitationTimestampMs(label)
|
||||
if (ts !== null && !seen.has(label)) {
|
||||
seen.add(label)
|
||||
results.push({ label, timestampMs: ts })
|
||||
}
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
export const MEETING_SUMMARY_PROMPT = `다음은 회의 전사록입니다. 아래 형식으로 정리해주세요:
|
||||
|
||||
## 요약
|
||||
(3줄 이내 핵심 요약)
|
||||
(3줄 이내 핵심 요약. 전사록에 [MM:SS] 시각이 있으면 관련 문장 끝에 [MM:SS] 인용 표기를 남기세요)
|
||||
|
||||
## 핵심 결정사항
|
||||
- (결정 1)
|
||||
- (결정 2)
|
||||
- (결정 1) [MM:SS]
|
||||
- (결정 2) [MM:SS]
|
||||
|
||||
## 할 일 목록
|
||||
- [ ] (할 일 1)
|
||||
- [ ] (할 일 2)
|
||||
- [ ] (할 일 1) [MM:SS]
|
||||
- [ ] (할 일 2) [MM:SS]
|
||||
|
||||
전사록에 [MM:SS] 타임스탬프가 포함되어 있다면 각 핵심 요약·결정사항·할 일 항목 끝에 근거가 되는 [MM:SS] 시각 인용을 함께 표기하세요.
|
||||
전사록 외의 내용을 추가하지 마세요. 전사록이 비어 있거나 내용이 부족하면 "요약할 내용이 충분하지 않습니다"라고만 출력하세요.`
|
||||
|
||||
class MeetingSummaryService extends EventEmitter {
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
// src/main/services/MemoService.ts
|
||||
// Phase 10.3: 음성 메모 태그 시스템. 히스토리 항목에 태그를 부착하고 태그별 검색/내보내기를 지원한다.
|
||||
|
||||
import { eq, and, desc, count, sql } from 'drizzle-orm'
|
||||
import { eq, and, or, desc, count, sql } from 'drizzle-orm'
|
||||
import { app } from 'electron'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { getDatabase } from '../db'
|
||||
import { memoTags, history } from '../db/schema'
|
||||
import type { MemoTagRow } from '../db/schema'
|
||||
import { containsPattern } from '../db/like-pattern'
|
||||
import { getLogger } from './LoggerService'
|
||||
import { getCloudSyncService } from './CloudSyncService'
|
||||
import { MEMO_TAG_MAX_LENGTH, memoTagKey, normalizeMemoTag, validateMemoTag } from '@d3ro/core/memo-tag-policy'
|
||||
|
|
@ -24,6 +25,14 @@ import type {
|
|||
|
||||
const logger = getLogger('MemoService')
|
||||
|
||||
export interface ExtendedExportMemoParams extends ExportMemoParams {
|
||||
savePath?: string
|
||||
includeUntagged?: boolean
|
||||
mode?: string
|
||||
isFavorite?: boolean
|
||||
search?: string
|
||||
}
|
||||
|
||||
class MemoService {
|
||||
/**
|
||||
* 특정 히스토리 항목에 부착된 태그 목록을 조회한다.
|
||||
|
|
@ -205,47 +214,126 @@ class MemoService {
|
|||
|
||||
/**
|
||||
* 태그+날짜 기준으로 그룹핑된 마크다운 파일을 생성하고 파일 경로를 반환한다.
|
||||
* 태그가 지정되지 않은 경우 태그가 없는 히스토리 항목도 함께 내보낼 수 있으며,
|
||||
* `savePath`가 전달되면 지정 경로에 저장한다.
|
||||
*/
|
||||
exportMarkdown(params: ExportMemoParams): string {
|
||||
exportMarkdown(params: ExtendedExportMemoParams): string {
|
||||
const db = getDatabase()
|
||||
|
||||
// 태그별 히스토리 조회
|
||||
const tagFilter = params.tag
|
||||
? eq(memoTags.tag, normalizeMemoTag(params.tag))
|
||||
: undefined
|
||||
|
||||
const dateConditions: ReturnType<typeof sql>[] = []
|
||||
const filterConditions = []
|
||||
if (params.from) {
|
||||
const fromMs = new Date(params.from).getTime()
|
||||
dateConditions.push(sql`${history.createdAt} >= ${fromMs}`)
|
||||
filterConditions.push(sql`${history.createdAt} >= ${fromMs}`)
|
||||
}
|
||||
if (params.to) {
|
||||
const toMs = new Date(params.to).getTime()
|
||||
dateConditions.push(sql`${history.createdAt} <= ${toMs}`)
|
||||
filterConditions.push(sql`${history.createdAt} <= ${toMs}`)
|
||||
}
|
||||
if (params.mode && params.mode !== 'all') {
|
||||
if (params.mode === 'file') {
|
||||
filterConditions.push(eq(history.mode, 'file-transcription'))
|
||||
} else if (params.mode === 'commandTranslate') {
|
||||
filterConditions.push(or(eq(history.mode, 'command'), eq(history.mode, 'translate')))
|
||||
} else {
|
||||
filterConditions.push(eq(history.mode, params.mode as HistoryEntry['mode']))
|
||||
}
|
||||
}
|
||||
if (typeof params.isFavorite === 'boolean') {
|
||||
filterConditions.push(eq(history.isFavorite, params.isFavorite))
|
||||
}
|
||||
if (params.search?.trim()) {
|
||||
const pattern = containsPattern(params.search.trim())
|
||||
filterConditions.push(
|
||||
or(
|
||||
pattern.match(history.originalText),
|
||||
pattern.match(history.polishedText),
|
||||
pattern.match(history.title),
|
||||
pattern.match(history.summaryText),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const conditions = [tagFilter, ...dateConditions].filter(
|
||||
(c): c is NonNullable<typeof c> => c !== undefined
|
||||
)
|
||||
type ExportRow = {
|
||||
tag: string
|
||||
title: string | null
|
||||
originalText: string
|
||||
polishedText: string | null
|
||||
createdAt: number
|
||||
duration: number
|
||||
}
|
||||
|
||||
const whereClause = conditions.length > 0 ? and(...conditions) : undefined
|
||||
let rows: ExportRow[] = []
|
||||
|
||||
const rows = db
|
||||
.select({
|
||||
tag: memoTags.tag,
|
||||
originalText: history.originalText,
|
||||
polishedText: history.polishedText,
|
||||
createdAt: history.createdAt,
|
||||
duration: history.duration
|
||||
})
|
||||
.from(memoTags)
|
||||
.innerJoin(history, eq(memoTags.historyId, history.id))
|
||||
.where(whereClause)
|
||||
.orderBy(memoTags.tag, desc(history.createdAt))
|
||||
.all()
|
||||
if (params.tag) {
|
||||
const normalizedTag = normalizeMemoTag(params.tag)
|
||||
const conditions = [eq(memoTags.tag, normalizedTag), ...filterConditions].filter(
|
||||
(c): c is NonNullable<typeof c> => c !== undefined,
|
||||
)
|
||||
const whereClause = conditions.length > 0 ? and(...conditions) : undefined
|
||||
|
||||
rows = db
|
||||
.select({
|
||||
tag: memoTags.tag,
|
||||
title: history.title,
|
||||
originalText: history.originalText,
|
||||
polishedText: history.polishedText,
|
||||
createdAt: history.createdAt,
|
||||
duration: history.duration,
|
||||
})
|
||||
.from(memoTags)
|
||||
.innerJoin(history, eq(memoTags.historyId, history.id))
|
||||
.where(whereClause)
|
||||
.orderBy(memoTags.tag, desc(history.createdAt))
|
||||
.all()
|
||||
} else if (params.includeUntagged === false) {
|
||||
const conditions = filterConditions.filter((c): c is NonNullable<typeof c> => c !== undefined)
|
||||
const whereClause = conditions.length > 0 ? and(...conditions) : undefined
|
||||
|
||||
rows = db
|
||||
.select({
|
||||
tag: memoTags.tag,
|
||||
title: history.title,
|
||||
originalText: history.originalText,
|
||||
polishedText: history.polishedText,
|
||||
createdAt: history.createdAt,
|
||||
duration: history.duration,
|
||||
})
|
||||
.from(memoTags)
|
||||
.innerJoin(history, eq(memoTags.historyId, history.id))
|
||||
.where(whereClause)
|
||||
.orderBy(memoTags.tag, desc(history.createdAt))
|
||||
.all()
|
||||
} else {
|
||||
const conditions = filterConditions.filter((c): c is NonNullable<typeof c> => c !== undefined)
|
||||
const whereClause = conditions.length > 0 ? and(...conditions) : undefined
|
||||
|
||||
const rawRows = db
|
||||
.select({
|
||||
tag: memoTags.tag,
|
||||
title: history.title,
|
||||
originalText: history.originalText,
|
||||
polishedText: history.polishedText,
|
||||
createdAt: history.createdAt,
|
||||
duration: history.duration,
|
||||
})
|
||||
.from(history)
|
||||
.leftJoin(memoTags, eq(memoTags.historyId, history.id))
|
||||
.where(whereClause)
|
||||
.orderBy(desc(history.createdAt))
|
||||
.all()
|
||||
|
||||
rows = rawRows.map((r) => ({
|
||||
tag: r.tag ?? 'untagged',
|
||||
title: r.title,
|
||||
originalText: r.originalText,
|
||||
polishedText: r.polishedText,
|
||||
createdAt: r.createdAt,
|
||||
duration: r.duration,
|
||||
}))
|
||||
}
|
||||
|
||||
// 태그별 → 날짜별 그룹핑
|
||||
const grouped = new Map<string, Map<string, typeof rows>>()
|
||||
const grouped = new Map<string, Map<string, ExportRow[]>>()
|
||||
for (const row of rows) {
|
||||
const dateKey = localDateKey(new Date(row.createdAt))
|
||||
if (!grouped.has(row.tag)) {
|
||||
|
|
@ -269,7 +357,7 @@ class MemoService {
|
|||
}
|
||||
|
||||
for (const [tag, dateMap] of grouped) {
|
||||
lines.push(`## #${tag}`)
|
||||
lines.push(tag === 'untagged' ? '## Untagged' : `## #${tag}`)
|
||||
lines.push('')
|
||||
|
||||
for (const [date, entries] of dateMap) {
|
||||
|
|
@ -282,26 +370,35 @@ class MemoService {
|
|||
minute: '2-digit'
|
||||
})
|
||||
const text = entry.polishedText ?? entry.originalText
|
||||
const titlePrefix = entry.title?.trim() ? `[${entry.title.trim()}] ` : ''
|
||||
const durationSec = Math.round(entry.duration)
|
||||
lines.push(`- **${time}** (${durationSec}s): ${text}`)
|
||||
lines.push(`- **${time}** (${durationSec}s): ${titlePrefix}${text}`)
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
}
|
||||
|
||||
// 파일 저장
|
||||
const exportDir = path.join(app.getPath('userData'), 'exports')
|
||||
if (!fs.existsSync(exportDir)) {
|
||||
fs.mkdirSync(exportDir, { recursive: true })
|
||||
}
|
||||
let filePath: string
|
||||
if (params.savePath?.trim()) {
|
||||
filePath = path.resolve(params.savePath.trim())
|
||||
const targetDir = path.dirname(filePath)
|
||||
if (!fs.existsSync(targetDir)) {
|
||||
fs.mkdirSync(targetDir, { recursive: true })
|
||||
}
|
||||
} else {
|
||||
const exportDir = path.join(app.getPath('userData'), 'exports')
|
||||
if (!fs.existsSync(exportDir)) {
|
||||
fs.mkdirSync(exportDir, { recursive: true })
|
||||
}
|
||||
|
||||
const fileName = buildMemoExportFileName(
|
||||
params.tag ? normalizeMemoTag(params.tag) : undefined,
|
||||
Date.now()
|
||||
)
|
||||
const filePath = path.join(exportDir, fileName)
|
||||
if (path.dirname(path.resolve(filePath)) !== path.resolve(exportDir)) {
|
||||
throw new D3ROError(ErrorCode.MemoExportFailed, 'Memo export path escapes the exports folder')
|
||||
const fileName = buildMemoExportFileName(
|
||||
params.tag ? normalizeMemoTag(params.tag) : undefined,
|
||||
Date.now()
|
||||
)
|
||||
filePath = path.join(exportDir, fileName)
|
||||
if (path.dirname(path.resolve(filePath)) !== path.resolve(exportDir)) {
|
||||
throw new D3ROError(ErrorCode.MemoExportFailed, 'Memo export path escapes the exports folder')
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -23,7 +23,8 @@ import {
|
|||
type GraphContext,
|
||||
type PersonalGraphQuery,
|
||||
type PersonalGraphStats,
|
||||
type PhraseSource
|
||||
type PhraseSource,
|
||||
type TwoHopGraphEdge
|
||||
} from '@d3ro/core/personal-graph'
|
||||
import { SUGGESTION_MEMORY_TAIL_CHARS, isLearnablePhrase, prefixTail } from '@d3ro/core/input-intelligence'
|
||||
import { analyzeWritingContext } from '@d3ro/core/writing-context'
|
||||
|
|
@ -254,16 +255,16 @@ class PersonalGraphService {
|
|||
const directFollowHops = firstHopEdges.filter(
|
||||
(edge) => edge.kind === 'follows' && anchors.includes(edge.fromPhrase)
|
||||
)
|
||||
const normalizedFirstHop = firstHopEdges.flatMap((edge) => {
|
||||
const normalizedFirstHop = firstHopEdges.flatMap<TwoHopGraphEdge>((edge) => {
|
||||
if (edge.kind === 'follows' && anchors.includes(edge.fromPhrase)) {
|
||||
return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'follows' as const, weight: edge.weight }]
|
||||
return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'follows', weight: edge.weight }]
|
||||
}
|
||||
if (edge.kind === 'shares_terms') {
|
||||
if (anchors.includes(edge.fromPhrase)) {
|
||||
return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'shares_terms' as const, weight: edge.weight }]
|
||||
return [{ from: edge.fromPhrase, to: edge.toPhrase, kind: 'shares_terms', weight: edge.weight }]
|
||||
}
|
||||
if (anchors.includes(edge.toPhrase)) {
|
||||
return [{ from: edge.toPhrase, to: edge.fromPhrase, kind: 'shares_terms' as const, weight: edge.weight }]
|
||||
return [{ from: edge.toPhrase, to: edge.fromPhrase, kind: 'shares_terms', weight: edge.weight }]
|
||||
}
|
||||
}
|
||||
return []
|
||||
|
|
|
|||
|
|
@ -2145,7 +2145,7 @@ export class SuggestionService extends EventEmitter {
|
|||
const anchor = this._anchor
|
||||
const anchorKind = this._anchorKind
|
||||
const provenance = this._provenance
|
||||
const composing = this._lastContext?.isComposing === true
|
||||
const composing = this._lastContext?.isComposing === true && /[가-힣]$/u.test(acceptPrefix)
|
||||
const appName = this._appName
|
||||
const windowTitle = this._windowTitle
|
||||
const targetWindow = this._windowHandle
|
||||
|
|
@ -2251,7 +2251,9 @@ export class SuggestionService extends EventEmitter {
|
|||
try {
|
||||
if (deleteCount > 0) {
|
||||
// 확정용 Space(+1)·백스페이스·붙여넣기(Ctrl, V) 키는 사용자 입력 통계에서 뺀다.
|
||||
this._learning.expectProgrammaticKeys?.(deleteCount + (composing ? 2 : 0) + 2)
|
||||
this._learning.expectProgrammaticKeys?.(
|
||||
deleteCount + (composing ? 2 : 0) + (insertMethod === 'keyboard' ? 0 : 2)
|
||||
)
|
||||
}
|
||||
const result =
|
||||
deleteCount > 0
|
||||
|
|
|
|||
|
|
@ -25,6 +25,16 @@ const logger = getLogger('TextInsertService')
|
|||
|
||||
type InsertMethod = 'clipboard' | 'keyboard'
|
||||
|
||||
export interface ReplacementOptions {
|
||||
commitComposition?: boolean
|
||||
/** Revalidate after queue/module waits, immediately before sending destructive keys. */
|
||||
canApply?: () => boolean
|
||||
/** Register synthetic input only when the replacement is about to run. */
|
||||
beforeApply?: () => void
|
||||
/** Automatic Windows corrections must not fall back to separate delete/type operations. */
|
||||
requireAtomic?: boolean
|
||||
}
|
||||
|
||||
interface InsertResult {
|
||||
success: boolean
|
||||
/** 실제로 쓴 방식 — 클립보드를 되돌릴 수 없으면 'clipboard' 요청도 'keyboard' 가 된다 */
|
||||
|
|
@ -101,11 +111,14 @@ export class TextInsertService extends EventEmitter {
|
|||
deleteCount: number,
|
||||
text: string,
|
||||
method: InsertMethod = 'clipboard',
|
||||
options: { commitComposition?: boolean } = {}
|
||||
options: ReplacementOptions = {}
|
||||
): Promise<InsertResult> {
|
||||
const run = this._tail.then(async () => {
|
||||
const skipped = (): InsertResult => ({ success: false, method, textLength: 0, durationMs: 0 })
|
||||
if (options.canApply && !options.canApply()) return skipped()
|
||||
if (method === 'keyboard' && this._keyboard.replaceBeforeCaret) {
|
||||
const start = performance.now()
|
||||
options.beforeApply?.()
|
||||
const handled = await this._keyboard.replaceBeforeCaret(deleteCount, text, options)
|
||||
if (handled) {
|
||||
this.emit('insert-started', { text, method: 'keyboard' })
|
||||
|
|
@ -122,7 +135,12 @@ export class TextInsertService extends EventEmitter {
|
|||
return result
|
||||
}
|
||||
}
|
||||
if (options.requireAtomic) return skipped()
|
||||
try {
|
||||
// Loading the fallback adapter can take seconds. A check before this await is insufficient.
|
||||
await this._keyboard.preload?.()
|
||||
if (options.canApply && !options.canApply()) return skipped()
|
||||
options.beforeApply?.()
|
||||
let count = deleteCount
|
||||
// 커서 앞 글자가 IME 조합 중이면 먼저 확정한다 (Space → 남은 공백까지 지운다).
|
||||
if (options.commitComposition && this._keyboard.commitComposition) {
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@ import { configGet, configSet } from './ConfigService'
|
|||
import { getLogger } from './LoggerService'
|
||||
import { buildTypoCheckPrompt } from './llm-prompts'
|
||||
import type { TypingContext } from './InputTelemetryService'
|
||||
import type { ReplacementOptions } from './TextInsertService'
|
||||
|
||||
const logger = getLogger('TypoCorrectionService')
|
||||
|
||||
|
|
@ -78,9 +79,13 @@ export type TypoVerdict = 'pass' | 'correcting' | 'checking'
|
|||
|
||||
export interface TypoCorrectionDeps {
|
||||
/** 커서 앞 deleteCount 글자를 지우고 text 를 넣는다. 성공 여부. */
|
||||
replaceBeforeCaret(deleteCount: number, text: string, options?: { commitComposition?: boolean }): Promise<boolean>
|
||||
replaceBeforeCaret(deleteCount: number, text: string, options?: ReplacementOptions): Promise<boolean>
|
||||
/** 마지막 키보드 입력 시각 */
|
||||
lastKeyAt(): number
|
||||
/** Monotonic revision including clicks/focus changes and same-millisecond key events. */
|
||||
inputRevision(): number
|
||||
/** OS-side activity also catches physical keys still waiting in the JS hook queue. */
|
||||
nativeInputTick(): number | null
|
||||
/** 곧 보낼 프로그램 키 수 (입력 통계 제외) */
|
||||
expectProgrammaticKeys(count: number): void
|
||||
/** 곧 삽입할 텍스트 (학습 제외). 취소 함수를 돌려준다. */
|
||||
|
|
@ -297,8 +302,12 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
const worthModel = this._worthModelCheck(region)
|
||||
const model = configGet('typoAutoCorrectUseModel') !== false ? this._deps.warmModel() : null
|
||||
if (!model || !worthModel) {
|
||||
// 아직 공백·문장부호로 끝나지 않은 커서 끝 토큰(c.end === prefix.length)은 사용자가 다음 음절을
|
||||
// 조합하는 도중일 수 있으므로 인플레이스 자동 백스페이스 삭제 대상에서 제외한다(제안 팝업 propose 에서만 제시).
|
||||
const tailJamo = detectJamoNoise(prefix, { ignoredWords }).filter(
|
||||
(c) => prefix.length - c.start <= MAX_MODEL_DELETE_CHARS
|
||||
(c) =>
|
||||
(c.to !== '' ? c.end < prefix.length : /[ \t]$/u.test(c.from)) &&
|
||||
prefix.length - c.start <= MAX_MODEL_DELETE_CHARS
|
||||
)
|
||||
const jamoPlan = planTypoReplacement(prefix, tailJamo)
|
||||
if (jamoPlan && jamoPlan.deleteCount <= MAX_MODEL_DELETE_CHARS) {
|
||||
|
|
@ -453,7 +462,11 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
if (abort.signal.aborted || this._check?.abort !== abort) return
|
||||
// 인플레이스 모델 교정은 커서 바로 앞 어절(MAX_MODEL_DELETE_CHARS 이내)만 고친다.
|
||||
// 문장 앞쪽 단어를 고치려고 50~70자를 통째로 백스페이스하면 사용자의 다음 타이핑과 정면 충돌한다.
|
||||
const tailCorrections = mergeTypoCorrections(fromModel, detectJamoNoise(prefix, { ignoredWords })).filter(
|
||||
// 또한 커서 바로 끝(c.end === prefix.length)의 미완성 낱자 삭제는 자동 인플레이스 교정에서 제외한다.
|
||||
const safeJamoNoise = detectJamoNoise(prefix, { ignoredWords }).filter((c) =>
|
||||
c.to !== '' ? c.end < prefix.length : /[ \t]$/u.test(c.from)
|
||||
)
|
||||
const tailCorrections = mergeTypoCorrections(fromModel, safeJamoNoise).filter(
|
||||
(c) => prefix.length - c.start <= MAX_MODEL_DELETE_CHARS
|
||||
)
|
||||
const basePlan = planTypoReplacement(prefix, tailCorrections)
|
||||
|
|
@ -534,19 +547,19 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
|
||||
private async _apply(plan: TypoReplacementPlan, context: TypingContext, keyAtDecision: number): Promise<boolean> {
|
||||
const preRegion = context.prefix.slice(typoRegionStart(context.prefix))
|
||||
if (this._deps.lastKeyAt() !== keyAtDecision) {
|
||||
const revision = context.inputRevision ?? this._deps.inputRevision()
|
||||
const canApply = (): boolean =>
|
||||
this.isEnabled() &&
|
||||
this._deps.lastKeyAt() === keyAtDecision &&
|
||||
this._deps.inputRevision() === revision &&
|
||||
(context.windowHandle == null || this._deps.foregroundHandle() === context.windowHandle) &&
|
||||
(context.nativeInputTick === undefined ||
|
||||
(context.nativeInputTick !== null && this._deps.nativeInputTick() === context.nativeInputTick))
|
||||
if (!canApply()) {
|
||||
this._unmarkRegionChecked(preRegion)
|
||||
logger.debug('오타 교정 취소: 판단 뒤 키 입력이 있었다')
|
||||
logger.debug('오타 교정 취소: 입력 또는 포커스가 변경됐다')
|
||||
return false
|
||||
}
|
||||
if (context.windowHandle != null) {
|
||||
const current = this._deps.foregroundHandle()
|
||||
if (current !== null && current !== context.windowHandle) {
|
||||
this._unmarkRegionChecked(preRegion)
|
||||
logger.debug('오타 교정 취소: 포커스가 다른 창으로 옮겨 갔다')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
this._applying = true
|
||||
// 커서 바로 앞 글자가 완성형 한글 음절([가-힣])이고 조합 중일 때만 Space 로 조합을 확정한 뒤 지운다.
|
||||
|
|
@ -554,14 +567,21 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
// 불필요한 Space 를 보내 앞의 글자까지 지우거나 유령 공백을 남기지 않는다.
|
||||
const commitComposition = context.isComposing === true && /[가-힣]$/u.test(context.prefix)
|
||||
// 확정용 Space(+2)·백스페이스 + 붙여넣기(Ctrl, V) 키는 사용자 입력 통계에서 뺀다.
|
||||
this._deps.expectProgrammaticKeys(plan.deleteCount + (commitComposition ? 2 : 0) + 2)
|
||||
const cancelInsert = this._deps.expectProgrammaticInsert(plan.insertText)
|
||||
let cancelInsert = (): void => undefined
|
||||
try {
|
||||
const ok = commitComposition
|
||||
? await this._deps.replaceBeforeCaret(plan.deleteCount, plan.insertText, { commitComposition: true })
|
||||
: await this._deps.replaceBeforeCaret(plan.deleteCount, plan.insertText)
|
||||
const ok = await this._deps.replaceBeforeCaret(plan.deleteCount, plan.insertText, {
|
||||
commitComposition,
|
||||
canApply,
|
||||
requireAtomic: process.platform === 'win32',
|
||||
beforeApply: () => {
|
||||
cancelInsert()
|
||||
this._deps.expectProgrammaticKeys(plan.deleteCount + (commitComposition ? 2 : 0) + 2)
|
||||
cancelInsert = this._deps.expectProgrammaticInsert(plan.insertText)
|
||||
}
|
||||
})
|
||||
if (!ok) {
|
||||
cancelInsert()
|
||||
this._deps.expectProgrammaticKeys(0)
|
||||
this._unmarkRegionChecked(preRegion)
|
||||
logger.warn('오타 교정 삽입 실패')
|
||||
return false
|
||||
|
|
@ -587,6 +607,7 @@ export class TypoCorrectionService extends EventEmitter {
|
|||
return true
|
||||
} catch (error) {
|
||||
cancelInsert()
|
||||
this._deps.expectProgrammaticKeys(0)
|
||||
this._lastCheckedRegion = ''
|
||||
logger.warn(`오타 교정 예외: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return false
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
// 기록과 회의를 스키마 변경 없이 함께 찾는 로컬 통합 검색.
|
||||
|
||||
import { EventEmitter } from 'events'
|
||||
import { count, desc, or } from 'drizzle-orm'
|
||||
import { count, desc, inArray, or } from 'drizzle-orm'
|
||||
import { formatTranscriptTimestamp, parseTranscriptLines } from '@d3ro/core/meeting-transcript'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
import type {
|
||||
UnifiedSearchParams,
|
||||
|
|
@ -10,7 +11,14 @@ import type {
|
|||
} from '@d3ro/core/types'
|
||||
import { getDatabase } from '../db'
|
||||
import { containsPattern } from '../db/like-pattern'
|
||||
import { history, meetingSessions, type History, type MeetingSessionRow } from '../db/schema'
|
||||
import {
|
||||
history,
|
||||
meetingMemos,
|
||||
meetingSessions,
|
||||
type History,
|
||||
type MeetingMemoRow,
|
||||
type MeetingSessionRow,
|
||||
} from '../db/schema'
|
||||
import { getLogger } from './LoggerService'
|
||||
|
||||
const logger = getLogger('UnifiedSearchService')
|
||||
|
|
@ -86,18 +94,59 @@ function recordResult(row: History, query: string): UnifiedSearchResult {
|
|||
}
|
||||
}
|
||||
|
||||
function meetingResult(row: MeetingSessionRow, query: string): UnifiedSearchResult {
|
||||
function findMatchingTranscriptSegmentSnippet(
|
||||
transcript: string | null | undefined,
|
||||
query: string,
|
||||
): string | null {
|
||||
const lines = parseTranscriptLines(transcript)
|
||||
for (const line of lines) {
|
||||
if (includesQuery(line.text, query) || includesQuery(line.speaker, query)) {
|
||||
if (!line.timed) return line.text
|
||||
const speakerPrefix = line.speaker ? `[${line.speaker}] ` : ''
|
||||
return `[${formatTranscriptTimestamp(line.timestampMs)}] ${speakerPrefix}${line.text}`
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function formatMemoSnippet(memo: MeetingMemoRow): string {
|
||||
return `[${formatTranscriptTimestamp(memo.timestampMs)}] ${memo.content}`
|
||||
}
|
||||
|
||||
function meetingResult(
|
||||
row: MeetingSessionRow,
|
||||
query: string,
|
||||
memoMatch?: MeetingMemoRow,
|
||||
): UnifiedSearchResult {
|
||||
const titleMatched = includesQuery(row.title, query)
|
||||
const matchingTranscript = [row.editedTranscript, row.rawTranscript]
|
||||
.find((value) => includesQuery(value, query))
|
||||
const displayContent = matchingTranscript ?? row.editedTranscript ?? row.rawTranscript ?? row.title
|
||||
const segmentSnippet = findMatchingTranscriptSegmentSnippet(
|
||||
matchingTranscript ?? row.editedTranscript ?? row.rawTranscript,
|
||||
query,
|
||||
)
|
||||
const memoSnippet = memoMatch ? formatMemoSnippet(memoMatch) : null
|
||||
const displayContent = segmentSnippet
|
||||
?? matchingTranscript
|
||||
?? memoSnippet
|
||||
?? row.editedTranscript
|
||||
?? row.rawTranscript
|
||||
?? row.title
|
||||
|
||||
const matchedField = titleMatched && !matchingTranscript && !memoSnippet
|
||||
? 'title'
|
||||
: matchingTranscript || segmentSnippet
|
||||
? 'transcript'
|
||||
: memoSnippet
|
||||
? 'content'
|
||||
: 'transcript'
|
||||
|
||||
return {
|
||||
source: 'meeting',
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
excerpt: createUnifiedSearchExcerpt(displayContent, query),
|
||||
matchedField: titleMatched ? 'title' : 'transcript',
|
||||
matchedField,
|
||||
occurredAt: row.startedAt,
|
||||
}
|
||||
}
|
||||
|
|
@ -147,16 +196,49 @@ class UnifiedSearchService extends EventEmitter {
|
|||
.select()
|
||||
.from(meetingSessions)
|
||||
.where(meetingConditions)
|
||||
.orderBy(desc(meetingSessions.startedAt))
|
||||
.orderBy(desc(meetingSessions.createdAt))
|
||||
.limit(limit)
|
||||
.all()
|
||||
const memoRows = db
|
||||
.select()
|
||||
.from(meetingMemos)
|
||||
.where(pattern.match(meetingMemos.content))
|
||||
.orderBy(desc(meetingMemos.timestampMs))
|
||||
.limit(limit)
|
||||
.all()
|
||||
|
||||
const memoBySessionId = new Map<string, MeetingMemoRow>()
|
||||
for (const memo of memoRows) {
|
||||
if (!memoBySessionId.has(memo.sessionId)) {
|
||||
memoBySessionId.set(memo.sessionId, memo)
|
||||
}
|
||||
}
|
||||
|
||||
const directMeetingIds = new Set(meetingRows.map((row) => row.id))
|
||||
const missingSessionIds = [...memoBySessionId.keys()].filter(
|
||||
(sessionId) => !directMeetingIds.has(sessionId),
|
||||
)
|
||||
const memoMatchedMeetings = missingSessionIds.length > 0
|
||||
? db
|
||||
.select()
|
||||
.from(meetingSessions)
|
||||
.where(inArray(meetingSessions.id, missingSessionIds))
|
||||
.orderBy(desc(meetingSessions.createdAt))
|
||||
.limit(limit)
|
||||
.all()
|
||||
: []
|
||||
|
||||
const combinedMeetingRows = [...meetingRows, ...memoMatchedMeetings]
|
||||
const results = mergeUnifiedSearchResults(
|
||||
recordRows.map((row) => recordResult(row, query)),
|
||||
meetingRows.map((row) => meetingResult(row, query)),
|
||||
combinedMeetingRows.map((row) => meetingResult(row, query, memoBySessionId.get(row.id))),
|
||||
limit,
|
||||
)
|
||||
return { query, results, total: recordTotal + meetingTotal }
|
||||
return {
|
||||
query,
|
||||
results,
|
||||
total: recordTotal + meetingTotal + memoMatchedMeetings.length,
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
logger.error(`Unified search failed: ${message}`)
|
||||
|
|
|
|||
|
|
@ -162,6 +162,86 @@ class VoiceConversationService extends EventEmitter {
|
|||
this._sendToRenderer(IPC_CHANNELS.VOICE_CONVERSATION.STATE_CHANGED, this.getSessionInfo())
|
||||
}
|
||||
|
||||
/**
|
||||
* 이전 대화 메시지(또는 지정한 텍스트)를 TTS로 다시 읽어준다.
|
||||
* 활성 세션 중이면 마이크 캡처를 일시 중지하고 speaking 상태로 재생한 뒤 다시 listening으로 복귀한다.
|
||||
*/
|
||||
async replayMessage(
|
||||
target?: string | { messageId?: string; text?: string },
|
||||
): Promise<void> {
|
||||
let textToSpeak = ''
|
||||
|
||||
if (typeof target === 'string') {
|
||||
const found = this._messages.find((m) => m.id === target)
|
||||
if (found) {
|
||||
textToSpeak = found.content
|
||||
} else if (this._messages.length === 0 && target.trim().length > 0) {
|
||||
textToSpeak = target
|
||||
} else {
|
||||
throw new D3ROError(ErrorCode.ConversationLLMFailed, `Conversation message not found: ${target}`)
|
||||
}
|
||||
} else if (target && typeof target === 'object') {
|
||||
if (target.messageId) {
|
||||
const found = this._messages.find((m) => m.id === target.messageId)
|
||||
if (found) {
|
||||
textToSpeak = found.content
|
||||
} else if (typeof target.text === 'string' && target.text.trim().length > 0) {
|
||||
textToSpeak = target.text
|
||||
} else {
|
||||
throw new D3ROError(
|
||||
ErrorCode.ConversationLLMFailed,
|
||||
`Conversation message not found: ${target.messageId}`,
|
||||
)
|
||||
}
|
||||
} else if (typeof target.text === 'string') {
|
||||
textToSpeak = target.text
|
||||
}
|
||||
} else {
|
||||
for (let i = this._messages.length - 1; i >= 0; i--) {
|
||||
if (this._messages[i].role === 'assistant') {
|
||||
textToSpeak = this._messages[i].content
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const trimmed = textToSpeak.trim()
|
||||
if (!trimmed) {
|
||||
throw new D3ROError(ErrorCode.ConversationLLMFailed, 'No conversation message to replay')
|
||||
}
|
||||
|
||||
const sentences = trimmed
|
||||
.split(/(?<=[.!?。!?])\s+/)
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
const ttsSentences = sentences.length > 0 ? sentences : [trimmed]
|
||||
|
||||
const wasActive = this._isActive
|
||||
const turn = this._turn
|
||||
if (wasActive) {
|
||||
this._stopListening()
|
||||
this._setState('speaking')
|
||||
}
|
||||
|
||||
this._sendToRenderer(IPC_CHANNELS.VOICE_CONVERSATION.TTS_STARTED, {})
|
||||
try {
|
||||
await getTTSPlaybackService().speakSentences(ttsSentences)
|
||||
} finally {
|
||||
if (!wasActive || (this._isActive && this._turn === turn)) {
|
||||
this._sendToRenderer(IPC_CHANNELS.VOICE_CONVERSATION.TTS_FINISHED, {})
|
||||
}
|
||||
if (wasActive && this._isActive && this._turn === turn) {
|
||||
this._resumeListening()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async speakMessage(
|
||||
target?: string | { messageId?: string; text?: string },
|
||||
): Promise<void> {
|
||||
return this.replayMessage(target)
|
||||
}
|
||||
|
||||
// ── 내부 로직 ──
|
||||
|
||||
private _setState(state: ConversationState): void {
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ import { getLlmGateway } from './llm/LlmGateway'
|
|||
import { buildInstructionInvocation, resolveTargetLanguage } from './llm-prompts'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
import { cleanDictatedText } from '@d3ro/core/dictation-cleaner'
|
||||
import { composeInstructionPipelinePrompt, parseActiveInstructionIds } from '@d3ro/core/instruction-template'
|
||||
import { TIMING } from '@d3ro/core/constants'
|
||||
import { RecognitionState, AudioState } from '@d3ro/core/types'
|
||||
import type { KeyBindingActionId, VoiceMode, VoiceState, LLMAction } from '@d3ro/core/types'
|
||||
|
|
@ -132,6 +133,8 @@ class SessionRun {
|
|||
audioStarted = false
|
||||
/** 사용자가 이미 정지를 요청했다 — 두 번째 release/토글은 무시한다 */
|
||||
stopRequested = false
|
||||
/** 이 세션을 시작한 키바인딩 액션 */
|
||||
actionId: KeyBindingActionId = 'dictation'
|
||||
sttReady = false
|
||||
transcribing = false
|
||||
audioBuffer: Buffer[] = []
|
||||
|
|
@ -266,31 +269,7 @@ class VoiceModeService extends EventEmitter {
|
|||
*/
|
||||
connectKeyBindings(): void {
|
||||
this._keyBindingHandler = (payload) => {
|
||||
switch (payload.actionId) {
|
||||
case 'caption':
|
||||
// Phase 10.1: caption은 VoiceModeService가 아닌 CaptionService로 라우팅.
|
||||
// 토글이므로 press만 처리하고 release는 버린다.
|
||||
if (payload.type === 'pressed') this._toggleCaption()
|
||||
return
|
||||
case 'dictation':
|
||||
case 'hands-free':
|
||||
case 'command':
|
||||
break
|
||||
default:
|
||||
// 음성 세션 액션만 여기서 처리한다. 팝업·제안 액션은 bootstrap이 직접 구독한다
|
||||
// (허용 목록이 아니면 새 액션이 생길 때마다 받아쓰기로 오인돼 녹음이 켜진다).
|
||||
return
|
||||
}
|
||||
|
||||
const holdMode = resolveGestureHoldMode(payload.actionId, payload.holdMode)
|
||||
const action: VoiceAction = {
|
||||
type: payload.type === 'pressed' ? 'press' : 'release',
|
||||
timestamp: payload.timestamp,
|
||||
mode: resolveGestureMode(payload.actionId, payload.isDoublePress),
|
||||
actionId: payload.actionId,
|
||||
holdMode
|
||||
}
|
||||
this._enqueueAction(action)
|
||||
this.handleShortcutTrigger(payload)
|
||||
}
|
||||
|
||||
getKeyBindingService().on('triggered', this._keyBindingHandler)
|
||||
|
|
@ -298,9 +277,47 @@ class VoiceModeService extends EventEmitter {
|
|||
logger.info('Key binding events connected')
|
||||
}
|
||||
|
||||
/**
|
||||
* 키바인딩 트리거 이벤트를 받아 세션 액션 큐에 넣는다.
|
||||
*/
|
||||
handleShortcutTrigger(payload: KeyBindingTriggerPayload): void {
|
||||
switch (payload.actionId) {
|
||||
case 'caption':
|
||||
// Phase 10.1: caption은 VoiceModeService가 아닌 CaptionService로 라우팅.
|
||||
// 토글이므로 press만 처리하고 release는 버린다.
|
||||
if (payload.type === 'pressed') void this._toggleCaption()
|
||||
return
|
||||
case 'dictation':
|
||||
case 'hands-free':
|
||||
case 'command':
|
||||
break
|
||||
default:
|
||||
// 음성 세션 액션만 여기서 처리한다. 팝업·제안 액션은 bootstrap이 직접 구독한다
|
||||
// (허용 목록이 아니면 새 액션이 생길 때마다 받아쓰기로 오인돼 녹음이 켜진다).
|
||||
return
|
||||
}
|
||||
|
||||
const holdMode = this._resolveHoldMode(payload.actionId, payload.holdMode)
|
||||
const action: VoiceAction = {
|
||||
type: payload.type === 'pressed' ? 'press' : 'release',
|
||||
timestamp: payload.timestamp,
|
||||
mode: resolveGestureMode(payload.actionId, payload.isDoublePress),
|
||||
actionId: payload.actionId,
|
||||
holdMode
|
||||
}
|
||||
this._enqueueAction(action)
|
||||
}
|
||||
|
||||
_resolveHoldMode(actionId: KeyBindingActionId, specHoldMode = false): boolean {
|
||||
return resolveGestureHoldMode(actionId, specHoldMode)
|
||||
}
|
||||
|
||||
// ── 세션 제어 ──────────────────────────────────────────
|
||||
|
||||
async startSession(mode: VoiceMode): Promise<void> {
|
||||
async startSession(
|
||||
mode: VoiceMode,
|
||||
options?: { actionId?: KeyBindingActionId },
|
||||
): Promise<void> {
|
||||
if (this._disposed) return
|
||||
if (this._session && !this._isInTerminalState()) {
|
||||
logger.warn('Session already active, ignoring startSession')
|
||||
|
|
@ -380,6 +397,7 @@ class VoiceModeService extends EventEmitter {
|
|||
|
||||
// 세션 생성
|
||||
const run = new SessionRun(randomUUID())
|
||||
run.actionId = options?.actionId ?? (mode === 'hands-free' ? 'hands-free' : 'dictation')
|
||||
run.captureSelection = windowContext !== null
|
||||
run.windowContext = windowContext
|
||||
this._run = run
|
||||
|
|
@ -469,7 +487,7 @@ class VoiceModeService extends EventEmitter {
|
|||
// 핫키를 뗀 뒤라 복사 단축키가 안전하다 — LLM 이 쓸 것이 확실하면 전사와 병렬로 선택 텍스트를
|
||||
// 캡처한다. 원문 삽입 경로(none·LLM 불가)에선 보내지 않는다: 쓰지도 않을 Ctrl+C 가 터미널에선
|
||||
// 프로세스를 중단시킨다. 음성 단축키로 LLM 경로가 될 수도 있으면 LLM 단계에서 늦게 캡처한다.
|
||||
if (routeUsesLlm(this._resolveLlmRoute(null))) this._startSelectionCapture(run)
|
||||
if (routeUsesLlm(this._resolveLlmRoute(null, run.actionId))) this._startSelectionCapture(run)
|
||||
|
||||
// 버퍼가 있으면 STT에 전달
|
||||
if (run.audioBuffer.length > 0 && run.sttReady) {
|
||||
|
|
@ -924,20 +942,30 @@ class VoiceModeService extends EventEmitter {
|
|||
return
|
||||
}
|
||||
|
||||
if (this._session) {
|
||||
this._session.transcription = result.text
|
||||
let rawText = result.text
|
||||
try {
|
||||
const { getDictionaryService } = await import('./DictionaryService')
|
||||
const corrected = getDictionaryService().applyDictionaryCorrections(rawText)
|
||||
rawText = corrected.text
|
||||
} catch {
|
||||
// DictionaryService 미초기화 시 무시
|
||||
}
|
||||
|
||||
this.emit('transcription-update', { text: result.text, isFinal: true })
|
||||
if (this._session) {
|
||||
this._session.transcription = rawText
|
||||
}
|
||||
|
||||
this.emit('transcription-update', { text: rawText, isFinal: true })
|
||||
|
||||
// Phase 10.5: 음성 단축키 — 키워드 매칭으로 LLM 명령어 자동 선택
|
||||
let effectiveText = result.text
|
||||
// 'command' 핫키로 진입한 세션은 voiceCommandsEnabled 설정과 무관하게 음성 명령 매칭을 항상 수행한다.
|
||||
let effectiveText = rawText
|
||||
let overrideInstructionId: string | null = null
|
||||
try {
|
||||
const { getVoiceCommandService } = await import('./VoiceCommandService')
|
||||
const vcSvc = getVoiceCommandService()
|
||||
if (vcSvc.isEnabled()) {
|
||||
const match = vcSvc.match(result.text)
|
||||
if (run.actionId === 'command' || vcSvc.isEnabled()) {
|
||||
const match = vcSvc.match(rawText)
|
||||
if (match.matched && match.instructionId) {
|
||||
effectiveText = match.cleanedText
|
||||
overrideInstructionId = match.instructionId
|
||||
|
|
@ -952,7 +980,7 @@ class VoiceModeService extends EventEmitter {
|
|||
// 결정적 구어 군더더기·추임새·말바꾸기·중복·동음이의어 1차 정리 (LLM 유무와 무관하게 0ms 즉시 적용)
|
||||
effectiveText = cleanDictatedText(effectiveText)
|
||||
|
||||
const route = this._resolveLlmRoute(overrideInstructionId)
|
||||
const route = this._resolveLlmRoute(overrideInstructionId, run.actionId)
|
||||
if (route.kind === 'insert-raw') {
|
||||
if (route.reason === 'llm-unavailable') {
|
||||
this.emit('error', {
|
||||
|
|
@ -999,10 +1027,16 @@ class VoiceModeService extends EventEmitter {
|
|||
}
|
||||
|
||||
/** 현재 설정으로 LLM 후처리 경로를 결정한다 (정책은 @d3ro/core/voice-llm-route 가 소유) */
|
||||
private _resolveLlmRoute(overrideInstructionId: string | null): VoiceLlmRoute {
|
||||
private _resolveLlmRoute(
|
||||
overrideInstructionId: string | null,
|
||||
actionId: KeyBindingActionId | undefined = this._run?.actionId,
|
||||
): VoiceLlmRoute {
|
||||
const backend = configGet('llmBackend')
|
||||
const configuredAction = configGet('defaultLLMAction')
|
||||
const defaultAction =
|
||||
actionId === 'command' && configuredAction === 'none' ? 'refine' : configuredAction
|
||||
return resolveVoiceLlmRoute({
|
||||
defaultAction: configGet('defaultLLMAction'),
|
||||
defaultAction,
|
||||
overrideInstructionId,
|
||||
activeChainId: configGet('activeChainId') ?? null,
|
||||
activeInstructionId: configGet('activeInstructionId') ?? null,
|
||||
|
|
@ -1073,19 +1107,33 @@ class VoiceModeService extends EventEmitter {
|
|||
}
|
||||
}
|
||||
|
||||
/** 지시문(음성 단축키 또는 활성 지시문)으로 처리한다. 지시문이 없으면 지시문 없이 custom 처리 */
|
||||
/** 지시문(음성 단축키 또는 활성 지시문·파이프라인)으로 처리한다. 지시문이 없으면 지시문 없이 custom 처리 */
|
||||
private async _processWithInstruction(userText: string, instructionId: string | null): Promise<string> {
|
||||
let invocationText = userText
|
||||
let instructionPrompt: string | undefined
|
||||
|
||||
if (instructionId) {
|
||||
const { getCustomInstructionService } = await import('./CustomInstructionService')
|
||||
const instruction = getCustomInstructionService().getById(instructionId)
|
||||
if (instruction) {
|
||||
const svc = getCustomInstructionService()
|
||||
const ids = parseActiveInstructionIds(instructionId)
|
||||
const matched = ids
|
||||
.map((id) => svc.getById(id))
|
||||
.filter((item): item is NonNullable<typeof item> => item !== null)
|
||||
|
||||
if (matched.length === 1) {
|
||||
const instruction = matched[0]
|
||||
const invocation = buildInstructionInvocation(instruction.prompt, userText, resolveTargetLanguage())
|
||||
invocationText = invocation.text
|
||||
instructionPrompt = invocation.systemPrompt
|
||||
logger.info(`Using custom instruction: "${instruction.name}"`)
|
||||
} else if (matched.length >= 2) {
|
||||
const composedPrompt = composeInstructionPipelinePrompt(matched)
|
||||
const invocation = buildInstructionInvocation(composedPrompt, userText, resolveTargetLanguage())
|
||||
invocationText = invocation.text
|
||||
instructionPrompt = invocation.systemPrompt
|
||||
logger.info(
|
||||
`Using custom instruction pipeline (${matched.length} steps): ${matched.map((i) => i.name).join(' → ')}`,
|
||||
)
|
||||
} else {
|
||||
logger.warn(`Custom instruction not found: ${instructionId} — processing without an instruction`)
|
||||
}
|
||||
|
|
@ -1275,7 +1323,7 @@ class VoiceModeService extends EventEmitter {
|
|||
)
|
||||
switch (intent.kind) {
|
||||
case 'start':
|
||||
await this.startSession(intent.mode)
|
||||
await this.startSession(intent.mode, { actionId: action.actionId })
|
||||
break
|
||||
case 'stop':
|
||||
// Speakly 패턴: 딜레이 없이 즉시 stop (딜레이가 race condition 유발)
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import { PubMaticAdapter } from './PubMaticAdapter'
|
|||
import { MintegralAdapter } from './MintegralAdapter'
|
||||
import { DirectHouseSponsorAdapter } from './DirectHouseSponsorAdapter'
|
||||
import { getAdSettlementService } from './AdSettlementService'
|
||||
import { getLicenseService } from '../LicenseService'
|
||||
|
||||
export class AdMediationEngine {
|
||||
private static instance: AdMediationEngine | null = null
|
||||
|
|
@ -30,6 +31,8 @@ export class AdMediationEngine {
|
|||
private impressionHistory: AdImpressionEvent[] = []
|
||||
private deliveredCreatives = new Map<string, AdCreativePayload>()
|
||||
private clickedCreatives = new Set<string>()
|
||||
private claimedRewards = new Set<string>()
|
||||
private lastRewardClaimedAt = 0
|
||||
|
||||
private constructor() {
|
||||
// Provider shells stay registered for explicit configuration diagnostics,
|
||||
|
|
@ -280,16 +283,116 @@ export class AdMediationEngine {
|
|||
getAdSettlementService().recordClick(networkId)
|
||||
}
|
||||
|
||||
public async claimReward(adId: string, networkId: string): Promise<AdRewardResult> {
|
||||
// Desktop mediation has no server-verified completion/nonce ledger. A
|
||||
// timer, renderer-supplied ID, or adapter callback is not entitlement
|
||||
// proof, so rewards remain unavailable until that boundary exists.
|
||||
void adId
|
||||
void networkId
|
||||
public async reportRewardCompletion(
|
||||
adId: string,
|
||||
networkId: string,
|
||||
nonce?: string,
|
||||
): Promise<AdRewardResult> {
|
||||
return this.claimReward(adId, networkId, nonce)
|
||||
}
|
||||
|
||||
public async claimReward(
|
||||
adId: string,
|
||||
networkId: string,
|
||||
nonce?: string,
|
||||
): Promise<AdRewardResult> {
|
||||
const trimmedAdId = adId?.trim()
|
||||
if (!trimmedAdId || !networkId) {
|
||||
return {
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const delivered = this.deliveredCreatives.get(trimmedAdId)
|
||||
const impression = this.impressionHistory.find((candidate) => candidate.adId === trimmedAdId)
|
||||
if (
|
||||
delivered === undefined ||
|
||||
delivered.networkId !== networkId ||
|
||||
impression === undefined
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const claimKey = nonce?.trim() ? `${trimmedAdId}:${nonce.trim()}` : trimmedAdId
|
||||
if (this.claimedRewards.has(trimmedAdId) || this.claimedRewards.has(claimKey)) {
|
||||
return {
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
const cooldownMs = Math.max(0, this.config.rewardCooldownSeconds * 1000)
|
||||
if (this.lastRewardClaimedAt > 0 && now - this.lastRewardClaimedAt < cooldownMs) {
|
||||
return {
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
nextAvailableAt: this.lastRewardClaimedAt + cooldownMs,
|
||||
}
|
||||
}
|
||||
|
||||
const adapter = this.adapters.get(networkId)
|
||||
if (!adapter?.reportRewardCompletion) {
|
||||
return {
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const completion = await adapter
|
||||
.reportRewardCompletion(trimmedAdId)
|
||||
.catch(() => ({ success: false, tokenReward: 0 }))
|
||||
if (!completion.success) {
|
||||
return {
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const rawTokens =
|
||||
completion.tokenReward > 0
|
||||
? completion.tokenReward
|
||||
: (delivered.rewardTokens ?? this.config.rewardTokensAmount)
|
||||
const tokensToGrant = rawTokens > 0 ? rawTokens : this.config.rewardTokensAmount
|
||||
if (tokensToGrant <= 0) {
|
||||
return {
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const grantResult = getLicenseService().grantRewardQuota(tokensToGrant, claimKey)
|
||||
if (!grantResult.granted) {
|
||||
return {
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
}
|
||||
}
|
||||
|
||||
this.claimedRewards.add(trimmedAdId)
|
||||
this.claimedRewards.add(claimKey)
|
||||
this.lastRewardClaimedAt = now
|
||||
impression.completed = true
|
||||
getAdSettlementService().recordCompletion(networkId)
|
||||
|
||||
return {
|
||||
success: false,
|
||||
tokensAdded: 0,
|
||||
newTotalQuota: 0,
|
||||
success: true,
|
||||
tokensAdded: grantResult.tokensAdded,
|
||||
newTotalQuota: grantResult.newTotalQuota,
|
||||
nextAvailableAt: now + cooldownMs,
|
||||
rewardId: grantResult.rewardId,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -25,6 +25,10 @@ export type LicenseStoreField =
|
|||
// cloud entitlement
|
||||
| 'licenseCloudTier'
|
||||
| 'licenseCloudVerifiedAt'
|
||||
// rewarded ad bonus quota (daily + replay nonces)
|
||||
| 'licenseRewardBonusDate'
|
||||
| 'licenseRewardBonusAmount'
|
||||
| 'licenseRewardClaimedNonces'
|
||||
// combined view (kept for older app versions that read the same file)
|
||||
| 'licenseTier'
|
||||
| 'licenseLastVerifiedAt'
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
// LLM 시스템 프롬프트 SSOT — PremiumLLMService 공용.
|
||||
|
||||
import { getLogger } from './LoggerService'
|
||||
import * as ConfigServiceModule from './ConfigService'
|
||||
import type { LLMAction } from '@d3ro/core/types'
|
||||
import {
|
||||
fillInstructionPlaceholders,
|
||||
|
|
@ -52,23 +53,49 @@ const BASE_SYSTEM_PROMPTS: Record<string, string> = {
|
|||
|
||||
/**
|
||||
* 번역 대상 언어 기본값.
|
||||
* `AppConfig`에는 번역 대상 언어 키가 없다 (`language`는 UI 로케일,
|
||||
* `sttLanguage`는 입력 언어라 둘 다 대상 언어가 아니다).
|
||||
*/
|
||||
export const DEFAULT_TARGET_LANGUAGE = 'English'
|
||||
|
||||
/**
|
||||
* 설정 UI에서 고를 수 있는 번역 대상 언어 목록.
|
||||
* 프롬프트(`{{targetLanguage}}로 번역해주세요`)에 자연스럽게 들어가도록 명확한 언어 이름을 쓴다.
|
||||
*/
|
||||
export const SUPPORTED_TARGET_LANGUAGES = [
|
||||
'English',
|
||||
'Korean',
|
||||
'Japanese',
|
||||
'Chinese (Simplified)',
|
||||
'Chinese (Traditional)',
|
||||
'Spanish',
|
||||
'French',
|
||||
'German',
|
||||
'Portuguese',
|
||||
'Vietnamese',
|
||||
'Indonesian',
|
||||
'Arabic',
|
||||
] as const
|
||||
|
||||
export type SupportedTargetLanguage = (typeof SUPPORTED_TARGET_LANGUAGES)[number]
|
||||
|
||||
/**
|
||||
* 번역 대상 언어를 해석한다. LLM을 호출하는 모든 경로가 이 함수를 쓴다.
|
||||
*
|
||||
* `AppConfig`에는 번역 대상 언어 키가 없다 — `language`는 UI 로케일이고
|
||||
* `sttLanguage`는 입력(원문) 언어라 어느 쪽도 대상 언어로 쓸 수 없다.
|
||||
* (입력 언어로 번역하면 원문 그대로가 되고, UI 로케일은 `'ko'` 같은 코드라
|
||||
* 프롬프트에 그대로 넣으면 문장이 깨진다.)
|
||||
*
|
||||
* 따라서 현재는 {@link DEFAULT_TARGET_LANGUAGE} 고정이다. 사용자가 대상 언어를
|
||||
* 고를 수 있으려면 설정 키가 필요하다.
|
||||
* 명시 인자가 있으면 우선하고, 없으면 `AppConfig.targetLanguage` 설정값을 읽는다.
|
||||
* 설정 서비스가 초기화되지 않았거나 값이 비어 있으면 {@link DEFAULT_TARGET_LANGUAGE}로 폴백한다.
|
||||
*/
|
||||
export function resolveTargetLanguage(): string {
|
||||
export function resolveTargetLanguage(explicit?: string | null): string {
|
||||
if (typeof explicit === 'string' && explicit.trim().length > 0) {
|
||||
return explicit.trim()
|
||||
}
|
||||
if (Object.keys(ConfigServiceModule).includes('getConfigService')) {
|
||||
const store = ConfigServiceModule.getConfigService()
|
||||
if (store) {
|
||||
const configured = store.get('targetLanguage')
|
||||
if (typeof configured === 'string' && configured.trim().length > 0) {
|
||||
return configured.trim()
|
||||
}
|
||||
}
|
||||
}
|
||||
return DEFAULT_TARGET_LANGUAGE
|
||||
}
|
||||
|
||||
|
|
@ -105,7 +132,7 @@ function warnUnresolved(unresolved: readonly string[]): void {
|
|||
function renderWithDefaults(prompt: string, vars: InstructionVars): RenderedInstruction {
|
||||
const rendered = renderInstruction(prompt, {
|
||||
text: vars.text,
|
||||
targetLanguage: vars.targetLanguage ?? DEFAULT_TARGET_LANGUAGE,
|
||||
targetLanguage: resolveTargetLanguage(vars.targetLanguage),
|
||||
})
|
||||
// 조용히 새어나간 플레이스홀더가 LLM에 그대로 전달되는 사고가 있었다.
|
||||
warnUnresolved(rendered.unresolved)
|
||||
|
|
@ -120,7 +147,7 @@ export function renderInstructionPrompt(prompt: string, vars: InstructionVars):
|
|||
warnUnresolved(findUnresolvedPlaceholders(prompt))
|
||||
return fillInstructionPlaceholders(prompt, {
|
||||
text: vars.text,
|
||||
targetLanguage: vars.targetLanguage ?? DEFAULT_TARGET_LANGUAGE,
|
||||
targetLanguage: resolveTargetLanguage(vars.targetLanguage),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -176,7 +203,7 @@ export function resolveSystemPrompt(
|
|||
if (action === 'translate') {
|
||||
return BASE_SYSTEM_PROMPTS.translate.replace(
|
||||
'{{targetLanguage}}',
|
||||
targetLanguage ?? DEFAULT_TARGET_LANGUAGE,
|
||||
resolveTargetLanguage(targetLanguage),
|
||||
)
|
||||
}
|
||||
return BASE_SYSTEM_PROMPTS[action] ?? BASE_SYSTEM_PROMPTS[CUSTOM_FALLBACK_ACTION]
|
||||
|
|
|
|||
|
|
@ -49,8 +49,8 @@ export const STT_PROVIDERS_META: STTProviderInfo[] = [
|
|||
{
|
||||
id: 'local',
|
||||
name: 'Local Whisper',
|
||||
description: '100% 완전 오프라인, 무료, 프라이버시 보호',
|
||||
badge: 'Offline · Free',
|
||||
description: 'Local faster-whisper inference on device',
|
||||
badge: 'Local · On-Device',
|
||||
requiresApiKey: false,
|
||||
defaultModel: 'large-v3-turbo',
|
||||
models: ['tiny', 'base', 'small', 'medium', 'large-v3', 'large-v3-turbo'],
|
||||
|
|
@ -59,8 +59,8 @@ export const STT_PROVIDERS_META: STTProviderInfo[] = [
|
|||
{
|
||||
id: 'd3ro-cloud',
|
||||
name: 'D3RO Cloud STT (Managed)',
|
||||
description: 'D3RO 클라우드 매니지드 전사 서비스 (키 설정 불필요)',
|
||||
badge: 'Cloud · Zero Config',
|
||||
description: 'Managed cloud speech-to-text gateway',
|
||||
badge: 'Cloud · Managed',
|
||||
requiresApiKey: false,
|
||||
defaultModel: 'default',
|
||||
defaultBaseUrl: 'http://127.0.0.1:5000',
|
||||
|
|
@ -70,8 +70,8 @@ export const STT_PROVIDERS_META: STTProviderInfo[] = [
|
|||
{
|
||||
id: 'openai',
|
||||
name: 'OpenAI Whisper',
|
||||
description: '공식 OpenAI 고품질 다국어 음성 인식',
|
||||
badge: 'Standard · High Accuracy',
|
||||
description: 'OpenAI Audio Transcriptions API',
|
||||
badge: 'Cloud · OpenAI API',
|
||||
requiresApiKey: true,
|
||||
defaultModel: 'whisper-1',
|
||||
defaultBaseUrl: 'https://api.openai.com/v1',
|
||||
|
|
@ -81,8 +81,8 @@ export const STT_PROVIDERS_META: STTProviderInfo[] = [
|
|||
{
|
||||
id: 'groq',
|
||||
name: 'Groq Whisper LPU',
|
||||
description: 'LPU 가속 기반 초저지연(~200ms) 초고속 인식',
|
||||
badge: 'Ultra Fast (~200ms)',
|
||||
description: 'Groq LPU-hosted Whisper API',
|
||||
badge: 'Cloud · Groq LPU',
|
||||
requiresApiKey: true,
|
||||
defaultModel: 'whisper-large-v3-turbo',
|
||||
defaultBaseUrl: 'https://api.groq.com/openai/v1',
|
||||
|
|
@ -92,8 +92,8 @@ export const STT_PROVIDERS_META: STTProviderInfo[] = [
|
|||
{
|
||||
id: 'deepgram',
|
||||
name: 'Deepgram Nova-3',
|
||||
description: '업계 최고 인식률, 스마트 문장 부호 및 포맷팅',
|
||||
badge: 'Industry Benchmark',
|
||||
description: 'Deepgram Nova speech recognition API',
|
||||
badge: 'Cloud · Deepgram API',
|
||||
requiresApiKey: true,
|
||||
defaultModel: 'nova-3',
|
||||
defaultBaseUrl: 'https://api.deepgram.com',
|
||||
|
|
@ -103,8 +103,8 @@ export const STT_PROVIDERS_META: STTProviderInfo[] = [
|
|||
{
|
||||
id: 'assemblyai',
|
||||
name: 'AssemblyAI Universal-2',
|
||||
description: '고도화된 음향 모델 및 문맥 인식 STT',
|
||||
badge: 'Advanced Acoustic',
|
||||
description: 'AssemblyAI asynchronous speech-to-text API',
|
||||
badge: 'Cloud · AssemblyAI API',
|
||||
requiresApiKey: true,
|
||||
defaultModel: 'best',
|
||||
defaultBaseUrl: 'https://api.assemblyai.com/v2',
|
||||
|
|
@ -114,8 +114,8 @@ export const STT_PROVIDERS_META: STTProviderInfo[] = [
|
|||
{
|
||||
id: 'google',
|
||||
name: 'Google Gemini 2.0 Flash / Cloud STT',
|
||||
description: 'Gemini 2.0 Flash 기반 한국어/다국어 인식',
|
||||
badge: 'Multilingual · Asian Languages',
|
||||
description: 'Google Generative Language multimodal audio API',
|
||||
badge: 'Cloud · Gemini Audio',
|
||||
requiresApiKey: true,
|
||||
defaultModel: 'gemini-2.0-flash',
|
||||
defaultBaseUrl: 'https://generativelanguage.googleapis.com/v1beta',
|
||||
|
|
@ -124,9 +124,9 @@ export const STT_PROVIDERS_META: STTProviderInfo[] = [
|
|||
},
|
||||
{
|
||||
id: 'custom',
|
||||
name: 'Custom (OpenAI 호환)',
|
||||
description: 'vLLM, 사내 프라이빗 서버, Together 등 커스텀 엔드포인트',
|
||||
badge: 'Self-Hosted / Proxy',
|
||||
name: 'Custom (OpenAI Compatible)',
|
||||
description: 'Custom OpenAI-compatible audio transcriptions endpoint',
|
||||
badge: 'Self-Hosted · Proxy',
|
||||
requiresApiKey: false,
|
||||
defaultModel: 'whisper-1',
|
||||
defaultBaseUrl: 'http://127.0.0.1:8000/v1',
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ export interface NutKeyboardModule {
|
|||
hasKeyboard(): boolean
|
||||
getKeyboard(): NutNativeKeyboard
|
||||
}
|
||||
Key: Pick<typeof NutKey, 'LeftControl' | 'LeftSuper' | 'V' | 'Backspace'>
|
||||
Key: Pick<typeof NutKey, 'LeftControl' | 'LeftSuper' | 'V' | 'Backspace' | 'Space'>
|
||||
}
|
||||
|
||||
export type NutModuleLoader = () => Promise<NutKeyboardModule>
|
||||
|
|
|
|||
|
|
@ -59,6 +59,9 @@ export function resolveVoiceIntent(gesture: VoiceGesture, phase: VoiceIntentPhas
|
|||
|
||||
if (gesture.type === 'press') {
|
||||
if (gesture.mode === 'dictation') {
|
||||
if (!gesture.holdMode) {
|
||||
return phase === 'idle' ? { kind: 'start', mode: 'dictation' } : STOP
|
||||
}
|
||||
return phase === 'idle' ? { kind: 'start', mode: 'dictation' } : IGNORE
|
||||
}
|
||||
return phase === 'idle' ? { kind: 'start', mode: 'hands-free' } : STOP
|
||||
|
|
@ -75,11 +78,9 @@ export function resolveGestureMode(actionId: KeyBindingActionId, isDoublePress:
|
|||
}
|
||||
|
||||
/**
|
||||
* 'command' 액션에는 아직 전용 핸들러가 없다.
|
||||
* 현행 동작대로 dictation 파이프라인으로 fallback 하며, 그 경로는 hold-to-talk 이므로
|
||||
* KEYBINDING_ACTIONS 의 holdMode(false)가 아니라 dictation 과 같은 값을 쓴다.
|
||||
* 키바인딩 스펙의 holdMode 설정을 그대로 존중한다.
|
||||
* 'command' 액션도 스펙/설정에 따라 토글(holdMode=false) 또는 홀드(holdMode=true)로 동작한다.
|
||||
*/
|
||||
export function resolveGestureHoldMode(actionId: KeyBindingActionId, specHoldMode: boolean): boolean {
|
||||
if (actionId === 'command') return true
|
||||
export function resolveGestureHoldMode(_actionId: KeyBindingActionId, specHoldMode: boolean): boolean {
|
||||
return specHoldMode
|
||||
}
|
||||
|
|
|
|||
21
apps/desktop/src/main/utils/inference-cpu-budget.ts
Normal file
21
apps/desktop/src/main/utils/inference-cpu-budget.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { availableParallelism } from 'node:os'
|
||||
|
||||
/** Leave scheduling headroom for the foreground app and IME; this is a worker cap, not CPU affinity. */
|
||||
export function inferenceCpuThreads(availableCpus: number): number {
|
||||
if (!Number.isFinite(availableCpus) || availableCpus < 1) return 1
|
||||
return Math.max(1, Math.min(4, Math.floor(availableCpus) - 2))
|
||||
}
|
||||
|
||||
/** A remote Ollama host has a different CPU budget; only constrain the local engine. */
|
||||
export function localInferenceCpuOptions(serverUrl: string): { num_thread?: number } {
|
||||
try {
|
||||
const hostname = new URL(serverUrl).hostname.toLowerCase()
|
||||
if (
|
||||
hostname !== 'localhost' && hostname !== 'localhost.' && hostname !== '[::1]' &&
|
||||
!/^127\.\d+\.\d+\.\d+$/.test(hostname)
|
||||
) return {}
|
||||
return { num_thread: inferenceCpuThreads(availableParallelism()) }
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
|
@ -79,9 +79,17 @@ const IME_CMODE_NATIVE = 0x0001
|
|||
const SMTO_ABORTIFHUNG = 0x0002
|
||||
const TITLE_BUFFER_CHARS = 512
|
||||
const PATH_BUFFER_CHARS = 1024
|
||||
const PROCESS_PATH_CACHE_MAX = 256
|
||||
const IME_MODE_CACHE_TTL_MS = 400
|
||||
|
||||
let api: Win32Api | null = null
|
||||
let loadFailed = false
|
||||
const processPathCache = new Map<number, string | null>()
|
||||
let imeModeCache: { hwnd: number; korean: boolean | null; at: number } | null = null
|
||||
|
||||
export function invalidateKoreanImeCache(): void {
|
||||
imeModeCache = null
|
||||
}
|
||||
|
||||
function loadApi(): Win32Api | null {
|
||||
if (api) return api
|
||||
|
|
@ -188,27 +196,38 @@ export function getForegroundWindowInfo(): ForegroundWindowInfo | null {
|
|||
: null
|
||||
|
||||
let appPath: string | null = null
|
||||
const processHandle = a.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId) as
|
||||
| bigint
|
||||
| number
|
||||
| null
|
||||
if (processHandle) {
|
||||
try {
|
||||
const sizeBuffer = Buffer.alloc(4)
|
||||
sizeBuffer.writeUInt32LE(PATH_BUFFER_CHARS, 0)
|
||||
const pathBuffer = Buffer.alloc(PATH_BUFFER_CHARS * 2)
|
||||
const pathOk = a.QueryFullProcessImageNameW(
|
||||
processHandle,
|
||||
0,
|
||||
pathBuffer,
|
||||
sizeBuffer
|
||||
) as boolean
|
||||
if (pathOk) {
|
||||
const length = sizeBuffer.readUInt32LE(0)
|
||||
appPath = a.koffi.decode(pathBuffer, 'char16_t', length).replace(/\0.*$/su, '')
|
||||
if (processId > 0 && processPathCache.has(processId)) {
|
||||
appPath = processPathCache.get(processId) ?? null
|
||||
} else if (processId > 0) {
|
||||
const processHandle = a.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId) as
|
||||
| bigint
|
||||
| number
|
||||
| null
|
||||
if (processHandle) {
|
||||
try {
|
||||
const sizeBuffer = Buffer.alloc(4)
|
||||
sizeBuffer.writeUInt32LE(PATH_BUFFER_CHARS, 0)
|
||||
const pathBuffer = Buffer.alloc(PATH_BUFFER_CHARS * 2)
|
||||
const pathOk = a.QueryFullProcessImageNameW(
|
||||
processHandle,
|
||||
0,
|
||||
pathBuffer,
|
||||
sizeBuffer
|
||||
) as boolean
|
||||
if (pathOk) {
|
||||
const length = sizeBuffer.readUInt32LE(0)
|
||||
appPath = a.koffi.decode(pathBuffer, 'char16_t', length).replace(/\0.*$/su, '')
|
||||
}
|
||||
} finally {
|
||||
a.CloseHandle(processHandle)
|
||||
}
|
||||
} finally {
|
||||
a.CloseHandle(processHandle)
|
||||
}
|
||||
if (appPath) {
|
||||
if (processPathCache.size >= PROCESS_PATH_CACHE_MAX) {
|
||||
const firstKey = processPathCache.keys().next().value
|
||||
if (firstKey !== undefined) processPathCache.delete(firstKey)
|
||||
}
|
||||
processPathCache.set(processId, appPath)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -241,6 +260,11 @@ export function isForegroundKoreanIme(foregroundHwnd?: number | null): boolean |
|
|||
const fg = Number(rawFg ?? 0)
|
||||
if (!Number.isFinite(fg) || fg <= 0) return null
|
||||
|
||||
const now = Date.now()
|
||||
if (imeModeCache && imeModeCache.hwnd === fg && now - imeModeCache.at < IME_MODE_CACHE_TTL_MS) {
|
||||
return imeModeCache.korean
|
||||
}
|
||||
|
||||
const pidBuffer = Buffer.alloc(4)
|
||||
const tid = Number(a.GetWindowThreadProcessId(fg, pidBuffer) ?? 0)
|
||||
let targetHwnd = fg
|
||||
|
|
@ -268,7 +292,10 @@ export function isForegroundKoreanIme(foregroundHwnd?: number | null): boolean |
|
|||
}
|
||||
|
||||
const imeWnd = Number((a.ImmGetDefaultIMEWnd(targetHwnd) as bigint | number | null) ?? 0)
|
||||
if (!Number.isFinite(imeWnd) || imeWnd <= 0) return null
|
||||
if (!Number.isFinite(imeWnd) || imeWnd <= 0) {
|
||||
imeModeCache = { hwnd: fg, korean: null, at: now }
|
||||
return null
|
||||
}
|
||||
|
||||
const convOut = [0]
|
||||
const convRes = a.SendMessageTimeoutW(
|
||||
|
|
@ -277,13 +304,18 @@ export function isForegroundKoreanIme(foregroundHwnd?: number | null): boolean |
|
|||
IMC_GETCONVERSIONMODE,
|
||||
0,
|
||||
SMTO_ABORTIFHUNG,
|
||||
30,
|
||||
8,
|
||||
convOut
|
||||
)
|
||||
if (Number(convRes) === 0) return null
|
||||
if (Number(convRes) === 0) {
|
||||
imeModeCache = { hwnd: fg, korean: null, at: now }
|
||||
return null
|
||||
}
|
||||
// Windows 한국어 IME(TSF/Chromium 포함)는 한/영('가'/'A') 상태를 IMC_GETOPENSTATUS 가 아니라
|
||||
// IMC_GETCONVERSIONMODE 의 IME_CMODE_NATIVE(0x0001) 비트로 나타낸다.
|
||||
return (Number(convOut[0]) & IME_CMODE_NATIVE) !== 0
|
||||
const korean = (Number(convOut[0]) & IME_CMODE_NATIVE) !== 0
|
||||
imeModeCache = { hwnd: fg, korean, at: now }
|
||||
return korean
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
|
@ -293,4 +325,6 @@ export function isForegroundKoreanIme(foregroundHwnd?: number | null): boolean |
|
|||
export function resetWin32ForegroundForTests(): void {
|
||||
api = null
|
||||
loadFailed = false
|
||||
processPathCache.clear()
|
||||
imeModeCache = null
|
||||
}
|
||||
36
apps/desktop/src/main/utils/win32-input-activity.ts
Normal file
36
apps/desktop/src/main/utils/win32-input-activity.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
import { getLogger } from '../services/LoggerService'
|
||||
|
||||
const logger = getLogger('win32-input-activity')
|
||||
|
||||
// LASTINPUTINFO is two DWORDs on both 32-bit and 64-bit Windows.
|
||||
const LAST_INPUT_INFO_SIZE = 8
|
||||
type GetLastInputInfoFn = (info: Buffer) => boolean
|
||||
|
||||
let getLastInputInfo: GetLastInputInfoFn | null = null
|
||||
let loadFailed = false
|
||||
|
||||
/**
|
||||
* Session input token read directly from Windows, independent of queued JS hook callbacks.
|
||||
* dwTime is a system tick, not an epoch timestamp or monotonic sequence: compare equality only.
|
||||
* Unsupported platforms or unavailable native state return null; callers must not infer idle.
|
||||
*/
|
||||
export function getLastNativeInputTick(): number | null {
|
||||
if (process.platform !== 'win32' || loadFailed) return null
|
||||
try {
|
||||
if (!getLastInputInfo) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const koffi = require('koffi') as {
|
||||
load: (library: string) => { func: (signature: string) => GetLastInputInfoFn }
|
||||
}
|
||||
getLastInputInfo = koffi.load('user32.dll').func('bool GetLastInputInfo(_Inout_ void *plii)')
|
||||
}
|
||||
const info = Buffer.alloc(LAST_INPUT_INFO_SIZE)
|
||||
info.writeUInt32LE(LAST_INPUT_INFO_SIZE, 0)
|
||||
if (!getLastInputInfo(info)) return null
|
||||
return info.readUInt32LE(4)
|
||||
} catch (error) {
|
||||
loadFailed = true
|
||||
logger.warn(`Windows 입력 시각 조회 실패: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@
|
|||
// IME 상태를 타지 않고 클립보드도 전혀 건드리지 않는다.
|
||||
|
||||
import { getLogger } from '../services/LoggerService'
|
||||
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
|
||||
|
||||
const logger = getLogger('win32-unicode-input')
|
||||
|
||||
|
|
@ -110,9 +111,30 @@ function writeUnicodeKeyPair(buffer: Buffer, pairIndex: number, codeUnit: number
|
|||
buffer.writeUInt32LE(KEYEVENTF_UNICODE | KEYEVENTF_KEYUP, upBase + unionOffset + 4)
|
||||
}
|
||||
|
||||
/** Only zero inserted events are safe to retry through another input backend. */
|
||||
function sendInputBatch(sendInput: SendInputFn, totalEvents: number, buffer: Buffer): boolean {
|
||||
let sent: number
|
||||
try {
|
||||
sent = sendInput(totalEvents, buffer, inputStructSize)
|
||||
} catch (error) {
|
||||
// A native-call exception does not prove that the input stream was untouched.
|
||||
throw new D3ROError(
|
||||
ErrorCode.TextInsertKeySimulationFailed,
|
||||
`SendInput failed with an unknown insertion result; retry blocked: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
}
|
||||
if (sent === totalEvents) return true
|
||||
if (sent === 0) return false
|
||||
// Replaying a partially applied batch can delete the user's next word or duplicate text.
|
||||
throw new D3ROError(
|
||||
ErrorCode.TextInsertKeySimulationFailed,
|
||||
`SendInput inserted ${sent}/${totalEvents} events; retry blocked to preserve existing input`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* UTF-16 문자열을 Windows SendInput(KEYEVENTF_UNICODE) 호출 한 번으로 입력 큐에 넣는다.
|
||||
* 성공 시 true, 지원하지 않거나 실패 시 false 를 반환한다.
|
||||
* 성공 시 true, 미지원 또는 입력 0건이면 false. 일부 입력/결과 불명은 재시도하지 않도록 예외를 던진다.
|
||||
*/
|
||||
export function sendWin32UnicodeText(text: string): boolean {
|
||||
if (!text) return true
|
||||
|
|
@ -128,9 +150,9 @@ export function sendWin32UnicodeText(text: string): boolean {
|
|||
writeUnicodeKeyPair(buffer, i, text.charCodeAt(i))
|
||||
}
|
||||
|
||||
const sent = sendInput(totalEvents, buffer, inputStructSize)
|
||||
return sent === totalEvents
|
||||
return sendInputBatch(sendInput, totalEvents, buffer)
|
||||
} catch (error) {
|
||||
if (error instanceof D3ROError) throw error
|
||||
logger.warn(`SendInput(KEYEVENTF_UNICODE) 실행 실패: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return false
|
||||
}
|
||||
|
|
@ -138,10 +160,11 @@ export function sendWin32UnicodeText(text: string): boolean {
|
|||
|
||||
/**
|
||||
* (선택적 IME 조합 확정 Space) + 커서 앞 백스페이스 N번 + UTF-16 문자열 입력을
|
||||
* 단 한 번의 Windows SendInput 호출로 원자적(atomic)으로 주입한다.
|
||||
* 단 한 번의 Windows SendInput 호출로 입력 큐에 연속해서 주입한다.
|
||||
*
|
||||
* Win32 SendInput 규약상 단일 호출 안의 INPUT 배열 사이에 사용자의 물리 키 입력이 끼어들 수 없으므로,
|
||||
* 빠른 타이핑 도중에도 지우기와 다시 쓰기가 경쟁하지 않고 < 0.5ms 안에 끝난다.
|
||||
* 배치 내부의 순서만 보장한다. 이전 스냅샷 이후 바뀐 커서/텍스트, 대상 앱의 처리 시간,
|
||||
* IME 상태까지 보장하지 않는다. 일부 입력만 성공하면 삭제/입력 배치를 재실행하지 않는다.
|
||||
*/
|
||||
export function sendWin32UnicodeReplacement(
|
||||
deleteCount: number,
|
||||
|
|
@ -177,9 +200,9 @@ export function sendWin32UnicodeReplacement(
|
|||
pairCursor += 1
|
||||
}
|
||||
|
||||
const sent = sendInput(totalEvents, buffer, inputStructSize)
|
||||
return sent === totalEvents
|
||||
return sendInputBatch(sendInput, totalEvents, buffer)
|
||||
} catch (error) {
|
||||
if (error instanceof D3ROError) throw error
|
||||
logger.warn(
|
||||
`SendInput(atomic replacement) 실행 실패: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue