feat(caption): let live captions use their own speech model

The speech engine now keeps an auxiliary model next to the dictation model
and transcribes with whichever the request names, reloading it once if the
engine restarted. Settings > STT gains a live-caption model so captions can
run on large-v3-turbo while dictation keeps its own model. The runtime
minimum rises to 1.7.0 because older engines would silently ignore the
model choice.

Suggestion paging moves to Up/Down: the page follows the selection and the
last item waits while more candidates are being generated. The Left/Right
page shortcuts are removed; they did nothing until a page had filled and
clash with Intel's display-rotation hotkeys.
This commit is contained in:
Yun Chan 2026-09-24 21:46:54 +09:00
parent 39b8e7448e
commit 4b0f685941
29 changed files with 222 additions and 234 deletions

View file

@ -210,14 +210,12 @@ async function initInputIntelligence(): Promise<void> {
sendToMainWindow(IPC_CHANNELS.SUGGESTION.STATE_CHANGED, state)
)
// 제안 수락/순환/페이지/닫기는 전역 키바인딩으로만 들어온다 — 오버레이는 포커스를 갖지 않는다.
// 제안 수락/순환/닫기는 전역 키바인딩으로만 들어온다 — 오버레이는 포커스를 갖지 않는다.
getKeyBindingService().on('triggered', (payload) => {
if (payload.type !== 'pressed') return
if (payload.actionId === 'suggestion-accept') void suggestion.accept()
else if (payload.actionId === 'suggestion-next') suggestion.next()
else if (payload.actionId === 'suggestion-prev') suggestion.previous()
else if (payload.actionId === 'suggestion-page-next') suggestion.pageNext()
else if (payload.actionId === 'suggestion-page-prev') suggestion.pagePrev()
else if (payload.actionId === 'suggestion-dismiss') suggestion.dismiss('dismissed')
})

View file

