Compare commits

..

3 commits

Author SHA1 Message Date
Yun Chan
a21de78303 chore(release): v1.16.2
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Failing after 1m6s
ci / 워크스페이스 빌드 검증 (push) Has been skipped
ci / 모바일 린트·타입·Jest (push) Successful in 48s
ci / Supabase Edge Functions + Cloudflare Worker (push) Successful in 24s
ci / .NET API 서버 테스트 (push) Successful in 20s
deploy-site / deploy (push) Successful in 54s
portable-unsigned / portable-windows (push) Failing after 14m51s
release / release-windows (push) Successful in 19m48s
2026-11-05 21:59:49 +09:00
Yun Chan
7fe49c437e chore: land in-progress workspace changes before 1.16.2
The tree carried uncommitted work from several areas (web push, mobile
screens, admin charts, test-hygiene cleanup, CI and map docs). It is landed
as one commit so the release pipeline can start from a clean tree; the
desktop transcript-correction behaviour shipped in the previous commit and
is unchanged here.
2026-11-05 21:58:44 +09:00
Yun Chan
9c2b6a9782 feat(meeting): correct transcripts with vocabulary learned from typing
Meeting and caption transcription never used what the app had already
learned: speech recognition ran with a fixed Korean prompt, the refine
prompt had no glossary, refined lines stopped inside the caption service,
and the saved transcript was a raw join of segments. Names and jargon the
user types every day were therefore re-mangled on every recording.

The learned corpus (user dictionary plus personal phrases) now feeds one
glossary that biases recognition, fixes mistyped words deterministically
right after each line is finalized, and is handed to the local model when
it polishes a line. Refined lines also reach the meeting transcript and
screen through a new segment-updated event.

Corrections never touch words the user actually wrote, refuse ties between
equally likely candidates, and keep particles intact.
2026-11-05 21:58:28 +09:00
180 changed files with 4940 additions and 4628 deletions

View file

@ -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' 프로세스와의 식별자 충돌을 방지한다.

View file

@ -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. 커밋·푸시는 사용자가 명시적으로 요청한 경우에만 실행
유저가 중단을 요청하지 않는 한 끝까지 진행.

View file

@ -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차 완료 후 발사

View file

@ -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=

View file

@ -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

View file

@ -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

View file

@ -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).

View file

@ -7,15 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
- Prevent fast Han/Eng auto-correction from interleaving with the next keystroke; defer corrections during continuous bursts and apply the current trailing correction region together after typing pauses.
### Planned
- macOS / Linux support
- Additional Whisper model management UI
- Plugin system for custom pipelines
## [1.16.2] - 2026-11-05
> Published from an annotated tag. Installer and update metadata are served by the
> canonical Forgejo feed; no binaries are committed to this repository.
### Added
- Meeting and live-caption transcription now use the vocabulary the app learned from your typing: dictionary words, pronunciations and frequently typed terms bias speech recognition before it runs, fix mistyped words as soon as each line is finalized (no model required), and are given to the local model when it polishes a line.
- Polished caption lines now reach the meeting transcript and the meeting screen instead of stopping inside the caption service, so the saved transcript carries the corrected text.
### Fixed
- Learned vocabulary used to feed typing suggestions only, which is why transcripts kept mangling names and jargon the app already knew.
## [1.16.1] - 2026-11-04
> Published from an annotated tag. Installer and update metadata are served by the

11
CODEOWNERS Normal file
View file

@ -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

View file

@ -3,7 +3,7 @@
"info": {
"title": "D3RO-VOICE Admin API",
"description": "Admin CRM Edge Functions for user management, subscription CRUD, payment history, and audit logs.",
"version": "1.16.1"
"version": "1.16.2"
},
"servers": [
{

View file

@ -1,13 +1,13 @@
{
"name": "@d3ro/admin",
"version": "1.16.1",
"version": "1.16.2",
"private": true,
"description": "D3RO Voice Admin CRM — SaaS 관리 도구",
"scripts": {
"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",

View file

@ -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 (
<Box sx={{ width: '100%', height: 250 }}>
<ResponsiveContainer>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" stroke={d3roPalette.border.subtle} />
<XAxis
dataKey="date"
tick={{ fill: d3roPalette.text.muted, fontFamily: d3roFontMono, fontSize: 11 }}
tickFormatter={(val: string) => val.slice(5)}
/>
<YAxis tick={{ fill: d3roPalette.text.muted, fontFamily: d3roFontMono, fontSize: 11 }} />
<Tooltip
contentStyle={{
background: d3roPalette.bg.card,
border: `1px solid ${d3roPalette.border.default}`,
fontFamily: d3roFontMono,
fontSize: 11,
color: d3roPalette.text.primary,
}}
/>
<Line
type="monotone"
dataKey="active_users"
stroke={d3roPalette.accent.main}
strokeWidth={2}
dot={{ fill: d3roPalette.accent.main, r: 3 }}
name="Active Users"
/>
</LineChart>
</ResponsiveContainer>
</Box>
)
}

View file

@ -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<string, string> = {
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<string, Record<string, string | number>>()
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 (
<Box sx={{ width: '100%', height: 300 }}>
<ResponsiveContainer>
<BarChart data={chartData}>
<CartesianGrid strokeDasharray="3 3" stroke={d3roPalette.border.subtle} />
<XAxis
dataKey="date"
tick={{ fill: d3roPalette.text.muted, fontFamily: d3roFontMono, fontSize: 11 }}
tickFormatter={(val: string) => val.slice(5)}
/>
<YAxis tick={{ fill: d3roPalette.text.muted, fontFamily: d3roFontMono, fontSize: 11 }} />
<Tooltip
contentStyle={{
background: d3roPalette.bg.card,
border: `1px solid ${d3roPalette.border.default}`,
fontFamily: d3roFontMono,
fontSize: 11,
color: d3roPalette.text.primary,
}}
/>
<Legend wrapperStyle={{ fontFamily: d3roFontMono, fontSize: 11 }} />
{features.map((feature) => (
<Bar
key={feature}
dataKey={feature}
stackId="a"
fill={FEATURE_COLORS[feature] ?? DEFAULT_COLOR}
/>
))}
</BarChart>
</ResponsiveContainer>
</Box>
)
}

View file

@ -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 (
<Box sx={{ width: '100%', height: Math.max(250, data.length * 28) }}>
<ResponsiveContainer>
<BarChart data={chartData} layout="vertical">
<CartesianGrid strokeDasharray="3 3" stroke={d3roPalette.border.subtle} />
<XAxis
type="number"
tick={{ fill: d3roPalette.text.muted, fontFamily: d3roFontMono, fontSize: 11 }}
/>
<YAxis
type="category"
dataKey="name"
width={100}
tick={{ fill: d3roPalette.text.muted, fontFamily: d3roFontMono, fontSize: 11 }}
/>
<Tooltip
contentStyle={{
background: d3roPalette.bg.card,
border: `1px solid ${d3roPalette.border.default}`,
fontFamily: d3roFontMono,
fontSize: 11,
color: d3roPalette.text.primary,
}}
/>
<Bar dataKey="total" fill={d3roPalette.accent.main} name="Total Calls" />
</BarChart>
</ResponsiveContainer>
</Box>
)
}

View file

@ -2,7 +2,7 @@
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Version>1.16.1</Version>
<Version>1.16.2</Version>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

View file

@ -1,6 +1,6 @@
{
"name": "@d3ro/desktop",
"version": "1.16.1",
"version": "1.16.2",
"productName": "d3ro-voice",
"description": "로컬 AI 음성 어시스턴트 (Electron)",
"main": "./out/main/index.js",

View file

@ -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);
});

View file

@ -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);
});

View file

