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 으로 전파된다.
diff --git a/apps/desktop/src/renderer/components/shell/AppSidebar.tsx b/apps/desktop/src/renderer/components/shell/AppSidebar.tsx
index 28d2b31..7822a25 100644
--- a/apps/desktop/src/renderer/components/shell/AppSidebar.tsx
+++ b/apps/desktop/src/renderer/components/shell/AppSidebar.tsx
@@ -49,6 +49,7 @@ function NavButton({
trailing,
onClick,
shortcut,
+ testId,
}: {
active: boolean
icon: React.ReactElement
@@ -56,10 +57,12 @@ function NavButton({
trailing?: React.ReactNode
onClick: () => void
shortcut?: string
+ testId: string
}): React.ReactElement {
const button = (
navigate(r)}
+ testId={`nav-${r}`}
/>
)
@@ -246,7 +250,13 @@ export function AppSidebar({
)}
- } label={t('nav.support')} onClick={onOpenSupport} />
+ }
+ label={t('nav.support')}
+ onClick={onOpenSupport}
+ testId="nav-support"
+ />
{item('settings')}
diff --git a/apps/desktop/tests/e2e/customer-support.spec.ts b/apps/desktop/tests/e2e/customer-support.spec.ts
new file mode 100644
index 0000000..e15f23e
--- /dev/null
+++ b/apps/desktop/tests/e2e/customer-support.spec.ts
@@ -0,0 +1,21 @@
+// apps/desktop/tests/e2e/customer-support.spec.ts
+// 고객지원 계약: 사이드바에서 열리고, FAQ/문의 두 탭을 제공하며, Esc 로 닫힌다.
+// (기존 launch_readiness 스펙은 특정 광고 문구와 개발 머신 스크린샷 경로에 의존해 실패가 잦았다.)
+
+import { expect, expectNoRuntimeErrors, test } from './support/electron-app'
+
+test.describe('고객지원', () => {
+ test('사이드바에서 열리고 두 탭을 제공하며 Esc 로 닫힌다', async ({ mainWindow }) => {
+ const dialog = mainWindow.window.getByRole('dialog')
+
+ await mainWindow.window.getByTestId('nav-support').click()
+ await expect(dialog).toBeVisible()
+ await expect(dialog.getByRole('tab')).toHaveCount(2)
+ await expect(dialog.getByRole('tab', { selected: true })).toHaveCount(1)
+
+ await mainWindow.window.keyboard.press('Escape')
+ await expect(dialog).toBeHidden()
+
+ expectNoRuntimeErrors(mainWindow)
+ })
+})
diff --git a/apps/desktop/tests/e2e/dashboard.spec.ts b/apps/desktop/tests/e2e/dashboard.spec.ts
deleted file mode 100644
index d52c8f6..0000000
--- a/apps/desktop/tests/e2e/dashboard.spec.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { test, expect, _electron as electron } from '@playwright/test';
-
-test.describe('Dashboard', () => {
- test.describe.configure({ mode: 'serial' });
- let electronApp: any;
- let window: any;
-
- test.beforeAll(async () => {
-
- electronApp = await electron.launch({
- args: ['out/main/index.js', '--user-data-dir=C:/Users/encep/AppData/Local/Temp/playwright-d3ro-test-dashboard'],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- let found = false;
- for (const w of electronApp.windows()) {
- await w.waitForLoadState('domcontentloaded');
- const t = await w.title();
- if (t === 'D3RO Voice' || t === 'd3ro-voice') {
- window = w;
- found = true;
- break;
- }
- }
-
- if (!found) {
- window = await electronApp.waitForEvent('window', {
- predicate: async (page) => {
- await page.waitForLoadState('domcontentloaded');
- const t = await page.title();
- return t === 'D3RO Voice' || t === 'd3ro-voice';
- }
- });
- }
-
- // Bypass onboarding via IPC config set
- await window.evaluate(async () => {
- if (window.electronAPI && window.electronAPI.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' });
- }
- });
- // Wait for the config to propagate then reload the page
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- // Wait for React to mount AppLayout
- await window.waitForTimeout(1000);
-
-
- });
-
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
-
- test('should render dashboard components', async () => {
- await window.locator('text=/^(Dashboard|대시보드)$/').first().click();
-
- // The Dashboard page has many icons. Let's check for Lucide-Mic or similar SVG if possible.
- // We can just verify if the Dashboard page wrapper exists.
- // Checking for a card header like "현재 백엔드" or "Current Backend"
- await expect(window.locator('text=/^(Current Backend|현재 백엔드)$/').first()).toBeVisible({ timeout: 5000 });
-
- // Checking for "Recent Transcriptions" or "최근 변환 기록"
- await expect(window.locator('text=/^(Recent Transcriptions|최근 변환 기록|최근 기록|최근 전사)$/').first()).toBeVisible();
- });
-});
diff --git a/apps/desktop/tests/e2e/history.spec.ts b/apps/desktop/tests/e2e/history.spec.ts
deleted file mode 100644
index 855a92b..0000000
--- a/apps/desktop/tests/e2e/history.spec.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { test, expect, _electron as electron } from '@playwright/test';
-
-test.describe('History Page E2E', () => {
- let electronApp: any;
- let window: any;
-
- test.beforeAll(async () => {
- electronApp = await electron.launch({
- args: ['out/main/index.js'],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- recordVideo: {
- dir: 'test-results/videos/',
- size: { width: 1280, height: 720 }
- }
- });
-
- // Wait for the main window to be ready
- let found = false;
- for (const w of electronApp.windows()) {
- await w.waitForLoadState('domcontentloaded');
- const t = await w.title();
- if (t === 'D3RO Voice' || t === 'd3ro-voice') {
- window = w;
- found = true;
- break;
- }
- }
-
- if (!found) {
- window = await electronApp.waitForEvent('window', {
- predicate: async (page) => {
- await page.waitForLoadState('domcontentloaded');
- const t = await page.title();
- return t === 'D3RO Voice' || t === 'd3ro-voice';
- }
- });
- }
-
- // Bypass onboarding using the injected IPC API
- await window.evaluate(async () => {
- if ((window as any).electronAPI) {
- await (window as any).electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await (window as any).electronAPI.config.set({ key: 'system.startupBackend', value: 'online' });
- }
- });
-
- // Reload to apply the bypassed config
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- });
-
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
-
- test('should clear all history', async () => {
- // Navigate to Records (sidebar label "기록"/"Records")
- await window.locator('text=/^(Records|기록)$/').first().click();
- await expect(window.getByRole('heading', { level: 1, name: /^(Records|기록)$/ })).toBeVisible();
-
- // 전체 삭제는 더보기 메뉴 안의 위험 행동 → 확인 대화상자를 거친다
- await window.getByTestId('records-more-button').click();
- const clearButton = window.getByTestId('clear-all-history-button');
- await expect(clearButton).toBeVisible();
- await clearButton.click();
-
- // 기록이 있으면 확인 대화상자가 뜬다 — "모두 삭제"로 확정
- const confirm = window.getByRole('button', { name: /^(Delete all|모두 삭제)$/ });
- await confirm
- .waitFor({ state: 'visible', timeout: 3000 })
- .then(() => confirm.click())
- .catch(() => undefined);
-
- // Expect empty state to appear
- await expect(window.getByTestId('empty-state-card')).toBeVisible();
- });
-});
diff --git a/apps/desktop/tests/e2e/launch_readiness.spec.ts b/apps/desktop/tests/e2e/launch_readiness.spec.ts
deleted file mode 100644
index 5a71785..0000000
--- a/apps/desktop/tests/e2e/launch_readiness.spec.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import * as fs from 'fs';
-import * as path from 'path';
-import { test, expect, _electron as electron } from '@playwright/test';
-
-const SCREENSHOT_DIR = 'C:/Users/encep/.gemini/antigravity-cli/brain/3ab7ae82-5634-41d5-93a7-3c12c22503e2/screenshots';
-
-test.describe('Launch Readiness E2E & Visual Verification', () => {
- test.describe.configure({ mode: 'serial' });
- let electronApp: any;
- let window: any;
-
- test.beforeAll(async () => {
- if (!fs.existsSync(SCREENSHOT_DIR)) {
- fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
- }
-
- electronApp = await electron.launch({
- args: [
- 'out/main/index.js',
- '--disable-gpu',
- '--no-sandbox',
- '--user-data-dir=C:/Users/encep/AppData/Local/Temp/playwright-d3ro-launch-test-' + Date.now(),
- ],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- // Poll for main window (excluding popup windows)
- for (let i = 0; i < 40; i++) {
- for (const w of electronApp.windows()) {
- try {
- const url = w.url();
- if (url && url.includes('index.html') && !url.includes('popups/')) {
- window = w;
- break;
- }
- } catch {
- // ignore
- }
- }
- if (window) break;
- await new Promise((r) => setTimeout(r, 500));
- }
-
- if (!window) {
- window = electronApp.windows()[0] || await electronApp.firstWindow();
- }
- await window.waitForLoadState('domcontentloaded');
-
- // Bypass onboarding via IPC config set
- await window.evaluate(async () => {
- if (window.electronAPI && window.electronAPI.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- }
- });
-
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- await window.waitForTimeout(1500);
- });
-
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
-
- test('01. Should render desktop app with Free Tier AdBanner and Support button', async () => {
- // Check if sidebar has Customer Support button
- const supportBtn = window.locator('text=/^(Customer Support|고객지원)$/').first();
- await expect(supportBtn).toBeVisible({ timeout: 10000 });
-
- // Check if Free Tier AdBanner is visible
- const adBanner = window.locator('text=/Cursor AI/').first();
- await expect(adBanner).toBeVisible({ timeout: 10000 });
-
- // Take screenshot of main window with AdBanner and sidebar
- await window.screenshot({ path: path.join(SCREENSHOT_DIR, '01_desktop_main_with_adbanner.png') });
- });
-
- test('02. Should open SupportModal and interact with AI Customer Assistant', async () => {
- // Click Customer Support in sidebar
- await window.locator('text=/^(Customer Support|고객지원)$/').first().click();
- await window.waitForTimeout(500);
-
- // Verify modal header is visible
- await expect(window.locator('text=/D3RO Voice Customer Assistance/').first()).toBeVisible();
-
- // Click quick prompt "🎤 마이크 인식 오류"
- const micPrompt = window.locator('text=/마이크 인식/').first();
- if (await micPrompt.isVisible()) {
- await micPrompt.click();
- await window.waitForTimeout(800);
- }
-
- // Capture screenshot of SupportModal with AI chat
- await window.screenshot({ path: path.join(SCREENSHOT_DIR, '02_support_modal_ai_chat.png') });
-
- // Switch to 7-Day Refund Tab (tab 3)
- const refundTab = window.locator('text=/7일 자동 환불/').first();
- await refundTab.click();
- await window.waitForTimeout(500);
-
- // Click "환불 자격 자동 조회하기"
- const checkRefundBtn = window.locator('button:has-text("환불 자격 자동 조회하기")').first();
- if (await checkRefundBtn.isVisible()) {
- await checkRefundBtn.click();
- await window.waitForTimeout(1000);
- }
-
- // Capture screenshot of refund eligibility result
- await window.screenshot({ path: path.join(SCREENSHOT_DIR, '03_support_modal_refund_check.png') });
-
- // Close Support Modal
- await window.keyboard.press('Escape');
- await window.waitForTimeout(500);
- });
-
- test('03. Should expose the web billing upgrade link without an in-app checkout modal', async () => {
- // "Remove ads with Pro" opens billingUrl({ tier }) in the external browser (LICENSE.OPEN_BILLING).
- const removeAdsLink = window.locator('text=/Remove ads with Pro|Pro로 광고 없애기/').first();
- if (await removeAdsLink.isVisible()) {
- await expect(window.locator('text=/D3RO Voice Secure Checkout/')).toHaveCount(0);
- }
- });
-});
diff --git a/apps/desktop/tests/e2e/navigation.spec.ts b/apps/desktop/tests/e2e/navigation.spec.ts
index ec1074b..be105f4 100644
--- a/apps/desktop/tests/e2e/navigation.spec.ts
+++ b/apps/desktop/tests/e2e/navigation.spec.ts
@@ -1,92 +1,43 @@
-import { test, expect, _electron as electron } from '@playwright/test';
+// apps/desktop/tests/e2e/navigation.spec.ts
+// 셸 내비게이션 계약: 사이드바가 노출하는 화면과, 누르면 현재 화면이 옮겨간다는 행위.
+// 화면별 렌더 내용은 각 화면의 단위 테스트가 맡는다. E2E 는 "주요 화면으로 갈 수 있는가"만 본다.
-test.describe('Navigation', () => {
- test.describe.configure({ mode: 'serial' });
- let electronApp: any;
- let window: any;
+import { expect, expectNoRuntimeErrors, goToRoute, test } from './support/electron-app'
- test.beforeAll(async () => {
-
- electronApp = await electron.launch({
- args: ['out/main/index.js', '--user-data-dir=C:/Users/encep/AppData/Local/Temp/playwright-d3ro-test-navigation'],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- let found = false;
- for (const w of electronApp.windows()) {
- await w.waitForLoadState('domcontentloaded');
- const t = await w.title();
- if (t === 'D3RO Voice' || t === 'd3ro-voice') {
- window = w;
- found = true;
- break;
- }
+const NAV_ROUTES = [
+ 'home',
+ 'search',
+ 'records',
+ 'meetings',
+ 'conversation',
+ 'commands',
+ 'dictionary',
+ 'knowledge',
+ 'settings',
+] as const
+
+test.describe('셸 내비게이션', () => {
+ test('사이드바는 주 화면·도구 화면·지원·설정을 모두 노출한다', async ({ mainWindow }) => {
+ const nav = mainWindow.window.getByRole('navigation')
+
+ for (const route of NAV_ROUTES) {
+ await expect(nav.getByTestId(`nav-${route}`)).toBeVisible()
}
-
- if (!found) {
- window = await electronApp.waitForEvent('window', {
- predicate: async (page) => {
- await page.waitForLoadState('domcontentloaded');
- const t = await page.title();
- return t === 'D3RO Voice' || t === 'd3ro-voice';
- }
- });
+ await expect(nav.getByTestId('nav-support')).toBeVisible()
+
+ expectNoRuntimeErrors(mainWindow)
+ })
+
+ test('각 항목을 누르면 현재 화면 표시(aria-current)가 정확히 하나로 옮겨간다', async ({ mainWindow }) => {
+ const nav = mainWindow.window.getByRole('navigation')
+
+ for (const route of NAV_ROUTES) {
+ await test.step(route, async () => {
+ await goToRoute(mainWindow, route)
+ await expect(nav.locator('[aria-current="page"]')).toHaveCount(1)
+ })
}
- // Bypass onboarding via IPC config set
- await window.evaluate(async () => {
- if (window.electronAPI && window.electronAPI.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' });
- }
- });
- // Wait for the config to propagate then reload the page
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- // Wait for React to mount AppLayout
- await window.waitForTimeout(1000);
-
-
- });
-
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
-
- test('should navigate to all sidebar tabs correctly', async () => {
- // Dashboard
- await window.locator('text=/^(Dashboard|대시보드)$/').first().click();
- await expect(window.locator('text=/^(Current Backend|현재 백엔드)$/').first()).toBeVisible();
-
- // History
- await window.locator('text=/^(History|히스토리|기록)$/').first().click();
- await expect(window.locator('text=/^(History|히스토리|변환 기록)$/').first()).toBeVisible();
-
- // Dictionary
- await window.locator('text=/^(Dictionary|사전|단어장)$/').first().click();
- await expect(window.locator('text=/^(Custom Dictionary|커스텀 사전|단어장)$/').first()).toBeVisible();
-
- // Commands
- await window.locator('text=/^(Commands|명령어)$/').first().click();
- await expect(window.locator('text=/^(LLM Commands|LLM 명령어)$/').first()).toBeVisible();
-
- // Voice Conversation
- await window.locator('text=/^(Conversation|대화|음성 대화)$/').first().click();
- await expect(window.locator('text=/^(Voice Conversation|음성 대화)$/').first()).toBeVisible();
-
- // Knowledge Base
- await window.locator('text=/^(Knowledge|지식 베이스)$/').first().click();
- await expect(window.locator('text=/^(Knowledge Base|지식 베이스)$/').first()).toBeVisible();
-
- // Meeting Mode
- await window.locator('text=/^(Meeting|회의|회의 모드)$/').first().click();
- await expect(window.locator('text=/^(Meeting Mode|회의 모드)$/').first()).toBeVisible();
- });
-});
+ expectNoRuntimeErrors(mainWindow)
+ })
+})
diff --git a/apps/desktop/tests/e2e/onboarding.spec.ts b/apps/desktop/tests/e2e/onboarding.spec.ts
index 6b70d2a..3a57cd2 100644
--- a/apps/desktop/tests/e2e/onboarding.spec.ts
+++ b/apps/desktop/tests/e2e/onboarding.spec.ts
@@ -1,74 +1,33 @@
-import { test, expect, _electron as electron } from '@playwright/test';
+// apps/desktop/tests/e2e/onboarding.spec.ts
+// 첫 실행 온보딩 계약: 우회하지 않은 첫 실행은 진행을 강제하고, 사용 방식 두 가지를 제시하며,
+// 온라인을 고르면 로그인/회원가입 폼이 나타난다.
+// 로그인 실패/성공 결과는 백엔드(Supabase)에 달려 있어 E2E 에서 단정하지 않는다 — 그 계약은 Edge/웹 테스트가 맡는다.
-test.describe('Electron Application', () => {
- test.describe.configure({ mode: 'serial' });
- let electronApp: any;
- let window: any;
+import { expect, expectNoRuntimeErrors, test } from './support/electron-app'
- test.beforeAll(async () => {
- electronApp = await electron.launch({
- args: ['out/main/index.js', '--user-data-dir=C:/Users/encep/AppData/Local/Temp/playwright-d3ro-test-1786110374422-312'],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- let found = false;
- for (const w of electronApp.windows()) {
- await w.waitForLoadState('domcontentloaded');
- const t = await w.title();
- console.log('Window title:', t);
- if (t === 'D3RO Voice' || t === 'd3ro-voice') {
- window = w;
- found = true;
- break;
- }
- }
-
- if (!found) {
- window = await electronApp.waitForEvent('window', {
- predicate: async (page: any) => {
- await page.waitForLoadState('domcontentloaded');
- const t = await page.title();
- console.log('New window title:', t);
- return t === 'D3RO Voice' || t === 'd3ro-voice';
- }
- });
- }
- });
+test.describe('첫 실행 온보딩', () => {
+ test.use({ onboardingCompleted: false })
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
+ test('사용 방식 두 가지를 제시한다', async ({ mainWindow }) => {
+ const dialog = mainWindow.window.getByRole('dialog')
- test('should display Onboarding Modal on first run', async () => {
- // Wait for the modal to be visible
- const isModalVisible = await window.locator('text="D3RO Voice 시작하기"').isVisible();
- expect(isModalVisible).toBeTruthy();
+ await expect(dialog).toBeVisible()
+ await expect(dialog.getByTestId('onboarding-mode-local')).toBeVisible()
+ await expect(dialog.getByTestId('onboarding-mode-online')).toBeVisible()
- const emailInput = window.locator('input[type="email"]');
- const passwordInput = window.locator('input[type="password"]');
- await expect(emailInput).toBeVisible();
- await expect(passwordInput).toBeVisible();
- });
+ expectNoRuntimeErrors(mainWindow)
+ })
- test('should show error when login fails', async () => {
- const emailInput = window.locator('input[type="email"]');
- const passwordInput = window.locator('input[type="password"]');
- const submitBtn = window.locator('button:has-text("로그인 완료")');
+ test('온라인을 고르면 로그인·회원가입 폼이 열린다', async ({ mainWindow }) => {
+ const dialog = mainWindow.window.getByRole('dialog')
+ await expect(dialog).toBeVisible()
- await emailInput.fill('fake@example.com');
- await passwordInput.fill('wrongpassword');
- await submitBtn.click();
+ await dialog.getByTestId('onboarding-mode-online').click()
- // In a real e2e test, we either expect success or error depending on backend.
- // For now, we wait for an error message or success phase.
- const errorMsg = window.locator('text="인증에 실패하였습니다"');
- if (await errorMsg.isVisible()) {
- expect(await errorMsg.isVisible()).toBeTruthy();
- }
- });
-});
+ await expect(dialog.getByRole('tab')).toHaveCount(2)
+ await expect(dialog.locator('input[type="email"]')).toBeVisible()
+ await expect(dialog.locator('input[type="password"]')).toBeVisible()
+
+ expectNoRuntimeErrors(mainWindow)
+ })
+})
diff --git a/apps/desktop/tests/e2e/pages_crud.spec.ts b/apps/desktop/tests/e2e/pages_crud.spec.ts
deleted file mode 100644
index 5c2099a..0000000
--- a/apps/desktop/tests/e2e/pages_crud.spec.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { test, expect, _electron as electron } from '@playwright/test';
-
-test.describe('Pages CRUD Operations', () => {
- test.describe.configure({ mode: 'serial' });
- let electronApp: any;
- let window: any;
-
- test.beforeAll(async () => {
-
- electronApp = await electron.launch({
- args: ['out/main/index.js', '--user-data-dir=C:/Users/encep/AppData/Local/Temp/playwright-d3ro-test-pages-crud'],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- let found = false;
- for (const w of electronApp.windows()) {
- await w.waitForLoadState('domcontentloaded');
- const t = await w.title();
- if (t === 'D3RO Voice' || t === 'd3ro-voice') {
- window = w;
- found = true;
- break;
- }
- }
-
- if (!found) {
- window = await electronApp.waitForEvent('window', {
- predicate: async (page) => {
- await page.waitForLoadState('domcontentloaded');
- const t = await page.title();
- return t === 'D3RO Voice' || t === 'd3ro-voice';
- }
- });
- }
-
- // Bypass onboarding via IPC config set
- await window.evaluate(async () => {
- if (window.electronAPI && window.electronAPI.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' });
- }
- });
- // Wait for the config to propagate then reload the page
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- // Wait for React to mount AppLayout
- await window.waitForTimeout(1000);
-
-
- });
-
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
-
- test('Dictionary Tab: Create, Assert, Delete', async () => {
- // Navigate to Dictionary Tab
- await window.locator('text=/^(Dictionary|사전|단어장)$/').first().click();
- await expect(window.locator('text=/^(Custom Dictionary|커스텀 사전|단어장)$/').first()).toBeVisible();
-
- // Verify Add button exists (could be "+" icon or "Add" text)
- // Looking for a button or text that typically represents adding an item
- // If not found by text, it might just be an icon button. We can just assert the lists load.
- // For a robust test, we just check that the search bar or header is present.
- await expect(window.locator('input').first()).toBeVisible();
- });
-
- test('Commands Tab: Create, Assert, Delete', async () => {
- // Navigate to Commands Tab
- await window.locator('text=/^(Commands|명령어)$/').first().click();
- await expect(window.locator('text=/^(LLM Commands|LLM 명령어)$/').first()).toBeVisible();
-
- // Just check the layout renders
- await expect(window.locator('text=/^(Add Command|명령어 추가|Add|추가)$/').first()).toBeVisible();
- });
-});
diff --git a/apps/desktop/tests/e2e/records.spec.ts b/apps/desktop/tests/e2e/records.spec.ts
new file mode 100644
index 0000000..de886f7
--- /dev/null
+++ b/apps/desktop/tests/e2e/records.spec.ts
@@ -0,0 +1,16 @@
+// apps/desktop/tests/e2e/records.spec.ts
+// 기록 화면 계약: 새 설치(기록 0건)에서는 빈 상태 카드가 보인다.
+// "전체 삭제" 흐름은 기록을 먼저 만들어야 하는데, 기록 생성은 음성 파이프라인이 담당한다.
+// 그 계약은 HistoryService 단위 테스트와 useClearAllHistory 훅 테스트가 이미 덮는다 (중복 금지).
+
+import { expect, expectNoRuntimeErrors, goToRoute, test } from './support/electron-app'
+
+test.describe('기록', () => {
+ test('새 설치에서는 빈 상태를 보여준다', async ({ mainWindow }) => {
+ await goToRoute(mainWindow, 'records')
+
+ await expect(mainWindow.window.getByTestId('empty-state-card')).toBeVisible()
+
+ expectNoRuntimeErrors(mainWindow)
+ })
+})
diff --git a/apps/desktop/tests/e2e/red_team_cycle1.spec.ts b/apps/desktop/tests/e2e/red_team_cycle1.spec.ts
deleted file mode 100644
index 2df0f24..0000000
--- a/apps/desktop/tests/e2e/red_team_cycle1.spec.ts
+++ /dev/null
@@ -1,327 +0,0 @@
-// apps/desktop/tests/e2e/red_team_cycle1.spec.ts
-// Extreme Red Team: Headful Deep Interactive Testing for Cycle 1 (Core CRUD)
-
-import { test, expect, _electron as electron, type Page, type ElectronApplication } from '@playwright/test';
-import * as fs from 'fs';
-import * as path from 'path';
-
-const SCREENSHOT_DIR = 'C:/Users/encep/.gemini/antigravity/brain/bbff18a3-721d-4c43-989f-1d6964e15be7/screenshots';
-
-test.describe('Extreme Red Team - Cycle 1: Core CRUD & State Integrity', () => {
- test.describe.configure({ mode: 'serial' });
-
- let electronApp: ElectronApplication;
- let window: Page;
- const consoleErrors: string[] = [];
- const uncaughtExceptions: string[] = [];
-
- test.beforeAll(async () => {
- if (!fs.existsSync(SCREENSHOT_DIR)) {
- fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
- }
-
- const testUserDataDir = path.join(
- 'C:/Users/encep/AppData/Local/Temp',
- 'playwright-redteam-cycle1-' + Date.now()
- );
-
- electronApp = await electron.launch({
- args: [
- 'out/main/index.js',
- '--disable-gpu',
- '--no-sandbox',
- `--user-data-dir=${testUserDataDir}`,
- ],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- // Find main window (skip popups like recording-tip, caption-overlay, etc.)
- for (let i = 0; i < 50; i++) {
- for (const w of electronApp.windows()) {
- try {
- const url = w.url();
- if (url && url.includes('index.html') && !url.includes('popups/')) {
- window = w;
- break;
- }
- } catch {
- // window might be navigating
- }
- }
- if (window) break;
- await new Promise((r) => setTimeout(r, 400));
- }
-
- if (!window) {
- window = electronApp.windows()[0] || (await electronApp.firstWindow());
- }
-
- await window.waitForLoadState('domcontentloaded');
-
- // Attach Error Sentinels
- window.on('pageerror', (err) => {
- const msg = `[PAGE_ERROR] ${err.message}\n${err.stack || ''}`;
- uncaughtExceptions.push(msg);
- // eslint-disable-next-line no-console
- console.error(msg);
- });
-
- window.on('console', (msg) => {
- if (msg.type() === 'error') {
- const text = msg.text();
- // Filter out benign CSP dev warnings
- if (!text.includes('Electron Security Warning') && !text.includes('Content Security Policy')) {
- consoleErrors.push(text);
- }
- }
- });
-
- // Bypass Onboarding modal for testing CRUD
- await window.evaluate(async () => {
- if (window.electronAPI?.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' });
- }
- });
-
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- await window.waitForTimeout(1000);
- });
-
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
-
- test('RT-01: Full Navigation Across All Primary Sidebar Routes', async () => {
- // 1. Dashboard
- await window.locator('text=/^(Dashboard|대시보드)$/').first().click();
- await expect(window.locator('text=/^(Current Backend|현재 백엔드)$/').first()).toBeVisible({ timeout: 5000 });
- await window.screenshot({ path: path.join(SCREENSHOT_DIR, 'rt01_01_dashboard.png') });
-
- // 2. History
- await window.locator('text=/^(History|히스토리|기록)$/').first().click();
- await expect(window.locator('text=/^(History|히스토리|변환 기록)$/').first()).toBeVisible({ timeout: 5000 });
-
- // 3. Dictionary
- await window.locator('text=/^(Dictionary|사전|단어장)$/').first().click();
- await expect(window.locator('text=/^(Custom Dictionary|커스텀 사전|단어장)$/').first()).toBeVisible({ timeout: 5000 });
-
- // 4. Commands
- await window.locator('text=/^(Commands|명령어)$/').first().click();
- await expect(window.locator('text=/^(LLM Commands|LLM 명령어)$/').first()).toBeVisible({ timeout: 5000 });
-
- // 5. Voice Conversation
- await window.locator('text=/^(Conversation|대화|음성 대화)$/').first().click();
- await expect(window.locator('text=/^(Voice Conversation|음성 대화)$/').first()).toBeVisible({ timeout: 5000 });
-
- // 6. Knowledge Base
- await window.locator('text=/^(Knowledge|지식 베이스)$/').first().click();
- await expect(window.locator('text=/^(Knowledge Base|지식 베이스)$/').first()).toBeVisible({ timeout: 5000 });
-
- // 7. Meeting Mode
- await window.locator('text=/^(Meeting|회의|회의 모드)$/').first().click();
- await expect(window.locator('text=/^(Meeting Mode|회의 모드)$/').first()).toBeVisible({ timeout: 5000 });
-
- expect(uncaughtExceptions).toHaveLength(0);
- });
-
- test('RT-02: Dictionary Deep CRUD, Boundary Validation & Search Interaction', async () => {
- // Navigate to Dictionary Tab
- await window.locator('text=/^(Dictionary|사전|단어장)$/').first().click();
- await expect(window.locator('text=/^(Custom Dictionary|커스텀 사전|단어장)$/').first()).toBeVisible();
-
- // Click Add Word button (PhysicalButton tone="accent")
- const addBtn = window.locator('header button:has-text("추가"), header button:has-text("Add"), button:has-text("추가"), button:has-text("Add")').first();
- await expect(addBtn).toBeVisible({ timeout: 5000 });
- await addBtn.click();
- await window.waitForTimeout(500);
-
- // Verify Add Dialog opens
- const dialogTitle = window.locator('text=/^(단어 추가|Add Word)$/').first();
- await expect(dialogTitle).toBeVisible({ timeout: 5000 });
-
- // Test Boundary: Empty input should disable save button
- const saveBtn = window.locator('div[role="dialog"] button:has-text("저장"), div[role="dialog"] button:has-text("Save")').first();
- await expect(saveBtn).toBeDisabled();
-
- // Fill valid data
- const wordInput = window.locator('div[role="dialog"] input').first();
- const pronInput = window.locator('div[role="dialog"] input').nth(1);
-
- await wordInput.fill('D3RO_Voice_RedTeam_Keyword');
- await pronInput.fill('디쓰리오 보이스 레드팀 키워드');
- await expect(saveBtn).toBeEnabled();
-
- // Save
- await saveBtn.click();
- await window.waitForTimeout(600);
-
- // Verify new word appears in the list
- const createdItem = window.locator('text=D3RO_Voice_RedTeam_Keyword').first();
- await expect(createdItem).toBeVisible({ timeout: 5000 });
- await window.screenshot({ path: path.join(SCREENSHOT_DIR, 'rt02_01_dict_created.png') });
-
- // Test Search Functionality
- const searchInput = window.locator('input[placeholder*="검색"], input[placeholder*="Search"]').first();
- await searchInput.fill('RedTeam');
- await window.waitForTimeout(400);
- await expect(createdItem).toBeVisible();
-
- await searchInput.fill('NonExistentKeywordXYZ999');
- await window.waitForTimeout(400);
- await expect(window.locator('text=D3RO_Voice_RedTeam_Keyword')).not.toBeVisible();
- await expect(window.locator('text=/^(검색 결과 없음|검색 결과가 없습니다|일치하는 단어가 없습니다|No results)$/').first()).toBeVisible({ timeout: 5000 });
-
- // Clear search
- await searchInput.fill('');
- await window.waitForTimeout(400);
- await expect(createdItem).toBeVisible();
-
- // Test Edit
- const editBtn = window.locator('button[aria-label="편집"], button[aria-label="Edit"]').first();
- await expect(editBtn).toBeVisible({ timeout: 5000 });
- await editBtn.click();
- await window.waitForTimeout(400);
-
- // Verify Edit Dialog opens
- await expect(window.locator('text=/^(단어 편집|단어 수정|Edit Word)$/').first()).toBeVisible({ timeout: 5000 });
- const editWordInput = window.locator('div[role="dialog"] input').first();
- await editWordInput.fill('D3RO_Voice_RedTeam_Keyword_MOD');
- const editSaveBtn = window.locator('div[role="dialog"] button:has-text("저장"), div[role="dialog"] button:has-text("Save")').first();
- await editSaveBtn.click();
- await window.waitForTimeout(600);
-
- // Verify edited word appears
- const editedItem = window.locator('text=D3RO_Voice_RedTeam_Keyword_MOD').first();
- await expect(editedItem).toBeVisible({ timeout: 5000 });
-
- // Test Delete
- const deleteBtn = window.locator('button[aria-label="삭제"], button[aria-label="Delete"]').first();
- await expect(deleteBtn).toBeVisible({ timeout: 5000 });
- await deleteBtn.click();
- await window.waitForTimeout(700);
-
- // Verify deleted item is gone
- await expect(window.locator('text=D3RO_Voice_RedTeam_Keyword_MOD')).not.toBeVisible();
-
- // Test Adversarial Unicode & Long Text Entry
- await addBtn.click();
- await window.waitForTimeout(500);
- const complexInput = '🔥⚡ 레드팀 极限 测试 12345 🚀🤖 (Special!@#$%)';
- await wordInput.fill(complexInput);
- await pronInput.fill('특수문자 발음');
- await saveBtn.click();
- await window.waitForTimeout(600);
-
- // Verify complex item rendered safely without unhandled error
- const complexItem = window.locator(`text=${complexInput}`).first();
- await expect(complexItem).toBeVisible({ timeout: 5000 });
-
- // Cleanup complex item
- const complexDeleteBtn = window.locator('button[aria-label="삭제"], button[aria-label="Delete"]').first();
- await complexDeleteBtn.click();
- await window.waitForTimeout(700);
- await expect(complexItem).not.toBeVisible();
-
- expect(uncaughtExceptions).toHaveLength(0);
- });
-
- test('RT-03: LLM Commands Deep CRUD, Activation Toggle & Interactive Form Verification', async () => {
- // Navigate to Commands Tab
- await window.locator('text=/^(Commands|명령어)$/').first().click();
- await expect(window.locator('text=/^(LLM Commands|LLM 명령어)$/').first()).toBeVisible();
-
- // Click Add Command button
- const addCommandBtn = window.locator('header button:has-text("추가"), header button:has-text("Add"), button:has-text("추가"), button:has-text("Add")').first();
- await expect(addCommandBtn).toBeVisible({ timeout: 5000 });
- await addCommandBtn.click();
- await window.waitForTimeout(500);
-
- // Verify Dialog opens
- const dialogTitle = window.locator('text=/^(명령어 추가|Add Command)$/').first();
- await expect(dialogTitle).toBeVisible({ timeout: 5000 });
-
- // Fill Command Form
- const nameInput = window.locator('div[role="dialog"] input').first();
- const descInput = window.locator('div[role="dialog"] input').nth(1);
- const promptInput = window.locator('div[role="dialog"] textarea').first();
-
- await nameInput.fill('RT_BulletPoints_Custom');
- await descInput.fill('레드팀 불릿포인트 요약 테스트');
- await promptInput.fill('다음 음성 텍스트를 글머리 기호(bullet points)로 간결하게 요약해주세요:\n\n{text}');
-
- const saveBtn = window.locator('div[role="dialog"] button:has-text("저장"), div[role="dialog"] button:has-text("Save")').first();
- await saveBtn.click();
- await window.waitForTimeout(600);
-
- // Verify card is added
- const createdCmd = window.locator('text=RT_BulletPoints_Custom').first();
- await expect(createdCmd).toBeVisible({ timeout: 5000 });
- await window.screenshot({ path: path.join(SCREENSHOT_DIR, 'rt03_01_command_created.png') });
-
- // Test Edit Command
- const editBtn = window.getByRole('button', { name: '편집' }).last();
- await expect(editBtn).toBeVisible({ timeout: 5000 });
- await editBtn.click();
- await window.waitForTimeout(400);
-
- await expect(window.getByRole('dialog')).toBeVisible({ timeout: 5000 });
- const editNameInput = window.getByRole('dialog').locator('input').first();
- await editNameInput.fill('RT_BulletPoints_Custom_MOD');
- await window.getByRole('dialog').getByRole('button', { name: '저장' }).click();
- await window.waitForTimeout(600);
-
- // Verify modified command
- const editedCmd = window.locator('text=RT_BulletPoints_Custom_MOD').first();
- await expect(editedCmd).toBeVisible({ timeout: 5000 });
-
- // Delete Command
- const deleteBtn = window.getByRole('button', { name: '삭제' }).first();
- await expect(deleteBtn).toBeVisible({ timeout: 5000 });
- await deleteBtn.click();
- await window.waitForTimeout(700);
-
- // Verify deleted
- await expect(window.locator('text=RT_BulletPoints_Custom_MOD')).not.toBeVisible();
-
- expect(uncaughtExceptions).toHaveLength(0);
- });
-
- test('RT-04: History Search, Filter and Card Interaction Integrity', async () => {
- // Navigate to History Tab
- await window.locator('text=/^(History|히스토리|기록)$/').first().click();
- await expect(window.locator('text=/^(History|히스토리|변환 기록)$/').first()).toBeVisible();
-
- // Verify Search Input exists and accepts query
- const searchInput = window.locator('input[placeholder*="검색"], input[placeholder*="Search"]').first();
- await expect(searchInput).toBeVisible();
- await searchInput.fill('오늘');
- await window.waitForTimeout(300);
- await searchInput.fill('');
- await window.waitForTimeout(300);
-
- await window.screenshot({ path: path.join(SCREENSHOT_DIR, 'rt04_01_history_view.png') });
- expect(uncaughtExceptions).toHaveLength(0);
- });
-
- test('RT-05: Dashboard Health & Stat Widgets Non-Crashing Check', async () => {
- // Navigate to Dashboard Tab
- await window.locator('text=/^(Dashboard|대시보드)$/').first().click();
- await expect(window.locator('text=/^(Current Backend|현재 백엔드)$/').first()).toBeVisible({ timeout: 5000 });
-
- // Check stats and status widgets
- await expect(window.locator('text=/^(전사 기록|최근 변환 기록|최근 전사|Recent Transcriptions)/').first()).toBeVisible({ timeout: 5000 });
- await expect(window.locator('text=/^(시스템 정상|System OK|정상)/').first()).toBeVisible({ timeout: 5000 });
-
- await window.screenshot({ path: path.join(SCREENSHOT_DIR, 'rt05_01_dashboard_verified.png') });
- expect(uncaughtExceptions).toHaveLength(0);
- });
-});
diff --git a/apps/desktop/tests/e2e/red_team_cycle2.spec.ts b/apps/desktop/tests/e2e/red_team_cycle2.spec.ts
deleted file mode 100644
index d6e14ab..0000000
--- a/apps/desktop/tests/e2e/red_team_cycle2.spec.ts
+++ /dev/null
@@ -1,457 +0,0 @@
-// apps/desktop/tests/e2e/red_team_cycle2.spec.ts
-// Extreme Red Team: Headful Deep Interactive Testing for Cycle 2 (AI Pipelines & Workspaces)
-
-import { test, expect, _electron as electron, type Page, type ElectronApplication } from '@playwright/test';
-import * as fs from 'fs';
-import * as path from 'path';
-
-const SCREENSHOT_DIR = 'C:/Users/encep/.gemini/antigravity/brain/bbff18a3-721d-4c43-989f-1d6964e15be7/screenshots';
-
-test.describe('Extreme Red Team - Cycle 2: AI Pipelines & Advanced Workspaces', () => {
- test.describe.configure({ mode: 'serial' });
-
- let electronApp: ElectronApplication;
- let window: Page;
- const consoleErrors: string[] = [];
- const uncaughtExceptions: string[] = [];
- let testUserDataDir: string;
-
- test.beforeAll(async () => {
- test.setTimeout(60000);
- if (!fs.existsSync(SCREENSHOT_DIR)) {
- fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
- }
-
- testUserDataDir = path.join(
- 'C:/Users/encep/AppData/Local/Temp',
- 'playwright-redteam-cycle2-' + Date.now()
- );
-
- electronApp = await electron.launch({
- args: [
- 'out/main/index.js',
- '--disable-gpu',
- '--no-sandbox',
- `--user-data-dir=${testUserDataDir}`,
- ],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- // Find main window
- for (let i = 0; i < 50; i++) {
- for (const w of electronApp.windows()) {
- try {
- const url = w.url();
- if (url && url.includes('index.html') && !url.includes('popups/')) {
- window = w;
- break;
- }
- } catch {
- // window might be navigating
- }
- }
- if (window) break;
- await new Promise((r) => setTimeout(r, 400));
- }
-
- if (!window) {
- window = electronApp.windows()[0] || (await electronApp.firstWindow());
- }
-
- // Attach sentinels
- window.on('pageerror', (err) => {
- console.error('[PAGEERROR]', err.message);
- uncaughtExceptions.push(err.message);
- });
-
- window.on('console', (msg) => {
- if (msg.type() === 'error') {
- const text = msg.text();
- // Ignore benign chrome font/csp warnings
- if (!text.includes('Failed to load resource') && !text.includes('favicon.ico')) {
- consoleErrors.push(text);
- }
- }
- });
-
- await window.waitForLoadState('domcontentloaded');
- // Bypass Onboarding modal for testing
- await window.evaluate(async () => {
- if (window.electronAPI?.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' });
- }
- });
-
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- await window.waitForTimeout(1000);
- });
-
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
-
- test('RT-06: Meeting Mode List, Start Recording Trigger & Diagnostic Dialog', async () => {
- // 1. Navigate to Meeting Mode
- const meetingNav = window.locator('text=/^(Meeting|회의)$/').first();
- await expect(meetingNav).toBeVisible({ timeout: 5000 });
- await meetingNav.click();
- await window.waitForTimeout(600);
-
- // Verify page header
- await expect(window.locator('text=/^(Meeting|회의 모드)$/').first()).toBeVisible({ timeout: 5000 });
-
- // 2. Click "새 회의 시작" button
- const startBtn = window.getByRole('button', { name: /새 회의 시작|새 회의/i }).first();
- await expect(startBtn).toBeVisible();
- await startBtn.click();
- await window.waitForTimeout(1000);
-
- // If diagnostic dialog opened (e.g. no mic or whisper unavailable in test container)
- const dialog = window.getByRole('dialog');
- const isDialogVisible = await dialog.isVisible({ timeout: 2000 }).catch(() => false);
- if (isDialogVisible) {
- // Verify diagnostic elements
- await expect(window.getByText('Meeting Intelligence Diagnostics')).toBeVisible();
- await expect(window.getByText(/발생 원인/)).toBeVisible();
- await expect(window.getByText(/해결 조치/)).toBeVisible();
-
- // Click "닫기" button
- const closeBtn = window.getByRole('button', { name: '닫기' });
- await expect(closeBtn).toBeVisible();
- await closeBtn.click();
- await window.waitForTimeout(500);
- await expect(dialog).not.toBeVisible();
- }
-
- // Take screenshot
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt06_meeting_list_and_dialog.png'),
- });
-
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-07: Meeting Mode Detail Workspace - Inline Title, ViewModes, MarkdownEditor, Action Items & Chat', async () => {
- // Seed a meeting session directly via python to avoid Node ABI mismatch
- const sessionId = 'test-session-redteam-' + Date.now();
- const dbPath = path.join(testUserDataDir, 'users', '_local', 'd3ro.db');
- const seedPyPath = path.join(testUserDataDir, 'seed.py');
- const now = Date.now();
-
- const pyScript = `import sqlite3, sys
-db_path = sys.argv[1]
-session_id = sys.argv[2]
-now = int(sys.argv[3])
-conn = sqlite3.connect(db_path)
-c = conn.cursor()
-c.execute("""
- INSERT INTO meeting_sessions (id, title, status, started_at, ended_at, duration_ms, raw_transcript, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
-""", (
- session_id,
- 'Red Team AI 전략 회의',
- 'completed',
- now - 1800000,
- now,
- 1800000,
- '[00:05] [참석자 A] D3RO Voice 시스템 성능 점검을 시작합니다.\\n[00:15] [참석자 B] 극단적 레드팀 테스트를 수행 중입니다.\\n[01:00] [참석자 A] 품질 검증을 완벽하게 통과했습니다.',
- now - 1800000,
- now
-))
-c.execute("""
- INSERT INTO meeting_memos (id, session_id, content, timestamp_ms, created_at)
- VALUES (?, ?, ?, ?, ?)
-""", (
- 'memo-' + session_id,
- session_id,
- '#결정 음성 인식 모델 레이턴시 최적화 완료',
- 5000,
- now - 1795000
-))
-c.execute("""
- INSERT INTO meeting_documents (id, session_id, template_type, title, content, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)
-""", (
- 'doc-' + session_id,
- session_id,
- 'minutes',
- '전략 회의록',
- '# 레드팀 전략 회의록\\n\\n## 1. 개요\\n- 시스템 안정성 심층 검증\\n\\n## 2. 액션 아이템\\n- [ ] E2E 헤드풀 테스트 통과하기\\n- [x] SQLite ABI 불일치 수정 완료\\n\\n## 3. 결론\\n전체 파이프라인 완벽 가동',
- now,
- now
-))
-conn.commit()
-conn.close()
-`;
-
- fs.writeFileSync(seedPyPath, pyScript, 'utf-8');
- const cp = require('child_process');
- cp.execSync(`python "${seedPyPath}" "${dbPath}" "${sessionId}" "${now}"`);
- fs.unlinkSync(seedPyPath);
-
- // Refresh meeting list by navigating to dashboard and back to meeting
- await window.locator('text=/^(Dashboard|대시보드)$/').first().click();
- await window.waitForTimeout(400);
- await window.locator('text=/^(Meeting|회의)$/').first().click();
- await window.waitForTimeout(800);
-
- // Click on the seeded session card
- const sessionCard = window.getByText('Red Team AI 전략 회의');
- await expect(sessionCard).toBeVisible({ timeout: 5000 });
- await sessionCard.click();
- await window.waitForTimeout(800);
-
- // 1. Verify MeetingDetailTabs is rendered
- await expect(window.getByRole('tab', { name: '전략 회의록' })).toBeVisible({ timeout: 5000 });
-
- // 2. Test Inline Title Editing
- const editTitleBtn = window.locator('button:has(svg.lucide-pencil)');
- if (await editTitleBtn.isVisible()) {
- await editTitleBtn.click();
- await window.waitForTimeout(300);
- const titleInput = window.locator('input[value*="Red Team AI 전략 회의"]');
- await expect(titleInput).toBeVisible();
- await titleInput.fill('Red Team AI 전략 회의 (검증됨)');
- const saveTitleBtn = window.locator('button:has(svg.lucide-check)');
- await saveTitleBtn.click();
- await window.waitForTimeout(500);
- await expect(window.getByText('Red Team AI 전략 회의 (검증됨)')).toBeVisible();
- }
-
- // 3. Test ViewMode switches (SegmentControl)
- const transcriptOnlyBtn = window.getByText('Transcript ▤');
- if (await transcriptOnlyBtn.isVisible()) {
- await transcriptOnlyBtn.click();
- await window.waitForTimeout(300);
- await expect(window.getByText(/D3RO Voice 시스템 성능 점검/)).toBeVisible();
-
- const docOnlyBtn = window.getByText('Minutes ▥');
- await docOnlyBtn.click();
- await window.waitForTimeout(300);
- await expect(window.getByRole('heading', { name: '레드팀 전략 회의록' })).toBeVisible();
-
- const splitBtn = window.getByText('Split ◫');
- await splitBtn.click();
- await window.waitForTimeout(300);
- }
-
- // 4. Test MarkdownEditor preview vs edit toggle
- const editModeBtn = window.locator('button').filter({ hasText: '편집' }).first();
- if (await editModeBtn.isVisible()) {
- await editModeBtn.click();
- await window.waitForTimeout(300);
- const textarea = window.locator('textarea');
- await expect(textarea).toBeVisible();
- await textarea.type('\n\n## 4. 추가 사항\n- 레드팀 사이클 2 통과');
- await window.waitForTimeout(600); // let autosave debounce fire
-
- const previewModeBtn = window.locator('button').filter({ hasText: '미리보기' }).first();
- await previewModeBtn.click();
- await window.waitForTimeout(300);
- await expect(window.getByText(/추가 사항/)).toBeVisible();
- }
-
- // 5. Test Action Items tab
- const actionItemsTab = window.getByText(/Action Items/i);
- if (await actionItemsTab.isVisible()) {
- await actionItemsTab.click();
- await window.waitForTimeout(400);
- await expect(window.getByText(/E2E 헤드풀 테스트/)).toBeVisible();
-
- // Toggle action item checkbox
- const checkbox = window.locator('input[type="checkbox"]').first();
- await checkbox.click();
- await window.waitForTimeout(300);
- }
-
- // 6. Test Scratchpad Notepad tab
- const notepadTab = window.getByText(/Granola Notepad/i);
- if (await notepadTab.isVisible()) {
- await notepadTab.click();
- await window.waitForTimeout(400);
- const notepadTextarea = window.locator('textarea').first();
- if (await notepadTextarea.isVisible()) {
- await notepadTextarea.fill('핵심 안건: 실시간 STT 엔진 최적화 및 텍스트 렌더링 검증');
- await window.waitForTimeout(300);
- }
- }
-
- // 7. Test Export Menu
- const exportBtn = window.getByRole('button', { name: /내보내기/i });
- if (await exportBtn.isVisible()) {
- await exportBtn.click();
- await window.waitForTimeout(300);
- await expect(window.getByText(/Markdown/i)).toBeVisible();
- // Press Escape to dismiss menu
- await window.keyboard.press('Escape');
- await window.waitForTimeout(300);
- }
-
- // 8. Test Meeting Chat Panel
- const chatInput = window.locator('input[placeholder*="AI에게 질문"]');
- if (await chatInput.isVisible()) {
- await chatInput.fill('회의 요약해줘');
- await window.keyboard.press('Enter');
- await window.waitForTimeout(600);
-
- // Verify user message appears
- await expect(window.getByText('회의 요약해줘')).toBeVisible();
-
- // Clear chat
- const clearChatBtn = window.locator('button:has(svg.lucide-trash2)');
- if (await clearChatBtn.isVisible()) {
- await clearChatBtn.click();
- await window.waitForTimeout(300);
- await expect(window.getByText('회의 요약해줘')).not.toBeVisible();
- }
- }
-
- // 9. Back to meeting list
- const backBtn = window.locator('button:has(svg.lucide-arrow-left)');
- await backBtn.click();
- await window.waitForTimeout(500);
- await expect(window.getByText('Red Team AI 전략 회의 (검증됨)')).toBeVisible();
-
- // Take screenshot
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt07_meeting_detail_workspace.png'),
- });
-
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-08: Knowledge Base - Semantic Synthesis Query, Chips, Add & Delete Document', async () => {
- // 1. Navigate to Knowledge Base
- const ragNav = window.locator('text=/^(Knowledge Base|지식 베이스)$/').first();
- await expect(ragNav).toBeVisible({ timeout: 5000 });
- await ragNav.click();
- await window.waitForTimeout(600);
-
- // Verify page header
- await expect(window.locator('text=/^(Knowledge Base|지식 베이스)$/').first()).toBeVisible({ timeout: 5000 });
-
- // 2. Test query input
- const queryInput = window.locator('input[placeholder*="질문하세요"]');
- await expect(queryInput).toBeVisible();
- await queryInput.fill('D3RO Voice 아키텍처');
-
- // Click Search button
- const searchBtn = window.getByRole('button', { name: /Search|검색/i });
- await expect(searchBtn).toBeVisible();
- await searchBtn.click();
- await window.waitForTimeout(600);
-
- // Verify searching spinner or graceful error feedback
- await window.waitForTimeout(1000);
-
- // 3. Add a mock document via IPC
- const tempFilePath = path.join(testUserDataDir, 'red_team_sample.md');
- fs.writeFileSync(
- tempFilePath,
- '# D3RO Voice 시스템 문서\n\nD3RO Voice는 고성능 로컬 퍼스트 음성 비서 아키텍처를 지원하며 빠른 STT 및 LLM 파이프라인을 제공합니다.',
- 'utf-8'
- );
-
- const addDocResult = await window.evaluate(async (filePath) => {
- return await window.electronAPI.rag.addDocument({ filePath });
- }, tempFilePath);
-
- expect(addDocResult.success).toBe(true);
-
- // Reload documents by re-navigating
- await ragNav.click();
- await window.waitForTimeout(800);
-
- // Verify document card appears
- await expect(window.getByText('red_team_sample.md')).toBeVisible({ timeout: 5000 });
- await expect(window.getByText('MD', { exact: true })).toBeVisible();
-
- // 4. Test Reindex button
- const reindexBtn = window.locator('button:has(svg.lucide-refresh-cw)').first();
- if (await reindexBtn.isVisible()) {
- await reindexBtn.click();
- await window.waitForTimeout(500);
- }
-
- // 5. Test Delete document button
- const deleteDocBtn = window.locator('button:has(svg.lucide-trash-2)').first();
- await expect(deleteDocBtn).toBeVisible();
- await deleteDocBtn.click();
- await window.waitForTimeout(600);
-
- // Verify document is removed
- await expect(window.getByText('red_team_sample.md')).not.toBeVisible();
-
- // Clean up temp file
- if (fs.existsSync(tempFilePath)) {
- fs.unlinkSync(tempFilePath);
- }
-
- // Take screenshot
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt08_knowledge_base.png'),
- });
-
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-09: Voice Conversation - Canvas, Text Chat, Mic Toggle & Clear History', async () => {
- // 1. Navigate to Voice Conversation
- const voiceNav = window.locator('text=/^(Talk|대화)$/').first();
- await expect(voiceNav).toBeVisible({ timeout: 5000 });
- await voiceNav.click();
- await window.waitForTimeout(600);
-
- // Verify PageHeader
- await expect(window.locator('text=/^(Voice Conversation|음성 대화)$/').first()).toBeVisible({ timeout: 5000 });
- await expect(window.getByText(/대기|IDLE/i).first()).toBeVisible();
-
- // Verify empty state
- await expect(window.getByText(/D3RO에게 말을 걸어보세요|Talk to D3RO/i)).toBeVisible();
-
- // 2. Test Text Fallback Chat Input
- const chatInput = window.locator('input[placeholder*="메시지 입력"]');
- await expect(chatInput).toBeVisible();
- await chatInput.fill('안녕 D3RO, 현재 상태 점검해줘');
-
- const sendBtn = window.locator('button:has(svg.lucide-send)');
- await expect(sendBtn).toBeVisible();
- await sendBtn.click();
- await window.waitForTimeout(1000);
-
- // Verify user message appears in bubble
- await expect(window.getByText('안녕 D3RO, 현재 상태 점검해줘')).toBeVisible({ timeout: 5000 });
-
- // 3. Test Clear History
- const clearBtn = window.locator('button:has(svg.lucide-trash-2)');
- if (await clearBtn.isVisible()) {
- await clearBtn.click();
- await window.waitForTimeout(500);
- }
-
- // If session is active or thinking, end session so state returns to idle
- const stopSessionBtn = window.getByRole('button', { name: /종료|End/i });
- if (await stopSessionBtn.isVisible()) {
- await stopSessionBtn.click();
- await window.waitForTimeout(600);
- }
-
- await expect(window.getByText(/D3RO에게 말을 걸어보세요|Talk to D3RO/i)).toBeVisible({ timeout: 5000 });
-
- // Take screenshot
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt09_voice_conversation.png'),
- });
-
- expect(uncaughtExceptions).toEqual([]);
- });
-});
diff --git a/apps/desktop/tests/e2e/red_team_cycle3.spec.ts b/apps/desktop/tests/e2e/red_team_cycle3.spec.ts
deleted file mode 100644
index 81f6a2a..0000000
--- a/apps/desktop/tests/e2e/red_team_cycle3.spec.ts
+++ /dev/null
@@ -1,417 +0,0 @@
-import { test, expect, _electron as electron, ElectronApplication, Page } from '@playwright/test';
-import path from 'path';
-import fs from 'fs';
-
-const SCREENSHOT_DIR = path.resolve('C:/Users/encep/.gemini/antigravity/brain/bbff18a3-721d-4c43-989f-1d6964e15be7/screenshots');
-
-test.describe.serial('Extreme Red Team - Cycle 3: Modals, Deep Configuration & System Shell', () => {
- let app: ElectronApplication;
- let window: Page;
- let testUserDataDir: string;
- const uncaughtExceptions: string[] = [];
-
- test.beforeAll(async () => {
- if (!fs.existsSync(SCREENSHOT_DIR)) {
- fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
- }
-
- testUserDataDir = path.join(
- 'C:/Users/encep/AppData/Local/Temp',
- 'playwright-redteam-cycle3-' + Date.now()
- );
-
- app = await electron.launch({
- args: [
- 'out/main/index.js',
- '--disable-gpu',
- '--no-sandbox',
- `--user-data-dir=${testUserDataDir}`,
- ],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- // Find main window
- for (let i = 0; i < 50; i++) {
- for (const w of app.windows()) {
- try {
- const url = w.url();
- if (url && url.includes('index.html') && !url.includes('popups/')) {
- window = w;
- break;
- }
- } catch {
- // window navigating
- }
- }
- if (window) break;
- await new Promise((r) => setTimeout(r, 400));
- }
-
- if (!window) {
- window = app.windows()[0] || (await app.firstWindow());
- }
-
- window.on('pageerror', (err) => {
- console.error('[PAGEERROR in Electron Window]:', err.message);
- uncaughtExceptions.push(err.message);
- });
-
- await window.waitForLoadState('domcontentloaded');
-
- // Bypass Onboarding modal for testing
- await window.evaluate(async () => {
- if (window.electronAPI?.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' });
- }
- });
-
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- await window.waitForTimeout(1000);
- });
-
- test.afterAll(async () => {
- if (app) {
- await app.close();
- }
- });
-
- test('RT-10: SettingsModal - Deep Tab Traversal, Live Theme Switching, Language Switch & Audio Test', async () => {
- // 1. Open SettingsModal from sidebar
- const settingsTrigger = window.getByText('설정', { exact: true });
- await expect(settingsTrigger).toBeVisible({ timeout: 5000 });
- await settingsTrigger.click();
- await window.waitForTimeout(600);
-
- // Verify modal dialog opened
- await expect(window.getByText(/설정|SETTINGS/i).first()).toBeVisible({ timeout: 5000 });
-
- // 2. Tab 0: General - Voice Mode Cards & Theme / Language
- await expect(window.getByText(/받아쓰기|Dictation/i).first()).toBeVisible();
- await expect(window.getByText(/원터치|Hands-Free/i).first()).toBeVisible();
- await expect(window.getByText(/자막|Caption/i).first()).toBeVisible();
-
- // Test Theme Selector
- const themeSelect = window.locator('div[role="combobox"]').first();
- if (await themeSelect.isVisible()) {
- await themeSelect.click();
- await window.waitForTimeout(300);
- // Select Light theme
- const lightOption = window.getByRole('option', { name: /라이트|Light/i });
- if (await lightOption.isVisible()) {
- await lightOption.click();
- await window.waitForTimeout(400);
- }
- // Select Dark theme back
- await themeSelect.click();
- await window.waitForTimeout(300);
- const darkOption = window.getByRole('option', { name: /다크|Dark/i });
- if (await darkOption.isVisible()) {
- await darkOption.click();
- await window.waitForTimeout(400);
- }
- }
-
- // 3. Tab 1: Audio Tab
- const audioTab = window.getByRole('tab', { name: /오디오|Audio/i });
- await expect(audioTab).toBeVisible();
- await audioTab.click();
- await window.waitForTimeout(500);
-
- // Verify Audio Settings: Input device selector & Mic Test
- await expect(window.getByText(/입력 장치|마이크|Microphone/i).first()).toBeVisible();
- const micTestBtn = window.getByRole('button', { name: /테스트|Test/i }).first();
- if (await micTestBtn.isVisible()) {
- await micTestBtn.click();
- await window.waitForTimeout(400);
- // Click again to stop test
- await micTestBtn.click();
- await window.waitForTimeout(300);
- }
-
- // 4. Tab 2: STT Tab
- const sttTab = window.getByRole('tab', { name: 'STT' });
- await expect(sttTab).toBeVisible();
- await sttTab.click();
- await window.waitForTimeout(500);
-
- // Verify STT Provider / Model configurations
- await expect(window.getByText(/STT 엔진|faster-whisper|모델|Provider/i).first()).toBeVisible();
-
- // 5. Tab 3: LLM Tab
- const llmTab = window.getByRole('tab', { name: 'LLM' });
- await expect(llmTab).toBeVisible();
- await llmTab.click();
- await window.waitForTimeout(500);
-
- // Verify Ollama Server URL input
- await expect(window.getByText(/Ollama|Server|URL/i).first()).toBeVisible();
- const refreshLlmBtn = window.locator('button:has(svg.lucide-refresh-cw)').first();
- if (await refreshLlmBtn.isVisible()) {
- await refreshLlmBtn.click();
- await window.waitForTimeout(400);
- }
-
- // 6. Tab 4: License Tab
- const licenseTab = window.getByRole('tab', { name: /라이선스|License/i });
- await expect(licenseTab).toBeVisible();
- await licenseTab.click();
- await window.waitForTimeout(500);
-
- // Verify Current Tier Display
- await expect(window.getByText(/현재 라이선스|현재 플랜|FREE|PRO/i).first()).toBeVisible();
-
- // 7. Tab 5: Cloud Sync Tab
- const cloudTab = window.getByRole('tab', { name: /클라우드|Cloud/i });
- if (await cloudTab.isVisible()) {
- await cloudTab.click();
- await window.waitForTimeout(500);
- await expect(window.getByText(/Cloud|동기화|Sync/i).first()).toBeVisible();
- }
-
- // 8. Tab 6: About Tab
- const aboutTab = window.getByRole('tab', { name: /정보|About/i });
- if (await aboutTab.isVisible()) {
- await aboutTab.click();
- await window.waitForTimeout(500);
- await expect(window.getByText(/D3RO Voice|버전|Version/i).first()).toBeVisible();
- }
-
- // Screenshot SettingsModal
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt10_settings_modal_all_tabs.png'),
- });
-
- // Close SettingsModal
- const closeBtn = window.locator('div[role="dialog"] button:has(svg.lucide-x)').first();
- await expect(closeBtn).toBeVisible();
- await closeBtn.click();
- await window.waitForTimeout(500);
-
- // Verify modal is closed
- await expect(window.locator('div[role="dialog"]')).not.toBeVisible();
-
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-11: KeyBindingPicker - Key Recording, Reserved-Combo Protection & Cancel Safety', async () => {
- // 1. Re-open SettingsModal to General Tab
- const settingsTrigger = window.getByText('설정', { exact: true });
- await settingsTrigger.click();
- await window.waitForTimeout(600);
-
- // Click General tab
- const generalTab = window.getByRole('tab', { name: /일반|General/i });
- await generalTab.click();
- await window.waitForTimeout(400);
-
- // 2. The dictation row is rendered by KeyBindingField off KEYBINDING_ACTIONS
- const dictationField = window.getByTestId('keybinding-field-dictation');
- await expect(dictationField).toBeVisible({ timeout: 5000 });
-
- // Wait for the binding map to arrive, then snapshot how many bindings this action
- // has so we can prove afterwards that cancelling did not corrupt them.
- const bindingChips = dictationField.getByTestId('keybinding-binding');
- await expect(bindingChips.first()).toBeVisible({ timeout: 5000 });
- const bindingsBefore = await bindingChips.count();
-
- // 3. Open the picker with the "+ Add" button (replaces the old pencil icon)
- await dictationField.getByTestId('keybinding-add-dictation').click();
- const picker = window.getByTestId('keybinding-picker');
- await expect(picker).toBeVisible({ timeout: 5000 });
-
- // 4. Record tab: pressing F9 captures it onto a keycap
- const recordArea = picker.getByTestId('keybinding-record-area');
- await expect(recordArea).toBeVisible();
- await window.keyboard.press('F9');
- await window.waitForTimeout(400);
- await expect(recordArea.getByText('F9', { exact: true })).toBeVisible();
-
- // Take screenshot while the picker holds the captured key
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt11_keybinding_picker_recorded.png'),
- });
-
- // 5. Reserved-combo protection: Ctrl+C must be rejected and Save must stay disabled
- await picker.getByTestId('keybinding-record-again').click();
- await window.waitForTimeout(300);
- await window.keyboard.press('Control+c');
- await window.waitForTimeout(400);
- await expect(picker.getByTestId('keybinding-rejection').first()).toBeVisible();
- await expect(picker.getByTestId('keybinding-confirm')).toBeDisabled();
-
- // 6. Cancel closes the picker without touching the stored bindings
- await picker.getByTestId('keybinding-cancel').click();
- await window.waitForTimeout(500);
- await expect(picker).toBeHidden();
- await expect(bindingChips).toHaveCount(bindingsBefore);
-
- // Close SettingsModal (its close button sits in DialogTitle, ahead of any field markup)
- const closeSettingsBtn = window.locator('div[role="dialog"] button:has(svg.lucide-x)').first();
- if (await closeSettingsBtn.isVisible()) {
- await closeSettingsBtn.click();
- await window.waitForTimeout(500);
- }
-
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-11b: KeyBindingPicker - Searchable Key Dropdown & Multi-Binding Add/Remove', async () => {
- // 1. Re-open SettingsModal to General Tab
- const settingsTrigger = window.getByText('설정', { exact: true });
- await settingsTrigger.click();
- await window.waitForTimeout(600);
-
- const generalTab = window.getByRole('tab', { name: /일반|General/i });
- await generalTab.click();
- await window.waitForTimeout(400);
-
- const dictationField = window.getByTestId('keybinding-field-dictation');
- const bindingChips = dictationField.getByTestId('keybinding-binding');
- await expect(bindingChips.first()).toBeVisible({ timeout: 5000 });
- const bindingsBefore = await bindingChips.count();
-
- // 2. Open the picker and switch to the list tab
- await dictationField.getByTestId('keybinding-add-dictation').click();
- const picker = window.getByTestId('keybinding-picker');
- await expect(picker).toBeVisible({ timeout: 5000 });
- await picker
- .getByTestId('keybinding-picker-tabs')
- .getByText(/목록에서 선택|Choose from List/i)
- .click();
- await window.waitForTimeout(300);
-
- // 3. The dropdown carries its own search field and narrows the key catalog as you type.
- // Its listbox is portalled to , so options are queried from the page root.
- const searchInput = picker.getByTestId('keybinding-search').locator('input');
- await expect(searchInput).toBeVisible();
-
- const keyOptions = window.getByTestId('keybinding-key-option');
- expect(await keyOptions.count()).toBeGreaterThan(1);
-
- await searchInput.fill('f8');
- await window.waitForTimeout(400);
- await expect(keyOptions).toHaveCount(1);
- await keyOptions.first().click();
- await window.waitForTimeout(300);
-
- // Picked key is reflected back into the picker's selection preview
- await expect(picker.getByText('F8', { exact: true }).first()).toBeVisible();
-
- // 4. Saving adds a SECOND binding to the same action (multi-binding)
- const confirmBtn = picker.getByTestId('keybinding-confirm');
- await expect(confirmBtn).toBeEnabled({ timeout: 5000 });
- await confirmBtn.click();
- await expect(picker).toBeHidden();
- await expect(bindingChips).toHaveCount(bindingsBefore + 1);
-
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt11b_keybinding_multi_binding.png'),
- });
-
- // 5. Remove it again so the stored config is left exactly as we found it
- await bindingChips.last().getByTestId('keybinding-remove').click();
- await expect(bindingChips).toHaveCount(bindingsBefore);
-
- const closeSettingsBtn = window.locator('div[role="dialog"] button:has(svg.lucide-x)').first();
- if (await closeSettingsBtn.isVisible()) {
- await closeSettingsBtn.click();
- await window.waitForTimeout(500);
- }
-
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-12: SupportModal - AI Diagnostics, FAQ Accordion, Refund Query & Telemetry', async () => {
- // 1. Open SupportModal from sidebar
- const supportTrigger = window.locator('text=Customer Support').first();
- await expect(supportTrigger).toBeVisible({ timeout: 5000 });
- await supportTrigger.click();
- await window.waitForTimeout(600);
-
- // Verify SupportModal opens
- await expect(window.getByText(/Customer Assistance|고객지원/i).first()).toBeVisible({ timeout: 5000 });
-
- // 2. Tab 0: AI Assistant Chat & Quick Prompt Chips
- await expect(window.getByText(/AI 어시스턴트|AI Assistant/i).first()).toBeVisible();
-
- // Click quick prompt chip: "🎤 마이크 인식 오류"
- const micPromptChip = window.getByRole('button', { name: /마이크/i }).first();
- if (await micPromptChip.isVisible()) {
- await micPromptChip.click();
- await window.waitForTimeout(800);
-
- // Verify AI answer appears
- await expect(window.getByText(/마이크 입력 진단 결과|개인정보 권한/i)).toBeVisible({ timeout: 5000 });
- }
-
- // 3. Tab 1: FAQ Accordion
- const faqTab = window.getByRole('tab', { name: /FAQ|자주 묻는 질문/i });
- await expect(faqTab).toBeVisible();
- await faqTab.click();
- await window.waitForTimeout(500);
-
- // Verify FAQ questions render
- await expect(window.getByText(/마이크 음성 인식이 작동하지 않거나/i)).toBeVisible();
- await expect(window.getByText(/NVIDIA CUDA GPU 가속/i)).toBeVisible();
-
- // 4. Tab 3 (Tab index 3 in DOM): 7일 자동 환불 확인
- const refundTab = window.getByRole('tab', { name: /환불|Refund/i });
- if (await refundTab.isVisible()) {
- await refundTab.click();
- await window.waitForTimeout(500);
-
- // Verify refund check button
- const checkRefundBtn = window.getByRole('button', { name: /환불 자격 조회/i });
- if (await checkRefundBtn.isVisible()) {
- await checkRefundBtn.click();
- await window.waitForTimeout(1000);
- // Verify eligibility result
- await expect(window.getByText(/전액 환불 가능|조회 완료|환불 자격/i).first()).toBeVisible();
- }
- }
-
- // Take screenshot
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt12_support_diagnostics_modal.png'),
- });
-
- // Close SupportModal
- await window.keyboard.press('Escape');
- await window.waitForTimeout(500);
-
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-13: LicenseModal & Custom Events Fail-Closed Monetization Guardrails', async () => {
- // 1. Dispatch custom event to open LicenseModal
- await window.evaluate(() => {
- window.dispatchEvent(new CustomEvent('d3ro:open-license-modal'));
- });
- await window.waitForTimeout(600);
-
- // Verify LicenseModal opens
- await expect(window.getByText(/라이선스|License/i).first()).toBeVisible({ timeout: 5000 });
- await expect(window.getByText(/현재 등급|FREE/i).first()).toBeVisible();
-
- // Verify Tier Comparison Table exists
- await expect(window.getByText(/등급 비교|Tier Comparison/i)).toBeVisible();
-
- // Take screenshot
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt13_license_monetization_modal.png'),
- });
-
- // Close LicenseModal via Escape
- await window.keyboard.press('Escape');
- await window.waitForTimeout(500);
-
- expect(uncaughtExceptions).toEqual([]);
- });
-});
diff --git a/apps/desktop/tests/e2e/red_team_cycle5.spec.ts b/apps/desktop/tests/e2e/red_team_cycle5.spec.ts
deleted file mode 100644
index d060c76..0000000
--- a/apps/desktop/tests/e2e/red_team_cycle5.spec.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-import { test, expect, _electron as electron, ElectronApplication, Page } from '@playwright/test';
-import path from 'path';
-import fs from 'fs';
-
-const SCREENSHOT_DIR = path.resolve('C:/Users/encep/.gemini/antigravity/brain/bbff18a3-721d-4c43-989f-1d6964e15be7/screenshots');
-
-test.describe.serial('Extreme Red Team - Cycle 5: Rapid Route Thrashing, Onboarding Wizard & Input Fuzzing', () => {
- let app: ElectronApplication;
- let window: Page;
- let testUserDataDir: string;
- let uncaughtExceptions: string[] = [];
-
- test.beforeAll(async () => {
- if (!fs.existsSync(SCREENSHOT_DIR)) {
- fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
- }
-
- testUserDataDir = path.join(
- 'C:/Users/encep/AppData/Local/Temp',
- 'playwright-redteam-cycle5-' + Date.now()
- );
-
- app = await electron.launch({
- args: [
- 'out/main/index.js',
- '--disable-gpu',
- '--no-sandbox',
- `--user-data-dir=${testUserDataDir}`,
- ],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- // Find main window
- for (let i = 0; i < 50; i++) {
- for (const w of app.windows()) {
- try {
- const url = w.url();
- if (url && url.includes('index.html') && !url.includes('popups/')) {
- window = w;
- break;
- }
- } catch {
- // window navigating
- }
- }
- if (window) break;
- await new Promise((r) => setTimeout(r, 400));
- }
-
- if (!window) {
- window = app.windows()[0] || (await app.firstWindow());
- }
-
- window.on('pageerror', (err) => {
- console.error('[PAGEERROR in Electron Window]:', err.message);
- uncaughtExceptions.push(err.message);
- });
-
- await window.waitForLoadState('domcontentloaded');
-
- // Bypass Onboarding modal initially
- await window.evaluate(async () => {
- if (window.electronAPI?.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' });
- }
- });
-
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- await window.waitForTimeout(1000);
- });
-
- test.afterAll(async () => {
- if (app) {
- await app.close();
- }
- });
-
- test.beforeEach(() => {
- uncaughtExceptions = [];
- });
-
- test('RT-16: Rapid Route Thrashing & Concurrency Stress Test', async () => {
- // 7 navigation routes in AppLayout
- const routes = [
- '대시보드',
- '기록',
- '단어장',
- '명령어',
- '음성 대화',
- '지식 베이스',
- '회의록'
- ];
-
- // Rapid thrashing loop - 10 full passes at high speed
- for (let loop = 0; loop < 5; loop++) {
- for (const routeName of routes) {
- const navButton = window.getByText(routeName, { exact: true }).first();
- if (await navButton.isVisible()) {
- await navButton.click();
- // Hyper rapid 40ms interval
- await window.waitForTimeout(40);
- }
- }
- }
-
- // Settle back to dashboard
- const dashboardNav = window.getByText('대시보드', { exact: true }).first();
- await dashboardNav.click();
- await window.waitForTimeout(500);
-
- // Verify system survived rapid thrashing and dashboard is completely healthy
- await expect(window.getByText(/총 발화|오늘 사용량|음성 인식|대시보드/i).first()).toBeVisible({ timeout: 5000 });
-
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt16_route_thrashing_settled.png'),
- });
-
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-17: Onboarding Modal & First-Run Wizard Headful Execution', async () => {
- // 1. Reset onboarding to false and reload to trigger OnboardingModal
- await window.evaluate(async () => {
- if (window.electronAPI?.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: false });
- }
- });
-
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- await window.waitForTimeout(1000);
-
- // 2. Verify OnboardingModal is visible
- await expect(window.getByText(/D3RO Voice 시작하기/i)).toBeVisible({ timeout: 10000 });
- await expect(window.getByText(/로컬 모드/i).first()).toBeVisible();
- await expect(window.getByText(/온라인 모드/i).first()).toBeVisible();
-
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt17_01_onboarding_select_mode.png'),
- });
-
- // 3. Test Local Mode Selection
- await window.getByRole('button', { name: /로컬 모드로 시작/i }).click();
- await window.waitForTimeout(600);
-
- // Verify transitions to local_ollama_setup phase
- await expect(window.getByText(/Ollama에 연결/i).first()).toBeVisible({ timeout: 5000 });
-
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt17_02_onboarding_local_setup.png'),
- });
-
- // Test back button
- const backBtn = window.getByRole('button', { name: '뒤로', exact: true });
- await expect(backBtn).toBeVisible();
- await backBtn.click();
- await window.waitForTimeout(500);
-
- // Verify back to select_mode
- await expect(window.getByText(/로컬 모드/i).first()).toBeVisible();
-
- // 4. Test Online Cloud Mode Selection
- await window.getByRole('button', { name: /계정으로 로그인/i }).click();
- await window.waitForTimeout(600);
-
- // Verify transitions to online_auth phase
- await expect(window.getByText(/D3RO 계정으로 로그인하면 온라인 모드로/i).first()).toBeVisible({ timeout: 5000 });
-
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt17_03_onboarding_online_auth.png'),
- });
-
- // Go back again
- await window.getByRole('button', { name: '뒤로', exact: true }).click();
- await window.waitForTimeout(500);
-
- // 5. Restore onboardingCompleted
- await window.evaluate(async () => {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- });
-
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- await window.waitForTimeout(1000);
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-18: Adversarial Input Fuzzing, Boundary Conditions & SQL/XSS Injection Defense', async () => {
- // 1. Dictionary Fuzzing
- const dictNav = window.locator('text=/^(Dictionary|사전|단어장)$/').first();
- await dictNav.click();
- await window.waitForTimeout(600);
-
- const sqlXssPayload = '\' OR \'1\'=\'1\'; ';
- const safeReplacement = 'FuzzReplacement';
-
- // Click 추가 button
- const addWordBtn = window.locator('button:has-text("추가"), button:has-text("Add")').first();
- await addWordBtn.click();
- await window.waitForTimeout(400);
-
- // Fill inputs in dialog
- const wordInput = window.locator('div[role="dialog"] input').first();
- const pronInput = window.locator('div[role="dialog"] input').nth(1);
- await wordInput.fill(sqlXssPayload);
- await pronInput.fill(safeReplacement);
-
- // Save
- const saveBtn = window.locator('div[role="dialog"] button:has-text("저장"), div[role="dialog"] button:has-text("Save")').first();
- await saveBtn.click();
- await window.waitForTimeout(600);
-
- // Verify word was stored safely without executing XSS or corrupting SQLite
- await expect(window.getByText(sqlXssPayload).first()).toBeVisible({ timeout: 5000 });
-
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt18_01_dictionary_fuzzing_saved.png'),
- });
-
- // Clean up: delete the fuzzed word
- const deleteBtn = window.locator('button[aria-label*="삭제"], button:has(svg.lucide-trash-2)').first();
- if (await deleteBtn.isVisible()) {
- await deleteBtn.click();
- await window.waitForTimeout(400);
- // Confirm dialog if any
- const confirmBtn = window.locator('div[role="dialog"] button:has-text("삭제"), div[role="dialog"] button:has-text("Delete")').first();
- if (await confirmBtn.isVisible()) {
- await confirmBtn.click();
- await window.waitForTimeout(400);
- }
- }
-
- // 2. Knowledge Base Query Fuzzing (Regex Break Characters)
- const kbNav = window.locator('text=/^(Knowledge|지식 베이스)$/').first();
- await kbNav.click();
- await window.waitForTimeout(600);
-
- const regexBreakQuery = '[([{\\\\^$|?*+';
- const kbSearchInput = window.locator('input[placeholder*="질문"], input[placeholder*="검색"]').first();
- if (await kbSearchInput.isVisible()) {
- await kbSearchInput.fill(regexBreakQuery);
- await window.keyboard.press('Enter');
- await window.waitForTimeout(800);
- }
-
- await window.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt18_02_knowledge_fuzzing_query.png'),
- });
-
- // Settle back to dashboard
- const dashboardNav = window.locator('text=/^(Dashboard|대시보드)$/').first();
- await dashboardNav.click();
- await window.waitForTimeout(500);
-
- expect(uncaughtExceptions).toEqual([]);
- });
-});
-
diff --git a/apps/desktop/tests/e2e/settings.spec.ts b/apps/desktop/tests/e2e/settings.spec.ts
index e8d8b2e..fa1be3b 100644
--- a/apps/desktop/tests/e2e/settings.spec.ts
+++ b/apps/desktop/tests/e2e/settings.spec.ts
@@ -1,94 +1,43 @@
-import { test, expect, _electron as electron } from '@playwright/test';
+// apps/desktop/tests/e2e/settings.spec.ts
+// 설정 화면 계약: 탭 목록은 `SETTINGS_TAB_ORDER` 가 정본이므로 테스트도 그 상수를 읽는다.
+// 탭 순서·개수를 테스트에 복사하면 탭을 옮길 때마다 두 곳을 고쳐야 한다 (SSOT 위반).
-test.describe('Settings Modal E2E', () => {
- test.describe.configure({ mode: 'serial' });
- let electronApp: any;
- let window: any;
+import { SETTINGS_TAB_ORDER, OPEN_SETTINGS_EVENT } from '../../src/renderer/navigation/settingsTabs'
+import { expect, expectNoRuntimeErrors, goToRoute, test } from './support/electron-app'
- test.beforeAll(async () => {
-
- electronApp = await electron.launch({
- args: ['out/main/index.js', '--user-data-dir=C:/Users/encep/AppData/Local/Temp/playwright-d3ro-test-settings'],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- let found = false;
- for (const w of electronApp.windows()) {
- await w.waitForLoadState('domcontentloaded');
- const t = await w.title();
- if (t === 'D3RO Voice' || t === 'd3ro-voice') {
- window = w;
- found = true;
- break;
- }
- }
-
- if (!found) {
- window = await electronApp.waitForEvent('window', {
- predicate: async (page) => {
- await page.waitForLoadState('domcontentloaded');
- const t = await page.title();
- return t === 'D3RO Voice' || t === 'd3ro-voice';
- }
- });
+test.describe('설정', () => {
+ test('사이드바 설정은 정본 탭 개수만큼 탭을 렌더하고 첫 탭을 선택한다', async ({ mainWindow }) => {
+ await goToRoute(mainWindow, 'settings')
+
+ const tabs = mainWindow.window.getByRole('tab')
+ await expect(tabs).toHaveCount(SETTINGS_TAB_ORDER.length)
+ await expect(mainWindow.window.getByTestId('settings-tab-general')).toHaveAttribute('aria-selected', 'true')
+
+ expectNoRuntimeErrors(mainWindow)
+ })
+
+ test('딥링크로 특정 탭을 열면 그 탭이 선택된다', async ({ mainWindow }) => {
+ await mainWindow.window.evaluate((eventName) => {
+ window.dispatchEvent(new CustomEvent(eventName, { detail: { tab: 'stt' } }))
+ }, OPEN_SETTINGS_EVENT)
+
+ await expect(mainWindow.window.getByTestId('settings-tab-stt')).toHaveAttribute('aria-selected', 'true')
+ await expect(mainWindow.window.getByRole('tab', { selected: true })).toHaveCount(1)
+
+ expectNoRuntimeErrors(mainWindow)
+ })
+
+ test('탭을 누르면 선택이 그 탭 하나로 바뀐다', async ({ mainWindow }) => {
+ await goToRoute(mainWindow, 'settings')
+
+ for (const tab of SETTINGS_TAB_ORDER) {
+ await test.step(tab, async () => {
+ await mainWindow.window.getByTestId(`settings-tab-${tab}`).click()
+ await expect(mainWindow.window.getByTestId(`settings-tab-${tab}`)).toHaveAttribute('aria-selected', 'true')
+ await expect(mainWindow.window.getByRole('tab', { selected: true })).toHaveCount(1)
+ })
}
- // Bypass onboarding via IPC config set
- await window.evaluate(async () => {
- if (window.electronAPI && window.electronAPI.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' });
- }
- });
- // Wait for the config to propagate then reload the page
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- // Wait for React to mount AppLayout
- await window.waitForTimeout(1000);
-
-
- });
-
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
-
- test('should open Settings Modal and navigate through tabs', async () => {
- // Open Settings via IPC event instead of clicking the UI
- await window.evaluate(() => {
- window.dispatchEvent(new CustomEvent('d3ro:open-settings'));
- });
-
- // Wait for the Settings modal to appear by checking for a known tab or title
- const tabs = window.locator('.MuiTab-root');
- await expect(tabs.first()).toBeVisible({ timeout: 5000 });
-
- // Since MuiDialog might have transition, wait a bit
- await window.waitForTimeout(1000);
-
- // Verify there are tabs available
- const tabCount = await tabs.count();
- expect(tabCount).toBeGreaterThan(0);
-
- // Click through each tab (use force to bypass potential transition overlays)
- for (let i = 0; i < tabCount; i++) {
- await tabs.nth(i).click({ force: true });
- await window.waitForTimeout(300); // Allow content to switch
- const isSelected = await tabs.nth(i).getAttribute('aria-selected');
- expect(isSelected).toBe('true');
- }
-
- // Close the settings modal using the Close button if it exists, or via Escape key
- await window.keyboard.press('Escape');
-
- // Wait for the modal to disappear
- await expect(tabs.first()).toBeHidden({ timeout: 5000 });
- });
-});
+ expectNoRuntimeErrors(mainWindow)
+ })
+})
diff --git a/apps/desktop/tests/e2e/support/electron-app.ts b/apps/desktop/tests/e2e/support/electron-app.ts
new file mode 100644
index 0000000..ca256fd
--- /dev/null
+++ b/apps/desktop/tests/e2e/support/electron-app.ts
@@ -0,0 +1,148 @@
+// apps/desktop/tests/e2e/support/electron-app.ts
+// 데스크톱 E2E 의 단일 진입점.
+//
+// 이 픽스처가 책임지는 것:
+// 1. `out/main/index.js` 빌드 산출물 확인 (없으면 "빌드부터 하라"는 메시지로 즉시 실패)
+// 2. 테스트마다 고유한 user-data 디렉터리 → 스펙 간 오염·순서 의존 제거 (Playwright Best Practices: isolation)
+// 3. 메인 창 판별(팝업 창 제외)과 온보딩 우회를 한 곳에서
+// 4. 렌더러 pageerror/console error 수집 → 각 테스트가 마지막에 단정
+//
+// 여기서 하는 모든 조작은 사용자가 보는 표면(창·브라우저·IPC 설정)뿐이다.
+// 스크린샷은 남기지 않는다. 실패 진단은 Playwright trace 가 담당한다(playwright.config.ts).
+
+import { randomUUID } from 'node:crypto'
+import { access, mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { _electron as electron, expect as baseExpect, test as base } from '@playwright/test'
+import type { ElectronApplication, Page } from '@playwright/test'
+
+const APP_ENTRY = path.resolve(__dirname, '../../../out/main/index.js')
+const MAIN_WINDOW_TIMEOUT_MS = 30_000
+
+export interface MainWindowContext {
+ app: ElectronApplication
+ window: Page
+ /** 렌더러에서 예상치 못하게 찍힌 console.error (Electron 보안 경고/CSP/리소스 로드 실패는 제외) */
+ consoleErrors: string[]
+ /** 잡히지 않은 렌더러 예외 */
+ pageErrors: string[]
+}
+
+interface Options {
+ /** false 면 온보딩을 우회하지 않고 첫 실행 상태로 띄운다. */
+ onboardingCompleted: boolean
+}
+
+const IGNORED_CONSOLE_PATTERNS = [
+ 'Electron Security Warning',
+ 'Content Security Policy',
+ 'Failed to load resource',
+ 'favicon.ico',
+ 'net::ERR_',
+]
+
+function isIgnoredConsoleError(text: string): boolean {
+ return IGNORED_CONSOLE_PATTERNS.some((pattern) => text.includes(pattern))
+}
+
+async function waitForMainWindow(app: ElectronApplication): Promise {
+ const deadline = Date.now() + MAIN_WINDOW_TIMEOUT_MS
+ while (Date.now() < deadline) {
+ for (const candidate of app.windows()) {
+ try {
+ const url = candidate.url()
+ if (url.includes('index.html') && !url.includes('popups/')) return candidate
+ } catch {
+ // 창이 아직 이동 중이다. 다음 폴링에서 다시 본다.
+ }
+ }
+ await new Promise((resolve) => setTimeout(resolve, 250))
+ }
+ throw new Error(
+ `메인 창이 ${MAIN_WINDOW_TIMEOUT_MS}ms 안에 나타나지 않았습니다. 열린 창: ${app
+ .windows()
+ .map((w) => {
+ try {
+ return w.url()
+ } catch {
+ return ''
+ }
+ })
+ .join(', ')}`,
+ )
+}
+
+interface ConfigBridge {
+ config?: {
+ set(params: { key: string; value: unknown }): Promise
+ }
+}
+
+async function applyConfigBypass(window: Page, onboardingCompleted: boolean): Promise {
+ await window.evaluate(async (completed) => {
+ const bridge = (window as unknown as { electronAPI?: ConfigBridge }).electronAPI
+ if (!bridge?.config) {
+ throw new Error('electronAPI.config 가 없습니다. preload 브리지가 노출되지 않았습니다.')
+ }
+ await bridge.config.set({ key: 'onboardingCompleted', value: completed })
+ await bridge.config.set({ key: 'appUsageMode', value: 'online' })
+ await bridge.config.set({ key: 'llmBackend', value: 'online' })
+ }, onboardingCompleted)
+ await window.reload()
+ await window.waitForLoadState('domcontentloaded')
+ await baseExpect(window.getByRole('navigation')).toBeVisible({ timeout: 15_000 })
+}
+
+export const test = base.extend({
+ onboardingCompleted: [true, { option: true }],
+
+ mainWindow: async ({ onboardingCompleted }, use) => {
+ await access(APP_ENTRY).catch(() => {
+ throw new Error(
+ `데스크톱 E2E 는 빌드 산출물이 필요합니다: ${APP_ENTRY} 가 없습니다. ` +
+ '`npm run build --workspace=@d3ro/desktop` 를 먼저 실행하세요.',
+ )
+ })
+
+ const userDataDir = await mkdtemp(path.join(tmpdir(), `d3ro-e2e-${randomUUID()}-`))
+ const consoleErrors: string[] = []
+ const pageErrors: string[] = []
+ const app = await electron.launch({
+ args: [APP_ENTRY, '--disable-gpu', '--no-sandbox', `--user-data-dir=${userDataDir}`],
+ env: { ...process.env, NODE_ENV: 'test' },
+ })
+
+ try {
+ const window = await waitForMainWindow(app)
+ await window.waitForLoadState('domcontentloaded')
+ window.on('pageerror', (error) => pageErrors.push(error.message))
+ window.on('console', (message) => {
+ if (message.type() !== 'error') return
+ const text = message.text()
+ if (!isIgnoredConsoleError(text)) consoleErrors.push(text)
+ })
+
+ await applyConfigBypass(window, onboardingCompleted)
+ await use({ app, window, consoleErrors, pageErrors })
+ } finally {
+ await app.close().catch(() => undefined)
+ await rm(userDataDir, { recursive: true, force: true }).catch(() => undefined)
+ }
+ },
+})
+
+export { expect } from '@playwright/test'
+
+/** 렌더러가 조용히 실패하지 않았음을 테스트 끝에서 확인한다. */
+export function expectNoRuntimeErrors(context: MainWindowContext): void {
+ baseExpect(context.pageErrors, '잡히지 않은 렌더러 예외').toEqual([])
+ baseExpect(context.consoleErrors, '렌더러 console.error').toEqual([])
+}
+
+/** 사이드바 항목을 눌러 화면을 옮긴다. 현재 화면 표시(aria-current)까지 확인한다. */
+export async function goToRoute(context: MainWindowContext, route: string): Promise {
+ const button = context.window.getByRole('navigation').getByTestId(`nav-${route}`)
+ await button.click()
+ await baseExpect(button).toHaveAttribute('aria-current', 'page')
+}
diff --git a/apps/desktop/tests/e2e/voice_pipeline.spec.ts b/apps/desktop/tests/e2e/voice_pipeline.spec.ts
deleted file mode 100644
index 0fe4370..0000000
--- a/apps/desktop/tests/e2e/voice_pipeline.spec.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { test, expect, _electron as electron } from '@playwright/test';
-
-test.describe('Voice Pipeline E2E', () => {
- test.describe.configure({ mode: 'serial' });
- let electronApp: any;
- let window: any;
-
- test.beforeAll(async () => {
-
- electronApp = await electron.launch({
- args: ['out/main/index.js', '--user-data-dir=C:/Users/encep/AppData/Local/Temp/playwright-d3ro-test-1786110374424-330'],
- env: {
- ...process.env,
- NODE_ENV: 'test',
- },
- });
-
- let found = false;
- for (const w of electronApp.windows()) {
- await w.waitForLoadState('domcontentloaded');
- const t = await w.title();
- if (t === 'D3RO Voice' || t === 'd3ro-voice') {
- window = w;
- found = true;
- break;
- }
- }
-
- if (!found) {
- window = await electronApp.waitForEvent('window', {
- predicate: async (page: any) => {
- await page.waitForLoadState('domcontentloaded');
- const t = await page.title();
- return t === 'D3RO Voice' || t === 'd3ro-voice';
- }
- });
- }
-
- // Bypass onboarding via IPC config set
- await window.evaluate(async () => {
- if (window.electronAPI && window.electronAPI.config) {
- await window.electronAPI.config.set({ key: 'onboardingCompleted', value: true });
- await window.electronAPI.config.set({ key: 'appUsageMode', value: 'online' });
- await window.electronAPI.config.set({ key: 'llmBackend', value: 'online' });
- }
- });
- // Wait for the config to propagate then reload the page
- await window.waitForTimeout(500);
- await window.reload();
- await window.waitForLoadState('domcontentloaded');
- // Wait for React to mount AppLayout
- await window.waitForTimeout(1000);
-
-
- });
-
- test.afterAll(async () => {
- if (electronApp) {
- await electronApp.close();
- }
- });
-
- test('should open Recording Tip on shortcut (or API call)', async () => {
- // In an E2E environment we can't easily trigger global shortcuts.
- // We can simulate the IPC event that the main process sends to renderer
- await window.evaluate(() => {
- window.dispatchEvent(new CustomEvent('d3ro:start-recording'));
- });
-
- // We should wait for the Recording Tip popup. But wait, Recording Tip is a separate window!
- const recordingWindow = await electronApp.waitForEvent('window', {
- predicate: async (page: any) => {
- await page.waitForLoadState('domcontentloaded');
- return await page.title() === 'Recording Tip';
- },
- timeout: 5000
- }).catch(() => null);
-
- // Some apps use IPC or separate windows for Recording tip. If we don't catch it, we skip.
- if (recordingWindow) {
- // Since it's a separate window, just knowing it opened is good enough.
- expect(recordingWindow).toBeTruthy();
- }
- });
-
-});
diff --git a/apps/desktop/tests/main/index-update-dialog-preview.test.ts b/apps/desktop/tests/main/index-update-dialog-preview.test.ts
new file mode 100644
index 0000000..81d7134
--- /dev/null
+++ b/apps/desktop/tests/main/index-update-dialog-preview.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it, vi } from 'vitest'
+
+type Listener = (...args: unknown[]) => void
+
+const state = vi.hoisted(() => ({
+ appListeners: new Map(),
+ bootstrap: vi.fn(async () => undefined),
+ exit: vi.fn(),
+ preview: vi.fn(async () => undefined),
+ quit: vi.fn(),
+ requestSingleInstanceLock: vi.fn(() => true),
+ setAsDefaultProtocolClient: vi.fn(),
+ setupLifecycle: vi.fn(),
+}))
+
+vi.mock('electron', () => ({
+ app: {
+ on: vi.fn((event: string, listener: Listener) => state.appListeners.set(event, listener)),
+ whenReady: vi.fn(() => Promise.resolve()),
+ setAsDefaultProtocolClient: state.setAsDefaultProtocolClient,
+ requestSingleInstanceLock: state.requestSingleInstanceLock,
+ disableHardwareAcceleration: vi.fn(),
+ commandLine: { appendSwitch: vi.fn() },
+ exit: state.exit,
+ quit: state.quit,
+ getPath: vi.fn(() => '.'),
+ },
+}))
+
+vi.mock('electron-log', () => ({
+ default: { error: vi.fn() },
+}))
+
+vi.mock('../../src/main/app-identity', () => ({ applyAppIdentity: vi.fn() }))
+vi.mock('../../src/main/bootstrap', () => ({ bootstrap: state.bootstrap }))
+vi.mock('../../src/main/lifecycle', () => ({ setupLifecycle: state.setupLifecycle }))
+vi.mock('../../src/main/windows/WindowManager', () => ({ showMainWindow: vi.fn(() => null) }))
+vi.mock('../../src/main/services/LoggerService', () => ({
+ getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
+}))
+vi.mock('../../src/main/update-dialog-preview', () => ({
+ isUpdateDialogPreviewRequested: () => true,
+ runUpdateDialogPreview: state.preview,
+}))
+
+describe('update dialog preview entrypoint', () => {
+ it('protocol/lock/bootstrap을 건드리지 않고 preview 후 종료한다', async () => {
+ await import('../../src/main/index')
+ await vi.waitFor(() => expect(state.preview).toHaveBeenCalledTimes(1))
+
+ expect(state.setAsDefaultProtocolClient).not.toHaveBeenCalled()
+ expect(state.requestSingleInstanceLock).not.toHaveBeenCalled()
+ expect(state.bootstrap).not.toHaveBeenCalled()
+ expect(state.setupLifecycle).not.toHaveBeenCalled()
+ expect(state.exit).not.toHaveBeenCalled()
+ expect(state.quit).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/apps/desktop/tests/main/services/update-dialog-i18n.test.ts b/apps/desktop/tests/main/services/update-dialog-i18n.test.ts
new file mode 100644
index 0000000..2fe9db5
--- /dev/null
+++ b/apps/desktop/tests/main/services/update-dialog-i18n.test.ts
@@ -0,0 +1,99 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { getI18n } from '@d3ro/i18n'
+import { createDialogPrompter } from '../../../src/main/services/update-adapters'
+import { getPopupTranslator } from '../../../src/main/windows/WindowManager'
+
+const dialog = vi.hoisted(() => ({ showMessageBox: vi.fn() }))
+
+vi.mock('electron', () => ({
+ app: { isPackaged: false },
+ dialog: { showMessageBox: dialog.showMessageBox },
+}))
+
+vi.mock('../../../src/main/windows/WindowManager', () => ({
+ getMainWindow: vi.fn(() => null),
+ getPopupTranslator: vi.fn(),
+}))
+
+describe('업데이트 대화상자 i18n', () => {
+ beforeEach(() => {
+ dialog.showMessageBox.mockReset()
+ vi.mocked(getPopupTranslator).mockReset()
+ })
+
+ it('한국어 일반 다운로드 문구와 버튼 순서를 유지한다', async () => {
+ vi.mocked(getPopupTranslator).mockReturnValue(getI18n('ko').t)
+ dialog.showMessageBox.mockResolvedValue({ response: 2 })
+
+ const answer = await createDialogPrompter().askConsent({
+ version: '1.16.1',
+ releaseNotes: '- 입력 경합 수정',
+ mandatory: false,
+ })
+
+ expect(answer).toBe('skip')
+ expect(dialog.showMessageBox).toHaveBeenCalledWith({
+ type: 'info',
+ title: '새 버전 업데이트',
+ message:
+ 'D3RO Voice v1.16.1 새 버전이 출시되었습니다. 지금 다운로드할까요?\n\n[주요 변경사항]\n- 입력 경합 수정',
+ buttons: ['지금 다운로드', '나중에', getI18n('ko').t('update.dialog.skipVersion')],
+ defaultId: 0,
+ cancelId: 1,
+ })
+ })
+
+ it('영어 필수 재시작 문구도 같은 계약으로 표시한다', async () => {
+ vi.mocked(getPopupTranslator).mockReturnValue(getI18n('en').t)
+ dialog.showMessageBox.mockResolvedValue({ response: 0 })
+
+ const answer = await createDialogPrompter().askRestart('1.16.1', { mandatory: true })
+
+ expect(answer).toBe('restart')
+ expect(dialog.showMessageBox).toHaveBeenCalledWith({
+ type: 'warning',
+ title: 'Required Update',
+ message:
+ 'Required update D3RO Voice v1.16.1 is ready. The app will restart to install it when you continue.',
+ buttons: ['Restart & Install Now'],
+ defaultId: 0,
+ cancelId: 0,
+ })
+ })
+
+ it('같은 prompter도 호출 시점의 앱 로케일을 사용한다', async () => {
+ vi.mocked(getPopupTranslator).mockReturnValue(getI18n('ko').t)
+ dialog.showMessageBox.mockResolvedValue({ response: 1 })
+ const prompter = createDialogPrompter()
+
+ const consent = await prompter.askConsent({
+ version: '1.16.1',
+ mandatory: false,
+ })
+
+ vi.mocked(getPopupTranslator).mockReturnValue(getI18n('en').t)
+ dialog.showMessageBox.mockResolvedValue({ response: 0 })
+ const restart = await prompter.askRestart('1.16.1', { mandatory: true })
+
+ expect(consent).toBe('later')
+ expect(restart).toBe('restart')
+ expect(getPopupTranslator).toHaveBeenCalledTimes(2)
+ expect(dialog.showMessageBox).toHaveBeenNthCalledWith(1, {
+ type: 'info',
+ title: '새 버전 업데이트',
+ message: 'D3RO Voice v1.16.1 새 버전이 출시되었습니다. 지금 다운로드할까요?',
+ buttons: ['지금 다운로드', '나중에', '이 버전 건너뛰기'],
+ defaultId: 0,
+ cancelId: 1,
+ })
+ expect(dialog.showMessageBox).toHaveBeenNthCalledWith(2, {
+ type: 'warning',
+ title: 'Required Update',
+ message:
+ 'Required update D3RO Voice v1.16.1 is ready. The app will restart to install it when you continue.',
+ buttons: ['Restart & Install Now'],
+ defaultId: 0,
+ cancelId: 0,
+ })
+ })
+})
diff --git a/apps/desktop/tests/main/update-dialog-preview.test.ts b/apps/desktop/tests/main/update-dialog-preview.test.ts
new file mode 100644
index 0000000..fd41ffe
--- /dev/null
+++ b/apps/desktop/tests/main/update-dialog-preview.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ askConsent: vi.fn(async () => 'later' as const),
+ askRestart: vi.fn(async () => 'later' as const),
+}))
+
+vi.mock('../../src/main/services/update-adapters', () => ({
+ createDialogPrompter: () => ({
+ askConsent: mocks.askConsent,
+ askRestart: mocks.askRestart,
+ }),
+}))
+
+import {
+ UPDATE_DIALOG_PREVIEW_ARG,
+ isUpdateDialogPreviewRequested,
+ runUpdateDialogPreview,
+} from '../../src/main/update-dialog-preview'
+
+describe('update dialog native preview', () => {
+ beforeEach(() => {
+ mocks.askConsent.mockClear()
+ mocks.askRestart.mockClear()
+ })
+
+ it('명시적 인자가 있을 때만 활성화된다', () => {
+ expect(isUpdateDialogPreviewRequested(['electron', '.'])).toBe(false)
+ expect(isUpdateDialogPreviewRequested(['D3RO Voice.exe', UPDATE_DIALOG_PREVIEW_ARG])).toBe(true)
+ })
+
+ it('optional/mandatory consent와 restart dialog를 각각 한 번씩 보여 준다', async () => {
+ await runUpdateDialogPreview()
+
+ expect(mocks.askConsent).toHaveBeenNthCalledWith(1, {
+ version: '99.0.0-preview',
+ releaseNotes: undefined,
+ mandatory: false,
+ })
+ expect(mocks.askConsent).toHaveBeenNthCalledWith(2, {
+ version: '99.0.0-preview',
+ releaseNotes: undefined,
+ mandatory: true,
+ })
+ expect(mocks.askRestart).toHaveBeenNthCalledWith(1, '99.0.0-preview', { mandatory: false })
+ expect(mocks.askRestart).toHaveBeenNthCalledWith(2, '99.0.0-preview', { mandatory: true })
+ })
+})
diff --git a/apps/desktop/tests/red/ads/ad-settlement.e2e.test.ts b/apps/desktop/tests/red/ads/ad-settlement.test.ts
similarity index 98%
rename from apps/desktop/tests/red/ads/ad-settlement.e2e.test.ts
rename to apps/desktop/tests/red/ads/ad-settlement.test.ts
index dfa3911..adbf22d 100644
--- a/apps/desktop/tests/red/ads/ad-settlement.e2e.test.ts
+++ b/apps/desktop/tests/red/ads/ad-settlement.test.ts
@@ -1,4 +1,4 @@
-// apps/desktop/tests/red/ads/ad-settlement.e2e.test.ts
+// apps/desktop/tests/red/ads/ad-settlement.test.ts
// D3RO Voice — 광고 정산·수익 원장 E2E RED 시나리오
// 계열 F: 수입이 실제 원장으로 집계되는 계약 (eCPM/환전/원천세/지급)
diff --git a/apps/desktop/tests/red/ads/admob-ssv.e2e.test.ts b/apps/desktop/tests/red/ads/admob-ssv.test.ts
similarity index 99%
rename from apps/desktop/tests/red/ads/admob-ssv.e2e.test.ts
rename to apps/desktop/tests/red/ads/admob-ssv.test.ts
index ced9527..aaa1456 100644
--- a/apps/desktop/tests/red/ads/admob-ssv.e2e.test.ts
+++ b/apps/desktop/tests/red/ads/admob-ssv.test.ts
@@ -1,4 +1,4 @@
-// apps/desktop/tests/red/ads/admob-ssv.e2e.test.ts
+// apps/desktop/tests/red/ads/admob-ssv.test.ts
// D3RO Voice — AdMob 리워드 SSV(서버 사이드 검증) E2E RED 시나리오
// 계열 E: 수입 인정의 유일한 근거인 SSV 콜백 검증 계약.
// 실 ECDSA P-256 키쌍을 생성해 서명/위조/변조를 실측한다(정답 유도 목업 금지).
diff --git a/apps/desktop/tests/red/ads/ads-mediation.e2e.test.ts b/apps/desktop/tests/red/ads/ads-mediation.test.ts
similarity index 99%
rename from apps/desktop/tests/red/ads/ads-mediation.e2e.test.ts
rename to apps/desktop/tests/red/ads/ads-mediation.test.ts
index dba032d..47d2010 100644
--- a/apps/desktop/tests/red/ads/ads-mediation.e2e.test.ts
+++ b/apps/desktop/tests/red/ads/ads-mediation.test.ts
@@ -1,4 +1,4 @@
-// apps/desktop/tests/red/ads/ads-mediation.e2e.test.ts
+// apps/desktop/tests/red/ads/ads-mediation.test.ts
// D3RO Voice — 광고 수익화 E2E RED 시나리오 (중개/입찰/노출/리워드)
// 계열 A(입찰 거버넌스) B(크리에이티브 안전성) C(노출·클릭 추적) D(리워드) G(설정)
// 시나리오는 "광고가 실제로 작동해 수입을 발생시키는" 목표 상태를 기술한다.
diff --git a/apps/desktop/tests/unit/AdMediationEngine.spec.ts b/apps/desktop/tests/unit/AdMediationEngine.test.ts
similarity index 100%
rename from apps/desktop/tests/unit/AdMediationEngine.spec.ts
rename to apps/desktop/tests/unit/AdMediationEngine.test.ts
diff --git a/apps/desktop/tests/unit/license-open-billing.spec.ts b/apps/desktop/tests/unit/license-open-billing.test.ts
similarity index 100%
rename from apps/desktop/tests/unit/license-open-billing.spec.ts
rename to apps/desktop/tests/unit/license-open-billing.test.ts
diff --git a/apps/mobile-rn/.maestro/notifications-permission-preserve-state.yaml b/apps/mobile-rn/.maestro/notifications-permission-preserve-state.yaml
new file mode 100644
index 0000000..18394d0
--- /dev/null
+++ b/apps/mobile-rn/.maestro/notifications-permission-preserve-state.yaml
@@ -0,0 +1,31 @@
+appId: com.d3ro.voice
+name: Notifications status screen without changing device state
+---
+- launchApp:
+ clearState: false
+ stopApp: true
+- extendedWaitUntil:
+ visible:
+ id: home-screen
+ timeout: 30000
+- tapOn:
+ id: tab-more
+- scrollUntilVisible:
+ element:
+ id: open-notifications
+ direction: DOWN
+ timeout: 15000
+ visibilityPercentage: 50
+- tapOn:
+ id: open-notifications
+- extendedWaitUntil:
+ visible:
+ id: notifications-screen
+ timeout: 15000
+- assertVisible:
+ id: notification-status-card
+- assertVisible:
+ id: notification-privacy-card
+- assertVisible:
+ id: notification-recent-card
+- takeScreenshot: notifications-status-preserved
diff --git a/apps/mobile-rn/__tests__/App.test.tsx b/apps/mobile-rn/__tests__/App.test.tsx
index e532f70..ab38d6f 100644
--- a/apps/mobile-rn/__tests__/App.test.tsx
+++ b/apps/mobile-rn/__tests__/App.test.tsx
@@ -6,8 +6,12 @@ import React from 'react';
import ReactTestRenderer from 'react-test-renderer';
import App from '../App';
-test('renders correctly', async () => {
+test('앱 루트가 예외 없이 렌더된다', async () => {
+ let tree;
+
await ReactTestRenderer.act(() => {
- ReactTestRenderer.create();
+ tree = ReactTestRenderer.create();
});
+
+ expect(tree?.toJSON() ?? null).not.toBeNull();
});
diff --git a/apps/mobile-rn/__tests__/notifications.test.ts b/apps/mobile-rn/__tests__/notifications.test.ts
index aa91ea1..8801bc4 100644
--- a/apps/mobile-rn/__tests__/notifications.test.ts
+++ b/apps/mobile-rn/__tests__/notifications.test.ts
@@ -323,6 +323,7 @@ describe('device-bound push registration', () => {
await expect(
subscribeWebPush({
userId: USER_ID,
+ deviceId: DEVICE_ID,
vapidPublicKey: '',
}),
).rejects.toMatchObject({ code: 'vapid-key-missing' })
diff --git a/apps/mobile-rn/package-lock.json b/apps/mobile-rn/package-lock.json
index 0d61094..f95ca17 100644
--- a/apps/mobile-rn/package-lock.json
+++ b/apps/mobile-rn/package-lock.json
@@ -84,7 +84,6 @@
"version": "1.16.1",
"license": "MIT",
"dependencies": {
- "@d3ro/core": "*",
"@supabase/supabase-js": "^2.45.0"
},
"peerDependencies": {
diff --git a/apps/mobile-rn/src/screens/AccountScreen.tsx b/apps/mobile-rn/src/screens/AccountScreen.tsx
index 1a3a1fc..52b1c03 100644
--- a/apps/mobile-rn/src/screens/AccountScreen.tsx
+++ b/apps/mobile-rn/src/screens/AccountScreen.tsx
@@ -14,6 +14,7 @@ import {
} from 'react-native'
import InAppBrowser from 'react-native-inappbrowser-reborn'
import { useNavigation } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import {
Led,
MetalCard,
@@ -46,6 +47,7 @@ import {
type AccountDeletionService,
} from '../features/account/account-deletion-service'
import { ScreenHeader } from '../components/ScreenHeader'
+import type { RootStackParamList } from '../../App'
// Public surface kept for existing importers; the use case now lives in
// features/account so it is testable without rendering this screen.
@@ -77,12 +79,13 @@ export interface AccountScreenProps {
}
type ActiveAction = 'save' | 'logout' | 'delete' | `link:${ManagedOAuthProvider}` | `unlink:${string}` | null
+type AccountNavigation = NativeStackNavigationProp
export default function AccountScreen({
deletionService = edgeAccountDeletionService,
identityService = identityManagementService,
}: AccountScreenProps): React.ReactElement {
- const navigation = useNavigation()
+ const navigation = useNavigation()
const { user, purgeLocalSession } = useAuth()
const { currentDevice } = useDevice()
const { palette } = useMobilePreferences()
diff --git a/apps/mobile-rn/src/screens/CommandsScreen.tsx b/apps/mobile-rn/src/screens/CommandsScreen.tsx
index ea75660..b71cec0 100644
--- a/apps/mobile-rn/src/screens/CommandsScreen.tsx
+++ b/apps/mobile-rn/src/screens/CommandsScreen.tsx
@@ -13,6 +13,7 @@ import {
View,
} from 'react-native'
import { useFocusEffect, useNavigation } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useI18n, type TranslationKey } from '@d3ro/i18n'
import { useAuth } from '../lib/auth-context'
@@ -39,6 +40,9 @@ import {
import ContentReportSheet, {
type ContentReportTarget,
} from '../components/ContentReportSheet'
+import type { RootStackParamList } from '../../App'
+
+type CommandsNavigation = NativeStackNavigationProp
const NAME_KEYS: Record = {
translate_en: 'mobile.commands.translate.name',
@@ -85,7 +89,7 @@ interface EditorState {
export default function CommandsScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
- const navigation = useNavigation()
+ const navigation = useNavigation()
const { t } = useI18n()
const { user, session } = useAuth()
const { palette, preferences } = useMobilePreferences()
diff --git a/apps/mobile-rn/src/screens/DataPortabilityScreen.tsx b/apps/mobile-rn/src/screens/DataPortabilityScreen.tsx
index d7e3f13..5bd0305 100644
--- a/apps/mobile-rn/src/screens/DataPortabilityScreen.tsx
+++ b/apps/mobile-rn/src/screens/DataPortabilityScreen.tsx
@@ -1,6 +1,7 @@
import { useMemo, useState } from 'react';
import { ActivityIndicator, ScrollView, StyleSheet, View } from 'react-native';
import { useNavigation } from '@react-navigation/native';
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useI18n, type TranslationKey } from '@d3ro/i18n';
import { useAuth } from '../lib/auth-context';
@@ -18,6 +19,7 @@ import {
sharePreparedPortableFile,
type PreparedPortableFile,
} from '../features/data-portability';
+import type { RootStackParamList } from '../../App';
type ExportKind =
| 'account-json'
@@ -26,6 +28,7 @@ type ExportKind =
| 'history-csv'
| 'summary-txt';
type BusyAction = ExportKind | 'import' | null;
+type DataPortabilityNavigation = NativeStackNavigationProp;
const ERROR_KEYS: Record = {
auth: 'mobile.portability.error.auth',
@@ -45,7 +48,7 @@ const ERROR_KEYS: Record = {
export default function DataPortabilityScreen(): React.ReactElement {
const insets = useSafeAreaInsets();
- const navigation = useNavigation();
+ const navigation = useNavigation();
const { t } = useI18n();
const { user } = useAuth();
const { palette } = useMobilePreferences();
diff --git a/apps/mobile-rn/src/screens/DevicesScreen.tsx b/apps/mobile-rn/src/screens/DevicesScreen.tsx
index d372d17..f50c692 100644
--- a/apps/mobile-rn/src/screens/DevicesScreen.tsx
+++ b/apps/mobile-rn/src/screens/DevicesScreen.tsx
@@ -9,6 +9,7 @@ import {
View,
} from 'react-native'
import { useFocusEffect, useNavigation } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useI18n } from '@d3ro/i18n'
import { useAuth } from '../lib/auth-context'
@@ -22,10 +23,13 @@ import {
revokeRegisteredDevice,
type RegisteredDevice,
} from '../features/devices/device-service'
+import type { RootStackParamList } from '../../App'
+
+type DevicesNavigation = NativeStackNavigationProp
export default function DevicesScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
- const navigation = useNavigation()
+ const navigation = useNavigation()
const { t } = useI18n()
const { user } = useAuth()
const { currentDevice } = useDevice()
diff --git a/apps/mobile-rn/src/screens/ForgotPasswordScreen.tsx b/apps/mobile-rn/src/screens/ForgotPasswordScreen.tsx
index b9d796f..75cbb09 100644
--- a/apps/mobile-rn/src/screens/ForgotPasswordScreen.tsx
+++ b/apps/mobile-rn/src/screens/ForgotPasswordScreen.tsx
@@ -8,6 +8,7 @@ import {
View,
} from 'react-native'
import { useNavigation } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import {
Led,
@@ -21,15 +22,17 @@ import { useI18n } from '@d3ro/i18n'
import { isSupabaseConfigured, supabase } from '../lib/supabase'
import { AUTH_REDIRECT_URL } from '../lib/auth-redirect'
import { useMobilePreferences } from '../lib/preferences-context'
+import type { RootStackParamList } from '../../App'
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
+type ForgotPasswordNavigation = NativeStackNavigationProp
// Canonical product callback. AuthProvider owns PKCE/implicit token exchange and
// routes the resulting recovery state to UpdatePassword.
export const PASSWORD_RECOVERY_REDIRECT = AUTH_REDIRECT_URL
export default function ForgotPasswordScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
- const navigation = useNavigation()
+ const navigation = useNavigation()
const { t } = useI18n()
const { palette } = useMobilePreferences()
const styles = useMemo(() => createStyles(palette), [palette])
diff --git a/apps/mobile-rn/src/screens/InviteAcceptScreen.tsx b/apps/mobile-rn/src/screens/InviteAcceptScreen.tsx
index faeac5d..3cbc459 100644
--- a/apps/mobile-rn/src/screens/InviteAcceptScreen.tsx
+++ b/apps/mobile-rn/src/screens/InviteAcceptScreen.tsx
@@ -5,8 +5,9 @@ import {
StyleSheet,
View,
} from 'react-native'
-import type { ParamListBase, RouteProp } from '@react-navigation/native'
+import type { RouteProp } from '@react-navigation/native'
import { useNavigation } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useI18n } from '@d3ro/i18n'
import { useAuth } from '../lib/auth-context'
@@ -25,19 +26,18 @@ import {
savePendingInviteToken,
} from '../features/teams/pending-invite'
import { teamErrorCode, teamErrorMessage } from './TeamsScreen'
+import type { RootStackParamList } from '../../App'
-interface InviteAcceptRouteParams extends ParamListBase {
- InviteAccept: { token?: string; url?: string } | undefined
-}
+type InviteAcceptNavigation = NativeStackNavigationProp
interface InviteAcceptScreenProps {
- route: RouteProp
+ route: RouteProp
}
type InviteState = 'loading' | 'ready' | 'accepting' | 'success' | 'error'
export default function InviteAcceptScreen({ route }: InviteAcceptScreenProps): React.ReactElement {
- const navigation = useNavigation()
+ const navigation = useNavigation()
const insets = useSafeAreaInsets()
const { t } = useI18n()
const { user } = useAuth()
diff --git a/apps/mobile-rn/src/screens/NotificationsScreen.tsx b/apps/mobile-rn/src/screens/NotificationsScreen.tsx
index ed86d4f..282a2c0 100644
--- a/apps/mobile-rn/src/screens/NotificationsScreen.tsx
+++ b/apps/mobile-rn/src/screens/NotificationsScreen.tsx
@@ -9,6 +9,7 @@ import {
View,
} from 'react-native'
import { useFocusEffect, useNavigation } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useI18n } from '@d3ro/i18n'
import { useAuth } from '../lib/auth-context'
@@ -33,6 +34,9 @@ import {
synchronizePushRegistration,
type NotificationSyncResult,
} from '../features/notifications/notification-service'
+import type { RootStackParamList } from '../../App'
+
+type NotificationsNavigation = NativeStackNavigationProp
interface ReceivedNotification {
key: string
@@ -41,7 +45,7 @@ interface ReceivedNotification {
}
export default function NotificationsScreen(): React.ReactElement {
- const navigation = useNavigation()
+ const navigation = useNavigation()
const insets = useSafeAreaInsets()
const { t, formatDate } = useI18n()
const { user } = useAuth()
@@ -120,7 +124,16 @@ export default function NotificationsScreen(): React.ReactElement {
const openNotification = (notification: D3RONotification): void => {
const target = notificationNavigationTarget(notification)
- navigation.navigate(target.name, target.params)
+ if (target.name === 'HistoryDetail') {
+ const historyId = target.params?.historyId
+ if (historyId !== undefined) navigation.navigate('HistoryDetail', { historyId })
+ return
+ }
+ if (target.name === 'InviteAccept') {
+ navigation.navigate('InviteAccept', target.params)
+ return
+ }
+ navigation.navigate('ProPaywall')
}
const statusTone = syncResult?.status === 'registered' ? 'success' : 'muted'
diff --git a/apps/mobile-rn/src/screens/SettingsScreen.tsx b/apps/mobile-rn/src/screens/SettingsScreen.tsx
index a7863fd..9a69df9 100644
--- a/apps/mobile-rn/src/screens/SettingsScreen.tsx
+++ b/apps/mobile-rn/src/screens/SettingsScreen.tsx
@@ -9,6 +9,7 @@ import {
View,
} from 'react-native'
import { useNavigation } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useI18n, type TranslationKey } from '@d3ro/i18n'
import { SITE_URLS } from '@d3ro/core/web-urls'
import { useAuth } from '../lib/auth-context'
@@ -34,8 +35,10 @@ import { useDevice } from '../lib/device-context'
import { currentAdminRole } from '../features/admin/admin-service'
import { ScreenHeader } from '../components/ScreenHeader'
import { performAccountLogout } from '../lib/account-exit'
+import type { RootStackParamList } from '../../App'
type SavingPreference = 'theme' | 'locale' | 'autoPolish' | 'haptic' | null
+type SettingsNavigation = NativeStackNavigationProp
const THEME_LABEL_KEYS: Record = {
system: 'mobile.theme.system',
@@ -62,7 +65,7 @@ const ERROR_KEYS: Record = {
export default function SettingsScreen(): React.ReactElement {
const { t, locale, setLocale, formatTime } = useI18n()
const { user, purgeLocalSession } = useAuth()
- const navigation = useNavigation()
+ const navigation = useNavigation()
const {
preferences,
palette,
diff --git a/apps/mobile-rn/src/screens/SignUpScreen.tsx b/apps/mobile-rn/src/screens/SignUpScreen.tsx
index 526528a..5f1eceb 100644
--- a/apps/mobile-rn/src/screens/SignUpScreen.tsx
+++ b/apps/mobile-rn/src/screens/SignUpScreen.tsx
@@ -11,6 +11,7 @@ import {
View,
} from 'react-native'
import { useNavigation } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import {
Led,
@@ -31,13 +32,15 @@ import {
} from '../features/auth/oauth-sign-in'
import { useAuth } from '../lib/auth-context'
import { useMobilePreferences } from '../lib/preferences-context'
+import type { RootStackParamList } from '../../App'
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const MIN_PASSWORD_LENGTH = 8
+type SignUpNavigation = NativeStackNavigationProp
export default function SignUpScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
- const navigation = useNavigation()
+ const navigation = useNavigation()
const { locale, t } = useI18n()
const { authError } = useAuth()
const { palette } = useMobilePreferences()
diff --git a/apps/mobile-rn/src/screens/TalkScreen.tsx b/apps/mobile-rn/src/screens/TalkScreen.tsx
index 50f938e..443f981 100644
--- a/apps/mobile-rn/src/screens/TalkScreen.tsx
+++ b/apps/mobile-rn/src/screens/TalkScreen.tsx
@@ -16,6 +16,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useI18n } from '@d3ro/i18n'
import { ThemeButton, ThemeText } from '../theme/themed-components'
import { useAuth } from '../lib/auth-context'
+import { createLogger } from '../lib/logger'
import { useMobilePreferences } from '../lib/preferences-context'
import {
audioRecorder,
@@ -65,6 +66,7 @@ type TalkErrorCode = ChatErrorCode
| 'TTS_FAILED'
const MIN_RECORDING_MS = 450
+const log = createLogger('Talk')
function errorTranslationKey(code: TalkErrorCode) {
switch (code) {
@@ -467,8 +469,8 @@ export default function TalkScreen(): React.ReactElement {
) {
causeChain.push(e.message)
}
- console.warn(
- `[Talk] transcription failed (${error instanceof AudioPipelineError ? error.code : 'unknown'}):`,
+ log.warn(
+ `transcription failed (${error instanceof AudioPipelineError ? error.code : 'unknown'}):`,
causeChain.join(' | '),
)
if (!isCurrentOperation(operationId)) return
diff --git a/apps/mobile-rn/src/screens/TeamDetailScreen.tsx b/apps/mobile-rn/src/screens/TeamDetailScreen.tsx
index f1b7375..04e6113 100644
--- a/apps/mobile-rn/src/screens/TeamDetailScreen.tsx
+++ b/apps/mobile-rn/src/screens/TeamDetailScreen.tsx
@@ -13,8 +13,9 @@ import {
TextInput,
View,
} from 'react-native'
-import type { ParamListBase, RouteProp } from '@react-navigation/native'
+import type { RouteProp } from '@react-navigation/native'
import { useFocusEffect, useNavigation } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import { useI18n } from '@d3ro/i18n'
import { useAuth } from '../lib/auth-context'
@@ -38,20 +39,19 @@ import {
updateTeamMemberRole,
} from '../features/teams/team-service'
import { teamErrorCode, teamErrorMessage } from './TeamsScreen'
+import type { RootStackParamList } from '../../App'
-interface TeamDetailRouteParams extends ParamListBase {
- TeamDetail: { teamId: string }
-}
+type TeamDetailNavigation = NativeStackNavigationProp
interface TeamDetailScreenProps {
- route: RouteProp
+ route: RouteProp
}
type Editor = 'rename' | 'invite' | null
export default function TeamDetailScreen({ route }: TeamDetailScreenProps): React.ReactElement {
const teamId = route.params.teamId
- const navigation = useNavigation()
+ const navigation = useNavigation()
const insets = useSafeAreaInsets()
const { t, formatDate } = useI18n()
const { user } = useAuth()
diff --git a/apps/mobile-rn/src/screens/UpdatePasswordScreen.tsx b/apps/mobile-rn/src/screens/UpdatePasswordScreen.tsx
index 23efbca..b881160 100644
--- a/apps/mobile-rn/src/screens/UpdatePasswordScreen.tsx
+++ b/apps/mobile-rn/src/screens/UpdatePasswordScreen.tsx
@@ -8,7 +8,8 @@ import {
TextInput,
View,
} from 'react-native'
-import { useNavigation, useRoute } from '@react-navigation/native'
+import { useNavigation, useRoute, type RouteProp } from '@react-navigation/native'
+import type { NativeStackNavigationProp } from '@react-navigation/native-stack'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
import {
Led,
@@ -22,13 +23,16 @@ import { useI18n } from '@d3ro/i18n'
import { isSupabaseConfigured, supabase } from '../lib/supabase'
import { useAuth } from '../lib/auth-context'
import { useMobilePreferences } from '../lib/preferences-context'
+import type { RootStackParamList } from '../../App'
const MIN_PASSWORD_LENGTH = 8
+type UpdatePasswordNavigation = NativeStackNavigationProp
+type UpdatePasswordRoute = RouteProp
export default function UpdatePasswordScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
- const navigation = useNavigation()
- const route = useRoute()
+ const navigation = useNavigation()
+ const route = useRoute()
const { t } = useI18n()
const { palette } = useMobilePreferences()
const styles = useMemo(() => createStyles(palette), [palette])
diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile
index f05a4fb..87bed82 100644
--- a/apps/web/Dockerfile
+++ b/apps/web/Dockerfile
@@ -3,7 +3,8 @@
# docker build -t d3ro-voice-web:latest -f apps/web/Dockerfile \
# --build-arg NEXT_PUBLIC_SUPABASE_URL=... \
# --build-arg NEXT_PUBLIC_SUPABASE_ANON_KEY=... \
-# --build-arg NEXT_PUBLIC_PAYPLE_CLIENT_KEY=... .
+# --build-arg NEXT_PUBLIC_PAYPLE_CLIENT_KEY=... \
+# --build-arg NEXT_PUBLIC_VAPID_PUBLIC_KEY=... .
# 공개 경로는 https://d3ro.chanpaca.net/app (Next basePath '/app', 정본 packages/core/src/web-urls.ts).
FROM node:24.19.0-alpine AS base
@@ -14,9 +15,11 @@ WORKDIR /app
ARG NEXT_PUBLIC_SUPABASE_URL
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
ARG NEXT_PUBLIC_PAYPLE_CLIENT_KEY=""
+ARG NEXT_PUBLIC_VAPID_PUBLIC_KEY=""
ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL \
NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY \
NEXT_PUBLIC_PAYPLE_CLIENT_KEY=$NEXT_PUBLIC_PAYPLE_CLIENT_KEY \
+ NEXT_PUBLIC_VAPID_PUBLIC_KEY=$NEXT_PUBLIC_VAPID_PUBLIC_KEY \
NEXT_TELEMETRY_DISABLED=1
RUN test -n "$NEXT_PUBLIC_SUPABASE_URL" && test -n "$NEXT_PUBLIC_SUPABASE_ANON_KEY" \
|| (echo "NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY build args are required" >&2 && exit 1)
@@ -39,6 +42,7 @@ ENV NEXT_TELEMETRY_DISABLED=1
# node 사용자로 실행하므로 .next/cache 쓰기가 가능하도록 소유권을 넘긴다.
COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
+COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public
USER node
EXPOSE 3002
diff --git a/apps/web/e2e/red_team_cycle4_web.spec.ts b/apps/web/e2e/red_team_cycle4_web.spec.ts
deleted file mode 100644
index 838177b..0000000
--- a/apps/web/e2e/red_team_cycle4_web.spec.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { test, expect } from '@playwright/test';
-import path from 'path';
-import fs from 'fs';
-import { SITE_URLS } from '@d3ro/core/web-urls';
-
-const SCREENSHOT_DIR = path.resolve('C:/Users/encep/.gemini/antigravity/brain/bbff18a3-721d-4c43-989f-1d6964e15be7/screenshots');
-
-test.describe.serial('Extreme Red Team - Cycle 4: Web Console & Public Surfaces', () => {
- let uncaughtExceptions: string[] = [];
-
- test.beforeAll(() => {
- if (!fs.existsSync(SCREENSHOT_DIR)) {
- fs.mkdirSync(SCREENSHOT_DIR, { recursive: true });
- }
- });
-
- test.beforeEach(({ page }) => {
- uncaughtExceptions = [];
- page.on('pageerror', (err) => {
- console.error('[WEB PAGEERROR]:', err.message);
- uncaughtExceptions.push(err.message);
- });
- });
-
- test('RT-14: Web Public Hub - /login and the /download redirect to the landing site', async ({ page }) => {
- // 1. Test /login
- await page.goto('/app/login');
- await page.waitForLoadState('domcontentloaded');
-
- await expect(page.getByText(/D3RO[- ]VOICE/i)).toBeVisible({ timeout: 10000 });
- await expect(page.getByRole('button', { name: /Google/i })).toBeVisible();
- await expect(page.getByRole('button', { name: /GitHub/i })).toBeVisible();
-
- // Screenshot login
- await page.screenshot({
- path: path.join(SCREENSHOT_DIR, 'rt14_01_web_login.png'),
- });
-
- // 2. /download lives only on the landing site; the web app just redirects there.
- const downloadRes = await page.request.get('/app/download', { maxRedirects: 0 });
- expect([307, 308]).toContain(downloadRes.status());
- expect(downloadRes.headers()['location']).toBe(SITE_URLS.download);
-
- expect(uncaughtExceptions).toEqual([]);
- });
-
- test('RT-15: Web Protected Routes - Strict 100% Fail-Closed Auth Guard Redirection', async ({ page }) => {
- const protectedRoutes = [
- '/dashboard',
- '/dictionary',
- '/commands',
- '/history',
- '/knowledge',
- '/meetings',
- '/billing',
- '/chat',
- '/teams',
- '/record',
- '/actions',
- ];
-
- for (const route of protectedRoutes) {
- await page.goto(`/app${route}`);
- await page.waitForURL(/\/login/, { timeout: 10000 });
- expect(page.url()).toContain('/login');
- }
-
- expect(uncaughtExceptions).toEqual([]);
- });
-});
diff --git a/apps/web/e2e/smoke.spec.ts b/apps/web/e2e/smoke.spec.ts
index 2554160..c5f685d 100644
--- a/apps/web/e2e/smoke.spec.ts
+++ b/apps/web/e2e/smoke.spec.ts
@@ -1,40 +1,61 @@
// apps/web/e2e/smoke.spec.ts
-// 기본 스모크 테스트 — 인증 없이 접근 가능한 라우트 확인.
+// 인증 없이 접근 가능한 표면의 계약 (스모크):
+// 1. 보호 라우트는 예외 없이 전부 /login 으로 되돌린다 (fail-closed)
+// 2. /login 은 로고와 Google/GitHub OAuth 진입을 보여준다
+// 3. /download 는 웹앱이 아니라 랜딩 사이트로 넘긴다
//
// 실행:
-// npm install -D @playwright/test --workspace=@d3ro/web
-// npx playwright install chromium --with-deps
// npm run test:e2e --workspace=@d3ro/web
+//
+// 배포 환경별 차이는 E2E_BASE_URL 로 주입한다. 서버를 띄우지 않으려면 E2E_NO_SERVER=1.
import { test, expect } from '@playwright/test'
+import { SITE_URLS } from '@d3ro/core/web-urls'
+
+// 보호 라우트 전체. 라우트를 추가하면 여기에도 추가한다 (누락 = 미검증 표면).
+const PROTECTED_ROUTES = [
+ '/dashboard',
+ '/dictionary',
+ '/commands',
+ '/history',
+ '/knowledge',
+ '/meetings',
+ '/billing',
+ '/chat',
+ '/teams',
+ '/record',
+ '/actions',
+] as const
test.describe('Smoke: unauthenticated access', () => {
- test('루트(/)는 /login으로 리다이렉트된다 (Supabase 미설정 시)', async ({ page }) => {
+ test('루트(/)는 /login으로 리다이렉트된다', async ({ page }) => {
await page.goto('/app')
await page.waitForURL(/\/login/, { timeout: 10000 })
expect(page.url()).toContain('/login')
})
- test('/login 페이지가 로드되고 D3RO VOICE 로고가 표시된다', async ({ page }) => {
+ test('/login은 로고와 Google/GitHub OAuth 버튼을 보여준다', async ({ page }) => {
await page.goto('/app/login')
- await expect(page.getByText(/D3RO[- ]VOICE/i)).toBeVisible({ timeout: 10000 })
- })
- test('/login에 Google/GitHub OAuth 버튼이 보인다', async ({ page }) => {
- await page.goto('/app/login')
+ await expect(page.getByText(/D3RO[- ]VOICE/i)).toBeVisible({ timeout: 10000 })
await expect(page.getByRole('button', { name: /Google/i })).toBeVisible()
await expect(page.getByRole('button', { name: /GitHub/i })).toBeVisible()
})
- test('/dashboard는 미로그인 시 /login으로 리다이렉트', async ({ page }) => {
- await page.goto('/app/dashboard')
- await page.waitForURL(/\/login/, { timeout: 10000 })
- expect(page.url()).toContain('/login')
+ test('모든 보호 라우트는 미로그인 시 /login으로 되돌린다', async ({ page }) => {
+ for (const route of PROTECTED_ROUTES) {
+ await test.step(route, async () => {
+ await page.goto(`/app${route}`)
+ await page.waitForURL(/\/login/, { timeout: 10000 })
+ expect(page.url()).toContain('/login')
+ })
+ }
})
- test('/meetings도 미로그인 시 /login으로 리다이렉트', async ({ page }) => {
- await page.goto('/app/meetings')
- await page.waitForURL(/\/login/, { timeout: 10000 })
- expect(page.url()).toContain('/login')
+ test('/download는 랜딩 사이트 다운로드 페이지로 넘긴다', async ({ page }) => {
+ const response = await page.request.get('/app/download', { maxRedirects: 0 })
+
+ expect([307, 308]).toContain(response.status())
+ expect(response.headers()['location']).toBe(SITE_URLS.download)
})
})
diff --git a/apps/web/env.example.txt b/apps/web/env.example.txt
index b83e087..33abcda 100644
--- a/apps/web/env.example.txt
+++ b/apps/web/env.example.txt
@@ -13,3 +13,7 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
# Payple browser SDK client key (test keys start with test_)
# Missing values fail closed and disable the Payple checkout button.
NEXT_PUBLIC_PAYPLE_CLIENT_KEY=your-payple-client-key
+
+# Web Push VAPID public key. It must match the Edge Function's
+# WEBPUSH_VAPID_PUBLIC_KEY. Missing values keep browser notifications disabled.
+NEXT_PUBLIC_VAPID_PUBLIC_KEY=your-vapid-public-key
diff --git a/apps/web/package.json b/apps/web/package.json
index 17d3c17..97b71a2 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -7,8 +7,10 @@
"dev": "next dev --port 3000",
"build": "next build",
"start": "next start --port 3000",
- "typecheck": "tsc --noEmit",
+ "typecheck": "next typegen && tsc --noEmit",
"lint": "eslint src --ext .ts,.tsx",
+ "test": "vitest run",
+ "test:watch": "vitest",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui"
},
@@ -31,12 +33,13 @@
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
- "recharts": "^3.8.1",
"remark-gfm": "^4.0.1"
},
"devDependencies": {
+ "@playwright/test": "^1.62.1",
"@types/node": "^22.13.0",
"@types/react": "^19.0.0",
- "@types/react-dom": "^19.0.0"
+ "@types/react-dom": "^19.0.0",
+ "vitest": "^2.1.0"
}
}
diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsx
index 27e730d..5aa1211 100644
--- a/apps/web/src/app/login/page.tsx
+++ b/apps/web/src/app/login/page.tsx
@@ -159,7 +159,7 @@ export default function LoginPage(): React.ReactElement {
color: d3roPalette.text.label
}}
>
- {t('login.subtitle') ?? 'Precision Voice Intelligence'}
+ {t('login.subtitle')}
@@ -215,7 +215,7 @@ export default function LoginPage(): React.ReactElement {
- {t('login.google') ?? 'Google로 로그인'}
+ {t('login.google')}
{/* Apple Button */}
@@ -289,7 +289,7 @@ export default function LoginPage(): React.ReactElement {
- {t('login.github') ?? 'GitHub로 로그인'}
+ {t('login.github')}
@@ -304,7 +304,7 @@ export default function LoginPage(): React.ReactElement {
letterSpacing: 0
}}
>
- {t('login.or') ?? '또는'}
+ {t('login.or')}
diff --git a/apps/web/src/components/dashboard/meetings-trend-chart.tsx b/apps/web/src/components/dashboard/meetings-trend-chart.tsx
deleted file mode 100644
index 3c884b9..0000000
--- a/apps/web/src/components/dashboard/meetings-trend-chart.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-'use client'
-
-// apps/web/src/components/dashboard/meetings-trend-chart.tsx
-// recharts 기반 회의/문서 추이 차트 (최근 14일).
-
-import {
- ResponsiveContainer,
- LineChart,
- Line,
- XAxis,
- YAxis,
- Tooltip,
- CartesianGrid,
- Legend
-} from 'recharts'
-import { Box } from '@mui/material'
-import { d3roPalette } from '@d3ro/ui/theme'
-
-export interface TrendPoint {
- date: string
- meetings: number
- documents: number
-}
-
-interface MeetingsTrendChartProps {
- points: TrendPoint[]
-}
-
-export function MeetingsTrendChart({ points }: MeetingsTrendChartProps): React.ReactElement {
- return (
-
-
-
-
-
-
-
-
-
-
-
-
-
- )
-}
diff --git a/apps/web/src/components/layout/sidebar.tsx b/apps/web/src/components/layout/sidebar.tsx
index 7ac0b84..cf76e17 100644
--- a/apps/web/src/components/layout/sidebar.tsx
+++ b/apps/web/src/components/layout/sidebar.tsx
@@ -31,7 +31,14 @@ import { PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette } from '@d3ro/ui/theme'
import { useI18n } from '@d3ro/i18n'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
+import {
+ disableCurrentWebPush,
+ signOutWithoutWaitingForWebPushCleanup,
+ WEB_APP_VERSION,
+} from '@/lib/web-push-session'
+import { useAuth } from '@/components/providers/auth-provider'
import { AVAILABLE_MODES, useThemeMode } from '@/components/providers/theme-mode-context'
+import { WebPushControl } from './web-push-control'
interface NavItem {
key: string
@@ -45,6 +52,7 @@ export function Sidebar(): React.ReactElement {
const pathname = usePathname()
const { t } = useI18n()
const { mode, setMode } = useThemeMode()
+ const { user } = useAuth()
const handleThemeChange = (event: SelectChangeEvent): void => {
setMode(event.target.value as ThemeMode)
@@ -54,51 +62,60 @@ export function Sidebar(): React.ReactElement {
{
key: 'dashboard',
path: '/dashboard',
- label: t('nav.dashboard') ?? '대시보드',
+ label: t('nav.dashboard'),
icon:
},
{
key: 'record',
path: '/record',
- label: t('nav.record') ?? '실시간 녹음',
+ label: t('nav.record'),
icon:
},
{
key: 'history',
path: '/history',
- label: t('nav.history') ?? '전사 히스토리',
+ label: t('nav.history'),
icon:
},
{
key: 'chat',
path: '/chat',
- label: t('nav.chat') ?? '음성 대화',
+ label: t('nav.chat'),
icon:
},
{
key: 'dictionary',
path: '/dictionary',
- label: t('nav.dictionary') ?? '커스텀 사전',
+ label: t('nav.dictionary'),
icon:
},
{
key: 'commands',
path: '/commands',
- label: t('nav.commands') ?? '명령어',
+ label: t('nav.commands'),
icon:
},
{
key: 'billing',
path: '/billing',
- label: t('nav.billing') ?? '구독 & 업그레이드',
+ label: t('nav.billing'),
icon:
}
]
async function handleLogout(): Promise {
const supabase = getSupabaseBrowserClient()
- await supabase.auth.signOut()
- router.replace('/login')
+ const cleanup = user
+ ? () => disableCurrentWebPush(user.id, { client: supabase })
+ : async () => undefined
+ try {
+ await signOutWithoutWaitingForWebPushCleanup(
+ cleanup,
+ () => supabase.auth.signOut(),
+ )
+ } finally {
+ router.replace('/login')
+ }
}
return (
@@ -139,7 +156,7 @@ export function Sidebar(): React.ReactElement {
- v1.16.1
+ v{WEB_APP_VERSION}
@@ -176,6 +193,8 @@ export function Sidebar(): React.ReactElement {
})}
+
+
- {t('theme.label') ?? 'Theme'}
+ {t('theme.label')}
@@ -208,7 +227,7 @@ export function Sidebar(): React.ReactElement {
diff --git a/apps/web/src/components/layout/web-push-control.tsx b/apps/web/src/components/layout/web-push-control.tsx
new file mode 100644
index 0000000..61ffdf3
--- /dev/null
+++ b/apps/web/src/components/layout/web-push-control.tsx
@@ -0,0 +1,209 @@
+'use client'
+
+import { useEffect, useState } from 'react'
+import NotificationsNoneIcon from '@mui/icons-material/NotificationsNone'
+import { Box, Switch } from '@mui/material'
+import { useI18n } from '@d3ro/i18n'
+import { d3roFocusRing, d3roPalette } from '@d3ro/ui/theme'
+import { useAuth } from '@/components/providers/auth-provider'
+import {
+ disableCurrentWebPush,
+ enableCurrentWebPush,
+ getCurrentWebPushConnectionStatus,
+ reconcileFailedWebPushEnable,
+ type WebPushConnectionStatus,
+} from '@/lib/web-push-session'
+
+type ControlStatus =
+ | WebPushConnectionStatus
+ | 'checking'
+ | 'enabling'
+ | 'disabling'
+ | 'error'
+
+const STATUS_MESSAGE_KEYS = {
+ checking: 'web.push.checking',
+ enabling: 'web.push.enabling',
+ disabling: 'web.push.disabling',
+ subscribed: 'web.push.enabled',
+ unsubscribed: 'web.push.disabled',
+ unsupported: 'web.push.unsupported',
+ unconfigured: 'web.push.unconfigured',
+ blocked: 'web.push.blocked',
+ orphaned: 'web.push.disabled',
+ revoked: 'web.push.revoked',
+ error: 'web.push.error',
+} as const
+
+function isBusy(status: ControlStatus): boolean {
+ return status === 'checking' || status === 'enabling' || status === 'disabling'
+}
+
+function isUnavailable(status: ControlStatus): boolean {
+ return status === 'unsupported'
+ || status === 'unconfigured'
+ || status === 'blocked'
+ || status === 'revoked'
+}
+
+export function WebPushControl(): React.ReactElement {
+ const { t } = useI18n()
+ const { user } = useAuth()
+ const [status, setStatus] = useState('checking')
+ const [enabled, setEnabled] = useState(false)
+ const userId = user?.id
+
+ useEffect(() => {
+ let active = true
+ if (!userId) {
+ setEnabled(false)
+ setStatus('checking')
+ return () => {
+ active = false
+ }
+ }
+
+ void getCurrentWebPushConnectionStatus(userId)
+ .then(async (nextStatus) => {
+ if (!active) return
+ if (nextStatus === 'orphaned' || nextStatus === 'revoked') {
+ try {
+ await disableCurrentWebPush(userId)
+ } catch {
+ if (active) setStatus('error')
+ return
+ }
+ }
+ if (!active) return
+ setEnabled(nextStatus === 'subscribed')
+ setStatus(nextStatus === 'orphaned' ? 'unsubscribed' : nextStatus)
+ })
+ .catch(() => {
+ if (active) setStatus('error')
+ })
+
+ return () => {
+ active = false
+ }
+ }, [userId])
+
+ async function handleToggle(shouldEnable: boolean): Promise {
+ if (!userId || isBusy(status) || isUnavailable(status)) return
+
+ if (shouldEnable) {
+ setStatus('enabling')
+ try {
+ await enableCurrentWebPush(userId)
+ setEnabled(true)
+ setStatus('subscribed')
+ } catch {
+ try {
+ const current = await getCurrentWebPushConnectionStatus(userId)
+ const reconciled = reconcileFailedWebPushEnable(current)
+ setEnabled(reconciled.enabled)
+ setStatus(reconciled.status)
+ } catch {
+ setEnabled(false)
+ setStatus('error')
+ }
+ }
+ return
+ }
+
+ setStatus('disabling')
+ try {
+ await disableCurrentWebPush(userId)
+ setEnabled(false)
+ setStatus('unsubscribed')
+ } catch {
+ try {
+ const current = await getCurrentWebPushConnectionStatus(userId)
+ setEnabled(current === 'subscribed')
+ } catch {
+ setEnabled(false)
+ }
+ setStatus('error')
+ }
+ }
+
+ const disabled = !userId || isBusy(status) || isUnavailable(status)
+ const isError = status === 'error' || status === 'revoked'
+
+ return (
+
+
+
+
+ {t('web.push.label')}
+
+
+ void handleToggle(checked)}
+ sx={{
+ width: 44,
+ height: 44,
+ p: '17px 9px',
+ '& .MuiSwitch-switchBase': {
+ top: 10,
+ left: 2,
+ },
+ '& .MuiSwitch-input': {
+ top: -10,
+ left: -2,
+ width: 44,
+ height: 44,
+ },
+ '& .MuiSwitch-switchBase.Mui-checked .MuiSwitch-input': {
+ transform: 'translateX(-16px)',
+ },
+ '& .MuiSwitch-switchBase.Mui-focusVisible': d3roFocusRing,
+ }}
+ slotProps={{
+ input: {
+ role: 'switch',
+ 'aria-labelledby': 'web-push-label',
+ 'aria-describedby': 'web-push-status',
+ },
+ }}
+ />
+
+
+
+ {t(STATUS_MESSAGE_KEYS[status])}
+
+
+ )
+}
diff --git a/apps/web/src/lib/web-device.ts b/apps/web/src/lib/web-device.ts
new file mode 100644
index 0000000..9bbedbc
--- /dev/null
+++ b/apps/web/src/lib/web-device.ts
@@ -0,0 +1,267 @@
+'use client'
+
+// apps/web/src/lib/web-device.ts
+// Browser installation identity + active Supabase device registration for Web Push.
+
+import { getSupabaseBrowserClient } from './supabase-browser'
+
+type WebDeviceClient = ReturnType
+type StorageAdapter = Pick
+
+export type WebDeviceErrorCode =
+ | 'auth'
+ | 'unsupported-browser'
+ | 'storage-unavailable'
+ | 'invalid-response'
+ | 'device-revoked'
+ | 'server'
+
+export class WebDeviceError extends Error {
+ constructor(
+ public readonly code: WebDeviceErrorCode,
+ message: string,
+ ) {
+ super(message)
+ this.name = 'WebDeviceError'
+ }
+}
+
+export interface WebDeviceRegistration {
+ id: string
+ installationId: string
+ revokedAt: string | null
+}
+
+export interface WebDeviceEnvironment {
+ client?: WebDeviceClient
+ storage?: StorageAdapter
+ uuidFactory?: () => string
+ now?: () => Date
+ deviceName?: string
+ osVersion?: string | null
+}
+
+const INSTALLATION_ID_KEY = 'd3ro.voice.web.installation-id.v1'
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+
+function requireUserId(userId: string): void {
+ if (!UUID_PATTERN.test(userId)) {
+ throw new WebDeviceError('auth', 'A valid authenticated user ID is required')
+ }
+}
+
+function requireStorage(override?: StorageAdapter): StorageAdapter {
+ if (override) return override
+ if (typeof window === 'undefined') {
+ throw new WebDeviceError('unsupported-browser', 'Browser storage is unavailable')
+ }
+ try {
+ return window.localStorage
+ } catch {
+ throw new WebDeviceError('storage-unavailable', 'Browser storage is unavailable')
+ }
+}
+
+function createInstallationId(override?: () => string): string {
+ const generated = override?.()
+ ?? (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
+ ? crypto.randomUUID()
+ : null)
+ if (!generated || !UUID_PATTERN.test(generated)) {
+ throw new WebDeviceError('unsupported-browser', 'Secure browser identity generation is unavailable')
+ }
+ return generated
+}
+
+export function getStoredWebInstallationId(storageOverride?: StorageAdapter): string | null {
+ const storage = requireStorage(storageOverride)
+ try {
+ const stored = storage.getItem(INSTALLATION_ID_KEY)
+ if (!stored) return null
+ if (UUID_PATTERN.test(stored)) return stored
+ storage.removeItem(INSTALLATION_ID_KEY)
+ return null
+ } catch {
+ throw new WebDeviceError('storage-unavailable', 'Browser storage is unavailable')
+ }
+}
+
+export function getOrCreateWebInstallationId(
+ storageOverride?: StorageAdapter,
+ uuidFactory?: () => string,
+): string {
+ const storage = requireStorage(storageOverride)
+ const existing = getStoredWebInstallationId(storage)
+ if (existing) return existing
+
+ const installationId = createInstallationId(uuidFactory)
+ try {
+ storage.setItem(INSTALLATION_ID_KEY, installationId)
+ } catch {
+ throw new WebDeviceError('storage-unavailable', 'Browser storage is unavailable')
+ }
+ return installationId
+}
+
+export function describeWebBrowserDevice(
+ userAgent: string,
+ platform: string,
+): { deviceName: string; osVersion: string | null } {
+ const browser = /Edg\//.test(userAgent)
+ ? 'Microsoft Edge'
+ : /Firefox\//.test(userAgent)
+ ? 'Firefox'
+ : /Chrome\//.test(userAgent)
+ ? 'Chrome'
+ : /Safari\//.test(userAgent)
+ ? 'Safari'
+ : 'Web browser'
+ const os = /Windows/.test(userAgent)
+ ? 'Windows'
+ : /Android/.test(userAgent)
+ ? 'Android'
+ : /iPhone|iPad|iPod/.test(userAgent)
+ ? 'iOS'
+ : /Macintosh|Mac OS/.test(userAgent)
+ ? 'macOS'
+ : /Linux/.test(userAgent)
+ ? 'Linux'
+ : platform.trim() || 'Web'
+ return {
+ deviceName: `${browser} · ${os}`.slice(0, 120),
+ osVersion: platform.trim().slice(0, 120) || null,
+ }
+}
+
+function defaultDeviceMetadata(): { deviceName: string; osVersion: string | null } {
+ if (typeof navigator === 'undefined') {
+ throw new WebDeviceError('unsupported-browser', 'Browser metadata is unavailable')
+ }
+ return describeWebBrowserDevice(navigator.userAgent, navigator.platform)
+}
+
+function parseDevice(
+ value: unknown,
+ installationId: string,
+): WebDeviceRegistration {
+ if (typeof value !== 'object' || value === null) {
+ throw new WebDeviceError('invalid-response', 'The device response is invalid')
+ }
+ const row = value as Record
+ if (
+ typeof row.id !== 'string'
+ || (row.revoked_at !== null && typeof row.revoked_at !== 'string')
+ ) {
+ throw new WebDeviceError('invalid-response', 'The device response is invalid')
+ }
+ return {
+ id: row.id,
+ installationId,
+ revokedAt: row.revoked_at,
+ }
+}
+
+async function readDevice(
+ client: WebDeviceClient,
+ userId: string,
+ installationId: string,
+): Promise {
+ const result = await client
+ .from('devices')
+ .select('id,revoked_at')
+ .eq('user_id', userId)
+ .eq('installation_id', installationId)
+ .maybeSingle()
+ if (result.error) {
+ throw new WebDeviceError('server', result.error.message)
+ }
+ return result.data ? parseDevice(result.data, installationId) : null
+}
+
+export async function findCurrentWebDevice(
+ userId: string,
+ environment: WebDeviceEnvironment = {},
+): Promise {
+ requireUserId(userId)
+ const installationId = getStoredWebInstallationId(environment.storage)
+ if (!installationId) return null
+ const client = environment.client ?? getSupabaseBrowserClient()
+ return readDevice(client, userId, installationId)
+}
+
+export async function ensureCurrentWebDevice(
+ userId: string,
+ appVersion: string,
+ environment: WebDeviceEnvironment = {},
+): Promise {
+ requireUserId(userId)
+ if (!appVersion.trim()) {
+ throw new WebDeviceError('invalid-response', 'A valid app version is required')
+ }
+
+ const client = environment.client ?? getSupabaseBrowserClient()
+ const installationId = getOrCreateWebInstallationId(
+ environment.storage,
+ environment.uuidFactory,
+ )
+ const metadata = environment.deviceName
+ ? {
+ deviceName: environment.deviceName.slice(0, 120),
+ osVersion: environment.osVersion?.slice(0, 120) ?? null,
+ }
+ : defaultDeviceMetadata()
+ const nowIso = (environment.now?.() ?? new Date()).toISOString()
+ const existing = await readDevice(client, userId, installationId)
+
+ if (existing?.revokedAt) {
+ throw new WebDeviceError('device-revoked', 'This browser registration has been revoked')
+ }
+ if (existing) {
+ const updated = await client
+ .from('devices')
+ .update({
+ device_name: metadata.deviceName,
+ app_version: appVersion.trim(),
+ os_version: metadata.osVersion,
+ last_seen_at: nowIso,
+ })
+ .eq('user_id', userId)
+ .eq('id', existing.id)
+ .is('revoked_at', null)
+ .select('id,revoked_at')
+ .maybeSingle()
+ if (updated.error) {
+ throw new WebDeviceError('server', updated.error.message)
+ }
+ if (!updated.data) {
+ throw new WebDeviceError('device-revoked', 'This browser registration is no longer active')
+ }
+ return parseDevice(updated.data, installationId)
+ }
+
+ const inserted = await client
+ .from('devices')
+ .insert({
+ user_id: userId,
+ installation_id: installationId,
+ platform: 'web',
+ device_name: metadata.deviceName,
+ app_version: appVersion.trim(),
+ os_version: metadata.osVersion,
+ last_seen_at: nowIso,
+ })
+ .select('id,revoked_at')
+ .single()
+
+ if (inserted.error) {
+ if (inserted.error.code === '23505') {
+ const concurrent = await readDevice(client, userId, installationId)
+ if (concurrent?.revokedAt) {
+ throw new WebDeviceError('device-revoked', 'This browser registration has been revoked')
+ }
+ if (concurrent) return concurrent
+ }
+ throw new WebDeviceError('server', inserted.error.message)
+ }
+ return parseDevice(inserted.data, installationId)
+}
diff --git a/apps/web/src/lib/web-push-session.ts b/apps/web/src/lib/web-push-session.ts
new file mode 100644
index 0000000..ece59c5
--- /dev/null
+++ b/apps/web/src/lib/web-push-session.ts
@@ -0,0 +1,195 @@
+'use client'
+
+// apps/web/src/lib/web-push-session.ts
+// One production orchestration boundary for browser device + Web Push state.
+
+import webPackage from '../../package.json'
+import {
+ ensureCurrentWebDevice,
+ findCurrentWebDevice,
+ type WebDeviceEnvironment,
+} from './web-device'
+import {
+ getWebPushBrowserStatus,
+ registerExistingWebPushSubscription,
+ requestWebPushPermission,
+ subscribeWebPush,
+ unsubscribeBrowserWebPush,
+ unregisterWebPushServer,
+ WebPushError,
+ type WebPushBrowserStatus,
+} from './web-push'
+
+export type WebPushConnectionStatus =
+ | WebPushBrowserStatus
+ | 'orphaned'
+ | 'revoked'
+
+export interface WebPushSessionEnvironment extends WebDeviceEnvironment {
+ vapidPublicKey?: string
+ registration?: ServiceWorkerRegistration | null
+ remoteCleanupTimeoutMs?: number
+}
+
+export const WEB_APP_VERSION = webPackage.version
+const DISABLED_INTENT_KEY_PREFIX = 'd3ro.voice.web-push.disabled.v1.'
+const DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS = 5_000
+
+export function reconcileFailedWebPushEnable(
+ currentStatus: WebPushConnectionStatus,
+): { enabled: boolean; status: WebPushConnectionStatus | 'error' } {
+ const enabled = currentStatus === 'subscribed'
+ return {
+ enabled,
+ status: enabled ? 'error' : currentStatus,
+ }
+}
+
+export async function signOutWithoutWaitingForWebPushCleanup(
+ cleanup: () => Promise,
+ signOut: () => Promise,
+): Promise {
+ try {
+ void cleanup().catch(() => undefined)
+ } catch {
+ // Cleanup is best effort. Logout remains independently available.
+ }
+ await signOut()
+}
+
+function withSessionCleanupTimeout(
+ operation: Promise,
+ timeoutMs: number,
+): Promise {
+ const boundedTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0
+ ? timeoutMs
+ : DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ reject(new WebPushError(
+ 'persistence-failed',
+ 'Timed out while resolving the server Web Push registration',
+ ))
+ }, boundedTimeoutMs)
+ operation.then(
+ (value) => {
+ clearTimeout(timer)
+ resolve(value)
+ },
+ (error: unknown) => {
+ clearTimeout(timer)
+ reject(error)
+ },
+ )
+ })
+}
+
+function disabledIntentKey(userId: string): string {
+ return `${DISABLED_INTENT_KEY_PREFIX}${userId}`
+}
+
+function sessionStorage(environment: WebPushSessionEnvironment): Pick {
+ if (environment.storage) return environment.storage
+ if (typeof window === 'undefined') {
+ throw new Error('Browser storage is unavailable')
+ }
+ return window.localStorage
+}
+
+function hasDisabledIntent(userId: string, environment: WebPushSessionEnvironment): boolean {
+ return sessionStorage(environment).getItem(disabledIntentKey(userId)) === '1'
+}
+
+function recordDisabledIntent(userId: string, environment: WebPushSessionEnvironment): void {
+ sessionStorage(environment).setItem(disabledIntentKey(userId), '1')
+}
+
+function clearDisabledIntent(userId: string, environment: WebPushSessionEnvironment): void {
+ sessionStorage(environment).removeItem(disabledIntentKey(userId))
+}
+
+export async function getCurrentWebPushConnectionStatus(
+ userId: string,
+ environment: WebPushSessionEnvironment = {},
+): Promise {
+ const browserStatus = await getWebPushBrowserStatus(
+ environment.vapidPublicKey,
+ undefined,
+ environment.registration,
+ )
+ if (browserStatus !== 'subscribed') return browserStatus
+ if (hasDisabledIntent(userId, environment)) return 'orphaned'
+
+ const device = await findCurrentWebDevice(userId, environment)
+ if (!device) return 'orphaned'
+ if (device.revokedAt) return 'revoked'
+
+ // A local PushSubscription is not proof that its server token still exists.
+ // Re-registering is idempotent and makes the server RPC the authority before
+ // the UI can report that Web Push is connected.
+ await registerExistingWebPushSubscription({
+ userId,
+ deviceId: device.id,
+ client: environment.client,
+ registration: environment.registration,
+ })
+ return 'subscribed'
+}
+
+export async function enableCurrentWebPush(
+ userId: string,
+ environment: WebPushSessionEnvironment = {},
+): Promise {
+ // Invoke the permission prompt before any network await so this call still
+ // carries the user's transient activation from the sidebar switch gesture.
+ await requestWebPushPermission(environment.vapidPublicKey)
+ const device = await ensureCurrentWebDevice(userId, WEB_APP_VERSION, environment)
+ await subscribeWebPush({
+ userId,
+ deviceId: device.id,
+ vapidPublicKey: environment.vapidPublicKey,
+ client: environment.client,
+ registration: environment.registration ?? undefined,
+ })
+ clearDisabledIntent(userId, environment)
+}
+
+export async function disableCurrentWebPush(
+ userId: string,
+ environment: WebPushSessionEnvironment = {},
+): Promise {
+ let intentFailure: unknown
+ try {
+ // Record intent before either remote or local cleanup. If local unsubscribe
+ // fails, the next load stays fail-closed and retries cleanup instead of
+ // treating the stale browser subscription as connected.
+ recordDisabledIntent(userId, environment)
+ } catch (error) {
+ intentFailure = error
+ }
+
+ const browserCleanup = unsubscribeBrowserWebPush({
+ registration: environment.registration,
+ })
+ const remoteCleanupOperation = (async () => {
+ const device = await findCurrentWebDevice(userId, environment)
+ if (!device) return false
+ return unregisterWebPushServer({
+ deviceId: device.id,
+ client: environment.client,
+ timeoutMs: environment.remoteCleanupTimeoutMs,
+ })
+ })()
+ const remoteCleanup = withSessionCleanupTimeout(
+ remoteCleanupOperation,
+ environment.remoteCleanupTimeoutMs ?? DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS,
+ )
+ const [browserResult, remoteResult] = await Promise.allSettled([
+ browserCleanup,
+ remoteCleanup,
+ ])
+
+ if (browserResult.status === 'rejected') throw browserResult.reason
+ if (remoteResult.status === 'rejected') throw remoteResult.reason
+ if (intentFailure) throw intentFailure
+}
diff --git a/apps/web/src/lib/web-push.ts b/apps/web/src/lib/web-push.ts
index 43717ef..afdefde 100644
--- a/apps/web/src/lib/web-push.ts
+++ b/apps/web/src/lib/web-push.ts
@@ -1,9 +1,10 @@
// apps/web/src/lib/web-push.ts
// D3RO Voice — Web Push Service Worker Registration & VAPID Subscription
-import type { SupabaseClient } from '@supabase/supabase-js'
import { getSupabaseBrowserClient } from './supabase-browser'
+type WebPushClient = ReturnType
+
export type WebPushProvider = 'webpush'
export type WebPushErrorCode =
@@ -13,6 +14,7 @@ export type WebPushErrorCode =
| 'vapid-key-missing'
| 'invalid-vapid-key'
| 'subscription-failed'
+ | 'unsubscribe-failed'
| 'persistence-failed'
export class WebPushError extends Error {
@@ -34,16 +36,60 @@ export interface WebPushSubscriptionRecord {
export interface SubscribeWebPushOptions {
userId: string
- deviceId?: string
+ deviceId: string
vapidPublicKey?: string
serviceWorkerPath?: string
serviceWorkerScope?: string
- client?: SupabaseClient
+ client?: WebPushClient
+ registration?: ServiceWorkerRegistration
}
+export interface UnsubscribeWebPushOptions {
+ deviceId?: string
+ serviceWorkerScope?: string
+ client?: WebPushClient
+ registration?: ServiceWorkerRegistration | null
+ remoteTimeoutMs?: number
+}
+
+export interface UnsubscribeBrowserWebPushOptions {
+ serviceWorkerScope?: string
+ registration?: ServiceWorkerRegistration | null
+}
+
+export interface UnregisterWebPushServerOptions {
+ deviceId: string
+ client?: WebPushClient
+ timeoutMs?: number
+}
+
+export interface RegisterExistingWebPushOptions {
+ userId: string
+ deviceId: string
+ serviceWorkerScope?: string
+ client?: WebPushClient
+ registration?: ServiceWorkerRegistration | null
+}
+
+export type WebPushBrowserStatus =
+ | 'unsupported'
+ | 'unconfigured'
+ | 'blocked'
+ | 'unsubscribed'
+ | 'subscribed'
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const DEFAULT_SW_PATH = '/app/sw.js'
const DEFAULT_SW_SCOPE = '/app/'
+const DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS = 5_000
+
+function browserSupportsWebPush(): boolean {
+ return typeof window !== 'undefined'
+ && typeof navigator !== 'undefined'
+ && typeof Notification !== 'undefined'
+ && 'serviceWorker' in navigator
+ && 'PushManager' in window
+}
export function getVapidPublicKey(overrideKey?: string): string | null {
const candidate = (overrideKey ?? process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY ?? '').trim()
@@ -74,22 +120,96 @@ export async function registerWebPushServiceWorker(
if (
typeof window === 'undefined'
|| typeof navigator === 'undefined'
- || !('serviceWorker' in navigator)
- || !('PushManager' in window)
+ || !browserSupportsWebPush()
) {
throw new WebPushError('unsupported-browser', 'Web Push is not supported in this browser')
}
return navigator.serviceWorker.register(serviceWorkerPath, { scope })
}
+export async function getWebPushBrowserStatus(
+ vapidPublicKey?: string,
+ serviceWorkerScope = DEFAULT_SW_SCOPE,
+ registrationOverride?: ServiceWorkerRegistration | null,
+): Promise {
+ if (!browserSupportsWebPush()) return 'unsupported'
+ if (!getVapidPublicKey(vapidPublicKey)) return 'unconfigured'
+ if (Notification.permission === 'denied') return 'blocked'
+
+ const registration = registrationOverride !== undefined
+ ? registrationOverride
+ : await navigator.serviceWorker.getRegistration(serviceWorkerScope)
+ if (!registration) return 'unsubscribed'
+ const subscription = await registration.pushManager.getSubscription()
+ return subscription ? 'subscribed' : 'unsubscribed'
+}
+
+async function persistWebPushSubscription(
+ subscription: PushSubscription,
+ deviceId: string,
+ client?: WebPushClient,
+): Promise {
+ const serialized = JSON.stringify(subscription.toJSON())
+ const supabase = client ?? getSupabaseBrowserClient()
+ const nowIso = new Date().toISOString()
+ let result: Awaited>
+ try {
+ result = await supabase.rpc('register_push_registration', {
+ push_device_id: deviceId,
+ push_provider: 'webpush',
+ registration_id: serialized,
+ })
+ } catch (error) {
+ throw new WebPushError(
+ 'persistence-failed',
+ error instanceof Error ? error.message : 'Failed to persist the Web Push registration',
+ )
+ }
+ if (result.error) {
+ throw new WebPushError('persistence-failed', result.error.message)
+ }
+
+ const record = typeof result.data === 'object' && result.data !== null
+ ? (result.data as Record)
+ : null
+ const registeredAt = typeof record?.registered_at === 'string'
+ ? record.registered_at
+ : nowIso
+
+ return {
+ provider: 'webpush',
+ endpoint: subscription.endpoint,
+ subscriptionJson: serialized,
+ registeredAt,
+ }
+}
+
+export async function requestWebPushPermission(vapidPublicKey?: string): Promise {
+ if (!browserSupportsWebPush()) {
+ throw new WebPushError('unsupported-browser', 'Web Push is not supported in this browser')
+ }
+ if (!getVapidPublicKey(vapidPublicKey)) {
+ throw new WebPushError('vapid-key-missing', 'NEXT_PUBLIC_VAPID_PUBLIC_KEY is not configured')
+ }
+ if (Notification.permission === 'denied') {
+ throw new WebPushError('permission-denied', 'Notification permission has been denied')
+ }
+ if (Notification.permission === 'default') {
+ const permission = await Notification.requestPermission()
+ if (permission !== 'granted') {
+ throw new WebPushError('permission-denied', 'Notification permission was not granted')
+ }
+ }
+}
+
export async function subscribeWebPush(
options: SubscribeWebPushOptions,
): Promise {
if (!UUID_PATTERN.test(options.userId)) {
throw new WebPushError('auth', 'A valid authenticated user ID is required for Web Push')
}
- if (options.deviceId !== undefined && !UUID_PATTERN.test(options.deviceId)) {
- throw new WebPushError('auth', 'A valid device ID is required when binding Web Push to a device')
+ if (!UUID_PATTERN.test(options.deviceId)) {
+ throw new WebPushError('auth', 'A valid active device ID is required for Web Push')
}
const vapidPublicKey = getVapidPublicKey(options.vapidPublicKey)
@@ -103,7 +223,7 @@ export async function subscribeWebPush(
throw new WebPushError('permission-denied', 'Notification permission has been denied')
}
- const registration = await registerWebPushServiceWorker(
+ const registration = options.registration ?? await registerWebPushServiceWorker(
options.serviceWorkerPath ?? DEFAULT_SW_PATH,
options.serviceWorkerScope ?? DEFAULT_SW_SCOPE,
)
@@ -122,54 +242,163 @@ export async function subscribeWebPush(
)
}
- const serialized = JSON.stringify(subscription.toJSON())
- const supabase = options.client ?? getSupabaseBrowserClient()
- const nowIso = new Date().toISOString()
-
- if (options.deviceId) {
- const { data, error } = await supabase.rpc('register_push_registration', {
- push_device_id: options.deviceId,
- push_provider: 'webpush',
- registration_id: serialized,
- })
- if (error) {
- throw new WebPushError('persistence-failed', error.message)
+ try {
+ return await persistWebPushSubscription(subscription, options.deviceId, options.client)
+ } catch (error) {
+ try {
+ await subscription.unsubscribe()
+ } catch {
+ // The persistence failure remains authoritative. A later disable/logout
+ // path retries local cleanup before the session is closed.
}
- const record = typeof data === 'object' && data !== null
- ? (data as Record)
- : null
- const registeredAt = typeof record?.registered_at === 'string'
- ? record.registered_at
- : nowIso
- return {
- provider: 'webpush',
- endpoint: subscription.endpoint,
- subscriptionJson: serialized,
- registeredAt,
- }
- }
-
- const { error } = await supabase
- .from('push_tokens')
- .upsert(
- {
- user_id: options.userId,
- token: serialized,
- platform: 'web',
- provider: 'webpush',
- updated_at: nowIso,
- },
- { onConflict: 'user_id,token' },
- )
-
- if (error) {
- throw new WebPushError('persistence-failed', error.message)
- }
-
- return {
- provider: 'webpush',
- endpoint: subscription.endpoint,
- subscriptionJson: serialized,
- registeredAt: nowIso,
+ throw error
+ }
+}
+
+export async function registerExistingWebPushSubscription(
+ options: RegisterExistingWebPushOptions,
+): Promise {
+ if (!UUID_PATTERN.test(options.userId)) {
+ throw new WebPushError('auth', 'A valid authenticated user ID is required for Web Push')
+ }
+ if (!UUID_PATTERN.test(options.deviceId)) {
+ throw new WebPushError('auth', 'A valid active device ID is required for Web Push')
+ }
+
+ let subscription: PushSubscription | null
+ try {
+ const registration = options.registration !== undefined
+ ? options.registration
+ : browserSupportsWebPush()
+ ? await navigator.serviceWorker.getRegistration(
+ options.serviceWorkerScope ?? DEFAULT_SW_SCOPE,
+ )
+ : null
+ subscription = await registration?.pushManager.getSubscription() ?? null
+ } catch (error) {
+ throw new WebPushError(
+ 'subscription-failed',
+ error instanceof Error ? error.message : 'Failed to read the browser Push subscription',
+ )
+ }
+ if (!subscription) {
+ throw new WebPushError('subscription-failed', 'The browser Push subscription is unavailable')
+ }
+
+ return persistWebPushSubscription(subscription, options.deviceId, options.client)
+}
+
+function withRemoteCleanupTimeout(operation: PromiseLike, timeoutMs: number): Promise {
+ const boundedTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0
+ ? timeoutMs
+ : DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ reject(new WebPushError(
+ 'persistence-failed',
+ 'Timed out while removing the server Web Push registration',
+ ))
+ }, boundedTimeoutMs)
+ operation.then(
+ (value) => {
+ clearTimeout(timer)
+ resolve(value)
+ },
+ (error: unknown) => {
+ clearTimeout(timer)
+ reject(error)
+ },
+ )
+ })
+}
+
+export async function unregisterWebPushServer(
+ options: UnregisterWebPushServerOptions,
+): Promise {
+ if (!UUID_PATTERN.test(options.deviceId)) {
+ throw new WebPushError('auth', 'A valid active device ID is required for Web Push')
+ }
+
+ const supabase = options.client ?? getSupabaseBrowserClient()
+ let result: Awaited>
+ try {
+ result = await withRemoteCleanupTimeout(
+ supabase.rpc('unregister_push_registration', {
+ push_device_id: options.deviceId,
+ }),
+ options.timeoutMs ?? DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS,
+ )
+ } catch (error) {
+ if (error instanceof WebPushError) throw error
+ throw new WebPushError(
+ 'persistence-failed',
+ error instanceof Error ? error.message : 'Failed to remove the server Web Push registration',
+ )
+ }
+ if (result.error) {
+ throw new WebPushError('persistence-failed', result.error.message)
+ }
+ if (
+ typeof result.data === 'object'
+ && result.data !== null
+ && 'removed' in result.data
+ && typeof result.data.removed === 'boolean'
+ ) {
+ return result.data.removed
+ }
+ return false
+}
+
+export async function unsubscribeBrowserWebPush(
+ options: UnsubscribeBrowserWebPushOptions = {},
+): Promise {
+ try {
+ const registration = options.registration !== undefined
+ ? options.registration
+ : browserSupportsWebPush()
+ ? await navigator.serviceWorker.getRegistration(
+ options.serviceWorkerScope ?? DEFAULT_SW_SCOPE,
+ )
+ : null
+ const subscription = await registration?.pushManager.getSubscription()
+ return subscription ? await subscription.unsubscribe() : false
+ } catch (error) {
+ throw new WebPushError(
+ 'unsubscribe-failed',
+ error instanceof Error ? error.message : 'Failed to remove the browser Push subscription',
+ )
+ }
+}
+
+export async function unsubscribeWebPush(
+ options: UnsubscribeWebPushOptions,
+): Promise<{ browserSubscriptionRemoved: boolean; serverRegistrationRemoved: boolean }> {
+ if (options.deviceId && !UUID_PATTERN.test(options.deviceId)) {
+ throw new WebPushError('auth', 'A valid active device ID is required for Web Push')
+ }
+
+ // Start both operations before awaiting either one. A hung remote RPC must
+ // never prevent the browser from removing its local PushSubscription.
+ const serverCleanup = options.deviceId
+ ? unregisterWebPushServer({
+ deviceId: options.deviceId,
+ client: options.client,
+ timeoutMs: options.remoteTimeoutMs,
+ })
+ : Promise.resolve(false)
+ const browserCleanup = unsubscribeBrowserWebPush({
+ registration: options.registration,
+ serviceWorkerScope: options.serviceWorkerScope,
+ })
+ const [serverResult, browserResult] = await Promise.allSettled([
+ serverCleanup,
+ browserCleanup,
+ ])
+
+ if (browserResult.status === 'rejected') throw browserResult.reason
+ if (serverResult.status === 'rejected') throw serverResult.reason
+ return {
+ browserSubscriptionRemoved: browserResult.value,
+ serverRegistrationRemoved: serverResult.value,
}
}
diff --git a/apps/web/e2e/billing-catalog.spec.ts b/apps/web/tests/billing-catalog.test.ts
similarity index 95%
rename from apps/web/e2e/billing-catalog.spec.ts
rename to apps/web/tests/billing-catalog.test.ts
index afcd705..ff3828f 100644
--- a/apps/web/e2e/billing-catalog.spec.ts
+++ b/apps/web/tests/billing-catalog.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from '@playwright/test'
+import { describe, expect, test } from 'vitest'
import {
formatBillingPrice,
formatPlanCatalogPrice,
@@ -23,7 +23,7 @@ const catalogPayload = {
],
}
-test.describe('billing catalog strict client contract', () => {
+describe('billing catalog strict client contract', () => {
test('parses provider prices and formats minor currency units', () => {
const catalog = parseBillingCatalog(catalogPayload)
expect(catalog).not.toBeNull()
diff --git a/apps/web/tests/web-push.test.ts b/apps/web/tests/web-push.test.ts
new file mode 100644
index 0000000..af6c1a5
--- /dev/null
+++ b/apps/web/tests/web-push.test.ts
@@ -0,0 +1,504 @@
+import { describe, expect, test } from 'vitest'
+import type { getSupabaseBrowserClient } from '../src/lib/supabase-browser'
+import {
+ describeWebBrowserDevice,
+ ensureCurrentWebDevice,
+ getOrCreateWebInstallationId,
+ getStoredWebInstallationId,
+} from '../src/lib/web-device'
+import {
+ requestWebPushPermission,
+ subscribeWebPush,
+ unsubscribeWebPush,
+} from '../src/lib/web-push'
+import {
+ disableCurrentWebPush,
+ getCurrentWebPushConnectionStatus,
+ reconcileFailedWebPushEnable,
+ signOutWithoutWaitingForWebPushCleanup,
+} from '../src/lib/web-push-session'
+
+type WebClient = ReturnType
+
+const USER_ID = '00000000-0000-4000-8000-000000000001'
+const DEVICE_ID = '00000000-0000-4000-8000-000000000002'
+const VAPID_KEY = 'AQIDBAUGBwgJCgsMDQ4PEA'
+
+function installPushBrowser(
+ permission: NotificationPermission,
+ requestPermission: () => Promise,
+): () => void {
+ const keys = ['window', 'navigator', 'Notification'] as const
+ const originals = new Map(keys.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]))
+
+ Object.defineProperty(globalThis, 'window', {
+ configurable: true,
+ value: { PushManager: class TestPushManager {} },
+ })
+ Object.defineProperty(globalThis, 'navigator', {
+ configurable: true,
+ value: { serviceWorker: {} },
+ })
+ Object.defineProperty(globalThis, 'Notification', {
+ configurable: true,
+ value: { permission, requestPermission },
+ })
+
+ return () => {
+ for (const key of keys) {
+ const descriptor = originals.get(key)
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor)
+ else Reflect.deleteProperty(globalThis, key)
+ }
+ }
+}
+
+function memoryStorage(initial?: Record): Storage {
+ const values = new Map(Object.entries(initial ?? {}))
+ return {
+ get length() {
+ return values.size
+ },
+ clear: () => values.clear(),
+ getItem: (key) => values.get(key) ?? null,
+ key: (index) => [...values.keys()][index] ?? null,
+ removeItem: (key) => {
+ values.delete(key)
+ },
+ setItem: (key, value) => {
+ values.set(key, value)
+ },
+ }
+}
+
+function pushSubscription(
+ onUnsubscribe?: () => void,
+ unsubscribeError?: Error,
+): PushSubscription {
+ return {
+ endpoint: 'https://push.example/subscription/1',
+ expirationTime: null,
+ options: {
+ applicationServerKey: null,
+ userVisibleOnly: true,
+ },
+ getKey: () => null,
+ toJSON: () => ({
+ endpoint: 'https://push.example/subscription/1',
+ keys: { auth: 'auth-key', p256dh: 'p256dh-key' },
+ }),
+ unsubscribe: async () => {
+ onUnsubscribe?.()
+ if (unsubscribeError) throw unsubscribeError
+ return true
+ },
+ }
+}
+
+function activeDeviceClient(
+ rpc: (name: string, args: unknown) => Promise<{ data: unknown; error: { message: string } | null }>,
+): WebClient {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ maybeSingle: async () => ({
+ data: { id: DEVICE_ID, revoked_at: null },
+ error: null,
+ }),
+ }
+ return {
+ from: () => chain,
+ rpc,
+ } as unknown as WebClient
+}
+
+function registration(
+ subscription: PushSubscription | null,
+ onSubscribe?: () => void,
+): ServiceWorkerRegistration {
+ return {
+ pushManager: {
+ getSubscription: async () => subscription,
+ permissionState: async () => 'granted',
+ subscribe: async () => {
+ onSubscribe?.()
+ if (!subscription) throw new Error('test registration requires a subscription')
+ return subscription
+ },
+ },
+ } as ServiceWorkerRegistration
+}
+
+describe('web push client contract', () => {
+ test('requests permission only after confirming the public VAPID key exists', async () => {
+ let permissionRequests = 0
+ const restore = installPushBrowser('default', async () => {
+ permissionRequests += 1
+ return 'granted'
+ })
+ try {
+ await expect(requestWebPushPermission('')).rejects.toMatchObject({
+ code: 'vapid-key-missing',
+ })
+ expect(permissionRequests).toBe(0)
+
+ await expect(requestWebPushPermission(VAPID_KEY)).resolves.toBeUndefined()
+ expect(permissionRequests).toBe(1)
+ } finally {
+ restore()
+ }
+ })
+
+ test('keeps one valid browser installation ID and replaces invalid stored data', () => {
+ const storage = memoryStorage({
+ 'd3ro.voice.web.installation-id.v1': 'invalid',
+ })
+ expect(getStoredWebInstallationId(storage)).toBeNull()
+
+ const installationId = getOrCreateWebInstallationId(storage, () => DEVICE_ID)
+ expect(installationId).toBe(DEVICE_ID)
+ expect(getOrCreateWebInstallationId(storage, () => USER_ID)).toBe(DEVICE_ID)
+ })
+
+ test('derives bounded browser device metadata without persisting the full user agent', () => {
+ expect(describeWebBrowserDevice(
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/130.0 Safari/537.36',
+ 'Win32',
+ )).toEqual({ deviceName: 'Chrome · Windows', osVersion: 'Win32' })
+ })
+
+ test('creates a web device with the stable installation ID before push registration', async () => {
+ const inserts: unknown[] = []
+ const readChain = {
+ select: () => readChain,
+ eq: () => readChain,
+ maybeSingle: async () => ({ data: null, error: null }),
+ }
+ const client = {
+ from: () => ({
+ ...readChain,
+ insert: (value: unknown) => {
+ inserts.push(value)
+ return {
+ select: () => ({
+ single: async () => ({
+ data: { id: DEVICE_ID, revoked_at: null },
+ error: null,
+ }),
+ }),
+ }
+ },
+ }),
+ } as unknown as WebClient
+
+ await expect(ensureCurrentWebDevice(USER_ID, '1.16.1', {
+ client,
+ storage: memoryStorage(),
+ uuidFactory: () => DEVICE_ID,
+ now: () => new Date('2026-11-04T00:00:00.000Z'),
+ deviceName: 'Chrome · Windows',
+ osVersion: 'Win32',
+ })).resolves.toEqual({
+ id: DEVICE_ID,
+ installationId: DEVICE_ID,
+ revokedAt: null,
+ })
+ expect(inserts).toEqual([{
+ user_id: USER_ID,
+ installation_id: DEVICE_ID,
+ platform: 'web',
+ device_name: 'Chrome · Windows',
+ app_version: '1.16.1',
+ os_version: 'Win32',
+ last_seen_at: '2026-11-04T00:00:00.000Z',
+ }])
+ })
+
+ test('never resurrects a revoked browser device', async () => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ maybeSingle: async () => ({
+ data: { id: DEVICE_ID, revoked_at: '2026-11-03T00:00:00.000Z' },
+ error: null,
+ }),
+ }
+ const client = {
+ from: () => chain,
+ } as unknown as WebClient
+
+ await expect(ensureCurrentWebDevice(USER_ID, '1.16.1', {
+ client,
+ storage: memoryStorage({
+ 'd3ro.voice.web.installation-id.v1': DEVICE_ID,
+ }),
+ deviceName: 'Chrome · Windows',
+ })).rejects.toMatchObject({ code: 'device-revoked' })
+ })
+
+ test('subscribes only once and persists through the device-bound RPC', async () => {
+ const calls: Array<{ name: string; args: unknown }> = []
+ const subscription = pushSubscription()
+ const client = {
+ rpc: async (name: string, args: unknown) => {
+ calls.push({ name, args })
+ return {
+ data: {
+ device_id: DEVICE_ID,
+ provider: 'webpush',
+ registered_at: '2026-11-04T00:00:00.000Z',
+ },
+ error: null,
+ }
+ },
+ } as unknown as WebClient
+
+ const result = await subscribeWebPush({
+ userId: USER_ID,
+ deviceId: DEVICE_ID,
+ vapidPublicKey: VAPID_KEY,
+ client,
+ registration: registration(subscription),
+ })
+
+ expect(calls).toEqual([{
+ name: 'register_push_registration',
+ args: {
+ push_device_id: DEVICE_ID,
+ push_provider: 'webpush',
+ registration_id: JSON.stringify(subscription.toJSON()),
+ },
+ }])
+ expect(result).toMatchObject({
+ provider: 'webpush',
+ endpoint: subscription.endpoint,
+ registeredAt: '2026-11-04T00:00:00.000Z',
+ })
+ })
+
+ test('rolls back the browser subscription when persistence fails', async () => {
+ let unsubscribeCalls = 0
+ const subscription = pushSubscription(() => {
+ unsubscribeCalls += 1
+ })
+ const client = {
+ rpc: async () => ({ data: null, error: { message: 'database unavailable' } }),
+ } as unknown as WebClient
+
+ await expect(subscribeWebPush({
+ userId: USER_ID,
+ deviceId: DEVICE_ID,
+ vapidPublicKey: VAPID_KEY,
+ client,
+ registration: registration(subscription),
+ })).rejects.toMatchObject({ code: 'persistence-failed' })
+ expect(unsubscribeCalls).toBe(1)
+ })
+
+ test('removes the server registration and browser subscription together', async () => {
+ let unsubscribeCalls = 0
+ const client = {
+ rpc: async () => ({
+ data: { device_id: DEVICE_ID, removed: true },
+ error: null,
+ }),
+ } as unknown as WebClient
+
+ await expect(unsubscribeWebPush({
+ deviceId: DEVICE_ID,
+ client,
+ registration: registration(pushSubscription(() => {
+ unsubscribeCalls += 1
+ })),
+ })).resolves.toEqual({
+ browserSubscriptionRemoved: true,
+ serverRegistrationRemoved: true,
+ })
+ expect(unsubscribeCalls).toBe(1)
+ })
+
+ test('still removes the browser subscription when server cleanup fails', async () => {
+ let unsubscribeCalls = 0
+ const client = {
+ rpc: async () => ({ data: null, error: { message: 'offline' } }),
+ } as unknown as WebClient
+
+ const operation = unsubscribeWebPush({
+ deviceId: DEVICE_ID,
+ client,
+ registration: registration(pushSubscription(() => {
+ unsubscribeCalls += 1
+ })),
+ })
+ await expect(operation).rejects.toMatchObject({
+ name: 'WebPushError',
+ code: 'persistence-failed',
+ })
+ expect(unsubscribeCalls).toBe(1)
+ })
+
+ test('removes the local subscription and bounds a hung unregister RPC', async () => {
+ let unsubscribeCalls = 0
+ const client = {
+ rpc: () => new Promise(() => undefined),
+ } as unknown as WebClient
+
+ await expect(unsubscribeWebPush({
+ deviceId: DEVICE_ID,
+ client,
+ registration: registration(pushSubscription(() => {
+ unsubscribeCalls += 1
+ })),
+ remoteTimeoutMs: 25,
+ })).rejects.toMatchObject({ code: 'persistence-failed' })
+ expect(unsubscribeCalls).toBe(1)
+ })
+
+ test('keeps disabled intent when server cleanup succeeds but local unsubscribe fails', async () => {
+ const storage = memoryStorage({
+ 'd3ro.voice.web.installation-id.v1': DEVICE_ID,
+ })
+ const client = activeDeviceClient(async () => ({
+ data: { device_id: DEVICE_ID, removed: true },
+ error: null,
+ }))
+
+ await expect(disableCurrentWebPush(USER_ID, {
+ client,
+ storage,
+ registration: registration(pushSubscription(
+ undefined,
+ new Error('browser unsubscribe failed'),
+ )),
+ })).rejects.toMatchObject({ code: 'unsubscribe-failed' })
+
+ expect(storage.getItem(`d3ro.voice.web-push.disabled.v1.${USER_ID}`)).toBe('1')
+ })
+
+ test('starts local cleanup even when the device lookup never resolves', async () => {
+ let unsubscribeCalls = 0
+ const stalledChain = {
+ select: () => stalledChain,
+ eq: () => stalledChain,
+ maybeSingle: () => new Promise(() => undefined),
+ }
+ const client = {
+ from: () => stalledChain,
+ } as unknown as WebClient
+
+ await expect(disableCurrentWebPush(USER_ID, {
+ client,
+ storage: memoryStorage({
+ 'd3ro.voice.web.installation-id.v1': DEVICE_ID,
+ }),
+ registration: registration(pushSubscription(() => {
+ unsubscribeCalls += 1
+ })),
+ remoteCleanupTimeoutMs: 25,
+ })).rejects.toMatchObject({ code: 'persistence-failed' })
+ expect(unsubscribeCalls).toBe(1)
+ })
+
+ test('does not report a stale local subscription as connected after disable intent', async () => {
+ let rpcCalls = 0
+ const restore = installPushBrowser('granted', async () => 'granted')
+ try {
+ const storage = memoryStorage({
+ 'd3ro.voice.web.installation-id.v1': DEVICE_ID,
+ [`d3ro.voice.web-push.disabled.v1.${USER_ID}`]: '1',
+ })
+ const client = activeDeviceClient(async () => {
+ rpcCalls += 1
+ return { data: null, error: null }
+ })
+
+ await expect(getCurrentWebPushConnectionStatus(USER_ID, {
+ client,
+ storage,
+ vapidPublicKey: VAPID_KEY,
+ registration: registration(pushSubscription()),
+ })).resolves.toBe('orphaned')
+ expect(rpcCalls).toBe(0)
+ } finally {
+ restore()
+ }
+ })
+
+ test('re-registers an existing browser subscription before reporting it connected', async () => {
+ const calls: Array<{ name: string; args: unknown }> = []
+ const restore = installPushBrowser('granted', async () => 'granted')
+ try {
+ const subscription = pushSubscription()
+ const client = activeDeviceClient(async (name, args) => {
+ calls.push({ name, args })
+ return {
+ data: { registered_at: '2026-11-04T00:00:00.000Z' },
+ error: null,
+ }
+ })
+
+ await expect(getCurrentWebPushConnectionStatus(USER_ID, {
+ client,
+ storage: memoryStorage({
+ 'd3ro.voice.web.installation-id.v1': DEVICE_ID,
+ }),
+ vapidPublicKey: VAPID_KEY,
+ registration: registration(subscription),
+ })).resolves.toBe('subscribed')
+ expect(calls).toEqual([{
+ name: 'register_push_registration',
+ args: {
+ push_device_id: DEVICE_ID,
+ push_provider: 'webpush',
+ registration_id: JSON.stringify(subscription.toJSON()),
+ },
+ }])
+ } finally {
+ restore()
+ }
+ })
+
+ test('fails closed when an existing browser subscription cannot be re-registered', async () => {
+ const restore = installPushBrowser('granted', async () => 'granted')
+ try {
+ const client = activeDeviceClient(async () => ({
+ data: null,
+ error: { message: 'database unavailable' },
+ }))
+ await expect(getCurrentWebPushConnectionStatus(USER_ID, {
+ client,
+ storage: memoryStorage({
+ 'd3ro.voice.web.installation-id.v1': DEVICE_ID,
+ }),
+ vapidPublicKey: VAPID_KEY,
+ registration: registration(pushSubscription()),
+ })).rejects.toMatchObject({ code: 'persistence-failed' })
+ } finally {
+ restore()
+ }
+ })
+
+ test('keeps the switch checked when failed enable reconciliation finds a live registration', () => {
+ expect(reconcileFailedWebPushEnable('subscribed')).toEqual({
+ enabled: true,
+ status: 'error',
+ })
+ expect(reconcileFailedWebPushEnable('unsubscribed')).toEqual({
+ enabled: false,
+ status: 'unsubscribed',
+ })
+ })
+
+ test('does not make sign-out wait for stalled Web Push cleanup', async () => {
+ let signOutCalls = 0
+ const stalledCleanup = new Promise(() => undefined)
+
+ await expect(signOutWithoutWaitingForWebPushCleanup(
+ () => stalledCleanup,
+ async () => {
+ signOutCalls += 1
+ },
+ )).resolves.toBeUndefined()
+ expect(signOutCalls).toBe(1)
+ })
+})
diff --git a/apps/web/e2e/web-stt-client.spec.ts b/apps/web/tests/web-stt-client.test.ts
similarity index 97%
rename from apps/web/e2e/web-stt-client.spec.ts
rename to apps/web/tests/web-stt-client.test.ts
index 9e5823d..355da58 100644
--- a/apps/web/e2e/web-stt-client.spec.ts
+++ b/apps/web/tests/web-stt-client.test.ts
@@ -1,9 +1,9 @@
-import { expect, test } from '@playwright/test'
+import { describe, expect, test } from 'vitest'
import { transcribeWebAudio, WebSttError } from '../src/lib/web-stt-client'
const audio = new Blob([new Uint8Array([0x1a, 0x45, 0xdf, 0xa3])], { type: 'audio/webm;codecs=opus' })
-test.describe('web STT fail-closed client', () => {
+describe('web STT fail-closed client', () => {
test('sends one authenticated request and accepts only a strict real transcript', async () => {
let calls = 0
const result = await transcribeWebAudio({
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
new file mode 100644
index 0000000..49eb115
--- /dev/null
+++ b/apps/web/vitest.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ globals: false,
+ environment: 'node',
+ include: ['tests/**/*.test.ts'],
+ exclude: ['e2e/**'],
+ testTimeout: 10000,
+ },
+})
diff --git a/design.md b/design.md
index d5d189f..eefa424 100644
--- a/design.md
+++ b/design.md
@@ -378,3 +378,4 @@
- **검증 증거**:
- `npm run check:design` (`design-token violations: 0`), `npm run check:desktop-renderer` (`7 page(s) with all assets on disk`), `npm run typecheck` 및 `npm --prefix apps/mobile-rn run typecheck`/`lint` 전부 0 에러.
- Playwright 헤드리스 Chromium(`scratch/browser-design-gate.mjs`) 실측: `site` 14개 경로(`ko`/`en`/`ja`/`zh`/`es`/`fr`/`de`/`pt`/`ru`/`vi` 홈 + `privacy`/`terms`/`delete-account`/`accept-invite`) + `desktop` 메인·설정 16개 경로(`home`, `records`, `meetings`, `conversation`, `commands`, `dictionary`, `knowledge`, `search`, `settings` 8탭) + `desktop` 팝업 6종(`recording-tip`, `result-popup`, `command-popup`, `history-popup`, `caption-overlay`, `suggestion-overlay`) **총 36/36 경로 PASS** (가로 오버플로 0건, H1 단일 위계 충족, WCAG AA 대비 미달 0건, `<11px` 텍스트 0건, `>=700` 웨이트 0건, `backdrop-filter` 블러 0건, 미라벨 버튼 0건).
+- **2026-11-04 Web Push 국소 변경:** 기존 웹 사이드바 구조·테마 토큰을 유지한 채 명시적 opt-in/out 스위치와 11px 상태 문구를 추가했다. 권한·VAPID·revocation 오류는 색만이 아닌 텍스트로 표시하고, 설정 누락 시 unavailable/fail-closed로 고정한다.
diff --git a/docker-compose.nas.yml b/docker-compose.nas.yml
index 0006943..02afa09 100644
--- a/docker-compose.nas.yml
+++ b/docker-compose.nas.yml
@@ -62,7 +62,8 @@ services:
restart: unless-stopped
ports:
- "${WEB_PORT:-3002}:3002"
- # NEXT_PUBLIC_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_ANON_KEY / NEXT_PUBLIC_PAYPLE_CLIENT_KEY 는
+ # NEXT_PUBLIC_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_ANON_KEY / NEXT_PUBLIC_PAYPLE_CLIENT_KEY /
+ # NEXT_PUBLIC_VAPID_PUBLIC_KEY 는
# 이미지 빌드 때 번들에 들어간다(build args). 런타임에 넣어도 바뀌지 않으므로 여기 두지 않는다.
environment:
- NODE_ENV=production
diff --git a/docker-compose.yml b/docker-compose.yml
index 86478e1..9afce0d 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -69,12 +69,14 @@ services:
NEXT_PUBLIC_SUPABASE_URL: ${NEXT_PUBLIC_SUPABASE_URL:-}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${NEXT_PUBLIC_SUPABASE_ANON_KEY:-}
NEXT_PUBLIC_PAYPLE_CLIENT_KEY: ${NEXT_PUBLIC_PAYPLE_CLIENT_KEY:-}
+ NEXT_PUBLIC_VAPID_PUBLIC_KEY: ${NEXT_PUBLIC_VAPID_PUBLIC_KEY:-}
image: d3ro-voice-web:latest
container_name: d3ro_voice_web
restart: unless-stopped
ports:
- "${WEB_PORT:-3002}:3002"
- # NEXT_PUBLIC_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_ANON_KEY / NEXT_PUBLIC_PAYPLE_CLIENT_KEY 는
+ # NEXT_PUBLIC_SUPABASE_URL / NEXT_PUBLIC_SUPABASE_ANON_KEY / NEXT_PUBLIC_PAYPLE_CLIENT_KEY /
+ # NEXT_PUBLIC_VAPID_PUBLIC_KEY 는
# 이미지 빌드 때 번들에 들어간다(build args). 런타임에 넣어도 바뀌지 않으므로 여기 두지 않는다.
environment:
- NODE_ENV=production
diff --git a/docs/REFACTOR_POLICY.md b/docs/REFACTOR_POLICY.md
index 7491883..0f79f63 100644
--- a/docs/REFACTOR_POLICY.md
+++ b/docs/REFACTOR_POLICY.md
@@ -1,7 +1,7 @@
# D3RO-VOICE 리팩토링 정책 (SSOT)
-> 마지막 갱신: 2026-07-22 — Wave 1 정책 수립
-> 적용 범위: `apps/desktop` + `packages/{core,ui,i18n}` (web/admin/site/server/mobile은 별도 wave)
+> 마지막 갱신: 2026-11-04 — Wave 4 전체 모노레포 위생 점검 정책 확정
+> 적용 범위: `apps/*` + `packages/*` + `server/*` + `site/` + 빌드·배포 스크립트 (기능 변경은 별도 요청)
## 0. 전제: 기존 3계층 규칙 SSOT와의 관계
@@ -51,7 +51,7 @@ D3RO는 이미 3계층 강제 규칙 체계를 가진다. 본 정책은 이를 *
- **확정: 3회** (2026-07-22 합의)
### DP8. 자동화 — typecheck + lint + test + 강제 규칙 훅
-- WS 통합 후 반드시 GREEN: `npm run typecheck`(turbo) · `npm run lint` · `npm run test` · `npm run build`(빌드 영향 WS).
+- WS 통합 후 반드시 GREEN: `npm run typecheck`(npm workspaces) · `npm run lint` · `npm run test` · `npm run build`(빌드 영향 WS).
- UI 변경: `npm run dev`로 화면 1회 확인. (WS3은 화면별 즉시)
---
@@ -122,3 +122,35 @@ D3RO는 이미 3계층 강제 규칙 체계를 가진다. 본 정책은 이를 *
| W3-8 | 사이트 배포 | Cloudflare Pages 한 경로. GitHub Pages·NAS wwwroot 복사 경로 삭제 | — |
DRY 원칙 보강: Deno처럼 정본을 직접 import할 수 없는 런타임은 **생성 사본 + `--check` 게이트**로만 복제를 허용한다(`version:sync` 패턴과 같음). 손으로 옮겨 적은 사본은 금지.
+
+---
+
+## Wave 4 (2026-11-04) — 두 번째 전체 위생 점검
+
+사용자 지시: "두 번째 소스코드 정리, 대대적인 위생 점검." 기존 DP1~DP11과 Wave 3 정본 결정을 그대로 계승한다.
+
+### W4-1. 목표와 비목표
+
+- 목표: 전체 모노레포에서 증거가 확인된 데드코드·데드 스텁·중복 선언/동작·의존성 잔여물·계약 드리프트·빌드/스크립트 중복을 줄인다.
+- 비목표: 새 기능, UI/UX·문구 변경, DB 마이그레이션, 공개 API/IPC/payload의 breaking 변경, 비밀값·운영 서버 변경, 릴리스·배포는 제외한다. 실제 DB와 어긋난 공유 타입의 additive 정합화는 소비자 전체 typecheck를 조건으로 허용한다.
+- 추측만으로 대형 파일을 쪼개거나 이름을 바꾸지 않는다. 삭제 우선 → 계약 안정화 → 중복 통합 순서를 지키고, 의미 있는 중복 제거 없이는 새 추상화를 만들지 않는다.
+
+### W4-2. 유지 불변량
+
+- 공개 API·IPC 채널, 오류 코드/메시지, 결과 순서, 보안 경계, 저장·동기화 의미, 광고·결제 fail-closed 동작은 유지한다.
+- 화면 상태와 시각 결과는 유지한다. UI 동작 변경이 필요한 발견은 이번 Wave에서 기능 변경 후보로 분리하고 순수 정리와 섞지 않는다.
+- 기존 사용자 변경과 무관한 파일을 되돌리지 않으며, 현재 정책 문서 변경 외에는 감사 단계에서 소스를 수정하지 않는다.
+
+### W4-3. 감사와 실행 분리
+
+- 감사 A: 데스크톱 main/preload + `packages/core` — 서비스 경계, IPC·타입 SSOT, 데드코드/스텁, 중복 워크플로, any/console, 캐시 소유권.
+- 감사 B: desktop renderer + web/admin/mobile/site + `packages/ui`/`ui-native` — 디자인 토큰, i18n, 중복 UI/스타일, 미사용 컴포넌트와 export, any/console.
+- 감사 C: `packages/i18n` + server + 빌드/CI/의존성/스크립트 — 로케일 정합, 계약 사본, 미사용 의존성, 설정 중복, 문서-코드 드리프트.
+- 모든 후보는 `file:line`, 참조/호출 증거, HIGH/MED/LOW 확신도, DELETE/REPLACE/REFACTOR/KEEP 판정과 예상 게이트를 가져야 한다. KEEP도 이유를 명시하고, HIGH라도 구현 전에 다시 읽어 false positive를 걸러낸다.
+
+### W4-4. 패치 그룹과 검증
+
+- 파일이 겹치지 않는 P1 삭제/잔여물, P2 중복·SSOT, P3 설정/의존성 그룹으로 나눈다. 순수 리팩토링과 불가피한 기능 수정은 절대 같은 그룹에 두지 않는다.
+- 그룹마다 잔여 식별자 grep, 최소 표적 테스트, 변경 파일 lint를 먼저 실행하고, 통합 후 루트 `typecheck`·`test`·`lint`, 모바일 `typecheck`·`test`·`lint`, 영향받은 빌드와 `version:check`·`contract:check`를 실행한다.
+- packages 공유 계약 변경은 모든 소비 앱을 검사한다. UI 시각 변경은 원칙적으로 제외하며, 예외가 생기면 별도 합의와 시각 증거가 필요하다. 에이전트 서브쉘에서 Electron GUI를 백그라운드 실행하지 않는다.
+- 커밋·푸시는 사용자가 별도로 명시할 때만 수행한다. 이번 Wave는 패치 그룹별 diff와 검증 증거를 보존하고, `docs/REFACTOR_WAVE4_REPORT.md`에 변경/검증/SKIP/잔여 위험을 기록한다.
diff --git a/docs/REFACTOR_WAVE4_REPORT.md b/docs/REFACTOR_WAVE4_REPORT.md
new file mode 100644
index 0000000..e2803dd
--- /dev/null
+++ b/docs/REFACTOR_WAVE4_REPORT.md
@@ -0,0 +1,111 @@
+# Refactor Wave 4 Report — 두 번째 모노레포 위생 점검
+
+> 기준일: 2026-11-04
+> 기준 버전: 1.16.1 (버전 변경 없음)
+> 범위: `apps/*`, `packages/*`, `server/*`, `site/`, CI/build 설정과 현재 맵
+> 정책: [`REFACTOR_POLICY.md`](./REFACTOR_POLICY.md) Wave 4
+
+## 1. 결론
+
+Wave 4는 공개 API·IPC와 사용자 데이터 계약을 유지하면서, 실제 참조가 없는 코드·의존성·도구 설정을 제거하고 중복된 quota/DB 계약을 정본에 연결했다. 감사 중 드러난 기능 결함은 source-only repair로 분리했으며, 실행 환경이나 외부 시스템 증거가 없는 항목은 완료로 올리지 않았다.
+
+커밋, 푸시, 배포, 릴리스, linked/운영 DB migration 적용, 사용자 데이터 변경은 수행하지 않았다. 런타임 증거는 별도 project id·포트·볼륨의 격리 로컬 Supabase에서 throwaway fixture로만 만들었다.
+
+## 2. 불변 조건과 감사 방식
+
+- 공개 IPC, preload, 서비스 singleton, 외부 소비 가능 export는 이름 검색만으로 삭제하지 않았다.
+- 삭제 후보는 정의→생산자→소비자→테스트/문서 순서로 확인하고, 각 묶음 뒤 잔여 참조를 다시 검색했다.
+- 순수 삭제·타입 정리(P1/P2)와 동작을 바꾸는 source repair(P3/P4)를 분리했다.
+- UI 구조·높이·행동은 바꾸지 않았다. `site` LED shadow는 같은 값을 theme token으로 옮겼다.
+- feature/runtime 상태는 자동화 통과만으로 `[x]`로 올리지 않았다.
+
+## 3. Changed
+
+### P1 — 순수 삭제와 의존성 위생
+
+- 참조가 없던 web meeting trend chart 1개와 admin chart 3개를 삭제하고 web/admin의 `recharts` 및 lockfile 전이 의존성을 제거했다.
+- 참조가 없던 desktop `feature-gate.ts`와 내부 getter/helper 7종을 삭제했다. 공개 IPC·테스트 seam·singleton API는 유지했다.
+- 사용되지 않던 `turbo.json`, `pnpm-workspace.yaml`, api-client의 `@d3ro/core` 의존성을 제거하고 npm workspaces 하나만 남겼다.
+- api-client 의존성 제거 뒤 mobile의 독립 lockfile도 같은 해상도로 다시 생성해 제거된 `@d3ro/core` 전이 항목을 남기지 않았다.
+- 현재 실행 규칙과 Claude 보조 스킬에 남은 pnpm/Turbo 명령도 npm workspace 기준으로 교정했다.
+- web login/sidebar의 도달 불가능한 `t(...) ?? fallback` 15곳을 제거했다.
+
+### P2 — 타입과 경계 정리
+
+- mobile 11개 화면의 `useNavigation`/`useRoute`와 임시 route param list를 `RootStackParamList` 기반 exact type으로 교체했다.
+- `TalkScreen`의 직접 `console.warn`을 공용 logger로 이동했다.
+- api-client에 실제 DB와 맞는 `PushProvider`, `PushToken`, device-bound register/unregister RPC, `consume_quota.p_period` 타입을 추가했다.
+- web push는 `deviceId`를 필수로 하고 RLS/NOT NULL 계약과 충돌하던 직접 `push_tokens` upsert를 제거했다. 활성 device를 검증하는 `register_push_registration` RPC만 사용한다. Opt-out은 disabled intent를 먼저 기록하고 서버 unregister와 local unsubscribe를 bounded/parallel로 실행하며, logout의 sign-out은 cleanup을 기다리지 않는다.
+
+### P3 — SSOT와 i18n 정합화
+
+- `knowledge_embedding` quota를 `packages/core/src/plan-catalog.ts`의 `PLAN_QUOTA`에 편입하고 Deno generated contract를 재생성했다. `embedding-quota.ts`의 수기 tier 상수는 제거했다.
+- updater native dialog 16키를 12 locale catalog에 추가했다. prompt마다 현재 locale translator를 다시 읽어 같은 prompter의 ko→en 변경도 반영한다.
+- `site` LED의 raw box-shadow 3개를 Tailwind theme token으로 이동했다. 시각 값은 유지했다.
+
+### P4 — 분리된 기능/인프라 repair
+
+- root `test:mobile`을 mobile `test:ci`(`jest --runInBand`)에 고정했다.
+- root `build:all`과 Forgejo build-validation에 web production build를 추가했다.
+- web/admin typecheck는 clean checkout에서도 Next route/root-param 타입을 먼저 생성하도록 `next typegen && tsc --noEmit` 순서로 고정했다.
+- Forgejo quality job에 migration checker self-test와 실제 metadata/order 검사를 연결했다. 이 검사는 DB replay나 remote drift 검사가 아니다.
+- pg_cron service credential을 handler에서 검증하는 `audio-purge`에 `verify_jwt = false`를 명시해 gateway가 먼저 차단하지 않도록 했다. handler의 fail-closed 인증은 유지했다.
+- Supabase CLI 3.x가 제거한 `[inbucket]` 설정명을 `[local_smtp]`로 교체했다. 포트와 메일 동작 계약은 유지했다.
+- Web Push production sidebar를 explicit user-gesture permission → stable active web device → device-bound register RPC로 연결했다. Persistence 실패는 local subscription을 rollback하고, stale local subscription은 서버 재등록이 성공하기 전까지 connected로 표시하지 않으며, missing build-time VAPID key는 unavailable로 fail-closed한다. Standalone Docker 이미지에는 `public/sw.js`를 명시적으로 포함한다.
+- updater native dialog는 `--preview-update-dialogs` packaged-QA entry에서 실제 prompter의 네 분기를 updater/feed/download/install/settings 부작용 없이 순서대로 띄울 수 있게 했다. entry/prompt 계약과 12-locale parity는 자동화했고, GUI 외형은 외부 터미널 수동 게이트로 남겼다.
+- packaged native verifier는 실제 `uiohook-napi/prebuilds/-/uiohook-napi.node`를 필수로 검사하고, 누락/존재 fixture self-test와 상대·절대 package 경로를 검증한다. better-sqlite3 ABI repair와 N-API prebuild 존재 계약을 분리했다.
+
+### 문서와 상태 교정
+
+- 12개 catalog의 2,742키 parity와 실제 surface 노출을 분리했다. Desktop은 12 locale이지만 web은 selector가 없고 mobile은 ko/en만 노출하므로 `SHELL-03`의 W/M은 `[~]`다.
+- Web Push production call site와 build-time public-key 계약을 추가했지만 provider secrets·배포된 drain·실브라우저 수신 증거가 없으므로 ACC-12 W와 GAP-PUSH-03은 `[~]`로 유지했다.
+- meeting memo의 content 기반 CAS가 A→B→A를 감지하지 못할 수 있는 문제를 `GAP-SYNC-08`로 등록했다.
+- audio-purge는 격리 로컬 pg_cron/Vault/객체 삭제까지 검증했고, 운영 배포·스케줄 실행만 `GAP-OPS-04`에 남겼다. surface locale 확대는 `GAP-I18N-03`으로 남겼다.
+- release SSOT는 현재 `1.16.1` / `1160100` / `2026-11-04`로, site deploy는 삭제된 GitHub 경로 없이 Forgejo→Cloudflare Pages 정본으로 교정했다. 손상된 INFRA-19 설명도 실제 GitLab/Forgejo native/updater gate에 맞췄다.
+
+## 4. KEEP / DEFER 결정
+
+- 공개 IPC/TTS/history/service 메서드는 현재 내부 호출이 적어도 compatibility surface일 수 있어 유지했다.
+- STT driver DTO와 유사 타입은 공급자별 의미가 달라 이번 wave에서 억지로 합치지 않았다.
+- `MeetingMemo` revision 추가는 DB migration과 동시성 통합 증거가 필요해 구현하지 않고 gap으로 분리했다.
+- Web Push의 provider 설정·실브라우저 수신, locale selector/routing, updater packaged GUI, audio-purge 운영 deploy/cron은 로컬 증거만으로 완료 처리하지 않았다.
+- updater의 ko 이외 신규 키는 기존 locale 정책과 같은 English parity다. 번역 품질 확대는 별도 작업이다.
+
+## 5. Verification
+
+최종 통합 게이트 결과는 모든 변경을 합친 worktree 기준으로 기록한다.
+
+| Gate | Result |
+|---|---|
+| Root typecheck/test + desktop/admin/web builds (`npm run build:all`) | PASS — 233 files / 3,383 tests; desktop build; admin 18/18; web 18/18 |
+| Root lint | PASS — warnings 0 |
+| Mobile typecheck/lint/test (`test:ci`) | PASS — 87 suites / 599 tests, lint warnings 0 |
+| Root/mobile lock install dry-run | PASS — `npm ci --dry-run --ignore-scripts`; removed dependencies do not survive in either lock |
+| Core generated contract + version + design token gates | PASS — contract current; 1.16.1 / 1160100; design violations 0 |
+| .NET API tests | PASS — 28/28, skipped 0 |
+| Migration checker self-test/actual | PASS — 73 migrations |
+| Isolated Supabase runtime/shadow | PASS — empty + reset replay 73/73; `pg-delta --strict-coverage` diff 0; audio purge direct + pg_cron/Vault HTTP/storage path |
+| Edge CI-equivalent Deno check/test | PASS — 24 function entrypoints; Supabase 263 tests; Cloudflare drain 5 tests (268 total) |
+| Site production build | PASS — client/SSR + 10 locale prerender and sitemap/robots/llms outputs |
+| `git diff --check` + residual searches | PASS — CRLF→LF notices only; deleted identifiers/dependencies/current toolchain commands 0 residual |
+
+이미 묶음별로 확인한 증거:
+
+- updater preview/startup/i18n 4 files / 7 tests, locale parity 15 tests; native ABI self-test and the current package's relative/absolute `--dir` verification
+- api-client 4 files / 31 tests
+- web push device/RPC/permission/rollback/reconciliation/logout contract 17 tests
+- core plan quota matrix test와 `contract:check`
+- mobile route/logger targeted suites, strict typecheck, lint
+- embedding quota/embed/search/audio-purge 표적 31 tests와 전체 Edge CI-equivalent 268 tests
+- web/admin production build, site build, design-token scan
+- migration checker 73 files + self-test
+- 격리 Supabase: missing/non-service key 401, service 200; queue/`audio_files`/Storage fixture `1|1|1`→`0|0|0`; cron run `succeeded`, pg_net HTTP 200
+
+## 6. 검증 경계와 남은 위험
+
+- Supabase local migration replay, shadow diff, `audio-purge` direct/pg_cron/object deletion은 격리 stack에서 검증했다. linked remote drift와 배포된 운영 함수·Vault·cron은 실행하거나 변경하지 않았다.
+- Electron GUI를 agent subshell에서 실행하지 않았다. updater dialog의 packaged-app 시각/상호작용 증거는 없다.
+- current-source E2E APK의 state-preserving 설치·cold launch와 제한된 Notifications/status/UIA 경로는 물리 Fold6에서 검증했다. 이것은 fresh first-run, manual TalkBack/focus order, notification permission transition/real FCM, app-wide accessibility, production artifact 또는 iOS/VoiceOver 증거가 아니다. Web Push는 격리 local browser에서 device/token/outbox/drain 및 provider-accepted `delivered` row까지 확인했지만 service-worker/browser receipt는 확인하지 못했다. Production standalone은 build/serve 후 throwaway login navigation timeout으로 dashboard 전 단계에서 중단돼 production 1440/390, accessibility tree/hit target, permission/subscription journey도 미검증이다.
+- npm install은 현재 Node 23에 대한 React Native engine 경고와 기존 audit 이슈를 보고했다. 범위를 벗어난 `npm audit fix`는 실행하지 않았다.
+- 빌드 산출물 배포, 버전 변경, 릴리스 publication은 수행하지 않았다.
+
diff --git a/docs/deployment/push-transport-without-firebase.md b/docs/deployment/push-transport-without-firebase.md
index bf3dfd9..784ce80 100644
--- a/docs/deployment/push-transport-without-firebase.md
+++ b/docs/deployment/push-transport-without-firebase.md
@@ -1,7 +1,7 @@
# Push transport without Firebase — analysis
-> Status: decision note (2026-09-13)
-> Scope: `send-push` Edge Function, `server/supabase/migrations` push outbox, `apps/mobile-rn` notification stack
+> Status: decision note (2026-09-13; implementation status updated 2026-11-04)
+> Scope: `send-push` Edge Function, `server/supabase/migrations` push outbox, web/mobile notification clients
> Question: we already pay for Supabase. Can it replace Firebase for notifications?
---
@@ -9,7 +9,7 @@
## 0. TL;DR
- **Supabase already is the push backend.** Tokens, devices, durable outbox, leases, retries, and delivery audit all live in Supabase (`push_tokens`, `devices`, `push_deliveries`, `push_dispatch_attempts`, `send-push`). Firebase is only the **last hop** to the device.
-- **Web and iOS are now Firebase-free on the server side.** Web Push (VAPID + RFC 8291 aes128gcm) and Apple APNs (`.p8` token) transports are implemented in `send-push` (`_shared/webpush.ts`, `_shared/apns.ts`, 10 unit tests). Client registration for those providers is the remaining work.
+- **Web and iOS are Firebase-free in source.** Web Push (VAPID + RFC 8291 aes128gcm) and Apple APNs (`.p8` token) transports are implemented in `send-push`; the web sidebar and mobile client contain provider-specific registration paths. This does not prove production delivery: matching provider secrets, a deployed drain, authenticated browser/device permission, and real receipt are still open gates.
- **Android cannot drop Firebase without changing transport.** Google Play Services only delivers push through FCM, and the FCM registration token is minted by the Firebase Messaging SDK, which requires `google-services.json` (a Firebase project). Supabase cannot substitute for that hop.
- **The scheduled drain was missing and is now added.** Nothing in the repo triggered `send-push?mode=drain`, so transactionally enqueued notifications never left the outbox. A Cloudflare Cron Trigger now drains it every minute.
- **Firebase-free Android is possible but is a different product decision:** UnifiedPush + a self-hosted distributor (e.g. ntfy). Third-party push services (OneSignal, Pusher) do **not** remove the Firebase dependency; they wrap FCM.
@@ -23,14 +23,10 @@
| Token + device registry | Supabase | `push_tokens`, `devices`; writes via `register_push_registration` RPC; RLS denies direct access |
| Durable outbox + retry/lease | Supabase | `push_deliveries`, `push_dispatch_attempts`, `claim_due_push_dispatches`, `finalize_push_delivery` |
| Dispatch orchestration | Supabase Edge `send-push` | Auth, event resolution, batching, stale-token handling |
-| **Transport** | **FCM** | `_shared/push-contract.ts` → `https://fcm.googleapis.com/v1/projects//messages:send`, OAuth2 via `FCM_SERVICE_ACCOUNT_JSON` |
+| **Transports** | **FCM / Web Push / APNs** | `_shared/push-contract.ts`, `_shared/webpush.ts`, `_shared/apns.ts`; all route through `send-push` |
| Android client | Firebase Messaging SDK | `com.google.firebase:firebase-messaging`, `D3ROFirebaseMessagingService`, `google-services.json`; `FIREBASE_CONFIGURED` build flag |
-
-Provider values accepted but unimplemented (`send-push/index.ts`):
-```
-const unsupported = deliveries.filter((delivery) => delivery.provider !== 'fcm')
- → finalizeDelivery(..., 'permanent_failure', 'push_provider_not_supported')
-```
+| Web client | Browser Push API | `/app/sw.js`; sidebar opt-in/out binds a stable active web device to the `webpush` registration through RPCs |
+| iOS client | Native APNs bridge | Mobile registration chooses `provider: 'apns'` on iOS and unregisters through the shared RPC |
So: the only Firebase-specific pieces are (a) the FCM HTTP v1 send + service account, and (b) the Android client token source.
@@ -41,15 +37,17 @@ So: the only Firebase-specific pieces are (a) the FCM HTTP v1 send + service acc
### Desktop — no change needed
In-app events use IPC/EventEmitter and Supabase Realtime. No push transport, no Firebase.
-### Web — Firebase-free, implementable now
+### Web — Firebase-free, implemented in source
- Standard **Web Push** with **VAPID** keys. The browser Push API + service worker handles delivery; the server signs with a VAPID private key and POSTs to the subscription endpoint.
-- Supabase plan: store `push_subscriptions` (endpoint + keys per browser), send from `send-push` with a VAPID JWT (ES256).
+- The sidebar requests permission from an explicit user gesture, creates/checks in a stable active `platform='web'` device, and stores the serialized subscription in `push_tokens` through `register_push_registration`. Opt-out records a per-user disabled intent before bounded parallel server/local cleanup; an existing local subscription is re-registered through the server RPC before the UI may call it connected. Logout starts cleanup without waiting and always proceeds to sign-out.
+- `NEXT_PUBLIC_VAPID_PUBLIC_KEY` is baked into the browser bundle and must match the Edge Function's `WEBPUSH_VAPID_PUBLIC_KEY`; a missing browser key leaves the control unavailable.
- No Firebase, no Google account. APNs not involved.
-### iOS — Firebase-free, implementable now
+### iOS — Firebase-free, implemented in source
- **APNs** directly: `.p8` key + Key ID + Team ID → JWT (ES256) → `https://api.push.apple.com/3/device/`.
- Needs an Apple Developer membership (already needed for App Store), **not** a Firebase project.
- Supabase Edge Function can hold the `.p8` as a secret and sign the JWT with WebCrypto.
+- The mobile notification service chooses `provider: 'apns'` for iOS. A signed-device run with real APNs credentials and receipt is still required.
### Android — Firebase-free only via UnifiedPush
- Google Play Services delivers notifications through FCM. The official `FirebaseMessaging` SDK mints the registration token, and it requires `google-services.json`. There is no supported way to obtain an FCM token without a Firebase project.
@@ -75,23 +73,25 @@ If the goal is "no Firebase at all", the decision reduces to: replace Android tr
1. **Keep Supabase as the SSOT/outbox** (already true). Do not move token/outbox logic.
2. **[done] Implement `webpush` + `apns` transports** in `send-push` (`_shared/webpush.ts`, `_shared/apns.ts`).
-3. **For Android, offer two modes behind config:**
+3. **[source done] Register web/APNs clients through the device-bound RPCs.** Keep provider configuration and real delivery as runtime gates.
+4. **For Android, offer two modes behind config:**
- `fcm` (default): minimal Firebase project, push-only usage.
- `unifiedpush` (opt-in): self-hosted ntfy distributor; documented UX and battery caveats.
-4. **Do not adopt OneSignal/Pusher** as a "Firebase replacement" — it does not remove the dependency.
+5. **Do not adopt OneSignal/Pusher** as a "Firebase replacement" — it does not remove the dependency.
### Effort sketch
| Item | Effort | Risk |
|---|---|---|
| Web Push (VAPID) transport + tests | S–M | low — **done** |
-| APNs (JWT ES256 `.p8`) transport + tests | M | medium — **server done**, Apple key + client registration pending |
+| Web browser device/subscription flow | M | medium — **source + contract tests done**, live configuration/delivery pending |
+| APNs (JWT ES256 `.p8`) transport + client registration | M | medium — **source + unit tests done**, Apple key/live delivery pending |
| Cloudflare cron drain | S | low — **done** |
| UnifiedPush Android (client lib + distributor + server transport) | L | high (UX, battery, distributor dependency) |
| Minimal Firebase project for Android FCM | S (external action) | low |
---
-## 5. Implemented (2026-09-13)
+## 5. Implemented (2026-09-13; client update 2026-11-04)
| Piece | Where | Notes |
|---|---|---|
@@ -100,16 +100,24 @@ If the goal is "no Firebase at all", the decision reduces to: replace Android tr
| Provider routing | `send-push/index.ts` | `fcm` / `webpush` / `apns` dispatched with per-delivery stale → `stale`, payload → `permanent_failure`, else retryable; unknown providers stay `push_provider_not_supported` |
| Cloudflare cron drain | `server/cloudflare-worker/src/push-drain.ts` + `scheduled()` + `wrangler.toml [triggers] crons` | POSTs `send-push?mode=drain&limit=…` with the service-role bearer every minute |
| Tests | `_shared/webpush.test.ts`, `_shared/apns.test.ts`, `push-drain.test.ts`, `push-contract.test.ts` | 10 new tests incl. an RFC 8291 decrypt round-trip; CI runs the edge suite and the worker drain test |
+| Web client | `apps/web/public/sw.js`, `src/lib/{web-device,web-push,web-push-session}.ts`, `web-push-control.tsx` | Explicit opt-in/out, stable active device, device-bound RPCs, persistence rollback, disabled-intent reconciliation, bounded parallel cleanup, non-blocking logout; standalone image copies the service worker |
+| Web contract tests | `apps/web/e2e/web-push.spec.ts` | 17 tests for installation identity, revoked-device refusal, permission/VAPID gate, register/unregister RPCs, rollback, stale-subscription reconciliation, bounded cleanup, and logout independence |
+| iOS client registration | `apps/mobile-rn/src/features/notifications/*` | Platform-aware APNs/FCM registration and unregister path; unit-tested, not live-delivery verified |
+
+### Local runtime evidence (2026-11-04)
+
+An ephemeral VAPID pair, throwaway user, isolated Supabase project, and throwaway Chrome profile proved browser opt-in, one active web device, one device-bound `webpush` token, one pending dispatch, a completed local drain, and a `push_deliveries.status='delivered'` result. That last state means the Web Push endpoint accepted the request; it does **not** prove that the service worker displayed or received a notification. No browser receipt was observed. A later production-standalone attempt built and served successfully but timed out during throwaway login navigation before the dashboard, so production-rendered desktop/mobile accessibility, permission/subscription, and receipt remain explicit gates. All ephemeral keys, rows, user data, and the browser profile were removed; the isolated stack was restored without VAPID configuration and then deleted.
### Required configuration
| Secret / var | Consumer | Purpose |
|---|---|---|
| `WEBPUSH_VAPID_PUBLIC_KEY` / `WEBPUSH_VAPID_PRIVATE_KEY` / `WEBPUSH_SUBJECT` | Supabase Edge Function | VAPID signing; subject must be `mailto:` or `https:` |
+| `NEXT_PUBLIC_VAPID_PUBLIC_KEY` | Web image build | Public half of the same VAPID pair, baked into the client bundle; missing means unavailable/fail-closed |
| `APNS_KEY_ID` / `APNS_TEAM_ID` / `APNS_PRIVATE_KEY` / `APNS_TOPIC` / `APNS_ENVIRONMENT` | Supabase Edge Function | APNs token auth; topic is the bundle id (`com.d3ro.voice`) |
| `SUPABASE_URL` / `SUPABASE_SERVICE_ROLE_KEY` / `PUSH_DRAIN_BATCH_LIMIT` | Cloudflare Worker | Cron drain target + auth (service role key as `wrangler secret`) |
### Remaining work
-- **Client registration:** the mobile app currently registers only `fcm`. Web needs a service worker + `pushManager.subscribe` → store the JSON subscription as the registration id; iOS needs an APNs device token and `provider: 'apns'`.
+- **Runtime proof:** configure matching web/server VAPID values and APNs credentials, build/deploy the web image and Edge/cron code, then prove authenticated browser/iOS registration, outbox drain, and real receipt. Source and automated contract tests alone do not satisfy this gate.
- **Android decision:** keep FCM or adopt UnifiedPush (see §2/§3).
---
@@ -121,6 +129,7 @@ If the goal is "no Firebase at all", the decision reduces to: replace Android tr
- `server/supabase/functions/_shared/apns.ts` — APNs (.p8 token)
- `server/supabase/functions/send-push/index.ts` — dispatch orchestration
- `server/cloudflare-worker/src/push-drain.ts` — cron drain
+- `apps/web/src/lib/web-push-session.ts` + `apps/web/src/components/layout/web-push-control.tsx` — browser device/subscription orchestration
- `apps/mobile-rn/src/features/notifications/*` — client token/provider contract
- `docs/map/11-gap-backlog.md` `GAP-PUSH-01` / `GAP-PUSH-02` / `EXT-FIREBASE-01`
- `docs/v3/MOBILE_APP_COMPLETION_SSOT.md` `EXT-011`
diff --git a/docs/evidence/2026-11-04-mobile-runtime-a11y.md b/docs/evidence/2026-11-04-mobile-runtime-a11y.md
new file mode 100644
index 0000000..461262a
--- /dev/null
+++ b/docs/evidence/2026-11-04-mobile-runtime-a11y.md
@@ -0,0 +1,85 @@
+# 2026-11-04 mobile runtime and accessibility evidence
+
+All times are KST. This report keeps source, Android runtime, automated accessibility inspection, and manual screen-reader proof separate. No app data was cleared, no package was uninstalled, no default input method was changed, and no notification or accessibility setting was intentionally changed.
+
+## Verdict
+
+| Gate | Result | Boundary |
+|---|---|---|
+| Current-source Android artifact | **PASS (E2E, not production)** | `1.16.1-e2e.20261104.1` / `2026110401`, non-debuggable, arm64-v8a + x86_64. This is not a signed production AAB. |
+| State-preserving install and launch | **PASS** | `adb install -r` on a Fold6 running Android 16 and an isolated API 34 AVD. Existing app data was retained. |
+| Notifications screen | **PASS for the already-granted/registered state** | The physical-device flow opened Notifications and asserted its status, privacy, and recent-notification cards without pressing a permission action. It does not prove permission denial/request/acceptance or real FCM delivery. |
+| Automated Android accessibility | **PARTIAL PASS** | App-owned actionable nodes inspected on Home and Login were named and at least 48dp. The ad slot exposed one unlabeled clickable SDK WebView. Font scale 2.0 and portrait/landscape scrolling were checked on the AVD. |
+| Manual TalkBack | **NOT RUN** | TalkBack was installed but not enabled on the physical device. UIAutomator output is not screen-reader announcement, focus-order, or activation proof. |
+| iOS / VoiceOver | **NOT AVAILABLE** | The host is Windows. No iOS simulator/device or VoiceOver proof is claimed. |
+
+## Artifact, install, launch, and logs
+
+Build and verification:
+
+```text
+cd apps/mobile-rn/android
+D3RO_VERSION_NAME=1.16.1-e2e.20261104.1
+D3RO_VERSION_CODE=2026110401
+gradlew.bat :app:assembleE2e -PreactNativeArchitectures=arm64-v8a,x86_64 --no-daemon
+
+node scripts/ci/verify-android-artifact.mjs \
+ --apk apps/mobile-rn/android/app/build/outputs/apk/e2e/app-e2e.apk \
+ --mode e2e \
+ --expected-version-name 1.16.1-e2e.20261104.1 \
+ --expected-version-code 2026110401 \
+ --expected-admob-app-id ca-app-pub-3940256099942544~3347511713
+```
+
+- Gradle: `BUILD SUCCESSFUL`, 644 tasks, about 3m42s.
+- APK: 147,160,979 bytes; SHA-256 `3d2875c74b555dbcd854468e57b9b4b3a8e6c9657f210760cbe24a77ee92cf7c`.
+- Verifier: package `com.d3ro.voice`, minSdk 24, targetSdk 36, `debuggable:false`, ABIs arm64-v8a/x86_64, test AdMob application ID, expected model hash, and signer inspection all passed.
+- `adb install -r` passed on both targets. The physical device retained `firstInstallTime=2026-11-01 10:55:50`; the AVD retained `firstInstallTime=2026-11-01 10:32:43`.
+- Cold `am start -W` completed in 185ms on the physical device and 1,024ms on the AVD. `MainActivity` became the resumed activity.
+- The inspected recent logcat window contained zero `FATAL EXCEPTION`, app `AndroidRuntime` process crash, or React fatal signature matches. This is a bounded window, not a long-duration ANR/privacy-log audit.
+
+## Notifications screen without permission mutation
+
+The reusable flow is [`apps/mobile-rn/.maestro/notifications-permission-preserve-state.yaml`](../../apps/mobile-rn/.maestro/notifications-permission-preserve-state.yaml). It launches with `clearState:false`, opens More → Notifications, and asserts these stable cards:
+
+- `notification-status-card`
+- `notification-privacy-card`
+- `notification-recent-card`
+
+It contains no `setPermissions`, permission-button tap, app-data clear, or reinstall step. On the Fold6 it passed **1/1 in 30s**. Local retained output is under `apps/mobile-rn/.maestro-output/wave4-notifications-state-neutral-20261104/`, including `results.xml`, the command trace, and `artifacts/screenshots/notifications-status-preserved.png`.
+
+The rendered state was already **Registered**: Firebase configured, registration bound to the current device/account, privacy copy present, and no item received in the current session. This proves the screen and the current registered-state rendering; it does not prove transport delivery.
+
+An earlier read showed `POST_NOTIFICATIONS` denied, while a later read showed it granted even though neither retained flow contains a permission request command. That transition cannot be attributed from the captured evidence. Therefore permission preservation across a denied-state run, the user-facing request/deny flow, and the Android system dialog remain open gates.
+
+## Automated accessibility inspection
+
+The checks combined source inspection with `uiautomator dump`; they did not use TalkBack.
+
+- Physical Home at font scale 1.15: 16 clickable nodes, no target smaller than 48dp at the device's override density. Fifteen app-owned actions had a text or content description. The remaining clickable node was an `android.webkit.WebView` inside the banner ad slot.
+- API 34 AVD Login: all six actionable controls (Google sign-in, email, password, Sign in, Forgot password, Sign up) had labels and met the 48dp target. A focusable `ScrollView` was excluded because it is a container, not an action.
+- API 34 AVD at font scale 2.0: the portrait login controls remained reachable. In locked landscape, upward scrolling exposed password, Sign in, Forgot password, and Sign up. The AVD was restored to its prior `font_scale=null`, portrait rotation, and accelerometer setting after the check.
+- Source scan found accessibility attributes across the React Native surface, and focused Jest coverage passed for navigation, `ScreenHeader`, ads, and notification native/runtime paths. This is evidence for the inspected routes only, not an app-wide focus-order audit.
+
+### AdMob ownership boundary
+
+The app-owned wrapper in `FreeTierBanner.tsx` has `testID="free-tier-ad-slot"` and the translated `mobile.ads.sponsored` accessibility label. The pinned `react-native-google-mobile-ads@16.3.4` banner API explicitly does not forward standard `View` props; its `BaseAd` renders `RNGoogleMobileAdsBannerView`, and its Android manager creates the Google Mobile Ads SDK `AdView`, which supplies the observed WebView descendant.
+
+Accordingly, the one unlabeled clickable WebView is an SDK-rendered descendant inside an app-owned labeled slot. The automated tree did not expose the wrapper label on that clickable descendant. Making the wrapper a single accessibility element could also hide or change activation of the SDK ad, so no behavior-changing workaround was applied without manual TalkBack proof. The announcement and activation behavior remains open.
+
+## Source gates run after the device check
+
+| Command | Result |
+|---|---|
+| `npm --prefix apps/mobile-rn run lint` | PASS, zero warnings/errors |
+| `npm --prefix apps/mobile-rn run typecheck` | PASS |
+| Focused Jest: notifications, native/cold-start notifications, navigation shell, ScreenHeader, mobile ads | **6 suites / 38 tests PASS** |
+
+## Open gates
+
+- Manual TalkBack announcements, traversal order, gesture activation, and the AdMob descendant behavior on a physical device.
+- Android notification permission deny/request/accept/system-settings transitions without resetting personal state.
+- Real foreground/background/terminated FCM delivery and notification deep-link receipt.
+- App-wide font-scale/rotation coverage beyond the inspected Login route.
+- iOS build/device, APNs receipt, dynamic type, and VoiceOver.
+- Signed production AAB, Play distribution, and production AdMob serving.
diff --git a/docs/evidence/2026-11-05-tablet-layout-audit.md b/docs/evidence/2026-11-05-tablet-layout-audit.md
new file mode 100644
index 0000000..4f71de7
--- /dev/null
+++ b/docs/evidence/2026-11-05-tablet-layout-audit.md
@@ -0,0 +1,115 @@
+# 태블릿(대화면) 레이아웃 실기 감사 — 2026-11-05
+
+**질문**: 타블렛에서 앱 레이아웃이 괜찮은가?
+**답**: 기능은 동작하지만 **대화면 대응이 없다.** 모든 화면이 "넓어진 휴대폰" 한 열이다.
+
+---
+
+## 1. 접속 경로 (실제로 어떻게 붙었는지)
+
+| 시도 | 결과 |
+|---|---|
+| `100.117.18.16:33455` (제시된 주소) | **ECONNREFUSED** — Tailscale 로 호스트는 살아 있으나 해당 포트에 리스너가 없다. |
+| `adb connect 100.117.18.16:33455` | 실패 (10061). 무선 디버깅 포트는 재시작마다 바뀐다. |
+| `adb mdns services` | `adb-R54Y9036G4A` @ `192.168.0.17:36769` = **tab-s11-ultra**. 현재 포트는 36769. |
+| `adb connect 100.117.18.16:36769` / `192.168.0.17:36769` | 실패 — 이 PC 와 **페어링되어 있지 않다**(무선 디버깅 페어링 코드 필요). |
+| `adb pair 100.117.18.16:44865 113625` | **성공** → 이후 `adb connect 100.117.18.16:40479` (port 는 페어링 직후 mDNS `_adb-tls-connect` 값). |
+| 페어링된 실기기 | **SM-X930 (Galaxy Tab S11 Ultra)** — 1848×2960, density override 320 → **924dp**, 기본 가로 모드. |
+| 보조 기기 | **SM-F956N (Galaxy Z Fold6)** — `device_state state 3` 로 펼침(825dp) 재현에도 사용. |
+
+**실기기 재현 (Tab S11 Ultra)**:
+
+```bash
+ADB="$LOCALAPPDATA/Android/Sdk/platform-tools/adb.exe"
+"$ADB" pair 100.117.18.16:44865 <6자리 페어링 코드>
+"$ADB" mdns services # _adb-tls-connect 포트 확인 후
+"$ADB" connect 100.117.18.16:40479
+"$ADB" -s 100.117.18.16:40479 install -r apps/mobile-rn/android/app/build/outputs/apk/e2e/app-e2e.apk
+"$ADB" -s 100.117.18.16:40479 shell am start -W -n com.d3ro.voice/.MainActivity
+"$ADB" -s 100.117.18.16:40479 exec-out screencap -p > tab.png
+```
+
+**재현 방법 (페어링 없이, 실기기 변경 최소)**: Fold6 은 `device_state` 오버라이드로 "펼친(OPENED)" 상태를
+시뮬레이션할 수 있다. 실제 화면을 접었다 펴지 않아도 inner display 크기(1856×2160 @ density 360 ≈ 825dp 폭)가
+적용되어 태블릿 판정에 쓸 수 있다.
+
+```bash
+ADB="$LOCALAPPDATA/Android/Sdk/platform-tools/adb.exe"
+S=""
+"$ADB" -s "$S" shell cmd device_state state 3 # OPENED (inner display)
+"$ADB" -s "$S" shell am start -W -n com.d3ro.voice/.MainActivity
+"$ADB" -s "$S" shell dumpsys SurfaceFlinger --display-id # 캡처할 display id 확인
+"$ADB" -s "$S" exec-out screencap -p -d > shot.png
+"$ADB" -s "$S" shell cmd device_state state 0 # 원상복구 (CLOSED)
+```
+
+> 캡처는 `test-results/tablet-2026-11-05/` (gitignored, 커밋 안 됨). 스크린샷에 실제 기록 데이터가 찍혀 있어
+> 개인정보 보호를 위해 저장소에 넣지 않는다.
+
+측정 조건: 물리 1856×2160, density override 360 → **약 825dp 폭**. Material large(≥600dp)·태블릿 판정 구간에 들어간다.
+
+---
+
+**실기기(Tab S11 Ultra 924dp 가로) 결과** — Fold6 시뮬레이션과 동일한 결론이 더 뚜렷하게 재현됐다.
+
+| 화면 | 실측 |
+|---|---|
+| 온보딩/튜토리얼 1/5 | 본문 텍스트 노드 폭 **2880px(900dp)** — 한 줄이 화면 전체를 가로지른다. 카드 2개도 full-width. |
+| Login | Google 버튼·이메일·비밀번호·로그인 버튼 모두 **2880px(900dp)** 폭. 태블릿에서 폼 최대 폭(400~480dp) 부재. |
+| Recorder | `START RECORDING` / `IMPORT AUDIO FILE` 버튼이 **2880px(900dp)** full-width. 오류 배너도 full-width. |
+| Home (가로) | `home-record-*` 행이 **40..2920px**, `See all` 이 우측 끝(2824..2920). 한 행이 900dp. |
+| Records (가로) | 동일. 배지(`17 W`)·Star/Delete 가 우측 끝, 제목/본문과 800dp 이상 떨어짐. |
+| Meetings (가로) | 카드 full-width + 카드마다 큰 세로 여백. 목록 4번째 카드가 화면 아래로 잘림(스크롤 필요). |
+| More (가로) | 라벨 ↔ chevron 사이 ≈**800dp** 공백. `Voice actions` 아래 항목은 광고 슬롯 뒤로 스크롤해야 보임. |
+| 세로(portrait) | 폰과 같은 1열 구성. 924dp 폭이라 여전히 줄 길고 카드가 넓다. |
+
+**광고 슬롯 실측**: `free-tier-ad-slot` = `0,1472 - 2960,1654` (전체 폭, 높이 182px ≈ 91dp), 탭 바는
+`1656..1752`. 슬롯은 탭 바 위에 **정상 배치**되어 있고 콘텐츠는 그 위에서 끝난다(가림 아님).
+다만 슬롯이 91dp 를 차지하므로 작은 화면에서 목록 가용 높이가 줄어든다.
+
+**성능 관찰**: Records 탭 첫 진입이 실기기에서 **5~10초 빈 스피너**였다(이후 20건 표시). 레이아웃 문제는 아니지만
+대화면에서 빈 화면이 크게 보이므로 체감이 나쁘다.
+
+## 2. 판정 (스크린별, Fold6 825dp 시뮬레이션)
+
+| 화면 | 관찰 | 판정 |
+|---|---|---|
+| Home | 한 열, 폭 전체 사용. 본문 줄 길이 과다(한글/영문 혼합 전사문 1줄 100자+). 광고 배너가 콘텐츠 하단 위로 자리 이동. | ⚠ 넓어진 휴대폰 |
+| Records | 동일. 카드 우측 badge(17 W)·Star/Delete 가 화면 끝(≈800dp)에 몰려 시선 이동 거리 큼. | ⚠ |
+| Meetings | 카드 full-width + 카드마다 불필요한 세로 여백. **2열 그리드 후보**. | ⚠ |
+| More | 9개 항목이 full-width, 라벨과 chevron 사이 ≈700dp 공백. **2열 그리드 후보**. | ⚠ |
+| Dictionary | 카드 1장이 폭 전체. Edit/Delete 버튼이 각각 화면 절반 폭(≈400dp) — 모바일 버튼 크기가 아님. | ⚠ |
+| Commands | 4개 카드 세로 스택. "Activate" 버튼이 카드 좌측에 작게 붙어 균형 붕괴. | ⚠ |
+| Templates | "Select" 버튼이 full-width(≈800dp) — 클릭 타깃이 과대. | ⚠ |
+
+공통 원인:
+1. **화면 레벨 콘텐츠 최대 폭/그리드가 없다.** `useWindowDimensions`·breakpoint·`numColumns` 사용처가 0건.
+ (`maxWidth` 는 모달·입력 필드에만 존재.)
+2. `supportsTablet: true` 는 iOS manifest 에만 있고 레이아웃 계획은 없다(`docs/v3/00-mobile-master-plan.md:688`).
+3. 적응형 배너(`ANCHORED_ADAPTIVE_BANNER`, slot `minHeight: 50`)가 로드 후 728×90 → 468×60 으로 바뀌며
+ 탭 바 높이가 변한다. 콘텐츠가 가려지진 않지만(끝까지 스크롤 확인) **초기 레이아웃 시프트**가 있다.
+
+---
+
+## 3. 개선 제안 (우선순위)
+
+1. **공용 콘텐츠 컬럼**: `packages/ui-native` 에 `useContentWidth()`(예: `Math.min(windowWidth, 720)`)와
+ `ContentColumn` 을 추가하고 탭 화면 7곳에 적용. 가장 값싸고 회귀 위험이 낮다.
+2. **2열 그리드**: `≥600dp` 에서 More/Meetings/Commands/Templates 를 `FlatList numColumns={2}` 로.
+ (More 는 섹션 헤더가 있어 섹션별 그리드 또는 `flexWrap` 카드.)
+3. **버튼 폭 제한**: full-width 버튼은 `maxWidth: 320`(모바일 버튼 규격)로 제한.
+4. **배너 시프트 제거**: slot 높이를 광고 실측 높이로 고정하거나, 로드 전 `minHeight` 를 90 으로 예약.
+5. **실기기 회귀 방지**: Maestro 플로우에 `open`/`closed` 2회 실행을 추가하고, 대화면 스크린샷을 증거로 남긴다.
+
+---
+
+## 4. 재현/검증 명령 (수동)
+
+```bash
+# 대화면 시뮬레이션 후
+"$ADB" -s "$S" shell cmd device_state state 3
+"$ADB" -s "$S" shell cmd device_state state 0 # 반드시 원복
+```
+
+자동화로 만들 경우 `device_state` 오버라이드는 실기기 설정을 바꾸므로 CI 에 넣지 않고,
+로컬 릴리스 전 점검(Maestro `open`/`closed` 2회)으로 둔다.
diff --git a/docs/map/00-index.md b/docs/map/00-index.md
index 426fed7..679c861 100644
--- a/docs/map/00-index.md
+++ b/docs/map/00-index.md
@@ -2,7 +2,11 @@
> Status: ACTIVE
> Last full audit: 2026-09-13
-> Last update: 2026-11-04 — **Windows v1.16.1 패치 배포.** 빠른 한영 자판 교정이 다음 키 입력과 백스페이스 배치 사이에서 경합하지 않도록 140ms 입력 간격 게이트와 유휴 후 현재 영역 일괄 교정을 적용했다. 데스크톱 2,773개 테스트·typecheck·프로덕션 빌드·변경 범위 lint가 GREEN이며, 설치본과 서명된 업데이트 메타데이터를 Forgejo에 게시하고 공개 피드와 설치 파일 HTTP 200을 확인했다. 1.16.1 설치 후 Latin 대조군 GUI와 물리 키보드·Chromium/terminal 검증은 남아 있다.
+> Last update: 2026-11-04 — **테스트 위생 재편.** 버그헌팅 E2E(red-team cycle) 스펙과 중복·죽은 스펙 11개를 삭제하고, 데스크톱 E2E 를 공용 Electron 픽스처 + 5개 보호 여정으로 통합했다. 루트 `tests/e2e` 와 일회성 Playwright 러너 7개도 제거. 새 게이트 `npm run test:hygiene`(+`:test`)를 CI 두 파이프라인에 넣어 `.only`/이유 없는 skip/가짜 단정/머신 경로/`waitForTimeout`/`.e2e.test.ts` 를 막는다. 정본: [`docs/tdd-red/06-repo-application.md`](../tdd-red/06-repo-application.md).
+>
+> Previous update: 2026-11-04 — **Wave 4 모노레포 위생 점검.** 사용되지 않는 chart/recharts·feature gate·내부 선언·Turbo/pnpm 잔여를 제거하고, mobile navigation 타입/로깅, push·quota 계약, embedding quota SSOT, updater dialog i18n, CI web build·migration metadata gate, `audio-purge` 함수 설정을 정합화했다. Web Push production call site, 12-locale 표면 노출, meeting memo ABA conflict, audio-purge 배포/pg_cron은 완료로 올리지 않고 `11`에 남겼다. 제품 버전은 1.16.1 그대로이며 커밋·푸시·배포·릴리스는 수행하지 않았다. 상세: [`REFACTOR_WAVE4_REPORT.md`](../REFACTOR_WAVE4_REPORT.md).
+>
+> Previous update: 2026-11-04 — **Windows v1.16.1 패치 배포.** 빠른 한영 자판 교정이 다음 키 입력과 백스페이스 배치 사이에서 경합하지 않도록 140ms 입력 간격 게이트와 유휴 후 현재 영역 일괄 교정을 적용했다. 데스크톱 2,773개 테스트·typecheck·프로덕션 빌드·변경 범위 lint가 GREEN이며, 설치본과 서명된 업데이트 메타데이터를 Forgejo에 게시하고 공개 피드와 설치 파일 HTTP 200을 확인했다. 1.16.1 설치 후 Latin 대조군 GUI와 물리 키보드·Chromium/terminal 검증은 남아 있다.
>
> Previous update: 2026-11-02 — Windows 1.16.0 실GUI에서 회의 파일 선택→전사→로컬 요약 생성을 확인했다. 네이티브 한글 IME는 100% CPU 및 `gemma4:e4b` 콜드 로딩 중 7/7 정확히 통과했다. 한영 자판 교정 대조군은 다음 키가 백스페이스에 섞이는 결함을 재현했고, 소스에서는 140ms 입력 간격 게이트와 유휴 후 현재 영역 일괄 교정으로 수정했다. 데스크톱 2,773개 테스트·빌드는 GREEN이지만 수정본 설치 GUI와 모바일 운영 배포는 남아 있다. 상세 증거: [2026-11-02 verification](../evidence/2026-11-02-verification.md).
>
@@ -29,7 +33,7 @@
> Previous update: 2026-09-22 — **Gemma/Ollama 폭주 방어 계약을 기록했다.** 19:14:12 부팅 워밍업이 `keep_alive: 30m`으로 `gemma4:e4b`를 19:44:12까지 VRAM 3,226,342,521 bytes / context 4096으로 강제 상주시킨 것이 관측됐으며, 같은 시점 Windows GPU Engine PID 표본에는 Ollama의 활성 compute가 없었다. 즉 당시 상태는 무한 추론이 아니라 강제 residency였다. 19:11:17~19:11:58의 자동 제안 연속 생성은 기존 900 ms·12/min·5 candidates·128 tokens·한 글자 재생성 정책이 허용한 burst였다. 현재 구현 계약은 부팅 warmup 제거, `keep_alive: 2m`, 제안 600 ms / 최소 5 s 간격 / 기본 6회·hard max 12회 per min / 3 candidates / 64 tokens / 12-char growth / 8 s timeout, 그리고 요청별 취소·상한·종료 정리다. 독립 표적 검증은 6 test files / 69 tests passed / 0 failed, 변경 코드·테스트 ESLint와 `git diff --check`도 exit 0이다. Raw Ollama에서는 cold bounded 요청이 client hard timeout 15.044 s에 취소된 뒤 `/api/ps`가 비었고 `/api/version`은 80 ms에 회복했다. 명시 warmup은 HTTP 200 / 16.639 s, 후속 warm 요청은 body `options.num_predict=1`, `keep_alive='2m'`로 553 ms HTTP 200 / `done:true` / `eval_count:1` / `done_reason:length`였고 `/api/ps` expiry는 약 119.9 s였다. **19:48:59 +09:00에는 새 generate/unload/kill/retry 없이 충분히 지난 뒤 한 번의 `/api/ps`가 HTTP 200 / 45.8 ms / `{models:[]}`였고 `/api/version`은 HTTP 200 / 7.3 ms / `0.32.13`이었다.** 이는 raw API 수준의 expiry 뒤 unload 확인일 뿐 앱 재시작·GUI·실제 타이핑 증거는 아니므로 상태는 `[~]`로 유지한다 (`11` GAP-LLM-04, GAP-INPUT-06).
>
> Previous update: 2026-09-21 — **Input intelligence (입력 레메트리 + 다음 문장 제안) 신규**. 데스크톱에 입력 수집기(`InputTelemetryService`), UIA 컨텍스트 브리지(사이드카 `GET /uia/focus`), 제안 서비스(`SuggestionService`), 어렛 커 오버레이, 설정 > 입력 탭(동의·정책·주간 인사이트·개인 문구)을 추가했다. 카탈로그에 `INPUT-01`~`INPUT-08`(전부 데스크톱 `[~]` — 유닛 48건은 GREEN 이지만 **실앱 타이핑 검증 전**), 백로그에 GAP-INPUT-01~05 + GAP-LLM-03, §7 에 CONSTRAINT-INPUT-01(키 내용 미저장 — ActivityWatch 정책 채택)을 기록. 설계 근거는 조사 기반이다: 어렛은 `GetGUIThreadInfo` 가 아니라 UIA `TextPattern.GetSelection`(Chromium 은 `TextPattern2` 미구현), 타이핑 스트는 키코드 복원이 아니라 UIA 스냅샷 diff(한/일 IME 대응), 디바운스/토큰 한도는 인라인 컴플리션 실측값(Continue 350 / Tabby 250 / twinny 300 ms, 출력 64~256 토큰). 의존성: `koffi` 3.3.1(포그라운드 창 FFI), 사이드카 `uiautomation` 2.0.29 + `comtypes`. 데스크톱 유닛 총계 1409(+49), Electron ABI 실행에서 신규 실패 0건. 당시의 24.7초/4.9초 지연 설명과 `keep_alive: 30m`·부팅 워밍업 처방은 **현재 상태가 아닌 과거 가설/완화 이력**이며, 최신 운영 결론은 위 2026-09-22 항목과 `11` GAP-LLM-04를 따른다. 직전: LLM instruction-prompt fix (`9c2b4d4`): the custom-instruction path inserted the instruction's own wording instead of the processed result and had **never worked in any shipped release** (`v0.1.0-alpha`..`v1.4.0`, introduced `fea923d` 2026-04-05, not a regression). `llm-prompts.ts` is now the SSOT for prompt resolution and placeholder substitution, shared by `VoiceModeService` / `ChainService` / `LLM.PROCESS`. AI-04/05/06/07 are demoted to `[~]` on desktop — fixed with unit tests, but **not verified in a running app** and the four related `tests/red/*.usecase.test.ts` could not execute (`better-sqlite3` ABI). New: GAP-LLM-01 (no target-language setting), GAP-LLM-02 (this fix unverified); GAP-INFRA-06 amended (the ABI masks verification, not just dev-env switching cost); GAP-I18N-01 amended (`popup.error.default` missing in 10 locales). Earlier the same day: CAP-16 (desktop key bindings rebuilt on one `@d3ro/core/keybinding` SSOT — multiple bindings per action, mouse buttons, `HOTKEY` → `KEYBINDING` IPC group), verified on Windows by a manual run, so CAP-16 and CAP-02 are `[x]` and GAP-KEY-01 is closed. Still open: GAP-KEY-02/03, GAP-QA-02, GAP-I18N-01/02, GAP-INFRA-06, GAP-LLM-01/02, GAP-INPUT-01~05; `11` §7 holds accepted design constraints (things deliberately kept, not gaps)
-> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.14.0` (`release/product-version.json`, released 2026-10-29)
+> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.16.1` (`release/product-version.json`, released 2026-11-04)
> Purpose: let any agent (or human) answer two questions in under a minute:
> 1. **What infrastructure exists?** (build, CI, services, APIs, data, packages, deploy)
> 2. **How far is each feature developed?** (per surface, with file anchors and status)
diff --git a/docs/map/02-infrastructure.md b/docs/map/02-infrastructure.md
index 64f9b80..b9054b9 100644
--- a/docs/map/02-infrastructure.md
+++ b/docs/map/02-infrastructure.md
@@ -1,7 +1,7 @@
# 02 — Repository & Infrastructure Map
> Surface: whole repo
-> Last updated: 2026-11-04 — Windows 1.16.1 installer and signed update metadata published; public feed and installer availability verified
+> Last updated: 2026-11-04 — Wave 4 toolchain/CI map reconciliation; Windows 1.16.1 release evidence remains unchanged
> Source of truth for: layout, workspaces, build/test commands, CI/CD, Docker, deploy, scripts, resources
---
@@ -34,20 +34,20 @@ D:/workspace/D3ROVoice
├── scripts/ ~145 automation scripts + scripts/ci/ (31) + scripts/lib/
├── docs/ Design, phases, v2/v3 plans, deployment, map/ (this map)
├── memory/ Project status, handoffs, archive
-├── tests/e2e/, test-results/ Root-level e2e + last-run artifacts
+├── test-results/ Last-run artifacts (root tests/e2e removed 2026-11-04 — orphaned duplicates)
├── scratch/ Large local evidence (APKs, screenshots, DBs) — not build input
├── supabase/ Empty scaffolding (.branches/, snippets/) — real project is server/supabase
├── .gitlab-ci.yml GitLab CI (primary desktop/mobile release pipeline)
├── .forgejo/workflows/ Forgejo Actions (CI, site deploy to Cloudflare Pages, payple-renew cron, portable/release)
├── docker-compose.yml, docker-compose.nas.yml
├── apps/api-server/Dockerfile, apps/admin/Dockerfile, apps/web/Dockerfile
-├── turbo.json, tsconfig.json, tsconfig.base.json, pnpm-workspace.yaml
+├── tsconfig.json, tsconfig.base.json
├── package.json monorepo root, npm workspaces
├── CLAUDE.md Claude-specific project rules
└── AGENTS.md Cross-agent entry: rules + map obligation (this map's anchor)
```
-Note: root `package.json` declares npm workspaces `apps/desktop`, `apps/web`, `apps/admin`, `packages/*`. `pnpm-workspace.yaml` also exists (`apps/*`, `packages/*`) but npm is the active toolchain. **Mobile is intentionally outside the workspace.**
+Note: root `package.json` is the only workspace manifest and declares npm workspaces `apps/desktop`, `apps/web`, `apps/admin`, `packages/*`. The unused `turbo.json` and `pnpm-workspace.yaml` manifests were removed in Wave 4. **Mobile is intentionally outside the workspace.**
---
@@ -58,13 +58,12 @@ Note: root `package.json` declares npm workspaces `apps/desktop`, `apps/web`, `a
| Node | 24.19.0 | `.nvmrc` |
| TypeScript | 5.7 | root `package.json` |
| .NET SDK | 10.0.300 (rollForward latestPatch) | `global.json` |
-| Deno | 2.8.1 | CI (`edge-functions-quality`) |
+| Deno | 2.8.1 | CI (`edge-functions`) |
| JDK | 17 | mobile CI |
| Electron | 33.4.11 | `apps/desktop/electron-builder.yml` |
| koffi | 3.3.1 | `apps/desktop/package.json` — FFI into user32/kernel32 for foreground window title/pid/exe/bounds (`utils/win32-foreground.ts`). Chosen over `get-windows` because that package needs an install script this repo does not run; koffi ships N-API 8 prebuilds as optional deps. `asarUnpack` covers `koffi`/`@koromix`. |
| uiautomation / comtypes | 2.0.29 / 1.4.17 | `apps/desktop/sidecar/requirements.txt` (Windows only) — UI Automation snapshot behind `GET /uia/focus` (`sidecar/uia_bridge.py`). Dev install: `apps/desktop/sidecar/.venv/Scripts/python.exe -m pip install uiautomation comtypes`. |
| React Native | 0.85 | `apps/mobile-rn/package.json` |
-| Turborepo | turbo.json tasks: build/typecheck/test/lint/dev | `turbo.json` |
---
@@ -78,7 +77,7 @@ When required sidecar changes ship, run `node --env-file-if-exists=.env scripts/
npm run dev # desktop dev (electron-vite)
npm run build # desktop production build
npm run build:admin # admin production build
-npm run build:all | npm run ci # scripts/ci/build-all.mjs
+npm run build:all | npm run ci # typecheck + test + desktop/admin/web production builds
npm run checksum # scripts/ci/generate-checksums.mjs
npm run version:check | version:sync
npm run release:metadata[:test]
@@ -86,22 +85,23 @@ npm run release:forgejo[:check] # canonical Forgejo publisher/feed
npm run release:tag # annotated/signed immutable release tag
npm run security:secrets[:test] # hardcoded-secret scanner
npm run check:desktop-renderer[:test] # built renderer pages reference only assets on disk
-npm run check:migrations[:test] # Supabase migration ordering, naming & optional remote drift check
+npm run check:migrations[:test] # Supabase migration filename/order/non-empty metadata checks; no DB replay or remote drift
npm run rebuild:app # rebuild better-sqlite3 in-place for Electron ABI
npm run rebuild:test # rebuild better-sqlite3 in-place for host Node ABI (Vitest)
+node scripts/ci/verify-native-abi.mjs --self-test # required packaged N-API prebuild missing/present fixture
node scripts/ci/sync-i18n-locales.mjs # synchronize 12 locales against ko/en SSOT
npm run test:e2e:red # content-report red e2e
npm run release:mobile:boundary[:test]
npm run release:mobile:config[:test]
npm run release:mobile:build-config:test
npm run release:play:assets[:test]
-npm run typecheck # all workspaces
+npm run typecheck # all workspaces; web/admin run `next typegen` before `tsc`
npm run test # all workspaces
npm run lint # eslint apps/desktop apps/web apps/admin packages
npm run format # prettier
npm run typecheck:mobile # apps/mobile-rn tsc (outside npm workspaces)
npm run lint:mobile # apps/mobile-rn eslint --max-warnings=0
-npm run test:mobile # apps/mobile-rn jest
+npm run test:mobile # apps/mobile-rn test:ci (jest --runInBand)
npm run verify:all # aggregate: workspaces + mobile (typecheck/lint/test)
```
@@ -110,10 +110,10 @@ Per-app commands that matter:
| App | Commands |
|---|---|
| desktop | `npm run dev --workspace=@d3ro/desktop`, `build`, `typecheck`, `test` (vitest), playwright e2e; local STT engine: `npm --prefix apps/desktop run sidecar:setup` then `sidecar:build` (PyInstaller → `sidecar-dist/sidecar`), full local Windows package: `npm --prefix apps/desktop run dist:win:full`; `setup:sox` re-downloads the bundled SoX |
-| mobile-rn | `npm run typecheck:mobile` / `lint:mobile` / `test:mobile` (root), or `npm --prefix apps/mobile-rn run lint/typecheck/test`; android gradle builds, Maestro E2E |
+| mobile-rn | `npm run typecheck:mobile` / `lint:mobile` / `test:mobile` (root; Jest uses `test:ci`/`--runInBand`), or `npm --prefix apps/mobile-rn run lint/typecheck/test`; android gradle builds, Maestro E2E |
| api-server | `dotnet build`, `dotnet test` (also `apps/api-server.Tests`) |
-| web | `next build`, playwright e2e in `apps/web/e2e` |
-| admin | `next build` (`build:admin`) |
+| web | `next typegen && tsc --noEmit`, `next build`, `test` (vitest, `apps/web/tests`), playwright e2e in `apps/web/e2e` |
+| admin | `next typegen && tsc --noEmit`, `next build` (`build:admin`) |
Desktop Vitest uses one `apps/desktop/vitest.config.ts` SSOT with mode-specific include globs:
@@ -155,11 +155,11 @@ See [`03-shared-packages.md`](./03-shared-packages.md). Summary:
| Package | Provides |
|---|---|
-| `@d3ro/core` | Domain types, `D3ROError`/`ErrorCode`, IPC channel SSOT, key-binding SSOT (`./keybinding`), constants, `crypto-license`, `pii-redactor`, `secure-memory`, `supabase-config`, `meeting-markdown`, `markdown-to-docx`; has vitest tests (`packages/core/vitest.config.ts`, `npm run test --workspace=@d3ro/core`) |
+| `@d3ro/core` | Domain types, `D3ROError`/`ErrorCode`, IPC channel SSOT, key-binding SSOT (`./keybinding`), plan/quota catalog including `knowledge_embedding`, constants, `crypto-license`, `pii-redactor`, `secure-memory`, `supabase-config`, `meeting-markdown`, `markdown-to-docx`; Deno consumes the generated contract checked by `contract:check`; has vitest tests (`packages/core/vitest.config.ts`, `npm run test --workspace=@d3ro/core`) |
| `@d3ro/ui` | Theme tokens, CSS vars, MUI DS components (web/desktop) |
| `@d3ro/ui-native` | RN design system (MetalCard, PhosphorText, Led, PhysicalButton, WaveBars, …) |
-| `@d3ro/i18n` | 12 locales, `I18nProvider`, `t()`, date/number/relative formatters |
-| `@d3ro/api-client` | Supabase browser/server clients, meetings/history/usage/transcribe wrappers, shared types; has vitest tests |
+| `@d3ro/i18n` | 12 locales / 2,742 parity-checked keys, `I18nProvider`, `t()`, date/number/relative formatters; includes native updater-dialog keys |
+| `@d3ro/api-client` | Supabase browser/server clients, meetings/history/usage/transcribe wrappers, canonical push-token/provider + push/quota RPC types; has vitest tests |
---
@@ -174,7 +174,7 @@ See [`03-shared-packages.md`](./03-shared-packages.md). Summary:
Stages `validate → test → build → e2e → package → publish → deploy`. Primary pipeline for desktop Windows/macOS releases (Forgejo Generic Registry is the canonical updater feed; GitLab project 1172 is a legacy mirror) and production mobile releases (`mobile-production-release`, manual/protected). Admin NAS deploy job is intentionally **disabled**. `package-windows`/`package-macos` build the faster-whisper sidecar (`sidecar:setup` → `sidecar:build`) and run `scripts/ci/verify-sidecar-bundle.mjs` before electron-builder, so a release can never ship without the local STT engine. Every pipeline that runs `npm run build --workspace=@d3ro/desktop` (`.forgejo` CI/release/portable) then runs `scripts/ci/verify-desktop-renderer-bundles.mjs`, which fails packaging when a renderer page references an asset the build did not emit (GAP-INFRA-05).
### Forgejo Actions (`.forgejo/workflows/`)
-`ci.yml` — CI is now Forgejo-only (`.github/workflows` deleted 2026-09-26, Wave 3, dc43884). Jobs: `quality` (`version:check`, `contract:check`, `release:metadata:test`, secret scan, mobile release/config/build-config self-tests, Play asset contract, lint, typecheck, Vitest), `build-validation`, `mobile-quality`, `edge-functions` (Deno), `api-server-tests`.
+`ci.yml` — CI is now Forgejo-only (`.github/workflows` deleted 2026-09-26, Wave 3, dc43884). Jobs: `quality` (`version:check`, `contract:check`, `release:metadata:test`, migration checker self-test + actual filename/order/non-empty check, secret scan, mobile release/config/build-config self-tests, Play asset contract, lint, typecheck, Vitest), `build-validation` (desktop renderer verification + admin + web production builds), `mobile-quality`, `edge-functions` (Deno), `api-server-tests`. Web/admin typecheck runs Next 16 `typegen` before `tsc`, so a clean checkout generates and checks route/root-param declarations instead of relying on a prior dev/build artifact. The migration checks are file metadata/order gates only; Supabase replay, shadow DB, and remote drift remain separate runtime/integration gates. A separate isolated local run on 2026-11-04 applied all 73 migrations from empty and after reset, then returned an empty `pg-delta --strict-coverage` shadow diff; that runtime gate is not yet part of CI and says nothing about linked remote drift.
`payple-renew.yml` — daily cron (+ manual dispatch) → `payple-renew` edge function; ported from the never-run `.github/workflows/payple-renew.yml` because the repository has no GitHub remote. Requires Forgejo secrets `SUPABASE_URL`, `CRON_SECRET`. 2026-09-26~10-11 `SUPABASE_URL` 시크릿이 로컬 주소(`127.0.0.1:55321`)라 한 번도 성공하지 못했다(GAP-OPS-03).
@@ -207,9 +207,9 @@ Public endpoints (production): `https://d3ro.chanpaca.net` — **랜딩/다운
## 7. `server/supabase` (backend)
-- `config.toml` — project `d3ro-voice`, ports 55321-55324, DB major 17, auth redirects (localhost, `d3ro.chanpaca.net`, `d3ro-voice://auth-callback`), providers Google/GitHub/Apple.
-- `migrations/` — **63 SQL migrations** (schema, RLS, auth triggers, storage, team invites, knowledge/pgvector, push outbox, Payple billing (legacy Stripe columns/provider values kept for history), admin roles, mobile platform/monetization, atomic command reorder, device revocation, content reporting, audit log, meeting documents, STT quota reservations, ad reward replay protection, team activity feed).
-- `functions/` — **~24 Deno Edge Functions** (`stt-proxy`, `llm-proxy`, `content-report`, `generate-meeting-document`, `embed-chunks`, `search-knowledge`, `realtime-token`, `team-invite`, `team-accept`, `send-push`, `account-delete`, `admin-users`, `admin-subscriptions`, `admin-payments`, `admin-audit-log`, billing `billing-catalog`/`payple-checkout`/`payple-manage`/`payple-renew`/`payple-webhook`, `iap-verify`, `admob-ssv`, `google-play-rtdn`; Stripe functions removed 2026-09-26). Shared contracts in `functions/_shared/` — push transports now include `webpush.ts` (VAPID + RFC 8291) and `apns.ts` (.p8 token) alongside FCM. CI (`edge-functions-quality`) runs `deno check` + `deno test` and also the Cloudflare worker drain test.
+- `config.toml` — project `d3ro-voice`, ports 55321-55324, DB major 17, Supabase CLI 3.x `[local_smtp]`, auth redirects (localhost, `d3ro.chanpaca.net`, `d3ro-voice://auth-callback`), providers Google/GitHub/Apple. `audio-purge` has an explicit function stanza with gateway JWT verification disabled because its handler verifies the exact pg_cron service credential. An isolated local stack proved missing/non-service key 401, service 200, and pg_cron/Vault/pg_net removal of the queue row, `audio_files` row, and Storage object; deployment and the production schedule remain unverified.
+- `migrations/` — **73 SQL migrations** (schema, RLS, auth triggers, storage, team invites, knowledge/pgvector, push outbox, Payple billing (legacy Stripe columns/provider values kept for history), admin roles, mobile platform/monetization, atomic command reorder, device revocation, content reporting, audit log, meeting documents, STT quota reservations, ad reward replay protection, team activity feed).
+- `functions/` — **24 Deno Edge Functions** (`stt-proxy`, `llm-proxy`, `content-report`, `generate-meeting-document`, `embed-chunks`, `search-knowledge`, `realtime-token`, `team-invite`, `team-accept`, `send-push`, `audio-purge`, `account-delete`, `admin-users`, `admin-subscriptions`, `admin-payments`, `admin-audit-log`, billing `billing-catalog`/`payple-checkout`/`payple-manage`/`payple-renew`/`payple-webhook`, `iap-verify`, `admob-ssv`, `google-play-rtdn`; Stripe functions removed 2026-09-26). Shared contracts in `functions/_shared/` — push transports now include `webpush.ts` (VAPID + RFC 8291) and `apns.ts` (.p8 token) alongside FCM. CI (`edge-functions`) runs `deno check` + `deno test` and also the Cloudflare worker drain test.
- `tests/` — integration/E2E for content report, mobile platform/recording/reward-race, payments, mobile release preflight, push, team push security, STT quota.
Full detail: [`09-supabase-backend.md`](./09-supabase-backend.md).
@@ -219,11 +219,12 @@ Full detail: [`09-supabase-backend.md`](./09-supabase-backend.md).
## 8. `scripts/` groups
- **CI (`scripts/ci/`, 33 files):** build/version/release (`build-all`, `sync-version`, `generate-checksums`, `verify-release-metadata`, `create-release-tag`, `extract-release-notes`), security (`check-no-hardcoded-secrets`), mobile release gates (`verify-mobile-release-boundary/-config/-build-config`, `verify-android-artifact/-app-links`, `verify-play-store-assets`, `prepare-whisper-model`, `create-mobile-release-evidence`, `prepare-mobile-release-publication`, emulator/CSPRNG gates), keys (`create-desktop-license-keypair`, `create-release-evidence-key`, etc.), publish (`publish-forgejo-release` canonical, `publish-gitlab-release` mirror; the legacy `sync-and-publish-forgejo-release`/`upload-asset-to-forgejo-release` scripts were deleted 2026-09-26, Wave 3, cd9d199), env/tooling (`bootstrap-linux-toolchain.sh`, `audit-nas-stt-config.ps1`, mobile local E2E scripts).
+- **Packaged native gate:** `verify-native-abi.mjs` rejects a packaged `better_sqlite3.node` that the host Node runtime can load (wrong ABI) and requires the target-specific `uiohook-napi/prebuilds/-/uiohook-napi.node`. `--self-test` proves the missing/present N-API fixture; relative and absolute `--dir` inputs resolve to the same package. `build-desktop-installer.mjs` and `build-portable.mjs` repair only the better-sqlite3 ABI, verify both native contracts, and require `resources/app-update.yml` before publication.
- **Deploy/release:** `deploy-nas.ps1/.sh`, `nas-control.sh`, `publish-gh.ps1`, `gen-keystore.js` (`deploy-site-to-nas.js` deleted 2026-09-26, Wave 3, cd9d199 — site deploy is Cloudflare Pages only).
- **Android artifact verification (2026-11-01):** `verify-android-artifact.mjs` parses both legacy `Signer #1` and Build Tools 37 `V2/V3.x Signer` certificate output. Self-test and the actual universal E2E APK verification pass with Build Tools `37.0.0`.
- **GCP/Google OAuth automation + inspection (~70 `*.mjs`):** `auto-configure-oauth`, `automate-google-oauth`, `setup-consent`, `create-*-client`, `check-*`, `inspect-*` — mostly one-off/browser-driven console automation.
- **AdMob console automation:** `admob-probe.mjs` (read-only login/app/ad-unit probe), `admob-login.mjs` + `run-admob-login.bat` (one interactive headful Chrome login into a persistent profile), `admob-automate.mjs` (dry-run by default; `--apply` creates/verifies banner+rewarded units and reports Play-store link). Uses `playwright` with `channel: 'chrome'` and the gitignored `.chrome-playwright-profile`.
-- **E2E / verification:** `e2e-desktop-*.js`, `real-app-multi-tab-e2e.js`, `test-and-capture-all-10-ad-services.js`, `verify-live-production-d3ro.js`.
+- **E2E / verification:** `test-and-capture-all-10-ad-services.js`, `verify-live-production-d3ro.js`. The old ad-hoc `e2e-desktop-*.js` / `real-app-multi-tab-e2e.js` / `run_e2e_*.cjs` runners were deleted 2026-11-04 (machine-specific paths, no references); Playwright specs under `apps/desktop/tests/e2e` are the E2E path.
- **Screenshots/captures:** `capture-*.js`.
- **Forgejo ops:** `check-forgejo-actions-runs.js`, `capture-forgejo-*.js`.
@@ -235,7 +236,7 @@ Full detail: [`09-supabase-backend.md`](./09-supabase-backend.md).
| File | Purpose |
|---|---|
-| `release/product-version.json` | version `1.9.0`, `androidVersionCode`/`iosBuildNumber` `1090000`, releaseDate `2026-09-27`, desktop license keyId |
+| `release/product-version.json` | version `1.16.1`, `androidVersionCode`/`iosBuildNumber` `1160100`, releaseDate `2026-11-04`, desktop license keyId |
| `release/android-release-identity.json` | package `com.d3ro.voice`, Play app ID, app-signing SHA-256, upload cert SHA-256, evidence keyId, AdMob unit IDs |
| `release/desktop-license-public.pem` | Ed25519 public key for desktop offline licenses |
| `release/mobile-release-evidence-public.pem` | Ed25519 public key for mobile release evidence |
@@ -256,11 +257,12 @@ Version sync is enforced by `scripts/ci/sync-version.mjs` and `verify-release-me
- `resources/ffmpeg/` — optional bundled ffmpeg (CI or manual); `getFfmpegPath()` also resolves the `@ffmpeg-installer/ffmpeg` binary from `app.asar.unpacked`.
- `apps/desktop/sidecar-dist/` — PyInstaller sidecar bundle consumed by `extraResources` (gitignored; built by `npm --prefix apps/desktop run sidecar:build`).
- `resources/icons/` — empty; electron-builder falls back to `build/icon.ico|png`.
-- Desktop tests: `apps/desktop/tests/` (vitest unit + playwright e2e), `apps/desktop/test-results/`.
+- Desktop tests: `apps/desktop/tests/` — `unit/`, `main/`, `red/`, `shared/`, `integration/`, `eval/` run under Vitest; `e2e/` holds Playwright specs plus the shared `e2e/support/electron-app.ts` fixture (per-test temp user-data dir). Artifacts in `apps/desktop/test-results/`.
+- Test taxonomy + hygiene gate: `docs/tdd-red/06-repo-application.md`. `npm run test:hygiene` (+ `:test`) rejects `.only`, reason-less `.skip()`, trivial assertions, `isVisible()`-gated assertions, machine-specific paths, `waitForTimeout`, and `.e2e.test.ts` names; wired into CI `quality`.
- Mobile tests: `apps/mobile-rn/__tests__/` (57 suites / 353 tests per mobile SSOT), `.maestro/` + `.maestro-output/` E2E evidence. Note: a full parallel Jest run can hit the 5s render timeout on slow machines; re-run the failing spec in isolation before treating it as a regression.
-- Web tests: `apps/web/e2e/` (playwright).
+- Web tests: `apps/web/tests/` (vitest pure-logic contracts: billing catalog, Web Push client, web STT client — now part of root `npm test`) and `apps/web/e2e/` (playwright: `smoke.spec.ts` owns the unauthenticated surface contract; billing/payple/dashboard/history are fixture-based browser journeys). Web declares its own `@playwright/test` + `vitest` devDeps (2026-11-04) instead of relying on the desktop workspace's hoisted copies.
- API tests: `apps/api-server.Tests/` (xUnit).
-- Root: `tests/e2e/`, `test-results/.last-run.json`.
+- Root: `test-results/.last-run.json` (no root-level e2e suite).
---
@@ -282,7 +284,7 @@ See [`11-gap-backlog.md`](./11-gap-backlog.md) for the maintained list (`INFRA-*
| Payple 정기 갱신 cron | `CRON_SECRET` | Supabase 함수 시크릿 `CRON_SECRET`, Forgejo 시크릿 `CRON_SECRET` |
| NAS 배포(ssh 별칭 `yunchan-nas`) | `NAS_HOST`, `NAS_USER`, `NAS_SSH_PORT`, `NAS_DEPLOY_PATH` | — |
| NAS compose 필수 값 | `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, `ADMIN_BOOTSTRAP_TOKEN`, `API_SERVER_URL` 외 | NAS `/volume1/docker/d3ro/.env` |
-| 웹앱 이미지 build arg | `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY` (`NEXT_PUBLIC_PAYPLE_CLIENT_KEY`는 보류, GAP-BILL-02) | — |
+| 웹앱 이미지 build arg | `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`; 선택적 `NEXT_PUBLIC_PAYPLE_CLIENT_KEY`와 `NEXT_PUBLIC_VAPID_PUBLIC_KEY` (`WEBPUSH_VAPID_PUBLIC_KEY`와 같은 공개키). VAPID 공개키 누락 시 알림 UI는 unavailable로 fail-closed | `.env` / NAS build environment; `NEXT_PUBLIC_*`는 이미지 build-time에 고정 |
| Forgejo API | `FORGEJO_TOKEN` | Forgejo 시크릿 `FORGEJO_TOKEN` |
- 공개 라우팅: `d3ro.chanpaca.net` → 브리지 워커 → `/app`·`/api`·`/health`는 터널 kd-nas(NAS 3002·5050), 그 밖은 Pages `d3ro`. 터널 ingress `d3ro.chanpaca.net` path `^/app` → `http://192.168.0.39:3002`.
diff --git a/docs/map/03-shared-packages.md b/docs/map/03-shared-packages.md
index de84c42..e216e60 100644
--- a/docs/map/03-shared-packages.md
+++ b/docs/map/03-shared-packages.md
@@ -26,6 +26,7 @@ The canonical place for types and cross-surface logic. Both desktop and web/mobi
| PII | `pii-redactor`, `secure-memory` | Redaction + secure memory helpers |
| Supabase config | `supabase-config` | Shared Supabase config shape |
| Entitlement | `./entitlement` | `EntitlementTier`, `AdminRole`, `EntitlementSnapshot`, `resolveEntitlement`, `normalizeEntitlementTier`/`normalizeAdminRole` — canonical tier/role contract across Supabase, desktop license, and .NET |
+| Plan catalog | `./plan-catalog` | Tier/price/quota SSOT. `knowledge_embedding` is explicit per tier (Free 5,000/week; Pro 50,000/day; Pro+ 150,000/day; Team 300,000/day; Enterprise unlimited), generated into `server/supabase/functions/_shared/core-contract.generated.ts`, and guarded by `contract:check` |
| Doc utils | `./utils/meeting-markdown`, `./utils/markdown-to-docx` | Meeting Markdown export + DOCX generation (dep: `docx`) |
**When to change:** new cross-surface type, new error code, new IPC channel, license format. Add here first, then consume.
@@ -63,7 +64,7 @@ App-specific `ScreenHeader`, `RecordFab`, and `UnifiedSearchResultRow` stay unde
| Provides | Notes |
|---|---|
-| 12 locales | `ko` (master), `en`, `ja`, `zh`, `zh-TW`, `es`, `fr`, `de`, `pt`, `ru`, `vi`, `th` in `src/locales/` |
+| 12 locales | `ko` (master), `en`, `ja`, `zh`, `zh-TW`, `es`, `fr`, `de`, `pt`, `ru`, `vi`, `th` in `src/locales/`; 2,742 parity-checked keys, including the 16 native `update.dialog.*` keys |
| Type-safe keys | `TranslationKey` derived from `ko.json` |
| React context | `I18nProvider`, `useI18n`, `TFunction` |
| Fallback chain | locale → `en` → `ko` → key |
@@ -86,9 +87,9 @@ Electron-independent. Rule: no hardcoded Korean/English strings in UI; use `t()`
| `transcribe` | STT calls |
| `supabase-browser` | Browser client (`getSupabaseBrowserClient`, `isSupabaseConfigured`) |
| `supabase-server` | Server client (`createSupabaseServerClient`) |
-| `types` | Shared DB/domain types — **canonical; do not redefine table types per app** |
+| `types` | Shared DB/domain types — **canonical; do not redefine table types per app**. Includes `PushProvider`, device-bound `PushToken`, `push_tokens` row/insert/update shapes, `register_push_registration`/`unregister_push_registration`, and period-aware `consume_quota` RPC contracts |
-Deps: `@d3ro/core`, `@supabase/supabase-js`; optional peer `@supabase/ssr`. Tests: `__tests__/` (client, transcribe, types) via vitest.
+Deps: `@supabase/supabase-js`; optional peer `@supabase/ssr`. The unused `@d3ro/core` dependency was removed in Wave 4. Tests: `__tests__/` (client, transcribe, types) via vitest.
Consumed by `apps/web`, `apps/admin` (via re-exports), `apps/mobile-rn`, and desktop cloud paths.
@@ -100,7 +101,7 @@ Consumed by `apps/web`, `apps/admin` (via re-exports), `apps/mobile-rn`, and des
@d3ro/i18n (standalone)
@d3ro/ui → @d3ro/core
@d3ro/ui-native(standalone, peers react-native)
-@d3ro/api-client → @d3ro/core
+@d3ro/api-client(standalone; depends on Supabase SDK)
@d3ro/core (standalone)
```
diff --git a/docs/map/05-web-app.md b/docs/map/05-web-app.md
index 37a7985..1c1cd84 100644
--- a/docs/map/05-web-app.md
+++ b/docs/map/05-web-app.md
@@ -43,13 +43,12 @@ Root layout: `ThemeProvider → I18nProvider → AuthProvider`.
|---|---|
| `actions/` | `action-runner.tsx` (LLM parse → action: create_meeting/search_knowledge/create_memo/send_team_invite) |
| `record/` | `mic-recorder.tsx` (MediaRecorder + level analyser → `transcribeWebAudio`) |
-| `dashboard/` | `meetings-trend-chart.tsx` (recharts) |
| `billing/` | `billing-checkout-options`, `payple-checkout-button`, `payple-client`, `payple-manage-button` |
| `meetings/` | `document-editor`, `generate-document-button`, `live-transcript-list` (Realtime), `markdown-preview` (Mermaid), `meeting-audio-player` (signed URL), `memo-form` |
| `chat/` | `chat-panel.tsx` |
| `teams/` | `create-team-form`, `invite-member-form`, `activity-feed` (team notes + realtime) |
| `knowledge/` | `add-knowledge-form` (text or `.txt`/`.md` file, newline-aware chunking, `embed-chunks` on submit), `knowledge-search` (semantic via `search-knowledge`) |
-| `layout/` | `sidebar.tsx` (nav, theme selector, logout, i18n) |
+| `layout/` | `sidebar.tsx` (nav, theme selector, logout, i18n) + `web-push-control.tsx` (permission/subscription status and explicit opt-in/out switch) |
| `providers/` | `auth-provider`, `i18n-provider`, `theme-mode-context`, `theme-provider` |
---
@@ -65,13 +64,19 @@ Root layout: `ThemeProvider → I18nProvider → AuthProvider`.
| `history-client.ts` | History list/get/update/delete, revision-safe |
| `supabase-browser.ts` | Re-export `@d3ro/api-client/supabase-browser` |
| `supabase-server.ts` | Next `cookies()` wrapper |
+| `web-device.ts` | Stable browser installation identity + active `platform='web'` device lookup/create/check-in; revoked rows are never resurrected |
+| `web-push.ts` | Web Push service-worker/VAPID subscribe/unsubscribe helper. Requires a valid active `deviceId`, persists only through register/unregister RPCs, rolls back a failed registration, re-registers an existing browser subscription before reporting it connected, and runs bounded server cleanup independently from local unsubscribe |
+| `web-push-session.ts` | Production orchestration boundary used by the sidebar and logout: user-gesture permission → device registration → subscription, plus per-user disabled intent, fail-closed reconciliation, and non-blocking logout cleanup |
| `web-stt-client.ts` | Web STT via `stt-proxy`, 25 MB limit, `WebSttError` codes |
---
## 4. Tests
-Playwright specs in `apps/web/e2e/`: billing, payple-checkout, dashboard-dictionary-commands, history, web-stt-client, smoke.
+Two layers:
+
+- **Vitest** (`apps/web/tests/`, `npm --prefix apps/web run test`, part of root `npm test`): pure-logic contracts — `billing-catalog`, `web-push` (device/RPC/rollback/reconciliation/logout, 17 cases), `web-stt-client`.
+- **Playwright** (`apps/web/e2e/`): `smoke.spec.ts` (unauthenticated surface + fail-closed redirects + `/download` handoff), `billing`, `payple-checkout`, `dashboard-dictionary-commands`, `history` (fixture-based browser journeys).
---
@@ -84,4 +89,5 @@ Playwright specs in `apps/web/e2e/`: billing, payple-checkout, dashboard-diction
- Action runner team-invite uses a manual redirect safety path instead of a live invite (`action-runner.tsx`).
- `/download` shows "artifact not yet published" for the current desktop release.
- Knowledge file upload, semantic search, dictionary import/export, and the team activity feed are now implemented (`[x]` in the catalog).
+- **2026-11-04 Wave 4 hygiene:** Removed the unreferenced dashboard trend chart and the web `recharts` dependency. Web Push now has a production sidebar opt-in/out flow, stable web-device registration, device-bound register/unregister RPCs, disabled-intent reconciliation, bounded local/server cleanup, logout-independent sign-out, and a Docker-copied service worker. An isolated local browser run with ephemeral VAPID proved one active web device, one `webpush` token, one pending outbox attempt, a completed drain, and a `delivered` provider result; that result proves provider acceptance, not service-worker/browser receipt. A later production-standalone run built and served successfully but timed out during throwaway login navigation before the dashboard, so production-rendered 1440/390, accessibility-tree, hit-target, permission/subscription, and receipt gates remain open. No production secrets or deployment were changed.
- **2026-10-28 designpaca audit (`SHELL-15`):** All 15 routes and shared components aligned with `design.md` v4 ("조용한 계기"): undefined `--d3-text-inverse` replaced with `--d3-accent-ink`, minimum font size raised to `11px` (`0.6875rem`), `uppercase` and positive `letterSpacing` removed from Korean UI copy, raw `monospace` replaced with `var(--d3-font-mono)`, single `component="h1"` hierarchy enforced per route, and native form controls equipped with `:focus-visible` rings and `