diff --git a/.agents/rules/desktop-app-execution-and-windows.md b/.agents/rules/desktop-app-execution-and-windows.md index f289da9d..2c58a9b2 100644 --- a/.agents/rules/desktop-app-execution-and-windows.md +++ b/.agents/rules/desktop-app-execution-and-windows.md @@ -5,7 +5,7 @@ - **현상**: 에이전트 서브쉘에서 Electron GUI 앱을 실행하면 프로세스는 정상 구동되고 로그도 정상(`Main window shown`)이지만, 사용자의 실제 모니터 화면(`WinSta0\Default`)에는 창이 물리적으로 보이지 않는다. - **규칙**: - 에이전트가 단독으로 GUI 창을 사용자 화면에 띄우려고 무리하게 백그라운드 구동을 반복하지 말 것. - - GUI 테스트/실행이 필요할 때는 사용자가 직접 외부 터미널 또는 파일 탐색기에서 `run-desktop.bat` 또는 `npm run dev --workspace=@d3ro/desktop`를 실행하도록 안내한다. + - GUI 테스트/실행이 필요할 때는 사용자가 직접 외부 터미널 또는 파일 탐색기에서 `run-desktop.bat` 또는 `pnpm --filter @d3ro/desktop dev`를 실행하도록 안내한다. ## 2. Electron 단일 인스턴스 잠금 (Single Instance Lock) & 사일런트 종료 방지 - **앱 식별자 명시**: `src/main/index.ts` 최상단에서 `app.requestSingleInstanceLock()` 호출 전에 반드시 `app.setName('d3ro-voice')`와 `app.setAppUserModelId('kr.twentyoz.d3ro-voice')`를 선언하여 일반 'Electron' 프로세스와의 식별자 충돌을 방지한다. diff --git a/.claude/skills/implement-phase/SKILL.md b/.claude/skills/implement-phase/SKILL.md index d9c7f9a9..6cc70ae6 100644 --- a/.claude/skills/implement-phase/SKILL.md +++ b/.claude/skills/implement-phase/SKILL.md @@ -42,24 +42,23 @@ allowed-tools: Read Write Edit Bash Glob Grep Agent ### V2 (Monorepo) 1. `packages/core/src/types/` 타입 정의 2. `packages/core/src/services/` 서비스 인터페이스 -3. 앱별 구현체 (`apps/desktop/`, `apps/web/`, `apps/mobile-rn/`) +3. 앱별 구현체 (`apps/desktop/`, `apps/web/`, `apps/mobile/`) 4. `packages/ui/` 공유 컴포넌트 5. `packages/i18n/` i18n 키 6. Supabase 마이그레이션 (필요 시) ## 3. 검증 ```bash -npm run typecheck # root npm workspaces +npm run typecheck # 또는 pnpm turbo typecheck npm run build ``` -## 4. 완료 후 체이닝 +## 4. 자동 체이닝 (완료 후) -구현 완료 시 다음을 순서대로 실행: +구현 완료 시 **자동으로** 다음을 순서대로 실행: 1. `/review-phase $ARGUMENTS` — 코드 리뷰 -2. 리뷰 GO → 관련 테스트와 전체 게이트 실행 -3. `docs/map/*`와 해당 SSOT 갱신 -4. 커밋·푸시는 사용자가 명시적으로 요청한 경우에만 실행 +2. 리뷰 GO → `/test-and-commit` — 테스트 + 커밋 +3. `memory/project_status.md` 갱신 (즉시) 유저가 중단을 요청하지 않는 한 끝까지 진행. diff --git a/.claude/skills/refactor-wave/SKILL.md b/.claude/skills/refactor-wave/SKILL.md index ce22926f..9aebd3bc 100644 --- a/.claude/skills/refactor-wave/SKILL.md +++ b/.claude/skills/refactor-wave/SKILL.md @@ -35,7 +35,7 @@ description: 대규모 리팩토링·코드 정리·SSOT 확립 워크플로우 | WS2 | 메인 프로세스 (`apps/desktop/src/main/services/`, preload, shared 타입, IPC) | | WS3 | 렌더러 UI (`apps/desktop/src/renderer/`, 화면별 분담) — **WS1 의존** | | WS4 | i18n (`packages/i18n/src/locales/`, t() 키 정리) | -| WS5 | 빌드/설정/팝업 (package.json, workspace/CI scripts, electron.vite.config, electron-builder.yml, Vanilla JS 팝업) | +| WS5 | 빌드/설정/팝업 (package.json, electron.vite.config, electron-builder.yml, turbo.json, Vanilla JS 팝업) | - 같은 파일을 두 워크스트림이 건드리면 충돌 → 분담 시 영역 명시 - WS3는 WS1 산출물(토큰 정의) 의존이라 1차 완료 후 발사 diff --git a/.env.example b/.env.example index 4a833811..bee11587 100644 --- a/.env.example +++ b/.env.example @@ -75,9 +75,6 @@ FCM_PROJECT_ID= WEBPUSH_VAPID_PUBLIC_KEY= WEBPUSH_VAPID_PRIVATE_KEY= WEBPUSH_SUBJECT= -# Browser bundle copy of the same public key. This is public by design and must -# match WEBPUSH_VAPID_PUBLIC_KEY; never expose the private key as NEXT_PUBLIC_*. -NEXT_PUBLIC_VAPID_PUBLIC_KEY= # Apple Push Notification service transport (Firebase-free). Token-based .p8 auth. APNS_KEY_ID= APNS_TEAM_ID= diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 81be11dc..8a657b55 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -62,11 +62,6 @@ jobs: npm run contract:check npm run release:metadata:test - - name: Supabase 마이그레이션 파일 정합성 - run: | - npm run check:migrations:test - npm run check:migrations - - name: 하드코딩 자격증명 검사 run: | npm run security:secrets:test @@ -79,11 +74,6 @@ jobs: npm run release:mobile:build-config:test npm run release:play:assets - - name: 테스트 위생 게이트 - run: | - npm run test:hygiene:test - npm run test:hygiene - - name: 린트 run: npm run lint @@ -130,9 +120,6 @@ jobs: - name: 어드민 빌드 run: npm run build --workspace=@d3ro/admin - - name: 웹앱 프로덕션 빌드 - run: npm run build --workspace=@d3ro/web - mobile-quality: name: 모바일 린트·타입·Jest runs-on: linux-builder diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 7b9cd5b4..55fe7289 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -32,8 +32,6 @@ lint-and-typecheck: - npm run release:metadata:test - npm run security:secrets:test - npm run security:secrets - - npm run test:hygiene:test - - npm run test:hygiene - npm run release:mobile:boundary:test - npm run release:mobile:config:test - npm run release:mobile:build-config:test diff --git a/AGENTS.md b/AGENTS.md index e20d5eb9..fcca68a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,15 +74,8 @@ These come from [`CLAUDE.md`](./CLAUDE.md) and are enforced here too: - Desktop: keep `app.setName('d3ro-voice')` + `app.setAppUserModelId` at the top; prevent dev silent exit. - Never hardcode secrets; production secrets are injected at build/CI time. Fail closed, never fake success. - Security-first: only defensive security work. -- **Tests**: behavior only (no private methods, call order, or CSS classes). Test names say what breaks: - `동작_시나리오_기대`. E2E is `*.spec.ts` (Playwright) and only for the critical journeys; everything else is - `*.test.ts(x)`. Never weaken/delete/skip a test to get green. -- **Protected journeys** (`apps/desktop/tests/e2e/{navigation,settings,onboarding,customer-support,records}.spec.ts`, - `apps/web/e2e/smoke.spec.ts`): do not edit assertions without a product-behavior reason in the commit body. -- **Test hygiene gate**: `npm run test:hygiene` rejects `.only`, reason-less `.skip()`, trivial assertions, - `isVisible()`-gated assertions, machine-specific paths, `waitForTimeout`, and `.e2e.test.ts` names. -Build/test commands: [`docs/map/02-infrastructure.md`](./docs/map/02-infrastructure.md) §3. Root: `npm run typecheck`, `npm run test`, `npm run lint`, `npm run test:hygiene`. Mobile: `npm --prefix apps/mobile-rn run lint|typecheck|test`. TDD policy: [`docs/tdd-red/06-repo-application.md`](./docs/tdd-red/06-repo-application.md). +Build/test commands: [`docs/map/02-infrastructure.md`](./docs/map/02-infrastructure.md) §3. Root: `npm run typecheck`, `npm run test`, `npm run lint`. Mobile: `npm --prefix apps/mobile-rn run lint|typecheck|test`. --- @@ -113,7 +106,6 @@ Full procedure and templates: [`docs/map/12-update-protocol.md`](./docs/map/12-u - [ ] Code implemented, wired end-to-end (no TODOs / placeholders / fake success). - [ ] Tests added/updated and passing; lint/typecheck clean on the touched scope. -- [ ] `npm run test:hygiene` clean; new behavior has a test that fails for the expected reason before the fix. - [ ] Relevant surface doc (`04`–`09`) updated if interfaces changed. - [ ] `10-feature-catalog.md` row updated (status per platform + anchors). - [ ] `11-gap-backlog.md` updated (closed/opened/external). diff --git a/CHANGELOG.md b/CHANGELOG.md index 0281cb2f..2cb99dd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,24 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- Prevent fast Han/Eng auto-correction from interleaving with the next keystroke; defer corrections during continuous bursts and apply the current trailing correction region together after typing pauses. + ### Planned - macOS / Linux support - Additional Whisper model management UI - Plugin system for custom pipelines -## [1.16.2] - 2026-11-05 - -> Published from an annotated tag. Installer and update metadata are served by the -> canonical Forgejo feed; no binaries are committed to this repository. - -### Added -- Meeting and live-caption transcription now use the vocabulary the app learned from your typing: dictionary words, pronunciations and frequently typed terms bias speech recognition before it runs, fix mistyped words as soon as each line is finalized (no model required), and are given to the local model when it polishes a line. -- Polished caption lines now reach the meeting transcript and the meeting screen instead of stopping inside the caption service, so the saved transcript carries the corrected text. - -### Fixed -- Learned vocabulary used to feed typing suggestions only, which is why transcripts kept mangling names and jargon the app already knew. - ## [1.16.1] - 2026-11-04 > Published from an annotated tag. Installer and update metadata are served by the diff --git a/CODEOWNERS b/CODEOWNERS deleted file mode 100644 index 1ddaf59e..00000000 --- a/CODEOWNERS +++ /dev/null @@ -1,11 +0,0 @@ -# 보호 수용 테스트 (Protected acceptance tests) -# -# 이 경로의 변경은 제품 행위가 바뀌었다는 뜻이다. 단정 삭제·약화·skip 은 -# 커밋 본문에 "왜 사용자가 하는 일이 바뀌었는가"를 적고 사람 리뷰를 받는다. -# 정책: docs/tdd-red/06-repo-application.md §5 - -/apps/desktop/tests/e2e/ @yunchan -/apps/web/e2e/ @yunchan -/apps/web/tests/ @yunchan -/docs/tdd-red/ @yunchan -/scripts/ci/check-test-hygiene.mjs @yunchan diff --git a/apps/admin-swagger/openapi.json b/apps/admin-swagger/openapi.json index e65af1e0..a159b01b 100644 --- a/apps/admin-swagger/openapi.json +++ b/apps/admin-swagger/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "D3RO-VOICE Admin API", "description": "Admin CRM Edge Functions for user management, subscription CRUD, payment history, and audit logs.", - "version": "1.16.2" + "version": "1.16.1" }, "servers": [ { diff --git a/apps/admin/package.json b/apps/admin/package.json index 8e59960a..9b2656fb 100644 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -1,13 +1,13 @@ { "name": "@d3ro/admin", - "version": "1.16.2", + "version": "1.16.1", "private": true, "description": "D3RO Voice Admin CRM — SaaS 관리 도구", "scripts": { "dev": "next dev --port 3001", "build": "next build", "start": "next start --port 3001", - "typecheck": "next typegen && tsc --noEmit" + "typecheck": "tsc --noEmit" }, "dependencies": { "@d3ro/api-client": "*", @@ -24,7 +24,8 @@ "lucide-react": "^1.33.0", "next": "16.3.1", "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "recharts": "^2.15.0" }, "devDependencies": { "@types/node": "^22.13.0", diff --git a/apps/admin/src/components/charts/dau-chart.tsx b/apps/admin/src/components/charts/dau-chart.tsx new file mode 100644 index 00000000..20ee032f --- /dev/null +++ b/apps/admin/src/components/charts/dau-chart.tsx @@ -0,0 +1,60 @@ +'use client' + +// apps/admin/src/components/charts/dau-chart.tsx +// DAU/활성 유저 추이 — Line chart + +import { + ResponsiveContainer, + LineChart, + Line, + XAxis, + YAxis, + CartesianGrid, + Tooltip, +} from 'recharts' +import { Box } from '@mui/material' +import { d3roPalette, d3roFontMono } from '@d3ro/ui/theme' + +interface DauRow { + date: string + active_users: number +} + +interface DauChartProps { + data: DauRow[] +} + +export function DauChart({ data }: DauChartProps): React.ReactElement { + return ( + + + + + val.slice(5)} + /> + + + + + + + ) +} diff --git a/apps/admin/src/components/charts/feature-usage-chart.tsx b/apps/admin/src/components/charts/feature-usage-chart.tsx new file mode 100644 index 00000000..820a6ef2 --- /dev/null +++ b/apps/admin/src/components/charts/feature-usage-chart.tsx @@ -0,0 +1,88 @@ +'use client' + +// apps/admin/src/components/charts/feature-usage-chart.tsx +// feature별 일간 API 호출 — StackedBar + +import { + ResponsiveContainer, + BarChart, + Bar, + XAxis, + YAxis, + CartesianGrid, + Tooltip, + Legend, +} from 'recharts' +import { Box } from '@mui/material' +import { d3roPalette, d3roFontMono } from '@d3ro/ui/theme' + +interface FeatureUsageRow { + date: string + feature: string + total_count: number + unique_users: number +} + +interface FeatureUsageChartProps { + data: FeatureUsageRow[] +} + +const FEATURE_COLORS: Record = { + llm_haiku: d3roPalette.accent.main, + llm_sonnet: d3roPalette.tag.green, + llm_opus: d3roPalette.tag.purple, + stt_transcribe: d3roPalette.tag.blue, + translate: d3roPalette.tag.blue, +} + +const DEFAULT_COLOR = d3roPalette.text.secondary + +export function FeatureUsageChart({ data }: FeatureUsageChartProps): React.ReactElement { + // Pivot: group by date, features as columns + const features = [...new Set(data.map(d => d.feature))] + const dateMap = new Map>() + + for (const row of data) { + const existing = dateMap.get(row.date) ?? { date: row.date } + existing[row.feature] = row.total_count + dateMap.set(row.date, existing) + } + + const chartData = [...dateMap.values()].sort((a, b) => + String(a.date).localeCompare(String(b.date)) + ) + + return ( + + + + + val.slice(5)} + /> + + + + {features.map((feature) => ( + + ))} + + + + ) +} diff --git a/apps/admin/src/components/charts/top-users-chart.tsx b/apps/admin/src/components/charts/top-users-chart.tsx new file mode 100644 index 00000000..148eab88 --- /dev/null +++ b/apps/admin/src/components/charts/top-users-chart.tsx @@ -0,0 +1,65 @@ +'use client' + +// apps/admin/src/components/charts/top-users-chart.tsx +// 유저별 사용량 Top 20 — Horizontal bar + +import { + ResponsiveContainer, + BarChart, + Bar, + XAxis, + YAxis, + CartesianGrid, + Tooltip, +} from 'recharts' +import { Box } from '@mui/material' +import { d3roPalette, d3roFontMono } from '@d3ro/ui/theme' + +interface TopUserRow { + user_id: string + name: string | null + total_count: number + feature_count: number +} + +interface TopUsersChartProps { + data: TopUserRow[] +} + +export function TopUsersChart({ data }: TopUsersChartProps): React.ReactElement { + const chartData = data.map(row => ({ + name: row.name ?? row.user_id.substring(0, 8), + total: row.total_count, + features: row.feature_count, + })) + + return ( + + + + + + + + + + + + ) +} diff --git a/apps/api-server/D3ROVoice.Api.csproj b/apps/api-server/D3ROVoice.Api.csproj index 9b140d46..07bd9006 100644 --- a/apps/api-server/D3ROVoice.Api.csproj +++ b/apps/api-server/D3ROVoice.Api.csproj @@ -2,7 +2,7 @@ net10.0 - 1.16.2 + 1.16.1 enable enable diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 2130ebd2..e49f1f12 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@d3ro/desktop", - "version": "1.16.2", + "version": "1.16.1", "productName": "d3ro-voice", "description": "로컬 AI 음성 어시스턴트 (Electron)", "main": "./out/main/index.js", diff --git a/apps/desktop/run_e2e_cdp.cjs b/apps/desktop/run_e2e_cdp.cjs new file mode 100644 index 00000000..ba14e4f2 --- /dev/null +++ b/apps/desktop/run_e2e_cdp.cjs @@ -0,0 +1,133 @@ +const fs = require('fs'); +const http = require('http'); +const WebSocket = require('ws'); +const path = require('path'); + +const ARTIFACTS_DIR = "C:\\Users\\encep\\.gemini\\antigravity\\brain\\8f83f382-c9ee-4ef3-8e9b-a7dec5371b5a"; + +function getTargets() { + return new Promise((resolve, reject) => { + http.get('http://127.0.0.1:9222/json/list', (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => resolve(JSON.parse(data))); + }).on('error', reject); + }); +} + +function sendCDP(ws, method, params = {}) { + return new Promise((resolve, reject) => { + const id = Math.floor(Math.random() * 1000000); + const handler = (data) => { + const msg = JSON.parse(data); + if (msg.id === id) { + ws.removeListener('message', handler); + if (msg.error) reject(msg.error); + else resolve(msg.result); + } + }; + ws.on('message', handler); + ws.send(JSON.stringify({ id, method, params })); + }); +} + +async function runE2E() { + const targets = await getTargets(); + const mainTarget = targets.find(t => t.title === 'D3RO Voice' || t.url.includes('index.html')); + if (!mainTarget) { + console.error('Main window target not found!', targets); + process.exit(1); + } + + console.log('Connecting to target:', mainTarget.title, mainTarget.webSocketDebuggerUrl); + // Replace localhost in webSocketDebuggerUrl if needed + const wsUrl = mainTarget.webSocketDebuggerUrl.replace('localhost', '127.0.0.1'); + const ws = new WebSocket(wsUrl); + + await new Promise((resolve) => ws.on('open', resolve)); + console.log('WebSocket connected!'); + + await sendCDP(ws, 'Page.enable'); + await sendCDP(ws, 'Runtime.enable'); + + // 1. Check DOM state + const domCheck = await sendCDP(ws, 'Runtime.evaluate', { + expression: ` + (() => { + const root = document.getElementById('root'); + return { + rootExists: !!root, + rootInnerHTML: root ? root.innerHTML.length : 0, + bodyText: document.body.innerText.substring(0, 300), + title: document.title, + buttonsCount: document.querySelectorAll('button, [role="button"]').length, + allText: document.body.innerText + }; + })() + `, + returnByValue: true + }); + console.log('--- Initial UI State ---'); + console.log(JSON.stringify(domCheck.result.value, null, 2)); + + // 2. Take screenshot 1: Main window default view + const shot1 = await sendCDP(ws, 'Page.captureScreenshot', { format: 'png' }); + const shot1Path = path.join(ARTIFACTS_DIR, 'e2e_main_screen.png'); + fs.writeFileSync(shot1Path, Buffer.from(shot1.data, 'base64')); + console.log('Saved screenshot 1:', shot1Path); + + // 3. Inspect interactive elements and click around + const interactRes = await sendCDP(ws, 'Runtime.evaluate', { + expression: ` + (() => { + const clickable = Array.from(document.querySelectorAll('button, div[onclick], a, [role="button"], svg, span')); + const labels = clickable.map(c => c.innerText || c.getAttribute('aria-label') || c.title || '').filter(Boolean); + return { count: clickable.length, labels: labels.slice(0, 20) }; + })() + `, + returnByValue: true + }); + console.log('Clickable elements:', interactRes.result.value); + + // 4. Test Navigation or Tabs click + const navTest = await sendCDP(ws, 'Runtime.evaluate', { + expression: ` + (() => { + const buttons = Array.from(document.querySelectorAll('button, [role="button"]')); + return buttons.map((btn, idx) => ({ idx, text: (btn.innerText || btn.getAttribute('aria-label') || '').trim() })); + })() + `, + returnByValue: true + }); + console.log('Found buttons list:', navTest.result.value); + + // Click various buttons to test UI response + const buttons = navTest.result.value; + if (buttons.length > 0) { + for (let i = 0; i < Math.min(buttons.length, 5); i++) { + await sendCDP(ws, 'Runtime.evaluate', { + expression: ` + (() => { + const btns = document.querySelectorAll('button, [role="button"]'); + if (btns[${i}]) btns[${i}].click(); + })() + ` + }); + await new Promise(r => setTimeout(r, 500)); + } + } + + // Screenshot 2: After interaction + const shot2 = await sendCDP(ws, 'Page.captureScreenshot', { format: 'png' }); + const shot2Path = path.join(ARTIFACTS_DIR, 'e2e_after_click.png'); + fs.writeFileSync(shot2Path, Buffer.from(shot2.data, 'base64')); + console.log('Saved screenshot 2:', shot2Path); + + ws.close(); + console.log('E2E script completed successfully!'); +} + +runE2E().catch(err => { + console.error('E2E Error:', err); + process.exit(1); +}); diff --git a/apps/desktop/run_e2e_full_suite.cjs b/apps/desktop/run_e2e_full_suite.cjs new file mode 100644 index 00000000..4099436d --- /dev/null +++ b/apps/desktop/run_e2e_full_suite.cjs @@ -0,0 +1,147 @@ +const fs = require('fs'); +const http = require('http'); +const WebSocket = require('ws'); +const path = require('path'); + +const ARTIFACTS_DIR = "C:\\Users\\encep\\.gemini\\antigravity\\brain\\8f83f382-c9ee-4ef3-8e9b-a7dec5371b5a"; + +function getTargets() { + return new Promise((resolve, reject) => { + http.get('http://127.0.0.1:9222/json/list', (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => resolve(JSON.parse(data))); + }).on('error', reject); + }); +} + +function sendCDP(ws, method, params = {}) { + return new Promise((resolve, reject) => { + const id = Math.floor(Math.random() * 1000000); + const handler = (data) => { + const msg = JSON.parse(data); + if (msg.id === id) { + ws.removeListener('message', handler); + if (msg.error) reject(msg.error); + else resolve(msg.result); + } + }; + ws.on('message', handler); + ws.send(JSON.stringify({ id, method, params })); + }); +} + +async function runFullSuite() { + const targets = await getTargets(); + const mainTarget = targets.find(t => t.title === 'D3RO Voice' || t.url.includes('index.html')); + if (!mainTarget) { + console.error('Target not found:', targets); + return; + } + + const wsUrl = mainTarget.webSocketDebuggerUrl.replace('localhost', '127.0.0.1'); + const ws = new WebSocket(wsUrl); + + await new Promise((resolve) => ws.on('open', resolve)); + console.log('--- STARTING FULL E2E VISUAL TEST SUITE ---'); + + await sendCDP(ws, 'Page.enable'); + await sendCDP(ws, 'Runtime.enable'); + + const errors = []; + ws.on('message', (data) => { + try { + const msg = JSON.parse(data); + if (msg.method === 'Runtime.consoleAPICalled' && msg.params.type === 'error') { + const errText = msg.params.args.map(a => a.value || a.description || JSON.stringify(a)).join(' '); + console.error('[RENDERER CONSOLE ERROR DETECTED]:', errText); + errors.push(errText); + } + } catch(e){} + }); + + const captureScreen = async (filename) => { + try { + const shot = await sendCDP(ws, 'Page.captureScreenshot', { format: 'png' }); + const targetPath = path.join(ARTIFACTS_DIR, filename); + fs.writeFileSync(targetPath, Buffer.from(shot.data, 'base64')); + console.log(`[Screen Captured] ${filename}`); + } catch(e) { + console.error(`Failed to capture ${filename}:`, e.message); + } + }; + + // 1. Initial Dashboard + await captureScreen('page_1_dashboard.png'); + + // 2. Dismiss modal + try { + await sendCDP(ws, 'Runtime.evaluate', { + expression: ` + (() => { + const btns = Array.from(document.querySelectorAll('button')); + const laterBtn = btns.find(b => b.innerText.includes('나중에')); + if (laterBtn) laterBtn.click(); + })() + ` + }); + } catch(e) { + console.error('Modal dismiss error:', e.message); + } + await new Promise(r => setTimeout(r, 600)); + + await captureScreen('page_1_dashboard_clean.png'); + + // 3. Test Navigation Tabs + const menuItems = ['히스토리', '사전', '명령어', '대화', '지식 베이스', '회의', '설정']; + for (let i = 0; i < menuItems.length; i++) { + const item = menuItems[i]; + console.log(`Navigating to tab: ${item}`); + + try { + await sendCDP(ws, 'Runtime.evaluate', { + expression: ` + (() => { + const elements = Array.from(document.querySelectorAll('div, span, p, a, button')); + const el = elements.find(e => e.innerText && e.innerText.trim() === '${item}'); + if (el) { + el.click(); + return true; + } + return false; + })() + ` + }); + } catch(e) { + console.error(`Tab click error (${item}):`, e.message); + } + + await new Promise(r => setTimeout(r, 800)); + await captureScreen(`page_${i + 2}_${item.replace(/\s+/g, '_')}.png`); + } + + // 4. Test Subtab + console.log('Testing Settings Sub-Tabs...'); + try { + await sendCDP(ws, 'Runtime.evaluate', { + expression: ` + (() => { + const tabs = Array.from(document.querySelectorAll('button, div[role="tab"]')); + if (tabs.length > 0) tabs[0].click(); + })() + ` + }); + } catch(e){} + await new Promise(r => setTimeout(r, 500)); + await captureScreen('page_settings_subtab.png'); + + console.log('--- E2E TEST SUITE FINISHED ---'); + console.log('Total Console Errors Detected during flow:', errors.length); + + ws.close(); +} + +runFullSuite().catch(err => { + console.error('Suite error:', err); + process.exit(1); +}); diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 8561aa6f..a9f83ccf 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -17,10 +17,8 @@ import { bootstrap } from './bootstrap' import { setupLifecycle } from './lifecycle' import { showMainWindow } from './windows/WindowManager' import { getLogger } from './services/LoggerService' -import { isUpdateDialogPreviewRequested } from './update-dialog-preview' const deepLinkLogger = getLogger('deep-link') -const updateDialogPreviewRequested = isUpdateDialogPreviewRequested() // EPIPE 에러 방지: electron-log가 stdout/stderr에 쓸 때 파이프가 끊기면 크래시 방지 process.stdout?.on?.('error', () => { /* ignore EPIPE */ }) @@ -33,14 +31,12 @@ process.on('uncaughtException', (err) => { // V2-4: deep link 프로토콜 등록 — d3ro-voice://auth-callback?code=... const PROTOCOL = 'd3ro-voice' -if (!updateDialogPreviewRequested) { - if (process.defaultApp) { - if (process.argv.length >= 2) { - app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [path.resolve(process.argv[1])]) - } - } else { - app.setAsDefaultProtocolClient(PROTOCOL) +if (process.defaultApp) { + if (process.argv.length >= 2) { + app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [path.resolve(process.argv[1])]) } +} else { + app.setAsDefaultProtocolClient(PROTOCOL) } /** @@ -134,10 +130,7 @@ async function handleDeepLink(url: string): Promise { } // 단일 인스턴스 잠금 (테스트 모드에서는 다중 인스턴스 허용) -const gotTheLock = - process.env.NODE_ENV === 'test' || updateDialogPreviewRequested - ? true - : app.requestSingleInstanceLock() +const gotTheLock = process.env.NODE_ENV === 'test' ? true : app.requestSingleInstanceLock() if (!gotTheLock) { deepLinkLogger.info('Another instance is already running. Existing window focused.') @@ -177,17 +170,6 @@ if (!gotTheLock) { }) app.whenReady().then(async () => { - if (updateDialogPreviewRequested) { - try { - const { runUpdateDialogPreview } = await import('./update-dialog-preview') - await runUpdateDialogPreview() - app.quit() - } catch (err) { - electronLog.error('Update dialog preview failed:', err) - app.exit(1) - } - return - } await bootstrap() setupLifecycle() }) diff --git a/apps/desktop/src/main/services/CaptionService.ts b/apps/desktop/src/main/services/CaptionService.ts index c4ec7d13..5115e308 100644 --- a/apps/desktop/src/main/services/CaptionService.ts +++ b/apps/desktop/src/main/services/CaptionService.ts @@ -14,7 +14,6 @@ import { getLocalLLMService } from './LocalLLMService' import { getHistoryService } from './HistoryService' import { configGet } from './ConfigService' import { buildCaptionRefinePrompt } from './llm-prompts' -import { getTranscriptGlossaryService } from './TranscriptGlossaryService' import { StreamingCaptionTrack, type CaptionTranscription } from './caption/StreamingCaptionTrack' import { CaptionAudioSources } from './caption/CaptionAudioSources' import { acceptCaptionRefinement } from '@d3ro/core/caption-streaming' @@ -98,8 +97,6 @@ const DEFAULT_START_OPTIONS: ResolvedStartOptions = { interface CaptionServiceEvents { 'state-changed': (state: CaptionState) => void 'segment': (segment: CaptionSegment) => void - /** 다듬기(학습 어휘 교정·LLM 교열)로 확정 줄의 텍스트가 바뀌었다 */ - 'segment-updated': (update: { id: string; text: string }) => void 'delta': (data: { text: string; isFinal: boolean }) => void 'session-saved': (summary: CaptionSessionResult) => void /** @@ -214,8 +211,7 @@ class CaptionService extends EventEmitter { this._segments = [] this._refineQueue = [] this._sessionLanguage = null - // 초기 컨텍스트 힌트 — Whisper 첫 청크 환각 방지. - // 학습 어휘 힌트는 _transcribe 가 매 인식마다 덧붙인다(트랙 문맥에 섞이면 중복된다). + // 초기 컨텍스트 힌트 — Whisper 첫 청크 환각 방지 const lang = configGet('sttLanguage') as string | undefined const initialContext = lang === 'ko' ? '다음은 한국어 대화입니다.' : '' @@ -471,8 +467,7 @@ class CaptionService extends EventEmitter { const language = configured === 'auto' ? (this._sessionLanguage ?? 'auto') : configured const result = await getLocalSTTService().transcribe(audio, { language, - // 학습 어휘 힌트는 매 인식마다 붙인다 — rolling context 가 잘려도 용어 편향이 유지된다. - initialPrompt: getTranscriptGlossaryService().sttHint(opts.initialPrompt), + initialPrompt: opts.initialPrompt, vadFilter: true, partial: opts.partial, modelId: this._captionModelId ?? undefined, @@ -498,14 +493,7 @@ class CaptionService extends EventEmitter { this._sendToMainWindow(IPC_CHANNELS.CAPTION.DELTA, delta) } - private _emitFinal(rawText: string, source: 'mic' | 'system'): void { - // 학습 어휘(사전 + 개인 문구)로 먼저 되돌린다 — LLM 이 꺼져 있어도 용어는 고쳐진다. - const corrected = getTranscriptGlossaryService().correct(rawText) - const text = corrected.text.trim() - if (!text) return - if (corrected.corrections.length > 0) { - logger.info(`자막 학습 어휘 교정 ${corrected.corrections.length}건 (${source})`) - } + private _emitFinal(text: string, source: 'mic' | 'system'): void { const segment: CaptionSegment = { id: crypto.randomUUID(), text, @@ -546,12 +534,7 @@ class CaptionService extends EventEmitter { const index = this._segments.findIndex((item) => item.id === segment.id) if (index === -1) return const previous = this._segments.slice(Math.max(0, index - 2), index).map((item) => item.text) - const glossary = getTranscriptGlossaryService().promptSection() - const { systemPrompt, text } = buildCaptionRefinePrompt({ - text: segment.text, - previous, - ...(glossary ? { glossary } : {}), - }) + const { systemPrompt, text } = buildCaptionRefinePrompt({ text: segment.text, previous }) try { const result = await getLocalLLMService().generate(text, { systemPrompt, @@ -561,24 +544,17 @@ class CaptionService extends EventEmitter { }) const refined = acceptCaptionRefinement(segment.text, result.text) if (!refined) return - // 모델이 용어를 다른 표기로 되돌렸을 수 있다 — 정본 표기를 마지막에 다시 강제한다. - this._replaceSegmentText(segment.id, getTranscriptGlossaryService().correct(refined).text) + const current = this._segments.find((item) => item.id === segment.id) + if (!current) return + current.text = refined + const update = { id: segment.id, text: refined } + sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update) + this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update) } catch (err) { logger.debug(`자막 다듬기 건너뜀: ${err instanceof Error ? err.message : String(err)}`) } } - /** 확정 줄 텍스트를 바꾸고 오버레이·메인 창·회의 모드에 알린다. */ - private _replaceSegmentText(segmentId: string, text: string): void { - const current = this._segments.find((item) => item.id === segmentId) - if (!current || current.text === text) return - current.text = text - const update = { id: segmentId, text } - sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update) - this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update) - this.emit('segment-updated', update) - } - // ── 내부: 세션 저장 ── private _saveSession(persist: boolean): CaptionSessionResult | null { diff --git a/apps/desktop/src/main/services/DictionaryService.ts b/apps/desktop/src/main/services/DictionaryService.ts index 75da3634..6b9e64f3 100644 --- a/apps/desktop/src/main/services/DictionaryService.ts +++ b/apps/desktop/src/main/services/DictionaryService.ts @@ -9,7 +9,6 @@ import { getDatabase } from '../db' import { dictionary } from '../db/schema' import type { Dictionary, NewDictionary } from '../db/schema' import { getLogger } from './LoggerService' -import { invalidateTranscriptGlossary } from './TranscriptGlossaryService' import { getCloudSyncService } from './CloudSyncService' import { getMainWindow } from '../windows/WindowManager' import { D3ROError, ErrorCode } from '@d3ro/core/errors' @@ -115,8 +114,6 @@ class DictionaryService { throw err } logger.info(`Dictionary entry added: "${word}"`) - // 학습 어휘 캐시(전사 교열·STT 힌트)는 즉시 무효화한다 — 방금 추가한 단어가 바로 쓰여야 한다. - invalidateTranscriptGlossary() // Phase 3.3: 자동 push (fire-and-forget) void getCloudSyncService().pushOne('dictionary', id) return this._toEntry(entry as Dictionary) @@ -153,7 +150,6 @@ class DictionaryService { } const updated = db.select().from(dictionary).where(eq(dictionary.id, params.id)).get() - invalidateTranscriptGlossary() // Phase 3.3: 자동 push (fire-and-forget) void getCloudSyncService().pushOne('dictionary', params.id) return updated ? this._toEntry(updated) : null @@ -162,10 +158,7 @@ class DictionaryService { delete(id: string): boolean { const db = getDatabase() const result = db.delete(dictionary).where(eq(dictionary.id, id)).run() - if (result.changes > 0) { - invalidateTranscriptGlossary() - getCloudSyncService().pushDelete('dictionary', id) - } + if (result.changes > 0) getCloudSyncService().pushDelete('dictionary', id) return result.changes > 0 } @@ -456,7 +449,6 @@ class DictionaryService { logger.info( `Dictionary import: ${outcome.imported} imported, ${outcome.skipped} skipped, ${outcome.errors} errors` ) - if (outcome.imported > 0) invalidateTranscriptGlossary() return outcome } diff --git a/apps/desktop/src/main/services/FileTranscriptionService.ts b/apps/desktop/src/main/services/FileTranscriptionService.ts index 63d75044..d5ec26a4 100644 --- a/apps/desktop/src/main/services/FileTranscriptionService.ts +++ b/apps/desktop/src/main/services/FileTranscriptionService.ts @@ -35,7 +35,6 @@ import type { } from '@d3ro/core/types' import { collapseRepeatedSegments, collapseRepeats, isDegenerateTranscript } from './file-transcription/repetition' -import { getTranscriptGlossaryService } from './TranscriptGlossaryService' import { SUPPORTED_MEDIA_EXTENSION_SET } from './file-transcription/media-formats' const logger = getLogger('FileTranscriptionService') @@ -179,8 +178,7 @@ class FileTranscriptionService extends EventEmitter { let result = await sttService.transcribe(chunkBuffer, { language: lang, - // 학습 어휘 힌트를 매 조각에 붙인다 — 앞 문맥이 없어도 고유명사 표기가 유지된다. - initialPrompt: getTranscriptGlossaryService().sttHint(previousContext) || undefined, + initialPrompt: previousContext || undefined, vadFilter: true, }) // 인식 중에 취소됐으면 결과를 버린다(STT 호출 자체는 끊을 수 없다) @@ -189,17 +187,12 @@ class FileTranscriptionService extends EventEmitter { // 앞 조각 힌트 때문에 반복 루프에 빠졌으면 힌트 없이 한 번 다시 듣는다 if (previousContext && isDegenerateTranscript(result.text ?? '')) { logger.warn(`청크 ${i + 1}/${totalChunks}: 반복 루프 감지 — 앞 문맥 없이 다시 전사`) - result = await sttService.transcribe(chunkBuffer, { - language: lang, - initialPrompt: getTranscriptGlossaryService().sttHint('') || undefined, - vadFilter: true, - }) + result = await sttService.transcribe(chunkBuffer, { language: lang, vadFilter: true }) throwIfCancelled() } const rawText = result.text?.trim() ?? '' - // 학습 어휘(사전 + 개인 문구)로 잘못 들은 어절을 되돌린다. - const chunkText = getTranscriptGlossaryService().correct(collapseRepeats(rawText)).text + const chunkText = collapseRepeats(rawText) if (chunkText.length > 0) { allTexts.push(chunkText) // 반복으로 망가진 결과는 다음 조각의 힌트로 넘기지 않는다 — 넘기면 반복이 다음 조각으로 번졌다 @@ -207,7 +200,7 @@ class FileTranscriptionService extends EventEmitter { for (const seg of collapseRepeatedSegments(result.segments)) { allSegments.push({ - text: getTranscriptGlossaryService().correct(seg.text).text, + text: seg.text, start: seg.start + startSec, end: seg.end + startSec, confidence: seg.confidence, diff --git a/apps/desktop/src/main/services/MeetingModeService.ts b/apps/desktop/src/main/services/MeetingModeService.ts index 9c270b88..3d6888e5 100644 --- a/apps/desktop/src/main/services/MeetingModeService.ts +++ b/apps/desktop/src/main/services/MeetingModeService.ts @@ -57,7 +57,6 @@ import { } from '@d3ro/core/meeting-transcript' import { markdownToDocx } from '@d3ro/core/utils/markdown-to-docx' import { getFileTranscriptionService } from './FileTranscriptionService' -import { getTranscriptGlossaryService } from './TranscriptGlossaryService' import { buildImportedMeetingTranscript } from './meeting/imported-recording' import type { MeetingModeState, @@ -372,11 +371,6 @@ class MeetingModeService extends EventEmitter { captionService.on('segment', listener) return () => { captionService.off('segment', listener) } }, - // 다듬기(학습 어휘·LLM 교열)로 바뀐 줄도 받아야 회의록 전사가 원문에 머물지 않는다. - onSegmentUpdated: (listener) => { - captionService.on('segment-updated', listener) - return () => { captionService.off('segment-updated', listener) } - }, // 회의가 소유한 세션만 멈춘다. 다른 소유자면 false(요약 없음). stop: () => captionService.stop('meeting'), }, @@ -391,10 +385,6 @@ class MeetingModeService extends EventEmitter { this.emit('segment', segment) this._sendToRenderer(IPC_CHANNELS.MEETING_MODE.SEGMENT, segment) }, - onSegmentUpdated: (update) => { - this.emit('segment-updated', update) - this._sendToRenderer(IPC_CHANNELS.MEETING_MODE.SEGMENT_UPDATED, update) - }, onStopError: (err) => { logger.error(`자막 정지 실패 — 지금까지의 전사로 저장한다: ${err instanceof Error ? err.message : String(err)}`) }, @@ -1429,14 +1419,10 @@ class MeetingModeService extends EventEmitter { if (!transcript) throw new D3ROError(ErrorCode.MeetingPolishFailed, '전사 텍스트가 없습니다') const llm = await this._resolveMeetingLlm() - // 사용자가 학습시킨 용어·표현을 교열 지시에 넘긴다 — 예전엔 일반 프롬프트만 받아 - // 고유명사·사내 용어가 매번 다르게 교정됐다. - const glossary = getTranscriptGlossaryService().promptSection() const polished = await this._rewriteTranscriptInChunks( llm, transcript, - '다음 음성 전사 텍스트를 다듬어주세요. 필러 단어(음, 어, 그, 아, 뭐 등), 말 바꾸기(A 아니 A가 아니라 B → B), 불필요한 어절·의미 중복을 제거하고 문장 구조를 자연스럽게 교정하되, 화자의 원래 말투(반말/존댓말)와 의미·내용은 절대 변경하지 마세요. 타임스탬프 형식 [MM:SS]과 화자 표기([화자 N] 등)는 그대로 유지하세요.' + - (glossary ? `\n\n${glossary}` : ''), + '다음 음성 전사 텍스트를 다듬어주세요. 필러 단어(음, 어, 그, 아, 뭐 등), 말 바꾸기(A 아니 A가 아니라 B → B), 불필요한 어절·의미 중복을 제거하고 문장 구조를 자연스럽게 교정하되, 화자의 원래 말투(반말/존댓말)와 의미·내용은 절대 변경하지 마세요. 타임스탬프 형식 [MM:SS]과 화자 표기([화자 N] 등)는 그대로 유지하세요.', ErrorCode.MeetingPolishFailed, ) diff --git a/apps/desktop/src/main/services/TranscriptGlossaryService.ts b/apps/desktop/src/main/services/TranscriptGlossaryService.ts deleted file mode 100644 index 1a938eae..00000000 --- a/apps/desktop/src/main/services/TranscriptGlossaryService.ts +++ /dev/null @@ -1,184 +0,0 @@ -// src/main/services/TranscriptGlossaryService.ts -// 전사 교열용 학습 어휘 창구(싱글톤). -// -// 왜 필요한가: -// - 사용자가 키보드로 친 문장은 개인 그래프(personal_phrases)와 사전(dictionary)에 쌓이지만, -// 회의록·자막 전사에는 그 어휘가 한 번도 쓰이지 않았다. 자막은 `다음은 한국어 대화입니다.`라는 -// 고정 힌트로 인식됐고, 확정된 줄은 용어 사전 없이 일반 프롬프트로만 다듬어졌다. -// - 이 서비스는 그 어휘를 한 곳에서 모아 STT 힌트·결정적 교정·LLM 교열 참고 블록으로 공급한다. -// 교정 규칙 자체는 core `transcript-correction` 이 정본이고, 여기서는 소스 수집과 캐시만 맡는다. -// -// 소스는 주입 가능하다(테스트는 DB 없이 가짜 소스). - -import { desc } from 'drizzle-orm' -import { getLogger } from './LoggerService' -import { getDatabase } from '../db' -import { dictionary, personalPhrases } from '../db/schema' -import { - appendGlossaryHint, - buildGlossaryPromptSection, - buildTranscriptGlossary, - correctLearnedTerms, - isGlossaryEmpty, - replaceDictionaryTerms, - type CorrectedTranscript, - type GlossaryDictionaryEntry, - type GlossaryPhrase, - type TranscriptCorrectionEntry, - type TranscriptGlossary, -} from '@d3ro/core/transcript-correction' - -const logger = getLogger('TranscriptGlossaryService') - -/** 학습 어휘 캐시 수명. 사전/학습은 회의 중에도 늘 수 있으므로 짧게 둔다. */ -const GLOSSARY_TTL_MS = 15_000 - -export interface TranscriptGlossarySources { - /** 사용자 사전 (정본 단어 + 발음 변형) */ - listDictionary(): readonly GlossaryDictionaryEntry[] - /** 개인 그래프에서 배운 문구 (빈도 포함) */ - listPhrases(): readonly GlossaryPhrase[] - now?: () => number -} - -interface CachedGlossary { - glossary: TranscriptGlossary - at: number -} - -export class TranscriptGlossaryService { - private _cache: CachedGlossary | null = null - private readonly _now: () => number - - constructor( - private readonly _sources: TranscriptGlossarySources, - private readonly _ttlMs: number = GLOSSARY_TTL_MS, - ) { - this._now = _sources.now ?? Date.now - } - - /** 현재 글로서리 (TTL 캐시). 소스가 실패하면 빈 글로서리 — 전사는 계속돼야 한다. */ - get(): TranscriptGlossary { - const now = this._now() - if (this._cache && now - this._cache.at < this._ttlMs) return this._cache.glossary - let glossary: TranscriptGlossary - try { - glossary = buildTranscriptGlossary({ - dictionary: this._sources.listDictionary(), - phrases: this._sources.listPhrases(), - }) - } catch (err) { - logger.warn(`학습 어휘 수집 실패 — 이번 전사는 어휘 없이 진행: ${err instanceof Error ? err.message : String(err)}`) - glossary = buildTranscriptGlossary({}) - } - this._cache = { glossary, at: now } - return glossary - } - - /** 사전·학습이 바뀌었을 때 호출한다. */ - invalidate(): void { - this._cache = null - } - - /** STT initial_prompt 에 학습 어휘 힌트를 덧붙인다. */ - sttHint(base: string): string { - return appendGlossaryHint(base, this.get()) - } - - /** LLM 교열 프롬프트에 넣는 용어·문체 참고 블록 (없으면 빈 문자열). */ - promptSection(): string { - return buildGlossaryPromptSection(this.get()) - } - - /** - * 학습 어휘 기반 결정적 교정 (LLM 없이 즉시). - * 1) 사전 발음 변형 → 정본 표기 - * 2) 학습 어절과 1자모 차이 나는 전사 어절 → 학습 어절 - * 사용자가 실제로 쓴 어절은 건드리지 않는다(core 규칙). - */ - correct(text: string): CorrectedTranscript { - if (!text || text.trim().length === 0) return { text, corrections: [] } - const glossary = this.get() - if (isGlossaryEmpty(glossary)) return { text, corrections: [] } - - const corrections: TranscriptCorrectionEntry[] = [] - let current = text - if (glossary.dictionary.length > 0) { - const dictionaryPass = replaceDictionaryTerms( - current, - glossary.dictionary.map((entry) => ({ word: entry.word, pronunciation: entry.variants.join(',') })), - ) - current = dictionaryPass.text - corrections.push(...dictionaryPass.changes) - } - - const learned = correctLearnedTerms(current, glossary) - if (learned.corrections.length > 0) corrections.push(...learned.corrections) - return { text: learned.text, corrections } - } - - /** - * 학습 어절만 교정한다. 사전 치환을 호출자가 사용 횟수 집계와 함께 처리하는 경로 - * (받아쓰기)에서 쓴다. - */ - correctLearned(text: string): CorrectedTranscript { - if (!text || text.trim().length === 0) return { text, corrections: [] } - const glossary = this.get() - if (isGlossaryEmpty(glossary)) return { text, corrections: [] } - return correctLearnedTerms(text, glossary) - } -} - -let instance: TranscriptGlossaryService | null = null - -/** DB 기반 기본 소스. DB 가 아직 없으면 빈 어휘를 돌려준다(전사를 막지 않는다). */ -function defaultSources(): TranscriptGlossarySources { - return { - listDictionary: () => { - try { - return getDatabase() - .select({ word: dictionary.word, pronunciation: dictionary.pronunciation }) - .from(dictionary) - .orderBy(desc(dictionary.usageCount)) - .limit(300) - .all() - } catch { - return [] - } - }, - listPhrases: () => { - try { - return getDatabase() - .select({ text: personalPhrases.phrase, count: personalPhrases.count }) - .from(personalPhrases) - .orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt)) - .limit(400) - .all() - } catch { - return [] - } - }, - } -} - -export function initTranscriptGlossaryService( - sources: TranscriptGlossarySources = defaultSources(), - ttlMs?: number, -): TranscriptGlossaryService { - instance = new TranscriptGlossaryService(sources, ttlMs) - return instance -} - -export function getTranscriptGlossaryService(): TranscriptGlossaryService { - if (!instance) instance = initTranscriptGlossaryService() - return instance -} - -/** 사전·학습이 바뀌었을 때 호출한다(아직 만들지 않았으면 아무 것도 하지 않는다). */ -export function invalidateTranscriptGlossary(): void { - instance?.invalidate() -} - -export function resetTranscriptGlossaryServiceForTests(): void { - instance = null -} diff --git a/apps/desktop/src/main/services/UiaContextService.ts b/apps/desktop/src/main/services/UiaContextService.ts index 4346d5ee..acb412da 100644 --- a/apps/desktop/src/main/services/UiaContextService.ts +++ b/apps/desktop/src/main/services/UiaContextService.ts @@ -12,6 +12,7 @@ // - 읽기 실패/타임아웃은 텍스트를 쓰지 않는다 (available=false). // - 실패 후에는 백오프를 걸어 매 키입력마다 사이드카를 두드리지 않는다. +import { D3ROError, ErrorCode } from '@d3ro/core/errors' import { emptyFocusSnapshot, type FocusSnapshot, @@ -207,3 +208,8 @@ export function getUiaContextService(): UiaContextService { export function resetUiaContextServiceForTests(): void { instance = null } + +/** 진단용 — D3ROError 로 감싼 브리지 오류 생성. */ +export function createUiaBridgeError(reason: string): D3ROError { + return new D3ROError(ErrorCode.UiaBridgeUnavailable, `UIA bridge unavailable: ${reason}`) +} diff --git a/apps/desktop/src/main/services/VoiceModeService.ts b/apps/desktop/src/main/services/VoiceModeService.ts index e3c7d911..e5f00b2d 100644 --- a/apps/desktop/src/main/services/VoiceModeService.ts +++ b/apps/desktop/src/main/services/VoiceModeService.ts @@ -27,7 +27,6 @@ import { configGet } from './ConfigService' import { getTextInsertService } from './TextInsertService' import { getLocalLLMService } from './LocalLLMService' import { getLlmGateway } from './llm/LlmGateway' -import { getTranscriptGlossaryService } from './TranscriptGlossaryService' import { buildInstructionInvocation, resolveTargetLanguage } from './llm-prompts' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import { cleanDictatedText } from '@d3ro/core/dictation-cleaner' @@ -908,12 +907,13 @@ class VoiceModeService extends EventEmitter { const stt = getSTTManager() const language = configGet('sttLanguage') - // 사전 + 학습 어휘 → STT initial_prompt 주입 (사용자가 학습시킨 용어를 인식 단계에서 미리 편향) + // Dictionary → STT initialPrompt 주입 (Speakly 패턴) let initialPrompt: string | undefined try { - initialPrompt = getTranscriptGlossaryService().sttHint('') || undefined + const { getDictionaryService } = await import('./DictionaryService') + initialPrompt = getDictionaryService().getPromptHints() || undefined } catch { - // 학습 어휘 소스 미준비 시 무시 + // DictionaryService 미초기화 시 무시 } // 사이드카는 요청을 직렬 처리하므로, 진행 중인 미리보기 요청이 최종 전사를 @@ -950,8 +950,6 @@ class VoiceModeService extends EventEmitter { } catch { // DictionaryService 미초기화 시 무시 } - // 사전에 없는 개인 어휘(학습한 어절)로 남은 오인식을 되돌린다. - rawText = getTranscriptGlossaryService().correctLearned(rawText).text if (this._session) { this._session.transcription = rawText diff --git a/apps/desktop/src/main/services/global-input-hook.ts b/apps/desktop/src/main/services/global-input-hook.ts index 0b94b3ec..c8684c6e 100644 --- a/apps/desktop/src/main/services/global-input-hook.ts +++ b/apps/desktop/src/main/services/global-input-hook.ts @@ -54,8 +54,16 @@ export function acquireGlobalInputHook(): () => void { } } +export function isGlobalInputHookRunning(): boolean { + return running +} + +export function getGlobalInputHookRefCount(): number { + return refCount +} + /** 테스트 전용 — 모듈 상태 초기화. */ export function resetGlobalInputHookForTests(): void { refCount = 0 running = false -} +} \ No newline at end of file diff --git a/apps/desktop/src/main/services/llm-prompts.ts b/apps/desktop/src/main/services/llm-prompts.ts index e41f922b..2d7fd598 100644 --- a/apps/desktop/src/main/services/llm-prompts.ts +++ b/apps/desktop/src/main/services/llm-prompts.ts @@ -529,8 +529,6 @@ const CAPTION_REFINE_SYSTEM_PROMPT = `실시간 음성 인식으로 받아 적 규칙: - 띄어쓰기, 문장부호, 앞 문맥으로 볼 때 명백하게 잘못 들은 단어만 고치세요. -- [사용자 용어] 가 있으면 전사에 나온 비슷한 표기를 그 용어로 바꾸세요(고유명사·제품명·사내 용어). -- [사용자가 실제로 쓰는 표현] 은 말투·용어 참고용입니다. 그 문장을 그대로 옮기거나 문장을 새로 쓰지 마세요. - 뜻을 바꾸거나, 요약하거나, 말을 더하거나 빼지 마세요. - 원문과 같은 언어, 같은 말투(존댓말/반말, 구어체)를 유지하세요. - 고친 문장 한 줄만 출력하세요. 설명, 따옴표, 번호를 붙이지 마세요. @@ -539,12 +537,8 @@ const CAPTION_REFINE_SYSTEM_PROMPT = `실시간 음성 인식으로 받아 적 export function buildCaptionRefinePrompt(input: { text: string previous: readonly string[] - /** 학습 어휘 참고 블록 (`buildGlossaryPromptSection` 결과) */ - glossary?: string }): { systemPrompt: string; text: string } { const sections: string[] = [] - const glossary = input.glossary?.trim() - if (glossary) sections.push(glossary, '') const previous = input.previous.filter((line) => line.trim().length > 0).slice(-2) if (previous.length > 0) sections.push('[앞 문맥]', ...previous, '') sections.push('[다듬을 자막]', input.text.trim()) diff --git a/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts b/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts index 7807e512..2d6b8657 100644 --- a/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts +++ b/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts @@ -16,8 +16,6 @@ import type { CaptionSegment, MeetingMemo } from '@d3ro/core/types' export interface RecordingCaptionPort { /** 확정 세그먼트 구독 — 해지 함수를 돌려준다 */ onSegment(listener: (segment: CaptionSegment) => void): () => void - /** 다듬기(학습 어휘·LLM 교열)로 확정 세그먼트 텍스트가 바뀌었을 때 (선택) */ - onSegmentUpdated?(listener: (update: { id: string; text: string }) => void): () => void /** 이 녹음이 소유한 자막 세션을 멈춘다(마지막 문장 flush 포함). 세그먼트 요약을 돌려줄 수 있다. */ stop(): Promise<{ segments: CaptionSegment[] } | null | false> } @@ -33,8 +31,6 @@ export interface MeetingRecordingSessionPorts { now?: () => number /** 세그먼트가 이 녹음에 추가될 때(구독으로 받은 것만) */ onSegment?: (segment: CaptionSegment) => void - /** 세그먼트 텍스트가 다듬어졌을 때 — 화면·기록이 원문에 머물지 않게 알린다 */ - onSegmentUpdated?: (update: { id: string; text: string }) => void /** 자막 정지 실패 — 정지는 계속 진행된다(스냅샷은 그때까지의 세그먼트로 만든다) */ onStopError?: (error: unknown) => void } @@ -58,7 +54,6 @@ export class MeetingRecordingSession { private _audio: Buffer[] = [] private _lastRms = 0 private _unsubscribeSegment: (() => void) | null = null - private _unsubscribeSegmentUpdated: (() => void) | null = null private _unsubscribeAudio: (() => void) | null = null private _stopPromise: Promise | null = null private _snapshot: RecordingSnapshot | null = null @@ -79,13 +74,6 @@ export class MeetingRecordingSession { this._segments.push(segment) this._ports.onSegment?.(segment) }) - this._unsubscribeSegmentUpdated = - this._ports.caption.onSegmentUpdated?.((update) => { - const target = this._segments.find((segment) => segment.id === update.id) - if (!target || target.text === update.text) return - target.text = update.text - this._ports.onSegmentUpdated?.(update) - }) ?? null } /** 오디오 구독을 건다(파일 저장·레벨 표시용). */ @@ -101,8 +89,6 @@ export class MeetingRecordingSession { detach(): void { this._unsubscribeSegment?.() this._unsubscribeSegment = null - this._unsubscribeSegmentUpdated?.() - this._unsubscribeSegmentUpdated = null this._unsubscribeAudio?.() this._unsubscribeAudio = null } @@ -172,8 +158,6 @@ export class MeetingRecordingSession { } finally { this._unsubscribeSegment?.() this._unsubscribeSegment = null - this._unsubscribeSegmentUpdated?.() - this._unsubscribeSegmentUpdated = null } // 구독 밖에서 확정된 세그먼트가 있으면 요약에서 보충한다 if (summary) { diff --git a/apps/desktop/src/main/services/sync/builtin-instruction-sync.ts b/apps/desktop/src/main/services/sync/builtin-instruction-sync.ts index 6ea359a0..743c5fdd 100644 --- a/apps/desktop/src/main/services/sync/builtin-instruction-sync.ts +++ b/apps/desktop/src/main/services/sync/builtin-instruction-sync.ts @@ -19,6 +19,10 @@ const SERVER_TO_DESKTOP_BUILTIN: Readonly> = Object.fromE Object.entries(DESKTOP_TO_SERVER_BUILTIN).map(([desktop, server]) => [server, desktop]) ) +export function isSyncedBuiltin(id: string): boolean { + return id in DESKTOP_TO_SERVER_BUILTIN +} + /** * 폰은 `{{text}}` 외의 자리표시자를 치환하지 않는다. 서버 번역 프리셋은 영어 고정(translate_en)이고 * 데스크톱 번역도 대상 언어 설정이 없어 영어로만 번역하므로 `{{targetLanguage}}` 를 English 로 바꿔 올린다. diff --git a/apps/desktop/src/main/services/update-adapters.ts b/apps/desktop/src/main/services/update-adapters.ts index 49ca2da0..c71768e9 100644 --- a/apps/desktop/src/main/services/update-adapters.ts +++ b/apps/desktop/src/main/services/update-adapters.ts @@ -6,7 +6,8 @@ import { existsSync, readdirSync } from 'node:fs' import { dirname, join } from 'node:path' import { app, dialog } from 'electron' import { getLogger } from './LoggerService' -import { getMainWindow, getPopupTranslator } from '../windows/WindowManager' +import { configGet } from './ConfigService' +import { getMainWindow } from '../windows/WindowManager' import { UPDATE_FEED_URL, UPDATE_POLICY_URL, versionedManifestUrl } from '../update-feed' import { verifyDownloadedUpdate } from '../update-signature' import { DEFAULT_UPDATE_POLICY, parseUpdatePolicy, type UpdatePolicy } from '../update-policy' @@ -194,8 +195,12 @@ export function createRemotePolicySource( } } -/** electron dialog 기반 프롬프터. 문구는 현재 앱 로케일의 update.dialog.* 키에서 가져온다. */ +/** + * electron dialog 기반 프롬프터. + * TODO(i18n): 문구가 아직 ko/en 인라인이다 — update.* 키를 locale 파일에 추가한 뒤 t() 로 옮긴다. + */ export function createDialogPrompter(): UpdatePrompter { + const isKorean = (): boolean => (configGet('language') as string | undefined)?.startsWith('ko') ?? true const show = async (options: Electron.MessageBoxOptions): Promise => { const win = getMainWindow() const { response } = @@ -207,19 +212,22 @@ export function createDialogPrompter(): UpdatePrompter { return { async askConsent({ version, releaseNotes, mandatory }): Promise { - const t = getPopupTranslator() - const notesText = - typeof releaseNotes === 'string' - ? `\n\n${t('update.dialog.releaseNotesHeading')}\n${releaseNotes}` - : '' - const mandatoryNote = mandatory ? `\n\n${t('update.dialog.mandatoryNote')}` : '' + const isKo = isKorean() + const notesText = typeof releaseNotes === 'string' ? `\n\n[주요 변경사항]\n${releaseNotes}` : '' + const mandatoryNote = mandatory + ? isKo + ? '\n\n이 업데이트는 필수입니다 (지원 종료 버전).' + : '\n\nThis update is required (end of support).' + : '' if (mandatory) { const response = await show({ type: 'info', - title: t('update.dialog.requiredTitle'), - message: `${t('update.dialog.requiredMessage', { version })}${mandatoryNote}${notesText}`, - buttons: [t('update.dialog.updateNow')], + title: isKo ? '필수 업데이트' : 'Required Update', + message: isKo + ? `D3RO Voice v${version} 업데이트가 필요합니다.${mandatoryNote}${notesText}` + : `D3RO Voice v${version} is required.${mandatoryNote}${notesText}`, + buttons: isKo ? ['지금 업데이트'] : ['Update Now'], defaultId: 0, cancelId: -1, }) @@ -228,13 +236,13 @@ export function createDialogPrompter(): UpdatePrompter { const response = await show({ type: 'info', - title: t('update.dialog.availableTitle'), - message: `${t('update.dialog.availableMessage', { version })}${notesText}`, - buttons: [ - t('update.dialog.downloadNow'), - t('update.dialog.later'), - t('update.dialog.skipVersion'), - ], + title: isKo ? '새 버전 업데이트' : 'Software Update', + message: isKo + ? `D3RO Voice v${version} 새 버전이 출시되었습니다. 지금 다운로드할까요?${notesText}` + : `A new version of D3RO Voice (v${version}) is available. Would you like to download it now?${notesText}`, + buttons: isKo + ? ['지금 다운로드', '나중에', '이 버전 건너뛰기'] + : ['Download Now', 'Later', 'Skip This Version'], defaultId: 0, cancelId: 1, }) @@ -244,14 +252,16 @@ export function createDialogPrompter(): UpdatePrompter { }, async askRestart(version, { mandatory }): Promise { - const t = getPopupTranslator() + const isKo = isKorean() if (mandatory) { // 필수 업데이트는 미룰 수 없다 — 작업을 마칠 시간만 주고, 닫아도 재시작한다. await show({ type: 'warning', - title: t('update.dialog.requiredInstallTitle'), - message: t('update.dialog.requiredRestartMessage', { version }), - buttons: [t('update.dialog.restartInstallNow')], + title: isKo ? '필수 업데이트 설치' : 'Required Update', + message: isKo + ? `D3RO Voice v${version} 필수 업데이트가 준비되었습니다. 확인을 누르면 앱을 재시작하여 설치합니다.` + : `Required update D3RO Voice v${version} is ready. The app will restart to install it when you continue.`, + buttons: isKo ? ['지금 재시작 및 설치'] : ['Restart & Install Now'], defaultId: 0, cancelId: 0, }) @@ -259,9 +269,11 @@ export function createDialogPrompter(): UpdatePrompter { } const response = await show({ type: 'info', - title: t('update.dialog.readyTitle'), - message: t('update.dialog.readyMessage', { version }), - buttons: [t('update.dialog.restartInstallNow'), t('update.dialog.installOnExit')], + title: isKo ? '업데이트 준비 완료' : 'Update Ready', + message: isKo + ? `D3RO Voice v${version} 다운로드가 완료되었습니다. 지금 앱을 재시작하여 설치를 완료할까요?` + : `D3RO Voice v${version} has been downloaded. Restart now to complete installation?`, + buttons: isKo ? ['지금 재시작 및 설치', '종료 시 자동 설치'] : ['Restart & Install Now', 'Install on Exit'], defaultId: 0, cancelId: 1, }) diff --git a/apps/desktop/src/main/update-dialog-preview.ts b/apps/desktop/src/main/update-dialog-preview.ts deleted file mode 100644 index cfc14903..00000000 --- a/apps/desktop/src/main/update-dialog-preview.ts +++ /dev/null @@ -1,21 +0,0 @@ -// 명시적으로 요청한 수동 QA 실행에서만 native updater dialog를 순서대로 보여 준다. -// 실제 feed, 다운로드, 설치, 사용자 설정은 건드리지 않는다. - -export const UPDATE_DIALOG_PREVIEW_ARG = '--preview-update-dialogs' - -export function isUpdateDialogPreviewRequested(argv: readonly string[] = process.argv): boolean { - return argv.includes(UPDATE_DIALOG_PREVIEW_ARG) -} - -export async function runUpdateDialogPreview(): Promise { - const { createDialogPrompter } = await import('./services/update-adapters') - const prompter = createDialogPrompter() - const version = '99.0.0-preview' - - // 반환값은 의도적으로 버린다. 이 진입점은 native layout/interaction만 확인하며 - // UpdateService나 electron-updater를 만들지 않으므로 다운로드·설치 부작용이 없다. - await prompter.askConsent({ version, releaseNotes: undefined, mandatory: false }) - await prompter.askConsent({ version, releaseNotes: undefined, mandatory: true }) - await prompter.askRestart(version, { mandatory: false }) - await prompter.askRestart(version, { mandatory: true }) -} diff --git a/apps/desktop/src/main/utils/feature-gate.ts b/apps/desktop/src/main/utils/feature-gate.ts new file mode 100644 index 00000000..19b5039f --- /dev/null +++ b/apps/desktop/src/main/utils/feature-gate.ts @@ -0,0 +1,72 @@ +// src/main/utils/feature-gate.ts +// Phase 11: Feature gating 유틸리티 +// 서비스에서 기능 사용 전 호출하여 접근 권한 확인 + 쿼터 차단 + +import { getLicenseService } from '../services/LicenseService' +import { D3ROError, ErrorCode } from '@d3ro/core/errors' +import type { FeatureAccess } from '@d3ro/core/types' +import { Feature } from '@d3ro/core/types' + +/** + * 기능 접근 권한을 확인하고, 불가 시 D3ROError를 throw한다. + * 서비스의 진입점에서 호출하여 게이팅한다. + * + * @throws D3ROError(QuotaExceeded) 일일 쿼터 초과 시 + * @throws D3ROError(TierRequired) 티어 부족 시 + */ +export function requireFeature(feature: Feature): void { + const access = getLicenseService().canUse(feature) + if (access.allowed) return + + if (access.reason === 'quota_exceeded') { + getLicenseService().promptUpgrade(feature, 'quota_exceeded') + throw new D3ROError( + ErrorCode.QuotaExceeded, + `Daily quota exceeded for ${feature}. Upgrade to Pro for unlimited access.`, + { + feature, + quota: access.quota, + requiredTier: access.requiredTier, + } + ) + } + + if (access.reason === 'tier_required') { + getLicenseService().promptUpgrade(feature, 'tier_required') + throw new D3ROError( + ErrorCode.TierRequired, + `Feature "${feature}" requires ${access.requiredTier ?? 'pro'} tier.`, + { + feature, + requiredTier: access.requiredTier, + } + ) + } + + // license_expired 등 기타 사유 + throw new D3ROError( + ErrorCode.FeatureNotAvailable, + `Feature "${feature}" is not available: ${access.reason}`, + { feature, reason: access.reason } + ) +} + +/** + * 기능 접근 가능 여부를 확인하고 결과를 반환한다 (throw하지 않음). + * UI에서 버튼 활성/비활성 등 조건부 렌더링에 사용한다. + */ +export function checkFeature(feature: Feature): FeatureAccess { + return getLicenseService().canUse(feature) +} + +/** + * 쿼터가 있는 기능의 사용을 기록한다. + * requireFeature() 통과 후, 실제 작업 성공 시 호출한다. + * + * @throws D3ROError(QuotaExceeded) 쿼터 초과 시 (이중 안전장치) + */ +export function consumeFeature(feature: Feature): void { + getLicenseService().consumeQuota(feature) +} + +export { Feature } diff --git a/apps/desktop/src/main/utils/paths.ts b/apps/desktop/src/main/utils/paths.ts index 60ce15a0..97d1a987 100644 --- a/apps/desktop/src/main/utils/paths.ts +++ b/apps/desktop/src/main/utils/paths.ts @@ -135,6 +135,23 @@ export function getSoxPath(): string { return cachedSoxPath } +/** + * rec 실행 파일 경로 (SoX의 음 명령). + * node-record-lpcm16은 rec를 사용한다. + */ +export function getRecPath(): string { + const recBin = `rec${EXE_SUFFIX}` + const bundledRec = isPackaged() + ? packagedResourcePath('sox', recBin) + : devResourcePath('sox', recBin) + + if (existsSync(bundledRec)) { + return bundledRec + } + + return 'rec' +} + /** sidecar 실행 방법 */ export interface SidecarLaunch { command: string @@ -268,6 +285,13 @@ export function getFfmpegPath(): string { return 'ffmpeg' } +/** + * 사용자 데이터 경로 (DB, 로그 등). + */ +export function getUserDataPath(): string { + return app.getPath('userData') +} + /** * Whisper 모델 사전 다운로드 디렉토리. * sidecar --models-dir로 전달되며, 메인 프로세스의 downloaded 판정에도 사용된다. @@ -288,4 +312,4 @@ export function getAppIconPath(): string | null { ? packagedResourcePath('icons', filename) : path.join(getAppRoot(), 'build', filename) return existsSync(candidate) ? candidate : null -} +} \ No newline at end of file diff --git a/apps/desktop/src/main/windows/TrayManager.ts b/apps/desktop/src/main/windows/TrayManager.ts index 622cc3dd..652cc0b2 100644 --- a/apps/desktop/src/main/windows/TrayManager.ts +++ b/apps/desktop/src/main/windows/TrayManager.ts @@ -42,3 +42,7 @@ export function createTray(): void { logger.info('Tray created') } + +export function getTray(): Tray | null { + return tray +} diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts index 818dfbb3..fa796ad6 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -793,9 +793,6 @@ const electronAPI = { on(IPC_CHANNELS.MEETING_MODE.STATE_CHANGED, cb), onSegment: (cb: (e: CaptionSegment) => void): Unsubscribe => on(IPC_CHANNELS.MEETING_MODE.SEGMENT, cb), - /** 다듬기(학습 어휘·LLM 교열)로 바뀐 확정 줄 — 화면이 원문에 머물지 않게 갱신한다 */ - onSegmentUpdated: (cb: (e: { id: string; text: string }) => void): Unsubscribe => - on(IPC_CHANNELS.MEETING_MODE.SEGMENT_UPDATED, cb), onProcessingProgress: (cb: (e: MeetingProcessingProgress) => void): Unsubscribe => on(IPC_CHANNELS.MEETING_MODE.PROCESSING_PROGRESS, cb), onSessionCompleted: (cb: (e: MeetingSessionDetail) => void): Unsubscribe => diff --git a/apps/desktop/src/renderer/components/OnboardingModal.tsx b/apps/desktop/src/renderer/components/OnboardingModal.tsx index 43cd20c3..169e16b7 100644 --- a/apps/desktop/src/renderer/components/OnboardingModal.tsx +++ b/apps/desktop/src/renderer/components/OnboardingModal.tsx @@ -68,15 +68,13 @@ interface ModeCardProps { points: readonly string[] action: React.ReactNode onSelect: () => void - testId: string } /** 사용 방식 카드 — 카드 전체를 눌러도, 안의 버튼(키보드 포커스·Enter)으로도 고를 수 있다. */ -function ModeCard({ icon, title, badge, description, points, action, onSelect, testId }: ModeCardProps): React.ReactElement { +function ModeCard({ icon, title, badge, description, points, action, onSelect }: ModeCardProps): React.ReactElement { return ( t(key))} onSelect={handleSelectLocalMode} - testId="onboarding-mode-local" action={ // 첫 포커스 — Enter 로 권장 경로를 바로 시작한다. 클릭은 카드 onClick 으로 전파된다.