@ -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 (!updateDialogPreviewRequested) {
if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [path.resolve(process.argv[1])])
}
} else {
} else {
app.setAsDefaultProtocolClient(PROTOCOL)
}
}
/**
@ -130,7 +134,10 @@ async function handleDeepLink(url: string): Promise<void> {
}
// 단일 인스턴스 잠금 (테스트 모드에서는 다중 인스턴스 허용)
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()
})

View file

@ -14,6 +14,7 @@ import { getLocalLLMService } from './LocalLLMService'
import { getHistoryService } from './HistoryService'
import { configGet } from './ConfigService'
import { buildCaptionRefinePrompt } from './llm-prompts'
import { getTranscriptGlossaryService } from './TranscriptGlossaryService'
import { StreamingCaptionTrack, type CaptionTranscription } from './caption/StreamingCaptionTrack'
import { CaptionAudioSources } from './caption/CaptionAudioSources'
import { acceptCaptionRefinement } from '@d3ro/core/caption-streaming'
@ -97,6 +98,8 @@ const DEFAULT_START_OPTIONS: ResolvedStartOptions = {
interface CaptionServiceEvents {
'state-changed': (state: CaptionState) => void
'segment': (segment: CaptionSegment) => void
/** 다듬기(학습 어휘 교정·LLM 교열)로 확정 줄의 텍스트가 바뀌었다 */
'segment-updated': (update: { id: string; text: string }) => void
'delta': (data: { text: string; isFinal: boolean }) => void
'session-saved': (summary: CaptionSessionResult) => void
/**
@ -211,7 +214,8 @@ class CaptionService extends EventEmitter {
this._segments = []
this._refineQueue = []
this._sessionLanguage = null
// 초기 컨텍스트 힌트 — Whisper 첫 청크 환각 방지
// 초기 컨텍스트 힌트 — Whisper 첫 청크 환각 방지.
// 학습 어휘 힌트는 _transcribe 가 매 인식마다 덧붙인다(트랙 문맥에 섞이면 중복된다).
const lang = configGet('sttLanguage') as string | undefined
const initialContext = lang === 'ko' ? '다음은 한국어 대화입니다.' : ''
@ -467,7 +471,8 @@ class CaptionService extends EventEmitter {
const language = configured === 'auto' ? (this._sessionLanguage ?? 'auto') : configured
const result = await getLocalSTTService().transcribe(audio, {
language,
initialPrompt: opts.initialPrompt,
// 학습 어휘 힌트는 매 인식마다 붙인다 — rolling context 가 잘려도 용어 편향이 유지된다.
initialPrompt: getTranscriptGlossaryService().sttHint(opts.initialPrompt),
vadFilter: true,
partial: opts.partial,
modelId: this._captionModelId ?? undefined,
@ -493,7 +498,14 @@ class CaptionService extends EventEmitter {
this._sendToMainWindow(IPC_CHANNELS.CAPTION.DELTA, delta)
}
private _emitFinal(text: string, source: 'mic' | 'system'): void {
private _emitFinal(rawText: string, source: 'mic' | 'system'): void {
// 학습 어휘(사전 + 개인 문구)로 먼저 되돌린다 — LLM 이 꺼져 있어도 용어는 고쳐진다.
const corrected = getTranscriptGlossaryService().correct(rawText)
const text = corrected.text.trim()
if (!text) return
if (corrected.corrections.length > 0) {
logger.info(`자막 학습 어휘 교정 ${corrected.corrections.length}건 (${source})`)
}
const segment: CaptionSegment = {
id: crypto.randomUUID(),
text,
@ -534,7 +546,12 @@ class CaptionService extends EventEmitter {
const index = this._segments.findIndex((item) => item.id === segment.id)
if (index === -1) return
const previous = this._segments.slice(Math.max(0, index - 2), index).map((item) => item.text)
const { systemPrompt, text } = buildCaptionRefinePrompt({ text: segment.text, previous })
const glossary = getTranscriptGlossaryService().promptSection()
const { systemPrompt, text } = buildCaptionRefinePrompt({
text: segment.text,
previous,
...(glossary ? { glossary } : {}),
})
try {
const result = await getLocalLLMService().generate(text, {
systemPrompt,
@ -544,17 +561,24 @@ class CaptionService extends EventEmitter {
})
const refined = acceptCaptionRefinement(segment.text, result.text)
if (!refined) return
const current = this._segments.find((item) => item.id === segment.id)
if (!current) return
current.text = refined
const update = { id: segment.id, text: refined }
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
// 모델이 용어를 다른 표기로 되돌렸을 수 있다 — 정본 표기를 마지막에 다시 강제한다.
this._replaceSegmentText(segment.id, getTranscriptGlossaryService().correct(refined).text)
} catch (err) {
logger.debug(`자막 다듬기 건너뜀: ${err instanceof Error ? err.message : String(err)}`)
}
}
/** 확정 줄 텍스트를 바꾸고 오버레이·메인 창·회의 모드에 알린다. */
private _replaceSegmentText(segmentId: string, text: string): void {
const current = this._segments.find((item) => item.id === segmentId)
if (!current || current.text === text) return
current.text = text
const update = { id: segmentId, text }
sendToCaptionOverlay(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
this._sendToMainWindow(IPC_CHANNELS.CAPTION.SEGMENT_UPDATED, update)
this.emit('segment-updated', update)
}
// ── 내부: 세션 저장 ──
private _saveSession(persist: boolean): CaptionSessionResult | null {

View file

@ -9,6 +9,7 @@ import { getDatabase } from '../db'
import { dictionary } from '../db/schema'
import type { Dictionary, NewDictionary } from '../db/schema'
import { getLogger } from './LoggerService'
import { invalidateTranscriptGlossary } from './TranscriptGlossaryService'
import { getCloudSyncService } from './CloudSyncService'
import { getMainWindow } from '../windows/WindowManager'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
@ -114,6 +115,8 @@ class DictionaryService {
throw err
}
logger.info(`Dictionary entry added: "${word}"`)
// 학습 어휘 캐시(전사 교열·STT 힌트)는 즉시 무효화한다 — 방금 추가한 단어가 바로 쓰여야 한다.
invalidateTranscriptGlossary()
// Phase 3.3: 자동 push (fire-and-forget)
void getCloudSyncService().pushOne('dictionary', id)
return this._toEntry(entry as Dictionary)
@ -150,6 +153,7 @@ class DictionaryService {
}
const updated = db.select().from(dictionary).where(eq(dictionary.id, params.id)).get()
invalidateTranscriptGlossary()
// Phase 3.3: 자동 push (fire-and-forget)
void getCloudSyncService().pushOne('dictionary', params.id)
return updated ? this._toEntry(updated) : null
@ -158,7 +162,10 @@ class DictionaryService {
delete(id: string): boolean {
const db = getDatabase()
const result = db.delete(dictionary).where(eq(dictionary.id, id)).run()
if (result.changes > 0) getCloudSyncService().pushDelete('dictionary', id)
if (result.changes > 0) {
invalidateTranscriptGlossary()
getCloudSyncService().pushDelete('dictionary', id)
}
return result.changes > 0
}
@ -449,6 +456,7 @@ class DictionaryService {
logger.info(
`Dictionary import: ${outcome.imported} imported, ${outcome.skipped} skipped, ${outcome.errors} errors`
)
if (outcome.imported > 0) invalidateTranscriptGlossary()
return outcome
}

View file

@ -35,6 +35,7 @@ import type {
} from '@d3ro/core/types'
import { collapseRepeatedSegments, collapseRepeats, isDegenerateTranscript } from './file-transcription/repetition'
import { getTranscriptGlossaryService } from './TranscriptGlossaryService'
import { SUPPORTED_MEDIA_EXTENSION_SET } from './file-transcription/media-formats'
const logger = getLogger('FileTranscriptionService')
@ -178,7 +179,8 @@ class FileTranscriptionService extends EventEmitter {
let result = await sttService.transcribe(chunkBuffer, {
language: lang,
initialPrompt: previousContext || undefined,
// 학습 어휘 힌트를 매 조각에 붙인다 — 앞 문맥이 없어도 고유명사 표기가 유지된다.
initialPrompt: getTranscriptGlossaryService().sttHint(previousContext) || undefined,
vadFilter: true,
})
// 인식 중에 취소됐으면 결과를 버린다(STT 호출 자체는 끊을 수 없다)
@ -187,12 +189,17 @@ class FileTranscriptionService extends EventEmitter {
// 앞 조각 힌트 때문에 반복 루프에 빠졌으면 힌트 없이 한 번 다시 듣는다
if (previousContext && isDegenerateTranscript(result.text ?? '')) {
logger.warn(`청크 ${i + 1}/${totalChunks}: 반복 루프 감지 — 앞 문맥 없이 다시 전사`)
result = await sttService.transcribe(chunkBuffer, { language: lang, vadFilter: true })
result = await sttService.transcribe(chunkBuffer, {
language: lang,
initialPrompt: getTranscriptGlossaryService().sttHint('') || undefined,
vadFilter: true,
})
throwIfCancelled()
}
const rawText = result.text?.trim() ?? ''
const chunkText = collapseRepeats(rawText)
// 학습 어휘(사전 + 개인 문구)로 잘못 들은 어절을 되돌린다.
const chunkText = getTranscriptGlossaryService().correct(collapseRepeats(rawText)).text
if (chunkText.length > 0) {
allTexts.push(chunkText)
// 반복으로 망가진 결과는 다음 조각의 힌트로 넘기지 않는다 — 넘기면 반복이 다음 조각으로 번졌다
@ -200,7 +207,7 @@ class FileTranscriptionService extends EventEmitter {
for (const seg of collapseRepeatedSegments(result.segments)) {
allSegments.push({
text: seg.text,
text: getTranscriptGlossaryService().correct(seg.text).text,
start: seg.start + startSec,
end: seg.end + startSec,
confidence: seg.confidence,

View file

@ -57,6 +57,7 @@ import {
} from '@d3ro/core/meeting-transcript'
import { markdownToDocx } from '@d3ro/core/utils/markdown-to-docx'
import { getFileTranscriptionService } from './FileTranscriptionService'
import { getTranscriptGlossaryService } from './TranscriptGlossaryService'
import { buildImportedMeetingTranscript } from './meeting/imported-recording'
import type {
MeetingModeState,
@ -371,6 +372,11 @@ class MeetingModeService extends EventEmitter {
captionService.on('segment', listener)
return () => { captionService.off('segment', listener) }
},
// 다듬기(학습 어휘·LLM 교열)로 바뀐 줄도 받아야 회의록 전사가 원문에 머물지 않는다.
onSegmentUpdated: (listener) => {
captionService.on('segment-updated', listener)
return () => { captionService.off('segment-updated', listener) }
},
// 회의가 소유한 세션만 멈춘다. 다른 소유자면 false(요약 없음).
stop: () => captionService.stop('meeting'),
},
@ -385,6 +391,10 @@ class MeetingModeService extends EventEmitter {
this.emit('segment', segment)
this._sendToRenderer(IPC_CHANNELS.MEETING_MODE.SEGMENT, segment)
},
onSegmentUpdated: (update) => {
this.emit('segment-updated', update)
this._sendToRenderer(IPC_CHANNELS.MEETING_MODE.SEGMENT_UPDATED, update)
},
onStopError: (err) => {
logger.error(`자막 정지 실패 — 지금까지의 전사로 저장한다: ${err instanceof Error ? err.message : String(err)}`)
},
@ -1419,10 +1429,14 @@ class MeetingModeService extends EventEmitter {
if (!transcript) throw new D3ROError(ErrorCode.MeetingPolishFailed, '전사 텍스트가 없습니다')
const llm = await this._resolveMeetingLlm()
// 사용자가 학습시킨 용어·표현을 교열 지시에 넘긴다 — 예전엔 일반 프롬프트만 받아
// 고유명사·사내 용어가 매번 다르게 교정됐다.
const glossary = getTranscriptGlossaryService().promptSection()
const polished = await this._rewriteTranscriptInChunks(
llm,
transcript,
'다음 음성 전사 텍스트를 다듬어주세요. 필러 단어(음, 어, 그, 아, 뭐 등), 말 바꾸기(A 아니 A가 아니라 B → B), 불필요한 어절·의미 중복을 제거하고 문장 구조를 자연스럽게 교정하되, 화자의 원래 말투(반말/존댓말)와 의미·내용은 절대 변경하지 마세요. 타임스탬프 형식 [MM:SS]과 화자 표기([화자 N] 등)는 그대로 유지하세요.',
'다음 음성 전사 텍스트를 다듬어주세요. 필러 단어(음, 어, 그, 아, 뭐 등), 말 바꾸기(A 아니 A가 아니라 B → B), 불필요한 어절·의미 중복을 제거하고 문장 구조를 자연스럽게 교정하되, 화자의 원래 말투(반말/존댓말)와 의미·내용은 절대 변경하지 마세요. 타임스탬프 형식 [MM:SS]과 화자 표기([화자 N] 등)는 그대로 유지하세요.' +
(glossary ? `\n\n${glossary}` : ''),
ErrorCode.MeetingPolishFailed,
)

View file

@ -0,0 +1,184 @@
// src/main/services/TranscriptGlossaryService.ts
// 전사 교열용 학습 어휘 창구(싱글톤).
//
// 왜 필요한가:
// - 사용자가 키보드로 친 문장은 개인 그래프(personal_phrases)와 사전(dictionary)에 쌓이지만,
// 회의록·자막 전사에는 그 어휘가 한 번도 쓰이지 않았다. 자막은 `다음은 한국어 대화입니다.`라는
// 고정 힌트로 인식됐고, 확정된 줄은 용어 사전 없이 일반 프롬프트로만 다듬어졌다.
// - 이 서비스는 그 어휘를 한 곳에서 모아 STT 힌트·결정적 교정·LLM 교열 참고 블록으로 공급한다.
// 교정 규칙 자체는 core `transcript-correction` 이 정본이고, 여기서는 소스 수집과 캐시만 맡는다.
//
// 소스는 주입 가능하다(테스트는 DB 없이 가짜 소스).
import { desc } from 'drizzle-orm'
import { getLogger } from './LoggerService'
import { getDatabase } from '../db'
import { dictionary, personalPhrases } from '../db/schema'
import {
appendGlossaryHint,
buildGlossaryPromptSection,
buildTranscriptGlossary,
correctLearnedTerms,
isGlossaryEmpty,
replaceDictionaryTerms,
type CorrectedTranscript,
type GlossaryDictionaryEntry,
type GlossaryPhrase,
type TranscriptCorrectionEntry,
type TranscriptGlossary,
} from '@d3ro/core/transcript-correction'
const logger = getLogger('TranscriptGlossaryService')
/** 학습 어휘 캐시 수명. 사전/학습은 회의 중에도 늘 수 있으므로 짧게 둔다. */
const GLOSSARY_TTL_MS = 15_000
export interface TranscriptGlossarySources {
/** 사용자 사전 (정본 단어 + 발음 변형) */
listDictionary(): readonly GlossaryDictionaryEntry[]
/** 개인 그래프에서 배운 문구 (빈도 포함) */
listPhrases(): readonly GlossaryPhrase[]
now?: () => number
}
interface CachedGlossary {
glossary: TranscriptGlossary
at: number
}
export class TranscriptGlossaryService {
private _cache: CachedGlossary | null = null
private readonly _now: () => number
constructor(
private readonly _sources: TranscriptGlossarySources,
private readonly _ttlMs: number = GLOSSARY_TTL_MS,
) {
this._now = _sources.now ?? Date.now
}
/** 현재 글로서리 (TTL 캐시). 소스가 실패하면 빈 글로서리 — 전사는 계속돼야 한다. */
get(): TranscriptGlossary {
const now = this._now()
if (this._cache && now - this._cache.at < this._ttlMs) return this._cache.glossary
let glossary: TranscriptGlossary
try {
glossary = buildTranscriptGlossary({
dictionary: this._sources.listDictionary(),
phrases: this._sources.listPhrases(),
})
} catch (err) {
logger.warn(`학습 어휘 수집 실패 — 이번 전사는 어휘 없이 진행: ${err instanceof Error ? err.message : String(err)}`)
glossary = buildTranscriptGlossary({})
}
this._cache = { glossary, at: now }
return glossary
}
/** 사전·학습이 바뀌었을 때 호출한다. */
invalidate(): void {
this._cache = null
}
/** STT initial_prompt 에 학습 어휘 힌트를 덧붙인다. */
sttHint(base: string): string {
return appendGlossaryHint(base, this.get())
}
/** LLM 교열 프롬프트에 넣는 용어·문체 참고 블록 (없으면 빈 문자열). */
promptSection(): string {
return buildGlossaryPromptSection(this.get())
}
/**
* 학습 어휘 기반 결정적 교정 (LLM 없이 즉시).
* 1) 사전 발음 변형 → 정본 표기
* 2) 학습 어절과 1자모 차이 나는 전사 어절 → 학습 어절
* 사용자가 실제로 쓴 어절은 건드리지 않는다(core 규칙).
*/
correct(text: string): CorrectedTranscript {
if (!text || text.trim().length === 0) return { text, corrections: [] }
const glossary = this.get()
if (isGlossaryEmpty(glossary)) return { text, corrections: [] }
const corrections: TranscriptCorrectionEntry[] = []
let current = text
if (glossary.dictionary.length > 0) {
const dictionaryPass = replaceDictionaryTerms(
current,
glossary.dictionary.map((entry) => ({ word: entry.word, pronunciation: entry.variants.join(',') })),
)
current = dictionaryPass.text
corrections.push(...dictionaryPass.changes)
}
const learned = correctLearnedTerms(current, glossary)
if (learned.corrections.length > 0) corrections.push(...learned.corrections)
return { text: learned.text, corrections }
}
/**
* 학습 어절만 교정한다. 사전 치환을 호출자가 사용 횟수 집계와 함께 처리하는 경로
* (받아쓰기)에서 쓴다.
*/
correctLearned(text: string): CorrectedTranscript {
if (!text || text.trim().length === 0) return { text, corrections: [] }
const glossary = this.get()
if (isGlossaryEmpty(glossary)) return { text, corrections: [] }
return correctLearnedTerms(text, glossary)
}
}
let instance: TranscriptGlossaryService | null = null
/** DB 기반 기본 소스. DB 가 아직 없으면 빈 어휘를 돌려준다(전사를 막지 않는다). */
function defaultSources(): TranscriptGlossarySources {
return {
listDictionary: () => {
try {
return getDatabase()
.select({ word: dictionary.word, pronunciation: dictionary.pronunciation })
.from(dictionary)
.orderBy(desc(dictionary.usageCount))
.limit(300)
.all()
} catch {
return []
}
},
listPhrases: () => {
try {
return getDatabase()
.select({ text: personalPhrases.phrase, count: personalPhrases.count })
.from(personalPhrases)
.orderBy(desc(personalPhrases.count), desc(personalPhrases.lastUsedAt))
.limit(400)
.all()
} catch {
return []
}
},
}
}
export function initTranscriptGlossaryService(
sources: TranscriptGlossarySources = defaultSources(),
ttlMs?: number,
): TranscriptGlossaryService {
instance = new TranscriptGlossaryService(sources, ttlMs)
return instance
}
export function getTranscriptGlossaryService(): TranscriptGlossaryService {
if (!instance) instance = initTranscriptGlossaryService()
return instance
}
/** 사전·학습이 바뀌었을 때 호출한다(아직 만들지 않았으면 아무 것도 하지 않는다). */
export function invalidateTranscriptGlossary(): void {
instance?.invalidate()
}
export function resetTranscriptGlossaryServiceForTests(): void {
instance = null
}

View file

@ -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}`)
}

View file

@ -27,6 +27,7 @@ import { configGet } from './ConfigService'
import { getTextInsertService } from './TextInsertService'
import { getLocalLLMService } from './LocalLLMService'
import { getLlmGateway } from './llm/LlmGateway'
import { getTranscriptGlossaryService } from './TranscriptGlossaryService'
import { buildInstructionInvocation, resolveTargetLanguage } from './llm-prompts'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import { cleanDictatedText } from '@d3ro/core/dictation-cleaner'
@ -907,13 +908,12 @@ class VoiceModeService extends EventEmitter {
const stt = getSTTManager()
const language = configGet('sttLanguage')
// Dictionary → STT initialPrompt 주입 (Speakly 패턴)
// 사전 + 학습 어휘 → STT initial_prompt 주입 (사용자가 학습시킨 용어를 인식 단계에서 미리 편향)
let initialPrompt: string | undefined
try {
const { getDictionaryService } = await import('./DictionaryService')
initialPrompt = getDictionaryService().getPromptHints() || undefined
initialPrompt = getTranscriptGlossaryService().sttHint('') || undefined
} catch {
// DictionaryService 미초기화 시 무시
// 학습 어휘 소스 미준비 시 무시
}
// 사이드카는 요청을 직렬 처리하므로, 진행 중인 미리보기 요청이 최종 전사를
@ -950,6 +950,8 @@ class VoiceModeService extends EventEmitter {
} catch {
// DictionaryService 미초기화 시 무시
}
// 사전에 없는 개인 어휘(학습한 어절)로 남은 오인식을 되돌린다.
rawText = getTranscriptGlossaryService().correctLearned(rawText).text
if (this._session) {
this._session.transcription = rawText

View file

@ -54,14 +54,6 @@ export function acquireGlobalInputHook(): () => void {
}
}
export function isGlobalInputHookRunning(): boolean {
return running
}
export function getGlobalInputHookRefCount(): number {
return refCount
}
/** 테스트 전용 — 모듈 상태 초기화. */
export function resetGlobalInputHookForTests(): void {
refCount = 0

View file

@ -529,6 +529,8 @@ const CAPTION_REFINE_SYSTEM_PROMPT = `실시간 음성 인식으로 받아 적
규칙:
- 띄어쓰기, 문장부호, 앞 문맥으로 볼 때 명백하게 잘못 들은 단어만 고치세요.
- [사용자 용어] 가 있으면 전사에 나온 비슷한 표기를 그 용어로 바꾸세요(고유명사·제품명·사내 용어).
- [사용자가 실제로 쓰는 표현] 은 말투·용어 참고용입니다. 그 문장을 그대로 옮기거나 문장을 새로 쓰지 마세요.
- 뜻을 바꾸거나, 요약하거나, 말을 더하거나 빼지 마세요.
- 원문과 같은 언어, 같은 말투(존댓말/반말, 구어체)를 유지하세요.
- 고친 문장 한 줄만 출력하세요. 설명, 따옴표, 번호를 붙이지 마세요.
@ -537,8 +539,12 @@ const CAPTION_REFINE_SYSTEM_PROMPT = `실시간 음성 인식으로 받아 적
export function buildCaptionRefinePrompt(input: {
text: string
previous: readonly string[]
/** 학습 어휘 참고 블록 (`buildGlossaryPromptSection` 결과) */
glossary?: string
}): { systemPrompt: string; text: string } {
const sections: string[] = []
const glossary = input.glossary?.trim()
if (glossary) sections.push(glossary, '')
const previous = input.previous.filter((line) => line.trim().length > 0).slice(-2)
if (previous.length > 0) sections.push('[앞 문맥]', ...previous, '')
sections.push('[다듬을 자막]', input.text.trim())

View file

@ -16,6 +16,8 @@ import type { CaptionSegment, MeetingMemo } from '@d3ro/core/types'
export interface RecordingCaptionPort {
/** 확정 세그먼트 구독 — 해지 함수를 돌려준다 */
onSegment(listener: (segment: CaptionSegment) => void): () => void
/** 다듬기(학습 어휘·LLM 교열)로 확정 세그먼트 텍스트가 바뀌었을 때 (선택) */
onSegmentUpdated?(listener: (update: { id: string; text: string }) => void): () => void
/** 이 녹음이 소유한 자막 세션을 멈춘다(마지막 문장 flush 포함). 세그먼트 요약을 돌려줄 수 있다. */
stop(): Promise<{ segments: CaptionSegment[] } | null | false>
}
@ -31,6 +33,8 @@ export interface MeetingRecordingSessionPorts {
now?: () => number
/** 세그먼트가 이 녹음에 추가될 때(구독으로 받은 것만) */
onSegment?: (segment: CaptionSegment) => void
/** 세그먼트 텍스트가 다듬어졌을 때 — 화면·기록이 원문에 머물지 않게 알린다 */
onSegmentUpdated?: (update: { id: string; text: string }) => void
/** 자막 정지 실패 — 정지는 계속 진행된다(스냅샷은 그때까지의 세그먼트로 만든다) */
onStopError?: (error: unknown) => void
}
@ -54,6 +58,7 @@ export class MeetingRecordingSession {
private _audio: Buffer[] = []
private _lastRms = 0
private _unsubscribeSegment: (() => void) | null = null
private _unsubscribeSegmentUpdated: (() => void) | null = null
private _unsubscribeAudio: (() => void) | null = null
private _stopPromise: Promise<RecordingSnapshot> | null = null
private _snapshot: RecordingSnapshot | null = null
@ -74,6 +79,13 @@ export class MeetingRecordingSession {
this._segments.push(segment)
this._ports.onSegment?.(segment)
})
this._unsubscribeSegmentUpdated =
this._ports.caption.onSegmentUpdated?.((update) => {
const target = this._segments.find((segment) => segment.id === update.id)
if (!target || target.text === update.text) return
target.text = update.text
this._ports.onSegmentUpdated?.(update)
}) ?? null
}
/** 오디오 구독을 건다(파일 저장·레벨 표시용). */
@ -89,6 +101,8 @@ export class MeetingRecordingSession {
detach(): void {
this._unsubscribeSegment?.()
this._unsubscribeSegment = null
this._unsubscribeSegmentUpdated?.()
this._unsubscribeSegmentUpdated = null
this._unsubscribeAudio?.()
this._unsubscribeAudio = null
}
@ -158,6 +172,8 @@ export class MeetingRecordingSession {
} finally {
this._unsubscribeSegment?.()
this._unsubscribeSegment = null
this._unsubscribeSegmentUpdated?.()
this._unsubscribeSegmentUpdated = null
}
// 구독 밖에서 확정된 세그먼트가 있으면 요약에서 보충한다
if (summary) {

View file

@ -19,10 +19,6 @@ const SERVER_TO_DESKTOP_BUILTIN: Readonly<Record<string, string>> = 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 로 바꿔 올린다.

View file

@ -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<number> => {
const win = getMainWindow()
const { response } =
@ -212,22 +207,19 @@ export function createDialogPrompter(): UpdatePrompter {
return {
async askConsent({ version, releaseNotes, mandatory }): Promise<ConsentAnswer> {
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<RestartAnswer> {
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,
})

View file

@ -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<void> {
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 })
}

View file

@ -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 }

View file

@ -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 판정에도 사용된다.

View file

@ -42,7 +42,3 @@ export function createTray(): void {
logger.info('Tray created')
}
export function getTray(): Tray | null {
return tray
}

View file

@ -793,6 +793,9 @@ const electronAPI = {
on(IPC_CHANNELS.MEETING_MODE.STATE_CHANGED, cb),
onSegment: (cb: (e: CaptionSegment) => void): Unsubscribe =>
on(IPC_CHANNELS.MEETING_MODE.SEGMENT, cb),
/** 다듬기(학습 어휘·LLM 교열)로 바뀐 확정 줄 — 화면이 원문에 머물지 않게 갱신한다 */
onSegmentUpdated: (cb: (e: { id: string; text: string }) => void): Unsubscribe =>
on(IPC_CHANNELS.MEETING_MODE.SEGMENT_UPDATED, cb),
onProcessingProgress: (cb: (e: MeetingProcessingProgress) => void): Unsubscribe =>
on(IPC_CHANNELS.MEETING_MODE.PROCESSING_PROGRESS, cb),
onSessionCompleted: (cb: (e: MeetingSessionDetail) => void): Unsubscribe =>

View file

@ -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 (
<Box
onClick={onSelect}
data-testid={testId}
sx={{
p: 2.5,
cursor: 'pointer',
@ -323,6 +325,7 @@ export function OnboardingModal({ open, onClose }: OnboardingModalProps): React.
description={t('onboarding.mode.local.desc')}
points={LOCAL_POINTS.map((key) => t(key))}
onSelect={handleSelectLocalMode}
testId="onboarding-mode-local"
action={
// 첫 포커스 — Enter 로 권장 경로를 바로 시작한다. 클릭은 카드 onClick 으로 전파된다.
<Button variant="contained" fullWidth autoFocus>
@ -336,6 +339,7 @@ export function OnboardingModal({ open, onClose }: OnboardingModalProps): React.
description={t('onboarding.mode.online.desc')}
points={ONLINE_POINTS.map((key) => t(key))}
onSelect={() => setPhase('online_auth')}
testId="onboarding-mode-online"
action={
<Button variant="outlined" fullWidth>
{t('onboarding.mode.online.action')}

View file

@ -327,7 +327,14 @@ export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose
}}
>
{SETTINGS_TAB_ORDER.map((tab) => (
<Tab key={tab} value={tab} label={tabMeta[tab].label} icon={tabMeta[tab].icon} iconPosition="start" />
<Tab
key={tab}
value={tab}
label={tabMeta[tab].label}
icon={tabMeta[tab].icon}
iconPosition="start"
data-testid={`settings-tab-${tab}`}
/>
))}
</Tabs>
</Box>

View file

@ -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 = (
<ButtonBase
onClick={onClick}
data-testid={testId}
aria-current={active ? 'page' : undefined}
sx={{
width: '100%',
@ -189,6 +192,7 @@ export function AppSidebar({
trailing={trailing}
shortcut={index !== undefined ? t('nav.shortcutHint', { n: index + 1 }) : undefined}
onClick={() => navigate(r)}
testId={`nav-${r}`}
/>
)
@ -246,7 +250,13 @@ export function AppSidebar({
</Box>
)}
<NavButton active={false} icon={<Headphones size={ICON} />} label={t('nav.support')} onClick={onOpenSupport} />
<NavButton
active={false}
icon={<Headphones size={ICON} />}
label={t('nav.support')}
onClick={onOpenSupport}
testId="nav-support"
/>
{item('settings')}
<Box sx={{ borderTop: `1px solid ${d3roPalette.border.subtle}`, mt: 1 }}>

View file

@ -187,6 +187,11 @@ export function MeetingModePage(): React.ReactElement {
}, 50)
})
// 다듬기(학습 어휘·LLM 교열)로 확정 줄이 바뀌면 화면도 그 문장으로 바꾼다.
const unsubSegmentUpdated = window.electronAPI.meetingMode.onSegmentUpdated((update) => {
setSegments((prev) => replaceSegmentText(prev, update.id, update.text))
})
const unsubProgress = window.electronAPI.meetingMode.onProcessingProgress((p) => {
setProgress(p)
})
@ -213,6 +218,7 @@ export function MeetingModePage(): React.ReactElement {
return () => {
unsubState()
unsubSegment()
unsubSegmentUpdated()
unsubProgress()
unsubCompleted()
unsubError()

View file

@ -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)
})
})

View file

@ -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();
});
});

View file

@ -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();
});
});

View file

@ -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);
}
});
});

View file

@ -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 () => {
const NAV_ROUTES = [
'home',
'search',
'records',
'meetings',
'conversation',
'commands',
'dictionary',
'knowledge',
'settings',
] as const
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',
},
});
test.describe('셸 내비게이션', () => {
test('사이드바는 주 화면·도구 화면·지원·설정을 모두 노출한다', async ({ mainWindow }) => {
const nav = mainWindow.window.getByRole('navigation')
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;
for (const route of NAV_ROUTES) {
await expect(nav.getByTestId(`nav-${route}`)).toBeVisible()
}
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)
})
}
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 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)
})
})

View file

@ -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',
},
});
test.describe('첫 실행 온보딩', () => {
test.use({ onboardingCompleted: false })
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;
}
}
test('사용 방식 두 가지를 제시한다', async ({ mainWindow }) => {
const dialog = mainWindow.window.getByRole('dialog')
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';
}
});
}
});
await expect(dialog).toBeVisible()
await expect(dialog.getByTestId('onboarding-mode-local')).toBeVisible()
await expect(dialog.getByTestId('onboarding-mode-online')).toBeVisible()
test.afterAll(async () => {
if (electronApp) {
await electronApp.close();
}
});
expectNoRuntimeErrors(mainWindow)
})
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();
test('온라인을 고르면 로그인·회원가입 폼이 열린다', async ({ mainWindow }) => {
const dialog = mainWindow.window.getByRole('dialog')
await expect(dialog).toBeVisible()
const emailInput = window.locator('input[type="email"]');
const passwordInput = window.locator('input[type="password"]');
await expect(emailInput).toBeVisible();
await expect(passwordInput).toBeVisible();
});
await dialog.getByTestId('onboarding-mode-online').click()
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("로그인 완료")');
await expect(dialog.getByRole('tab')).toHaveCount(2)
await expect(dialog.locator('input[type="email"]')).toBeVisible()
await expect(dialog.locator('input[type="password"]')).toBeVisible()
await emailInput.fill('fake@example.com');
await passwordInput.fill('wrongpassword');
await submitBtn.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();
}
});
});
expectNoRuntimeErrors(mainWindow)
})
})

View file

@ -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();
});
});

View file

@ -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)
})
})

View file

@ -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);
});
});

View file

@ -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([]);
});
});

View file

@ -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 <body>, 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([]);
});
});

View file

@ -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\'; <script>alert("XSS")</script>';
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([]);
});
});

View file

@ -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 () => {
test.describe('설정', () => {
test('사이드바 설정은 정본 탭 개수만큼 탭을 렌더하고 첫 탭을 선택한다', async ({ mainWindow }) => {
await goToRoute(mainWindow, 'settings')
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',
},
});
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')
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;
}
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)
})
}
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 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)
})
})

View file

@ -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<Page> {
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 '<navigating>'
}
})
.join(', ')}`,
)
}
interface ConfigBridge {
config?: {
set(params: { key: string; value: unknown }): Promise<unknown>
}
}
async function applyConfigBypass(window: Page, onboardingCompleted: boolean): Promise<void> {
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<Options & { mainWindow: MainWindowContext }>({
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<void> {
const button = context.window.getByRole('navigation').getByTestId(`nav-${route}`)
await button.click()
await baseExpect(button).toHaveAttribute('aria-current', 'page')
}

View file

@ -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();
}
});
});

View file

@ -0,0 +1,58 @@
import { describe, expect, it, vi } from 'vitest'
type Listener = (...args: unknown[]) => void
const state = vi.hoisted(() => ({
appListeners: new Map<string, Listener>(),
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)
})
})

View file

@ -0,0 +1,155 @@
// tests/main/services/transcript-glossary.test.ts
// 학습한 어휘(사용자 사전 + 개인 문구)가 전사 교열에 실제로 쓰이는지 검증한다.
// 예전에는 자막이 고정 힌트로만 인식되고, 전사된 줄은 용어 사전 없이 다듬어져
// 사용자가 키보드로 배운 표기가 회의록에 반영되지 않았다.
import { describe, expect, it } from 'vitest'
import { useRedHarness } from '../../red/harness'
import {
getTranscriptGlossaryService,
TranscriptGlossaryService,
} from '../../../src/main/services/TranscriptGlossaryService'
import { getDictionaryService } from '../../../src/main/services/DictionaryService'
import { getPersonalGraphService } from '../../../src/main/services/PersonalGraphService'
import { MeetingRecordingSession } from '../../../src/main/services/meeting/MeetingRecordingSession'
import type { CaptionSegment } from '@d3ro/core/types'
useRedHarness()
/** 같은 문장을 n 번 친 것으로 개인 그래프에 남긴다(count 누적). */
function learnPhrase(text: string, times: number): void {
for (let i = 0; i < times; i += 1) {
getPersonalGraphService().indexText(text, { source: 'typed', appName: 'notepad.exe' })
}
}
describe('학습한 어휘가 전사 교정에 쓰인다', () => {
it('키보드로 배운 어절과 한 글자 다른 전사 어절을 되돌린다', () => {
learnPhrase('회의록 정리해줘', 5)
const result = getTranscriptGlossaryService().correct('회이록 정리해줘')
expect(result.text).toBe('회의록 정리해줘')
expect(result.corrections).toEqual([{ from: '회이록', to: '회의록', source: 'learned' }])
})
it('사용자 사전의 발음 표기를 정본 표기로 바꾼다', () => {
getDictionaryService().add({ word: 'D3RO', pronunciation: '디에로' })
const result = getTranscriptGlossaryService().correct('디에로 보이스 좋네요')
expect(result.text).toBe('D3RO 보이스 좋네요')
})
it('STT 힌트에 사전 단어와 학습 어절이 함께 들어간다', () => {
getDictionaryService().add({ word: 'Whisper' })
learnPhrase('녹음 파일 올려줘', 4)
const hint = getTranscriptGlossaryService().sttHint('다음은 한국어 대화입니다.')
expect(hint.startsWith('다음은 한국어 대화입니다.')).toBe(true)
expect(hint).toContain('Whisper')
expect(hint).toContain('녹음')
})
it('한 번만 쓴 어절은 학습 어휘로 쓰지 않는다', () => {
learnPhrase('회의록 정리해줘', 1)
const result = getTranscriptGlossaryService().correct('회이록 정리해줘')
expect(result.text).toBe('회이록 정리해줘')
})
it('사전에 단어를 추가하면 캐시를 기다리지 않고 바로 반영된다', () => {
expect(getTranscriptGlossaryService().sttHint('')).not.toContain('Supabase')
getDictionaryService().add({ word: 'Supabase', pronunciation: '수파베이스' })
expect(getTranscriptGlossaryService().sttHint('')).toContain('Supabase')
})
it('LLM 교열 프롬프트에 사용자 용어 블록을 넣는다', () => {
getDictionaryService().add({ word: 'D3RO', pronunciation: '디에로' })
learnPhrase('오늘 회의는 세 시에 시작합니다', 3)
const section = getTranscriptGlossaryService().promptSection()
expect(section).toContain('[사용자 용어')
expect(section).toContain('D3RO')
expect(section).toContain('오늘 회의는 세 시에 시작합니다')
})
})
describe('글로서리 캐시', () => {
it('캐시가 살아 있으면 소스를 다시 읽지 않고, 무효화하면 다시 읽는다', () => {
let dictionaryReads = 0
let now = 1_000
const service = new TranscriptGlossaryService(
{
listDictionary: () => {
dictionaryReads += 1
return [{ word: 'D3RO', pronunciation: null }]
},
listPhrases: () => [{ text: '회의록 정리해줘', count: 5 }],
now: () => now,
},
1_000,
)
service.get()
service.get()
expect(dictionaryReads).toBe(1)
now += 1_500
service.get()
expect(dictionaryReads).toBe(2)
service.invalidate()
service.get()
expect(dictionaryReads).toBe(3)
})
it('소스가 실패해도 빈 어휘로 진행한다', () => {
const service = new TranscriptGlossaryService({
listDictionary: () => {
throw new Error('db down')
},
listPhrases: () => [{ text: '회의록', count: 5 }],
})
expect(service.get().promptHint).toBe('')
expect(service.correct('회이록').text).toBe('회이록')
})
})
describe('회의 세션이 다듬어진 줄을 받는다', () => {
it('자막이 알린 수정 문장이 회의 세그먼트에 반영된다', () => {
const segmentListeners = new Set<(segment: CaptionSegment) => void>()
const updateListeners = new Set<(update: { id: string; text: string }) => void>()
const updates: Array<{ id: string; text: string }> = []
const session = new MeetingRecordingSession('session-1', 0, {
caption: {
onSegment: (listener) => {
segmentListeners.add(listener)
return () => segmentListeners.delete(listener)
},
onSegmentUpdated: (listener) => {
updateListeners.add(listener)
return () => updateListeners.delete(listener)
},
stop: async () => null,
},
audio: { onChunk: () => () => undefined },
onSegmentUpdated: (update) => updates.push(update),
now: () => 1_000,
})
session.attachCaption()
const segment: CaptionSegment = { id: 'seg-1', text: '회이록 정리해줘', timestamp: 500, isFinal: true }
for (const listener of segmentListeners) listener(segment)
for (const listener of updateListeners) listener({ id: 'seg-1', text: '회의록 정리해줘' })
expect(session.segments[0].text).toBe('회의록 정리해줘')
expect(updates).toEqual([{ id: 'seg-1', text: '회의록 정리해줘' }])
})
})

View file

@ -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,
})
})
})

