d3ro-voice/apps/desktop/src/renderer/components/OnboardingModal.tsx
Yun Chan 7fe49c437e chore: land in-progress workspace changes before 1.16.2
The tree carried uncommitted work from several areas (web push, mobile
screens, admin charts, test-hygiene cleanup, CI and map docs). It is landed
as one commit so the release pipeline can start from a clean tree; the
desktop transcript-correction behaviour shipped in the previous commit and
is unchanged here.
2026-11-05 21:58:44 +09:00

606 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// src/renderer/components/OnboardingModal.tsx
// 첫 실행 온보딩 — 3단계: ① 사용 방식 선택(로컬 Ollama / 온라인 계정) ② 준비(Ollama 연결·모델 또는 로그인) ③ 완료.
// v4(2026-09-28): 평면 다이얼로그 + 단계 표시(n/3, 진행 막대) + "나중에 설정" 건너뛰기.
// 첫 실행은 Esc·배경 클릭으로 닫히지 않는다(onboarding-dismiss 정책) — 대신 명시적인 건너뛰기 버튼이 있다.
import { useState, useEffect, useCallback } from 'react'
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
Typography,
Box,
LinearProgress,
TextField,
Tab,
Tabs,
Alert,
} from '@mui/material'
import { CheckCircle2, Cloud, Download, Play, RefreshCw, ExternalLink, Cpu, Check } from 'lucide-react'
import { d3roPalette, d3roRadius, d3roNumeralSx, d3roTransition, typoSx } from '@d3ro/ui/theme'
import { Led, TactileBadge } from '@d3ro/ui/components/ds'
import { useI18n } from '@d3ro/i18n'
import type { TranslationKey } from '@d3ro/i18n'
import type { LLMModel, LLMStatus } from '@d3ro/core/types'
import { useOllamaModelPull } from '../hooks/useOllamaModelPull'
import { canDismissOnboarding } from './onboarding-dismiss'
import type { OnboardingPhase } from './onboarding-dismiss'
type Phase = OnboardingPhase
interface OnboardingModalProps {
open: boolean
onClose: () => void
}
/** 첫 실행에서 받는 기본 로컬 모델 */
const DEFAULT_LOCAL_MODEL = 'gemma4:e4b'
const AUTH_FORM_ID = 'onboarding-auth-form'
const TOTAL_STEPS = 3
const STEP_OF_PHASE: Readonly<Record<Phase, number>> = {
select_mode: 1,
local_ollama_setup: 2,
online_auth: 2,
failed: 2,
success: 3,
}
const LOCAL_POINTS: readonly TranslationKey[] = [
'onboarding.mode.local.point1',
'onboarding.mode.local.point2',
'onboarding.mode.local.point3',
]
const ONLINE_POINTS: readonly TranslationKey[] = [
'onboarding.mode.online.point1',
'onboarding.mode.online.point2',
'onboarding.mode.online.point3',
]
interface ModeCardProps {
icon: React.ReactNode
title: string
badge?: string
description: string
points: readonly string[]
action: React.ReactNode
onSelect: () => void
testId: string
}
/** 사용 방식 카드 — 카드 전체를 눌러도, 안의 버튼(키보드 포커스·Enter)으로도 고를 수 있다. */
function ModeCard({ icon, title, badge, description, points, action, onSelect, testId }: ModeCardProps): React.ReactElement {
return (
<Box
onClick={onSelect}
data-testid={testId}
sx={{
p: 2.5,
cursor: 'pointer',
borderRadius: d3roRadius.card,
border: `1px solid ${d3roPalette.border.default}`,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
gap: 2,
transition: d3roTransition('background-color', 'border-color'),
'&:hover': { bgcolor: d3roPalette.surface.overlaySoft, borderColor: d3roPalette.border.strong },
}}
>
<Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
{icon}
<Typography component="h3" sx={{ ...typoSx('heading'), color: d3roPalette.text.primary }}>
{title}
</Typography>
{badge && <TactileBadge tone="accent">{badge}</TactileBadge>}
</Box>
<Typography sx={{ ...typoSx('compact'), color: d3roPalette.text.secondary, mb: 1.5 }}>{description}</Typography>
<Box component="ul" sx={{ m: 0, p: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 0.75 }}>
{points.map((point) => (
<Box component="li" key={point} sx={{ display: 'flex', alignItems: 'flex-start', gap: 1 }}>
<Check size={14} color={d3roPalette.text.tertiary} style={{ marginTop: 3, flexShrink: 0 }} aria-hidden />
<Typography sx={{ ...typoSx('small'), color: d3roPalette.text.secondary }}>{point}</Typography>
</Box>
))}
</Box>
</Box>
{action}
</Box>
)
}
export function OnboardingModal({ open, onClose }: OnboardingModalProps): React.ReactElement {
const { t } = useI18n()
const [internalOpen, setInternalOpen] = useState(false)
const [phase, setPhase] = useState<Phase>('select_mode')
// 이미 온보딩을 마친 사용자면 모달을 언제든 닫을 수 있다(첫 실행만 진행을 강제).
const [onboardingCompleted, setOnboardingCompleted] = useState(false)
// Local Ollama State
const [ollamaStatus, setOllamaStatus] = useState<LLMStatus | null>(null)
const [installedModels, setInstalledModels] = useState<LLMModel[]>([])
const [activeModel, setActiveModel] = useState<string>(DEFAULT_LOCAL_MODEL)
const [checkingOllama, setCheckingOllama] = useState(false)
const [startingOllama, setStartingOllama] = useState(false)
const [ollamaMsg, setOllamaMsg] = useState<string | null>(null)
// Auth State
const [authTab, setAuthTab] = useState<'login' | 'register'>('login')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [authError, setAuthError] = useState('')
const [authLoading, setAuthLoading] = useState(false)
// Error State — 'failed' 단계는 현재 진입 경로가 없다(호환용으로 유지)
const errorMsg = ''
const isVisible = open || internalOpen
const checkOllama = useCallback(async () => {
setCheckingOllama(true)
try {
const res = await window.electronAPI.llm.checkConnection()
if (res.success && res.data) {
setInstalledModels(res.data.models)
}
const st = await window.electronAPI.llm.getStatus()
if (st.success) {
setOllamaStatus(st.data)
}
} finally {
setCheckingOllama(false)
}
}, [])
useEffect(() => {
window.electronAPI.config.getAll().then((res) => {
if (!res.success) return
setOnboardingCompleted(res.data.onboardingCompleted)
if (!res.data.onboardingCompleted) {
setInternalOpen(true)
setPhase('select_mode')
}
})
}, [])
// 모델 받기 — 받기에 성공한 경우에만 활성 모델로 저장 (autoSelect)
const {
pullingModelId: pullingModel,
progress: pullProgress,
error: pullError,
pull,
} = useOllamaModelPull({ enabled: isVisible, autoSelect: true, onPulled: checkOllama })
useEffect(() => {
if (!isVisible) return
const unsubStatus = window.electronAPI.llm.onStatusChanged((e) => {
setOllamaStatus(e.status)
})
return () => {
unsubStatus()
}
}, [isVisible])
const handleSelectLocalMode = async () => {
setPhase('local_ollama_setup')
await window.electronAPI.config.set({ key: 'appUsageMode', value: 'local' })
await window.electronAPI.config.set({ key: 'llmBackend', value: 'local' })
await window.electronAPI.config.set({ key: 'sttProvider', value: 'local' })
await checkOllama()
// 자동으로 Ollama 기동 시도
await window.electronAPI.llm.startServer()
setTimeout(() => checkOllama(), 1500)
}
const handleStartOllama = async () => {
setStartingOllama(true)
setOllamaMsg(null)
try {
const res = await window.electronAPI.llm.startServer()
if (res.success) {
if (res.data === 'running') {
setOllamaMsg(t('ollamaGuide.start.running'))
} else if (res.data === 'starting') {
setOllamaMsg(t('ollamaGuide.start.starting'))
setTimeout(() => checkOllama(), 2000)
} else if (res.data === 'not-installed') {
setOllamaMsg(t('ollamaGuide.start.notInstalled'))
} else {
setOllamaMsg(t('ollamaGuide.start.failed'))
}
}
} finally {
setStartingOllama(false)
}
}
const handlePullModel = async (modelId: string) => {
const outcome = await pull(modelId)
if (outcome === 'selected') setActiveModel(modelId)
}
const handleCompleteLocalSetup = async () => {
await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true })
setPhase('success')
}
const handleAuthSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setAuthError('')
setAuthLoading(true)
try {
const res = authTab === 'login'
? await window.electronAPI.onlineAuth.login({ email, password })
: await window.electronAPI.onlineAuth.register({ email, password })
if (res.success) {
await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' })
await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' })
await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true })
setPhase('success')
} else {
setAuthError(res.error?.message ?? t('onboarding.auth.failed'))
}
} catch (err) {
setAuthError(t('onboarding.auth.error', { message: err instanceof Error ? err.message : String(err) }))
} finally {
setAuthLoading(false)
}
}
const handleClose = () => {
setInternalOpen(false)
onClose()
}
// 첫 실행 건너뛰기 — 기본값(로컬 모드)으로 시작하고 다시 묻지 않는다. 설정 › 정보에서 다시 열 수 있다.
// Ollama 도 온라인 계정도 없는 사용자가 첫 실행에서 갇히지 않게 하는 출구.
const handleSkip = async () => {
await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true })
setOnboardingCompleted(true)
handleClose()
}
const dismissible = canDismissOnboarding(phase, onboardingCompleted)
const isOllamaConnected = ollamaStatus?.connectionState === 'connected'
const hasInstalledLlm = installedModels.length > 0
const step = STEP_OF_PHASE[phase]
const stepLabel = t('onboarding.step', { current: step, total: TOTAL_STEPS })
if (!isVisible) return <></>
const sectionBox = {
p: 2,
borderRadius: d3roRadius.inner,
border: `1px solid ${d3roPalette.border.subtle}`,
} as const
return (
<Dialog
open={isVisible}
onClose={dismissible ? handleClose : () => {}}
maxWidth="sm"
fullWidth
aria-labelledby="onboarding-title"
>
<DialogTitle id="onboarding-title" component="h2" sx={{ ...typoSx('title'), color: d3roPalette.text.primary, pb: 1 }}>
{t('onboarding.wizard.title')}
</DialogTitle>
{/* 단계 표시 — 숫자 + 진행 막대 */}
<Box sx={{ px: 3, pb: 2 }}>
<Typography sx={{ ...typoSx('small'), ...d3roNumeralSx, color: d3roPalette.text.tertiary, mb: 0.75 }}>
{stepLabel}
</Typography>
<LinearProgress
variant="determinate"
value={(step / TOTAL_STEPS) * 100}
aria-label={t('onboarding.wizard.progress')}
aria-valuetext={stepLabel}
sx={{ height: 2, borderRadius: 1 }}
/>
</Box>
<DialogContent sx={{ pt: 1, pb: 2 }}>
{/* ── 1. 사용 방식 선택 ── */}
{phase === 'select_mode' && (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<Typography sx={{ ...typoSx('body'), color: d3roPalette.text.secondary }}>
{t('onboarding.mode.intro')}
</Typography>
<Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', sm: '1fr 1fr' }, gap: 2 }}>
<ModeCard
icon={<Cpu size={18} color={d3roPalette.text.secondary} aria-hidden />}
title={t('onboarding.mode.local.title')}
badge={t('onboarding.mode.local.badge')}
description={t('onboarding.mode.local.desc')}
points={LOCAL_POINTS.map((key) => t(key))}
onSelect={handleSelectLocalMode}
testId="onboarding-mode-local"
action={
// 첫 포커스 — Enter 로 권장 경로를 바로 시작한다. 클릭은 카드 onClick 으로 전파된다.
<Button variant="contained" fullWidth autoFocus>
{t('onboarding.mode.local.action')}
</Button>
}
/>
<ModeCard
icon={<Cloud size={18} color={d3roPalette.text.secondary} aria-hidden />}
title={t('onboarding.mode.online.title')}
description={t('onboarding.mode.online.desc')}
points={ONLINE_POINTS.map((key) => t(key))}
onSelect={() => setPhase('online_auth')}
testId="onboarding-mode-online"
action={
<Button variant="outlined" fullWidth>
{t('onboarding.mode.online.action')}
</Button>
}
/>
</Box>
</Box>
)}
{/* ── 2a. 로컬 Ollama 준비 ── */}
{phase === 'local_ollama_setup' && (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{/* 연결 상태 — 실제로 조회한 값만 쓴다 */}
<Box sx={{ ...sectionBox, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 2, flexWrap: 'wrap' }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, minWidth: 0 }}>
<Led color={isOllamaConnected ? 'green' : 'orange'} pulse={checkingOllama} size={8} />
<Box role="status" sx={{ minWidth: 0 }}>
<Typography sx={{ ...typoSx('compact'), fontWeight: 500, color: d3roPalette.text.primary }}>
{isOllamaConnected
? ollamaStatus?.serverVersion
? t('onboarding.local.connectedVersion', { version: ollamaStatus.serverVersion })
: t('onboarding.local.connected')
: t('onboarding.local.disconnected')}
</Typography>
<Typography sx={{ ...typoSx('small'), color: d3roPalette.text.tertiary }}>
{isOllamaConnected
? t('onboarding.local.connectedDetail', { count: installedModels.length, model: activeModel })
: t('onboarding.local.disconnectedDetail')}
</Typography>
</Box>
</Box>
<Box sx={{ display: 'flex', gap: 1 }}>
<Button
size="small"
variant="outlined"
startIcon={<RefreshCw size={13} className={checkingOllama ? 'animate-spin' : ''} />}
onClick={checkOllama}
disabled={checkingOllama}
>
{t('onboarding.local.recheck')}
</Button>
{!isOllamaConnected && (
<Button
size="small"
variant="outlined"
startIcon={<Play size={13} />}
onClick={handleStartOllama}
disabled={startingOllama}
>
{t('onboarding.local.start')}
</Button>
)}
</Box>
</Box>
{ollamaMsg && (
<Alert severity={isOllamaConnected ? 'success' : 'info'} sx={{ py: 0.5 }}>
{ollamaMsg}
</Alert>
)}
{/* Ollama 미설치 시 안내 */}
{!isOllamaConnected && (
<Box sx={sectionBox}>
<Typography component="h3" sx={{ ...typoSx('compact'), fontWeight: 500, color: d3roPalette.text.primary, mb: 0.75 }}>
{t('onboarding.local.installTitle')}
</Typography>
<Typography sx={{ ...typoSx('small'), color: d3roPalette.text.secondary }}>
{t('onboarding.local.installStep1')}
</Typography>
<Typography sx={{ ...typoSx('small'), color: d3roPalette.text.secondary, mb: 1.5 }}>
{t('onboarding.local.installStep2')}
</Typography>
<Button
variant="outlined"
size="small"
endIcon={<ExternalLink size={14} />}
onClick={() => window.electronAPI.system.openExternal({ url: 'https://ollama.com/download' })}
>
{t('onboarding.local.openDownload')}
</Button>
</Box>
)}
{/* 기본 모델 받기 */}
<Box>
<Typography component="h3" sx={{ ...typoSx('compact'), fontWeight: 500, color: d3roPalette.text.primary, mb: 0.5 }}>
{t('onboarding.local.modelTitle', { model: DEFAULT_LOCAL_MODEL })}
</Typography>
<Typography sx={{ ...typoSx('small'), color: d3roPalette.text.tertiary, mb: 1.5 }}>
{t('onboarding.local.modelDesc')}
</Typography>
{pullingModel ? (
<Box sx={sectionBox}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
<Typography sx={{ ...typoSx('small'), color: d3roPalette.text.secondary }}>
{pullProgress.status || t('onboarding.statusPreparing')}
</Typography>
<Typography sx={{ ...typoSx('small'), ...d3roNumeralSx, color: d3roPalette.text.primary }}>
{pullProgress.percent}%
</Typography>
</Box>
<LinearProgress
variant="determinate"
value={pullProgress.percent}
aria-label={t('onboarding.local.pull', { model: pullingModel })}
sx={{ height: 4, borderRadius: 2 }}
/>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
{pullError && (
<Alert severity="error" sx={{ py: 0.5 }}>
{pullError.stage === 'pull'
? t('onboarding.failed', { message: pullError.message })
: pullError.message}
</Alert>
)}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
<Button
variant="outlined"
startIcon={<Download size={14} />}
onClick={() => handlePullModel(DEFAULT_LOCAL_MODEL)}
disabled={!isOllamaConnected}
>
{t('onboarding.local.pull', { model: DEFAULT_LOCAL_MODEL })}
</Button>
{hasInstalledLlm && (
<Typography sx={{ ...typoSx('small'), color: d3roPalette.status.success, display: 'flex', alignItems: 'center', gap: 0.5 }}>
<CheckCircle2 size={14} aria-hidden /> {t('onboarding.local.modelReady')}
</Typography>
)}
</Box>
</Box>
)}
</Box>
{!isOllamaConnected && (
<Typography sx={{ ...typoSx('small'), color: d3roPalette.text.tertiary }}>
{t('onboarding.local.finishHint')}
</Typography>
)}
</Box>
)}
{/* ── 2b. 온라인 계정 로그인 ── */}
{phase === 'online_auth' && (
<Box component="form" id={AUTH_FORM_ID} onSubmit={handleAuthSubmit}>
<Typography sx={{ ...typoSx('body'), color: d3roPalette.text.secondary, mb: 2 }}>
{t('onboarding.auth.intro')}
</Typography>
<Tabs
value={authTab}
onChange={(_, v: 'login' | 'register') => setAuthTab(v)}
sx={{ mb: 2, borderBottom: `1px solid ${d3roPalette.border.subtle}` }}
>
<Tab label={t('login.signIn')} value="login" />
<Tab label={t('login.signUp')} value="register" />
</Tabs>
{authError && (
<Typography role="alert" sx={{ color: d3roPalette.status.danger, mb: 2, ...typoSx('small') }}>
{authError}
</Typography>
)}
<TextField
fullWidth
autoFocus
label={t('onboarding.auth.email')}
type="email"
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
sx={{ mb: 2 }}
/>
<TextField
fullWidth
label={t('onboarding.auth.password')}
type="password"
autoComplete={authTab === 'login' ? 'current-password' : 'new-password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</Box>
)}
{/* ── 3. 완료 ── */}
{phase === 'success' && (
<Box sx={{ textAlign: 'center', py: 3 }}>
<CheckCircle2 size={40} style={{ color: d3roPalette.status.success, margin: '0 auto 16px' }} aria-hidden />
<Typography component="h3" sx={{ ...typoSx('heading'), color: d3roPalette.text.primary, mb: 1 }}>
{t('onboarding.done.title')}
</Typography>
<Typography sx={{ ...typoSx('body'), color: d3roPalette.text.secondary, maxWidth: 440, mx: 'auto' }}>
{t('onboarding.done.desc')}
</Typography>
</Box>
)}
{phase === 'failed' && (
<Typography role="alert" sx={{ ...typoSx('body'), color: d3roPalette.status.danger, py: 2 }}>
{t('onboarding.failedPhase', { message: errorMsg })}
</Typography>
)}
</DialogContent>
{/* ── 하단 행동: 왼쪽 = 뒤로·건너뛰기·닫기, 오른쪽 = 이 단계의 주 행동 하나 ── */}
<DialogActions sx={{ px: 3, pb: 2.5, pt: 1.5, justifyContent: 'space-between', gap: 1, borderTop: `1px solid ${d3roPalette.border.subtle}` }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
{(phase === 'local_ollama_setup' || phase === 'online_auth') && (
<Button variant="text" onClick={() => setPhase('select_mode')}>
{t('common.back')}
</Button>
)}
{phase !== 'success' && !dismissible && (
<Button variant="text" onClick={handleSkip} title={t('onboarding.wizard.skipHint')}>
{t('onboarding.wizard.skip')}
</Button>
)}
{phase !== 'success' && dismissible && (
<Button variant="text" onClick={handleClose}>
{t('onboarding.close')}
</Button>
)}
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
{phase === 'local_ollama_setup' && (
<Button variant="contained" onClick={handleCompleteLocalSetup} disabled={!isOllamaConnected}>
{t('onboarding.local.finish')}
</Button>
)}
{phase === 'online_auth' && (
<Button type="submit" form={AUTH_FORM_ID} variant="contained" disabled={authLoading}>
{authLoading
? t('onboarding.auth.processing')
: authTab === 'login'
? t('onboarding.auth.submitLogin')
: t('onboarding.auth.submitRegister')}
</Button>
)}
{phase === 'failed' && (
<Button variant="contained" onClick={() => setPhase('select_mode')}>
{t('common.retry')}
</Button>
)}
{phase === 'success' && (
<Button variant="contained" onClick={handleClose} autoFocus>
{t('onboarding.done.start')}
</Button>
)}
</Box>
</DialogActions>
</Dialog>
)
}