diff --git a/.agents/rules/desktop-app-execution-and-windows.md b/.agents/rules/desktop-app-execution-and-windows.md index 2c58a9b..f289da9 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` 또는 `pnpm --filter @d3ro/desktop dev`를 실행하도록 안내한다. + - GUI 테스트/실행이 필요할 때는 사용자가 직접 외부 터미널 또는 파일 탐색기에서 `run-desktop.bat` 또는 `npm run dev --workspace=@d3ro/desktop`를 실행하도록 안내한다. ## 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 6cc70ae..d9c7f9a 100644 --- a/.claude/skills/implement-phase/SKILL.md +++ b/.claude/skills/implement-phase/SKILL.md @@ -42,23 +42,24 @@ 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/`) +3. 앱별 구현체 (`apps/desktop/`, `apps/web/`, `apps/mobile-rn/`) 4. `packages/ui/` 공유 컴포넌트 5. `packages/i18n/` i18n 키 6. Supabase 마이그레이션 (필요 시) ## 3. 검증 ```bash -npm run typecheck # 또는 pnpm turbo typecheck +npm run typecheck # root npm workspaces npm run build ``` -## 4. 자동 체이닝 (완료 후) +## 4. 완료 후 체이닝 -구현 완료 시 **자동으로** 다음을 순서대로 실행: +구현 완료 시 다음을 순서대로 실행: 1. `/review-phase $ARGUMENTS` — 코드 리뷰 -2. 리뷰 GO → `/test-and-commit` — 테스트 + 커밋 -3. `memory/project_status.md` 갱신 (즉시) +2. 리뷰 GO → 관련 테스트와 전체 게이트 실행 +3. `docs/map/*`와 해당 SSOT 갱신 +4. 커밋·푸시는 사용자가 명시적으로 요청한 경우에만 실행 유저가 중단을 요청하지 않는 한 끝까지 진행. diff --git a/.claude/skills/refactor-wave/SKILL.md b/.claude/skills/refactor-wave/SKILL.md index 9aebd3b..ce22926 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, electron.vite.config, electron-builder.yml, turbo.json, Vanilla JS 팝업) | +| WS5 | 빌드/설정/팝업 (package.json, workspace/CI scripts, electron.vite.config, electron-builder.yml, Vanilla JS 팝업) | - 같은 파일을 두 워크스트림이 건드리면 충돌 → 분담 시 영역 명시 - WS3는 WS1 산출물(토큰 정의) 의존이라 1차 완료 후 발사 diff --git a/.env.example b/.env.example index bee1158..4a83381 100644 --- a/.env.example +++ b/.env.example @@ -75,6 +75,9 @@ 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 8a657b5..81be11d 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -62,6 +62,11 @@ 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 @@ -74,6 +79,11 @@ 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 @@ -120,6 +130,9 @@ 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 55fe728..7b9cd5b 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -32,6 +32,8 @@ 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 fcca68a..e20d5eb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,8 +74,15 @@ 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`. Mobile: `npm --prefix apps/mobile-rn run lint|typecheck|test`. +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). --- @@ -106,6 +113,7 @@ 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/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..1ddaf59 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,11 @@ +# 보호 수용 테스트 (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/package.json b/apps/admin/package.json index 9b2656f..6dd2c29 100644 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -7,7 +7,7 @@ "dev": "next dev --port 3001", "build": "next build", "start": "next start --port 3001", - "typecheck": "tsc --noEmit" + "typecheck": "next typegen && tsc --noEmit" }, "dependencies": { "@d3ro/api-client": "*", @@ -24,8 +24,7 @@ "lucide-react": "^1.33.0", "next": "16.3.1", "react": "^19.0.0", - "react-dom": "^19.0.0", - "recharts": "^2.15.0" + "react-dom": "^19.0.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 deleted file mode 100644 index 20ee032..0000000 --- a/apps/admin/src/components/charts/dau-chart.tsx +++ /dev/null @@ -1,60 +0,0 @@ -'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 deleted file mode 100644 index 820a6ef..0000000 --- a/apps/admin/src/components/charts/feature-usage-chart.tsx +++ /dev/null @@ -1,88 +0,0 @@ -'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 deleted file mode 100644 index 148eab8..0000000 --- a/apps/admin/src/components/charts/top-users-chart.tsx +++ /dev/null @@ -1,65 +0,0 @@ -'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/desktop/run_e2e_cdp.cjs b/apps/desktop/run_e2e_cdp.cjs deleted file mode 100644 index ba14e4f..0000000 --- a/apps/desktop/run_e2e_cdp.cjs +++ /dev/null @@ -1,133 +0,0 @@ -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 deleted file mode 100644 index 4099436..0000000 --- a/apps/desktop/run_e2e_full_suite.cjs +++ /dev/null @@ -1,147 +0,0 @@ -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 a9f83cc..8561aa6 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -17,8 +17,10 @@ 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 */ }) @@ -31,12 +33,14 @@ process.on('uncaughtException', (err) => { // V2-4: deep link 프로토콜 등록 — d3ro-voice://auth-callback?code=... const PROTOCOL = 'd3ro-voice' -if (process.defaultApp) { - if (process.argv.length >= 2) { - app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [path.resolve(process.argv[1])]) +if (!updateDialogPreviewRequested) { + if (process.defaultApp) { + if (process.argv.length >= 2) { + app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [path.resolve(process.argv[1])]) + } + } else { + app.setAsDefaultProtocolClient(PROTOCOL) } -} else { - app.setAsDefaultProtocolClient(PROTOCOL) } /** @@ -130,7 +134,10 @@ async function handleDeepLink(url: string): Promise { } // 단일 인스턴스 잠금 (테스트 모드에서는 다중 인스턴스 허용) -const gotTheLock = process.env.NODE_ENV === 'test' ? true : app.requestSingleInstanceLock() +const gotTheLock = + process.env.NODE_ENV === 'test' || updateDialogPreviewRequested + ? true + : app.requestSingleInstanceLock() if (!gotTheLock) { deepLinkLogger.info('Another instance is already running. Existing window focused.') @@ -170,6 +177,17 @@ 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/UiaContextService.ts b/apps/desktop/src/main/services/UiaContextService.ts index acb412d..4346d5e 100644 --- a/apps/desktop/src/main/services/UiaContextService.ts +++ b/apps/desktop/src/main/services/UiaContextService.ts @@ -12,7 +12,6 @@ // - 읽기 실패/타임아웃은 텍스트를 쓰지 않는다 (available=false). // - 실패 후에는 백오프를 걸어 매 키입력마다 사이드카를 두드리지 않는다. -import { D3ROError, ErrorCode } from '@d3ro/core/errors' import { emptyFocusSnapshot, type FocusSnapshot, @@ -208,8 +207,3 @@ 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/global-input-hook.ts b/apps/desktop/src/main/services/global-input-hook.ts index c8684c6..0b94b3e 100644 --- a/apps/desktop/src/main/services/global-input-hook.ts +++ b/apps/desktop/src/main/services/global-input-hook.ts @@ -54,16 +54,8 @@ 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/sync/builtin-instruction-sync.ts b/apps/desktop/src/main/services/sync/builtin-instruction-sync.ts index 743c5fd..6ea359a 100644 --- a/apps/desktop/src/main/services/sync/builtin-instruction-sync.ts +++ b/apps/desktop/src/main/services/sync/builtin-instruction-sync.ts @@ -19,10 +19,6 @@ 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 c71768e..49ca2da 100644 --- a/apps/desktop/src/main/services/update-adapters.ts +++ b/apps/desktop/src/main/services/update-adapters.ts @@ -6,8 +6,7 @@ import { existsSync, readdirSync } from 'node:fs' import { dirname, join } from 'node:path' import { app, dialog } from 'electron' import { getLogger } from './LoggerService' -import { configGet } from './ConfigService' -import { getMainWindow } from '../windows/WindowManager' +import { getMainWindow, getPopupTranslator } 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' @@ -195,12 +194,8 @@ export function createRemotePolicySource( } } -/** - * electron dialog 기반 프롬프터. - * TODO(i18n): 문구가 아직 ko/en 인라인이다 — update.* 키를 locale 파일에 추가한 뒤 t() 로 옮긴다. - */ +/** electron dialog 기반 프롬프터. 문구는 현재 앱 로케일의 update.dialog.* 키에서 가져온다. */ 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 } = @@ -212,22 +207,19 @@ export function createDialogPrompter(): UpdatePrompter { return { async askConsent({ version, releaseNotes, mandatory }): Promise { - 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).' - : '' + 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')}` : '' if (mandatory) { const response = await show({ type: 'info', - title: isKo ? '필수 업데이트' : 'Required Update', - message: isKo - ? `D3RO Voice v${version} 업데이트가 필요합니다.${mandatoryNote}${notesText}` - : `D3RO Voice v${version} is required.${mandatoryNote}${notesText}`, - buttons: isKo ? ['지금 업데이트'] : ['Update Now'], + title: t('update.dialog.requiredTitle'), + message: `${t('update.dialog.requiredMessage', { version })}${mandatoryNote}${notesText}`, + buttons: [t('update.dialog.updateNow')], defaultId: 0, cancelId: -1, }) @@ -236,13 +228,13 @@ export function createDialogPrompter(): UpdatePrompter { const response = await show({ type: 'info', - 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'], + 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'), + ], defaultId: 0, cancelId: 1, }) @@ -252,16 +244,14 @@ export function createDialogPrompter(): UpdatePrompter { }, async askRestart(version, { mandatory }): Promise { - const isKo = isKorean() + const t = getPopupTranslator() if (mandatory) { // 필수 업데이트는 미룰 수 없다 — 작업을 마칠 시간만 주고, 닫아도 재시작한다. await show({ type: 'warning', - 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'], + title: t('update.dialog.requiredInstallTitle'), + message: t('update.dialog.requiredRestartMessage', { version }), + buttons: [t('update.dialog.restartInstallNow')], defaultId: 0, cancelId: 0, }) @@ -269,11 +259,9 @@ export function createDialogPrompter(): UpdatePrompter { } const response = await show({ type: 'info', - 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'], + title: t('update.dialog.readyTitle'), + message: t('update.dialog.readyMessage', { version }), + buttons: [t('update.dialog.restartInstallNow'), t('update.dialog.installOnExit')], defaultId: 0, cancelId: 1, }) diff --git a/apps/desktop/src/main/update-dialog-preview.ts b/apps/desktop/src/main/update-dialog-preview.ts new file mode 100644 index 0000000..cfc1490 --- /dev/null +++ b/apps/desktop/src/main/update-dialog-preview.ts @@ -0,0 +1,21 @@ +// 명시적으로 요청한 수동 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 deleted file mode 100644 index 19b5039..0000000 --- a/apps/desktop/src/main/utils/feature-gate.ts +++ /dev/null @@ -1,72 +0,0 @@ -// 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 97d1a98..60ce15a 100644 --- a/apps/desktop/src/main/utils/paths.ts +++ b/apps/desktop/src/main/utils/paths.ts @@ -135,23 +135,6 @@ 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 @@ -285,13 +268,6 @@ export function getFfmpegPath(): string { return 'ffmpeg' } -/** - * 사용자 데이터 경로 (DB, 로그 등). - */ -export function getUserDataPath(): string { - return app.getPath('userData') -} - /** * Whisper 모델 사전 다운로드 디렉토리. * sidecar --models-dir로 전달되며, 메인 프로세스의 downloaded 판정에도 사용된다. @@ -312,4 +288,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 652cc0b..622cc3d 100644 --- a/apps/desktop/src/main/windows/TrayManager.ts +++ b/apps/desktop/src/main/windows/TrayManager.ts @@ -42,7 +42,3 @@ export function createTray(): void { logger.info('Tray created') } - -export function getTray(): Tray | null { - return tray -} diff --git a/apps/desktop/src/renderer/components/OnboardingModal.tsx b/apps/desktop/src/renderer/components/OnboardingModal.tsx index 169e16b..43cd20c 100644 --- a/apps/desktop/src/renderer/components/OnboardingModal.tsx +++ b/apps/desktop/src/renderer/components/OnboardingModal.tsx @@ -68,13 +68,15 @@ interface ModeCardProps { points: readonly string[] action: React.ReactNode onSelect: () => void + testId: string } /** 사용 방식 카드 — 카드 전체를 눌러도, 안의 버튼(키보드 포커스·Enter)으로도 고를 수 있다. */ -function ModeCard({ icon, title, badge, description, points, action, onSelect }: ModeCardProps): React.ReactElement { +function ModeCard({ icon, title, badge, description, points, action, onSelect, testId }: ModeCardProps): React.ReactElement { return ( t(key))} onSelect={handleSelectLocalMode} + testId="onboarding-mode-local" action={ // 첫 포커스 — Enter 로 권장 경로를 바로 시작한다. 클릭은 카드 onClick 으로 전파된다.