View file

@ -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 })
})
})

View file

@ -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/환전/원천세/지급)

View file

@ -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 키쌍을 생성해 서명/위조/변조를 실측한다(정답 유도 목업 금지).

View file

@ -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(설정)
// 시나리오는 "광고가 실제로 작동해 수입을 발생시키는" 목표 상태를 기술한다.

View file

@ -36,6 +36,7 @@ import {
LocalSTTService,
resetLocalSTTServiceForTests,
} from '../../src/main/services/LocalSTTService'
import { resetTranscriptGlossaryServiceForTests } from '../../src/main/services/TranscriptGlossaryService'
import { D3ROError, ErrorCode, type IPCResult } from '@d3ro/core/errors'
import type { NewHistory } from '../../src/main/db/schema'
@ -102,6 +103,7 @@ export function resetAllSingletons(): void {
resetMeetingSummaryServiceForTests()
resetLocalLLMServiceForTests()
resetLocalSTTServiceForTests()
resetTranscriptGlossaryServiceForTests()
}
export function useRedHarness(): void {

View file

@ -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

View file

@ -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(<App />);
tree = ReactTestRenderer.create(<App />);
});
expect(tree?.toJSON() ?? null).not.toBeNull();
});

View file

@ -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' })

View file

@ -151,8 +151,8 @@ def versionSettingsValid = configuredVersionName != null &&
configuredVersionName ==~ strictSemver &&
configuredVersionCodeValue != null &&
configuredVersionCodeValue <= 2100000000L
def resolvedVersionName = versionSettingsValid ? configuredVersionName : "1.16.1"
def resolvedVersionCode = versionSettingsValid ? configuredVersionCodeValue.toInteger() : 1160100
def resolvedVersionName = versionSettingsValid ? configuredVersionName : "1.16.2"
def resolvedVersionCode = versionSettingsValid ? configuredVersionCodeValue.toInteger() : 1160200
def requiredReleaseSettings = [
D3RO_RELEASE_STORE_FILE: releaseStoreFilePath,

View file

@ -257,7 +257,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1160100;
CURRENT_PROJECT_VERSION = 1160200;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = D3ROVoice/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
@ -265,7 +265,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.16.1;
MARKETING_VERSION = 1.16.2;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
@ -287,14 +287,14 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1160100;
CURRENT_PROJECT_VERSION = 1160200;
INFOPLIST_FILE = D3ROVoice/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.16.1;
MARKETING_VERSION = 1.16.2;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",

View file

@ -0,0 +1 @@
Stability and performance improvements.

View file

@ -0,0 +1 @@
안정성과 성능을 개선했습니다.

View file

@ -1,12 +1,12 @@
{
"name": "@d3ro/mobile-rn",
"version": "1.16.1",
"version": "1.16.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@d3ro/mobile-rn",
"version": "1.16.1",
"version": "1.16.2",
"dependencies": {
"@d3ro/api-client": "file:../../packages/api-client",
"@d3ro/core": "file:../../packages/core",
@ -62,7 +62,7 @@
},
"../..": {
"name": "d3ro-voice-monorepo",
"version": "1.16.1",
"version": "1.16.2",
"license": "MIT",
"workspaces": [
"apps/desktop",
@ -81,10 +81,9 @@
},
"../../packages/api-client": {
"name": "@d3ro/api-client",
"version": "1.16.1",
"version": "1.16.2",
"license": "MIT",
"dependencies": {
"@d3ro/core": "*",
"@supabase/supabase-js": "^2.45.0"
},
"peerDependencies": {
@ -98,7 +97,7 @@
},
"../../packages/core": {
"name": "@d3ro/core",
"version": "1.16.1",
"version": "1.16.2",
"license": "MIT",
"dependencies": {
"docx": "^9.6.1"
@ -109,7 +108,7 @@
},
"../../packages/i18n": {
"name": "@d3ro/i18n",
"version": "1.16.1",
"version": "1.16.2",
"license": "MIT",
"devDependencies": {
"@types/react": "^19.0.0"
@ -120,7 +119,7 @@
},
"../../packages/ui-native": {
"name": "@d3ro/ui-native",
"version": "1.16.1",
"version": "1.16.2",
"license": "MIT",
"devDependencies": {
"@types/react": "*"

View file

@ -1,6 +1,6 @@
{
"name": "@d3ro/mobile-rn",
"version": "1.16.1",
"version": "1.16.2",
"private": true,
"scripts": {
"android": "react-native run-android",

View file

@ -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<RootStackParamList, 'Account'>
export default function AccountScreen({
deletionService = edgeAccountDeletionService,
identityService = identityManagementService,
}: AccountScreenProps): React.ReactElement {
const navigation = useNavigation<any>()
const navigation = useNavigation<AccountNavigation>()
const { user, purgeLocalSession } = useAuth()
const { currentDevice } = useDevice()
const { palette } = useMobilePreferences()

View file

@ -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<RootStackParamList, 'Commands'>
const NAME_KEYS: Record<CommandBuiltinKey, TranslationKey> = {
translate_en: 'mobile.commands.translate.name',
@ -85,7 +89,7 @@ interface EditorState {
export default function CommandsScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
const navigation = useNavigation<any>()
const navigation = useNavigation<CommandsNavigation>()
const { t } = useI18n()
const { user, session } = useAuth()
const { palette, preferences } = useMobilePreferences()

View file

@ -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<RootStackParamList, 'DataPortability'>;
const ERROR_KEYS: Record<PortabilityError['code'], TranslationKey> = {
auth: 'mobile.portability.error.auth',
@ -45,7 +48,7 @@ const ERROR_KEYS: Record<PortabilityError['code'], TranslationKey> = {
export default function DataPortabilityScreen(): React.ReactElement {
const insets = useSafeAreaInsets();
const navigation = useNavigation<any>();
const navigation = useNavigation<DataPortabilityNavigation>();
const { t } = useI18n();
const { user } = useAuth();
const { palette } = useMobilePreferences();

View file

@ -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<RootStackParamList, 'Devices'>
export default function DevicesScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
const navigation = useNavigation<any>()
const navigation = useNavigation<DevicesNavigation>()
const { t } = useI18n()
const { user } = useAuth()
const { currentDevice } = useDevice()

View file

@ -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<RootStackParamList, 'ForgotPassword'>
// 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<any>()
const navigation = useNavigation<ForgotPasswordNavigation>()
const { t } = useI18n()
const { palette } = useMobilePreferences()
const styles = useMemo(() => createStyles(palette), [palette])

View file

@ -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<RootStackParamList, 'InviteAccept'>
interface InviteAcceptScreenProps {
route: RouteProp<InviteAcceptRouteParams, 'InviteAccept'>
route: RouteProp<RootStackParamList, 'InviteAccept'>
}
type InviteState = 'loading' | 'ready' | 'accepting' | 'success' | 'error'
export default function InviteAcceptScreen({ route }: InviteAcceptScreenProps): React.ReactElement {
const navigation = useNavigation<any>()
const navigation = useNavigation<InviteAcceptNavigation>()
const insets = useSafeAreaInsets()
const { t } = useI18n()
const { user } = useAuth()

View file

@ -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<RootStackParamList, 'Notifications'>
interface ReceivedNotification {
key: string
@ -41,7 +45,7 @@ interface ReceivedNotification {
}
export default function NotificationsScreen(): React.ReactElement {
const navigation = useNavigation<any>()
const navigation = useNavigation<NotificationsNavigation>()
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'

View file

@ -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<RootStackParamList, 'Settings'>
const THEME_LABEL_KEYS: Record<MobileThemeMode, TranslationKey> = {
system: 'mobile.theme.system',
@ -62,7 +65,7 @@ const ERROR_KEYS: Record<PreferencesErrorCode, TranslationKey> = {
export default function SettingsScreen(): React.ReactElement {
const { t, locale, setLocale, formatTime } = useI18n()
const { user, purgeLocalSession } = useAuth()
const navigation = useNavigation<any>()
const navigation = useNavigation<SettingsNavigation>()
const {
preferences,
palette,

View file

@ -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<RootStackParamList, 'SignUp'>
export default function SignUpScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
const navigation = useNavigation<any>()
const navigation = useNavigation<SignUpNavigation>()
const { locale, t } = useI18n()
const { authError } = useAuth()
const { palette } = useMobilePreferences()

View file

@ -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

View file

@ -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<RootStackParamList, 'TeamDetail'>
interface TeamDetailScreenProps {
route: RouteProp<TeamDetailRouteParams, 'TeamDetail'>
route: RouteProp<RootStackParamList, 'TeamDetail'>
}
type Editor = 'rename' | 'invite' | null
export default function TeamDetailScreen({ route }: TeamDetailScreenProps): React.ReactElement {
const teamId = route.params.teamId
const navigation = useNavigation<any>()
const navigation = useNavigation<TeamDetailNavigation>()
const insets = useSafeAreaInsets()
const { t, formatDate } = useI18n()
const { user } = useAuth()

View file

@ -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<RootStackParamList, 'UpdatePassword'>
type UpdatePasswordRoute = RouteProp<RootStackParamList, 'UpdatePassword'>
export default function UpdatePasswordScreen(): React.ReactElement {
const insets = useSafeAreaInsets()
const navigation = useNavigation<any>()
const route = useRoute<any>()
const navigation = useNavigation<UpdatePasswordNavigation>()
const route = useRoute<UpdatePasswordRoute>()
const { t } = useI18n()
const { palette } = useMobilePreferences()
const styles = useMemo(() => createStyles(palette), [palette])

View file

@ -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

View file

@ -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([]);
});
});

View file

@ -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')
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)
})
})

View file

@ -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

View file

@ -1,14 +1,16 @@
{
"name": "@d3ro/web",
"version": "1.16.1",
"version": "1.16.2",
"private": true,
"description": "D3RO Voice 웹 앱 — Next.js 기반 SaaS 인터페이스",
"scripts": {
"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"
}
}

View file

@ -159,7 +159,7 @@ export default function LoginPage(): React.ReactElement {
color: d3roPalette.text.label
}}
>
{t('login.subtitle') ?? 'Precision Voice Intelligence'}
{t('login.subtitle')}
</Box>
</Box>
@ -215,7 +215,7 @@ export default function LoginPage(): React.ReactElement {
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M12.545,10.239v3.821h5.445c-0.712,2.315-2.647,3.972-5.445,3.972c-3.332,0-6.033-2.701-6.033-6.032s2.701-6.032,6.033-6.032c1.498,0,2.866,0.549,3.921,1.453l2.814-2.814C17.503,2.988,15.139,2,12.545,2C7.021,2,2.543,6.477,2.543,12s4.478,10,10.002,10c8.396,0,10.249-7.85,9.426-11.748L12.545,10.239z" />
</svg>
{t('login.google') ?? 'Google로 로그인'}
{t('login.google')}
</Box>
{/* Apple Button */}
@ -289,7 +289,7 @@ export default function LoginPage(): React.ReactElement {
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
{t('login.github') ?? 'GitHub로 로그인'}
{t('login.github')}
</Box>
</Stack>
@ -304,7 +304,7 @@ export default function LoginPage(): React.ReactElement {
letterSpacing: 0
}}
>
{t('login.or') ?? '또는'}
{t('login.or')}
</Box>
<Box sx={{ flex: 1, height: '1px', bgcolor: d3roPalette.border.default }} />
</Box>

View file

@ -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 (
<Box sx={{ width: '100%', height: 260 }}>
<ResponsiveContainer width="100%" height="100%">
<LineChart data={points} margin={{ top: 5, right: 12, left: -12, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke={d3roPalette.border.subtle} />
<XAxis
dataKey="date"
stroke={d3roPalette.text.muted}
fontSize={11}
tickLine={false}
/>
<YAxis
stroke={d3roPalette.text.muted}
fontSize={11}
tickLine={false}
allowDecimals={false}
/>
<Tooltip
contentStyle={{
backgroundColor: d3roPalette.bg.elevated,
border: `1px solid ${d3roPalette.border.default}`,
borderRadius: 8,
color: d3roPalette.text.primary,
fontSize: 12
}}
labelStyle={{ color: d3roPalette.text.label }}
/>
<Legend
wrapperStyle={{ fontSize: 11, color: d3roPalette.text.secondary }}
iconType="circle"
/>
<Line
type="monotone"
dataKey="meetings"
name="Meetings"
stroke={d3roPalette.accent.main}
strokeWidth={2}
dot={{ r: 3 }}
activeDot={{ r: 5 }}
/>
<Line
type="monotone"
dataKey="documents"
name="Documents"
stroke={d3roPalette.tag.purple}
strokeWidth={2}
dot={{ r: 3 }}
activeDot={{ r: 5 }}
/>
</LineChart>
</ResponsiveContainer>
</Box>
)
}

View file

@ -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<ThemeMode>): void => {
setMode(event.target.value as ThemeMode)
@ -54,52 +62,61 @@ export function Sidebar(): React.ReactElement {
{
key: 'dashboard',
path: '/dashboard',
label: t('nav.dashboard') ?? '대시보드',
label: t('nav.dashboard'),
icon: <DashboardIcon />
},
{
key: 'record',
path: '/record',
label: t('nav.record') ?? '실시간 녹음',
label: t('nav.record'),
icon: <MicIcon />
},
{
key: 'history',
path: '/history',
label: t('nav.history') ?? '전사 히스토리',
label: t('nav.history'),
icon: <HistoryIcon />
},
{
key: 'chat',
path: '/chat',
label: t('nav.chat') ?? '음성 대화',
label: t('nav.chat'),
icon: <ChatIcon />
},
{
key: 'dictionary',
path: '/dictionary',
label: t('nav.dictionary') ?? '커스텀 사전',
label: t('nav.dictionary'),
icon: <BookIcon />
},
{
key: 'commands',
path: '/commands',
label: t('nav.commands') ?? '명령어',
label: t('nav.commands'),
icon: <AutoAwesomeIcon />
},
{
key: 'billing',
path: '/billing',
label: t('nav.billing') ?? '구독 & 업그레이드',
label: t('nav.billing'),
icon: <PaymentIcon />
}
]
async function handleLogout(): Promise<void> {
const supabase = getSupabaseBrowserClient()
await supabase.auth.signOut()
const cleanup = user
? () => disableCurrentWebPush(user.id, { client: supabase })
: async () => undefined
try {
await signOutWithoutWaitingForWebPushCleanup(
cleanup,
() => supabase.auth.signOut(),
)
} finally {
router.replace('/login')
}
}
return (
<Box
@ -139,7 +156,7 @@ export function Sidebar(): React.ReactElement {
</PhosphorText>
</Box>
<Box sx={{ fontSize: '11px', fontFamily: 'var(--d3-font-mono)', color: d3roPalette.text.muted }}>
v1.16.1
v{WEB_APP_VERSION}
</Box>
</Box>
@ -176,6 +193,8 @@ export function Sidebar(): React.ReactElement {
})}
</List>
<WebPushControl />
<Box sx={{ px: 2, py: 1.5, borderTop: `1px solid ${d3roPalette.border.default}` }}>
<FormControl fullWidth size="small">
<InputLabel
@ -183,18 +202,18 @@ export function Sidebar(): React.ReactElement {
sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}
>
<PaletteIcon fontSize="inherit" />
{t('theme.label') ?? 'Theme'}
{t('theme.label')}
</InputLabel>
<Select<ThemeMode>
labelId="theme-mode-label"
id="theme-mode-select"
value={mode}
onChange={handleThemeChange}
label={t('theme.label') ?? 'Theme'}
label={t('theme.label')}
>
{AVAILABLE_MODES.map((m) => (
<MenuItem key={m} value={m}>
{t(`theme.${m}`) ?? m}
{t(`theme.${m}`)}
</MenuItem>
))}
</Select>
@ -208,7 +227,7 @@ export function Sidebar(): React.ReactElement {
<LogoutIcon />
</ListItemIcon>
<ListItemText
primary={t('nav.logout') ?? '로그아웃'}
primary={t('nav.logout')}
primaryTypographyProps={{ fontSize: 13, color: d3roPalette.text.secondary }}
/>
</ListItemButton>

View file

@ -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<ControlStatus>('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<void> {
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 (
<Box sx={{ px: 2, py: 1.5, borderTop: `1px solid ${d3roPalette.border.default}` }}>
<Box sx={{ minHeight: 44, display: 'flex', alignItems: 'center', gap: 1 }}>
<NotificationsNoneIcon
aria-hidden="true"
sx={{ width: 20, height: 20, color: d3roPalette.text.label }}
/>
<Box
id="web-push-label"
sx={{ flex: 1, color: d3roPalette.text.secondary, fontSize: 13 }}
>
{t('web.push.label')}
</Box>
<Box
component="label"
htmlFor="web-push-toggle"
sx={{
width: 44,
height: 44,
flexShrink: 0,
display: 'grid',
placeItems: 'center',
cursor: disabled ? 'not-allowed' : 'pointer',
}}
>
<Switch
id="web-push-toggle"
size="small"
checked={enabled}
disabled={disabled}
onChange={(_event, checked) => 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',
},
}}
/>
</Box>
</Box>
<Box
id="web-push-status"
role="status"
aria-live="polite"
aria-atomic="true"
sx={{
minHeight: 32,
mt: 0.5,
color: isError ? d3roPalette.status.danger : d3roPalette.text.muted,
fontSize: 11,
lineHeight: 1.45,
}}
>
{t(STATUS_MESSAGE_KEYS[status])}
</Box>
</Box>
)
}

View file

@ -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<typeof getSupabaseBrowserClient>
type StorageAdapter = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
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<string, unknown>
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<WebDeviceRegistration | null> {
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<WebDeviceRegistration | null> {
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<WebDeviceRegistration> {
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)
}

View file

@ -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<void>,
signOut: () => Promise<unknown>,
): Promise<void> {
try {
void cleanup().catch(() => undefined)
} catch {
// Cleanup is best effort. Logout remains independently available.
}
await signOut()
}
function withSessionCleanupTimeout<T>(
operation: Promise<T>,
timeoutMs: number,
): Promise<T> {
const boundedTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0
? timeoutMs
: DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS
return new Promise<T>((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<Storage, 'getItem' | 'setItem' | 'removeItem'> {
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<WebPushConnectionStatus> {
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<void> {
// 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<void> {
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
}

View file

@ -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<typeof getSupabaseBrowserClient>
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<WebPushBrowserStatus> {
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<WebPushSubscriptionRecord> {
const serialized = JSON.stringify(subscription.toJSON())
const supabase = client ?? getSupabaseBrowserClient()
const nowIso = new Date().toISOString()
let result: Awaited<ReturnType<typeof supabase.rpc>>
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<string, unknown>)
: 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<void> {
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<WebPushSubscriptionRecord> {
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<string, unknown>)
: 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<WebPushSubscriptionRecord> {
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<T>(operation: PromiseLike<T>, timeoutMs: number): Promise<T> {
const boundedTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0
? timeoutMs
: DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS
return new Promise<T>((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<boolean> {
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<ReturnType<typeof supabase.rpc>>
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<boolean> {
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,
}
}

View file

@ -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()

View file

@ -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<typeof getSupabaseBrowserClient>
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<NotificationPermission>,
): () => 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<string, string>): 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<never>(() => 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<never>(() => 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<void>(() => undefined)
await expect(signOutWithoutWaitingForWebPushCleanup(
() => stalledCleanup,
async () => {
signOutCalls += 1
},
)).resolves.toBeUndefined()
expect(signOutCalls).toBe(1)
})
})

Some files were not shown because too many files have changed in this diff Show more