@ -75,6 +75,8 @@ class CaptionService extends EventEmitter {
private _systemTrack: StreamingCaptionTrack | null = null
/** 'auto' 언어일 때 첫 확정 결과로 고정한다 — 중간 결과마다 언어가 흔들리지 않게 */
private _sessionLanguage: string | null = null
/** 자막 전용 모델 (null 이면 받아쓰기 모델) */
private _captionModelId: string | null = null
private _refineQueue: CaptionSegment[] = []
private _refining = false
@ -126,6 +128,9 @@ class CaptionService extends EventEmitter {
// STT 초기화 (모델 로딩 — 시간 소요)
const sttService = getLocalSTTService()
await sttService.initialize()
// 자막 전용 모델을 골랐으면 받아쓰기 모델과 별도로 올려 둔다(보조 자리).
this._captionModelId = configGet('captionSttModelId') ?? null
if (this._captionModelId) await sttService.ensureAuxModel(this._captionModelId)
// 세션 초기화
this._sessionId = crypto.randomUUID()
@ -318,6 +323,7 @@ class CaptionService extends EventEmitter {
initialPrompt: opts.initialPrompt,
vadFilter: true,
partial: opts.partial,
modelId: this._captionModelId ?? undefined,
})
if (!opts.partial && configured === 'auto' && !this._sessionLanguage && result.text.trim() && result.language) {
this._sessionLanguage = result.language

View file

@ -6,7 +6,6 @@ import type { AppConfig, ConfigChangedEvent, KeyBinding, KeyBindingActionId, Key
import {
bindingsEqual,
createDefaultBindingMap,
detectBindingConflicts,
findActionSpec,
kb,
normalizeBinding,
@ -76,14 +75,12 @@ function bindingListEquals(a: readonly KeyBinding[], b: readonly KeyBinding[]):
}
/**
* 다음 문장 페이지 넘기기(최대 12개 순차 생성) 도입에 맞춰 제안 단축키를 옮긴다.
* 다음 문장 제안 단축키를 1.6.0 배치로 옮긴다.
*
* - 수락은 화살표(→)에서 Enter 로 옮긴다 — 화살표를 페이지 이동에 내주기 위해서다.
* - 닫기는 화살표(←)에서 Backspace 로 옮긴다(평범한 Esc 가 주 수단이 됐다).
* - 수락은 화살표(→)에서 Enter 로, 닫기는 화살표(←)에서 Backspace 로 옮긴다
* (평범한 Esc 가 주 수단이 됐다).
* - 사용자가 정확히 옛 기본값 그대로일 때만 옮긴다. 다른 키로 커스터마이즈했다면
* 절대 건드리지 않는다(설계 요구사항).
* - 새 페이지 이동 액션(suggestion-page-next/prev)의 기본값은, 위 이관 뒤에도 다른
* 액션과 충돌하지 않을 때만 켠다. 충돌하면 바인딩 없이 두고 경고를 남긴다.
* 절대 건드리지 않는다.
*/
function migrateSuggestionOverlayBindings(activeStore: ElectronStore<AppConfig>): void {
const raw = activeStore.store as unknown as Record<string, unknown>
@ -99,19 +96,6 @@ function migrateSuggestionOverlayBindings(activeStore: ElectronStore<AppConfig>)
migrateIfOldDefault('suggestion-accept', OLD_SUGGESTION_ACCEPT_DEFAULT)
migrateIfOldDefault('suggestion-dismiss', OLD_SUGGESTION_DISMISS_DEFAULT)
for (const actionId of ['suggestion-page-next', 'suggestion-page-prev'] as const) {
const candidate = bindings[actionId] ?? []
const hasConflict = candidate.some(
(binding) => detectBindingConflicts(actionId, binding, bindings).length > 0
)
if (hasConflict) {
logger.warn(
`${actionId} 기본 바인딩이 다른 액션과 충돌해 바인딩 없이 둔다 (사용자가 설정에서 직접 지정할 수 있다)`
)
bindings[actionId] = []
}
}
activeStore.set('keyBindings', bindings)
}
@ -187,6 +171,7 @@ const CONFIG_DEFAULTS: AppConfig = {
captionAudioSource: 'mic',
captionOverlayPosition: null,
captionRefineEnabled: true,
captionSttModelId: null,
updateChannel: 'latest',
updateDeviceId: '',
skippedUpdateVersion: null,

View file

@ -55,6 +55,10 @@ export interface TranscribeOptions {
vadFilter?: boolean
/** 음 중 실시간 미리보기 요청 — 상태/이벤트를 건드리지 않고 greedy 디코딩을 사용한다. */
partial?: boolean
/** 받아쓰기 모델 대신 쓸 모델 (ensureAuxModel 로 올려 둔 것) */
modelId?: string
/** 내부용 — 409 후 모델을 다시 올리고 재시도한 요청인지 */
retriedAfterLoad?: boolean
}
/** sidecar /health 응답 */
@ -204,6 +208,8 @@ class LocalSTTService extends EventEmitter {
private _sidecarStarting: Promise<void> | null = null
private _port: number = SIDECAR_PORT
private _currentModelId: string | null = null
/** 보조 자리에 올린 모델 (실시간 자막 전용 모델 등). 사이드카가 죽으면 함께 사라진다 */
private _auxModelId: string | null = null
private _restartCount: number = 0
private _disposed: boolean = false
private _gpuAccelerated: boolean = false
@ -547,6 +553,7 @@ class LocalSTTService extends EventEmitter {
this._audioBuffer = []
this._modelReady = false
this._auxModelId = null
await this._shutdownSidecar()
this._setState(STTState.Uninitialized)
@ -731,6 +738,7 @@ class LocalSTTService extends EventEmitter {
this._sidecarProcess = null
}
this._modelReady = false
this._auxModelId = null
if (!this._disposed) {
this._handleSidecarCrash()
@ -858,14 +866,25 @@ class LocalSTTService extends EventEmitter {
)
}
private async _loadModel(modelId: string): Promise<void> {
logger.info(`모델 로딩 시작: ${modelId}`)
/**
* 받아쓰기(기본) 모델과 다른 모델을 보조 자리에 올린다 — 실시간 자막처럼 따로 고른 모델용.
* 기본 모델과 같으면 아무것도 하지 않는다.
*/
async ensureAuxModel(modelId: string): Promise<void> {
await this._ensureSidecarRunning()
if (modelId === this._currentModelId || modelId === this._auxModelId) return
await this._loadModel(modelId, 'aux')
this._auxModelId = modelId
}
private async _loadModel(modelId: string, slot: 'primary' | 'aux' = 'primary'): Promise<void> {
logger.info(`모델 로딩 시작: ${modelId} (${slot})`)
const startTime = Date.now()
const response = await fetch(`${this._baseUrl}/load`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model_id: modelId }),
body: JSON.stringify({ model_id: modelId, slot }),
signal: AbortSignal.timeout(SIDECAR_REQUEST_TIMEOUT_MS),
})
@ -881,7 +900,7 @@ class LocalSTTService extends EventEmitter {
const loadTimeMs = Date.now() - startTime
const model = MODEL_CATALOG.find((m) => m.id === modelId)
if (model) {
if (model && slot === 'primary') {
this.emit('model-loaded', {
model: { ...model, downloaded: true },
loadTimeMs,
@ -937,6 +956,10 @@ class LocalSTTService extends EventEmitter {
if (initialPrompt) {
formData.append('initial_prompt', initialPrompt)
}
const modelId = options?.modelId
if (modelId && modelId !== this._currentModelId) {
formData.append('model_id', modelId)
}
const response = await fetch(`${this._baseUrl}/transcribe`, {
method: 'POST',
@ -946,6 +969,13 @@ class LocalSTTService extends EventEmitter {
),
})
// 사이드카가 재시작되며 보조 모델을 잃었으면 다시 올리고 한 번만 재시도한다.
if (response.status === 409 && modelId && !options?.retriedAfterLoad) {
this._auxModelId = null
await this.ensureAuxModel(modelId)
return this._sendToSidecar(audioBuffer, { ...options, retriedAfterLoad: true })
}
if (!response.ok) {
const errorText = await response.text()
throw new D3ROError(
@ -1042,6 +1072,7 @@ class LocalSTTService extends EventEmitter {
const modelToReload = this._currentModelId
this._currentModelId = null
this._modelReady = false
this._auxModelId = null
// setTimeout으로 이벤트 루프에 양보
setTimeout(() => {

View file

@ -74,10 +74,11 @@ const RUNTIME_VERSION_FILE = '.runtime-version'
/**
* 이 앱이 요구하는 런타임 최소 버전. 사이드카 API 가 바뀔 때만 올린다.
* 1.5.0 — UIA 브리지(`/uia/focus`)가 처음 들어간 사이드카. ffmpeg 는 CLI 가 안정적이라 확인하지 않는다.
* 1.5.0 — UIA 브리지(`/uia/focus`). 1.7.0 — 보조 모델 자리(`/load` slot, `/transcribe` model_id).
* ffmpeg 는 CLI 가 안정적이라 확인하지 않는다.
*/
const RUNTIME_MIN_VERSION: Record<RuntimeComponent, string | null> = {
sidecar: '1.5.0',
sidecar: '1.7.0',
ffmpeg: null
}
const DOWNLOAD_TIMEOUT_MS = 120_000

View file

@ -1000,6 +1000,7 @@ class SuggestionService extends EventEmitter {
if (token !== this._generationToken || this._isDuplicateCandidate(candidateText)) return false
this._candidates.push({ text: candidateText, rank: this._candidates.length })
logger.debug(`제안 후보 추가 ${this._candidates.length}/${SUGGESTION_DEFAULTS.maxCandidatesTotal}`)
this._armVisibleTtl()
this.emit('updated', this.getState())
this._record({
@ -1176,26 +1177,17 @@ class SuggestionService extends EventEmitter {
return this.getState()
}
/**
* 다음 후보로 — 페이지는 활성 후보를 따라 넘어간다.
*
* 마지막 후보에서 아직 더 만드는 중이면 그 자리에 머문다: 처음으로 돌아가 버리면
* 곧 도착할 후보를 보려던 사용자가 길을 잃는다. 다 만들었으면 처음으로 돌아간다.
*/
next(): SuggestionState {
if (this._candidates.length > 1) {
this._moveActive((this._activeIndex + 1) % this._candidates.length)
}
return this.getState()
}
/** 다음 페이지의 첫 항목으로 — 그 페이지에 후보가 없으면 그대로 둔다. */
pageNext(): SuggestionState {
const pageSize = SUGGESTION_DEFAULTS.pageSize
const totalPages = Math.ceil(this._candidates.length / pageSize)
const currentPage = Math.floor(this._activeIndex / pageSize)
if (currentPage < totalPages - 1) this._moveActive((currentPage + 1) * pageSize)
return this.getState()
}
/** 이전 페이지의 첫 항목으로 — 이미 첫 페이지면 그대로 둔다. */
pagePrev(): SuggestionState {
const currentPage = Math.floor(this._activeIndex / SUGGESTION_DEFAULTS.pageSize)
if (currentPage > 0) this._moveActive((currentPage - 1) * SUGGESTION_DEFAULTS.pageSize)
const last = this._candidates.length - 1
if (last < 1) return this.getState()
if (this._activeIndex < last) this._moveActive(this._activeIndex + 1)
else if (!this._filling) this._moveActive(0)
return this.getState()
}

View file

@ -84,7 +84,6 @@ function getPopupI18nStrings(): Record<string, string> {
suggestionAppPhrases: t('popup.suggestion.appPhrases'),
// 키 힌트 줄 (동작 낱말 — 실제 키는 사용자 바인딩에서 매번 계산해 붙인다)
suggestionHintMoveLabel: t('popup.suggestion.hintMove'),
suggestionHintPageLabel: t('popup.suggestion.hintPage'),
suggestionHintAcceptLabel: t('popup.suggestion.hintAccept'),
suggestionHintCloseLabel: t('popup.suggestion.hintDismiss'),
suggestionHintGeneratingMore: t('popup.suggestion.hintGeneratingMore'),
@ -113,10 +112,9 @@ function sameModifiers(a: readonly string[], b: readonly string[]): boolean {
}
export interface SuggestionKeyHints {
/** 이동·페이지·수락이 모두 같은 수정자를 쓰면 그 수정자(예: "Ctrl+Alt") — 한 번만 보여준다 */
/** 이동·수락이 모두 같은 수정자를 쓰면 그 수정자(예: "Ctrl+Alt") — 한 번만 보여준다 */
shared: string | null
move: string | null
page: string | null
accept: string | null
close: string
}
@ -139,11 +137,9 @@ function buildSuggestionKeyHints(): SuggestionKeyHints {
const prev = splitOf('suggestion-prev')
const next = splitOf('suggestion-next')
const pagePrev = splitOf('suggestion-page-prev')
const pageNext = splitOf('suggestion-page-next')
const accept = splitOf('suggestion-accept')
const present = [prev, next, pagePrev, pageNext, accept].filter((b): b is SplitBinding => b !== null)
const present = [prev, next, accept].filter((b): b is SplitBinding => b !== null)
const common = present[0]?.modifiers ?? []
const shareAll =
present.length > 0 && common.length > 0 && present.every((b) => sameModifiers(b.modifiers, common))
@ -159,7 +155,6 @@ function buildSuggestionKeyHints(): SuggestionKeyHints {
return {
shared: shareAll ? joinBindingSegments(common, platform) : null,
move: pair(prev, next),
page: pair(pagePrev, pageNext),
accept: accept ? label(accept) : null,
close: 'Esc'
}

View file

@ -51,6 +51,9 @@ import type {
} from '@d3ro/core/types'
import { CodexOAuthGuideModal } from './CodexOAuthGuideModal'
/** 자막 모델 선택지 "받아쓰기와 같게" — 설정에는 null 로 저장한다 */
const SAME_AS_DICTATION = '__same__'
interface STTTabProps {
config: Partial<AppConfig>
updateConfig: (key: keyof AppConfig, value: AppConfig[keyof AppConfig]) => void
@ -362,6 +365,30 @@ export function STTTab({ config, updateConfig }: STTTabProps): React.ReactElemen
</Select>
</FormControl>
{/* 실시간 자막 전용 모델 — 1초마다 다시 인식하므로 받아쓰기와 다른 모델이 나을 수 있다 */}
<FormControl size="small" fullWidth>
<InputLabel>{t('settings.captionModel')}</InputLabel>
<Select
label={t('settings.captionModel')}
value={config.captionSttModelId ?? SAME_AS_DICTATION}
onChange={(e) =>
updateConfig('captionSttModelId', e.target.value === SAME_AS_DICTATION ? null : e.target.value)
}
>
<MenuItem value={SAME_AS_DICTATION}>{t('settings.captionModel.same')}</MenuItem>
{localModels
.filter((m) => m.downloaded)
.map((m) => (
<MenuItem key={m.id} value={m.id}>
{m.name}
</MenuItem>
))}
</Select>
<Typography sx={{ mt: 0.5, fontSize: d3roTypo.meta.size, color: d3roPalette.text.secondary }}>
{t('settings.captionModel.desc')}
</Typography>
</FormControl>
{/* 모델 다운로드 진행 바 또는 다운로드 버튼 */}
{(() => {
const selected = localModels.find((m) => m.id === (config.sttModelId ?? 'large-v3-turbo'))

View file

@ -143,7 +143,7 @@
keyHintsContainer.textContent = ''
if (!keyHints) return
// 이동·페이지·수락이 같은 수정자를 쓰면 앞에 한 번만 보여준다 ("Ctrl+Alt +").
// 이동·수락이 같은 수정자를 쓰면 앞에 한 번만 보여준다 ("Ctrl+Alt +").
if (keyHints.shared) {
var shared = document.createElement('span')
shared.className = 'key-hint shared'
@ -154,7 +154,6 @@
var entries = [
[keyHints.move, i18nStrings.suggestionHintMoveLabel, ''],
[keyHints.page, i18nStrings.suggestionHintPageLabel, ''],
[keyHints.accept, i18nStrings.suggestionHintAcceptLabel, ''],
[keyHints.close, i18nStrings.suggestionHintCloseLabel, ' close-hint']
]