// src/renderer/components/SettingsModal.tsx
// 설정 화면 — v4(2026-09-28)부터 모달이 아니라 메인 창의 전체 화면 라우트로 렌더된다(이름은 호환용으로 유지).
// open 은 "이 화면이 현재 보이는가" — 보일 때만 설정·장치·모델을 불러온다. onClose 는 이전 화면으로 돌아간다.
// 본문 문법: 구획(h3 + 1px 선) 안에 설정 행(왼쪽 라벨·설명, 오른쪽 컨트롤) — settings/SettingsRows.
import { useState, useEffect, useCallback, useMemo } from 'react'
import {
Tabs,
Tab,
Box,
TextField,
Select,
MenuItem,
Switch,
FormControlLabel,
Typography,
FormControl,
Button,
} from '@mui/material'
import { Keyboard, Mic, Lock, Cloud, RefreshCw, Play, HelpCircle, TextCursorInput } from 'lucide-react'
import { d3roPalette, d3roRadius, d3roTransition, d3roTypo, typoSx } from '@d3ro/ui/theme'
import { Led } from '@d3ro/ui/components/ds'
import { LicenseTab } from './LicenseTab'
import { CloudSyncSection } from './CloudSyncSection'
import { STTTab } from './STTTab'
import { CaptionModelSelect } from './CaptionModelSelect'
import { InputConsentPanel } from './input-insights/InputConsentPanel'
import { KeyBindingField } from './keybinding/KeyBindingField'
import { asTranslationKey } from './keybinding/translation-key'
import { SettingNote, SettingRow, SettingsSection, SETTING_CONTROL_WIDTH } from './settings/SettingsRows'
import { UpdateSection } from './settings/UpdateSection'
import { useI18n, LOCALE_META } from '@d3ro/i18n'
import type { Locale } from '@d3ro/i18n'
import type { KeyBindingActionGroup } from '@d3ro/core/keybinding'
import { auditKeyBindingMap, KEYBINDING_ACTIONS } from '@d3ro/core/keybinding'
import type { ThemeMode, AppConfig, AudioDevice, LLMModel, LLMStatus, STTModel } from '@d3ro/core/types'
import { useKeyBindingMap } from '../hooks/useKeyBindingMap'
import { DEFAULT_SETTINGS_TAB, SETTINGS_TAB_ORDER } from '../navigation/settingsTabs'
import type { SettingsTabId } from '../navigation/settingsTabs'
interface SettingsModalProps {
open: boolean
initialTab?: SettingsTabId
onClose: () => void
}
interface TabPanelProps {
children: React.ReactNode
value: SettingsTabId
tab: SettingsTabId
}
function TabPanel({ children, value, tab }: TabPanelProps): React.ReactElement | null {
if (value !== tab) return null
return {children}
}
/** 행 오른쪽 Select·TextField 공통 폭 */
const controlSx = { width: SETTING_CONTROL_WIDTH, maxWidth: '100%' } as const
/** 행 오른쪽 스위치 — 라벨은 행 왼쪽 글자(aria-labelledby)가 맡는다. */
function RowSwitch({
labelId,
checked,
onChange,
}: {
labelId: string
checked: boolean
onChange: (checked: boolean) => void
}): React.ReactElement {
return (
onChange(e.target.checked)}
inputProps={{ 'aria-labelledby': labelId }}
/>
)
}
// ── 액션 그룹 섹션 ─────────────────────────────────────
const ACTION_GROUP_LABEL_KEYS: Readonly> = {
voice: 'keybinding.ui.sectionVoice',
window: 'keybinding.ui.sectionWindow',
input: 'keybinding.ui.sectionInput',
}
const ACTION_GROUP_ORDER: readonly KeyBindingActionGroup[] = ['voice', 'window', 'input']
/** 설치된 모델이 없을 때도 고를 수 있게 보여 주는 기본 후보 */
const RECOMMENDED_OLLAMA_MODEL = 'gemma4:e4b'
const FALLBACK_OLLAMA_MODELS = ['llama3.2:3b', 'qwen2.5:3b'] as const
type OllamaFeedback = { tone: 'info' | 'error'; message: string }
export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose }: SettingsModalProps): React.ReactElement {
const { t, locale, setLocale } = useI18n()
const [activeTab, setActiveTab] = useState(initialTab)
const tabMeta = useMemo>(
() => ({
general: { label: t('settings.tabs.general'), icon: },
audio: { label: t('settings.tabs.audio'), icon: },
stt: { label: t('settings.tabs.stt') },
llm: { label: t('settings.tabs.llm') },
input: { label: t('input.tab'), icon: },
license: { label: t('license.nav'), icon: },
cloud: { label: t('settings.tabs.cloud'), icon: },
about: { label: t('settings.tabs.about') },
}),
[t],
)
const [config, setConfig] = useState>({})
const [loading, setLoading] = useState(true)
const [appVersion, setAppVersion] = useState(null)
const keybindingMap = useKeyBindingMap()
const keybindingIssues = useMemo(
() => (keybindingMap === null ? [] : auditKeyBindingMap(keybindingMap)),
[keybindingMap]
)
useEffect(() => {
if (open && initialTab !== undefined) {
setActiveTab(initialTab)
}
}, [open, initialTab])
useEffect(() => {
if (!open) return
let cancelled = false
void window.electronAPI.system.getVersion()
.then((result) => {
if (!cancelled && result.success) setAppVersion(result.data)
})
.catch(() => {
if (!cancelled) setAppVersion(null)
})
return () => {
cancelled = true
}
}, [open])
// 전역 단축키 on/off (개별 바인딩은 KeyBindingField 가 담당한다)
const [keybindingEnabled, setKeybindingEnabled] = useState(true)
// 오디오 디바이스
const [audioDevices, setAudioDevices] = useState([])
const [selectedDeviceId, setSelectedDeviceId] = useState('default')
const [micTesting, setMicTesting] = useState(false)
const [micLevel, setMicLevel] = useState(0)
const [micTestFailed, setMicTestFailed] = useState(false)
// 실시간 자막 모델 선택지 — 받아 둔 로컬 Whisper 모델만
const [downloadedSttModels, setDownloadedSttModels] = useState([])
useEffect(() => {
if (!open) return
window.electronAPI.stt.getModels().then((res) => {
if (res.success && res.data) setDownloadedSttModels(res.data.filter((m) => m.downloaded))
})
}, [open])
// Ollama 상태 — null 은 "아직 조회하지 않음"(연결됨/오프라인으로 단정하지 않는다)
const [ollamaStatus, setOllamaStatus] = useState(null)
const [ollamaModels, setOllamaModels] = useState([])
const [checkingOllama, setCheckingOllama] = useState(false)
const [startingOllama, setStartingOllama] = useState(false)
const [ollamaFeedback, setOllamaFeedback] = useState(null)
const refreshOllama = useCallback(async () => {
setCheckingOllama(true)
try {
const res = await window.electronAPI.llm.checkConnection()
if (res.success && res.data) {
setOllamaModels(res.data.models)
}
const st = await window.electronAPI.llm.getStatus()
if (st.success) setOllamaStatus(st.data)
} finally {
setCheckingOllama(false)
}
}, [])
// 설정 로드
useEffect(() => {
if (!open) return
setLoading(true)
refreshOllama()
Promise.all([
window.electronAPI.config.getAll(),
window.electronAPI.keybinding.isEnabled(),
])
.then(([configResult, enabledResult]) => {
if (configResult.success) setConfig(configResult.data)
if (enabledResult.success) setKeybindingEnabled(enabledResult.data)
})
.finally(() => setLoading(false))
Promise.all([
window.electronAPI.audio.getDevices(),
window.electronAPI.audio.getSelectedDevice(),
]).then(([devicesResult, selectedResult]) => {
if (devicesResult.success) setAudioDevices(devicesResult.data)
if (selectedResult.success && selectedResult.data) setSelectedDeviceId(selectedResult.data)
})
}, [open, refreshOllama])
const updateConfig = useCallback((key: keyof AppConfig, value: AppConfig[keyof AppConfig]) => {
setConfig((prev) => ({ ...prev, [key]: value }))
window.electronAPI.config.set({ key, value })
}, [])
const handleKeybindingToggle = useCallback((enabled: boolean) => {
setKeybindingEnabled(enabled)
void window.electronAPI.keybinding.setEnabled({ enabled })
}, [])
const handleLanguageChange = useCallback((newLocale: string) => {
setLocale(newLocale as Locale)
setConfig((prev) => ({ ...prev, language: newLocale }))
}, [setLocale])
const handleMicTest = useCallback(async () => {
if (micTesting) {
// 메인 프로세스 캡처까지 실제로 중지 — done 이벤트가 구독 해제를 마무리
await window.electronAPI.audio.stopTest()
setMicTesting(false)
setMicLevel(0)
return
}
setMicTesting(true)
setMicTestFailed(false)
setMicLevel(0)
// level 0은 무음/초기화 중일 뿐 — 종료 판정은 done 플래그로만
const unsub = window.electronAPI.audio.onTestLevel((e) => {
setMicLevel(e.level)
if (e.done) {
setMicTesting(false)
setMicLevel(0)
unsub()
}
})
const result = await window.electronAPI.audio.testDevice({ deviceId: selectedDeviceId })
if (!result.success) {
setMicTesting(false)
setMicLevel(0)
setMicTestFailed(true)
unsub()
}
}, [micTesting, selectedDeviceId])
const handleStartOllama = useCallback(async () => {
setStartingOllama(true)
setOllamaFeedback(null)
try {
const res = await window.electronAPI.llm.startServer()
if (!res.success) {
setOllamaFeedback({ tone: 'error', message: t('settings.llm.feedback.failed') })
} else if (res.data === 'running') {
setOllamaFeedback({ tone: 'info', message: t('settings.llm.feedback.running') })
} else if (res.data === 'starting') {
setOllamaFeedback({ tone: 'info', message: t('settings.llm.feedback.started') })
setTimeout(() => refreshOllama(), 2000)
} else if (res.data === 'not-installed') {
setOllamaFeedback({ tone: 'error', message: t('settings.llm.feedback.notInstalled') })
}
} finally {
setStartingOllama(false)
}
}, [refreshOllama, t])
if (loading) {
return (
{t('common.loading')}
)
}
const ollamaConnected = ollamaStatus?.connectionState === 'connected'
const ollamaStatusText =
ollamaStatus === null
? t('settings.llm.ollamaChecking')
: ollamaConnected
? ollamaStatus.serverVersion
? t('settings.llm.ollamaConnectedVersion', { version: ollamaStatus.serverVersion, count: ollamaModels.length })
: t('settings.llm.ollamaConnected', { count: ollamaModels.length })
: t('settings.llm.ollamaOffline')
const activeOllamaModel = config.llmModelId ?? RECOMMENDED_OLLAMA_MODEL
// v4: 설정은 모달이 아니라 전체 화면 — 왼쪽 세로 탭 + 오른쪽 한 열(읽기 폭 제한).
// 모달 폭 600px 에 탭 8개가 넘쳐 '클라우드·정보'가 잘리던 문제(2026-09-28 실측)를 구조로 해결한다.
return (
{t('settings.title')}
setActiveTab(v)}
aria-label={t('settings.title')}
sx={{
'& .MuiTabs-indicator': { display: 'none' },
'& .MuiTab-root': {
alignItems: 'center',
justifyContent: 'flex-start',
gap: 1,
minHeight: 36,
px: 1.5,
py: 0,
borderRadius: d3roRadius.button,
color: d3roPalette.text.secondary,
fontSize: d3roTypo.compact.size,
fontWeight: 400,
textAlign: 'left',
'&:hover': { color: d3roPalette.text.primary, bgcolor: d3roPalette.surface.overlaySoft },
'&.Mui-selected': { color: d3roPalette.text.primary, fontWeight: 500, bgcolor: d3roPalette.surface.overlayStrong },
'& svg': { margin: 0 },
},
}}
>
{SETTINGS_TAB_ORDER.map((tab) => (
))}
{tabMeta[activeTab].label}
{/* ── 일반 탭 ─────────────────────────────── */}
handleKeybindingToggle(e.target.checked)}
/>
}
label={
{t('keybinding.ui.globalEnabled')}
}
/>
}
description={
{keybindingIssues.length === 0
? t('keybinding.ui.auditClear')
: t('keybinding.ui.auditIssues', { count: keybindingIssues.length })}
{keybindingIssues.slice(0, 3).map((issue) => {
const action = KEYBINDING_ACTIONS.find((entry) => entry.id === issue.actionId)
const actionLabel = action ? t(asTranslationKey(action.labelKey)) : issue.actionId
const conflictLabels = issue.conflictActionIds
.map((actionId) => {
const conflict = KEYBINDING_ACTIONS.find((entry) => entry.id === actionId)
return conflict ? t(asTranslationKey(conflict.labelKey)) : actionId
})
.join(', ')
return (
{issue.kind === 'invalid'
? t('keybinding.ui.auditInvalid', {
action: actionLabel,
reason: issue.reasonKey ? t(asTranslationKey(issue.reasonKey)) : t('keybinding.ui.auditUnknown')
})
: t('keybinding.ui.auditConflict', { action: actionLabel, conflicts: conflictLabels })}
)
})}
}
>
{ACTION_GROUP_ORDER.map((group) => {
const actions = KEYBINDING_ACTIONS.filter((action) => action.group === group)
if (actions.length === 0) return null
return (
{t(asTranslationKey(ACTION_GROUP_LABEL_KEYS[group]))}
{actions.map((action) => (
))}
)
})}
}
/>
}
/>
updateConfig('closeToTray', checked)}
/>
}
/>
updateConfig('autoLaunch', checked)}
/>
}
/>
updateConfig('autoInsert', checked)}
/>
}
/>
updateConfig('soundEnabled', checked)}
/>
}
/>
{/* ── 오디오 탭 ────────────────────────────── */}
}
/>
{micTesting ? t('common.stop') : t('common.test')}
}
>
0.7 ? d3roPalette.status.warning : d3roPalette.accent.main,
transition: d3roTransition('width'),
}}
/>
{micTestFailed && (
{t('settings.micTest.failed')}
)}
}
/>
updateConfig('captionSttModelId', modelId)}
/>
updateConfig('captionRefineEnabled', checked)}
/>
}
/>
}
/>
{/* ── STT 탭 ───────────────────────────────── */}
{/* ── LLM 탭 ──────────────────────────────── */}
}
/>
{/* 로컬 Ollama */}
{config.llmBackend !== 'online' && (
<>
{ollamaStatus !== null && }
{ollamaStatusText}
}
control={
<>
}
onClick={refreshOllama}
disabled={checkingOllama}
>
{t('settings.llm.checkConnection')}
{ollamaStatus !== null && !ollamaConnected && (
}
onClick={handleStartOllama}
disabled={startingOllama}
>
{startingOllama ? t('settings.llm.startingOllama') : t('settings.llm.startOllama')}
)}
>
}
>
{ollamaFeedback && (
{ollamaFeedback.message}
)}
}
onClick={() => window.dispatchEvent(new CustomEvent('d3ro:open-ollama-guide'))}
>
{t('settings.llm.openGuide')}
}
/>
}
/>
updateConfig('ollamaServerUrl', e.target.value)}
size="small"
sx={controlSx}
inputProps={{ 'aria-labelledby': 'settings-ollama-url', spellCheck: false }}
/>
}
/>
>
)}
{/* 온라인 API */}
{config.llmBackend === 'online' && (
<>
updateConfig('onlineApiUrl', e.target.value)}
size="small"
sx={controlSx}
inputProps={{ 'aria-labelledby': 'settings-online-url', spellCheck: false }}
/>
}
/>
>
)}
}
/>
)['voiceCommandsEnabled'] as boolean ?? false}
onChange={(checked) => {
updateConfig('voiceCommandsEnabled' as keyof AppConfig, checked as never)
void window.electronAPI.voiceCommand.setEnabled({ enabled: checked })
}}
/>
}
/>
{
updateConfig('screenContextEnabled', checked)
void window.electronAPI.context.setEnabled({ enabled: checked })
}}
/>
}
/>
{/* ── 입력 인사이트 탭 ─────────────────────────── */}
{/* ── 라이선스 탭 ────────────────────────────── */}
{/* ── Cloud Sync 탭 ──────────────────────────── */}
{/* ── 정보 탭 ──────────────────────────────── */}
{appVersion === null ? '—' : `v${appVersion}`}
}
/>
{
window.electronAPI.config.set({
key: 'onboardingCompleted',
value: false,
})
onClose()
setTimeout(() => window.location.reload(), 300)
}}
>
{t('settings.about.restartOnboarding.action')}
}
/>
)
}