diff --git a/.claude/skills/refactor-wave/SKILL.md b/.claude/skills/refactor-wave/SKILL.md index ce22926..d2758a0 100644 --- a/.claude/skills/refactor-wave/SKILL.md +++ b/.claude/skills/refactor-wave/SKILL.md @@ -224,5 +224,8 @@ Node로 vitest를 돌리면 better-sqlite3 ABI 불일치로 수백 건이 가짜 | Wave 1 | 2026-07-22 | b820c78(WS1)·aef4428(WS2)·078304d(WS3)·87f2dac(WS4) | `docs/REFACTOR_WAVE1_REPORT.md` | | Wave 2 | 2026-07-22 | efac690(AMBER)·660e622(NATIVE)·00a99e4(POPUP)·4c25620(DEPS)·5b6e7aa(PATTERN) | `docs/REFACTOR_WAVE2_REPORT.md` | | Wave 3 | 2026-09-26 | 88f24d8(WS-A 계약)·b6fe588(WS-B 웹앱)·cd9d199(WS-C 중복 삭제)·dc43884(WS-D CI)·9297860(사이트) | `docs/REFACTOR_WAVE3_REPORT.md` | +| Wave 4 | 2026-11-04 | — (보고서 참조) | `docs/REFACTOR_WAVE4_REPORT.md` | +| Wave 5 | 2026-11-13 | f95bc9c 외 (보고서 참조) | `docs/REFACTOR_WAVE5_REPORT.md` | +| Wave 6 | 2026-11-14 | 워킹 트리 (미커밋) | `docs/REFACTOR_WAVE6_REPORT.md` | 다음 wave 추가 시 본 표 갱신. diff --git a/.eslintignore b/.eslintignore index 08316ec..735d005 100644 --- a/.eslintignore +++ b/.eslintignore @@ -12,8 +12,9 @@ build/ !apps/desktop/build/entitlements.mac.plist *.tsbuildinfo -# 별개 서브 프로젝트 (자체 lint 설정 사용) -site/ +# 별개 서브 프로젝트 (Deno 런타임) +site/dist/ +site/dist-ssr/ server/supabase/functions/ # 환경 diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 2f81b8e..1e3e82e 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -85,12 +85,26 @@ jobs: npm run test:hygiene:test npm run test:hygiene - - name: 보호 수용 테스트·품질 래칫 + - name: 보호 수용 테스트·품질 래칫·디자인/i18n 계약 run: | npm run check:protected-tests:test npm run check:protected-tests -- --base HEAD^ npm run test:quality:test npm run test:quality + npm run check:i18n:test + npm run check:i18n + npm run check:ds-contract:test + npm run check:ds-contract + npm run check:design:test + npm run check:design + npm run test:affected:test + npm run release:installer:smoke:test + + - name: 마케팅 사이트(site/) 정적 검사 + run: | + npm --prefix site ci --workspaces=false + npm run typecheck:site + npm run lint:site - name: 린트 run: npm run lint @@ -138,8 +152,17 @@ jobs: - name: 어드민 빌드 run: npm run build --workspace=@d3ro/admin - - name: 웹앱 프로덕션 빌드 - run: npm run build --workspace=@d3ro/web + - name: 웹앱 프로덕션 빌드 + 스모크(Chromium 설치 시) + run: | + npm run build --workspace=@d3ro/web + if [ -d "${PLAYWRIGHT_BROWSERS_PATH:-$HOME/.cache/ms-playwright}" ]; then + npm run test:acceptance:web + fi + + - name: 마케팅 사이트(site/) 프로덕션 빌드 + run: | + npm --prefix site ci --workspaces=false + npm --prefix site run build mobile-quality: name: 모바일 린트·타입·Jest diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index 19e3d4f..df65a58 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -76,7 +76,13 @@ jobs: env: WIN_CSC_LINK: "${{ secrets.WIN_CSC_LINK }}" WIN_CSC_KEY_PASSWORD: "${{ secrets.WIN_CSC_KEY_PASSWORD }}" - run: node scripts/ci/build-desktop-installer.mjs + run: | + node scripts/ci/build-desktop-installer.mjs + node scripts/ci/verify-desktop-installer-smoke.mjs --self-test + node scripts/ci/verify-desktop-installer-smoke.mjs + if ($env:D3RO_RUN_WINDOWS_E2E -eq '1') { + npm run test:acceptance:desktop + } - name: Forgejo 피드 게시 (latest.yml Ed25519 서명 + 공개 URL 검증) if: steps.feed.outputs.published != 'true' diff --git a/.gitignore b/.gitignore index 5d2919a..9257190 100644 --- a/.gitignore +++ b/.gitignore @@ -33,9 +33,7 @@ apps/desktop/build/sidecar.spec !apps/desktop/build/entitlements.mac.plist sidecar-dist/ -# Bundled binaries (download via scripts; SoX는 직접 커밋) -resources/sox/*.exe -resources/sox/*.dll +# Bundled binaries (SoX는 apps/desktop/resources/sox에 필수 런타임만 커밋) apps/desktop/resources/ollama/ apps/desktop/build/installer.nsh !apps/desktop/build/installer.nsh @@ -135,3 +133,4 @@ site/dist-ssr/ # Local reference clones /araso/ /.codex/ +/.pi/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ee72d9..8fd1f6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Plugin system for custom pipelines +## [1.17.0] - 2026-11-14 + +> Multi-surface quality, 12-locale parity, speaker diarization, tablet responsive layout, and stability hardening across Desktop, Mobile, Web, Admin, and Cloud services. + +### Added +- 12-locale product switcher across Desktop, Web (`LocaleSwitcher`), and Mobile (`index.native.tsx` + Onboarding/Settings/Account) backed by unified `2,500 keys × 12 locales` parity contracts. +- Speaker diarization across Desktop sidecar (`POST /diarize`), Web, and Mobile meeting transcripts with speaker badges and multi-speaker filter chips. +- Tablet and foldable responsive layouts (`@d3ro/ui-native/responsive`) with bounded content columns, 2-column grids, and fixed `FreeTierBanner` ad slot reservations. +- Monotonic `meeting_memos.revision` column and compare-and-swap conflict protection against A→B→A stale overwrites. +- Automated TDD 2.0 test-quality and protected-journey CI gates (`test:hygiene`, `test:quality`, `check:protected-tests`). + +### Changed +- Consolidated shared validation, formatting, IPC emission (`safeSendToRenderer`), mobile service/cache guards, and Supabase Edge JSON helpers (`jsonResponse`, `readJsonBody`) while deduplicating `@d3ro/core`, `@d3ro/ui`, and `.NET` helpers. +- Cached canvas wave gradients in `@d3ro/ui` and tuned search/chunk caches across Desktop and Mobile. + +### Fixed +- Desktop `OnlineLLMService.chatStream` abort, 401 token refresh, and malformed SSE handling; `UnifiedSearchService` tie-breakers and FTS5 fallbacks; `SqliteChunkStore` cache invalidation; `DiskWavAudioSink` file descriptor and size bounds; timer and sidecar lifecycle leaks. +- `@d3ro/i18n` async locale load race and unmount cleanup; `@d3ro/core` PII restoration, CSV BOM/CR escaping, timestamp, and search edge cases; renderer IPC/timer cleanup and Vanilla JS popup hardening. +- Mobile durable upload queue premature discard, audio recording lease cleanup, and unmount playback/locale races. +- Web `MarkdownPreview` DOM XSS/race protection and `WebPush` reentry guards; Admin cookie `sameSite`, CSRF, UUID validation, and cost bounds; `.NET` proxy Base64 bounds and `CancellationToken` propagation; Cloudflare Worker SSRF/timeout hardening; sidecar `UploadFile` handle and `/shutdown` thread cleanup. + ## [1.16.5] - 2026-11-06 > Transcript polish now guards what the model must not break, measured against the local model. diff --git a/apps/admin/src/app/(admin)/audit-log/[id]/page.tsx b/apps/admin/src/app/(admin)/audit-log/[id]/page.tsx index e205a5a..8b39265 100644 --- a/apps/admin/src/app/(admin)/audit-log/[id]/page.tsx +++ b/apps/admin/src/app/(admin)/audit-log/[id]/page.tsx @@ -10,6 +10,7 @@ import { requireManager } from '@/lib/admin-guard' import Link from 'next/link' import { notFound } from 'next/navigation' import { AuditDiffViewer } from '@/components/audit-diff-viewer' +import { DetailRow } from '@/components/detail-row' import { sanitizeAuditSnapshot } from '@/lib/audit-sanitize' interface PageProps { @@ -114,11 +115,11 @@ export default async function AuditLogDetailPage({ params }: PageProps): Promise Transaction Metadata - - - - - + + + + + @@ -164,14 +165,3 @@ export default async function AuditLogDetailPage({ params }: PageProps): Promise ) } - -function Row({ label, value, isMono }: { label: string; value: string; isMono?: boolean }): React.ReactElement { - return ( - - {label} - - {value} - - - ) -} diff --git a/apps/admin/src/app/(admin)/models/page.tsx b/apps/admin/src/app/(admin)/models/page.tsx index 8a322b2..7b094fd 100644 --- a/apps/admin/src/app/(admin)/models/page.tsx +++ b/apps/admin/src/app/(admin)/models/page.tsx @@ -3,7 +3,7 @@ // apps/admin/src/app/(admin)/models/page.tsx // D3RO Voice — Dynamic AI Models & Cloud STT Transcription Provider Manager (Midnight Glass v2) -import React, { useState, useEffect } from 'react' +import React, { useState, useEffect, useRef } from 'react' import { Box, Typography, @@ -111,19 +111,29 @@ export default function ServiceModelsPage(): React.ReactElement { const [llmCompletionCost, setLlmCompletionCost] = useState('0') const [llmMemo, setLlmMemo] = useState('') + const mountedRef = useRef(true) + const loadSeqRef = useRef(0) + const loadData = async () => { + const seq = ++loadSeqRef.current setDataError(null) try { const [sttData, llmData] = await Promise.all([fetchSttEndpointsClient(), fetchModelEndpointsClient()]) + if (!mountedRef.current || loadSeqRef.current !== seq) return setSttEndpoints(sttData) setLlmEndpoints(llmData) } catch (error) { + if (!mountedRef.current || loadSeqRef.current !== seq) return setDataError(error instanceof Error ? error.message : '관리자 백엔드에서 엔드포인트를 불러오지 못했습니다.') } } useEffect(() => { - loadData() + mountedRef.current = true + void loadData() + return () => { + mountedRef.current = false + } }, []) // ── STT Handlers ────────────────────────────────────────────────────────── @@ -160,11 +170,17 @@ export default function ServiceModelsPage(): React.ReactElement { setSttFallbackPriority(ep.fallbackPriority) setSttIsDefault(ep.isDefault) setSttTestModalResult(null) + setSttMemo('') setSttModalOpen(true) } const handleSaveSttEndpoint = async (e: React.FormEvent) => { e.preventDefault() + const parsedCostPerMinute = parseFloat(sttCostPerMinute) + if (!Number.isFinite(parsedCostPerMinute) || parsedCostPerMinute < 0) { + alert('분당 비용은 0 이상의 유효한 숫자여야 합니다.') + return + } setSttLoading(true) try { @@ -178,8 +194,8 @@ export default function ServiceModelsPage(): React.ReactElement { language: sttLanguage, prompt: sttPrompt ? sttPrompt : undefined, temperature: 0.0, - costPerMinute: parseFloat(sttCostPerMinute), - costPerSecond: parseFloat(sttCostPerMinute) / 60, + costPerMinute: parsedCostPerMinute, + costPerSecond: parsedCostPerMinute / 60, isDefault: sttIsDefault, isActive: true, fallbackPriority: sttFallbackPriority, @@ -193,11 +209,13 @@ export default function ServiceModelsPage(): React.ReactElement { } await loadData() - setSttModalOpen(false) + if (mountedRef.current) setSttModalOpen(false) } catch (err) { - alert('Error saving STT endpoint: ' + (err instanceof Error ? err.message : String(err))) + if (mountedRef.current) { + alert('Error saving STT endpoint: ' + (err instanceof Error ? err.message : String(err))) + } } finally { - setSttLoading(false) + if (mountedRef.current) setSttLoading(false) } } @@ -206,6 +224,7 @@ export default function ServiceModelsPage(): React.ReactElement { if (memo.length < 3) return try { await setDefaultSttEndpointClient(id, memo) + if (!mountedRef.current) return setSttEndpoints((prev) => prev.map((ep) => ({ ...ep, @@ -213,7 +232,9 @@ export default function ServiceModelsPage(): React.ReactElement { })) ) } catch (err) { - alert('Error: ' + (err instanceof Error ? err.message : String(err))) + if (mountedRef.current) { + alert('Error: ' + (err instanceof Error ? err.message : String(err))) + } } } @@ -221,11 +242,13 @@ export default function ServiceModelsPage(): React.ReactElement { setSttPingStatus((prev) => ({ ...prev, [id]: 'Testing...' })) try { const result = await testSttEndpointClient(id) + if (!mountedRef.current) return setSttPingStatus((prev) => ({ ...prev, [id]: result.success ? `⚡ OK • ${result.latencyMs}ms` : `❌ ${result.message}` })) } catch (error) { + if (!mountedRef.current) return setSttPingStatus((prev) => ({ ...prev, [id]: `❌ ${error instanceof Error ? error.message : 'Test failed'}` @@ -238,19 +261,21 @@ export default function ServiceModelsPage(): React.ReactElement { setSttTestModalResult(null) try { const result = await testSttEndpointClient(sttEditingId ?? 0, sttApiKey, sttEndpointUrl) + if (!mountedRef.current) return setSttTestModalResult({ success: result.success, message: result.message, ms: result.latencyMs, }) } catch (err) { + if (!mountedRef.current) return setSttTestModalResult({ success: false, message: err instanceof Error ? err.message : 'Test failed', ms: 0, }) } finally { - setTestingInModal(false) + if (mountedRef.current) setTestingInModal(false) } } @@ -260,9 +285,13 @@ export default function ServiceModelsPage(): React.ReactElement { if (memo.length < 3) return try { await deleteSttEndpointClient(id, memo) - setSttEndpoints((prev) => prev.filter((ep) => ep.id !== id)) + if (mountedRef.current) { + setSttEndpoints((prev) => prev.filter((ep) => ep.id !== id)) + } } catch (err) { - alert('Error: ' + (err instanceof Error ? err.message : String(err))) + if (mountedRef.current) { + alert('Error: ' + (err instanceof Error ? err.message : String(err))) + } } } @@ -282,6 +311,15 @@ export default function ServiceModelsPage(): React.ReactElement { const handleAddLlmEndpoint = async (e: React.FormEvent) => { e.preventDefault() + const parsedPromptCost = parseFloat(llmPromptCost) + const parsedCompletionCost = parseFloat(llmCompletionCost) + if ( + !Number.isFinite(parsedPromptCost) || parsedPromptCost < 0 + || !Number.isFinite(parsedCompletionCost) || parsedCompletionCost < 0 + ) { + alert('토큰 비용은 0 이상의 유효한 숫자여야 합니다.') + return + } setLlmLoading(true) try { @@ -291,11 +329,12 @@ export default function ServiceModelsPage(): React.ReactElement { provider: llmProvider, endpointUrl: llmEndpointUrl, apiKey: llmApiKey, - costPer1kPromptTokens: parseFloat(llmPromptCost), - costPer1kCompletionTokens: parseFloat(llmCompletionCost), + costPer1kPromptTokens: parsedPromptCost, + costPer1kCompletionTokens: parsedCompletionCost, memo: llmMemo.trim(), }) await loadData() + if (!mountedRef.current) return setLlmModalOpen(false) setLlmModelId('') setLlmModelName('') @@ -303,9 +342,11 @@ export default function ServiceModelsPage(): React.ReactElement { setLlmApiKey('') setLlmMemo('') } catch (err) { - alert('Error: ' + (err instanceof Error ? err.message : String(err))) + if (mountedRef.current) { + alert('Error: ' + (err instanceof Error ? err.message : String(err))) + } } finally { - setLlmLoading(false) + if (mountedRef.current) setLlmLoading(false) } } @@ -315,9 +356,13 @@ export default function ServiceModelsPage(): React.ReactElement { if (memo.length < 3) return try { await deleteModelEndpointClient(id, memo) - setLlmEndpoints((current) => current.filter((endpoint) => endpoint.id !== id)) + if (mountedRef.current) { + setLlmEndpoints((current) => current.filter((endpoint) => endpoint.id !== id)) + } } catch (error) { - alert('Error: ' + (error instanceof Error ? error.message : String(error))) + if (mountedRef.current) { + alert('Error: ' + (error instanceof Error ? error.message : String(error))) + } } } diff --git a/apps/admin/src/app/(admin)/subscriptions/[id]/page.tsx b/apps/admin/src/app/(admin)/subscriptions/[id]/page.tsx index 7d97fef..275a1d7 100644 --- a/apps/admin/src/app/(admin)/subscriptions/[id]/page.tsx +++ b/apps/admin/src/app/(admin)/subscriptions/[id]/page.tsx @@ -7,6 +7,8 @@ import { DoubleBezelCard, TactileBadge } from '@d3ro/ui/components/ds' import { getSupabaseAdminClient, isSupabaseAdminConfigured } from '@/lib/supabase-admin' import { UnavailableAdminPanel } from '@/components/unavailable-admin-panel' import { requireManager, hasMinRole } from '@/lib/admin-guard' +import { ADMIN_UUID_PATTERN } from '@/lib/request-security' +import { DetailRow } from '@/components/detail-row' import Link from 'next/link' import { notFound } from 'next/navigation' import { SubscriptionDetailClient } from './client' @@ -16,6 +18,7 @@ interface PageProps { } export default async function SubscriptionDetailPage({ params }: PageProps): Promise { + const admin = await requireManager() if (!isSupabaseAdminConfigured()) { return ( - - - + + + @@ -135,11 +138,11 @@ export default async function SubscriptionDetailPage({ params }: PageProps): Pro Contract Status & Pricing - - - - - + + + + + @@ -215,14 +218,3 @@ export default async function SubscriptionDetailPage({ params }: PageProps): Pro ) } - -function Row({ label, value, isMono }: { label: string; value: string; isMono?: boolean }): React.ReactElement { - return ( - - {label} - - {value} - - - ) -} diff --git a/apps/admin/src/app/(admin)/users/[id]/page.tsx b/apps/admin/src/app/(admin)/users/[id]/page.tsx index 650a43e..9fc6bd3 100644 --- a/apps/admin/src/app/(admin)/users/[id]/page.tsx +++ b/apps/admin/src/app/(admin)/users/[id]/page.tsx @@ -7,6 +7,8 @@ import { DoubleBezelCard, TactileBadge } from '@d3ro/ui/components/ds' import { getSupabaseAdminClient, isSupabaseAdminConfigured } from '@/lib/supabase-admin' import { UnavailableAdminPanel } from '@/components/unavailable-admin-panel' import { requireManager, isAdmin } from '@/lib/admin-guard' +import { ADMIN_UUID_PATTERN } from '@/lib/request-security' +import { DetailRow } from '@/components/detail-row' import Link from 'next/link' import { notFound } from 'next/navigation' import { RoleChangeButton } from './role-change-button' @@ -17,6 +19,7 @@ interface PageProps { } export default async function AdminUserDetailPage({ params }: PageProps): Promise { + const admin = await requireManager() if (!isSupabaseAdminConfigured()) { return ( - - - - - + + + + + @@ -181,10 +184,10 @@ export default async function AdminUserDetailPage({ params }: PageProps): Promis - - - - + + + + @@ -280,19 +283,3 @@ export default async function AdminUserDetailPage({ params }: PageProps): Promis ) } - -function Row({ label, value, valueColor, isMono }: { - label: string - value: string - valueColor?: string - isMono?: boolean -}): React.ReactElement { - return ( - - {label} - - {value} - - - ) -} diff --git a/apps/admin/src/app/api/admin/backend/[...segments]/route.ts b/apps/admin/src/app/api/admin/backend/[...segments]/route.ts index 1645186..332cda5 100644 --- a/apps/admin/src/app/api/admin/backend/[...segments]/route.ts +++ b/apps/admin/src/app/api/admin/backend/[...segments]/route.ts @@ -1,6 +1,7 @@ import { NextRequest, NextResponse } from 'next/server' import { AdminBackendError, fetchAdminBackend } from '@/lib/backend-session' import type { AdminRole } from '@/lib/admin-session' +import { isSameOriginRequest, readBoundedTextBody } from '@/lib/request-security' export const runtime = 'nodejs' @@ -40,26 +41,6 @@ function requiredRole(method: string, path: string): AdminRole | null { return null } -function isSameOrigin(request: NextRequest): boolean { - const origin = request.headers.get('origin') - if (!origin) return request.headers.get('sec-fetch-site') !== 'cross-site' - try { - const requestOrigin = new URL(origin).origin - if (requestOrigin === request.nextUrl.origin) return true - - const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase() - const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() - ?? request.headers.get('host')?.trim() - if ((forwardedProto !== 'http' && forwardedProto !== 'https') || - !forwardedHost || !/^[A-Za-z0-9.:[\]-]+$/.test(forwardedHost)) { - return false - } - return requestOrigin === `${forwardedProto}://${forwardedHost}` - } catch { - return false - } -} - async function proxy( request: NextRequest, context: { params: Promise<{ segments: string[] }> } @@ -68,15 +49,19 @@ async function proxy( const path = pathFor(segments) const role = path ? requiredRole(request.method, path) : null if (!path || !role) return NextResponse.json({ error: 'admin_route_not_allowed' }, { status: 404 }) - if (request.method !== 'GET' && !isSameOrigin(request)) { + if (request.method !== 'GET' && !isSameOriginRequest(request)) { return NextResponse.json({ error: 'cross_site_request_rejected' }, { status: 403 }) } let body: string | undefined if (request.method !== 'GET') { - body = await request.text() - if (new TextEncoder().encode(body).byteLength > 64 * 1024) { - return NextResponse.json({ error: 'request_too_large' }, { status: 413 }) + try { + body = await readBoundedTextBody(request, 64 * 1024) + } catch (error) { + if (error instanceof AdminBackendError) { + return NextResponse.json({ error: error.message }, { status: error.status }) + } + return NextResponse.json({ error: 'invalid_request' }, { status: 400 }) } } diff --git a/apps/admin/src/app/api/admin/license/route.ts b/apps/admin/src/app/api/admin/license/route.ts index 27459af..7f5cb73 100644 --- a/apps/admin/src/app/api/admin/license/route.ts +++ b/apps/admin/src/app/api/admin/license/route.ts @@ -6,6 +6,7 @@ import { NextRequest, NextResponse } from 'next/server' import { issueSignedLicenseKey, type SignedLicensePayload } from '@d3ro/core/utils/crypto-license' import type { LicenseTier } from '@d3ro/core/types' import { AdminBackendError, fetchAdminBackend, requireVerifiedBackendSession } from '@/lib/backend-session' +import { isSameOriginRequest, readBoundedJsonObject } from '@/lib/request-security' export const runtime = 'nodejs' @@ -32,19 +33,12 @@ function resolveSigningKey(): string | null { return null } -function isSameOrigin(request: NextRequest): boolean { - const origin = request.headers.get('origin') - if (!origin) return request.headers.get('sec-fetch-site') !== 'cross-site' - try { - return new URL(origin).origin === request.nextUrl.origin - } catch { - return false - } -} - export async function POST(request: NextRequest): Promise { - if (!isSameOrigin(request)) { - return NextResponse.json({ error: 'cross_site_request_rejected' }, { status: 403 }) + if (!isSameOriginRequest(request)) { + return NextResponse.json( + { error: 'cross_site_request_rejected' }, + { status: 403, headers: { 'Cache-Control': 'no-store' } } + ) } try { @@ -52,20 +46,24 @@ export async function POST(request: NextRequest): Promise { } catch (error) { const status = error instanceof AdminBackendError ? error.status : 401 const message = error instanceof AdminBackendError ? error.message : 'admin_session_invalid' - return NextResponse.json({ error: message }, { status }) + return NextResponse.json({ error: message }, { status, headers: { 'Cache-Control': 'no-store' } }) } - let body: unknown + let candidate: Record try { - body = await request.json() - } catch { - return NextResponse.json({ error: 'invalid_request' }, { status: 400 }) + candidate = await readBoundedJsonObject(request, 16 * 1024) + } catch (error) { + if (error instanceof AdminBackendError) { + return NextResponse.json( + { error: error.message }, + { status: error.status, headers: { 'Cache-Control': 'no-store' } } + ) + } + return NextResponse.json( + { error: 'invalid_request' }, + { status: 400, headers: { 'Cache-Control': 'no-store' } } + ) } - if (!body || typeof body !== 'object' || Array.isArray(body)) { - return NextResponse.json({ error: 'invalid_request' }, { status: 400 }) - } - - const candidate = body as Record const customerEmail = typeof candidate.customerEmail === 'string' ? candidate.customerEmail.trim().toLowerCase() : '' const tier = candidate.tier const validity = typeof candidate.validity === 'string' ? candidate.validity : '' @@ -139,5 +137,5 @@ export async function POST(request: NextRequest): Promise { licenseId: payload.licenseId, expiresAt: payload.expiresAt, auditRecorded - }) + }, { headers: { 'Cache-Control': 'no-store' } }) } diff --git a/apps/admin/src/app/api/admin/supabase/[operation]/route.ts b/apps/admin/src/app/api/admin/supabase/[operation]/route.ts index 1af74b6..cea6ada 100644 --- a/apps/admin/src/app/api/admin/supabase/[operation]/route.ts +++ b/apps/admin/src/app/api/admin/supabase/[operation]/route.ts @@ -1,46 +1,17 @@ import { NextRequest, NextResponse } from 'next/server' import { AdminBackendError, requireVerifiedBackendSession } from '@/lib/backend-session' +import { ADMIN_UUID_PATTERN, isSameOriginRequest, readBoundedJsonObject } from '@/lib/request-security' import { getSupabaseAdminClient } from '@/lib/supabase-admin' export const runtime = 'nodejs' -const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i +const UUID = ADMIN_UUID_PATTERN const ROLES = new Set(['user', 'manager', 'admin', 'super_admin']) const TIERS = new Set(['free', 'pro', 'pro_plus']) const STATUSES = new Set(['active', 'canceled', 'past_due', 'expired']) -function sameOrigin(request: NextRequest): boolean { - const origin = request.headers.get('origin') - if (!origin) return request.headers.get('sec-fetch-site') !== 'cross-site' - try { - const requestOrigin = new URL(origin).origin - if (requestOrigin === request.nextUrl.origin) return true - const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase() - const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() - ?? request.headers.get('host')?.trim() - if ((forwardedProto !== 'http' && forwardedProto !== 'https') || - !forwardedHost || !/^[A-Za-z0-9.:[\]-]+$/.test(forwardedHost)) { - return false - } - return requestOrigin === `${forwardedProto}://${forwardedHost}` - } catch { - return false - } -} - async function bodyObject(request: NextRequest): Promise> { - if (request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') { - throw new AdminBackendError('application_json_required', 415) - } - const text = await request.text() - if (new TextEncoder().encode(text).byteLength > 32 * 1024) throw new AdminBackendError('request_too_large', 413) - try { - const parsed = JSON.parse(text) as unknown - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error() - return parsed as Record - } catch { - throw new AdminBackendError('invalid_request', 400) - } + return await readBoundedJsonObject(request, 32 * 1024, { requireJsonContentType: true }) } function onlyKeys(body: Record, allowed: readonly string[]): void { @@ -220,7 +191,7 @@ async function handlePayments(request: NextRequest): Promise { } async function route(request: NextRequest, context: { params: Promise<{ operation: string }> }): Promise { - if (request.method !== 'GET' && !sameOrigin(request)) { + if (request.method !== 'GET' && !isSameOriginRequest(request)) { return NextResponse.json({ error: 'cross_site_request_rejected' }, { status: 403 }) } try { diff --git a/apps/admin/src/app/api/auth/login/route.ts b/apps/admin/src/app/api/auth/login/route.ts index 4874751..454b022 100644 --- a/apps/admin/src/app/api/auth/login/route.ts +++ b/apps/admin/src/app/api/auth/login/route.ts @@ -1,4 +1,6 @@ import { NextResponse } from 'next/server' +import { AdminBackendError } from '@/lib/backend-session' +import { readBoundedJsonObject } from '@/lib/request-security' import { checkRateLimit, recordFailedAttempt, @@ -52,23 +54,24 @@ function failure(key: string, status: number, retryAfterSeconds?: number): NextR }, { status, - headers: retryAfterSeconds ? { 'Retry-After': String(retryAfterSeconds) } : undefined + headers: { + 'Cache-Control': 'no-store', + ...(retryAfterSeconds ? { 'Retry-After': String(retryAfterSeconds) } : {}) + } } ) } export async function POST(request: Request): Promise { - let body: unknown + let candidate: Record try { - body = await request.json() - } catch { + candidate = await readBoundedJsonObject(request, 16 * 1024) + } catch (error) { + if (error instanceof AdminBackendError) { + return failure(error.message, error.status) + } return failure('invalid_request', 400) } - if (!body || typeof body !== 'object' || Array.isArray(body)) { - return failure('invalid_request', 400) - } - - const candidate = body as Record if (candidate.trap) return failure('access_denied', 403) const email = typeof candidate.usernameOrEmail === 'string' @@ -132,10 +135,13 @@ export async function POST(request: Request): Promise { expiresAt }) - const response = NextResponse.json({ - success: true, - user: { email: authenticatedEmail, role } - }) + const response = NextResponse.json( + { + success: true, + user: { email: authenticatedEmail, role } + }, + { headers: { 'Cache-Control': 'no-store' } } + ) response.cookies.set({ name: 'd3ro_admin_session', value: signedCookieValue, diff --git a/apps/admin/src/app/api/auth/logout/route.ts b/apps/admin/src/app/api/auth/logout/route.ts index 9bf6e13..d5399d6 100644 --- a/apps/admin/src/app/api/auth/logout/route.ts +++ b/apps/admin/src/app/api/auth/logout/route.ts @@ -1,40 +1,49 @@ // apps/admin/src/app/api/auth/logout/route.ts // D3RO Voice — Admin Session Logout Handler -import { NextResponse } from 'next/server' +import { NextRequest, NextResponse } from 'next/server' import { adminCookieSecure } from '@/lib/admin-session' +import { isSameOriginRequest } from '@/lib/request-security' -export async function POST(): Promise { - const response = NextResponse.json({ success: true, message: 'Logged out successfully' }) - +function clearAdminSessionCookie(response: NextResponse): NextResponse { response.cookies.set({ name: 'd3ro_admin_session', value: '', httpOnly: true, secure: adminCookieSecure(), - sameSite: 'lax', + sameSite: 'strict', path: '/', maxAge: 0, expires: new Date(0), }) - return response } -export async function GET(request: Request): Promise { +export async function POST(request: NextRequest): Promise { + if (!isSameOriginRequest(request)) { + return NextResponse.json( + { error: 'cross_site_request_rejected' }, + { status: 403, headers: { 'Cache-Control': 'no-store' } } + ) + } + + const response = NextResponse.json( + { success: true, message: 'Logged out successfully' }, + { headers: { 'Cache-Control': 'no-store' } } + ) + return clearAdminSessionCookie(response) +} + +export async function GET(request: NextRequest): Promise { + if (request.headers.get('sec-fetch-site') === 'cross-site') { + return NextResponse.json( + { error: 'cross_site_request_rejected' }, + { status: 403, headers: { 'Cache-Control': 'no-store' } } + ) + } + const url = new URL(request.url) const response = NextResponse.redirect(new URL('/login', url.origin)) - - response.cookies.set({ - name: 'd3ro_admin_session', - value: '', - httpOnly: true, - secure: adminCookieSecure(), - sameSite: 'lax', - path: '/', - maxAge: 0, - expires: new Date(0), - }) - - return response + response.headers.set('Cache-Control', 'no-store') + return clearAdminSessionCookie(response) } diff --git a/apps/admin/src/components/checksum-copy.tsx b/apps/admin/src/components/checksum-copy.tsx index 9f4af04..36c32aa 100644 --- a/apps/admin/src/components/checksum-copy.tsx +++ b/apps/admin/src/components/checksum-copy.tsx @@ -1,6 +1,6 @@ 'use client' -import { useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { Box, Tooltip } from '@mui/material' import { Check, Copy } from 'lucide-react' import { C, FONT_MONO } from '@/lib/console-theme' @@ -11,12 +11,33 @@ interface ChecksumCopyProps { export function ChecksumCopy({ value }: ChecksumCopyProps): React.ReactElement { const [copied, setCopied] = useState(false) + const mountedRef = useRef(true) + const resetTimerRef = useRef | null>(null) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + if (resetTimerRef.current !== null) { + clearTimeout(resetTimerRef.current) + resetTimerRef.current = null + } + } + }, []) const handleCopy = (): void => { - void navigator.clipboard.writeText(value).then(() => { - setCopied(true) - setTimeout(() => setCopied(false), 2000) - }) + if (!navigator.clipboard?.writeText) return + void navigator.clipboard.writeText(value) + .then(() => { + if (!mountedRef.current) return + setCopied(true) + if (resetTimerRef.current !== null) clearTimeout(resetTimerRef.current) + resetTimerRef.current = setTimeout(() => { + resetTimerRef.current = null + if (mountedRef.current) setCopied(false) + }, 2000) + }) + .catch(() => undefined) } return ( diff --git a/apps/admin/src/components/detail-row.tsx b/apps/admin/src/components/detail-row.tsx new file mode 100644 index 0000000..0011f71 --- /dev/null +++ b/apps/admin/src/components/detail-row.tsx @@ -0,0 +1,37 @@ +import { Box, Typography } from '@mui/material' +import { C, FONT_MONO, FONT_SANS } from '@/lib/console-theme' + +interface DetailRowProps { + label: string + value: string + valueColor?: string + isMono?: boolean +} + +export function DetailRow({ label, value, valueColor, isMono }: DetailRowProps): React.ReactElement { + return ( + + + {label} + + + {value} + + + ) +} diff --git a/apps/admin/src/components/license-issuer-dialog.tsx b/apps/admin/src/components/license-issuer-dialog.tsx index 7594ef7..55655d2 100644 --- a/apps/admin/src/components/license-issuer-dialog.tsx +++ b/apps/admin/src/components/license-issuer-dialog.tsx @@ -3,7 +3,7 @@ // apps/admin/src/components/license-issuer-dialog.tsx // Ed25519 라이선스 발급 다이얼로그 — 서명은 서버(/api/admin/license)에서만 수행한다. -import { useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { Dialog, DialogTitle, @@ -52,6 +52,19 @@ export function LicenseIssuerDialog({ open, onClose }: LicenseIssuerDialogProps) const [loading, setLoading] = useState(false) const [copied, setCopied] = useState(false) const [error, setError] = useState(null) + const mountedRef = useRef(true) + const copyTimerRef = useRef | null>(null) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + if (copyTimerRef.current !== null) { + clearTimeout(copyTimerRef.current) + copyTimerRef.current = null + } + } + }, []) const handleGenerate = async (): Promise => { setError(null) @@ -78,20 +91,31 @@ export function LicenseIssuerDialog({ open, onClose }: LicenseIssuerDialogProps) if (!response.ok || data.success !== true || typeof data.licenseKey !== 'string') { throw new Error(describeIssueError(data.error)) } + if (!mountedRef.current) return setGeneratedKey(data.licenseKey) setAuditRecorded(data.auditRecorded !== false) } catch (err) { - setError(err instanceof Error ? err.message : 'Failed to generate license key') + if (mountedRef.current) { + setError(err instanceof Error ? err.message : 'Failed to generate license key') + } } finally { - setLoading(false) + if (mountedRef.current) setLoading(false) } } const handleCopy = (): void => { - if (!generatedKey) return + if (!generatedKey || !navigator.clipboard?.writeText) return void navigator.clipboard.writeText(generatedKey) - setCopied(true) - setTimeout(() => setCopied(false), 3000) + .then(() => { + if (!mountedRef.current) return + setCopied(true) + if (copyTimerRef.current !== null) clearTimeout(copyTimerRef.current) + copyTimerRef.current = setTimeout(() => { + copyTimerRef.current = null + if (mountedRef.current) setCopied(false) + }, 3000) + }) + .catch(() => undefined) } const inputSx = { diff --git a/apps/admin/src/components/payment-history.tsx b/apps/admin/src/components/payment-history.tsx index 6610122..c62aad7 100644 --- a/apps/admin/src/components/payment-history.tsx +++ b/apps/admin/src/components/payment-history.tsx @@ -36,17 +36,25 @@ export function PaymentHistory({ userId }: PaymentHistoryProps): React.ReactElem const [error, setError] = useState(null) useEffect(() => { + let active = true + setLoading(true) + setError(null) const load = async (): Promise => { try { - const result = await callAdminApi(`admin-payments?userId=${userId}`) + const result = await callAdminApi(`admin-payments?userId=${encodeURIComponent(userId)}`) + if (!active) return setData(result) } catch (caught) { + if (!active) return setError(caught instanceof Error ? caught.message : 'Failed to load payment data') } finally { - setLoading(false) + if (active) setLoading(false) } } void load() + return () => { + active = false + } }, [userId]) if (loading) { diff --git a/apps/admin/src/lib/admin-guard.ts b/apps/admin/src/lib/admin-guard.ts index 07bdcdc..cca94e9 100644 --- a/apps/admin/src/lib/admin-guard.ts +++ b/apps/admin/src/lib/admin-guard.ts @@ -3,6 +3,7 @@ import { cookies } from 'next/headers' import { redirect } from 'next/navigation' +import { hasMinimumAdminRole } from '@d3ro/core/admin-roles' import { verifySession } from './security' import type { AdminRole } from './admin-session' @@ -57,9 +58,7 @@ export async function requireSuperAdmin(): Promise { export function hasMinRole(user?: AdminUser | null, minRole: AdminRole = 'manager'): boolean { if (!user) return false - if (user.role === 'super_admin') return true - if (user.role === 'admin' && minRole !== 'super_admin') return true - return user.role === minRole + return hasMinimumAdminRole(user.role, minRole) } export function isSuperAdmin(user?: AdminUser | null): boolean { diff --git a/apps/admin/src/lib/request-security.ts b/apps/admin/src/lib/request-security.ts new file mode 100644 index 0000000..f95a590 --- /dev/null +++ b/apps/admin/src/lib/request-security.ts @@ -0,0 +1,94 @@ +import 'server-only' + +import type { NextRequest } from 'next/server' +import { AdminBackendError } from '@/lib/backend-session' + +export const ADMIN_UUID_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i + +export function isSameOriginRequest(request: Pick): boolean { + const origin = request.headers.get('origin') + if (!origin) return request.headers.get('sec-fetch-site') !== 'cross-site' + try { + const requestOrigin = new URL(origin).origin + if (requestOrigin === request.nextUrl.origin) return true + + const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase() + const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() + ?? request.headers.get('host')?.trim() + if ( + (forwardedProto !== 'http' && forwardedProto !== 'https') + || !forwardedHost + || !/^[A-Za-z0-9.:[\]-]+$/.test(forwardedHost) + ) { + return false + } + return requestOrigin === `${forwardedProto}://${forwardedHost}` + } catch { + return false + } +} + +export async function readBoundedTextBody(request: Request, maxBytes: number): Promise { + const contentLengthHeader = request.headers.get('content-length')?.trim() + if (contentLengthHeader) { + const declaredLength = Number(contentLengthHeader) + if (Number.isFinite(declaredLength) && declaredLength > maxBytes) { + throw new AdminBackendError('request_too_large', 413) + } + } + + if (!request.body) { + return '' + } + + const reader = request.body.getReader() + const chunks: Uint8Array[] = [] + let totalBytes = 0 + + try { + for (let next = await reader.read(); !next.done; next = await reader.read()) { + const { value } = next + totalBytes += value.byteLength + if (totalBytes > maxBytes) { + await reader.cancel().catch(() => undefined) + throw new AdminBackendError('request_too_large', 413) + } + chunks.push(value) + } + } finally { + reader.releaseLock() + } + + const combined = new Uint8Array(totalBytes) + let offset = 0 + for (const chunk of chunks) { + combined.set(chunk, offset) + offset += chunk.byteLength + } + return new TextDecoder().decode(combined) +} + +export async function readBoundedJsonObject( + request: Request, + maxBytes: number, + options: { requireJsonContentType?: boolean } = {}, +): Promise> { + if (options.requireJsonContentType) { + const contentType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() + if (contentType !== 'application/json') { + throw new AdminBackendError('application_json_required', 415) + } + } + + const text = await readBoundedTextBody(request, maxBytes) + try { + const parsed = JSON.parse(text) as unknown + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error('non_object_json') + } + return parsed as Record + } catch { + throw new AdminBackendError('invalid_request', 400) + } +} diff --git a/apps/api-server.Tests/SttControllerSecurityTests.cs b/apps/api-server.Tests/SttControllerSecurityTests.cs index 6c5039e..dfc4eac 100644 --- a/apps/api-server.Tests/SttControllerSecurityTests.cs +++ b/apps/api-server.Tests/SttControllerSecurityTests.cs @@ -91,6 +91,24 @@ public sealed class SttControllerSecurityTests Assert.Equal("edge-internal", service.LastUserEmail); } + [Fact] + public async Task InternalGateway_PropagatesRequestAbortedTokenToSttService() + { + var service = new RecordingSttService(); + using var cts = new CancellationTokenSource(); + var controller = CreateController( + service, + null, + isAuthenticated: false, + suppliedGatewayToken: GatewayToken, + includeAudioForm: true, + requestAborted: cts.Token); + + await controller.TranscribeFromQuotaGateway(); + + Assert.Equal(cts.Token, service.LastCancellationToken); + } + private static SttController CreateController( RecordingSttService service, string? userId, @@ -98,7 +116,8 @@ public sealed class SttControllerSecurityTests string? email = null, string configuredGatewayToken = GatewayToken, string? suppliedGatewayToken = null, - bool includeAudioForm = false) + bool includeAudioForm = false, + CancellationToken requestAborted = default) { var claims = new List(); if (userId != null) claims.Add(new Claim(ClaimTypes.NameIdentifier, userId)); @@ -106,7 +125,8 @@ public sealed class SttControllerSecurityTests var identity = new ClaimsIdentity(claims, isAuthenticated ? "test-auth" : null); var context = new DefaultHttpContext { - User = new ClaimsPrincipal(identity) + User = new ClaimsPrincipal(identity), + RequestAborted = requestAborted }; if (includeAudioForm) { @@ -152,6 +172,7 @@ public sealed class SttControllerSecurityTests public int LastUserId { get; private set; } public string? LastUserEmail { get; private set; } public bool LastRecordUsage { get; private set; } = true; + public CancellationToken LastCancellationToken { get; private set; } public Task TranscribeAsync( int userId, @@ -160,19 +181,25 @@ public sealed class SttControllerSecurityTests byte[]? audioBytes = null, string? contentType = null, string? fileName = null, - bool recordUsage = true) + bool recordUsage = true, + CancellationToken cancellationToken = default) { TranscribeCalls++; LastUserId = userId; LastUserEmail = userEmail; LastRecordUsage = recordUsage; + LastCancellationToken = cancellationToken; if (Exception != null) throw Exception; return Task.FromResult(new SttTranscribeResponse( "real transcript", 0.99, "ko", 1, "test", "test-model", 1, 0)); } - public Task TestEndpointAsync(int endpointId, string? testApiKey = null, string? testEndpointUrl = null) => + public Task TestEndpointAsync( + int endpointId, + string? testApiKey = null, + string? testEndpointUrl = null, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task> GetAllEndpointsAsync() => diff --git a/apps/api-server.Tests/SttFailClosedTests.cs b/apps/api-server.Tests/SttFailClosedTests.cs index 3ed359b..3706307 100644 --- a/apps/api-server.Tests/SttFailClosedTests.cs +++ b/apps/api-server.Tests/SttFailClosedTests.cs @@ -121,6 +121,108 @@ public sealed class SttFailClosedTests Assert.DoesNotContain(apiKey, fixture.Handler.LastRequestUri, StringComparison.Ordinal); } + [Fact] + public async Task OversizedAudioBase64_IsRejectedBeforeDecodingOrCallingProvider() + { + await using var fixture = await SttFixture.CreateAsync( + apiKey: "configured-key", + _ => throw new InvalidOperationException("HTTP should not be called")); + + // Over 26 MiB base64 payload (~36.4M chars), prefixed like a browser data URL. + var oversizedPayload = "data:audio/wav;base64," + new string('A', 36_400_000); + + await Assert.ThrowsAsync(() => + fixture.Service.TranscribeAsync( + 13, + "user@example.test", + new SttTranscribeRequest(AudioBase64: oversizedPayload, Language: "ko"))); + + Assert.Equal(0, fixture.Handler.CallCount); + Assert.Empty(await fixture.Db.SttUsageLogs.ToListAsync()); + } + + [Fact] + public async Task ClientCancellation_StopsFailoverChainBeforeCallingFallbackProvider() + { + using var cts = new CancellationTokenSource(); + await using var fixture = await SttFixture.CreateAsync( + apiKey: "configured-key", + req => + { + cts.Cancel(); + throw new OperationCanceledException(cts.Token); + }, + providerType: "groq", + endpointUrl: "https://primary.example.test/transcriptions"); + + fixture.Db.SttProviderEndpoints.Add(new SttProviderEndpoint + { + Name = "Backup provider", + ProviderType = "openai", + EndpointUrl = "https://fallback.example.test/transcriptions", + ApiKey = "backup-key", + ModelId = "whisper-backup", + Method = "multipart", + Language = "ko", + IsDefault = false, + IsActive = true, + FallbackPriority = 2 + }); + await fixture.Db.SaveChangesAsync(); + + await Assert.ThrowsAnyAsync(() => + fixture.Service.TranscribeAsync( + 14, + "user@example.test", + new SttTranscribeRequest(Language: "ko"), + new byte[] { 1, 2, 3 }, + "audio/webm", + "recording.webm", + cancellationToken: cts.Token)); + + Assert.Equal(1, fixture.Handler.CallCount); + Assert.Empty(await fixture.Db.ErrorLogs.ToListAsync()); + Assert.Empty(await fixture.Db.SttUsageLogs.ToListAsync()); + } + + [Fact] + public async Task LlmProxyService_ClientCancellation_PropagatesWithoutMockFallback() + { + await using var fixture = await SttFixture.CreateAsync( + apiKey: "unused", + _ => throw new OperationCanceledException()); + fixture.Db.ModelEndpoints.Add(new ServiceModelEndpoint + { + ModelId = "remote-llm", + ModelName = "Remote LLM", + Provider = "OpenAI", + EndpointUrl = "https://llm.example.test/v1/chat/completions", + ApiKey = "configured-llm-key", + CostPer1kPromptTokens = 0.001m, + CostPer1kCompletionTokens = 0.002m, + IsActive = true + }); + await fixture.Db.SaveChangesAsync(); + + using var cts = new CancellationTokenSource(); + cts.Cancel(); + var llmService = new LlmProxyService( + fixture.Db, + new StubHttpClientFactory(fixture.Handler), + NullLogger.Instance); + + await Assert.ThrowsAnyAsync(() => + llmService.GenerateAsync( + 15, + "user@example.test", + new LlmGenerateRequest("Hello", Model: "remote-llm"), + cts.Token)); + + Assert.Equal(0, fixture.Handler.CallCount); + Assert.Empty(await fixture.Db.UsageLogs.ToListAsync()); + Assert.Empty(await fixture.Db.ErrorLogs.ToListAsync()); + } + private sealed class SttFixture : IAsyncDisposable { private readonly SqliteConnection _connection; diff --git a/apps/api-server/Controllers/AdminController.cs b/apps/api-server/Controllers/AdminController.cs index 26d7ab9..aee54ad 100644 --- a/apps/api-server/Controllers/AdminController.cs +++ b/apps/api-server/Controllers/AdminController.cs @@ -303,7 +303,7 @@ public class AdminController : ControllerBase [HttpPost("stt-endpoints/{id}/test")] public async Task TestSttEndpoint(int id) { - var result = await _sttService.TestEndpointAsync(id); + var result = await _sttService.TestEndpointAsync(id, cancellationToken: HttpContext.RequestAborted); return Ok(result); } @@ -316,7 +316,7 @@ public class AdminController : ControllerBase return BadRequest(new { message = "유효한 HTTP(S) Endpoint URL이 필요합니다." }); } - var result = await _sttService.TestEndpointAsync(0, dto.ApiKey, endpointUri.AbsoluteUri); + var result = await _sttService.TestEndpointAsync(0, dto.ApiKey, endpointUri.AbsoluteUri, HttpContext.RequestAborted); return Ok(result); } diff --git a/apps/api-server/Controllers/LlmController.cs b/apps/api-server/Controllers/LlmController.cs index d44c8f0..98ae3ec 100644 --- a/apps/api-server/Controllers/LlmController.cs +++ b/apps/api-server/Controllers/LlmController.cs @@ -32,7 +32,7 @@ public class LlmController : ControllerBase return BadRequest(new { message = "Prompt는 필수 항목입니다." }); } - var result = await _llmService.GenerateAsync(userId, userEmail, request); + var result = await _llmService.GenerateAsync(userId, userEmail, request, HttpContext.RequestAborted); return Ok(result); } @@ -43,7 +43,7 @@ public class LlmController : ControllerBase var userEmail = User.FindFirstValue(ClaimTypes.Email) ?? "unknown@user"; int userId = int.TryParse(userIdStr, out var id) ? id : 0; - var result = await _llmService.ChatAsync(userId, userEmail, request); + var result = await _llmService.ChatAsync(userId, userEmail, request, HttpContext.RequestAborted); return Ok(result); } } diff --git a/apps/api-server/Controllers/SttController.cs b/apps/api-server/Controllers/SttController.cs index 12dafed..90b9aae 100644 --- a/apps/api-server/Controllers/SttController.cs +++ b/apps/api-server/Controllers/SttController.cs @@ -62,7 +62,7 @@ public class SttController : ControllerBase return StatusCode(StatusCodes.Status415UnsupportedMediaType, new { error = "unsupported_media_type" }); } - var form = await Request.ReadFormAsync(); + var form = await Request.ReadFormAsync(HttpContext.RequestAborted); var file = form.Files.GetFile("file") ?? form.Files.GetFile("audio"); if (file == null || file.Length == 0) { @@ -70,7 +70,7 @@ public class SttController : ControllerBase } await using var memoryStream = new MemoryStream(); - await file.CopyToAsync(memoryStream); + await file.CopyToAsync(memoryStream, HttpContext.RequestAborted); var language = form["language"].ToString(); var prompt = form["prompt"].ToString(); var request = new SttTranscribeRequest( @@ -89,9 +89,14 @@ public class SttController : ControllerBase memoryStream.ToArray(), file.ContentType ?? "application/octet-stream", file.FileName ?? "recording.bin", - recordUsage: false); + recordUsage: false, + cancellationToken: HttpContext.RequestAborted); return Ok(result); } + catch (OperationCanceledException) when (HttpContext.RequestAborted.IsCancellationRequested) + { + return StatusCode(499); + } catch (SttProviderUnavailableException) { return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "stt_provider_unavailable" }); @@ -112,20 +117,4 @@ public class SttController : ControllerBase var suppliedDigest = SHA256.HashData(Encoding.UTF8.GetBytes(supplied)); return CryptographicOperations.FixedTimeEquals(configuredDigest, suppliedDigest); } - - [HttpGet("providers")] - [Authorize(Policy = "ManagerOrAbove")] - public async Task GetActiveProviders() - { - var endpoints = await _sttService.GetAllEndpointsAsync(); - return Ok(endpoints); - } - - [HttpPost("test")] - [Authorize(Policy = "ManagerOrAbove")] - public async Task TestConnection([FromQuery] int endpointId = 0) - { - var result = await _sttService.TestEndpointAsync(endpointId); - return Ok(result); - } } diff --git a/apps/api-server/Services/LlmProxyService.cs b/apps/api-server/Services/LlmProxyService.cs index 3e828ef..000156b 100644 --- a/apps/api-server/Services/LlmProxyService.cs +++ b/apps/api-server/Services/LlmProxyService.cs @@ -4,6 +4,7 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; +using System.Threading; using System.Threading.Tasks; using D3ROVoice.Api.Data; using D3ROVoice.Api.Dtos; @@ -14,8 +15,8 @@ namespace D3ROVoice.Api.Services; public interface ILlmProxyService { - Task GenerateAsync(int userId, string userEmail, LlmGenerateRequest request); - Task ChatAsync(int userId, string userEmail, LlmChatRequest request); + Task GenerateAsync(int userId, string userEmail, LlmGenerateRequest request, CancellationToken cancellationToken = default); + Task ChatAsync(int userId, string userEmail, LlmChatRequest request, CancellationToken cancellationToken = default); } public class LlmProxyService : ILlmProxyService @@ -31,15 +32,16 @@ public class LlmProxyService : ILlmProxyService _logger = logger; } - public async Task GenerateAsync(int userId, string userEmail, LlmGenerateRequest request) + public async Task GenerateAsync(int userId, string userEmail, LlmGenerateRequest request, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); var modelId = string.IsNullOrWhiteSpace(request.Model) ? "d3ro-gpt4o-mini" : request.Model; - var endpoint = await _db.ModelEndpoints.FirstOrDefaultAsync(m => m.ModelId == modelId && m.IsActive); + var endpoint = await _db.ModelEndpoints.FirstOrDefaultAsync(m => m.ModelId == modelId && m.IsActive, cancellationToken); if (endpoint == null) { // fallback: first active model endpoint or create default mockup endpoint - endpoint = await _db.ModelEndpoints.FirstOrDefaultAsync(m => m.IsActive); + endpoint = await _db.ModelEndpoints.FirstOrDefaultAsync(m => m.IsActive, cancellationToken); if (endpoint == null) { endpoint = new ServiceModelEndpoint @@ -71,7 +73,7 @@ public class LlmProxyService : ILlmProxyService { try { - var client = _httpClientFactory.CreateClient(); + using var client = _httpClientFactory.CreateClient(); client.Timeout = TimeSpan.FromSeconds(60); var payload = new @@ -86,7 +88,7 @@ public class LlmProxyService : ILlmProxyService max_tokens = request.MaxTokens }; - var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) { Content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json") }; @@ -96,12 +98,12 @@ public class LlmProxyService : ILlmProxyService httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey); } - var httpResponse = await client.SendAsync(httpRequest); + using var httpResponse = await client.SendAsync(httpRequest, cancellationToken); sw.Stop(); if (httpResponse.IsSuccessStatusCode) { - var jsonStr = await httpResponse.Content.ReadAsStringAsync(); + var jsonStr = await httpResponse.Content.ReadAsStringAsync(cancellationToken); using var doc = JsonDocument.Parse(jsonStr); var root = doc.RootElement; @@ -124,6 +126,10 @@ public class LlmProxyService : ILlmProxyService completionTokens = Math.Max(15, responseText.Length / 4); } } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } catch (Exception ex) { sw.Stop(); @@ -165,7 +171,7 @@ public class LlmProxyService : ILlmProxyService }; _db.UsageLogs.Add(usageLog); - await _db.SaveChangesAsync(); + await _db.SaveChangesAsync(cancellationToken); return new LlmGenerateResponse( responseText, @@ -177,9 +183,9 @@ public class LlmProxyService : ILlmProxyService ); } - public async Task ChatAsync(int userId, string userEmail, LlmChatRequest request) + public async Task ChatAsync(int userId, string userEmail, LlmChatRequest request, CancellationToken cancellationToken = default) { var lastMsg = request.Messages.Count > 0 ? request.Messages[^1].Content : ""; - return await GenerateAsync(userId, userEmail, new LlmGenerateRequest(lastMsg, request.Model, null, request.Temperature, request.MaxTokens)); + return await GenerateAsync(userId, userEmail, new LlmGenerateRequest(lastMsg, request.Model, null, request.Temperature, request.MaxTokens), cancellationToken); } } diff --git a/apps/api-server/Services/SttProxyService.cs b/apps/api-server/Services/SttProxyService.cs index 5ce276a..aa4bc3a 100644 --- a/apps/api-server/Services/SttProxyService.cs +++ b/apps/api-server/Services/SttProxyService.cs @@ -7,6 +7,7 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; +using System.Threading; using System.Threading.Tasks; using D3ROVoice.Api.Data; using D3ROVoice.Api.Dtos; @@ -24,10 +25,15 @@ public interface ISttProxyService byte[]? audioBytes = null, string? contentType = null, string? fileName = null, - bool recordUsage = true + bool recordUsage = true, + CancellationToken cancellationToken = default ); - Task TestEndpointAsync(int endpointId, string? testApiKey = null, string? testEndpointUrl = null); + Task TestEndpointAsync( + int endpointId, + string? testApiKey = null, + string? testEndpointUrl = null, + CancellationToken cancellationToken = default); Task> GetAllEndpointsAsync(); Task CreateEndpointAsync(CreateSttEndpointDto dto); Task UpdateEndpointAsync(int id, UpdateSttEndpointDto dto); @@ -49,6 +55,9 @@ public sealed class SttProviderUnavailableException : Exception public class SttProxyService : ISttProxyService { + private const int MaxAudioBytes = 26 * 1024 * 1024; + private const int MaxBase64Length = ((MaxAudioBytes + 2) / 3) * 4; + private readonly AppDbContext _db; private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; @@ -67,32 +76,25 @@ public class SttProxyService : ISttProxyService byte[]? audioBytes = null, string? contentType = null, string? fileName = null, - bool recordUsage = true + bool recordUsage = true, + CancellationToken cancellationToken = default ) { + cancellationToken.ThrowIfCancellationRequested(); + // 1. Resolve Audio Bytes byte[] finalAudioBytes; if (audioBytes != null && audioBytes.Length > 0) { + if (audioBytes.Length > MaxAudioBytes) + { + throw new ArgumentException("Audio payload exceeds maximum allowed size."); + } finalAudioBytes = audioBytes; } else if (!string.IsNullOrWhiteSpace(request.AudioBase64)) { - try - { - var cleanBase64 = request.AudioBase64; - var commaIdx = cleanBase64.IndexOf(','); - if (commaIdx >= 0) - { - cleanBase64 = cleanBase64.Substring(commaIdx + 1); - } - finalAudioBytes = Convert.FromBase64String(cleanBase64); - } - catch (Exception ex) - { - _logger.LogError(ex, "Failed to decode base64 audio data"); - throw new ArgumentException("Invalid AudioBase64 data format.", ex); - } + finalAudioBytes = DecodeAudioBase64(request.AudioBase64); } else { @@ -104,7 +106,7 @@ public class SttProxyService : ISttProxyService var durationSeconds = EstimateAudioDuration(finalAudioBytes, effectiveContentType); // 2. Resolve Candidate Endpoints (Primary + Fallbacks) - var candidates = await GetCandidateEndpointsAsync(request.Provider, request.ModelId); + var candidates = await GetCandidateEndpointsAsync(request.Provider, request.ModelId, cancellationToken); if (candidates.Count == 0) { throw new SttProviderUnavailableException(providerAttempted: false); @@ -117,6 +119,7 @@ public class SttProxyService : ISttProxyService // 3. Failover Execution Chain foreach (var endpoint in candidates) { + cancellationToken.ThrowIfCancellationRequested(); var epSw = Stopwatch.StartNew(); try { @@ -136,7 +139,8 @@ public class SttProxyService : ISttProxyService finalAudioBytes, effectiveContentType, effectiveFileName, - request + request, + cancellationToken ); epSw.Stop(); @@ -167,7 +171,11 @@ public class SttProxyService : ISttProxyService CreatedAt = DateTime.UtcNow }; _db.SttUsageLogs.Add(usageLog); - await _db.SaveChangesAsync(); + await _db.SaveChangesAsync(cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; } catch (Exception dbEx) { @@ -186,6 +194,10 @@ public class SttProxyService : ISttProxyService Cost: cost ); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } catch (Exception ex) { epSw.Stop(); @@ -205,7 +217,11 @@ public class SttProxyService : ISttProxyService Endpoint = null, CreatedAt = DateTime.UtcNow }); - await _db.SaveChangesAsync(); + await _db.SaveChangesAsync(cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; } catch { @@ -220,15 +236,67 @@ public class SttProxyService : ISttProxyService throw new SttProviderUnavailableException(providerAttempted); } + private byte[] DecodeAudioBase64(string audioBase64) + { + var prefixScanLength = Math.Min(audioBase64.Length, 128); + var commaIdx = audioBase64.IndexOf(',', 0, prefixScanLength); + var payloadStart = commaIdx >= 0 ? commaIdx + 1 : 0; + var payloadLength = audioBase64.Length - payloadStart; + + if (payloadLength > MaxBase64Length) + { + throw new ArgumentException("AudioBase64 exceeds maximum allowed length."); + } + + try + { + var cleanBase64 = (payloadStart > 0 ? audioBase64.Substring(payloadStart) : audioBase64).Trim(); + if (cleanBase64.Length == 0 || cleanBase64.Length > MaxBase64Length) + { + throw new ArgumentException("Invalid AudioBase64 payload length."); + } + var decoded = Convert.FromBase64String(cleanBase64); + if (decoded.Length == 0 || decoded.Length > MaxAudioBytes) + { + throw new ArgumentException("Invalid decoded AudioBase64 payload size."); + } + return decoded; + } + catch (ArgumentException) + { + throw; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to decode base64 audio data"); + throw new ArgumentException("Invalid AudioBase64 data format.", ex); + } + } + + private static async Task SendForStringAsync( + HttpClient client, + HttpRequestMessage httpRequest, + CancellationToken cancellationToken) + { + using var response = await client.SendAsync(httpRequest, cancellationToken); + var responseBody = await response.Content.ReadAsStringAsync(cancellationToken); + if (!response.IsSuccessStatusCode) + { + throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}."); + } + return responseBody; + } + private async Task<(string Transcript, double Confidence, string? Language, double Duration)> ExecuteProviderTranscriptionAsync( SttProviderEndpoint endpoint, byte[] audioBytes, string contentType, string fileName, - SttTranscribeRequest request + SttTranscribeRequest request, + CancellationToken cancellationToken ) { - var client = _httpClientFactory.CreateClient(); + using var client = _httpClientFactory.CreateClient(); client.Timeout = TimeSpan.FromSeconds(90); var providerType = endpoint.ProviderType.ToLowerInvariant(); @@ -245,31 +313,31 @@ public class SttProxyService : ISttProxyService case "openai": case "custom": { - return await CallOpenAiCompatibleSttAsync(client, endpoint, audioBytes, contentType, fileName, request); + return await CallOpenAiCompatibleSttAsync(client, endpoint, audioBytes, contentType, fileName, request, cancellationToken); } case "deepgram": { - return await CallDeepgramSttAsync(client, endpoint, audioBytes, contentType, request); + return await CallDeepgramSttAsync(client, endpoint, audioBytes, contentType, request, cancellationToken); } case "google": { - return await CallGoogleSttAsync(client, endpoint, audioBytes, contentType, request); + return await CallGoogleSttAsync(client, endpoint, audioBytes, contentType, request, cancellationToken); } case "assemblyai": { - return await CallAssemblyAiSttAsync(client, endpoint, audioBytes, contentType, request); + return await CallAssemblyAiSttAsync(client, endpoint, audioBytes, contentType, request, cancellationToken); } case "azure": { - return await CallAzureSttAsync(client, endpoint, audioBytes, contentType, request); + return await CallAzureSttAsync(client, endpoint, audioBytes, contentType, request, cancellationToken); } case "local-sidecar": { - return await CallLocalSidecarSttAsync(client, endpoint, audioBytes, contentType, fileName, request); + return await CallLocalSidecarSttAsync(client, endpoint, audioBytes, contentType, fileName, request, cancellationToken); } default: { - return await CallOpenAiCompatibleSttAsync(client, endpoint, audioBytes, contentType, fileName, request); + return await CallOpenAiCompatibleSttAsync(client, endpoint, audioBytes, contentType, fileName, request, cancellationToken); } } } @@ -280,7 +348,8 @@ public class SttProxyService : ISttProxyService byte[] audioBytes, string contentType, string fileName, - SttTranscribeRequest request + SttTranscribeRequest request, + CancellationToken cancellationToken ) { using var form = new MultipartFormDataContent(); @@ -307,7 +376,7 @@ public class SttProxyService : ISttProxyService form.Add(new StringContent(temp.ToString("0.0")), "temperature"); form.Add(new StringContent("verbose_json"), "response_format"); - var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) { Content = form }; @@ -319,13 +388,7 @@ public class SttProxyService : ISttProxyService ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson); - var httpResponse = await client.SendAsync(httpRequest); - var responseBody = await httpResponse.Content.ReadAsStringAsync(); - - if (!httpResponse.IsSuccessStatusCode) - { - throw new HttpRequestException($"STT upstream returned HTTP {httpResponse.StatusCode}."); - } + var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken); using var doc = JsonDocument.Parse(responseBody); var root = doc.RootElement; @@ -356,7 +419,8 @@ public class SttProxyService : ISttProxyService SttProviderEndpoint endpoint, byte[] audioBytes, string contentType, - SttTranscribeRequest request + SttTranscribeRequest request, + CancellationToken cancellationToken ) { var lang = request.Language ?? endpoint.Language ?? "ko"; @@ -366,7 +430,7 @@ public class SttProxyService : ISttProxyService ? $"{baseUrl}&model={model}&language={lang}&smart_format=true&punctuate=true" : $"{baseUrl}?model={model}&language={lang}&smart_format=true&punctuate=true"; - var httpRequest = new HttpRequestMessage(HttpMethod.Post, url) + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url) { Content = new ByteArrayContent(audioBytes) }; @@ -379,13 +443,7 @@ public class SttProxyService : ISttProxyService ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson); - var response = await client.SendAsync(httpRequest); - var responseBody = await response.Content.ReadAsStringAsync(); - - if (!response.IsSuccessStatusCode) - { - throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}."); - } + var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken); using var doc = JsonDocument.Parse(responseBody); var root = doc.RootElement; @@ -421,7 +479,8 @@ public class SttProxyService : ISttProxyService SttProviderEndpoint endpoint, byte[] audioBytes, string contentType, - SttTranscribeRequest request + SttTranscribeRequest request, + CancellationToken cancellationToken ) { var base64Audio = Convert.ToBase64String(audioBytes); @@ -457,19 +516,13 @@ public class SttProxyService : ISttProxyService } }; - var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) { Content = new StringContent(JsonSerializer.Serialize(geminiPayload), Encoding.UTF8, "application/json") }; httpRequest.Headers.Add("X-Goog-Api-Key", apiKey); - var response = await client.SendAsync(httpRequest); - var responseBody = await response.Content.ReadAsStringAsync(); - - if (!response.IsSuccessStatusCode) - { - throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}."); - } + var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken); using var doc = JsonDocument.Parse(responseBody); var root = doc.RootElement; @@ -507,19 +560,13 @@ public class SttProxyService : ISttProxyService } }; - var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) { Content = new StringContent(JsonSerializer.Serialize(gcpPayload), Encoding.UTF8, "application/json") }; httpRequest.Headers.Add("X-Goog-Api-Key", apiKey); - var response = await client.SendAsync(httpRequest); - var responseBody = await response.Content.ReadAsStringAsync(); - - if (!response.IsSuccessStatusCode) - { - throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}."); - } + var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken); using var doc = JsonDocument.Parse(responseBody); var root = doc.RootElement; @@ -555,22 +602,18 @@ public class SttProxyService : ISttProxyService SttProviderEndpoint endpoint, byte[] audioBytes, string contentType, - SttTranscribeRequest request + SttTranscribeRequest request, + CancellationToken cancellationToken ) { // 1. Upload audio - var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.assemblyai.com/v2/upload") + using var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.assemblyai.com/v2/upload") { Content = new ByteArrayContent(audioBytes) }; uploadRequest.Headers.Add("Authorization", endpoint.ApiKey); - var uploadResp = await client.SendAsync(uploadRequest); - var uploadBody = await uploadResp.Content.ReadAsStringAsync(); - if (!uploadResp.IsSuccessStatusCode) - { - throw new HttpRequestException($"STT upstream upload returned HTTP {uploadResp.StatusCode}."); - } + var uploadBody = await SendForStringAsync(client, uploadRequest, cancellationToken); using var uploadDoc = JsonDocument.Parse(uploadBody); var uploadUrl = uploadDoc.RootElement.GetProperty("upload_url").GetString()!; @@ -585,18 +628,13 @@ public class SttProxyService : ISttProxyService format_text = true }; - var transRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.assemblyai.com/v2/transcript") + using var transRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.assemblyai.com/v2/transcript") { Content = new StringContent(JsonSerializer.Serialize(transcriptPayload), Encoding.UTF8, "application/json") }; transRequest.Headers.Add("Authorization", endpoint.ApiKey); - var transResp = await client.SendAsync(transRequest); - var transBody = await transResp.Content.ReadAsStringAsync(); - if (!transResp.IsSuccessStatusCode) - { - throw new HttpRequestException($"STT upstream job returned HTTP {transResp.StatusCode}."); - } + var transBody = await SendForStringAsync(client, transRequest, cancellationToken); using var transDoc = JsonDocument.Parse(transBody); var id = transDoc.RootElement.GetProperty("id").GetString()!; @@ -604,17 +642,11 @@ public class SttProxyService : ISttProxyService // 3. Poll for result (up to 20 seconds) for (int i = 0; i < 20; i++) { - await Task.Delay(1000); - var pollReq = new HttpRequestMessage(HttpMethod.Get, $"https://api.assemblyai.com/v2/transcript/{id}"); + await Task.Delay(1000, cancellationToken); + using var pollReq = new HttpRequestMessage(HttpMethod.Get, $"https://api.assemblyai.com/v2/transcript/{id}"); pollReq.Headers.Add("Authorization", endpoint.ApiKey); - var pollResp = await client.SendAsync(pollReq); - var pollBody = await pollResp.Content.ReadAsStringAsync(); - - if (!pollResp.IsSuccessStatusCode) - { - throw new HttpRequestException($"STT upstream poll returned HTTP {pollResp.StatusCode}."); - } + var pollBody = await SendForStringAsync(client, pollReq, cancellationToken); using var pollDoc = JsonDocument.Parse(pollBody); var status = pollDoc.RootElement.GetProperty("status").GetString(); @@ -647,7 +679,8 @@ public class SttProxyService : ISttProxyService SttProviderEndpoint endpoint, byte[] audioBytes, string contentType, - SttTranscribeRequest request + SttTranscribeRequest request, + CancellationToken cancellationToken ) { var lang = request.Language ?? endpoint.Language ?? "ko-KR"; @@ -657,7 +690,7 @@ public class SttProxyService : ISttProxyService ? $"{endpoint.EndpointUrl}&language={lang}&format=detailed" : $"{endpoint.EndpointUrl}?language={lang}&format=detailed"; - var httpRequest = new HttpRequestMessage(HttpMethod.Post, url) + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url) { Content = new ByteArrayContent(audioBytes) }; @@ -668,13 +701,7 @@ public class SttProxyService : ISttProxyService httpRequest.Headers.Add("Ocp-Apim-Subscription-Key", endpoint.ApiKey); } - var response = await client.SendAsync(httpRequest); - var responseBody = await response.Content.ReadAsStringAsync(); - - if (!response.IsSuccessStatusCode) - { - throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}."); - } + var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken); using var doc = JsonDocument.Parse(responseBody); var root = doc.RootElement; @@ -709,7 +736,8 @@ public class SttProxyService : ISttProxyService byte[] audioBytes, string contentType, string fileName, - SttTranscribeRequest request + SttTranscribeRequest request, + CancellationToken cancellationToken ) { using var form = new MultipartFormDataContent(); @@ -720,7 +748,7 @@ public class SttProxyService : ISttProxyService form.Add(new StringContent(endpoint.ModelId), "model"); form.Add(new StringContent(request.Language ?? endpoint.Language ?? "ko"), "language"); - var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) + using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) { Content = form }; @@ -730,13 +758,7 @@ public class SttProxyService : ISttProxyService httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey); } - var response = await client.SendAsync(httpRequest); - var responseBody = await response.Content.ReadAsStringAsync(); - - if (!response.IsSuccessStatusCode) - { - throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}."); - } + var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken); using var doc = JsonDocument.Parse(responseBody); var root = doc.RootElement; @@ -752,12 +774,16 @@ public class SttProxyService : ISttProxyService return (text, 0.99, endpoint.Language, duration); } - public async Task TestEndpointAsync(int endpointId, string? testApiKey = null, string? testEndpointUrl = null) + public async Task TestEndpointAsync( + int endpointId, + string? testApiKey = null, + string? testEndpointUrl = null, + CancellationToken cancellationToken = default) { SttProviderEndpoint? endpoint = null; if (endpointId > 0) { - endpoint = await _db.SttProviderEndpoints.FindAsync(endpointId); + endpoint = await _db.SttProviderEndpoints.FindAsync(new object[] { endpointId }, cancellationToken); } if (endpoint == null) @@ -792,7 +818,8 @@ public class SttProxyService : ISttProxyService syntheticWav, "audio/wav", "test_audio.wav", - new SttTranscribeRequest(Language: endpoint.Language ?? "ko") + new SttTranscribeRequest(Language: endpoint.Language ?? "ko"), + cancellationToken ); sw.Stop(); @@ -805,6 +832,10 @@ public class SttProxyService : ISttProxyService ModelId: endpoint.ModelId ); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } catch (Exception ex) { sw.Stop(); @@ -968,16 +999,19 @@ public class SttProxyService : ISttProxyService ); } - private async Task> GetCandidateEndpointsAsync(string? requestedProvider, string? requestedModel) + private async Task> GetCandidateEndpointsAsync( + string? requestedProvider, + string? requestedModel, + CancellationToken cancellationToken) { var query = _db.SttProviderEndpoints.Where(e => e.IsActive); if (!string.IsNullOrWhiteSpace(requestedProvider)) { - var match = await query.FirstOrDefaultAsync(e => e.ProviderType.ToLower() == requestedProvider.ToLower()); + var match = await query.FirstOrDefaultAsync(e => e.ProviderType.ToLower() == requestedProvider.ToLower(), cancellationToken); if (match != null) { - var others = await query.Where(e => e.Id != match.Id).OrderBy(e => e.FallbackPriority).ToListAsync(); + var others = await query.Where(e => e.Id != match.Id).OrderBy(e => e.FallbackPriority).ToListAsync(cancellationToken); others.Insert(0, match); return others; } @@ -985,10 +1019,10 @@ public class SttProxyService : ISttProxyService if (!string.IsNullOrWhiteSpace(requestedModel)) { - var match = await query.FirstOrDefaultAsync(e => e.ModelId.ToLower() == requestedModel.ToLower()); + var match = await query.FirstOrDefaultAsync(e => e.ModelId.ToLower() == requestedModel.ToLower(), cancellationToken); if (match != null) { - var others = await query.Where(e => e.Id != match.Id).OrderBy(e => e.FallbackPriority).ToListAsync(); + var others = await query.Where(e => e.Id != match.Id).OrderBy(e => e.FallbackPriority).ToListAsync(cancellationToken); others.Insert(0, match); return others; } @@ -998,7 +1032,7 @@ public class SttProxyService : ISttProxyService return await query .OrderByDescending(e => e.IsDefault) .ThenBy(e => e.FallbackPriority) - .ToListAsync(); + .ToListAsync(cancellationToken); } private static bool HasRequiredProviderConfiguration(SttProviderEndpoint endpoint) diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.yml index 00bf6fb..3f61199 100644 --- a/apps/desktop/electron-builder.yml +++ b/apps/desktop/electron-builder.yml @@ -22,8 +22,6 @@ files: - "!out/**/*.map" # ffmpeg 정적 바이너리(61MB)는 설치본에 넣지 않는다 — 필요할 때 런타임으로 내려받는다 - "!node_modules/@ffmpeg-installer/**" - # ffmpeg 정적 바이너리(61MB)는 설치본에 넣지 않는다 — 필요할 때 런타임으로 내려받는다 - - "!node_modules/@ffmpeg-installer/**" # ──────────────────────────────────────────────────────────────────── # 자동 업데이트 feed — 이 설정이 있어야 electron-builder가 @@ -41,12 +39,11 @@ publish: # electron-updater(기본 채널 latest)가 latest.yml을 찾으므로 항상 latest 채널로 고정. detectUpdateChannel: false -# native 모듈은 asar 외부에 배치 +# native 모듈은 asar 외부에 배치 (Windows 는 koffi SendInput 으로 단일화되어 @nut-tree-fork 불필요) asarUnpack: - "node_modules/better-sqlite3/**" - "node_modules/uiohook-napi/**" - - "node_modules/@nut-tree-fork/**" - # koffi — 포그라운드 창 제목/프로세스 조회(User32 FFI). prebuilt 바이너리 포함. + # koffi — 포그라운드 창 제목/프로세스 조회 및 SendInput(User32 FFI). prebuilt 바이너리 포함. - "node_modules/koffi/**" - "node_modules/@koromix/**" @@ -68,6 +65,9 @@ win: # macOS # ──────────────────────────────────────────────────────────────────── mac: + # macOS 키 입력 시뮬레이션(⌘+V / ⌘+C)은 @nut-tree-fork 네이티브 어댑터를 사용한다. + asarUnpack: + - "node_modules/@nut-tree-fork/**" # icns는 electron-builder가 build/icon.png(1024)에서 자동 생성 icon: build/icon.png category: public.app-category.productivity @@ -120,11 +120,17 @@ extraResources: filter: - "*.wav" - # SoX 바이너리 - # 주의: filter에 "**/*"를 쓰면 하위 디렉토리가 통째로 누락된다(실측). - # 디렉토리를 그대로 복사할 때는 filter를 지정하지 않는다. + # SoX 바이너리 (평면 파일만 허용 — wget.exe/PDF/문서 등 불필요 파일 유입 차단. + # 주의: "**/*" 패턴은 하위 디렉토리 누락 버그가 있으므로 평면 글롭만 사용한다) - from: resources/sox/ to: sox/ + filter: + - "sox.exe" + - "zlib1.dll" + - "LICENSE.GPL.txt" + - "sox" + - "*.dylib" + - "*.so*" # 주의: 로컬 AI 런타임(사이드카 엔진, ffmpeg)은 여기에 넣지 않는다. # 포함하면 설치본이 Cloudflare 업로드 한도(100MiB)를 넘어 자동 업데이트 메타데이터를 diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.ts index 6b8b6b1..dee4933 100644 --- a/apps/desktop/electron.vite.config.ts +++ b/apps/desktop/electron.vite.config.ts @@ -1,13 +1,29 @@ import { createPublicKey } from 'crypto' -import { readFileSync } from 'fs' +import { copyFileSync, mkdirSync, readdirSync, readFileSync } from 'fs' import { resolve } from 'path' import { defineConfig, externalizeDepsPlugin } from 'electron-vite' import react from '@vitejs/plugin-react' -const sharedAlias = { - '@d3ro/core': resolve(__dirname, '../../packages/core/src'), - '@d3ro/ui': resolve(__dirname, '../../packages/ui/src'), - '@d3ro/i18n': resolve(__dirname, '../../packages/i18n/src/index.tsx') +const sharedAlias = [ + { find: /^@d3ro\/i18n\/main$/, replacement: resolve(__dirname, '../../packages/i18n/src/main.ts') }, + { find: /^@d3ro\/i18n$/, replacement: resolve(__dirname, '../../packages/i18n/src/index.tsx') }, + { find: /^@d3ro\/core(\/.*)?$/, replacement: `${resolve(__dirname, '../../packages/core/src')}$1` }, + { find: /^@d3ro\/ui(\/.*)?$/, replacement: `${resolve(__dirname, '../../packages/ui/src')}$1` }, +] + +const copyMainLocalesPlugin = { + name: 'copy-main-locales', + writeBundle(options: { dir?: string }): void { + const outDir = options.dir ?? resolve(__dirname, 'out/main') + const srcDir = resolve(__dirname, '../../packages/i18n/src/locales') + const destDir = resolve(outDir, 'locales') + mkdirSync(destDir, { recursive: true }) + for (const file of readdirSync(srcDir)) { + if (file.endsWith('.json')) { + copyFileSync(resolve(srcDir, file), resolve(destDir, file)) + } + } + }, } const workspaceExclude = ['@d3ro/core', '@d3ro/ui', '@d3ro/i18n'] @@ -27,7 +43,8 @@ export default defineConfig({ plugins: [ externalizeDepsPlugin({ exclude: ['electron-store', ...workspaceExclude] - }) + }), + copyMainLocalesPlugin ], resolve: { alias: sharedAlias } }, diff --git a/apps/desktop/resources/sox/ChangeLog.txt b/apps/desktop/resources/sox/ChangeLog.txt deleted file mode 100644 index 8a947ea..0000000 --- a/apps/desktop/resources/sox/ChangeLog.txt +++ /dev/null @@ -1,1703 +0,0 @@ -Change History --------------- - -This file contains a list of all changes starting after the release of -sox-11gamma, followed by a list of prior authors and features. - -sox-14.4.1 2013-02-01 ----------- - -Newly deprecated features (to be removed in future): - - Deprec- Feature [O(ption)] Removal - ated in [F(ormat)] [E(ffect)] Replacement due after - ------- ---------------------- ---------------------- ------- - 14.4.1 OpenMP < 3.0 OpenMP >= 3.0 14.4.1 - 14.4.1 F ffmpeg ffmpeg/avconf via pipe 14.4.1 - -File formats: - - o Fix pipe file-type detection regression. (robs) - o MAUD write fixes. [3507927] (Carl Eric Codere and Ulrich Klauer) - o Fix crash when seeking within a FLAC file. [3476843] (Eric Wong) - o Fix Ogg Vorbis files with certain numbers of channels being - truncated. (Ulrich Klauer) - o Fix reading 64-bit float WAVs. [3481510] (nu774 and Ulrich Klauer) - o Fix potential buffer overrun when writing FLAC files directly via - sox_write(). [3474924] (Eric Wong) - -Audio device drivers: - - o Check whether pulseaudio is available before choosing it as - default. (robs) - -Effects: - - o Restore 8 seconds default for spectrogram, if the input length is - not known. (Ulrich Klauer) - o Set output length for splice to unknown instead of 0. (Ulrich Klauer) - o Increase maximum width for spectrograms. (Ulrich Klauer) - o Fix memory leaks in LADSPA effect. (Eric Wong) - o Fix hang in several effects (rate, tempo, and those based on - dft_filter) when processing long files. [3592482, 3594822] (MrMod) - o Prevent (m)compand from tampering with their arguments. (Ulrich Klauer) - -Other bug fixes: - - o Fix input length calculation for combine methods other than - concatenate. (Ulrich Klauer) - o Fix to configure.ac to work with Autoconf 2.69. [3600293] (cbagwell) - o Use binary mode for pipes on all Windows compilers, rather than - MSVC only. [3602130] (Ulrich Klauer) - - -sox-14.4.0 2012-03-04 ----------- - -Previously deprecated features that have been removed in this release: - - Deprec- Feature [O(ption)] - ated in [F(ormat)] [E(ffect)] Replacement - ------- ---------------------- ---------------------- - 14.3.0 O --interactive --no-clobber - 14.3.0 E filter ~= sinc - 14.3.0 E norm -b, norm -i gain -B, gain -en - 14.3.0 PLAY_RATE_ARG SOX_OPTS - 14.2.0 E key alias pitch - 14.2.0 E pan ~= remix - 14.1.0 E resample alias rate - 14.1.0 E polyphase alias rate - 14.1.0 E rabbit alias rate - 14.3.1 F sndfile: sndfile 1.0.11 sndfile > 1.0.11 - 14.3.0 F flac: libFLAC < 1.1.3 libFLAC >= 1.1.3 - 14.3.1 F mp3: lame 3.97 lame > 3.97 - -Newly deprecated features (to be removed in future): - - Deprec- Feature [O(ption)] Removal - ated in [F(ormat)] [E(ffect)] Replacement due after - ------- ---------------------- ---------------------- ------- - 14.4.0 E mixer remix 14.4.0 + 1 year - 14.4.0 E swap with parameters remix 14.4.0 - -Previously deprecated features (to be removed in future): - - Deprec- Feature [O(ption)] Removal - ated in [F(ormat)] [E(ffect)] Replacement due after - ------- ---------------------- ---------------------- ------- - 14.3.0 O -1/-2/-3/-4/-8 -b 14.4.0 - 14.3.0 O -s/-u/-f -e 14.4.0 - 14.3.0 O -A/-U/-o/-i/-a/-g -e 14.4.0 - -File formats: - - o Mention in man pages that WAV files support floating point encodings. - o Add support for floating point encodings in AIFF-C files. (Ulrich Klauer) - o Pad WAV data chunk to an even number of bytes (as required by the - specification). [3203418] (Ulrich Klauer) - o Add optional MP2 write support with twolame library. (Paul Kelly) - -Audio device drivers: - - o Give pulseaudio driver higher priority than alsa or oss now that - its proven stable and gives user more features; such as per app - volume control. (cbagwell) - o Fix bug when specifying OSX coreaudio device name. Would only - search for first 3 devices. (cbagwell) - o Fix sox hangups are exit when using coreaudio. (cbagwell) - o Improve buffering in coreaudio driver (Michael Chen) - o Support enabling play/rec mode when user invokes sox as either - play or play.exe on windows. (cbagwell) - o Fix compile of sunaudio driver on OpenBSD (cbagwell) - -Effects: - - o Improvements to man pages for tempo effect. Really made in 14.3.2. - (Jim Harkins). - o New upsample effect. (robs) - o Fix to effects pipeline to let fade effect specify time from end of - file again. (cbagwell and Thor Andreassen) - o Fix man page default error for splice effect. (Ulrich Klauer) - o Enable support for --plot option on biquad and fir effects. (Ulrich Klauer) - o Effects chain can now be unlimited in length. (Ulrich Klauer) - o Fix newfile/restart effects when merging or mixing files. (Ulrich Klauer) - o Fix crashes in compand and mcompand effects. [3420893] (Ulrich Klauer) - o Let the delay effect gracefully handle the special case that a delay can - be more than the input length. [3055399] (Ulrich Klauer) - o New hilbert and downsample effects. (Ulrich Klauer) - o Fix problem where fade would sometimes fail if specifying a fade-out - immediately after a fade-in. (robs) - o Stricter syntax checking for several effects (might reveal bugs hidden - in existing scripts). (Ulrich Klauer) - o Calculate output audio length for most effects. (Ulrich Klauer) - o Fix problems with several effects when the buffer size was not evenly - divisible by the number of channels. [3420899] (Ulrich Klauer) - o Complete rewrite of the trim effect with extended syntax (backwards - compatible) and capabilities. [FR 2941349] (Ulrich Klauer) - o Fix trim optimization unexpectedly seeking backwards. (Ulrich Klauer) - o Prevent samples from getting lost at effects chain transitions in - multiple effects chain/multiple output modes. (Ulrich Klauer) - -Misc: - - o Minor improvements to the man page. (Ulrich Klauer) - o When using pipes (-p) on Windows, set file mode to binary. (cbagwell) - o Updated .dat format description in soxformat. (Jan Stary) - o Doxygen documentation for libSoX. (Doug Cook) - -Other bug fixes: - - o Fix several memory leaks. [3309913] (Jin-Myung Won and Ulrich Klauer) - o Fixed crashes in apps that call sox_format_init/quit() multiple times. - (cbagwell) - -Internal improvements: - - o Added use_threads variable to sox_globals. This should be used to enable - or disable use of parallel effects processing instead of directly calling - omp_set_num_threads. (Doug Cook) - o Fix compiler warnings. (Cristian Morales Vega [P. 3072301], Doug Cook) - o Improve large file support by using 64-bit numbers to count - samples. (Doug Cook, Thor Andreassen, Ulrich Klauer) - -sox-14.3.2 2011-02-27 ----------- - -File formats: - - o Add seek support to mp3 handler for speed improvements. (Pavel Karneliuk) - o Fix bug were WavPack header was not updated correctly when closing - file. Fixed libsox memory leak when closing WavPack files. - (David Bryant) - o Fix RIFF chunk length error when writing 24-bit files. (David Bryant) - o 24-bit WAV files were leaving channel maps unassigned. Change to use - common channel mappings based on channel count. This allows to - work more seemlessly with other apps such as WavPack and Foobar2000. - (David Bryant) - o Fix ffmpeg playback bug caused by alignment requirements on some platforms. - Closes bug #3017690. (Reuben Thomas). - o Fix memory leak in ffmpeg. (Doug Cook) - o Handle 0 length chunks in WAV files gracefully. (Beat Jorg) - o When skipping over chunks, account for word alignment. Helps - with some Logic Pro generated files. (D Lambley) - o Fix incorrect MP3 file length determination with VBR & .5s initial - silence. (robs) - -Audio device drivers: - - o Fix immediate segfault on OSX while attempting to record. (Adam Fritzler) - o Fix segfault on OSX playback for some HW that gives smaller then - requested buffers. (cbagwell) - o Clean up system resource in coreaudio on close. Allows running - back-to-back open()/close()'s without exiting app first. (cbagwell) - o Add support for 32-bit samples to OSS driver. (Eric Lammerts) - o Add support for 24 and 32-bit samples to waveaudio (Win32) driver. - (Doug Cook) - o Support specifying audio device other than default on OSX (cbagwell) - -Effects: - - o F.R. [3051700] spectrogram -r for `raw' spectrogram, no legend. (robs) - o Fix -w option on stats effect. (Ronald Sprouse) - o Fix segfault with some ladspa plugins (Thor Andreassen) - o Optionally look for png.h in libpng directory to support OpenBSD - packaging. Helps enable spectrograph effect. (cbagwell) - o libpng15 requires application to include zlib.h header file. (cbagwell) - Add this to spectrograph effect. [3184238] - o Enable LADSPA effects on all platforms without any external - dependencies. Mainly useful for Linux, Windows and OS X which have - binaries readily available. (cbagwell) - o Support specifying an absolute end location for trim effect instead - only an offset from trim begin location. (Ulrich Klauer) - o Fix regression where MP3 handler required libmad headers to be installed. - (Samuli Suominen) - o Allow dynamic loading of lame to be enabled even if lame header files - are not installed. (Doug Cook) - -Other new features: - - o Soxi now reports duration of AMR files. (robs) - o Document the "multiple" combine option in man pages and in - usage output (Ulrich Klauer). - -Internal improvements: - - o Distribute msvc9 project files that had been in CVS only. (cbagwell) - o Add msvc10 project files (also compatible with the Windows SDK 7.1). - (Doug Cook) - o cmake now compiles waveaudio driver under windows environment. (cbagwell) - [3072672] - -sox-14.3.1 2010-04-11 ----------- - -Newly deprecated features (to be removed in future): - - Deprec- Feature [O(ption)] Removal - ated in [F(ormat)] [E(ffect)] Replacement due after - ------- ---------------------- ---------------------- ------- - 14.3.1 F mp3: lame 3.97 lame > 3.97 2011-04-11 - 14.3.1 F sndfile: sndfile 1.0.11 sndfile > 1.0.11 14.3.1 - -Previously deprecated features (to be removed in future): - - Deprec- Feature [O(ption)] Removal - ated in [F(ormat)] [E(ffect)] Replacement due after - ------- ---------------------- ---------------------- ------- - 14.2.0 E key alias pitch 14.3.1 - 14.2.0 E pan ~= mixer/remix 14.3.1 - 14.3.0 F flac: libFLAC 1.1.2,3 libFLAC > 1.1.3 14.3.1 - 14.3.0 PLAY_RATE_ARG SOX_OPTS 14.3.1 - 14.3.0 E norm -b, norm -i gain -B, gain -en 2010-06-14 - 14.3.0 E filter ~=sinc 2010-06-14 - 14.1.0 E resample alias rate 2010-06-14 - 14.1.0 E polyphase alias rate 2010-06-14 - 14.1.0 E rabbit alias rate 2010-06-14 - -LibSoX interface changes: - - o Added new variants of sox_open to allow read/write from/to memory - buffers (in POSIX 2008 environment); see example5.c. (robs) - -File formats: - - o New Grandstream ring-tone (gsrt) format. (robs) - o CVSD encode/decode speed-ups. (Kimberly Rockwell, P. Chaintreuil) - o Add ability to select MP3 compression parameters. (Jim Harkins) - o Now writes out ID3-tags in MP3 files with lame supports it. (Doug Cook) - o Also can write VBR Tag ("XING Header") in MP3 files. (Jim Hark / - Doug Cook) - o Increase percision of MP3 encoders to use 24-bits instead of - 16-bits. (Doug Cook) - o Fix failed writing 24-bit PAF files (and possibly other libsndfile - based formats). (cbagwell) - o Allow libsndfile to be dlopen()'ed at runtime if --enable-dl-sndfile - is used. (Doug Cook) - o Allow amr-nb/amr-wb to be dlopen()'ed at runtime if - --enable-dl-amrwb or --enable-dl-amrnb is used. (Doug Cook) - o amrnb and amrwb formats can optionally use opencore-amr libraries. - (cbagwell) - -Audio device drivers: - - o Add native windows audio driver. (Pavel Karneliuk, Doug Cook) - o Add 32-bit support to ALSA driver. (Pavel Hofman) - o Make OpenBSD sndio audio driver default over older sunau driver. - (cbagwell) - -Effects: - - o Fix [2254919] silence doesn't trim digital silence correctly. (robs) - o Fix [2859842] stats effect crashes on 64-bit arch. (Ulrich Klauer) - -Other new features: - - o Added libSoX example #4: concatenating audio files. (robs) - o Show soxi version & usage information when no args given. (robs) - -Other bug fixes: - - o Fix build so that grouped files (e.g. play -r 6k "*.vox" plays all - at 6k) works. (robs) - o Fix build to support auto file type detection with pipes on FreeBSD - and elsewhere. (Dan Nelson) - o Fix simultaneous play & rec not working. (robs) - o Fix multi-threading problems on multi-core Windows OS; also, change - default to single-threaded. - o Fix mistaken file size with pipe input on Windows. (Doug Cook) - o Fix missing documentation for -R (repeatable), and pulseaudio driver. - o Fix memory leak of format private data. (Slawomir Testowy) - -Internal improvements: - - o Move bit-rot detection support files to sub-directory (could - previously cause build problems). (robs) - o [2859244] Fixes to improve compatibility with MSVC. (Doug Cook) - o Added utilities to help any format handler dlopen() external - libraries at run time instead of link time. (Doug Cook) - o Compiling with mingw now has feature parity with cygwin. (Doug Cook - and cbagwell) - - - -sox-14.3.0 2009-06-14 ----------- - -Previously deprecated features that have been removed in this release: - - Deprec- Feature [O(ption)] - ated in [F(ormat)] [E(ffect)] Replacement - ------- ---------------------- ---------------------- - 14.1.0 E resample * ~= rate - 14.1.0 E polyphase * ~= rate - 14.1.0 E rabbit * ~= rate - 14.2.0 E dither: RPDF,scaled dither (TPDF only) - 14.1.0 F flac: libFLAC 1.1.1 libFLAC > 1.1.1 - - * But interface retained as an alias for `rate'. - -LibSoX interface changes: - - o sox_format_init() has been supeseded by sox_init(). - o Removed obsolete error codes (SOX_E...); new sox_strerror() - function to convert error codes to text. - o Use of sox_effect_options() is now mandatory when initialising an - effect (see example0.c for an example of this). - o sox_flow_effects() has a new (3rd) parameter: a void pointer - `client_data' that is passed as a new (2nd) parameter to the flow - callback function. client_data may be NULL. - -File formats: - - o Slight improvement to A-law/u-law conversion accuracy: round LSB - instead of truncating. (robs) - o Fix length in wav header with multi-channel output to pipe. (robs) - o Fix [2028181] w64 float format incompatibility. (Tim Munro) - o Fix reading AIFF files with pad bytes in COMT chunks. (Joe Holt) - o Fix AIFF file length bug to stop reading trash data on files that - have extra chunks at end of file. (Joe Holt) - o Fix file length being 4 bytes short for AIFF sowt CD tracks. (Joe Holt) - o Fix [2404566] segfault when converting from MS ADPCM wav file. (robs) - o Fix slight FLAC seek inaccuracy e.g. when using `trim' effect. (robs) - o Fix mp3 decode sometimes being up to a block short. (robs) - o Fix not outputing GSM-in-wav when input is GSM-in-wav. (robs) - -Audio device drivers: - - o New native OpenBSD audio handler for play/recording. (Alexandre Ratchov) - o 24-bit support for ALSA handler. (robs) - o Warn if ALSA under/overrun. (robs) - -Effects: - - o New `stats' effect; multichannel audio statistics. (robs) - o New `sinc' FFT filter effect; replacement for `filter'. (robs) - o New `fir' filter effect using external coefficients/file. (robs) - o New `biquad' filter effect using external coefficients. (robs) - o New `overdrive' effect. (robs) - o New `vad' Voice Activity Detector effect. (robs) - o `synth' enhancements: can now set common parameters for multiple - channels, new `pluck' and `tpdf' types, `scientific' note - notation, [2778142] just intonation. (robs) - o New multi-channel support and revised sizing options for `spectrogram'. - N.B. revised options are not directly backwards compatible -- see the - man page for details of the new syntax. (robs) - o Richer gain/normalise options. (robs) - o [2704442] Slight change to `riaa' gain: now norm'd to 0dB @ 1k - (previously 19.9dB @ DC). (Glenn Davis) - o Fix [2487589] `dither' clipping detection & handling. (robs) - o Fix `repeat' sometimes stopping repeating too soon. (robs) - o Fix `repeat' sometimes repeating wrong audio segments. (robs) - o Fix [2332343] 'silence' segfault with certain lengths. (cbagwell) - o Fix `silence' empty output file with A-law input. (robs) - o Fix temporary file problems in Windows (cygwin) with normalise and - other effects. (robs) - o Fix [2779041] spectrogram PNG file is invalid on Windows. (robs) - o Fix [2787587] `trim x 0' should produce zero length audio. (robs) - o Parallel effects channel processing on some hyper-threading/mult-core - architectures. New `--single-threaded' option to disable this. (robs) - -Other new features: - - o Added ability to create shared DLL's on cygwin (cbagwell) - o New `--guard' & `--norm' options; use temporary files to guard against - clipping for many, but not currently all, effects. (robs) - o New `--ignore-length' option to ignore length in input file header (for - simple encodings & for mp3); instead, read to end of file. (robs) - o New `--temp DIRECTORY' option. (robs) - o New `--play-rate-arg ARG' option. (robs) - o New SOX_OPTS environment variable; can be used to provide default - values for above and other options. (robs) - o Grouped files, e.g. play -r 6k "*.vox" plays all at 6k. (robs) - o Automatically `dither'; new `--no-dither' option to disable this. (robs) - o Can now use `v' & `V' keys to adjust volume whilst playing audio (on some - systems). (robs) - o New bitrate, time in seconds, & total options for soxi; bitrate - and file-size display for sox. (robs) - o `Magic' (libmagic) file type detection now selected using `--magic' - option (where supported). - o [2003121] In many cases, no longer need to specify -t when inputing - audio from a `pipe'. (robs) - o Support more Shoutcast URL variants. (robs) - o Added libSoX example #3: playing audio. (robs) - -Other bug fixes: - - o Fix [2262177] SoX build could fail with parse /etc/issue error. (robs) - o Fix "no handler for detected file type `application/octet-stream; - charset=binary'" with raw files when using libmagic. (robs) - -Internal improvements: - - o Rationalise use of and make repeatable across different platforms - pseudo random number generators. (robs) - o Rationalise effects' options interface (getopt compatible). (robs) - o Added stub headers to allow test compilation of all sources on - linux. (robs) - - -sox-14.2.0 2008-11-09 ----------- - -Previously deprecated features that have been removed in this release: - - Deprec- Feature [O(ption)] - ated in [F(ormat)] [E(ffect)] Replacement - ------- ---------------------- ---------------------- - 14.0.0 E pitch new pitch = old key - -File formats: - - o New `.cvu' unfiltered CVSD; supports any bit-rate. (robs) - o New `.sox' native format intended for intermediate files. (robs) - o Fix WAV write on 64-bit arch. (robs) - o Fix writing PRC ADPCM files. (Silas Brown) - o Fix problems reading short mp3 files. (robs) - -Effects: - - o N.B. Reduced default bandwidth setting for `rate' effect from 99% - to 95%; use `rate -s' to be compatible with SoX v14.1.0. (robs) - o New options for `rate' effect to configure phase response, - band-width and aliasing. (robs) - o New options for 'dither' effect: RPDF, TPDF, noise-shaping. (robs) - o New `riaa' effect: RIAA vinyl playback EQ. (robs) - o New `loudness' effect: gain control with ISO 226 loudness - compensation. (robs) - o New `bend' effect; pitch bending. (robs) - o New -b option for the norm effect; can be used to fix stereo - imbalance. (robs) - o Wider tempo range for `tempo' effect. (robs) - o New --effects-file option to read effects and arguments from - a file instead of command line. (cbagwell) - o `filter' effect now supports --plot. (robs) - o Improved documentation for the `stat' effect. (robs) - o Fix broken audio pass-through with noiseprof effect. (robs) - o Fix graph legend display when using --plot octave. (robs) - o Fix rare crash with `rate' effect. (robs) - o Fix [2190767] `norm' under-amplifying in some cases. (George Yohng) - o Fix [2007062] Earwax effect can overflow; should clip. (robs) - o Fix [2223251] mcompand should use linkwitz-riley. (robs) - o Fix `phaser' clicks and overflows. (robs) - o Trim will now skip past 2G point correctly. (cbagwell) - o Improved handling of speed changes in the effects chain. (robs) - -Other new features: - - o New psuedo-effects "newfile" and ":" to allow running - multiple effect chains on a single file. newfile will - create a new output file when an effect chain terminates. - Of most use with trim and silence effects. (cbagwell) - o Can now use multiple pipes as inputs to the combiner; - see `Special Filenames' in sox(1). (robs) - o Display SoX build/run environment information with -V -V. (robs) - o Display (with -V) the detected file-type if it differs from the - file extension. (robs) - o New -t option for soxi; to display the detected file type. (robs) - o New -b/--bits, -e/--encoding alternative options for specifying - audio encoding parameters. (robs) - o [FR 1958680] Support more than 32 input files. (robs) - o New native Mac OSX audio handler for playing/recording. (cbagwell) - -Other bug fixes: - - o Bump library version because it was not binary compatible with - SoX 14.0.1 (Pascal Giard) - o Turn off versioning of special libsox_fmt* libraries since thats - not really needed. (kwizart) - o Fixed crash when running play with no arguments. (Dan Nelson) - o Allow libpng to be found with -static option. (cbagwell) - o Allow libsamplerate to be found if pkg-config is installed but - no samplerate.pc exists. (cbagwell) - o [2038855] external lpc10 lib patch. (Oden Eriksson, Mandriva) - o Fix memory leaks in effects chain when restarting effects. (cbagwell) - o Fixed pkg-config CFLAGS. (evilynux) - o Fix sndfile inclusion in build in some circumstances. (robs) - o Fix [2026912] Fails on URL-like filenames. (robs) - o Always add _LARGEFILE_SUPPORT when off_t is 64bits to work around - buggy platforms. Fixes not able to read WAV files. (cbagwell) - -Internal improvements: - - o Fixed all compiler warnings (with gcc 4.3.1, 64-bit arch.). (robs) - o Updates to internal effects chain API. (cbagwell) - o Retire old FFT routines (speeds up `noisered' effect). (robs) - o Allow effects to use getopt. (robs) - o Use libmagic for mp3. (robs) - o Change sox_seek() offset to 64-bit to work with > 2G files (cbagwell) - o Merged libsfx back into libsox to align with sox.h API. (cbagwell) - - -sox-14.1.0 2008-7-29 ----------- - -Previously deprecated features that have been removed in this release: - - Deprec- Feature [O(ption)] - ated in [F(ormat)] [E(ffect)] Replacement - ------- ---------------------- ---------------------- - 13.0.0 O -e -n - 13.0.0 O -b/-w/-l/-d -1/-2/-4/-8 - 13.0.0 E avg, pick mixer - 13.0.0 E highp, lowp highpass -1, lowpass -1 - 13.0.0 E mask dither - 13.0.0 E vibro ~= tremolo - 13.0.0 F auto Becomes internal only - -File formats: - - o New option --help-format shows info about supported format(s). (robs) - o New WavPack format (includes lossless audio compression, but not - guaranteed lossless file compression). (robs) - o New htk format. (robs) - o Add .f4 & .f8 raw file extensions. (robs) - o Writing aiff, aifc & dvms now repeatable with -R. (robs) - o Writing hcom no longer fails with unsupported rate--chooses - best match. (robs) - o Au/snd: added support for 32-bit integer and 64-bit float PCM - encoding/decoding; display name of unsupported encoding. (robs) - o Can now write .amb (.wav variant) files [FR 1902232]. (robs) - o Can now read 2,3(2.6),4 bit ADPCM .voc files [FR 1714991]. (robs) - o Can now read some MP3 ID3 tags. (robs) - o Can now write Sounder files. (robs) - o Can now write DEC-variant au files (with -x). (robs) - o Comments support for SoundTool files. (robs) - o Fix [1864216] comments mangled when writing ogg-vorbis. (robs) - o Fix short noise at end of alsa playback. (Morita Sho/Tim Munro/robs) - o Fix wve seek accuracy. (robs) - o Fix lpc10 not working. (robs) - o Fix [1187257] wav MS-ADPCM block-align size incorrect. (robs) - o For wav & au, fix [548256] size in header wrong when piping out. (robs) - o Fix IRCAM SF header processing; support all (modern) variants. (robs) - o Fix 24-bit read/write on big-endian systems. (robs) - o Fix crash trying to open non-existent play-list. (robs) - o Fix FLAC read from stdin with libFLAC >= 8. (Patrick Taylor Ramsey/robs) - o Fix [1997637] Trim effect loses samples (with wav). (robs) - -Effects: - - o New `splice' effect; splice together audio sections. (robs) - o New `remix' effect; mixes any number of channels. (robs) - o New `norm' (normalise) effect. (robs) - o New `delay' effect; delay one or more channels. (robs) - o New `contrast' enhancement effect [FR 708923]. (robs) - o Improved `rate' resampling effect; resample, polyphase, & rabbit - now deprecated. (robs) - o New `spectrogram' effect; creates a PNG (if built with PNG lib). (robs) - o `synth' can now sweep linearly and squarely (as well as - exponentially). (robs) - o Can now `fade' out to EOF without giving file-length (if it can - be determined from the input file header). (robs) - o Fix synth max. level setting for some output encodings. (robs) - o Fix crash on 64-bit arch. with tempo & key effects. (Sami Liedes) - o `gain' alias for the vol effect. (robs) - -Other new features: - - o Now possible to control play-back resampling quality (and hence - cpu-load) via the PLAY_RATE_ARG environment variable. (robs) - o Command line support for multiple file comments. (robs) - o New --combine=mix-power option to mix combine using 1/sqrt(n) scaling - instead of 1/n [FR 2012856]. (robs) - o New --input-buffer option to specify (only) input buffer size. (robs) - o New `soxi' utility to extract/display file header fields. (robs) - o Pkg-config support. (Pascal Giard) - o Simple VU meter. (robs) - o Heuristic to detect when playing an album and set - the default replay-gain mode to `album'. (robs) - o Better auto-choice of output file format parameters when - type is different to that of input file. (robs) - o SoX now treats (and displays) encoding size & signal precision - separately. (robs) - o Default audio devices (sox), and allow environment variables to - be used to override the default audio device driver (rec/play) - and default audio device (all). (robs) - o Simpler file info display for `play'. (robs) - o For some file-types, warn if file size seems too short. (robs) - o Added auto-detect for caf, sndr, txw & sf files. (robs) - o Added example0: simpler example of how to develop applications that - use the libSoX effects chain. (robs) - o Added example2: simple example of how to develop applications that - use libSoX to read an audio file. (robs) - o Moved contents of soxexam man page into soxeffect man page. (robs) - -Other bug fixes: - - o Fix [1890983] rec shortcut should apply bit depth (8-bit, - 16-bit, etc.) to input handler. (robs) - o Fix ungraceful handling of out of disc space and other write - errors (bug was introduced in 14.0.0). (robs) - o Fix endian selection (-B, -L, -x) in some circumstances. (robs) - o Fix auto-detect of hcom files. (robs) - -Internal improvements: - - o Use FORTIFY_SOURCE with gcc. (robs) - o Fixed all compiler warnings (with gcc 4.2.3, 32-bit arch). (robs) - o Reimplement (separately) SoundTool & Sounder format handlers. (robs) - o Allow formats & effects to have any size of private data. (robs) - - -sox-14.0.1 2008-01-29 ----------- - - File formats: - - o Added support for non-standard, non-WAVE_FORMAT_EXTENSIBLE - (esp. 24-bit) PCM wav (see wavpcm in soxformat.7 for details). (robs) - - Effects: - - o Reimplemented reverb to be similar to freeverb. (robs) - - Bug fixes: - - o Fix Sndtool read error causing noise at start. (Reynir Stefánsson) - o Fix mixer with >4 numbers, and mixer -3 behaving as mixer -4. (robs) - o Fix [1748909] sox does not report remaining playtime of mp3s. (robs) - o Fix failure to read AIFF files with empty MARK chunk. (robs) - o Fix spurious 'Premature EOF' message in some circumstances. (robs) - o Switched to 16-bit for libao driver since not all its plugins - support it (such as oss, nas, and pulse audio) (Morita Sho) - o Stop crash when "rec" is run with no arguments (Morita Sho). - o Fix -V (without argument) on non-gnu systems. (robs) - o Fix reported (with -V) output audio length in some cases. (robs) - o Fix actual FLAC output file audio length in some cases. (robs) - o Fix poor 24-bit FLAC compression & support newer versions of - libFLAC (1.2.x). (robs) - o Fix loss of 1 decoded FLAC block when using "trim 0 ...". (robs) - o Fix trim when first effect with IMA-ADPCM input wav file. (robs) - - Internal improvements: - - o Let "make distcheck" run some automated test scripts. - o Distribute missing cmake files. - o Fix ogg vorbis compile error on some platforms. - o Remove unused libltdl that could cause header mismatch with - installed libltdl. - o Fix AMR detection with --disable-shared. (robs) - o Updated configure to support linking to static libraries - on mingw for flac, ogg, and libsamplerate libraries. - o Added example1: simple example of how to develop applications that - use the libSoX effects chain. (robs) - - -sox-14.0.0 2007-09-11 ----------- - - File formats: - - o Added ffmpeg support. (Reuben Thomas) - o FLAC: added seekable decoding; added seek-table generation. (robs) - o Added M3U & PLS playlist formats [FR# 1667341] (Note: SHOUTcast PLS - is only partially supported). (robs) - o Made format readers and writers into individual modules for easier - distribution of differently-licensed code. (Reuben Thomas) - o Added libao support. (Reuben Thomas) - o Added support for ADPCM-encoded PRC files, based on Danny Smith's - rec2wav and sndcmp. (Reuben Thomas) - o Added AMR-NB [FR# 728875] & AMR-WB formats (with external libs). (robs) - o Added LPC-10 support. (Reuben Thomas) - - Effects: - - o Use LADSPA effects (one input, one output). (Reuben Thomas) - o --octave option changed to --plot; can now also use gnuplot to - plot effect transfer function. (robs) - o Added soft-knee companding. (robs) - o Show (with --plot) compand transfer function. (robs) - o Allow e.g. "vol 6dB" (as well as "vol 6 dB"). (robs) - o Changed deemph filter from 1st order to 2nd order for - slightly better accuracy. (robs) - o Add option to silence effect to leave periods of silence - in and only strip out extra silence. (Mark Schreiber) - o synth can now generate any number of channels. (robs) - o mixer can now mixdown to mono any number of channels. (robs) - o Added oops effect (mixer special case). (robs) - o All effects that could only work on mono or stereo audio, now - work with any number of channels. (robs) - o Added WSOLA-based key and tempo effects. (robs) - - Other new features: - - o Show (with -S) if clipping is occurring. (robs) - o Added internet input file support (needs wget). (robs) - o Made it possible to build without sound drivers. (Reuben Thomas) - - Bug fixes: - - o Fix (m)compand transfer function non-linearities; fix compand - drain volume. (robs) - o Fix crash with pan effect. (robs) - o Add missing RM define to Makefiles so installs work. - (Bug# 1666599) (cbagwell) - o Fix I/O performance regression in 13.0.0. (Reuben Thomas) - o Fix .lu, .la read regression in 13.0.0 [Bug# 1715076]. (robs) - o Fix uncompressed NIST/Sphere read regression in v13 [Bug #1736016]. - o Fix displayed times when playing a file and using trim. (robs) - o Fix CDDA sector duration display for non-CDDA sample rates. (robs) - o synth fixes: brown noise; inverted square wave; offset < 0. (robs) - o Fix crash when encoding Vorbis or FLAC: with no comment. (robs) - o Fix effect drain problems: chorus, echo(s), phaser. (robs) - o Fix rabbit responsiveness and memory problems. (Peter Samuelson) - o Fix broken stereo audio when recording using ALSA. (robs) - o Fix OSS driver on big endian machines that was introduced in - last release. - - Internal improvements: - - o Renamed libst to libsox for name recongition and to avoid - duplications with other existing libst libraries. (Reuben Thomas) - o Moved effects to libsfx. (Reuben Thomas) - o Got rid of several hundred compiler warnings. (robs, Reuben Thomas) - o Added basic performance testing of I/O. (Reuben Thomas) - o Effects chain processing now available in libSoX. (robs) - o Added effects-chain buffering for effects that use a window [FR# - 1621695]. (robs) - o Added cmake build files for Win32. (robs) - - -sox-13.0.0 2007-02-11 ----------- - - File formats: - - o Support for .caf, .paf, .fap, .nist, .w64, .nist, Matlab 4.2/5.0 - (Octave 2.0/2.1), .pvf, .sds, .sd2 and .xi file formats via libsndfile. - If available, libsndfile can also be used to handle all the other file - formats it understands. (Reuben Thomas) - o Add FLAC support (robs) - o Support Maxis's XA format. (Dwayne C. Litzenberger) - o Add support for 24-bit PCM raw, wav (WAVE_FORMAT_EXTENSIBLE) [FR# 801015], - au, aiff, & flac files. (robs) - o Add AIFF-C output support. (shashimoto) - o New .ima file format for raw IMA ADPCM. (robs) - o Allow the rate and number of channels of .au files to be overridden - by command-line arguments. (robs) - o Add seek support for GSM data in WAV files. Rafal Maszkowski - o Allow encoding quality to be specified (FLAC & Ogg, but not - MP3 yet). (robs) - o Rename -b to -1, -w to -2, -l to -4, -d to -8, and mask to dither. - (robs) - o New options for specifying endianness (and separate options for - nibble & bit reversal) [FR# 1621702]. (robs) - o Improved multi-channel file reading; fixes [1599990]. (robs) - - Effects: - - o Equalizer effect (Pascal Giard) - o bass and treble altering effects. (robs) - o New optional rabbit resample routine, using libsamplerate - (aka Secret Rabbit Code). (Reuben Thomas) - o Added allpass filter effect. (robs) - o Documented the butterworth filter effects; added variable Q. (robs) - o "rate" effect made an alias for "resample". - o Visualisation of various filters' frequency response via Octave. (robs) - o Can now specify width of many 2nd-order filters as: Hz, octaves, - or Q. (robs) - o Dither/mask amount now specifiable. (robs) - o Consistent (and hopefully complete) clipping detection and - reporting. (robs) - o Allow command-line time parameters of < 1 sec to omit the - leading 0. (robs) - o Improved synth usage and improved the synth entry in the man- - page. (robs) - o Higher quality audio speed adjustment; also fixes [1155364]. (robs) - o Replacement flanger effect; also fixes [1393245]. (robs) - o Added silence padding effect. (robs) - o Added ability for noiseprof to use stdout and noisered to use stdin - [FR# 1621694]. (Reuben Thomas) - o vibro effect name deprecated in favour of tremolo; this effect - reimplemented as a special case of synth. (robs) - - Other new features: - - o Remove soxmix. (Reuben Thomas) - o Preview mode now removed, as all it did was use rate rather than - resample, and rate has been removed. - o -V now gives only user-relevant messages, use -V -V to get - developer-relevant messages. (robs) - o -V output much improved and expanded; now includes display of - (auto-)selected effects. (robs) - o sox man-page overhaul, new soxexam man-page entries. (robs) - o Added command line options for specifying the output file - comment. (robs) - o Added ability to merge e.g. 2 mono files to 1 stereo file - [FR# 1297076]. (robs) - o Removed the restrictions whereby multiple input files had to have - the same data encoding & size, and in most situations where they - had to have the same # of channels, and for play where they had - to have the same sampling-rate. (robs) - o Options to apply replay-gain on input; enabled by default - with `play'. (robs) - o Can now use Ctrl-C to skip to next track when playing multiple - files (e.g. play *.mp3); Ctrl-C twice to exit. (robs) - o Added --interactive option to prompt to overwrite pre-existing - output file. (robs) - o Added large file support. (Reuben Thomas) - - Bug fixes: - - o Fix writing MP3 files on AMD64 processors. - o More fixes to MP3 tag reading. Sometimes tags were - detected as valid MP3 frames. - o Fix to stop, avoiding a crash, when starting of effects fails. - (Reuben Thomas) - o Fixed a bug introduced in 12.18.2 that stopped the draining - of effects from occuring. This had stopped the reverse effect, - among others, from working. (Reuben Thomas) - o Several effects are now optimised out in situations where they need - do nothing, e.g. changing rate from 8000 to 8000, or changing volume - by 0dB [Bug# 1395781]. (robs) - o Fix rounding error when reading command-line time - parameters. (robs) - o Fix nul file hander ignoring other format options if rate - option has not been given. (robs) - o Fix synth length accuracy. (robs) - o Fix broken audio when downmixing with any of the following - effects: synth, deemph, vibro. (robs) - o Fixed deemph & earwax effects to work with MP3, vorbis, - & FLAC. (robs) - o Fix wav file handler discarding the last PCM sample in certain - circumstances. (robs) - o Fix [1627972] AIFF read bug when MARK chunk present. (Richard Fuller) - o Fix [1160154] VOX to WAV conversion problem. (robs) - o Removed (for output file only) the potentially - problematic -v option. Use the vol effect instead. (robs) - o Improved the accuracy of integer and floating point PCM - conversions. (robs) - o Don't go into a loop on zero-padded WAVs. (Jorge Serna) - o Fix to AIFF writing to avoid writing invalid files in some situations. - (Reuben Thomas) - o Fix compander effect bugs: [1613030] Compand fails to compress - clipping, [1181423] compand with 0 sec attack/release. (robs) - - Internal improvements: - - o More and better self-tests. (robs) - o Build system overhaul to use the full set of GNU autotools. - (Reuben Thomas) - o Add new getopt1.c to win32 project file. - o Remove old, optional rate change and alaw/ulaw conversion code. - (Reuben Thomas) - o Removed the old internally invoked (but mentioned in the man page) - copy effect. (robs) - - -sox-12.18.2 2006-09-03 ------------ - - o Adding in Debian's disk full fix (#313206). - o Finally got rid of reference to cleanup() function in - library. Applications are now required to detect - all failures from return codes and cleanup as they - want. - o Changed how list of formats and effects are stored internally. - Effects libst users only. Dirk - o Store effects usage so that its accessable by applications. - Dirk - o Modify the synth effect to not use SIGINT to stop processing - and instead return ST_EOF. This allows exact acount of - samples to be written out instead of an approximate amount. - o Fix hangup when attempting to write stereo MP3 files. - (1512218) Kendrick Shaw - o Fix deemph effect would lose stereo separation. (1479249) robs - o Adding cross-platform support for getopt_long - o Make help screens print much more information and add - new --help-effect option. (Originally from Dirk). - o Add support for using an external gsm library instead of - just the internal one. Vladimir Nadvornik - o Updates to nul file handler to prevent crashes during output. - Martin Panter (1482869) - - -sox-12.18.1 2006-05-07 ------------- - - o The "filter" effect could go into infinite drain mode. Now - only drain 1 buffer. noisered as well. - o SoX was ignoring user aborts (ctrl-c) if it occured during - effect drain operations. This was bad if effects had - bugs and stuck in infinite loop. - o Stop SoX from crashing when file type could not be auto - determined (1417776). - o Output filenames with multiple '.' confused SoX. (1417776) - Christian Hammer - o Moved to a common set of CLIP routines. This fixed clipping - bugs in noisered and mcompand. - o Stop SoX from crashing on sphere files that contain large text - strings. (1430025) Ulf Hamhammar - o Fix some overflow crashes in aiff handler. (1430024) Ulf Hamhammar. - o Under windows, set piped input/output to binary mode (1417794). Martin - Panter - o Fixed broken internal version of strdup(). (1417790) Marty - o Stop infinite loop when reading MP3's with a tag size of - exactly 8192 bytes. (1417511) Hans Fugal - o Fix typo in stlib.dsp for loading in Visual Studio 6. - o Fixed problems in silence effect related to removing multiple - periods of silence from the middle of the sound file. - o Reduced the window size greatly on the silence effect to - prevent leaving in silence that looked like noise still based - on RMS values. - o Prevent infinite loop in pitch effect from uninitialize variable. - Frank Heckenbach - o Prevent crashes when printing error mesages (1447239) - o Added makefile and support files to compile using Open Watcom - compiler. (1417798) Marty - o Stop calling flow() on effects that returned EOF during drain(). Allows - two back-to-back reverse effects to work. - o Added support for multiple channels in .dat files. - (1366634) tomchristie - - -sox-12.17.9 2005-12-05 ------------ - - o Updates to compile under VC6. Jimen Ching - o Declare st_signalinfo_t to specifically be signed in case - platform does not default ot signed chars. This - is required for NetBSD/powerpc. - o When seek()ing in AIFF, SMP, and WAV handlers, remaining samples were - incorrectly computed based on bytes and not samples. Jukka - o Changed noisered effect to just warn during clipping instead - of aborting. Ian Turner - o Fixed bug were pieces of audio were lost every buffer read - when running both -c and -r options together on mono audio. - Users probably percieved it as shorter audio files that - played with a sped up tempo. - Bugfix will also apply to other times when multiple effects - are ran on the command line. - o Added support for -V option to play/rec scripts. - o Fix to silence effect to allow negative periods to be specified - (to remove silence from middle of sound file). - o Fix swap option handling so that special case of "swap 1 1" will - work. - o Track length of Ogg Vorbis files on read. - o Add support for displaying a status line that tracks progress - of read/write routines. Part of information requires read - file handlers to be able to determine file length. - o Converted alsa driver to use asoundlib instead of directly - talking to kernel driver. This also means that device names - are now the ALSA logical names instead of /dev type names. - o Added ALSA support to play/rec scripts. - o Added st_open*, st_read, st_write, st_seek, st_close routines - to help simplify developer interface to libst. See libst.3.. - o Removed st_initformat(), st_copyformat(), and - st_checkformat() from library. If your app used those - functions then copy them from 12.17.8 source code - directly into your application or update to use new - routines. - o Force word-alignment on AIFF SSND and APPL chunks on input. - Matthew Hodgson. - o Add fix to WAV handler to only return data in multiples - of sample_size*channels to better handle corrupt files. - o Fixed bug where "-4" option didn't work with avg - effect (Tom Christie). - o Fixed fade's fade-out-length to match man page - description as noted by Geoff Kuenning. This required - updates to the sample crossfade scripts. Also modified fade - effect to report when no more samples will be produced to - prevent unneeded reading of whole file. - o Allow aborting SoX with SIGTERM, along with previous SIGINT. - Norman Ramsey. - - -sox-12.17.8 2005-08-22 ------------ - - o noisered effect had compile problems with some compilers. - o "-x" option was being ignored since 12.17.7. - o Stuart Brady added support for reading and writing RIFX files (big - endian RIFF/WAV files). Also added support for auto detecting - DEC-style ".sd\0" files. - o Gene Mar found typo in polyphase nuttall calculation. - o SMP buffer overflow (detected by gcc 4.0). Reported by Marcus Meissner - and Matthias Saou. - o Fixed URL in manpage to resample overviews. - o Fixed WAV handler so that it didn't think WAV chunks with max size - were invalid chunks. This allows WAV's to be used in pipes since - they have to default to max size. - o WAV files with alaw or ulaw data don't need extended format chunks. - (Lars Immisch) - o In AIFF files, fixed problem were short comments should cause - AIFF handler to get confused and become misaligned. - - -sox-12.17.7 2004-12-20 ------------ - - o Christian Weisgerber sent patches to man page fixes - and patches for sunaudio driver on openbsd. - o Default volume for soxmix wrongly set to 0 instead - of 1/#_input_files (float rounding error). - o Update to ALSA driver to do a better job of detecting - unsupported sample rate/size/encoding and change to - a supported one. - o Fix bug in alsa writing were last last partial buffer - wasn't being flushed. - o Guentcho Skordev pointed out ogg vorbis files were using - the same value for serial numbers each time. - o Changed sox to only read the exact size of a WAV data chunk - if cooledit IFF LIST chunk is found at the end of the file. - Normally, this isn't done to allow reading > 2gig WAV files. - o Modified configure to detect cygwin compiler after detecting - gcc compiler (fixes some default CFLAGS options). - o Added explicit rule for compile *.o from *.c so that - CPPFLAGS is always referenced. Not all platform's default - rule includes CPPFLAGS (FreeBSD). - o Under linux, add include path to /lib/modules/* so that ALSA - include files can be auto detected. - o Ian Turner added an effect to remove noise from an audio - file by first profiling silent periods of the audio - to determine what the noise is (like background hiss on - cassette tapes). - - -sox-12.17.6 2004-10-13 ------------ - - o Changed comment code to always use copies of strings to - fix bug in WAV handlering freeing argv[] memory. - o Use calloc() to create ft_t structures so that all - memory is initialized before being referenced. - o Fixed VOC EOF bug were it thought there was an extra - block when there wasn't. - o Restructured directory layout so that source code is in - a seperate directory. - o Modified SoX to accept multiple input files. Concatenates - files together in this case. - o Removed map effect so that loops and instr could be removed - from effects structures. This makes effects engine stand - alone from the rest of the sox package. - o Benedikt Zeyen found a bug in synth effect when generating - brown noise that could cause clipping. - o David Leverton sent another patch to prevent crashes on - amd64's when resampling. - o Fixed a bug were MP3 files with large ID3v2 tags could - cause SoX to stick in a loop forever. Now, it will - abort on IDv3 tags larger then 100k. Could still be - improved to handle any size. - o Changed volume option (-v) so that it tracks the file - it was specified. This means that when specified with - the input file, it changes volume before effects engine - and when specified with output file, its done after effects - engine. - o Added crossfade_cat.sh script that will concatenate to - audio files and do a crossfade between them. - o Fixed bug in fade effect were it was impossible to do a - fadeout starting from the beginning of the audio file. - o Removed rounding error when changing volume of audio with - "-v" option. This error caused doing a "-v -1.0" twice - to not result in the original file. - o Fixed a possible overflow in lots of effects were MIN - value was treated as -MAX instead of -MAX-1. - o Modifed sox so its OK for effects to not process any - input or output bytes as long as they return ST_EOF. - o When effects output data and reported ST_EOF at the - same time, that buffer was discarded as well as - data from any chained effect. - o Added patch from Eric Benson that attempts to do a seek() - if the first effect is trim. This greatly speeds up - processing large files. - o Daniel Pouzzner implemented a multi-band compander (using - the butterworth filters to split the audio into bands). - o Donnie Smith updated the silence effect so that its possible - to remove silence from the middle of a sound file by - using a negative value for stop_periods. - o Changed float routines to only work with normalized values - from -1:1. - o Modifed .au handler to be able to read and write 32-bit - and 64-bit float data. Only tested reading so far. - o WAV with GSM data now always pads data to even number of bytes. - o Added support for writing 32-bit audio to AIFF. - - -sox-12.17.5 2004-08-15 ------------ - - o Thomas Klausner sent in patches to compile audio drivers under - NetBSD. - o Rahul Powar pointed out a memory leak in the WAV file handler. - It wasn't calling the correct close() function when closing - input files. - o Modified play.1 man page to not use multiple name lines. This - appears to confuse some conversion programs. Updated sox.1 - man page for typo in reverb option. - o Andrew Church fixed problem with header of stereo 8SVX files. - o Jimen Ching added support to scan over garbage data at the - beginning of MP3 files to find valid frames. This is useful - to play WAV and AIFF files that have MP3 data in them until - those handlers support it directly. To play those, force - sox to use the mp3 handler with the "-t mp3" option. - o Added patch from Ulf Harnhammar to wav handler to prevent - buffer overflows. - o Added patch from Redhat to allow resample to work on certain 64-bit - machines (Sam Varshavchik) - o Tony Seebregts added a file handler for headerless Dialogic/OKI ADPCM - files (VOX files). - o Jan Paul Schmidt added a repeat effect to do loops the brute force way. - This is also good for file format that don't support loops as well. - o Fix for OSS driver in rate tolerance calcs that were off because - of type conversion problems. Guenter Geiger. - o Allow reading sphere files with headers greater then 256 bytes. Jimen - Ching. - o Fix for vorbis were comments are displayed in KEY=value format always. - Stop printing some info to stdout in case output is a pipe. Guenter - Geiger. - o J Robert Ray submitted fix for AIFF handler to ignore lowercase - chunks that are unknown. - o Bugfix for 8-bit voc files. Jimen Ching - o General warning cleanups (cbagwell) - o Memory leaks in reading WAV files (Ufuk Kayserilioglu) - o Rearrange link order of ogg vorbis libraries so that they - can be compiled as static. (Christian Weisgerbr) - - -sox-12.17.4 2003-03-22 ------------ - - o Peter Nyhlen fixed a problem with reading Comments in Ogg Vorbis files. - o Added install target to allow installing libgsm from main Makefile. - Leigh Smith. - o Minor updates to sox.c to free unused memory and close all input - files during failures. - o Pieter Krul added a patch that makes play script look at AUDIODEV - environment variable if it exists to find which device to use. - This allows scripts to work with Solaris SunRays and is a good idea - in general. - o Updated config.sub to detect latest supported OS's. - o Fabrizio Gennari added support for reading and writing - MP3 files using the external libraries libmad and libmp3lame. - o Jens Henrik Goebbert sent in several bugfixes for integer overflows - in the compand effect. - o Dan Dickerman sent in patches for integer overflows in the resample - effect. - o Jimen Ching sent in a fix for multi-channel sound file processing - using the avg effect. - o Richards Bannister added patches to clean up prototypes and filter - private sizes being to small. - o Jimen Ching adds -d option to specify 64bit data size and changed - Ulaw/Alaw encoding to default to 8bit data size if not specified. - o David Singer pointed out that a MS program creates AIFF files - with an invalid length of 0 in its header. Changed SoX to warn the - user but continue instead of aborting since SoX can still read - the file just fine. - o Bert van Leeuwen added a file handler for Psion record.app used - for System/Alarms in some Psion devices. - o Richard Bannister sent in a patch to make writing vorbis files - work with Vorbis 1.0 libraries. - o Fixed configure scripts so that they can be ran with the - --with-oss-dsp, --with-alsa, and --with-sun-audio options. - Was causing compile time problems. Reported by Raul Coronado. - o Change Ogg Vorbis support to use VBR encoding to match defaults - of oggenc based on suggestion from Christian Weisgerber. - o Prints error message now when a channel value of -1 is given. - Reported by Pierre Fortin. - o Fixed bug were memory could be trashed if a input WAV file contained - a comment. Found by Rhys Chard. - o Change command line to compile soxmix.o slightly to try and make - Forte compiler happy. - o Added support for ALSA 0.9 driver. Jimen Ching - - -sox-12.17.3 2001-12-15 ------------ - - o Removed check that prevented pan from being invoked when the - input and output channels were the same. - o Ciaran Anscomb added a flush to sunaudio driver after changing - settings. This is because it can start buffering data as soon - as the device is open and the buffered data can be in a - wrong format. - o trim wasn't accounting for # of channels and was generally broken. - o Jeff Bonggren fixed trim bugs were it was failing when triming - data that equaled to BUFSIZ. Also, trim now immediately returns - ST_EOF when its done instead of requiring an extra call that - returns no data. - o auto effect wasn't rewinding the file if the file was less then - 132 bytes. Changed auto parsing of header to be incremental - instead of reading in a large buffer. - o William Plant pointed out a bad pointer access in fade effect's - parsing of options. - o Ken pointed out a problem were private data was not 8-byte aligned - and causing crashes on most RISC CPU's. Fixed by going back to - old style of declaring private data as type "double" which usually - forces strictest alignment. - o ima_rw was miscompiling on alpha's because of a header ordering - problem. - o Erik de Castro Lopo pointed out that when writing 16-bit VOC files - the headers did not contain the correct length or encoding type. - o Seperated st.h into 2 files. st.h for libst users and st_i.h for - internal use. - o Added new types used extensively by libst: st_sample_t & st_size_t. - This allows for more deterministic behavior on 64-bit machines and - also allows sox to possibly work with much larger file sizes. - o SoX was some times getting confused and thinking an EOF was an - error case when reading audio files. Removed unneeded aborts - when EOF was OK. - o Silence effect was broken on stereo files. Also, made thresholds - relative to original bit percision of audio data. When 16-bit audio - is scaled up to 32-bits, a little bit of noise starts to look like a - large amplitude of noise. Also, now using RMS values to smooth out - clicks. RMS rolling window size is 1/10 of sample rate. - o Changed Floats into a type of encoding instead of a size of audio data. - o Put a flush at the end of OSS driver so that no old data would be - left in internal buffers after changing audio format parameters. - o Fixed problem where play script wasn't installed correctly if you - build from another directory (pointed out by Mike Castle). - o Made GSM support internal to libst (no external library required). - o Change configure script to enable ulaw/alaw lookup tables and GSM - support by default. Also have Makefile's make use of more configure - prefix options to allow for customized installs. - o Reverted ulaw/alaw conversion routines back to Sun's versions. - o Modified raw file handler to write files in the same generic buffered - fashion that was added for reading in 12.17.2. Seems to have - speed up some types of writing. - o Reading Ogg Vorbis files could get confused of when EOF was reached. - o Added uninstall rules to Makefile. Added new ststdint.h to define - *int*_t typedefs. - o Added internal strcasecmp for OS/2. - o Added support for swapping "bit" order (MSB becomes LSB) for raw u-law - and A-law data. Some ISDN equipment prefers it this way. Use -x flag - or new .la or .lu file extensions. - o Annonymous patch submitted to fix types and spelling problems in - various files. Also, updated VOC files to have u-law and A-law - support as well as able to read in VOC files using a pipe. More - examples added to soxexam file. - - -sox-12.17.2 2001-09-15 ------------ - - o Daniel Culbert found and fixed a bug in the polyphase effect - that occurs on platforms that rand() can return large values. - The bug resulted in polyphase resampling an audio file to a - different rate then it said it was. - o Stan Seibert contributed a handler for Ogg Vorbis files. It - handles all input formats but can only save using default - settings. - o Darrick Servis has made major cleanups in the code in regards - to error conditions. Helps people using libst. - o Darrick Servis has added added optional seek functionality sox. - Several formats have been modified to make use of this. - o Geoff Kuenning rewrote the average effect into a general-purpose - parametric mapping from N channels to M channels. - o Geoff Kuenning added an optional delay-time parameter to the compander - effect to allow companding to effectively operate based on future - knowledge. - o Geoff Kuenning Added support to fade and trim effect for specifying time - in hh:mm:ss.frac format. - Fixed a bug that caused integer overflow when large start/stop times - were used. - o Geoff Kuenning updated play/rec/soxeffect scripts to handle all effects - added since 12.17. Spell-checked soxexam.1 file. - o Jimen Ching updated ALSA configure support to auto-detect 4.x or 5.x API - and compile correctly under those two. All other versions are unsupported. - o Merged in the NetBSD package changes into CVS finally. - o Removed broken support for non-ANSI compilers. - o Makefile now places the correct path to SoX in the play/rec scripts - based on configuration script values. - o Alexander Pevzner provided a fix for OSS driver for sound being - dropped under heavy CPU loads. Moved GETBLKSIZE operation - until after setting up the format (SBLive! was modify the block size - after changing formats). - o With help from David Blythe, updated OSS drivers to use newer format - interface. OSS driver will now attempt to detect a valid endian type - to use with sound card. - o Carsten Borchardt pointed out a bug in lowp filter. Added new - nul file handler that reads and writes from/to nothing. - Also added new synth effect that creates sounds using a simple - synthesizer. Created a testcd.sh that uses two new features - to create a test sound CD for testing audio equipment. - o Ben Last added a new program that uses libst and will merge two - seperate audio files into a single file with multiple channels. - This was merged into the standard sox.c file by cbagwell. - o Andreas Menke fixed some problems with the speed effect and - how effects were drained. Also improved the usage of printf()'s - to use stderr. - o Corrected AU header length value when comments were less than - 4 bytes. - o Added support for reading non-standard bit size data from AIFF files. - o Ignore unmatched MARK/INSTR chunks in AIFF files now instead of quiting. - o Fixed ALAW encoding bug in .au files as pointed out by Bruce Forsberg. - o Unified the raw reading functions. Probably slightly faster for - most datatypes but was done to fix recording from the OSS driver. - Control-C stopped working somewhere during the 12.17 series. - o Ford Prefect added a dcshift which can shift the midline amplitude - towards the true center. This will allow for a greater range - of volume adjustments without clipping audio data. - o Heikki Leinonen submitted a silence effect that will trim off - silence from the beginning of a file. cbagwell made some modifications - to trim off front and back as well as some other tweaks. - o Made the "auto" effect the default file handler for input files. - Also have auto handler now use file extensions if it can't figure - it out. - - -sox-12.17.1 2000-11-19 ------------ - - o Andreas Kies fixed a bug were we were not detecting correctly - if an output file was seekable. - o Fixed a bug in the mask effect introduced in 12.17. If the libc - version of rand() returned more then 15-bit values then it would - trash your data. Reported by Friedhel Mehnert. - o Added a new fade in/out effect from Ari Moisio. - o AIFF files now ignore a MARK chunk if the loop type is NoLoop (0). - o Fixed bug were it was impossible to output ADPCM data in wav files. - o Fixed bug were rate had to be specified for sphere files (fix from - Antti Honkela). - o Added small work around to let compile with cygwin's gcc 95.2 - which also now allows to compile with GSM support under windows. - o Removed accessing of sound devices in tests for sound support and - instead just look for needed header files. This allows the sound - support to be detected even if the device is currently busy or when - compiled on a box that doesn't have a sound card but the OS supports - it (which is the enviornment of most distributions creating new - binaries). - o Added support to partially handle AIFC files but only uncompressed - versions. This should allow people to work with raw CD audio data - on Mac OSX and also gives a basis for adding future support for - things like ADPCM processing. - o Added new "earwax" effect from Edward Beingessner. It is meant to - be used for CD audio played through headphones. It will move the - sound stage from left/right to in front of you. - o Trim effect did not compute locations as was documented in the - man pages. Changed effect so that it computed the time the - same way that the fade effect does. - - -sox-12.17 2000-09-08 ---------- - - o Sox can now read and write w98 compatible gsm .wav files, - if compiled properly with libgsm. Thanks go to Stuart - Daines for the gsm-wav patches. - This is new, and relatively untested. See -g format option. - o Sox can now write IMA_ADPCM and ADPCM compressed .wav, - this is new, and relatively untested. See -i and -a format - options in manpage. - o General changes to wav.c for writing additional wav formats. - Reading wave headers: more consistency checks. - Writing wave headers: fixes for w98. - o Speedups to adpcm read routines, new codex versions are - now in ima_rw.c and adpcm.c. - o Speedups for raw.c, especially for gcc with glibc. - o Fixed a segfault problem with ulaw/alaw conversion, where - an out-of-range index into the tables could occur. - o More detailed output from the stat effect. - o Continued rewrite of resample.c, now it is almost as - fast with floating arithmetic as the old (buggy) version - was with 16-bit integer arithmetic. The older version - in sox-12.16 shifted frequencies slightly and was less - accurate. (Stan Brooks) - o Extensive rewrite of polyphas.c, should be faster and use less memory - now. The sox-12.16 polyphase code had some bugs. (Stan Brooks) - o New effect 'filter' which is a high-quality DSP lowpass/ - highpass/bandpass filter using windowed sinc function - methods, like polyphase and resample. (Stan Brooks) - o Jan Paul Schmidt added new low/high/bandpass and bandlimit - filters to sox. They have much better results then the old - versions of low/high/bandpass. The new effects are all - Butterworth filters. - o New data file type supported, -sl or extension .sl for - signed 32-bit integers. Some simplification of the raw.c - source. - o Some test programs and scripts in the test directory, for - making gnuplot plots of frequency response, error-levels - of rate-conversion and filter effects. - o Removed sbdsp code. All modern unixes are support via OSS, - ALSA, or sun audio device interfaces. - o Added AVR handler from Jan Paul Schmidt. - o SoX now waits until the last possible moment before opening - the output file. This will allow all input and effect options - to be parsed for errors and abort before overwriting any file. - o SoX will no longer write to files that exists. This will keep - it from deleting files when a user mistakenly types "sox *.wav". - o Added new compander effect from Nick Bailey. Nice general purpose - filter. - o Under Solaris, SoX now checks hardware ability to play stereo/PCM - and forces output data to match. Sorry, no SunOS support. I don't - have access to one any more. - o Fixed array overrun bug in rate effect as pointed out by Ian - Donaldson. - o Fixed clip24() range as pointed out by Ted Powell. - o Fixed possible segfault in echos effect, as pointed out by Zinx - Verituse. - o Moved most documentation to new "soxexam.1" manual page so that - all users on a unix system will have access to important information. - This means no more TIPS, CHEATS, or CHEATS.eft files. - o Richard Kent fixed a byte alignment problem in aiff comment code. - o Loring Holden added support to create missing directories on install - and support for installs from outside the source directory. - o Fabien COELHO added a pan and volume effect. - o Fabien COELHO added a speed effect to sox (like speeding up a tape - machine). Also added pitch which changes pitch without effecting - duration and stretch which stretch time without effecting pitch. - o Leigh Smith updated aiff support to use the COMT check when writing - comments instead of the ANNO. It is the prefered method from Apple - and newer programs are starting to require it. Also fixed some bugs - in how we compute the length of various chunks in output files. - o Changed the default block alignement for IMA ADPCM WAV files to use - 256 which is what windows programs use. Badly written readers expect - 256. - o Matthias Nutt helped add support for specifying multiple effects - to SoX on the command line. - o Curt Zirzow added a trim effect to trim off audio data. - o Updated ALSA driver to support new interface. Jimen Ching - - -sox-12.16 1999-07-13 ---------- - - o Changed raw data functions to perform I/O operations using block reads. - Should improve speeds greatly, especially when filesize is in megs. - Got code ready to tweak speed more which also forced me to clean up - Endian test code. - o Fixed a bug in .au's handling of G.723. It wasn't using the correct - number of bits. Added A-law support to .au. - o Quoted $filename in play/rec scripts so that files with spaces in - their names can be given. - o Old OS/2 support didn't work. Replaced with known working EMX - GCC compatible code. - o ADPCM WAV files were defaulting to 8-bit outputs and thus losing - some persision. Now defaults to 16-bit signed uncompressed data. - o Fixed a couple cross-platform compiler issues. - o Jimen Ching has added support for "configure" in to SOX. Finally, - a good solution to cross-platform compiling! - o Jimen Ching has added native support for the ALSA driver to play - and record audio from. (jching@flex.com) - o Minor correction for -r example in manual page. - o Renamed sox.sh to soxeffect and rewrote. Symbolic links can be made - from this file to the name of a sox effect. It will then run that - effect on STDIN and output the results to STDOUT. - o Fixed up some makefiles and 16-bit support from patches sent by - Mark Morgan Lloyd (markMLl.in@telemetry.co.uk). Also added some - nice DOS test bat files from him as well. - o Cleaned up some more cross-platform compile problems. In the process - got it working with Turbo C again, kinda. It still locks DOS up at times. - o Made AIFF handler work with invalid headers that some programs generate. - Also fix an Endian bug thats been there for quite a long time (when - ran on Intel machines). Made comment lengths even length to make - most MacOS programs happy. cbagwell - o Resample function was updated by Andreas Wilde - (andreas@eakaw2.et.tu-dresden.de) to fix problem were freqs. were - off by a factor of 2. - o Added an effect that swaps stereo channels. cbagwell - o Combined play and rec scripts to a single program to ease mantaince. - Also added GNU style long-options (--help). Careful, some options have - change (but more logical). - o Fixed a very old silly bug were low/high/bandpass filters would - add some trash data to the end of the sound file. - o "avg" effect wouldn't give error message when you tried to average - x number of channels in to the same number of channels. - o Fixed core dump when writting AIFF files with no comments. - (Olaf Pueschel) - - -sox-12.15 1998-10-01 ---------- - - o Juergen Mueller moved Sox forward quite a bit by adding all the - most commonly known "Guitar Effects". He enhanced echo support, - added chorus, flanger, and reverb effects. He also wrote a very - handy CHEAT.eft file for using various effects. - o Incorporated Yamaha TX-16W sampler file support provided by - Rob Talley (rob@aii.com) and Mark Lakata (lakata@physics.berkeley.edu). - o Fixed a small bug in hcom compression, dependent on sign - extension. Leigh Smith (leigh@psychokiller.dialix.oz.au). - o sox -h now prints out the file formats and effects supported. - Leigh Smith and Chris Bagwell. - o smp transfers comments more completely. Leigh Smith. - o aiff manages markers and loops correctly and produces more - verbose output. Leigh Smith. - o Added polyphase resampler (kb@ece.cmu.edu). This adds a slightly - different resampling algorithm to the mix. - o Michael Brown (mjb@pootle.demon.co.uk) sent a patch to stop crashes - from happening when reading mono MS ADPCM files. - o Fabrice Bellard has added a less buggy 'rate' conversion. I've left - the old rate code included but if all goes well this will become - the new 'rate'. Please test and let me know how it works. Resample - effect needs to be reworked now. - o Heiko Eissfeldt: Implemented a simple deemphasis effect for - certain audio cd samples. - o Matija Nalis (mnalis@public.srce.hr) sent a patch to fix volume adjustment - (-v) option of sox. - o Fixed typo in optimazation flag in unix makefile, as pointed out by - Manoj Kasichainula (manojk@io.com). - o Fixed missing ';;' in play script. cbagwell - o Fixed bug in determining length of IMA and MS ADPCM WAVE files. cbagwell - o Fixed bug in how stereo effects were drained which fixed the - "reverse" effect from only saving half of stereo files. cbagwell - o Can use "-e" without an effect again. - o Added -g and -a options for new style support of GSM and ADPCM. Added - error checking to various formats to avoid allowing these types. - - -sox-12.14 1998-05-15 ---------- - - o Bumped major version number up and shortened name. The shorter name - should help the various distributions using this package. - o Added support for MS ADPCM and IMA (or DVI) ADPCM for .wav files. - Thanks to Mark Podlipec's xanim for this code (podlipec@ici.net). - o Change Lance Norskog's email address to thinman@meer.net. The old - one was bouncing. - o Added path string to play and rec strings so that it could be run by - users without complete paths setup (i.e. Ran by "rc" files during bootup - or shutdown) - o Fixed -e option from Richard Guenther - (richard.guenther@student.uni-tuebingen.de) and fixed a small bug - in stat. - o Fixed a bug in the mask effect for ULAW/ALAW files. - o Fixed a bug in cdr output files that appended trash to end of file. - o Guenter Geiger (geiger@iem.mhsg.ac.at) made a rather large patch to - allow sox to work on 64-bit alphas. It was done the easiest meathod - by changing all long declarations to use a macro that knows to - make it 32-bits. Want to port to another 64-bit-but-not-alpha - machine? Grep for "alpha" to see changes. There are most likely - several bugs left for alphas. Guenter is also supporting this - package for the Debian distribution. - o Did some major code cleanups to clear out some warning messages - during compile. This is to clear up problems I'm finding under - both alpha and dos. Some warning messages are actually useful - now (pointing out possible data loss). Hopefully, I didn't - break anything. - o Code clean up allows me to finally compile code under Turbo C - again. Too bad the EXE gets a currupted stack somewhere and locks - up the system. Anyone want to try it with Borland C for me? - If you get a working EXE I would like to start distributing a DOS - package like there used to be. - o Speaking of cleanups, anyone want to help cleanup the makefiles for - various platforms? They are quite outdated right now and it is - very obvious that Sox hasn't been able to compile under all the - platforms it once did for several releases. Please send in - the cleaned-up makefile versions along with what programs you - used to compile it with. - o There is a known bug in hcom's compress() function. It is allocating - memory that can't be free'd under some OS's. It causes a core dump. - - -sox-11gamma-cb3 1997-03-28 ---------------- - -This release of sox is mainly a bugfix release. The following things -have changed: - - o Documentation has been updated when it was obviously wrong. - Much more work could be done. Man pages were updated to - work correctly on Solaris and add some missing info. - o Several people sent me patches to fix compiling on Solaris - as well as fix a few bugs. - o Change USS driver's name to OSS. Man, does that driver - like to change names! This could cause problems if you - have made your own custom play and rec scripts. - o Updated my email address. Sorry if I haven't responded to - any emails as I no longer have access to my old address. - Please use cbagwell@sprynet.com. - o Fixed unix test scripts so that they worked again. - o Fixed endian bug in psion .wve code. - o Replaced outdated voc info file with detailed format info - inside voc code. - o Added new sound format, cvsd (Continuously Variable Slope Delta) - from Thomas Sailer (sailer@ife.ee.ethz.ch). - - -sox-11gamma-cb2 1996-10-04 ---------------- - -This release of sox is based on the latest gamma version released -plus some patches I've made to support the following new features: - -I would like to thank everyone that wrote me about the long -standing bug in Sox that could DELETE your /dev/* file if the -program was aborted for reason such as invalid audio file. Special -thanks for Bryan Franklin for sending in a patch when I was -to busy to even look for it. - - o Better play support for 8-bit stereo voc files. New support - for outputing both 8-bit and 16-bit stereo voc files. - o Built-in support for playing and recording from Linux /dev/dsp. - This is a re-write and seperate module from the previous - support included inside the sbdsp module. Also fixes a buffer - size bug that showed up when using newer versions of OSS. - This driver will work with OSS (and older versions called USS, TASD - and Voxware). - o Support for audio playing and recording with SunOS /dev/audio. - o Fixes a bug were /dev/audio or /dev/dsp could be deleted - when playing an invalid format audio file. - o Expanded options for play and rec scripts. You can now specify - sox effects after the filename and hear them in real time. - Please be sure that an older version of sox is not in your path - because these script will possibly find it first and - incorrectly use it. - o Setting play/record volume still requires an external program. - If you have one a command line program to do this (such as - "mixer" for Linux) then you will want to edit the play and rec - to use this. The current support for it is only in example - form of how it can be done. - - -List of earlier SoX Contributors --------------------------------- -Covering the time from its creation (Jul '91) until sox-11gamma (Feb '95): - - o Lance Norskog thinman at netcom.com - Creator & maintenance - o Guido Van Rossum guido at cwi.nl - AU, AIFF, AUTO, HCOM, reverse, many bug fixes - o Jef Poskanzer jef at well.sf.ca.us - original code for u-law and delay line - o Bill Neisius bill%solaria at hac2arpa.hac.com - DOS port, 8SVX, Sounder, Soundtool formats - Apollo fixes, stat with auto-picker - o Rick Richardson rick at digibd.com - WAV and SB driver handlers, fixes - o David Champion dgc3 at midway.uchicago.edu - Amiga port - o Pace Willisson pace at blitz.com - Fixes for ESIX - o Leigh Smith leigh at psychok.dialix.oz.au - SMP and comment movement support. - o David Sanderson dws at ssec.wisc.edu - AIX3.1 fixes - o Glenn Lewis glewis at pcocd2.intel.com - AIFF chunking fixes - o Brian Campbell brianc at quantum.qnx.com - QNX port and 16-bit fixes - o Chris Adams gt8741 at prism.gatech.edu - DOS port fixes - o John Kohl jtkohl at kolvir.elcr.ca.us - BSD386 port, VOC stereo support - o Ken Kubo ken at hmcvax.claremont.edu - VMS port, VOC stereo support - o Frank Gadegast phade at cs.tu-berlin.de - Microsoft C 7.0 & C Borland 3.0 ports - o David Elliot dce at scmc.sony.com - CD-R format support - o David Sears dns at essnj3.essnjay.com - Linux support - o Tom Littlejohn tlit at seq1.loc.gov - Raw textual data - o Boisy G. Pitre boisy at microware.com - OS9 port - o Sun Microsystems, Guido Van Rossum - CCITT G.711, G.721, G.723 implementation - o Graeme Gill graeme at labtam.labtam.oz.au - A-LAW format, Good .WAV handling, avg channel expansion - o Allen Grider grider at hfsi.hfsi.com - VOC stereo mode, WAV file handling - o Michel Fingerhut Michel.Fingerhut at ircam.fr - Upgrade 'sf' format to current IRCAM format. Float file support. - o Chris Knight - Achimedes Acorn support - o Richard Caley R.Caley at ed.ac.uk - Psion WVE handler - o Lutz Vieweg lkv at mania.RoBIN.de - MAUD (Amiga) file handler - o Tim Gardner timg at tpi.com - Windows NT port for V7 - o Jimen Ching jiching at wiliki.eng.hawaii.edu - Libst porting bugs - o Lauren Weinstein lauren at vortex.com - DOS porting, scripts, professional use diff --git a/apps/desktop/resources/sox/README.txt b/apps/desktop/resources/sox/README.txt deleted file mode 100644 index 268ba1e..0000000 --- a/apps/desktop/resources/sox/README.txt +++ /dev/null @@ -1,197 +0,0 @@ - SoX: Sound eXchange - =================== - -SoX (Sound eXchange) is the Swiss Army knife of sound processing tools: it -can convert sound files between many different file formats & audio devices, -and can apply many sound effects & transformations, as well as doing basic -analysis and providing input to more capable analysis and plotting tools. - -SoX is licensed under the GNU GPL and GNU LGPL. To be precise, the 'sox' -and 'soxi' programs are distributed under the GPL, while the library -'libsox' (in which most of SoX's functionality resides) is dual-licensed. -Note that some optional components of libsox are GPL only: if you use these, -you must use libsox under the GPL. See INSTALL for the list of optional -components and their licences. - -If this distribution is of source code (as opposed to pre-built binaries), -then you will need to compile and install SoX as described in the 'INSTALL' -file. - -Changes between this release and previous releases of SoX can be found in -the 'ChangeLog' file; a summary of the file formats and effects supported in -this release can be found below. Detailed documentation for using SoX can -be found in the distributed 'man' pages: - - o sox(1) - o soxi(1) - o soxformat(7) - o libsox(3) - -or in plain text or PDF files for those systems without man. - -The majority of SoX features and fixes are contributed by SoX users - thank -you very much for making SoX a success! There are several new features -wanted for SoX, listed on the feature request tracker at the SoX project -home-page: - - http://sourceforge.net/projects/sox - -users are encouraged to implement them! - -Please submit bug reports, new feature requests, and patches to the relevant -tracker at the above address, or by email: - - mailto:sox-devel@lists.sourceforge.net - -Also accessible via the project home-page is the SoX users' discussion -mailing list which you can join to discuss all matters SoX with other SoX -users; the mail address for this list is: - - mailto:sox-users@lists.sourceforge.net - -The current release handles the following audio file formats: - - - o Raw files in various binary formats - o Raw textual data - o Amiga 8svx files - o Apple/SGI AIFF files - o SUN .au files - o PCM, u-law, A-law - o G7xx ADPCM files (read only) - o mutant DEC .au files - o NeXT .snd files - o AVR files - o CDDA (Compact Disc Digital Audio format) - o CVS and VMS files (continuous variable slope) - o Grandstream ring-tone files - o GSM files - o HTK files - o LPC-10 files - o Macintosh HCOM files - o Amiga MAUD files - o AMR-WB & AMR-NB (with optional libamrwb & libamrnb libraries) - o MP2/MP3 (with optional libmad, libtwolame and libmp3lame libraries) - o MP4, AAC, AC3, WAVPACK, AMR-NB files (with optional ffmpeg library) - o AVI, WMV, Ogg Theora, MPEG video files (with optional ffmpeg library) - - o Ogg Vorbis files (with optional Ogg Vorbis libraries) - o FLAC files (with optional libFLAC) - o IRCAM SoundFile files - o NIST SPHERE files - o Turtle beach SampleVision files - o Sounder & Soundtool (DOS) files - o Yamaha TX-16W sampler files - o SoundBlaster .VOC files - o Dialogic/OKI ADPCM files (.VOX) - o Microsoft .WAV files - o PCM, floating point - o u-law, A-law, MS ADPCM, IMA (DMI) ADPCM - o GSM - o RIFX (big endian) - o WavPack files (with optional libwavpack library) - o Psion (palmtop) A-law WVE files and Record voice notes - o Maxis XA Audio files - o EA ADPCM (read support only, for now) - o Pseudo formats that allow direct playing/recording from most audio devices - o The "null" pseudo-file that reads and writes from/to nowhere - - -The audio effects/tools included in this release are as follows: - - o Tone/filter effects - o allpass: RBJ all-pass biquad IIR filter - o bandpass: RBJ band-pass biquad IIR filter - o bandreject: RBJ band-reject biquad IIR filter - o band: SPKit resonator band-pass IIR filter - o bass: Tone control: RBJ shelving biquad IIR filter - o equalizer: RBJ peaking equalisation biquad IIR filter - o firfit+: FFT convolution FIR filter using given freq. response (W.I.P.) - o highpass: High-pass filter: Single pole or RBJ biquad IIR - o hilbert: Hilbert transform filter (90 degrees phase shift) - o lowpass: Low-pass filter: single pole or RBJ biquad IIR - o sinc: Sinc-windowed low/high-pass/band-pass/reject FIR - o treble: Tone control: RBJ shelving biquad IIR filter - - o Production effects - o chorus: Make a single instrument sound like many - o delay: Delay one or more channels - o echo: Add an echo - o echos: Add a sequence of echos - o flanger: Stereo flanger - o overdrive: Non-linear distortion - o phaser: Phase shifter - o repeat: Loop the audio a number of times - o reverb: Add reverberation - o reverse: Reverse the audio (to search for Satanic messages ;-) - o tremolo: Sinusoidal volume modulation - - o Volume/level effects - o compand: Signal level compression/expansion/limiting - o contrast: Phase contrast volume enhancement - o dcshift: Apply or remove DC offset - o fade: Apply a fade-in and/or fade-out to the audio - o gain: Apply gain or attenuation; normalise/equalise/balance/headroom - o loudness: Gain control with ISO 226 loudness compensation - o mcompand: Multi-band compression/expansion/limiting - o norm: Normalise to 0dB (or other) - o vol: Adjust audio volume - - o Editing effects - o pad: Pad (usually) the ends of the audio with silence - o silence: Remove portions of silence from the audio - o splice: Perform the equivalent of a cross-faded tape splice - o trim: Cuts portions out of the audio - o vad: Voice activity detector - - o Mixing effects - o channels: Auto mix or duplicate to change number of channels - o divide+: Divide sample values by those in the 1st channel (W.I.P.) - o remix: Produce arbitrarily mixed output channels - o swap: Swap stereo channels - - o Pitch/tempo effects - o bend: Bend pitch at given times without changing tempo - o pitch: Adjust pitch (= key) without changing tempo - o speed: Adjust pitch & tempo together - o stretch: Adjust tempo without changing pitch (simple alg.) - o tempo: Adjust tempo without changing pitch (WSOLA alg.) - - o Mastering effects - o dither: Add dither noise to increase quantisation SNR - o rate: Change audio sampling rate - - o Specialised filters/mixers - o deemph: ISO 908 CD de-emphasis (shelving) IIR filter - o earwax: Process CD audio to best effect for headphone use - o noisered: Filter out noise from the audio - o oops: Out Of Phase Stereo (or `Karaoke') effect - o riaa: RIAA vinyl playback equalisation - - o Analysis `effects' - o noiseprof: Produce a DFT profile of the audio (use with noisered) - o spectrogram: graph signal level vs. frequency & time (needs `libpng') - o stat: Enumerate audio peak & RMS levels, approx. freq., etc. - o stats: Multichannel aware `stat' - - o Miscellaneous effects - o ladspa: Apply LADSPA plug-in effects e.g. CMT (Computer Music Toolkit) - o synth: Synthesise/modulate audio tones or noise signals - o newfile: Create a new output file when an effects chain ends. - o restart: Restart 1st effects chain when multiple chains exist. - - o Low-level signal processing effects - o biquad: 2nd-order IIR filter using externally provided coefficients - o downsample: Reduce sample rate by discarding samples - o fir: FFT convolution FIR filter using externally provided coefficients - o upsample: Increase sample rate by zero stuffing - - + Experimental or incomplete effect; may change in future. - -Multiple audio files can be combined (and then further processed with -effects) using any one of the following combiner methods: - - o concatenate - o mix - o merge: E.g. two mono files to one stereo file - o sequence: For playing multiple audio files/streams diff --git a/apps/desktop/resources/sox/README.win32.txt b/apps/desktop/resources/sox/README.win32.txt deleted file mode 100644 index 0ed7815..0000000 --- a/apps/desktop/resources/sox/README.win32.txt +++ /dev/null @@ -1,167 +0,0 @@ -SoX ---- - -This file contains information specific to the Win32 version of SoX. -Please refer to the README file for general information. - -The binary SOX.EXE can be installed anywhere you desire. The only -restriction is that the included ZLIB1..DLL and LIBGOMP-1.DLL must be -located in the same directory as SOX.EXE or somewhere within your PATH. - -SoX Helper Applications ------------------------ - -SoX also includes support for SOXI.EXE, PLAY.EXE and REC.EXE and their -behaviors are documented in included PDF's. They have the same -install restrictions as SOX.EXE. - -SOXI.EXE, PLAY.EXE, and REC.EXE are not distributed with this package to -reduce size requirements. They are, in fact, only copies of the original -SOX.EXE binary which changes SOX.EXE's behavior based on the -executable's filename. - -If you wish to make use of these utils then you can create them -yourself. - -copy sox.exe soxi.exe -copy sox.exe play.exe -copy sox.exe rec.exe - -If you are concerned with disk space, the play and record -functionality can be equated using the "-d" option with SOX.EXE. soxi -functionality can be equated using the "--info" option with SOX.EXE. The -rough syntax is: - -play: sox [input files and options] -d [effects] -rec: sox -d [output file and options] [effects] -soxi: sox --info [input files and options] - -Acknowledgements ----------------- - -SOX.EXE included in this package makes use of the following projects. -See the cygbuild script included with the source code package for -further information on how it was compiled and packaged. - - SoX - http://sox.sourceforge.net - - FLAC - http://flac.sourceforge.net - - LADSPA - http://www.ladspa.org - - libid3tag - http://www.underbit.com/products/mad - - libsndfile - http://www.mega-nerd.com/libsndfile - - Ogg Vorbis - http://www.vorbis.com - - PNG - http://www.libpng.org/pub/png - - WavPack - http://www.wavpack.com - - wget - http://www.gnu.org/software/wget - -Enjoy, -The SoX Development Team - -Appendix - wget Support ------------------------ - -SoX can make use of the wget command line utility to load files over -the internet. A binary copy of wget has been included with this -package of SoX for your convience. - -For SoX to make use of wget, it must be located either in your PATH or -within the same directory that SoX is ran from. - -Custom configuration of wget can be made by editing the file wget.ini -contained in the same directory as wget.exe. - -Please consult wget's homepage for access to source code as well as -further instructions on configuring. - -http://www.gnu.org/software/wget - -Appendix - MP3 Support ----------------------- - -SoX contains support for reading and writing MP3 files but does not ship -with the DLL's that perform decoding and encoding of MP3 data because -of patent restrictions. For further details, refer to: - -http://en.wikipedia.org/wiki/MP3#Licensing_and_patent_issues - -MP3 support can be enabled by placing Lame encoding DLL and/or -MAD decoding DLL into the same directory as SOX.EXE. These -can be compiled yourself, they may turn up on searches of the internet -or may be included with other MP3 applications already installed -on your system. For encoding/writing, try searching for lame-enc.dll, -libmp3lame-0.dll, libmp3lame.dll, or cygmp3lame-0.dll. For -decoding/reading, try searching for libmad-0.dll, libmad.dll or cygmad-0.dll. - -Instructions are included here for using MSYS to create the DLL's. -It is assumed you already have MSYS installed on your system -with a working gcc compiler. The commands are ran from MSYS -bash shell. - -Obtain the latest Lame and MAD source code from approprate locations. - -Lame MP3 encoder http://lame.sourceforge.net -MAD MP3 decoder http://www.underbit.com/products/mad - -cd lame-398-2 -./configure --disabled-static --enable-shared -make -cp libmp3lame/.libs/libmp3lame-0.dll /path/to/sox - -MAD libraries up to 0.15.1b have a bug in configure that will not allow -building DLL under mingw. This can be resolved by adding LDFLAGS -to configure and editing the generated Makefile to remove an invalid -option. - -cd libmad-0.15.1b -./configure --enable-shared --disable-static LDFLAGS="-no-undefined" -[edit Makefile, search for "-fforce-mem" and delete it.] -make -cp libmad-0.dll /path/to/sox/ - -Appendix - AMR-NB/AMR-WB Support --------------------------------- - -SoX contains support for reading and writing AMR-NB and AMR-WB files but -does not ship with the DLL's that perform decoding and encoding of AMR -data because of patent restrictions. - -AMR-NB/AMR-WB support can be enabled by placing required DLL's -into the same directory as SOX.EXE. These can be compiled yourself, -they may turn up on searches of the internet or may be included with other -MP3 applications already installed on your system. For AMR-NB support, -try searching for libamrnb-3.dll, libopencore-amrnb-0.dll, or -libopencore-amrnb.dll. For AMR-WB support, try searching for libamrwb-3.dll, -libopencore-amrwb-0.dll, or libopencore-amrwb.dll. - -Instructions are included here for using MSYS to create the DLL's. -It is assumed you already have MSYS installed on your system with -working gcc compiler. These commands are ran from MSYS bash shell. - -Obtain the latest amrnb and amrwb source code from -http://sourceforge.net/projects/opencore-amr . - -cd opencore-amr-0.1.2 -./configure --enable-shared --disable-static LDFLAGS="-no-undefined" -make -cp amrnb/.libs/libopencore-amrnb-0.dll /path/to/sox -cp amrwb/.libs/libopencore-amrwb-0.dll /path/to/sox - -Appendix - LADSPA Plugins -------------------------- - -SoX has built in support for LADSPA Plugins. These plugins are -mostly built for Linux but some are available for Windows. -The Audacity GUI application has a page that points to a collection -of Windows LADSPA plugins. - -http://audacity.sourceforge.net/download/plugins - -SoX will search for these plugins based on LADSPA_PATH -enviornment variable. See sox.txt for further information. diff --git a/apps/desktop/resources/sox/batch-example.bat b/apps/desktop/resources/sox/batch-example.bat deleted file mode 100644 index 65d8876..0000000 --- a/apps/desktop/resources/sox/batch-example.bat +++ /dev/null @@ -1,14 +0,0 @@ -rem Example of how to do batch processing with SoX on MS-Windows. -rem -rem Place this file in the same folder as sox.exe (& rename it as appropriate). -rem You can then drag and drop a selection of files onto the batch file (or -rem onto a `short-cut' to it). -rem -rem In this example, the converted files end up in a folder called `converted', -rem but this, of course, can be changed, as can the parameters to the sox -rem command. - -cd %~dp0 -mkdir converted -FOR %%A IN (%*) DO sox %%A "converted/%%~nxA" rate -v 44100 -pause diff --git a/apps/desktop/resources/sox/pthreadgc2.dll b/apps/desktop/resources/sox/pthreadgc2.dll deleted file mode 100644 index 5f4b701..0000000 Binary files a/apps/desktop/resources/sox/pthreadgc2.dll and /dev/null differ diff --git a/apps/desktop/resources/sox/sox.pdf b/apps/desktop/resources/sox/sox.pdf deleted file mode 100644 index 2447e9d..0000000 Binary files a/apps/desktop/resources/sox/sox.pdf and /dev/null differ diff --git a/apps/desktop/resources/sox/soxformat.pdf b/apps/desktop/resources/sox/soxformat.pdf deleted file mode 100644 index 3981ceb..0000000 Binary files a/apps/desktop/resources/sox/soxformat.pdf and /dev/null differ diff --git a/apps/desktop/resources/sox/soxi.pdf b/apps/desktop/resources/sox/soxi.pdf deleted file mode 100644 index 63b6196..0000000 Binary files a/apps/desktop/resources/sox/soxi.pdf and /dev/null differ diff --git a/apps/desktop/resources/sox/wget.exe b/apps/desktop/resources/sox/wget.exe deleted file mode 100644 index f2a11c1..0000000 Binary files a/apps/desktop/resources/sox/wget.exe and /dev/null differ diff --git a/apps/desktop/resources/sox/wget.ini b/apps/desktop/resources/sox/wget.ini deleted file mode 100644 index 7aeacc7..0000000 --- a/apps/desktop/resources/sox/wget.ini +++ /dev/null @@ -1,112 +0,0 @@ -### -### Sample Wget initialization file .wgetrc -### - -## You can use this file to change the default behaviour of wget or to -## avoid having to type many many command-line options. This file does -## not contain a comprehensive list of commands -- look at the manual -## to find out what you can put into this file. -## -## Wget initialization file can reside in /usr/local/etc/wgetrc -## (global, for all users) or $HOME/.wgetrc (for a single user). -## -## To use the settings in this file, you will have to uncomment them, -## as well as change them, in most cases, as the values on the -## commented-out lines are the default values (e.g. "off"). - - -## -## Global settings (useful for setting up in /usr/local/etc/wgetrc). -## Think well before you change them, since they may reduce wget's -## functionality, and make it behave contrary to the documentation: -## - -# You can set retrieve quota for beginners by specifying a value -# optionally followed by 'K' (kilobytes) or 'M' (megabytes). The -# default quota is unlimited. -#quota = inf - -# You can lower (or raise) the default number of retries when -# downloading a file (default is 20). -#tries = 20 - -# Lowering the maximum depth of the recursive retrieval is handy to -# prevent newbies from going too "deep" when they unwittingly start -# the recursive retrieval. The default is 5. -#reclevel = 5 - -# By default Wget uses "passive FTP" transfer where the client -# initiates the data connection to the server rather than the other -# way around. That is required on systems behind NAT where the client -# computer cannot be easily reached from the Internet. However, some -# firewalls software explicitly supports active FTP and in fact has -# problems supporting passive transfer. If you are in such -# environment, use "passive_ftp = off" to revert to active FTP. -#passive_ftp = off - -# The "wait" command below makes Wget wait between every connection. -# If, instead, you want Wget to wait only between retries of failed -# downloads, set waitretry to maximum number of seconds to wait (Wget -# will use "linear backoff", waiting 1 second after the first failure -# on a file, 2 seconds after the second failure, etc. up to this max). -waitretry = 10 - - -## -## Local settings (for a user to set in his $HOME/.wgetrc). It is -## *highly* undesirable to put these settings in the global file, since -## they are potentially dangerous to "normal" users. -## -## Even when setting up your own ~/.wgetrc, you should know what you -## are doing before doing so. -## - -# Set this to on to use timestamping by default: -#timestamping = off - -# It is a good idea to make Wget send your email address in a `From:' -# header with your request (so that server administrators can contact -# you in case of errors). Wget does *not* send `From:' by default. -#header = From: Your Name - -# You can set up other headers, like Accept-Language. Accept-Language -# is *not* sent by default. -#header = Accept-Language: en - -# You can set the default proxies for Wget to use for http and ftp. -# They will override the value in the environment. -#http_proxy = http://proxy.yoyodyne.com:18023/ -#ftp_proxy = http://proxy.yoyodyne.com:18023/ - -# If you do not want to use proxy at all, set this to off. -#use_proxy = on - -# You can customize the retrieval outlook. Valid options are default, -# binary, mega and micro. -#dot_style = default - -# Setting this to off makes Wget not download /robots.txt. Be sure to -# know *exactly* what /robots.txt is and how it is used before changing -# the default! -#robots = on - -# It can be useful to make Wget wait between connections. Set this to -# the number of seconds you want Wget to wait. -#wait = 0 - -# You can force creating directory structure, even if a single is being -# retrieved, by setting this to on. -#dirstruct = off - -# You can turn on recursive retrieving by default (don't do this if -# you are not sure you know what it means) by setting this to on. -#recursive = off - -# To always back up file X as X.orig before converting its links (due -# to -k / --convert-links / convert_links = on having been specified), -# set this variable to on: -#backup_converted = off - -# To have Wget follow FTP links from HTML files by default, set this -# to on: -#follow_ftp = off diff --git a/apps/desktop/scripts/download-sox.ps1 b/apps/desktop/scripts/download-sox.ps1 index 0976ce1..1d3b3ae 100644 --- a/apps/desktop/scripts/download-sox.ps1 +++ b/apps/desktop/scripts/download-sox.ps1 @@ -1,4 +1,4 @@ -# scripts/download-sox.ps1 +# scripts/download-sox.ps1 # SoX Windows 바이너리를 resources/sox/에 다운로드한다. # 실행: powershell -ExecutionPolicy Bypass -File scripts/download-sox.ps1 @@ -36,7 +36,7 @@ try { Write-Host " https://sourceforge.net/projects/sox/files/sox/14.4.1/sox-14.4.1-win32.zip/download" Write-Host "" Write-Host "2. 다운로드한 zip에서 아래 파일들을 복사:" -ForegroundColor White - Write-Host " sox.exe, rec.exe, libmad-0.dll, libmp3lame-0.dll, libsox-3.dll" + Write-Host " sox.exe, zlib1.dll, LICENSE.GPL.txt" Write-Host "" Write-Host "3. 복사 위치:" -ForegroundColor White Write-Host " $DEST_DIR" @@ -54,7 +54,7 @@ if ($fileSize -lt 100000) { Write-Host " https://sourceforge.net/projects/sox/files/sox/14.4.1/sox-14.4.1-win32.zip/download" Write-Host "" Write-Host "2. 다운로드한 zip 압축 해제 후 아래 파일들을 복사:" -ForegroundColor White - Write-Host " sox.exe, rec.exe, libmad-0.dll, libmp3lame-0.dll, libsox-3.dll" + Write-Host " sox.exe, zlib1.dll, LICENSE.GPL.txt" Write-Host "" Write-Host "3. 복사 위치:" -ForegroundColor White Write-Host " $DEST_DIR" @@ -82,7 +82,7 @@ if (-not $SOX_EXTRACTED) { $SOX_EXTRACTED = Get-Item $TEMP_DIR } -$filesToCopy = @("sox.exe", "rec.exe", "libmad-0.dll", "libmp3lame-0.dll", "libsox-3.dll") +$filesToCopy = @("sox.exe", "zlib1.dll", "LICENSE.GPL.txt") New-Item -ItemType Directory -Force -Path $DEST_DIR | Out-Null $copied = 0 diff --git a/apps/desktop/sidecar/main.py b/apps/desktop/sidecar/main.py index e9d42ed..fd66bf8 100644 --- a/apps/desktop/sidecar/main.py +++ b/apps/desktop/sidecar/main.py @@ -29,9 +29,10 @@ import logging import os import signal import sys +import tempfile import threading import time -from contextlib import asynccontextmanager +from contextlib import asynccontextmanager, suppress from pathlib import Path from typing import AsyncGenerator @@ -599,28 +600,40 @@ async def load_model(body: dict) -> JSONResponse: # noqa: ANN001 @app.post("/unload") async def unload_model(request: Request) -> JSONResponse: - """보조 자리 모델을 내려 VRAM/RAM 을 돌려준다. + """보조 자리 또는 기본(primary) 자리 모델을 내려 VRAM/RAM 을 돌려준다. - 자막·회의가 끝난 뒤에도 보조 모델(예: large-v3-turbo)이 받아쓰기 모델과 함께 상주하면 - GPU 여유가 줄어 Ollama 모델 로드가 느려지거나 OOM 이 난다. 기본(primary) 모델은 받아쓰기 - 지연을 막기 위해 내리지 않는다. + 사이드카 HTTP 프로세스 자체는 UIA 브리지(/uia/focus)가 계속 쓰므로 살려 둔 채, + 클라우드 STT 전환·장시간 유휴·자막 종료 시 Whisper CTranslate2 모델 메모리만 회수한다. - Request body: { "slot": "aux" } + Request body: { "slot": "aux" | "primary" | "all" } """ + global _model, _model_id + body = await request.json() slot: str = body.get("slot", "aux") - if slot != "aux": + if slot not in ("aux", "primary", "all"): return JSONResponse( status_code=400, - content={"status": "error", "message": "only the aux slot can be unloaded"}, + content={"status": "error", "message": "slot must be aux, primary, or all"}, ) + released: list[str] = [] async with _inference_lock: - released = list(_aux_models) - _aux_models.clear() + if slot in ("primary", "all") and _model is not None: + if _model_id: + released.append(_model_id) + _model_devices.pop(_model_id, None) + _model = None + _model_id = None + if slot in ("aux", "all") and _aux_models: + for aux_id in list(_aux_models): + released.append(aux_id) + _model_devices.pop(aux_id, None) + _aux_models.clear() + if released: gc.collect() - logger.info("보조 모델 언로드: %s", ", ".join(released)) + logger.info("모델 언로드(%s): %s", slot, ", ".join(released)) return JSONResponse(content={"status": "unloaded", "models": released}) @@ -708,14 +721,21 @@ async def transcribe( start_time = time.monotonic() try: - pcm_bytes = await audio.read() + try: + pcm_bytes = await audio.read() + finally: + await audio.close() - if len(pcm_bytes) == 0: + if len(pcm_bytes) < 2: return JSONResponse( status_code=400, content={"status": "error", "message": "오디오 데이터가 비어있습니다"}, ) + if len(pcm_bytes) % 2 != 0: + logger.warning("홀수 바이트 PCM 입력(%dB) — 마지막 1바이트를 버립니다", len(pcm_bytes)) + pcm_bytes = pcm_bytes[:-1] + audio_array = ( np.frombuffer(pcm_bytes, dtype=np.int16).astype(np.float32) / 32768.0 ) @@ -756,6 +776,8 @@ async def transcribe( finally: cancel.set() watcher.cancel() + with suppress(asyncio.CancelledError, Exception): + await watcher processing_time = int((time.monotonic() - start_time) * 1000) @@ -872,11 +894,134 @@ async def uia_focus(timeoutMs: int = 1500) -> JSONResponse: return JSONResponse(content=snapshot) +def _run_pyannote_diarization( + audio_bytes: bytes, + hf_token: str, + num_speakers: int | None, +) -> dict[str, object]: + """선택 설치된 pyannote.audio 파이프라인으로 화자 구간을 추출한다.""" + try: + from pyannote.audio import Pipeline # type: ignore[import-not-found] + except Exception as exc: + raise ModuleNotFoundError(str(exc)) from exc + + fd, temp_path_str = tempfile.mkstemp(suffix=".wav", prefix="d3ro-diarize-") + temp_path = Path(temp_path_str) + try: + with os.fdopen(fd, "wb") as handle: + handle.write(audio_bytes) + + try: + pipeline = Pipeline.from_pretrained( + "pyannote/speaker-diarization-3.1", + token=hf_token, + ) + except TypeError: + pipeline = Pipeline.from_pretrained( + "pyannote/speaker-diarization-3.1", + use_auth_token=hf_token, + ) + + call_kwargs: dict[str, object] = {} + if num_speakers is not None and num_speakers > 0: + call_kwargs["num_speakers"] = num_speakers + + annotation = pipeline(str(temp_path), **call_kwargs) + segments: list[dict[str, object]] = [] + speakers: set[str] = set() + for turn, _track, speaker in annotation.itertracks(yield_label=True): + speaker_label = str(speaker) + speakers.add(speaker_label) + segments.append( + { + "speaker": speaker_label, + "start": round(float(turn.start), 3), + "end": round(float(turn.end), 3), + } + ) + return { + "status": "ok", + "segments": segments, + "num_speakers": len(speakers), + } + finally: + try: + temp_path.unlink(missing_ok=True) + except OSError: + pass + + +@app.post("/diarize") +async def diarize( + audio: UploadFile = File(...), + hf_token: str = Form(""), + num_speakers: int | None = Form(None), +) -> JSONResponse: + """pyannote.audio 기반 화자 분리 엔드포인트 (미설치 시 503 반환으로 LLM 폴백 유도).""" + token = hf_token.strip() + if not token: + return JSONResponse( + status_code=400, + content={ + "status": "error", + "code": "missing_hf_token", + "message": "Hugging Face 토큰이 비어 있습니다", + }, + ) + + try: + audio_bytes = await audio.read() + finally: + await audio.close() + if not audio_bytes: + return JSONResponse( + status_code=400, + content={ + "status": "error", + "code": "empty_audio", + "message": "오디오 파일이 비어 있습니다", + }, + ) + + async with _inference_lock: + try: + result = await asyncio.to_thread( + _run_pyannote_diarization, + audio_bytes, + token, + num_speakers, + ) + return JSONResponse(content=result) + except ModuleNotFoundError: + return JSONResponse( + status_code=503, + content={ + "status": "unavailable", + "code": "pyannote_not_installed", + "message": "pyannote.audio 패키지가 설치되어 있지 않습니다", + }, + ) + except Exception as exc: + logger.warning("pyannote 화자 분리 실패: %s", exc) + return JSONResponse( + status_code=500, + content={ + "status": "error", + "code": "diarization_failed", + "message": f"화자 분리 실행 실패: {exc}", + }, + ) + + @app.post("/shutdown") async def shutdown() -> JSONResponse: """서버를 graceful하게 종료한다.""" logger.info("종료 요청 수신") + if _download_thread is not None and _download_thread.is_alive(): + _download_cancel.set() + await asyncio.to_thread(_download_thread.join, 2.0) + try: import uia_bridge diff --git a/apps/desktop/sidecar/tests/test_diarize_endpoint.py b/apps/desktop/sidecar/tests/test_diarize_endpoint.py new file mode 100644 index 0000000..2efc498 --- /dev/null +++ b/apps/desktop/sidecar/tests/test_diarize_endpoint.py @@ -0,0 +1,115 @@ +""" +사이드카 /diarize 엔드포인트 계약 테스트 (GAP-MTG-02). +""" + +from __future__ import annotations + +import sys +import types +import unittest +from pathlib import Path +from unittest import mock + +SIDECAR_DIR = Path(__file__).resolve().parent.parent +if str(SIDECAR_DIR) not in sys.path: + sys.path.insert(0, str(SIDECAR_DIR)) + +from fastapi.testclient import TestClient # noqa: E402 + +import main # noqa: E402 + + +class _FakeTurn: + def __init__(self, start: float, end: float) -> None: + self.start = start + self.end = end + + +class _FakeAnnotation: + def itertracks(self, yield_label: bool = False): + tracks = [ + (_FakeTurn(0.2, 4.5), "A", "SPEAKER_00"), + (_FakeTurn(5.0, 9.8), "B", "SPEAKER_01"), + (_FakeTurn(10.1, 13.0), "C", "SPEAKER_00"), + ] + if yield_label: + return tracks + return [(t[0], t[1]) for t in tracks] + + +class DiarizeEndpointTest(unittest.TestCase): + def setUp(self) -> None: + self.client = TestClient(main.app) + + def test_diarize_rejects_empty_hf_token(self) -> None: + response = self.client.post( + "/diarize", + files={"audio": ("audio.wav", b"RIFF0000WAVEfmt ", "audio/wav")}, + data={"hf_token": " "}, + ) + self.assertEqual(response.status_code, 400) + body = response.json() + self.assertEqual(body["code"], "missing_hf_token") + + def test_diarize_returns_503_when_pyannote_not_installed(self) -> None: + with mock.patch.dict(sys.modules, {"pyannote": None, "pyannote.audio": None}): + response = self.client.post( + "/diarize", + files={"audio": ("audio.wav", b"RIFF0000WAVEfmt ", "audio/wav")}, + data={"hf_token": "hf_test_token"}, + ) + self.assertEqual(response.status_code, 503) + body = response.json() + self.assertEqual(body["code"], "pyannote_not_installed") + + def test_diarize_returns_segments_and_cleans_temp_file(self) -> None: + observed_paths: list[Path] = [] + observed_kwargs: list[dict[str, object]] = [] + + class _FakePipeline: + @classmethod + def from_pretrained(cls, model_id: str, **kwargs: object) -> "_FakePipeline": + self_inst = cls() + self_inst.model_id = model_id + self_inst.init_kwargs = kwargs + return self_inst + + def __call__(self, audio_path: str, **kwargs: object) -> _FakeAnnotation: + observed_paths.append(Path(audio_path)) + observed_kwargs.append(dict(kwargs)) + self.temp_existed_during_call = Path(audio_path).exists() + return _FakeAnnotation() + + fake_pyannote = types.ModuleType("pyannote") + fake_pyannote_audio = types.ModuleType("pyannote.audio") + fake_pyannote_audio.Pipeline = _FakePipeline # type: ignore[attr-defined] + + with mock.patch.dict( + sys.modules, + {"pyannote": fake_pyannote, "pyannote.audio": fake_pyannote_audio}, + ): + response = self.client.post( + "/diarize", + files={"audio": ("audio.wav", b"RIFF1234WAVEfmt ", "audio/wav")}, + data={"hf_token": "hf_valid_token", "num_speakers": "2"}, + ) + + self.assertEqual(response.status_code, 200) + body = response.json() + self.assertEqual(body["status"], "ok") + self.assertEqual(body["num_speakers"], 2) + self.assertEqual( + body["segments"], + [ + {"speaker": "SPEAKER_00", "start": 0.2, "end": 4.5}, + {"speaker": "SPEAKER_01", "start": 5.0, "end": 9.8}, + {"speaker": "SPEAKER_00", "start": 10.1, "end": 13.0}, + ], + ) + self.assertEqual(observed_kwargs, [{"num_speakers": 2}]) + self.assertEqual(len(observed_paths), 1) + self.assertFalse(observed_paths[0].exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/desktop/sidecar/tests/test_transcribe_hygiene.py b/apps/desktop/sidecar/tests/test_transcribe_hygiene.py new file mode 100644 index 0000000..1bbb75c --- /dev/null +++ b/apps/desktop/sidecar/tests/test_transcribe_hygiene.py @@ -0,0 +1,87 @@ +"""Sidecar /transcribe & /shutdown hygiene regression tests.""" + +from __future__ import annotations + +import sys +import threading +import unittest +from pathlib import Path +from unittest import mock + +SIDECAR_DIR = Path(__file__).resolve().parent.parent +if str(SIDECAR_DIR) not in sys.path: + sys.path.insert(0, str(SIDECAR_DIR)) + +from fastapi.testclient import TestClient # noqa: E402 + +import main # noqa: E402 + + +class _FakeModel: + pass + + +class TranscribeAndShutdownHygieneTest(unittest.TestCase): + def setUp(self) -> None: + self._orig_model = main._model + self._orig_model_id = main._model_id + self._orig_thread = main._download_thread + main._model = _FakeModel() # type: ignore[assignment] + main._model_id = "tiny" + self.client = TestClient(main.app) + + def tearDown(self) -> None: + main._model = self._orig_model + main._model_id = self._orig_model_id + main._download_thread = self._orig_thread + main._download_cancel.clear() + + def test_transcribe_single_byte_pcm_returns_400_without_frombuffer_crash(self) -> None: + res = self.client.post( + "/transcribe", + files={"audio": ("chunk.pcm", b"\x01", "application/octet-stream")}, + ) + self.assertEqual(res.status_code, 400) + self.assertEqual(res.json()["status"], "error") + + def test_transcribe_odd_byte_pcm_truncates_trailing_byte_and_succeeds(self) -> None: + observed_samples: list[int] = [] + + def fake_transcribe(_model, audio_array, _kwargs, _resolved_id, _is_primary, _cancel): + observed_samples.append(len(audio_array)) + return [{"text": "ok", "start": 0.0, "end": 0.1}], "ok", "ko" + + with mock.patch.object(main, "_transcribe_blocking", side_effect=fake_transcribe): + res = self.client.post( + "/transcribe", + files={"audio": ("chunk.pcm", b"\x00\x01\x02\x03\x99", "application/octet-stream")}, + ) + + self.assertEqual(res.status_code, 200) + self.assertEqual(observed_samples, [2]) + self.assertEqual(res.json()["text"], "ok") + + def test_shutdown_cancels_active_download_thread(self) -> None: + stopped = threading.Event() + + def fake_worker() -> None: + main._download_cancel.wait(timeout=5.0) + stopped.set() + + main._download_cancel.clear() + worker = threading.Thread(target=fake_worker, daemon=True) + main._download_thread = worker + worker.start() + + with mock.patch.object(main, "_server", None): + res = self.client.post("/shutdown") + + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json()["status"], "shutting_down") + self.assertTrue(main._download_cancel.is_set()) + self.assertTrue(stopped.is_set()) + self.assertFalse(worker.is_alive()) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/desktop/src/main/bootstrap.ts b/apps/desktop/src/main/bootstrap.ts index 717e722..550dbc3 100644 --- a/apps/desktop/src/main/bootstrap.ts +++ b/apps/desktop/src/main/bootstrap.ts @@ -35,7 +35,6 @@ import { openStartupDatabase } from './db/startup-database' import { createMainWindow, getMainWindow, - preloadPopupWindows, showHistoryPopup, hideHistoryPopup, sendKeyToHistoryPopup, @@ -44,8 +43,8 @@ import { hideCommandPopup, sendKeyToCommandPopup, isCommandPopupVisible, - getHistoryPopupWindow, - getCommandPopupWindow, + peekHistoryPopupWindow, + peekCommandPopupWindow, reapplyThemeToAllPopups, } from './windows/WindowManager' import { createTray } from './windows/TrayManager' @@ -57,6 +56,8 @@ import { setupLifecycle } from './lifecycle' import { getShutdownRegistry } from './shutdown-registry' import { shouldDismissOnEscape } from './suggestion-overlay-policy' import { registerAllIpcHandlers } from './ipc' +import { disposeAudioHandlers } from './ipc/audio-handlers' +import { safeSendToRenderer } from './ipc/renderer-broadcast' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' import type { IPCChannel } from '@d3ro/core/ipc-channels' @@ -128,6 +129,7 @@ export async function bootstrap(): Promise { */ function registerCoreShutdownSteps(): void { const registry = getShutdownRegistry() + registry.register({ name: 'audio-test', dispose: () => disposeAudioHandlers() }) registry.register({ name: 'local-llm', dispose: () => disposeLocalLLMService() }) registry.register({ name: 'local-stt', dispose: () => disposeLocalSTTServiceIfStarted() }) } @@ -169,7 +171,9 @@ async function initConfigEffects(): Promise { effects.register('theme', () => reapplyThemeToAllPopups()) // 팝업 문서 lang 도 같은 재주입에서 맞춘다 effects.register('language', () => reapplyThemeToAllPopups()) - // 자동 한영·오타 교정이나 제안 설정이 바뀌면 입력 문맥 관찰기 실행 여부도 동기화한다 + // 자동 한영·오타 교정이나 제안·입력 텔레메트리 설정이 바뀌면 관찰기 실행/마우스 훅 상태도 즉시 동기화한다 + effects.register('inputTelemetryEnabled', () => getInputTelemetryService().applyConfig()) + effects.register('inputTelemetryPaused', () => getInputTelemetryService().applyConfig()) effects.register('typoAutoCorrectEnabled', () => getInputTelemetryService().applyConfig()) effects.register('suggestionEnabled', () => getInputTelemetryService().applyConfig()) effects.start() @@ -208,10 +212,12 @@ async function initInputIntelligence(): Promise { const telemetry = getInputTelemetryService() const suggestion = getSuggestionService() - // 첫 제안 수락·받아쓰기 삽입이 키 입력 모듈 로딩(수 초)을 기다리지 않게, 부팅이 끝난 뒤 미리 불러 둔다. - setTimeout(() => { - void getTextInsertService().preload() - }, 5_000).unref?.() + // macOS 등 nut-js 를 쓰는 환경에서만 부팅 뒤 미리 불러 둔다 (Windows 는 koffi SendInput 즉시 로드). + if (process.platform !== 'win32') { + setTimeout(() => { + void getTextInsertService().preload() + }, 5_000).unref?.() + } // 오타 교정이 먼저 본다 — 고치는 중이면 텍스트가 곧 바뀌니 제안으로 넘기지 않고(교정 뒤 새 // 스냅샷이 온다), 모델로 검사 중이면 끝날 때('settled') 넘긴다. 제안이 고친 문장을 기준으로 @@ -384,7 +390,8 @@ async function initAutoUpdate(): Promise { } async function initPopupWindows(): Promise { - preloadPopupWindows() + // 팝업 창(녹음 팁·결과·기록·명령)은 부팅 시 숨긴 Chromium 프로세스 4개를 선점하지 않고, + // 실제 핫키/이벤트가 발생해 표시할 때 처음 생성한 뒤 재사용한다 (~180-260MB 초기 메모리 절감). // 시스템 테마를 따르는 설정이면 OS 다크/라이트 전환 때 팝업도 다시 칠한다(언어가 바뀌면 lang 도 함께) const onNativeThemeUpdated = (): void => { @@ -444,7 +451,10 @@ function createPopupNavigationController(): PopupNavigationController { hide: () => hideHistoryPopup(), isVisible: () => isHistoryPopupVisible(), sendKey: (key) => sendKeyToHistoryPopup(key), - containsPoint: (point) => windowContains(getHistoryPopupWindow(), point), + containsPoint: (point) => { + const win = peekHistoryPopupWindow() + return win ? windowContains(win, point) : false + }, }, command: { show: () => { @@ -455,7 +465,10 @@ function createPopupNavigationController(): PopupNavigationController { hide: () => hideCommandPopup(), isVisible: () => isCommandPopupVisible(), sendKey: (key) => sendKeyToCommandPopup(key), - containsPoint: (point) => windowContains(getCommandPopupWindow(), point), + containsPoint: (point) => { + const win = peekCommandPopupWindow() + return win ? windowContains(win, point) : false + }, }, }, shortcuts: { @@ -551,10 +564,7 @@ async function initVoiceMode(): Promise { /** 메인 윈도우 렌더러에 UI 갱신 이벤트 전송 */ function notifyRenderer(channel: IPCChannel, data?: Record): void { - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send(channel, data ?? {}) - } + safeSendToRenderer(channel, data ?? {}) } async function initLLMPolling(): Promise { @@ -568,6 +578,11 @@ async function initLLMPolling(): Promise { */ async function initSTTWarmup(): Promise { try { + const activeProvider = (configGet('sttProvider') as string | undefined) || 'local' + if (activeProvider !== 'local') { + logger.info(`[bootstrap] skipping local STT warmup (active provider: ${activeProvider})`) + return + } const { getSTTManager } = await import('./services/stt/STTManager') void getSTTManager().warmUpLocal() } catch (err) { diff --git a/apps/desktop/src/main/db/index.ts b/apps/desktop/src/main/db/index.ts index c2a9b08..cced388 100644 --- a/apps/desktop/src/main/db/index.ts +++ b/apps/desktop/src/main/db/index.ts @@ -15,6 +15,7 @@ import * as schema from './schema' import { getLogger } from '../services/LoggerService' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import { emitAccountScopeChanged, LOCAL_SCOPE_ID } from '../services/account-scope' +import { invalidateEmbeddedChunksCache } from '../services/rag/chunk-store' const logger = getLogger('database') @@ -88,8 +89,12 @@ function archiveLegacyDbIfExists(): void { export function applySchema(s: Database.Database): void { s.pragma('journal_mode = WAL') + s.pragma('synchronous = NORMAL') s.pragma('foreign_keys = ON') s.pragma('busy_timeout = 5000') + s.pragma('temp_store = MEMORY') + s.pragma('cache_size = -16000') + s.pragma('mmap_size = 67108864') s.exec(` CREATE TABLE IF NOT EXISTS history ( @@ -187,11 +192,12 @@ export function applySchema(s: Database.Database): void { CREATE INDEX IF NOT EXISTS idx_rag_documents_added_at ON rag_documents(added_at); CREATE TABLE IF NOT EXISTS rag_chunks ( - id TEXT PRIMARY KEY, - document_id TEXT NOT NULL, - content TEXT NOT NULL, - embedding TEXT NOT NULL, - chunk_index INTEGER NOT NULL + id TEXT PRIMARY KEY, + document_id TEXT NOT NULL, + content TEXT NOT NULL, + embedding TEXT NOT NULL, + embedding_blob BLOB, + chunk_index INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_rag_chunks_document_id ON rag_chunks(document_id); `) @@ -217,6 +223,7 @@ export function applySchema(s: Database.Database): void { updated_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_meeting_sessions_created_at ON meeting_sessions(created_at DESC); + CREATE INDEX IF NOT EXISTS idx_meeting_sessions_started_at ON meeting_sessions(started_at DESC); CREATE INDEX IF NOT EXISTS idx_meeting_sessions_status ON meeting_sessions(status); CREATE TABLE IF NOT EXISTS meeting_memos ( @@ -228,6 +235,7 @@ export function applySchema(s: Database.Database): void { ); CREATE INDEX IF NOT EXISTS idx_meeting_memos_session_id ON meeting_memos(session_id); CREATE INDEX IF NOT EXISTS idx_meeting_memos_timestamp ON meeting_memos(timestamp_ms); + CREATE INDEX IF NOT EXISTS idx_meeting_memos_created_at ON meeting_memos(created_at DESC); `) // Phase 14.5: meeting_documents 테이블 @@ -383,6 +391,8 @@ export function applySchema(s: Database.Database): void { // 기기 간 동기화: 모바일과 같은 필드(즐겨찾기, 메모 수정 시각) + 로컬 outbox/커서 addColumnIfMissing(s, 'history', 'is_favorite', 'INTEGER NOT NULL DEFAULT 0') addColumnIfMissing(s, 'meeting_memos', 'updated_at', 'INTEGER') + addColumnIfMissing(s, 'meeting_memos', 'revision', 'INTEGER NOT NULL DEFAULT 1') + addColumnIfMissing(s, 'rag_chunks', 'embedding_blob', 'BLOB') s.exec(` CREATE TABLE IF NOT EXISTS sync_outbox ( entity TEXT NOT NULL, @@ -403,6 +413,150 @@ export function applySchema(s: Database.Database): void { updated_at INTEGER NOT NULL ); `) + + applySearchIndexSchema(s) +} + +const FTS5_BACKFILL_KEY = 'fts5Backfill:v1' + +/** + * 로컬 통합 검색용 FTS5 trigram 가상 테이블 + 동기화 트리거 + 기존 DB 1회 백필. + * 한글/영문/혼합 부분 문자열(3자 이상) 검색에서 전체 테이블 스캔을 제거한다. + */ +function applySearchIndexSchema(s: Database.Database): void { + try { + s.exec(` + CREATE VIRTUAL TABLE IF NOT EXISTS history_fts USING fts5( + row_id UNINDEXED, + search_text, + tokenize = 'trigram' + ); + + CREATE TRIGGER IF NOT EXISTS trg_history_fts_ai AFTER INSERT ON history BEGIN + INSERT INTO history_fts(row_id, search_text) + VALUES ( + new.id, + coalesce(new.title, '') || char(10) || + coalesce(new.original_text, '') || char(10) || + coalesce(new.polished_text, '') || char(10) || + coalesce(new.summary_text, '') + ); + END; + + CREATE TRIGGER IF NOT EXISTS trg_history_fts_ad AFTER DELETE ON history BEGIN + DELETE FROM history_fts WHERE row_id = old.id; + END; + + CREATE TRIGGER IF NOT EXISTS trg_history_fts_au + AFTER UPDATE OF title, original_text, polished_text, summary_text ON history BEGIN + DELETE FROM history_fts WHERE row_id = old.id; + INSERT INTO history_fts(row_id, search_text) + VALUES ( + new.id, + coalesce(new.title, '') || char(10) || + coalesce(new.original_text, '') || char(10) || + coalesce(new.polished_text, '') || char(10) || + coalesce(new.summary_text, '') + ); + END; + + CREATE VIRTUAL TABLE IF NOT EXISTS meeting_sessions_fts USING fts5( + row_id UNINDEXED, + search_text, + tokenize = 'trigram' + ); + + CREATE TRIGGER IF NOT EXISTS trg_meeting_sessions_fts_ai AFTER INSERT ON meeting_sessions BEGIN + INSERT INTO meeting_sessions_fts(row_id, search_text) + VALUES ( + new.id, + coalesce(new.title, '') || char(10) || + coalesce(new.edited_transcript, '') || char(10) || + coalesce(new.raw_transcript, '') + ); + END; + + CREATE TRIGGER IF NOT EXISTS trg_meeting_sessions_fts_ad AFTER DELETE ON meeting_sessions BEGIN + DELETE FROM meeting_sessions_fts WHERE row_id = old.id; + END; + + CREATE TRIGGER IF NOT EXISTS trg_meeting_sessions_fts_au + AFTER UPDATE OF title, edited_transcript, raw_transcript ON meeting_sessions BEGIN + DELETE FROM meeting_sessions_fts WHERE row_id = old.id; + INSERT INTO meeting_sessions_fts(row_id, search_text) + VALUES ( + new.id, + coalesce(new.title, '') || char(10) || + coalesce(new.edited_transcript, '') || char(10) || + coalesce(new.raw_transcript, '') + ); + END; + + CREATE VIRTUAL TABLE IF NOT EXISTS meeting_memos_fts USING fts5( + row_id UNINDEXED, + search_text, + tokenize = 'trigram' + ); + + CREATE TRIGGER IF NOT EXISTS trg_meeting_memos_fts_ai AFTER INSERT ON meeting_memos BEGIN + INSERT INTO meeting_memos_fts(row_id, search_text) + VALUES (new.id, coalesce(new.content, '')); + END; + + CREATE TRIGGER IF NOT EXISTS trg_meeting_memos_fts_ad AFTER DELETE ON meeting_memos BEGIN + DELETE FROM meeting_memos_fts WHERE row_id = old.id; + END; + + CREATE TRIGGER IF NOT EXISTS trg_meeting_memos_fts_au + AFTER UPDATE OF content ON meeting_memos BEGIN + DELETE FROM meeting_memos_fts WHERE row_id = old.id; + INSERT INTO meeting_memos_fts(row_id, search_text) + VALUES (new.id, coalesce(new.content, '')); + END; + `) + + const backfilled = s + .prepare('SELECT value FROM sync_state WHERE key = ?') + .get(FTS5_BACKFILL_KEY) as { value: string } | undefined + if (!backfilled) { + const now = Date.now() + const backfill = s.transaction(() => { + s.exec(` + DELETE FROM history_fts; + INSERT INTO history_fts(row_id, search_text) + SELECT + id, + coalesce(title, '') || char(10) || + coalesce(original_text, '') || char(10) || + coalesce(polished_text, '') || char(10) || + coalesce(summary_text, '') + FROM history; + + DELETE FROM meeting_sessions_fts; + INSERT INTO meeting_sessions_fts(row_id, search_text) + SELECT + id, + coalesce(title, '') || char(10) || + coalesce(edited_transcript, '') || char(10) || + coalesce(raw_transcript, '') + FROM meeting_sessions; + + DELETE FROM meeting_memos_fts; + INSERT INTO meeting_memos_fts(row_id, search_text) + SELECT id, coalesce(content, '') + FROM meeting_memos; + `) + s.prepare( + 'INSERT OR REPLACE INTO sync_state(key, value, updated_at) VALUES (?, ?, ?)' + ).run(FTS5_BACKFILL_KEY, String(now), now) + }) + backfill() + } + } catch (err) { + logger.warn( + `FTS5 search index setup skipped: ${err instanceof Error ? err.message : String(err)}` + ) + } } function addColumnIfMissing( @@ -508,7 +662,15 @@ export function openLocal(): OpenForUserResult { * 현재 열려있는 DB 닫기. 아무 것도 안 열려 있으면 no-op. */ export function closeCurrent(): void { - if (!sqlite) return + const prevDb = db + if (!sqlite) { + if (prevDb) { + invalidateEmbeddedChunksCache(prevDb) + db = null + currentUserId = null + } + return + } const prevUserId = currentUserId try { @@ -518,6 +680,7 @@ export function closeCurrent(): void { `Database close error: ${err instanceof Error ? err.message : String(err)}` ) } + if (prevDb) invalidateEmbeddedChunksCache(prevDb) sqlite = null db = null currentUserId = null @@ -631,6 +794,9 @@ export function importLocalModeData(): LocalImportResult | null { markDone() }) copy() + if (result.imported > 0 && db) { + invalidateEmbeddedChunksCache(db) + } logger.info(`Imported ${result.imported} local-mode row(s) into ${userId}: ${JSON.stringify(result.tables)}`) return result } finally { @@ -653,6 +819,8 @@ export function bindTestDatabase( testDb: BetterSQLite3Database, userId: string = LOCAL_USER_ID, ): void { + if (db) invalidateEmbeddedChunksCache(db) + invalidateEmbeddedChunksCache(testDb) db = testDb currentUserId = userId emitAccountScopeChanged(userId) @@ -660,6 +828,7 @@ export function bindTestDatabase( /** Vitest 전용: bindTestDatabase 해제. */ export function unbindTestDatabase(): void { + if (db) invalidateEmbeddedChunksCache(db) db = null currentUserId = null } diff --git a/apps/desktop/src/main/db/like-pattern.ts b/apps/desktop/src/main/db/like-pattern.ts index 70aec3c..900fa9c 100644 --- a/apps/desktop/src/main/db/like-pattern.ts +++ b/apps/desktop/src/main/db/like-pattern.ts @@ -5,13 +5,11 @@ // '100%' 는 '100' 이 들어간 모든 행과 일치했다. 메타문자를 이스케이프하고 ESCAPE 절을 붙인다. import { sql, type AnyColumn, type SQL } from 'drizzle-orm' +import { escapeLikePattern } from '@d3ro/core/guards' const LIKE_ESCAPE_CHAR = '\\' -/** LIKE 메타문자(%, _, 이스케이프 문자 자체)를 글자 그대로 찾도록 이스케이프한다. */ -export function escapeLikePattern(text: string): string { - return text.replace(/[\\%_]/g, (char) => `${LIKE_ESCAPE_CHAR}${char}`) -} +export { escapeLikePattern } export interface ContainsPattern { /** 바인딩될 LIKE 패턴 (`%…%`, 이스케이프됨) */ diff --git a/apps/desktop/src/main/db/schema.ts b/apps/desktop/src/main/db/schema.ts index 77a3371..9b8ec69 100644 --- a/apps/desktop/src/main/db/schema.ts +++ b/apps/desktop/src/main/db/schema.ts @@ -1,7 +1,7 @@ // src/main/db/schema.ts // 설계서 03의 drizzle-orm 스키마 정의 -import { sqliteTable, text, integer, real, index, uniqueIndex, primaryKey } from 'drizzle-orm/sqlite-core' +import { sqliteTable, text, integer, real, blob, index, uniqueIndex, primaryKey } from 'drizzle-orm/sqlite-core' // ── history ────────────────────────────────────────────── export const history = sqliteTable( @@ -141,8 +141,10 @@ export const ragChunks = sqliteTable( id: text('id').primaryKey(), documentId: text('document_id').notNull(), content: text('content').notNull(), - /** 임베딩 벡터 (JSON 직렬화 float[]) */ + /** 임베딩 벡터 (JSON 직렬화 float[] — 호환/동기화용) */ embedding: text('embedding').notNull(), + /** 임베딩 벡터 (Float32 리틀엔디언 바이너리 — 고속 무파싱 로드용) */ + embeddingBlob: blob('embedding_blob', { mode: 'buffer' }), chunkIndex: integer('chunk_index').notNull(), }, (table) => [ @@ -181,6 +183,7 @@ export const meetingSessions = sqliteTable( }, (table) => [ index('idx_meeting_sessions_created_at').on(table.createdAt), + index('idx_meeting_sessions_started_at').on(table.startedAt), index('idx_meeting_sessions_status').on(table.status), ] ) @@ -193,6 +196,7 @@ export const meetingMemos = sqliteTable( sessionId: text('session_id').notNull(), content: text('content').notNull(), timestampMs: integer('timestamp_ms').notNull(), + revision: integer('revision').notNull().default(1), createdAt: integer('created_at').notNull(), /** 모바일에서 수정한 메모를 커서로 가져오기 위한 수정 시각 (없으면 createdAt) */ updatedAt: integer('updated_at'), @@ -200,6 +204,7 @@ export const meetingMemos = sqliteTable( (table) => [ index('idx_meeting_memos_session_id').on(table.sessionId), index('idx_meeting_memos_timestamp').on(table.timestampMs), + index('idx_meeting_memos_created_at').on(table.createdAt), ] ) diff --git a/apps/desktop/src/main/ipc/audio-handlers.ts b/apps/desktop/src/main/ipc/audio-handlers.ts index f3ddb48..1faae3c 100644 --- a/apps/desktop/src/main/ipc/audio-handlers.ts +++ b/apps/desktop/src/main/ipc/audio-handlers.ts @@ -4,8 +4,8 @@ import { ipcMain } from 'electron' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors' import { getAudioCaptureService, calculateRMS, type CaptureLease } from '../services/AudioCaptureService' -import { getMainWindow } from '../windows/WindowManager' import { configGet, configSet } from '../services/ConfigService' +import { safeSendToRenderer } from './renderer-broadcast' import type { SetDeviceParams, TestDeviceParams } from '@d3ro/core/types' let testTimer: ReturnType | null = null @@ -44,6 +44,10 @@ async function stopAudioTest(): Promise { await lease?.release().catch(() => { /* ignore */ }) } +export async function disposeAudioHandlers(): Promise { + await stopAudioTest() +} + export function registerAudioHandlers(): void { ipcMain.handle(IPC_CHANNELS.AUDIO.GET_DEVICES, async () => { try { @@ -103,19 +107,13 @@ export function registerAudioHandlers(): void { // level 0은 "무음/초기화 중"일 뿐 종료가 아님 — 종료는 done:true로만 알린다. testLevelInterval = setInterval(() => { const level = testLastRms > 0 ? Math.min(1.0, Math.pow(testLastRms, 0.28)) : 0 - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level, done: false }) - } + safeSendToRenderer(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level, done: false }) }, 100) // durationMs(기본 5초) 후 자동 중지 testTimer = setTimeout(() => { void stopAudioTest() - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level: 0, done: true }) - } + safeSendToRenderer(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level: 0, done: true }) }, durationMs) return ipcSuccess({ averageLevel: 0, peakLevel: 0, hasAudio: true }) @@ -131,10 +129,7 @@ export function registerAudioHandlers(): void { // 테스트 수동 중지 (STOP 버튼) ipcMain.handle(IPC_CHANNELS.AUDIO.STOP_TEST, async () => { await stopAudioTest() - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level: 0, done: true }) - } + safeSendToRenderer(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level: 0, done: true }) return ipcSuccess(undefined) }) } diff --git a/apps/desktop/src/main/ipc/cloud-sync-handlers.ts b/apps/desktop/src/main/ipc/cloud-sync-handlers.ts index 334b9c7..80cae2f 100644 --- a/apps/desktop/src/main/ipc/cloud-sync-handlers.ts +++ b/apps/desktop/src/main/ipc/cloud-sync-handlers.ts @@ -1,13 +1,14 @@ // src/main/ipc/cloud-sync-handlers.ts // Phase V2-4: CloudSync IPC 핸들러 -import { ipcMain, BrowserWindow } from 'electron' +import { ipcMain } from 'electron' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' import { ipcSuccess, ipcError, ErrorCode, D3ROError } from '@d3ro/core/errors' import { getCloudSyncService } from '../services/CloudSyncService' import { getLogger } from '../services/LoggerService' import { onConfigChanged } from '../services/ConfigService' import { isApplyingRemoteSettings } from '../services/sync/settings-sync' +import { broadcastToAllWindows } from './renderer-broadcast' const logger = getLogger('cloud-sync-handlers') @@ -95,37 +96,28 @@ export function registerCloudSyncHandlers(): void { } }) - // 이벤트 → renderer 브로드캐스트 - function broadcast(channel: string, payload: unknown): void { - BrowserWindow.getAllWindows().forEach((win) => { - if (!win.isDestroyed()) { - win.webContents.send(channel, payload) - } - }) - } - sync.on('auth-changed', (payload) => { - broadcast(IPC_CHANNELS.CLOUD_SYNC.AUTH_CHANGED, payload) + broadcastToAllWindows(IPC_CHANNELS.CLOUD_SYNC.AUTH_CHANGED, payload) }) sync.on('sync-progress', (payload) => { - broadcast(IPC_CHANNELS.CLOUD_SYNC.SYNC_PROGRESS, payload) + broadcastToAllWindows(IPC_CHANNELS.CLOUD_SYNC.SYNC_PROGRESS, payload) }) sync.on('sync-complete', (payload) => { - broadcast(IPC_CHANNELS.CLOUD_SYNC.SYNC_COMPLETE, payload) + broadcastToAllWindows(IPC_CHANNELS.CLOUD_SYNC.SYNC_COMPLETE, payload) }) sync.on('sync-error', (payload) => { - broadcast(IPC_CHANNELS.CLOUD_SYNC.SYNC_ERROR, payload) + broadcastToAllWindows(IPC_CHANNELS.CLOUD_SYNC.SYNC_ERROR, payload) }) // 다른 기기의 변경이 반영되면 앱 공통 새로고침 신호로 알린다 (이력·사전·회의·명령 화면이 구독). // 동기화가 메인에서 바꾼 설정(언어·테마 등)을 화면에도 알린다 — IPC로 바꿀 때만 방송되던 경로. // (팝업 테마 등 키별 부수효과는 config-effects 레지스트리가 모든 경로에 한 번씩 적용한다) onConfigChanged((event) => { if (!isApplyingRemoteSettings()) return - broadcast(IPC_CHANNELS.CONFIG.CHANGED, event) + broadcastToAllWindows(IPC_CHANNELS.CONFIG.CHANGED, event) }) sync.on('data-changed', (payload) => { - broadcast(IPC_CHANNELS.APP.DATA_CHANGED, { type: 'cloud-sync', entities: payload.entities }) + broadcastToAllWindows(IPC_CHANNELS.APP.DATA_CHANGED, { type: 'cloud-sync', entities: payload.entities }) }) logger.info('Cloud Sync IPC handlers registered') diff --git a/apps/desktop/src/main/ipc/config-handlers.ts b/apps/desktop/src/main/ipc/config-handlers.ts index 91202ea..b71573b 100644 --- a/apps/desktop/src/main/ipc/config-handlers.ts +++ b/apps/desktop/src/main/ipc/config-handlers.ts @@ -1,15 +1,14 @@ // src/main/ipc/config-handlers.ts -import { ipcMain, BrowserWindow } from 'electron' +import { ipcMain } from 'electron' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors' import { configGet, configSet, configGetAll, configReset } from '../services/ConfigService' +import { broadcastToAllWindows } from './renderer-broadcast' /** 설정 변경 시 모든 렌더러에 broadcast */ function broadcastConfigChanged(key: string, value: unknown, previousValue?: unknown): void { - for (const win of BrowserWindow.getAllWindows()) { - win.webContents.send(IPC_CHANNELS.CONFIG.CHANGED, { key, value, previousValue }) - } + broadcastToAllWindows(IPC_CHANNELS.CONFIG.CHANGED, { key, value, previousValue }) } import type { ConfigGetParams, diff --git a/apps/desktop/src/main/ipc/keybinding-handlers.ts b/apps/desktop/src/main/ipc/keybinding-handlers.ts index 1830726..bef1e66 100644 --- a/apps/desktop/src/main/ipc/keybinding-handlers.ts +++ b/apps/desktop/src/main/ipc/keybinding-handlers.ts @@ -3,8 +3,9 @@ // 키바인딩 IPC. 액션을 파라미터로 받는 단일 채널 집합이며, // 검증·충돌 판정은 전부 `packages/core/src/keybinding.ts` 의 함수를 쓴다. -import { ipcMain, BrowserWindow } from 'electron' +import { ipcMain } from 'electron' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' +import { broadcastToAllWindows } from './renderer-broadcast' import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors' import { bindingKey, @@ -37,9 +38,7 @@ import type { } from '@d3ro/core/types' function broadcast(channel: string, payload: unknown): void { - for (const win of BrowserWindow.getAllWindows()) { - win.webContents.send(channel, payload) - } + broadcastToAllWindows(channel, payload) } /** 바인딩 맵 변경을 모든 창에 알린다 (창 간 동기화). */ diff --git a/apps/desktop/src/main/ipc/license-handlers.ts b/apps/desktop/src/main/ipc/license-handlers.ts index 9c5c33e..2905d3b 100644 --- a/apps/desktop/src/main/ipc/license-handlers.ts +++ b/apps/desktop/src/main/ipc/license-handlers.ts @@ -1,7 +1,7 @@ // src/main/ipc/license-handlers.ts // Phase 11: 라이센스 IPC 핸들러 -import { app, ipcMain, BrowserWindow } from 'electron' +import { app, ipcMain } from 'electron' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors' import { getLicenseService } from '../services/LicenseService' @@ -13,22 +13,19 @@ import type { import { Feature } from '@d3ro/core/types' import { billingUrl, PUBLIC_SITE_ORIGIN } from '@d3ro/core/web-urls' import { openExternalSafe } from '../windows/web-contents-hardening' +import { broadcastToAllWindows } from './renderer-broadcast' /** 개발 빌드는 로컬 웹앱(`npm run dev --workspace=@d3ro/web`)의 결제 페이지를 연다. */ const DEV_WEB_ORIGIN = 'http://localhost:3000' /** 업그레이드 유도 이벤트를 모든 렌더러에 broadcast */ function broadcastUpgradePrompt(event: UpgradePromptEvent): void { - for (const win of BrowserWindow.getAllWindows()) { - win.webContents.send(IPC_CHANNELS.LICENSE.UPGRADE_PROMPT, event) - } + broadcastToAllWindows(IPC_CHANNELS.LICENSE.UPGRADE_PROMPT, event) } /** 티어 변경을 모든 렌더러에 broadcast */ function broadcastTierChanged(info: LicenseInfo): void { - for (const win of BrowserWindow.getAllWindows()) { - win.webContents.send(IPC_CHANNELS.LICENSE.TIER_CHANGED, info) - } + broadcastToAllWindows(IPC_CHANNELS.LICENSE.TIER_CHANGED, info) } export function registerLicenseHandlers(): void { diff --git a/apps/desktop/src/main/ipc/llm-handlers.ts b/apps/desktop/src/main/ipc/llm-handlers.ts index 862f2ef..0268a88 100644 --- a/apps/desktop/src/main/ipc/llm-handlers.ts +++ b/apps/desktop/src/main/ipc/llm-handlers.ts @@ -10,7 +10,7 @@ import { getLlmGateway } from '../services/llm/LlmGateway' import { configGet, configSet } from '../services/ConfigService' import { buildInstructionInvocation, resolveTargetLanguage } from '../services/llm-prompts' import { normalizeLoopbackUrl } from '../utils/loopback' -import { getMainWindow } from '../windows/WindowManager' +import { safeSendToRenderer } from './renderer-broadcast' import type { SetLLMModelParams, SetServerUrlParams, @@ -18,13 +18,6 @@ import type { PullModelParams } from '@d3ro/core/types' -function safeSendToRenderer(channel: string, data: unknown): void { - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send(channel, data) - } -} - export function registerLLMHandlers(): void { const localLlm = getLocalLLMService() localLlm.on('availability-changed', () => { diff --git a/apps/desktop/src/main/ipc/renderer-broadcast.ts b/apps/desktop/src/main/ipc/renderer-broadcast.ts new file mode 100644 index 0000000..09a88bd --- /dev/null +++ b/apps/desktop/src/main/ipc/renderer-broadcast.ts @@ -0,0 +1,29 @@ +// src/main/ipc/renderer-broadcast.ts +// 메인/전체 렌더러 창으로 안전하게 IPC 이벤트를 송신하는 공용 헬퍼. + +import { BrowserWindow } from 'electron' +import { getMainWindow } from '../windows/WindowManager' + +function canSendToWindow(win: BrowserWindow | null | undefined): win is BrowserWindow { + if (!win || win.isDestroyed()) return false + const contents = win.webContents as { isDestroyed?: () => boolean } | undefined + if (!contents) return false + return typeof contents.isDestroyed === 'function' ? !contents.isDestroyed() : true +} + +/** 메인 창이 살아 있을 때만 IPC 채널로 데이터를 전송한다. */ +export function safeSendToRenderer(channel: string, data: unknown): void { + const win = getMainWindow() + if (canSendToWindow(win)) { + win.webContents.send(channel, data) + } +} + +/** 파괴되지 않은 모든 BrowserWindow 렌더러에 IPC 이벤트를 브로드캐스트한다. */ +export function broadcastToAllWindows(channel: string, payload: unknown): void { + for (const win of BrowserWindow.getAllWindows()) { + if (canSendToWindow(win)) { + win.webContents.send(channel, payload) + } + } +} diff --git a/apps/desktop/src/main/ipc/stt-handlers.ts b/apps/desktop/src/main/ipc/stt-handlers.ts index 443f277..6e8b861 100644 --- a/apps/desktop/src/main/ipc/stt-handlers.ts +++ b/apps/desktop/src/main/ipc/stt-handlers.ts @@ -10,7 +10,7 @@ import type { RuntimeComponent } from '../services/RuntimeProvisioner' import { parseRuntimeEnsureRequest } from './runtime-ensure-request' import { getSTTManager } from '../services/stt/STTManager' import { configGet, configSet } from '../services/ConfigService' -import { getMainWindow } from '../windows/WindowManager' +import { safeSendToRenderer } from './renderer-broadcast' import type { SetSTTModelParams, SetSTTLanguageParams, @@ -21,13 +21,6 @@ import type { STTProviderType, } from '@d3ro/core/types' -function safeSendToRenderer(channel: string, data: unknown): void { - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send(channel, data) - } -} - /** * 던져진 오류를 IPC 오류로 바꾼다. D3ROError 면 그 코드를 보존하고, 아니면 fallback 코드를 쓴다. * (예전 런타임 핸들러는 `ipcError(error, code)` 로 인자 순서가 뒤바뀌어 code 자리에 Error 객체가, diff --git a/apps/desktop/src/main/ipc/support-handlers.ts b/apps/desktop/src/main/ipc/support-handlers.ts index 48f232c..2376552 100644 --- a/apps/desktop/src/main/ipc/support-handlers.ts +++ b/apps/desktop/src/main/ipc/support-handlers.ts @@ -5,6 +5,7 @@ import { app, ipcMain } from 'electron' import os from 'os' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' import { ok } from '@d3ro/core/errors' +import { redactPII } from '@d3ro/core/utils/pii-redactor' import type { SystemDiagnosticsPayload, AIAssistQuery, @@ -88,6 +89,16 @@ export function registerSupportHandlers(): void { }, ) => { const now = Date.now() + const rawDiagnostics = ticketData.diagnostics ?? ticketData.diagnosticsSnapshot + const sanitizedDiagnostics: SystemDiagnosticsPayload | undefined = rawDiagnostics + ? { + ...rawDiagnostics, + recentErrors: (rawDiagnostics.recentErrors ?? []).map((entry) => ({ + ...entry, + message: redactPII(entry.message, 'mask').redactedText, + })), + } + : undefined const newTicket: SupportTicket = { id: `tkt_${now}`, userId: 'user_local', @@ -96,9 +107,9 @@ export function registerSupportHandlers(): void { category: ticketData.category || 'general', priority: ticketData.priority || 'normal', status: 'open', - subject: ticketData.subject || '고객 지원 문의', - description: ticketData.description || '', - diagnostics: ticketData.diagnostics ?? ticketData.diagnosticsSnapshot, + subject: redactPII(ticketData.subject || '고객 지원 문의', 'mask').redactedText, + description: redactPII(ticketData.description || '', 'mask').redactedText, + diagnostics: sanitizedDiagnostics, slaDueAt: ticketData.slaDueAt ?? now + 24 * 60 * 60 * 1000, createdAt: now, updatedAt: now, diff --git a/apps/desktop/src/main/ipc/voice-handlers.ts b/apps/desktop/src/main/ipc/voice-handlers.ts index 30ad9ba..f2aa665 100644 --- a/apps/desktop/src/main/ipc/voice-handlers.ts +++ b/apps/desktop/src/main/ipc/voice-handlers.ts @@ -4,16 +4,9 @@ import { ipcMain } from 'electron' import { IPC_CHANNELS } from '@d3ro/core/ipc-channels' import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors' import { getVoiceModeService } from '../services/VoiceModeService' -import { getMainWindow } from '../windows/WindowManager' +import { safeSendToRenderer } from './renderer-broadcast' import type { StartRecordingParams, StopRecordingParams, CancelRecordingParams, SetVoiceModeParams, VoiceErrorEvent } from '@d3ro/core/types' -function safeSendToRenderer(channel: string, data: unknown): void { - const win = getMainWindow() - if (win && !win.isDestroyed()) { - win.webContents.send(channel, data) - } -} - /** 두 IPC 전송 경로(invoke/send)가 공유하는 단일 취소 동작 */ function cancelVoiceSession(): void { getVoiceModeService().cancelSession() diff --git a/apps/desktop/src/main/services/AudioCaptureService.ts b/apps/desktop/src/main/services/AudioCaptureService.ts index 828ff93..e1cfc91 100644 --- a/apps/desktop/src/main/services/AudioCaptureService.ts +++ b/apps/desktop/src/main/services/AudioCaptureService.ts @@ -12,6 +12,7 @@ import { getSoxPath } from '../utils/paths' import type { AudioDevice } from '@d3ro/core/types' import { AUDIO_FORMAT, TIMING } from '@d3ro/core/constants' import { D3ROError, ErrorCode } from '@d3ro/core/errors' +import { secureWipeAudioChunks, secureZeroBuffer } from '@d3ro/core/utils/secure-memory' const logger = getLogger('AudioCaptureService') @@ -522,15 +523,22 @@ class AudioCaptureService extends EventEmitter { if (rms > peakRms) peakRms = rms }) - proc.on('error', (err) => { - reject(new D3ROError(ErrorCode.AudioCaptureStartFailed, `SoX 실행 실패: ${err.message}`)) - }) - - setTimeout(() => { + let settled = false + const durationTimer = setTimeout(() => { proc.kill() }, durationMs) + proc.on('error', (err) => { + if (settled) return + settled = true + clearTimeout(durationTimer) + reject(new D3ROError(ErrorCode.AudioCaptureStartFailed, `SoX 실행 실패: ${err.message}`)) + }) + proc.on('close', () => { + if (settled) return + settled = true + clearTimeout(durationTimer) if (buffers.length === 0) { resolve({ averageLevel: 0, peakLevel: 0, hasAudio: false }) return @@ -645,8 +653,9 @@ class AudioCaptureService extends EventEmitter { } } + secureZeroBuffer(this._residualBuffer) + secureWipeAudioChunks(this._levelAccumulator) this._residualBuffer = Buffer.alloc(0) - this._levelAccumulator = [] } // EventEmitter 타입 오버라이드 diff --git a/apps/desktop/src/main/services/InputTelemetryService.ts b/apps/desktop/src/main/services/InputTelemetryService.ts index 3a24e4b..56685fc 100644 --- a/apps/desktop/src/main/services/InputTelemetryService.ts +++ b/apps/desktop/src/main/services/InputTelemetryService.ts @@ -380,24 +380,16 @@ class InputTelemetryService extends EventEmitter { this._onKeyUp = (e: UiohookKeyboardEvent) => this._handleKeyUp(e) this._onMouseDown = (e: UiohookMouseEvent) => this._handleMouseDown(e) this._onMouseUp = (e: UiohookMouseEvent) => this._handleMouseUp(e) - this._onMouseMove = (e: UiohookMouseEvent) => this._handleMouseMove(e) - this._onWheel = (e: UiohookWheelEvent) => this._handleWheel(e) uIOhook.on('keydown', this._onKeyDown) uIOhook.on('keyup', this._onKeyUp) uIOhook.on('mousedown', this._onMouseDown) uIOhook.on('mouseup', this._onMouseUp) - uIOhook.on('mousemove', this._onMouseMove) - uIOhook.on('wheel', this._onWheel) this._releaseHook = acquireGlobalInputHook() this._running = true this._inputRevision += 1 - this._flushTimer = setInterval( - () => this._flush(), - INPUT_TELEMETRY_DEFAULTS.flushIntervalMs - ) - this._flushTimer.unref?.() + this._syncCollectionMode() // 주기 샘플러. // @@ -411,9 +403,6 @@ class InputTelemetryService extends EventEmitter { ) this._sampleTimer.unref?.() - if (this._isTelemetryCollectionEnabled()) { - this._pruneOldData() - } logger.info( this._isTelemetryCollectionEnabled() ? '입력 텔레메트리 시작 (키/마우스 집계)' @@ -476,9 +465,52 @@ class InputTelemetryService extends EventEmitter { const shouldRun = this._isEnabledByConfig() if (shouldRun && !this._running) this.start() else if (!shouldRun && this._running) this.stop() + else if (this._running) this._syncCollectionMode() this._emitState() } + /** + * 입력 텔레메트리 수집 동의가 켜진 동안에만 고빈도 마우스(mousemove 1,000Hz / wheel) 훅과 + * 5초 DB 플러시 타이머를 가동한다. 기본 모드(오타 교정·제안만 활성)에서는 N-API 호출 폭풍을 원천 차단한다. + */ + private _syncCollectionMode(): void { + if (this._running && this._isTelemetryCollectionEnabled()) { + if (!this._onMouseMove) { + this._onMouseMove = (e: UiohookMouseEvent) => this._handleMouseMove(e) + uIOhook.on('mousemove', this._onMouseMove) + } + if (!this._onWheel) { + this._onWheel = (e: UiohookWheelEvent) => this._handleWheel(e) + uIOhook.on('wheel', this._onWheel) + } + if (!this._flushTimer) { + this._flushTimer = setInterval( + () => this._flush(), + INPUT_TELEMETRY_DEFAULTS.flushIntervalMs + ) + this._flushTimer.unref?.() + } + if (this._prunedAt === 0) { + this._pruneOldData() + } + return + } + + if (this._onMouseMove) { + uIOhook.removeListener('mousemove', this._onMouseMove) + this._onMouseMove = null + } + if (this._onWheel) { + uIOhook.removeListener('wheel', this._onWheel) + this._onWheel = null + } + if (this._flushTimer) { + clearInterval(this._flushTimer) + this._flushTimer = null + } + this._pending.clear() + } + dispose(): void { this.stop() this._recentWrites.clear() @@ -579,11 +611,6 @@ class InputTelemetryService extends EventEmitter { // 실제 키 입력은 화면을 바꾼다 — 이전 UIA 응답은 무효다. this._inputRevision += 1 this._registerInput(true) - const bucket = this._bucket() - // 한글·일본어 IME 가 켜져 있으면 Windows 는 글자 키를 VK_PROCESSKEY 로 넘기고, uiohook 은 그것을 - // 변환표에 없는 키코드로 보낸다 — 그대로 'other' 로 두면 한글 타이핑 전체가 "타이핑 아님" 이 되어 - // 제안이 영영 뜨지 않았다(2026-10-03 실측: 글자 키가 전부 key=other). 수정자 없이 눌린 미지의 - // 키는 IME 조합 키로 본다. 실제 텍스트 변화(editedSinceFocus)가 함께 있어야 제안이 열린다. const keyClass = vk === null ? this._modifiers.ctrl || this._modifiers.alt || this._modifiers.meta @@ -591,9 +618,12 @@ class InputTelemetryService extends EventEmitter { : 'ime' : classifyKeyStroke(vk, this._modifiers) - if (keyClass === 'shortcut') bucket.shortcuts += 1 - else bucket.keystrokes += 1 - if (keyClass === 'backspace') bucket.backspaces += 1 + if (this._isTelemetryCollectionEnabled()) { + const bucket = this._bucket() + if (keyClass === 'shortcut') bucket.shortcuts += 1 + else bucket.keystrokes += 1 + if (keyClass === 'backspace') bucket.backspaces += 1 + } this._lastKeyAt = Date.now() this._lastKeyClass = keyClass @@ -650,9 +680,11 @@ class InputTelemetryService extends EventEmitter { this._lastClickPos !== null && manhattanDistance(this._lastClickPos, position) < 6 - const bucket = this._bucket() - if (isDoubleClick) bucket.doubleClicks += 1 - else bucket.clicks += 1 + if (this._isTelemetryCollectionEnabled()) { + const bucket = this._bucket() + if (isDoubleClick) bucket.doubleClicks += 1 + else bucket.clicks += 1 + } this._lastClickAt = now this._lastClickButton = button @@ -706,10 +738,12 @@ class InputTelemetryService extends EventEmitter { const now = Date.now() const gap = this._lastEventAt === 0 ? 0 : now - this._lastEventAt - if (gap > 0 && gap <= INPUT_TELEMETRY_DEFAULTS.activeIdleTimeoutMs) { - this._bucket().activeMs += gap - } else if (isKeyboard && this._lastActiveTickAt > 0) { - this._bucket().activeMs += 250 + if (this._isTelemetryCollectionEnabled()) { + if (gap > 0 && gap <= INPUT_TELEMETRY_DEFAULTS.activeIdleTimeoutMs) { + this._bucket().activeMs += gap + } else if (isKeyboard && this._lastActiveTickAt > 0) { + this._bucket().activeMs += 250 + } } if (isKeyboard) this._lastActiveTickAt = now @@ -1240,10 +1274,12 @@ class InputTelemetryService extends EventEmitter { return } - const bucket = this._bucket() - bucket.chars += delta.insertedChars - bucket.words += delta.insertedWords - bucket.sentences += delta.insertedSentences + if (this._isTelemetryCollectionEnabled()) { + const bucket = this._bucket() + bucket.chars += delta.insertedChars + bucket.words += delta.insertedWords + bucket.sentences += delta.insertedSentences + } if (!delta.insertedText) return const typedText = this._withoutExpectedInsert(delta.insertedText) @@ -1493,41 +1529,43 @@ class InputTelemetryService extends EventEmitter { try { const db = getDatabase() - for (const [key, bucket] of entries) { - const [date, hourRaw, appName] = key.split('|') - const hour = Number(hourRaw) - if (!date || Number.isNaN(hour)) continue + db.transaction((tx) => { + for (const [key, bucket] of entries) { + const [date, hourRaw, appName] = key.split('|') + const hour = Number(hourRaw) + if (!date || Number.isNaN(hour)) continue - mergeActivityBucket(this._sessionTotals, bucket) + mergeActivityBucket(this._sessionTotals, bucket) - db.insert(inputActivity) - .values({ - id: crypto.randomUUID(), - date, - hour, - appName: appName ?? '', - ...bucket, - updatedAt: now - }) - .onConflictDoUpdate({ - target: [inputActivity.date, inputActivity.hour, inputActivity.appName], - set: { - keystrokes: sql`${inputActivity.keystrokes} + ${bucket.keystrokes}`, - shortcuts: sql`${inputActivity.shortcuts} + ${bucket.shortcuts}`, - backspaces: sql`${inputActivity.backspaces} + ${bucket.backspaces}`, - clicks: sql`${inputActivity.clicks} + ${bucket.clicks}`, - doubleClicks: sql`${inputActivity.doubleClicks} + ${bucket.doubleClicks}`, - scrollTicks: sql`${inputActivity.scrollTicks} + ${bucket.scrollTicks}`, - mouseDistancePx: sql`${inputActivity.mouseDistancePx} + ${bucket.mouseDistancePx}`, - chars: sql`${inputActivity.chars} + ${bucket.chars}`, - words: sql`${inputActivity.words} + ${bucket.words}`, - sentences: sql`${inputActivity.sentences} + ${bucket.sentences}`, - activeMs: sql`${inputActivity.activeMs} + ${bucket.activeMs}`, + tx.insert(inputActivity) + .values({ + id: crypto.randomUUID(), + date, + hour, + appName: appName ?? '', + ...bucket, updatedAt: now - } - }) - .run() - } + }) + .onConflictDoUpdate({ + target: [inputActivity.date, inputActivity.hour, inputActivity.appName], + set: { + keystrokes: sql`${inputActivity.keystrokes} + ${bucket.keystrokes}`, + shortcuts: sql`${inputActivity.shortcuts} + ${bucket.shortcuts}`, + backspaces: sql`${inputActivity.backspaces} + ${bucket.backspaces}`, + clicks: sql`${inputActivity.clicks} + ${bucket.clicks}`, + doubleClicks: sql`${inputActivity.doubleClicks} + ${bucket.doubleClicks}`, + scrollTicks: sql`${inputActivity.scrollTicks} + ${bucket.scrollTicks}`, + mouseDistancePx: sql`${inputActivity.mouseDistancePx} + ${bucket.mouseDistancePx}`, + chars: sql`${inputActivity.chars} + ${bucket.chars}`, + words: sql`${inputActivity.words} + ${bucket.words}`, + sentences: sql`${inputActivity.sentences} + ${bucket.sentences}`, + activeMs: sql`${inputActivity.activeMs} + ${bucket.activeMs}`, + updatedAt: now + } + }) + .run() + } + }) this.emit('activity', { totals: { ...this._sessionTotals }, appName: this._foreground.appName diff --git a/apps/desktop/src/main/services/LocalLLMService.ts b/apps/desktop/src/main/services/LocalLLMService.ts index cb72289..ef0ce6d 100644 --- a/apps/desktop/src/main/services/LocalLLMService.ts +++ b/apps/desktop/src/main/services/LocalLLMService.ts @@ -185,6 +185,7 @@ class LocalLLMService extends EventEmitter { private _serverVersion: string | null = null private _activeRequests = new Set() private _ensureRunningPromise: Promise<'running' | 'starting' | 'not-installed' | 'failed'> | null = null + private _startCheckTimers = new Set>() private _disposed = false get state(): LLMState { @@ -200,10 +201,17 @@ class LocalLLMService extends EventEmitter { */ async startServer(): Promise<'running' | 'starting' | 'not-installed' | 'failed'> { const result = await this.ensureRunning() - if (result === 'starting' || result === 'running') { - // 1초 뒤 빠른 재확인 - setTimeout(() => this._checkAvailability(), 1000) - setTimeout(() => this._checkAvailability(), 3000) + if ((result === 'starting' || result === 'running') && !this._disposed) { + // 1초·3초 뒤 빠른 재확인 (dispose 시 정리될 수 있도록 핸들을 추적한다) + for (const delayMs of [1000, 3000]) { + const timer = setTimeout(() => { + this._startCheckTimers.delete(timer) + if (!this._disposed) { + void this._checkAvailability() + } + }, delayMs) + this._startCheckTimers.add(timer) + } } return result } @@ -977,6 +985,10 @@ class LocalLLMService extends EventEmitter { dispose(): void { this._disposed = true + for (const timer of this._startCheckTimers) { + clearTimeout(timer) + } + this._startCheckTimers.clear() this.stopPolling() this.cancelGeneration() this._refreshState() diff --git a/apps/desktop/src/main/services/LocalSTTService.ts b/apps/desktop/src/main/services/LocalSTTService.ts index fe96146..b4aa32e 100644 --- a/apps/desktop/src/main/services/LocalSTTService.ts +++ b/apps/desktop/src/main/services/LocalSTTService.ts @@ -128,6 +128,8 @@ const SIDECAR_REQUEST_TIMEOUT_MS = 120000 const SIDECAR_TRANSCRIBE_MS_PER_AUDIO_SECOND = 3000 /** 부분 전사(미리보기) 타임아웃 — 실패해도 무시되므로 짧게 잡는다 */ const SIDECAR_PARTIAL_TIMEOUT_MS = 15000 +/** 장시간 받아쓰기가 없을 때 Whisper 기본 모델(1.6~3.1GB)만 내려 RAM/VRAM 을 돌려주는 유휴 한도(15분). */ +const IDLE_MODEL_UNLOAD_MS = 15 * 60_000 /** 알려진 Whisper 모델 카탈로그 */ const MODEL_CATALOG: STTModel[] = [ @@ -240,6 +242,7 @@ class LocalSTTService extends EventEmitter { private _initializing: { modelId: string; promise: Promise } | null = null // errorEmitted 플래그로 이벤트 중복 방지 private _errorEmitted: boolean = false + private _idleUnloadTimer: NodeJS.Timeout | null = null // ── 상태 접근자 ── @@ -256,6 +259,11 @@ class LocalSTTService extends EventEmitter { return this._supervisor.baseUrl } + /** 실행 중인 sidecar HTTP 기본 URL (기동되지 않았으면 null) */ + get sidecarBaseUrl(): string | null { + return this._supervisor.isHealthy ? this._supervisor.baseUrl : null + } + // ── 공개 메서드 ── /** @@ -302,6 +310,7 @@ class LocalSTTService extends EventEmitter { } private async _loadInitial(targetModel: string): Promise { + this._clearIdleUnload() this._setState(STTState.Loading) this._errorEmitted = false @@ -316,6 +325,7 @@ class LocalSTTService extends EventEmitter { this._setState(STTState.Ready) // 모델까지 올라갔으면 사이드카는 안정적이다 — 크래시 재시작 카운트 초기화 this._supervisor.markStable() + this._scheduleIdleUnload() logger.info(`STT 초기화 완료: 모델=${targetModel}`) } catch (err) { @@ -626,6 +636,7 @@ class LocalSTTService extends EventEmitter { logger.info('LocalSTTService dispose 시작') + this._clearIdleUnload() this._initializing = null this._modelReady = false this._auxModelId = null @@ -636,6 +647,60 @@ class LocalSTTService extends EventEmitter { logger.info('LocalSTTService dispose 완료') } + private _clearIdleUnload(): void { + if (this._idleUnloadTimer) { + clearTimeout(this._idleUnloadTimer) + this._idleUnloadTimer = null + } + } + + private _scheduleIdleUnload(): void { + this._clearIdleUnload() + if (this._disposed || !this._modelReady) return + this._idleUnloadTimer = setTimeout(() => { + this._idleUnloadTimer = null + void this.releasePrimaryModel() + }, IDLE_MODEL_UNLOAD_MS) + this._idleUnloadTimer.unref?.() + } + + /** + * 기본(primary) Whisper 모델만 메모리에서 내리고 사이드카 HTTP 프로세스(UIA 브리지)는 유지한다. + * 클라우드 STT 전환이나 장시간 유휴 시 1.6~3.1GB RAM/VRAM 을 즉시 회수하며, + * 다음 로컬 전사 요청이 들어오면 transcribe() 가 다시 자동으로 모델을 올린다. + */ + async releasePrimaryModel(): Promise { + this._clearIdleUnload() + if (this._disposed || (!this._currentModelId && !this._modelReady)) return + if (this._state === STTState.Transcribing || this._initializing) { + this._scheduleIdleUnload() + return + } + + const modelId = this._currentModelId + this._modelReady = false + this._currentModelId = null + this._setState(STTState.Uninitialized) + + if (!this._supervisor.isHealthy) return + try { + const response = await fetch(`${this._baseUrl}/unload`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ slot: 'primary' }), + signal: AbortSignal.timeout(SIDECAR_REQUEST_TIMEOUT_MS), + }) + await response.body?.cancel() + if (response.ok) { + logger.info(`기본 STT 모델 언로드: ${modelId ?? 'unknown'}`) + } + } catch (error) { + logger.debug( + `기본 STT 모델 언로드 통신 무시: ${error instanceof Error ? error.message : String(error)}`, + ) + } + } + private _emitDownloadProgress( modelId: string, percent: number, @@ -738,6 +803,7 @@ class LocalSTTService extends EventEmitter { } const isPartial = options?.partial === true + this._clearIdleUnload() if (!isPartial) { this._setState(STTState.Transcribing) @@ -857,6 +923,10 @@ class LocalSTTService extends EventEmitter { ErrorCode.STTTranscriptionFailed, `전사 실패: ${message}`, ) + } finally { + if (this._modelReady) { + this._scheduleIdleUnload() + } } } @@ -864,6 +934,7 @@ class LocalSTTService extends EventEmitter { /** 사이드카가 죽으면 올려 둔 모델도 함께 사라진다 */ private _onSidecarExit(): void { + this._clearIdleUnload() this._modelReady = false this._auxModelId = null } diff --git a/apps/desktop/src/main/services/MeetingModeService.ts b/apps/desktop/src/main/services/MeetingModeService.ts index 0e37717..f9f45c6 100644 --- a/apps/desktop/src/main/services/MeetingModeService.ts +++ b/apps/desktop/src/main/services/MeetingModeService.ts @@ -14,7 +14,10 @@ import { getMainWindow } from '../windows/WindowManager' import { getDatabase } from '../db' import { onAccountScopeChanged } from './account-scope' import { getLlmGateway } from './llm/LlmGateway' +import { getLocalSTTService } from './LocalSTTService' import { MeetingRecordingSession, type RecordingSnapshot } from './meeting/MeetingRecordingSession' +import { DiskWavAudioSink, writeWavHeader16kMonoPcm16 } from './meeting/disk-wav-audio-sink' +import { getSidecarBaseUrl } from '../utils/paths' import { isRecoverableMeeting, syncStateRecordingLedger, @@ -51,6 +54,7 @@ import { applySpeakerLabels, buildTranscriptFromSegments, chunkTranscriptByLines, + formatPyannoteSpeakerLabel, formatTranscriptLines, looksTruncatedRewrite, parseTranscriptLines, @@ -389,6 +393,10 @@ class MeetingModeService extends EventEmitter { return () => { audioCaptureService.off('audio-data', handler) } }, }, + audioSink: new DiskWavAudioSink(meetingAudioFilePathSync(sessionId)), + onAudioSinkError: (err) => { + logger.warn(`회의 오디오 디스크 스트리밍 실패: ${err instanceof Error ? err.message : String(err)}`) + }, onSegment: (segment) => { this.emit('segment', segment) this._sendToRenderer(IPC_CHANNELS.MEETING_MODE.SEGMENT, segment) @@ -747,7 +755,11 @@ class MeetingModeService extends EventEmitter { this._captionFailures.delete(snapshot.id) this._clearLocalRecording(snapshot.id) - if (snapshot.pcm.length > 0) { + if (snapshot.audioSavedToDisk) { + const wavPath = meetingAudioFilePathSync(snapshot.id) + getCloudSyncService().pushOne('meeting_audio', snapshot.id) + logger.info(`회의 오디오 저장(디스크 스트리밍): ${wavPath} (${snapshot.pcmByteLength}B)`) + } else if (snapshot.pcm.length > 0) { try { const wavPath = meetingAudioFilePathSync(snapshot.id) fs.mkdirSync(pathDirname(wavPath), { recursive: true }) @@ -999,27 +1011,7 @@ class MeetingModeService extends EventEmitter { /** PCM16 버퍼를 WAV 파일로 저장 (16kHz mono 16-bit) */ private _saveWav(filePath: string, pcmBuffer: Buffer): void { - const sampleRate = 16000 - const numChannels = 1 - const bitsPerSample = 16 - const byteRate = sampleRate * numChannels * (bitsPerSample / 8) - const blockAlign = numChannels * (bitsPerSample / 8) - const dataSize = pcmBuffer.length - - const header = Buffer.alloc(44) - header.write('RIFF', 0) - header.writeUInt32LE(36 + dataSize, 4) - header.write('WAVE', 8) - header.write('fmt ', 12) - header.writeUInt32LE(16, 16) // fmt chunk size - header.writeUInt16LE(1, 20) // PCM - header.writeUInt16LE(numChannels, 22) - header.writeUInt32LE(sampleRate, 24) - header.writeUInt32LE(byteRate, 28) - header.writeUInt16LE(blockAlign, 32) - header.writeUInt16LE(bitsPerSample, 34) - header.write('data', 36) - header.writeUInt32LE(dataSize, 40) + const header = writeWavHeader16kMonoPcm16(Buffer.alloc(44), pcmBuffer.length) // 헤더와 PCM 을 이어 붙이지 않고 따로 쓴다 — 3시간 회의면 concat 사본만 350MB 가 더 생긴다 const fd = fs.openSync(filePath, 'w') @@ -1488,8 +1480,11 @@ class MeetingModeService extends EventEmitter { maxTokens: REWRITE_CHUNK_MAX_TOKENS, }) const rawText = carry ? stripEchoedContext(result.text, previousTail) : result.text.trim() - // 모델이 원문에 없던 시각·화자 표기를 붙였으면 지우고, 지운 한정 부사(거의 등)는 되돌린다. - const text = restoreProtectedQualifiers(chunk, stripInventedMarkers(chunk, rawText)) + // 교열(!carry)에서는 모델이 원문에 없던 시각·화자 표기를 붙였으면 지우고, 화자 구분(carry)에서는 화자 표기를 허용한다. + const text = restoreProtectedQualifiers( + chunk, + stripInventedMarkers(chunk, rawText, { allowSpeakerMarkers: carry }), + ) if (looksTruncatedRewrite(chunk, text)) { throw new D3ROError( failureCode, @@ -1641,7 +1636,7 @@ ${excerpt.text}` try { const audioBuffer = fs.readFileSync(audioPath) - const serverUrl = `http://127.0.0.1:18765` + const serverUrl = getLocalSTTService().sidecarBaseUrl ?? getSidecarBaseUrl(18765) const formData = new FormData() formData.append('audio', new Blob([audioBuffer]), 'audio.wav') @@ -1675,7 +1670,7 @@ ${excerpt.text}` const labeledLines = applySpeakerLabels( parseTranscriptLines(transcript), diarResult.segments, - (raw) => raw.replace('SPEAKER_', '화자 '), + (raw) => formatPyannoteSpeakerLabel(raw), ) this._sendToRenderer(IPC_CHANNELS.MEETING_MODE.DIARIZATION_PROGRESS, { sessionId, percent: 85 }) diff --git a/apps/desktop/src/main/services/OnlineLLMService.ts b/apps/desktop/src/main/services/OnlineLLMService.ts index 911fb19..ad8924c 100644 --- a/apps/desktop/src/main/services/OnlineLLMService.ts +++ b/apps/desktop/src/main/services/OnlineLLMService.ts @@ -7,6 +7,7 @@ import { configGet, configSet } from './ConfigService' import { normalizeLoopbackUrl } from '../utils/loopback' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import type { LLMAction } from '@d3ro/core/types' +import { redactPII, redactPIIMessages, rehydrateText } from '@d3ro/core/utils/pii-redactor' import { resolveSystemPrompt } from './llm-prompts' interface OnlineGenerateResponse { @@ -41,35 +42,38 @@ class OnlineLLMService extends EventEmitter { return token } - async processText( - text: string, - action: LLMAction, - targetLanguage?: string, - customPrompt?: string + private async _postOnlineRequest( + endpoint: string, + payload: Record, + externalSignal?: AbortSignal ): Promise { const token = this._ensureAuth() const apiUrl = normalizeLoopbackUrl(configGet('onlineApiUrl') ?? 'http://127.0.0.1:5000') - const systemPrompt = resolveSystemPrompt(action, targetLanguage, customPrompt) // cancelGeneration() 이 실제로 이 요청을 끊도록 컨트롤러를 등록한다(예전엔 한 번도 할당되지 않아 no-op). this._abortController?.abort() const controller = new AbortController() this._abortController = controller + const onExternalAbort = (): void => { + controller.abort() + } + if (externalSignal) { + if (externalSignal.aborted) { + controller.abort() + } else { + externalSignal.addEventListener('abort', onExternalAbort, { once: true }) + } + } + try { - const response = await fetch(`${apiUrl}/api/llm/generate`, { + const response = await fetch(`${apiUrl}${endpoint}`, { signal: controller.signal, method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, - body: JSON.stringify({ - prompt: text, - systemPrompt, - model: configGet('llmModelId') ?? 'd3ro-gpt4o-mini', - temperature: 0.7, - maxTokens: 2048 - }) + body: JSON.stringify(payload) }) if (response.status === 401) { @@ -87,11 +91,11 @@ class OnlineLLMService extends EventEmitter { ) } - const data = (await response.json()) as OnlineGenerateResponse - if (!data.text || !data.text.trim()) { + const data = (await response.json()) as Partial | null + if (typeof data?.text !== 'string' || data.text.trim().length === 0) { throw new D3ROError(ErrorCode.LLMProcessingFailed, 'Online LLM returned empty text') } - return data.text.trim() + return data.text } catch (err) { if (err instanceof D3ROError) throw err if (controller.signal.aborted) { @@ -102,37 +106,48 @@ class OnlineLLMService extends EventEmitter { `온라인 API 서버 연결 실패: ${err instanceof Error ? err.message : String(err)}` ) } finally { + externalSignal?.removeEventListener('abort', onExternalAbort) if (this._abortController === controller) this._abortController = null } } + async processText( + text: string, + action: LLMAction, + targetLanguage?: string, + customPrompt?: string + ): Promise { + this._ensureAuth() + const systemPrompt = resolveSystemPrompt(action, targetLanguage, customPrompt) + const redaction = redactPII(text, 'tokenize') + const rawText = await this._postOnlineRequest('/api/llm/generate', { + prompt: redaction.redactedText, + systemPrompt, + model: configGet('llmModelId') ?? 'd3ro-gpt4o-mini', + temperature: 0.7, + maxTokens: 2048 + }) + return rehydrateText(rawText.trim(), redaction.tokens) + } + async *chatStream( messages: Array<{ role: string; content: string }>, - options?: { model?: string; temperature?: number } + options?: { model?: string; temperature?: number; signal?: AbortSignal } ): AsyncGenerator { - const token = this._ensureAuth() - const apiUrl = normalizeLoopbackUrl(configGet('onlineApiUrl') ?? 'http://127.0.0.1:5000') - - const response = await fetch(`${apiUrl}/api/llm/chat`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}` - }, - body: JSON.stringify({ - messages: messages.map((m) => ({ role: m.role, content: m.content })), + this._ensureAuth() + const redactedBatch = redactPIIMessages(messages) + const rawText = await this._postOnlineRequest( + '/api/llm/chat', + { + messages: redactedBatch.messages.map((m) => ({ role: m.role, content: m.content })), model: options?.model ?? configGet('llmModelId') ?? 'd3ro-gpt4o-mini', temperature: options?.temperature ?? 0.7 - }) - }) - - if (!response.ok) { - throw new D3ROError(ErrorCode.LLMProcessingFailed, `Online API Error: ${response.status}`) - } - - const data = (await response.json()) as OnlineGenerateResponse - yield data.text - return data.text + }, + options?.signal + ) + const restored = rehydrateText(rawText, redactedBatch.tokens) + yield restored + return restored } cancelGeneration(): void { @@ -152,7 +167,7 @@ class OnlineLLMService extends EventEmitter { let instance: OnlineLLMService | null = null export function resetOnlineLLMServiceForTests(): void { - if (instance) instance.removeAllListeners() + if (instance) instance.dispose() instance = null } diff --git a/apps/desktop/src/main/services/PersonalGraphService.ts b/apps/desktop/src/main/services/PersonalGraphService.ts index 23ac7e6..0eebf7d 100644 --- a/apps/desktop/src/main/services/PersonalGraphService.ts +++ b/apps/desktop/src/main/services/PersonalGraphService.ts @@ -76,82 +76,101 @@ class PersonalGraphService { .orderBy(desc(personalPhrases.lastUsedAt)) .limit(INCREMENTAL_SHARES_SCAN_LIMIT) .all() + .map((existing) => ({ + phrase: existing.phrase, + terms: parseTerms(existing.terms), + })) + .filter((existing) => existing.terms.length > 0) - for (const sentence of sentences) { + const preparedSentences = sentences.map((sentence) => { const terms = extractTerms(sentence) - db.insert(personalPhrases) - .values({ - id: crypto.randomUUID(), - phrase: sentence, - count: 1, - source: meta.source, - lastUsedAt: at, - createdAt: at, - terms: JSON.stringify(terms), - appName: meta.appName ?? null - }) - .onConflictDoUpdate({ - target: personalPhrases.phrase, - set: { - count: sql`${personalPhrases.count} + 1`, - lastUsedAt: at, - terms: JSON.stringify(terms), - appName: meta.appName ?? null - } - }) - .run() + return { sentence, terms, termsJson: JSON.stringify(terms) } + }) - if (terms.length > 0) { - for (const existing of recentExisting) { - if (existing.phrase === sentence) continue - const existingTerms = parseTerms(existing.terms) - if (existingTerms.length === 0) continue - if (jaccard(terms, existingTerms) >= SHARES_TERMS_MIN_SIMILARITY) { - this._upsertEdge(existing.phrase, sentence, 'shares_terms') + db.transaction((tx) => { + for (const entry of preparedSentences) { + tx.insert(personalPhrases) + .values({ + id: crypto.randomUUID(), + phrase: entry.sentence, + count: 1, + source: meta.source, + lastUsedAt: at, + createdAt: at, + terms: entry.termsJson, + appName: meta.appName ?? null + }) + .onConflictDoUpdate({ + target: personalPhrases.phrase, + set: { + count: sql`${personalPhrases.count} + 1`, + lastUsedAt: at, + terms: entry.termsJson, + appName: meta.appName ?? null + } + }) + .run() + + if (entry.terms.length > 0) { + for (const existing of recentExisting) { + if (existing.phrase === entry.sentence) continue + if (jaccard(entry.terms, existing.terms) >= SHARES_TERMS_MIN_SIMILARITY) { + this._upsertEdge(existing.phrase, entry.sentence, 'shares_terms', tx, at) + } } } } - } - // 같은 앱에서 직전 세션(10분 이내)에 쓴 문장과 첫 문장을 follows 로 연결 - if (scopeKey) { - const previousInScope = this._lastIndexedByScope.get(scopeKey) - if ( - previousInScope && - previousInScope.phrase !== sentences[0] && - Math.abs(at - previousInScope.at) <= SESSION_FOLLOWS_WINDOW_MS - ) { - this._upsertEdge(previousInScope.phrase, sentences[0], 'follows') + // 같은 앱에서 직전 세션(10분 이내)에 쓴 문장과 첫 문장을 follows 로 연결 + if (scopeKey) { + const previousInScope = this._lastIndexedByScope.get(scopeKey) + if ( + previousInScope && + previousInScope.phrase !== sentences[0] && + Math.abs(at - previousInScope.at) <= SESSION_FOLLOWS_WINDOW_MS + ) { + this._upsertEdge(previousInScope.phrase, sentences[0], 'follows', tx, at) + } } + + // follows 엣지 (같은 텍스트 내 인접 문장) + for (const edge of buildSequenceEdges(sentences)) { + this._upsertEdge(edge.from, edge.to, 'follows', tx, at) + } + + // 같은 텍스트 안에서 용어를 많이 공유하는 쌍 (사전 계산한 terms 재사용) + for (let i = 0; i < preparedSentences.length; i += 1) { + const termsA = preparedSentences[i].terms + if (termsA.length === 0) continue + for (let j = i + 1; j < preparedSentences.length; j += 1) { + const termsB = preparedSentences[j].terms + if (termsB.length === 0) continue + if (jaccard(termsA, termsB) < SHARES_TERMS_MIN_SIMILARITY) continue + this._upsertEdge(preparedSentences[i].sentence, preparedSentences[j].sentence, 'shares_terms', tx, at) + } + } + }) + + if (scopeKey) { this._lastIndexedByScope.set(scopeKey, { phrase: sentences[sentences.length - 1], at }) } - - // follows 엣지 (같은 텍스트 내 인접 문장) - for (const edge of buildSequenceEdges(sentences)) { - this._upsertEdge(edge.from, edge.to, 'follows') - } - - // 같은 텍스트 안에서 용어를 많이 공유하는 쌍 - for (let i = 0; i < sentences.length; i += 1) { - const termsA = extractTerms(sentences[i]) - for (let j = i + 1; j < sentences.length; j += 1) { - const termsB = extractTerms(sentences[j]) - if (jaccard(termsA, termsB) < SHARES_TERMS_MIN_SIMILARITY) continue - this._upsertEdge(sentences[i], sentences[j], 'shares_terms') - } - } } catch (error) { logger.warn(`그래프 반영 실패: ${error instanceof Error ? error.message : String(error)}`) } } - private _upsertEdge(from: string, to: string, kind: 'follows' | 'shares_terms'): void { - const db = getDatabase() - const now = Date.now() - db.insert(phraseEdges) + private _upsertEdge( + from: string, + to: string, + kind: 'follows' | 'shares_terms', + executor: Pick, 'insert'> = getDatabase(), + now = Date.now() + ): void { + executor + .insert(phraseEdges) .values({ id: crypto.randomUUID(), fromPhrase: from, @@ -421,26 +440,29 @@ class PersonalGraphService { runMaintenance(limit = MAINTENANCE_NODE_LIMIT): number { try { const db = getDatabase() - const nodes = db - .select() + const parsedNodes = db + .select({ phrase: personalPhrases.phrase, terms: personalPhrases.terms }) .from(personalPhrases) .orderBy(desc(personalPhrases.lastUsedAt)) .limit(limit) .all() + .map((node) => ({ phrase: node.phrase, terms: parseTerms(node.terms) })) + .filter((node) => node.terms.length > 0) let created = 0 - for (let i = 0; i < nodes.length; i += 1) { - const termsA = parseTerms(nodes[i].terms) - if (termsA.length === 0) continue - for (let j = i + 1; j < nodes.length; j += 1) { - const termsB = parseTerms(nodes[j].terms) - if (termsB.length === 0) continue - if (jaccard(termsA, termsB) < SHARES_TERMS_MIN_SIMILARITY) continue - this._upsertEdge(nodes[i].phrase, nodes[j].phrase, 'shares_terms') - created += 1 - if (created >= 200) return created + const now = Date.now() + db.transaction((tx) => { + for (let i = 0; i < parsedNodes.length; i += 1) { + const termsA = parsedNodes[i].terms + for (let j = i + 1; j < parsedNodes.length; j += 1) { + const termsB = parsedNodes[j].terms + if (jaccard(termsA, termsB) < SHARES_TERMS_MIN_SIMILARITY) continue + this._upsertEdge(parsedNodes[i].phrase, parsedNodes[j].phrase, 'shares_terms', tx, now) + created += 1 + if (created >= 200) return + } } - } + }) if (created > 0) logger.info(`그래프 유지보수: shares_terms 엣지 ${created}개 생성`) return created } catch (error) { diff --git a/apps/desktop/src/main/services/ScreenContextService.ts b/apps/desktop/src/main/services/ScreenContextService.ts index 6e2455f..35ba123 100644 --- a/apps/desktop/src/main/services/ScreenContextService.ts +++ b/apps/desktop/src/main/services/ScreenContextService.ts @@ -16,6 +16,7 @@ import { isTerminalHost, type ForegroundWindowPort, } from './foreground-window-port' +import { sendWin32CopyChord } from '../utils/win32-unicode-input' const logger = getLogger('screen-context') @@ -43,6 +44,8 @@ export interface ScreenContextServiceDeps { foreground?: ForegroundWindowPort /** 복사 단축키 수정자 결정용 플랫폼 (기본: process.platform) */ platform?: NodeJS.Platform + /** 네이티브 복사 단축키 주입기 (성공 시 true 반환하여 nut-js 로드를 생략) */ + sendCopyShortcut?: () => Promise } // ============================================================ @@ -54,10 +57,16 @@ export class ScreenContextService { private _nutLoadPromise: Promise | null = null private readonly _foreground: ForegroundWindowPort private readonly _platform: NodeJS.Platform + private readonly _sendCopyShortcut: (() => Promise) | null constructor(deps: ScreenContextServiceDeps = {}) { this._platform = deps.platform ?? process.platform this._foreground = deps.foreground ?? createDefaultForegroundWindowPort(this._platform) + this._sendCopyShortcut = + deps.sendCopyShortcut ?? + (!process.env.VITEST && this._platform === 'win32' + ? async () => sendWin32CopyChord() + : null) } /** @@ -234,7 +243,6 @@ export class ScreenContextService { * TextInsertService의 역방향: clipboard save → 복사 단축키 simulate → clipboard read → clipboard restore */ private async _captureSelectedText(): Promise { - const nut = await this._ensureNut() const port = electronClipboardPort // 1. 기존 클립보드 저장 + 온전히 되돌릴 수 있는지 판정 (삽입과 같은 정책) @@ -250,10 +258,14 @@ export class ScreenContextService { // 2. 클립보드 비우기 (이전 내용이 남아있으면 "선택 없음"을 감지할 수 없으므로) port.clear() - // 3. 복사 단축키 시뮬레이션 (macOS ⌘+C, 그 외 Ctrl+C) - const modifier = this._platform === 'darwin' ? nut.Key.LeftSuper : nut.Key.LeftControl - await nut.pressKey(modifier, nut.Key.C) - await nut.releaseKey(modifier, nut.Key.C) + // 3. 복사 단축키 시뮬레이션 (Windows 프로덕션은 koffi SendInput, macOS/폴백은 nut-js) + const copiedByNative = this._sendCopyShortcut ? await this._sendCopyShortcut() : false + if (!copiedByNative) { + const nut = await this._ensureNut() + const modifier = this._platform === 'darwin' ? nut.Key.LeftSuper : nut.Key.LeftControl + await nut.pressKey(modifier, nut.Key.C) + await nut.releaseKey(modifier, nut.Key.C) + } // 4. 클립보드에 텍스트가 복사될 때까지 대기 await this._sleep(150) diff --git a/apps/desktop/src/main/services/SuggestionService.ts b/apps/desktop/src/main/services/SuggestionService.ts index e2b06f9..7a8c62d 100644 --- a/apps/desktop/src/main/services/SuggestionService.ts +++ b/apps/desktop/src/main/services/SuggestionService.ts @@ -15,7 +15,6 @@ import { COMPOSING_IDLE_MULTIPLIER, isAppScopedLearning, SUGGESTION_DEFAULTS, - SUGGESTION_MAX_OUTPUT_CHARS, buildLocalSuggestionCandidateEntries, decideInFlightGeneration, decideSuggestion, @@ -28,7 +27,6 @@ import { selectPhraseHints, shouldPersistSuggestionPrefix, isTerminalApp, - extractTerminalPromptPrefix, type AnchorKind, type PhysicalRect, type SuggestionCandidate, @@ -39,7 +37,7 @@ import { type SuggestionState, type SuggestionStep } from '@d3ro/core/input-intelligence' -import { buildQueryTerms, scoreCandidatePersonalization } from '@d3ro/core/personal-graph' +import { buildQueryTerms } from '@d3ro/core/personal-graph' import { splitFirstWord } from '@d3ro/core/suggestion-text' import { predictPersonalContinuation } from '@d3ro/core/personal-ngram' import { analyzeWritingContext } from '@d3ro/core/writing-context' @@ -67,6 +65,17 @@ import { type SuggestionModelRequest, type SuggestionModelRequestInput } from './suggestion/SuggestionModelRequest' +import { + applyCorrectionToContext, + buildDecisionInputSignature, + isDuplicateCandidateText, + normalizeSuggestionPolicyConfig, + rerankFilledCandidates, + resolveTerminalTypingContext, + sameCandidateText, + toSuggestionCorrectionFromPlan, + type SuggestionPolicyConfig +} from './suggestion/suggestion-policy-helpers' import { LOCAL_LLM_KEEP_ALIVE, LOCAL_LLM_KEEP_ALIVE_MS } from './llm/model-residency' import { getForegroundWindowInfo } from '../utils/win32-foreground' @@ -103,17 +112,6 @@ export interface SuggestionTypoProposer { ): Promise<{ originalText: string; insertText: string; corrections: Array<{ start: number; end: number; to: string }> } | null> } -/** 교정을 적용한 문맥 — 모델에는 고친 글을 보여 주고, 세션 비교는 원문으로 한다. */ -function applyCorrectionToContext(context: TypingContext, correction: SuggestionCorrection): TypingContext { - const replaceTail = (text: string): string => - text.endsWith(correction.from) ? text.slice(0, text.length - correction.from.length) + correction.to : text - return { - ...context, - prefix: replaceTail(context.prefix), - documentBefore: context.documentBefore == null ? context.documentBefore : replaceTail(context.documentBefore) - } -} - /** 서비스 협력자 — 기본값은 getSuggestionService() 가 연결한다 (DIP). */ export interface SuggestionServiceDeps { repository: SuggestionRepository @@ -143,16 +141,7 @@ export function createDefaultSuggestionServiceDeps(): SuggestionServiceDeps { } } -/** 설정에서 읽은 정책 값 (SSOT 기본값과 상한 적용 후). */ -interface PolicyConfig { - triggerDelayMs: number - minPrefixChars: number - maxRequestsPerMinute: number - dailyBudget: number - maxCandidates: number - maxChars: number - excludedApps: string[] -} +type PolicyConfig = SuggestionPolicyConfig export interface SuggestionRequestResult { ok: boolean @@ -233,25 +222,6 @@ interface FirstCandidatePublication extends SuggestionGenerationRequest { timing: GenerationTiming } -/** - * 스냅샷 한 번(약 0.8초) 사이에 사람이 칠 수 있는 글자 수 상한. 빈 터미널 입력칸이 이보다 크게 - * 한 번에 채워지면 타이핑이 아니다(Claude Code 의 회색 추천 문구). - */ -const TERMINAL_TYPING_STEP_CHARS = 8 - -/** 공백·끝 문장부호를 무시하고 같은 후보인가 */ -function sameCandidateText(a: string, b: string): boolean { - const norm = (text: string) => text.replace(/\s+/gu, ' ').replace(/[.!?。!?…,]+$/u, '').trim() - return norm(a) === norm(b) -} - -function commonPrefixLength(a: string, b: string): number { - const max = Math.min(a.length, b.length) - let index = 0 - while (index < max && a[index] === b[index]) index += 1 - return index -} - /** 이 길이를 넘는 모델 출력은 버린다 (스트리밍 폭주 방지) */ const MAX_RAW_OUTPUT_CHARS = 1200 /** "제안 사항 없음" 을 보여 주는 시간 */ @@ -995,38 +965,13 @@ export class SuggestionService extends EventEmitter { * (끝에서 치거나 지움) 커서는 입력 줄 끝이다. 중간을 고친 모양이면 다음 입력까지 막는다. */ private _terminalContext(input: TypingContext): TypingContext { - if (input.vimMode === 'normal' || input.vimMode === 'command') { - this._lastTerminalPrompt = '' - this._terminalPromptTyped = false - return { ...input, prefix: '', documentBefore: null, caretReliable: false } - } - const extracted = extractTerminalPromptPrefix(input.fullText ?? input.prefix) - const prompt = extracted ?? (input.terminalMode ? input.prefix : null) - const previous = this._lastTerminalPrompt - this._lastTerminalPrompt = prompt - let typed: boolean - if (prompt === null) typed = false - else if (prompt.length === 0) typed = true - else if (previous === null) typed = prompt.length <= TERMINAL_TYPING_STEP_CHARS - else if (prompt === previous) typed = this._terminalPromptTyped - else if (previous.length === 0 && prompt.length > TERMINAL_TYPING_STEP_CHARS) { - // 빈 입력칸이 한 번에 긴 글로 바뀌었다 — Claude Code 의 회색 "추천 문구" 다. UIA 는 그것도 - // 입력 글자로 준다(실측 2026-10-03: 빈 칸 → 28·29자, 그 뒤에 이어 쓴 ", ready for next test - // cycle." 이 사용자 메시지 앞에 삽입됐다). 사용자가 치기 시작하면 다음 판정에서 다시 믿는다. - typed = false - } else { - // 바뀐 곳이 끝부분뿐이면 끝에서 치는 중이다: 늘어남·줄어듦, 그리고 한글 조합처럼 마지막 - // 한두 글자가 바뀌는 것("자ㄹ" → "자료"). 조합을 "중간 편집" 으로 보던 탓에 멈춘 뒤에도 - // 막혀 있었다(실측: 30초 동안 치는데 내내 caret-unknown). - typed = commonPrefixLength(previous, prompt) >= Math.min(previous.length, prompt.length) - 2 - } - this._terminalPromptTyped = typed - return { - ...input, - prefix: prompt ?? '', - documentBefore: null, - caretReliable: extracted !== null ? typed : typed && input.caretReliable !== false - } + const { context, nextState } = resolveTerminalTypingContext(input, { + lastPrompt: this._lastTerminalPrompt, + promptTyped: this._terminalPromptTyped + }) + this._lastTerminalPrompt = nextState.lastPrompt + this._terminalPromptTyped = nextState.promptTyped + return context } /** 로컬 기억은 모델과 무관하다 — 같은 정책을 "모델 있음 · 표시 없음" 으로 평가한다. */ @@ -1604,13 +1549,7 @@ export class SuggestionService extends EventEmitter { if (!this._typoProposer) return null try { const plan = await this._typoProposer.propose(context, signal, { thorough }) - if (!plan || !context.prefix.endsWith(plan.originalText)) return null - const base = plan.corrections[0]?.start ?? 0 - return { - from: plan.originalText, - to: plan.insertText, - edits: plan.corrections.map((edit) => ({ start: edit.start - base, end: edit.end - base, to: edit.to })) - } + return toSuggestionCorrectionFromPlan(context.prefix, plan) ?? null } catch (error) { logger.debug(`제안용 오타 교정 실패 — 교정 없이 제안한다: ${error instanceof Error ? error.message : String(error)}`) return null @@ -1720,30 +1659,13 @@ export class SuggestionService extends EventEmitter { private _appendFilledCandidate(candidate: SuggestionCandidate, prefix: string, memory: LocalMemoryContext): void { this._candidates.push({ ...candidate, rank: this._candidates.length }) if (this._activeIndex === 0 && this._candidates.length >= 2) { - const personalContext = { + this._candidates = rerankFilledCandidates(this._candidates, candidate.text, { prefix, continuationHints: memory.continuationHints, followUpHints: memory.followUpHints, relatedHints: memory.relatedHints, phraseHints: memory.phraseHints - } - const newScore = scoreCandidatePersonalization(candidate.text, personalContext) - if (newScore >= 1.5) { - const personalItems = this._candidates.filter((item) => item.source === 'personal') - const modelItems = this._candidates - .filter((item) => item.source !== 'personal') - .map((item, idx) => ({ - item, - idx, - score: scoreCandidatePersonalization(item.text, personalContext) - })) - .sort((a, b) => (Math.abs(b.score - a.score) >= 0.8 ? b.score - a.score : a.idx - b.idx)) - .map((entry) => entry.item) - this._candidates = [...personalItems, ...modelItems].map((item, index) => ({ - ...item, - rank: index - })) - } + }) } logger.debug(`제안 후보 추가 ${this._candidates.length}/${SUGGESTION_DEFAULTS.maxCandidatesTotal}`) this._armVisibleTtl() @@ -1791,15 +1713,7 @@ export class SuggestionService extends EventEmitter { /** 정규화 후 완전 중복이거나 기존 후보의 접두/확장이면 중복으로 본다. */ private _isDuplicateCandidate(candidate: string): boolean { - const normalized = candidate.replace(/\s+/gu, ' ').trim().toLowerCase() - return this._candidates.some((existing) => { - const existingNormalized = existing.text.replace(/\s+/gu, ' ').trim().toLowerCase() - return ( - existingNormalized === normalized || - existingNormalized.startsWith(normalized) || - normalized.startsWith(existingNormalized) - ) - }) + return isDuplicateCandidateText(candidate, this._candidates) } /** @@ -1833,17 +1747,9 @@ export class SuggestionService extends EventEmitter { /** 판단 입력을 서명이 바뀔 때만 남긴다. */ private _logDecisionInputs(context: TypingContext): void { - const signature = [ - context.available, - context.isEditable, - context.isPassword, - context.isComposing, - context.anchor ? 'A' : '-', - context.editedSinceFocus, - context.typedRecently, - getLocalLLMService().isAvailable(), - this.isEnabled() - ].join('|') + const modelAvailable = getLocalLLMService().isAvailable() + const enabled = this.isEnabled() + const signature = buildDecisionInputSignature(context, { modelAvailable, enabled }) if (signature === this._lastDecisionSignature) return this._lastDecisionSignature = signature @@ -1851,8 +1757,8 @@ export class SuggestionService extends EventEmitter { `제안 판단 입력: avail=${context.available} edit=${context.isEditable} pw=${context.isPassword} ` + `comp=${context.isComposing} edited=${context.editedSinceFocus} typed=${context.typedRecently} ` + `prefixLen=${context.prefix.length} idle=${context.idleMs}ms ` + - `app=${context.appName ?? '-'} enabled=${this.isEnabled()} ` + - `model=${getLocalLLMService().isAvailable()} anchor=${context.anchor ? 'yes' : 'no'}` + `app=${context.appName ?? '-'} enabled=${enabled} ` + + `model=${modelAvailable} anchor=${context.anchor ? 'yes' : 'no'}` ) } @@ -2328,24 +2234,13 @@ export class SuggestionService extends EventEmitter { // ── 내부 ────────────────────────────────────────────── private readPolicyConfig(): PolicyConfig { - return { - triggerDelayMs: Math.max( - SUGGESTION_DEFAULTS.minTriggerDelayMs, - configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs - ), - minPrefixChars: configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars, - maxRequestsPerMinute: - Math.min( - configGet('suggestionMaxRequestsPerMinute') || SUGGESTION_DEFAULTS.maxRequestsPerMinute, - 30 - ), - dailyBudget: configGet('suggestionDailyBudget') || SUGGESTION_DEFAULTS.dailyBudget, - maxCandidates: SUGGESTION_DEFAULTS.maxCandidates, - maxChars: SUGGESTION_MAX_OUTPUT_CHARS, - // 터미널은 셸 프롬프트라 문장 제안이 의미 없다 — 사용자 목록과 무관하게 뺀다. - // 터미널도 제안한다(입력 줄만 추출). 학습 제외는 InputTelemetryService 가 따로 한다. - excludedApps: [...configGet('inputExcludedApps')] - } + return normalizeSuggestionPolicyConfig({ + triggerDelayMs: configGet('suggestionTriggerDelayMs'), + minPrefixChars: configGet('suggestionMinPrefixChars'), + maxRequestsPerMinute: configGet('suggestionMaxRequestsPerMinute'), + dailyBudget: configGet('suggestionDailyBudget'), + excludedApps: configGet('inputExcludedApps') + }) } /** diff --git a/apps/desktop/src/main/services/UnifiedSearchService.ts b/apps/desktop/src/main/services/UnifiedSearchService.ts index 88af554..74a139f 100644 --- a/apps/desktop/src/main/services/UnifiedSearchService.ts +++ b/apps/desktop/src/main/services/UnifiedSearchService.ts @@ -1,8 +1,14 @@ -// 기록과 회의를 스키마 변경 없이 함께 찾는 로컬 통합 검색. +// 기록과 회의를 FTS5 trigram 역색인(3자 이상) + 정확한 부분 문자열 검증으로 함께 찾는 로컬 통합 검색. import { EventEmitter } from 'events' -import { count, desc, inArray, or } from 'drizzle-orm' +import { and, count, desc, inArray, or, sql } from 'drizzle-orm' import { formatTranscriptTimestamp, parseTranscriptLines } from '@d3ro/core/meeting-transcript' +import { isRecord } from '@d3ro/core/guards' +import { + createUnifiedSearchExcerpt, + includesSearchQuery, + mergeUnifiedSearchResults, +} from '@d3ro/core/unified-search' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import type { UnifiedSearchParams, @@ -21,18 +27,19 @@ import { } from '../db/schema' import { getLogger } from './LoggerService' +export { createUnifiedSearchExcerpt, mergeUnifiedSearchResults } + const logger = getLogger('UnifiedSearchService') const DEFAULT_LIMIT = 30 const MAX_LIMIT = 50 const MAX_QUERY_LENGTH = 200 -const EXCERPT_LENGTH = 180 export function validateUnifiedSearchParams(value: unknown): UnifiedSearchParams { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { + if (!isRecord(value)) { throw new D3ROError(ErrorCode.ConfigInvalidValue, 'Unified search parameters are required') } - const candidate = value as Record + const candidate = value if (typeof candidate.query !== 'string') { throw new D3ROError(ErrorCode.ConfigInvalidValue, 'Unified search query must be a string', { field: 'query', @@ -56,32 +63,45 @@ export function normalizeUnifiedSearchQuery(value: string): string { return value.slice(0, MAX_QUERY_LENGTH).trim().replace(/\s+/g, ' ') } -function includesQuery(value: string | null | undefined, query: string): boolean { - return value?.toLocaleLowerCase().includes(query.toLocaleLowerCase()) === true +/** + * SQLite FTS5 trigram 구문 리터럴 생성. + * trigram 토크나이저는 유니코드 코드포인트 3글자 이상부터 역색인을 탄다. + */ +function toFtsTrigramPhrase(query: string): string | null { + if (query.includes('\0') || Array.from(query).length < 3) return null + return `"${query.replaceAll('"', '""')}"` } -export function createUnifiedSearchExcerpt( - value: string | null | undefined, - query: string, - maxLength = EXCERPT_LENGTH, -): string { - const text = (value ?? '').replace(/\s+/g, ' ').trim() - if (text.length <= maxLength) return text +interface SqliteMasterClient { + prepare?: (sql: string) => { all: (...args: unknown[]) => Array<{ name: string }> } +} - const matchAt = text.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) - if (matchAt < 0) return `${text.slice(0, maxLength - 1).trimEnd()}…` +const REQUIRED_FTS_TABLES = [ + 'history_fts', + 'meeting_sessions_fts', + 'meeting_memos_fts', +] as const - const context = Math.max(20, Math.floor((maxLength - query.length) / 2)) - const start = Math.max(0, matchAt - context) - const end = Math.min(text.length, start + maxLength) - const body = text.slice(start, end).trim() - return `${start > 0 ? '…' : ''}${body}${end < text.length ? '…' : ''}` +function hasAllFtsTables(db: unknown): boolean { + const client = (db as { $client?: SqliteMasterClient } | null | undefined)?.$client + if (!client || typeof client.prepare !== 'function') return false + try { + const rows = client + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('history_fts', 'meeting_sessions_fts', 'meeting_memos_fts')", + ) + .all() + const present = new Set(rows.map((row) => row.name)) + return REQUIRED_FTS_TABLES.every((name) => present.has(name)) + } catch { + return false + } } function recordResult(row: History, query: string): UnifiedSearchResult { - const titleMatched = includesQuery(row.title, query) + const titleMatched = includesSearchQuery(row.title, query) const matchingContent = [row.polishedText, row.originalText, row.summaryText] - .find((value) => includesQuery(value, query)) + .find((value) => includesSearchQuery(value, query)) const displayContent = matchingContent ?? row.polishedText ?? row.originalText ?? row.summaryText ?? row.title return { @@ -100,7 +120,7 @@ function findMatchingTranscriptSegmentSnippet( ): string | null { const lines = parseTranscriptLines(transcript) for (const line of lines) { - if (includesQuery(line.text, query) || includesQuery(line.speaker, query)) { + if (includesSearchQuery(line.text, query) || includesSearchQuery(line.speaker, query)) { if (!line.timed) return line.text const speakerPrefix = line.speaker ? `[${line.speaker}] ` : '' return `[${formatTranscriptTimestamp(line.timestampMs)}] ${speakerPrefix}${line.text}` @@ -118,9 +138,9 @@ function meetingResult( query: string, memoMatch?: MeetingMemoRow, ): UnifiedSearchResult { - const titleMatched = includesQuery(row.title, query) + const titleMatched = includesSearchQuery(row.title, query) const matchingTranscript = [row.editedTranscript, row.rawTranscript] - .find((value) => includesQuery(value, query)) + .find((value) => includesSearchQuery(value, query)) const segmentSnippet = findMatchingTranscriptSegmentSnippet( matchingTranscript ?? row.editedTranscript ?? row.rawTranscript, query, @@ -151,14 +171,78 @@ function meetingResult( } } -export function mergeUnifiedSearchResults( - records: readonly UnifiedSearchResult[], - meetings: readonly UnifiedSearchResult[], +interface SearchConditions { + recordConditions: ReturnType + meetingConditions: ReturnType + memoBaseCondition: ReturnType['match']> +} + +interface SearchQueryRows { + recordTotal: number + recordRows: History[] + meetingTotal: number + meetingRows: MeetingSessionRow[] + memoRows: MeetingMemoRow[] +} + +function executeUnifiedSearchQueries( + db: ReturnType, + query: string, limit: number, -): UnifiedSearchResult[] { - return [...records, ...meetings] - .sort((left, right) => right.occurredAt - left.occurredAt || left.id.localeCompare(right.id)) - .slice(0, limit) + conditions: SearchConditions, + useFts: boolean, +): SearchQueryRows { + const ftsPhrase = useFts ? toFtsTrigramPhrase(query) : null + const recordWhere = ftsPhrase + ? and( + sql`${history.id} IN (SELECT row_id FROM history_fts WHERE history_fts MATCH ${ftsPhrase})`, + conditions.recordConditions, + ) + : conditions.recordConditions + const meetingWhere = ftsPhrase + ? and( + sql`${meetingSessions.id} IN (SELECT row_id FROM meeting_sessions_fts WHERE meeting_sessions_fts MATCH ${ftsPhrase})`, + conditions.meetingConditions, + ) + : conditions.meetingConditions + const memoWhere = ftsPhrase + ? and( + sql`${meetingMemos.id} IN (SELECT row_id FROM meeting_memos_fts WHERE meeting_memos_fts MATCH ${ftsPhrase})`, + conditions.memoBaseCondition, + ) + : conditions.memoBaseCondition + + const memoSessionMatch = sql`${meetingSessions.id} IN (SELECT ${meetingMemos.sessionId} FROM meeting_memos WHERE ${memoWhere})` + const anyMeetingWhere = or(meetingWhere, memoSessionMatch) + + const recordTotal = db.select({ count: count() }).from(history).where(recordWhere).get()?.count ?? 0 + const recordRows = db + .select() + .from(history) + .where(recordWhere) + .orderBy(desc(history.createdAt)) + .limit(limit) + .all() + const meetingTotal = db.select({ count: count() }).from(meetingSessions).where(anyMeetingWhere).get()?.count ?? 0 + const meetingRows = db + .select() + .from(meetingSessions) + .where(anyMeetingWhere) + .orderBy(desc(meetingSessions.startedAt)) + .limit(limit) + .all() + + const meetingIds = meetingRows.map((row) => row.id) + const memoRows = meetingIds.length > 0 + ? db + .select() + .from(meetingMemos) + .where(and(inArray(meetingMemos.sessionId, meetingIds), memoWhere)) + .orderBy(desc(meetingMemos.createdAt)) + .all() + : [] + + return { recordTotal, recordRows, meetingTotal, meetingRows, memoRows } } class UnifiedSearchService extends EventEmitter { @@ -171,73 +255,51 @@ class UnifiedSearchService extends EventEmitter { try { const db = getDatabase() const pattern = containsPattern(query) - const recordConditions = or( - pattern.match(history.title), - pattern.match(history.originalText), - pattern.match(history.polishedText), - pattern.match(history.summaryText), - ) - const meetingConditions = or( - pattern.match(meetingSessions.title), - pattern.match(meetingSessions.editedTranscript), - pattern.match(meetingSessions.rawTranscript), - ) + const conditions: SearchConditions = { + recordConditions: or( + pattern.match(history.title), + pattern.match(history.originalText), + pattern.match(history.polishedText), + pattern.match(history.summaryText), + ), + meetingConditions: or( + pattern.match(meetingSessions.title), + pattern.match(meetingSessions.editedTranscript), + pattern.match(meetingSessions.rawTranscript), + ), + memoBaseCondition: pattern.match(meetingMemos.content), + } - const recordTotal = db.select({ count: count() }).from(history).where(recordConditions).get()?.count ?? 0 - const recordRows = db - .select() - .from(history) - .where(recordConditions) - .orderBy(desc(history.createdAt)) - .limit(limit) - .all() - const meetingTotal = db.select({ count: count() }).from(meetingSessions).where(meetingConditions).get()?.count ?? 0 - const meetingRows = db - .select() - .from(meetingSessions) - .where(meetingConditions) - .orderBy(desc(meetingSessions.createdAt)) - .limit(limit) - .all() - const memoRows = db - .select() - .from(meetingMemos) - .where(pattern.match(meetingMemos.content)) - .orderBy(desc(meetingMemos.timestampMs)) - .limit(limit) - .all() + const canTryFts = hasAllFtsTables(db) && toFtsTrigramPhrase(query) !== null + let queryRows: SearchQueryRows + if (canTryFts) { + try { + queryRows = executeUnifiedSearchQueries(db, query, limit, conditions, true) + } catch (ftsError) { + const message = ftsError instanceof Error ? ftsError.message : String(ftsError) + logger.warn(`Unified search FTS5 query failed, falling back to LIKE: ${message}`) + queryRows = executeUnifiedSearchQueries(db, query, limit, conditions, false) + } + } else { + queryRows = executeUnifiedSearchQueries(db, query, limit, conditions, false) + } const memoBySessionId = new Map() - for (const memo of memoRows) { + for (const memo of queryRows.memoRows) { if (!memoBySessionId.has(memo.sessionId)) { memoBySessionId.set(memo.sessionId, memo) } } - const directMeetingIds = new Set(meetingRows.map((row) => row.id)) - const missingSessionIds = [...memoBySessionId.keys()].filter( - (sessionId) => !directMeetingIds.has(sessionId), - ) - const memoMatchedMeetings = missingSessionIds.length > 0 - ? db - .select() - .from(meetingSessions) - .where(inArray(meetingSessions.id, missingSessionIds)) - .orderBy(desc(meetingSessions.createdAt)) - .limit(limit) - .all() - : [] - - const combinedMeetingRows = [...meetingRows, ...memoMatchedMeetings] const results = mergeUnifiedSearchResults( - recordRows.map((row) => recordResult(row, query)), - combinedMeetingRows.map((row) => meetingResult(row, query, memoBySessionId.get(row.id))), + queryRows.recordRows.map((row) => recordResult(row, query)), + queryRows.meetingRows.map((row) => meetingResult(row, query, memoBySessionId.get(row.id))), limit, ) return { query, results, - total: recordTotal + meetingTotal + memoMatchedMeetings.length, + total: queryRows.recordTotal + queryRows.meetingTotal, } } catch (error) { const message = error instanceof Error ? error.message : String(error) diff --git a/apps/desktop/src/main/services/VoiceModeService.ts b/apps/desktop/src/main/services/VoiceModeService.ts index aa73893..19f0a47 100644 --- a/apps/desktop/src/main/services/VoiceModeService.ts +++ b/apps/desktop/src/main/services/VoiceModeService.ts @@ -31,6 +31,7 @@ import { getTranscriptGlossaryService } from './TranscriptGlossaryService' import { buildInstructionInvocation, resolveTargetLanguage } from './llm-prompts' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import { cleanDictatedText } from '@d3ro/core/dictation-cleaner' +import { secureWipeAudioChunks, secureZeroBuffer } from '@d3ro/core/utils/secure-memory' import { composeInstructionPipelinePrompt, parseActiveInstructionIds } from '@d3ro/core/instruction-template' import { TIMING } from '@d3ro/core/constants' import { RecognitionState, AudioState } from '@d3ro/core/types' @@ -887,7 +888,7 @@ class VoiceModeService extends EventEmitter { const merged = Buffer.concat(run.audioBuffer) run.lastAudio = merged // WAV 저장용 (run 소유) - run.audioBuffer = [] + secureWipeAudioChunks(run.audioBuffer) run.audioBufferBytes = 0 // Bug 13: 너무 짧은 오디오는 STT 호출 전에 에러 피드백. @@ -1247,6 +1248,9 @@ class VoiceModeService extends EventEmitter { this._clearSttWaitTimer(run) this._stopPartialLoop(run) run.partialInFlight = null + secureWipeAudioChunks(run.audioBuffer) + secureZeroBuffer(run.lastAudio) + run.lastAudio = null void this._releaseAudio(run) if (this._run === run) this._resetToIdle() } diff --git a/apps/desktop/src/main/services/ads/AdMediationEngine.ts b/apps/desktop/src/main/services/ads/AdMediationEngine.ts index 05fda5f..d9024b5 100644 --- a/apps/desktop/src/main/services/ads/AdMediationEngine.ts +++ b/apps/desktop/src/main/services/ads/AdMediationEngine.ts @@ -11,16 +11,8 @@ import type { AdRevenueStats, } from '@d3ro/core/types' import type { IAdNetworkAdapter } from './BaseAdAdapter' -import { EthicalAdsAdapter } from './EthicalAdsAdapter' -import { CarbonAdsAdapter } from './CarbonAdsAdapter' -import { PlaywireAdapter } from './PlaywireAdapter' -import { UnityAdsAdapter } from './UnityAdsAdapter' -import { AppLovinAdapter } from './AppLovinAdapter' -import { GoogleAdManagerAdapter } from './GoogleAdManagerAdapter' -import { InMobiAdapter } from './InMobiAdapter' -import { PubMaticAdapter } from './PubMaticAdapter' -import { MintegralAdapter } from './MintegralAdapter' import { DirectHouseSponsorAdapter } from './DirectHouseSponsorAdapter' +import { createUnavailableAdAdapters } from './UnavailableAdAdapter' import { getAdSettlementService } from './AdSettlementService' import { getLicenseService } from '../LicenseService' @@ -40,15 +32,7 @@ export class AdMediationEngine { // integrated. No adapter may fabricate a bid or creative. const adapterList: IAdNetworkAdapter[] = [ new DirectHouseSponsorAdapter(), - new PlaywireAdapter(), - new EthicalAdsAdapter(), - new CarbonAdsAdapter(), - new UnityAdsAdapter(), - new AppLovinAdapter(), - new GoogleAdManagerAdapter(), - new InMobiAdapter(), - new PubMaticAdapter(), - new MintegralAdapter(), + ...createUnavailableAdAdapters(), ] for (const adapter of adapterList) { @@ -152,12 +136,15 @@ export class AdMediationEngine { const bidPromises = enabledAdapters.map(async (adapter) => { const adapterStart = Date.now() try { + let bidTimer: ReturnType | undefined const bidResult = await Promise.race([ adapter.requestBid(request), - new Promise((_, reject) => - setTimeout(() => reject(new Error('Bid Timeout')), timeoutMs) - ), - ]) + new Promise((_, reject) => { + bidTimer = setTimeout(() => reject(new Error('Bid Timeout')), timeoutMs) + }), + ]).finally(() => { + if (bidTimer !== undefined) clearTimeout(bidTimer) + }) if ( bidResult.hasBid diff --git a/apps/desktop/src/main/services/ads/AppLovinAdapter.ts b/apps/desktop/src/main/services/ads/AppLovinAdapter.ts deleted file mode 100644 index 443a1da..0000000 --- a/apps/desktop/src/main/services/ads/AppLovinAdapter.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { UnavailableAdAdapter } from './UnavailableAdAdapter' - -export class AppLovinAdapter extends UnavailableAdAdapter { - constructor() { - super( - 'applovin_max', - 'AppLovin MAX', - ['rewarded_video', 'banner_dock', 'export_sponsor'], - 5.5, - ) - } -} diff --git a/apps/desktop/src/main/services/ads/CarbonAdsAdapter.ts b/apps/desktop/src/main/services/ads/CarbonAdsAdapter.ts deleted file mode 100644 index 394e2a2..0000000 --- a/apps/desktop/src/main/services/ads/CarbonAdsAdapter.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { UnavailableAdAdapter } from './UnavailableAdAdapter' - -export class CarbonAdsAdapter extends UnavailableAdAdapter { - constructor() { - super('carbon_ads', 'Carbon Ads', ['banner_dock'], 3.5) - } -} diff --git a/apps/desktop/src/main/services/ads/EthicalAdsAdapter.ts b/apps/desktop/src/main/services/ads/EthicalAdsAdapter.ts deleted file mode 100644 index 616a130..0000000 --- a/apps/desktop/src/main/services/ads/EthicalAdsAdapter.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { UnavailableAdAdapter } from './UnavailableAdAdapter' - -export class EthicalAdsAdapter extends UnavailableAdAdapter { - constructor() { - super('ethical_ads', 'EthicalAds', ['banner_dock', 'export_sponsor'], 3.2) - } -} diff --git a/apps/desktop/src/main/services/ads/GoogleAdManagerAdapter.ts b/apps/desktop/src/main/services/ads/GoogleAdManagerAdapter.ts deleted file mode 100644 index 7b061c0..0000000 --- a/apps/desktop/src/main/services/ads/GoogleAdManagerAdapter.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { UnavailableAdAdapter } from './UnavailableAdAdapter' - -export class GoogleAdManagerAdapter extends UnavailableAdAdapter { - constructor() { - super( - 'google_ad_manager', - 'Google Ad Manager', - ['banner_dock', 'rewarded_video', 'export_sponsor'], - 2, - ) - } -} diff --git a/apps/desktop/src/main/services/ads/InMobiAdapter.ts b/apps/desktop/src/main/services/ads/InMobiAdapter.ts deleted file mode 100644 index d065bbd..0000000 --- a/apps/desktop/src/main/services/ads/InMobiAdapter.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { UnavailableAdAdapter } from './UnavailableAdAdapter' - -export class InMobiAdapter extends UnavailableAdAdapter { - constructor() { - super('inmobi', 'InMobi', ['banner_dock', 'rewarded_video'], 2.8) - } -} diff --git a/apps/desktop/src/main/services/ads/MintegralAdapter.ts b/apps/desktop/src/main/services/ads/MintegralAdapter.ts deleted file mode 100644 index d20c4b6..0000000 --- a/apps/desktop/src/main/services/ads/MintegralAdapter.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { UnavailableAdAdapter } from './UnavailableAdAdapter' - -export class MintegralAdapter extends UnavailableAdAdapter { - constructor() { - super('mintegral', 'Mintegral', ['rewarded_video', 'banner_dock'], 4) - } -} diff --git a/apps/desktop/src/main/services/ads/PlaywireAdapter.ts b/apps/desktop/src/main/services/ads/PlaywireAdapter.ts deleted file mode 100644 index d5fec5f..0000000 --- a/apps/desktop/src/main/services/ads/PlaywireAdapter.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { UnavailableAdAdapter } from './UnavailableAdAdapter' - -export class PlaywireAdapter extends UnavailableAdAdapter { - constructor() { - super( - 'playwire', - 'Playwire RAMP', - ['banner_dock', 'rewarded_video', 'export_sponsor'], - 4.5, - ) - } -} diff --git a/apps/desktop/src/main/services/ads/PubMaticAdapter.ts b/apps/desktop/src/main/services/ads/PubMaticAdapter.ts deleted file mode 100644 index 18bb5c8..0000000 --- a/apps/desktop/src/main/services/ads/PubMaticAdapter.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { UnavailableAdAdapter } from './UnavailableAdAdapter' - -export class PubMaticAdapter extends UnavailableAdAdapter { - constructor() { - super('pubmatic', 'PubMatic OpenWrap', ['banner_dock', 'export_sponsor'], 3) - } -} diff --git a/apps/desktop/src/main/services/ads/UnavailableAdAdapter.ts b/apps/desktop/src/main/services/ads/UnavailableAdAdapter.ts index b742113..419c26b 100644 --- a/apps/desktop/src/main/services/ads/UnavailableAdAdapter.ts +++ b/apps/desktop/src/main/services/ads/UnavailableAdAdapter.ts @@ -1,6 +1,70 @@ import type { AdFormat, AdMediationAuctionRequest, AdNetworkId } from '@d3ro/core/types' import type { AdBidResponse, IAdNetworkAdapter } from './BaseAdAdapter' +export interface UnavailableAdNetworkSpec { + readonly networkId: AdNetworkId + readonly networkName: string + readonly supportedFormats: AdFormat[] + readonly defaultFloorEcpm: number +} + +export const UNAVAILABLE_AD_NETWORK_SPECS: readonly UnavailableAdNetworkSpec[] = [ + { + networkId: 'playwire', + networkName: 'Playwire RAMP', + supportedFormats: ['banner_dock', 'rewarded_video', 'export_sponsor'], + defaultFloorEcpm: 4.5, + }, + { + networkId: 'ethical_ads', + networkName: 'EthicalAds', + supportedFormats: ['banner_dock', 'export_sponsor'], + defaultFloorEcpm: 3.2, + }, + { + networkId: 'carbon_ads', + networkName: 'Carbon Ads', + supportedFormats: ['banner_dock'], + defaultFloorEcpm: 3.5, + }, + { + networkId: 'unity_ads', + networkName: 'Unity LevelPlay', + supportedFormats: ['rewarded_video', 'banner_dock'], + defaultFloorEcpm: 6, + }, + { + networkId: 'applovin_max', + networkName: 'AppLovin MAX', + supportedFormats: ['rewarded_video', 'banner_dock', 'export_sponsor'], + defaultFloorEcpm: 5.5, + }, + { + networkId: 'google_ad_manager', + networkName: 'Google Ad Manager', + supportedFormats: ['banner_dock', 'rewarded_video', 'export_sponsor'], + defaultFloorEcpm: 2, + }, + { + networkId: 'inmobi', + networkName: 'InMobi', + supportedFormats: ['banner_dock', 'rewarded_video'], + defaultFloorEcpm: 2.8, + }, + { + networkId: 'pubmatic', + networkName: 'PubMatic OpenWrap', + supportedFormats: ['banner_dock', 'export_sponsor'], + defaultFloorEcpm: 3, + }, + { + networkId: 'mintegral', + networkName: 'Mintegral', + supportedFormats: ['rewarded_video', 'banner_dock'], + defaultFloorEcpm: 4, + }, +] + /** * Fail-closed boundary for providers whose official desktop SDK or * authenticated decision endpoint is not integrated. Demo creatives are not @@ -35,3 +99,15 @@ export class UnavailableAdAdapter implements IAdNetworkAdapter { return { success: false, tokenReward: 0 } } } + +export function createUnavailableAdAdapters(): UnavailableAdAdapter[] { + return UNAVAILABLE_AD_NETWORK_SPECS.map( + (spec) => + new UnavailableAdAdapter( + spec.networkId, + spec.networkName, + [...spec.supportedFormats], + spec.defaultFloorEcpm, + ), + ) +} diff --git a/apps/desktop/src/main/services/ads/UnityAdsAdapter.ts b/apps/desktop/src/main/services/ads/UnityAdsAdapter.ts deleted file mode 100644 index ce3a339..0000000 --- a/apps/desktop/src/main/services/ads/UnityAdsAdapter.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { UnavailableAdAdapter } from './UnavailableAdAdapter' - -export class UnityAdsAdapter extends UnavailableAdAdapter { - constructor() { - super('unity_ads', 'Unity LevelPlay', ['rewarded_video', 'banner_dock'], 6) - } -} diff --git a/apps/desktop/src/main/services/dictionary/dictionary-file-codec.ts b/apps/desktop/src/main/services/dictionary/dictionary-file-codec.ts index b338e29..62ed3f3 100644 --- a/apps/desktop/src/main/services/dictionary/dictionary-file-codec.ts +++ b/apps/desktop/src/main/services/dictionary/dictionary-file-codec.ts @@ -2,6 +2,8 @@ // 사전 내보내기/가져오기 파일 형식(CSV·JSON) — 순수 함수만 둔다 (fs/dialog/DB/동기화 의존 없음). // DictionaryService 는 파일 IO·DB 쓰기·동기화 push 만 맡고, 형식 변환과 행 검증은 여기서 한다. +import { csvCell, parseCsvRows } from '@d3ro/core/csv' +import { isRecord } from '@d3ro/core/guards' import { validateDictionaryDraft, type DictionaryWriteProblem } from '@d3ro/core/dictionary-policy' import type { DictionaryEntry } from '@d3ro/core/types' @@ -16,56 +18,6 @@ export const DICTIONARY_CSV_HEADER = [ 'updatedAt' ] as const -function csvCell(value: unknown): string { - const text = value === null || value === undefined ? '' : String(value) - const escaped = text.replace(/"/g, '""') - const needsQuotes = /[",\r\n]/.test(escaped) || /^[=+\-@]/.test(escaped) - return needsQuotes ? `"${escaped}"` : escaped -} - -function parseCsvRows(input: string): string[][] { - const rows: string[][] = [] - let row: string[] = [] - let field = '' - let inQuotes = false - for (let i = 0; i < input.length; i += 1) { - const char = input[i] - if (inQuotes) { - if (char === '"') { - if (input[i + 1] === '"') { - field += '"' - i += 1 - } else { - inQuotes = false - } - } else { - field += char - } - continue - } - if (char === '"') { - inQuotes = true - } else if (char === ',') { - row.push(field) - field = '' - } else if (char === '\n') { - row.push(field) - rows.push(row) - row = [] - field = '' - } else if (char === '\r') { - // skip CR; LF terminates the row - } else { - field += char - } - } - if (field.length > 0 || row.length > 0) { - row.push(field) - rows.push(row) - } - return rows.filter((candidate) => candidate.some((cell) => cell.trim().length > 0)) -} - function pickString(source: Record, keys: string[]): string | null { for (const key of keys) { const value = source[key] @@ -134,9 +86,7 @@ function parseJson(raw: string): Array> { } else { throw new Error('expected an array or an object with an "entries" array') } - return (list as unknown[]).filter( - (item): item is Record => !!item && typeof item === 'object' - ) + return (list as unknown[]).filter(isRecord) } function parseCsv(raw: string): Array> { diff --git a/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts b/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts index 7807e51..a747502 100644 --- a/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts +++ b/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts @@ -11,6 +11,7 @@ // Electron·DB 를 모른다. 자막/오디오는 포트로 받는다(테스트는 가짜 포트). import type { CaptionSegment, MeetingMemo } from '@d3ro/core/types' +import type { RecordingAudioSinkPort } from './disk-wav-audio-sink' /** 자막 엔진(CaptionService)에 대한 최소 계약 */ export interface RecordingCaptionPort { @@ -30,6 +31,8 @@ export interface RecordingAudioPort { export interface MeetingRecordingSessionPorts { caption: RecordingCaptionPort audio: RecordingAudioPort + /** 디스크 스트리밍 싱크 — 주입 시 PCM 을 메모리에 쌓지 않고 임시 파일로 곧장 기록한다 */ + audioSink?: RecordingAudioSinkPort now?: () => number /** 세그먼트가 이 녹음에 추가될 때(구독으로 받은 것만) */ onSegment?: (segment: CaptionSegment) => void @@ -37,6 +40,8 @@ export interface MeetingRecordingSessionPorts { onSegmentUpdated?: (update: { id: string; text: string }) => void /** 자막 정지 실패 — 정지는 계속 진행된다(스냅샷은 그때까지의 세그먼트로 만든다) */ onStopError?: (error: unknown) => void + /** 디스크 스트리밍 쓰기/마무리 오류 — 전사 저장을 막지 않고 경고만 남긴다 */ + onAudioSinkError?: (error: unknown) => void } /** 정지 시점의 불변 스냅샷 — 후처리·저장은 이것만 읽는다 */ @@ -47,8 +52,12 @@ export interface RecordingSnapshot { readonly durationMs: number readonly segments: readonly CaptionSegment[] readonly memos: readonly MeetingMemo[] - /** 녹음 PCM (없으면 길이 0) */ + /** 녹음 PCM (디스크 싱크 사용 시 길이 0) */ readonly pcm: Buffer + /** 디스크 싱크가 최종 WAV 파일로 저장을 마쳤는지 */ + readonly audioSavedToDisk: boolean + /** 총 녹음 PCM 바이트 길이 (메모리 또는 디스크 싱크 기준) */ + readonly pcmByteLength: number } export class MeetingRecordingSession { @@ -56,6 +65,7 @@ export class MeetingRecordingSession { private _segments: CaptionSegment[] = [] private _memos: MeetingMemo[] = [] private _audio: Buffer[] = [] + private _audioSinkBroken = false private _lastRms = 0 private _unsubscribeSegment: (() => void) | null = null private _unsubscribeSegmentUpdated: (() => void) | null = null @@ -93,7 +103,18 @@ export class MeetingRecordingSession { if (this._unsubscribeAudio || this._stopPromise) return this._unsubscribeAudio = this._ports.audio.onChunk((buffer) => { this._lastRms = this._measureLevel(buffer) - this._audio.push(Buffer.from(buffer)) + if (this._ports.audioSink) { + if (this._audioSinkBroken) return + try { + this._ports.audioSink.append(buffer) + } catch (err) { + this._audioSinkBroken = true + this._ports.audioSink.discard() + this._ports.onAudioSinkError?.(err) + } + } else { + this._audio.push(Buffer.from(buffer)) + } }) } @@ -105,6 +126,9 @@ export class MeetingRecordingSession { this._unsubscribeSegmentUpdated = null this._unsubscribeAudio?.() this._unsubscribeAudio = null + if (!this._stopPromise) { + this._ports.audioSink?.discard() + } } get isStopping(): boolean { @@ -188,6 +212,31 @@ export class MeetingRecordingSession { } private _freeze(endedAt: number, includeAudio = true): RecordingSnapshot { + let audioSavedToDisk = false + let pcmByteLength = 0 + let pcm = Buffer.alloc(0) + + if (this._ports.audioSink) { + if (includeAudio) { + // shutdown() 처럼 stop() 없이 최종 오디오를 마무리할 때도 추가 쓰기를 먼저 끊는다. + this._unsubscribeAudio?.() + this._unsubscribeAudio = null + try { + const finalized = this._ports.audioSink.finalize() + audioSavedToDisk = finalized.saved + pcmByteLength = finalized.pcmByteLength + } catch (err) { + this._ports.audioSink.discard() + this._ports.onAudioSinkError?.(err) + } + } else { + pcmByteLength = this._ports.audioSink.pcmByteLength + } + } else if (includeAudio && this._audio.length > 0) { + pcm = Buffer.concat(this._audio) + pcmByteLength = pcm.length + } + return Object.freeze({ id: this.id, startedAt: this.startedAt, @@ -195,7 +244,9 @@ export class MeetingRecordingSession { durationMs: Math.max(0, endedAt - this.startedAt), segments: Object.freeze(this._segments.map((segment) => ({ ...segment }))), memos: Object.freeze(this._memos.map((memo) => ({ ...memo }))), - pcm: includeAudio && this._audio.length > 0 ? Buffer.concat(this._audio) : Buffer.alloc(0), + pcm, + audioSavedToDisk, + pcmByteLength, }) } } diff --git a/apps/desktop/src/main/services/meeting/disk-wav-audio-sink.ts b/apps/desktop/src/main/services/meeting/disk-wav-audio-sink.ts new file mode 100644 index 0000000..40cc1dd --- /dev/null +++ b/apps/desktop/src/main/services/meeting/disk-wav-audio-sink.ts @@ -0,0 +1,131 @@ +// src/main/services/meeting/disk-wav-audio-sink.ts +// GAP-PERF-01 잔여: 장시간 회의 녹음 시 PCM 청크를 메모리에 누적하지 않고 +// 임시 `.wav.part` 디스크 파일로 즉시 스트리밍한 뒤 종료 시 44B RIFF/WAVE 헤더를 기록한다. + +import fs from 'fs' +import path from 'path' + +export interface RecordingAudioSinkResult { + readonly saved: boolean + readonly pcmByteLength: number +} + +export interface RecordingAudioSinkPort { + readonly pcmByteLength: number + append(chunk: Buffer): void + finalize(): RecordingAudioSinkResult + discard(): void +} + +const WAV_HEADER_BYTES = 44 +const SAMPLE_RATE = 16000 +const NUM_CHANNELS = 1 +const BITS_PER_SAMPLE = 16 +export const MAX_WAV_DATA_BYTES = 0xffffffff - 36 + +/** 16kHz mono 16-bit PCM WAV 헤더(44바이트)를 채운다. */ +export function writeWavHeader16kMonoPcm16(header: Buffer, dataSize: number): Buffer { + if (!Number.isSafeInteger(dataSize) || dataSize < 0 || dataSize > MAX_WAV_DATA_BYTES) { + throw new RangeError( + `WAV data size exceeds uint32 RIFF limit (0..${MAX_WAV_DATA_BYTES}): ${dataSize}`, + ) + } + const byteRate = SAMPLE_RATE * NUM_CHANNELS * (BITS_PER_SAMPLE / 8) + const blockAlign = NUM_CHANNELS * (BITS_PER_SAMPLE / 8) + header.write('RIFF', 0) + header.writeUInt32LE(36 + dataSize, 4) + header.write('WAVE', 8) + header.write('fmt ', 12) + header.writeUInt32LE(16, 16) + header.writeUInt16LE(1, 20) + header.writeUInt16LE(NUM_CHANNELS, 22) + header.writeUInt32LE(SAMPLE_RATE, 24) + header.writeUInt32LE(byteRate, 28) + header.writeUInt16LE(blockAlign, 32) + header.writeUInt16LE(BITS_PER_SAMPLE, 34) + header.write('data', 36) + header.writeUInt32LE(dataSize, 40) + return header +} + +export class DiskWavAudioSink implements RecordingAudioSinkPort { + readonly tempPartPath: string + private _fd: number | null = null + private _pcmByteLength = 0 + private _finalized: RecordingAudioSinkResult | null = null + private _discarded = false + + constructor(readonly targetWavPath: string) { + this.tempPartPath = `${targetWavPath}.part` + } + + get pcmByteLength(): number { + return this._pcmByteLength + } + + append(chunk: Buffer): void { + if (this._discarded || this._finalized !== null || chunk.length === 0) return + const nextByteLength = this._pcmByteLength + chunk.length + if (nextByteLength > MAX_WAV_DATA_BYTES) { + throw new RangeError( + `WAV data size exceeds uint32 RIFF limit (${nextByteLength} > ${MAX_WAV_DATA_BYTES})`, + ) + } + if (this._fd === null) { + fs.mkdirSync(path.dirname(this.targetWavPath), { recursive: true }) + this._fd = fs.openSync(this.tempPartPath, 'w+') + try { + fs.writeSync(this._fd, Buffer.alloc(WAV_HEADER_BYTES), 0, WAV_HEADER_BYTES, 0) + } catch (err) { + this._closeAndRemovePart() + throw err + } + } + fs.writeSync(this._fd, chunk, 0, chunk.length, WAV_HEADER_BYTES + this._pcmByteLength) + this._pcmByteLength = nextByteLength + } + + finalize(): RecordingAudioSinkResult { + if (this._finalized !== null) return this._finalized + if (this._discarded || this._fd === null || this._pcmByteLength === 0) { + this._closeAndRemovePart() + this._finalized = Object.freeze({ saved: false, pcmByteLength: 0 }) + return this._finalized + } + + const header = writeWavHeader16kMonoPcm16(Buffer.alloc(WAV_HEADER_BYTES), this._pcmByteLength) + try { + fs.writeSync(this._fd, header, 0, WAV_HEADER_BYTES, 0) + } finally { + fs.closeSync(this._fd) + this._fd = null + } + + fs.rmSync(this.targetWavPath, { force: true }) + fs.renameSync(this.tempPartPath, this.targetWavPath) + this._finalized = Object.freeze({ saved: true, pcmByteLength: this._pcmByteLength }) + return this._finalized + } + + discard(): void { + if (this._discarded || this._finalized !== null) return + this._discarded = true + this._closeAndRemovePart() + } + + private _closeAndRemovePart(): void { + if (this._fd !== null) { + try { + fs.closeSync(this._fd) + } catch { + // 이미 닫혔거나 디스크 핸들 정리 실패는 무시 + } + this._fd = null + } + try { + fs.rmSync(this.tempPartPath, { force: true }) + } catch { + // 임시 파일 제거 실패는 무시 + } + } +} diff --git a/apps/desktop/src/main/services/rag/chunk-store.ts b/apps/desktop/src/main/services/rag/chunk-store.ts index 25bab76..f72b3f6 100644 --- a/apps/desktop/src/main/services/rag/chunk-store.ts +++ b/apps/desktop/src/main/services/rag/chunk-store.ts @@ -1,11 +1,15 @@ // src/main/services/rag/chunk-store.ts -// 지식 문서·청크 저장소 포트와 SQLite(drizzle) 구현. RAGService는 getDatabase()를 직접 부르지 않는다. +// 지식 문서·청크 저장소 포트와 SQLite(drizzle) 구현. +// 임베딩은 Float32 바이너리 BLOB 으로 직렬화하고 DB 인스턴스별 WeakMap 에 캐시해 질의 시 JSON.parse 를 0회로 줄인다. -import { asc, eq } from 'drizzle-orm' -import { getDatabase } from '../../db' +import { asc, eq, isNotNull, ne, or, sql } from 'drizzle-orm' +import { getDatabase, isDatabaseOpen } from '../../db' import { ragChunks, ragDocuments } from '../../db/schema' +import { getLogger } from '../LoggerService' import type { RAGDocument } from '@d3ro/core/types' +const logger = getLogger('SqliteChunkStore') + export type StoredDocument = RAGDocument export interface StoredChunk { @@ -15,6 +19,8 @@ export interface StoredChunk { /** JSON 직렬화 float[]. 아직 임베딩하지 않았으면 빈 문자열. */ embedding: string chunkIndex: number + /** 디코딩된 Float32 벡터 (listEmbeddedChunks 캐시에서 채워진다) */ + vector?: Float32Array } export interface ChunkStore { @@ -36,6 +42,68 @@ export interface ChunkStore { counts(): { documentCount: number; totalChunks: number } } +/** DB 인스턴스(계정별·테스트별)마다 자동 격리되는 임베딩 청크 메모리 캐시 */ +const embeddedChunksCache = new WeakMap() + +/** + * 외부 경로(동기화 어댑터, DB 초기화·임포트·종료 등)에서 `rag_documents`/`rag_chunks`를 + * 변경·삭제한 뒤 stale 임베딩 캐시를 비운다. + */ +export function invalidateEmbeddedChunksCache(dbInstance?: object): void { + if (dbInstance) { + embeddedChunksCache.delete(dbInstance) + return + } + if (typeof isDatabaseOpen === 'function' && !isDatabaseOpen()) { + return + } + try { + embeddedChunksCache.delete(getDatabase()) + } catch { + // DB가 열려 있지 않거나 테스트 partial mock 환경이면 조용히 건너뛴다. + } +} + +function encodeFloat32Buffer(embedding: readonly number[]): Buffer { + const vector = Float32Array.from(embedding) + return Buffer.from(vector.buffer, vector.byteOffset, vector.byteLength) +} + +export function decodeFloat32Buffer( + blob: Buffer | null | undefined, + jsonFallback: string, +): Float32Array | undefined { + if (blob && blob.byteLength >= 4 && blob.byteLength % 4 === 0) { + const aligned = blob.buffer.slice(blob.byteOffset, blob.byteOffset + blob.byteLength) + return new Float32Array(aligned) + } + if (jsonFallback.length > 0) { + try { + const parsed: unknown = JSON.parse(jsonFallback) + if (!Array.isArray(parsed) || parsed.length === 0) { + logger.warn('Skipping RAG chunk with non-array or empty JSON embedding fallback') + return undefined + } + const vec = new Float32Array(parsed.length) + for (let i = 0; i < parsed.length; i++) { + const value = parsed[i] + if (typeof value !== 'number' || !Number.isFinite(value)) { + logger.warn(`Skipping RAG chunk with non-finite embedding value at index ${i}`) + return undefined + } + vec[i] = value + } + return vec + } catch (err) { + logger.warn( + `Skipping RAG chunk with malformed JSON embedding fallback: ${err instanceof Error ? err.message : String(err)}`, + ) + return undefined + } + } + return undefined +} + function toDocument(r: typeof ragDocuments.$inferSelect): StoredDocument { return { id: r.id, @@ -73,24 +141,48 @@ export class SqliteChunkStore implements ChunkStore { removeDocument(id: string): boolean { const db = getDatabase() - db.delete(ragChunks).where(eq(ragChunks.documentId, id)).run() - return db.delete(ragDocuments).where(eq(ragDocuments.id, id)).run().changes > 0 + try { + return db.transaction((tx) => { + tx.delete(ragChunks).where(eq(ragChunks.documentId, id)).run() + return tx.delete(ragDocuments).where(eq(ragDocuments.id, id)).run().changes > 0 + }) + } finally { + invalidateEmbeddedChunksCache(db) + } } replaceChunks(documentId: string, chunks: readonly string[]): void { - getDatabase().transaction((tx) => { - tx.delete(ragChunks).where(eq(ragChunks.documentId, documentId)).run() - chunks.forEach((content, index) => { - tx.insert(ragChunks) - .values({ id: crypto.randomUUID(), documentId, content, embedding: '', chunkIndex: index }) - .run() + const db = getDatabase() + try { + db.transaction((tx) => { + tx.delete(ragChunks).where(eq(ragChunks.documentId, documentId)).run() + chunks.forEach((content, index) => { + tx.insert(ragChunks) + .values({ + id: crypto.randomUUID(), + documentId, + content, + embedding: '', + embeddingBlob: null, + chunkIndex: index, + }) + .run() + }) }) - }) + } finally { + invalidateEmbeddedChunksCache(db) + } } listChunks(documentId: string): StoredChunk[] { return getDatabase() - .select() + .select({ + id: ragChunks.id, + documentId: ragChunks.documentId, + content: ragChunks.content, + embedding: ragChunks.embedding, + chunkIndex: ragChunks.chunkIndex, + }) .from(ragChunks) .where(eq(ragChunks.documentId, documentId)) .orderBy(asc(ragChunks.chunkIndex)) @@ -98,18 +190,56 @@ export class SqliteChunkStore implements ChunkStore { } setEmbedding(chunkId: string, embedding: readonly number[]): void { - getDatabase().update(ragChunks).set({ embedding: JSON.stringify(embedding) }).where(eq(ragChunks.id, chunkId)).run() + const db = getDatabase() + try { + db.update(ragChunks) + .set({ + embedding: JSON.stringify(embedding), + embeddingBlob: encodeFloat32Buffer(embedding), + }) + .where(eq(ragChunks.id, chunkId)) + .run() + } finally { + invalidateEmbeddedChunksCache(db) + } } listEmbeddedChunks(): StoredChunk[] { - return getDatabase().select().from(ragChunks).all().filter((c) => c.embedding.length > 0) + const db = getDatabase() + const cached = embeddedChunksCache.get(db) + if (cached) return cached + + const rows = db + .select() + .from(ragChunks) + .where(or(ne(ragChunks.embedding, ''), isNotNull(ragChunks.embeddingBlob))) + .all() + + const loaded: StoredChunk[] = [] + for (const row of rows) { + const vector = decodeFloat32Buffer(row.embeddingBlob, row.embedding) + if (!vector) continue + // Float32Array 로 디코딩한 뒤 다중 KB JSON 문자열은 캐시에 중복 보관하지 않는다. + loaded.push({ + id: row.id, + documentId: row.documentId, + content: row.content, + embedding: '', + chunkIndex: row.chunkIndex, + vector, + }) + } + embeddedChunksCache.set(db, loaded) + return loaded } counts(): { documentCount: number; totalChunks: number } { const db = getDatabase() + const docRow = db.select({ value: sql`count(*)` }).from(ragDocuments).get() + const chunkRow = db.select({ value: sql`count(*)` }).from(ragChunks).get() return { - documentCount: db.select({ id: ragDocuments.id }).from(ragDocuments).all().length, - totalChunks: db.select({ id: ragChunks.id }).from(ragChunks).all().length, + documentCount: Number(docRow?.value ?? 0), + totalChunks: Number(chunkRow?.value ?? 0), } } } diff --git a/apps/desktop/src/main/services/rag/retrieval.ts b/apps/desktop/src/main/services/rag/retrieval.ts index 2caee38..79b647a 100644 --- a/apps/desktop/src/main/services/rag/retrieval.ts +++ b/apps/desktop/src/main/services/rag/retrieval.ts @@ -1,5 +1,5 @@ // src/main/services/rag/retrieval.ts -// 벡터 검색과 답변 프롬프트 조립 — 순수 함수(RAGService에서 옮김, 동작 동일). +// 벡터 검색과 답변 프롬프트 조립 — 순수 함수(Float32Array 직접 연산 지원으로 JSON.parse 제거). import type { RAGQueryResult } from '@d3ro/core/types' @@ -8,24 +8,43 @@ export type RetrievedChunk = RAGQueryResult['results'][number] export interface EmbeddedChunk { documentId: string content: string - /** JSON 직렬화 float[] */ + /** JSON 직렬화 float[] (호환/폴백용) */ embedding: string + /** 미리 디코딩된 Float32Array 또는 수치 배열 (있으면 JSON.parse 생략) */ + vector?: ArrayLike } -export function cosineSimilarity(a: readonly number[], b: readonly number[]): number { +export function cosineSimilarity(a: ArrayLike, b: ArrayLike): number { if (a.length !== b.length) return 0 let dotProduct = 0 let normA = 0 let normB = 0 for (let i = 0; i < a.length; i++) { - dotProduct += a[i] * b[i] - normA += a[i] * a[i] - normB += b[i] * b[i] + const ai = a[i] + const bi = b[i] + dotProduct += ai * bi + normA += ai * ai + normB += bi * bi } const denom = Math.sqrt(normA) * Math.sqrt(normB) return denom === 0 ? 0 : dotProduct / denom } +function resolveChunkVector(chunk: EmbeddedChunk): ArrayLike | undefined { + if (chunk.vector && chunk.vector.length > 0) return chunk.vector + if (!chunk.embedding) return undefined + try { + const parsed: unknown = JSON.parse(chunk.embedding) + if (!Array.isArray(parsed) || parsed.length === 0) return undefined + for (let i = 0; i < parsed.length; i++) { + if (typeof parsed[i] !== 'number' || !Number.isFinite(parsed[i])) return undefined + } + return parsed as number[] + } catch { + return undefined + } +} + /** 질의 임베딩과 가장 가까운 청크 topK개 (유사도 내림차순). */ export function rankChunks( queryEmbedding: readonly number[], @@ -33,12 +52,17 @@ export function rankChunks( fileNames: ReadonlyMap, topK: number ): RetrievedChunk[] { - const scored = chunks.map((chunk) => ({ - documentId: chunk.documentId, - fileName: fileNames.get(chunk.documentId) ?? 'unknown', - content: chunk.content, - similarity: cosineSimilarity(queryEmbedding, JSON.parse(chunk.embedding) as number[]), - })) + const scored: RetrievedChunk[] = [] + for (const chunk of chunks) { + const vector = resolveChunkVector(chunk) + if (!vector) continue + scored.push({ + documentId: chunk.documentId, + fileName: fileNames.get(chunk.documentId) ?? 'unknown', + content: chunk.content, + similarity: cosineSimilarity(queryEmbedding, vector), + }) + } scored.sort((a, b) => b.similarity - a.similarity) return scored.slice(0, topK) } diff --git a/apps/desktop/src/main/services/runtime/runtime-index.ts b/apps/desktop/src/main/services/runtime/runtime-index.ts index 8e55f48..f2607cb 100644 --- a/apps/desktop/src/main/services/runtime/runtime-index.ts +++ b/apps/desktop/src/main/services/runtime/runtime-index.ts @@ -7,6 +7,7 @@ // 부품 이름도 검증하지 않아 `..\` 같은 이름이 임시 폴더 밖 경로로 이어질 수 있었다. // 여기서 한 번에 검증하고, 검증을 통과한 값만 설치 단계로 넘긴다. +import { isRecord } from '@d3ro/core/guards' import { D3ROError, ErrorCode } from '@d3ro/core/errors' import { compareVersions } from '../../update-policy' @@ -118,9 +119,6 @@ function invalid(detail: string): D3ROError { return new D3ROError(ErrorCode.ConfigReadFailed, `런타임 인덱스 형식이 올바르지 않습니다: ${detail}`) } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} /** 임시 폴더 안에만 놓일 수 있는 단순 파일 이름인지 (경로 구분자·`..` 금지) */ function isSafeFileName(value: unknown): value is string { diff --git a/apps/desktop/src/main/services/stt/STTManager.ts b/apps/desktop/src/main/services/stt/STTManager.ts index ee19f0f..2b3318b 100644 --- a/apps/desktop/src/main/services/stt/STTManager.ts +++ b/apps/desktop/src/main/services/stt/STTManager.ts @@ -165,6 +165,9 @@ export class STTManager extends EventEmitter implements STTEngine { setProvider(provider: STTProviderType): void { logger.info(`STT provider changed to: ${provider}`) configSet('sttProvider', provider) + if (provider !== 'local') { + void getLocalSTTService().releasePrimaryModel() + } this.emit('provider-changed', { provider }) } diff --git a/apps/desktop/src/main/services/suggestion/suggestion-policy-helpers.ts b/apps/desktop/src/main/services/suggestion/suggestion-policy-helpers.ts new file mode 100644 index 0000000..5102e9c --- /dev/null +++ b/apps/desktop/src/main/services/suggestion/suggestion-policy-helpers.ts @@ -0,0 +1,220 @@ +// src/main/services/suggestion/suggestion-policy-helpers.ts +// SuggestionService에서 사용하는 순수 정책·후보 중복/재정렬·오타교정·터미널 문맥 계산기. + +import { + SUGGESTION_DEFAULTS, + SUGGESTION_MAX_OUTPUT_CHARS, + extractTerminalPromptPrefix, + type SuggestionCandidate, + type SuggestionCorrection +} from '@d3ro/core/input-intelligence' +import { scoreCandidatePersonalization } from '@d3ro/core/personal-graph' +import type { TypingContext } from '../InputTelemetryService' + +/** 설정에서 읽은 정책 값 (SSOT 기본값과 상한 적용 후). */ +export interface SuggestionPolicyConfig { + triggerDelayMs: number + minPrefixChars: number + maxRequestsPerMinute: number + dailyBudget: number + maxCandidates: number + maxChars: number + excludedApps: string[] +} + +export interface RawSuggestionPolicyConfigInput { + triggerDelayMs?: number | null + minPrefixChars?: number | null + maxRequestsPerMinute?: number | null + dailyBudget?: number | null + excludedApps?: readonly string[] | null +} + +export interface CandidatePersonalizationInput { + prefix: string + continuationHints: string[] + followUpHints: string[] + relatedHints: string[] + phraseHints: string[] +} + +export interface TypoCorrectionPlanLike { + originalText: string + insertText: string + corrections: ReadonlyArray<{ start: number; end: number; to: string }> +} + +export interface TerminalPromptTrackingState { + lastPrompt: string | null + promptTyped: boolean +} + +/** + * 스냅샷 한 번(약 0.8초) 사이에 사람이 칠 수 있는 글자 수 상한. 빈 터미널 입력칸이 이보다 크게 + * 한 번에 채워지면 타이핑이 아니다(Claude Code 의 회색 추천 문구). + */ +export const TERMINAL_TYPING_STEP_CHARS = 8 + +/** 교정을 적용한 문맥 — 모델에는 고친 글을 보여 주고, 세션 비교는 원문으로 한다. */ +export function applyCorrectionToContext( + context: TypingContext, + correction: SuggestionCorrection +): TypingContext { + const replaceTail = (text: string): string => + text.endsWith(correction.from) ? text.slice(0, text.length - correction.from.length) + correction.to : text + return { + ...context, + prefix: replaceTail(context.prefix), + documentBefore: context.documentBefore == null ? context.documentBefore : replaceTail(context.documentBefore) + } +} + +/** 공백·끝 문장부호를 무시하고 같은 후보인가 */ +export function sameCandidateText(a: string, b: string): boolean { + const norm = (text: string): string => text.replace(/\s+/gu, ' ').replace(/[.!?。!?…,]+$/u, '').trim() + return norm(a) === norm(b) +} + +export function commonPrefixLength(a: string, b: string): number { + const max = Math.min(a.length, b.length) + let index = 0 + while (index < max && a[index] === b[index]) index += 1 + return index +} + +/** 정규화 후 완전 중복이거나 기존 후보의 접두/확장이면 중복으로 본다. */ +export function isDuplicateCandidateText( + candidate: string, + existingCandidates: ReadonlyArray> +): boolean { + const normalized = candidate.replace(/\s+/gu, ' ').trim().toLowerCase() + return existingCandidates.some((existing) => { + const existingNormalized = existing.text.replace(/\s+/gu, ' ').trim().toLowerCase() + return ( + existingNormalized === normalized || + existingNormalized.startsWith(normalized) || + normalized.startsWith(existingNormalized) + ) + }) +} + +/** 채우기 후보가 개인화 점수 임계(>=1.5)를 넘으면 개인 후보 뒤에 개인화 점수순으로 재정렬한다. */ +export function rerankFilledCandidates( + candidates: readonly SuggestionCandidate[], + newCandidateText: string, + personalContext: CandidatePersonalizationInput +): SuggestionCandidate[] { + if (candidates.length < 2) { + return candidates.map((item, index) => ({ ...item, rank: index })) + } + const newScore = scoreCandidatePersonalization(newCandidateText, personalContext) + if (newScore < 1.5) { + return candidates.map((item, index) => ({ ...item, rank: index })) + } + const personalItems = candidates.filter((item) => item.source === 'personal') + const modelItems = candidates + .filter((item) => item.source !== 'personal') + .map((item, idx) => ({ + item, + idx, + score: scoreCandidatePersonalization(item.text, personalContext) + })) + .sort((a, b) => (Math.abs(b.score - a.score) >= 0.8 ? b.score - a.score : a.idx - b.idx)) + .map((entry) => entry.item) + + return [...personalItems, ...modelItems].map((item, index) => ({ + ...item, + rank: index + })) +} + +export function normalizeSuggestionPolicyConfig( + raw: RawSuggestionPolicyConfigInput +): SuggestionPolicyConfig { + return { + triggerDelayMs: Math.max( + SUGGESTION_DEFAULTS.minTriggerDelayMs, + raw.triggerDelayMs || SUGGESTION_DEFAULTS.triggerDelayMs + ), + minPrefixChars: raw.minPrefixChars || SUGGESTION_DEFAULTS.minPrefixChars, + maxRequestsPerMinute: Math.min( + raw.maxRequestsPerMinute || SUGGESTION_DEFAULTS.maxRequestsPerMinute, + 30 + ), + dailyBudget: raw.dailyBudget || SUGGESTION_DEFAULTS.dailyBudget, + maxCandidates: SUGGESTION_DEFAULTS.maxCandidates, + maxChars: SUGGESTION_MAX_OUTPUT_CHARS, + excludedApps: raw.excludedApps ? [...raw.excludedApps] : [] + } +} + +export function toSuggestionCorrectionFromPlan( + prefix: string, + plan: TypoCorrectionPlanLike | null | undefined +): SuggestionCorrection | undefined { + if (!plan || !prefix.endsWith(plan.originalText)) return undefined + const base = plan.corrections[0]?.start ?? 0 + return { + from: plan.originalText, + to: plan.insertText, + edits: plan.corrections.map((edit) => ({ + start: edit.start - base, + end: edit.end - base, + to: edit.to + })) + } +} + +export function buildDecisionInputSignature( + context: TypingContext, + runtime: { modelAvailable: boolean; enabled: boolean } +): string { + return [ + context.available, + context.isEditable, + context.isPassword, + context.isComposing, + context.anchor ? 'A' : '-', + context.editedSinceFocus, + context.typedRecently, + runtime.modelAvailable, + runtime.enabled + ].join('|') +} + +export function resolveTerminalTypingContext( + input: TypingContext, + state: TerminalPromptTrackingState +): { context: TypingContext; nextState: TerminalPromptTrackingState } { + if (input.vimMode === 'normal' || input.vimMode === 'command') { + return { + context: { ...input, prefix: '', documentBefore: null, caretReliable: false }, + nextState: { lastPrompt: '', promptTyped: false } + } + } + const extracted = extractTerminalPromptPrefix(input.fullText ?? input.prefix) + const prompt = extracted ?? (input.terminalMode ? input.prefix : null) + const previous = state.lastPrompt + let typed: boolean + if (prompt === null) typed = false + else if (prompt.length === 0) typed = true + else if (previous === null) typed = prompt.length <= TERMINAL_TYPING_STEP_CHARS + else if (prompt === previous) typed = state.promptTyped + else if (previous.length === 0 && prompt.length > TERMINAL_TYPING_STEP_CHARS) { + typed = false + } else { + typed = commonPrefixLength(previous, prompt) >= Math.min(previous.length, prompt.length) - 2 + } + return { + context: { + ...input, + prefix: prompt ?? '', + documentBefore: null, + caretReliable: extracted !== null ? typed : typed && input.caretReliable !== false + }, + nextState: { + lastPrompt: prompt, + promptTyped: typed + } + } +} diff --git a/apps/desktop/src/main/services/sync/sync-adapters.ts b/apps/desktop/src/main/services/sync/sync-adapters.ts index ab36886..93828d0 100644 --- a/apps/desktop/src/main/services/sync/sync-adapters.ts +++ b/apps/desktop/src/main/services/sync/sync-adapters.ts @@ -16,6 +16,7 @@ import { getCustomInstructionService, instructionLimitViolation } from '../Custo import { getDictationTemplateService } from '../DictationTemplateService' import { getMeetingDocTemplateService } from '../MeetingDocTemplateService' import { getRAGService } from '../RAGService' +import { invalidateEmbeddedChunksCache } from '../rag/chunk-store' import { deleteHistoryLocally } from '../history-deletion' import { purgeRemoteAudio } from './audio-sync' import { pushMeetingSegments } from './transcript-sync' @@ -578,14 +579,25 @@ const meetingMemosAdapter: SyncAdapter = { // 부모 회의가 아직 로컬에 없으면 고아 행을 만들지 않고 미룬다(회의 pull이 실패했을 수 있다). // 남의 팀 회의에 단 내 메모는 끝내 부모가 오지 않는다 — 엔진이 몇 번 재시도 후 포기한다. if (!hasLocalMeeting(meetingId)) return 'deferred' + const db = getDatabase() const createdAt = ms(row.created_at, Date.now()) + const remoteRevision = Math.max(1, int(num(row.revision)) ?? 1) + const existing = db + .select({ revision: meetingMemos.revision }) + .from(meetingMemos) + .where(eq(meetingMemos.id, id)) + .get() + if (existing && row.revision !== undefined && remoteRevision < existing.revision) { + return true + } const values = { sessionId: meetingId, content, timestampMs: int(num(row.timestamp_ms)) ?? 0, + revision: existing ? Math.max(existing.revision, remoteRevision) : remoteRevision, updatedAt: ms(row.updated_at, createdAt), } - getDatabase() + db .insert(meetingMemos) .values({ id, ...values, createdAt }) .onConflictDoUpdate({ target: meetingMemos.id, set: values }) @@ -1025,16 +1037,20 @@ const knowledgeAdapter: SyncAdapter = { // (새 문서든 재색인된 문서든) 완성본을 영영 놓친다. 잘린 청크로 로컬을 덮지도 않는다. const chunks = completeKnowledgeChunks(chunkRows, num(row.chunk_count)) if (chunks === null) return 'deferred' - return getRAGService().applyRemoteDocument({ + const applied = getRAGService().applyRemoteDocument({ id, fileName: str(row.file_name) ?? str(row.title) ?? 'document', fileType: oneOf(row.file_type, KNOWLEDGE_TYPES) ?? 'txt', chunks, addedAt: ms(row.created_at, Date.now()), }) + invalidateEmbeddedChunksCache() + return applied }, deleteLocal(id) { - return getRAGService().removeRemote(id) + const removed = getRAGService().removeRemote(id) + invalidateEmbeddedChunksCache() + return removed }, } diff --git a/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts b/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts index 28bd7d2..367eda9 100644 --- a/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts +++ b/apps/desktop/src/main/services/text-insert/nut-keyboard-port.ts @@ -4,7 +4,14 @@ import type { Key as NutKey } from '@nut-tree-fork/nut-js' import { getLogger } from '../LoggerService' -import { sendWin32UnicodeReplacement, sendWin32UnicodeText } from '../../utils/win32-unicode-input' +import { + isWin32SendInputAvailable, + sendWin32Backspaces, + sendWin32PasteChord, + sendWin32SpaceKey, + sendWin32UnicodeReplacement, + sendWin32UnicodeText, +} from '../../utils/win32-unicode-input' import { D3ROError, ErrorCode } from '@d3ro/core/errors' const logger = getLogger('TextInsertService') @@ -99,8 +106,15 @@ export class NutKeyboardPort implements KeyboardPort { private readonly _load: NutModuleLoader = loadNutModule ) {} + private _useWin32NativeSendInput(): boolean { + return this._platform === 'win32' && this._load === loadNutModule + } + /** 붙여넣기 단축키를 한 번의 코드(chord)로 보내 await 사이에 modifier 가 눌린 채 남지 않게 한다. */ async paste(): Promise { + if (this._useWin32NativeSendInput() && sendWin32PasteChord()) { + return + } const nut = await this._ensureNut() const pasteModKey = this._platform === 'darwin' ? nut.Key.LeftSuper : nut.Key.LeftControl await nut.native.click(pasteModKey, nut.Key.V) @@ -109,7 +123,7 @@ export class NutKeyboardPort implements KeyboardPort { /** 텍스트 전체를 네이티브 호출 한 번으로 타이핑한다 (글자 사이 JS 대기 없음). */ async type(text: string): Promise { if (!text) return - if (this._platform === 'win32' && this._load === loadNutModule && sendWin32UnicodeText(text)) { + if (this._useWin32NativeSendInput() && sendWin32UnicodeText(text)) { return } const nut = await this._ensureNut() @@ -117,6 +131,9 @@ export class NutKeyboardPort implements KeyboardPort { } async commitComposition(): Promise { + if (this._useWin32NativeSendInput() && sendWin32SpaceKey()) { + return + } const nut = await this._ensureNut() await nut.native.click(nut.Key.Space) } @@ -127,8 +144,7 @@ export class NutKeyboardPort implements KeyboardPort { options: { commitComposition?: boolean } = {} ): Promise { if ( - this._platform === 'win32' && - this._load === loadNutModule && + this._useWin32NativeSendInput() && sendWin32UnicodeReplacement(deleteCount, text, options) ) { return true @@ -136,9 +152,12 @@ export class NutKeyboardPort implements KeyboardPort { return false } - /** 백스페이스를 count 번 — 키마다 네이티브 keyTap 한 번이다. */ + /** 백스페이스를 count 번 — Windows 는 단일 SendInput 배치로, 그 외 OS 는 네이티브 keyTap 으로 전송한다. */ async backspace(count: number): Promise { if (count <= 0) return + if (this._useWin32NativeSendInput() && sendWin32Backspaces(count)) { + return + } const nut = await this._ensureNut() for (let index = 0; index < count; index += 1) { await nut.native.click(nut.Key.Backspace) @@ -146,10 +165,13 @@ export class NutKeyboardPort implements KeyboardPort { } /** - * nut-js 를 미리 불러 둔다. 첫 로딩이 수 초 걸려(실측 2026-10-03: 재시작 뒤 첫 제안 수락이 4.9초, - * 그중 nut-js 로딩 4.8초) 사용자가 수락하고 한참 기다렸다. 실패는 여기서 삼키고 실제 삽입 때 다시 알린다. + * 키 입력 백엔드를 미리 불러 둔다. + * Windows 에서는 이미 로드된 koffi user32 SendInput 을 그대로 쓰므로 무거운 nut-js 를 로드하지 않는다. */ async preload(): Promise { + if (this._useWin32NativeSendInput() && isWin32SendInputAvailable()) { + return + } try { await this._ensureNut() } catch { diff --git a/apps/desktop/src/main/utils/win32-unicode-input.ts b/apps/desktop/src/main/utils/win32-unicode-input.ts index a56746a..485cb47 100644 --- a/apps/desktop/src/main/utils/win32-unicode-input.ts +++ b/apps/desktop/src/main/utils/win32-unicode-input.ts @@ -20,7 +20,10 @@ const INPUT_KEYBOARD = 1 const KEYEVENTF_KEYUP = 0x0002 const KEYEVENTF_UNICODE = 0x0004 const VK_BACK = 0x08 +const VK_CONTROL = 0x11 const VK_SPACE = 0x20 +const VK_C = 0x43 +const VK_V = 0x56 type SendInputFn = (cInputs: number, pInputs: Buffer, cbSize: number) => number @@ -83,18 +86,89 @@ function ensureLoaded(): SendInputFn | null { } } -function writeVirtualKeyPair(buffer: Buffer, pairIndex: number, vk: number): void { - const downBase = pairIndex * 2 * inputStructSize - buffer.writeUInt32LE(INPUT_KEYBOARD, downBase) - buffer.writeUInt16LE(vk, downBase + unionOffset) - buffer.writeUInt16LE(0, downBase + unionOffset + 2) - buffer.writeUInt32LE(0, downBase + unionOffset + 4) +function writeKeyEvent(buffer: Buffer, eventIndex: number, vk: number, keyUp: boolean): void { + const base = eventIndex * inputStructSize + buffer.writeUInt32LE(INPUT_KEYBOARD, base) + buffer.writeUInt16LE(vk, base + unionOffset) + buffer.writeUInt16LE(0, base + unionOffset + 2) + buffer.writeUInt32LE(keyUp ? KEYEVENTF_KEYUP : 0, base + unionOffset + 4) +} - const upBase = (pairIndex * 2 + 1) * inputStructSize - buffer.writeUInt32LE(INPUT_KEYBOARD, upBase) - buffer.writeUInt16LE(vk, upBase + unionOffset) - buffer.writeUInt16LE(0, upBase + unionOffset + 2) - buffer.writeUInt32LE(KEYEVENTF_KEYUP, upBase + unionOffset + 4) +function writeVirtualKeyPair(buffer: Buffer, pairIndex: number, vk: number): void { + writeKeyEvent(buffer, pairIndex * 2, vk, false) + writeKeyEvent(buffer, pairIndex * 2 + 1, vk, true) +} + +/** Windows SendInput(koffi) 백엔드를 즉시 사용할 수 있는지 확인한다. */ +export function isWin32SendInputAvailable(): boolean { + const sendInput = ensureLoaded() + return Boolean(sendInput && inputStructSize > 0) +} + +/** + * 수정자 + 일반 키 조합(예: Ctrl+V, Ctrl+C)을 단일 SendInput 원자 배치(4 이벤트)로 전송한다. + * await 사이에 Ctrl 이 눌린 채 남지 않는다. + */ +export function sendWin32KeyChord(modifierVk: number, keyVk: number): boolean { + const sendInput = ensureLoaded() + if (!sendInput || inputStructSize <= 0) return false + + try { + const totalEvents = 4 + const buffer = Buffer.alloc(totalEvents * inputStructSize) + writeKeyEvent(buffer, 0, modifierVk, false) + writeKeyEvent(buffer, 1, keyVk, false) + writeKeyEvent(buffer, 2, keyVk, true) + writeKeyEvent(buffer, 3, modifierVk, true) + return sendInputBatch(sendInput, totalEvents, buffer) + } catch (error) { + if (error instanceof D3ROError) throw error + logger.warn(`SendInput(chord) 실행 실패: ${error instanceof Error ? error.message : String(error)}`) + return false + } +} + +export function sendWin32PasteChord(): boolean { + return sendWin32KeyChord(VK_CONTROL, VK_V) +} + +export function sendWin32CopyChord(): boolean { + return sendWin32KeyChord(VK_CONTROL, VK_C) +} + +export function sendWin32SpaceKey(): boolean { + const sendInput = ensureLoaded() + if (!sendInput || inputStructSize <= 0) return false + + try { + const buffer = Buffer.alloc(2 * inputStructSize) + writeVirtualKeyPair(buffer, 0, VK_SPACE) + return sendInputBatch(sendInput, 2, buffer) + } catch (error) { + if (error instanceof D3ROError) throw error + logger.warn(`SendInput(space) 실행 실패: ${error instanceof Error ? error.message : String(error)}`) + return false + } +} + +export function sendWin32Backspaces(count: number): boolean { + const safeCount = Math.max(0, Math.trunc(count)) + if (safeCount === 0) return true + const sendInput = ensureLoaded() + if (!sendInput || inputStructSize <= 0) return false + + try { + const totalEvents = safeCount * 2 + const buffer = Buffer.alloc(totalEvents * inputStructSize) + for (let i = 0; i < safeCount; i += 1) { + writeVirtualKeyPair(buffer, i, VK_BACK) + } + return sendInputBatch(sendInput, totalEvents, buffer) + } catch (error) { + if (error instanceof D3ROError) throw error + logger.warn(`SendInput(backspace) 실행 실패: ${error instanceof Error ? error.message : String(error)}`) + return false + } } function writeUnicodeKeyPair(buffer: Buffer, pairIndex: number, codeUnit: number): void { diff --git a/apps/desktop/src/main/windows/WindowManager.ts b/apps/desktop/src/main/windows/WindowManager.ts index 0edb2e3..40a5038 100644 --- a/apps/desktop/src/main/windows/WindowManager.ts +++ b/apps/desktop/src/main/windows/WindowManager.ts @@ -30,7 +30,7 @@ import { getIsQuitting, setIsQuitting } from '../lifecycle' import { hardenWebContents } from './web-contents-hardening' import { commandPopupSize, historyPopupSize } from './popup-list-geometry' import { configGet, configSet } from '../services/ConfigService' -import { getI18n } from '@d3ro/i18n' +import { getI18n } from '@d3ro/i18n/main' import { createPopupWindow, injectPopupTheme, @@ -223,6 +223,9 @@ let historyPopupWindow: BrowserWindow | null = null let commandPopupWindow: BrowserWindow | null = null let captionOverlayWindow: BrowserWindow | null = null let suggestionOverlayWindow: BrowserWindow | null = null +let mainAlwaysOnTopTimer: ReturnType | null = null +let historyHideTimer: ReturnType | null = null +let commandHideTimer: ReturnType | null = null // ── 메인 윈도우 ─────────────────────────────────────── @@ -324,6 +327,10 @@ export function createMainWindow(): BrowserWindow { }) mainWindow.on('closed', () => { + if (mainAlwaysOnTopTimer) { + clearTimeout(mainAlwaysOnTopTimer) + mainAlwaysOnTopTimer = null + } mainWindow = null }) @@ -346,7 +353,9 @@ export function createMainWindow(): BrowserWindow { mainWindow.show() mainWindow.focus() mainWindow.setAlwaysOnTop(true) - setTimeout(() => { + if (mainAlwaysOnTopTimer) clearTimeout(mainAlwaysOnTopTimer) + mainAlwaysOnTopTimer = setTimeout(() => { + mainAlwaysOnTopTimer = null try { mainWindow?.setAlwaysOnTop(false) } catch { @@ -570,6 +579,10 @@ function createHistoryPopupWindow(): BrowserWindow { name: 'history-popup', bounds: { width: 360, height: 400 }, onClosed: () => { + if (historyHideTimer) { + clearTimeout(historyHideTimer) + historyHideTimer = null + } historyPopupWindow = null } }) @@ -583,7 +596,16 @@ export function getHistoryPopupWindow(): BrowserWindow { return historyPopupWindow } +/** 창을 새로 만들지 않고 현재 살아있는 HistoryPopup 인스턴스만 조회한다. */ +export function peekHistoryPopupWindow(): BrowserWindow | null { + return historyPopupWindow && !historyPopupWindow.isDestroyed() ? historyPopupWindow : null +} + export function showHistoryPopup(entries: Array>): void { + if (historyHideTimer) { + clearTimeout(historyHideTimer) + historyHideTimer = null + } const win = getHistoryPopupWindow() // 커서 위치에 즉시 배치+표시 (2-phase 제거 — 숨겨진 윈도우 렌더러 비활성 문제 방지) @@ -598,8 +620,12 @@ export function showHistoryPopup(entries: Array>): void export function hideHistoryPopup(): void { if (historyPopupWindow && !historyPopupWindow.isDestroyed()) { + if (historyHideTimer) { + clearTimeout(historyHideTimer) + } sendToPopupWindow(historyPopupWindow, IPC_CHANNELS.POPUP_HISTORY.HIDE, {}) - setTimeout(() => { + historyHideTimer = setTimeout(() => { + historyHideTimer = null if (historyPopupWindow && !historyPopupWindow.isDestroyed()) { historyPopupWindow.hide() } @@ -624,6 +650,10 @@ function createCommandPopupWindow(): BrowserWindow { name: 'command-popup', bounds: commandPopupSize(0), onClosed: () => { + if (commandHideTimer) { + clearTimeout(commandHideTimer) + commandHideTimer = null + } commandPopupWindow = null } }) @@ -636,7 +666,16 @@ export function getCommandPopupWindow(): BrowserWindow { return commandPopupWindow } +/** 창을 새로 만들지 않고 현재 살아있는 CommandPopup 인스턴스만 조회한다. */ +export function peekCommandPopupWindow(): BrowserWindow | null { + return commandPopupWindow && !commandPopupWindow.isDestroyed() ? commandPopupWindow : null +} + export function showCommandPopup(commands: Array>, activeId: string | null): void { + if (commandHideTimer) { + clearTimeout(commandHideTimer) + commandHideTimer = null + } const win = getCommandPopupWindow() placePopupNearCursor(win, commandPopupSize(commands.length)) sendToPopupWindow(win, IPC_CHANNELS.POPUP_COMMAND.SHOW_ITEMS, { commands, activeId, _i18n: getPopupI18nStrings() }) @@ -647,8 +686,12 @@ export function showCommandPopup(commands: Array>, activ export function hideCommandPopup(): void { if (commandPopupWindow && !commandPopupWindow.isDestroyed()) { + if (commandHideTimer) { + clearTimeout(commandHideTimer) + } sendToPopupWindow(commandPopupWindow, IPC_CHANNELS.POPUP_COMMAND.HIDE, {}) - setTimeout(() => { + commandHideTimer = setTimeout(() => { + commandHideTimer = null if (commandPopupWindow && !commandPopupWindow.isDestroyed()) { commandPopupWindow.hide() } diff --git a/apps/desktop/src/main/windows/recording-tip-error-message.ts b/apps/desktop/src/main/windows/recording-tip-error-message.ts index ae0b3c4..f5139d5 100644 --- a/apps/desktop/src/main/windows/recording-tip-error-message.ts +++ b/apps/desktop/src/main/windows/recording-tip-error-message.ts @@ -7,7 +7,7 @@ // 분류되지 않는 코드는 기존 동작대로 원문을 그린다. import { classifyVoiceError, type VoiceErrorMessageId } from '@d3ro/core/voice-error-message' -import type { TranslationKey } from '@d3ro/i18n' +import type { TranslationKey } from '@d3ro/i18n/main' export type RecordingTipTranslate = (key: TranslationKey, params?: Record) => string diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx index bc0a2b3..3b2b323 100644 --- a/apps/desktop/src/renderer/App.tsx +++ b/apps/desktop/src/renderer/App.tsx @@ -9,7 +9,7 @@ import { useState, useEffect, useMemo } from 'react' import { ThemeProvider, CssBaseline, useMediaQuery } from '@mui/material' import { getTheme } from '@d3ro/ui/theme' -import { I18nProvider, useI18n, type I18nStorage, type Locale } from '@d3ro/i18n' +import { I18nProvider, isValidLocale, useI18n, type I18nStorage, type Locale } from '@d3ro/i18n' import { AppLayout } from './components/AppLayout' import { UpgradePromptModal } from './components/UpgradePromptModal' import { createSystemAudioCaptureController } from './utils/systemAudioCapture' @@ -32,8 +32,8 @@ function SyncedLocale(): null { useEffect( () => window.electronAPI.config.onChanged((e: ConfigChangedEvent) => { - if (e.key === 'language' && typeof e.value === 'string' && e.value !== locale) { - setLocale(e.value as Locale) + if (e.key === 'language' && typeof e.value === 'string' && isValidLocale(e.value) && e.value !== locale) { + setLocale(e.value) } }), [locale, setLocale], @@ -41,24 +41,35 @@ function SyncedLocale(): null { return null } +function isThemeMode(value: unknown): value is ThemeMode { + return value === 'auto' || value === 'dark' || value === 'light' +} + export function App(): React.ReactElement { const [themeMode, setThemeMode] = useState('auto') const prefersDark = useMediaQuery('(prefers-color-scheme: dark)') // 설정에서 테마 로드 + 변경 감지 useEffect(() => { - window.electronAPI.config.getTheme().then((result) => { - if (result.success) { - setThemeMode(result.data) - } - }) + let cancelled = false + window.electronAPI.config + .getTheme() + .then((result) => { + if (!cancelled && result.success && isThemeMode(result.data)) { + setThemeMode(result.data) + } + }) + .catch(() => {}) const unsub = window.electronAPI.config.onChanged((e: ConfigChangedEvent) => { - if (e.key === 'theme') { - setThemeMode(e.value as ThemeMode) + if (e.key === 'theme' && isThemeMode(e.value)) { + setThemeMode(e.value) } }) - return unsub + return () => { + cancelled = true + unsub() + } }, []) // 시스템 오디오 캡처: 메인 프로세스의 시작/중지 요청에 응답. diff --git a/apps/desktop/src/renderer/components/AppLayout.tsx b/apps/desktop/src/renderer/components/AppLayout.tsx index b225cfe..c567e37 100644 --- a/apps/desktop/src/renderer/components/AppLayout.tsx +++ b/apps/desktop/src/renderer/components/AppLayout.tsx @@ -4,7 +4,7 @@ // 버전·모델은 설정에, 시계는 OS 에 있고, "100% LOCAL PRIVACY · ZERO CLOUD SYNC"는 기기 간 동기화와 모순된 문구였다. // 의미 있는 상태(로컬 AI 연결·자막·회의 녹음 중)는 사이드바 아래 한 줄로 옮겼다. -import React, { useState, useEffect, useCallback } from 'react' +import React, { Suspense, lazy, useState, useEffect, useCallback } from 'react' import { Alert, Box, Button, IconButton, Snackbar } from '@mui/material' import { X } from 'lucide-react' import { OverlayScrollbarsComponent } from 'overlayscrollbars-react' @@ -13,28 +13,29 @@ import { d3roPalette } from '@d3ro/ui/theme' import { useI18n } from '@d3ro/i18n' import type { LicenseTier } from '@d3ro/core/types' import { HomePage } from '../pages/HomePage' -import { HistoryPage } from '../pages/HistoryPage' -import { DictionaryPage } from '../pages/DictionaryPage' -import { CommandsPage } from '../pages/CommandsPage' -import { VoiceConversationPage } from '../pages/VoiceConversationPage' -import { KnowledgeBasePage } from '../pages/KnowledgeBasePage' -import { MeetingModePage } from '../pages/MeetingModePage' -import { UnifiedSearchPage } from '../pages/UnifiedSearchPage' -import { SettingsModal } from './SettingsModal' import { OPEN_SETTINGS_EVENT, readOpenSettingsTab, DEFAULT_SETTINGS_TAB } from '../navigation/settingsTabs' import type { SettingsTabId } from '../navigation/settingsTabs' import { presentError, settingsTabOf } from '../navigation/error-recovery' import { AppNavigationProvider, PRIMARY_ROUTES, useAppNavigation, useRouteRequest } from '../navigation/app-navigation' -import { LicenseModal } from './LicenseModal' -import { OnboardingModal } from './OnboardingModal' -import { OllamaGuideModal } from './OllamaGuideModal' import { AdBanner } from './ads/AdBanner' -import { RewardedQuotaModal } from './ads/RewardedQuotaModal' -import { SupportModal } from './support/SupportModal' import { TitleBar } from './TitleBar' import { AppSidebar } from './shell/AppSidebar' import { NotifyProvider, useNotify } from './shared' +const HistoryPage = lazy(() => import('../pages/HistoryPage').then((m) => ({ default: m.HistoryPage }))) +const DictionaryPage = lazy(() => import('../pages/DictionaryPage').then((m) => ({ default: m.DictionaryPage }))) +const CommandsPage = lazy(() => import('../pages/CommandsPage').then((m) => ({ default: m.CommandsPage }))) +const VoiceConversationPage = lazy(() => import('../pages/VoiceConversationPage').then((m) => ({ default: m.VoiceConversationPage }))) +const KnowledgeBasePage = lazy(() => import('../pages/KnowledgeBasePage').then((m) => ({ default: m.KnowledgeBasePage }))) +const MeetingModePage = lazy(() => import('../pages/MeetingModePage').then((m) => ({ default: m.MeetingModePage }))) +const UnifiedSearchPage = lazy(() => import('../pages/UnifiedSearchPage').then((m) => ({ default: m.UnifiedSearchPage }))) +const SettingsModal = lazy(() => import('./SettingsModal').then((m) => ({ default: m.SettingsModal }))) +const LicenseModal = lazy(() => import('./LicenseModal').then((m) => ({ default: m.LicenseModal }))) +const OnboardingModal = lazy(() => import('./OnboardingModal').then((m) => ({ default: m.OnboardingModal }))) +const OllamaGuideModal = lazy(() => import('./OllamaGuideModal').then((m) => ({ default: m.OllamaGuideModal }))) +const RewardedQuotaModal = lazy(() => import('./ads/RewardedQuotaModal').then((m) => ({ default: m.RewardedQuotaModal }))) +const SupportModal = lazy(() => import('./support/SupportModal').then((m) => ({ default: m.SupportModal }))) + /** 입력 요소에 포커스가 있으면 전역 단축키를 무시한다 — 타자 중에 화면이 바뀌면 안 된다. */ function isTypingTarget(target: EventTarget | null): boolean { if (!(target instanceof HTMLElement)) return false @@ -71,17 +72,28 @@ function Shell(): React.ReactElement { }) useEffect(() => { - window.electronAPI.config.getAll().then((r) => { - if (r.success && !r.data.onboardingCompleted) { - setOnboardingOpen(true) - } - }) + let cancelled = false + window.electronAPI.config + .getAll() + .then((r) => { + if (!cancelled && r.success && !r.data.onboardingCompleted) { + setOnboardingOpen(true) + } + }) + .catch(() => {}) + return () => { + cancelled = true + } }, []) useEffect(() => { - window.electronAPI.license.getInfo().then((r) => { - if (r.success) setCurrentTier(r.data.tier) - }) + let cancelled = false + window.electronAPI.license + .getInfo() + .then((r) => { + if (!cancelled && r.success) setCurrentTier(r.data.tier) + }) + .catch(() => {}) const unsubTier = window.electronAPI.license.onTierChanged((info) => { setCurrentTier(info.tier) @@ -125,6 +137,7 @@ function Shell(): React.ReactElement { }) return () => { + cancelled = true unsubTier() unsubUpgrade() unsubFallback() @@ -196,15 +209,17 @@ function Shell(): React.ReactElement { }} style={{ height: '100%', width: '100%' }} > - {route === 'home' && } - {route === 'search' && } - {route === 'records' && } - {route === 'meetings' && } - {route === 'conversation' && } - {route === 'commands' && } - {route === 'dictionary' && } - {route === 'knowledge' && } - {route === 'settings' && } + + {route === 'home' && } + {route === 'search' && } + {route === 'records' && } + {route === 'meetings' && } + {route === 'conversation' && } + {route === 'commands' && } + {route === 'dictionary' && } + {route === 'knowledge' && } + {route === 'settings' && } + @@ -219,15 +234,19 @@ function Shell(): React.ReactElement { - setLicenseModalOpen(false)} /> - setOnboardingOpen(false)} /> - setSupportModalOpen(false)} /> - setOllamaGuideOpen(false)} /> - setRewardedModalOpen(false)} - onRewardClaimed={(tokens) => notify({ message: t('shell.rewardClaimed', { tokens }), severity: 'success' })} - /> + + {licenseModalOpen && setLicenseModalOpen(false)} />} + {onboardingOpen && setOnboardingOpen(false)} />} + {supportModalOpen && setSupportModalOpen(false)} />} + {ollamaGuideOpen && setOllamaGuideOpen(false)} />} + {rewardedModalOpen && ( + setRewardedModalOpen(false)} + onRewardClaimed={(tokens) => notify({ message: t('shell.rewardClaimed', { tokens }), severity: 'success' })} + /> + )} + (null) const [busy, setBusy] = useState(false) const [audioSync, setAudioSync] = useState(true) + const mountedRef = useRef(true) + const refreshSeqRef = useRef(0) const refreshState = useCallback(async () => { - const r = await window.electronAPI.cloudSync.getState() - if (r.success) setState(r.data) + const seq = ++refreshSeqRef.current + try { + const r = await window.electronAPI.cloudSync.getState() + if (mountedRef.current && refreshSeqRef.current === seq && r.success) setState(r.data) + } catch { + // ignore IPC failure + } }, []) // 초기 상태 로드 + 이벤트 구독 useEffect(() => { + mountedRef.current = true + let cancelled = false void refreshState() - void window.electronAPI.config.get({ key: 'cloudSyncAudio' }).then((r) => { - if (r.success) setAudioSync(r.data !== false) - }) + void window.electronAPI.config + .get({ key: 'cloudSyncAudio' }) + .then((r) => { + if (!cancelled && r.success) setAudioSync(r.data !== false) + }) + .catch(() => {}) const unsubAuth = window.electronAPI.cloudSync.onAuthChanged(() => { void refreshState() @@ -60,6 +73,8 @@ export function CloudSyncSection(): React.ReactElement { void refreshState() }) return () => { + cancelled = true + mountedRef.current = false unsubAuth() unsubComplete() unsubError() @@ -76,13 +91,16 @@ export function CloudSyncSection(): React.ReactElement { setBusy(true) try { const r = await window.electronAPI.cloudSync.signIn({ provider }) + if (!mountedRef.current) return if (!r.success) { setError(r.error.message) } else { setInfo(t('cloudSync.browserPending')) } + } catch (err: unknown) { + if (mountedRef.current) setError(toErrorMessage(err)) } finally { - setBusy(false) + if (mountedRef.current) setBusy(false) } } @@ -90,10 +108,14 @@ export function CloudSyncSection(): React.ReactElement { setBusy(true) try { await window.electronAPI.cloudSync.signOut() - setInfo(t('cloudSync.signedOut')) + if (mountedRef.current) setInfo(t('cloudSync.signedOut')) + } catch { + // ignore sign-out IPC rejection } finally { - setBusy(false) - void refreshState() + if (mountedRef.current) { + setBusy(false) + void refreshState() + } } } @@ -105,14 +127,19 @@ export function CloudSyncSection(): React.ReactElement { try { const pushed = await window.electronAPI.cloudSync.pushAll() const pulled = await window.electronAPI.cloudSync.pullAll() + if (!mountedRef.current) return const count = (pushed.success ? pushed.data.pushed : 0) + (pulled.success ? pulled.data.pushed : 0) const errors = (pushed.success ? pushed.data.errors.length : 1) + (pulled.success ? pulled.data.errors.length : 1) if (!pushed.success) setError(pushed.error.message) else if (!pulled.success) setError(pulled.error.message) setInfo(errors > 0 ? t('cloudSync.doneWithErrors', { count, errors }) : t('cloudSync.done', { count })) + } catch (err: unknown) { + if (mountedRef.current) setError(toErrorMessage(err)) } finally { - setBusy(false) - void refreshState() + if (mountedRef.current) { + setBusy(false) + void refreshState() + } } } diff --git a/apps/desktop/src/renderer/components/CodexOAuthGuideModal.tsx b/apps/desktop/src/renderer/components/CodexOAuthGuideModal.tsx index 2d8bf22..ae80c05 100644 --- a/apps/desktop/src/renderer/components/CodexOAuthGuideModal.tsx +++ b/apps/desktop/src/renderer/components/CodexOAuthGuideModal.tsx @@ -2,7 +2,7 @@ // OpenAI API 키 · Codex OAuth(ChatGPT 구독) · 다른 STT 서비스 키 발급 안내 모달. STT 설정 탭에서 연다. // v4(2026-09-28): 평면 다이얼로그 — 제목(h2) + 탭 + 번호 단계(소제목 + 설명, 1px 선). 근거 없는 성능·가격 수식어 제거. -import { useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { Dialog, DialogTitle, @@ -78,11 +78,25 @@ export function CodexOAuthGuideModal({ open, onClose }: CodexOAuthGuideModalProp const { t } = useI18n() const [tab, setTab] = useState(0) const [copied, setCopied] = useState(false) + const copyTimerRef = useRef | null>(null) + + useEffect(() => { + return () => { + if (copyTimerRef.current) { + clearTimeout(copyTimerRef.current) + copyTimerRef.current = null + } + } + }, []) const handleCopy = (text: string) => { - navigator.clipboard.writeText(text) + void navigator.clipboard.writeText(text).catch(() => {}) setCopied(true) - setTimeout(() => setCopied(false), 2000) + if (copyTimerRef.current) clearTimeout(copyTimerRef.current) + copyTimerRef.current = setTimeout(() => { + copyTimerRef.current = null + setCopied(false) + }, 2000) } const handleOpenLink = (url: string) => { diff --git a/apps/desktop/src/renderer/components/FileDropZone.tsx b/apps/desktop/src/renderer/components/FileDropZone.tsx index 6c56c9a..7906321 100644 --- a/apps/desktop/src/renderer/components/FileDropZone.tsx +++ b/apps/desktop/src/renderer/components/FileDropZone.tsx @@ -28,6 +28,16 @@ export function FileDropZone(): React.ReactElement { const [error, setError] = useState(null) const [copied, setCopied] = useState(false) const dropRef = useRef(null) + const copyTimerRef = useRef | null>(null) + + useEffect(() => { + return () => { + if (copyTimerRef.current) { + clearTimeout(copyTimerRef.current) + copyTimerRef.current = null + } + } + }, []) useEffect(() => { const unsubProgress = window.electronAPI.fileTranscription.onProgress((data) => { @@ -136,9 +146,13 @@ export function FileDropZone(): React.ReactElement { const handleCopy = useCallback(() => { if (result?.fullText) { - navigator.clipboard.writeText(result.fullText) + void navigator.clipboard.writeText(result.fullText).catch(() => {}) setCopied(true) - setTimeout(() => setCopied(false), 2000) + if (copyTimerRef.current) clearTimeout(copyTimerRef.current) + copyTimerRef.current = setTimeout(() => { + copyTimerRef.current = null + setCopied(false) + }, 2000) } }, [result]) diff --git a/apps/desktop/src/renderer/components/OllamaGuideModal.tsx b/apps/desktop/src/renderer/components/OllamaGuideModal.tsx index 2349c31..eb04c93 100644 --- a/apps/desktop/src/renderer/components/OllamaGuideModal.tsx +++ b/apps/desktop/src/renderer/components/OllamaGuideModal.tsx @@ -2,7 +2,7 @@ // Ollama 설치·실행·모델 받기·동작 확인 안내 모달. AppLayout 이 'd3ro:open-ollama-guide' 이벤트로 연다. // v4(2026-09-28): 평면 다이얼로그 — 제목(h2) + 번호 붙은 소제목 3개 + 1px 선. 연결 상태는 실제 조회 값만 쓴다. -import { useState, useEffect, useCallback } from 'react' +import { useState, useEffect, useCallback, useRef } from 'react' import { Dialog, DialogTitle, @@ -52,11 +52,25 @@ const DEFAULT_SERVER_URL = 'http://localhost:11434' function CodeBlock({ code }: { code: string }): React.ReactElement { const { t } = useI18n() const [copied, setCopied] = useState(false) + const copyTimerRef = useRef | null>(null) + + useEffect(() => { + return () => { + if (copyTimerRef.current) { + clearTimeout(copyTimerRef.current) + copyTimerRef.current = null + } + } + }, []) const handleCopy = useCallback(() => { - navigator.clipboard.writeText(code) + void navigator.clipboard.writeText(code).catch(() => {}) setCopied(true) - setTimeout(() => setCopied(false), 2000) + if (copyTimerRef.current) clearTimeout(copyTimerRef.current) + copyTimerRef.current = setTimeout(() => { + copyTimerRef.current = null + setCopied(false) + }, 2000) }, [code]) return ( @@ -115,24 +129,45 @@ export function OllamaGuideModal({ open, onClose }: OllamaGuideModalProps): Reac const [testResult, setTestResult] = useState(null) const [testFailed, setTestFailed] = useState(false) const [testing, setTesting] = useState(false) + const mountedRef = useRef(true) + const refreshSeqRef = useRef(0) + const startTimerRef = useRef | null>(null) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + if (startTimerRef.current) { + clearTimeout(startTimerRef.current) + startTimerRef.current = null + } + } + }, []) const refreshStatus = useCallback(async () => { + const seq = ++refreshSeqRef.current + const isFresh = (): boolean => mountedRef.current && refreshSeqRef.current === seq setChecking(true) try { const res = await window.electronAPI.llm.checkConnection() + if (!isFresh()) return if (res.success && res.data) { setInstalledModels(res.data.models) } const st = await window.electronAPI.llm.getStatus() + if (!isFresh()) return if (st.success) { setLlmStatus(st.data) } const active = await window.electronAPI.llm.getActiveModel() + if (!isFresh()) return if (active.success && active.data) { setActiveModel(active.data) } + } catch { + // ignore IPC failure } finally { - setChecking(false) + if (isFresh()) setChecking(false) } }, []) @@ -167,20 +202,27 @@ export function OllamaGuideModal({ open, onClose }: OllamaGuideModalProps): Reac setStartMessage(null) try { const res = await window.electronAPI.llm.startServer() + if (!mountedRef.current) return if (res.success) { if (res.data === 'running') { setStartMessage(t('ollamaGuide.start.running')) } else if (res.data === 'starting') { setStartMessage(t('ollamaGuide.start.starting')) - setTimeout(() => refreshStatus(), 2000) + if (startTimerRef.current) clearTimeout(startTimerRef.current) + startTimerRef.current = setTimeout(() => { + startTimerRef.current = null + if (mountedRef.current) void refreshStatus() + }, 2000) } else if (res.data === 'not-installed') { setStartMessage(t('ollamaGuide.start.notInstalled')) } else { setStartMessage(t('ollamaGuide.start.failed')) } } + } catch { + if (mountedRef.current) setStartMessage(t('ollamaGuide.start.failed')) } finally { - setStarting(false) + if (mountedRef.current) setStarting(false) } }, [refreshStatus, t]) diff --git a/apps/desktop/src/renderer/components/OnboardingModal.tsx b/apps/desktop/src/renderer/components/OnboardingModal.tsx index 43cd20c..0948322 100644 --- a/apps/desktop/src/renderer/components/OnboardingModal.tsx +++ b/apps/desktop/src/renderer/components/OnboardingModal.tsx @@ -3,7 +3,7 @@ // v4(2026-09-28): 평면 다이얼로그 + 단계 표시(n/3, 진행 막대) + "나중에 설정" 건너뛰기. // 첫 실행은 Esc·배경 클릭으로 닫히지 않는다(onboarding-dismiss 정책) — 대신 명시적인 건너뛰기 버튼이 있다. -import { useState, useEffect, useCallback } from 'react' +import { useState, useEffect, useCallback, useRef } from 'react' import { Dialog, DialogTitle, @@ -139,32 +139,58 @@ export function OnboardingModal({ open, onClose }: OnboardingModalProps): React. const errorMsg = '' const isVisible = open || internalOpen + const mountedRef = useRef(true) + const ollamaSeqRef = useRef(0) + const ollamaTimerRef = useRef | null>(null) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + if (ollamaTimerRef.current) { + clearTimeout(ollamaTimerRef.current) + ollamaTimerRef.current = null + } + } + }, []) const checkOllama = useCallback(async () => { + const seq = ++ollamaSeqRef.current setCheckingOllama(true) try { const res = await window.electronAPI.llm.checkConnection() + if (!mountedRef.current || ollamaSeqRef.current !== seq) return if (res.success && res.data) { setInstalledModels(res.data.models) } const st = await window.electronAPI.llm.getStatus() + if (!mountedRef.current || ollamaSeqRef.current !== seq) return if (st.success) { setOllamaStatus(st.data) } + } catch { + // ignore IPC failure } finally { - setCheckingOllama(false) + if (mountedRef.current && ollamaSeqRef.current === seq) setCheckingOllama(false) } }, []) useEffect(() => { - window.electronAPI.config.getAll().then((res) => { - if (!res.success) return - setOnboardingCompleted(res.data.onboardingCompleted) - if (!res.data.onboardingCompleted) { - setInternalOpen(true) - setPhase('select_mode') - } - }) + let cancelled = false + window.electronAPI.config + .getAll() + .then((res) => { + if (cancelled || !res.success) return + setOnboardingCompleted(res.data.onboardingCompleted) + if (!res.data.onboardingCompleted) { + setInternalOpen(true) + setPhase('select_mode') + } + }) + .catch(() => {}) + return () => { + cancelled = true + } }, []) // 모델 받기 — 받기에 성공한 경우에만 활성 모델로 저장 (autoSelect) @@ -192,10 +218,17 @@ export function OnboardingModal({ open, onClose }: OnboardingModalProps): React. await window.electronAPI.config.set({ key: 'appUsageMode', value: 'local' }) await window.electronAPI.config.set({ key: 'llmBackend', value: 'local' }) await window.electronAPI.config.set({ key: 'sttProvider', value: 'local' }) + if (!mountedRef.current) return await checkOllama() + if (!mountedRef.current) return // 자동으로 Ollama 기동 시도 await window.electronAPI.llm.startServer() - setTimeout(() => checkOllama(), 1500) + if (!mountedRef.current) return + if (ollamaTimerRef.current) clearTimeout(ollamaTimerRef.current) + ollamaTimerRef.current = setTimeout(() => { + ollamaTimerRef.current = null + if (mountedRef.current) void checkOllama() + }, 1500) } const handleStartOllama = async () => { @@ -203,20 +236,27 @@ export function OnboardingModal({ open, onClose }: OnboardingModalProps): React. setOllamaMsg(null) try { const res = await window.electronAPI.llm.startServer() + if (!mountedRef.current) return if (res.success) { if (res.data === 'running') { setOllamaMsg(t('ollamaGuide.start.running')) } else if (res.data === 'starting') { setOllamaMsg(t('ollamaGuide.start.starting')) - setTimeout(() => checkOllama(), 2000) + if (ollamaTimerRef.current) clearTimeout(ollamaTimerRef.current) + ollamaTimerRef.current = setTimeout(() => { + ollamaTimerRef.current = null + if (mountedRef.current) void checkOllama() + }, 2000) } else if (res.data === 'not-installed') { setOllamaMsg(t('ollamaGuide.start.notInstalled')) } else { setOllamaMsg(t('ollamaGuide.start.failed')) } } + } catch { + if (mountedRef.current) setOllamaMsg(t('ollamaGuide.start.failed')) } finally { - setStartingOllama(false) + if (mountedRef.current) setStartingOllama(false) } } diff --git a/apps/desktop/src/renderer/components/SettingsModal.tsx b/apps/desktop/src/renderer/components/SettingsModal.tsx index 8c5b45d..d641193 100644 --- a/apps/desktop/src/renderer/components/SettingsModal.tsx +++ b/apps/desktop/src/renderer/components/SettingsModal.tsx @@ -3,37 +3,22 @@ // open 은 "이 화면이 현재 보이는가" — 보일 때만 설정·장치·모델을 불러온다. onClose 는 이전 화면으로 돌아간다. // 본문 문법: 구획(h3 + 1px 선) 안에 설정 행(왼쪽 라벨·설명, 오른쪽 컨트롤) — settings/SettingsRows. -import { useState, useEffect, useCallback, useMemo } from 'react' -import { - Tabs, - Tab, - Box, - TextField, - Select, - MenuItem, - Switch, - FormControlLabel, - Typography, - FormControl, - Button, -} from '@mui/material' -import { Keyboard, Mic, Lock, Cloud, RefreshCw, Play, HelpCircle, TextCursorInput } from 'lucide-react' -import { d3roPalette, d3roRadius, d3roTransition, d3roTypo, typoSx } from '@d3ro/ui/theme' -import { Led } from '@d3ro/ui/components/ds' +import { useState, useEffect, useCallback, useMemo, useRef } from 'react' +import { Tabs, Tab, Box, Typography } from '@mui/material' +import { Keyboard, Mic, Lock, Cloud, TextCursorInput } from 'lucide-react' +import { d3roPalette, d3roRadius, d3roTypo, typoSx } from '@d3ro/ui/theme' import { LicenseTab } from './LicenseTab' import { CloudSyncSection } from './CloudSyncSection' import { STTTab } from './STTTab' -import { CaptionModelSelect } from './CaptionModelSelect' import { InputConsentPanel } from './input-insights/InputConsentPanel' -import { KeyBindingField } from './keybinding/KeyBindingField' -import { asTranslationKey } from './keybinding/translation-key' -import { SettingNote, SettingRow, SettingsSection, SETTING_CONTROL_WIDTH } from './settings/SettingsRows' -import { UpdateSection } from './settings/UpdateSection' -import { useI18n, LOCALE_META } from '@d3ro/i18n' +import { GeneralSettingsTab } from './settings/GeneralSettingsTab' +import { AudioSettingsTab } from './settings/AudioSettingsTab' +import { LlmSettingsTab, type OllamaFeedback } from './settings/LlmSettingsTab' +import { AboutSettingsTab } from './settings/AboutSettingsTab' +import { useI18n } from '@d3ro/i18n' import type { Locale } from '@d3ro/i18n' -import type { KeyBindingActionGroup } from '@d3ro/core/keybinding' -import { auditKeyBindingMap, KEYBINDING_ACTIONS } from '@d3ro/core/keybinding' -import type { ThemeMode, AppConfig, AudioDevice, LLMModel, LLMStatus, STTModel } from '@d3ro/core/types' +import { auditKeyBindingMap } from '@d3ro/core/keybinding' +import type { AppConfig, AudioDevice, LLMModel, LLMStatus, STTModel } from '@d3ro/core/types' import { useKeyBindingMap } from '../hooks/useKeyBindingMap' import { DEFAULT_SETTINGS_TAB, SETTINGS_TAB_ORDER } from '../navigation/settingsTabs' import type { SettingsTabId } from '../navigation/settingsTabs' @@ -55,45 +40,12 @@ function TabPanel({ children, value, tab }: TabPanelProps): React.ReactElement | return {children} } -/** 행 오른쪽 Select·TextField 공통 폭 */ -const controlSx = { width: SETTING_CONTROL_WIDTH, maxWidth: '100%' } as const - -/** 행 오른쪽 스위치 — 라벨은 행 왼쪽 글자(aria-labelledby)가 맡는다. */ -function RowSwitch({ - labelId, - checked, - onChange, -}: { - labelId: string - checked: boolean - onChange: (checked: boolean) => void -}): React.ReactElement { - return ( - onChange(e.target.checked)} - inputProps={{ 'aria-labelledby': labelId }} - /> - ) -} - -// ── 액션 그룹 섹션 ───────────────────────────────────── -const ACTION_GROUP_LABEL_KEYS: Readonly> = { - voice: 'keybinding.ui.sectionVoice', - window: 'keybinding.ui.sectionWindow', - input: 'keybinding.ui.sectionInput', -} - -const ACTION_GROUP_ORDER: readonly KeyBindingActionGroup[] = ['voice', 'window', 'input'] - -/** 설치된 모델이 없을 때도 고를 수 있게 보여 주는 기본 후보 */ -const RECOMMENDED_OLLAMA_MODEL = 'gemma4:e4b' -const FALLBACK_OLLAMA_MODELS = ['llama3.2:3b', 'qwen2.5:3b'] as const - -type OllamaFeedback = { tone: 'info' | 'error'; message: string } - -export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose }: SettingsModalProps): React.ReactElement { - const { t, locale, setLocale } = useI18n() +export function SettingsModal({ + open, + initialTab = DEFAULT_SETTINGS_TAB, + onClose +}: SettingsModalProps): React.ReactElement { + const { t, setLocale } = useI18n() const [activeTab, setActiveTab] = useState(initialTab) const tabMeta = useMemo>( () => ({ @@ -104,9 +56,9 @@ export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose input: { label: t('input.tab'), icon: }, license: { label: t('license.nav'), icon: }, cloud: { label: t('settings.tabs.cloud'), icon: }, - about: { label: t('settings.tabs.about') }, + about: { label: t('settings.tabs.about') } }), - [t], + [t] ) const [config, setConfig] = useState>({}) const [loading, setLoading] = useState(true) @@ -127,7 +79,8 @@ export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose if (!open) return let cancelled = false - void window.electronAPI.system.getVersion() + void window.electronAPI.system + .getVersion() .then((result) => { if (!cancelled && result.success) setAppVersion(result.data) }) @@ -140,26 +93,68 @@ export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose } }, [open]) - // 전역 단축키 on/off (개별 바인딩은 KeyBindingField 가 담당한다) const [keybindingEnabled, setKeybindingEnabled] = useState(true) - - // 오디오 디바이스 const [audioDevices, setAudioDevices] = useState([]) const [selectedDeviceId, setSelectedDeviceId] = useState('default') const [micTesting, setMicTesting] = useState(false) const [micLevel, setMicLevel] = useState(0) const [micTestFailed, setMicTestFailed] = useState(false) - - // 실시간 자막 모델 선택지 — 받아 둔 로컬 Whisper 모델만 const [downloadedSttModels, setDownloadedSttModels] = useState([]) - useEffect(() => { - if (!open) return - window.electronAPI.stt.getModels().then((res) => { - if (res.success && res.data) setDownloadedSttModels(res.data.filter((m) => m.downloaded)) - }) - }, [open]) + const mountedRef = useRef(true) + const ollamaSeqRef = useRef(0) + const micTestUnsubRef = useRef<(() => void) | null>(null) + const micTestActiveRef = useRef(false) + const ollamaRefreshTimerRef = useRef | null>(null) + const reloadTimerRef = useRef | null>(null) + + const cleanupMicTest = useCallback((stopDevice: boolean) => { + micTestActiveRef.current = false + if (micTestUnsubRef.current) { + micTestUnsubRef.current() + micTestUnsubRef.current = null + } + if (stopDevice) { + void window.electronAPI.audio.stopTest().catch(() => {}) + } + }, []) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + cleanupMicTest(true) + if (ollamaRefreshTimerRef.current) { + clearTimeout(ollamaRefreshTimerRef.current) + ollamaRefreshTimerRef.current = null + } + if (reloadTimerRef.current) { + clearTimeout(reloadTimerRef.current) + reloadTimerRef.current = null + } + } + }, [cleanupMicTest]) + + useEffect(() => { + if (!open) { + cleanupMicTest(true) + setMicTesting(false) + setMicLevel(0) + return + } + let cancelled = false + window.electronAPI.stt + .getModels() + .then((res) => { + if (!cancelled && res.success && res.data) { + setDownloadedSttModels(res.data.filter((m) => m.downloaded)) + } + }) + .catch(() => {}) + return () => { + cancelled = true + } + }, [open, cleanupMicTest]) - // Ollama 상태 — null 은 "아직 조회하지 않음"(연결됨/오프라인으로 단정하지 않는다) const [ollamaStatus, setOllamaStatus] = useState(null) const [ollamaModels, setOllamaModels] = useState([]) const [checkingOllama, setCheckingOllama] = useState(false) @@ -167,46 +162,63 @@ export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose const [ollamaFeedback, setOllamaFeedback] = useState(null) const refreshOllama = useCallback(async () => { + const seq = ++ollamaSeqRef.current setCheckingOllama(true) try { const res = await window.electronAPI.llm.checkConnection() + if (!mountedRef.current || ollamaSeqRef.current !== seq) return if (res.success && res.data) { setOllamaModels(res.data.models) } const st = await window.electronAPI.llm.getStatus() + if (!mountedRef.current || ollamaSeqRef.current !== seq) return if (st.success) setOllamaStatus(st.data) + } catch { + // IPC 오류 시 마지막 상태 유지 } finally { - setCheckingOllama(false) + if (mountedRef.current && ollamaSeqRef.current === seq) { + setCheckingOllama(false) + } } }, []) - // 설정 로드 useEffect(() => { if (!open) return + let cancelled = false setLoading(true) - refreshOllama() + void refreshOllama() Promise.all([ window.electronAPI.config.getAll(), - window.electronAPI.keybinding.isEnabled(), + window.electronAPI.keybinding.isEnabled() ]) .then(([configResult, enabledResult]) => { + if (cancelled) return if (configResult.success) setConfig(configResult.data) if (enabledResult.success) setKeybindingEnabled(enabledResult.data) }) - .finally(() => setLoading(false)) + .catch(() => {}) + .finally(() => { + if (!cancelled) setLoading(false) + }) Promise.all([ window.electronAPI.audio.getDevices(), - window.electronAPI.audio.getSelectedDevice(), - ]).then(([devicesResult, selectedResult]) => { - if (devicesResult.success) setAudioDevices(devicesResult.data) - if (selectedResult.success && selectedResult.data) setSelectedDeviceId(selectedResult.data) - }) + window.electronAPI.audio.getSelectedDevice() + ]) + .then(([devicesResult, selectedResult]) => { + if (cancelled) return + if (devicesResult.success) setAudioDevices(devicesResult.data) + if (selectedResult.success && selectedResult.data) setSelectedDeviceId(selectedResult.data) + }) + .catch(() => {}) + return () => { + cancelled = true + } }, [open, refreshOllama]) - const updateConfig = useCallback((key: keyof AppConfig, value: AppConfig[keyof AppConfig]) => { + const updateConfig = useCallback((key: K, value: AppConfig[K]) => { setConfig((prev) => ({ ...prev, [key]: value })) window.electronAPI.config.set({ key, value }) }, []) @@ -216,60 +228,107 @@ export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose void window.electronAPI.keybinding.setEnabled({ enabled }) }, []) - const handleLanguageChange = useCallback((newLocale: string) => { - setLocale(newLocale as Locale) - setConfig((prev) => ({ ...prev, language: newLocale })) - }, [setLocale]) + const handleLanguageChange = useCallback( + (newLocale: string) => { + setLocale(newLocale as Locale) + setConfig((prev) => ({ ...prev, language: newLocale })) + }, + [setLocale] + ) + + const handleSelectAudioDevice = useCallback((deviceId: string) => { + setSelectedDeviceId(deviceId) + window.electronAPI.audio.setSelectedDevice({ deviceId }) + }, []) const handleMicTest = useCallback(async () => { if (micTesting) { - // 메인 프로세스 캡처까지 실제로 중지 — done 이벤트가 구독 해제를 마무리 - await window.electronAPI.audio.stopTest() + cleanupMicTest(true) setMicTesting(false) setMicLevel(0) return } + cleanupMicTest(false) + micTestActiveRef.current = true setMicTesting(true) setMicTestFailed(false) setMicLevel(0) - // level 0은 무음/초기화 중일 뿐 — 종료 판정은 done 플래그로만 const unsub = window.electronAPI.audio.onTestLevel((e) => { + if (!mountedRef.current || !micTestActiveRef.current) return setMicLevel(e.level) if (e.done) { + cleanupMicTest(false) setMicTesting(false) setMicLevel(0) - unsub() } }) - const result = await window.electronAPI.audio.testDevice({ deviceId: selectedDeviceId }) - if (!result.success) { - setMicTesting(false) - setMicLevel(0) - setMicTestFailed(true) - unsub() + micTestUnsubRef.current = unsub + try { + const result = await window.electronAPI.audio.testDevice({ deviceId: selectedDeviceId }) + if (!mountedRef.current || !micTestActiveRef.current) { + cleanupMicTest(true) + return + } + if (!result.success) { + cleanupMicTest(false) + setMicTesting(false) + setMicLevel(0) + setMicTestFailed(true) + } + } catch { + cleanupMicTest(false) + if (mountedRef.current) { + setMicTesting(false) + setMicLevel(0) + setMicTestFailed(true) + } } - }, [micTesting, selectedDeviceId]) + }, [micTesting, selectedDeviceId, cleanupMicTest]) const handleStartOllama = useCallback(async () => { setStartingOllama(true) setOllamaFeedback(null) try { const res = await window.electronAPI.llm.startServer() + if (!mountedRef.current) return if (!res.success) { setOllamaFeedback({ tone: 'error', message: t('settings.llm.feedback.failed') }) } else if (res.data === 'running') { setOllamaFeedback({ tone: 'info', message: t('settings.llm.feedback.running') }) } else if (res.data === 'starting') { setOllamaFeedback({ tone: 'info', message: t('settings.llm.feedback.started') }) - setTimeout(() => refreshOllama(), 2000) + if (ollamaRefreshTimerRef.current) clearTimeout(ollamaRefreshTimerRef.current) + ollamaRefreshTimerRef.current = setTimeout(() => { + ollamaRefreshTimerRef.current = null + if (mountedRef.current) void refreshOllama() + }, 2000) } else if (res.data === 'not-installed') { setOllamaFeedback({ tone: 'error', message: t('settings.llm.feedback.notInstalled') }) } + } catch { + if (mountedRef.current) { + setOllamaFeedback({ tone: 'error', message: t('settings.llm.feedback.failed') }) + } } finally { - setStartingOllama(false) + if (mountedRef.current) setStartingOllama(false) } }, [refreshOllama, t]) + const handleRestartOnboarding = useCallback(() => { + void window.electronAPI.config + .set({ + key: 'onboardingCompleted', + value: false + }) + .catch(() => {}) + onClose() + if (reloadTimerRef.current) clearTimeout(reloadTimerRef.current) + reloadTimerRef.current = setTimeout(() => { + reloadTimerRef.current = null + window.location.reload() + }, 300) + }, [onClose]) + if (loading) { return ( @@ -278,673 +337,122 @@ export function SettingsModal({ open, initialTab = DEFAULT_SETTINGS_TAB, onClose ) } - const ollamaConnected = ollamaStatus?.connectionState === 'connected' - const ollamaStatusText = - ollamaStatus === null - ? t('settings.llm.ollamaChecking') - : ollamaConnected - ? ollamaStatus.serverVersion - ? t('settings.llm.ollamaConnectedVersion', { version: ollamaStatus.serverVersion, count: ollamaModels.length }) - : t('settings.llm.ollamaConnected', { count: ollamaModels.length }) - : t('settings.llm.ollamaOffline') - const activeOllamaModel = config.llmModelId ?? RECOMMENDED_OLLAMA_MODEL - - // v4: 설정은 모달이 아니라 전체 화면 — 왼쪽 세로 탭 + 오른쪽 한 열(읽기 폭 제한). - // 모달 폭 600px 에 탭 8개가 넘쳐 '클라우드·정보'가 잘리던 문제(2026-09-28 실측)를 구조로 해결한다. return ( - - {t('settings.title')} - - setActiveTab(v)} - aria-label={t('settings.title')} - sx={{ - '& .MuiTabs-indicator': { display: 'none' }, - '& .MuiTab-root': { - alignItems: 'center', - justifyContent: 'flex-start', - gap: 1, - minHeight: 36, - px: 1.5, - py: 0, - borderRadius: d3roRadius.button, - color: d3roPalette.text.secondary, - fontSize: d3roTypo.compact.size, - fontWeight: 400, - textAlign: 'left', - '&:hover': { color: d3roPalette.text.primary, bgcolor: d3roPalette.surface.overlaySoft }, - '&.Mui-selected': { color: d3roPalette.text.primary, fontWeight: 500, bgcolor: d3roPalette.surface.overlayStrong }, - '& svg': { margin: 0 }, - }, - }} - > - {SETTINGS_TAB_ORDER.map((tab) => ( - - ))} - + + {t('settings.title')} + + setActiveTab(v)} + aria-label={t('settings.title')} + sx={{ + '& .MuiTabs-indicator': { display: 'none' }, + '& .MuiTab-root': { + alignItems: 'center', + justifyContent: 'flex-start', + gap: 1, + minHeight: 36, + px: 1.5, + py: 0, + borderRadius: d3roRadius.button, + color: d3roPalette.text.secondary, + fontSize: d3roTypo.compact.size, + fontWeight: 400, + textAlign: 'left', + '&:hover': { color: d3roPalette.text.primary, bgcolor: d3roPalette.surface.overlaySoft }, + '&.Mui-selected': { + color: d3roPalette.text.primary, + fontWeight: 500, + bgcolor: d3roPalette.surface.overlayStrong + }, + '& svg': { margin: 0 } + } + }} + > + {SETTINGS_TAB_ORDER.map((tab) => ( + + ))} + - - {tabMeta[activeTab].label} - + + {tabMeta[activeTab].label} + - {/* ── 일반 탭 ─────────────────────────────── */} - - handleKeybindingToggle(e.target.checked)} - /> - } - label={ - - {t('keybinding.ui.globalEnabled')} - - } - /> - } - description={ - - - {keybindingIssues.length === 0 - ? t('keybinding.ui.auditClear') - : t('keybinding.ui.auditIssues', { count: keybindingIssues.length })} - - {keybindingIssues.slice(0, 3).map((issue) => { - const action = KEYBINDING_ACTIONS.find((entry) => entry.id === issue.actionId) - const actionLabel = action ? t(asTranslationKey(action.labelKey)) : issue.actionId - const conflictLabels = issue.conflictActionIds - .map((actionId) => { - const conflict = KEYBINDING_ACTIONS.find((entry) => entry.id === actionId) - return conflict ? t(asTranslationKey(conflict.labelKey)) : actionId - }) - .join(', ') - return ( - - {issue.kind === 'invalid' - ? t('keybinding.ui.auditInvalid', { - action: actionLabel, - reason: issue.reasonKey ? t(asTranslationKey(issue.reasonKey)) : t('keybinding.ui.auditUnknown') - }) - : t('keybinding.ui.auditConflict', { action: actionLabel, conflicts: conflictLabels })} - - ) - })} - - } - > - {ACTION_GROUP_ORDER.map((group) => { - const actions = KEYBINDING_ACTIONS.filter((action) => action.group === group) - if (actions.length === 0) return null - return ( - - - {t(asTranslationKey(ACTION_GROUP_LABEL_KEYS[group]))} - - {actions.map((action) => ( - - ))} - - ) - })} - + + + - - - - - } - /> - - - - } - /> - + + + - - updateConfig('closeToTray', checked)} - /> - } - /> - updateConfig('autoLaunch', checked)} - /> - } - /> - updateConfig('autoInsert', checked)} - /> - } - /> - updateConfig('soundEnabled', checked)} - /> - } - /> - - + + + - {/* ── 오디오 탭 ────────────────────────────── */} - - - - - - } - /> - - {micTesting ? t('common.stop') : t('common.test')} - - } - > - - 0.7 ? d3roPalette.status.warning : d3roPalette.accent.main, - transition: d3roTransition('width'), - }} - /> - - {micTestFailed && ( - - {t('settings.micTest.failed')} - - )} - - + + + - - - - - } - /> - updateConfig('captionSttModelId', modelId)} - /> - updateConfig('captionRefineEnabled', checked)} - /> - } - /> - + + + - - - - - } - /> - - + + + - {/* ── STT 탭 ───────────────────────────────── */} - - - + + + - {/* ── LLM 탭 ──────────────────────────────── */} - - - - - - } - /> - - {/* 로컬 Ollama */} - {config.llmBackend !== 'online' && ( - <> - - {ollamaStatus !== null && } - {ollamaStatusText} - - } - control={ - <> - - {ollamaStatus !== null && !ollamaConnected && ( - - )} - - } - > - {ollamaFeedback && ( - - {ollamaFeedback.message} - - )} - - - } - onClick={() => window.dispatchEvent(new CustomEvent('d3ro:open-ollama-guide'))} - > - {t('settings.llm.openGuide')} - - } - /> - - - - - } - /> - - updateConfig('ollamaServerUrl', e.target.value)} - size="small" - sx={controlSx} - inputProps={{ 'aria-labelledby': 'settings-ollama-url', spellCheck: false }} - /> - } - /> - - )} - - {/* 온라인 API */} - {config.llmBackend === 'online' && ( - <> - updateConfig('onlineApiUrl', e.target.value)} - size="small" - sx={controlSx} - inputProps={{ 'aria-labelledby': 'settings-online-url', spellCheck: false }} - /> - } - /> - - - )} - - - - - - - } - /> - - - - } - /> - )['voiceCommandsEnabled'] as boolean ?? false} - onChange={(checked) => { - updateConfig('voiceCommandsEnabled' as keyof AppConfig, checked as never) - void window.electronAPI.voiceCommand.setEnabled({ enabled: checked }) - }} - /> - } - /> - { - updateConfig('screenContextEnabled', checked) - void window.electronAPI.context.setEnabled({ enabled: checked }) - }} - /> - } - /> - - - - {/* ── 입력 인사이트 탭 ─────────────────────────── */} - - - - - {/* ── 라이선스 탭 ────────────────────────────── */} - - - - - {/* ── Cloud Sync 탭 ──────────────────────────── */} - - - - - {/* ── 정보 탭 ──────────────────────────────── */} - - - - - - {appVersion === null ? '—' : `v${appVersion}`} - - } - /> - - - - - - { - window.electronAPI.config.set({ - key: 'onboardingCompleted', - value: false, - }) - onClose() - setTimeout(() => window.location.reload(), 300) - }} - > - {t('settings.about.restartOnboarding.action')} - - } - /> - - + + + ) diff --git a/apps/desktop/src/renderer/components/TemplateSection.tsx b/apps/desktop/src/renderer/components/TemplateSection.tsx index 25a3cd4..98677ed 100644 --- a/apps/desktop/src/renderer/components/TemplateSection.tsx +++ b/apps/desktop/src/renderer/components/TemplateSection.tsx @@ -41,17 +41,34 @@ export function TemplateSection(): React.ReactElement { const [saving, setSaving] = useState(false) const isSavingRef = useRef(false) + const mountedRef = useRef(true) + const loadSeqRef = useRef(0) const loadData = useCallback(async () => { + const seq = ++loadSeqRef.current + const isFresh = (): boolean => mountedRef.current && loadSeqRef.current === seq setLoading(true) - const result = await window.electronAPI.dictationTemplate.getAll() - if (result.success) setTemplates(result.data) - const sessionResult = await window.electronAPI.dictationTemplate.getSessionState() - if (sessionResult.success) setSession(sessionResult.data) - setLoading(false) + try { + const result = await window.electronAPI.dictationTemplate.getAll() + if (!isFresh()) return + if (result.success) setTemplates(result.data) + const sessionResult = await window.electronAPI.dictationTemplate.getSessionState() + if (!isFresh()) return + if (sessionResult.success) setSession(sessionResult.data) + } catch { + // IPC 조회 실패 시 마지막 목록/세션 유지 + } finally { + if (isFresh()) setLoading(false) + } }, []) - useEffect(() => { loadData() }, [loadData]) + useEffect(() => { + mountedRef.current = true + void loadData() + return () => { + mountedRef.current = false + } + }, [loadData]) // 다른 기기에서 바뀐 템플릿이 반영되면 다시 불러온다. useEffect( diff --git a/apps/desktop/src/renderer/components/TitleBar.tsx b/apps/desktop/src/renderer/components/TitleBar.tsx index e4e4fdd..efe8621 100644 --- a/apps/desktop/src/renderer/components/TitleBar.tsx +++ b/apps/desktop/src/renderer/components/TitleBar.tsx @@ -4,7 +4,7 @@ // macOS(hiddenInset)에서는 네이티브 교통신호가 좌측에 표시되므로 커스텀 // 컨트롤을 숨기고 그만큼의 좌측 여백을 확보한다. -import { useState, useEffect, useCallback } from 'react' +import { useState, useEffect, useCallback, useRef } from 'react' import { Box } from '@mui/material' import { Minus, Square, Copy, X } from 'lucide-react' import { d3roPalette, d3roRadius } from '@d3ro/ui/theme' @@ -15,16 +15,38 @@ const isDarwin = window.electronAPI?.platform === 'darwin' export function TitleBar(): React.ReactElement { const [isMaximized, setIsMaximized] = useState(false) + const mountedRef = useRef(true) + const maximizeTimerRef = useRef | null>(null) useEffect(() => { - window.electronAPI.window.isMaximized().then((r) => { if (r.success) setIsMaximized(r.data) }) + mountedRef.current = true + window.electronAPI.window + .isMaximized() + .then((r) => { + if (mountedRef.current && r.success) setIsMaximized(r.data) + }) + .catch(() => {}) + return () => { + mountedRef.current = false + if (maximizeTimerRef.current) { + clearTimeout(maximizeTimerRef.current) + maximizeTimerRef.current = null + } + } }, []) const handleMaximize = useCallback(() => { window.electronAPI.window.maximize() // 토글 후 상태 재조회 (이벤트 채널이 없어 폴링 1회) - setTimeout(() => { - window.electronAPI.window.isMaximized().then((r) => { if (r.success) setIsMaximized(r.data) }) + if (maximizeTimerRef.current) clearTimeout(maximizeTimerRef.current) + maximizeTimerRef.current = setTimeout(() => { + maximizeTimerRef.current = null + window.electronAPI.window + .isMaximized() + .then((r) => { + if (mountedRef.current && r.success) setIsMaximized(r.data) + }) + .catch(() => {}) }, 120) }, []) diff --git a/apps/desktop/src/renderer/components/ads/AdBanner.tsx b/apps/desktop/src/renderer/components/ads/AdBanner.tsx index ecbf71b..ce19f41 100644 --- a/apps/desktop/src/renderer/components/ads/AdBanner.tsx +++ b/apps/desktop/src/renderer/components/ads/AdBanner.tsx @@ -3,7 +3,7 @@ // v4(2026-09-28): 광고임을 먼저 밝히는 "광고" 표지, 중립 표면 + 1px 선. 네트워크별 색 배지·강조색 CTA·글로우 제거 — // 광고가 앱의 주 행동(강조색)과 경쟁하지 않는다. -import React, { useState, useEffect, useCallback } from 'react' +import React, { useState, useEffect, useCallback, useRef } from 'react' import { Box, Typography, Button, Link } from '@mui/material' import { ExternalLink } from 'lucide-react' import { d3roPalette, d3roRadius, typoSx } from '@d3ro/ui/theme' @@ -19,10 +19,16 @@ interface AdBannerProps { export function AdBanner({ tier, onUpgrade }: AdBannerProps): React.ReactElement | null { const { t } = useI18n() const [creative, setCreative] = useState(null) + const mountedRef = useRef(true) + const auctionSeqRef = useRef(0) // Fetch highest bidding ad creative via mediation auction const fetchAdAuction = useCallback(async () => { - if (tier !== 'free') return + const seq = ++auctionSeqRef.current + if (tier !== 'free') { + setCreative(null) + return + } setCreative(null) try { if (window.electronAPI?.ads?.requestAuction) { @@ -31,6 +37,7 @@ export function AdBanner({ tier, onUpgrade }: AdBannerProps): React.ReactElement format: 'banner_dock', floorEcpm: 2.0, }) + if (!mountedRef.current || auctionSeqRef.current !== seq) return if (res.success && res.data?.winner) { setCreative(res.data.winner) // Record impression @@ -44,16 +51,30 @@ export function AdBanner({ tier, onUpgrade }: AdBannerProps): React.ReactElement } } } catch { - setCreative(null) + if (mountedRef.current && auctionSeqRef.current === seq) setCreative(null) } }, [tier]) useEffect(() => { - fetchAdAuction() + mountedRef.current = true + if (tier !== 'free') { + auctionSeqRef.current += 1 + setCreative(null) + return () => { + mountedRef.current = false + } + } + void fetchAdAuction() // Auto-refresh ad creative every 45s for free tier - const interval = setInterval(fetchAdAuction, 45000) - return () => clearInterval(interval) - }, [fetchAdAuction]) + const interval = setInterval(() => { + void fetchAdAuction() + }, 45000) + return () => { + mountedRef.current = false + auctionSeqRef.current += 1 + clearInterval(interval) + } + }, [fetchAdAuction, tier]) // 유료 등급(Pro·Pro+·팀·엔터프라이즈)에는 광고를 보이지 않는다 if (tier !== 'free' || creative === null) { diff --git a/apps/desktop/src/renderer/components/ads/RewardedQuotaModal.tsx b/apps/desktop/src/renderer/components/ads/RewardedQuotaModal.tsx index b49aed3..5639bcb 100644 --- a/apps/desktop/src/renderer/components/ads/RewardedQuotaModal.tsx +++ b/apps/desktop/src/renderer/components/ads/RewardedQuotaModal.tsx @@ -3,7 +3,7 @@ // nothing until the main-process verification boundary confirms it. // v4(2026-09-28): MUI Dialog 기본 표면 + 제목 h2 + "광고" 표지. 글로우·청록 배지·가짜 동영상 크롬 제거, 문구 i18n(ads.rewarded.*). -import React, { useState, useEffect, useCallback } from 'react' +import React, { useState, useEffect, useCallback, useRef } from 'react' import { Dialog, DialogTitle, DialogContent, DialogActions, Box, Typography, Button, IconButton, LinearProgress } from '@mui/material' import { X } from 'lucide-react' import { d3roPalette, d3roRadius, typoSx } from '@d3ro/ui/theme' @@ -27,8 +27,13 @@ export function RewardedQuotaModal({ const [completed, setCompleted] = useState(false) const [loading, setLoading] = useState(false) const [errorMessage, setErrorMessage] = useState(null) + const mountedRef = useRef(true) + const openRef = useRef(open) + openRef.current = open + const auctionSeqRef = useRef(0) const fetchRewardedAuction = useCallback(async () => { + const seq = ++auctionSeqRef.current setLoading(true) setErrorMessage(null) setCreative(null) @@ -39,6 +44,7 @@ export function RewardedQuotaModal({ format: 'rewarded_video', floorEcpm: 4.0, }) + if (!mountedRef.current || !openRef.current || auctionSeqRef.current !== seq) return if (res.success && res.data?.winner) { setCreative(res.data.winner) setTimeLeft(res.data.winner.durationSeconds || 15) @@ -53,24 +59,37 @@ export function RewardedQuotaModal({ return } } - setErrorMessage(t('ads.rewarded.notAvailable')) + if (mountedRef.current && openRef.current && auctionSeqRef.current === seq) { + setErrorMessage(t('ads.rewarded.notAvailable')) + } } catch { - setErrorMessage(t('ads.rewarded.unreachable')) + if (mountedRef.current && openRef.current && auctionSeqRef.current === seq) { + setErrorMessage(t('ads.rewarded.unreachable')) + } } finally { - setLoading(false) + if (mountedRef.current && auctionSeqRef.current === seq) setLoading(false) } }, [t]) useEffect(() => { + mountedRef.current = true if (!open) { + auctionSeqRef.current += 1 setCreative(null) setTimeLeft(0) setCompleted(false) + setLoading(false) setErrorMessage(null) - return + return () => { + mountedRef.current = false + } } void fetchRewardedAuction() + return () => { + mountedRef.current = false + auctionSeqRef.current += 1 + } }, [open, fetchRewardedAuction]) useEffect(() => { @@ -91,18 +110,23 @@ export function RewardedQuotaModal({ const handleClaim = async () => { if (creative === null || !completed) return - if (window.electronAPI?.ads?.claimReward) { - const res = await window.electronAPI.ads.claimReward({ - adId: creative.id, - networkId: creative.networkId as string, - }) - if (res.success && res.data?.success && res.data.tokensAdded > 0) { - onRewardClaimed(res.data.tokensAdded) - onClose() - return + try { + if (window.electronAPI?.ads?.claimReward) { + const res = await window.electronAPI.ads.claimReward({ + adId: creative.id, + networkId: creative.networkId as string, + }) + if (!mountedRef.current) return + if (res.success && res.data?.success && res.data.tokensAdded > 0) { + onRewardClaimed(res.data.tokensAdded) + onClose() + return + } } + } catch { + // fall through to verification error message } - setErrorMessage(t('ads.rewarded.verifyFailed')) + if (mountedRef.current) setErrorMessage(t('ads.rewarded.verifyFailed')) } const titleId = 'rewarded-quota-title' diff --git a/apps/desktop/src/renderer/components/input-insights/InputConsentPanel.tsx b/apps/desktop/src/renderer/components/input-insights/InputConsentPanel.tsx index a7c4dc1..caebfbe 100644 --- a/apps/desktop/src/renderer/components/input-insights/InputConsentPanel.tsx +++ b/apps/desktop/src/renderer/components/input-insights/InputConsentPanel.tsx @@ -104,19 +104,32 @@ export function InputConsentPanel(): React.ReactElement { [refresh] ) + const feedbackTimerRef = useRef | null>(null) + useEffect(() => { let cancelled = false - void window.electronAPI.llm.getModels().then((result) => { - if (!cancelled && result.success) setModels(result.data) - }) + void window.electronAPI.llm + .getModels() + .then((result) => { + if (!cancelled && result.success) setModels(result.data) + }) + .catch(() => {}) return () => { cancelled = true + if (feedbackTimerRef.current) { + clearTimeout(feedbackTimerRef.current) + feedbackTimerRef.current = null + } } }, []) const flash = useCallback((message: string, tone: 'success' | 'error' = 'success'): void => { setFeedback({ message, tone }) - setTimeout(() => setFeedback(null), 2500) + if (feedbackTimerRef.current) clearTimeout(feedbackTimerRef.current) + feedbackTimerRef.current = setTimeout(() => { + feedbackTimerRef.current = null + setFeedback(null) + }, 2500) }, []) const handleConsent = useCallback( diff --git a/apps/desktop/src/renderer/components/meeting/EditableSegment.tsx b/apps/desktop/src/renderer/components/meeting/EditableSegment.tsx index b782361..75dafa6 100644 --- a/apps/desktop/src/renderer/components/meeting/EditableSegment.tsx +++ b/apps/desktop/src/renderer/components/meeting/EditableSegment.tsx @@ -3,24 +3,22 @@ import { useState, useRef, useCallback } from 'react' import { Box, TextField, Tooltip, Chip } from '@mui/material' +import { resolveSpeakerColorIndex } from '@d3ro/core/meeting-transcript' import { d3roPalette, d3roFontMono, d3roFontSans, d3roRadius, d3roTransition, d3roFocusRing, typoSx } from '@d3ro/ui/theme' import { useI18n } from '@d3ro/i18n' import { isImeComposingEvent } from '../../utils/keyboard' -// Phase 15.5: 화자별 색상 매핑 (d3roPalette SSOT) -const SPEAKER_COLORS = [ - d3roPalette.tag.purple, - d3roPalette.tag.green, - d3roPalette.tag.orange, - d3roPalette.tag.red, - d3roPalette.tag.blue, -] +// Phase 15.5: 화자별 색상 매핑 (d3roPalette SSOT — 하드코딩 hex/알파 접미사 금지) +const SPEAKER_STYLES = [ + { color: d3roPalette.tag.purple, bg: d3roPalette.tag.purpleBg, border: d3roPalette.tag.purpleGlow }, + { color: d3roPalette.tag.green, bg: d3roPalette.tag.greenBg, border: d3roPalette.tag.greenGlow }, + { color: d3roPalette.tag.orange, bg: d3roPalette.tag.orangeBg, border: d3roPalette.tag.orangeGlow }, + { color: d3roPalette.tag.red, bg: d3roPalette.tag.redBg, border: d3roPalette.tag.redGlow }, + { color: d3roPalette.tag.blue, bg: d3roPalette.tag.blueBg, border: d3roPalette.tag.blueGlow }, +] as const -function getSpeakerColor(speaker: string): string { - // "화자 1" → 0, "화자 2" → 1, ... - const match = /(\d+)$/.exec(speaker) - const idx = match ? (parseInt(match[1], 10) - 1) : 0 - return SPEAKER_COLORS[idx % SPEAKER_COLORS.length] +function getSpeakerStyle(speaker: string): (typeof SPEAKER_STYLES)[number] { + return SPEAKER_STYLES[resolveSpeakerColorIndex(speaker, SPEAKER_STYLES.length)] } interface EditableSegmentProps { @@ -83,7 +81,8 @@ export function EditableSegment({ [handleCommit], ) - const speakerColor = speaker ? getSpeakerColor(speaker) : undefined + const speakerStyle = speaker ? getSpeakerStyle(speaker) : undefined + const speakerColor = speakerStyle?.color if (editing) { return ( @@ -200,7 +199,7 @@ export function EditableSegment({ > {formatTimestamp(timestamp)} - {speaker && ( + {speaker && speakerStyle && ( diff --git a/apps/desktop/src/renderer/components/meeting/MeetingChatPanel.tsx b/apps/desktop/src/renderer/components/meeting/MeetingChatPanel.tsx index 772468d..9badae8 100644 --- a/apps/desktop/src/renderer/components/meeting/MeetingChatPanel.tsx +++ b/apps/desktop/src/renderer/components/meeting/MeetingChatPanel.tsx @@ -144,6 +144,21 @@ export function MeetingChatPanel({ sessionId, onClose }: MeetingChatPanelProps): }, [sessionId]) const isSendingChatRef = useRef(false) + const sendResetTimerRef = useRef | null>(null) + + useEffect(() => { + isSendingChatRef.current = false + if (sendResetTimerRef.current) { + clearTimeout(sendResetTimerRef.current) + sendResetTimerRef.current = null + } + return () => { + if (sendResetTimerRef.current) { + clearTimeout(sendResetTimerRef.current) + sendResetTimerRef.current = null + } + } + }, [sessionId]) const handleSend = useCallback(() => { const text = inputValue.trim() @@ -160,7 +175,9 @@ export function MeetingChatPanel({ sessionId, onClose }: MeetingChatPanelProps): setStreaming(true) window.electronAPI.meetingChat.send({ sessionId, message: text }) inputRef.current?.focus() - setTimeout(() => { + if (sendResetTimerRef.current) clearTimeout(sendResetTimerRef.current) + sendResetTimerRef.current = setTimeout(() => { + sendResetTimerRef.current = null isSendingChatRef.current = false }, 500) }, [inputValue, streaming, sessionId]) diff --git a/apps/desktop/src/renderer/components/meeting/MeetingDetailTabs.tsx b/apps/desktop/src/renderer/components/meeting/MeetingDetailTabs.tsx index ea0e848..1f6ed09 100644 --- a/apps/desktop/src/renderer/components/meeting/MeetingDetailTabs.tsx +++ b/apps/desktop/src/renderer/components/meeting/MeetingDetailTabs.tsx @@ -24,6 +24,7 @@ import type { MeetingExportFormat, MeetingSessionDetail, } from '@d3ro/core/types' +import { toErrorMessage } from '../../utils/error-message' import { useMeetingTranscript } from './useMeetingTranscript' import { useMeetingDocuments } from './useMeetingDocuments' import { buildNotesEnhanceRequest, pickNotesEnhanceTemplateId } from './notes-enhancement' @@ -166,15 +167,25 @@ export function MeetingDetailTabs({ // 템플릿 로드 (다른 기기에서 바뀐 템플릿이 반영되면 다시) useEffect(() => { + let cancelled = false + let loadSeq = 0 const load = (): void => { - window.electronAPI.meetingDocTemplate.getAll().then((resp) => { - if (resp.success) setTemplates(resp.data) - }) + const seq = ++loadSeq + void window.electronAPI.meetingDocTemplate + .getAll() + .then((resp) => { + if (!cancelled && seq === loadSeq && resp.success) setTemplates(resp.data) + }) + .catch(() => {}) } load() - return window.electronAPI.app.onDataChanged((data) => { + const unsub = window.electronAPI.app.onDataChanged((data) => { if (data.type === 'cloud-sync' && data.entities?.includes('user_templates')) load() }) + return () => { + cancelled = true + unsub() + } }, []) // ── 제목 저장 ── (저장이 확정된 뒤에만 반영한다) @@ -186,7 +197,7 @@ export function MeetingDetailTabs({ const resp = await window.electronAPI.meetingMode.updateTitle({ sessionId: detail.id, title }) if (!resp.success) failure = resp.error.message } catch (err: unknown) { - failure = err instanceof Error ? err.message : String(err) + failure = toErrorMessage(err) } if (failure !== null) { notify({ message: t('meetings.renameFailed', { message: failure }), severity: 'error' }) diff --git a/apps/desktop/src/renderer/components/meeting/TranscriptTab.tsx b/apps/desktop/src/renderer/components/meeting/TranscriptTab.tsx index 55031df..e59488a 100644 --- a/apps/desktop/src/renderer/components/meeting/TranscriptTab.tsx +++ b/apps/desktop/src/renderer/components/meeting/TranscriptTab.tsx @@ -2,8 +2,9 @@ // Phase 14.5: 전사 편집 탭 (상세 페이지용) — 요약의 근거. // 복사·내보내기는 상세 머리의 행동 줄 한 곳에 있다(예전 "전사 다운로드" 버튼은 거기로 옮겼다). -import { useEffect, useMemo } from 'react' -import { Box, Switch, FormControlLabel, LinearProgress, Typography } from '@mui/material' +import { useEffect, useMemo, useState } from 'react' +import { Box, Switch, FormControlLabel, LinearProgress, Typography, Chip } from '@mui/material' +import { extractDistinctSpeakers } from '@d3ro/core/meeting-transcript' import { EditableSegment } from './EditableSegment' import { PhysicalButton } from '@d3ro/ui/components/ds' import { d3roPalette, d3roFontMono, typoSx } from '@d3ro/ui/theme' @@ -48,10 +49,23 @@ export function TranscriptTab({ }: TranscriptTabProps): React.ReactElement { const { t } = useI18n() const showEdited = view === 'edited' + const [selectedSpeaker, setSelectedSpeaker] = useState(null) + const distinctSpeakers = useMemo(() => extractDistinctSpeakers(segments), [segments]) + + useEffect(() => { + if (selectedSpeaker && !distinctSpeakers.includes(selectedSpeaker)) { + setSelectedSpeaker(null) + } + }, [distinctSpeakers, selectedSpeaker]) + + const filteredSegments = useMemo( + () => (selectedSpeaker ? segments.filter((s) => s.speaker === selectedSpeaker) : segments), + [segments, selectedSpeaker], + ) // 세그먼트 + 메모를 타임스탬프 순으로 인터리브 const timeline: TimelineItem[] = [ - ...segments.map((s) => ({ + ...filteredSegments.map((s) => ({ kind: 'segment' as const, id: s.id, timestamp: s.timestamp, @@ -139,6 +153,48 @@ export function TranscriptTab({ {/* 다듬기 진행 표시 */} {polishing && } + {/* 복수 화자 필터 칩 */} + {distinctSpeakers.length >= 2 && ( + + setSelectedSpeaker(null)} + variant={selectedSpeaker === null ? 'filled' : 'outlined'} + sx={{ + fontSize: 11, + height: 22, + bgcolor: selectedSpeaker === null ? d3roPalette.accent.dim : 'transparent', + color: selectedSpeaker === null ? d3roPalette.accent.light : d3roPalette.text.secondary, + borderColor: selectedSpeaker === null ? d3roPalette.accent.main : d3roPalette.border.default, + }} + /> + {distinctSpeakers.map((sp) => { + const active = selectedSpeaker === sp + return ( + setSelectedSpeaker(active ? null : sp)} + variant={active ? 'filled' : 'outlined'} + sx={{ + fontSize: 11, + height: 22, + bgcolor: active ? d3roPalette.accent.dim : 'transparent', + color: active ? d3roPalette.accent.light : d3roPalette.text.secondary, + borderColor: active ? d3roPalette.accent.main : d3roPalette.border.default, + }} + /> + ) + })} + + )} + {/* 타임라인 */} {timeline.length === 0 ? ( diff --git a/apps/desktop/src/renderer/components/meeting/meeting-documents-model.ts b/apps/desktop/src/renderer/components/meeting/meeting-documents-model.ts index 1244ed6..7e58d93 100644 --- a/apps/desktop/src/renderer/components/meeting/meeting-documents-model.ts +++ b/apps/desktop/src/renderer/components/meeting/meeting-documents-model.ts @@ -11,6 +11,7 @@ import type { IPCResult } from '@d3ro/core/errors' import type { MeetingDocument } from '@d3ro/core/types' +import { toErrorMessage } from '../../utils/error-message' // ── 상세 탭 · 문서 선택 ───────────────────────────────────────────── @@ -134,10 +135,6 @@ export type DocumentCommandResult = | { status: 'skipped' } | { status: 'failed'; message: string } -function errorMessage(err: unknown): string { - return err instanceof Error ? err.message : String(err) -} - export class MeetingDocumentsStore { private state: MeetingDocumentsState private readonly listeners = new Set<() => void>() @@ -226,7 +223,7 @@ export class MeetingDocumentsStore { try { outcome = await this.port.remove(documentId) } catch (err: unknown) { - outcome = { ok: false, message: errorMessage(err) } + outcome = { ok: false, message: toErrorMessage(err) } } if (!outcome.ok) { this.setState({ ...this.state, error: outcome.message }) @@ -297,7 +294,7 @@ export class MeetingDocumentsStore { try { outcome = await this.port.saveContent(documentId, content) } catch (err: unknown) { - outcome = { ok: false, message: errorMessage(err) } + outcome = { ok: false, message: toErrorMessage(err) } } if (!outcome.ok) { this.setState({ ...this.state, error: outcome.message }) diff --git a/apps/desktop/src/renderer/components/meeting/meeting-format.ts b/apps/desktop/src/renderer/components/meeting/meeting-format.ts index 915d564..7598fd6 100644 --- a/apps/desktop/src/renderer/components/meeting/meeting-format.ts +++ b/apps/desktop/src/renderer/components/meeting/meeting-format.ts @@ -1,17 +1,13 @@ // src/renderer/components/meeting/meeting-format.ts // 회의 화면 공용 표기(React 없음) — 경과 시각, 회의 상태 라벨·배지. +import { formatDurationClockFromMs } from '@d3ro/core/format' import type { TranslationKey } from '@d3ro/i18n' import type { MeetingSessionSummary } from '@d3ro/core/types' /** 녹음 경과·전사 시각 — "mm:ss", 한 시간이 넘으면 "h:mm:ss". 라틴 숫자이므로 모노·tabular 로 그린다. */ export function formatElapsed(ms: number): string { - const totalSec = Math.max(0, Math.floor(ms / 1000)) - const h = Math.floor(totalSec / 3600) - const m = Math.floor((totalSec % 3600) / 60) - const s = totalSec % 60 - const mmss = `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}` - return h > 0 ? `${h}:${mmss}` : mmss + return formatDurationClockFromMs(ms, { padMinutes: true, showHours: true }) } export type MeetingStatus = MeetingSessionSummary['status'] diff --git a/apps/desktop/src/renderer/components/meeting/meeting-transcript-model.ts b/apps/desktop/src/renderer/components/meeting/meeting-transcript-model.ts index faa4276..bfe9f9b 100644 --- a/apps/desktop/src/renderer/components/meeting/meeting-transcript-model.ts +++ b/apps/desktop/src/renderer/components/meeting/meeting-transcript-model.ts @@ -7,6 +7,7 @@ // 영속화는 SaveEditedTranscript 포트로 주입받아 IPC 없이도 검증할 수 있다. import type { IPCResult } from '@d3ro/core/errors' +import { toErrorMessage } from '../../utils/error-message' import { applyTranscriptSegmentEdit, isTranscriptViewEditable, @@ -33,10 +34,6 @@ export type TranscriptCommandResult = | { status: 'skipped'; reason: 'read-only-view' | 'no-change' } | { status: 'failed'; message: string } -function errorMessage(err: unknown): string { - return err instanceof Error ? err.message : String(err) -} - /** meetingMode.updateTranscript 형태의 IPC 호출을 저장 포트로 감싼다. */ export function saveViaUpdateTranscript( updateTranscript: (params: { sessionId: string; editedTranscript: string }) => Promise>, @@ -99,7 +96,7 @@ export class MeetingTranscriptModel { try { outcome = await this.save(next) } catch (err: unknown) { - outcome = { ok: false, message: errorMessage(err) } + outcome = { ok: false, message: toErrorMessage(err) } } if (outcome.ok) return { status: 'saved' } if (this.state.edited === next) { diff --git a/apps/desktop/src/renderer/components/settings/AboutSettingsTab.tsx b/apps/desktop/src/renderer/components/settings/AboutSettingsTab.tsx new file mode 100644 index 0000000..f228235 --- /dev/null +++ b/apps/desktop/src/renderer/components/settings/AboutSettingsTab.tsx @@ -0,0 +1,57 @@ +// src/renderer/components/settings/AboutSettingsTab.tsx +// 설정 화면 — 정보 탭(업데이트 확인·적용, 버전·엔진 정보, 온보딩 재시작). + +import { Button, Typography } from '@mui/material' +import { d3roPalette, typoSx } from '@d3ro/ui/theme' +import { useI18n } from '@d3ro/i18n' +import { SettingRow, SettingsSection } from './SettingsRows' +import { UpdateSection } from './UpdateSection' + +interface AboutSettingsTabProps { + appVersion: string | null + onRestartOnboarding: () => void +} + +export function AboutSettingsTab({ + appVersion, + onRestartOnboarding +}: AboutSettingsTabProps): React.ReactElement { + const { t } = useI18n() + + return ( + <> + + + + + {appVersion === null ? '—' : `v${appVersion}`} + + } + /> + + + + + + + {t('settings.about.restartOnboarding.action')} + + } + /> + + + ) +} diff --git a/apps/desktop/src/renderer/components/settings/AudioSettingsTab.tsx b/apps/desktop/src/renderer/components/settings/AudioSettingsTab.tsx new file mode 100644 index 0000000..a38e17d --- /dev/null +++ b/apps/desktop/src/renderer/components/settings/AudioSettingsTab.tsx @@ -0,0 +1,159 @@ +// src/renderer/components/settings/AudioSettingsTab.tsx +// 설정 화면 — 오디오 탭(마이크 선택·테스트, 실시간 자막, 텍스트 삽입 방식). + +import { Box, Button, FormControl, MenuItem, Select } from '@mui/material' +import { d3roPalette, d3roRadius, d3roTransition } from '@d3ro/ui/theme' +import { useI18n } from '@d3ro/i18n' +import type { AppConfig, AudioDevice, STTModel } from '@d3ro/core/types' +import { CaptionModelSelect } from '../CaptionModelSelect' +import { RowSwitch, SETTING_CONTROL_SX, SettingNote, SettingRow, SettingsSection } from './SettingsRows' +import { clampMicMeterPercent } from './settings-model-helpers' + +interface AudioSettingsTabProps { + config: Partial + audioDevices: readonly AudioDevice[] + selectedDeviceId: string + micTesting: boolean + micLevel: number + micTestFailed: boolean + downloadedSttModels: STTModel[] + onSelectDevice: (deviceId: string) => void + onMicTest: () => void + onUpdateConfig: (key: K, value: AppConfig[K]) => void +} + +export function AudioSettingsTab({ + config, + audioDevices, + selectedDeviceId, + micTesting, + micLevel, + micTestFailed, + downloadedSttModels, + onSelectDevice, + onMicTest, + onUpdateConfig +}: AudioSettingsTabProps): React.ReactElement { + const { t } = useI18n() + const meterPercent = clampMicMeterPercent(micLevel) + + return ( + <> + + + + + } + /> + + {micTesting ? t('common.stop') : t('common.test')} + + } + > + + 0.7 ? d3roPalette.status.warning : d3roPalette.accent.main, + transition: d3roTransition('width') + }} + /> + + {micTestFailed && ( + + {t('settings.micTest.failed')} + + )} + + + + + + + + } + /> + onUpdateConfig('captionSttModelId', modelId)} + /> + onUpdateConfig('captionRefineEnabled', checked)} + /> + } + /> + + + + + + + } + /> + + + ) +} diff --git a/apps/desktop/src/renderer/components/settings/GeneralSettingsTab.tsx b/apps/desktop/src/renderer/components/settings/GeneralSettingsTab.tsx new file mode 100644 index 0000000..c83d4cd --- /dev/null +++ b/apps/desktop/src/renderer/components/settings/GeneralSettingsTab.tsx @@ -0,0 +1,218 @@ +// src/renderer/components/settings/GeneralSettingsTab.tsx +// 설정 화면 — 일반 탭(단축키 감사·표시, 인터페이스 테마·언어, 앱 동작 스위치). + +import { Box, FormControl, FormControlLabel, MenuItem, Select, Switch, Typography } from '@mui/material' +import { d3roPalette, typoSx } from '@d3ro/ui/theme' +import { useI18n, LOCALE_META } from '@d3ro/i18n' +import type { KeyBindingActionGroup } from '@d3ro/core/keybinding' +import { auditKeyBindingMap, KEYBINDING_ACTIONS } from '@d3ro/core/keybinding' +import type { AppConfig, ThemeMode } from '@d3ro/core/types' +import { KeyBindingField } from '../keybinding/KeyBindingField' +import { asTranslationKey } from '../keybinding/translation-key' +import { RowSwitch, SETTING_CONTROL_SX, SettingRow, SettingsSection } from './SettingsRows' + +type KeyBindingAuditIssue = ReturnType[number] + +const ACTION_GROUP_LABEL_KEYS: Readonly> = { + voice: 'keybinding.ui.sectionVoice', + window: 'keybinding.ui.sectionWindow', + input: 'keybinding.ui.sectionInput' +} + +const ACTION_GROUP_ORDER: readonly KeyBindingActionGroup[] = ['voice', 'window', 'input'] + +interface GeneralSettingsTabProps { + config: Partial + keybindingEnabled: boolean + keybindingIssues: readonly KeyBindingAuditIssue[] + onToggleKeybinding: (enabled: boolean) => void + onLanguageChange: (newLocale: string) => void + onUpdateConfig: (key: K, value: AppConfig[K]) => void +} + +export function GeneralSettingsTab({ + config, + keybindingEnabled, + keybindingIssues, + onToggleKeybinding, + onLanguageChange, + onUpdateConfig +}: GeneralSettingsTabProps): React.ReactElement { + const { t, locale } = useI18n() + + return ( + <> + onToggleKeybinding(e.target.checked)} + /> + } + label={ + + {t('keybinding.ui.globalEnabled')} + + } + /> + } + description={ + + + {keybindingIssues.length === 0 + ? t('keybinding.ui.auditClear') + : t('keybinding.ui.auditIssues', { count: keybindingIssues.length })} + + {keybindingIssues.slice(0, 3).map((issue) => { + const action = KEYBINDING_ACTIONS.find((entry) => entry.id === issue.actionId) + const actionLabel = action ? t(asTranslationKey(action.labelKey)) : issue.actionId + const conflictLabels = issue.conflictActionIds + .map((actionId) => { + const conflict = KEYBINDING_ACTIONS.find((entry) => entry.id === actionId) + return conflict ? t(asTranslationKey(conflict.labelKey)) : actionId + }) + .join(', ') + return ( + + {issue.kind === 'invalid' + ? t('keybinding.ui.auditInvalid', { + action: actionLabel, + reason: issue.reasonKey ? t(asTranslationKey(issue.reasonKey)) : t('keybinding.ui.auditUnknown') + }) + : t('keybinding.ui.auditConflict', { action: actionLabel, conflicts: conflictLabels })} + + ) + })} + + } + > + {ACTION_GROUP_ORDER.map((group) => { + const actions = KEYBINDING_ACTIONS.filter((action) => action.group === group) + if (actions.length === 0) return null + return ( + + + {t(asTranslationKey(ACTION_GROUP_LABEL_KEYS[group]))} + + {actions.map((action) => ( + + ))} + + ) + })} + + + + + + + } + /> + + + + } + /> + + + + onUpdateConfig('closeToTray', checked)} + /> + } + /> + onUpdateConfig('autoLaunch', checked)} + /> + } + /> + onUpdateConfig('autoInsert', checked)} + /> + } + /> + onUpdateConfig('soundEnabled', checked)} + /> + } + /> + + + ) +} diff --git a/apps/desktop/src/renderer/components/settings/LlmSettingsTab.tsx b/apps/desktop/src/renderer/components/settings/LlmSettingsTab.tsx new file mode 100644 index 0000000..0cebdbf --- /dev/null +++ b/apps/desktop/src/renderer/components/settings/LlmSettingsTab.tsx @@ -0,0 +1,310 @@ +// src/renderer/components/settings/LlmSettingsTab.tsx +// 설정 화면 — LLM 탭(로컬 Ollama / 온라인 API 전환 및 후처리 기본 옵션). + +import { Box, Button, FormControl, MenuItem, Select, TextField } from '@mui/material' +import { HelpCircle, Play, RefreshCw } from 'lucide-react' +import { d3roPalette } from '@d3ro/ui/theme' +import { Led } from '@d3ro/ui/components/ds' +import { useI18n } from '@d3ro/i18n' +import type { AppConfig, LLMModel, LLMStatus } from '@d3ro/core/types' +import { RowSwitch, SETTING_CONTROL_SX, SettingNote, SettingRow, SettingsSection } from './SettingsRows' +import { + RECOMMENDED_OLLAMA_MODEL, + formatModelSizeGb, + listUninstalledFallbackModels, + resolveActiveOllamaModel, + resolveOllamaStatusSummary +} from './settings-model-helpers' + +export type OllamaFeedback = { tone: 'info' | 'error'; message: string } + +interface LlmSettingsTabProps { + config: Partial + ollamaStatus: LLMStatus | null + ollamaModels: readonly LLMModel[] + checkingOllama: boolean + startingOllama: boolean + ollamaFeedback: OllamaFeedback | null + onRefreshOllama: () => void + onStartOllama: () => void + onUpdateConfig: (key: K, value: AppConfig[K]) => void +} + +export function LlmSettingsTab({ + config, + ollamaStatus, + ollamaModels, + checkingOllama, + startingOllama, + ollamaFeedback, + onRefreshOllama, + onStartOllama, + onUpdateConfig +}: LlmSettingsTabProps): React.ReactElement { + const { t } = useI18n() + + const statusSummary = resolveOllamaStatusSummary(ollamaStatus, ollamaModels.length) + const ollamaConnected = statusSummary.kind === 'connected' || statusSummary.kind === 'connectedVersion' + const ollamaStatusText = + statusSummary.kind === 'checking' + ? t('settings.llm.ollamaChecking') + : statusSummary.kind === 'connectedVersion' + ? t('settings.llm.ollamaConnectedVersion', { + version: statusSummary.version, + count: statusSummary.count + }) + : statusSummary.kind === 'connected' + ? t('settings.llm.ollamaConnected', { count: statusSummary.count }) + : t('settings.llm.ollamaOffline') + + const activeOllamaModel = resolveActiveOllamaModel(config.llmModelId) + const uninstalledFallbackModels = listUninstalledFallbackModels(ollamaModels) + + return ( + <> + + + + + } + /> + + {config.llmBackend !== 'online' && ( + <> + + {ollamaStatus !== null && } + {ollamaStatusText} + + } + control={ + <> + + {ollamaStatus !== null && !ollamaConnected && ( + + )} + + } + > + {ollamaFeedback && ( + + {ollamaFeedback.message} + + )} + + + } + onClick={() => window.dispatchEvent(new CustomEvent('d3ro:open-ollama-guide'))} + > + {t('settings.llm.openGuide')} + + } + /> + + + + + } + /> + + onUpdateConfig('ollamaServerUrl', e.target.value)} + size="small" + sx={SETTING_CONTROL_SX} + inputProps={{ 'aria-labelledby': 'settings-ollama-url', spellCheck: false }} + /> + } + /> + + )} + + {config.llmBackend === 'online' && ( + <> + onUpdateConfig('onlineApiUrl', e.target.value)} + size="small" + sx={SETTING_CONTROL_SX} + inputProps={{ 'aria-labelledby': 'settings-online-url', spellCheck: false }} + /> + } + /> + + + )} + + + + + + + } + /> + + + + } + /> + )['voiceCommandsEnabled'] as boolean) ?? false} + onChange={(checked) => { + onUpdateConfig('voiceCommandsEnabled' as keyof AppConfig, checked as never) + void window.electronAPI.voiceCommand.setEnabled({ enabled: checked }) + }} + /> + } + /> + { + onUpdateConfig('screenContextEnabled', checked) + void window.electronAPI.context.setEnabled({ enabled: checked }) + }} + /> + } + /> + + + ) +} diff --git a/apps/desktop/src/renderer/components/settings/SettingsRows.tsx b/apps/desktop/src/renderer/components/settings/SettingsRows.tsx index 8bff0d5..abd798b 100644 --- a/apps/desktop/src/renderer/components/settings/SettingsRows.tsx +++ b/apps/desktop/src/renderer/components/settings/SettingsRows.tsx @@ -3,7 +3,7 @@ // 행 = 왼쪽 라벨+설명(tertiary), 오른쪽 컨트롤. 카드 속 카드·글로우·모노 대문자 라벨을 쓰지 않는다. import { useId } from 'react' -import { Box, Typography } from '@mui/material' +import { Box, Switch, Typography } from '@mui/material' import { d3roPalette, typoSx } from '@d3ro/ui/theme' interface SettingsSectionProps { @@ -93,3 +93,23 @@ export function SettingNote({ children, color }: { children: React.ReactNode; co /** 행 안 Select·TextField 의 공통 폭 */ export const SETTING_CONTROL_WIDTH = 240 +export const SETTING_CONTROL_SX = { width: SETTING_CONTROL_WIDTH, maxWidth: '100%' } as const + +/** 행 오른쪽 스위치 — 라벨은 행 왼쪽 글자(aria-labelledby)가 맡는다. */ +export function RowSwitch({ + labelId, + checked, + onChange, +}: { + labelId: string + checked: boolean + onChange: (checked: boolean) => void +}): React.ReactElement { + return ( + onChange(e.target.checked)} + inputProps={{ 'aria-labelledby': labelId }} + /> + ) +} diff --git a/apps/desktop/src/renderer/components/settings/settings-model-helpers.ts b/apps/desktop/src/renderer/components/settings/settings-model-helpers.ts new file mode 100644 index 0000000..f5e573d --- /dev/null +++ b/apps/desktop/src/renderer/components/settings/settings-model-helpers.ts @@ -0,0 +1,48 @@ +// src/renderer/components/settings/settings-model-helpers.ts +// 설정 화면(오디오·로컬 LLM)에서 사용하는 순수 상태·포맷 계산 함수. + +import type { LLMModel, LLMStatus } from '@d3ro/core/types' + +/** 설치된 모델이 없을 때도 고를 수 있게 보여 주는 기본 후보 */ +export const RECOMMENDED_OLLAMA_MODEL = 'gemma4:e4b' +export const FALLBACK_OLLAMA_MODELS = ['llama3.2:3b', 'qwen2.5:3b'] as const + +export type OllamaStatusSummary = + | { kind: 'checking' } + | { kind: 'offline' } + | { kind: 'connected'; count: number } + | { kind: 'connectedVersion'; version: string; count: number } + +export function resolveActiveOllamaModel(configuredModelId: string | null | undefined): string { + return configuredModelId && configuredModelId.trim().length > 0 + ? configuredModelId + : RECOMMENDED_OLLAMA_MODEL +} + +export function listUninstalledFallbackModels( + installedModels: readonly Pick[] +): string[] { + return FALLBACK_OLLAMA_MODELS.filter((name) => !installedModels.some((model) => model.name === name)) +} + +export function formatModelSizeGb(sizeBytes: number): number { + if (!Number.isFinite(sizeBytes) || sizeBytes <= 0) return 0 + return Math.round((sizeBytes / (1024 * 1024 * 1024)) * 10) / 10 +} + +export function clampMicMeterPercent(level: number): number { + if (!Number.isFinite(level) || level <= 0) return 0 + return Math.min(100, Math.max(0, Math.round(level * 100))) +} + +export function resolveOllamaStatusSummary( + status: Pick | null, + modelCount: number +): OllamaStatusSummary { + if (status === null) return { kind: 'checking' } + if (status.connectionState !== 'connected') return { kind: 'offline' } + if (status.serverVersion) { + return { kind: 'connectedVersion', version: status.serverVersion, count: modelCount } + } + return { kind: 'connected', count: modelCount } +} diff --git a/apps/desktop/src/renderer/components/voice-conversation/VoiceRecordingPanel.tsx b/apps/desktop/src/renderer/components/voice-conversation/VoiceRecordingPanel.tsx index ca23564..20b033a 100644 --- a/apps/desktop/src/renderer/components/voice-conversation/VoiceRecordingPanel.tsx +++ b/apps/desktop/src/renderer/components/voice-conversation/VoiceRecordingPanel.tsx @@ -12,16 +12,12 @@ import { useEffect, useRef, useState } from 'react' import { Box, Typography } from '@mui/material' import { GradientWave, Led } from '@d3ro/ui/components/ds' import { d3roPalette, d3roFontMono, d3roRadius, typoSx } from '@d3ro/ui/theme' +import { formatDurationClockFromMs } from '@d3ro/core/format' import { useI18n } from '@d3ro/i18n' const WAVE_HEIGHT = 48 -function formatDuration(ms: number): string { - const elapsed = Math.floor(ms / 1000) - const minutes = Math.floor(elapsed / 60) - const seconds = elapsed % 60 - return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}` -} +const formatDuration = (ms: number): string => formatDurationClockFromMs(ms) /** * Voice Conversation이 listening 상태일 때만 렌더되는 몰입 녹음 패널. diff --git a/apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts b/apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts index 500176f..8f273e2 100644 --- a/apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts +++ b/apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts @@ -1,7 +1,7 @@ // src/renderer/hooks/useAppUpdateStatus.ts // 앱 업데이트 상태 구독 — 설정 정보 탭(UpdateSection)과 타이틀바 칩(UpdateChip)이 같이 쓴다. -import { useCallback, useEffect, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import type { AppUpdateStatus } from '@d3ro/core/types' export interface AppUpdateControls { @@ -16,15 +16,26 @@ export interface AppUpdateControls { export function useAppUpdateStatus(): AppUpdateControls { const [status, setStatus] = useState(null) const [busy, setBusy] = useState(false) + const aliveRef = useRef(true) + const receivedEventRef = useRef(false) useEffect(() => { - let alive = true - void window.electronAPI.appUpdate.getStatus().then((result) => { - if (alive && result.success) setStatus(result.data) + aliveRef.current = true + receivedEventRef.current = false + void window.electronAPI.appUpdate + .getStatus() + .then((result) => { + if (aliveRef.current && !receivedEventRef.current && result.success) { + setStatus(result.data) + } + }) + .catch(() => {}) + const unsubscribe = window.electronAPI.appUpdate.onStatusChanged((next) => { + receivedEventRef.current = true + setStatus(next) }) - const unsubscribe = window.electronAPI.appUpdate.onStatusChanged((next) => setStatus(next)) return () => { - alive = false + aliveRef.current = false unsubscribe() } }, []) @@ -33,9 +44,12 @@ export function useAppUpdateStatus(): AppUpdateControls { setBusy(true) void request() .then((result) => { - if (result.success) setStatus(result.data) + if (aliveRef.current && result.success) setStatus(result.data) + }) + .catch(() => {}) + .finally(() => { + if (aliveRef.current) setBusy(false) }) - .finally(() => setBusy(false)) }, []) return { diff --git a/apps/desktop/src/renderer/hooks/useKeyBindingMap.ts b/apps/desktop/src/renderer/hooks/useKeyBindingMap.ts index 74ecb68..0d5f278 100644 --- a/apps/desktop/src/renderer/hooks/useKeyBindingMap.ts +++ b/apps/desktop/src/renderer/hooks/useKeyBindingMap.ts @@ -22,9 +22,12 @@ function ensureSubscribed(): void { if (subscribed) return subscribed = true window.electronAPI.keybinding.onChanged((event) => publish(event.map)) - void window.electronAPI.keybinding.getMap().then((result) => { - if (result.success) publish(result.data) - }) + void window.electronAPI.keybinding + .getMap() + .then((result) => { + if (result.success) publish(result.data) + }) + .catch(() => {}) } /** 맵이 아직 도착하지 않았으면 null. */ diff --git a/apps/desktop/src/renderer/hooks/useLicenseState.ts b/apps/desktop/src/renderer/hooks/useLicenseState.ts index 375a01d..cf3c604 100644 --- a/apps/desktop/src/renderer/hooks/useLicenseState.ts +++ b/apps/desktop/src/renderer/hooks/useLicenseState.ts @@ -1,7 +1,7 @@ // src/renderer/hooks/useLicenseState.ts // LicenseTab/LicenseModal 공용 — 라이선스 + 클라우드 인증 상태 관리 -import { useState, useEffect, useCallback } from 'react' +import { useState, useEffect, useCallback, useRef } from 'react' import type { LicenseInfo, LicenseTier, @@ -33,30 +33,52 @@ export function useLicenseState(): LicenseState { const [usage, setUsage] = useState([]) const [comparison, setComparison] = useState([]) const [cloud, setCloud] = useState({ authenticated: false, userEmail: null }) + const mountedRef = useRef(true) + const loadSeqRef = useRef(0) const loadData = useCallback(() => { - window.electronAPI.license.getInfo().then((r) => { - if (r.success) setLicenseInfo(r.data) - }) - window.electronAPI.license.getAllUsage().then((r) => { - if (r.success) setUsage(r.data) - }) - window.electronAPI.license.getTierComparison().then((r) => { - if (r.success) setComparison(r.data) - }) - window.electronAPI.cloudSync.getState().then((r) => { - if (r.success) setCloud({ authenticated: r.data.authenticated, userEmail: r.data.userEmail }) - }) + const seq = ++loadSeqRef.current + const isFresh = (): boolean => mountedRef.current && loadSeqRef.current === seq + + window.electronAPI.license + .getInfo() + .then((r) => { + if (isFresh() && r.success) setLicenseInfo(r.data) + }) + .catch(() => {}) + window.electronAPI.license + .getAllUsage() + .then((r) => { + if (isFresh() && r.success) setUsage(r.data) + }) + .catch(() => {}) + window.electronAPI.license + .getTierComparison() + .then((r) => { + if (isFresh() && r.success) setComparison(r.data) + }) + .catch(() => {}) + window.electronAPI.cloudSync + .getState() + .then((r) => { + if (isFresh() && r.success) setCloud({ authenticated: r.data.authenticated, userEmail: r.data.userEmail }) + }) + .catch(() => {}) }, []) useEffect(() => { + mountedRef.current = true loadData() const unsubTier = window.electronAPI.license.onTierChanged(() => loadData()) const unsubAuth = window.electronAPI.cloudSync.onAuthChanged((payload) => { setCloud({ authenticated: payload.user !== null, userEmail: payload.user?.email ?? null }) loadData() }) - return () => { unsubTier(); unsubAuth() } + return () => { + mountedRef.current = false + unsubTier() + unsubAuth() + } }, [loadData]) const currentTier = licenseInfo?.tier ?? 'free' diff --git a/apps/desktop/src/renderer/pages/HomePage.tsx b/apps/desktop/src/renderer/pages/HomePage.tsx index 877d2ba..1b768b9 100644 --- a/apps/desktop/src/renderer/pages/HomePage.tsx +++ b/apps/desktop/src/renderer/pages/HomePage.tsx @@ -5,7 +5,7 @@ // 방금 무엇을 했나(최근 기록·최근 회의), 막힌 것이 있나(조회된 상태만 — 조회하지 않은 상태를 '정상'이라 쓰지 않는다). // 통계는 한 줄. 카드·링·글로우 없이 제목과 1px 선으로 구획한다. -import React, { useCallback, useEffect, useState } from 'react' +import React, { useCallback, useEffect, useRef, useState } from 'react' import { Alert, Box, Button, ButtonBase, Tooltip, Typography } from '@mui/material' import { Captions, CaptionsOff, Users } from 'lucide-react' import { PhysicalButton, TactileBadge } from '@d3ro/ui/components/ds' @@ -129,45 +129,90 @@ export function HomePage(): React.ReactElement { const [meetingRecording, setMeetingRecording] = useState(false) const [licenseTier, setLicenseTier] = useState('free') const [usageQuotas, setUsageQuotas] = useState([]) + const mountedRef = useRef(true) + const loadSeqRef = useRef(0) + const llmEventSeqRef = useRef(0) + const captionEventSeqRef = useRef(0) const loadData = useCallback(() => { - window.electronAPI.stats.getSummary().then((r) => { - if (r.success) setStats(r.data) - }) - window.electronAPI.history.getAll({ page: 0, pageSize: RECENT_RECORDS, sortOrder: 'desc' }).then((r) => { - setRecords(r.success ? r.data.entries : []) - }) - window.electronAPI.meetingMode.getSessions({ page: 1, pageSize: RECENT_MEETINGS }).then((r) => { - setMeetings(r.success ? r.data.sessions : []) - }) - window.electronAPI.llm.getStatus().then((r) => { - if (r.success) setLlmConnected(r.data.connectionState === 'connected') - }) - window.electronAPI.caption.getState().then((r) => { - if (r.success) setCaptionState(r.data) - }) - window.electronAPI.meetingMode.getState().then((r) => { - if (r.success) setMeetingRecording(r.data.state === 'recording') - }) - window.electronAPI.license.getInfo().then((r) => { - if (r.success) setLicenseTier(r.data.tier) - }) - window.electronAPI.license.getAllUsage().then((r) => { - if (r.success) setUsageQuotas(r.data) - }) + const seq = ++loadSeqRef.current + const llmSeq = llmEventSeqRef.current + const captionSeq = captionEventSeqRef.current + const isFresh = (): boolean => mountedRef.current && loadSeqRef.current === seq + + window.electronAPI.stats + .getSummary() + .then((r) => { + if (isFresh() && r.success) setStats(r.data) + }) + .catch(() => {}) + window.electronAPI.history + .getAll({ page: 0, pageSize: RECENT_RECORDS, sortOrder: 'desc' }) + .then((r) => { + if (isFresh()) setRecords(r.success ? r.data.entries : []) + }) + .catch(() => {}) + window.electronAPI.meetingMode + .getSessions({ page: 1, pageSize: RECENT_MEETINGS }) + .then((r) => { + if (isFresh()) setMeetings(r.success ? r.data.sessions : []) + }) + .catch(() => {}) + window.electronAPI.llm + .getStatus() + .then((r) => { + if (isFresh() && llmEventSeqRef.current === llmSeq && r.success) { + setLlmConnected(r.data.connectionState === 'connected') + } + }) + .catch(() => {}) + window.electronAPI.caption + .getState() + .then((r) => { + if (isFresh() && captionEventSeqRef.current === captionSeq && r.success) { + setCaptionState(r.data) + } + }) + .catch(() => {}) + window.electronAPI.meetingMode + .getState() + .then((r) => { + if (isFresh() && r.success) setMeetingRecording(r.data.state === 'recording') + }) + .catch(() => {}) + window.electronAPI.license + .getInfo() + .then((r) => { + if (isFresh() && r.success) setLicenseTier(r.data.tier) + }) + .catch(() => {}) + window.electronAPI.license + .getAllUsage() + .then((r) => { + if (isFresh() && r.success) setUsageQuotas(r.data) + }) + .catch(() => {}) }, []) useEffect(() => { + mountedRef.current = true loadData() const unsubData = window.electronAPI.app.onDataChanged(() => loadData()) - const unsubLlm = window.electronAPI.llm.onStatusChanged((e) => setLlmConnected(e.status.connectionState === 'connected')) - const unsubCaption = window.electronAPI.caption.onStateChanged((e) => setCaptionState(e.state)) + const unsubLlm = window.electronAPI.llm.onStatusChanged((e) => { + llmEventSeqRef.current += 1 + setLlmConnected(e.status.connectionState === 'connected') + }) + const unsubCaption = window.electronAPI.caption.onStateChanged((e) => { + captionEventSeqRef.current += 1 + setCaptionState(e.state) + }) // 회의 녹음 중의 자막은 회의가 소유한다 — 홈에서 켜고 끌 수 없다. const unsubMeeting = window.electronAPI.meetingMode.onStateChanged((e) => { setMeetingRecording(e.state === 'recording') loadData() }) return () => { + mountedRef.current = false unsubData() unsubLlm() unsubCaption() diff --git a/apps/desktop/src/renderer/pages/KnowledgeBasePage.tsx b/apps/desktop/src/renderer/pages/KnowledgeBasePage.tsx index 3808830..0cef6d0 100644 --- a/apps/desktop/src/renderer/pages/KnowledgeBasePage.tsx +++ b/apps/desktop/src/renderer/pages/KnowledgeBasePage.tsx @@ -53,17 +53,29 @@ export function KnowledgeBasePage(): React.ReactElement { const [adding, setAdding] = useState(false) const [addError, setAddError] = useState(null) const [queryError, setQueryError] = useState(null) + const mountedRef = useRef(true) + const docsSeqRef = useRef(0) + const querySeqRef = useRef(0) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + } + }, []) const loadDocuments = useCallback(async () => { + const seq = ++docsSeqRef.current setLoading(true) try { const resp = await window.electronAPI.rag.getDocuments() + if (!mountedRef.current || docsSeqRef.current !== seq) return if (resp.success) setDocuments(resp.data) setLoadError(!resp.success) } catch { - setLoadError(true) + if (mountedRef.current && docsSeqRef.current === seq) setLoadError(true) } finally { - setLoading(false) + if (mountedRef.current && docsSeqRef.current === seq) setLoading(false) } }, []) @@ -81,12 +93,16 @@ export function KnowledgeBasePage(): React.ReactElement { // 색인 실행이 끝나면(성공·실패 무관) 진행 표시를 내리고, 문서가 끝내 색인되지 않았으면 알린다. const unsubComplete = window.electronAPI.rag.onIndexComplete((data) => { setIndexProgress(null) - void window.electronAPI.rag.getDocuments().then((resp) => { - if (!resp.success) return - setDocuments(resp.data) - const doc = resp.data.find((d) => d.id === data.documentId) - if (doc && !doc.indexed) setAddError(t('mobile.knowledge.error.indexUnavailable')) - }) + const seq = ++docsSeqRef.current + void window.electronAPI.rag + .getDocuments() + .then((resp) => { + if (!mountedRef.current || docsSeqRef.current !== seq || !resp.success) return + setDocuments(resp.data) + const doc = resp.data.find((d) => d.id === data.documentId) + if (doc && !doc.indexed) setAddError(t('mobile.knowledge.error.indexUnavailable')) + }) + .catch(() => {}) }) return () => { unsubProgress() @@ -103,17 +119,20 @@ export function KnowledgeBasePage(): React.ReactElement { setAddError(null) try { const resp = await window.electronAPI.rag.addDocument() + if (!mountedRef.current) return if (resp.success) { void loadDocuments() } else { const errMessage = resolveRagAddError(resp) if (errMessage) setAddError(errMessage) } + } catch { + if (mountedRef.current) setAddError(t('tools.knowledge.queryFailed')) } finally { - setAdding(false) + if (mountedRef.current) setAdding(false) isAddingRef.current = false } - }, [adding, loadDocuments]) + }, [adding, loadDocuments, t]) const handleRemoveDocument = (doc: RAGDocument) => { remove({ @@ -126,27 +145,36 @@ export function KnowledgeBasePage(): React.ReactElement { const handleReindex = useCallback(async (docId: string) => { setAddError(null) - const resp = await window.electronAPI.rag.reindex(docId) - // 임베딩 실패는 rag:indexComplete 뒤 문서 상태로 알린다. 그 밖의 실패(문서 없음·파싱 실패)만 여기서 보인다. - if (!resp.success && resp.error.code !== ErrorCode.RAGEmbeddingFailed) setAddError(resp.error.message) - }, []) + try { + const resp = await window.electronAPI.rag.reindex(docId) + if (!mountedRef.current) return + // 임베딩 실패는 rag:indexComplete 뒤 문서 상태로 알린다. 그 밖의 실패(문서 없음·파싱 실패)만 여기서 보인다. + if (!resp.success && resp.error.code !== ErrorCode.RAGEmbeddingFailed) setAddError(resp.error.message) + } catch { + if (mountedRef.current) setAddError(t('mobile.knowledge.error.indexUnavailable')) + } + }, [t]) /** 질문할 문장을 인자로 받는다 — 예시 칩이 setQuery 직후 부를 때 이전 query 를 잡지 않게 */ const runQuery = useCallback( async (text: string) => { const trimmed = text.trim() if (!trimmed) return + const seq = ++querySeqRef.current setQuerying(true) setResult(null) setQueryError(null) try { const resp = await window.electronAPI.rag.query({ query: trimmed }) + if (!mountedRef.current || querySeqRef.current !== seq) return if (resp.success) setResult(resp.data) else setQueryError(resp.error?.message || t('tools.knowledge.queryFailed')) } catch { - setQueryError(t('tools.knowledge.queryFailed')) + if (mountedRef.current && querySeqRef.current === seq) { + setQueryError(t('tools.knowledge.queryFailed')) + } } finally { - setQuerying(false) + if (mountedRef.current && querySeqRef.current === seq) setQuerying(false) } }, [t], diff --git a/apps/desktop/src/renderer/pages/MeetingModePage.tsx b/apps/desktop/src/renderer/pages/MeetingModePage.tsx index f571681..eab2e38 100644 --- a/apps/desktop/src/renderer/pages/MeetingModePage.tsx +++ b/apps/desktop/src/renderer/pages/MeetingModePage.tsx @@ -98,6 +98,21 @@ export function MeetingModePage(): React.ReactElement { // 상세 뷰 상태 const [detail, setDetail] = useState(null) + const detailIdRef = useRef(null) + detailIdRef.current = detail?.id ?? null + const mountedRef = useRef(true) + const segmentScrollTimerRef = useRef | null>(null) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + if (segmentScrollTimerRef.current) { + clearTimeout(segmentScrollTimerRef.current) + segmentScrollTimerRef.current = null + } + } + }, []) // ── 사전 환경 점검 로드 ── (헤더 설명 한 줄: 마이크 · 음성 인식) useEffect(() => { @@ -152,21 +167,29 @@ export function MeetingModePage(): React.ReactElement { // 다른 기기(모바일·웹)에서 보고 있던 회의가 지워졌으면 목록으로 돌아간다(편집 중인 상세는 덮어쓰지 않는다). // 목록의 다시 불러오기는 MeetingListView 가 맡는다. - useEffect( - () => - window.electronAPI.app.onDataChanged((data) => { - if (data.type !== 'cloud-sync' || viewRef.current !== 'detail' || !detail) return - const entities = data.entities ?? [] - if (!entities.some((e) => e === 'meetings' || e === 'meeting_memos' || e === 'meeting_documents')) return - window.electronAPI.meetingMode.getSession({ sessionId: detail.id }).then((resp) => { + useEffect(() => { + let cancelled = false + const unsub = window.electronAPI.app.onDataChanged((data) => { + const targetId = detailIdRef.current + if (data.type !== 'cloud-sync' || viewRef.current !== 'detail' || !targetId) return + const entities = data.entities ?? [] + if (!entities.some((e) => e === 'meetings' || e === 'meeting_memos' || e === 'meeting_documents')) return + void window.electronAPI.meetingMode + .getSession({ sessionId: targetId }) + .then((resp) => { + if (cancelled || detailIdRef.current !== targetId || viewRef.current !== 'detail') return if (!resp.success) { setDetail(null) setView('list') } }) - }), - [detail, setView], - ) + .catch(() => {}) + }) + return () => { + cancelled = true + unsub() + } + }, [setView]) // ── IPC 이벤트 구독 ── useEffect(() => { @@ -180,7 +203,9 @@ export function MeetingModePage(): React.ReactElement { const unsubSegment = window.electronAPI.meetingMode.onSegment((seg) => { setSegments((prev) => [...prev, seg]) - setTimeout(() => { + if (segmentScrollTimerRef.current) clearTimeout(segmentScrollTimerRef.current) + segmentScrollTimerRef.current = setTimeout(() => { + segmentScrollTimerRef.current = null if (transcriptRef.current) { transcriptRef.current.scrollTop = transcriptRef.current.scrollHeight } @@ -408,6 +433,7 @@ export function MeetingModePage(): React.ReactElement { isViewingDetailRef.current = true try { const resp = await window.electronAPI.meetingMode.getSession({ sessionId }) + if (!mountedRef.current) return if (resp.success) { setDetail(resp.data) setView('detail') @@ -415,7 +441,9 @@ export function MeetingModePage(): React.ReactElement { notify({ message: t('meeting.viewDetailError'), severity: 'error' }) } } catch { - notify({ message: t('meeting.viewDetailError'), severity: 'error' }) + if (mountedRef.current) { + notify({ message: t('meeting.viewDetailError'), severity: 'error' }) + } } finally { isViewingDetailRef.current = false } diff --git a/apps/desktop/src/renderer/pages/UnifiedSearchPage.tsx b/apps/desktop/src/renderer/pages/UnifiedSearchPage.tsx index 8293024..a30f391 100644 --- a/apps/desktop/src/renderer/pages/UnifiedSearchPage.tsx +++ b/apps/desktop/src/renderer/pages/UnifiedSearchPage.tsx @@ -24,6 +24,16 @@ type SearchState = | { status: 'ready'; response: UnifiedSearchResponse } | { status: 'error' } +function formatSearchDate(occurredAt: number, locale: string): { iso?: string; label: string } { + if (!Number.isFinite(occurredAt)) return { label: '' } + const date = new Date(occurredAt) + if (!Number.isFinite(date.getTime())) return { label: '' } + return { + iso: date.toISOString(), + label: date.toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' }), + } +} + function resultIcon(source: UnifiedSearchResult['source']): React.ReactElement { return source === 'record' ? : } @@ -148,6 +158,7 @@ export function UnifiedSearchPage(): React.ReactElement { const title = result.title?.trim() || (result.source === 'record' ? t('unifiedSearch.untitledRecord') : t('unifiedSearch.untitledMeeting')) + const searchDate = formatSearchDate(result.occurredAt, locale) return ( @@ -201,10 +212,10 @@ export function UnifiedSearchPage(): React.ReactElement { - {new Date(result.occurredAt).toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' })} + {searchDate.label} diff --git a/apps/desktop/src/renderer/pages/VoiceConversationPage.tsx b/apps/desktop/src/renderer/pages/VoiceConversationPage.tsx index 1947c1a..4dd5e98 100644 --- a/apps/desktop/src/renderer/pages/VoiceConversationPage.tsx +++ b/apps/desktop/src/renderer/pages/VoiceConversationPage.tsx @@ -78,12 +78,21 @@ export function VoiceConversationPage(): React.ReactElement { const streamingText = isRealtime ? realtime.streamingText : localStreamingText const streamingMsgId = isRealtime ? realtime.streamingMsgId : localStreamingMsgId + const scrollTimerRef = useRef | null>(null) + useEffect(() => { - window.electronAPI.config.getAll().then((r) => { - if (r.success && r.data.conversationBackend === 'realtime') { - setBackend('realtime') - } - }) + let cancelled = false + window.electronAPI.config + .getAll() + .then((r) => { + if (!cancelled && r.success && r.data.conversationBackend === 'realtime') { + setBackend('realtime') + } + }) + .catch(() => {}) + return () => { + cancelled = true + } }, []) useEffect(() => { @@ -96,58 +105,86 @@ export function VoiceConversationPage(): React.ReactElement { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) }, []) + const scheduleScrollToBottom = useCallback(() => { + if (scrollTimerRef.current) clearTimeout(scrollTimerRef.current) + scrollTimerRef.current = setTimeout(() => { + scrollTimerRef.current = null + scrollToBottom() + }, 50) + }, [scrollToBottom]) + useEffect(() => { + return () => { + if (scrollTimerRef.current) { + clearTimeout(scrollTimerRef.current) + scrollTimerRef.current = null + } + } + }, []) + + useEffect(() => { + let cancelled = false + let receivedLiveEvent = false + const unsubState = window.electronAPI.voiceConversation.onStateChanged((info) => { + receivedLiveEvent = true setLocalState(info.state) setLocalMessages(info.messages) setLocalActive(info.isActive) }) const unsubUser = window.electronAPI.voiceConversation.onUserMessage((msg) => { + receivedLiveEvent = true setLocalMessages((prev) => [...prev, msg]) setLocalStreamingText('') setLocalStreamingMsgId(null) - setTimeout(scrollToBottom, 50) + scheduleScrollToBottom() }) const unsubDelta = window.electronAPI.voiceConversation.onAssistantDelta( (data: ConversationAssistantDelta) => { + receivedLiveEvent = true setLocalStreamingMsgId(data.messageId) setLocalStreamingText(data.accumulated) - setTimeout(scrollToBottom, 50) + scheduleScrollToBottom() }, ) const unsubComplete = window.electronAPI.voiceConversation.onAssistantMessage((msg) => { + receivedLiveEvent = true setLocalMessages((prev) => [ ...prev, { id: msg.messageId, role: 'assistant', content: msg.content, timestamp: Date.now() }, ]) setLocalStreamingText('') setLocalStreamingMsgId(null) - setTimeout(scrollToBottom, 50) + scheduleScrollToBottom() }) const unsubError = window.electronAPI.voiceConversation.onError((err: ConversationError) => { setErrorBanner(err) }) - window.electronAPI.voiceConversation.getState().then((r) => { - if (r.success) { - setLocalState(r.data.state) - setLocalMessages(r.data.messages) - setLocalActive(r.data.isActive) - } - }) + window.electronAPI.voiceConversation + .getState() + .then((r) => { + if (!cancelled && !receivedLiveEvent && r.success) { + setLocalState(r.data.state) + setLocalMessages(r.data.messages) + setLocalActive(r.data.isActive) + } + }) + .catch(() => {}) return () => { + cancelled = true unsubState() unsubUser() unsubDelta() unsubComplete() unsubError() } - }, [scrollToBottom]) + }, [scheduleScrollToBottom]) useEffect(() => { - if (isRealtime) setTimeout(scrollToBottom, 50) - }, [isRealtime, realtime.messages, realtime.streamingText, scrollToBottom]) + if (isRealtime) scheduleScrollToBottom() + }, [isRealtime, realtime.messages, realtime.streamingText, scheduleScrollToBottom]) const isSendingRef = useRef(false) const isStartingSessionRef = useRef(false) diff --git a/apps/desktop/src/renderer/popups/caption-overlay/script.js b/apps/desktop/src/renderer/popups/caption-overlay/script.js index 5e99082..e354f42 100644 --- a/apps/desktop/src/renderer/popups/caption-overlay/script.js +++ b/apps/desktop/src/renderer/popups/caption-overlay/script.js @@ -21,10 +21,11 @@ var i18nStrings = {} // ── 상태 ────────────────────────────────────────────── - /** @type {Array<{el: HTMLElement, timer: number|null, id: string}>} */ + /** @type {Array<{el: HTMLElement, timer: number|null, fadeTimer: number|null, id: string}>} */ var lines = [] /** @type {HTMLElement|null} */ var deltaLine = null + var unsubs = [] // ── 자막 줄 추가 ────────────────────────────────────── @@ -33,6 +34,7 @@ * @param {{id: string, text: string, timestamp: number, isFinal: boolean}} segment */ function addSegment(segment) { + if (!segment || typeof segment.text !== 'string') return // 첫 자막이 오면 준비 안내를 걷는다 (그 전까지는 계속 보여 빈 화면을 만들지 않는다). removeStatusLine() // delta 줄이 있으면 제거 (확정 줄로 교체) @@ -45,11 +47,11 @@ linesContainer.appendChild(el) // auto-clear 타이머 설정 - var timer = setTimeout(function () { + var entry = { el: el, timer: null, fadeTimer: null, id: segment.id } + entry.timer = setTimeout(function () { fadeAndRemoveLine(entry) }, config.autoClearMs) - var entry = { el: el, timer: timer, id: segment.id } lines.push(entry) // maxLines 초과 시 가장 오래된 줄 제거 @@ -57,6 +59,7 @@ var oldest = lines.shift() if (oldest) { if (oldest.timer) clearTimeout(oldest.timer) + if (oldest.fadeTimer) clearTimeout(oldest.fadeTimer) if (oldest.el.parentNode) { oldest.el.parentNode.removeChild(oldest.el) } @@ -69,6 +72,7 @@ * @param {{text: string, isFinal: boolean}} data */ function updateDelta(data) { + if (!data || typeof data !== 'object') return if (data.isFinal) { // isFinal이면 segment로 처리 removeDeltaLine() @@ -105,6 +109,7 @@ * @param {{id: string, text: string}} update */ function updateSegment(update) { + if (!update || typeof update.id !== 'string' || typeof update.text !== 'string') return for (var i = 0; i < lines.length; i++) { if (lines[i].id !== update.id) continue lines[i].el.textContent = update.text @@ -131,8 +136,10 @@ * @param {{el: HTMLElement, timer: number|null, id: string}} entry */ function fadeAndRemoveLine(entry) { + entry.timer = null entry.el.classList.add('fading') - setTimeout(function () { + entry.fadeTimer = setTimeout(function () { + entry.fadeTimer = null if (entry.el.parentNode) { entry.el.parentNode.removeChild(entry.el) } @@ -149,6 +156,7 @@ function clearAllLines() { for (var i = 0; i < lines.length; i++) { if (lines[i].timer) clearTimeout(lines[i].timer) + if (lines[i].fadeTimer) clearTimeout(lines[i].fadeTimer) if (lines[i].el.parentNode) { lines[i].el.parentNode.removeChild(lines[i].el) } @@ -162,10 +170,11 @@ * @param {object} newConfig */ function applyConfig(newConfig) { - if (newConfig.fontSize !== undefined) config.fontSize = newConfig.fontSize - if (newConfig.opacity !== undefined) config.opacity = newConfig.opacity - if (newConfig.maxLines !== undefined) config.maxLines = newConfig.maxLines - if (newConfig.autoClearMs !== undefined) config.autoClearMs = newConfig.autoClearMs + if (!newConfig || typeof newConfig !== 'object') return + if (typeof newConfig.fontSize === 'number' && Number.isFinite(newConfig.fontSize)) config.fontSize = newConfig.fontSize + if (typeof newConfig.opacity === 'number' && Number.isFinite(newConfig.opacity)) config.opacity = newConfig.opacity + if (typeof newConfig.maxLines === 'number' && Number.isFinite(newConfig.maxLines) && newConfig.maxLines >= 1) config.maxLines = newConfig.maxLines + if (typeof newConfig.autoClearMs === 'number' && Number.isFinite(newConfig.autoClearMs) && newConfig.autoClearMs >= 0) config.autoClearMs = newConfig.autoClearMs // 기존 줄에 폰트 크기 반영 for (var i = 0; i < lines.length; i++) { @@ -183,37 +192,45 @@ // ── IPC 리스너 ──────────────────────────────────────── + function registerIpc(channel, handler) { + if (!window.popupAPI) return + var unsub = window.popupAPI.on(channel, handler) + if (typeof unsub === 'function') unsubs.push(unsub) + } + if (window.popupAPI) { // 확정된 자막 세그먼트 - window.popupAPI.on('caption:segment', function (segment) { + registerIpc('caption:segment', function (segment) { addSegment(segment) }) // 중간 전사 결과 (delta) - window.popupAPI.on('caption:delta', function (data) { + registerIpc('caption:delta', function (data) { updateDelta(data) }) // 문맥 다듬기 결과 - window.popupAPI.on('caption:segmentUpdated', function (update) { + registerIpc('caption:segmentUpdated', function (update) { updateSegment(update) }) // 설정 업데이트 - window.popupAPI.on('caption:config', function (newConfig) { + registerIpc('caption:config', function (newConfig) { applyConfig(newConfig) }) // 숨기기 (세션 종료) - window.popupAPI.on('caption:hide', function () { + registerIpc('caption:hide', function () { clearAllLines() + removeStatusLine() }) // 상태 변경 // starting: 음성 모델을 준비하는 중 // active : 듣고 있지만 첫 자막은 아직 — 소리를 모아 첫 인식을 마칠 때까지 몇 초 걸린다. // active 가 되자마자 안내를 지우면 그 몇 초가 빈 화면이라 "고장" 처럼 보였다. - window.popupAPI.on('caption:stateChanged', function (data) { + registerIpc('caption:stateChanged', function (data) { + if (!data || typeof data !== 'object') return if (data._i18n) { i18nStrings = data._i18n if (handleHint) handleHint.textContent = i18nStrings.captionDragHint || '' @@ -225,6 +242,7 @@ if (lines.length === 0) showStatusLine(i18nStrings.captionWaiting) } else if (data.state === 'inactive' || data.state === 'stopping') { clearAllLines() + removeStatusLine() } }) } @@ -263,13 +281,30 @@ if (window.popupAPI) window.popupAPI.send(channel, value) } - document.addEventListener('mousemove', function () { + function onDocumentMouseMove() { if (!root) return root.classList.add('hovering') if (hoverTimer) clearTimeout(hoverTimer) hoverTimer = setTimeout(function () { + hoverTimer = null if (!dragging) root.classList.remove('hovering') }, 1500) + } + + document.addEventListener('mousemove', onDocumentMouseMove) + + window.addEventListener('beforeunload', function () { + clearAllLines() + removeStatusLine() + if (hoverTimer) { + clearTimeout(hoverTimer) + hoverTimer = null + } + document.removeEventListener('mousemove', onDocumentMouseMove) + while (unsubs.length > 0) { + var unsub = unsubs.pop() + if (typeof unsub === 'function') unsub() + } }) if (handle) { diff --git a/apps/desktop/src/renderer/popups/command-popup/script.js b/apps/desktop/src/renderer/popups/command-popup/script.js index 796ba29..c812f14 100644 --- a/apps/desktop/src/renderer/popups/command-popup/script.js +++ b/apps/desktop/src/renderer/popups/command-popup/script.js @@ -12,6 +12,7 @@ var selectedIndex = 0 var currentCommands = [] var i18n = {} + var unsubs = [] function tr(key) { return (i18n && i18n[key]) || '' @@ -59,8 +60,8 @@ } function renderItems(commands, activeId) { - currentCommands = commands - itemsContainer.innerHTML = '' + currentCommands = Array.isArray(commands) ? commands : [] + itemsContainer.textContent = '' items = [] var activeIds = String(activeId || '') .split(',') @@ -73,15 +74,16 @@ itemsContainer.appendChild(none) items.push(none) - if (commands.length === 0) { + if (currentCommands.length === 0) { var empty = document.createElement('div') empty.className = 'list-empty' empty.textContent = tr('commandEmpty') itemsContainer.appendChild(empty) } else { - commands.forEach(function (cmd, i) { - var index = i + 1 - var row = makeRow(index, index <= 9 ? String(index) : '', cmd.name, cmd.description || '', activeIds.indexOf(cmd.id) !== -1, false) + currentCommands.forEach(function (cmd) { + if (!cmd) return + var index = items.length + var row = makeRow(index, index <= 9 ? String(index) : '', cmd.name || '', cmd.description || '', activeIds.indexOf(cmd.id) !== -1, false) itemsContainer.appendChild(row) items.push(row) }) @@ -113,7 +115,21 @@ window.popupAPI.send('command:selected', { id: cmd.id, name: cmd.name }) } - window.popupAPI.on('command:showItems', function (data) { + function registerIpc(channel, handler) { + if (!window.popupAPI) return + var unsub = window.popupAPI.on(channel, handler) + if (typeof unsub === 'function') unsubs.push(unsub) + } + + function cleanup() { + while (unsubs.length > 0) { + var unsub = unsubs.pop() + if (typeof unsub === 'function') unsub() + } + } + + registerIpc('command:showItems', function (data) { + if (!data || typeof data !== 'object') return selectedIndex = 0 if (data._i18n) i18n = data._i18n applyI18nToHtml() @@ -121,17 +137,18 @@ container.classList.remove('hiding') }) - window.popupAPI.on('command:show', function () { + registerIpc('command:show', function () { container.classList.add('visible') container.classList.remove('hiding') }) - window.popupAPI.on('command:hide', function () { + registerIpc('command:hide', function () { container.classList.add('hiding') container.classList.remove('visible') }) - window.popupAPI.on('command:keyEvent', function (data) { + registerIpc('command:keyEvent', function (data) { + if (!data || typeof data.key !== 'string') return var key = data.key if (key === 'ArrowUp') updateSelection(selectedIndex - 1) else if (key === 'ArrowDown') updateSelection(selectedIndex + 1) @@ -142,4 +159,6 @@ if (idx <= currentCommands.length) selectAndApply(idx) } }) + + window.addEventListener('beforeunload', cleanup) })() diff --git a/apps/desktop/src/renderer/popups/history-popup/script.js b/apps/desktop/src/renderer/popups/history-popup/script.js index 196bc9c..5dca30f 100644 --- a/apps/desktop/src/renderer/popups/history-popup/script.js +++ b/apps/desktop/src/renderer/popups/history-popup/script.js @@ -12,6 +12,7 @@ var selectedIndex = 0 var currentEntries = [] var i18n = {} + var unsubs = [] function tr(key) { return (i18n && i18n[key]) || '' @@ -24,7 +25,8 @@ } function relativeTime(timestamp) { - var sec = Math.floor((Date.now() - timestamp) / 1000) + if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) return '' + var sec = Math.max(0, Math.floor((Date.now() - timestamp) / 1000)) if (sec < 60) return tr('timeJustNow') var min = Math.floor(sec / 60) if (min < 60) return tr('timeMinutesAgo').replace('{{m}}', min) @@ -34,11 +36,11 @@ } function renderItems(entries) { - currentEntries = entries - itemsContainer.innerHTML = '' + currentEntries = Array.isArray(entries) ? entries : [] + itemsContainer.textContent = '' items = [] - if (entries.length === 0) { + if (currentEntries.length === 0) { var empty = document.createElement('div') empty.className = 'list-empty' empty.textContent = tr('historyEmpty') @@ -46,7 +48,8 @@ return } - entries.forEach(function (entry, index) { + currentEntries.forEach(function (entry, index) { + if (!entry) return var row = document.createElement('div') row.className = 'd3-item d3-list-item' + (index === selectedIndex ? ' selected' : '') row.id = 'history-item-' + index @@ -59,7 +62,7 @@ var text = document.createElement('span') text.className = 'item-text' - text.textContent = entry.polishedText || entry.originalText + text.textContent = entry.polishedText || entry.originalText || '' var time = document.createElement('span') time.className = 'item-meta d3-numeral' @@ -96,7 +99,21 @@ window.popupAPI.send('history:itemSelected', { id: entry.id, text: entry.polishedText || entry.originalText }) } - window.popupAPI.on('history:showItems', function (data) { + function registerIpc(channel, handler) { + if (!window.popupAPI) return + var unsub = window.popupAPI.on(channel, handler) + if (typeof unsub === 'function') unsubs.push(unsub) + } + + function cleanup() { + while (unsubs.length > 0) { + var unsub = unsubs.pop() + if (typeof unsub === 'function') unsub() + } + } + + registerIpc('history:showItems', function (data) { + if (!data || typeof data !== 'object') return selectedIndex = 0 if (data._i18n) i18n = data._i18n applyI18nToHtml() @@ -104,17 +121,18 @@ container.classList.remove('hiding') }) - window.popupAPI.on('history:show', function () { + registerIpc('history:show', function () { container.classList.add('visible') container.classList.remove('hiding') }) - window.popupAPI.on('history:hide', function () { + registerIpc('history:hide', function () { container.classList.add('hiding') container.classList.remove('visible') }) - window.popupAPI.on('history:keyEvent', function (data) { + registerIpc('history:keyEvent', function (data) { + if (!data || typeof data.key !== 'string') return var key = data.key if (key === 'ArrowUp') updateSelection(selectedIndex - 1) else if (key === 'ArrowDown') updateSelection(selectedIndex + 1) @@ -125,4 +143,6 @@ if (idx < currentEntries.length) selectAndInsert(idx) } }) + + window.addEventListener('beforeunload', cleanup) })() diff --git a/apps/desktop/src/renderer/popups/recording-tip/script.js b/apps/desktop/src/renderer/popups/recording-tip/script.js index f0e143b..3e47ebe 100644 --- a/apps/desktop/src/renderer/popups/recording-tip/script.js +++ b/apps/desktop/src/renderer/popups/recording-tip/script.js @@ -44,6 +44,7 @@ var recordingStartTime = 0 var currentState = 'idle' var i18n = {} + var unsubs = [] function tr(key, fallback) { return (i18n && i18n[key]) || fallback || '' @@ -71,7 +72,7 @@ } function updateDuration() { - var elapsed = Math.floor((Date.now() - recordingStartTime) / 1000) + var elapsed = Math.max(0, Math.floor((Date.now() - recordingStartTime) / 1000)) var minutes = Math.floor(elapsed / 60) var seconds = elapsed % 60 durationText.textContent = minutes + ':' + (seconds < 10 ? '0' : '') + seconds @@ -161,8 +162,9 @@ } function applyState(data) { - if (data && data._i18n) i18n = data._i18n - var state = data && data.state + if (!data || typeof data !== 'object') return + if (data._i18n) i18n = data._i18n + var state = data.state if (state === 'recording') showRecording() else if (state === 'thinking') showThinking() else if (state === 'done') showDone() @@ -170,13 +172,25 @@ container.style.opacity = '1' } + function registerIpc(channel, handler) { + if (!window.popupAPI) return + var unsub = window.popupAPI.on(channel, handler) + if (typeof unsub === 'function') unsubs.push(unsub) + } + + function onContainerClick() { + if (currentState !== 'recording') return + window.popupAPI.send('voice:cancelRecording', {}) + } + function setupListeners() { - window.popupAPI.on('voice:audioLevel', function (data) { - audioLevel = (data && data.level) || 0 + registerIpc('voice:audioLevel', function (data) { + var rawLevel = data && typeof data.level === 'number' ? data.level : 0 + audioLevel = Number.isFinite(rawLevel) ? Math.max(0, Math.min(1, rawLevel)) : 0 }) // 실시간 부분 전사 — 녹음 중 말하는 내용 미리보기. 최근 문장이 보이도록 아래쪽을 남긴다(CSS: flex-end). - window.popupAPI.on('voice:partialTranscript', function (data) { + registerIpc('voice:partialTranscript', function (data) { if (currentState !== 'recording') return var text = (data && data.text) || '' if (text.length === 0) return @@ -184,17 +198,25 @@ show(partialText, true) }) - window.popupAPI.on('window:tipStateChanged', applyState) + registerIpc('window:tipStateChanged', applyState) // 클릭 취소는 녹음 중에만 — 처리 중 클릭이 받아쓴 글을 버리던 사고 방지 - container.addEventListener('click', function () { - if (currentState !== 'recording') return - window.popupAPI.send('voice:cancelRecording', {}) - }) + container.addEventListener('click', onContainerClick) + } + + function cleanup() { + stopTimers() + container.removeEventListener('click', onContainerClick) + while (unsubs.length > 0) { + var unsub = unsubs.pop() + if (typeof unsub === 'function') unsub() + } } document.addEventListener('DOMContentLoaded', function () { createWaveBars() setupListeners() }) + + window.addEventListener('beforeunload', cleanup) })() diff --git a/apps/desktop/src/renderer/popups/result-popup/script.js b/apps/desktop/src/renderer/popups/result-popup/script.js index 5fe8776..61d2c97 100644 --- a/apps/desktop/src/renderer/popups/result-popup/script.js +++ b/apps/desktop/src/renderer/popups/result-popup/script.js @@ -18,6 +18,11 @@ var copiedTimer = null var remainingTime = 0 var lastTick = 0 + var isVisible = false + var prepareVersion = 0 + var rafId1 = null + var rafId2 = null + var unsubs = [] function tr(key) { return (i18n && i18n[key]) || '' @@ -56,9 +61,21 @@ } function resumeAutoClose() { + if (!isVisible) return startAutoCloseTimer(remainingTime > 0 ? remainingTime : 2000) } + function cancelPendingMeasure() { + if (rafId1 !== null) { + cancelAnimationFrame(rafId1) + rafId1 = null + } + if (rafId2 !== null) { + cancelAnimationFrame(rafId2) + rafId2 = null + } + } + function resetCopied() { clearTimeout(copiedTimer) copyBtn.classList.remove('copied') @@ -86,8 +103,35 @@ container.addEventListener('mouseenter', pauseAutoClose) container.addEventListener('mouseleave', resumeAutoClose) + function registerIpc(channel, handler) { + if (!window.popupAPI) return + var unsub = window.popupAPI.on(channel, handler) + if (typeof unsub === 'function') unsubs.push(unsub) + } + + function cleanup() { + isVisible = false + prepareVersion += 1 + cancelPendingMeasure() + pauseAutoClose() + clearTimeout(copiedTimer) + copiedTimer = null + while (unsubs.length > 0) { + var unsub = unsubs.pop() + if (typeof unsub === 'function') unsub() + } + } + // Phase 1: prepare — 결과 텍스트 세팅 + 크기 측정 - window.popupAPI.on('result:prepare', function (data) { + registerIpc('result:prepare', function (data) { + if (!data || typeof data !== 'object') return + isVisible = false + prepareVersion += 1 + var seq = prepareVersion + cancelPendingMeasure() + pauseAutoClose() + remainingTime = 0 + if (data._i18n) i18n = data._i18n applyI18nToHtml() resetCopied() @@ -95,8 +139,12 @@ resultText.scrollTop = 0 container.classList.remove('visible') - requestAnimationFrame(function () { - requestAnimationFrame(function () { + rafId1 = requestAnimationFrame(function () { + rafId1 = null + if (seq !== prepareVersion) return + rafId2 = requestAnimationFrame(function () { + rafId2 = null + if (seq !== prepareVersion) return var rect = container.getBoundingClientRect() window.popupAPI.send('result:measured', { width: Math.ceil(rect.width) + 4, @@ -107,15 +155,21 @@ }) // Phase 2: show — 리사이즈 완료 후 표시 - window.popupAPI.on('result:show', function (data) { + registerIpc('result:show', function (data) { + isVisible = true container.classList.add('visible') - var autoHideMs = (data && data.autoHideMs) || 5000 + var autoHideMs = data && typeof data.autoHideMs === 'number' ? data.autoHideMs : 5000 if (autoHideMs > 0) startAutoCloseTimer(autoHideMs) }) - window.popupAPI.on('result:hide', function () { + registerIpc('result:hide', function () { + isVisible = false + prepareVersion += 1 + cancelPendingMeasure() container.classList.remove('visible') - clearInterval(autoCloseTimer) - autoCloseTimer = null + pauseAutoClose() + remainingTime = 0 }) + + window.addEventListener('beforeunload', cleanup) })() diff --git a/apps/desktop/src/renderer/popups/suggestion-overlay/script.js b/apps/desktop/src/renderer/popups/suggestion-overlay/script.js index c807254..e616c1f 100644 --- a/apps/desktop/src/renderer/popups/suggestion-overlay/script.js +++ b/apps/desktop/src/renderer/popups/suggestion-overlay/script.js @@ -39,6 +39,7 @@ var correction = null var generatingSince = 0 var tickTimer = null + var unsubs = [] // 후보 없이 끝났을 때 잠깐 보이는 알림 ('no-suggestion') — 메인이 1초 뒤 창을 닫는다 var notice = null @@ -242,17 +243,25 @@ if (payload._i18n) { i18nStrings = payload._i18n // 닫기 버튼은 아이콘뿐이라 이름을 붙인다(2026-09-28 감사: 스크린리더가 읽을 이름이 없었다) - var closeButton = document.getElementById('close') if (closeButton && i18nStrings.close) { closeButton.setAttribute('aria-label', i18nStrings.close) closeButton.setAttribute('title', i18nStrings.close) } } if (payload._keyHints) keyHints = payload._keyHints - candidates = (payload.candidates || []).map(function (candidate) { - return candidate && candidate.text ? candidate.text : String(candidate) + var rawCandidates = Array.isArray(payload.candidates) ? payload.candidates : [] + candidates = rawCandidates.map(function (candidate) { + return candidate && typeof candidate.text === 'string' ? candidate.text : String(candidate) }) - activeIndex = payload.activeIndex || 0 + if (candidates.length === 0) { + activeIndex = 0 + } else { + var requestedIndex = + typeof payload.activeIndex === 'number' && Number.isFinite(payload.activeIndex) + ? Math.floor(payload.activeIndex) + : 0 + activeIndex = Math.max(0, Math.min(candidates.length - 1, requestedIndex)) + } if (payload.targetTotal !== undefined) targetTotal = payload.targetTotal || 0 if (payload.generating !== undefined) generating = payload.generating === true if (payload.warmingUp !== undefined) warmingUp = payload.warmingUp === true @@ -262,13 +271,23 @@ if (payload.notice !== undefined) notice = payload.notice || null } + function stopTick() { + if (tickTimer) { + clearInterval(tickTimer) + tickTimer = null + } + generatingSince = 0 + } + function startTick() { + if (!generating && !warmingUp) { + stopTick() + return + } if (tickTimer) return tickTimer = setInterval(function () { if (!generating && !warmingUp) { - clearInterval(tickTimer) - tickTimer = null - generatingSince = 0 + stopTick() return } render() @@ -324,9 +343,25 @@ }) } - if (window.popupAPI) { - window.popupAPI.on('suggestionPopup:show', handleShow) - window.popupAPI.on('suggestionPopup:update', handleUpdate) - window.popupAPI.on('suggestionPopup:hide', handleHide) + function registerIpc(channel, handler) { + if (!window.popupAPI) return + var unsub = window.popupAPI.on(channel, handler) + if (typeof unsub === 'function') unsubs.push(unsub) } + + function cleanup() { + stopTick() + while (unsubs.length > 0) { + var unsub = unsubs.pop() + if (typeof unsub === 'function') unsub() + } + } + + if (window.popupAPI) { + registerIpc('suggestionPopup:show', handleShow) + registerIpc('suggestionPopup:update', handleUpdate) + registerIpc('suggestionPopup:hide', handleHide) + } + + window.addEventListener('beforeunload', cleanup) })() diff --git a/apps/desktop/src/renderer/services/ollamaModelPullController.ts b/apps/desktop/src/renderer/services/ollamaModelPullController.ts index cd3372b..1715ee5 100644 --- a/apps/desktop/src/renderer/services/ollamaModelPullController.ts +++ b/apps/desktop/src/renderer/services/ollamaModelPullController.ts @@ -11,6 +11,7 @@ // - 상태는 불변 스냅샷으로 노출해 useSyncExternalStore로 구독할 수 있다. import type { IPCResult } from '@d3ro/core/errors' +import { toErrorMessage } from '../utils/error-message' export interface OllamaPullProgressEvent { modelId: string @@ -84,10 +85,6 @@ const INITIAL_SNAPSHOT: OllamaModelPullSnapshot = Object.freeze({ error: null, }) as OllamaModelPullSnapshot -function errorMessage(err: unknown): string { - return err instanceof Error ? err.message : String(err) -} - /** IPC 호출을 IPCResult로 정규화 — reject도 실패 결과로 바꾼다 */ async function settle(call: () => Promise>): Promise<{ ok: true } | { ok: false; message: string }> { try { @@ -95,7 +92,7 @@ async function settle(call: () => Promise>): Promise<{ ok: true if (res.success) return { ok: true } return { ok: false, message: res.error.message } } catch (err) { - return { ok: false, message: errorMessage(err) } + return { ok: false, message: toErrorMessage(err) } } } diff --git a/apps/desktop/src/renderer/utils/error-message.ts b/apps/desktop/src/renderer/utils/error-message.ts new file mode 100644 index 0000000..ae30090 --- /dev/null +++ b/apps/desktop/src/renderer/utils/error-message.ts @@ -0,0 +1,6 @@ +// src/renderer/utils/error-message.ts +// unknown 예외를 일관된 사용자/상태 메시지로 변환하는 공유 헬퍼. + +export function toErrorMessage(err: unknown): string { + return err instanceof Error ? err.message : String(err) +} diff --git a/apps/desktop/src/renderer/utils/formatters.ts b/apps/desktop/src/renderer/utils/formatters.ts index ebb327b..dca6f11 100644 --- a/apps/desktop/src/renderer/utils/formatters.ts +++ b/apps/desktop/src/renderer/utils/formatters.ts @@ -1,21 +1,34 @@ // src/renderer/utils/formatters.ts // 공유 포맷팅 유틸리티 — SSOT, 중복 제거 +import { formatDurationClockFromSeconds } from '@d3ro/core/format' + /** 초 단위 duration → "M:SS" 형식 */ export function formatDuration(sec: number): string { - const m = Math.floor(sec / 60) - const s = Math.round(sec % 60) - return `${m}:${s.toString().padStart(2, '0')}` + return formatDurationClockFromSeconds(sec, { rounding: 'round' }) +} + +function toSafeTimestampDate(ts: number): Date | null { + if (!Number.isFinite(ts)) return null + const date = new Date(ts) + return Number.isFinite(date.getTime()) ? date : null +} + +function toTotalMinutes(ms: number): number { + if (!Number.isFinite(ms) || ms <= 0) return 0 + return Math.round(ms / 60000) } /** 타임스탬프 → "YYYY-MM-DD" 날짜 키 (그룹핑용) */ export function getDateKey(ts: number): string { - const d = new Date(ts) + const d = toSafeTimestampDate(ts) + if (!d) return '' return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` } /** 큰 숫자 → "1.2K" / "3.4M" 축약 */ export function formatNumber(n: number): string { + if (!Number.isFinite(n)) return '0' if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M` if (n >= 1000) return `${(n / 1000).toFixed(1)}K` return `${n}` @@ -23,7 +36,7 @@ export function formatNumber(n: number): string { /** ms → 녹음 시간 수치 ("12" 또는 "1:30") */ export function formatRecordingTime(ms: number): string { - const totalMin = Math.round(ms / 60000) + const totalMin = toTotalMinutes(ms) if (totalMin >= 60) { const h = Math.floor(totalMin / 60) const m = totalMin % 60 @@ -34,8 +47,7 @@ export function formatRecordingTime(ms: number): string { /** ms → 녹음 시간 단위 ("HR" 또는 "MIN") */ export function formatRecordingTimeUnit(ms: number): string { - const totalMin = Math.round(ms / 60000) - return totalMin >= 60 ? 'HR' : 'MIN' + return toTotalMinutes(ms) >= 60 ? 'HR' : 'MIN' } /** @@ -43,7 +55,7 @@ export function formatRecordingTimeUnit(ms: number): string { * "MIN"/"HR" 영문 대문자 단위를 한국어 화면에 그대로 찍던 문제를 대신한다(2026-09-28). */ export function formatDurationLong(ms: number, locale: string): string { - const totalMin = Math.max(0, Math.round(ms / 60000)) + const totalMin = toTotalMinutes(ms) const unit = (value: number, u: 'hour' | 'minute'): string => new Intl.NumberFormat(locale, { style: 'unit', unit: u, unitDisplay: 'short' }).format(value) if (totalMin < 60) return unit(totalMin, 'minute') @@ -54,10 +66,12 @@ export function formatDurationLong(ms: number, locale: string): string { /** 타임스탬프 → 로케일 시:분 ("오후 3:04" / "3:04 PM") */ export function formatClockTime(ts: number, locale: string): string { - return new Date(ts).toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' }) + const d = toSafeTimestampDate(ts) + return d ? d.toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' }) : '' } /** 타임스탬프 → 로케일 날짜 ("9월 28일 (일)" / "Sun, Sep 28") */ export function formatDayLabel(ts: number, locale: string): string { - return new Date(ts).toLocaleDateString(locale, { month: 'long', day: 'numeric', weekday: 'short' }) + const d = toSafeTimestampDate(ts) + return d ? d.toLocaleDateString(locale, { month: 'long', day: 'numeric', weekday: 'short' }) : '' } diff --git a/apps/desktop/tests/helpers/fakeSyncRemote.ts b/apps/desktop/tests/helpers/fakeSyncRemote.ts index 8b73939..0ec87a5 100644 --- a/apps/desktop/tests/helpers/fakeSyncRemote.ts +++ b/apps/desktop/tests/helpers/fakeSyncRemote.ts @@ -48,7 +48,7 @@ export class FakeSyncRemote implements SyncRemote { mobileInsert(table: string, row: RemoteRow): RemoteRow { const at = this.now() - const full = { user_id: this.userId, created_at: at, updated_at: at, ...row } + const full = { user_id: this.userId, revision: 1, created_at: at, updated_at: at, ...row } this.rows(table).push(full) return full } @@ -56,7 +56,11 @@ export class FakeSyncRemote implements SyncRemote { mobileUpdate(table: string, id: string, patch: RemoteRow): void { const row = this.find(table, id) if (!row) throw new Error(`no ${table}/${id}`) + const changed = Object.keys(patch).some((k) => k !== 'updated_at' && row[k] !== patch[k]) Object.assign(row, patch, { updated_at: this.now() }) + if ((table === 'history' || table === 'meeting_memos') && changed) { + row.revision = Number(row.revision ?? 1) + 1 + } } mobileDelete(table: string, id: string): void { @@ -232,7 +236,9 @@ export class FakeSyncRemote implements SyncRemote { if (existing) { const changed = Object.keys(row).some((k) => k !== 'updated_at' && existing[k] !== row[k]) Object.assign(existing, row, { updated_at: this.now() }) - if (table === 'history' && changed) existing.revision = Number(existing.revision ?? 1) + 1 + if ((table === 'history' || table === 'meeting_memos') && changed) { + existing.revision = Number(existing.revision ?? 1) + 1 + } } else { const at = this.now() this.rows(table).push({ id: crypto.randomUUID(), revision: 1, created_at: at, ...row, updated_at: row.updated_at ?? at }) diff --git a/apps/desktop/tests/main/db/sqlite-optimizations.test.ts b/apps/desktop/tests/main/db/sqlite-optimizations.test.ts new file mode 100644 index 0000000..1695be8 --- /dev/null +++ b/apps/desktop/tests/main/db/sqlite-optimizations.test.ts @@ -0,0 +1,246 @@ +// tests/main/db/sqlite-optimizations.test.ts +// SQLite 4대 수술 검증: +// 1) WAL 성능 PRAGMA (synchronous=NORMAL, temp_store=MEMORY, cache_size=-16000) +// 2) FTS5 trigram 가상 테이블 + INSERT/UPDATE/DELETE 트리거 + UnifiedSearchService 연동 +// 3) RAG Float32 바이너리 BLOB + 메모리 캐시 (JSON.parse 0회) +// 4) PersonalGraphService 단일 트랜잭션 일괄 반영 + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { eq } from 'drizzle-orm' +import { createTestDb } from '../../helpers/createTestDb' +import { bindTestDatabase, unbindTestDatabase } from '../../../src/main/db' +import { + history, + meetingMemos, + meetingSessions, + ragChunks, +} from '../../../src/main/db/schema' +import { + getUnifiedSearchService, + resetUnifiedSearchServiceForTests, +} from '../../../src/main/services/UnifiedSearchService' +import { SqliteChunkStore } from '../../../src/main/services/rag/chunk-store' +import { rankChunks } from '../../../src/main/services/rag/retrieval' +import { + getPersonalGraphService, + resetPersonalGraphServiceForTests, +} from '../../../src/main/services/PersonalGraphService' + +const BASE_TS = 1_730_000_000_000 + +describe('SQLite 성능 및 검색/벡터 최적화', () => { + let testDb: ReturnType + + beforeEach(() => { + testDb = createTestDb() + bindTestDatabase(testDb.db) + resetUnifiedSearchServiceForTests() + resetPersonalGraphServiceForTests() + }) + + afterEach(() => { + resetUnifiedSearchServiceForTests() + resetPersonalGraphServiceForTests() + unbindTestDatabase() + testDb.close() + vi.restoreAllMocks() + }) + + it('applySchema_실행시_WAL성능프라그마와FTS5트리그램테이블을설정한다', () => { + const synchronous = testDb.sqlite.pragma('synchronous', { simple: true }) + const tempStore = testDb.sqlite.pragma('temp_store', { simple: true }) + const cacheSize = testDb.sqlite.pragma('cache_size', { simple: true }) + + // synchronous: 1 = NORMAL, temp_store: 2 = MEMORY, cache_size: -16000 (~16MB) + expect(synchronous).toBe(1) + expect(tempStore).toBe(2) + expect(cacheSize).toBe(-16000) + + const chunkColumns = testDb.sqlite.pragma('table_info(rag_chunks)') as Array<{ name: string }> + expect(chunkColumns.map((col) => col.name)).toContain('embedding_blob') + + const ftsTables = testDb.sqlite + .prepare( + `SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('history_fts', 'meeting_sessions_fts', 'meeting_memos_fts') ORDER BY name` + ) + .all() as Array<{ name: string }> + expect(ftsTables.map((row) => row.name)).toEqual([ + 'history_fts', + 'meeting_memos_fts', + 'meeting_sessions_fts', + ]) + }) + + it('UnifiedSearchService_3자이상검색시_FTS5인덱스를타고수정삭제와동기화된다', () => { + testDb.db + .insert(history) + .values({ + id: 'rec-1', + title: '주간 아키텍처 점검', + originalText: '초안 텍스트', + polishedText: '데이터베이스 인덱싱 최적화 방안을 논의했습니다.', + summaryText: '인덱싱 요약', + duration: 12.5, + createdAt: BASE_TS + 100, + updatedAt: BASE_TS + 100, + }) + .run() + + testDb.db + .insert(meetingSessions) + .values({ + id: 'mtg-1', + title: '스프린트 회고', + status: 'completed', + startedAt: BASE_TS + 200, + rawTranscript: '[00:01] 백엔드 인덱싱 지연을 줄였습니다.', + createdAt: BASE_TS + 200, + updatedAt: BASE_TS + 200, + }) + .run() + + testDb.db + .insert(meetingSessions) + .values({ + id: 'mtg-2', + title: '배포 체크리스트', + status: 'completed', + startedAt: BASE_TS + 300, + rawTranscript: '[00:05] 릴리스 일정 공유', + createdAt: BASE_TS + 300, + updatedAt: BASE_TS + 300, + }) + .run() + + testDb.db + .insert(meetingMemos) + .values({ + id: 'memo-1', + sessionId: 'mtg-2', + content: '메모에만 적힌 인덱싱 확인 항목', + timestampMs: 5_000, + createdAt: BASE_TS + 310, + }) + .run() + + // EXPLAIN QUERY PLAN 검증: 전체 테이블 스캔 대신 history_fts 가상 테이블 인덱스를 타야 한다. + const planRows = testDb.sqlite + .prepare( + `EXPLAIN QUERY PLAN SELECT id FROM history WHERE id IN (SELECT row_id FROM history_fts WHERE history_fts MATCH '"인덱싱"')` + ) + .all() as Array<{ detail: string }> + expect(planRows.some((row) => row.detail.includes('history_fts'))).toBe(true) + expect(planRows.some((row) => row.detail.includes('SCAN history '))).toBe(false) + + const initial = getUnifiedSearchService().search({ query: '인덱싱' }) + expect(initial.total).toBe(3) + expect(initial.results.map((item) => item.id)).toEqual(['mtg-2', 'mtg-1', 'rec-1']) + + // UPDATE 트리거 동기화 검증 + testDb.db + .update(history) + .set({ + polishedText: '쿼리 플랜 개편안을 확정했습니다 (100% 달성).', + summaryText: '개편안 요약', + updatedAt: BASE_TS + 400, + }) + .where(eq(history.id, 'rec-1')) + .run() + + // DELETE 트리거 동기화 검증 + testDb.db.delete(meetingMemos).where(eq(meetingMemos.id, 'memo-1')).run() + + const afterMutation = getUnifiedSearchService().search({ query: '인덱싱' }) + expect(afterMutation.results.map((item) => item.id)).toEqual(['mtg-1']) + + // 리터럴 % 와일드카드 및 2자 이하 짧은 검색어도 정확히 일치해야 한다. + const literalPercent = getUnifiedSearchService().search({ query: '100% 달성' }) + expect(literalPercent.results.map((item) => item.id)).toEqual(['rec-1']) + + const shortQuery = getUnifiedSearchService().search({ query: '회고' }) + expect(shortQuery.results.map((item) => item.id)).toEqual(['mtg-1']) + }) + + it('SqliteChunkStore_임베딩저장시_Float32바이너리와메모리캐시로JSON재파싱없이검색한다', () => { + const store = new SqliteChunkStore() + store.insertDocument({ + id: 'doc-1', + fileName: 'architecture.md', + filePath: '/docs/architecture.md', + fileType: 'md', + chunkCount: 2, + indexed: true, + indexedAt: BASE_TS, + addedAt: BASE_TS, + }) + store.replaceChunks('doc-1', ['SQLite WAL 모드 설명', '벡터 임베딩 바이너리 직렬화']) + + const chunks = store.listChunks('doc-1') + expect(chunks).toHaveLength(2) + + store.setEmbedding(chunks[0].id, [1, 0, 0]) + store.setEmbedding(chunks[1].id, [0, 1, 0]) + + const rawRow = testDb.db + .select() + .from(ragChunks) + .where(eq(ragChunks.id, chunks[0].id)) + .get() + expect(rawRow?.embeddingBlob?.byteLength).toBe(12) + + const parseSpy = vi.spyOn(JSON, 'parse') + const embeddedFirst = store.listEmbeddedChunks() + expect(embeddedFirst).toHaveLength(2) + + const ranked = rankChunks( + [0.05, 0.99, 0], + embeddedFirst, + new Map([['doc-1', 'architecture.md']]), + 2, + ) + expect(ranked[0].content).toBe('벡터 임베딩 바이너리 직렬화') + expect(parseSpy).not.toHaveBeenCalled() + + // 두 번째 조회는 메모리 캐시를 그대로 반환하고, replaceChunks/removeDocument 시 즉시 무효화한다. + const selectSpy = vi.spyOn(testDb.db, 'select') + const embeddedCached = store.listEmbeddedChunks() + expect(embeddedCached).toHaveLength(2) + expect(selectSpy).not.toHaveBeenCalled() + + expect(store.counts()).toEqual({ documentCount: 1, totalChunks: 2 }) + + store.removeDocument('doc-1') + expect(store.listEmbeddedChunks()).toEqual([]) + expect(store.counts()).toEqual({ documentCount: 0, totalChunks: 0 }) + }) + + it('PersonalGraphService_다중문장색인중중간실패시_단일트랜잭션으로전체롤백하고정상시일괄반영한다', () => { + const graph = getPersonalGraphService() + + // phrase_edges 쓰기 단계에서 실패를 유도해 앞선 personal_phrases INSERT 까지 원자적으로 롤백되는지 검증한다. + testDb.sqlite.exec(` + CREATE TRIGGER fail_edge_insert BEFORE INSERT ON phrase_edges + BEGIN + SELECT RAISE(ABORT, 'simulated_edge_failure'); + END; + `) + + graph.indexText( + '배포 파이프라인 성능 점검 결과를 공유드립니다. 배포 파이프라인 성능 점검 지표를 확인했습니다.', + { source: 'typed', appName: 'Slack.exe', at: BASE_TS }, + ) + expect(graph.getStats(3650).nodes).toBe(0) + + testDb.sqlite.exec('DROP TRIGGER fail_edge_insert;') + + graph.indexText( + '배포 파이프라인 성능 점검 결과를 공유드립니다. 배포 파이프라인 성능 점검 지표를 확인했습니다.', + { source: 'typed', appName: 'Slack.exe', at: BASE_TS }, + ) + + const stats = graph.getStats(3650) + expect(stats.nodes).toBe(2) + expect(stats.followsEdges).toBe(1) + expect(stats.sharesTermsEdges).toBe(1) + }) +}) diff --git a/apps/desktop/tests/main/ipc/renderer-broadcast.test.ts b/apps/desktop/tests/main/ipc/renderer-broadcast.test.ts new file mode 100644 index 0000000..ab9cb4e --- /dev/null +++ b/apps/desktop/tests/main/ipc/renderer-broadcast.test.ts @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +const state = vi.hoisted(() => ({ + mainWindow: null as null | { + isDestroyed: () => boolean + webContents: { isDestroyed?: () => boolean; send: ReturnType } + }, + allWindows: [] as Array<{ + isDestroyed: () => boolean + webContents: { isDestroyed?: () => boolean; send: ReturnType } + }>, +})) + +vi.mock('electron', () => ({ + BrowserWindow: { + getAllWindows: () => state.allWindows, + }, +})) + +vi.mock('../../../src/main/windows/WindowManager', () => ({ + getMainWindow: () => state.mainWindow, +})) + +import { broadcastToAllWindows, safeSendToRenderer } from '../../../src/main/ipc/renderer-broadcast' + +describe('renderer-broadcast IPC helper', () => { + afterEach(() => { + state.mainWindow = null + state.allWindows = [] + vi.clearAllMocks() + }) + + it('safeSendToRenderer_mainWindowLive_sendsPayloadAndSkipsDestroyedStates', () => { + const liveSend = vi.fn() + state.mainWindow = { + isDestroyed: () => false, + webContents: { isDestroyed: () => false, send: liveSend }, + } + safeSendToRenderer('voice:error', { code: 1 }) + expect(liveSend).toHaveBeenCalledTimes(1) + expect(liveSend).toHaveBeenCalledWith('voice:error', { code: 1 }) + + const destroyedWindowSend = vi.fn() + state.mainWindow = { + isDestroyed: () => true, + webContents: { isDestroyed: () => false, send: destroyedWindowSend }, + } + safeSendToRenderer('voice:error', { code: 2 }) + expect(destroyedWindowSend).not.toHaveBeenCalled() + + const destroyedContentsSend = vi.fn() + state.mainWindow = { + isDestroyed: () => false, + webContents: { isDestroyed: () => true, send: destroyedContentsSend }, + } + safeSendToRenderer('voice:error', { code: 3 }) + expect(destroyedContentsSend).not.toHaveBeenCalled() + + state.mainWindow = null + safeSendToRenderer('voice:error', { code: 4 }) + expect(liveSend).toHaveBeenCalledTimes(1) + }) + + it('broadcastToAllWindows_mixedWindows_sendsOnlyToNonDestroyedWindows', () => { + const sendLiveA = vi.fn() + const sendDestroyedWin = vi.fn() + const sendDestroyedContents = vi.fn() + const sendMinimalFake = vi.fn() + + state.allWindows = [ + { isDestroyed: () => false, webContents: { isDestroyed: () => false, send: sendLiveA } }, + { isDestroyed: () => true, webContents: { isDestroyed: () => false, send: sendDestroyedWin } }, + { isDestroyed: () => false, webContents: { isDestroyed: () => true, send: sendDestroyedContents } }, + { isDestroyed: () => false, webContents: { send: sendMinimalFake } }, + ] + + broadcastToAllWindows('config:changed', { key: 'theme', value: 'dark' }) + + expect(sendLiveA).toHaveBeenCalledTimes(1) + expect(sendLiveA).toHaveBeenCalledWith('config:changed', { key: 'theme', value: 'dark' }) + expect(sendDestroyedWin).not.toHaveBeenCalled() + expect(sendDestroyedContents).not.toHaveBeenCalled() + expect(sendMinimalFake).toHaveBeenCalledTimes(1) + expect(sendMinimalFake).toHaveBeenCalledWith('config:changed', { key: 'theme', value: 'dark' }) + }) +}) diff --git a/apps/desktop/tests/main/services/UnifiedSearchService.test.ts b/apps/desktop/tests/main/services/UnifiedSearchService.test.ts index 09c23bc..8f4f1de 100644 --- a/apps/desktop/tests/main/services/UnifiedSearchService.test.ts +++ b/apps/desktop/tests/main/services/UnifiedSearchService.test.ts @@ -1,129 +1,134 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ErrorCode } from '@d3ro/core/errors' -import type { History, MeetingMemoRow, MeetingSessionRow } from '../../../src/main/db/schema' +import { + bindTestDatabase, + unbindTestDatabase, +} from '../../../src/main/db' +import { + history, + meetingMemos, + meetingSessions, + type NewHistory, + type NewMeetingMemoRow, + type NewMeetingSessionRow, +} from '../../../src/main/db/schema' +import { + createUnifiedSearchExcerpt, + getUnifiedSearchService, + normalizeUnifiedSearchQuery, + resetUnifiedSearchServiceForTests, +} from '../../../src/main/services/UnifiedSearchService' +import { createTestDb } from '../../helpers/createTestDb' -interface MockBuilderOptions { - get?: unknown - all?: unknown[] - error?: Error -} - -function createMockBuilder(options: MockBuilderOptions = {}) { - const builder = { - from: vi.fn(), - where: vi.fn(), - orderBy: vi.fn(), - limit: vi.fn(), - get: vi.fn(), - all: vi.fn(), +function makeHistoryRow(overrides: Partial & { id: string }): NewHistory { + return { + title: '제품 메모', + originalText: '초기 원문', + polishedText: '다음 분기 출시 계획을 정리했습니다.', + focusedApp: null, + focusedAppName: null, + focusedAppWindowTitle: null, + mode: 'dictation', + status: 'completed', + errorCode: null, + audioLocalPath: null, + duration: 10, + detectedLanguage: 'ko', + micDevice: null, + wordCount: 6, + sttModel: null, + llmModel: null, + sttLatencyMs: null, + llmLatencyMs: null, + createdAt: 100, + updatedAt: 100, + appVersion: '1.9.0', + summaryText: null, + isFavorite: false, + ...overrides, } - builder.from.mockImplementation(() => { - if (options.error !== undefined) throw options.error - return builder - }) - builder.where.mockReturnValue(builder) - builder.orderBy.mockReturnValue(builder) - builder.limit.mockReturnValue(builder) - builder.get.mockReturnValue(options.get ?? null) - builder.all.mockReturnValue(options.all ?? []) - return builder } -const selectQueue: ReturnType[] = [] -const mockDb = { - select: vi.fn(() => selectQueue.shift() ?? createMockBuilder()), +function makeMeetingRow( + overrides: Partial & { id: string }, +): NewMeetingSessionRow { + return { + title: '주간 회의', + status: 'completed', + startedAt: 200, + endedAt: 300, + durationMs: 100, + rawTranscript: '출시 계획을 다음 주에 검토합니다.', + editedTranscript: null, + minutesMarkdown: null, + minutesJson: null, + sttModel: null, + llmModel: null, + sttLatencyMs: null, + llmLatencyMs: null, + errorMessage: null, + createdAt: 200, + updatedAt: 300, + ...overrides, + } } -vi.mock('../../../src/main/db', () => ({ - getDatabase: () => mockDb, -})) - -vi.mock('../../../src/main/services/LoggerService', () => ({ - getLogger: () => ({ - info: vi.fn(), - warn: vi.fn(), - error: vi.fn(), - debug: vi.fn(), - }), -})) - -const record: History = { - id: 'record-1', - title: '제품 메모', - originalText: '초기 원문', - polishedText: '다음 분기 출시 계획을 정리했습니다.', - focusedApp: null, - focusedAppName: null, - focusedAppWindowTitle: null, - mode: 'dictation', - status: 'completed', - errorCode: null, - audioLocalPath: null, - duration: 10, - detectedLanguage: 'ko', - micDevice: null, - wordCount: 6, - sttModel: null, - llmModel: null, - sttLatencyMs: null, - llmLatencyMs: null, - createdAt: 100, - updatedAt: 100, - appVersion: '1.9.0', - summaryText: null, - isFavorite: false, -} - -const meeting: MeetingSessionRow = { - id: 'meeting-1', - title: '주간 회의', - status: 'completed', - startedAt: 200, - endedAt: 300, - durationMs: 100, - rawTranscript: '출시 계획을 다음 주에 검토합니다.', - editedTranscript: null, - minutesMarkdown: null, - minutesJson: null, - sttModel: null, - llmModel: null, - sttLatencyMs: null, - llmLatencyMs: null, - errorMessage: null, - createdAt: 200, - updatedAt: 300, +function makeMemoRow( + overrides: Partial & { id: string; sessionId: string }, +): NewMeetingMemoRow { + return { + content: '기본 메모 내용', + timestampMs: 10_000, + revision: 1, + createdAt: 210, + updatedAt: 210, + ...overrides, + } } describe('UnifiedSearchService', () => { + let closeDb: (() => void) | null = null + + function useFreshTestDb() { + const testDb = createTestDb() + closeDb = testDb.close + bindTestDatabase(testDb.db) + return testDb + } + beforeEach(() => { - selectQueue.length = 0 - vi.clearAllMocks() + resetUnifiedSearchServiceForTests() + unbindTestDatabase() }) - it('normalizes input and creates a bounded excerpt around the match', async () => { - const { createUnifiedSearchExcerpt, normalizeUnifiedSearchQuery } = await import( - '../../../src/main/services/UnifiedSearchService' - ) + afterEach(() => { + resetUnifiedSearchServiceForTests() + unbindTestDatabase() + if (closeDb) { + closeDb() + closeDb = null + } + vi.restoreAllMocks() + }) + + it('normalizes input and creates a bounded excerpt around the match', () => { expect(normalizeUnifiedSearchQuery(' 출시\n 계획 ')).toBe('출시 계획') expect(normalizeUnifiedSearchQuery('a'.repeat(250))).toHaveLength(200) expect(normalizeUnifiedSearchQuery(` ${'a'.repeat(199)} b`)).toBe('a'.repeat(199)) - const excerpt = createUnifiedSearchExcerpt(`앞부분 ${'x'.repeat(80)} 출시 계획 ${'y'.repeat(80)}`, '출시 계획', 60) + const excerpt = createUnifiedSearchExcerpt( + `앞부분 ${'x'.repeat(80)} 출시 계획 ${'y'.repeat(80)}`, + '출시 계획', + 60, + ) expect(excerpt).toContain('출시 계획') expect(excerpt.startsWith('…')).toBe(true) expect(excerpt.endsWith('…')).toBe(true) }) - it('merges records and meeting transcripts by occurrence time and preserves source ids', async () => { - selectQueue.push( - createMockBuilder({ get: { count: 1 } }), - createMockBuilder({ all: [record] }), - createMockBuilder({ get: { count: 1 } }), - createMockBuilder({ all: [meeting] }), - ) - const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import( - '../../../src/main/services/UnifiedSearchService' - ) - resetUnifiedSearchServiceForTests() + it('merges records and meeting transcripts by occurrence time and preserves source ids', () => { + const { db } = useFreshTestDb() + db.insert(history).values(makeHistoryRow({ id: 'record-1', createdAt: 100, updatedAt: 100 })).run() + db.insert(meetingSessions).values(makeMeetingRow({ id: 'meeting-1', startedAt: 200, createdAt: 200 })).run() const response = getUnifiedSearchService().search({ query: '계획', limit: 10 }) @@ -139,17 +144,12 @@ describe('UnifiedSearchService', () => { expect(response.results[1]).toMatchObject({ matchedField: 'content' }) }) - it('returns immediately for an empty query', async () => { - const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import( - '../../../src/main/services/UnifiedSearchService' - ) - resetUnifiedSearchServiceForTests() + it('returns immediately for an empty query without opening DB', () => { expect(getUnifiedSearchService().search({ query: ' ' })).toEqual({ query: '', results: [], total: 0, }) - expect(mockDb.select).not.toHaveBeenCalled() }) it.each([ @@ -160,58 +160,43 @@ describe('UnifiedSearchService', () => { { query: '계획', limit: Number.NaN }, { query: '계획', limit: Number.POSITIVE_INFINITY }, { query: '계획', limit: '10' }, - ])('rejects malformed runtime parameters with ConfigInvalidValue: %o', async (params) => { - const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import( - '../../../src/main/services/UnifiedSearchService' - ) - resetUnifiedSearchServiceForTests() - + ])('rejects malformed runtime parameters with ConfigInvalidValue: %o', (params) => { expect(() => getUnifiedSearchService().search(params)).toThrowError( expect.objectContaining({ code: ErrorCode.ConfigInvalidValue }), ) - expect(mockDb.select).not.toHaveBeenCalled() }) - it('maps database failures to the IPC error contract', async () => { - selectQueue.push(createMockBuilder({ error: new Error('database unavailable') })) - const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import( - '../../../src/main/services/UnifiedSearchService' - ) - resetUnifiedSearchServiceForTests() + it('maps database failures to the IPC error contract', () => { expect(() => getUnifiedSearchService().search({ query: '계획' })).toThrowError( expect.objectContaining({ code: ErrorCode.DBQueryFailed }), ) }) - it('includes meeting_memos and timed transcript segments in meeting search results', async () => { - const memoOnlyMeeting: MeetingSessionRow = { - ...meeting, - id: 'meeting-memo-1', - title: '설계 검토 회의', - startedAt: 400, - createdAt: 400, - rawTranscript: '[00:10] 아키텍처 개요 설명', - } - const memoRow: MeetingMemoRow = { - id: 'memo-1', - sessionId: 'meeting-memo-1', - content: '마이그레이션 체크리스트 확인 필요', - timestampMs: 75_000, - createdAt: 410, - updatedAt: 410, - } - selectQueue.push( - createMockBuilder({ get: { count: 0 } }), - createMockBuilder({ all: [] }), - createMockBuilder({ get: { count: 0 } }), - createMockBuilder({ all: [] }), - createMockBuilder({ all: [memoRow] }), - createMockBuilder({ all: [memoOnlyMeeting] }), - ) - const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import( - '../../../src/main/services/UnifiedSearchService' - ) - resetUnifiedSearchServiceForTests() + it('includes meeting_memos and timed transcript segments in meeting search results', () => { + const { db } = useFreshTestDb() + db.insert(meetingSessions) + .values( + makeMeetingRow({ + id: 'meeting-memo-1', + title: '설계 검토 회의', + startedAt: 400, + createdAt: 400, + rawTranscript: '[00:10] 아키텍처 개요 설명', + }), + ) + .run() + db.insert(meetingMemos) + .values( + makeMemoRow({ + id: 'memo-1', + sessionId: 'meeting-memo-1', + content: '마이그레이션 체크리스트 확인 필요', + timestampMs: 75_000, + createdAt: 410, + updatedAt: 410, + }), + ) + .run() const response = getUnifiedSearchService().search({ query: '체크리스트', limit: 10 }) @@ -226,4 +211,246 @@ describe('UnifiedSearchService', () => { }), ]) }) + + it('search_oldLongMeetingMemoVsRecentShortMeeting_prioritizesRecentMeetingAndCreatedAtMemo', () => { + const { db } = useFreshTestDb() + // Old long meeting: high timestampMs (2 hours in), early createdAt/startedAt + db.insert(meetingSessions) + .values([ + makeMeetingRow({ + id: 'old-long-meeting', + title: '과거 장기 회의', + startedAt: 100, + createdAt: 100, + rawTranscript: '잡담 내용', + }), + makeMeetingRow({ + id: 'recent-short-meeting', + title: '최신 짧은 회의', + startedAt: 900, + createdAt: 900, + rawTranscript: '일반 진행 상황', + }), + ]) + .run() + + db.insert(meetingMemos) + .values([ + makeMemoRow({ + id: 'old-late-offset-memo', + sessionId: 'old-long-meeting', + content: '로드맵 1차 초안 메모', + timestampMs: 7_200_000, + createdAt: 110, + updatedAt: 110, + }), + makeMemoRow({ + id: 'recent-early-offset-memo', + sessionId: 'recent-short-meeting', + content: '로드맵 최신 결정사항', + timestampMs: 5_000, + createdAt: 910, + updatedAt: 910, + }), + makeMemoRow({ + id: 'recent-earlier-created-memo', + sessionId: 'recent-short-meeting', + content: '로드맵 중간 메모', + timestampMs: 60_000, + createdAt: 905, + updatedAt: 905, + }), + ]) + .run() + + const limited = getUnifiedSearchService().search({ query: '로드맵', limit: 1 }) + expect(limited.total).toBe(2) + expect(limited.results.map((r) => r.id)).toEqual(['recent-short-meeting']) + expect(limited.results[0].excerpt).toBe('[00:05] 로드맵 최신 결정사항') + }) + + it('search_meetingStartedAtDiffersFromCreatedAt_ordersByStartedAt', () => { + const { db } = useFreshTestDb() + db.insert(meetingSessions) + .values([ + makeMeetingRow({ + id: 'older-started-imported-later', + title: '과거 회의 사후 동기화', + startedAt: 500, + createdAt: 950, + rawTranscript: '분기 목표 리뷰', + }), + makeMeetingRow({ + id: 'newer-started-created-earlier', + title: '최근 회의', + startedAt: 800, + createdAt: 200, + rawTranscript: '분기 목표 확정', + }), + ]) + .run() + + const limited = getUnifiedSearchService().search({ query: '분기 목표', limit: 1 }) + expect(limited.total).toBe(2) + expect(limited.results[0].id).toBe('newer-started-created-earlier') + expect(limited.results[0].occurredAt).toBe(800) + }) + + it('search_meetingMatchesDirectlyOutsideLimitAndViaMemos_countsDistinctTotalWithoutDoubleCounting', () => { + const { db } = useFreshTestDb() + db.insert(history) + .values( + makeHistoryRow({ + id: 'hist-overlap', + title: '아키텍처 기록', + polishedText: '아키텍처 변경 공지', + createdAt: 1_000, + updatedAt: 1_000, + }), + ) + .run() + + db.insert(meetingSessions) + .values([ + makeMeetingRow({ + id: 'meet-both-recent', + title: '아키텍처 위원회', + startedAt: 900, + createdAt: 900, + rawTranscript: '아키텍처 리뷰', + }), + makeMeetingRow({ + id: 'meet-both-old-outside-limit', + title: '초기 아키텍처 회의', + startedAt: 100, + createdAt: 100, + rawTranscript: '아키텍처 설계 초안', + }), + makeMeetingRow({ + id: 'meet-memo-only-1', + title: '일반 스탠드업 1', + startedAt: 700, + createdAt: 700, + rawTranscript: '진행 보고', + }), + makeMeetingRow({ + id: 'meet-memo-only-2', + title: '일반 스탠드업 2', + startedAt: 600, + createdAt: 600, + rawTranscript: '진행 보고', + }), + ]) + .run() + + db.insert(meetingMemos) + .values([ + makeMemoRow({ + id: 'memo-m1', + sessionId: 'meet-both-recent', + content: '아키텍처 메모 1', + createdAt: 905, + }), + makeMemoRow({ + id: 'memo-m2', + sessionId: 'meet-both-old-outside-limit', + content: '아키텍처 메모 2', + createdAt: 950, + }), + makeMemoRow({ + id: 'memo-m3a', + sessionId: 'meet-memo-only-1', + content: '아키텍처 후속 과제 A', + createdAt: 710, + }), + makeMemoRow({ + id: 'memo-m3b', + sessionId: 'meet-memo-only-1', + content: '아키텍처 후속 과제 B', + createdAt: 720, + }), + makeMemoRow({ + id: 'memo-m4', + sessionId: 'meet-memo-only-2', + content: '아키텍처 후속 과제 C', + createdAt: 610, + }), + ]) + .run() + + const response = getUnifiedSearchService().search({ query: '아키텍처', limit: 1 }) + // 1 history + 4 distinct meetingSessions = 5 total, even though limit is 1 and meet-both-old matches both directly and via memo + expect(response.results).toHaveLength(1) + expect(response.total).toBe(5) + }) + + it('search_ftsTablesAbsent_fallsBackToLikeFilteringSafely', () => { + const { db, sqlite } = useFreshTestDb() + db.insert(history) + .values( + makeHistoryRow({ + id: 'hist-legacy', + title: '레거시 노트', + polishedText: '트라이그램 없는 데이터베이스 검색 테스트', + createdAt: 300, + updatedAt: 300, + }), + ) + .run() + db.insert(meetingSessions) + .values( + makeMeetingRow({ + id: 'meet-legacy', + title: '레거시 회의', + startedAt: 400, + createdAt: 400, + rawTranscript: '일반 회의록', + }), + ) + .run() + db.insert(meetingMemos) + .values( + makeMemoRow({ + id: 'memo-legacy', + sessionId: 'meet-legacy', + content: '데이터베이스 백업 메모', + createdAt: 410, + }), + ) + .run() + + sqlite.exec('DROP TABLE IF EXISTS history_fts') + sqlite.exec('DROP TABLE IF EXISTS meeting_sessions_fts') + sqlite.exec('DROP TABLE IF EXISTS meeting_memos_fts') + + const response = getUnifiedSearchService().search({ query: '데이터베이스', limit: 10 }) + expect(response.total).toBe(2) + expect(response.results.map((r) => r.id)).toEqual(['meet-legacy', 'hist-legacy']) + }) + + it('search_ftsMatchThrowsAtRuntime_fallsBackToLikeFilteringSafely', () => { + const { db, sqlite } = useFreshTestDb() + db.insert(history) + .values( + makeHistoryRow({ + id: 'hist-fts-broken', + title: '복구 테스트', + polishedText: '인덱스 손상 복구 검증', + createdAt: 500, + updatedAt: 500, + }), + ) + .run() + + // Replace history_fts with a plain non-FTS table so sqlite_master reports it exists, causing MATCH to fail at runtime + sqlite.exec('DROP TRIGGER IF EXISTS history_fts_ai') + sqlite.exec('DROP TRIGGER IF EXISTS history_fts_au') + sqlite.exec('DROP TRIGGER IF EXISTS history_fts_ad') + sqlite.exec('DROP TABLE history_fts') + sqlite.exec('CREATE TABLE history_fts (row_id TEXT)') + + const response = getUnifiedSearchService().search({ query: '손상 복구', limit: 10 }) + expect(response.total).toBe(1) + expect(response.results.map((r) => r.id)).toEqual(['hist-fts-broken']) + }) }) diff --git a/apps/desktop/tests/main/services/bug-hunt-timer-cleanup.test.ts b/apps/desktop/tests/main/services/bug-hunt-timer-cleanup.test.ts new file mode 100644 index 0000000..520ebeb --- /dev/null +++ b/apps/desktop/tests/main/services/bug-hunt-timer-cleanup.test.ts @@ -0,0 +1,114 @@ +import { EventEmitter } from 'events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { initInMemoryConfig, resetInMemoryConfig } from '../../../src/main/services/ConfigService' +import { AdMediationEngine } from '../../../src/main/services/ads/AdMediationEngine' +import { + getAudioCaptureService, + resetAudioCaptureServiceForTests, +} from '../../../src/main/services/AudioCaptureService' +import { + getLocalLLMService, + resetLocalLLMServiceForTests, +} from '../../../src/main/services/LocalLLMService' + +const spawnState = vi.hoisted(() => ({ + nextProc: null as null | (EventEmitter & { + stdout: EventEmitter + stderr: EventEmitter + kill: ReturnType + }), +})) + +vi.mock('child_process', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + spawn: vi.fn((...args: Parameters) => { + if (spawnState.nextProc) { + const proc = spawnState.nextProc + spawnState.nextProc = null + return proc + } + return actual.spawn(...args) + }), + } +}) + +describe('Main service timer cleanup regressions', () => { + beforeEach(() => { + vi.useFakeTimers() + initInMemoryConfig() + resetLocalLLMServiceForTests() + resetAudioCaptureServiceForTests() + ;(AdMediationEngine as unknown as { instance: null }).instance = null + }) + + afterEach(() => { + resetLocalLLMServiceForTests() + resetAudioCaptureServiceForTests() + ;(AdMediationEngine as unknown as { instance: null }).instance = null + spawnState.nextProc = null + resetInMemoryConfig() + vi.unstubAllGlobals() + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('LocalLLMService_disposeAfterStartServer_cancelsPendingAvailabilityCheckTimers', async () => { + const fetchMock = vi.fn(async () => new Response(JSON.stringify({ version: '0.5.0' }), { status: 200 })) + vi.stubGlobal('fetch', fetchMock) + + const llm = getLocalLLMService() + const status = await llm.startServer() + expect(status).toBe('running') + expect(vi.getTimerCount()).toBe(2) + + const callsBeforeDispose = fetchMock.mock.calls.length + llm.dispose() + + expect(vi.getTimerCount()).toBe(0) + await vi.advanceTimersByTimeAsync(5_000) + expect(fetchMock).toHaveBeenCalledTimes(callsBeforeDispose) + }) + + it('AdMediationEngine_runAuctionSettlesBeforeTimeout_clearsBidTimeoutTimer', async () => { + const engine = AdMediationEngine.getInstance() + const config = engine.getConfig() + engine.setConfig({ + headerBiddingTimeoutMs: 15_000, + networks: config.networks.map((n) => + n.id === 'direct_sponsor' ? { ...n, enabled: true } : n, + ), + }) + + const result = await engine.runAuction({ + placementId: 'dock-1', + format: 'banner_dock', + }) + + expect(result.winner === null).toBe(true) + expect(result.winningBidEcpm).toBe(0) + expect(result.participatingBids).toHaveLength(1) + expect(vi.getTimerCount()).toBe(0) + }) + + it('AudioCaptureService_testCaptureExitsEarly_clearsDurationKillTimer', async () => { + const proc = Object.assign(new EventEmitter(), { + stdout: new EventEmitter(), + stderr: new EventEmitter(), + kill: vi.fn(), + }) + spawnState.nextProc = proc + + const service = getAudioCaptureService() + const capturePromise = service.testCapture(10_000) + expect(vi.getTimerCount()).toBe(1) + + proc.emit('close', 0) + const stats = await capturePromise + + expect(stats).toEqual({ averageLevel: 0, peakLevel: 0, hasAudio: false }) + expect(proc.kill).not.toHaveBeenCalled() + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/apps/desktop/tests/main/services/disk-wav-audio-sink.test.ts b/apps/desktop/tests/main/services/disk-wav-audio-sink.test.ts new file mode 100644 index 0000000..97377a0 --- /dev/null +++ b/apps/desktop/tests/main/services/disk-wav-audio-sink.test.ts @@ -0,0 +1,200 @@ +// tests/main/services/disk-wav-audio-sink.test.ts +// GAP-PERF-01 잔여: 장시간 회의 녹음 PCM 디스크 스트리밍 계약 테스트 + +import fs from 'fs' +import os from 'os' +import path from 'path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { CaptionSegment } from '@d3ro/core/types' +import { MeetingRecordingSession } from '../../../src/main/services/meeting/MeetingRecordingSession' +import { + DiskWavAudioSink, + MAX_WAV_DATA_BYTES, + writeWavHeader16kMonoPcm16, +} from '../../../src/main/services/meeting/disk-wav-audio-sink' + +describe('DiskWavAudioSink & MeetingRecordingSession 스트리밍', () => { + let tempDir = '' + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'd3ro-wav-sink-')) + }) + + afterEach(() => { + vi.restoreAllMocks() + if (tempDir) { + fs.rmSync(tempDir, { recursive: true, force: true }) + } + }) + + it('녹음종료_다중PCM청크스트리밍_메모리누적없이유효한WAV헤더와페이로드를기록한다', async () => { + const wavPath = path.join(tempDir, 'meeting-audio', 'session-1.wav') + const sink = new DiskWavAudioSink(wavPath) + + let chunkListener: ((buffer: Buffer) => void) | null = null + const session = new MeetingRecordingSession('session-1', 1_000, { + caption: { + onSegment: () => () => undefined, + stop: async () => ({ + segments: [{ id: 'seg-1', text: '회의 발언', timestamp: 2_000, isFinal: true } satisfies CaptionSegment], + }), + }, + audio: { + onChunk: (listener) => { + chunkListener = listener + return () => { + chunkListener = null + } + }, + }, + audioSink: sink, + now: () => 5_000, + }) + + session.attachCaption() + session.attachAudio() + + const chunk1 = Buffer.from([0x01, 0x02, 0x03, 0x04]) + const chunk2 = Buffer.from([0x05, 0x06, 0x07, 0x08, 0x09, 0x0a]) + chunkListener?.(chunk1) + chunkListener?.(chunk2) + + // 중간 체크포인트는 임시 .part 를 유지하고 최종 WAV 를 아직 닫지 않는다 + const mid = session.checkpoint({ includeAudio: false }) + expect(mid.pcm.length).toBe(0) + expect(mid.audioSavedToDisk).toBe(false) + expect(fs.existsSync(`${wavPath}.part`)).toBe(true) + expect(fs.existsSync(wavPath)).toBe(false) + + const snapshot = await session.stop() + + expect(snapshot.pcm.length).toBe(0) + expect(snapshot.audioSavedToDisk).toBe(true) + expect(snapshot.pcmByteLength).toBe(10) + expect(fs.existsSync(`${wavPath}.part`)).toBe(false) + expect(fs.existsSync(wavPath)).toBe(true) + + const written = fs.readFileSync(wavPath) + expect(written.length).toBe(44 + 10) + expect(written.subarray(0, 4).toString('ascii')).toBe('RIFF') + expect(written.readUInt32LE(4)).toBe(36 + 10) + expect(written.subarray(8, 12).toString('ascii')).toBe('WAVE') + expect(written.subarray(12, 16).toString('ascii')).toBe('fmt ') + expect(written.readUInt16LE(20)).toBe(1) + expect(written.readUInt16LE(22)).toBe(1) + expect(written.readUInt32LE(24)).toBe(16000) + expect(written.readUInt16LE(34)).toBe(16) + expect(written.subarray(36, 40).toString('ascii')).toBe('data') + expect(written.readUInt32LE(40)).toBe(10) + expect([...written.subarray(44)]).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + }) + + it('세션분리_시작실패나중단시detach호출_임시part파일을제거한다', () => { + const wavPath = path.join(tempDir, 'session-abort.wav') + const sink = new DiskWavAudioSink(wavPath) + + let chunkListener: ((buffer: Buffer) => void) | null = null + const session = new MeetingRecordingSession('session-abort', 1_000, { + caption: { + onSegment: () => () => undefined, + stop: async () => null, + }, + audio: { + onChunk: (listener) => { + chunkListener = listener + return () => { + chunkListener = null + } + }, + }, + audioSink: sink, + now: () => 2_000, + }) + + session.attachAudio() + chunkListener?.(Buffer.from([0x11, 0x22])) + expect(fs.existsSync(`${wavPath}.part`)).toBe(true) + + session.detach() + + expect(fs.existsSync(`${wavPath}.part`)).toBe(false) + expect(fs.existsSync(wavPath)).toBe(false) + }) + + it('무음종료_청크가하나도없을때_빈WAV파일을남기지않는다', async () => { + const wavPath = path.join(tempDir, 'session-empty.wav') + const sink = new DiskWavAudioSink(wavPath) + const session = new MeetingRecordingSession('session-empty', 1_000, { + caption: { + onSegment: () => () => undefined, + stop: async () => null, + }, + audio: { + onChunk: () => () => undefined, + }, + audioSink: sink, + now: () => 2_000, + }) + + session.attachAudio() + const snapshot = await session.stop() + + expect(snapshot.audioSavedToDisk).toBe(false) + expect(snapshot.pcmByteLength).toBe(0) + expect(fs.existsSync(wavPath)).toBe(false) + expect(fs.existsSync(`${wavPath}.part`)).toBe(false) + }) + + it('append_initialPlaceholderWriteSyncThrows_closesOpenedFdRemovesPartAndRethrows', () => { + const wavPath = path.join(tempDir, 'placeholder-fail.wav') + const sink = new DiskWavAudioSink(wavPath) + + const openedFds: number[] = [] + const realOpenSync = fs.openSync + vi.spyOn(fs, 'openSync').mockImplementation((...args) => { + const fd = realOpenSync(...args) + openedFds.push(fd) + return fd + }) + const closeSpy = vi.spyOn(fs, 'closeSync') + vi.spyOn(fs, 'writeSync').mockImplementationOnce(() => { + throw new Error('ENOSPC: no space left on device') + }) + + expect(() => sink.append(Buffer.from([0x01, 0x02]))).toThrow('ENOSPC: no space left on device') + expect(openedFds).toHaveLength(1) + expect(closeSpy).toHaveBeenCalledWith(openedFds[0]) + expect(fs.existsSync(`${wavPath}.part`)).toBe(false) + expect(sink.pcmByteLength).toBe(0) + expect(sink.finalize()).toEqual({ saved: false, pcmByteLength: 0 }) + }) + + it('writeWavHeader16kMonoPcm16_withinAndBeyondUint32Limit_validatesRange', () => { + const maxHeader = writeWavHeader16kMonoPcm16(Buffer.alloc(44), MAX_WAV_DATA_BYTES) + expect(maxHeader.readUInt32LE(4)).toBe(0xffffffff) + expect(maxHeader.readUInt32LE(40)).toBe(MAX_WAV_DATA_BYTES) + + expect(() => writeWavHeader16kMonoPcm16(Buffer.alloc(44), MAX_WAV_DATA_BYTES + 1)).toThrow( + RangeError, + ) + expect(() => writeWavHeader16kMonoPcm16(Buffer.alloc(44), -1)).toThrow(RangeError) + expect(() => writeWavHeader16kMonoPcm16(Buffer.alloc(44), 1.5)).toThrow(RangeError) + }) + + it('append_chunkExceedingUint32Limit_throwsRangeErrorWithoutCorruptingExistingAudio', () => { + const wavPath = path.join(tempDir, 'limit-check.wav') + const sink = new DiskWavAudioSink(wavPath) + + const initialChunk = Buffer.from([0xaa, 0xbb]) + sink.append(initialChunk) + expect(sink.pcmByteLength).toBe(2) + + const oversizedSlice = { length: MAX_WAV_DATA_BYTES } as unknown as Buffer + expect(() => sink.append(oversizedSlice)).toThrow(RangeError) + expect(sink.pcmByteLength).toBe(2) + + const finalized = sink.finalize() + expect(finalized).toEqual({ saved: true, pcmByteLength: 2 }) + expect(fs.readFileSync(wavPath).subarray(44)).toEqual(initialChunk) + }) +}) diff --git a/apps/desktop/tests/main/services/meeting-diarization.test.ts b/apps/desktop/tests/main/services/meeting-diarization.test.ts new file mode 100644 index 0000000..4c9d249 --- /dev/null +++ b/apps/desktop/tests/main/services/meeting-diarization.test.ts @@ -0,0 +1,133 @@ +// tests/main/services/meeting-diarization.test.ts +// GAP-MTG-02: MeetingModeService.diarizeSession pyannote HTTP 경로 및 LLM 폴백 검증 + +import fs from 'fs' +import path from 'path' +import { eq } from 'drizzle-orm' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { app } from 'electron' +import { useRedHarness } from '../../red/harness' + +const llmCapture = vi.hoisted(() => ({ + calls: [] as Array<{ text: string; systemPrompt?: string }>, +})) + +vi.mock('../../../src/main/services/LocalLLMService', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getLocalLLMService: () => ({ + isAvailable: () => true, + generate: async (text: string, options?: { systemPrompt?: string }) => { + llmCapture.calls.push({ text, systemPrompt: options?.systemPrompt }) + return { + text: '[00:02] [화자 1] 안녕하세요\n[00:08] [화자 2] 반갑습니다', + model: 'gemma-test', + } + }, + cancelGeneration: vi.fn(), + }), + } +}) + +useRedHarness() + +import { configSet } from '../../../src/main/services/ConfigService' +import { getMeetingModeService } from '../../../src/main/services/MeetingModeService' +import { getDatabase } from '../../../src/main/db' +import { meetingSessions } from '../../../src/main/db/schema' + +function insertCompletedSession(sessionId: string, rawTranscript: string): string { + const startedAt = 1_700_000_000_000 + getDatabase() + .insert(meetingSessions) + .values({ + id: sessionId, + title: '화자 구분 테스트 회의', + status: 'completed', + startedAt, + endedAt: startedAt + 15_000, + durationMs: 15_000, + rawTranscript, + createdAt: startedAt, + updatedAt: startedAt, + }) + .run() + + const audioDir = path.join(app.getPath('userData'), 'meeting-audio') + fs.mkdirSync(audioDir, { recursive: true }) + const wavPath = path.join(audioDir, `${sessionId}.wav`) + fs.writeFileSync(wavPath, Buffer.from('RIFF0000WAVEfmt ')) + return wavPath +} + +describe('MeetingModeService.diarizeSession (GAP-MTG-02)', () => { + beforeEach(() => { + llmCapture.calls = [] + configSet('llmBackend', 'local') + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('화자분리_사이드카diarize성공시_pyannote구간을1기반화자라벨로저장한다', async () => { + const sessionId = '11111111-1111-4111-8111-111111111111' + insertCompletedSession(sessionId, '[00:02] 안녕하세요\n[00:08] 반갑습니다') + configSet('hfToken', 'hf_valid_token') + + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue( + new Response( + JSON.stringify({ + status: 'ok', + num_speakers: 2, + segments: [ + { speaker: 'SPEAKER_00', start: 0.0, end: 5.0 }, + { speaker: 'SPEAKER_01', start: 5.5, end: 12.0 }, + ], + }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ), + ) + + await getMeetingModeService().diarizeSession(sessionId, 2) + + expect(fetchSpy).toHaveBeenCalledTimes(1) + expect(String(fetchSpy.mock.calls[0]?.[0])).toContain('/diarize') + expect(llmCapture.calls).toHaveLength(0) + + const updated = getDatabase() + .select() + .from(meetingSessions) + .where(eq(meetingSessions.id, sessionId)) + .get() + expect(updated?.editedTranscript).toBe('[00:02] [화자 1] 안녕하세요\n[00:08] [화자 2] 반갑습니다') + }) + + it('화자분리_사이드카pyannote미설치503응답시_LLM화자추정으로폴백한다', async () => { + const sessionId = '22222222-2222-4222-8222-222222222222' + insertCompletedSession(sessionId, '[00:02] 안녕하세요\n[00:08] 반갑습니다') + configSet('hfToken', 'hf_valid_token') + + vi.spyOn(globalThis, 'fetch').mockResolvedValue( + new Response( + JSON.stringify({ + status: 'unavailable', + code: 'pyannote_not_installed', + message: 'pyannote.audio 패키지가 설치되어 있지 않습니다', + }), + { status: 503, headers: { 'Content-Type': 'application/json' } }, + ), + ) + + await getMeetingModeService().diarizeSession(sessionId, 2) + + expect(llmCapture.calls).toHaveLength(1) + const updated = getDatabase() + .select() + .from(meetingSessions) + .where(eq(meetingSessions.id, sessionId)) + .get() + expect(updated?.editedTranscript).toBe('[00:02] [화자 1] 안녕하세요\n[00:08] [화자 2] 반갑습니다') + }) +}) diff --git a/apps/desktop/tests/main/services/online-llm-service.test.ts b/apps/desktop/tests/main/services/online-llm-service.test.ts new file mode 100644 index 0000000..278c20d --- /dev/null +++ b/apps/desktop/tests/main/services/online-llm-service.test.ts @@ -0,0 +1,239 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { D3ROError, ErrorCode } from '@d3ro/core/errors' +import { + configGet, + configSet, + initInMemoryConfig, + resetInMemoryConfig, +} from '../../../src/main/services/ConfigService' +import { + getOnlineLLMService, + resetOnlineLLMServiceForTests, +} from '../../../src/main/services/OnlineLLMService' + +async function collectChatStream( + gen: AsyncGenerator, +): Promise<{ tokens: string[]; result: string }> { + const tokens: string[] = [] + let next = await gen.next() + while (!next.done) { + tokens.push(next.value) + next = await gen.next() + } + return { tokens, result: next.value } +} + +function captureAbortedFetch(onStarted: () => void): typeof fetch { + return vi.fn((_input: string | URL | Request, init?: RequestInit) => { + const signal = init?.signal + return new Promise((_resolve, reject) => { + if (signal?.aborted) { + reject(new DOMException('The operation was aborted', 'AbortError')) + return + } + signal?.addEventListener( + 'abort', + () => reject(new DOMException('The operation was aborted', 'AbortError')), + { once: true }, + ) + onStarted() + }) + }) as unknown as typeof fetch +} + +describe('OnlineLLMService chatStream', () => { + beforeEach(() => { + initInMemoryConfig() + configSet('authToken', 'valid-jwt-token') + configSet('onlineApiUrl', 'http://127.0.0.1:5000') + resetOnlineLLMServiceForTests() + }) + + afterEach(() => { + resetOnlineLLMServiceForTests() + resetInMemoryConfig() + vi.unstubAllGlobals() + }) + + it('chatStream_cancelGenerationCalledDuringRequest_abortsFetchAndThrowsCancelled', async () => { + const service = getOnlineLLMService() + let startedResolve!: () => void + const started = new Promise((resolve) => { + startedResolve = resolve + }) + + vi.stubGlobal('fetch', captureAbortedFetch(startedResolve)) + + const run = collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])) + await started + service.cancelGeneration() + + await expect(run).rejects.toMatchObject({ + name: 'D3ROError', + code: ErrorCode.LLMProcessingCancelled, + }) + + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ text: 'recovered' }), { status: 200 })), + ) + const retry = await collectChatStream(service.chatStream([{ role: 'user', content: 'next' }])) + expect(retry.tokens).toEqual(['recovered']) + expect(retry.result).toBe('recovered') + }) + + it('chatStream_disposeCalledDuringRequest_abortsFetchAndBlocksFutureCalls', async () => { + const service = getOnlineLLMService() + let startedResolve!: () => void + const started = new Promise((resolve) => { + startedResolve = resolve + }) + + vi.stubGlobal('fetch', captureAbortedFetch(startedResolve)) + + const run = collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])) + await started + service.dispose() + + await expect(run).rejects.toMatchObject({ + name: 'D3ROError', + code: ErrorCode.LLMProcessingCancelled, + }) + + await expect( + collectChatStream(service.chatStream([{ role: 'user', content: 'after-dispose' }])), + ).rejects.toMatchObject({ + name: 'D3ROError', + code: ErrorCode.LLMProcessingFailed, + }) + }) + + it('chatStream_externalSignalAborted_abortsFetchAndThrowsCancelled', async () => { + const service = getOnlineLLMService() + let startedResolve!: () => void + const started = new Promise((resolve) => { + startedResolve = resolve + }) + vi.stubGlobal('fetch', captureAbortedFetch(startedResolve)) + + const external = new AbortController() + const run = collectChatStream( + service.chatStream([{ role: 'user', content: 'hello' }], { signal: external.signal }), + ) + await started + external.abort() + + await expect(run).rejects.toMatchObject({ + name: 'D3ROError', + code: ErrorCode.LLMProcessingCancelled, + }) + }) + + it('chatStream_serverReturns401_clearsAuthTokenAndThrowsUnreachable', async () => { + const service = getOnlineLLMService() + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('Unauthorized', { status: 401 })), + ) + + await expect( + collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])), + ).rejects.toMatchObject({ + name: 'D3ROError', + code: ErrorCode.LLMServerUnreachable, + }) + expect(configGet('authToken')).toBe(null) + }) + + it('chatStream_serverReturns500_throwsLLMProcessingFailed', async () => { + const service = getOnlineLLMService() + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('Internal Error', { status: 500 })), + ) + + await expect( + collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])), + ).rejects.toMatchObject({ + name: 'D3ROError', + code: ErrorCode.LLMProcessingFailed, + }) + expect(configGet('authToken')).toBe('valid-jwt-token') + }) + + it.each([ + { label: 'missing text field', body: { model: 'd3ro-gpt4o-mini' } }, + { label: 'whitespace-only text', body: { text: ' \n\t ' } }, + { label: 'null response json', body: null }, + ])('chatStream_emptyOrInvalidPayload_$label_throwsLLMProcessingFailed', async ({ body }) => { + const service = getOnlineLLMService() + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify(body), { status: 200 })), + ) + + let caught: unknown + try { + await collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])) + } catch (err) { + caught = err + } + + expect(caught instanceof D3ROError).toBe(true) + expect((caught as D3ROError).code).toBe(ErrorCode.LLMProcessingFailed) + }) + + it('chatStream_fetchRejectsOrInvalidJson_wrapsInLLMProcessingFailed', async () => { + const service = getOnlineLLMService() + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new Error('socket hang up') + }), + ) + + await expect( + collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])), + ).rejects.toMatchObject({ + name: 'D3ROError', + code: ErrorCode.LLMProcessingFailed, + }) + + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('{not-json', { status: 200 })), + ) + + await expect( + collectChatStream(service.chatStream([{ role: 'user', content: 'hello' }])), + ).rejects.toMatchObject({ + name: 'D3ROError', + code: ErrorCode.LLMProcessingFailed, + }) + }) + + it('chatStream_messageContainsPII_redactsBeforeFetchAndRehydratesOutput', async () => { + const service = getOnlineLLMService() + let sentBody = '' + vi.stubGlobal( + 'fetch', + vi.fn(async (_url: string | URL | Request, init?: RequestInit) => { + sentBody = String(init?.body ?? '') + const parsed = JSON.parse(sentBody) as { messages: Array<{ content: string }> } + const redactedUserMsg = parsed.messages[0].content + return new Response( + JSON.stringify({ text: `확인 완료: ${redactedUserMsg}` }), + { status: 200 }, + ) + }), + ) + + const { tokens, result } = await collectChatStream( + service.chatStream([{ role: 'user', content: '연락처는 alice@example.com 입니다.' }]), + ) + + expect(sentBody.includes('alice@example.com')).toBe(false) + expect(tokens).toEqual(['확인 완료: 연락처는 alice@example.com 입니다.']) + expect(result).toBe('확인 완료: 연락처는 alice@example.com 입니다.') + }) +}) diff --git a/apps/desktop/tests/main/services/pii-zdr-wiring.test.ts b/apps/desktop/tests/main/services/pii-zdr-wiring.test.ts new file mode 100644 index 0000000..b8af5e6 --- /dev/null +++ b/apps/desktop/tests/main/services/pii-zdr-wiring.test.ts @@ -0,0 +1,111 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const mockConfigStore = new Map() + +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: vi.fn((key: string) => mockConfigStore.get(key)), + configSet: vi.fn((key: string, value: unknown) => { + mockConfigStore.set(key, value) + }), +})) + +import { + getOnlineLLMService, + resetOnlineLLMServiceForTests, +} from '../../../src/main/services/OnlineLLMService' +import { secureWipeAudioChunks } from '@d3ro/core/utils/secure-memory' + +describe('클라우드 LLM PII 가명화·복원 배선 (W5-01)', () => { + const originalFetch = globalThis.fetch + + beforeEach(() => { + mockConfigStore.clear() + mockConfigStore.set('authToken', 'jwt-test-token') + mockConfigStore.set('onlineApiUrl', 'http://127.0.0.1:5000') + mockConfigStore.set('llmModelId', 'd3ro-gpt4o-mini') + resetOnlineLLMServiceForTests() + }) + + afterEach(() => { + globalThis.fetch = originalFetch + resetOnlineLLMServiceForTests() + }) + + it('processText_민감정보포함프롬프트_클라우드전송시토큰화하고응답에서원문을복원한다', async () => { + let capturedBody: { prompt?: string } = {} + + globalThis.fetch = vi.fn(async (_input, init) => { + capturedBody = JSON.parse(String(init?.body ?? '{}')) as { prompt?: string } + const sentPrompt = capturedBody.prompt ?? '' + return new Response( + JSON.stringify({ + text: `정리됨: ${sentPrompt}`, + model: 'd3ro-gpt4o-mini', + promptTokens: 10, + completionTokens: 10, + totalDurationMs: 25, + cost: 0, + }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ) + }) as typeof fetch + + const result = await getOnlineLLMService().processText( + '연락처 010-1234-5678 및 주민번호 950101-1234567 확인 부탁드립니다', + 'refine', + ) + + expect(capturedBody.prompt).not.toContain('010-1234-5678') + expect(capturedBody.prompt).not.toContain('950101-1234567') + expect(capturedBody.prompt).toContain('[REDACTED_PHONE_NUMBER_') + expect(capturedBody.prompt).toContain('[REDACTED_KR_RRN_') + expect(result).toBe( + '정리됨: 연락처 010-1234-5678 및 주민번호 950101-1234567 확인 부탁드립니다', + ) + }) + + it('chatStream_다중메시지민감정보_요청메시지에서PII를숨기고스트림응답에서복원한다', async () => { + let capturedMessages: Array<{ role: string; content: string }> = [] + + globalThis.fetch = vi.fn(async (_input, init) => { + const parsed = JSON.parse(String(init?.body ?? '{}')) as { + messages: Array<{ role: string; content: string }> + } + capturedMessages = parsed.messages + return new Response( + JSON.stringify({ + text: `확인된 이메일은 ${parsed.messages[0]?.content ?? ''} 입니다.`, + model: 'd3ro-gpt4o-mini', + promptTokens: 8, + completionTokens: 8, + totalDurationMs: 20, + cost: 0, + }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ) + }) as typeof fetch + + const chunks: string[] = [] + for await (const chunk of getOnlineLLMService().chatStream([ + { role: 'user', content: 'founder@d3ro.ai' }, + ])) { + chunks.push(chunk) + } + + expect(capturedMessages[0]?.content).not.toContain('founder@d3ro.ai') + expect(capturedMessages[0]?.content).toContain('[REDACTED_EMAIL_') + expect(chunks.join('')).toBe('확인된 이메일은 founder@d3ro.ai 입니다.') + }) + + it('secureWipeAudioChunks_오디오버퍼폐기시_내부바이트를전부0으로덮어쓰고배열을비운다', () => { + const chunkA = Buffer.from([12, 34, 56, 78]) + const chunkB = Buffer.from([90, 11, 22, 33]) + const chunks = [chunkA, chunkB] + + secureWipeAudioChunks(chunks) + + expect(chunks).toHaveLength(0) + expect(Array.from(chunkA.values())).toEqual([0, 0, 0, 0]) + expect(Array.from(chunkB.values())).toEqual([0, 0, 0, 0]) + }) +}) diff --git a/apps/desktop/tests/main/services/rag-chunk-store-cache.test.ts b/apps/desktop/tests/main/services/rag-chunk-store-cache.test.ts new file mode 100644 index 0000000..d75bf0f --- /dev/null +++ b/apps/desktop/tests/main/services/rag-chunk-store-cache.test.ts @@ -0,0 +1,227 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { eq } from 'drizzle-orm' +import { bindTestDatabase, unbindTestDatabase } from '../../../src/main/db' +import { ragChunks } from '../../../src/main/db/schema' +import { + decodeFloat32Buffer, + invalidateEmbeddedChunksCache, + SqliteChunkStore, +} from '../../../src/main/services/rag/chunk-store' +import { rankChunks } from '../../../src/main/services/rag/retrieval' +import { resetRAGServiceForTests } from '../../../src/main/services/RAGService' +import { adapterFor } from '../../../src/main/services/sync/sync-adapters' +import { createTestDb } from '../../helpers/createTestDb' + +describe('SqliteChunkStore cache optimization, invalidation & hardening', () => { + let closeDb: (() => void) | null = null + + function setupDb() { + const testDb = createTestDb() + closeDb = testDb.close + bindTestDatabase(testDb.db) + return testDb + } + + beforeEach(() => { + unbindTestDatabase() + resetRAGServiceForTests() + }) + + afterEach(() => { + resetRAGServiceForTests() + unbindTestDatabase() + if (closeDb) { + closeDb() + closeDb = null + } + vi.restoreAllMocks() + }) + + it('listEmbeddedChunks_decodesFloat32Vector_stripsRedundantJsonStringFromCache', () => { + setupDb() + const store = new SqliteChunkStore() + store.insertDocument({ + id: 'doc-1', + fileName: 'guide.md', + filePath: 'C:/docs/guide.md', + fileType: 'md', + chunkCount: 2, + indexed: true, + indexedAt: 1_000, + addedAt: 1_000, + }) + store.replaceChunks('doc-1', ['alpha content', 'beta content']) + const chunks = store.listChunks('doc-1') + store.setEmbedding(chunks[0].id, [1, 0, 0]) + store.setEmbedding(chunks[1].id, [0, 1, 0]) + + const parseSpy = vi.spyOn(JSON, 'parse') + const cached = store.listEmbeddedChunks() + + expect(cached).toHaveLength(2) + expect(cached.map((c) => c.embedding)).toEqual(['', '']) + expect(Array.from(cached[0].vector ?? [])).toEqual([1, 0, 0]) + expect(Array.from(cached[1].vector ?? [])).toEqual([0, 1, 0]) + + const ranked = rankChunks([0, 0.9, 0.1], cached, new Map([['doc-1', 'guide.md']]), 1) + expect(ranked).toHaveLength(1) + expect(ranked[0].content).toBe('beta content') + expect(parseSpy).not.toHaveBeenCalled() + }) + + it('invalidateEmbeddedChunksCache_afterDirectDbDelete_clearsStaleCachedChunks', () => { + const { db } = setupDb() + const store = new SqliteChunkStore() + store.insertDocument({ + id: 'doc-stale', + fileName: 'stale.txt', + filePath: 'C:/docs/stale.txt', + fileType: 'txt', + chunkCount: 1, + indexed: true, + indexedAt: 2_000, + addedAt: 2_000, + }) + store.replaceChunks('doc-stale', ['to be deleted']) + const chunks = store.listChunks('doc-stale') + store.setEmbedding(chunks[0].id, [0.5, 0.5]) + + expect(store.listEmbeddedChunks()).toHaveLength(1) + + // Simulate out-of-band delete bypassing SqliteChunkStore methods + db.delete(ragChunks).where(eq(ragChunks.documentId, 'doc-stale')).run() + // Before invalidation cache still serves stale entry + expect(store.listEmbeddedChunks()).toHaveLength(1) + + invalidateEmbeddedChunksCache(db) + expect(store.listEmbeddedChunks()).toEqual([]) + + // Also verify zero-arg invalidation clears currently open DB + store.replaceChunks('doc-stale', ['re-added']) + const nextChunks = store.listChunks('doc-stale') + store.setEmbedding(nextChunks[0].id, [1, 0]) + expect(store.listEmbeddedChunks()).toHaveLength(1) + + db.delete(ragChunks).where(eq(ragChunks.documentId, 'doc-stale')).run() + invalidateEmbeddedChunksCache() + expect(store.listEmbeddedChunks()).toEqual([]) + }) + + it('knowledgeAdapter_deleteLocalAndApplyRemote_invalidatesEmbeddedChunksCache', async () => { + const { db } = setupDb() + const store = new SqliteChunkStore() + const docId = '11111111-1111-4111-8111-111111111111' + store.insertDocument({ + id: docId, + fileName: 'sync.md', + filePath: 'remote://sync.md', + fileType: 'md', + chunkCount: 1, + indexed: true, + indexedAt: 3_000, + addedAt: 3_000, + }) + store.replaceChunks(docId, ['synced chunk']) + const [chunk] = store.listChunks(docId) + store.setEmbedding(chunk.id, [1, 0]) + expect(store.listEmbeddedChunks()).toHaveLength(1) + + // Even if RAGService uses an external custom store that mutates SQL directly, + // knowledgeAdapter.deleteLocal / applyRemote must invalidate SqliteChunkStore cache. + const spyStore: SqliteChunkStore = Object.assign(Object.create(SqliteChunkStore.prototype), { + removeDocument(id: string) { + db.delete(ragChunks).where(eq(ragChunks.documentId, id)).run() + return true + }, + getDocument: () => null, + insertDocument: () => {}, + replaceChunks: () => {}, + listChunks: () => [], + updateDocument: () => {}, + }) + resetRAGServiceForTests({ store: spyStore }) + + const adapter = adapterFor('knowledge_documents') + expect(adapter === null).toBe(false) + expect(adapter!.deleteLocal(docId)).toBe(true) + expect(store.listEmbeddedChunks()).toEqual([]) + + // Populate again and verify applyRemote also invalidates cache + store.replaceChunks(docId, ['before remote apply']) + const [reChunk] = store.listChunks(docId) + store.setEmbedding(reChunk.id, [0, 1]) + expect(store.listEmbeddedChunks()).toHaveLength(1) + + await adapter!.applyRemote( + { + id: docId, + file_name: 'sync.md', + file_type: 'md', + chunk_count: 1, + created_at: '2026-01-01T00:00:00.000Z', + updated_at: '2026-01-02T00:00:00.000Z', + }, + { + userId: 'user-1', + isCurrent: () => true, + remote: { + selectChildren: vi.fn(async () => [{ chunk_index: 0, content: 'updated chunk' }]), + } as never, + }, + ) + // Cache was cleared so listEmbeddedChunks re-queries DB (still 1 here until re-indexed, selectSpy verifies DB query) + const selectSpy = vi.spyOn(db, 'select') + expect(store.listEmbeddedChunks()).toHaveLength(1) + expect(selectSpy).toHaveBeenCalledTimes(1) + }) + + it.each([ + { label: 'malformed json', json: '{bad-json' }, + { label: 'non-array primitive', json: '42' }, + { label: 'empty array', json: '[]' }, + { label: 'non-finite element', json: '[1, null, 3]' }, + ])('decodeFloat32Buffer_$label_returnsUndefinedWithoutThrowing', ({ json }) => { + expect(decodeFloat32Buffer(null, json)).toBe(undefined) + expect(decodeFloat32Buffer(Buffer.alloc(3), json)).toBe(undefined) + }) + + it('listEmbeddedChunksAndRankChunks_oneCorruptedRow_skipsBrokenRowAndRetrievesHealthyRows', () => { + const { db } = setupDb() + const store = new SqliteChunkStore() + store.insertDocument({ + id: 'doc-mixed', + fileName: 'mixed.txt', + filePath: 'C:/docs/mixed.txt', + fileType: 'txt', + chunkCount: 2, + indexed: true, + indexedAt: 4_000, + addedAt: 4_000, + }) + store.replaceChunks('doc-mixed', ['corrupt chunk', 'healthy chunk']) + const chunks = store.listChunks('doc-mixed') + + // Inject corrupted JSON fallback without binary blob into chunk 0 + db.update(ragChunks) + .set({ embedding: '{corrupt', embeddingBlob: null }) + .where(eq(ragChunks.id, chunks[0].id)) + .run() + store.setEmbedding(chunks[1].id, [0, 1, 0]) + + const loaded = store.listEmbeddedChunks() + expect(loaded).toHaveLength(1) + expect(loaded[0].content).toBe('healthy chunk') + + const ranked = rankChunks( + [0, 1, 0], + [ + ...loaded, + { documentId: 'doc-mixed', content: 'broken memory chunk', embedding: '{bad' }, + ], + new Map([['doc-mixed', 'mixed.txt']]), + 5, + ) + expect(ranked).toHaveLength(1) + expect(ranked[0].content).toBe('healthy chunk') + }) +}) diff --git a/apps/desktop/tests/main/services/runtime-hygiene-optimizations.test.ts b/apps/desktop/tests/main/services/runtime-hygiene-optimizations.test.ts new file mode 100644 index 0000000..5dca33c --- /dev/null +++ b/apps/desktop/tests/main/services/runtime-hygiene-optimizations.test.ts @@ -0,0 +1,198 @@ +// tests/main/services/runtime-hygiene-optimizations.test.ts +// 런타임/프로세스 디커플링 검증: +// 1) InputTelemetryService: 텔레메트리 비활성(기본 모드) 시 1,000Hz mousemove 훅을 붙이지 않고, 설정 토글 시 동적 연결/해제 +// 2) LocalSTTService & STTManager: 클라우드 공급자 전환 또는 유휴 언로드 시 사이드카(UIA 브리지)는 살려둔 채 기본 Whisper 모델만 내려 RAM/VRAM 회수 + +import { EventEmitter } from 'events' +import type { ChildProcess } from 'child_process' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const hookCalls = vi.hoisted(() => ({ + on: vi.fn(), + removeListener: vi.fn(), +})) + +vi.mock('electron', () => ({ + app: { getPath: () => '/tmp/d3ro-test' }, + screen: { getPrimaryDisplay: () => ({ scaleFactor: 1 }) }, +})) + +vi.mock('uiohook-napi', () => ({ + uIOhook: { + on: hookCalls.on, + removeListener: hookCalls.removeListener, + }, +})) + +vi.mock('../../../src/main/services/global-input-hook', () => ({ + acquireGlobalInputHook: () => () => undefined, +})) + +vi.mock('../../../src/main/services/KeyBindingService', () => ({ + uiohookCodeToVk: () => null, +})) + +vi.mock('../../../src/main/services/UiaContextService', () => ({ + getUiaContextService: () => ({ + isAvailable: () => false, + lastReason: 'test', + lastSuccessAt: 0, + }), +})) + +vi.mock('../../../src/main/utils/win32-foreground', () => ({ + getForegroundWindowInfo: () => null, + isForegroundKoreanIme: () => false, +})) + +import { + configSet, + initInMemoryConfig, + resetInMemoryConfig, +} from '../../../src/main/services/ConfigService' +import { + getInputTelemetryService, + resetInputTelemetryServiceForTests, +} from '../../../src/main/services/InputTelemetryService' +import { + LocalSTTService, + getLocalSTTService, + resetLocalSTTServiceForTests, +} from '../../../src/main/services/LocalSTTService' +import { SidecarSupervisor, type SidecarFetchFn } from '../../../src/main/services/stt/SidecarSupervisor' +import { getSTTManager, resetSTTManagerForTests } from '../../../src/main/services/stt/STTManager' + +class FakeSidecarProcess extends EventEmitter { + exitCode: number | null = null + signalCode: NodeJS.Signals | null = null + stdout = null + stderr = null + kill = vi.fn((): boolean => { + this.exitCode = 0 + this.emit('exit', 0, null) + return true + }) +} + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }) +} + +describe('런타임 백그라운드 오버헤드 및 모델 상주 최적화', () => { + beforeEach(() => { + initInMemoryConfig() + hookCalls.on.mockClear() + hookCalls.removeListener.mockClear() + resetInputTelemetryServiceForTests() + resetLocalSTTServiceForTests() + resetSTTManagerForTests() + }) + + afterEach(() => { + resetInputTelemetryServiceForTests() + resetLocalSTTServiceForTests() + resetSTTManagerForTests() + resetInMemoryConfig() + vi.unstubAllGlobals() + vi.restoreAllMocks() + }) + + it('InputTelemetryService_텔레메트리비활성기본모드시_mousemove훅을붙이지않고켜질때만연결한다', () => { + configSet('inputTelemetryEnabled', false) + configSet('inputTelemetryPaused', false) + configSet('typoAutoCorrectEnabled', true) + + const telemetry = getInputTelemetryService() + telemetry.start() + + const attachedEvents = hookCalls.on.mock.calls.map((call) => call[0] as string) + expect(attachedEvents).toContain('keydown') + expect(attachedEvents).toContain('mousedown') + expect(attachedEvents).not.toContain('mousemove') + expect(attachedEvents).not.toContain('wheel') + + // 사용자가 입력 텔레메트리를 켜면 실행 중에도 mousemove·wheel 리스너를 즉시 연결한다. + hookCalls.on.mockClear() + configSet('inputTelemetryEnabled', true) + telemetry.applyConfig() + + const dynamicallyAttached = hookCalls.on.mock.calls.map((call) => call[0] as string) + expect(dynamicallyAttached).toContain('mousemove') + expect(dynamicallyAttached).toContain('wheel') + + // 다시 끄면 키보드·클릭 관찰은 유지하면서 mousemove·wheel 만 분리한다. + hookCalls.removeListener.mockClear() + configSet('inputTelemetryEnabled', false) + telemetry.applyConfig() + + const dynamicallyDetached = hookCalls.removeListener.mock.calls.map((call) => call[0] as string) + expect(dynamicallyDetached).toContain('mousemove') + expect(dynamicallyDetached).toContain('wheel') + expect(telemetry.isRunning).toBe(true) + + telemetry.stop() + }) + + it('LocalSTTService_기본모델언로드및클라우드공급자전환시_사이드카는유지한채모델메모리만회수한다', async () => { + const unloadBodies: Array> = [] + let clock = 0 + + const fetchFn: SidecarFetchFn = async (input, init) => { + if (input.endsWith('/health')) { + return jsonResponse({ status: 'ready', model: 'tiny', gpu: false }) + } + if (input.endsWith('/load')) { + return jsonResponse({ status: 'loaded', model_id: 'tiny', load_time_ms: 5 }) + } + if (input.endsWith('/unload')) { + const parsed = JSON.parse(String(init?.body ?? '{}')) as Record + unloadBodies.push(parsed) + return jsonResponse({ status: 'unloaded', models: ['tiny'] }) + } + if (input.endsWith('/shutdown')) { + return jsonResponse({ ok: true }) + } + throw new TypeError(`unexpected ${input}`) + } + + const supervisor = new SidecarSupervisor({ + resolveLaunch: async () => ({ command: 'fake-sidecar', args: [], source: 'venv' }), + modelsDir: () => 'models', + baseUrlFor: (port) => `http://127.0.0.1:${port}`, + spawn: vi.fn(() => { + const proc = new FakeSidecarProcess() + setImmediate(() => proc.emit('spawn')) + return proc as unknown as ChildProcess + }), + fetch: fetchFn, + findFreePort: async (start) => start, + now: () => clock, + sleep: async (ms) => { + clock += ms + }, + }) + + vi.stubGlobal('fetch', fetchFn) + const local = new LocalSTTService({ supervisor }) + await local.initialize('tiny') + expect(local.currentModelId).toBe('tiny') + expect(local.getStatus().engineState).toBe('ready') + + await local.releasePrimaryModel() + + expect(unloadBodies).toEqual([{ slot: 'primary' }]) + expect(local.currentModelId).toBe(null) + expect(local.getStatus().engineState).toBe('not-installed') + expect(supervisor.isHealthy).toBe(true) + + // STTManager 가 클라우드 공급자로 전환할 때도 싱글톤 LocalSTTService 의 releasePrimaryModel 을 호출해야 한다. + const releaseSpy = vi.spyOn(getLocalSTTService(), 'releasePrimaryModel').mockResolvedValue() + getSTTManager().setProvider('d3ro-cloud') + expect(releaseSpy).toHaveBeenCalledTimes(1) + + await local.dispose() + }) +}) diff --git a/apps/desktop/tests/main/windows/popup-hide-show-race.test.ts b/apps/desktop/tests/main/windows/popup-hide-show-race.test.ts new file mode 100644 index 0000000..508bb73 --- /dev/null +++ b/apps/desktop/tests/main/windows/popup-hide-show-race.test.ts @@ -0,0 +1,142 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +type Listener = (...args: unknown[]) => void + +const state = vi.hoisted(() => ({ + windows: [] as Array<{ + visible: boolean + destroyed: boolean + windowListeners: Map + }>, +})) + +vi.unmock('../../../src/main/windows/WindowManager') + +vi.mock('electron', () => { + class FakeBrowserWindow { + visible = false + destroyed = false + windowListeners = new Map() + webContents = { + on: vi.fn(), + send: vi.fn(), + isDestroyed: () => false, + insertCSS: async () => '', + executeJavaScript: async () => undefined, + invalidate: vi.fn(), + setWindowOpenHandler: vi.fn(), + } + showInactive = vi.fn(() => { + this.visible = true + }) + show = vi.fn(() => { + this.visible = true + }) + hide = vi.fn(() => { + this.visible = false + }) + setIgnoreMouseEvents = vi.fn() + setBounds = vi.fn() + setAlwaysOnTop = vi.fn() + moveTop = vi.fn() + loadURL = vi.fn(async () => undefined) + loadFile = vi.fn(async () => undefined) + + constructor() { + state.windows.push(this) + } + + on(event: string, listener: Listener): this { + this.windowListeners.set(event, listener) + return this + } + + isVisible(): boolean { + return this.visible + } + + isDestroyed(): boolean { + return this.destroyed + } + } + + return { + nativeTheme: { shouldUseDarkColors: true, on: () => undefined, removeListener: () => undefined }, + app: { quit: vi.fn(), getPath: vi.fn(() => '.'), on: vi.fn(), getVersion: vi.fn(() => '1.0.0'), isPackaged: false }, + BrowserWindow: Object.assign(FakeBrowserWindow, { getAllWindows: vi.fn(() => []) }), + screen: { + getPrimaryDisplay: vi.fn(() => ({ workAreaSize: { width: 1280, height: 720 }, workArea: { x: 0, y: 0, width: 1280, height: 720 } })), + getAllDisplays: vi.fn(() => [{ workArea: { x: 0, y: 0, width: 1280, height: 720 } }]), + getCursorScreenPoint: vi.fn(() => ({ x: 400, y: 400 })), + getDisplayNearestPoint: vi.fn(() => ({ workArea: { x: 0, y: 0, width: 1280, height: 720 } })), + screenToDipRect: vi.fn((_win: unknown, rect: { x: number; y: number; width: number; height: number }) => rect), + }, + ipcMain: { on: vi.fn(), once: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, + Menu: { setApplicationMenu: vi.fn(), buildFromTemplate: vi.fn() }, + clipboard: { writeText: vi.fn() }, + shell: { openExternal: vi.fn(async () => undefined) }, + safeStorage: { isEncryptionAvailable: vi.fn(() => false) }, + nativeImage: { createFromPath: vi.fn(), createEmpty: vi.fn() }, + Tray: vi.fn(), + dialog: { showErrorBox: vi.fn() }, + } +}) + +vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } })) +vi.mock('../../../src/main/services/ConfigService', () => ({ + configGet: (key: string) => (key === 'language' ? 'ko' : key === 'theme' ? 'dark' : {}), + configSet: vi.fn(), +})) + +describe('WindowManager popup hide/show timer race regressions', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.resetModules() + state.windows.length = 0 + }) + + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('showHistoryPopup_calledWithin150msAfterHide_cancelsPendingHideTimerAndStaysVisible', async () => { + const wm = await import('../../../src/main/windows/WindowManager') + + wm.showHistoryPopup([{ id: 'h-1', text: 'first' }]) + expect(wm.isHistoryPopupVisible()).toBe(true) + + wm.hideHistoryPopup() + await vi.advanceTimersByTimeAsync(50) + // Re-open before the 150ms hide timer fires + wm.showHistoryPopup([{ id: 'h-1', text: 'second' }]) + expect(wm.isHistoryPopupVisible()).toBe(true) + + await vi.advanceTimersByTimeAsync(200) + expect(wm.isHistoryPopupVisible()).toBe(true) + + // Subsequent hide still hides cleanly after 150ms + wm.hideHistoryPopup() + await vi.advanceTimersByTimeAsync(160) + expect(wm.isHistoryPopupVisible()).toBe(false) + }) + + it('showCommandPopup_calledWithin150msAfterHide_cancelsPendingHideTimerAndStaysVisible', async () => { + const wm = await import('../../../src/main/windows/WindowManager') + + wm.showCommandPopup([{ id: 'cmd-1', name: 'Summarize' }], null) + expect(wm.isCommandPopupVisible()).toBe(true) + + wm.hideCommandPopup() + await vi.advanceTimersByTimeAsync(50) + wm.showCommandPopup([{ id: 'cmd-1', name: 'Summarize' }], 'cmd-1') + expect(wm.isCommandPopupVisible()).toBe(true) + + await vi.advanceTimersByTimeAsync(200) + expect(wm.isCommandPopupVisible()).toBe(true) + + wm.hideCommandPopup() + await vi.advanceTimersByTimeAsync(160) + expect(wm.isCommandPopupVisible()).toBe(false) + }) +}) diff --git a/apps/desktop/tests/red/ads/ads-mediation.test.ts b/apps/desktop/tests/red/ads/ads-mediation.test.ts index 47d2010..12c12fa 100644 --- a/apps/desktop/tests/red/ads/ads-mediation.test.ts +++ b/apps/desktop/tests/red/ads/ads-mediation.test.ts @@ -6,16 +6,8 @@ import { beforeEach, describe, expect, it } from 'vitest' import { getAdMediationEngine } from '../../../src/main/services/ads/AdMediationEngine' -import { EthicalAdsAdapter } from '../../../src/main/services/ads/EthicalAdsAdapter' -import { CarbonAdsAdapter } from '../../../src/main/services/ads/CarbonAdsAdapter' -import { PlaywireAdapter } from '../../../src/main/services/ads/PlaywireAdapter' -import { UnityAdsAdapter } from '../../../src/main/services/ads/UnityAdsAdapter' -import { AppLovinAdapter } from '../../../src/main/services/ads/AppLovinAdapter' -import { GoogleAdManagerAdapter } from '../../../src/main/services/ads/GoogleAdManagerAdapter' -import { InMobiAdapter } from '../../../src/main/services/ads/InMobiAdapter' -import { PubMaticAdapter } from '../../../src/main/services/ads/PubMaticAdapter' -import { MintegralAdapter } from '../../../src/main/services/ads/MintegralAdapter' import { DirectHouseSponsorAdapter } from '../../../src/main/services/ads/DirectHouseSponsorAdapter' +import { createUnavailableAdAdapters } from '../../../src/main/services/ads/UnavailableAdAdapter' import type { AdFormat, AdImpressionEvent } from '@d3ro/core/types' const FX = { @@ -33,16 +25,8 @@ const FX = { } as const const ADAPTER_CASES = [ - ['EthicalAds', new EthicalAdsAdapter()], - ['Carbon Ads', new CarbonAdsAdapter()], - ['Playwire', new PlaywireAdapter()], - ['Unity Ads', new UnityAdsAdapter()], - ['AppLovin', new AppLovinAdapter()], - ['Google Ad Manager', new GoogleAdManagerAdapter()], - ['InMobi', new InMobiAdapter()], - ['PubMatic', new PubMaticAdapter()], - ['Mintegral', new MintegralAdapter()], - ['Direct sponsor', new DirectHouseSponsorAdapter()], + ...createUnavailableAdAdapters().map((adapter) => [adapter.networkName, adapter] as const), + ['Direct sponsor', new DirectHouseSponsorAdapter()] as const, ] as const const FORMATS: AdFormat[] = ['banner', 'interstitial', 'rewarded_video', 'native'] diff --git a/apps/desktop/tests/unit/AdMediationEngine.test.ts b/apps/desktop/tests/unit/AdMediationEngine.test.ts index 876663a..1fe264e 100644 --- a/apps/desktop/tests/unit/AdMediationEngine.test.ts +++ b/apps/desktop/tests/unit/AdMediationEngine.test.ts @@ -3,28 +3,12 @@ import { Feature, type AdMediationConfig } from '@d3ro/core/types' import { getAdMediationEngine } from '../../src/main/services/ads/AdMediationEngine' import { getAdSettlementService } from '../../src/main/services/ads/AdSettlementService' import { getLicenseService } from '../../src/main/services/LicenseService' -import { EthicalAdsAdapter } from '../../src/main/services/ads/EthicalAdsAdapter' -import { CarbonAdsAdapter } from '../../src/main/services/ads/CarbonAdsAdapter' -import { PlaywireAdapter } from '../../src/main/services/ads/PlaywireAdapter' -import { UnityAdsAdapter } from '../../src/main/services/ads/UnityAdsAdapter' -import { AppLovinAdapter } from '../../src/main/services/ads/AppLovinAdapter' -import { GoogleAdManagerAdapter } from '../../src/main/services/ads/GoogleAdManagerAdapter' -import { InMobiAdapter } from '../../src/main/services/ads/InMobiAdapter' -import { PubMaticAdapter } from '../../src/main/services/ads/PubMaticAdapter' -import { MintegralAdapter } from '../../src/main/services/ads/MintegralAdapter' import { DirectHouseSponsorAdapter } from '../../src/main/services/ads/DirectHouseSponsorAdapter' +import { createUnavailableAdAdapters } from '../../src/main/services/ads/UnavailableAdAdapter' -const adapterCases = [ - ['EthicalAds', new EthicalAdsAdapter()], - ['Carbon Ads', new CarbonAdsAdapter()], - ['Playwire', new PlaywireAdapter()], - ['Unity Ads', new UnityAdsAdapter()], - ['AppLovin', new AppLovinAdapter()], - ['Google Ad Manager', new GoogleAdManagerAdapter()], - ['InMobi', new InMobiAdapter()], - ['PubMatic', new PubMaticAdapter()], - ['Mintegral', new MintegralAdapter()], -] as const +const adapterCases = createUnavailableAdAdapters().map( + (adapter) => [adapter.networkName, adapter] as const, +) describe('desktop ad provider boundaries', () => { it.each(adapterCases)('%s returns no bid until a real provider is integrated', async (_name, adapter) => { diff --git a/apps/desktop/tests/unit/renderer-popups-and-helpers.test.ts b/apps/desktop/tests/unit/renderer-popups-and-helpers.test.ts new file mode 100644 index 0000000..4021e57 --- /dev/null +++ b/apps/desktop/tests/unit/renderer-popups-and-helpers.test.ts @@ -0,0 +1,500 @@ +import fs from 'node:fs' +import path from 'node:path' +import vm from 'node:vm' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createFakeClock, createSeededRandom } from '@d3ro/core/ports' +import { toErrorMessage } from '../../src/renderer/utils/error-message' +import { formatElapsed } from '../../src/renderer/components/meeting/meeting-format' +import { + formatClockTime, + formatDayLabel, + formatDurationLong, + formatNumber, + formatRecordingTime, + formatRecordingTimeUnit, + getDateKey, +} from '../../src/renderer/utils/formatters' + +interface FakeClassList { + tokens: Set + add: (...cls: string[]) => void + remove: (...cls: string[]) => void + toggle: (cls: string, force?: boolean) => boolean + contains: (cls: string) => boolean +} + +class FakeElement { + id: string + tagName: string + children: FakeElement[] = [] + parentNode: FakeElement | null = null + attributes = new Map() + listeners = new Map void>>() + style: Record = {} + hidden = false + type = '' + scrollTop = 0 + offsetWidth = 0 + innerHtmlWrites: string[] = [] + private _innerHTML = '' + private _textContent = '' + readonly classList: FakeClassList + + constructor(tagName: string, id = '') { + this.tagName = tagName.toUpperCase() + this.id = id + const tokens = new Set() + this.classList = { + tokens, + add: (...cls: string[]) => { + for (const c of cls) tokens.add(c) + }, + remove: (...cls: string[]) => { + for (const c of cls) tokens.delete(c) + }, + toggle: (cls: string, force?: boolean) => { + const next = force ?? !tokens.has(cls) + if (next) tokens.add(cls) + else tokens.delete(cls) + return next + }, + contains: (cls: string) => tokens.has(cls), + } + } + + get className(): string { + return Array.from(this.classList.tokens).join(' ') + } + + set className(val: string) { + this.classList.tokens.clear() + for (const part of val.split(/\s+/).filter(Boolean)) { + this.classList.tokens.add(part) + } + } + + get firstChild(): FakeElement | null { + return this.children[0] ?? null + } + + get textContent(): string { + if (this.tagName === '#TEXT') return this._textContent + return this.children.map((c) => c.textContent).join('') + } + + set textContent(val: string) { + if (this.tagName === '#TEXT') { + this._textContent = val + this.children = [] + return + } + this._textContent = '' + if (val === '') { + this.children = [] + return + } + const textNode = new FakeElement('#TEXT') + textNode._textContent = val + this.children = [textNode] + } + + get innerHTML(): string { + return this._innerHTML + } + + set innerHTML(val: string) { + this.innerHtmlWrites.push(val) + this._innerHTML = val + if (val === '') this.children = [] + } + + appendChild(child: FakeElement): FakeElement { + child.parentNode = this + this.children.push(child) + return child + } + + insertBefore(child: FakeElement, refChild: FakeElement | null): FakeElement { + child.parentNode = this + const idx = refChild ? this.children.indexOf(refChild) : -1 + if (idx < 0) this.children.push(child) + else this.children.splice(idx, 0, child) + return child + } + + removeChild(child: FakeElement): FakeElement { + const idx = this.children.indexOf(child) + if (idx >= 0) { + this.children.splice(idx, 1) + child.parentNode = null + } + return child + } + + setAttribute(name: string, value: string): void { + this.attributes.set(name, value) + } + + getAttribute(name: string): string | null { + return this.attributes.get(name) ?? null + } + + removeAttribute(name: string): void { + this.attributes.delete(name) + } + + addEventListener(type: string, cb: (event?: unknown) => void): void { + const list = this.listeners.get(type) ?? [] + list.push(cb) + this.listeners.set(type, list) + } + + removeEventListener(type: string, cb: (event?: unknown) => void): void { + const list = this.listeners.get(type) + if (!list) return + const idx = list.indexOf(cb) + if (idx >= 0) list.splice(idx, 1) + } + + dispatch(type: string, event: unknown = {}): void { + for (const cb of this.listeners.get(type) ?? []) cb(event) + } + + scrollIntoView(): void {} + setPointerCapture(): void {} + getBoundingClientRect(): { width: number; height: number } { + return { width: 200, height: 80 } + } +} + +interface PopupSandbox { + elements: Map + emitIpc: (channel: string, data?: unknown) => void + sent: Array<{ channel: string; payload: unknown }> + unsubCalls: () => number + registeredCount: () => number + triggerDocument: (type: string) => void + triggerWindow: (type: string) => void + flushRaf: () => void + pendingRafCount: () => number +} + +function loadPopupSandbox(popupName: string, elementIds: readonly string[]): PopupSandbox { + const scriptPath = path.resolve( + __dirname, + '../../src/renderer/popups', + popupName, + 'script.js', + ) + const code = fs.readFileSync(scriptPath, 'utf8') + const elements = new Map() + for (const id of elementIds) { + elements.set(id, new FakeElement('div', id)) + } + + const ipcHandlers = new Map void>>() + const sent: Array<{ channel: string; payload: unknown }> = [] + let activeSubscriptions = 0 + let totalUnsubs = 0 + + const docListeners = new Map void>>() + const winListeners = new Map void>>() + let rafId = 0 + const rafQueue = new Map void>() + const fakeClock = createFakeClock(1_700_000_000_000) + const seededRandom = createSeededRandom(42) + + const fakeWindow = { + addEventListener(type: string, cb: () => void): void { + const list = winListeners.get(type) ?? [] + list.push(cb) + winListeners.set(type, list) + }, + removeEventListener(type: string, cb: () => void): void { + const list = winListeners.get(type) + if (!list) return + const idx = list.indexOf(cb) + if (idx >= 0) list.splice(idx, 1) + }, + popupAPI: { + send(channel: string, payload?: unknown): void { + sent.push({ channel, payload }) + }, + on(channel: string, cb: (data?: unknown) => void): () => void { + activeSubscriptions += 1 + const list = ipcHandlers.get(channel) ?? [] + list.push(cb) + ipcHandlers.set(channel, list) + let removed = false + return () => { + if (removed) return + removed = true + activeSubscriptions -= 1 + totalUnsubs += 1 + const current = ipcHandlers.get(channel) ?? [] + const idx = current.indexOf(cb) + if (idx >= 0) current.splice(idx, 1) + } + }, + }, + } + + const FakeDate = class extends Date { + constructor(value?: number | string | Date) { + super(value === undefined ? fakeClock.now() : (value as number)) + } + static now(): number { + return fakeClock.now() + } + } + + const fakeMath = Object.assign(Object.create(Math), { + random: () => seededRandom.next(), + }) + + const context: Record = { + window: fakeWindow, + document: { + getElementById: (id: string) => elements.get(id) ?? null, + querySelectorAll: () => [], + createElement: (tag: string) => new FakeElement(tag), + createTextNode: (text: string) => { + const node = new FakeElement('#text') + node.textContent = text + return node + }, + addEventListener(type: string, cb: () => void): void { + const list = docListeners.get(type) ?? [] + list.push(cb) + docListeners.set(type, list) + }, + removeEventListener(type: string, cb: () => void): void { + const list = docListeners.get(type) + if (!list) return + const idx = list.indexOf(cb) + if (idx >= 0) list.splice(idx, 1) + }, + }, + Date: FakeDate, + Math: fakeMath, + Number, + String, + Array, + setTimeout, + clearTimeout, + setInterval, + clearInterval, + requestAnimationFrame(cb: () => void): number { + rafId += 1 + rafQueue.set(rafId, cb) + return rafId + }, + cancelAnimationFrame(id: number): void { + rafQueue.delete(id) + }, + } + + vm.runInNewContext(code, context, { filename: scriptPath }) + + return { + elements, + sent, + unsubCalls: () => totalUnsubs, + registeredCount: () => activeSubscriptions, + emitIpc(channel: string, data?: unknown): void { + for (const cb of [...(ipcHandlers.get(channel) ?? [])]) { + cb(data) + } + }, + triggerDocument(type: string): void { + for (const cb of docListeners.get(type) ?? []) cb() + }, + triggerWindow(type: string): void { + for (const cb of winListeners.get(type) ?? []) cb() + }, + flushRaf(): void { + const entries = Array.from(rafQueue.entries()) + rafQueue.clear() + for (const [, cb] of entries) cb() + }, + pendingRafCount: () => rafQueue.size, + } +} + +describe('렌더러 포맷터 및 팝업 스크립트 방어 동작', () => { + afterEach(() => { + vi.useRealTimers() + }) + + it('formatters와formatElapsed_비유한수와음수입력시_NaN이나음수문자열을반환하지않는다', () => { + expect(formatElapsed(Number.NaN)).toBe('00:00') + expect(formatElapsed(-500)).toBe('00:00') + expect(formatElapsed(3_665_000)).toBe('1:01:05') + + expect(formatDurationLong(Number.NaN, 'en')).toBe('0 min') + expect(formatNumber(Number.NaN)).toBe('0') + expect(formatRecordingTime(Number.NaN)).toBe('0') + expect(formatRecordingTimeUnit(Number.NaN)).toBe('MIN') + expect(getDateKey(Number.NaN)).toBe('') + expect(formatClockTime(Number.NaN, 'en')).toBe('') + expect(formatDayLabel(Number.NaN, 'en')).toBe('') + + expect(toErrorMessage(new Error('network down'))).toBe('network down') + expect(toErrorMessage('plain failure')).toBe('plain failure') + }) + + it('commandPopup_innerHTML을사용하지않고null페이로드및beforeunload해제를안전하게처리한다', () => { + const sandbox = loadPopupSandbox('command-popup', ['container', 'items']) + const items = sandbox.elements.get('items')! + + sandbox.emitIpc('command:showItems', { + commands: [{ id: '1', name: '', description: 'desc' }], + activeId: '', + }) + sandbox.emitIpc('command:showItems', null) + sandbox.emitIpc('command:keyEvent', null) + + expect(items.innerHtmlWrites).toEqual([]) + expect(items.children[1]?.textContent).toContain('') + + sandbox.triggerWindow('beforeunload') + expect(sandbox.registeredCount()).toBe(0) + expect(sandbox.unsubCalls()).toBe(4) + }) + + it('historyPopup_비유한타임스탬프와null페이로드에서도_NaN을렌더링하지않고언로드시구독을해제한다', () => { + const sandbox = loadPopupSandbox('history-popup', ['container', 'items']) + const items = sandbox.elements.get('items')! + + sandbox.emitIpc('history:showItems', { + entries: [{ id: '1', originalText: '원문', polishedText: '', createdAt: Number.NaN }], + }) + sandbox.emitIpc('history:showItems', null) + sandbox.emitIpc('history:keyEvent', null) + + expect(items.innerHtmlWrites).toEqual([]) + expect(items.children[0]?.textContent.includes('NaN')).toBe(false) + + sandbox.triggerWindow('beforeunload') + expect(sandbox.registeredCount()).toBe(0) + }) + + it('resultPopup_prepare직후hide수신시_측정IPC를보내지않고숨겨진상태mouseleave로타이머가돌지않는다', () => { + vi.useFakeTimers({ now: 1_700_000_000_000 }) + const sandbox = loadPopupSandbox('result-popup', [ + 'container', + 'result-text', + 'copy-btn', + 'copy-icon', + 'check-icon', + 'copy-label', + 'close-btn', + ]) + const container = sandbox.elements.get('container')! + + sandbox.emitIpc('result:prepare', { text: '복사할 문장' }) + sandbox.emitIpc('result:hide') + sandbox.flushRaf() + sandbox.flushRaf() + + expect(sandbox.sent.filter((item) => item.channel === 'result:measured')).toEqual([]) + + container.dispatch('mouseleave') + vi.advanceTimersByTime(5000) + expect(sandbox.sent.filter((item) => item.channel === 'window:hideResultPopup')).toEqual([]) + + sandbox.triggerWindow('beforeunload') + expect(sandbox.registeredCount()).toBe(0) + }) + + it('captionOverlay_hide이후지연페이드타이머가새세션자막을지우지않고언로드시리소스를정리한다', () => { + vi.useFakeTimers({ now: 1_700_000_000_000 }) + const sandbox = loadPopupSandbox('caption-overlay', [ + 'lines', + 'container', + 'root', + 'handle', + 'handleHint', + ]) + const lines = sandbox.elements.get('lines')! + + sandbox.emitIpc('caption:config', { autoClearMs: 1000 }) + sandbox.emitIpc('caption:segment', { id: 's1', text: '첫 문장', timestamp: 1, isFinal: true }) + // 1000ms 뒤 fadeAndRemoveLine(500ms 타이머 시작) 진입 + vi.advanceTimersByTime(1000) + // fade-out 도중 hide 후 곧바로 새 자막이 들어와도 이전 fade 타이머는 취소되어야 한다 + sandbox.emitIpc('caption:hide') + expect(lines.children).toHaveLength(0) + + sandbox.emitIpc('caption:segment', { id: 's2', text: '새 세션 문장', timestamp: 2, isFinal: true }) + sandbox.emitIpc('caption:stateChanged', null) + vi.advanceTimersByTime(600) + expect(lines.children).toHaveLength(1) + expect(lines.children[0]?.textContent).toBe('새 세션 문장') + + sandbox.triggerWindow('beforeunload') + expect(vi.getTimerCount()).toBe(0) + expect(sandbox.registeredCount()).toBe(0) + }) + + it('suggestionOverlay_범위초과activeIndex에서도_유효페이지후보를표시하고언로드시정리한다', () => { + vi.useFakeTimers({ now: 1_700_000_000_000 }) + const sandbox = loadPopupSandbox('suggestion-overlay', [ + 'candidates', + 'provenance', + 'progress', + 'keyHints', + 'footer', + 'status', + 'statusText', + 'panel', + 'close', + ]) + const candidates = sandbox.elements.get('candidates')! + + sandbox.emitIpc('suggestionPopup:show', { + candidates: [{ text: '첫째' }, { text: '둘째' }], + activeIndex: 99, + generating: true, + }) + + expect(candidates.children).toHaveLength(2) + expect(candidates.children[1]?.classList.contains('active')).toBe(true) + + sandbox.triggerWindow('beforeunload') + expect(vi.getTimerCount()).toBe(0) + expect(sandbox.registeredCount()).toBe(0) + }) + + it('recordingTip_음수레벨클램프와언로드시인터벌및IPC해제를수행한다', () => { + vi.useFakeTimers({ now: 1_700_000_000_000 }) + const sandbox = loadPopupSandbox('recording-tip', [ + 'container', + 'wave-bars', + 'duration-text', + 'status-text', + 'cancel-hint', + 'progress', + 'partial-text', + 'done-view', + 'done-text', + 'error-view', + 'error-text', + 'head-row', + ]) + + sandbox.triggerDocument('DOMContentLoaded') + sandbox.emitIpc('voice:audioLevel', { level: -2 }) + sandbox.emitIpc('window:tipStateChanged', { state: 'recording' }) + vi.advanceTimersByTime(1000) + + const barHeights = sandbox.elements + .get('wave-bars')! + .children.map((bar) => Number.parseInt(bar.style.height, 10)) + expect(barHeights.every((h) => Number.isFinite(h) && h >= 2 && h <= 22)).toBe(true) + + sandbox.triggerWindow('beforeunload') + expect(vi.getTimerCount()).toBe(0) + expect(sandbox.registeredCount()).toBe(0) + }) +}) diff --git a/apps/desktop/tests/unit/settings-and-suggestion-helpers.test.ts b/apps/desktop/tests/unit/settings-and-suggestion-helpers.test.ts new file mode 100644 index 0000000..f4c2c67 --- /dev/null +++ b/apps/desktop/tests/unit/settings-and-suggestion-helpers.test.ts @@ -0,0 +1,186 @@ +import { describe, expect, it } from 'vitest' +import { + FALLBACK_OLLAMA_MODELS, + RECOMMENDED_OLLAMA_MODEL, + clampMicMeterPercent, + formatModelSizeGb, + listUninstalledFallbackModels, + resolveActiveOllamaModel, + resolveOllamaStatusSummary +} from '../../src/renderer/components/settings/settings-model-helpers' +import { + applyCorrectionToContext, + buildDecisionInputSignature, + isDuplicateCandidateText, + normalizeSuggestionPolicyConfig, + rerankFilledCandidates, + resolveTerminalTypingContext, + sameCandidateText, + toSuggestionCorrectionFromPlan +} from '../../src/main/services/suggestion/suggestion-policy-helpers' +import type { TypingContext } from '../../src/main/services/InputTelemetryService' + +function createTypingContext(overrides: Partial = {}): TypingContext { + return { + available: true, + isEditable: true, + isPassword: false, + isComposing: false, + hasSelection: false, + editedSinceFocus: true, + typedRecently: true, + prefix: '회의 안건을 정리했습니다', + documentBefore: '회의 안건을 정리했습니다', + fullText: '회의 안건을 정리했습니다', + appName: 'Notion', + windowTitle: '주간 회의록', + windowHandle: 101, + anchor: null, + anchorKind: null, + idleMs: 700, + ...overrides + } +} + +describe('settings-model-helpers', () => { + it('활성모델결정_설정없을때_권장모델을반환한다', () => { + expect(resolveActiveOllamaModel(undefined)).toBe(RECOMMENDED_OLLAMA_MODEL) + expect(resolveActiveOllamaModel('qwen2.5:7b')).toBe('qwen2.5:7b') + }) + + it('미설치기본모델목록_설치된모델제외_나머지후보만반환한다', () => { + expect(listUninstalledFallbackModels([{ name: 'llama3.2:3b' }])).toEqual(['qwen2.5:3b']) + expect(listUninstalledFallbackModels([])).toEqual([...FALLBACK_OLLAMA_MODELS]) + }) + + it('모델크기표시_바이트입력시_소수첫째자리기가바이트를계산한다', () => { + const twoPointFiveGb = Math.round(2.5 * 1024 * 1024 * 1024) + expect(formatModelSizeGb(twoPointFiveGb)).toBe(2.5) + expect(formatModelSizeGb(0)).toBe(0) + }) + + it('마이크레벨백분율_범위초과및음수_0과100사이정수로고정한다', () => { + expect(clampMicMeterPercent(-0.3)).toBe(0) + expect(clampMicMeterPercent(0.456)).toBe(46) + expect(clampMicMeterPercent(1.8)).toBe(100) + }) + + it('Ollama상태요약_연결상태별_적절한번역키와인자를반환한다', () => { + expect(resolveOllamaStatusSummary(null, 0)).toEqual({ kind: 'checking' }) + expect( + resolveOllamaStatusSummary({ connectionState: 'disconnected', models: [] }, 0) + ).toEqual({ kind: 'offline' }) + expect( + resolveOllamaStatusSummary({ connectionState: 'connected', serverVersion: '0.6.2', models: [] }, 3) + ).toEqual({ kind: 'connectedVersion', version: '0.6.2', count: 3 }) + expect( + resolveOllamaStatusSummary({ connectionState: 'connected', models: [] }, 2) + ).toEqual({ kind: 'connected', count: 2 }) + }) +}) + +describe('suggestion-policy-helpers', () => { + it('오타교정문맥적용_접두끝일치시_prefix와documentBefore끝만교체한다', () => { + const context = createTypingContext({ + prefix: '오늘 회으에서', + documentBefore: '제목\n오늘 회으에서' + }) + const updated = applyCorrectionToContext(context, { + from: '회으에서', + to: '회의에서', + edits: [{ start: 0, end: 2, to: '회의' }] + }) + + expect(updated.prefix).toBe('오늘 회의에서') + expect(updated.documentBefore).toBe('제목\n오늘 회의에서') + }) + + it('후보동일성및중복검사_공백문장부호정규화및접두확장_중복으로판정한다', () => { + expect(sameCandidateText('다음 주에 공유드릴게요!', '다음 주에 공유드릴게요.')).toBe(true) + expect( + isDuplicateCandidateText('다음 주에 공유드릴게요 그리고 검토 부탁드립니다', [ + { text: '다음 주에 공유드릴게요', rank: 0 } + ]) + ).toBe(true) + expect( + isDuplicateCandidateText('내일 오전에 다시 확인하겠습니다', [ + { text: '다음 주에 공유드릴게요', rank: 0 } + ]) + ).toBe(false) + }) + + it('채우기후보재정렬_개인화점수높은신규후보_개인후보유지하고모델후보앞으로배치한다', () => { + const candidates = [ + { text: '먼저', rank: 0, source: 'personal' as const }, + { text: '일반적인 안내 문장입니다.', rank: 1 }, + { text: '주간 배포 체크리스트 공유드립니다.', rank: 2 } + ] + const reranked = rerankFilledCandidates(candidates, '주간 배포 체크리스트 공유드립니다.', { + prefix: '이번 스프린트 마무리하며', + continuationHints: ['주간 배포 체크리스트 공유드립니다.'], + followUpHints: ['주간 배포 체크리스트 공유드립니다.'], + relatedHints: [], + phraseHints: ['주간 배포 체크리스트'] + }) + + expect(reranked[0]).toEqual({ text: '먼저', rank: 0, source: 'personal' }) + expect(reranked[1]).toEqual({ text: '주간 배포 체크리스트 공유드립니다.', rank: 1 }) + expect(reranked[2]).toEqual({ text: '일반적인 안내 문장입니다.', rank: 2 }) + }) + + it('정책설정정규화_최소지연시간및분당최대요청상한_강제적용한다', () => { + const normalized = normalizeSuggestionPolicyConfig({ + triggerDelayMs: 50, + minPrefixChars: 0, + maxRequestsPerMinute: 999, + dailyBudget: 0, + excludedApps: ['1Password.exe'] + }) + + expect(normalized.triggerDelayMs).toBeGreaterThanOrEqual(200) + expect(normalized.maxRequestsPerMinute).toBe(30) + expect(normalized.excludedApps).toEqual(['1Password.exe']) + }) + + it('교정계획변환_접두끝불일치시_제외하고일치시상대오프셋으로변환한다', () => { + const mismatched = toSuggestionCorrectionFromPlan('다른 문장', { + originalText: '회으', + insertText: '회의', + corrections: [{ start: 10, end: 12, to: '회의' }] + }) + expect(mismatched).toBe(undefined) + + const matched = toSuggestionCorrectionFromPlan('오늘 회으 진행', { + originalText: '회으 진행', + insertText: '회의 진행', + corrections: [{ start: 3, end: 5, to: '회의' }] + }) + expect(matched).toEqual({ + from: '회으 진행', + to: '회의 진행', + edits: [{ start: 0, end: 2, to: '회의' }] + }) + }) + + it('판단입력서명및터미널문맥_회색추천문구와끝타이핑_정확히구분한다', () => { + const context = createTypingContext({ anchor: { x: 10, y: 20, width: 4, height: 18 } }) + expect( + buildDecisionInputSignature(context, { modelAvailable: true, enabled: true }) + ).toBe('true|true|false|false|A|true|true|true|true') + + const emptyStep = resolveTerminalTypingContext( + createTypingContext({ appName: 'WindowsTerminal', fullText: 'PS D:\\repo> ' }), + { lastPrompt: null, promptTyped: false } + ) + expect(emptyStep.context.caretReliable).toBe(true) + + const ghostSuggestionStep = resolveTerminalTypingContext( + createTypingContext({ + appName: 'WindowsTerminal', + fullText: 'PS D:\\repo> run the entire verification pipeline now' + }), + emptyStep.nextState + ) + expect(ghostSuggestionStep.context.caretReliable).toBe(false) + }) +}) diff --git a/apps/desktop/tsconfig.node.json b/apps/desktop/tsconfig.node.json index 74c8647..d4a1b9e 100644 --- a/apps/desktop/tsconfig.node.json +++ b/apps/desktop/tsconfig.node.json @@ -14,7 +14,8 @@ "@d3ro/core/*": ["../../packages/core/src/*"], "@d3ro/ui": ["../../packages/ui/src/index.ts"], "@d3ro/ui/*": ["../../packages/ui/src/*"], - "@d3ro/i18n": ["../../packages/i18n/src/index.tsx"] + "@d3ro/i18n": ["../../packages/i18n/src/index.tsx"], + "@d3ro/i18n/main": ["../../packages/i18n/src/main.ts"] }, "strict": true, "noImplicitAny": true, diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.ts index 488d99f..3b57f7c 100644 --- a/apps/desktop/vitest.config.ts +++ b/apps/desktop/vitest.config.ts @@ -28,10 +28,11 @@ export default defineConfig(({ mode }) => ({ } }, resolve: { - alias: { - '@d3ro/core': resolve(__dirname, '../../packages/core/src'), - '@d3ro/ui': resolve(__dirname, '../../packages/ui/src'), - '@d3ro/i18n': resolve(__dirname, '../../packages/i18n/src/index.tsx') - } + alias: [ + { find: /^@d3ro\/i18n\/main$/, replacement: resolve(__dirname, '../../packages/i18n/src/main.ts') }, + { find: /^@d3ro\/i18n$/, replacement: resolve(__dirname, '../../packages/i18n/src/index.tsx') }, + { find: /^@d3ro\/core(\/.*)?$/, replacement: `${resolve(__dirname, '../../packages/core/src')}$1` }, + { find: /^@d3ro\/ui(\/.*)?$/, replacement: `${resolve(__dirname, '../../packages/ui/src')}$1` }, + ] } })) diff --git a/apps/mobile-rn/App.tsx b/apps/mobile-rn/App.tsx index 5abf307..4686041 100644 --- a/apps/mobile-rn/App.tsx +++ b/apps/mobile-rn/App.tsx @@ -364,7 +364,7 @@ function RootNavigator(): React.ReactElement { }} > {isRecoveringPassword ? ( - + UpdatePasswordScreen} /> ) : needsOnboarding ? ( <> @@ -377,52 +377,52 @@ function RootNavigator(): React.ReactElement { /> )} - - + InviteAcceptScreen} /> + LoginScreen} /> ) : user === null ? ( <> - - - + SignUpScreen} /> + ForgotPasswordScreen} /> + InviteAcceptScreen} /> ) : ( <> - - - - - - - - - - - - - + AccountScreen} /> + HistoryDetailScreen} /> + DevicesScreen} /> + DictionaryScreen} /> + CommandsScreen} /> + MeetingDetailScreen} /> + KnowledgeScreen} /> + ActionsScreen} /> + TeamsScreen} /> + TeamDetailScreen} /> + InviteAcceptScreen} /> + NotificationsScreen} /> + DataPortabilityScreen} /> {({ route }) => ( )} - - - - - - - + MemosScreen} /> + AdminScreen} /> + AdminUserDetailScreen} /> + TalkScreen} /> + SettingsScreen} /> + UnifiedSearchScreen} /> + UpdatePasswordScreen} /> OnboardingScreen} options={{ presentation: 'fullScreenModal' }} /> ProPaywallScreen} options={{ presentation: 'modal' }} /> diff --git a/apps/mobile-rn/__tests__/durable-queue-early-discard.test.ts b/apps/mobile-rn/__tests__/durable-queue-early-discard.test.ts new file mode 100644 index 0000000..975f0e6 --- /dev/null +++ b/apps/mobile-rn/__tests__/durable-queue-early-discard.test.ts @@ -0,0 +1,137 @@ +import AsyncStorage from '@react-native-async-storage/async-storage' +import { FileSystem } from 'react-native-file-access' +import type { + AudioPipelineResult, + LocalAudioInput, +} from '../src/features/import/audio-import-types' + +const mockProcessAudioInput = jest.fn, [LocalAudioInput, unknown]>() +const mockFailMeetingRecording = jest.fn(async () => undefined) +const mockMarkMeetingProcessingFailure = jest.fn(async () => undefined) +const mockQueueMeetingRecording = jest.fn(async () => undefined) + +jest.mock('../src/features/import/audio-transcription-service', () => ({ + processAudioInput: (input: LocalAudioInput, options: unknown) => + mockProcessAudioInput(input, options), +})) +jest.mock('../src/features/meetings/meetings-service', () => ({ + failMeetingRecording: () => mockFailMeetingRecording(), + markMeetingProcessingFailure: () => mockMarkMeetingProcessingFailure(), + queueMeetingRecording: () => mockQueueMeetingRecording(), +})) + +import { + clearQueuedAudioForUser, + discardQueuedAudio, + durableQueueTestContract, + processQueuedAudioNow, + type DurableQueueItem, +} from '../src/features/recording/durable-processing-queue' + +const FIXED_NOW_MS = 1_700_000_000_000 +const USER_A = '11111111-1111-4111-8111-111111111111' +const MEETING_ID = '22222222-2222-4222-8222-222222222222' + +const mockFileSystem = FileSystem as typeof FileSystem & { filesystem: Map } + +function makeItem(suffix: string): DurableQueueItem { + const path = `${durableQueueTestContract.queueDirectory}/queued-${suffix}.wav` + return { + schemaVersion: 1, + id: suffix, + userId: USER_A, + meetingId: MEETING_ID, + path, + uri: `file://${path}`, + fileName: `${suffix}.wav`, + mimeType: 'audio/wav', + sizeBytes: 5, + durationMs: 1_000, + source: 'recording', + languageCode: 'ko', + status: 'pending', + phase: null, + attempts: 0, + uploadedBytes: 0, + nextAttemptAtMs: FIXED_NOW_MS, + lastErrorCode: null, + lastErrorMessage: null, + createdAtMs: FIXED_NOW_MS, + updatedAtMs: FIXED_NOW_MS, + } +} + +describe('durable processing queue early discard race', () => { + beforeEach(async () => { + jest.useFakeTimers({ now: FIXED_NOW_MS }) + await AsyncStorage.clear() + mockFileSystem.filesystem.clear() + mockProcessAudioInput.mockReset() + mockFailMeetingRecording.mockClear() + mockMarkMeetingProcessingFailure.mockClear() + mockQueueMeetingRecording.mockClear() + }) + + afterEach(async () => { + jest.restoreAllMocks() + await clearQueuedAudioForUser(USER_A).catch(() => undefined) + jest.useRealTimers() + }) + + test('discardQueuedAudio_파일존재확인중폐기호출시_전사나실패기록없이안전하게중단', async () => { + const first = makeItem('aaa111') + mockFileSystem.filesystem.set(first.path, 'audio-bytes') + await AsyncStorage.setItem(durableQueueTestContract.storageKey, JSON.stringify([first])) + + let resolveExists: (present: boolean) => void = () => undefined + const existsGate = new Promise((resolve) => { + resolveExists = resolve + }) + let gateUsed = false + jest.spyOn(FileSystem, 'exists').mockImplementation(async (path) => { + if (path === first.path && !gateUsed) { + gateUsed = true + return existsGate + } + return mockFileSystem.filesystem.has(path) + }) + + const runPromise = processQueuedAudioNow(USER_A, first.id).catch((error: unknown) => error) + for (let index = 0; index < 5; index += 1) { + await jest.advanceTimersByTimeAsync(0) + } + + await discardQueuedAudio(USER_A, first.id) + resolveExists(true) + + const outcome = await runPromise + expect(outcome).toMatchObject({ code: 'cancelled' }) + expect(mockProcessAudioInput).not.toHaveBeenCalled() + expect(mockFailMeetingRecording).not.toHaveBeenCalled() + expect(mockMarkMeetingProcessingFailure).not.toHaveBeenCalled() + + const persisted = durableQueueTestContract.parseQueue( + await AsyncStorage.getItem(durableQueueTestContract.storageKey), + ) + expect(persisted).toEqual([]) + + const replacement = makeItem('aaa111') + mockFileSystem.filesystem.set(replacement.path, 'audio-bytes-2') + await AsyncStorage.setItem(durableQueueTestContract.storageKey, JSON.stringify([replacement])) + mockProcessAudioInput.mockResolvedValueOnce({ + historyId: null, + audioFileId: 'audio-2', + meetingId: MEETING_ID, + processingJobId: null, + transcript: 'ok', + provider: 'test', + language: 'ko', + durationSeconds: 1, + deduplicated: false, + }) + + const replayResult = await processQueuedAudioNow(USER_A, replacement.id) + expect(replayResult.transcript).toBe('ok') + expect(mockProcessAudioInput).toHaveBeenCalledTimes(1) + }) +}) diff --git a/apps/mobile-rn/__tests__/free-tier-banner-resize.test.tsx b/apps/mobile-rn/__tests__/free-tier-banner-resize.test.tsx new file mode 100644 index 0000000..fc7ed28 --- /dev/null +++ b/apps/mobile-rn/__tests__/free-tier-banner-resize.test.tsx @@ -0,0 +1,90 @@ +import React from 'react' +import { StyleSheet } from 'react-native' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' + +const mockUseResponsiveLayout = jest.fn(() => ({ bannerSlotMinHeight: 90 })) +const mockUseMobileAds = jest.fn(() => ({ + eligible: true, + bannerUnitId: 'ca-app-pub-3940256099942544/6300978111' as string | null, + status: 'ready' as const, +})) + +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => ({ t: (key: string) => key }), +})) + +jest.mock('@d3ro/ui-native', () => { + const actual = jest.requireActual('@d3ro/ui-native') as typeof import('@d3ro/ui-native') + return { + ...actual, + useResponsiveLayout: () => mockUseResponsiveLayout(), + } +}) + +jest.mock('../src/lib/preferences-context', () => { + const { d3roNativeDarkPalette } = jest.requireActual('@d3ro/ui-native') as typeof import('@d3ro/ui-native') + return { + useMobilePreferences: () => ({ palette: d3roNativeDarkPalette }), + } +}) + +jest.mock('../src/lib/mobile-ads-context', () => ({ + useMobileAds: () => mockUseMobileAds(), +})) + +import FreeTierBanner from '../src/components/FreeTierBanner' + +describe('FreeTierBanner responsive height reset', () => { + let renderer: ReactTestRenderer | null = null + + beforeEach(() => { + mockUseResponsiveLayout.mockReturnValue({ bannerSlotMinHeight: 90 }) + mockUseMobileAds.mockReturnValue({ + eligible: true, + bannerUnitId: 'ca-app-pub-3940256099942544/6300978111', + status: 'ready', + }) + }) + + afterEach(() => { + if (renderer !== null) { + act(() => renderer!.unmount()) + renderer = null + } + }) + + test('FreeTierBanner_태블릿에서폰크기로축소시_고착된measuredHeight초기화', async () => { + await act(async () => { + renderer = create() + }) + + const slot = () => renderer!.root.findByProps({ testID: 'free-tier-ad-slot' }) + expect(StyleSheet.flatten(slot().props.style).minHeight).toBe(90) + + await act(async () => { + slot().props.onLayout({ nativeEvent: { layout: { height: 96 } } }) + }) + expect(StyleSheet.flatten(slot().props.style).minHeight).toBe(96) + + mockUseResponsiveLayout.mockReturnValue({ bannerSlotMinHeight: 50 }) + await act(async () => { + renderer!.update() + }) + expect(StyleSheet.flatten(slot().props.style).minHeight).toBe(50) + + await act(async () => { + slot().props.onLayout({ nativeEvent: { layout: { height: 72 } } }) + }) + expect(StyleSheet.flatten(slot().props.style).minHeight).toBe(72) + + mockUseMobileAds.mockReturnValue({ + eligible: true, + bannerUnitId: 'ca-app-pub-3940256099942544/9999999999', + status: 'ready', + }) + await act(async () => { + renderer!.update() + }) + expect(StyleSheet.flatten(slot().props.style).minHeight).toBe(50) + }) +}) diff --git a/apps/mobile-rn/__tests__/history-detail-unmount-regression.test.tsx b/apps/mobile-rn/__tests__/history-detail-unmount-regression.test.tsx new file mode 100644 index 0000000..0460503 --- /dev/null +++ b/apps/mobile-rn/__tests__/history-detail-unmount-regression.test.tsx @@ -0,0 +1,184 @@ +import React from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import type { HistoryDetail } from '../src/features/history/history-service' + +const USER_ID = '11111111-1111-4111-8111-111111111111' +const HISTORY_ID = '22222222-2222-4222-8222-222222222222' +const AUDIO_ID = '33333333-3333-4333-8333-333333333333' + +const mockStartPlayer = jest.fn(async () => 'started') +const mockStopPlayer = jest.fn(async () => 'stopped') +const mockPausePlayer = jest.fn(async () => 'paused') +const mockResumePlayer = jest.fn(async () => 'resumed') +const mockGetHistoryDetail = jest.fn, [string, string]>() +const mockCreateAudioPlaybackUrl = jest.fn, [string, unknown]>() +const mockGoBack = jest.fn() + +const mockT = (key: string): string => key +const mockFormatDate = (): string => '2026-11-14' +const mockAuthValue = { user: { id: USER_ID } } +const { d3roNativeDarkPalette } = jest.requireActual('@d3ro/ui-native') as typeof import('@d3ro/ui-native') +const mockPreferencesValue = { palette: d3roNativeDarkPalette } + +jest.mock('react-native-safe-area-context', () => ({ + useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }), +})) +jest.mock('react-native-nitro-sound', () => ({ + useSoundWithStates: () => ({ + state: { + isPlaying: false, + playback: { position: 0, duration: 1_000 }, + }, + startPlayer: () => mockStartPlayer(), + stopPlayer: () => mockStopPlayer(), + pausePlayer: () => mockPausePlayer(), + resumePlayer: () => mockResumePlayer(), + }), +})) +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => ({ + t: mockT, + formatDate: mockFormatDate, + }), +})) +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => mockAuthValue, +})) +jest.mock('../src/lib/preferences-context', () => ({ + useMobilePreferences: () => mockPreferencesValue, +})) +jest.mock('../src/features/history/history-cache', () => ({ + loadHistoryCache: jest.fn(async () => null), +})) +jest.mock('../src/features/history/history-service', () => { + class MockHistoryServiceError extends Error { + code: string + + constructor(code: string, message: string) { + super(message) + this.code = code + } + } + return { + HistoryServiceError: MockHistoryServiceError, + getHistoryDetail: (userId: string, historyId: string) => mockGetHistoryDetail(userId, historyId), + createAudioPlaybackUrl: (userId: string, audioFile: unknown) => + mockCreateAudioPlaybackUrl(userId, audioFile), + updateHistoryRevisionSafe: jest.fn(), + deleteHistoryRevisionSafe: jest.fn(), + } +}) + +import HistoryDetailScreen from '../src/screens/HistoryDetailScreen' + +const SAMPLE_DETAIL: HistoryDetail = { + entry: { + id: HISTORY_ID, + user_id: USER_ID, + title: 'Sample Memo', + original_text: 'Original transcript', + polished_text: 'Polished transcript', + focused_app: null, + focused_app_name: null, + focused_app_window_title: null, + mode: 'dictation', + status: 'completed', + error_code: null, + audio_storage_key: 'audio/sample.wav', + duration: 12, + detected_language: 'ko', + mic_device: null, + word_count: 2, + stt_model: 'whisper', + llm_model: null, + stt_latency_ms: null, + llm_latency_ms: null, + app_version: '1.16.5', + summary_text: null, + is_favorite: false, + revision: 1, + created_at: '2026-11-14T00:00:00.000Z', + updated_at: '2026-11-14T00:00:00.000Z', + }, + audioFiles: [ + { + id: AUDIO_ID, + user_id: USER_ID, + history_id: HISTORY_ID, + meeting_id: null, + storage_bucket: 'audio-files', + storage_key: 'audio/sample.wav', + original_name: 'sample.wav', + mime_type: 'audio/wav', + size_bytes: 2048, + duration_ms: 12_000, + checksum_sha256: 'abc', + upload_status: 'uploaded', + retention_until: null, + created_at: '2026-11-14T00:00:00.000Z', + updated_at: '2026-11-14T00:00:00.000Z', + }, + ], + jobs: [], +} + +describe('HistoryDetailScreen unmount audio & async cleanup', () => { + beforeEach(() => { + mockStartPlayer.mockClear() + mockStopPlayer.mockClear() + mockPausePlayer.mockClear() + mockResumePlayer.mockClear() + mockGetHistoryDetail.mockReset().mockResolvedValue(SAMPLE_DETAIL) + mockCreateAudioPlaybackUrl.mockReset() + mockGoBack.mockClear() + }) + + test('HistoryDetailScreen_언마운트시_플레이어를중지하고진행중URL응답후재생을시작하지않음', async () => { + let resolveSignedUrl: (url: string) => void = () => undefined + mockCreateAudioPlaybackUrl.mockImplementation( + () => new Promise((resolve) => { + resolveSignedUrl = resolve + }), + ) + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create( + , + ) + await Promise.resolve() + await Promise.resolve() + }) + + const audioRow = renderer.root.findByProps({ testID: `history-audio-${AUDIO_ID}` }) + const playButton = audioRow.findAll( + (node) => typeof node.props.onPress === 'function' + && node.props.accessibilityLabel === 'mobile.hist.audioPlay', + )[0] + + await act(async () => { + playButton.props.onPress() + await Promise.resolve() + }) + + expect(mockCreateAudioPlaybackUrl).toHaveBeenCalledTimes(1) + + act(() => { + renderer.unmount() + }) + expect(mockStopPlayer).toHaveBeenCalledTimes(1) + + await act(async () => { + resolveSignedUrl('https://storage.example/signed.wav') + await Promise.resolve() + }) + expect(mockStartPlayer).not.toHaveBeenCalled() + }) +}) diff --git a/apps/mobile-rn/__tests__/meeting-detail-speakers.test.tsx b/apps/mobile-rn/__tests__/meeting-detail-speakers.test.tsx new file mode 100644 index 0000000..a050209 --- /dev/null +++ b/apps/mobile-rn/__tests__/meeting-detail-speakers.test.tsx @@ -0,0 +1,155 @@ +import React from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' + +const mockGetMeetingDetail = jest.fn() +const mockLoadTemplateLibrary = jest.fn() + +jest.mock('@react-navigation/native', () => { + const ReactValue = require('react') as typeof React + return { + useFocusEffect: (callback: () => void | (() => void)) => { + ReactValue.useEffect(callback, []) + }, + } +}) +jest.mock('react-native-safe-area-context', () => ({ + useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }), +})) +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => ({ + t: (key: string) => key, + formatDate: () => '2026-11-13', + }), +})) +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => ({ + user: { id: '11111111-1111-4111-8111-111111111111' }, + session: { access_token: 'tok' }, + loading: false, + }), +})) +jest.mock('../src/lib/preferences-context', () => { + const { getMobileThemePalette } = require('../src/theme/mobile-theme') as typeof import('../src/theme/mobile-theme') + return { + useMobilePreferences: () => ({ + palette: getMobileThemePalette('dark'), + }), + } +}) +jest.mock('../src/components/ContentReportSheet', () => ({ + __esModule: true, + default: () => null, +})) +jest.mock('../src/features/templates', () => ({ + generateMeetingDocumentOnce: jest.fn(), + loadTemplateLibrary: (...args: unknown[]) => mockLoadTemplateLibrary(...args), + TemplateServiceError: class TemplateServiceError extends Error {}, +})) +jest.mock('../src/features/meetings/meetings-service', () => { + const actual = jest.requireActual('../src/features/meetings/meetings-service') as Record + return { + ...actual, + getMeetingDetail: (...args: unknown[]) => mockGetMeetingDetail(...args), + subscribeToMeetingDetail: () => ({ + unsubscribe: async () => undefined, + }), + } +}) + +import MeetingDetailScreen from '../src/screens/MeetingDetailScreen' + +describe('모바일 회의 상세 화자 배지 및 필터링 (GAP-MTG-02)', () => { + beforeEach(() => { + mockLoadTemplateLibrary.mockResolvedValue({ + templates: [], + selections: {}, + }) + mockGetMeetingDetail.mockResolvedValue({ + meeting: { + id: '22222222-2222-4222-8222-222222222222', + user_id: '11111111-1111-4111-8111-111111111111', + team_id: null, + title: '화자 구분 회의', + status: 'completed', + started_at: '2026-11-13T01:00:00.000Z', + ended_at: '2026-11-13T01:10:00.000Z', + duration_ms: 600_000, + raw_transcript: null, + edited_transcript: null, + minutes_markdown: null, + minutes_json: null, + stt_model: 'whisper', + llm_model: null, + stt_latency_ms: null, + llm_latency_ms: null, + error_message: null, + audio_storage_key: null, + created_at: '2026-11-13T01:00:00.000Z', + updated_at: '2026-11-13T01:10:00.000Z', + }, + transcripts: [ + { + id: 't1', + meeting_id: '22222222-2222-4222-8222-222222222222', + segment_index: 0, + timestamp_ms: 2_000, + duration_ms: 4_000, + text: '첫 번째 안건 시작합니다', + speaker: '화자 1', + edited: false, + created_at: '2026-11-13T01:00:02.000Z', + }, + { + id: 't2', + meeting_id: '22222222-2222-4222-8222-222222222222', + segment_index: 1, + timestamp_ms: 8_000, + duration_ms: 5_000, + text: '일정 검토 결과를 공유드립니다', + speaker: '화자 2', + edited: true, + created_at: '2026-11-13T01:00:08.000Z', + }, + ], + memos: [], + documents: [], + processingJobs: [], + }) + }) + + it('화자필터_복수화자세그먼트표시및화자선택시_해당화자세그먼트만필터링한다', async () => { + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create( + , + ) + }) + + expect(renderer.root.findAllByProps({ testID: 'meeting-speaker-filter-bar' }).length).toBeGreaterThan(0) + expect(renderer.root.findAllByProps({ testID: 'meeting-transcript-speaker-t1' }).length).toBeGreaterThan(0) + expect(renderer.root.findAllByProps({ testID: 'meeting-transcript-speaker-t2' }).length).toBeGreaterThan(0) + + const filterSpeaker2 = renderer.root.findAllByProps({ testID: 'meeting-speaker-filter-화자 2' })[0] + await act(async () => { + filterSpeaker2.props.onPress() + }) + + expect(renderer.root.findAllByProps({ testID: 'meeting-transcript-t1' })).toHaveLength(0) + expect(renderer.root.findAllByProps({ testID: 'meeting-transcript-t2' }).length).toBeGreaterThan(0) + + const filterAll = renderer.root.findAllByProps({ testID: 'meeting-speaker-filter-all' })[0] + await act(async () => { + filterAll.props.onPress() + }) + + expect(renderer.root.findAllByProps({ testID: 'meeting-transcript-t1' }).length).toBeGreaterThan(0) + expect(renderer.root.findAllByProps({ testID: 'meeting-transcript-t2' }).length).toBeGreaterThan(0) + + act(() => { + renderer.unmount() + }) + }) +}) diff --git a/apps/mobile-rn/__tests__/meeting-detail-unmount-regression.test.tsx b/apps/mobile-rn/__tests__/meeting-detail-unmount-regression.test.tsx new file mode 100644 index 0000000..ba0ddc7 --- /dev/null +++ b/apps/mobile-rn/__tests__/meeting-detail-unmount-regression.test.tsx @@ -0,0 +1,156 @@ +import React from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import type { PreparedPortableFile } from '../src/features/data-portability' + +const USER_ID = '11111111-1111-4111-8111-111111111111' +const MEETING_ID = '22222222-2222-4222-8222-222222222222' + +const mockT = (key: string): string => key +const mockFormatDate = (): string => '2026-11-14' +const mockAuthValue = { + user: { id: USER_ID }, + session: { access_token: 'tok-1' }, +} +const { d3roNativeDarkPalette } = jest.requireActual('@d3ro/ui-native') as typeof import('@d3ro/ui-native') +const mockPreferencesValue = { palette: d3roNativeDarkPalette } +const mockGetMeetingDetail = jest.fn() +const mockLoadTemplateLibrary = jest.fn(async () => ({ templates: [], selections: {} })) +const mockPrepareMeetingExportFile = jest.fn, [unknown, unknown]>() +const mockSharePreparedPortableFile = jest.fn(async () => undefined) + +jest.mock('@react-navigation/native', () => { + const ReactValue = require('react') as typeof React + return { + useFocusEffect: (callback: () => void | (() => void)) => { + ReactValue.useEffect(callback, [callback]) + }, + } +}) +jest.mock('react-native-safe-area-context', () => ({ + useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }), +})) +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => ({ + t: mockT, + formatDate: mockFormatDate, + }), +})) +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => mockAuthValue, +})) +jest.mock('../src/lib/preferences-context', () => ({ + useMobilePreferences: () => mockPreferencesValue, +})) +jest.mock('../src/components/ContentReportSheet', () => ({ + __esModule: true, + default: () => null, +})) +jest.mock('../src/features/data-portability', () => ({ + prepareMeetingExportFile: (payload: unknown, format: unknown) => + mockPrepareMeetingExportFile(payload, format), + sharePreparedPortableFile: () => mockSharePreparedPortableFile(), +})) +jest.mock('../src/features/templates', () => ({ + generateMeetingDocumentOnce: jest.fn(), + loadTemplateLibrary: () => mockLoadTemplateLibrary(), + TemplateServiceError: class TemplateServiceError extends Error {}, +})) +jest.mock('../src/features/meetings/meetings-service', () => { + const actual = jest.requireActual('../src/features/meetings/meetings-service') as Record + return { + ...actual, + getMeetingDetail: () => mockGetMeetingDetail(), + subscribeToMeetingDetail: () => ({ + unsubscribe: async () => undefined, + }), + } +}) + +import MeetingDetailScreen, { formatElapsedMs } from '../src/screens/MeetingDetailScreen' + +describe('MeetingDetailScreen format & unmount cleanup regressions', () => { + beforeEach(() => { + mockPrepareMeetingExportFile.mockReset() + mockSharePreparedPortableFile.mockClear() + mockGetMeetingDetail.mockReset().mockResolvedValue({ + meeting: { + id: MEETING_ID, + user_id: USER_ID, + team_id: null, + title: 'Weekly Sync', + status: 'completed', + started_at: '2026-11-14T00:00:00.000Z', + ended_at: '2026-11-14T00:10:00.000Z', + duration_ms: 600_000, + raw_transcript: null, + edited_transcript: null, + minutes_markdown: null, + minutes_json: null, + stt_model: 'whisper', + llm_model: null, + stt_latency_ms: null, + llm_latency_ms: null, + error_message: null, + audio_storage_key: null, + created_at: '2026-11-14T00:00:00.000Z', + updated_at: '2026-11-14T00:10:00.000Z', + }, + transcripts: [], + memos: [], + documents: [], + processingJobs: [], + }) + }) + + test('formatElapsedMs_공통포맷터위임시_기존밀리초시계규칙을그대로유지', () => { + expect(formatElapsedMs(0)).toBe('00:00') + expect(formatElapsedMs(-5_000)).toBe('00:00') + expect(formatElapsedMs(65_000)).toBe('01:05') + expect(formatElapsedMs(3_661_000)).toBe('1:01:01') + }) + + test('exportMeeting_파일생성중언마운트시_임시파일을정리하고공유를호출하지않음', async () => { + let resolvePrepared: (file: PreparedPortableFile) => void = () => undefined + mockPrepareMeetingExportFile.mockImplementation( + () => new Promise((resolve) => { + resolvePrepared = resolve + }), + ) + const mockDispose = jest.fn(async () => undefined) + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create( + , + ) + await Promise.resolve() + await Promise.resolve() + }) + + await act(async () => { + renderer.root.findByProps({ testID: 'meeting-export-md' }).props.onPress() + await Promise.resolve() + }) + + act(() => { + renderer.unmount() + }) + + await act(async () => { + resolvePrepared({ + path: '/tmp/weekly-sync.md', + uri: 'file:///tmp/weekly-sync.md', + fileName: 'weekly-sync.md', + mimeType: 'text/markdown', + dispose: mockDispose, + }) + await Promise.resolve() + }) + + expect(mockDispose).toHaveBeenCalledTimes(1) + expect(mockSharePreparedPortableFile).not.toHaveBeenCalled() + }) +}) diff --git a/apps/mobile-rn/__tests__/meetings.test.ts b/apps/mobile-rn/__tests__/meetings.test.ts index af0d02a..59e4bc9 100644 --- a/apps/mobile-rn/__tests__/meetings.test.ts +++ b/apps/mobile-rn/__tests__/meetings.test.ts @@ -40,6 +40,7 @@ import { computeMemoTimestamp, createMeetingCreationIdempotencyKey, createMeetingWorkspaceWithMetadata, + deleteMeetingMemoConflictSafe, findActiveTranscriptSegmentId, getMeetingRecordingLanguage, MeetingServiceError, @@ -399,6 +400,46 @@ describe('meeting mutation safety', () => { expect(mockQuery.eq).toHaveBeenCalledWith('timestamp_ms', current.timestamp_ms) expect(mockQuery.eq).toHaveBeenCalledWith('created_at', current.created_at) }) + + test('메모수정과삭제는_A에서B다시A로되돌아온ABA동시편집도_불변revision_CAS로차단한다', async () => { + const serverRowAfterAba: Record = { + id: '33333333-3333-4333-8333-333333333333', + meeting_id: MEETING_ID, + user_id: USER_ID, + content: 'original-A', + timestamp_ms: 12_345, + revision: 3, + created_at: '2026-08-21T00:00:12.345Z', + updated_at: '2026-08-21T00:02:00.000Z', + } + const eqFilters: Array<[string, unknown]> = [] + mockQuery.eq.mockImplementation((column: string, value: unknown) => { + eqFilters.push([column, value]) + return mockQuery + }) + mockMaybeSingle.mockImplementation(async () => { + const matched = eqFilters.every(([col, val]) => serverRowAfterAba[col] === val) + eqFilters.length = 0 + return { data: matched ? { ...serverRowAfterAba, content: 'stale-client-overwrite', revision: 4 } : null, error: null } + }) + + const staleClientSnapshot = { + id: '33333333-3333-4333-8333-333333333333', + meeting_id: MEETING_ID, + user_id: USER_ID, + content: 'original-A', + timestamp_ms: 12_345, + revision: 1, + created_at: '2026-08-21T00:00:12.345Z', + updated_at: '2026-08-21T00:00:12.345Z', + } as MeetingMemo + + await expect(updateMeetingMemoConflictSafe(USER_ID, staleClientSnapshot, 'stale-client-overwrite')) + .rejects.toMatchObject({ code: 'conflict' }) + + await expect(deleteMeetingMemoConflictSafe(USER_ID, staleClientSnapshot)) + .rejects.toMatchObject({ code: 'conflict' }) + }) }) describe('meeting realtime subscription', () => { diff --git a/apps/mobile-rn/__tests__/onboarding-locale-regression.test.tsx b/apps/mobile-rn/__tests__/onboarding-locale-regression.test.tsx new file mode 100644 index 0000000..32651b0 --- /dev/null +++ b/apps/mobile-rn/__tests__/onboarding-locale-regression.test.tsx @@ -0,0 +1,131 @@ +import React from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import type { Locale } from '@d3ro/i18n/shared' +import type { PreferenceMutationResult } from '../src/lib/preferences-context' + +let mockLocale: Locale = 'en' +const mockSetLocale = jest.fn((next: Locale) => { + mockLocale = next +}) +const mockUpdatePreferences = jest.fn, [unknown]>() +const mockCompleteOnboarding = jest.fn, [unknown]>() + +jest.mock('react-native-safe-area-context', () => ({ + useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }), +})) +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => ({ + locale: mockLocale, + setLocale: mockSetLocale, + t: (key: string) => key, + }), +})) +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => ({ user: null }), +})) +jest.mock('../src/lib/preferences-context', () => { + const { getMobileThemePalette } = jest.requireActual( + '../src/theme/mobile-theme', + ) + return { + useMobilePreferences: () => ({ + preferences: { themeMode: 'dark' }, + palette: getMobileThemePalette('dark'), + syncStatus: 'local', + errorCode: null, + updatePreferences: (patch: unknown) => mockUpdatePreferences(patch), + completeOnboarding: (outcome: unknown) => mockCompleteOnboarding(outcome), + }), + } +}) + +import OnboardingScreen from '../src/screens/OnboardingScreen' + +describe('OnboardingScreen locale & finish lock regressions', () => { + let renderer: ReactTestRenderer | null = null + + beforeEach(() => { + mockLocale = 'en' + mockSetLocale.mockClear() + mockUpdatePreferences.mockReset() + mockCompleteOnboarding.mockReset() + }) + + afterEach(() => { + if (renderer !== null) { + act(() => renderer!.unmount()) + renderer = null + } + }) + + test('selectLocale_저장확정후에만setLocale을호출하고_실패시오류를노출', async () => { + let resolveLocaleSave: (value: PreferenceMutationResult) => void = () => undefined + mockUpdatePreferences + .mockImplementationOnce( + () => new Promise((resolve) => { + resolveLocaleSave = resolve + }), + ) + .mockResolvedValueOnce({ localSaved: false, serverSynced: false }) + + await act(async () => { + renderer = create( + false, goBack: jest.fn() } as never} + route={{ params: undefined } as never} + />, + ) + }) + + await act(async () => { + renderer!.root.findByProps({ testID: 'onboarding-language-ja' }).props.onPress() + await Promise.resolve() + }) + expect(mockSetLocale).not.toHaveBeenCalled() + + await act(async () => { + resolveLocaleSave({ localSaved: true, serverSynced: true }) + await Promise.resolve() + }) + expect(mockSetLocale).toHaveBeenCalledWith('ja') + + await act(async () => { + renderer!.root.findByProps({ testID: 'onboarding-language-de' }).props.onPress() + await Promise.resolve() + }) + expect(mockSetLocale).toHaveBeenCalledTimes(1) + const errorBox = renderer!.root.findByProps({ testID: 'onboarding-settings-error' }) + expect( + errorBox.findAll( + (node) => typeof node.type === 'string' && node.props.children === 'mobile.preferences.cacheWriteError', + ).length, + ).toBe(1) + }) + + test('finish_completeOnboarding예외발생시_saving잠금을해제하여재시도허용', async () => { + mockCompleteOnboarding + .mockRejectedValueOnce(new Error('storage offline')) + .mockResolvedValueOnce({ localSaved: true, serverSynced: true }) + + await act(async () => { + renderer = create( + false, goBack: jest.fn() } as never} + route={{ params: undefined } as never} + />, + ) + }) + + await act(async () => { + renderer!.root.findByProps({ testID: 'onboarding-skip' }).props.onPress() + await Promise.resolve() + }) + + await act(async () => { + renderer!.root.findByProps({ testID: 'onboarding-skip' }).props.onPress() + await Promise.resolve() + }) + + expect(mockCompleteOnboarding).toHaveBeenCalledTimes(2) + }) +}) diff --git a/apps/mobile-rn/__tests__/preferences.test.ts b/apps/mobile-rn/__tests__/preferences.test.ts index dca7175..752f3f4 100644 --- a/apps/mobile-rn/__tests__/preferences.test.ts +++ b/apps/mobile-rn/__tests__/preferences.test.ts @@ -47,6 +47,11 @@ describe('mobile preferences model', () => { hapticEnabled: false, preferredSttModel: 'cloud-default', }) + + expect(normalizePreferences({ locale: 'ja' }).locale).toBe('ja') + expect(normalizePreferences({ locale: 'zh-TW' }).locale).toBe('zh-TW') + expect(normalizePreferencesPatch({ locale: 'es' })).toEqual({ locale: 'es' }) + expect(normalizePreferencesPatch({ locale: 'invalid-locale' })).toEqual({}) }) test('applies an offline patch without discarding server metadata', () => { diff --git a/apps/mobile-rn/__tests__/record-permission-session-regression.test.tsx b/apps/mobile-rn/__tests__/record-permission-session-regression.test.tsx new file mode 100644 index 0000000..190dd26 --- /dev/null +++ b/apps/mobile-rn/__tests__/record-permission-session-regression.test.tsx @@ -0,0 +1,138 @@ +import React from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' + +const mockCancelSession = jest.fn(async () => undefined) +const mockRequestPermission = jest.fn(async () => false) +const mockAcquire = jest.fn(async () => ({ + restore: async () => ({ state: 'idle', recording: null, meetingId: null, interruptionReason: null }), + start: jest.fn(async () => undefined), + stop: jest.fn(), + cleanup: jest.fn(async () => undefined), + cancel: mockCancelSession, + pause: jest.fn(async () => undefined), + resume: jest.fn(async () => undefined), +})) + +const mockAuthValue = { user: { id: '11111111-1111-4111-8111-111111111111' } } +const mockT = (key: string): string => key +const { d3roNativeDarkPalette } = jest.requireActual('@d3ro/ui-native') as typeof import('@d3ro/ui-native') +const mockPreferencesValue = { palette: d3roNativeDarkPalette } + +jest.mock('@react-navigation/native', () => ({ + useNavigation: () => ({ goBack: jest.fn(), getParent: () => null, setParams: jest.fn() }), +})) +jest.mock('react-native-safe-area-context', () => ({ + useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }), +})) +jest.mock('../src/components/ScreenHeader', () => ({ ScreenHeader: () => null })) +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => ({ t: mockT, locale: 'ko' }), +})) +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => mockAuthValue, +})) +jest.mock('../src/lib/preferences-context', () => ({ + useMobilePreferences: () => mockPreferencesValue, +})) +jest.mock('@d3ro/ui-native', () => { + const { Pressable, Text, View } = require('react-native') as typeof import('react-native') + const Passthrough = ({ children }: React.PropsWithChildren>) => {children} + return { + Led: () => null, + WaveBars: () => null, + NativeThemeProvider: Passthrough, + PhosphorText: ({ children, ...props }: React.PropsWithChildren>) => ( + {children} + ), + PhysicalButton: ({ label, onPress, disabled, testID }: { + label: string + onPress?: () => void + disabled?: boolean + testID?: string + }) => ( + + {label} + + ), + d3roNativeFonts: { sans: 'sans' }, + d3roNativeNumerals: {}, + } +}) +jest.mock('../src/lib/audio-recorder', () => { + class RecorderBusyError extends Error {} + return { + RecorderBusyError, + audioRecorder: { + acquire: () => mockAcquire(), + requestPermission: () => mockRequestPermission(), + }, + } +}) +jest.mock('../src/features/import/audio-file-picker', () => ({ + pickAudioFile: jest.fn(), +})) +jest.mock('../src/features/import/incoming-media-intent', () => ({ + consumeIncomingMediaAudio: jest.fn(), +})) +jest.mock('../src/features/notifications/notification-native', () => ({ + showLocalTranscriptionCompleted: jest.fn(async () => true), +})) +jest.mock('../src/features/recording/durable-processing-queue', () => { + class QueuedAudioPendingError extends Error {} + return { + QueuedAudioPendingError, + discardQueuedAudio: jest.fn(async () => undefined), + enqueueAudioProcessing: jest.fn(), + processQueuedAudioNow: jest.fn(), + retryQueuedAudio: jest.fn(async () => undefined), + subscribeToDurableQueue: () => () => undefined, + } +}) +jest.mock('../src/features/meetings/meetings-service', () => ({ + beginMeetingRecording: jest.fn(), + cancelMeetingRecording: jest.fn(), + failMeetingRecording: jest.fn(), + getMeetingRecordingLanguage: jest.fn(async () => 'ko'), +})) + +import RecordScreen from '../src/screens/RecordScreen' + +describe('RecordScreen permission denial session cleanup', () => { + let renderer: ReactTestRenderer | null = null + + beforeEach(() => { + mockCancelSession.mockClear() + mockAcquire.mockClear() + mockRequestPermission.mockReset().mockResolvedValue(false) + }) + + afterEach(() => { + if (renderer !== null) { + act(() => renderer!.unmount()) + renderer = null + } + }) + + test('startRecording_마이크권한거부시_acquire한세션을cancel하여리스를반환', async () => { + await act(async () => { + renderer = create( + null, setParams: jest.fn() } as never} + route={{ params: {} } as never} + />, + ) + await Promise.resolve() + }) + + mockAcquire.mockClear() + await act(async () => { + renderer!.root.findByProps({ testID: 'record-start' }).props.onPress() + await Promise.resolve() + await Promise.resolve() + }) + + expect(mockAcquire).toHaveBeenCalledTimes(1) + expect(mockCancelSession).toHaveBeenCalledTimes(1) + expect(JSON.stringify(renderer!.toJSON())).toContain('mobile.rec.micDenied') + }) +}) diff --git a/apps/mobile-rn/__tests__/responsive-layout.test.tsx b/apps/mobile-rn/__tests__/responsive-layout.test.tsx new file mode 100644 index 0000000..def0605 --- /dev/null +++ b/apps/mobile-rn/__tests__/responsive-layout.test.tsx @@ -0,0 +1,195 @@ +import React from 'react' +import { StyleSheet, View } from 'react-native' +import * as ReactNative from 'react-native' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { + ACTION_BUTTON_MAX_WIDTH_DP, + CONTENT_MAX_WIDTH_DP, + ContentColumn, + FORM_MAX_WIDTH_DP, + WIDE_CONTENT_MAX_WIDTH_DP, + resolveResponsiveLayout, +} from '@d3ro/ui-native' + +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => ({ t: (key: string) => key }), +})) + +jest.mock('@react-navigation/native', () => ({ + useNavigation: () => ({ navigate: jest.fn(), goBack: jest.fn() }), +})) + +jest.mock('react-native-safe-area-context', () => ({ + useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }), +})) + +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => ({ user: null, session: null }), +})) + +jest.mock('../src/lib/entitlement-context', () => ({ + useEntitlement: () => ({ snapshot: { tier: 'free' } }), +})) + +jest.mock('../src/lib/preferences-context', () => { + const { d3roNativeDarkPalette } = jest.requireActual('@d3ro/ui-native') as typeof import('@d3ro/ui-native') + return { + useMobilePreferences: () => ({ palette: d3roNativeDarkPalette }), + } +}) + +jest.mock('../src/lib/mobile-ads-context', () => ({ + useMobileAds: () => ({ + eligible: true, + bannerUnitId: 'ca-app-pub-3940256099942544/6300978111', + status: 'ready', + }), +})) + +import FreeTierBanner from '../src/components/FreeTierBanner' +import MoreScreen from '../src/screens/MoreScreen' + +function findHostViewByTestId(renderer: ReactTestRenderer, testID: string) { + const matches = renderer.root.findAll( + (node) => node.type === 'View' && node.props.testID === testID, + ) + expect(matches.length).toBe(1) + return matches[0] +} + +describe('모바일 태블릿·폴더블 대화면 반응형 레이아웃 (GAP-UX-08)', () => { + afterEach(() => { + act(() => { + ReactNative.Dimensions.set({ + window: { width: 750, height: 1334, scale: 2, fontScale: 2 }, + screen: { width: 750, height: 1334, scale: 2, fontScale: 2 }, + }) + }) + jest.restoreAllMocks() + }) + + it('resolveResponsiveLayout_화면폭별_폰1열과폴더블태블릿2열및배너예약높이를결정한다', () => { + const phone = resolveResponsiveLayout(390) + expect(phone.isLargeScreen).toBe(false) + expect(phone.gridColumns).toBe(1) + expect(phone.bannerSlotMinHeight).toBe(50) + + const foldable = resolveResponsiveLayout(825) + expect(foldable.isLargeScreen).toBe(true) + expect(foldable.gridColumns).toBe(2) + expect(foldable.bannerSlotMinHeight).toBe(90) + expect(foldable.contentMaxWidth).toBe(CONTENT_MAX_WIDTH_DP) + expect(foldable.formMaxWidth).toBe(FORM_MAX_WIDTH_DP) + expect(foldable.actionButtonMaxWidth).toBe(ACTION_BUTTON_MAX_WIDTH_DP) + + const tablet = resolveResponsiveLayout(924) + expect(tablet.isLargeScreen).toBe(true) + expect(tablet.gridColumns).toBe(2) + expect(tablet.bannerSlotMinHeight).toBe(90) + expect(tablet.wideContentMaxWidth).toBe(WIDE_CONTENT_MAX_WIDTH_DP) + }) + + it('ContentColumn_변형별_중앙정렬과최대폭제한스타일을적용한다', () => { + let renderer!: ReactTestRenderer + act(() => { + renderer = create( + + + + + , + ) + }) + + const defaultStyle = StyleSheet.flatten(findHostViewByTestId(renderer, 'col-default').props.style) + const formStyle = StyleSheet.flatten(findHostViewByTestId(renderer, 'col-form').props.style) + const wideStyle = StyleSheet.flatten(findHostViewByTestId(renderer, 'col-wide').props.style) + + expect(defaultStyle.maxWidth).toBe(720) + expect(defaultStyle.alignSelf).toBe('center') + expect(formStyle.maxWidth).toBe(480) + expect(wideStyle.maxWidth).toBe(960) + act(() => { + renderer.unmount() + }) + }) + + it('FreeTierBanner_폰390dp에서는50dp_태블릿924dp에서는90dp최소높이를예약한다', () => { + act(() => { + ReactNative.Dimensions.set({ + window: { width: 390, height: 844, scale: 3, fontScale: 1 }, + screen: { width: 390, height: 844, scale: 3, fontScale: 1 }, + }) + }) + + let phoneRenderer!: ReactTestRenderer + act(() => { + phoneRenderer = create() + }) + const phoneSlot = findHostViewByTestId(phoneRenderer, 'free-tier-ad-slot') + expect(StyleSheet.flatten(phoneSlot.props.style).minHeight).toBe(50) + act(() => { + phoneRenderer.unmount() + }) + + act(() => { + ReactNative.Dimensions.set({ + window: { width: 924, height: 600, scale: 2, fontScale: 1 }, + screen: { width: 924, height: 600, scale: 2, fontScale: 1 }, + }) + }) + + let tabletRenderer!: ReactTestRenderer + act(() => { + tabletRenderer = create() + }) + + const tabletSlot = findHostViewByTestId(tabletRenderer, 'free-tier-ad-slot') + expect(StyleSheet.flatten(tabletSlot.props.style).minHeight).toBe(90) + act(() => { + tabletRenderer.unmount() + }) + }) + + it('MoreScreen_폰390dp에서는1열리스트_태블릿825dp에서는2열그리드로전환한다', () => { + act(() => { + ReactNative.Dimensions.set({ + window: { width: 390, height: 844, scale: 3, fontScale: 1 }, + screen: { width: 390, height: 844, scale: 3, fontScale: 1 }, + }) + }) + + let phoneRenderer!: ReactTestRenderer + act(() => { + phoneRenderer = create() + }) + const phoneLists = phoneRenderer.root.findAll( + (node) => node.type === 'View' && node.props.testID === 'more-rows-list', + ) + expect(phoneLists.length).toBe(2) + act(() => { + phoneRenderer.unmount() + }) + + act(() => { + ReactNative.Dimensions.set({ + window: { width: 825, height: 691, scale: 2.5, fontScale: 1 }, + screen: { width: 825, height: 691, scale: 2.5, fontScale: 1 }, + }) + }) + let foldableRenderer!: ReactTestRenderer + act(() => { + foldableRenderer = create() + }) + const foldableGrids = foldableRenderer.root.findAll( + (node) => node.type === 'View' && node.props.testID === 'more-rows-grid', + ) + expect(foldableGrids.length).toBe(2) + const gridStyle = StyleSheet.flatten(foldableGrids[0].props.style) + expect(gridStyle.flexDirection).toBe('row') + expect(gridStyle.flexWrap).toBe('wrap') + act(() => { + foldableRenderer.unmount() + }) + }) +}) diff --git a/apps/mobile-rn/__tests__/service-guards.test.ts b/apps/mobile-rn/__tests__/service-guards.test.ts new file mode 100644 index 0000000..b34a0e8 --- /dev/null +++ b/apps/mobile-rn/__tests__/service-guards.test.ts @@ -0,0 +1,220 @@ +import { LOCALE_CODES, type TranslationKey } from '@d3ro/i18n/shared' + +jest.mock('../src/lib/supabase', () => ({ + supabase: { + from: jest.fn(), + rpc: jest.fn(), + storage: { from: jest.fn() }, + channel: jest.fn(), + removeChannel: jest.fn(async () => 'ok'), + }, +})) + +import { Dirs, FileSystem } from 'react-native-file-access' +import { + assertRecordWith, + createLabeledUuidAssert, + createUuidAssert, + extractSupabaseErrorInfo, + getTypedSupabaseClient, + isSupabaseAuthFailure, + isSupabaseForbiddenFailure, + isSupabaseNetworkFailure, + parseBoundedStringWith, + parseIsoTimestampWith, + parseSafeIntegerWith, + parseUuidWith, + requireUuidWith, +} from '../src/features/shared/service-guards' +import { + isOwnedCachePath, + localPathFromCacheUri, + removeOwnedCacheFile, +} from '../src/features/shared/owned-cache-files' +import { throwIfPipelineCancelled } from '../src/features/import/abort-guard' +import { AudioPipelineError } from '../src/features/import/audio-import-types' +import { toSpeechLanguageTag } from '../src/lib/locale-speech' +import { resolveMeetingErrorMessage } from '../src/features/meetings/meeting-error-message' +import { MeetingServiceError } from '../src/features/meetings/meetings-service' + +class DomainGuardError extends Error { + readonly code: string + + constructor(code: string, message: string) { + super(message) + this.code = code + } +} + +const VALID_UUID_UPPER = '123E4567-E89B-42D3-A456-426614174000' +const VALID_UUID_LOWER = '123e4567-e89b-42d3-a456-426614174000' +const mockFileSystem = FileSystem as typeof FileSystem & { filesystem: Map } + +describe('shared mobile service guards', () => { + beforeEach(() => { + mockFileSystem.filesystem.clear() + }) + + test('requireUuidWith_유효하지않은값_도메인에러발생', () => { + const assertId = createUuidAssert(() => new DomainGuardError('auth', 'User required')) + const assertLabeled = createLabeledUuidAssert( + (label) => new DomainGuardError('validation', `Invalid ${label}`), + ) + + expect(() => assertId('not-a-uuid')).toThrow(new DomainGuardError('auth', 'User required')) + expect(() => assertLabeled(42, 'meeting id')).toThrow( + new DomainGuardError('validation', 'Invalid meeting id'), + ) + expect(() => requireUuidWith(VALID_UUID_LOWER, () => new Error('unused'))).not.toThrow() + expect(typeof getTypedSupabaseClient().from).toBe('function') + }) + + test('parseUuidWith_공백대소문자옵션_정규화및보존검증', () => { + const makeError = () => new DomainGuardError('validation', 'bad-uuid') + + expect(parseUuidWith(` ${VALID_UUID_UPPER} `, makeError, { trim: true })).toBe( + VALID_UUID_LOWER, + ) + expect( + parseUuidWith(VALID_UUID_UPPER, makeError, { normalizeCase: 'preserve' }), + ).toBe(VALID_UUID_UPPER) + expect(() => parseUuidWith(VALID_UUID_UPPER, makeError)).not.toThrow() + expect(() => parseUuidWith(` ${VALID_UUID_UPPER}`, makeError)).toThrow('bad-uuid') + expect(() => parseUuidWith(123, makeError)).toThrow('bad-uuid') + }) + + test('레코드문자열정수타임스탬프검증기_경계위반시_정확한도메인에러발생', () => { + const makeError = (code: string) => () => new DomainGuardError(code, code) + + expect(assertRecordWith({ ok: true }, makeError('not-record'))).toEqual({ ok: true }) + expect(() => assertRecordWith(['array'], makeError('not-record'))).toThrow('not-record') + expect(() => assertRecordWith(null, makeError('not-record'))).toThrow('not-record') + + expect(parseBoundedStringWith('abc', makeError('str'), { minLength: 2, maxLength: 3 })).toBe( + 'abc', + ) + expect(() => + parseBoundedStringWith('a', makeError('str'), { minLength: 2, maxLength: 3 }), + ).toThrow('str') + expect(() => parseBoundedStringWith('abcd', makeError('str'), { maxLength: 3 })).toThrow('str') + + expect(parseSafeIntegerWith(10, makeError('int'), { min: 1, max: 10 })).toBe(10) + expect(() => parseSafeIntegerWith(10.5, makeError('int'), { min: 0, max: 20 })).toThrow('int') + expect(() => parseSafeIntegerWith(0, makeError('int'), { min: 1, max: 10 })).toThrow('int') + + expect( + parseIsoTimestampWith('2026-11-14T00:00:00Z', makeError('ts'), { + requireTimePrefix: true, + normalizeToIso: true, + }), + ).toBe('2026-11-14T00:00:00.000Z') + expect(() => + parseIsoTimestampWith('2026-11-14', makeError('ts'), { requireTimePrefix: true }), + ).toThrow('ts') + expect(() => parseIsoTimestampWith('not-a-date', makeError('ts'))).toThrow('ts') + }) + + test('Supabase에러분류기_네트워크인증권한실패를_정확히식별', () => { + const typeError = new TypeError('Failed to fetch') + const typeInfo = extractSupabaseErrorInfo(typeError, 'fallback') + expect(typeInfo).toEqual({ + code: '', + message: 'Failed to fetch', + lower: 'failed to fetch', + }) + expect(isSupabaseNetworkFailure(typeError, typeInfo)).toBe(true) + + const jwtInfo = extractSupabaseErrorInfo({ code: 'PGRST301', message: 'JWT expired' }, 'fb') + expect(isSupabaseAuthFailure(jwtInfo)).toBe(true) + expect(isSupabaseForbiddenFailure(jwtInfo)).toBe(false) + + const rlsInfo = extractSupabaseErrorInfo({ code: '42501', message: 'Permission denied' }, 'fb') + expect(isSupabaseAuthFailure(rlsInfo)).toBe(false) + expect(isSupabaseAuthFailure(rlsInfo, { include42501: true })).toBe(true) + expect(isSupabaseForbiddenFailure(rlsInfo)).toBe(true) + }) +}) + +describe('owned cache files and abort guard', () => { + beforeEach(() => { + mockFileSystem.filesystem.clear() + }) + + test('removeOwnedCacheFile_캐시경로만삭제하고_경로이탈은거부', async () => { + const ownedPath = `${Dirs.CacheDir}/exports/sample.txt` + mockFileSystem.filesystem.set(ownedPath, 'content') + + expect(localPathFromCacheUri('file:///tmp/my%20file.txt')).toBe('/tmp/my file.txt') + expect(localPathFromCacheUri('/raw/path.txt')).toBe('/raw/path.txt') + expect(isOwnedCachePath(ownedPath)).toBe(true) + expect(isOwnedCachePath(`${Dirs.CacheDir}/../secret.txt`)).toBe(false) + + await removeOwnedCacheFile(ownedPath, () => new Error('outside-root')) + expect(mockFileSystem.filesystem.has(ownedPath)).toBe(false) + + await expect( + removeOwnedCacheFile('/etc/passwd', () => new Error('outside-root')), + ).rejects.toThrow('outside-root') + }) + + test('throwIfPipelineCancelled_중단된신호시_AudioPipelineError발생', () => { + const controller = new AbortController() + expect(() => throwIfPipelineCancelled(controller.signal)).not.toThrow() + + controller.abort() + expect(() => throwIfPipelineCancelled(controller.signal, 'Stopped early')).toThrow( + new AudioPipelineError('cancelled', 'Stopped early'), + ) + }) +}) + +describe('speech language tags and meeting error messages', () => { + test('toSpeechLanguageTag_전체12개지원로케일을_올바른BCP47태그로매핑', () => { + const expected: Record<(typeof LOCALE_CODES)[number], string> = { + ko: 'ko-KR', + en: 'en-US', + ja: 'ja', + zh: 'zh-CN', + 'zh-TW': 'zh-TW', + es: 'es', + fr: 'fr', + de: 'de', + pt: 'pt', + ru: 'ru', + vi: 'vi', + th: 'th', + } + const actual = Object.fromEntries( + LOCALE_CODES.map((code) => [code, toSpeechLanguageTag(code)]), + ) + expect(actual).toEqual(expected) + }) + + test('resolveMeetingErrorMessage_서비스에러코드를_정확한번역키로매핑', () => { + const t = (key: TranslationKey): string => key + expect(resolveMeetingErrorMessage(new MeetingServiceError('auth', 'a'), t)).toBe( + 'mobile.meetings.loginRequired', + ) + expect(resolveMeetingErrorMessage(new MeetingServiceError('conflict', 'c'), t)).toBe( + 'mobile.meetings.errorConflict', + ) + expect(resolveMeetingErrorMessage(new MeetingServiceError('forbidden', 'f'), t)).toBe( + 'mobile.meetings.errorForbidden', + ) + expect(resolveMeetingErrorMessage(new MeetingServiceError('network', 'n'), t)).toBe( + 'mobile.meetings.errorNetwork', + ) + expect(resolveMeetingErrorMessage(new MeetingServiceError('not-found', 'nf'), t)).toBe( + 'mobile.meetings.errorNotFound', + ) + expect(resolveMeetingErrorMessage(new MeetingServiceError('validation', 'v'), t)).toBe( + 'mobile.meetings.errorValidation', + ) + expect(resolveMeetingErrorMessage(new MeetingServiceError('server', 's'), t)).toBe( + 'mobile.meetings.errorServer', + ) + expect(resolveMeetingErrorMessage(new Error('unexpected'), t)).toBe( + 'mobile.meetings.errorServer', + ) + }) +}) diff --git a/apps/mobile-rn/__tests__/settings-locale-sync-regression.test.tsx b/apps/mobile-rn/__tests__/settings-locale-sync-regression.test.tsx new file mode 100644 index 0000000..5d721ec --- /dev/null +++ b/apps/mobile-rn/__tests__/settings-locale-sync-regression.test.tsx @@ -0,0 +1,152 @@ +import React from 'react' +import { Alert } from 'react-native' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import type { Locale } from '@d3ro/i18n/shared' +import type { PreferenceMutationResult } from '../src/lib/preferences-context' + +let mockLocale: Locale = 'ko' +const mockSetLocale = jest.fn((next: Locale) => { + mockLocale = next +}) +const mockUpdatePreferences = jest.fn, [unknown]>() +const mockRetrySync = jest.fn(async () => true) + +jest.mock('@react-navigation/native', () => ({ + useNavigation: () => ({ navigate: jest.fn(), goBack: jest.fn() }), +})) +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => ({ + locale: mockLocale, + setLocale: mockSetLocale, + t: (key: string) => key, + formatTime: () => '12:00', + }), +})) +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => ({ + user: { id: '11111111-1111-4111-8111-111111111111', email: 'user@example.com', app_metadata: {} }, + purgeLocalSession: jest.fn(async () => undefined), + }), +})) +jest.mock('../src/lib/entitlement-context', () => ({ + useEntitlement: () => ({ + snapshot: { tier: 'free', adFree: false, overageCredits: 0 }, + }), +})) +jest.mock('../src/lib/mobile-ads-context', () => ({ + useMobileAds: () => ({ + eligible: true, + privacyOptionsRequired: false, + showPrivacyOptions: jest.fn(async () => false), + }), +})) +jest.mock('../src/lib/device-context', () => ({ + useDevice: () => ({ currentDevice: null }), +})) +jest.mock('../src/components/ScreenHeader', () => ({ ScreenHeader: () => null })) +jest.mock('../src/lib/preferences-context', () => { + const { d3roNativeDarkPalette } = jest.requireActual('@d3ro/ui-native') as typeof import('@d3ro/ui-native') + return { + useMobilePreferences: () => ({ + preferences: { + themeMode: 'dark', + locale: mockLocale, + autoPolishEnabled: true, + hapticEnabled: false, + }, + palette: d3roNativeDarkPalette, + syncStatus: 'synced', + errorCode: null, + lastSyncedAt: null, + updatePreferences: (patch: unknown) => mockUpdatePreferences(patch), + retrySync: () => mockRetrySync(), + }), + } +}) + +import SettingsScreen from '../src/screens/SettingsScreen' + +describe('SettingsScreen locale sync & saving lock regressions', () => { + let renderer: ReactTestRenderer | null = null + let alertSpy: jest.SpyInstance + + beforeEach(() => { + mockLocale = 'ko' + mockSetLocale.mockClear() + mockUpdatePreferences.mockReset() + mockRetrySync.mockClear() + alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined) + }) + + afterEach(() => { + alertSpy.mockRestore() + if (renderer !== null) { + act(() => renderer!.unmount()) + renderer = null + } + }) + + test('selectLocale_저장완료전에i18n변경하지않고_성공시에만setLocale호출', async () => { + let resolveSave: (value: PreferenceMutationResult) => void = () => undefined + mockUpdatePreferences.mockImplementation( + () => new Promise((resolve) => { + resolveSave = resolve + }), + ) + + await act(async () => { + renderer = create() + }) + + const frenchOption = renderer!.root.findByProps({ testID: 'settings-language-fr' }) + await act(async () => { + frenchOption.props.onPress() + await Promise.resolve() + }) + + expect(mockUpdatePreferences).toHaveBeenCalledWith({ locale: 'fr' }) + expect(mockSetLocale).not.toHaveBeenCalled() + + await act(async () => { + resolveSave({ localSaved: true, serverSynced: true }) + await Promise.resolve() + }) + + expect(mockSetLocale).toHaveBeenCalledTimes(1) + expect(mockSetLocale).toHaveBeenCalledWith('fr') + expect(alertSpy).not.toHaveBeenCalled() + }) + + test('selectLocale_로컬저장실패시_setLocale을건너뛰고저장잠금을해제', async () => { + mockUpdatePreferences + .mockResolvedValueOnce({ localSaved: false, serverSynced: false }) + .mockRejectedValueOnce(new Error('disk error')) + .mockResolvedValueOnce({ localSaved: true, serverSynced: false }) + + await act(async () => { + renderer = create() + }) + + await act(async () => { + renderer!.root.findByProps({ testID: 'settings-language-es' }).props.onPress() + await Promise.resolve() + }) + expect(mockSetLocale).not.toHaveBeenCalled() + expect(alertSpy).toHaveBeenCalledWith( + 'mobile.preferences.saveFailedTitle', + 'mobile.preferences.cacheWriteError', + ) + + await act(async () => { + renderer!.root.findByProps({ testID: 'settings-theme-light' }).props.onPress() + await Promise.resolve() + }) + expect(renderer!.root.findByProps({ testID: 'settings-theme-dark' }).props.disabled).toBe(false) + + await act(async () => { + renderer!.root.findByProps({ testID: 'settings-theme-dark' }).props.onPress() + await Promise.resolve() + }) + expect(mockUpdatePreferences).toHaveBeenNthCalledWith(3, { themeMode: 'dark' }) + }) +}) diff --git a/apps/mobile-rn/__tests__/talk-locale-recorder-regression.test.tsx b/apps/mobile-rn/__tests__/talk-locale-recorder-regression.test.tsx new file mode 100644 index 0000000..ee32a98 --- /dev/null +++ b/apps/mobile-rn/__tests__/talk-locale-recorder-regression.test.tsx @@ -0,0 +1,217 @@ +import React from 'react' +import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' +import type { Locale } from '@d3ro/i18n/shared' + +const USER_ID = '11111111-1111-4111-8111-111111111111' + +let mockLocale: Locale = 'fr' +let mockGreeting = 'Bonjour greeting' +const mockAcquire = jest.fn() +const mockRequestPermission = jest.fn(async () => false) +const mockSpeakTalkText = jest.fn(async () => ({ status: 'completed' })) +const mockStopTalkSpeech = jest.fn(async () => true) +const mockShutdownTalkSpeech = jest.fn(async () => undefined) +const mockStreamTalkResponse = jest.fn() + +jest.mock('@react-navigation/native', () => { + const ReactValue = require('react') as typeof React + return { + useNavigation: () => ({ goBack: jest.fn() }), + useFocusEffect: (effect: () => void | (() => void)) => { + ReactValue.useEffect(effect, [effect]) + }, + } +}) +jest.mock('react-native-safe-area-context', () => ({ + useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }), +})) +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => ({ + t: (key: string) => (key === 'mobile.talk.greeting' ? mockGreeting : key), + }), +})) +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => ({ session: { user: { id: USER_ID }, access_token: 'tok-1' } }), +})) +jest.mock('../src/lib/preferences-context', () => ({ + useMobilePreferences: () => ({ + palette: { + bg: { app: 'app', sidebar: 'sidebar', card: 'card', inset: 'inset' }, + text: { primary: 'primary', muted: 'muted' }, + border: { default: 'border' }, + accent: { main: 'accent', dim: 'dim', pressed: 'pressed' }, + tag: { red: 'red' }, + }, + preferences: { preferredLlmModel: 'default', locale: mockLocale }, + }), +})) +jest.mock('../src/theme/themed-components', () => { + const { Pressable, Text } = require('react-native') as typeof import('react-native') + return { + ThemeText: ({ children, ...props }: React.PropsWithChildren>) => ( + {children} + ), + ThemeButton: ({ label, onPress, ...props }: { label: string; onPress?: () => void }) => ( + + {label} + + ), + } +}) +jest.mock('../src/components/ContentReportSheet', () => ({ + __esModule: true, + default: () => null, +})) +jest.mock('../src/features/chat/chat-service', () => { + class MockChatServiceError extends Error { + code: string + retryable: boolean + + constructor(mockCode: string, mockRetryable: boolean) { + super(mockCode) + this.code = mockCode + this.retryable = mockRetryable + } + } + return { ChatServiceError: MockChatServiceError } +}) +jest.mock('../src/features/talk/llm-stream-service', () => ({ + streamTalkResponse: (...args: unknown[]) => mockStreamTalkResponse(...args), +})) +jest.mock('../src/features/talk/talk-transcription-service', () => ({ + transcribeTalkRecording: jest.fn(), +})) +jest.mock('../src/features/talk/talk-tts', () => { + class MockTalkTtsError extends Error { + code = 'FAILED' + } + return { + shutdownTalkSpeech: () => mockShutdownTalkSpeech(), + speakTalkText: (...args: unknown[]) => mockSpeakTalkText(...args), + stopTalkSpeech: () => mockStopTalkSpeech(), + TalkTtsError: MockTalkTtsError, + } +}) +jest.mock('../src/features/talk/talk-debug-audio', () => ({ + isDeterministicTalkAudioAvailable: () => false, + synthesizeDeterministicTalkAudio: jest.fn(), +})) +jest.mock('../src/lib/audio-recorder', () => { + class MockRecorderBusyError extends Error { + code = 'recorder_busy' + holder = 'record' + } + return { + RecorderBusyError: MockRecorderBusyError, + audioRecorder: { + acquire: (...args: unknown[]) => mockAcquire(...args), + requestPermission: () => mockRequestPermission(), + }, + } +}) + +import TalkScreen from '../src/screens/TalkScreen' + +function byTestId(root: ReactTestInstance, testID: string, prop: string): ReactTestInstance { + const match = root.findAll( + (node) => node.props.testID === testID && typeof node.props[prop] === 'function', + )[0] + if (match === undefined) throw new Error(`Missing ${testID} with ${prop}`) + return match +} + +function allText(root: ReactTestInstance): string { + return root.findAll((node) => typeof node.props.children === 'string') + .map((node) => node.props.children as string) + .join('\n') +} + +async function flush(): Promise { + for (let index = 0; index < 5; index += 1) { + await act(async () => { + await Promise.resolve() + }) + } +} + +describe('TalkScreen locale speech & recorder lease cleanup', () => { + let renderer: ReactTestRenderer | null = null + + beforeEach(() => { + mockLocale = 'fr' + mockGreeting = 'Bonjour greeting' + mockAcquire.mockReset() + mockRequestPermission.mockReset().mockResolvedValue(false) + mockSpeakTalkText.mockReset().mockResolvedValue({ status: 'completed' }) + mockStopTalkSpeech.mockReset().mockResolvedValue(true) + mockShutdownTalkSpeech.mockReset().mockResolvedValue(undefined) + mockStreamTalkResponse.mockReset() + }) + + afterEach(() => { + if (renderer !== null) { + act(() => renderer!.unmount()) + renderer = null + } + }) + + test('beginRecording_마이크권한거부시_획득한녹음세션을즉시취소하여잠금해제', async () => { + const cancelSession = jest.fn(async () => undefined) + mockAcquire.mockResolvedValue({ + start: jest.fn(), + stop: jest.fn(), + cancel: cancelSession, + cleanup: jest.fn(), + }) + + await act(async () => { + renderer = create() + }) + await act(async () => { + byTestId(renderer!.root, 'talk-ptt', 'onPressIn').props.onPressIn() + }) + await flush() + + expect(cancelSession).toHaveBeenCalledTimes(1) + expect(allText(renderer!.root)).toContain('mobile.talk.error.micPermission') + }) + + test('TalkScreen_12개지원로케일전환및음성재생시_해당BCP47태그와인사말을동기화', async () => { + mockStreamTalkResponse.mockResolvedValue({ text: 'Réponse vocale', generationId: 'gen-fr-1' }) + + await act(async () => { + renderer = create() + }) + expect(allText(renderer!.root)).toContain('Bonjour greeting') + + mockLocale = 'ja' + mockGreeting = 'こんにちは greeting' + await act(async () => { + renderer!.update() + }) + expect(allText(renderer!.root)).toContain('こんにちは greeting') + + await act(async () => { + byTestId(renderer!.root, 'talk-input', 'onChangeText').props.onChangeText('Test question') + }) + await act(async () => { + byTestId(renderer!.root, 'talk-send', 'onPress').props.onPress() + }) + await flush() + + const speechButton = renderer!.root.findAll( + (node) => typeof node.props.testID === 'string' && node.props.testID.startsWith('talk-speech-'), + )[0] + await act(async () => { + speechButton.props.onPress() + }) + await flush() + + expect(mockSpeakTalkText).toHaveBeenCalledWith( + expect.objectContaining({ + text: 'Réponse vocale', + languageTag: 'ja', + }), + ) + }) +}) diff --git a/apps/mobile-rn/android/app/build.gradle b/apps/mobile-rn/android/app/build.gradle index ca8acac..25a1043 100644 --- a/apps/mobile-rn/android/app/build.gradle +++ b/apps/mobile-rn/android/app/build.gradle @@ -278,7 +278,7 @@ react { debuggableVariants = ["debug"] } -def enableProguardInReleaseBuilds = false +def enableProguardInReleaseBuilds = true def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' android { @@ -294,6 +294,7 @@ android { androidResources { noCompress += ["bin"] + localeFilters += ["ko", "en", "ja", "zh", "b+zh+TW", "es", "fr", "de", "pt", "ru", "vi", "th"] } defaultConfig { @@ -383,7 +384,8 @@ android { abiFilters "arm64-v8a" } minifyEnabled enableProguardInReleaseBuilds - proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" + shrinkResources enableProguardInReleaseBuilds + proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" } } diff --git a/apps/mobile-rn/android/app/proguard-rules.pro b/apps/mobile-rn/android/app/proguard-rules.pro index c874f1a..07e24b5 100644 --- a/apps/mobile-rn/android/app/proguard-rules.pro +++ b/apps/mobile-rn/android/app/proguard-rules.pro @@ -1,12 +1,80 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html +# D3RO Voice Android R8 / ProGuard Configuration +# Applied alongside getDefaultProguardFile("proguard-android-optimize.txt") in release builds. + +# Preserve readable crash stack traces with file & line numbers +-keepattributes SourceFile,LineNumberTable,*Annotation*,Signature,Exceptions,InnerClasses,EnclosingMethod +-renamesourcefileattribute SourceFile + +# D3RO Voice first-party native modules, services, activities, and BuildConfig +-keep class com.d3ro.voice.** { *; } + +# React Native 0.85 / Hermes / JSI / TurboModules +-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip +-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStripAny +-keep,allowobfuscation @interface com.facebook.jni.annotations.DoNotStrip +-keep,allowobfuscation @interface com.facebook.jni.annotations.DoNotStripAny +-keep,allowobfuscation @interface com.facebook.yoga.annotations.DoNotStrip + +-keep @com.facebook.proguard.annotations.DoNotStrip class * +-keepclassmembers class * { + @com.facebook.proguard.annotations.DoNotStrip *; +} +-keep @com.facebook.proguard.annotations.DoNotStripAny class * { *; } +-keep @com.facebook.jni.annotations.DoNotStrip class * +-keepclassmembers class * { + @com.facebook.jni.annotations.DoNotStrip *; +} +-keep @com.facebook.jni.annotations.DoNotStripAny class * { *; } +-keep @com.facebook.yoga.annotations.DoNotStrip class * +-keepclassmembers class * { + @com.facebook.yoga.annotations.DoNotStrip *; +} + +-keep class * implements com.facebook.react.bridge.JavaScriptModule { *; } +-keep class * implements com.facebook.react.bridge.NativeModule { *; } +-keepclassmembers,includedescriptorclasses class * { native ; } +-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp ; } +-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup ; } + +-dontwarn com.facebook.react.** +-keep,includedescriptorclasses class com.facebook.react.bridge.** { *; } +-keep,includedescriptorclasses class com.facebook.react.turbomodule.core.** { *; } +-keep,includedescriptorclasses class com.facebook.react.internal.turbomodule.core.** { *; } +-keep class com.facebook.jni.** { *; } +-keep class com.facebook.hermes.** { *; } +-keep class com.facebook.soloader.** { *; } -# Add any project specific keep options here: # whisper.rn JSI and TurboModule entry points -keep class com.rnwhisper.** { *; } + +# Nitro Modules (react-native-nitro-modules, react-native-nitro-sound, react-native-iap) +-keep class com.margelo.nitro.** { *; } +-keep class * extends com.margelo.nitro.core.HybridObject { *; } +-keep class * implements com.margelo.nitro.HybridObject { *; } +-dontwarn com.margelo.nitro.** + +# Keychain & Google Tink reflective crypto primitives +-keep class com.oblador.keychain.** { *; } +-keep class com.google.crypto.tink.** { *; } +-dontwarn com.google.crypto.tink.** + +# Google Mobile Ads, UMP Consent, and Firebase Messaging +-keep class io.invertase.googlemobileads.** { *; } +-keep class com.google.android.gms.ads.** { *; } +-keep class com.google.android.ump.** { *; } +-keep class com.google.firebase.** { *; } + +# React Navigation & community native bridges +-keep class com.swmansion.gesturehandler.** { *; } +-keep class com.swmansion.rnscreens.** { *; } +-keep class com.th3rdwave.safeareacontext.** { *; } +-keep class com.alpha0010.fs.** { *; } +-keep class com.reactnativedocumentpicker.** { *; } +-keep class com.proyecto26.inappbrowser.** { *; } +-keep class com.reactnativecommunity.asyncstorage.** { *; } + +# Okio / Kotlin / Android standard warnings +-keep class sun.misc.Unsafe { *; } +-dontwarn java.nio.file.* +-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement +-dontwarn okio.** diff --git a/apps/mobile-rn/jest.config.js b/apps/mobile-rn/jest.config.js index 9b95ec0..888efab 100644 --- a/apps/mobile-rn/jest.config.js +++ b/apps/mobile-rn/jest.config.js @@ -12,6 +12,7 @@ module.exports = { '^react$': '/node_modules/react', '^react/jsx-runtime$': '/node_modules/react/jsx-runtime.js', '^react/jsx-dev-runtime$': '/node_modules/react/jsx-dev-runtime.js', + '^react-native$': '/node_modules/react-native', '^@react-native-async-storage/async-storage$': '@react-native-async-storage/async-storage/jest/async-storage-mock', '^react-native-file-access$': 'react-native-file-access/jest/mock', diff --git a/apps/mobile-rn/metro.config.js b/apps/mobile-rn/metro.config.js index 0260c61..8f1859f 100644 --- a/apps/mobile-rn/metro.config.js +++ b/apps/mobile-rn/metro.config.js @@ -5,6 +5,14 @@ const projectRoot = __dirname; const monorepoRoot = path.resolve(projectRoot, '../..'); const config = { + transformer: { + getTransformOptions: async () => ({ + transform: { + experimentalImportSupport: false, + inlineRequires: true, + }, + }), + }, watchFolders: [ path.resolve(monorepoRoot, 'packages/core'), path.resolve(monorepoRoot, 'packages/ui-native'), diff --git a/apps/mobile-rn/package-lock.json b/apps/mobile-rn/package-lock.json index e33f8f3..7353e00 100644 --- a/apps/mobile-rn/package-lock.json +++ b/apps/mobile-rn/package-lock.json @@ -19,7 +19,6 @@ "@react-navigation/native": "^7.1.0", "@react-navigation/native-stack": "^7.3.0", "@supabase/supabase-js": "^2.45.0", - "d3ro-voice-monorepo": "file:../..", "react": "19.2.3", "react-native": "^0.85.0", "react-native-file-access": "^4.0.3", @@ -63,7 +62,10 @@ "../..": { "name": "d3ro-voice-monorepo", "version": "1.16.5", + "dev": true, "license": "MIT", + "optional": true, + "peer": true, "workspaces": [ "apps/desktop", "apps/web", @@ -5415,10 +5417,6 @@ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, - "node_modules/d3ro-voice-monorepo": { - "resolved": "../..", - "link": true - }, "node_modules/data-view-buffer": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", diff --git a/apps/mobile-rn/package.json b/apps/mobile-rn/package.json index e9e4649..8617934 100644 --- a/apps/mobile-rn/package.json +++ b/apps/mobile-rn/package.json @@ -24,7 +24,6 @@ "@react-navigation/native": "^7.1.0", "@react-navigation/native-stack": "^7.3.0", "@supabase/supabase-js": "^2.45.0", - "d3ro-voice-monorepo": "file:../..", "react": "19.2.3", "react-native": "^0.85.0", "react-native-file-access": "^4.0.3", diff --git a/apps/mobile-rn/src/components/FreeTierBanner.tsx b/apps/mobile-rn/src/components/FreeTierBanner.tsx index 93deac5..67ee4ba 100644 --- a/apps/mobile-rn/src/components/FreeTierBanner.tsx +++ b/apps/mobile-rn/src/components/FreeTierBanner.tsx @@ -4,6 +4,7 @@ import { BannerAd, BannerAdSize, } from 'react-native-google-mobile-ads' +import { useResponsiveLayout } from '@d3ro/ui-native' import { useMobileAds } from '../lib/mobile-ads-context' import { useMobilePreferences } from '../lib/preferences-context' import { ThemeText } from '../theme/themed-components' @@ -16,10 +17,12 @@ export default function FreeTierBanner(): React.ReactElement | null { const { t } = useI18n() const ads = useMobileAds() const { palette } = useMobilePreferences() + const { bannerSlotMinHeight } = useResponsiveLayout() const [loaded, setLoaded] = useState(false) const [failed, setFailed] = useState(false) const [retryAttempt, setRetryAttempt] = useState(0) const [retryKey, setRetryKey] = useState(0) + const [measuredHeight, setMeasuredHeight] = useState(0) useEffect(() => { setLoaded(false) @@ -28,6 +31,10 @@ export default function FreeTierBanner(): React.ReactElement | null { setRetryKey(0) }, [ads.bannerUnitId]) + useEffect(() => { + setMeasuredHeight(0) + }, [ads.bannerUnitId, ads.eligible, bannerSlotMinHeight]) + useEffect(() => { if (!failed || !ads.bannerUnitId) return undefined const delay = Math.min( @@ -45,11 +52,20 @@ export default function FreeTierBanner(): React.ReactElement | null { if (!ads.eligible) return null + const reservedMinHeight = Math.max(bannerSlotMinHeight, measuredHeight) + return ( { + const nextHeight = Math.round(event.nativeEvent.layout.height) + if (nextHeight > measuredHeight) { + setMeasuredHeight(nextHeight) + } + }} style={[ styles.slot, { + minHeight: reservedMinHeight, backgroundColor: palette.bg.inset, borderTopColor: palette.border.subtle, }, diff --git a/apps/mobile-rn/src/features/actions/action-service.ts b/apps/mobile-rn/src/features/actions/action-service.ts index d97e2f3..3eb4ed7 100644 --- a/apps/mobile-rn/src/features/actions/action-service.ts +++ b/apps/mobile-rn/src/features/actions/action-service.ts @@ -1,3 +1,4 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' import AsyncStorage from '@react-native-async-storage/async-storage' import { SUPABASE_URL } from '@d3ro/core/supabase-config' import { @@ -147,7 +148,6 @@ export interface ActionExecutionOutcome { historyRecorded: boolean } -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 EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ const MAX_INPUT_CHARS = 4_000 const MAX_RATIONALE_CHARS = 300 @@ -171,9 +171,6 @@ Do not invent missing IDs. Use unknown when required data is absent.` let historySequence = 0 let historyQueue: Promise = Promise.resolve() -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function normalizeBoundedString(value: unknown, max: number): string | null { if (typeof value !== 'string') return null @@ -227,7 +224,7 @@ export function parseActionJson(text: string): ParsedMobileAction { const content = normalizeBoundedString(value.args.content, MAX_MEMO_CHARS) if ( meetingId === null - || !UUID_PATTERN.test(meetingId) + || !isUuid(meetingId) || content === null || !hasOnlyKeys(value.args, ['meeting_id', 'content']) ) { @@ -246,7 +243,7 @@ export function parseActionJson(text: string): ParsedMobileAction { const role = value.args.role === undefined ? 'member' : value.args.role if ( teamId === null - || !UUID_PATTERN.test(teamId) + || !isUuid(teamId) || email === null || !EMAIL_PATTERN.test(email) || (role !== 'admin' && role !== 'member') @@ -344,7 +341,7 @@ export async function parseActionCommand( ) } const generationId = response.headers?.get('X-D3RO-Generation-Id')?.trim() ?? '' - if (!UUID_PATTERN.test(generationId)) { + if (!isUuid(generationId)) { throw new ActionServiceError('INVALID_RESPONSE', true) } const snapshot = extractLlmText(body) @@ -367,7 +364,7 @@ export async function parseActionCommand( } function actionHistoryKey(userId: string): string { - if (!UUID_PATTERN.test(userId)) throw new ActionServiceError('AUTH_REQUIRED', false, 401) + if (!isUuid(userId)) throw new ActionServiceError('AUTH_REQUIRED', false, 401) return `${HISTORY_KEY_PREFIX}.${userId}` } @@ -598,7 +595,7 @@ async function performAllowedAction(options: ExecuteActionOptions): Promise { - if (!UUID_PATTERN.test(options.userId) || options.accessToken.trim().length === 0) { + if (!isUuid(options.userId) || options.accessToken.trim().length === 0) { throw new ActionServiceError('AUTH_REQUIRED', false, 401) } const input = normalizeActionInput(options.input) diff --git a/apps/mobile-rn/src/features/admin/admin-service.ts b/apps/mobile-rn/src/features/admin/admin-service.ts index 83c0904..ad9e53d 100644 --- a/apps/mobile-rn/src/features/admin/admin-service.ts +++ b/apps/mobile-rn/src/features/admin/admin-service.ts @@ -1,4 +1,12 @@ +import { isUuid } from '@d3ro/core/guards' import { SUPABASE_ANON_KEY, SUPABASE_URL } from '@d3ro/core/supabase-config' +import { + assertRecordWith, + parseBoundedStringWith, + parseIsoTimestampWith, + parseSafeIntegerWith, + parseUuidWith, +} from '../shared/service-guards' export const ADMIN_ROLES = ['user', 'manager', 'admin', 'super_admin'] as const export const ADMIN_TIERS = ['free', 'pro', 'pro_plus'] as const @@ -130,7 +138,6 @@ interface RequestOptions { signal?: AbortSignal } -const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ const MAX_RESPONSE_BYTES = 1024 * 1024 const REQUEST_TIMEOUT_MS = 20_000 @@ -139,10 +146,7 @@ const TIER_SET = new Set(ADMIN_TIERS) const STATUS_SET = new Set(ADMIN_SUBSCRIPTION_STATUSES) function recordValue(value: unknown): Record { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { - throw invalidResponse() - } - return value as Record + return assertRecordWith(value, invalidResponse) } function assertOnlyKeys(value: Record, allowed: readonly string[]): void { @@ -151,8 +155,7 @@ function assertOnlyKeys(value: Record, allowed: readonly string } function requiredString(value: unknown, maximum = 2048): string { - if (typeof value !== 'string' || value.length < 1 || value.length > maximum) throw invalidResponse() - return value + return parseBoundedStringWith(value, invalidResponse, { maxLength: maximum }) } function nullableString(value: unknown, maximum = 4096): string | null { @@ -161,15 +164,11 @@ function nullableString(value: unknown, maximum = 4096): string | null { } function uuid(value: unknown): string { - const normalized = requiredString(value, 36) - if (!UUID_PATTERN.test(normalized)) throw invalidResponse() - return normalized.toLowerCase() + return parseUuidWith(requiredString(value, 36), invalidResponse) } function isoDateTime(value: unknown): string { - const normalized = requiredString(value, 40) - if (!Number.isFinite(Date.parse(normalized))) throw invalidResponse() - return normalized + return parseIsoTimestampWith(requiredString(value, 40), invalidResponse, { maxLength: 40 }) } function nullableIsoDateTime(value: unknown): string | null { @@ -177,13 +176,11 @@ function nullableIsoDateTime(value: unknown): string | null { } function nonNegativeInteger(value: unknown, maximum = 1_000_000): number { - if (!Number.isSafeInteger(value) || Number(value) < 0 || Number(value) > maximum) throw invalidResponse() - return Number(value) + return parseSafeIntegerWith(value, invalidResponse, { min: 0, max: maximum }) } function positiveInteger(value: unknown, maximum = Number.MAX_SAFE_INTEGER): number { - if (!Number.isSafeInteger(value) || Number(value) < 1 || Number(value) > maximum) throw invalidResponse() - return Number(value) + return parseSafeIntegerWith(value, invalidResponse, { min: 1, max: maximum }) } function role(value: unknown): AdminRole { @@ -517,7 +514,7 @@ export async function getAdminUser( userId: string, signal?: AbortSignal, ): Promise { - if (!UUID_PATTERN.test(userId)) throw new AdminServiceError('validation', null, false) + if (!isUuid(userId)) throw new AdminServiceError('validation', null, false) const payload = await requestAdmin(`admin-users${queryString({ userId })}`, { accessToken, signal }) const body = recordValue(payload) assertOnlyKeys(body, ['profile', 'subscription', 'account']) @@ -566,7 +563,7 @@ export async function listAdminAudit(options: { const page = options.page ?? 1 const limit = options.limit ?? 20 validatedPage(page, limit) - if (options.targetId !== undefined && !UUID_PATTERN.test(options.targetId)) { + if (options.targetId !== undefined && !isUuid(options.targetId)) { throw new AdminServiceError('validation', null, false) } const payload = await requestAdmin(`admin-audit-log${queryString({ @@ -583,7 +580,7 @@ export async function getAdminPaymentHistory( userId: string, signal?: AbortSignal, ): Promise { - if (!UUID_PATTERN.test(userId)) throw new AdminServiceError('validation', null, false) + if (!isUuid(userId)) throw new AdminServiceError('validation', null, false) const payload = await requestAdmin(`admin-payments${queryString({ userId, source: 'db' })}`, { accessToken, signal, @@ -609,7 +606,7 @@ export async function getAdminPaymentHistory( } function validatedIdempotencyKey(value: string): string { - if (!UUID_PATTERN.test(value)) throw new AdminServiceError('validation', null, false) + if (!isUuid(value)) throw new AdminServiceError('validation', null, false) return value.toLowerCase() } @@ -627,7 +624,7 @@ export async function changeAdminUserRole(options: { memo: string signal?: AbortSignal }): Promise<{ userId: string; newRole: AdminRole }> { - if (!UUID_PATTERN.test(options.userId) || !ROLE_SET.has(options.newRole)) { + if (!isUuid(options.userId) || !ROLE_SET.has(options.newRole)) { throw new AdminServiceError('validation', null, false) } const idempotencyKey = validatedIdempotencyKey(options.idempotencyKey) @@ -697,7 +694,7 @@ async function mutateAdminSubscription( signal?: AbortSignal }, ): Promise { - if (!UUID_PATTERN.test(options.userId)) throw new AdminServiceError('validation', null, false) + if (!isUuid(options.userId)) throw new AdminServiceError('validation', null, false) const idempotencyKey = validatedIdempotencyKey(options.idempotencyKey) const body = action === 'delete' ? { memo: validatedMemo(options.mutation.memo) } diff --git a/apps/mobile-rn/src/features/audio/linked-audio-cleanup.ts b/apps/mobile-rn/src/features/audio/linked-audio-cleanup.ts index 65d0c11..7acfe57 100644 --- a/apps/mobile-rn/src/features/audio/linked-audio-cleanup.ts +++ b/apps/mobile-rn/src/features/audio/linked-audio-cleanup.ts @@ -1,5 +1,6 @@ -import type { AudioFileUploadStatus, D3roSupabaseClient } from '@d3ro/api-client' +import type { AudioFileUploadStatus } from '@d3ro/api-client' import { supabase } from '../../lib/supabase' +import { getTypedSupabaseClient } from '../shared/service-guards' /** * 기록·회의를 지울 때 거기에 연결된 원본 음성(audio 버킷 객체 + audio_files 행)을 함께 정리한다. @@ -130,10 +131,6 @@ export async function purgeUnlinkedAudio( return result } -function database(): D3roSupabaseClient { - return supabase as unknown as D3roSupabaseClient -} - const AUDIO_BUCKET = 'audio' function toRefs(rows: ReadonlyArray<{ id: string; storage_key: string; upload_status: AudioFileUploadStatus }> | null): LinkedAudioRef[] { @@ -148,7 +145,7 @@ function toRefs(rows: ReadonlyArray<{ id: string; storage_key: string; upload_st export function createSupabaseLinkedAudioStore(): LinkedAudioStore { return { async findLinked(userId, column, ownerId) { - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('audio_files') .select('id, storage_key, upload_status') .eq('user_id', userId) @@ -158,7 +155,7 @@ export function createSupabaseLinkedAudioStore(): LinkedAudioStore { return toRefs(data) }, async claimUnlinked(userId, ids) { - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('audio_files') .update({ upload_status: 'deleted' }) .eq('user_id', userId) @@ -172,7 +169,7 @@ export function createSupabaseLinkedAudioStore(): LinkedAudioStore { }, async findReferencedKeys(userId, keys, excludeIds) { if (keys.length === 0) return [] - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('audio_files') .select('id, storage_key') .eq('user_id', userId) @@ -189,7 +186,7 @@ export function createSupabaseLinkedAudioStore(): LinkedAudioStore { if (error !== null) throw error }, async deleteRows(userId, ids) { - const { error } = await database() + const { error } = await getTypedSupabaseClient() .from('audio_files') .delete() .eq('user_id', userId) @@ -198,7 +195,7 @@ export function createSupabaseLinkedAudioStore(): LinkedAudioStore { if (error !== null) throw error }, async restoreStatus(userId, id, status) { - const { error } = await database() + const { error } = await getTypedSupabaseClient() .from('audio_files') .update({ upload_status: status }) .eq('user_id', userId) diff --git a/apps/mobile-rn/src/features/chat/chat-service.ts b/apps/mobile-rn/src/features/chat/chat-service.ts index a973f29..9cf92c2 100644 --- a/apps/mobile-rn/src/features/chat/chat-service.ts +++ b/apps/mobile-rn/src/features/chat/chat-service.ts @@ -1,3 +1,4 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' import { SUPABASE_URL } from '@d3ro/core/supabase-config' export type ChatRole = 'user' | 'assistant' @@ -44,11 +45,7 @@ export interface ReportableChatResult { const MAX_MESSAGES = 40 const MAX_MESSAGE_CHARS = 8_000 -const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} export function normalizeChatMessages(messages: ChatRequestMessage[]): ChatRequestMessage[] { if (messages.length === 0 || messages.length > MAX_MESSAGES) { @@ -135,7 +132,7 @@ async function sendChatRequest( : response.headers?.get('X-D3RO-Generation-Id')?.trim() ?? '' if ( generationPurpose !== null - && (typeof generationId !== 'string' || !UUID_PATTERN.test(generationId)) + && (typeof generationId !== 'string' || !isUuid(generationId)) ) { throw new ChatServiceError('INVALID_RESPONSE', true) } diff --git a/apps/mobile-rn/src/features/commands/command-service.ts b/apps/mobile-rn/src/features/commands/command-service.ts index 04dfeb7..7e0dbad 100644 --- a/apps/mobile-rn/src/features/commands/command-service.ts +++ b/apps/mobile-rn/src/features/commands/command-service.ts @@ -1,3 +1,4 @@ +import { isUuid } from '@d3ro/core/guards' import { ChatServiceError, sendReportableCommandMessage, @@ -5,6 +6,11 @@ import { type ReportableChatResult, } from '../chat/chat-service' import { supabase } from '../../lib/supabase' +import { + assertRecordWith, + createUuidAssert, + parseIsoTimestampWith, +} from '../shared/service-guards' export type BuiltinCommandId = | 'builtin-translate-en' @@ -170,23 +176,20 @@ const COMMAND_COLUMNS = [ 'id', 'user_id', 'builtin_key', 'name', 'description', 'prompt', 'icon', 'sort_order', 'revision', 'created_at', 'updated_at', ].join(',') -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 BUILTIN_KEYS = new Set([ 'translate_en', 'summarize', 'formal', 'explain_code', ]) function record(value: unknown): Record { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { - throw new CommandSyncError('server') - } - return value as Record + return assertRecordWith(value, () => new CommandSyncError('server')) } function timestamp(value: unknown): string { - if (typeof value !== 'string' || !Number.isFinite(Date.parse(value))) { - throw new CommandSyncError('server') - } - return new Date(value).toISOString() + return parseIsoTimestampWith( + value, + () => new CommandSyncError('server'), + { normalizeToIso: true }, + ) } export function normalizeSyncedCommand(value: unknown, expectedUserId?: string): SyncedCommand { @@ -197,10 +200,8 @@ export function normalizeSyncedCommand(value: unknown, expectedUserId?: string): ? row.builtin_key as CommandBuiltinKey : undefined if ( - typeof row.id !== 'string' - || !UUID_PATTERN.test(row.id) - || typeof row.user_id !== 'string' - || !UUID_PATTERN.test(row.user_id) + !isUuid(row.id) + || !isUuid(row.user_id) || (expectedUserId !== undefined && row.user_id !== expectedUserId) || builtinKey === undefined || typeof row.name !== 'string' @@ -237,9 +238,7 @@ export function normalizeSyncedCommand(value: unknown, expectedUserId?: string): } } -function requireUserId(userId: string): void { - if (!UUID_PATTERN.test(userId)) throw new CommandSyncError('auth') -} +const requireUserId = createUuidAssert(() => new CommandSyncError('auth')) function validateCustomFields(input: { name: string @@ -279,7 +278,7 @@ export async function loadSyncedCommandCatalog(userId: string): Promise { requireUserId(userId) - if (instructionId !== null && !UUID_PATTERN.test(instructionId)) { + if (instructionId !== null && !isUuid(instructionId)) { throw new CommandSyncError('validation') } const result = await supabase.rpc('set_active_custom_instruction', { @@ -374,7 +373,7 @@ export async function setActiveSyncedCommand( const row = record(result.data) if (row.user_id !== userId) throw new CommandSyncError('auth') const active = row.active_instruction_id - if (active !== null && (typeof active !== 'string' || !UUID_PATTERN.test(active))) { + if (active !== null && (typeof active !== 'string' || !isUuid(active))) { throw new CommandSyncError('server') } return active diff --git a/apps/mobile-rn/src/features/dashboard/dashboard-service.ts b/apps/mobile-rn/src/features/dashboard/dashboard-service.ts index 91ad7cf..db160d7 100644 --- a/apps/mobile-rn/src/features/dashboard/dashboard-service.ts +++ b/apps/mobile-rn/src/features/dashboard/dashboard-service.ts @@ -1,4 +1,6 @@ +import { isRecord } from '@d3ro/core/guards' import { supabase } from '../../lib/supabase' +import { requireUuidWith } from '../shared/service-guards' export interface DashboardRecentEntry { id: string @@ -28,9 +30,6 @@ export class DashboardServiceError extends Error { } } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function nonNegativeNumber(value: unknown): number | null { const numeric = typeof value === 'number' ? value : Number(value) @@ -104,9 +103,7 @@ export function normalizeDashboardStats(value: unknown): MobileDashboardStats { } export async function loadDashboardStats(userId: string): Promise { - if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(userId)) { - throw new DashboardServiceError('auth') - } + requireUuidWith(userId, () => new DashboardServiceError('auth')) const { data, error } = await supabase.rpc('mobile_dashboard_stats') if (error) throw new DashboardServiceError('server') return normalizeDashboardStats(data) diff --git a/apps/mobile-rn/src/features/data-portability/account-portability-service.ts b/apps/mobile-rn/src/features/data-portability/account-portability-service.ts index 4d0e335..85c7ac2 100644 --- a/apps/mobile-rn/src/features/data-portability/account-portability-service.ts +++ b/apps/mobile-rn/src/features/data-portability/account-portability-service.ts @@ -7,6 +7,7 @@ import { import { parseImportedPortableFile } from './legacy-import'; import { parsePortableArchive } from './portability-schema'; import { PortabilityError, toPortabilityError } from './portability-error'; +import { createUuidAssert } from '../shared/service-guards'; import type { PortableArchive, PortablePayload, @@ -36,15 +37,9 @@ export interface AccountImportResult { detectedFormat: string; } -function requireUserId(userId: string): void { - if ( - !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test( - userId, - ) - ) { - throw new PortabilityError('auth', 'A valid signed-in account is required'); - } -} +const requireUserId = createUuidAssert( + () => new PortabilityError('auth', 'A valid signed-in account is required'), +); async function assertCurrentUser( client: SupabaseClient, diff --git a/apps/mobile-rn/src/features/data-portability/data-file-picker.ts b/apps/mobile-rn/src/features/data-portability/data-file-picker.ts index 18f3510..be76795 100644 --- a/apps/mobile-rn/src/features/data-portability/data-file-picker.ts +++ b/apps/mobile-rn/src/features/data-portability/data-file-picker.ts @@ -5,7 +5,11 @@ import { pick, types, } from '@react-native-documents/picker'; -import { Dirs, FileSystem } from 'react-native-file-access'; +import { FileSystem } from 'react-native-file-access'; +import { + localPathFromCacheUri, + removeOwnedCacheFile, +} from '../shared/owned-cache-files'; import { PortabilityError } from './portability-error'; import { PORTABILITY_MAX_BYTES } from './portability-types'; @@ -28,32 +32,17 @@ const ALLOWED_MIME_TYPES = new Set([ '', ]); -function localPathFromUri(uri: string): string { - if (!uri.startsWith('file://')) return uri; - const path = decodeURIComponent(uri.slice('file://'.length)); - return path.startsWith('/') ? path : `/${path}`; -} - -function isOwnedCachePath(path: string): boolean { - const root = Dirs.CacheDir.replace(/\\/g, '/').replace(/\/$/, ''); - const normalized = path.replace(/\\/g, '/'); - return ( - normalized.startsWith(`${root}/`) && - !normalized - .slice(root.length + 1) - .split('/') - .includes('..') - ); -} +const localPathFromUri = localPathFromCacheUri; async function removeOwnedCopy(path: string): Promise { - if (!isOwnedCachePath(path)) { - throw new PortabilityError( - 'file-read', - 'Refusing to remove a file outside the import cache', - ); - } - if (await FileSystem.exists(path)) await FileSystem.unlink(path); + await removeOwnedCacheFile( + path, + () => + new PortabilityError( + 'file-read', + 'Refusing to remove a file outside the import cache', + ), + ); } function validateMetadata( diff --git a/apps/mobile-rn/src/features/data-portability/legacy-import.ts b/apps/mobile-rn/src/features/data-portability/legacy-import.ts index 157ab7e..8e2ecd2 100644 --- a/apps/mobile-rn/src/features/data-portability/legacy-import.ts +++ b/apps/mobile-rn/src/features/data-portability/legacy-import.ts @@ -1,3 +1,5 @@ +import { isUuid } from '@d3ro/core/guards'; +import { assertRecordWith, requireUuidWith } from '../shared/service-guards'; import { createPortableArchive, sha256Hex, @@ -22,9 +24,6 @@ import { type PortablePayload, } from './portability-types'; -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; - export interface ImportedPortableFile { archive: PortableArchive; payload: PortablePayload; @@ -47,10 +46,10 @@ interface LegacyContext { type UnknownRecord = Record; function record(value: unknown, label: string): UnknownRecord { - if (value === null || typeof value !== 'object' || Array.isArray(value)) { - throw new PortabilityError('format', `${label} must be an object`); - } - return value as UnknownRecord; + return assertRecordWith( + value, + () => new PortabilityError('format', `${label} must be an object`), + ); } function deterministicUuid( @@ -77,7 +76,7 @@ function legacyId( namespace: string, identity: string, ): string { - if (typeof value === 'string' && UUID_PATTERN.test(value)) + if (isUuid(value)) return value.toLowerCase(); return deterministicUuid(context.ownerId, namespace, identity); } @@ -643,8 +642,10 @@ export function parseImportedPortableFile( ownerId: string, now = new Date().toISOString(), ): ImportedPortableFile { - if (!UUID_PATTERN.test(ownerId)) - throw new PortabilityError('auth', 'A valid signed-in account is required'); + requireUuidWith( + ownerId, + () => new PortabilityError('auth', 'A valid signed-in account is required'), + ); if ( utf8ByteLength(raw) === 0 || utf8ByteLength(raw) > PORTABILITY_MAX_BYTES + 128 * 1024 diff --git a/apps/mobile-rn/src/features/data-portability/meeting-export.ts b/apps/mobile-rn/src/features/data-portability/meeting-export.ts index 7f0e5fb..dc7408b 100644 --- a/apps/mobile-rn/src/features/data-portability/meeting-export.ts +++ b/apps/mobile-rn/src/features/data-portability/meeting-export.ts @@ -1,3 +1,4 @@ +import { formatDurationClockFromMs } from '@d3ro/core/format'; import type { Meeting, MeetingDocument, @@ -24,18 +25,10 @@ function formatDuration(milliseconds: number | null): string { } function formatElapsed(milliseconds: number): string { - const seconds = Math.max(0, Math.floor(milliseconds / 1_000)); - const hours = Math.floor(seconds / 3_600); - const minutes = Math.floor((seconds % 3_600) / 60); - const remainder = seconds % 60; - return hours > 0 - ? `${hours}:${String(minutes).padStart(2, '0')}:${String( - remainder, - ).padStart(2, '0')}` - : `${String(minutes).padStart(2, '0')}:${String(remainder).padStart( - 2, - '0', - )}`; + return formatDurationClockFromMs(milliseconds, { + padMinutes: true, + showHours: true, + }); } function escapeMarkdownTable(value: string): string { diff --git a/apps/mobile-rn/src/features/data-portability/portability-schema.ts b/apps/mobile-rn/src/features/data-portability/portability-schema.ts index 5bf40cc..3ef5cce 100644 --- a/apps/mobile-rn/src/features/data-portability/portability-schema.ts +++ b/apps/mobile-rn/src/features/data-portability/portability-schema.ts @@ -1,3 +1,9 @@ +import { + assertRecordWith, + parseBoundedStringWith, + parseIsoTimestampWith, + parseUuidWith, +} from '../shared/service-guards' import { createPortableArchive, utf8ByteLength } from './canonical-json'; import { PortabilityError } from './portability-error'; import { @@ -23,8 +29,6 @@ import { type PortabilitySource, } from './portability-types'; -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 CHECKSUM_PATTERN = /^[0-9a-f]{64}$/; const ARCHIVE_MAX_BYTES = PORTABILITY_MAX_BYTES + 128 * 1024; @@ -35,14 +39,15 @@ function fail(message: string): never { } function record(value: unknown, label: string): UnknownRecord { - if (value === null || typeof value !== 'object' || Array.isArray(value)) { - return fail(`${label} must be an object`); - } - const prototype = Object.getPrototypeOf(value); + const parsed = assertRecordWith( + value, + () => new PortabilityError('format', `${label} must be an object`), + ); + const prototype = Object.getPrototypeOf(parsed); if (prototype !== Object.prototype && prototype !== null) { return fail(`${label} has an unsupported prototype`); } - return value as UnknownRecord; + return parsed; } function exactKeys( @@ -66,16 +71,15 @@ function stringValue( maxLength: number, allowEmpty = false, ): string { - if ( - typeof value !== 'string' || - (!allowEmpty && value.length === 0) || - value.length > maxLength - ) { - return fail( - `${label} must be ${allowEmpty ? '0' : '1'}-${maxLength} characters`, - ); - } - return value; + return parseBoundedStringWith( + value, + () => + new PortabilityError( + 'format', + `${label} must be ${allowEmpty ? '0' : '1'}-${maxLength} characters`, + ), + { minLength: allowEmpty ? 0 : 1, maxLength }, + ); } function nullableString( @@ -88,21 +92,19 @@ function nullableString( } function uuid(value: unknown, label: string): string { - if (typeof value !== 'string' || !UUID_PATTERN.test(value)) { - return fail(`${label} must be a UUID`); - } - return value.toLowerCase(); + return parseUuidWith( + value, + () => new PortabilityError('format', `${label} must be a UUID`), + ); } function timestamp(value: unknown, label: string): string { const parsed = stringValue(value, label, 40); - if ( - !/^\d{4}-\d{2}-\d{2}T/.test(parsed) || - !Number.isFinite(Date.parse(parsed)) - ) { - return fail(`${label} must be an ISO-8601 timestamp`); - } - return parsed; + return parseIsoTimestampWith( + parsed, + () => new PortabilityError('format', `${label} must be an ISO-8601 timestamp`), + { requireTimePrefix: true }, + ); } function nullableTimestamp(value: unknown, label: string): string | null { diff --git a/apps/mobile-rn/src/features/data-portability/portable-text.ts b/apps/mobile-rn/src/features/data-portability/portable-text.ts index 8dbdda6..60f43fe 100644 --- a/apps/mobile-rn/src/features/data-portability/portable-text.ts +++ b/apps/mobile-rn/src/features/data-portability/portable-text.ts @@ -1,3 +1,4 @@ +import { csvCell as coreCsvCell } from '@d3ro/core/csv'; import { PortabilityError } from './portability-error'; import type { PortableDictionaryRow, @@ -5,14 +6,8 @@ import type { PortablePayload, } from './portability-types'; -const DANGEROUS_CSV_PREFIX = /^[=+\-@]/; - -function csvCell(value: unknown): string { - if (value === null || value === undefined) return ''; - let text = String(value); - if (DANGEROUS_CSV_PREFIX.test(text)) text = `'${text}`; - return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text; -} +const formatPortableCsvCell = (value: unknown): string => + coreCsvCell(value, { prefixFormulaWithApostrophe: true }); export function parseCsv( input: string, @@ -113,7 +108,7 @@ export function buildDictionaryCsv(rows: PortableDictionaryRow[]): string { row.created_at, row.updated_at, ] - .map(csvCell) + .map(formatPortableCsvCell) .join(','), ); return `\uFEFF${header.join(',')}\r\n${body.join('\r\n')}\r\n`; @@ -159,7 +154,7 @@ export function buildHistoryCsv(rows: PortableHistoryRow[]): string { row.created_at, row.updated_at, ] - .map(csvCell) + .map(formatPortableCsvCell) .join(','), ); return `\uFEFF${header.join(',')}\r\n${body.join('\r\n')}\r\n`; diff --git a/apps/mobile-rn/src/features/devices/device-service.ts b/apps/mobile-rn/src/features/devices/device-service.ts index b05d8fa..ed7e9ac 100644 --- a/apps/mobile-rn/src/features/devices/device-service.ts +++ b/apps/mobile-rn/src/features/devices/device-service.ts @@ -1,5 +1,7 @@ +import { isRecord } from '@d3ro/core/guards' import type { MobileRuntimeConfig } from '../../lib/native-config' import { supabase } from '../../lib/supabase' +import { createUuidAssert } from '../shared/service-guards' /** 서버 devices.platform CHECK 목록과 같다. 데스크톱(windows/macos)도 같은 계정의 기기로 등록된다. */ export const DEVICE_PLATFORMS = ['android', 'ios', 'web', 'windows', 'macos'] as const @@ -31,9 +33,6 @@ export class DeviceServiceError extends Error { } } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function iso(value: unknown): string | null { return typeof value === 'string' && Number.isFinite(Date.parse(value)) @@ -78,11 +77,7 @@ export function normalizeRegisteredDevice(value: unknown): RegisteredDevice { } } -function requireUserId(userId: string): void { - if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(userId)) { - throw new DeviceServiceError('auth') - } -} +const requireUserId = createUuidAssert(() => new DeviceServiceError('auth')) const DEVICE_COLUMNS = [ 'id', 'user_id', 'installation_id', 'platform', 'device_name', 'app_version', diff --git a/apps/mobile-rn/src/features/dictionary/dictionary-service.ts b/apps/mobile-rn/src/features/dictionary/dictionary-service.ts index 9165299..fcb6d28 100644 --- a/apps/mobile-rn/src/features/dictionary/dictionary-service.ts +++ b/apps/mobile-rn/src/features/dictionary/dictionary-service.ts @@ -1,6 +1,14 @@ import type { RealtimeChannel } from '@supabase/supabase-js' -import type { D3roSupabaseClient, DictionaryEntry } from '@d3ro/api-client' +import type { DictionaryEntry } from '@d3ro/api-client' +import { escapeLikePattern } from '@d3ro/core/guards' import { supabase } from '../../lib/supabase' +import { + createLabeledUuidAssert, + extractSupabaseErrorInfo, + getTypedSupabaseClient, + isSupabaseAuthFailure, + isSupabaseNetworkFailure, +} from '../shared/service-guards' export type DictionaryCategory = DictionaryEntry['category'] @@ -58,18 +66,11 @@ const DEFAULT_PAGE_SIZE = 30 const MAX_PAGE_SIZE = 50 const MAX_WORD_LENGTH = 120 const MAX_PRONUNCIATION_LENGTH = 200 -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 CATEGORIES: readonly DictionaryCategory[] = ['user', 'technical', 'auto'] -function client(): D3roSupabaseClient { - return supabase as unknown as D3roSupabaseClient -} - -function requireUuid(value: string, label: string): void { - if (!UUID_PATTERN.test(value)) { - throw new DictionaryServiceError('auth', `A valid ${label} is required`) - } -} +const requireUuid = createLabeledUuidAssert( + (label) => new DictionaryServiceError('auth', `A valid ${label} is required`), +) function assertOwnedEntry(userId: string, entry: DictionaryEntry): void { requireUuid(userId, 'authenticated user') @@ -121,27 +122,16 @@ export function normalizeDictionaryDraft( function dictionaryError(error: unknown): DictionaryServiceError { if (error instanceof DictionaryServiceError) return error - const candidate = error as { code?: unknown; message?: unknown } - const code = typeof candidate?.code === 'string' ? candidate.code : '' - const message = typeof candidate?.message === 'string' - ? candidate.message - : 'Dictionary request failed' - const lower = message.toLowerCase() - - if (code === '23505') return new DictionaryServiceError('duplicate', message) - if ( - error instanceof TypeError - || lower.includes('network request failed') - || lower.includes('failed to fetch') - || lower.includes('networkerror') - ) { - return new DictionaryServiceError('network', message) + const info = extractSupabaseErrorInfo(error, 'Dictionary request failed') + if (info.code === '23505') return new DictionaryServiceError('duplicate', info.message) + if (isSupabaseNetworkFailure(error, info)) { + return new DictionaryServiceError('network', info.message) } - if (code === 'PGRST301' || code === '42501' || lower.includes('jwt')) { - return new DictionaryServiceError('auth', message) + if (isSupabaseAuthFailure(info, { include42501: true })) { + return new DictionaryServiceError('auth', info.message) } - if (code.startsWith('22')) return new DictionaryServiceError('validation', message) - return new DictionaryServiceError('server', message) + if (info.code.startsWith('22')) return new DictionaryServiceError('validation', info.message) + return new DictionaryServiceError('server', info.message) } function validateCursor(cursor: DictionaryCursor): void { @@ -151,16 +141,12 @@ function validateCursor(cursor: DictionaryCursor): void { } } -function escapeLikePattern(value: string): string { - return value.replace(/[\\%_]/g, (character) => `\\${character}`) -} - async function findDuplicate( userId: string, draft: NormalizedDictionaryDraft, excludingId?: string, ): Promise | null> { - let query = client() + let query = getTypedSupabaseClient() .from('dictionary') .select('id') .eq('user_id', userId) @@ -199,7 +185,7 @@ export async function listDictionaryPage( if (options.cursor !== null && options.cursor !== undefined) validateCursor(options.cursor) try { - let query = client() + let query = getTypedSupabaseClient() .from('dictionary') .select('*', { count: 'exact' }) .eq('user_id', options.userId) @@ -250,7 +236,7 @@ export async function createDictionaryEntry( throw new DictionaryServiceError('duplicate', 'This word already exists in the category') } - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('dictionary') .insert({ user_id: userId, @@ -281,7 +267,7 @@ export async function updateDictionaryEntry( throw new DictionaryServiceError('duplicate', 'This word already exists in the category') } - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('dictionary') .update({ word: normalized.word, @@ -315,7 +301,7 @@ export async function deleteDictionaryEntry( assertOwnedEntry(userId, current) try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('dictionary') .delete() .eq('user_id', userId) @@ -347,7 +333,7 @@ export async function getDictionaryPromptHints( const limit = Math.min(requestedLimit, 50) try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('dictionary') .select('word') .eq('user_id', userId) diff --git a/apps/mobile-rn/src/features/history/history-cache.ts b/apps/mobile-rn/src/features/history/history-cache.ts index 2c8a29c..e5702cd 100644 --- a/apps/mobile-rn/src/features/history/history-cache.ts +++ b/apps/mobile-rn/src/features/history/history-cache.ts @@ -1,3 +1,4 @@ +import { isRecord } from '@d3ro/core/guards' import { Platform } from 'react-native' import * as Keychain from 'react-native-keychain' import type { HistoryListEntry, HistoryFilter } from './history-service' @@ -23,9 +24,6 @@ function cacheService(userId: string): string { return `${CACHE_SERVICE_PREFIX}${userId}` } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} function isNullableString(value: unknown): value is string | null { return value === null || typeof value === 'string' diff --git a/apps/mobile-rn/src/features/history/history-service.ts b/apps/mobile-rn/src/features/history/history-service.ts index 96f107e..d713c8f 100644 --- a/apps/mobile-rn/src/features/history/history-service.ts +++ b/apps/mobile-rn/src/features/history/history-service.ts @@ -1,13 +1,19 @@ import type { RealtimeChannel } from '@supabase/supabase-js' import type { AudioFile, - D3roSupabaseClient, HistoryEntry, HistoryMode, HistoryStatus, ProcessingJob, } from '@d3ro/api-client' import { supabase } from '../../lib/supabase' +import { + createUuidAssert, + extractSupabaseErrorInfo, + getTypedSupabaseClient, + isSupabaseAuthFailure, + isSupabaseNetworkFailure, +} from '../shared/service-guards' import { createSupabaseLinkedAudioStore, purgeUnlinkedAudio, @@ -70,15 +76,9 @@ const PAGE_SIZE = 20 const MAX_PAGE_SIZE = 50 const ACTIVE_JOB_STATUSES = ['queued', 'running'] as const -function client(): D3roSupabaseClient { - return supabase as unknown as D3roSupabaseClient -} - -function requireUserId(userId: string): void { - if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(userId)) { - throw new HistoryServiceError('auth', 'A valid authenticated user is required') - } -} +const requireUserId = createUuidAssert( + () => new HistoryServiceError('auth', 'A valid authenticated user is required'), +) export function sanitizeHistorySearch(value: string): string { return value @@ -91,28 +91,18 @@ export function sanitizeHistorySearch(value: string): string { function historyError(error: unknown): HistoryServiceError { if (error instanceof HistoryServiceError) return error - - const candidate = error as { code?: unknown; message?: unknown } - const code = typeof candidate?.code === 'string' ? candidate.code : '' - const message = typeof candidate?.message === 'string' ? candidate.message : 'History request failed' - const lower = message.toLowerCase() - - if ( - error instanceof TypeError - || lower.includes('network request failed') - || lower.includes('failed to fetch') - || lower.includes('networkerror') - ) { - return new HistoryServiceError('network', message) + const info = extractSupabaseErrorInfo(error, 'History request failed') + if (isSupabaseNetworkFailure(error, info)) { + return new HistoryServiceError('network', info.message) } - if (code === 'PGRST301' || code === '42501' || lower.includes('jwt')) { - return new HistoryServiceError('auth', message) + if (isSupabaseAuthFailure(info, { include42501: true })) { + return new HistoryServiceError('auth', info.message) } - return new HistoryServiceError('server', message) + return new HistoryServiceError('server', info.message) } async function activeHistoryIds(userId: string): Promise { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('processing_jobs') .select('history_id') .eq('user_id', userId) @@ -134,7 +124,7 @@ async function activeJobsByHistory( ): Promise> { if (historyIds.length === 0) return new Map() - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('processing_jobs') .select('id, history_id, status, progress, created_at') .eq('user_id', userId) @@ -170,7 +160,7 @@ export async function listHistoryPage( if (processingIds.length === 0) return { entries: [], nextCursor: null } } - let query = client() + let query = getTypedSupabaseClient() .from('history') .select('*') .eq('user_id', options.userId) @@ -227,7 +217,7 @@ export async function getHistoryDetail( if (historyId.length === 0) throw new HistoryServiceError('validation', 'History id is required') try { - const { data: entry, error: entryError } = await client() + const { data: entry, error: entryError } = await getTypedSupabaseClient() .from('history') .select('*') .eq('user_id', userId) @@ -238,14 +228,14 @@ export async function getHistoryDetail( if (entry === null) throw new HistoryServiceError('not-found', 'History entry was not found') const [audioResult, jobResult] = await Promise.all([ - client() + getTypedSupabaseClient() .from('audio_files') .select('*') .eq('user_id', userId) .eq('history_id', historyId) .neq('upload_status', 'deleted') .order('created_at', { ascending: false }), - client() + getTypedSupabaseClient() .from('processing_jobs') .select('*') .eq('user_id', userId) @@ -288,7 +278,7 @@ export async function updateHistoryRevisionSafe( } try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('history') .update({ ...patch, @@ -337,7 +327,7 @@ export async function deleteHistoryRevisionSafe( } try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('history') .delete() .eq('user_id', userId) diff --git a/apps/mobile-rn/src/features/import/abort-guard.ts b/apps/mobile-rn/src/features/import/abort-guard.ts new file mode 100644 index 0000000..1a077f1 --- /dev/null +++ b/apps/mobile-rn/src/features/import/abort-guard.ts @@ -0,0 +1,13 @@ +import { AudioPipelineError } from './audio-import-types'; + +/** + * Aborts an in-flight import/transcription step when the caller cancels `signal`. + */ +export function throwIfPipelineCancelled( + signal: AbortSignal, + message = 'Audio processing was cancelled', +): void { + if (signal.aborted) { + throw new AudioPipelineError('cancelled', message); + } +} diff --git a/apps/mobile-rn/src/features/import/android-audio-decoder.ts b/apps/mobile-rn/src/features/import/android-audio-decoder.ts index 8e3f8c8..d78a9de 100644 --- a/apps/mobile-rn/src/features/import/android-audio-decoder.ts +++ b/apps/mobile-rn/src/features/import/android-audio-decoder.ts @@ -1,10 +1,14 @@ import { NativeModules, Platform } from 'react-native'; -import { Dirs, FileSystem } from 'react-native-file-access'; +import { FileSystem } from 'react-native-file-access'; import { AudioPipelineError, type LocalAudioInput, } from './audio-import-types'; import { createUuidV4 } from '../../lib/random-id'; +import { + isOwnedCachePath, + removeOwnedCacheFile, +} from '../shared/owned-cache-files'; interface NativeDecodedAudio { path: string; @@ -62,34 +66,27 @@ function nativeErrorCode(error: unknown): string | null { } function ownedCachePath(path: string): boolean { - const roots = [Dirs.CacheDir]; - if (Dirs.CacheDir.startsWith('/data/data/')) { - roots.push(`/data/user/0/${Dirs.CacheDir.slice('/data/data/'.length)}`); - } else if (Dirs.CacheDir.startsWith('/data/user/0/')) { - roots.push(`/data/data/${Dirs.CacheDir.slice('/data/user/0/'.length)}`); - } - return roots.some(rootValue => { - const root = rootValue.endsWith('/') ? rootValue : `${rootValue}/`; - return path.startsWith(root) && !path.slice(root.length).includes('../'); - }); + return isOwnedCachePath(path, { androidDataUserMirror: true }); } async function removeOwnedDecodedAudio(path: string): Promise { - if (!ownedCachePath(path)) { - throw new AudioPipelineError( - 'cleanup', - 'Refusing to remove decoded audio outside the app cache', - ); - } - try { - if (await FileSystem.exists(path)) await FileSystem.unlink(path); - } catch (error) { - throw new AudioPipelineError( - 'cleanup', - 'Temporary decoded audio could not be removed', - error, - ); - } + await removeOwnedCacheFile( + path, + () => + new AudioPipelineError( + 'cleanup', + 'Refusing to remove decoded audio outside the app cache', + ), + { + androidDataUserMirror: true, + onCleanupError: (error) => + new AudioPipelineError( + 'cleanup', + 'Temporary decoded audio could not be removed', + error, + ), + }, + ); } function validateNativeResult(value: NativeDecodedAudio): void { diff --git a/apps/mobile-rn/src/features/import/audio-file-picker.ts b/apps/mobile-rn/src/features/import/audio-file-picker.ts index ef7bb58..6e59d02 100644 --- a/apps/mobile-rn/src/features/import/audio-file-picker.ts +++ b/apps/mobile-rn/src/features/import/audio-file-picker.ts @@ -5,7 +5,7 @@ import { pick, types, } from '@react-native-documents/picker'; -import { Dirs, FileSystem } from 'react-native-file-access'; +import { removeOwnedCacheFile } from '../shared/owned-cache-files'; import { AudioPipelineError, type LocalAudioInput, @@ -16,29 +16,23 @@ import { validateLocalAudio, } from './audio-validation'; -function isOwnedImportCachePath(path: string): boolean { - const root = Dirs.CacheDir.endsWith('/') - ? Dirs.CacheDir - : `${Dirs.CacheDir}/`; - return path.startsWith(root) && !path.slice(root.length).includes('../'); -} - async function removeOwnedImportCopy(path: string): Promise { - if (!isOwnedImportCachePath(path)) { - throw new AudioPipelineError( - 'cleanup', - 'Refusing to remove a file outside the app import cache', - ); - } - try { - if (await FileSystem.exists(path)) await FileSystem.unlink(path); - } catch (error) { - throw new AudioPipelineError( - 'cleanup', - 'The temporary imported audio file could not be removed', - error, - ); - } + await removeOwnedCacheFile( + path, + () => + new AudioPipelineError( + 'cleanup', + 'Refusing to remove a file outside the app import cache', + ), + { + onCleanupError: (error) => + new AudioPipelineError( + 'cleanup', + 'The temporary imported audio file could not be removed', + error, + ), + }, + ); } export async function pickAudioFile(): Promise { try { diff --git a/apps/mobile-rn/src/features/import/audio-transcription-service.ts b/apps/mobile-rn/src/features/import/audio-transcription-service.ts index eaa39e5..4dec4f1 100644 --- a/apps/mobile-rn/src/features/import/audio-transcription-service.ts +++ b/apps/mobile-rn/src/features/import/audio-transcription-service.ts @@ -1,6 +1,5 @@ import type { AudioFile, - D3roSupabaseClient, HistoryEntry, } from '@d3ro/api-client'; import type { Session } from '@supabase/supabase-js'; @@ -8,6 +7,8 @@ import { SUPABASE_ANON_KEY, SUPABASE_URL } from '@d3ro/core/supabase-config'; import { FileSystem } from 'react-native-file-access'; import { supabase } from '../../lib/supabase'; import { getMobileRuntimeConfig } from '../../lib/native-config'; +import { getTypedSupabaseClient } from '../shared/service-guards'; +import { throwIfPipelineCancelled } from './abort-guard'; import { AudioPipelineError, type AudioPipelineErrorCode, @@ -45,26 +46,16 @@ interface OperationState { processingJobId: string | null; } -function database(): D3roSupabaseClient { - return supabase as unknown as D3roSupabaseClient; -} - -function throwIfCancelled(signal: AbortSignal): void { - if (signal.aborted) { - throw new AudioPipelineError('cancelled', 'Audio processing was cancelled'); - } -} - async function requireCurrentSession( expectedUserId: string, signal: AbortSignal, ): Promise { - throwIfCancelled(signal); + throwIfPipelineCancelled(signal); const { data: { session }, error, } = await supabase.auth.getSession(); - throwIfCancelled(signal); + throwIfPipelineCancelled(signal); if (error !== null || session === null || session.user.id !== expectedUserId) { throw new AudioPipelineError( @@ -98,7 +89,7 @@ async function findExistingAudio( sha256: string, storageKey?: string, ): Promise { - let query = database() + let query = getTypedSupabaseClient() .from('audio_files') .select('*') .eq('user_id', userId) @@ -125,7 +116,7 @@ async function loadLinkedHistory( historyId: string | null, ): Promise { if (historyId === null) return null; - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('history') .select('*') .eq('user_id', userId) @@ -148,7 +139,7 @@ async function insertAudioMetadata( storageKey: string, meetingId?: string, ): Promise<{ audioFile: AudioFile; created: boolean }> { - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('audio_files') .insert({ user_id: userId, @@ -185,7 +176,7 @@ async function updateAudioStatus( userId: string, uploadStatus: AudioFile['upload_status'], ): Promise { - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('audio_files') .update({ upload_status: uploadStatus }) .eq('id', audioFile.id) @@ -209,7 +200,7 @@ async function uploadAudio( parentSignal: AbortSignal, onProgress?: (uploadedBytes: number, totalBytes: number) => void, ): Promise { - throwIfCancelled(parentSignal); + throwIfPipelineCancelled(parentSignal); const deadline = createLinkedDeadline(parentSignal, UPLOAD_TIMEOUT_MS); try { @@ -275,7 +266,7 @@ async function persistSuccessfulHistory( let inserted = false; if (existingHistory !== null) { - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('history') .update({ ...patch, revision: existingHistory.revision + 1 }) .eq('id', existingHistory.id) @@ -292,7 +283,7 @@ async function persistSuccessfulHistory( } history = data; } else { - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('history') .insert({ user_id: userId, @@ -313,7 +304,7 @@ async function persistSuccessfulHistory( inserted = true; } - const { data: linkedAudio, error: linkError } = await database() + const { data: linkedAudio, error: linkError } = await getTypedSupabaseClient() .from('audio_files') .update({ history_id: history.id, @@ -327,7 +318,7 @@ async function persistSuccessfulHistory( if (linkError !== null || linkedAudio?.history_id !== history.id) { if (inserted) { - await database() + await getTypedSupabaseClient() .from('history') .delete() .eq('id', history.id) @@ -353,7 +344,7 @@ async function persistFailedHistory( let historyId = existingHistory?.id ?? null; if (existingHistory !== null) { - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('history') .update({ status: 'error', @@ -367,7 +358,7 @@ async function persistFailedHistory( .maybeSingle(); if (error !== null || data === null) return; } else { - const { data, error } = await database() + const { data, error } = await getTypedSupabaseClient() .from('history') .insert({ user_id: userId, @@ -396,7 +387,7 @@ async function persistFailedHistory( } if (historyId !== null) { - await database() + await getTypedSupabaseClient() .from('audio_files') .update({ history_id: historyId, upload_status: 'uploaded' }) .eq('id', audioFile.id) @@ -410,7 +401,7 @@ async function bestEffortMarkUploadFailed( ): Promise { if (state.audioFile === null) return; try { - await database() + await getTypedSupabaseClient() .from('audio_files') .update({ upload_status: 'failed' }) .eq('id', state.audioFile.id) @@ -467,7 +458,7 @@ async function processCore( error, ); } - throwIfCancelled(options.signal); + throwIfPipelineCancelled(options.signal); if (!/^[0-9a-f]{64}$/.test(sha256)) { throw new AudioPipelineError('file-read', 'The audio checksum is invalid'); } @@ -529,7 +520,7 @@ async function processCore( } let audioBytes = await readAudioBytes(input); - throwIfCancelled(options.signal); + throwIfPipelineCancelled(options.signal); if (audioBytes.byteLength !== input.sizeBytes) { throw new AudioPipelineError( 'file-read', diff --git a/apps/mobile-rn/src/features/import/audio-validation.ts b/apps/mobile-rn/src/features/import/audio-validation.ts index 55a0446..5761c24 100644 --- a/apps/mobile-rn/src/features/import/audio-validation.ts +++ b/apps/mobile-rn/src/features/import/audio-validation.ts @@ -1,3 +1,4 @@ +import { isUuid } from '@d3ro/core/guards'; import { FileSystem } from 'react-native-file-access'; import { AudioPipelineError, @@ -320,7 +321,7 @@ export function buildAudioStorageKey( sha256: string, fileName: string, ): string { - if (!/^[0-9a-f-]{36}$/i.test(userId)) { + if (!isUuid(userId)) { throw new AudioPipelineError('auth', 'A valid account is required'); } if (!/^[0-9a-f]{64}$/.test(sha256)) { diff --git a/apps/mobile-rn/src/features/import/incoming-media-intent.ts b/apps/mobile-rn/src/features/import/incoming-media-intent.ts index 1ee032b..92be2d6 100644 --- a/apps/mobile-rn/src/features/import/incoming-media-intent.ts +++ b/apps/mobile-rn/src/features/import/incoming-media-intent.ts @@ -1,3 +1,4 @@ +import { isRecord } from '@d3ro/core/guards'; import { NativeEventEmitter, NativeModules, Platform } from 'react-native'; import { Dirs, FileSystem } from 'react-native-file-access'; import { @@ -46,9 +47,6 @@ const emitter = nativeModule === undefined ? null : new NativeEventEmitter(nativ const INCOMING_DIRECTORY = 'd3ro-incoming-media'; const FILE_NAME_PATTERN = /^incoming-[0-9a-f-]{36}\.[a-z0-9]{1,8}$/; -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} function incomingDirectory(): string { const cache = Dirs.CacheDir.endsWith('/') ? Dirs.CacheDir.slice(0, -1) : Dirs.CacheDir; diff --git a/apps/mobile-rn/src/features/import/local-whisper-transcription.ts b/apps/mobile-rn/src/features/import/local-whisper-transcription.ts index 9e7a600..04a1cb8 100644 --- a/apps/mobile-rn/src/features/import/local-whisper-transcription.ts +++ b/apps/mobile-rn/src/features/import/local-whisper-transcription.ts @@ -6,17 +6,12 @@ import { type MobileTranscriptionResult, } from './audio-import-types'; import { prepareAudioForWhisper } from './android-audio-decoder'; +import { throwIfPipelineCancelled } from './abort-guard'; const ANDROID_MODEL_ASSET = 'models/ggml-tiny.bin'; const LOCAL_PROVIDER = 'whisper.cpp-tiny-local'; let localTranscriptionActive = false; -function throwIfCancelled(signal: AbortSignal): void { - if (signal.aborted) { - throw new AudioPipelineError('cancelled', 'Audio processing was cancelled'); - } -} - function normalizeLanguage(value: string, fallback: string): string { const normalized = value.trim().toLowerCase(); return /^[a-z]{2,3}(?:-[a-z0-9]+)?$/.test(normalized) @@ -61,16 +56,16 @@ export async function transcribeAudioLocally( let pipelineError: unknown = null; try { - throwIfCancelled(signal); + throwIfPipelineCancelled(signal); prepared = await prepareAudioForWhisper(input, signal); - throwIfCancelled(signal); + throwIfPipelineCancelled(signal); context = await initWhisper({ filePath: ANDROID_MODEL_ASSET, isBundleAsset: true, useGpu: false, useFlashAttn: false, }); - throwIfCancelled(signal); + throwIfPipelineCancelled(signal); const task = context.transcribe(prepared.path, { language: languageCode, diff --git a/apps/mobile-rn/src/features/import/resumable-audio-upload.ts b/apps/mobile-rn/src/features/import/resumable-audio-upload.ts index 3df17b0..40fd0a5 100644 --- a/apps/mobile-rn/src/features/import/resumable-audio-upload.ts +++ b/apps/mobile-rn/src/features/import/resumable-audio-upload.ts @@ -4,6 +4,7 @@ import { SUPABASE_ANON_KEY, SUPABASE_URL } from '@d3ro/core/supabase-config'; import { FileSystem } from 'react-native-file-access'; import { AudioPipelineError, type LocalAudioInput } from './audio-import-types'; import { decodeBase64 } from './audio-validation'; +import { throwIfPipelineCancelled } from './abort-guard'; const TUS_VERSION = '1.0.0'; const TUS_CHUNK_BYTES = 6 * 1024 * 1024; @@ -28,12 +29,6 @@ export interface ResumableUploadOptions { onProgress?: (uploadedBytes: number, totalBytes: number) => void; } -function throwIfCancelled(signal: AbortSignal): void { - if (signal.aborted) { - throw new AudioPipelineError('cancelled', 'Audio upload was cancelled'); - } -} - function checkpointKey(userId: string, storageKey: string): string { return `${CHECKPOINT_PREFIX}${userId}/${storageKey.replace(/[^A-Za-z0-9._-]/g, '_')}`; } @@ -154,7 +149,7 @@ async function saveCheckpoint(checkpoint: UploadCheckpoint): Promise { } async function createUpload(options: ResumableUploadOptions): Promise { - throwIfCancelled(options.signal); + throwIfPipelineCancelled(options.signal, 'Audio upload was cancelled'); const response = await fetch(`${SUPABASE_URL}/storage/v1/upload/resumable`, { method: 'POST', headers: { @@ -225,7 +220,7 @@ function throwUploadResponse(status: number): never { export async function uploadAudioResumably( options: ResumableUploadOptions, ): Promise { - throwIfCancelled(options.signal); + throwIfPipelineCancelled(options.signal, 'Audio upload was cancelled'); const stat = await FileSystem.stat(options.input.path); if (stat.type !== 'file' || stat.size !== options.input.sizeBytes) { throw new AudioPipelineError('file-read', 'The audio file changed before upload'); @@ -250,7 +245,7 @@ export async function uploadAudioResumably( options.onProgress?.(checkpoint.offset, checkpoint.size); while (checkpoint.offset < checkpoint.size) { - throwIfCancelled(options.signal); + throwIfPipelineCancelled(options.signal, 'Audio upload was cancelled'); const chunkSize = Math.min(TUS_CHUNK_BYTES, checkpoint.size - checkpoint.offset); const encoded = await FileSystem.readFileChunk( options.input.path, diff --git a/apps/mobile-rn/src/features/knowledge/knowledge-file-picker.ts b/apps/mobile-rn/src/features/knowledge/knowledge-file-picker.ts index 633eec8..6cba6bd 100644 --- a/apps/mobile-rn/src/features/knowledge/knowledge-file-picker.ts +++ b/apps/mobile-rn/src/features/knowledge/knowledge-file-picker.ts @@ -5,7 +5,11 @@ import { pick, types, } from '@react-native-documents/picker' -import { Dirs, FileSystem } from 'react-native-file-access' +import { FileSystem } from 'react-native-file-access' +import { + localPathFromCacheUri, + removeOwnedCacheFile, +} from '../shared/owned-cache-files' import { KnowledgeServiceError, KNOWLEDGE_MAX_CONTENT_CHARS, @@ -30,29 +34,19 @@ const TEXT_MIME_TYPES = new Set([ 'application/octet-stream', ]) -function localPathFromUri(uri: string): string { - if (!uri.startsWith('file://')) return uri - const withoutScheme = uri.replace(/^file:\/\//, '') - return decodeURIComponent(withoutScheme.startsWith('/') ? withoutScheme : `/${withoutScheme}`) -} - -function isOwnedCachePath(path: string): boolean { - const normalizedRoot = Dirs.CacheDir.replace(/\\/g, '/').replace(/\/$/, '') - const normalizedPath = path.replace(/\\/g, '/') - return normalizedPath.startsWith(`${normalizedRoot}/`) - && !normalizedPath.slice(normalizedRoot.length + 1).split('/').includes('..') -} +const localPathFromUri = localPathFromCacheUri async function removeOwnedCopy(path: string): Promise { - if (!isOwnedCachePath(path)) { - throw new KnowledgeServiceError( - 'validation', - false, - null, - 'Refusing to remove a file outside the app import cache', - ) - } - if (await FileSystem.exists(path)) await FileSystem.unlink(path) + await removeOwnedCacheFile( + path, + () => + new KnowledgeServiceError( + 'validation', + false, + null, + 'Refusing to remove a file outside the app import cache', + ), + ) } export function classifyKnowledgeFile( diff --git a/apps/mobile-rn/src/features/knowledge/knowledge-service.ts b/apps/mobile-rn/src/features/knowledge/knowledge-service.ts index 5a6357f..c0bad52 100644 --- a/apps/mobile-rn/src/features/knowledge/knowledge-service.ts +++ b/apps/mobile-rn/src/features/knowledge/knowledge-service.ts @@ -1,12 +1,20 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' import type { RealtimeChannel } from '@supabase/supabase-js' import type { - D3roSupabaseClient, KnowledgeDocument, KnowledgeFileType, } from '@d3ro/api-client' import { SUPABASE_URL } from '@d3ro/core/supabase-config' import { supabase } from '../../lib/supabase' import { createUuidV4 } from '../../lib/random-id' +import { + createLabeledUuidAssert, + extractSupabaseErrorInfo, + getTypedSupabaseClient, + isSupabaseAuthFailure, + isSupabaseForbiddenFailure, + isSupabaseNetworkFailure, +} from '../shared/service-guards' import { type ForegroundReconciliationDeps, knowledgeRealtimeBindings, @@ -92,7 +100,6 @@ interface KnowledgeIndexOptions { timeoutMs?: number } -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_PAGE_SIZE = 30 const MAX_PAGE_SIZE = 50 const MAX_TITLE_LENGTH = 160 @@ -101,19 +108,9 @@ export const KNOWLEDGE_CHUNK_SIZE = 800 const MAX_SEARCH_LENGTH = 500 const MAX_SEARCH_RESULTS = 12 -function client(): D3roSupabaseClient { - return supabase as unknown as D3roSupabaseClient -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -function requireUuid(value: string, label: string): void { - if (!UUID_PATTERN.test(value)) { - throw new KnowledgeServiceError('auth', false, null, `A valid ${label} is required`) - } -} +const requireUuid = createLabeledUuidAssert( + (label) => new KnowledgeServiceError('auth', false, null, `A valid ${label} is required`), +) export function normalizeKnowledgeTitle(value: string): string { const title = value.trim().replace(/\s+/g, ' ') @@ -207,31 +204,20 @@ function assertDocument(row: KnowledgeDocument | null, expectedId?: string): Kno function toKnowledgeError(error: unknown): KnowledgeServiceError { if (error instanceof KnowledgeServiceError) return error - const candidate = error as { code?: unknown; message?: unknown } - const code = typeof candidate?.code === 'string' ? candidate.code : '' - const message = typeof candidate?.message === 'string' - ? candidate.message - : 'Knowledge request failed' - const lower = message.toLowerCase() - - if ( - error instanceof TypeError - || lower.includes('network request failed') - || lower.includes('failed to fetch') - || lower.includes('networkerror') - ) { - return new KnowledgeServiceError('network', true, null, message) + const info = extractSupabaseErrorInfo(error, 'Knowledge request failed') + if (isSupabaseNetworkFailure(error, info)) { + return new KnowledgeServiceError('network', true, null, info.message) } - if (code === '42501' || lower.includes('permission denied') || lower.includes('row-level security')) { - return new KnowledgeServiceError('forbidden', false, 403, message) + if (isSupabaseForbiddenFailure(info)) { + return new KnowledgeServiceError('forbidden', false, 403, info.message) } - if (code === 'PGRST301' || lower.includes('jwt')) { - return new KnowledgeServiceError('auth', false, 401, message) + if (isSupabaseAuthFailure(info)) { + return new KnowledgeServiceError('auth', false, 401, info.message) } - if (code.startsWith('22')) { - return new KnowledgeServiceError('validation', false, 400, message) + if (info.code.startsWith('22')) { + return new KnowledgeServiceError('validation', false, 400, info.message) } - return new KnowledgeServiceError('server', true, null, message) + return new KnowledgeServiceError('server', true, null, info.message) } function createRequestDeadline( @@ -291,7 +277,7 @@ export async function listKnowledgeDocuments( const search = sanitizeKnowledgeSearch(options.search ?? '') try { - let query = client() + let query = getTypedSupabaseClient() .from('knowledge_documents') .select('*', { count: 'exact' }) .order('created_at', { ascending: false }) @@ -345,7 +331,7 @@ export async function createKnowledgeDocument( let created: KnowledgeDocument | null = null try { - const documentResult = await client() + const documentResult = await getTypedSupabaseClient() .from('knowledge_documents') .insert({ user_id: input.userId, @@ -362,7 +348,7 @@ export async function createKnowledgeDocument( if (documentResult.error !== null) throw documentResult.error created = assertDocument(documentResult.data) - const chunkResult = await client() + const chunkResult = await getTypedSupabaseClient() .from('knowledge_chunks') .insert(chunks.map((content, chunkIndex) => ({ document_id: created?.id ?? '', @@ -382,7 +368,7 @@ export async function createKnowledgeDocument( return created } catch (error) { if (created !== null) { - const cleanup = await client() + const cleanup = await getTypedSupabaseClient() .from('knowledge_documents') .delete() .eq('id', created.id) @@ -404,7 +390,7 @@ async function forcePendingIndexState( userId: string, documentId: string, ): Promise { - await client() + await getTypedSupabaseClient() .from('knowledge_documents') .update({ indexed: false, indexed_at: null }) .eq('id', documentId) @@ -459,12 +445,12 @@ export async function indexKnowledgeDocument( } const [documentResult, embeddedCountResult] = await Promise.all([ - client() + getTypedSupabaseClient() .from('knowledge_documents') .select('*') .eq('id', document.id) .maybeSingle(), - client() + getTypedSupabaseClient() .from('knowledge_chunks') .select('id', { count: 'exact', head: true }) .eq('document_id', document.id) @@ -509,7 +495,7 @@ export async function deleteKnowledgeDocument( throw new KnowledgeServiceError('forbidden', false, 403, 'Only the owner can delete this document') } try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('knowledge_documents') .delete() .eq('id', document.id) @@ -539,8 +525,8 @@ function parseSearchResult(value: unknown): KnowledgeSearchResult { const chunkIndex = value.chunk_index const similarity = value.similarity if ( - !UUID_PATTERN.test(id) - || !UUID_PATTERN.test(documentId) + !isUuid(id) + || !isUuid(documentId) || content.length === 0 || content.length > 8_000 || !Number.isSafeInteger(chunkIndex) diff --git a/apps/mobile-rn/src/features/meetings/meeting-error-message.ts b/apps/mobile-rn/src/features/meetings/meeting-error-message.ts new file mode 100644 index 0000000..a7a660c --- /dev/null +++ b/apps/mobile-rn/src/features/meetings/meeting-error-message.ts @@ -0,0 +1,18 @@ +import type { TranslationKey } from '@d3ro/i18n' +import { MeetingServiceError } from './meetings-service' + +export type TranslateFn = (key: TranslationKey) => string + +/** + * Resolves the localized user-facing error message for a meeting operation failure. + */ +export function resolveMeetingErrorMessage(error: unknown, t: TranslateFn): string { + if (!(error instanceof MeetingServiceError)) return t('mobile.meetings.errorServer') + if (error.code === 'auth') return t('mobile.meetings.loginRequired') + if (error.code === 'conflict') return t('mobile.meetings.errorConflict') + if (error.code === 'forbidden') return t('mobile.meetings.errorForbidden') + if (error.code === 'network') return t('mobile.meetings.errorNetwork') + if (error.code === 'not-found') return t('mobile.meetings.errorNotFound') + if (error.code === 'validation') return t('mobile.meetings.errorValidation') + return t('mobile.meetings.errorServer') +} diff --git a/apps/mobile-rn/src/features/meetings/meetings-service.ts b/apps/mobile-rn/src/features/meetings/meetings-service.ts index 08fa857..34da2f2 100644 --- a/apps/mobile-rn/src/features/meetings/meetings-service.ts +++ b/apps/mobile-rn/src/features/meetings/meetings-service.ts @@ -1,7 +1,6 @@ import type { RealtimeChannel } from '@supabase/supabase-js' import { parseTranscriptLines } from '@d3ro/core/meeting-transcript' import type { - D3roSupabaseClient, Meeting, MeetingLanguage, MeetingDocument, @@ -11,6 +10,14 @@ import type { } from '@d3ro/api-client' import { supabase } from '../../lib/supabase' import { createUuidV4 } from '../../lib/random-id' +import { + createLabeledUuidAssert, + extractSupabaseErrorInfo, + getTypedSupabaseClient, + isSupabaseAuthFailure, + isSupabaseForbiddenFailure, + isSupabaseNetworkFailure, +} from '../shared/service-guards' import { createSupabaseLinkedAudioStore, purgeUnlinkedAudio, @@ -107,7 +114,6 @@ export interface MeetingProcessingResult { sttLatencyMs: number } -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_PAGE_SIZE = 30 const MAX_PAGE_SIZE = 50 const MAX_TITLE_LENGTH = 160 @@ -116,15 +122,9 @@ const MAX_DOCUMENT_CONTENT_LENGTH = 100_000 const MAX_ATTENDEES = 50 const MAX_ATTENDEE_LENGTH = 120 -function client(): D3roSupabaseClient { - return supabase as unknown as D3roSupabaseClient -} - -function requireUuid(value: string, label: string): void { - if (!UUID_PATTERN.test(value)) { - throw new MeetingServiceError('auth', `A valid ${label} is required`) - } -} +const requireUuid = createLabeledUuidAssert( + (label) => new MeetingServiceError('auth', `A valid ${label} is required`), +) function normalizeWhitespace(value: string): string { return value.trim().replace(/\s+/g, ' ') @@ -419,30 +419,19 @@ function assertDetailRelationships(detail: MeetingDetail): MeetingDetail { function toMeetingServiceError(error: unknown): MeetingServiceError { if (error instanceof MeetingServiceError) return error - const candidate = error as { code?: unknown; message?: unknown } - const code = typeof candidate?.code === 'string' ? candidate.code : '' - const message = typeof candidate?.message === 'string' - ? candidate.message - : 'Meeting request failed' - const lower = message.toLowerCase() - - if ( - error instanceof TypeError - || lower.includes('network request failed') - || lower.includes('failed to fetch') - || lower.includes('networkerror') - ) { - return new MeetingServiceError('network', message) + const info = extractSupabaseErrorInfo(error, 'Meeting request failed') + if (isSupabaseNetworkFailure(error, info)) { + return new MeetingServiceError('network', info.message) } - if (code === '42501' || lower.includes('permission denied') || lower.includes('row-level security')) { - return new MeetingServiceError('forbidden', message) + if (isSupabaseForbiddenFailure(info)) { + return new MeetingServiceError('forbidden', info.message) } - if (code === 'PGRST301' || lower.includes('jwt')) { - return new MeetingServiceError('auth', message) + if (isSupabaseAuthFailure(info)) { + return new MeetingServiceError('auth', info.message) } - if (code === 'PT409') return new MeetingServiceError('conflict', message) - if (code.startsWith('22')) return new MeetingServiceError('validation', message) - return new MeetingServiceError('server', message) + if (info.code === 'PT409') return new MeetingServiceError('conflict', info.message) + if (info.code.startsWith('22')) return new MeetingServiceError('validation', info.message) + return new MeetingServiceError('server', info.message) } async function callMeetingRpc( @@ -466,7 +455,7 @@ export async function listMeetingsPage( const search = sanitizeMeetingSearch(options.search ?? '') try { - let query = client() + let query = getTypedSupabaseClient() .from('meetings') .select('*', { count: 'exact' }) .order('started_at', { ascending: false }) @@ -500,19 +489,19 @@ export async function getMeetingDetail( try { const [meetingResult, transcriptResult, memoResult, documentResult] = await Promise.all([ - client().from('meetings').select('*').eq('id', meetingId).maybeSingle(), - client() + getTypedSupabaseClient().from('meetings').select('*').eq('id', meetingId).maybeSingle(), + getTypedSupabaseClient() .from('transcripts') .select('*') .eq('meeting_id', meetingId) .order('segment_index', { ascending: true }), - client() + getTypedSupabaseClient() .from('meeting_memos') .select('*') .eq('meeting_id', meetingId) .order('timestamp_ms', { ascending: true }) .order('created_at', { ascending: true }), - client() + getTypedSupabaseClient() .from('meeting_documents') .select('*') .eq('meeting_id', meetingId) @@ -545,7 +534,7 @@ export async function getMeetingRecordingLanguage( requireUuid(userId, 'authenticated user') requireUuid(meetingId, 'meeting id') try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('meetings') .select('*') .eq('id', meetingId) @@ -569,7 +558,7 @@ export async function createMeetingWorkspace( const title = normalizeMeetingTitle(titleValue) try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('meetings') .insert({ user_id: userId, title, status: 'recording' }) .select('*') @@ -626,7 +615,7 @@ export async function updateMeetingTitleRevisionSafe( if (current.title === title) return current try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('meetings') .update({ title }) .eq('id', current.id) @@ -669,7 +658,7 @@ export async function deleteMeetingRevisionSafe( } try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('meetings') .delete() .eq('id', current.id) @@ -703,7 +692,7 @@ export async function createMeetingMemo( const timestampMs = computeMemoTimestamp(meeting.started_at, nowMs) try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('meeting_memos') .insert({ meeting_id: meeting.id, @@ -723,6 +712,14 @@ export async function createMeetingMemo( } } +function assertMemoRevision(revision: number | undefined): number | null { + if (revision === undefined) return null + if (!Number.isSafeInteger(revision) || revision < 1) { + throw new MeetingServiceError('validation', 'Memo revision is invalid') + } + return revision +} + export async function updateMeetingMemoConflictSafe( userId: string, current: MeetingMemo, @@ -733,11 +730,12 @@ export async function updateMeetingMemoConflictSafe( if (current.user_id !== userId) { throw new MeetingServiceError('forbidden', 'Only the memo author can edit it') } + const expectedRevision = assertMemoRevision(current.revision) const content = normalizeMemoContent(contentValue) if (content === current.content) return current try { - const { data, error } = await client() + let query = getTypedSupabaseClient() .from('meeting_memos') .update({ content }) .eq('id', current.id) @@ -746,6 +744,10 @@ export async function updateMeetingMemoConflictSafe( .eq('content', current.content) .eq('timestamp_ms', current.timestamp_ms) .eq('created_at', current.created_at) + if (expectedRevision !== null) { + query = query.eq('revision', expectedRevision) + } + const { data, error } = await query .select('*') .maybeSingle() if (error !== null) throw error @@ -770,9 +772,10 @@ export async function deleteMeetingMemoConflictSafe( if (current.user_id !== userId) { throw new MeetingServiceError('forbidden', 'Only the memo author can delete it') } + const expectedRevision = assertMemoRevision(current.revision) try { - const { data, error } = await client() + let query = getTypedSupabaseClient() .from('meeting_memos') .delete() .eq('id', current.id) @@ -781,6 +784,10 @@ export async function deleteMeetingMemoConflictSafe( .eq('content', current.content) .eq('timestamp_ms', current.timestamp_ms) .eq('created_at', current.created_at) + if (expectedRevision !== null) { + query = query.eq('revision', expectedRevision) + } + const { data, error } = await query .select('id') .maybeSingle() if (error !== null) throw error @@ -805,7 +812,7 @@ export async function updateMeetingDocumentRevisionSafe( if (draft.title === current.title && draft.content === current.content) return current try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('meeting_documents') .update(draft) .eq('id', current.id) @@ -837,7 +844,7 @@ export async function deleteMeetingDocumentRevisionSafe( } try { - const { data, error } = await client() + const { data, error } = await getTypedSupabaseClient() .from('meeting_documents') .delete() .eq('id', current.id) diff --git a/apps/mobile-rn/src/features/memos/memo-service.ts b/apps/mobile-rn/src/features/memos/memo-service.ts index 88d3af8..c2175b1 100644 --- a/apps/mobile-rn/src/features/memos/memo-service.ts +++ b/apps/mobile-rn/src/features/memos/memo-service.ts @@ -1,6 +1,13 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' import type { RealtimeChannel } from '@supabase/supabase-js' import type { HistoryEntry, MemoTag } from '@d3ro/api-client' import { supabase } from '../../lib/supabase' +import { + createLabeledUuidAssert, + extractSupabaseErrorInfo, + isSupabaseAuthFailure, + isSupabaseNetworkFailure, +} from '../shared/service-guards' import type { MemoHistoryItem, MemoSearchResult, @@ -29,15 +36,11 @@ export interface MemoSubscription { unsubscribe: () => Promise } -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 isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} -function requireUuid(value: string, label: string): void { - if (!UUID_PATTERN.test(value)) throw new MemoServiceError('auth', `A valid ${label} is required`) -} +const requireUuid = createLabeledUuidAssert( + (label) => new MemoServiceError('auth', `A valid ${label} is required`), +) export function normalizeMemoTag(value: string): { tag: string; normalizedTag: string } { const tag = value.trim().replace(/\s+/g, ' ') @@ -54,25 +57,19 @@ export function sanitizeMemoSearch(value: string): string { function toMemoError(error: unknown): MemoServiceError { if (error instanceof MemoServiceError) return error - const candidate = error as { code?: unknown; message?: unknown } - const code = typeof candidate?.code === 'string' ? candidate.code : '' - const message = typeof candidate?.message === 'string' ? candidate.message : 'Memo request failed' - const lower = message.toLowerCase() - if ( - error instanceof TypeError - || lower.includes('network request failed') - || lower.includes('failed to fetch') - || lower.includes('networkerror') - ) return new MemoServiceError('network', message, true) - if (code === '40001' || lower.includes('conflict')) { - return new MemoServiceError('conflict', message, true) + const info = extractSupabaseErrorInfo(error, 'Memo request failed') + if (isSupabaseNetworkFailure(error, info)) { + return new MemoServiceError('network', info.message, true) } - if (code === 'P0002') return new MemoServiceError('not-found', message) - if (code === '42501' || code === 'PGRST301' || lower.includes('jwt')) { - return new MemoServiceError('auth', message) + if (info.code === '40001' || info.lower.includes('conflict')) { + return new MemoServiceError('conflict', info.message, true) } - if (code.startsWith('22')) return new MemoServiceError('validation', message) - return new MemoServiceError('server', message, true) + if (info.code === 'P0002') return new MemoServiceError('not-found', info.message) + if (isSupabaseAuthFailure(info, { include42501: true })) { + return new MemoServiceError('auth', info.message) + } + if (info.code.startsWith('22')) return new MemoServiceError('validation', info.message) + return new MemoServiceError('server', info.message, true) } async function rpc(name: string, params: Record = {}): Promise { @@ -85,7 +82,7 @@ function assertHistory(value: unknown, userId: string): HistoryEntry { if ( !isRecord(value) || typeof value.id !== 'string' - || !UUID_PATTERN.test(value.id) + || !isUuid(value.id) || value.user_id !== userId || typeof value.original_text !== 'string' || typeof value.created_at !== 'string' diff --git a/apps/mobile-rn/src/features/notifications/notification-contract.ts b/apps/mobile-rn/src/features/notifications/notification-contract.ts index af2b4f9..f590cd2 100644 --- a/apps/mobile-rn/src/features/notifications/notification-contract.ts +++ b/apps/mobile-rn/src/features/notifications/notification-contract.ts @@ -1,3 +1,5 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' + export type NotificationEventType = | 'transcription.completed' | 'team.invite.created' @@ -48,13 +50,9 @@ export class NotificationContractError extends Error { } } -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 INVITE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{20,128}$/ const COMMON_KEYS = new Set(['schema_version', 'event_type', 'resource_id', 'route']) -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function stringValue(data: Record, key: string): string { const value = data[key] @@ -77,7 +75,7 @@ function assertExactKeys(data: Record, expected: readonly strin function uuid(data: Record, key: string): string { const value = stringValue(data, key) - if (!UUID_PATTERN.test(value)) throw new NotificationContractError('invalid-payload') + if (!isUuid(value)) throw new NotificationContractError('invalid-payload') return value } diff --git a/apps/mobile-rn/src/features/notifications/notification-native.ts b/apps/mobile-rn/src/features/notifications/notification-native.ts index 00dbf90..e373532 100644 --- a/apps/mobile-rn/src/features/notifications/notification-native.ts +++ b/apps/mobile-rn/src/features/notifications/notification-native.ts @@ -1,3 +1,4 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' import { NativeEventEmitter, NativeModules, @@ -47,9 +48,6 @@ interface NativeSubscription { const nativeModule = NativeModules.D3RONotifications as D3RONotificationNativeModule | undefined const emitter = nativeModule === undefined ? null : new NativeEventEmitter(nativeModule) -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} export function resolveNativePushProvider(platform: string = Platform.OS): MobilePushProvider { return platform === 'ios' ? 'apns' : 'fcm' @@ -155,7 +153,7 @@ export async function clearNativeFullSyncRequired(): Promise { export async function showLocalTranscriptionCompleted(historyId: string): Promise { if (nativeModule === undefined) return false - if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(historyId)) { + if (!isUuid(historyId)) { throw new Error('notification_history_id_invalid') } return nativeModule.showLocalTranscriptionCompleted(historyId) diff --git a/apps/mobile-rn/src/features/notifications/notification-service.ts b/apps/mobile-rn/src/features/notifications/notification-service.ts index 9678bdc..c52c7bd 100644 --- a/apps/mobile-rn/src/features/notifications/notification-service.ts +++ b/apps/mobile-rn/src/features/notifications/notification-service.ts @@ -1,4 +1,6 @@ +import { isRecord } from '@d3ro/core/guards' import { supabase } from '../../lib/supabase' +import { extractSupabaseErrorInfo, requireUuidWith } from '../shared/service-guards' import type { RegisteredDevice } from '../devices/device-service' import { deleteNativePushRegistration, @@ -27,22 +29,16 @@ export class NotificationServiceError extends Error { } } -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 isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function requireUuid(value: string, code: 'auth' | 'invalid-device'): void { - if (!UUID_PATTERN.test(value)) throw new NotificationServiceError(code) + requireUuidWith(value, () => new NotificationServiceError(code)) } function toServiceError(error: unknown): NotificationServiceError { if (error instanceof NotificationServiceError) return error - const candidate = error as { code?: unknown; message?: unknown } - const code = typeof candidate?.code === 'string' ? candidate.code : '' - const message = typeof candidate?.message === 'string' ? candidate.message.toLowerCase() : '' - if (code === 'PGRST202' || message.includes('could not find the function')) { + const info = extractSupabaseErrorInfo(error, '') + if (info.code === 'PGRST202' || info.lower.includes('could not find the function')) { return new NotificationServiceError('server-contract') } return new NotificationServiceError('server') diff --git a/apps/mobile-rn/src/features/recording/durable-processing-queue.ts b/apps/mobile-rn/src/features/recording/durable-processing-queue.ts index da57def..b7159af 100644 --- a/apps/mobile-rn/src/features/recording/durable-processing-queue.ts +++ b/apps/mobile-rn/src/features/recording/durable-processing-queue.ts @@ -363,21 +363,28 @@ async function markMeetingQueued(item: DurableQueueItem): Promise { - if (!(await FileSystem.exists(item.path))) { - throw new AudioPipelineError('file-read', 'Queued audio file is missing'); - } const controller = new AbortController(); runningControllers.set(item.id, controller); - let current: DurableQueueItem = { - ...item, - status: 'running' as const, - attempts: item.attempts + 1, - lastErrorCode: null, - lastErrorMessage: null, - updatedAtMs: Date.now(), - }; - await replaceItem(current); + let current: DurableQueueItem = item; try { + if (discardedItems.has(item.id)) { + throw new AudioPipelineError('cancelled', 'Queued audio processing was cancelled'); + } + if (!(await FileSystem.exists(item.path))) { + throw new AudioPipelineError('file-read', 'Queued audio file is missing'); + } + if (discardedItems.has(item.id) || controller.signal.aborted) { + throw new AudioPipelineError('cancelled', 'Queued audio processing was cancelled'); + } + current = { + ...item, + status: 'running' as const, + attempts: item.attempts + 1, + lastErrorCode: null, + lastErrorMessage: null, + updatedAtMs: Date.now(), + }; + await replaceItem(current); current = await markMeetingQueued(current); const result = await processAudioInput(queueInput(current), { expectedUserId: current.userId, @@ -393,6 +400,9 @@ async function processItemCore(item: DurableQueueItem): Promise { @@ -548,7 +560,9 @@ export async function clearQueuedAudioForUser(userId: string): Promise { } catch (error) { firstRemovalError ??= error; } - if (!runningControllers.has(item.id)) discardedItems.delete(item.id); + if (!runningControllers.has(item.id) && !runningItemPromises.has(item.id)) { + discardedItems.delete(item.id); + } } await mutateQueue(items => items.filter(item => !removedIds.has(item.id))); if (firstRemovalError !== null) throw firstRemovalError; diff --git a/apps/mobile-rn/src/features/reporting/content-report-service.ts b/apps/mobile-rn/src/features/reporting/content-report-service.ts index f00681e..5cdcd7b 100644 --- a/apps/mobile-rn/src/features/reporting/content-report-service.ts +++ b/apps/mobile-rn/src/features/reporting/content-report-service.ts @@ -1,4 +1,6 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' import { SUPABASE_ANON_KEY, SUPABASE_URL } from '@d3ro/core/supabase-config' +import { parseUuidWith } from '../shared/service-guards' export const CONTENT_REPORT_REASONS = [ 'harmful', @@ -50,7 +52,6 @@ export interface ContentReportReceipt { createdAt: string } -const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i const REASON_SET = new Set(CONTENT_REPORT_REASONS) const SOURCE_SET = new Set([ 'talk_response', @@ -71,16 +72,13 @@ export class ContentReportError extends Error { } } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function requireUuid(value: string): string { - const normalized = value.trim() - if (!UUID_PATTERN.test(normalized)) { - throw new ContentReportError('INVALID_REQUEST', false) - } - return normalized.toLowerCase() + return parseUuidWith( + value, + () => new ContentReportError('INVALID_REQUEST', false), + { trim: true }, + ) } function normalizeInput(input: AiContentReportInput): { @@ -142,7 +140,7 @@ function parseReceipt(value: unknown): ContentReportReceipt { if ( !isRecord(value) || typeof value.reportId !== 'string' - || !UUID_PATTERN.test(value.reportId) + || !isUuid(value.reportId) || value.status !== 'submitted' || typeof value.idempotent !== 'boolean' || typeof value.createdAt !== 'string' diff --git a/apps/mobile-rn/src/features/search/unified-search-service.ts b/apps/mobile-rn/src/features/search/unified-search-service.ts index 830c3b1..9acbb90 100644 --- a/apps/mobile-rn/src/features/search/unified-search-service.ts +++ b/apps/mobile-rn/src/features/search/unified-search-service.ts @@ -3,14 +3,24 @@ import type { UnifiedSearchResponse, UnifiedSearchResult, } from '@d3ro/core/types' +import { escapePostgrestLikePattern, isRecord } from '@d3ro/core/guards' +import { + createUnifiedSearchExcerpt, + includesSearchQuery, + mergeUnifiedSearchResults, +} from '@d3ro/core/unified-search' import { formatTranscriptTimestamp } from '@d3ro/core/meeting-transcript' -import { supabase } from '../../lib/supabase' +import { + extractSupabaseErrorInfo, + getTypedSupabaseClient, + isSupabaseAuthFailure, + isSupabaseNetworkFailure, + requireUuidWith, +} from '../shared/service-guards' -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_LIMIT = 30 const MAX_LIMIT = 50 const MAX_QUERY_LENGTH = 100 -const EXCERPT_LENGTH = 180 const MAX_BOUNDED_TEXT_LENGTH = 600 const HISTORY_SEARCH_COLUMNS = 'id,title,original_text,polished_text,summary_text,created_at' const MEETING_SEARCH_COLUMNS = 'id,title,raw_transcript,edited_transcript,started_at' @@ -84,20 +94,17 @@ export interface MobileUnifiedSearchOptions { signal?: AbortSignal } -function client(): D3roSupabaseClient { - return supabase as unknown as D3roSupabaseClient -} - function requireOptions(options: MobileUnifiedSearchOptions): void { - if (typeof options !== 'object' || options === null || Array.isArray(options)) { + if (!isRecord(options)) { throw new UnifiedSearchServiceError('invalid', 'Unified search options are required') } } function requireUserId(userId: unknown): asserts userId is string { - if (typeof userId !== 'string' || !UUID_PATTERN.test(userId)) { - throw new UnifiedSearchServiceError('auth', 'A valid authenticated user is required') - } + requireUuidWith( + userId, + () => new UnifiedSearchServiceError('auth', 'A valid authenticated user is required'), + ) } function requireQuery(query: unknown): asserts query is string { @@ -123,32 +130,8 @@ export function sanitizeUnifiedSearchQuery(value: string): string { .trim() } -export function createPostgrestLikePattern(query: string): string { - const escaped = query.replace(/[\\%_*]/g, (character) => `\\${character}`) - return `*${escaped}*` -} - -function includesQuery(value: string | null | undefined, query: string): boolean { - return value?.toLocaleLowerCase().includes(query.toLocaleLowerCase()) === true -} - -export function createMobileSearchExcerpt( - value: string | null | undefined, - query: string, - maxLength = EXCERPT_LENGTH, -): string { - const text = (value ?? '').replace(/\s+/g, ' ').trim() - if (text.length <= maxLength) return text - - const matchAt = text.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) - if (matchAt < 0) return `${text.slice(0, maxLength - 1).trimEnd()}…` - - const context = Math.max(20, Math.floor((maxLength - query.length) / 2)) - const start = Math.max(0, matchAt - context) - const end = Math.min(text.length, start + maxLength) - const excerpt = text.slice(start, end).trim() - return `${start > 0 ? '…' : ''}${excerpt}${end < text.length ? '…' : ''}` -} +export const createPostgrestLikePattern = escapePostgrestLikePattern +export const createMobileSearchExcerpt = createUnifiedSearchExcerpt function occurredAt(value: string): number { const timestamp = Date.parse(value) @@ -156,9 +139,9 @@ function occurredAt(value: string): number { } function recordResult(row: UnifiedSearchHistoryRow, query: string): UnifiedSearchResult { - const titleMatched = includesQuery(row.title, query) + const titleMatched = includesSearchQuery(row.title, query) const matchingContent = [row.polished_text, row.original_text, row.summary_text] - .find((value) => includesQuery(value, query)) + .find((value) => includesSearchQuery(value, query)) const preview = matchingContent ?? row.polished_text ?? row.original_text @@ -180,9 +163,9 @@ function meetingResult( query: string, segmentMatch?: UnifiedSearchTranscriptSegmentRow, ): UnifiedSearchResult { - const titleMatched = includesQuery(row.title, query) + const titleMatched = includesSearchQuery(row.title, query) const matchingTranscript = [row.edited_transcript, row.raw_transcript] - .find((value) => includesQuery(value, query)) + .find((value) => includesSearchQuery(value, query)) const segmentSnippet = segmentMatch ? formatSegmentSnippet(segmentMatch) : null const preview = matchingTranscript ?? segmentSnippet @@ -248,15 +231,7 @@ function boundPayloadText( return createMobileSearchExcerpt(value, query, MAX_BOUNDED_TEXT_LENGTH) } -export function mergeMobileUnifiedSearchResults( - records: readonly UnifiedSearchResult[], - meetings: readonly UnifiedSearchResult[], - limit: number, -): UnifiedSearchResult[] { - return [...records, ...meetings] - .sort((left, right) => right.occurredAt - left.occurredAt || left.id.localeCompare(right.id)) - .slice(0, limit) -} +export const mergeMobileUnifiedSearchResults = mergeUnifiedSearchResults function toSearchError(error: unknown, signal?: AbortSignal): UnifiedSearchServiceError { if (signal?.aborted || isUnifiedSearchAbortedError(error)) { @@ -264,27 +239,17 @@ function toSearchError(error: unknown, signal?: AbortSignal): UnifiedSearchServi } if (error instanceof UnifiedSearchServiceError) return error - const candidate = error as { code?: unknown; message?: unknown; name?: unknown } - if (candidate?.name === 'AbortError') { + if (isRecord(error) && error.name === 'AbortError') { return new UnifiedSearchServiceError('aborted', 'Unified search request was aborted') } - const code = typeof candidate?.code === 'string' ? candidate.code : '' - const message = typeof candidate?.message === 'string' - ? candidate.message - : 'Unified search request failed' - const lower = message.toLocaleLowerCase() - if ( - error instanceof TypeError - || lower.includes('network request failed') - || lower.includes('failed to fetch') - || lower.includes('networkerror') - ) { - return new UnifiedSearchServiceError('network', message) + const info = extractSupabaseErrorInfo(error, 'Unified search request failed') + if (isSupabaseNetworkFailure(error, info)) { + return new UnifiedSearchServiceError('network', info.message) } - if (code === 'PGRST301' || code === '42501' || lower.includes('jwt')) { - return new UnifiedSearchServiceError('auth', message) + if (isSupabaseAuthFailure(info, { include42501: true })) { + return new UnifiedSearchServiceError('auth', info.message) } - return new UnifiedSearchServiceError('server', message) + return new UnifiedSearchServiceError('server', info.message) } export function createSupabaseUnifiedSearchSource( @@ -379,7 +344,7 @@ export function createSupabaseUnifiedSearchSource( } } -const supabaseSearchSource = createSupabaseUnifiedSearchSource(client()) +const supabaseSearchSource = createSupabaseUnifiedSearchSource(getTypedSupabaseClient()) export async function searchUnifiedContent( options: MobileUnifiedSearchOptions, diff --git a/apps/mobile-rn/src/features/shared/owned-cache-files.ts b/apps/mobile-rn/src/features/shared/owned-cache-files.ts new file mode 100644 index 0000000..706a8ae --- /dev/null +++ b/apps/mobile-rn/src/features/shared/owned-cache-files.ts @@ -0,0 +1,70 @@ +import { Dirs, FileSystem } from 'react-native-file-access' + +export interface OwnedCachePathOptions { + /** Also accept `/data/data/` <-> `/data/user/0/` Android multi-user symlink mirrors. */ + androidDataUserMirror?: boolean +} + +export interface RemoveOwnedCacheFileOptions extends OwnedCachePathOptions { + onCleanupError?: (error: unknown) => Error +} + +/** + * Decodes a `file://` URI into an absolute filesystem path, returning raw paths unchanged. + */ +export function localPathFromCacheUri(uri: string): string { + if (!uri.startsWith('file://')) return uri + const decoded = decodeURIComponent(uri.slice('file://'.length)) + return decoded.startsWith('/') ? decoded : `/${decoded}` +} + +function resolveCacheRoots(androidDataUserMirror: boolean): string[] { + const base = Dirs.CacheDir.replace(/\\/g, '/').replace(/\/$/, '') + const roots = [base] + if (androidDataUserMirror) { + if (base.startsWith('/data/data/')) { + roots.push(`/data/user/0/${base.slice('/data/data/'.length)}`) + } else if (base.startsWith('/data/user/0/')) { + roots.push(`/data/data/${base.slice('/data/user/0/'.length)}`) + } + } + return roots +} + +/** + * Checks whether `path` resides strictly under the app's own cache directory without `..` traversal. + */ +export function isOwnedCachePath( + path: string, + options: OwnedCachePathOptions = {}, +): boolean { + const normalized = path.replace(/\\/g, '/') + return resolveCacheRoots(options.androidDataUserMirror === true).some((root) => { + if (!normalized.startsWith(`${root}/`)) return false + const relative = normalized.slice(root.length + 1) + return relative.length > 0 && !relative.split('/').includes('..') + }) +} + +/** + * Deletes a temporary cache file only when it lives inside the app's owned cache root. + */ +export async function removeOwnedCacheFile( + path: string, + createOutsideRootError: () => Error, + options: RemoveOwnedCacheFileOptions = {}, +): Promise { + if (!isOwnedCachePath(path, options)) { + throw createOutsideRootError() + } + try { + if (await FileSystem.exists(path)) { + await FileSystem.unlink(path) + } + } catch (error) { + if (options.onCleanupError !== undefined) { + throw options.onCleanupError(error) + } + throw error + } +} diff --git a/apps/mobile-rn/src/features/shared/service-guards.ts b/apps/mobile-rn/src/features/shared/service-guards.ts new file mode 100644 index 0000000..fd6f45e --- /dev/null +++ b/apps/mobile-rn/src/features/shared/service-guards.ts @@ -0,0 +1,207 @@ +import type { D3roSupabaseClient } from '@d3ro/api-client' +import { isRecord, isUuid } from '@d3ro/core/guards' +import { supabase } from '../../lib/supabase' + +export interface SupabaseErrorInfo { + readonly code: string + readonly message: string + readonly lower: string +} + +/** + * Returns the shared mobile Supabase client cast to the strongly-typed D3RO schema. + */ +export function getTypedSupabaseClient(): D3roSupabaseClient { + return supabase as unknown as D3roSupabaseClient +} + +/** + * Asserts that `value` is a valid UUID or throws the caller's domain error. + */ +export function requireUuidWith( + value: unknown, + createError: () => E, +): asserts value is string { + if (!isUuid(value)) { + throw createError() + } +} + +/** + * Builds a single-argument UUID assertion helper bound to a domain error factory. + */ +export function createUuidAssert( + createError: () => E, +): (value: unknown) => void { + return (value: unknown): void => { + requireUuidWith(value, createError) + } +} + +/** + * Builds a labeled UUID assertion helper bound to a domain error factory. + */ +export function createLabeledUuidAssert( + createError: (label: string) => E, +): (value: unknown, label: string) => void { + return (value: unknown, label: string): void => { + requireUuidWith(value, () => createError(label)) + } +} + +/** + * Validates `value` as a UUID string and normalizes casing/whitespace as configured. + */ +export function parseUuidWith( + value: unknown, + createError: () => E, + options: { trim?: boolean; normalizeCase?: 'lower' | 'preserve' } = {}, +): string { + if (typeof value !== 'string') { + throw createError() + } + const candidate = options.trim ? value.trim() : value + if (!isUuid(candidate)) { + throw createError() + } + return options.normalizeCase === 'preserve' ? candidate : candidate.toLowerCase() +} + +/** + * Validates that `value` is a plain JSON-like record object or throws the caller's domain error. + */ +export function assertRecordWith( + value: unknown, + createError: () => E, +): Record { + if (!isRecord(value)) { + throw createError() + } + return value +} + +/** + * Validates that `value` is a string within inclusive `[minLength, maxLength]` bounds. + */ +export function parseBoundedStringWith( + value: unknown, + createError: () => E, + options: { minLength?: number; maxLength: number }, +): string { + const minLength = options.minLength ?? 1 + if ( + typeof value !== 'string' + || value.length < minLength + || value.length > options.maxLength + ) { + throw createError() + } + return value +} + +/** + * Validates that `value` is a safe integer within `[min, max]`. + */ +export function parseSafeIntegerWith( + value: unknown, + createError: () => E, + options: { min?: number; max?: number } = {}, +): number { + const min = options.min ?? 0 + const max = options.max ?? Number.MAX_SAFE_INTEGER + if ( + typeof value !== 'number' + || !Number.isSafeInteger(value) + || value < min + || value > max + ) { + throw createError() + } + return value +} + +/** + * Validates an ISO-8601 timestamp string and optionally normalizes it via `toISOString()`. + */ +export function parseIsoTimestampWith( + value: unknown, + createError: () => E, + options: { + requireTimePrefix?: boolean + normalizeToIso?: boolean + maxLength?: number + } = {}, +): string { + if (typeof value !== 'string' || value.length === 0) { + throw createError() + } + if (options.maxLength !== undefined && value.length > options.maxLength) { + throw createError() + } + if (options.requireTimePrefix && !/^\d{4}-\d{2}-\d{2}T/.test(value)) { + throw createError() + } + if (!Number.isFinite(Date.parse(value))) { + throw createError() + } + return options.normalizeToIso ? new Date(value).toISOString() : value +} + +/** + * Extracts normalized PostgREST/Supabase error metadata without casting away type safety. + */ +export function extractSupabaseErrorInfo( + error: unknown, + fallbackMessage: string, +): SupabaseErrorInfo { + const candidate = isRecord(error) ? error : null + const code = typeof candidate?.code === 'string' ? candidate.code : '' + const message = typeof candidate?.message === 'string' + ? candidate.message + : fallbackMessage + return { + code, + message, + lower: message.toLowerCase(), + } +} + +/** + * Identifies client-side network failures raised by fetch / React Native networking. + */ +export function isSupabaseNetworkFailure( + error: unknown, + info: SupabaseErrorInfo, +): boolean { + return ( + error instanceof TypeError + || info.lower.includes('network request failed') + || info.lower.includes('failed to fetch') + || info.lower.includes('networkerror') + ) +} + +/** + * Identifies missing/expired JWT authorization failures from PostgREST/Supabase. + */ +export function isSupabaseAuthFailure( + info: SupabaseErrorInfo, + options: { include42501?: boolean } = {}, +): boolean { + return ( + info.code === 'PGRST301' + || info.lower.includes('jwt') + || (options.include42501 === true && info.code === '42501') + ) +} + +/** + * Identifies RLS / Postgres permission denial failures. + */ +export function isSupabaseForbiddenFailure(info: SupabaseErrorInfo): boolean { + return ( + info.code === '42501' + || info.lower.includes('permission denied') + || info.lower.includes('row-level security') + ) +} diff --git a/apps/mobile-rn/src/features/talk/llm-stream-service.ts b/apps/mobile-rn/src/features/talk/llm-stream-service.ts index 8ea9b3b..7468ede 100644 --- a/apps/mobile-rn/src/features/talk/llm-stream-service.ts +++ b/apps/mobile-rn/src/features/talk/llm-stream-service.ts @@ -1,3 +1,4 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' import { SUPABASE_ANON_KEY, SUPABASE_URL } from '@d3ro/core/supabase-config' import { ChatServiceError, @@ -31,7 +32,6 @@ interface SseAccumulator { } const DEFAULT_TIMEOUT_MS = 45_000 -const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i class Utf8StreamDecoder { private pending: number[] = [] @@ -95,9 +95,6 @@ class Utf8StreamDecoder { } } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function errorCodeForResponse(status: number, body: unknown): ChatErrorCode { const serverCode = isRecord(body) && typeof body.error === 'string' @@ -282,7 +279,7 @@ export async function streamTalkResponse( } const generationId = response.headers.get('X-D3RO-Generation-Id')?.trim() ?? '' - if (!UUID_PATTERN.test(generationId)) { + if (!isUuid(generationId)) { throw new ChatServiceError('INVALID_RESPONSE', true) } const text = await consumeStreamingBody(response, options.onTextDelta) diff --git a/apps/mobile-rn/src/features/teams/team-service.ts b/apps/mobile-rn/src/features/teams/team-service.ts index 45c2202..ce08ae3 100644 --- a/apps/mobile-rn/src/features/teams/team-service.ts +++ b/apps/mobile-rn/src/features/teams/team-service.ts @@ -1,8 +1,14 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' import type { RealtimeChannel } from '@supabase/supabase-js' import type { Meeting, Team, TeamRole } from '@d3ro/api-client' import { PUBLIC_SITE_ORIGIN, SITE_URLS } from '@d3ro/core/web-urls' import { supabase } from '../../lib/supabase' import { invokeEdgeFunction, type EdgeFunctionFailure } from '../../lib/edge-functions' +import { + createLabeledUuidAssert, + isSupabaseAuthFailure, + isSupabaseNetworkFailure, +} from '../shared/service-guards' export interface TeamSummary extends Team { role: TeamRole @@ -96,7 +102,6 @@ export interface TeamSubscription { unsubscribe: () => Promise } -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 EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ const INVITE_TOKEN_PATTERN = /^[A-Za-z0-9_-]{32}$/ const TEAM_NAME_MAX_LENGTH = 80 @@ -105,9 +110,6 @@ const TRUSTED_INVITE_ORIGIN = PUBLIC_SITE_ORIGIN // '/accept-invite' — 사이트 정본 URL에서 경로만 떼어 끝 슬래시 유무를 모두 허용한다. const INVITE_PATH = SITE_URLS.acceptInvite.slice(PUBLIC_SITE_ORIGIN.length).replace(/\/$/, '') -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function isIsoDate(value: unknown): value is string { return typeof value === 'string' && Number.isFinite(Date.parse(value)) @@ -122,11 +124,9 @@ function firstRow(value: unknown): unknown { return value } -function requireUuid(value: string, label: string): void { - if (!UUID_PATTERN.test(value)) { - throw new TeamServiceError('validation', `${label} is invalid`) - } -} +const requireUuid = createLabeledUuidAssert( + (label) => new TeamServiceError('validation', `${label} is invalid`), +) export function normalizeTeamName(value: string): string { const name = value.trim().replace(/\s+/g, ' ') @@ -204,11 +204,11 @@ function normalizeTeam(value: unknown): Team { const avatarUrl = value.avatar_url ?? null if ( typeof value.id !== 'string' - || !UUID_PATTERN.test(value.id) + || !isUuid(value.id) || typeof value.name !== 'string' || value.name.trim().length === 0 || typeof value.owner_id !== 'string' - || !UUID_PATTERN.test(value.owner_id) + || !isUuid(value.owner_id) || (avatarUrl !== null && typeof avatarUrl !== 'string') || !isIsoDate(value.created_at) || !isIsoDate(value.updated_at) @@ -236,7 +236,7 @@ export function normalizeTeamMember(value: unknown): TeamMemberDirectoryEntry { const avatarUrl = value.avatar_url ?? value.avatarUrl ?? null if ( typeof userId !== 'string' - || !UUID_PATTERN.test(userId) + || !isUuid(userId) || !isRole(value.role) || !isIsoDate(joinedAt) || (displayName !== null && typeof displayName !== 'string') @@ -262,7 +262,7 @@ export function normalizeTeamInvite(value: unknown): TeamInviteListEntry { const invitedBy = value.invited_by ?? value.invitedBy ?? null if ( typeof value.id !== 'string' - || !UUID_PATTERN.test(value.id) + || !isUuid(value.id) || typeof value.email !== 'string' || (value.role !== 'admin' && value.role !== 'member') || !isIsoDate(expiresAt) @@ -305,7 +305,7 @@ export function normalizeTeamActivity(value: unknown): TeamActivityEntry { const body = value.body ?? null if ( typeof value.id !== 'string' - || !UUID_PATTERN.test(value.id) + || !isUuid(value.id) || typeof value.team_id !== 'string' || !isActivityKind(value.kind) || (actorId !== null && typeof actorId !== 'string') @@ -343,13 +343,12 @@ function toTeamServiceError(error: unknown): TeamServiceError { if (error instanceof TeamServiceError) return error const details = errorDetails(error) const lower = details.message.toLowerCase() + const info = { code: details.code, message: details.message, lower } const hasCode = (code: string): boolean => details.code === code || lower.includes(code) - if ( - error instanceof TypeError - || lower.includes('network request failed') - || lower.includes('failed to fetch') - ) return new TeamServiceError('network', details.message || 'Team request failed') - if (details.code === 'PGRST301' || lower.includes('jwt') || lower.includes('not authenticated')) { + if (isSupabaseNetworkFailure(error, info)) { + return new TeamServiceError('network', details.message || 'Team request failed') + } + if (isSupabaseAuthFailure(info) || lower.includes('not authenticated')) { return new TeamServiceError('auth', details.message || 'Authentication is required') } if (details.code === 'PGRST202' || lower.includes('could not find the function')) { @@ -545,7 +544,7 @@ export async function createTeamActivity( p_body: trimmed === '' ? null : trimmed, p_metadata: {}, }) - if (!isRecord(result) || typeof result.id !== 'string' || !UUID_PATTERN.test(result.id)) { + if (!isRecord(result) || !isUuid(result.id)) { throw new TeamServiceError('invalid-response', 'Team activity response is malformed') } return { @@ -720,7 +719,7 @@ export async function createTeamInvite( const emailError = data.email_error ?? null if ( typeof data.id !== 'string' - || !UUID_PATTERN.test(data.id) + || !isUuid(data.id) || typeof data.url !== 'string' || !isIsoDate(expiresAt) || typeof emailSent !== 'boolean' @@ -760,7 +759,7 @@ export async function acceptTeamInvite(tokenValue: string): Promise new Error('invalid_generation_identity')) function storageKey(userId: string, meetingId: string, templateId: string): string { requireUuid(userId) @@ -22,7 +21,7 @@ export async function getOrCreateGenerationIdempotencyKey( ): Promise { const key = storageKey(userId, meetingId, templateId) const existing = await AsyncStorage.getItem(key) - if (existing !== null && UUID_PATTERN.test(existing)) return existing + if (isUuid(existing)) return existing if (existing !== null) await AsyncStorage.removeItem(key) const created = createUuidV4() await AsyncStorage.setItem(key, created) diff --git a/apps/mobile-rn/src/features/templates/template-service.ts b/apps/mobile-rn/src/features/templates/template-service.ts index 0f042db..68afb84 100644 --- a/apps/mobile-rn/src/features/templates/template-service.ts +++ b/apps/mobile-rn/src/features/templates/template-service.ts @@ -1,6 +1,6 @@ -import type { RealtimeChannel, SupabaseClient } from '@supabase/supabase-js' +import { isRecord, isUuid } from '@d3ro/core/guards' +import type { RealtimeChannel } from '@supabase/supabase-js' import type { - Database, DictationTemplateField, MeetingDocument, TemplateKind, @@ -9,6 +9,13 @@ import type { } from '@d3ro/api-client' import { SUPABASE_URL } from '@d3ro/core/supabase-config' import { supabase } from '../../lib/supabase' +import { + createLabeledUuidAssert, + extractSupabaseErrorInfo, + getTypedSupabaseClient, + isSupabaseAuthFailure, + isSupabaseNetworkFailure, +} from '../shared/service-guards' import { asyncStorageGenerationKeyStore, type GenerationKeyStore, @@ -59,20 +66,13 @@ export interface TemplateSubscription { unsubscribe: () => Promise } -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 FIELD_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]*$/ const TEMPLATE_COLUMNS = 'id,user_id,template_kind,builtin_key,name,description,fields,output_format,template_type,system_prompt,is_builtin,revision,created_at,updated_at' const SELECTION_COLUMNS = 'user_id,template_kind,template_id,revision,updated_at' -function db(): SupabaseClient { - return supabase as unknown as SupabaseClient -} - -function requireUuid(value: string, label: string): void { - if (!UUID_PATTERN.test(value)) { - throw new TemplateServiceError('auth', `A valid ${label} is required`) - } -} +const requireUuid = createLabeledUuidAssert( + (label) => new TemplateServiceError('auth', `A valid ${label} is required`), +) function normalizeSingleLine(value: string): string { return value.trim().replace(/\s+/g, ' ') @@ -160,38 +160,29 @@ export function normalizeTemplateDraft( function toServiceError(error: unknown): TemplateServiceError { if (error instanceof TemplateServiceError) return error - const candidate = error as { code?: unknown; message?: unknown } - const code = typeof candidate?.code === 'string' ? candidate.code : '' - const message = typeof candidate?.message === 'string' - ? candidate.message - : 'Template request failed' - const lower = message.toLowerCase() - if ( - error instanceof TypeError - || lower.includes('network request failed') - || lower.includes('failed to fetch') - || lower.includes('networkerror') - || lower.includes('abort') - ) return new TemplateServiceError('network', message, true) - if (code === 'PT409' || lower.includes('revision_conflict')) { - return new TemplateServiceError('conflict', message, true) + const info = extractSupabaseErrorInfo(error, 'Template request failed') + if (isSupabaseNetworkFailure(error, info) || info.lower.includes('abort')) { + return new TemplateServiceError('network', info.message, true) } - if (lower.includes('builtin_template_immutable')) { - return new TemplateServiceError('builtin', message) + if (info.code === 'PT409' || info.lower.includes('revision_conflict')) { + return new TemplateServiceError('conflict', info.message, true) } - if (code === '42501') return new TemplateServiceError('forbidden', message) - if (code === 'P0002') return new TemplateServiceError('not-found', message) - if (code === 'PGRST301' || lower.includes('jwt')) { - return new TemplateServiceError('auth', message) + if (info.lower.includes('builtin_template_immutable')) { + return new TemplateServiceError('builtin', info.message) } - if (code.startsWith('22')) return new TemplateServiceError('validation', message) - return new TemplateServiceError('server', message, true) + if (info.code === '42501') return new TemplateServiceError('forbidden', info.message) + if (info.code === 'P0002') return new TemplateServiceError('not-found', info.message) + if (isSupabaseAuthFailure(info)) { + return new TemplateServiceError('auth', info.message) + } + if (info.code.startsWith('22')) return new TemplateServiceError('validation', info.message) + return new TemplateServiceError('server', info.message, true) } function assertTemplate(value: UserTemplate | null, userId: string): UserTemplate { if ( value === null - || !UUID_PATTERN.test(value.id) + || !isUuid(value.id) || value.user_id !== userId || !['dictation', 'meeting_document'].includes(value.template_kind) || !Number.isSafeInteger(value.revision) @@ -216,7 +207,7 @@ export async function loadTemplateLibrary( const search = sanitizeTemplateSearch(searchValue) try { await rpc('bootstrap_user_templates_v1') - let templateQuery = db() + let templateQuery = getTypedSupabaseClient() .from('user_templates') .select(TEMPLATE_COLUMNS) .eq('user_id', userId) @@ -230,7 +221,7 @@ export async function loadTemplateLibrary( const [templateResult, selectionResult] = await Promise.all([ templateQuery, - db() + getTypedSupabaseClient() .from('user_template_selections') .select(SELECTION_COLUMNS) .eq('user_id', userId), @@ -242,7 +233,7 @@ export async function loadTemplateLibrary( .map((row) => assertTemplate(row as UserTemplate, userId)) const selections: TemplateLibrary['selections'] = {} for (const selection of selectionResult.data ?? []) { - if (selection.user_id !== userId || !UUID_PATTERN.test(selection.template_id)) { + if (selection.user_id !== userId || !isUuid(selection.template_id)) { throw new TemplateServiceError('server', 'Server returned an invalid template selection') } selections[selection.template_kind] = selection @@ -389,9 +380,6 @@ function generationError(status: number, body: unknown): TemplateServiceError { return new TemplateServiceError('server', code || 'Document generation failed', true, response) } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} export async function generateMeetingDocument( options: GenerateMeetingDocumentOptions, diff --git a/apps/mobile-rn/src/lib/billing-context.tsx b/apps/mobile-rn/src/lib/billing-context.tsx index c6d3c8d..60bd3d7 100644 --- a/apps/mobile-rn/src/lib/billing-context.tsx +++ b/apps/mobile-rn/src/lib/billing-context.tsx @@ -1,3 +1,4 @@ +import { isRecord, isUuid } from '@d3ro/core/guards' import { createContext, useCallback, @@ -84,7 +85,6 @@ export interface IapVerifyResult { const BillingContext = createContext(null) const PRODUCT_IDS = new Set(GOOGLE_PLAY_SUBSCRIPTION_IDS) const GOOGLE_PLAY_PACKAGE_NAME = 'com.d3ro.voice' -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 PRODUCT_TIERS: Readonly> = { d3ro_voice_pro_monthly: 'pro', d3ro_voice_pro_plus_monthly: 'pro_plus', @@ -130,9 +130,6 @@ function purchaseIdentity(purchase: Purchase): string | null { return `${purchase.productId}:${token}` } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} export function isVerifiedActivePurchase( result: IapVerifyResult | null | undefined, @@ -171,7 +168,7 @@ function verifiedRestorableProduct( || !isRecord(result.verification) || !isRecord(result.purchase) || typeof result.purchase.purchase_id !== 'string' - || !UUID_PATTERN.test(result.purchase.purchase_id) + || !isUuid(result.purchase.purchase_id) || result.finish_transaction !== false ) throw new Error('restore_verification_response_invalid') diff --git a/apps/mobile-rn/src/lib/locale-speech.ts b/apps/mobile-rn/src/lib/locale-speech.ts new file mode 100644 index 0000000..6b34bd1 --- /dev/null +++ b/apps/mobile-rn/src/lib/locale-speech.ts @@ -0,0 +1,16 @@ +import { toBcp47, type Locale } from '@d3ro/i18n/shared' + +/** + * Maps an app UI locale to a platform TTS/speech BCP-47 language tag while + * preserving the explicit regional defaults expected by mobile speech providers. + */ +export function toSpeechLanguageTag(locale: Locale): string { + switch (locale) { + case 'ko': + return 'ko-KR' + case 'en': + return 'en-US' + default: + return toBcp47(locale) + } +} diff --git a/apps/mobile-rn/src/lib/native-config.ts b/apps/mobile-rn/src/lib/native-config.ts index 9ae3ef6..1c01762 100644 --- a/apps/mobile-rn/src/lib/native-config.ts +++ b/apps/mobile-rn/src/lib/native-config.ts @@ -1,3 +1,4 @@ +import { isUuid } from '@d3ro/core/guards' import { NativeModules, Platform } from 'react-native' export interface MobileRuntimeConfig { @@ -57,7 +58,7 @@ export function normalizeMobileRuntimeConfig( || typeof candidate.playStoreInstalled !== 'boolean' || typeof candidate.installedFromPlayStore !== 'boolean' || typeof candidate.installationId !== 'string' - || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(candidate.installationId) + || !isUuid(candidate.installationId) || typeof candidate.deviceName !== 'string' || candidate.deviceName.trim().length === 0 || candidate.deviceName.length > 120 diff --git a/apps/mobile-rn/src/lib/preferences-store.ts b/apps/mobile-rn/src/lib/preferences-store.ts index 5966238..9b6b119 100644 --- a/apps/mobile-rn/src/lib/preferences-store.ts +++ b/apps/mobile-rn/src/lib/preferences-store.ts @@ -6,6 +6,8 @@ // unit-tested without React, AsyncStorage or Supabase. The React provider only // subscribes to snapshots and forwards triggers (owner change, foreground, // realtime rows, Settings retry). +import { isRecord } from '@d3ro/core/guards' +import { isValidLocale, type Locale } from '@d3ro/i18n/shared' import { isMobileThemeMode, type MobileThemeMode } from '../theme/mobile-theme' export const CURRENT_ONBOARDING_VERSION = 1 @@ -29,7 +31,7 @@ export const USER_SETTINGS_COLUMNS = [ const MAX_WRITE_ATTEMPTS = 3 -export type SupportedMobileLocale = 'ko' | 'en' +export type SupportedMobileLocale = Locale export type PreferencesSyncStatus = | 'loading' | 'local' @@ -195,12 +197,9 @@ export function preferencesOwnerFor(userId: string | null): PreferencesOwner { } } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function normalizeLocale(value: unknown): SupportedMobileLocale { - return value === 'en' ? 'en' : 'ko' + return typeof value === 'string' && isValidLocale(value) ? value : 'ko' } function normalizeNullableString(value: unknown): string | null { @@ -265,7 +264,7 @@ export function normalizePreferencesPatch(value: unknown): MobilePreferencesPatc const patch: MobilePreferencesPatch = {} if (isMobileThemeMode(value.themeMode)) patch.themeMode = value.themeMode - if (value.locale === 'ko' || value.locale === 'en') patch.locale = value.locale + if (typeof value.locale === 'string' && isValidLocale(value.locale)) patch.locale = value.locale if (typeof value.hapticEnabled === 'boolean') patch.hapticEnabled = value.hapticEnabled if (typeof value.autoPolishEnabled === 'boolean') { patch.autoPolishEnabled = value.autoPolishEnabled diff --git a/apps/mobile-rn/src/screens/AccountScreen.tsx b/apps/mobile-rn/src/screens/AccountScreen.tsx index 52b1c03..bdd9b34 100644 --- a/apps/mobile-rn/src/screens/AccountScreen.tsx +++ b/apps/mobile-rn/src/screens/AccountScreen.tsx @@ -24,6 +24,7 @@ import { d3roNativeFonts, } from '@d3ro/ui-native' import { useI18n } from '@d3ro/i18n' +import { LOCALE_META } from '@d3ro/i18n/shared' import { useAuth } from '../lib/auth-context' import { supabase } from '../lib/supabase' import { performAccountLogout } from '../lib/account-exit' @@ -107,11 +108,24 @@ export default function AccountScreen({ const [authCapabilities, setAuthCapabilities] = useState(null) const identityAccountRef = useRef(null) const identityRequestRef = useRef(0) + const profileRequestRef = useRef(0) + const mountedRef = useRef(true) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + profileRequestRef.current += 1 + identityRequestRef.current += 1 + } + }, []) const providers = useMemo(() => user ? collectProviders(user) : [], [user]) const loadProfile = useCallback(async (): Promise => { + const request = ++profileRequestRef.current if (!user) { + if (!mountedRef.current) return setProfile(null) setLoadingProfile(false) return @@ -128,6 +142,7 @@ export default function AccountScreen({ .eq('id', user.id) .single() + if (!mountedRef.current || profileRequestRef.current !== request) return if (error) throw error if (!data) throw new Error(t('mobile.account.profileMissing')) @@ -138,10 +153,13 @@ export default function AccountScreen({ setProfileLocale(loadedProfile.locale || 'ko') setAvatarFailed(false) } catch (error) { + if (!mountedRef.current || profileRequestRef.current !== request) return setProfile(null) setErrorMessage(error instanceof Error ? error.message : String(error)) } finally { - setLoadingProfile(false) + if (mountedRef.current && profileRequestRef.current === request) { + setLoadingProfile(false) + } } }, [t, user]) @@ -193,7 +211,7 @@ export default function AccountScreen({ }, [refreshIdentities, user]) const isCurrentIdentityAccount = useCallback((expectedUserId: string): boolean => ( - identityAccountRef.current === expectedUserId + mountedRef.current && identityAccountRef.current === expectedUserId ), []) async function linkIdentity(provider: ManagedOAuthProvider): Promise { @@ -294,6 +312,8 @@ export default function AccountScreen({ async function saveProfile(): Promise { if (!user || !profile || activeAction) return + const expectedUserId = user.id + const request = ++profileRequestRef.current const normalizedName = name.trim() const normalizedAvatarUrl = avatarUrl.trim() @@ -330,10 +350,17 @@ export default function AccountScreen({ avatar_url: normalizedAvatarUrl || null, locale: profileLocale, }) - .eq('id', user.id) + .eq('id', expectedUserId) .select(PROFILE_COLUMNS) .single() + if ( + !mountedRef.current + || identityAccountRef.current !== expectedUserId + || profileRequestRef.current !== request + ) { + return + } if (error) throw error if (!data) throw new Error(t('mobile.account.profileUpdateMissing')) @@ -344,6 +371,13 @@ export default function AccountScreen({ setProfileLocale(savedProfile.locale || 'ko') setSuccessMessage(t('mobile.account.profileSaved')) } catch (error) { + if ( + !mountedRef.current + || identityAccountRef.current !== expectedUserId + || profileRequestRef.current !== request + ) { + return + } // Roll every optimistic field back to the last server-confirmed row. setProfile(previous) setName(previous.name ?? '') @@ -351,7 +385,7 @@ export default function AccountScreen({ setProfileLocale(previous.locale || 'ko') setErrorMessage(error instanceof Error ? error.message : String(error)) } finally { - setActiveAction(null) + if (mountedRef.current) setActiveAction(null) } } @@ -368,11 +402,12 @@ export default function AccountScreen({ purgeLocalSession, }) } catch { + if (!mountedRef.current) return const message = t('mobile.auth.logoutFailed') setErrorMessage(message) Alert.alert(t('mobile.auth.errorTitle'), message) } finally { - setActiveAction(null) + if (mountedRef.current) setActiveAction(null) } } @@ -406,6 +441,7 @@ export default function AccountScreen({ }, purgeLocalSession, }) + if (!mountedRef.current) return if (!result.ok) { const message = t(accountDeletionFailureMessageKey(result.code)) setErrorMessage(message) @@ -413,11 +449,12 @@ export default function AccountScreen({ return } } catch { + if (!mountedRef.current) return const message = t('mobile.auth.localDataCleanupBody') setErrorMessage(message) Alert.alert(t('mobile.auth.errorTitle'), message) } finally { - setActiveAction(null) + if (mountedRef.current) setActiveAction(null) } } @@ -535,28 +572,24 @@ export default function AccountScreen({ {t('mobile.account.locale')} - {(['ko', 'en'] as const).map((candidate) => ( + {LOCALE_META.map((item) => ( setProfileLocale(candidate)} + onPress={() => setProfileLocale(item.code)} disabled={Boolean(activeAction)} > - {candidate === 'ko' - ? t('mobile.account.languageKorean') - : t('mobile.account.languageEnglish')} + {item.nativeName} ))} @@ -994,15 +1027,17 @@ function createStyles(palette: Palette) { paddingHorizontal: 13, paddingVertical: 12, }, - localeRow: { flexDirection: 'row', gap: 9 }, + localeRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 9 }, localeButton: { - flex: 1, + minWidth: '30%', + flexGrow: 1, minHeight: 48, alignItems: 'center', borderRadius: 8, borderWidth: 1, borderColor: palette.border.default, backgroundColor: palette.bg.inset, + paddingHorizontal: 8, paddingVertical: 11, }, localeButtonActive: { borderColor: palette.accent.main, backgroundColor: palette.accent.dim }, diff --git a/apps/mobile-rn/src/screens/CommandsScreen.tsx b/apps/mobile-rn/src/screens/CommandsScreen.tsx index b71cec0..68dd52d 100644 --- a/apps/mobile-rn/src/screens/CommandsScreen.tsx +++ b/apps/mobile-rn/src/screens/CommandsScreen.tsx @@ -16,6 +16,7 @@ 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 { useResponsiveLayout } from '@d3ro/ui-native' import { useAuth } from '../lib/auth-context' import { useMobilePreferences } from '../lib/preferences-context' import { supabase } from '../lib/supabase' @@ -93,6 +94,7 @@ export default function CommandsScreen(): React.ReactElement { const { t } = useI18n() const { user, session } = useAuth() const { palette, preferences } = useMobilePreferences() + const { contentMaxWidth, isLargeScreen, wideContentMaxWidth } = useResponsiveLayout() const styles = useMemo(() => createStyles(palette), [palette]) const alive = useRef(true) const request = useRef(null) @@ -309,7 +311,7 @@ export default function CommandsScreen(): React.ReactElement { {t('mobile.commands.loading')} ) : ( - + {commands.map((command) => { const selectedNow = selected?.id === command.id const active = activeId === command.id @@ -369,7 +371,12 @@ export default function CommandsScreen(): React.ReactElement { return ( {t('mobile.commands.testBench')} - + {selected ? t('mobile.commands.selected', { name: displayName(selected) }) @@ -574,7 +581,7 @@ type Palette = ReturnType['palette'] function createStyles(palette: Palette): ReturnType { return StyleSheet.create({ container: { flex: 1, backgroundColor: palette.bg.app }, - content: { paddingHorizontal: 20 }, + content: { paddingHorizontal: 20, width: '100%', alignSelf: 'center' }, header: { minHeight: 76, flexDirection: 'row', alignItems: 'center', gap: 10 }, back: { minWidth: 48, minHeight: 48, alignItems: 'center', justifyContent: 'center' }, headerCopy: { flex: 1, gap: 3 }, @@ -583,7 +590,9 @@ function createStyles(palette: Palette): ReturnType { loading: { minHeight: 160, alignItems: 'center', justifyContent: 'center', gap: 10 }, error: { gap: 10, marginBottom: 12, borderColor: palette.tag.red }, list: { gap: 10, marginBottom: 24 }, + listGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 12 }, card: { gap: 10 }, + cardGridItem: { width: '48.5%', flexGrow: 1 }, selected: { borderColor: palette.accent.main, backgroundColor: palette.accent.dim }, active: { borderColor: palette.tag.green }, copy: { gap: 7 }, @@ -591,7 +600,7 @@ function createStyles(palette: Palette): ReturnType { name: { flex: 1 }, actions: { flexDirection: 'row', flexWrap: 'wrap', gap: 7 }, sectionLabel: { marginBottom: 8, letterSpacing: 2 }, - bench: { gap: 13 }, + bench: { gap: 13, width: '100%' }, input: { minHeight: 130, maxHeight: 250, @@ -607,8 +616,8 @@ function createStyles(palette: Palette): ReturnType { output: { gap: 7, padding: 12, borderWidth: 1, borderRadius: 9, borderColor: palette.accent.main }, outputHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }, outputText: { lineHeight: 21 }, - backdrop: { flex: 1, justifyContent: 'flex-end', padding: 18, backgroundColor: palette.scrim }, - editor: { gap: 13, maxHeight: '92%' }, + backdrop: { flex: 1, justifyContent: 'flex-end', alignItems: 'center', padding: 18, backgroundColor: palette.scrim }, + editor: { gap: 13, maxHeight: '92%', maxWidth: 560, width: '100%' }, editorActions: { flexDirection: 'row', justifyContent: 'flex-end', gap: 9 }, }) } diff --git a/apps/mobile-rn/src/screens/DictionaryScreen.tsx b/apps/mobile-rn/src/screens/DictionaryScreen.tsx index 9b073ca..8247504 100644 --- a/apps/mobile-rn/src/screens/DictionaryScreen.tsx +++ b/apps/mobile-rn/src/screens/DictionaryScreen.tsx @@ -21,6 +21,7 @@ import { import { useIsFocused } from '@react-navigation/native' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { useI18n, type TranslationKey } from '@d3ro/i18n' +import { useResponsiveLayout } from '@d3ro/ui-native' import type { DictionaryEntry } from '@d3ro/api-client' import { useAuth } from '../lib/auth-context' import { useMobilePreferences } from '../lib/preferences-context' @@ -90,6 +91,7 @@ export default function DictionaryScreen(): React.ReactElement { const { user } = useAuth() const isFocused = useIsFocused() const { palette } = useMobilePreferences() + const { gridColumns, wideContentMaxWidth } = useResponsiveLayout() const styles = useMemo(() => createStyles(palette), [palette]) const requestGeneration = useRef(0) const realtimeTimer = useRef | null>(null) @@ -277,7 +279,10 @@ export default function DictionaryScreen(): React.ReactElement { }, [deletingId, load, t, user?.id]) const renderEntry = useCallback(({ item }: { item: DictionaryEntry }): React.ReactElement => ( - + 1 && styles.entryCardGrid]} + testID={`dictionary-entry-${item.id}`} + > {item.word} @@ -312,7 +317,7 @@ export default function DictionaryScreen(): React.ReactElement { /> - ), [deletingId, openEdit, removeEntry, styles, t]) + ), [deletingId, gridColumns, openEdit, removeEntry, styles, t]) const listEmpty = loading ? ( @@ -368,7 +373,7 @@ export default function DictionaryScreen(): React.ReactElement { )} - + 1 ? styles.columnRow : undefined} keyExtractor={(item) => item.id} renderItem={renderEntry} contentContainerStyle={entries.length === 0 - ? styles.emptyList - : [styles.listContent, { paddingBottom: Math.max(insets.bottom, 24) }]} + ? [styles.emptyList, { maxWidth: wideContentMaxWidth }] + : [styles.listContent, { maxWidth: wideContentMaxWidth, paddingBottom: Math.max(insets.bottom, 24) }]} keyboardShouldPersistTaps="handled" refreshControl={( { backgroundColor: palette.accent.dim, }, searchArea: { + width: '100%', + alignSelf: 'center', paddingHorizontal: 20, paddingTop: 12, paddingBottom: 10, @@ -631,8 +641,9 @@ function createStyles(palette: Palette): ReturnType { backgroundColor: palette.accent.main, borderColor: palette.accent.main, }, - listContent: { padding: 20 }, - emptyList: { flexGrow: 1 }, + listContent: { padding: 20, width: '100%', alignSelf: 'center' }, + columnRow: { gap: 12 }, + emptyList: { flexGrow: 1, width: '100%', alignSelf: 'center' }, centerState: { flex: 1, minHeight: 280, @@ -643,6 +654,7 @@ function createStyles(palette: Palette): ReturnType { }, centerText: { textAlign: 'center', lineHeight: 21 }, entryCard: { marginBottom: 12, gap: 10 }, + entryCardGrid: { flex: 1 }, entryHeader: { flexDirection: 'row', alignItems: 'flex-start', @@ -660,7 +672,7 @@ function createStyles(palette: Palette): ReturnType { borderColor: palette.border.subtle, }, entryActions: { flexDirection: 'row', gap: 10, marginTop: 4 }, - entryButton: { flex: 1, minHeight: 48 }, + entryButton: { flex: 1, maxWidth: 180, minHeight: 48 }, loadMore: { flexDirection: 'row', justifyContent: 'center', diff --git a/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx b/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx index 18b3aa5..33cfdba 100644 --- a/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx +++ b/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ActivityIndicator, Alert, @@ -18,6 +18,7 @@ import { PhysicalButton, } from '@d3ro/ui-native' import { useI18n, type TranslationKey } from '@d3ro/i18n' +import { formatBytes, formatDurationClockFromMs } from '@d3ro/core/format' import type { AudioFile, HistoryEntry } from '@d3ro/api-client' import { useAuth } from '../lib/auth-context' import { @@ -84,6 +85,10 @@ export default function HistoryDetailScreen({ const { palette } = useMobilePreferences() const styles = useMemo(() => createStyles(palette), [palette]) const player = useSoundWithStates() + const playerRef = useRef(player) + playerRef.current = player + const mountedRef = useRef(true) + const loadGenerationRef = useRef(0) const [detail, setDetail] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) @@ -99,6 +104,15 @@ export default function HistoryDetailScreen({ const [paused, setPaused] = useState(false) const [audioBusy, setAudioBusy] = useState(false) + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + loadGenerationRef.current += 1 + void Promise.resolve(playerRef.current.stopPlayer()).catch(() => undefined) + } + }, []) + const applyEntry = useCallback((entry: HistoryEntry): void => { setTitle(entry.title ?? '') setOriginalText(entry.original_text) @@ -106,7 +120,9 @@ export default function HistoryDetailScreen({ }, []) const load = useCallback(async (): Promise => { + const generation = ++loadGenerationRef.current if (user === null) { + if (!mountedRef.current) return setError(t('mobile.account.loginRequired')) setLoading(false) return @@ -116,14 +132,17 @@ export default function HistoryDetailScreen({ setError(null) try { const nextDetail = await getHistoryDetail(user.id, route.params.historyId) + if (!mountedRef.current || loadGenerationRef.current !== generation) return setDetail(nextDetail) applyEntry(nextDetail.entry) setOffline(false) setConflict(false) } catch (requestError) { + if (!mountedRef.current || loadGenerationRef.current !== generation) return if (requestError instanceof HistoryServiceError && requestError.code === 'network') { try { const cached = await loadHistoryCache(user.id) + if (!mountedRef.current || loadGenerationRef.current !== generation) return const entry = cached?.entries.find((item) => item.id === route.params.historyId) if (entry !== undefined) { setDetail({ entry, audioFiles: [], jobs: [] }) @@ -135,13 +154,16 @@ export default function HistoryDetailScreen({ // The request error below remains authoritative when secure cache access fails. } } + if (!mountedRef.current || loadGenerationRef.current !== generation) return setError( requestError instanceof HistoryServiceError && requestError.code === 'not-found' ? t('mobile.hist.notFound') : t('mobile.hist.loadError'), ) } finally { - setLoading(false) + if (mountedRef.current && loadGenerationRef.current === generation) { + setLoading(false) + } } }, [applyEntry, route.params.historyId, t, user]) @@ -194,11 +216,13 @@ export default function HistoryDetailScreen({ detail.entry.revision, patch, ) + if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, entry: updated }) applyEntry(updated) setEditing(false) setConflict(false) } catch (requestError) { + if (!mountedRef.current) return if (requestError instanceof HistoryServiceError && requestError.code === 'conflict') { setConflict(true) setError(t('mobile.hist.conflict')) @@ -206,7 +230,7 @@ export default function HistoryDetailScreen({ setError(t('mobile.hist.editFailed')) } } finally { - setSaving(false) + if (mountedRef.current) setSaving(false) } } @@ -223,12 +247,14 @@ export default function HistoryDetailScreen({ previous.revision, { is_favorite: optimistic.is_favorite }, ) + if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, entry: updated }) } catch { + if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, entry: previous }) setError(t('mobile.hist.favoriteFailed')) } finally { - setSaving(false) + if (mountedRef.current) setSaving(false) } } @@ -254,8 +280,10 @@ export default function HistoryDetailScreen({ setError(null) try { await deleteHistoryRevisionSafe(user.id, detail.entry.id, detail.entry.revision) + if (!mountedRef.current) return navigation.goBack() } catch { + if (!mountedRef.current) return setError(t('mobile.hist.deleteFailed')) setDeleting(false) } @@ -272,7 +300,7 @@ export default function HistoryDetailScreen({ message, }) } catch { - setError(t('mobile.hist.shareFailed')) + if (mountedRef.current) setError(t('mobile.hist.shareFailed')) } } @@ -283,25 +311,34 @@ export default function HistoryDetailScreen({ try { if (activeAudioId === audioFile.id && player.state.isPlaying) { await player.pausePlayer() - setPaused(true) + if (mountedRef.current) setPaused(true) return } if (activeAudioId === audioFile.id && paused) { await player.resumePlayer() - setPaused(false) + if (mountedRef.current) setPaused(false) return } - if (activeAudioId !== null) await player.stopPlayer() + if (activeAudioId !== null) { + await player.stopPlayer() + if (!mountedRef.current) return + } const signedUrl = await createAudioPlaybackUrl(user.id, audioFile) + if (!mountedRef.current) return await player.startPlayer(signedUrl) + if (!mountedRef.current) { + void Promise.resolve(player.stopPlayer()).catch(() => undefined) + return + } setActiveAudioId(audioFile.id) setPaused(false) } catch { + if (!mountedRef.current) return setActiveAudioId(null) setPaused(false) setError(t('mobile.hist.audioError')) } finally { - setAudioBusy(false) + if (mountedRef.current) setAudioBusy(false) } } @@ -309,12 +346,13 @@ export default function HistoryDetailScreen({ setAudioBusy(true) try { await player.stopPlayer() + if (!mountedRef.current) return setActiveAudioId(null) setPaused(false) } catch { - setError(t('mobile.hist.audioError')) + if (mountedRef.current) setError(t('mobile.hist.audioError')) } finally { - setAudioBusy(false) + if (mountedRef.current) setAudioBusy(false) } } @@ -633,18 +671,10 @@ function MetaRow({ label, value }: { label: string; value: string }): React.Reac ) } -export function formatDuration(durationMs: number): string { - const totalSeconds = Math.max(0, Math.floor(durationMs / 1000)) - const minutes = Math.floor(totalSeconds / 60) - const seconds = totalSeconds % 60 - return `${minutes}:${String(seconds).padStart(2, '0')}` -} +export { formatBytes } -export function formatBytes(bytes: number): string { - if (!Number.isFinite(bytes) || bytes <= 0) return '0 B' - if (bytes < 1024) return `${Math.round(bytes)} B` - if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB` - return `${(bytes / (1024 * 1024)).toFixed(1)} MB` +export function formatDuration(durationMs: number): string { + return formatDurationClockFromMs(durationMs) } type Palette = ReturnType['palette'] diff --git a/apps/mobile-rn/src/screens/HistoryScreen.tsx b/apps/mobile-rn/src/screens/HistoryScreen.tsx index caea7e3..b7f4a77 100644 --- a/apps/mobile-rn/src/screens/HistoryScreen.tsx +++ b/apps/mobile-rn/src/screens/HistoryScreen.tsx @@ -345,7 +345,7 @@ function createStyles(palette: Palette) { return StyleSheet.create({ container: { flex: 1, backgroundColor: palette.bg.app }, center: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 32, backgroundColor: palette.bg.app }, - searchRow: { paddingHorizontal: 20, paddingTop: 12 }, + searchRow: { paddingHorizontal: 20, paddingTop: 12, width: '100%', maxWidth: 720, alignSelf: 'center' }, searchInput: { minHeight: 48, paddingHorizontal: 14, @@ -356,12 +356,12 @@ function createStyles(palette: Palette) { color: palette.text.primary, fontSize: 14, }, - filters: { flexDirection: 'row', paddingHorizontal: 20, paddingVertical: 12, gap: 12, borderBottomWidth: 1, borderBottomColor: palette.border.subtle }, + filters: { flexDirection: 'row', paddingHorizontal: 20, paddingVertical: 12, gap: 12, borderBottomWidth: 1, borderBottomColor: palette.border.subtle, width: '100%', maxWidth: 720, alignSelf: 'center' }, offlineBanner: { gap: 4, paddingHorizontal: 20, paddingVertical: 10, backgroundColor: palette.accent.dim }, warningBanner: { paddingHorizontal: 20, paddingVertical: 8 }, errorBanner: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 12, paddingHorizontal: 20, paddingVertical: 10, backgroundColor: palette.bg.card, borderBottomWidth: 1, borderBottomColor: palette.tag.red }, retryButton: { minWidth: 72, minHeight: 48, alignItems: 'center', justifyContent: 'center' }, - listContent: { padding: 20 }, + listContent: { padding: 20, width: '100%', maxWidth: 720, alignSelf: 'center' }, emptyList: { flexGrow: 1, alignItems: 'center', justifyContent: 'center', padding: 32 }, emptyText: { textAlign: 'center' }, dateHeader: { letterSpacing: 3, marginBottom: 8, marginTop: 16 }, diff --git a/apps/mobile-rn/src/screens/HomeScreen.tsx b/apps/mobile-rn/src/screens/HomeScreen.tsx index db4e2c4..8b71b97 100644 --- a/apps/mobile-rn/src/screens/HomeScreen.tsx +++ b/apps/mobile-rn/src/screens/HomeScreen.tsx @@ -19,6 +19,7 @@ import type { NativeStackNavigationProp } from '@react-navigation/native-stack' import { useSafeAreaInsets } from 'react-native-safe-area-context' import type { Meeting } from '@d3ro/api-client' import { useI18n, type TFunction } from '@d3ro/i18n' +import { CONTENT_MAX_WIDTH_DP } from '@d3ro/ui-native' import { useAuth } from '../lib/auth-context' import { useEntitlement } from '../lib/entitlement-context' import { useMobilePreferences } from '../lib/preferences-context' @@ -345,7 +346,7 @@ const stylesStatic = StyleSheet.create({ function createStyles(palette: Palette) { return StyleSheet.create({ container: { flex: 1, backgroundColor: palette.bg.app }, - content: { paddingHorizontal: 20 }, + content: { paddingHorizontal: 20, width: '100%', maxWidth: CONTENT_MAX_WIDTH_DP, alignSelf: 'center' }, header: { gap: 2 }, searchEntry: { minHeight: 64, diff --git a/apps/mobile-rn/src/screens/LoginScreen.tsx b/apps/mobile-rn/src/screens/LoginScreen.tsx index 04a028a..2e1d163 100644 --- a/apps/mobile-rn/src/screens/LoginScreen.tsx +++ b/apps/mobile-rn/src/screens/LoginScreen.tsx @@ -355,6 +355,9 @@ function createStyles(palette: Palette) { flexGrow: 1, justifyContent: 'center', paddingHorizontal: 24, + width: '100%', + maxWidth: 480, + alignSelf: 'center', }, branding: { alignItems: 'center', marginBottom: 40 }, leds: { flexDirection: 'row', gap: 10, marginBottom: 20 }, diff --git a/apps/mobile-rn/src/screens/MeetingDetailScreen.tsx b/apps/mobile-rn/src/screens/MeetingDetailScreen.tsx index 44c2ab1..7488c8e 100644 --- a/apps/mobile-rn/src/screens/MeetingDetailScreen.tsx +++ b/apps/mobile-rn/src/screens/MeetingDetailScreen.tsx @@ -21,6 +21,11 @@ import type { MeetingMemo, UserTemplate, } from '@d3ro/api-client' +import { + extractDistinctSpeakers, + resolveSpeakerColorIndex, +} from '@d3ro/core/meeting-transcript' +import { formatDurationClockFromMs } from '@d3ro/core/format' import { useI18n, type TranslationKey } from '@d3ro/i18n' import { useAuth } from '../lib/auth-context' import { useMobilePreferences } from '../lib/preferences-context' @@ -39,6 +44,7 @@ import { loadTemplateLibrary, TemplateServiceError, } from '../features/templates' +import { resolveMeetingErrorMessage } from '../features/meetings/meeting-error-message' import { buildMeetingTranscriptView, createMeetingMemo, @@ -96,6 +102,7 @@ export default function MeetingDetailScreen({ const { user, session } = useAuth() const { palette } = useMobilePreferences() const styles = useMemo(() => createStyles(palette), [palette]) + const mountedRef = useRef(true) const refreshTimer = useRef | null>(null) const requestGeneration = useRef(0) const templateGeneration = useRef(0) @@ -116,6 +123,20 @@ export default function MeetingDetailScreen({ const [selectedDocumentTemplate, setSelectedDocumentTemplate] = useState(null) const [reportTarget, setReportTarget] = useState(null) const [currentPositionMs, setCurrentPositionMs] = useState(initialAudioPositionMs) + const [selectedSpeaker, setSelectedSpeaker] = useState(null) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + requestGeneration.current += 1 + templateGeneration.current += 1 + if (refreshTimer.current !== null) { + clearTimeout(refreshTimer.current) + refreshTimer.current = null + } + } + }, []) const handleSeekTimestamp = useCallback((timestampMs: number): void => { const clamped = Math.max(0, Math.floor(timestampMs)) @@ -129,6 +150,7 @@ export default function MeetingDetailScreen({ ): Promise => { const generation = ++requestGeneration.current if (user === null) { + if (!mountedRef.current) return setDetail(null) setError(t('mobile.meetings.loginRequired')) setLoading(false) @@ -140,15 +162,15 @@ export default function MeetingDetailScreen({ if (!keepCurrent) setError(null) try { const loaded = await getMeetingDetail(user.id, route.params.meetingId) - if (generation !== requestGeneration.current) return + if (!mountedRef.current || generation !== requestGeneration.current) return setDetail(loaded) setError(null) setConflict(false) } catch (requestError) { - if (generation !== requestGeneration.current) return + if (!mountedRef.current || generation !== requestGeneration.current) return setError(meetingErrorMessage(requestError, t)) } finally { - if (generation === requestGeneration.current) { + if (mountedRef.current && generation === requestGeneration.current) { setLoading(false) setRefreshing(false) } @@ -160,12 +182,12 @@ export default function MeetingDetailScreen({ ): Promise => { const generation = ++templateGeneration.current if (user === null) { - setSelectedDocumentTemplate(null) + if (mountedRef.current) setSelectedDocumentTemplate(null) return } try { const library = await loadTemplateLibrary(user.id, 'meeting_document') - if (generation !== templateGeneration.current) return + if (!mountedRef.current || generation !== templateGeneration.current) return const selectedId = meetingTemplateId ?? library.selections.meeting_document?.template_id setSelectedDocumentTemplate( @@ -176,7 +198,7 @@ export default function MeetingDetailScreen({ ?? null, ) } catch (requestError) { - if (generation !== templateGeneration.current) return + if (!mountedRef.current || generation !== templateGeneration.current) return setSelectedDocumentTemplate(null) setError(templateErrorMessage(requestError, t)) } @@ -201,12 +223,16 @@ export default function MeetingDetailScreen({ const subscription = subscribeToMeetingDetail( route.params.meetingId, () => { + if (!mountedRef.current) return if (refreshTimer.current !== null) clearTimeout(refreshTimer.current) refreshTimer.current = setTimeout(() => { - void load(false, true) + refreshTimer.current = null + if (mountedRef.current) void load(false, true) }, 250) }, - (status) => setRealtimeConnected(status === 'SUBSCRIBED'), + (status) => { + if (mountedRef.current) setRealtimeConnected(status === 'SUBSCRIBED') + }, ) return () => { if (refreshTimer.current !== null) { @@ -254,10 +280,12 @@ export default function MeetingDetailScreen({ try { if (editor.kind === 'meeting') { const updated = await updateMeetingTitleRevisionSafe(editor.current, editorTitle) + if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, meeting: updated }) } else if (editor.kind === 'memo') { if (user === null) return const updated = await updateMeetingMemoConflictSafe(user.id, editor.current, editorContent) + if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, memos: current.memos.map((memo) => memo.id === updated.id ? updated : memo), @@ -268,6 +296,7 @@ export default function MeetingDetailScreen({ editorTitle, editorContent, ) + if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, documents: current.documents.map((document) => ( @@ -279,12 +308,13 @@ export default function MeetingDetailScreen({ setConflict(false) setError(null) } catch (requestError) { + if (!mountedRef.current) return const isConflict = requestError instanceof MeetingServiceError && requestError.code === 'conflict' setConflict(isConflict) setEditorError(meetingErrorMessage(requestError, t)) } finally { - setEditorBusy(false) + if (mountedRef.current) setEditorBusy(false) } } @@ -294,15 +324,17 @@ export default function MeetingDetailScreen({ setError(null) try { const created = await createMeetingMemo(user.id, detail.meeting, memoDraft) + if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, memos: [...current.memos, created].sort(compareMemos), }) setMemoDraft('') } catch (requestError) { + if (!mountedRef.current) return setError(meetingErrorMessage(requestError, t)) } finally { - setBusyKey(null) + if (mountedRef.current) setBusyKey(null) } } @@ -328,8 +360,10 @@ export default function MeetingDetailScreen({ setError(null) try { await deleteMeetingRevisionSafe(user.id, detail.meeting) + if (!mountedRef.current) return navigation.goBack() } catch (requestError) { + if (!mountedRef.current) return handleMutationError(requestError) setBusyKey(null) } @@ -356,14 +390,16 @@ export default function MeetingDetailScreen({ setError(null) try { await deleteMeetingMemoConflictSafe(user.id, memo) + if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, memos: current.memos.filter((candidate) => candidate.id !== memo.id), }) } catch (requestError) { + if (!mountedRef.current) return handleMutationError(requestError) } finally { - setBusyKey(null) + if (mountedRef.current) setBusyKey(null) } } @@ -388,15 +424,17 @@ export default function MeetingDetailScreen({ setError(null) try { await deleteMeetingDocumentRevisionSafe(user.id, document) + if (!mountedRef.current) return setDetail((current) => current === null ? null : { ...current, documents: current.documents.filter((candidate) => candidate.id !== document.id), }) setExpandedDocumentId((current) => current === document.id ? null : current) } catch (requestError) { + if (!mountedRef.current) return handleMutationError(requestError) } finally { - setBusyKey(null) + if (mountedRef.current) setBusyKey(null) } } @@ -420,12 +458,16 @@ export default function MeetingDetailScreen({ memos: detail.memos, documents: detail.documents, }, format) + if (!mountedRef.current) { + await prepared.dispose().catch(() => undefined) + return + } await sharePreparedPortableFile(prepared, t('mobile.meetings.exportShareTitle')) } catch { await prepared?.dispose().catch(() => undefined) - setError(t('mobile.meetings.exportFailed')) + if (mountedRef.current) setError(t('mobile.meetings.exportFailed')) } finally { - setBusyKey((current) => current === key ? null : current) + if (mountedRef.current) setBusyKey((current) => current === key ? null : current) } } @@ -451,6 +493,7 @@ export default function MeetingDetailScreen({ templateId, title, }) + if (!mountedRef.current) return setDetail((current) => { if (current === null) return null const existing = current.documents.some((document) => document.id === generated.document.id) @@ -465,9 +508,10 @@ export default function MeetingDetailScreen({ }) setExpandedDocumentId(generated.document.id) } catch (requestError) { + if (!mountedRef.current) return setError(templateErrorMessage(requestError, t)) } finally { - setBusyKey(null) + if (mountedRef.current) setBusyKey(null) } } @@ -477,6 +521,33 @@ export default function MeetingDetailScreen({ const seekableSegments = useMemo(() => ( detail === null ? [] : parseTranscriptSeekSegments(detail.meeting, detail.transcripts) ), [detail]) + const distinctSpeakers = useMemo( + () => extractDistinctSpeakers(seekableSegments), + [seekableSegments], + ) + useEffect(() => { + if (selectedSpeaker !== null && !distinctSpeakers.includes(selectedSpeaker)) { + setSelectedSpeaker(null) + } + }, [distinctSpeakers, selectedSpeaker]) + const visibleSegments = useMemo( + () => ( + selectedSpeaker === null + ? seekableSegments + : seekableSegments.filter((segment) => segment.speaker?.trim() === selectedSpeaker) + ), + [seekableSegments, selectedSpeaker], + ) + const speakerColors = useMemo( + () => [ + palette.tag.purple, + palette.tag.green, + palette.tag.orange, + palette.tag.red, + palette.tag.blue, + ], + [palette], + ) const activeSegmentId = useMemo(() => ( findActiveTranscriptSegmentId(seekableSegments, currentPositionMs) ), [currentPositionMs, seekableSegments]) @@ -671,14 +742,62 @@ export default function MeetingDetailScreen({ {formatElapsedMs(currentPositionMs)} )} + {distinctSpeakers.length >= 2 && ( + + setSelectedSpeaker(null)} + style={[ + styles.speakerFilterChip, + selectedSpeaker === null && styles.speakerFilterChipActive, + ]} + testID="meeting-speaker-filter-all" + > + + {t('mobile.hist.all')} + + + {distinctSpeakers.map((sp) => { + const active = selectedSpeaker === sp + const spColor = speakerColors[resolveSpeakerColorIndex(sp, speakerColors.length)] + return ( + setSelectedSpeaker(active ? null : sp)} + style={[ + styles.speakerFilterChip, + active && { borderColor: spColor, backgroundColor: palette.overlay.soft }, + ]} + testID={`meeting-speaker-filter-${sp}`} + > + + {sp} + + + ) + })} + + )} {transcript?.source === 'segments' || seekableSegments.some((segment) => segment.timed) ? ( - seekableSegments.map((segment) => { + visibleSegments.map((segment) => { const isActive = activeSegmentId === segment.id + const speakerLabel = segment.speaker?.trim() || null + const speakerColor = speakerLabel + ? speakerColors[resolveSpeakerColorIndex(speakerLabel, speakerColors.length)] + : null return ( ) : null} - {segment.speaker !== null && ( - {segment.speaker} + {speakerLabel !== null && speakerColor !== null && ( + + + {speakerLabel} + + )} {segment.edited && ( @@ -1052,12 +1181,7 @@ function compareMemos(left: MeetingMemo, right: MeetingMemo): number { } export function formatElapsedMs(value: number): string { - const totalSeconds = Math.max(0, Math.floor(value / 1_000)) - const hours = Math.floor(totalSeconds / 3_600) - const minutes = Math.floor((totalSeconds % 3_600) / 60) - const seconds = totalSeconds % 60 - const base = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}` - return hours > 0 ? `${hours}:${base}` : base + return formatDurationClockFromMs(value, { padMinutes: true, showHours: true }) } export function formatMinutesJson(value: Record): string { @@ -1071,14 +1195,7 @@ export function formatMinutesJson(value: Record): string { type Translate = ReturnType['t'] function meetingErrorMessage(error: unknown, t: Translate): string { - if (!(error instanceof MeetingServiceError)) return t('mobile.meetings.errorServer') - if (error.code === 'auth') return t('mobile.meetings.loginRequired') - if (error.code === 'conflict') return t('mobile.meetings.errorConflict') - if (error.code === 'forbidden') return t('mobile.meetings.errorForbidden') - if (error.code === 'network') return t('mobile.meetings.errorNetwork') - if (error.code === 'not-found') return t('mobile.meetings.errorNotFound') - if (error.code === 'validation') return t('mobile.meetings.errorValidation') - return t('mobile.meetings.errorServer') + return resolveMeetingErrorMessage(error, t) } function templateErrorMessage(error: unknown, t: Translate): string { @@ -1164,7 +1281,26 @@ function createStyles(palette: Palette): ReturnType { borderLeftWidth: 3, borderLeftColor: palette.accent.main, }, - segmentMeta: { flexDirection: 'row', alignItems: 'center', gap: 10 }, + segmentMeta: { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', gap: 8 }, + speakerFilterRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginBottom: 4 }, + speakerFilterChip: { + paddingHorizontal: 10, + paddingVertical: 4, + borderRadius: 999, + borderWidth: 1, + borderColor: palette.border.default, + backgroundColor: palette.bg.card, + }, + speakerFilterChipActive: { + borderColor: palette.accent.main, + backgroundColor: palette.accent.dim, + }, + speakerBadge: { + paddingHorizontal: 8, + paddingVertical: 2, + borderRadius: 999, + borderWidth: 1, + }, readingText: { lineHeight: 23 }, codeText: { lineHeight: 21, diff --git a/apps/mobile-rn/src/screens/MeetingsScreen.tsx b/apps/mobile-rn/src/screens/MeetingsScreen.tsx index c0e4b72..23f23a0 100644 --- a/apps/mobile-rn/src/screens/MeetingsScreen.tsx +++ b/apps/mobile-rn/src/screens/MeetingsScreen.tsx @@ -17,6 +17,7 @@ import type { NavigationProp, ParamListBase } from '@react-navigation/native' import { useFocusEffect } from '@react-navigation/native' import type { Meeting, MeetingLanguage, UserTemplate } from '@d3ro/api-client' import { useI18n } from '@d3ro/i18n' +import { useResponsiveLayout } from '@d3ro/ui-native' import { useAuth } from '../lib/auth-context' import { useMobilePreferences } from '../lib/preferences-context' import { ThemeButton, ThemeCard, ThemeText } from '../theme/themed-components' @@ -29,6 +30,7 @@ import { MeetingServiceError, updateMeetingTitleRevisionSafe, } from '../features/meetings/meetings-service' +import { resolveMeetingErrorMessage } from '../features/meetings/meeting-error-message' import { loadTemplateLibrary } from '../features/templates' import { useTabScreenBottomPadding } from '../navigation/tab-layout' @@ -53,6 +55,7 @@ export default function MeetingsScreen({ const { t, formatDate } = useI18n() const { user } = useAuth() const { palette } = useMobilePreferences() + const { gridColumns, wideContentMaxWidth } = useResponsiveLayout() const styles = useMemo(() => createStyles(palette), [palette]) const requestGeneration = useRef(0) const templateRequestGeneration = useRef(0) @@ -362,7 +365,7 @@ export default function MeetingsScreen({ testID="meetings-header" /> - + {error !== null && ( - + {error} ) : ( 1 ? styles.columnRow : undefined} keyExtractor={(meeting) => meeting.id} contentContainerStyle={[ meetings.length === 0 ? styles.emptyList : styles.list, - { paddingBottom: bottomPadding }, + { maxWidth: wideContentMaxWidth, paddingBottom: bottomPadding }, ]} keyboardShouldPersistTaps="handled" refreshControl={( @@ -432,7 +438,10 @@ export default function MeetingsScreen({ const busy = busyId === meeting.id const owned = meeting.user_id === user?.id return ( - + 1 && styles.cardGridItem]} + testID={`meeting-card-${meeting.id}`} + > ['t'] function meetingErrorMessage(error: unknown, t: Translate): string { - if (!(error instanceof MeetingServiceError)) return t('mobile.meetings.errorServer') - if (error.code === 'auth') return t('mobile.meetings.loginRequired') - if (error.code === 'conflict') return t('mobile.meetings.errorConflict') - if (error.code === 'forbidden') return t('mobile.meetings.errorForbidden') - if (error.code === 'network') return t('mobile.meetings.errorNetwork') - if (error.code === 'not-found') return t('mobile.meetings.errorNotFound') - if (error.code === 'validation') return t('mobile.meetings.errorValidation') - return t('mobile.meetings.errorServer') + return resolveMeetingErrorMessage(error, t) } type Palette = ReturnType['palette'] @@ -768,7 +770,7 @@ function createStyles(palette: Palette): ReturnType { }, headerCopy: { flex: 1, gap: 4 }, headerActions: { flexDirection: 'row', gap: 8, flexShrink: 0 }, - searchWrap: { paddingHorizontal: 20, paddingBottom: 12 }, + searchWrap: { paddingHorizontal: 20, paddingBottom: 12, width: '100%', alignSelf: 'center' }, searchInput: { minHeight: 48, borderWidth: 1, @@ -784,6 +786,8 @@ function createStyles(palette: Palette): ReturnType { marginBottom: 10, paddingHorizontal: 12, minHeight: 52, + width: '100%', + alignSelf: 'center', flexDirection: 'row', alignItems: 'center', gap: 10, @@ -794,11 +798,13 @@ function createStyles(palette: Palette): ReturnType { }, errorText: { flex: 1 }, center: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 12, padding: 32 }, - list: { paddingHorizontal: 20, paddingTop: 4 }, - emptyList: { flexGrow: 1, justifyContent: 'center', paddingHorizontal: 20 }, + list: { paddingHorizontal: 20, paddingTop: 4, width: '100%', alignSelf: 'center' }, + columnRow: { gap: 12 }, + emptyList: { flexGrow: 1, justifyContent: 'center', paddingHorizontal: 20, width: '100%', alignSelf: 'center' }, emptyCard: { alignItems: 'center', paddingVertical: 36 }, emptyText: { textAlign: 'center' }, card: { marginBottom: 12, padding: 0, overflow: 'hidden' }, + cardGridItem: { flex: 1 }, cardBody: { padding: 16, gap: 7 }, cardTop: { flexDirection: 'row', alignItems: 'flex-start', gap: 12 }, cardTitle: { flex: 1 }, diff --git a/apps/mobile-rn/src/screens/MoreScreen.tsx b/apps/mobile-rn/src/screens/MoreScreen.tsx index 3a134a3..c2cc475 100644 --- a/apps/mobile-rn/src/screens/MoreScreen.tsx +++ b/apps/mobile-rn/src/screens/MoreScreen.tsx @@ -14,6 +14,7 @@ import type { BottomTabNavigationProp } from '@react-navigation/bottom-tabs' import type { NativeStackNavigationProp } from '@react-navigation/native-stack' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { useI18n, type TranslationKey } from '@d3ro/i18n' +import { useResponsiveLayout } from '@d3ro/ui-native' import { currentAdminRole } from '../features/admin/admin-service' import { useAuth } from '../lib/auth-context' import { useEntitlement, type MobileSubscriptionTier } from '../lib/entitlement-context' @@ -170,6 +171,7 @@ export default function MoreScreen(): React.ReactElement { const { user } = useAuth() const { snapshot } = useEntitlement() const { palette } = useMobilePreferences() + const { isLargeScreen, wideContentMaxWidth } = useResponsiveLayout() const styles = useMemo(() => createStyles(palette), [palette]) const accountItems = currentAdminRole(user?.app_metadata) === null ? ACCOUNT_ITEMS @@ -186,7 +188,7 @@ export default function MoreScreen(): React.ReactElement { style={styles.container} contentContainerStyle={[ styles.content, - { paddingTop: insets.top + 16, paddingBottom: bottomPadding }, + { maxWidth: wideContentMaxWidth, paddingTop: insets.top + 16, paddingBottom: bottomPadding }, ]} testID="more-screen" > @@ -198,12 +200,14 @@ export default function MoreScreen(): React.ReactElement { title={t('mobile.more.section.tools')} items={TOOL_ITEMS} describe={description} + isLargeScreen={isLargeScreen} onOpen={(route) => navigation.navigate(route)} /> navigation.navigate(route)} /> @@ -214,11 +218,13 @@ function MoreSection({ title, items, describe, + isLargeScreen, onOpen, }: { title: string items: readonly MoreItem[] describe: (item: MoreItem) => string + isLargeScreen: boolean onOpen: (route: MoreRoute) => void }): React.ReactElement { const { t } = useI18n() @@ -229,7 +235,13 @@ function MoreSection({ {title} - + {items.map((item, index) => { const itemDescription = describe(item) return ( @@ -242,7 +254,9 @@ function MoreSection({ testID={item.testID} style={({ pressed }) => [ styles.row, - index > 0 && { borderTopColor: palette.border.subtle, borderTopWidth: 1 }, + isLargeScreen + ? [styles.rowGridCard, { borderColor: palette.border.subtle }] + : index > 0 && { borderTopColor: palette.border.subtle, borderTopWidth: 1 }, pressed && { backgroundColor: palette.bg.cardHover }, ]} > @@ -306,11 +320,12 @@ type Palette = ReturnType['palette'] function createStyles(palette: Palette) { return StyleSheet.create({ container: { flex: 1, backgroundColor: palette.bg.app }, - content: { paddingHorizontal: 20 }, + content: { paddingHorizontal: 20, width: '100%', alignSelf: 'center' }, title: { marginBottom: 8 }, section: { marginTop: 20 }, sectionTitle: { minHeight: 32, justifyContent: 'center', letterSpacing: 0 }, rows: { borderTopWidth: 1, borderBottomWidth: 1 }, + rowsGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 12 }, row: { minHeight: 72, flexDirection: 'row', @@ -318,6 +333,14 @@ function createStyles(palette: Palette) { gap: 14, paddingVertical: 10, }, + rowGridCard: { + width: '48.5%', + flexGrow: 1, + paddingHorizontal: 14, + borderWidth: 1, + borderRadius: 12, + backgroundColor: palette.bg.card, + }, copy: { flex: 1, gap: 3 }, }) } diff --git a/apps/mobile-rn/src/screens/OnboardingScreen.tsx b/apps/mobile-rn/src/screens/OnboardingScreen.tsx index 60cc47c..e4910ba 100644 --- a/apps/mobile-rn/src/screens/OnboardingScreen.tsx +++ b/apps/mobile-rn/src/screens/OnboardingScreen.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { Pressable, ScrollView, @@ -8,6 +8,7 @@ import { import { useSafeAreaInsets } from 'react-native-safe-area-context' import type { NativeStackScreenProps } from '@react-navigation/native-stack' import { useI18n, type TranslationKey } from '@d3ro/i18n' +import { LOCALE_META } from '@d3ro/i18n/shared' import type { RootStackParamList } from '../../App' import { MOBILE_THEME_MODES, @@ -119,11 +120,21 @@ export default function OnboardingScreen({ updatePreferences, completeOnboarding, } = useMobilePreferences() + const mountedRef = useRef(true) + const localeRequestRef = useRef(0) const [step, setStep] = useState(0) const [audience, setAudience] = useState(null) const [saving, setSaving] = useState(false) const [localSaveFailed, setLocalSaveFailed] = useState(false) + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + localeRequestRef.current += 1 + } + }, []) + const isReplay = route.params?.replay === true const isLastStep = step === SLIDES.length - 1 const slide = SLIDES[step] @@ -132,10 +143,27 @@ export default function OnboardingScreen({ [step], ) + async function applyLocaleSelection(nextLocale: SupportedMobileLocale): Promise { + const request = ++localeRequestRef.current + try { + const result = await updatePreferences({ locale: nextLocale }) + if (!mountedRef.current || localeRequestRef.current !== request) return + if (!result.localSaved) { + setLocalSaveFailed(true) + return + } + setLocalSaveFailed(false) + setLocale(nextLocale) + } catch { + if (mountedRef.current && localeRequestRef.current === request) { + setLocalSaveFailed(true) + } + } + } + function selectLocale(nextLocale: SupportedMobileLocale): void { if (locale === nextLocale) return - setLocale(nextLocale) - void updatePreferences({ locale: nextLocale }) + void applyLocaleSelection(nextLocale) } function selectTheme(nextTheme: MobileThemeMode): void { @@ -149,18 +177,24 @@ export default function OnboardingScreen({ onFreshFinish?.(selectedAudience) setSaving(true) setLocalSaveFailed(false) - const result = await completeOnboarding(outcome) - if (!result.localSaved) { - setLocalSaveFailed(true) - setSaving(false) - return + try { + const result = await completeOnboarding(outcome) + if (!mountedRef.current) return + if (!result.localSaved) { + setLocalSaveFailed(true) + return + } + const exit = resolveOnboardingExit(true, user !== null, isReplay, navigation.canGoBack()) + // Authenticated fresh completion changes the root navigator branch. The + // parent observes needsOnboarding true -> false and resets to Main after + // the new branch mounts; replacing here targets the already-stale + // onboarding navigator and produces an unhandled REPLACE warning. + if (exit === 'back') navigation.goBack() + } catch { + if (mountedRef.current) setLocalSaveFailed(true) + } finally { + if (mountedRef.current) setSaving(false) } - const exit = resolveOnboardingExit(true, user !== null, isReplay, navigation.canGoBack()) - // Authenticated fresh completion changes the root navigator branch. The - // parent observes needsOnboarding true -> false and resets to Main after - // the new branch mounts; replacing here targets the already-stale - // onboarding navigator and produces an unhandled REPLACE warning. - if (exit === 'back') navigation.goBack() } return ( @@ -188,26 +222,29 @@ export default function OnboardingScreen({ : t('mobile.onboarding.setupLabel')} - - {(['ko', 'en'] as const).map((candidate) => ( + {LOCALE_META.map((item) => ( selectLocale(candidate)} + accessibilityState={{ selected: locale === item.code }} + accessibilityLabel={item.nativeName} + testID={`onboarding-language-${item.code}`} + onPress={() => selectLocale(item.code)} style={({ pressed }) => [ styles.localeButton, { - borderColor: locale === candidate + borderColor: locale === item.code ? palette.accent.main : palette.border.default, - backgroundColor: locale === candidate + backgroundColor: locale === item.code ? palette.accent.dim : 'transparent', opacity: pressed ? 0.72 : 1, @@ -216,13 +253,13 @@ export default function OnboardingScreen({ > - {candidate.toUpperCase()} + {item.code.toUpperCase()} ))} - + ['t']>[0]; @@ -398,15 +396,23 @@ export default function RecordScreen({ route, navigation }: RecordScreenProps): recorderActiveRef.current = true; const meetingToBegin = armedMeetingIdRef.current; let meetingBegun = false; + let recorder: RecorderSession | null = null; try { // Re-check on every start (not the cached handle) so a busy recorder is // reported before a meeting is marked as recording. - const recorder = await audioRecorder.acquire('record'); + recorder = await audioRecorder.acquire('record'); recorderSessionRef.current = recorder; const granted = await audioRecorder.requestPermission(); - if (!mountedRef.current) return; + if (!mountedRef.current) { + recorderActiveRef.current = false; + if (recorderSessionRef.current === recorder) recorderSessionRef.current = null; + await recorder.cancel().catch(() => undefined); + return; + } if (!granted) { recorderActiveRef.current = false; + if (recorderSessionRef.current === recorder) recorderSessionRef.current = null; + await recorder.cancel().catch(() => undefined); setError(t('mobile.rec.micDenied')); setState('error'); return; @@ -423,9 +429,19 @@ export default function RecordScreen({ route, navigation }: RecordScreenProps): meetingId: activeMeetingIdRef.current ?? undefined, onStateChange: applyRecorderSnapshot, }); - if (mountedRef.current) setState('recording'); + if (!mountedRef.current) { + recorderActiveRef.current = false; + if (recorderSessionRef.current === recorder) recorderSessionRef.current = null; + await recorder.cancel().catch(() => undefined); + return; + } + setState('recording'); } catch (recordingError) { recorderActiveRef.current = false; + if (recorder !== null) { + if (recorderSessionRef.current === recorder) recorderSessionRef.current = null; + await recorder.cancel().catch(() => undefined); + } if (meetingBegun && user !== null && meetingToBegin !== null) { await failMeetingRecording( user.id, @@ -1014,7 +1030,7 @@ type Palette = ReturnType['palette']; function createStyles(palette: Palette) { return StyleSheet.create({ container: { flex: 1, backgroundColor: palette.bg.app }, - content: { paddingBottom: 100 }, + content: { paddingBottom: 100, width: '100%', maxWidth: 720, alignSelf: 'center' }, headerRight: { flexDirection: 'row', alignItems: 'center', gap: 8 }, headerTime: { ...d3roNativeNumerals }, meetingContext: { paddingHorizontal: 20, paddingTop: 12, gap: 4 }, @@ -1029,7 +1045,7 @@ function createStyles(palette: Palette) { errorText: { color: palette.tag.red }, listeningRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap', gap: 8, paddingHorizontal: 16, paddingBottom: 16 }, listeningText: { letterSpacing: 2 }, - buttons: { paddingHorizontal: 20, paddingBottom: 16 }, + buttons: { paddingHorizontal: 20, paddingBottom: 16, width: '100%', maxWidth: 360, alignSelf: 'center' }, buttonSpacer: { height: 12 }, }); } diff --git a/apps/mobile-rn/src/screens/SettingsScreen.tsx b/apps/mobile-rn/src/screens/SettingsScreen.tsx index 9a69df9..b8b03bb 100644 --- a/apps/mobile-rn/src/screens/SettingsScreen.tsx +++ b/apps/mobile-rn/src/screens/SettingsScreen.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { Alert, Linking, @@ -11,6 +11,7 @@ import { import { useNavigation } from '@react-navigation/native' import type { NativeStackNavigationProp } from '@react-navigation/native-stack' import { useI18n, type TranslationKey } from '@d3ro/i18n' +import { LOCALE_META } from '@d3ro/i18n/shared' import { SITE_URLS } from '@d3ro/core/web-urls' import { useAuth } from '../lib/auth-context' import { useEntitlement } from '../lib/entitlement-context' @@ -75,6 +76,8 @@ export default function SettingsScreen(): React.ReactElement { updatePreferences, retrySync, } = useMobilePreferences() + const mountedRef = useRef(true) + const localeRequestRef = useRef(0) const [savingPreference, setSavingPreference] = useState(null) const [loggingOut, setLoggingOut] = useState(false) const [retrying, setRetrying] = useState(false) @@ -83,6 +86,14 @@ export default function SettingsScreen(): React.ReactElement { const { currentDevice } = useDevice() const adminRole = currentAdminRole(user?.app_metadata) + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + localeRequestRef.current += 1 + } + }, []) + const initials = user?.email ? user.email.substring(0, 2).toUpperCase() : 'US' @@ -95,23 +106,38 @@ export default function SettingsScreen(): React.ReactElement { async function persistPreference( key: Exclude, patch: MobilePreferencesPatch, - ): Promise { - if (savingPreference !== null) return + ): Promise { + if (savingPreference !== null) return false setSavingPreference(key) - const result = await updatePreferences(patch) - setSavingPreference(null) - if (!result.localSaved) { + let saved = false + try { + const result = await updatePreferences(patch) + saved = result.localSaved + } catch { + saved = false + } finally { + if (mountedRef.current) setSavingPreference(null) + } + if (!mountedRef.current) return false + if (!saved) { Alert.alert( t('mobile.preferences.saveFailedTitle'), t('mobile.preferences.cacheWriteError'), ) } + return saved + } + + async function applyLocaleSelection(nextLocale: SupportedMobileLocale): Promise { + const request = ++localeRequestRef.current + const saved = await persistPreference('locale', { locale: nextLocale }) + if (!saved || !mountedRef.current || localeRequestRef.current !== request) return + setLocale(nextLocale) } function selectLocale(nextLocale: SupportedMobileLocale): void { if (locale === nextLocale || savingPreference !== null) return - setLocale(nextLocale) - void persistPreference('locale', { locale: nextLocale }) + void applyLocaleSelection(nextLocale) } async function performLogout(): Promise { @@ -124,9 +150,11 @@ export default function SettingsScreen(): React.ReactElement { purgeLocalSession, }) } catch { - Alert.alert(t('mobile.auth.errorTitle'), t('mobile.auth.logoutFailed')) + if (mountedRef.current) { + Alert.alert(t('mobile.auth.errorTitle'), t('mobile.auth.logoutFailed')) + } } finally { - setLoggingOut(false) + if (mountedRef.current) setLoggingOut(false) } } @@ -144,13 +172,16 @@ export default function SettingsScreen(): React.ReactElement { async function handleRetry(): Promise { if (retrying) return setRetrying(true) - await retrySync() - setRetrying(false) + try { + await retrySync() + } finally { + if (mountedRef.current) setRetrying(false) + } } async function openAdPrivacyOptions(): Promise { const opened = await mobileAds.showPrivacyOptions() - if (!opened) { + if (!opened && mountedRef.current) { Alert.alert( t('mobile.set.adPrivacy'), t('mobile.set.adPrivacyUnavailable'), @@ -326,24 +357,33 @@ export default function SettingsScreen(): React.ReactElement { description={t('mobile.set.languageDesc')} /> - selectLocale('ko')} - /> - selectLocale('en')} - /> + {LOCALE_META.map((item) => ( + selectLocale(item.code)} + style={({ pressed }) => [ + styles.localeOption, + { + borderColor: locale === item.code ? palette.accent.main : palette.border.default, + backgroundColor: locale === item.code ? palette.accent.dim : palette.bg.inset, + opacity: savingPreference !== null ? 0.5 : pressed ? 0.72 : 1, + }, + ]} + > + + {item.nativeName} + + + ))} @@ -760,6 +800,17 @@ const styles = StyleSheet.create({ settingHeader: { gap: 4, padding: 15, paddingBottom: 10 }, settingBlock: { borderTopWidth: 1, marginTop: 15, paddingTop: 2 }, segmentRow: { flexDirection: 'row', gap: 8, paddingHorizontal: 15, paddingBottom: 15 }, + localeGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, paddingHorizontal: 15, paddingBottom: 15 }, + localeOption: { + minHeight: 48, + minWidth: '30%', + flexGrow: 1, + alignItems: 'center', + justifyContent: 'center', + borderWidth: 1, + borderRadius: 9, + paddingHorizontal: 8, + }, segmentOption: { minHeight: 48, flex: 1, diff --git a/apps/mobile-rn/src/screens/TalkScreen.tsx b/apps/mobile-rn/src/screens/TalkScreen.tsx index 443f981..eafa565 100644 --- a/apps/mobile-rn/src/screens/TalkScreen.tsx +++ b/apps/mobile-rn/src/screens/TalkScreen.tsx @@ -14,10 +14,12 @@ import { import { useFocusEffect } from '@react-navigation/native' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { useI18n } from '@d3ro/i18n' +import { formatDurationClockFromMs } from '@d3ro/core/format' 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 { toSpeechLanguageTag } from '../lib/locale-speech' import { audioRecorder, type RecordedAudio, @@ -102,12 +104,8 @@ function transcriptionErrorCode(error: unknown): TalkErrorCode { } } -function formatDuration(durationMs: number): string { - const seconds = Math.max(0, Math.floor(durationMs / 1000)) - return `${Math.floor(seconds / 60).toString().padStart(2, '0')}:${(seconds % 60) - .toString() - .padStart(2, '0')}` -} +const formatDuration = (durationMs: number): string => + formatDurationClockFromMs(durationMs, { padMinutes: true }) function phaseTranslationKey(phase: TalkPhase) { switch (phase) { @@ -147,13 +145,25 @@ export default function TalkScreen(): React.ReactElement { const sessionRef = useRef(session) sessionRef.current = session + const greetingContent = t('mobile.talk.greeting') const initialMessage = useMemo(() => ({ id: 'welcome', role: 'assistant', - content: t('mobile.talk.greeting'), + content: greetingContent, createdAt: Date.now(), - }), [t]) + }), [greetingContent]) const [messages, setMessages] = useState(() => [initialMessage]) + + useEffect(() => { + setMessages((current) => { + if (current.length !== 1 || current[0].id !== 'welcome' || current[0].content === greetingContent) { + return current + } + const next = [{ ...current[0], content: greetingContent }] + messagesRef.current = next + return next + }) + }, [greetingContent]) const [input, setInput] = useState('') const [phase, setPhase] = useState('idle') const [recordingProgress, setRecordingProgress] = useState({ @@ -360,7 +370,7 @@ export default function TalkScreen(): React.ReactElement { await playSpeech( assistantId, content, - preferences.locale === 'en' ? 'en-US' : 'ko-KR', + toSpeechLanguageTag(preferences.locale), ) } } catch (error) { @@ -410,6 +420,7 @@ export default function TalkScreen(): React.ReactElement { if (recordingFinishingRef.current || !recordingActiveRef.current || recorderSession === null) return recordingFinishingRef.current = true recordingActiveRef.current = false + if (recorderSessionRef.current === recorderSession) recorderSessionRef.current = null try { let recording: RecordedAudio @@ -508,10 +519,20 @@ export default function TalkScreen(): React.ReactElement { // recording on the Record tab holds the microphone. recorderSession = await audioRecorder.acquire('talk') recorderSessionRef.current = recorderSession - if (!isCurrentOperation(operationId)) return + if (!isCurrentOperation(operationId)) { + if (recorderSessionRef.current === recorderSession) recorderSessionRef.current = null + await recorderSession.cancel().catch(() => undefined) + return + } const granted = await audioRecorder.requestPermission() - if (!isCurrentOperation(operationId)) return + if (!isCurrentOperation(operationId)) { + if (recorderSessionRef.current === recorderSession) recorderSessionRef.current = null + await recorderSession.cancel().catch(() => undefined) + return + } if (!granted) { + if (recorderSessionRef.current === recorderSession) recorderSessionRef.current = null + await recorderSession.cancel().catch(() => undefined) setErrorCode('MIC_PERMISSION_DENIED') return } @@ -520,6 +541,7 @@ export default function TalkScreen(): React.ReactElement { if (isCurrentOperation(operationId)) setRecordingProgress(progress) }) if (!isCurrentOperation(operationId)) { + if (recorderSessionRef.current === recorderSession) recorderSessionRef.current = null await recorderSession.cancel().catch(() => undefined) return } @@ -533,7 +555,10 @@ export default function TalkScreen(): React.ReactElement { } // A session only discards a capture Talk holds; when acquisition failed // there is nothing of Talk's to clean up. - if (recorderSession !== null) await recorderSession.cancel().catch(() => undefined) + if (recorderSession !== null) { + if (recorderSessionRef.current === recorderSession) recorderSessionRef.current = null + await recorderSession.cancel().catch(() => undefined) + } } finally { recordingStartingRef.current = false } @@ -584,7 +609,7 @@ export default function TalkScreen(): React.ReactElement { text: preferences.locale === 'en' ? 'Mobile voice transcription verified' : '모바일 음성 전사 검증', - languageTag: preferences.locale === 'en' ? 'en-US' : 'ko-KR', + languageTag: toSpeechLanguageTag(preferences.locale), }) if (!isCurrentOperation(operationId)) { await fixture.dispose() @@ -640,7 +665,7 @@ export default function TalkScreen(): React.ReactElement { void playSpeech( message.id, message.content, - preferences.locale === 'en' ? 'en-US' : 'ko-KR', + toSpeechLanguageTag(preferences.locale), ) }, [playSpeech, preferences.locale, speakingMessageId, stopSpeech]) diff --git a/apps/mobile-rn/src/screens/TemplatesScreen.tsx b/apps/mobile-rn/src/screens/TemplatesScreen.tsx index 8874048..a1b9252 100644 --- a/apps/mobile-rn/src/screens/TemplatesScreen.tsx +++ b/apps/mobile-rn/src/screens/TemplatesScreen.tsx @@ -21,6 +21,7 @@ import { } from 'react-native' import { useIsFocused } from '@react-navigation/native' import { useI18n, type TranslationKey } from '@d3ro/i18n' +import { ACTION_BUTTON_MAX_WIDTH_DP, useResponsiveLayout } from '@d3ro/ui-native' import type { DictationTemplateField, DocumentTemplateType, @@ -136,6 +137,7 @@ export default function TemplatesScreen({ const { t } = useI18n() const { user } = useAuth() const { palette } = useMobilePreferences() + const { gridColumns, wideContentMaxWidth } = useResponsiveLayout() const styles = useMemo(() => createStyles(palette), [palette]) const generation = useRef(0) const realtimeTimer = useRef | null>(null) @@ -335,7 +337,11 @@ export default function TemplatesScreen({ const busy = busyId === item.id return ( 1 && styles.cardGridItem, + selected && styles.cardSelected, + ]} testID={`template-${item.id}`} > @@ -390,7 +396,7 @@ export default function TemplatesScreen({ ) - }, [busyId, choose, confirmDelete, selections, styles, t]) + }, [busyId, choose, confirmDelete, gridColumns, selections, styles, t]) const empty = loading ? ( @@ -426,7 +432,7 @@ export default function TemplatesScreen({ {t('mobile.templates.realtimeWaiting')} )} - + {(['dictation', 'meeting_document'] as const).map((value) => { const active = value === kind @@ -463,10 +469,15 @@ export default function TemplatesScreen({ )} 1 ? styles.columnRow : undefined} keyExtractor={(item) => item.id} renderItem={renderTemplate} - contentContainerStyle={templates.length === 0 ? styles.emptyList : styles.list} + contentContainerStyle={templates.length === 0 + ? [styles.emptyList, { maxWidth: wideContentMaxWidth }] + : [styles.list, { maxWidth: wideContentMaxWidth }]} keyboardShouldPersistTaps="handled" refreshControl={( { }, headerText: { flex: 1, gap: 4 }, banner: { paddingHorizontal: 20, paddingVertical: 8, backgroundColor: palette.accent.dim }, - controls: { padding: 16, gap: 10, borderBottomWidth: 1, borderBottomColor: palette.border.subtle }, + controls: { padding: 16, width: '100%', alignSelf: 'center', gap: 10, borderBottomWidth: 1, borderBottomColor: palette.border.subtle }, tabs: { flexDirection: 'row', gap: 8 }, tab: { flex: 1, minHeight: 48, alignItems: 'center', justifyContent: 'center', borderRadius: 9, borderWidth: 1, borderColor: palette.border.default }, tabActive: { backgroundColor: palette.accent.main, borderColor: palette.accent.main }, input: { minHeight: 48, borderWidth: 1, borderColor: palette.border.default, borderRadius: 10, backgroundColor: palette.bg.inset, color: palette.text.primary, paddingHorizontal: 12, fontSize: 14 }, - inlineError: { padding: 12, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 10, borderBottomWidth: 1, borderBottomColor: palette.tag.red }, - list: { padding: 16, gap: 12, paddingBottom: 36 }, - emptyList: { flexGrow: 1 }, + inlineError: { padding: 12, width: '100%', alignSelf: 'center', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 10, borderBottomWidth: 1, borderBottomColor: palette.tag.red }, + list: { padding: 16, gap: 12, paddingBottom: 36, width: '100%', alignSelf: 'center' }, + columnRow: { gap: 12 }, + emptyList: { flexGrow: 1, width: '100%', alignSelf: 'center' }, center: { flex: 1, minHeight: 260, alignItems: 'center', justifyContent: 'center', gap: 14, padding: 32 }, centerText: { textAlign: 'center' }, card: { gap: 12 }, + cardGridItem: { flex: 1 }, cardSelected: { borderColor: palette.accent.main, borderWidth: 1 }, cardHeader: { flexDirection: 'row', alignItems: 'flex-start', gap: 10 }, cardTitle: { flex: 1, gap: 5 }, titleRow: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', gap: 8 }, badge: { paddingHorizontal: 8, paddingVertical: 3, borderRadius: 999, backgroundColor: palette.accent.dim }, actions: { flexDirection: 'row', alignItems: 'center', gap: 8 }, - flexButton: { flex: 1 }, + flexButton: { flex: 1, maxWidth: ACTION_BUTTON_MAX_WIDTH_DP }, modalBackdrop: { flex: 1, justifyContent: 'center', padding: 16, backgroundColor: palette.scrim }, modalList: { width: '100%', maxWidth: 680, maxHeight: '94%', alignSelf: 'center', borderRadius: 14, backgroundColor: palette.bg.card }, modalCard: { padding: 18, gap: 14 }, diff --git a/apps/web/src/app/(app)/dashboard/page.tsx b/apps/web/src/app/(app)/dashboard/page.tsx index 288d572..da12bd5 100644 --- a/apps/web/src/app/(app)/dashboard/page.tsx +++ b/apps/web/src/app/(app)/dashboard/page.tsx @@ -1,7 +1,7 @@ 'use client' import Link from 'next/link' -import { useCallback, useEffect, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import { Alert, Box, Button, CircularProgress, Typography } from '@mui/material' import { ArrowUpRight, @@ -73,12 +73,25 @@ function formatDuration(seconds: number): string { export default function DashboardPage(): React.ReactElement { const { user, loading: authLoading } = useAuth() + const userId = user?.id const [snapshot, setSnapshot] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) + const mountedRef = useRef(true) + const requestSeqRef = useRef(0) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + } + }, []) const load = useCallback(async (): Promise => { - if (!user) { + const seq = ++requestSeqRef.current + const isStale = (): boolean => !mountedRef.current || requestSeqRef.current !== seq + + if (!userId) { if (!authLoading) { setSnapshot(null) setError('세션이 만료되었습니다. 다시 로그인해 주세요.') @@ -90,14 +103,19 @@ export default function DashboardPage(): React.ReactElement { setError(null) try { const client = getSupabaseBrowserClient() as unknown as D3roSupabaseClient - setSnapshot(await loadDashboardSnapshot(client, user.id)) + const nextSnapshot = await loadDashboardSnapshot(client, userId) + if (isStale()) return + setSnapshot(nextSnapshot) } catch (requestError) { + if (isStale()) return setSnapshot(null) setError(dashboardMessage(requestError)) } finally { - setLoading(false) + if (!isStale()) { + setLoading(false) + } } - }, [authLoading, user]) + }, [authLoading, userId]) useEffect(() => { void load() diff --git a/apps/web/src/app/(app)/history/[id]/page.tsx b/apps/web/src/app/(app)/history/[id]/page.tsx index d0c269f..ddf5850 100644 --- a/apps/web/src/app/(app)/history/[id]/page.tsx +++ b/apps/web/src/app/(app)/history/[id]/page.tsx @@ -16,6 +16,7 @@ import { } from '@mui/material' import { ArrowLeft, Check, Copy, RefreshCw, Save, Star, Trash2 } from 'lucide-react' import type { D3roSupabaseClient, HistoryEntry } from '@d3ro/api-client' +import { formatDurationClockFromSeconds } from '@d3ro/core/format' import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds' import { d3roFontMono, d3roPalette } from '@d3ro/ui/theme' import { getSupabaseBrowserClient } from '@/lib/supabase-browser' @@ -330,11 +331,5 @@ function Metadata({ label, value }: { label: string; value: string }): React.Rea ) } -function formatDuration(durationSeconds: number): string { - const totalSeconds = Number.isFinite(durationSeconds) ? Math.max(0, Math.floor(durationSeconds)) : 0 - const hours = Math.floor(totalSeconds / 3600) - const minutes = Math.floor((totalSeconds % 3600) / 60) - const seconds = totalSeconds % 60 - if (hours > 0) return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}` - return `${minutes}:${String(seconds).padStart(2, '0')}` -} +const formatDuration = (durationSeconds: number): string => + formatDurationClockFromSeconds(durationSeconds, { showHours: true }) diff --git a/apps/web/src/app/(app)/history/page.tsx b/apps/web/src/app/(app)/history/page.tsx index 777f8dd..840fa2f 100644 --- a/apps/web/src/app/(app)/history/page.tsx +++ b/apps/web/src/app/(app)/history/page.tsx @@ -2,6 +2,7 @@ import Link from 'next/link' import React, { useCallback, useEffect, useRef, useState } from 'react' +import { formatDurationClockFromSeconds } from '@d3ro/core/format' import { Alert, Box, @@ -387,11 +388,5 @@ export default function HistoryPage(): React.ReactElement { ) } -function formatDuration(durationSeconds: number): string { - const totalSeconds = Number.isFinite(durationSeconds) ? Math.max(0, Math.floor(durationSeconds)) : 0 - const hours = Math.floor(totalSeconds / 3600) - const minutes = Math.floor((totalSeconds % 3600) / 60) - const seconds = totalSeconds % 60 - if (hours > 0) return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}` - return `${minutes}:${String(seconds).padStart(2, '0')}` -} +const formatDuration = (durationSeconds: number): string => + formatDurationClockFromSeconds(durationSeconds, { showHours: true }) diff --git a/apps/web/src/app/(app)/teams/page.tsx b/apps/web/src/app/(app)/teams/page.tsx index 043a5fd..1b71672 100644 --- a/apps/web/src/app/(app)/teams/page.tsx +++ b/apps/web/src/app/(app)/teams/page.tsx @@ -1,43 +1,17 @@ // apps/web/src/app/(app)/teams/page.tsx // 팀 리스트 + 새 팀 생성 — auth/Sidebar는 (app)/layout.tsx가 제공 -import Link from 'next/link' -import { Box, Grid } from '@mui/material' -import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds' -import { d3roPalette, typoSx } from '@d3ro/ui/theme' +import { Box } from '@mui/material' +import { PhosphorText } from '@d3ro/ui/components/ds' import { CreateTeamForm } from '@/components/teams/create-team-form' +import { TeamCardGrid } from '@/components/teams/team-card-grid' import { getSupabaseServerClient } from '@/lib/supabase-server' +import { loadUserTeamsWithCounts, type SupabaseTeamReader, type WebTeamRow } from '@/lib/team-client' -interface TeamRow { - id: string - name: string - avatar_url: string | null - member_count: number - role: 'owner' | 'admin' | 'member' -} - -async function loadTeams(): Promise { +async function loadTeams(): Promise { try { const supabase = await getSupabaseServerClient() - // 본인이 속한 팀만 RLS로 자동 필터링 - const { data: members } = await supabase - .from('team_members') - .select('team_id, role, teams(id, name, avatar_url)') - - if (!members) return [] - - return members - .filter((m: { teams: unknown }) => m.teams !== null) - .map((m: { team_id: string; role: string; teams: unknown }) => { - const team = m.teams as { id: string; name: string; avatar_url: string | null } - return { - id: team.id, - name: team.name, - avatar_url: team.avatar_url, - member_count: 0, // count는 별도 query 필요. MVP에서는 생략 - role: m.role as 'owner' | 'admin' | 'member' - } - }) + return await loadUserTeamsWithCounts(supabase as unknown as SupabaseTeamReader) } catch { return [] } @@ -56,50 +30,7 @@ export default async function TeamsPage(): Promise { - {teams.length === 0 ? ( - - 아직 가입한 팀이 없습니다. 위에서 새 팀을 만들거나, 다른 팀에서 초대를 받아보세요. - - ) : ( - - {teams.map((team) => ( - - - - - {team.name} - - - {team.role.toUpperCase()} - - - - - ))} - - )} + ) } diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsx index 5aa1211..47ca278 100644 --- a/apps/web/src/app/login/page.tsx +++ b/apps/web/src/app/login/page.tsx @@ -11,6 +11,7 @@ import { Box, Stack, Alert } from '@mui/material' import { useI18n } from '@d3ro/i18n' import { getSupabaseBrowserClient, isSupabaseConfigured } from '@/lib/supabase-browser' import { useAuth } from '@/components/providers/auth-provider' +import { LocaleSwitcher } from '@/components/layout/locale-switcher' import { appUrlFor, safeReturnPath } from '@/lib/web-app-url' /** (app) 레이아웃이 붙여 보낸 `?next=` — 로그인 뒤 돌아갈 웹앱 내부 경로. */ @@ -111,6 +112,9 @@ export default function LoginPage(): React.ReactElement { }} > {/* Header & LED Indicators */} + + + ): void => { + const next = event.target.value + if (isValidLocale(next)) { + setLocale(next) + } + } + + return ( + + + + {t('settings.language')} + + + labelId="web-locale-select-label" + id="web-locale-select" + data-testid="web-locale-select" + value={locale} + onChange={handleLocaleChange} + label={t('settings.language')} + > + {LOCALE_META.map((item) => ( + + {item.nativeName} + + ))} + + + ) +} diff --git a/apps/web/src/components/layout/sidebar.tsx b/apps/web/src/components/layout/sidebar.tsx index cf76e17..dbc95b4 100644 --- a/apps/web/src/components/layout/sidebar.tsx +++ b/apps/web/src/components/layout/sidebar.tsx @@ -38,6 +38,7 @@ import { } from '@/lib/web-push-session' import { useAuth } from '@/components/providers/auth-provider' import { AVAILABLE_MODES, useThemeMode } from '@/components/providers/theme-mode-context' +import { LocaleSwitcher } from './locale-switcher' import { WebPushControl } from './web-push-control' interface NavItem { @@ -195,7 +196,8 @@ export function Sidebar(): React.ReactElement { - + + boolean + enable: (userId: string) => Promise + disable: (userId: string) => Promise + getStatus: (userId: string) => Promise + onUpdate: (update: { enabled?: boolean; status: ControlStatus }) => void +} + +export async function runWebPushToggle(params: WebPushToggleParams): Promise { + const { userId, shouldEnable, isCurrent, enable, disable, getStatus, onUpdate } = params + if (!isCurrent()) return + + if (shouldEnable) { + onUpdate({ status: 'enabling' }) + try { + await enable(userId) + if (!isCurrent()) return + onUpdate({ enabled: true, status: 'subscribed' }) + } catch { + if (!isCurrent()) return + try { + const current = await getStatus(userId) + if (!isCurrent()) return + const reconciled = reconcileFailedWebPushEnable(current) + onUpdate({ enabled: reconciled.enabled, status: reconciled.status }) + } catch { + if (!isCurrent()) return + onUpdate({ enabled: false, status: 'error' }) + } + } + return + } + + onUpdate({ status: 'disabling' }) + try { + await disable(userId) + if (!isCurrent()) return + onUpdate({ enabled: false, status: 'unsubscribed' }) + } catch { + if (!isCurrent()) return + try { + const current = await getStatus(userId) + if (!isCurrent()) return + onUpdate({ enabled: current === 'subscribed', status: 'error' }) + } catch { + if (!isCurrent()) return + onUpdate({ enabled: false, status: 'error' }) + } + } +} + export function WebPushControl(): React.ReactElement { const { t } = useI18n() const { user } = useAuth() const [status, setStatus] = useState('checking') const [enabled, setEnabled] = useState(false) const userId = user?.id + const mountedRef = useRef(true) + const activeUserIdRef = useRef(userId) + const activeToggleSeqRef = useRef(null) + const nextToggleSeqRef = useRef(0) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + } + }, []) useEffect(() => { let active = true + activeUserIdRef.current = userId + activeToggleSeqRef.current = null if (!userId) { setEnabled(false) setStatus('checking') @@ -88,41 +154,30 @@ export function WebPushControl(): React.ReactElement { }, [userId]) async function handleToggle(shouldEnable: boolean): Promise { - if (!userId || isBusy(status) || isUnavailable(status)) return - - if (shouldEnable) { - setStatus('enabling') - try { - await enableCurrentWebPush(userId) - setEnabled(true) - setStatus('subscribed') - } catch { - try { - const current = await getCurrentWebPushConnectionStatus(userId) - const reconciled = reconcileFailedWebPushEnable(current) - setEnabled(reconciled.enabled) - setStatus(reconciled.status) - } catch { - setEnabled(false) - setStatus('error') - } - } + if (!userId || activeToggleSeqRef.current !== null || isBusy(status) || isUnavailable(status)) { return } + const targetUserId = userId + const toggleSeq = ++nextToggleSeqRef.current + activeToggleSeqRef.current = toggleSeq - setStatus('disabling') try { - await disableCurrentWebPush(userId) - setEnabled(false) - setStatus('unsubscribed') - } catch { - try { - const current = await getCurrentWebPushConnectionStatus(userId) - setEnabled(current === 'subscribed') - } catch { - setEnabled(false) + await runWebPushToggle({ + userId: targetUserId, + shouldEnable, + isCurrent: () => mountedRef.current && activeUserIdRef.current === targetUserId, + enable: enableCurrentWebPush, + disable: disableCurrentWebPush, + getStatus: getCurrentWebPushConnectionStatus, + onUpdate: (update) => { + if (update.enabled !== undefined) setEnabled(update.enabled) + setStatus(update.status) + }, + }) + } finally { + if (activeToggleSeqRef.current === toggleSeq) { + activeToggleSeqRef.current = null } - setStatus('error') } } diff --git a/apps/web/src/components/meetings/document-editor.tsx b/apps/web/src/components/meetings/document-editor.tsx index 021e1a1..03aee94 100644 --- a/apps/web/src/components/meetings/document-editor.tsx +++ b/apps/web/src/components/meetings/document-editor.tsx @@ -5,6 +5,7 @@ // 클릭 → 다이얼로그 열림 → textarea 편집 → 저장 시 meeting_documents UPDATE import { useState } from 'react' +import dynamic from 'next/dynamic' import { useRouter } from 'next/navigation' import { Dialog, @@ -27,7 +28,11 @@ import EditIcon from '@mui/icons-material/Edit' import VisibilityIcon from '@mui/icons-material/Visibility' import { d3roPalette, typoSx } from '@d3ro/ui/theme' import { getSupabaseBrowserClient } from '@/lib/supabase-browser' -import { MarkdownPreview } from './markdown-preview' + +const MarkdownPreview = dynamic( + () => import('./markdown-preview').then((m) => m.MarkdownPreview), + { ssr: false }, +) interface DocumentEditorProps { doc: { diff --git a/apps/web/src/components/meetings/live-transcript-list.tsx b/apps/web/src/components/meetings/live-transcript-list.tsx index d493987..838d917 100644 --- a/apps/web/src/components/meetings/live-transcript-list.tsx +++ b/apps/web/src/components/meetings/live-transcript-list.tsx @@ -5,7 +5,13 @@ import { useCallback, useEffect, useMemo, useState } from 'react' import { Box, Stack } from '@mui/material' -import { formatTranscriptTimestamp, parseTranscriptLines } from '@d3ro/core/meeting-transcript' +import { + extractDistinctSpeakers, + formatTranscriptTimestamp, + parseTranscriptLines, + resolveSpeakerColorIndex, +} from '@d3ro/core/meeting-transcript' +import { useI18n } from '@d3ro/i18n' import { d3roFontMono, d3roFocusRing, d3roPalette, typoSx } from '@d3ro/ui/theme' import { getSupabaseBrowserClient } from '../../lib/supabase-browser' import { @@ -14,6 +20,14 @@ import { type MeetingAudioTimeUpdateDetail } from './meeting-audio-player' +const WEB_SPEAKER_STYLES = [ + { color: d3roPalette.tag.purple, bg: d3roPalette.tag.purpleBg, border: d3roPalette.tag.purpleGlow }, + { color: d3roPalette.tag.green, bg: d3roPalette.tag.greenBg, border: d3roPalette.tag.greenGlow }, + { color: d3roPalette.tag.orange, bg: d3roPalette.tag.orangeBg, border: d3roPalette.tag.orangeGlow }, + { color: d3roPalette.tag.red, bg: d3roPalette.tag.redBg, border: d3roPalette.tag.redGlow }, + { color: d3roPalette.tag.blue, bg: d3roPalette.tag.blueBg, border: d3roPalette.tag.blueGlow }, +] as const + export interface TranscriptRow { id: string segment_index: number @@ -84,8 +98,10 @@ export function LiveTranscriptList({ currentPositionMs, onSeekTimestamp }: LiveTranscriptListProps): React.ReactElement { + const { t } = useI18n() const [segments, setSegments] = useState(initial) const [internalPositionMs, setInternalPositionMs] = useState(null) + const [selectedSpeaker, setSelectedSpeaker] = useState(null) useEffect(() => { setSegments(initial) @@ -152,6 +168,22 @@ export function LiveTranscriptList({ return parseFallbackTranscriptRows(fallbackTranscript) }, [fallbackTranscript, segments]) + const distinctSpeakers = useMemo( + () => extractDistinctSpeakers(effectiveSegments), + [effectiveSegments], + ) + + useEffect(() => { + if (selectedSpeaker && !distinctSpeakers.includes(selectedSpeaker)) { + setSelectedSpeaker(null) + } + }, [distinctSpeakers, selectedSpeaker]) + + const visibleSegments = useMemo(() => { + if (!selectedSpeaker) return effectiveSegments + return effectiveSegments.filter((seg) => seg.speaker?.trim() === selectedSpeaker) + }, [effectiveSegments, selectedSpeaker]) + const effectivePositionMs = currentPositionMs !== undefined ? currentPositionMs : internalPositionMs const activeSegmentId = useMemo( () => findActiveWebTranscriptSegmentId(effectiveSegments, effectivePositionMs), @@ -167,15 +199,74 @@ export function LiveTranscriptList({ if (effectiveSegments.length === 0) { return ( - 전사 세그먼트가 없습니다. + {t('meetings.transcript.empty')} ) } return ( - {effectiveSegments.map((seg) => { + {distinctSpeakers.length >= 2 && ( + + setSelectedSpeaker(null)} + sx={{ + px: 1.25, + py: 0.35, + borderRadius: 99, + border: `1px solid ${selectedSpeaker === null ? d3roPalette.accent.main : d3roPalette.border.default}`, + bgcolor: selectedSpeaker === null ? d3roPalette.accent.dim : d3roPalette.bg.card, + color: selectedSpeaker === null ? d3roPalette.accent.light : d3roPalette.text.secondary, + fontSize: 11, + fontWeight: 500, + cursor: 'pointer', + '&:focus-visible': d3roFocusRing, + }} + > + {t('records.filter.all')} + + {distinctSpeakers.map((sp) => { + const active = selectedSpeaker === sp + const style = WEB_SPEAKER_STYLES[resolveSpeakerColorIndex(sp, WEB_SPEAKER_STYLES.length)] + return ( + setSelectedSpeaker(active ? null : sp)} + sx={{ + px: 1.25, + py: 0.35, + borderRadius: 99, + border: `1px solid ${active ? style.color : d3roPalette.border.default}`, + bgcolor: active ? style.bg : d3roPalette.bg.card, + color: active ? style.color : d3roPalette.text.secondary, + fontSize: 11, + fontWeight: 500, + cursor: 'pointer', + '&:focus-visible': d3roFocusRing, + }} + > + {sp} + + ) + })} + + )} + {visibleSegments.map((seg) => { const isActive = activeSegmentId === seg.id const formattedTime = formatTranscriptTimestamp(seg.timestamp_ms) + const speakerLabel = seg.speaker?.trim() || null + const speakerStyle = speakerLabel + ? WEB_SPEAKER_STYLES[resolveSpeakerColorIndex(speakerLabel, WEB_SPEAKER_STYLES.length)] + : null return ( [{formattedTime}] - {seg.speaker && ( - - {seg.speaker} + {speakerLabel && speakerStyle && ( + + {speakerLabel} )} {seg.edited && ( diff --git a/apps/web/src/components/meetings/markdown-preview.tsx b/apps/web/src/components/meetings/markdown-preview.tsx index 1dd6e1a..0ca6c18 100644 --- a/apps/web/src/components/meetings/markdown-preview.tsx +++ b/apps/web/src/components/meetings/markdown-preview.tsx @@ -4,7 +4,7 @@ // react-markdown + remark-gfm 렌더 + mermaid code block → 다이어그램 자동 변환. // DocumentEditor 미리보기 탭에서 사용. -import { useEffect, useMemo, useRef } from 'react' +import { useEffect, useId, useRef } from 'react' import ReactMarkdown from 'react-markdown' import remarkGfm from 'remark-gfm' import { Box } from '@mui/material' @@ -14,58 +14,131 @@ interface MarkdownPreviewProps { content: string } -// mermaid는 번들 크기가 크고 brower-only라서 lazy import. +export interface MermaidRenderer { + render: (id: string, source: string) => Promise<{ svg: string }> +} + +export interface MermaidRenderTarget { + textContent: string | null + innerHTML: string + isConnected?: boolean + classList: { + remove: (token: string) => void + add: (token: string) => void + } + replaceChildren: (...nodes: Node[]) => void +} + +// mermaid는 번들 크기가 크고 browser-only라서 lazy import. let mermaidReady: Promise | null = null function loadMermaid(): Promise { if (!mermaidReady) { - mermaidReady = import('mermaid').then((mod) => { - const m = mod.default - m.initialize({ - startOnLoad: false, - theme: 'dark', - securityLevel: 'strict', - fontFamily: - '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' + mermaidReady = import('mermaid') + .then((mod) => { + const m = mod.default + m.initialize({ + startOnLoad: false, + theme: 'dark', + securityLevel: 'strict', + fontFamily: + '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif' + }) + return m + }) + .catch((err: unknown) => { + mermaidReady = null + throw err }) - return m - }) } return mermaidReady } +export function renderMermaidErrorElement( + doc: Pick, + node: Pick, + err: unknown, + errorColor: string = d3roPalette.tag.red, +): void { + const msg = err instanceof Error ? err.message : String(err) + const pre = doc.createElement('pre') + pre.style.color = errorColor + pre.style.whiteSpace = 'pre-wrap' + pre.textContent = `mermaid error: ${msg}` + node.replaceChildren(pre) +} + +export async function renderMermaidNodes(options: { + nodes: readonly MermaidRenderTarget[] + idPrefix: string + loadMermaid: () => Promise + isCancelled: () => boolean + doc: Pick +}): Promise { + const { nodes, idPrefix, loadMermaid: load, isCancelled, doc } = options + if (nodes.length === 0 || isCancelled()) return + + let mermaid: MermaidRenderer + try { + mermaid = await load() + } catch (err: unknown) { + if (isCancelled()) return + for (const node of nodes) { + if (node.isConnected === false) continue + renderMermaidErrorElement(doc, node, err) + } + return + } + + if (isCancelled()) return + + await Promise.all( + nodes.map(async (node, idx) => { + const source = node.textContent ?? '' + const id = `${idPrefix}-${idx}` + try { + const { svg } = await mermaid.render(id, source) + if (isCancelled() || node.isConnected === false) return + node.innerHTML = svg + node.classList.remove('d3ro-mermaid-source') + node.classList.add('d3ro-mermaid-rendered') + } catch (err: unknown) { + if (isCancelled() || node.isConnected === false) return + renderMermaidErrorElement(doc, node, err) + } + }), + ) +} + export function MarkdownPreview({ content }: MarkdownPreviewProps): React.ReactElement { const rootRef = useRef(null) - // Unique run id for this component instance to avoid id collisions. - const runId = useMemo(() => `mermaid-${Math.random().toString(36).slice(2, 9)}`, []) + const renderSeqRef = useRef(0) + const reactId = useId() + const baseId = `mermaid-${reactId.replace(/[^a-zA-Z0-9_-]/g, '') || 'diagram'}` - // content 바뀔 때마다 mermaid 블록 재렌더. + // content에 실제 mermaid 블록이 있을 때만 무거운 mermaid 청크를 다운로드·초기화한다. useEffect(() => { + const root = rootRef.current + if (!root) return + const initialNodes = Array.from(root.querySelectorAll('.d3ro-mermaid-source')) + if (initialNodes.length === 0) return + let cancelled = false - void loadMermaid().then((mermaid) => { - if (cancelled || !rootRef.current) return - const nodes = rootRef.current.querySelectorAll('.d3ro-mermaid-source') - nodes.forEach((node, idx) => { - const source = node.textContent ?? '' - const id = `${runId}-${idx}` - mermaid - .render(id, source) - .then(({ svg }) => { - if (cancelled) return - node.innerHTML = svg - node.classList.remove('d3ro-mermaid-source') - node.classList.add('d3ro-mermaid-rendered') - }) - .catch((err: unknown) => { - const msg = err instanceof Error ? err.message : String(err) - node.innerHTML = `
mermaid error: ${msg}
` - }) - }) + renderSeqRef.current += 1 + const idPrefix = `${baseId}-${renderSeqRef.current}` + + void renderMermaidNodes({ + nodes: initialNodes, + idPrefix, + loadMermaid, + isCancelled: () => cancelled || !rootRef.current, + doc: document, }) + return () => { cancelled = true } - }, [content, runId]) + }, [content, baseId]) return ( 동기화) -import { I18nProvider as BaseI18nProvider, type I18nStorage, type Locale } from '@d3ro/i18n' +import { useEffect } from 'react' +import { + I18nProvider as BaseI18nProvider, + isValidLocale, + toBcp47, + useI18n, + type I18nStorage, + type Locale, +} from '@d3ro/i18n' -const LOCALE_KEY = 'd3ro.voice.locale' +export const WEB_LOCALE_STORAGE_KEY = 'd3ro.voice.locale' -const localStorageI18nStorage: I18nStorage = { - load: () => { - if (typeof window === 'undefined') return null - try { - return window.localStorage.getItem(LOCALE_KEY) - } catch { - return null - } - }, - save: (locale: Locale) => { - if (typeof window === 'undefined') return - try { - window.localStorage.setItem(LOCALE_KEY, locale) - } catch { - // storage 차단 시 무시 - } +export interface KeyValueLike { + getItem(key: string): string | null + setItem(key: string, value: string): void +} + +export function resolveInitialBrowserLocale(navigatorLanguage?: string | null): Locale { + if (!navigatorLanguage) return 'ko' + const trimmed = navigatorLanguage.trim() + if (isValidLocale(trimmed)) return trimmed + const lower = trimmed.toLowerCase() + if (lower.startsWith('zh-tw') || lower.startsWith('zh-hant') || lower.startsWith('zh-hk')) { + return 'zh-TW' + } + const base = lower.split('-')[0] ?? '' + if (isValidLocale(base)) return base + return 'ko' +} + +export function createWebLocaleStorage( + getStorage: () => KeyValueLike | null = () => (typeof window === 'undefined' ? null : window.localStorage), + getNavigatorLanguage: () => string | null = () => + typeof navigator === 'undefined' ? null : navigator.language, +): I18nStorage { + return { + load: () => { + try { + const stored = getStorage()?.getItem(WEB_LOCALE_STORAGE_KEY) + if (stored && isValidLocale(stored)) { + return stored + } + } catch { + // storage 차단 시 브라우저 언어로 폴백 + } + return resolveInitialBrowserLocale(getNavigatorLanguage()) + }, + save: (locale: Locale) => { + try { + getStorage()?.setItem(WEB_LOCALE_STORAGE_KEY, locale) + } catch { + // storage 차단 시 무시 + } + }, } } -export function I18nProvider({ children }: { children: React.ReactNode }): React.ReactElement { - return {children} +const defaultWebLocaleStorage = createWebLocaleStorage() + +function HtmlLangSynchronizer(): null { + const { locale } = useI18n() + useEffect(() => { + if (typeof document !== 'undefined') { + document.documentElement.lang = toBcp47(locale) + } + }, [locale]) + return null +} + +export function I18nProvider({ children }: { children: React.ReactNode }): React.ReactElement { + return ( + + + {children} + + ) } diff --git a/apps/web/src/components/teams/team-card-grid.tsx b/apps/web/src/components/teams/team-card-grid.tsx new file mode 100644 index 0000000..bfb3a79 --- /dev/null +++ b/apps/web/src/components/teams/team-card-grid.tsx @@ -0,0 +1,69 @@ +'use client' + +import Link from 'next/link' +import { Box, Grid } from '@mui/material' +import { MetalCard } from '@d3ro/ui/components/ds' +import { d3roPalette, typoSx } from '@d3ro/ui/theme' +import { useI18n } from '@d3ro/i18n' +import type { WebTeamRow } from '@/lib/team-client' + +export function TeamCardGrid({ teams }: { teams: WebTeamRow[] }): React.ReactElement { + const { t } = useI18n() + + if (teams.length === 0) { + return ( + + {t('mobile.teams.empty')} + + ) + } + + return ( + + {teams.map((team) => ( + + + + + {team.name} + + + + {team.role.toUpperCase()} + + + {t('mobile.teams.memberCount', { count: team.member_count })} + + + + + + ))} + + ) +} diff --git a/apps/web/src/lib/command-client.ts b/apps/web/src/lib/command-client.ts index 4da8443..2d82aef 100644 --- a/apps/web/src/lib/command-client.ts +++ b/apps/web/src/lib/command-client.ts @@ -1,3 +1,4 @@ +import { isRecord } from '@d3ro/core/guards' import { SUPABASE_URL } from '@d3ro/core/supabase-config' import type { SupabaseClient } from '@supabase/supabase-js' @@ -61,9 +62,6 @@ const MESSAGE_MAX_CHARS = 8_000 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 BUILTIN_KEYS = new Set(['translate_en', 'summarize', 'formal', 'explain_code']) -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function untyped(client: SupabaseClient): SupabaseClient { return client diff --git a/apps/web/src/lib/dashboard-client.ts b/apps/web/src/lib/dashboard-client.ts index 23a1ccb..73ea96b 100644 --- a/apps/web/src/lib/dashboard-client.ts +++ b/apps/web/src/lib/dashboard-client.ts @@ -1,3 +1,4 @@ +import { isRecord } from '@d3ro/core/guards' import type { D3roSupabaseClient, Subscription } from '@d3ro/api-client' import type { SupabaseClient } from '@supabase/supabase-js' import { @@ -61,9 +62,6 @@ export class DashboardClientError extends Error { 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 isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} function nonNegativeNumber(value: unknown): number | null { const numeric = typeof value === 'number' ? value : Number(value) diff --git a/apps/web/src/lib/dictionary-client.ts b/apps/web/src/lib/dictionary-client.ts index 033fc31..d3ff7f9 100644 --- a/apps/web/src/lib/dictionary-client.ts +++ b/apps/web/src/lib/dictionary-client.ts @@ -1,4 +1,6 @@ import type { D3roSupabaseClient, DictionaryEntry } from '@d3ro/api-client' +import { csvCell, parseCsvRows } from '@d3ro/core/csv' +import { escapeLikePattern, isUuid } from '@d3ro/core/guards' export type DictionaryCategory = DictionaryEntry['category'] export type DictionaryFilter = DictionaryCategory | 'all' @@ -38,14 +40,13 @@ export class DictionaryClientError extends Error { } } -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 CATEGORIES: readonly DictionaryCategory[] = ['user', 'technical', 'auto'] const MAX_WORD_LENGTH = 120 const MAX_PRONUNCIATION_LENGTH = 200 const MAX_PAGE_SIZE = 50 function requireUuid(value: string, code: 'auth' | 'validation', message: string): void { - if (!UUID_PATTERN.test(value)) throw new DictionaryClientError(code, message) + if (!isUuid(value)) throw new DictionaryClientError(code, message) } function normalizeText(value: string): string { @@ -106,10 +107,6 @@ function assertOwned(userId: string, entry: DictionaryEntry): void { } } -function escapeLikePattern(value: string): string { - return value.replace(/[\\%_]/g, (character) => `\\${character}`) -} - async function findDuplicate( client: D3roSupabaseClient, userId: string, @@ -273,54 +270,6 @@ export interface DictionaryImportResult { const CSV_HEADER = ['word', 'pronunciation', 'category', 'usageCount', 'createdAt', 'updatedAt'] -function csvCell(value: unknown): string { - const text = value === null || value === undefined ? '' : String(value) - const escaped = text.replace(/"/g, '""') - const needsQuotes = /[",\r\n]/.test(escaped) || /^[=+\-@]/.test(escaped) - return needsQuotes ? `"${escaped}"` : escaped -} - -function parseCsvRows(input: string): string[][] { - const rows: string[][] = [] - let row: string[] = [] - let field = '' - let inQuotes = false - for (let i = 0; i < input.length; i += 1) { - const char = input[i] - if (inQuotes) { - if (char === '"') { - if (input[i + 1] === '"') { - field += '"' - i += 1 - } else { - inQuotes = false - } - } else { - field += char - } - continue - } - if (char === '"') { - inQuotes = true - } else if (char === ',') { - row.push(field) - field = '' - } else if (char === '\n') { - row.push(field) - rows.push(row) - row = [] - field = '' - } else if (char !== '\r') { - field += char - } - } - if (field.length > 0 || row.length > 0) { - row.push(field) - rows.push(row) - } - return rows.filter((candidate) => candidate.some((cell) => cell.trim().length > 0)) -} - function coerceDraft(record: Record): DictionaryDraft | null { const word = typeof record.word === 'string' ? record.word : '' const pronunciation = typeof record.pronunciation === 'string' && record.pronunciation.trim() !== '' diff --git a/apps/web/src/lib/history-client.ts b/apps/web/src/lib/history-client.ts index cddfb31..d3366df 100644 --- a/apps/web/src/lib/history-client.ts +++ b/apps/web/src/lib/history-client.ts @@ -1,3 +1,4 @@ +import { isUuid } from '@d3ro/core/guards' import type { D3roSupabaseClient, HistoryEntry } from '@d3ro/api-client' export type HistoryListFilter = 'all' | 'favorites' @@ -40,10 +41,9 @@ export interface HistoryUpdate { } const MAX_PAGE_SIZE = 50 -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 requireUuid(value: string, code: 'auth' | 'validation', message: string): void { - if (!UUID_PATTERN.test(value)) throw new HistoryClientError(code, message) + if (!isUuid(value)) throw new HistoryClientError(code, message) } function mapError(error: unknown): HistoryClientError { diff --git a/apps/web/src/lib/team-client.ts b/apps/web/src/lib/team-client.ts new file mode 100644 index 0000000..efeae4b --- /dev/null +++ b/apps/web/src/lib/team-client.ts @@ -0,0 +1,91 @@ +import { isRecord } from '@d3ro/core/guards' + +export type WebTeamRole = 'owner' | 'admin' | 'member' + +export interface WebTeamRow { + id: string + name: string + avatar_url: string | null + member_count: number + role: WebTeamRole +} + +function isWebTeamRole(value: unknown): value is WebTeamRole { + return value === 'owner' || value === 'admin' || value === 'member' +} + +export function aggregateTeamMemberCounts(rows: readonly unknown[]): Map { + const counts = new Map() + for (const row of rows) { + if (!isRecord(row) || typeof row.team_id !== 'string' || row.team_id.length === 0) { + continue + } + counts.set(row.team_id, (counts.get(row.team_id) ?? 0) + 1) + } + return counts +} + +export function buildTeamRowsWithCounts( + membershipRows: readonly unknown[], + memberCountRows: readonly unknown[], +): WebTeamRow[] { + const counts = aggregateTeamMemberCounts(memberCountRows) + const result: WebTeamRow[] = [] + + for (const row of membershipRows) { + if (!isRecord(row) || !isWebTeamRole(row.role) || !isRecord(row.teams)) { + continue + } + const team = row.teams + if (typeof team.id !== 'string' || typeof team.name !== 'string') { + continue + } + result.push({ + id: team.id, + name: team.name, + avatar_url: typeof team.avatar_url === 'string' ? team.avatar_url : null, + member_count: Math.max(1, counts.get(team.id) ?? 1), + role: row.role, + }) + } + + return result +} + +export interface SupabaseTeamReader { + from(table: 'team_members'): { + select(columns: string): PromiseLike<{ data: unknown[] | null; error: unknown }> & { + in(column: string, values: string[]): PromiseLike<{ data: unknown[] | null; error: unknown }> + } + } +} + +export async function loadUserTeamsWithCounts(client: SupabaseTeamReader): Promise { + const { data: memberships, error: membershipError } = await client + .from('team_members') + .select('team_id, role, teams(id, name, avatar_url)') + + if (membershipError || !memberships || memberships.length === 0) { + return [] + } + + const teamIds = Array.from( + new Set( + memberships + .filter((row): row is { team_id: string } => isRecord(row) && typeof row.team_id === 'string' && row.team_id.length > 0) + .map((row) => row.team_id), + ), + ) + + if (teamIds.length === 0) { + return [] + } + + const { data: allMemberRows, error: memberCountError } = await client + .from('team_members') + .select('team_id') + .in('team_id', teamIds) + + const memberCountRows = memberCountError || !allMemberRows ? [] : allMemberRows + return buildTeamRowsWithCounts(memberships, memberCountRows) +} diff --git a/apps/web/src/lib/web-push-session.ts b/apps/web/src/lib/web-push-session.ts index ece59c5..d87f4fc 100644 --- a/apps/web/src/lib/web-push-session.ts +++ b/apps/web/src/lib/web-push-session.ts @@ -16,7 +16,7 @@ import { subscribeWebPush, unsubscribeBrowserWebPush, unregisterWebPushServer, - WebPushError, + withWebPushTimeout, type WebPushBrowserStatus, } from './web-push' @@ -57,33 +57,6 @@ export async function signOutWithoutWaitingForWebPushCleanup( await signOut() } -function withSessionCleanupTimeout( - operation: Promise, - timeoutMs: number, -): Promise { - const boundedTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0 - ? timeoutMs - : DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - reject(new WebPushError( - 'persistence-failed', - 'Timed out while resolving the server Web Push registration', - )) - }, boundedTimeoutMs) - operation.then( - (value) => { - clearTimeout(timer) - resolve(value) - }, - (error: unknown) => { - clearTimeout(timer) - reject(error) - }, - ) - }) -} - function disabledIntentKey(userId: string): string { return `${DISABLED_INTENT_KEY_PREFIX}${userId}` } @@ -180,9 +153,10 @@ export async function disableCurrentWebPush( timeoutMs: environment.remoteCleanupTimeoutMs, }) })() - const remoteCleanup = withSessionCleanupTimeout( + const remoteCleanup = withWebPushTimeout( remoteCleanupOperation, environment.remoteCleanupTimeoutMs ?? DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS, + 'Timed out while resolving the server Web Push registration', ) const [browserResult, remoteResult] = await Promise.allSettled([ browserCleanup, diff --git a/apps/web/src/lib/web-push.ts b/apps/web/src/lib/web-push.ts index afdefde..a671158 100644 --- a/apps/web/src/lib/web-push.ts +++ b/apps/web/src/lib/web-push.ts @@ -288,16 +288,17 @@ export async function registerExistingWebPushSubscription( return persistWebPushSubscription(subscription, options.deviceId, options.client) } -function withRemoteCleanupTimeout(operation: PromiseLike, timeoutMs: number): Promise { +export function withWebPushTimeout( + operation: PromiseLike, + timeoutMs: number, + timeoutMessage: string, +): Promise { const boundedTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS return new Promise((resolve, reject) => { const timer = setTimeout(() => { - reject(new WebPushError( - 'persistence-failed', - 'Timed out while removing the server Web Push registration', - )) + reject(new WebPushError('persistence-failed', timeoutMessage)) }, boundedTimeoutMs) operation.then( (value) => { @@ -322,11 +323,12 @@ export async function unregisterWebPushServer( const supabase = options.client ?? getSupabaseBrowserClient() let result: Awaited> try { - result = await withRemoteCleanupTimeout( + result = await withWebPushTimeout( supabase.rpc('unregister_push_registration', { push_device_id: options.deviceId, }), options.timeoutMs ?? DEFAULT_REMOTE_CLEANUP_TIMEOUT_MS, + 'Timed out while removing the server Web Push registration', ) } catch (error) { if (error instanceof WebPushError) throw error diff --git a/apps/web/tests/live-transcript-speakers.test.tsx b/apps/web/tests/live-transcript-speakers.test.tsx new file mode 100644 index 0000000..483a142 --- /dev/null +++ b/apps/web/tests/live-transcript-speakers.test.tsx @@ -0,0 +1,81 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it, vi } from 'vitest' +import { I18nProvider as BaseI18nProvider } from '@d3ro/i18n' +import { + LiveTranscriptList, + parseFallbackTranscriptRows, +} from '@/components/meetings/live-transcript-list' + +vi.mock('@/lib/supabase-browser', () => ({ + getSupabaseBrowserClient: () => ({ + channel: () => ({ + on() { + return this + }, + subscribe() { + return this + }, + }), + removeChannel: async () => undefined, + }), +})) + +describe('웹 회의 화자 배지 및 필터 표시 (GAP-MTG-02)', () => { + it('parseFallbackTranscriptRows_화자포함원문입력_각세그먼트에speaker를보존한다', () => { + const rows = parseFallbackTranscriptRows( + '[00:03] [화자 1] 첫 번째 안건입니다\n[00:12] [화자 2] 예산안을 검토하겠습니다', + ) + expect(rows).toEqual([ + { + id: 'fallback-line-0', + segment_index: 0, + timestamp_ms: 3_000, + text: '첫 번째 안건입니다', + speaker: '화자 1', + edited: false, + }, + { + id: 'fallback-line-1', + segment_index: 1, + timestamp_ms: 12_000, + text: '예산안을 검토하겠습니다', + speaker: '화자 2', + edited: false, + }, + ]) + }) + + it('LiveTranscriptList_복수화자세그먼트렌더시_화자배지와화자필터바를표시한다', () => { + const html = renderToStaticMarkup( + + + , + ) + + expect(html).toContain('data-testid="web-speaker-filter-bar"') + expect(html).toContain('data-testid="transcript-speaker-seg-1"') + expect(html).toContain('data-testid="transcript-speaker-seg-2"') + expect(html).toContain('화자 1') + expect(html).toContain('화자 2') + }) +}) diff --git a/apps/web/tests/locale-switcher.test.tsx b/apps/web/tests/locale-switcher.test.tsx new file mode 100644 index 0000000..552aa93 --- /dev/null +++ b/apps/web/tests/locale-switcher.test.tsx @@ -0,0 +1,51 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' +import { I18nProvider as BaseI18nProvider, LOCALE_META } from '@d3ro/i18n' +import { LocaleSwitcher } from '@/components/layout/locale-switcher' +import { + WEB_LOCALE_STORAGE_KEY, + createWebLocaleStorage, + resolveInitialBrowserLocale, +} from '@/components/providers/i18n-provider' + +describe('웹 12개 로케일 전환 및 영속화 (GAP-I18N-03)', () => { + it('resolveInitialBrowserLocale_브라우저언어태그별_지원되는12개로케일로정규화한다', () => { + expect(resolveInitialBrowserLocale('ja-JP')).toBe('ja') + expect(resolveInitialBrowserLocale('zh-TW')).toBe('zh-TW') + expect(resolveInitialBrowserLocale('zh-Hant-HK')).toBe('zh-TW') + expect(resolveInitialBrowserLocale('zh-CN')).toBe('zh') + expect(resolveInitialBrowserLocale('fr-FR')).toBe('fr') + expect(resolveInitialBrowserLocale('unsupported-XX')).toBe('ko') + }) + + it('createWebLocaleStorage_저장된유효로케일을우선로드하고변경시저장한다', () => { + const store = new Map() + const adapter = createWebLocaleStorage( + () => ({ + getItem: (key) => store.get(key) ?? null, + setItem: (key, val) => { + store.set(key, val) + }, + }), + () => 'en-US', + ) + + expect(adapter.load()).toBe('en') + adapter.save('de') + expect(store.get(WEB_LOCALE_STORAGE_KEY)).toBe('de') + expect(adapter.load()).toBe('de') + }) + + it('LocaleSwitcher_초기로케일렌더시_언어선택컨트롤과현재언어를표시한다', () => { + expect(LOCALE_META).toHaveLength(12) + const html = renderToStaticMarkup( + + + , + ) + + expect(html).toContain('data-testid="web-locale-select"') + expect(html).toContain('Language') + expect(html).toContain('English') + }) +}) diff --git a/apps/web/tests/markdown-preview.test.ts b/apps/web/tests/markdown-preview.test.ts new file mode 100644 index 0000000..79d6e5b --- /dev/null +++ b/apps/web/tests/markdown-preview.test.ts @@ -0,0 +1,179 @@ +import { describe, expect, it } from 'vitest' +import { d3roPalette } from '@d3ro/ui/theme' +import { + renderMermaidErrorElement, + renderMermaidNodes, + type MermaidRenderTarget, +} from '@/components/meetings/markdown-preview' + +interface FakePreElement { + tagName: string + style: { color: string; whiteSpace: string } + textContent: string | null +} + +function createFakeDoc(): { + doc: Pick + created: FakePreElement[] +} { + const created: FakePreElement[] = [] + return { + created, + doc: { + createElement(tagName: string): HTMLElement { + const el: FakePreElement = { + tagName, + style: { color: '', whiteSpace: '' }, + textContent: null, + } + created.push(el) + return el as unknown as HTMLElement + }, + }, + } +} + +function createFakeTarget(source: string, isConnected = true): { + target: MermaidRenderTarget + tokens: Set + replaced: FakePreElement[][] +} { + const tokens = new Set(['d3ro-mermaid-source']) + const replaced: FakePreElement[][] = [] + const target: MermaidRenderTarget = { + textContent: source, + innerHTML: '', + isConnected, + classList: { + remove: (token: string) => { + tokens.delete(token) + }, + add: (token: string) => { + tokens.add(token) + }, + }, + replaceChildren: (...nodes: Node[]) => { + replaced.push(nodes as unknown as FakePreElement[]) + }, + } + return { target, tokens, replaced } +} + +describe('MarkdownPreview mermaid 비동기 렌더링 안전성', () => { + it('renderMermaidNodes_빠른업데이트또는언마운트취소_이전비동기렌더결과를DOM에기록하지않는다', async () => { + let resolveRender: ((value: { svg: string }) => void) | null = null + let cancelled = false + const { doc } = createFakeDoc() + const { target, tokens } = createFakeTarget('graph TD; A-->B;') + + const pending = renderMermaidNodes({ + nodes: [target], + idPrefix: 'mermaid-r0-1', + doc, + isCancelled: () => cancelled, + loadMermaid: async () => ({ + render: () => + new Promise<{ svg: string }>((resolve) => { + resolveRender = resolve + }), + }), + }) + + await new Promise((resolve) => { + setTimeout(resolve, 0) + }) + cancelled = true + resolveRender?.({ svg: 'stale' }) + await pending + + expect(target.innerHTML).toBe('') + expect(Array.from(tokens)).toEqual(['d3ro-mermaid-source']) + }) + + it('renderMermaidNodes_취소후렌더실패시_오류DOM을기록하지않는다', async () => { + let rejectRender: ((reason?: unknown) => void) | null = null + let cancelled = false + const { doc, created } = createFakeDoc() + const { target, replaced } = createFakeTarget('invalid syntax') + + const pending = renderMermaidNodes({ + nodes: [target], + idPrefix: 'mermaid-r0-2', + doc, + isCancelled: () => cancelled, + loadMermaid: async () => ({ + render: () => + new Promise<{ svg: string }>((_resolve, reject) => { + rejectRender = reject + }), + }), + }) + + await new Promise((resolve) => { + setTimeout(resolve, 0) + }) + cancelled = true + rejectRender?.(new Error('parse failed')) + await pending + + expect(created).toEqual([]) + expect(replaced).toEqual([]) + expect(target.innerHTML).toBe('') + }) + + it('renderMermaidNodes_에러메시지에HTML태그포함시_innerHTML에주입하지않고textContent로렌더링한다', async () => { + const { doc, created } = createFakeDoc() + const { target, replaced } = createFakeTarget('bad diagram') + + await renderMermaidNodes({ + nodes: [target], + idPrefix: 'mermaid-r0-3', + doc, + isCancelled: () => false, + loadMermaid: async () => ({ + render: async () => { + throw new Error('') + }, + }), + }) + + expect(target.innerHTML).toBe('') + expect(created).toHaveLength(1) + expect(created[0]).toEqual({ + tagName: 'pre', + style: { color: d3roPalette.tag.red, whiteSpace: 'pre-wrap' }, + textContent: 'mermaid error: ', + }) + expect(replaced).toEqual([[created[0]]]) + }) + + it('renderMermaidNodes_청크로드실패시_연결된노드에만오류를표시하고분리된노드는건너뛴다', async () => { + const { doc } = createFakeDoc() + const connected = createFakeTarget('graph TD; A-->B;', true) + const detached = createFakeTarget('graph TD; B-->C;', false) + + await renderMermaidNodes({ + nodes: [connected.target, detached.target], + idPrefix: 'mermaid-r0-4', + doc, + isCancelled: () => false, + loadMermaid: async () => { + throw new Error('chunk load failed') + }, + }) + + expect(connected.replaced).toHaveLength(1) + expect(connected.replaced[0]?.[0]?.textContent).toBe('mermaid error: chunk load failed') + expect(detached.replaced).toEqual([]) + }) + + it('renderMermaidErrorElement_문자열에러입력시_안전하게포맷한다', () => { + const { doc, created } = createFakeDoc() + const { target, replaced } = createFakeTarget('') + + renderMermaidErrorElement(doc, target, 'plain failure', d3roPalette.tag.red) + + expect(created[0]?.textContent).toBe('mermaid error: plain failure') + expect(replaced).toEqual([[created[0]]]) + }) +}) diff --git a/apps/web/tests/team-client-edge.test.ts b/apps/web/tests/team-client-edge.test.ts new file mode 100644 index 0000000..c486c58 --- /dev/null +++ b/apps/web/tests/team-client-edge.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from 'vitest' +import { loadUserTeamsWithCounts, type SupabaseTeamReader } from '@/lib/team-client' + +describe('team-client 방어적 조회 검증', () => { + it('loadUserTeamsWithCounts_중복및빈teamId멤버십입력시_고유ID만으로카운트를조회한다', async () => { + const capturedIds: string[][] = [] + const client: SupabaseTeamReader = { + from() { + return { + select() { + const chain = { + then( + onfulfilled?: (value: { data: unknown[] | null; error: unknown }) => unknown, + ) { + return Promise.resolve({ + data: [ + { + team_id: 'team-1', + role: 'owner', + teams: { id: 'team-1', name: 'Core', avatar_url: null }, + }, + { + team_id: 'team-1', + role: 'owner', + teams: { id: 'team-1', name: 'Core', avatar_url: null }, + }, + { + team_id: '', + role: 'member', + teams: null, + }, + { + team_id: 'team-2', + role: 'member', + teams: { id: 'team-2', name: 'Ops', avatar_url: null }, + }, + ], + error: null, + }).then(onfulfilled) + }, + async in(_column: string, values: string[]) { + capturedIds.push(values) + return { + data: [{ team_id: 'team-1' }, { team_id: 'team-1' }, { team_id: 'team-2' }], + error: null, + } + }, + } + return chain + }, + } + }, + } + + const teams = await loadUserTeamsWithCounts(client) + + expect(capturedIds).toEqual([['team-1', 'team-2']]) + expect(teams.map((t) => ({ id: t.id, count: t.member_count }))).toEqual([ + { id: 'team-1', count: 2 }, + { id: 'team-1', count: 2 }, + { id: 'team-2', count: 1 }, + ]) + }) + + it('loadUserTeamsWithCounts_멤버수조회오류발생시_부분데이터를신뢰하지않고기본값1로반환한다', async () => { + const client: SupabaseTeamReader = { + from() { + return { + select() { + return { + then( + onfulfilled?: (value: { data: unknown[] | null; error: unknown }) => unknown, + ) { + return Promise.resolve({ + data: [ + { + team_id: 'team-1', + role: 'admin', + teams: { id: 'team-1', name: 'Core', avatar_url: null }, + }, + ], + error: null, + }).then(onfulfilled) + }, + async in() { + return { + data: [{ team_id: 'team-1' }, { team_id: 'team-1' }, { team_id: 'team-1' }], + error: { message: 'query failed' }, + } + }, + } + }, + } + }, + } + + const teams = await loadUserTeamsWithCounts(client) + + expect(teams).toEqual([ + { + id: 'team-1', + name: 'Core', + avatar_url: null, + member_count: 1, + role: 'admin', + }, + ]) + }) +}) diff --git a/apps/web/tests/team-client.test.ts b/apps/web/tests/team-client.test.ts new file mode 100644 index 0000000..38b6afa --- /dev/null +++ b/apps/web/tests/team-client.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from 'vitest' +import { + aggregateTeamMemberCounts, + buildTeamRowsWithCounts, + loadUserTeamsWithCounts, + type SupabaseTeamReader, +} from '@/lib/team-client' + +describe('웹 팀 목록 멤버 수 집계 (05-web-app.md)', () => { + it('aggregateTeamMemberCounts_팀별멤버행수를정확히합산하고비정상행은무시한다', () => { + const counts = aggregateTeamMemberCounts([ + { team_id: 'team-a' }, + { team_id: 'team-a' }, + { team_id: 'team-a' }, + { team_id: 'team-b' }, + { team_id: '' }, + null, + ]) + + expect(counts.get('team-a')).toBe(3) + expect(counts.get('team-b')).toBe(1) + expect(counts.has('')).toBe(false) + }) + + it('buildTeamRowsWithCounts_멤버십과멤버집계를결합해실제member_count를반환한다', () => { + const rows = buildTeamRowsWithCounts( + [ + { + team_id: 'team-a', + role: 'owner', + teams: { id: 'team-a', name: 'Core Platform', avatar_url: null }, + }, + { + team_id: 'team-b', + role: 'member', + teams: { id: 'team-b', name: 'Design Ops', avatar_url: 'https://example.com/a.png' }, + }, + { + team_id: 'team-orphan', + role: 'member', + teams: null, + }, + ], + [{ team_id: 'team-a' }, { team_id: 'team-a' }, { team_id: 'team-a' }, { team_id: 'team-a' }], + ) + + expect(rows).toEqual([ + { + id: 'team-a', + name: 'Core Platform', + avatar_url: null, + member_count: 4, + role: 'owner', + }, + { + id: 'team-b', + name: 'Design Ops', + avatar_url: 'https://example.com/a.png', + member_count: 1, + role: 'member', + }, + ]) + }) + + it('loadUserTeamsWithCounts_Supabase쿼리결과로부터팀별멤버수를조회한다', async () => { + const fakeClient: SupabaseTeamReader = { + from: () => ({ + select: (columns: string) => { + const basePromise = Promise.resolve({ + data: columns.includes('teams(') + ? [ + { + team_id: 'team-1', + role: 'admin', + teams: { id: 'team-1', name: 'Voice Team', avatar_url: null }, + }, + ] + : [], + error: null, + }) + return Object.assign(basePromise, { + in: (_col: string, ids: string[]) => + Promise.resolve({ + data: ids.includes('team-1') + ? [{ team_id: 'team-1' }, { team_id: 'team-1' }, { team_id: 'team-1' }] + : [], + error: null, + }), + }) + }, + }), + } + + const teams = await loadUserTeamsWithCounts(fakeClient) + expect(teams).toHaveLength(1) + expect(teams[0]?.member_count).toBe(3) + expect(teams[0]?.role).toBe('admin') + }) +}) diff --git a/apps/web/tests/web-push-control.test.ts b/apps/web/tests/web-push-control.test.ts new file mode 100644 index 0000000..b349b9e --- /dev/null +++ b/apps/web/tests/web-push-control.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest' +import { runWebPushToggle } from '@/components/layout/web-push-control' +import type { WebPushConnectionStatus } from '@/lib/web-push-session' + +describe('WebPushControl 비동기 토글 가드', () => { + it('runWebPushToggle_활성화중사용자전환또는언마운트발생_후속상태갱신을차단한다', async () => { + let current = true + let resolveEnable: (() => void) | null = null + const updates: Array<{ enabled?: boolean; status: string }> = [] + + const pending = runWebPushToggle({ + userId: 'user-a', + shouldEnable: true, + isCurrent: () => current, + enable: () => + new Promise((resolve) => { + resolveEnable = resolve + }), + disable: async () => undefined, + getStatus: async (): Promise => 'unsubscribed', + onUpdate: (update) => updates.push(update), + }) + + await new Promise((resolve) => { + setTimeout(resolve, 0) + }) + current = false + resolveEnable?.() + await pending + + expect(updates).toEqual([{ status: 'enabling' }]) + }) + + it('runWebPushToggle_실패후재조회중취소시_오류상태를덮어쓰지않는다', async () => { + let current = true + let resolveStatus: ((value: WebPushConnectionStatus) => void) | null = null + const updates: Array<{ enabled?: boolean; status: string }> = [] + + const pending = runWebPushToggle({ + userId: 'user-a', + shouldEnable: true, + isCurrent: () => current, + enable: async () => { + throw new Error('push failed') + }, + disable: async () => undefined, + getStatus: () => + new Promise((resolve) => { + resolveStatus = resolve + }), + onUpdate: (update) => updates.push(update), + }) + + await new Promise((resolve) => { + setTimeout(resolve, 0) + }) + current = false + resolveStatus?.('blocked') + await pending + + expect(updates).toEqual([{ status: 'enabling' }]) + }) + + it('runWebPushToggle_비활성화성공및실패복구_기대상태를순서대로반영한다', async () => { + const successUpdates: Array<{ enabled?: boolean; status: string }> = [] + await runWebPushToggle({ + userId: 'user-a', + shouldEnable: false, + isCurrent: () => true, + enable: async () => undefined, + disable: async () => undefined, + getStatus: async (): Promise => 'unsubscribed', + onUpdate: (update) => successUpdates.push(update), + }) + expect(successUpdates).toEqual([ + { status: 'disabling' }, + { enabled: false, status: 'unsubscribed' }, + ]) + + const recoveryUpdates: Array<{ enabled?: boolean; status: string }> = [] + await runWebPushToggle({ + userId: 'user-a', + shouldEnable: false, + isCurrent: () => true, + enable: async () => undefined, + disable: async () => { + throw new Error('unsubscribe failed') + }, + getStatus: async (): Promise => 'subscribed', + onUpdate: (update) => recoveryUpdates.push(update), + }) + expect(recoveryUpdates).toEqual([ + { status: 'disabling' }, + { enabled: true, status: 'error' }, + ]) + }) +}) diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts index 49eb115..ab31a6c 100644 --- a/apps/web/vitest.config.ts +++ b/apps/web/vitest.config.ts @@ -1,10 +1,19 @@ +import path from 'node:path' import { defineConfig } from 'vitest/config' export default defineConfig({ + resolve: { + alias: { + '@': path.resolve(__dirname, './src'), + }, + }, + esbuild: { + jsx: 'automatic', + }, test: { globals: false, environment: 'node', - include: ['tests/**/*.test.ts'], + include: ['tests/**/*.test.{ts,tsx}'], exclude: ['e2e/**'], testTimeout: 10000, }, diff --git a/docs/REFACTOR_POLICY.md b/docs/REFACTOR_POLICY.md index 0f79f63..d700ed2 100644 --- a/docs/REFACTOR_POLICY.md +++ b/docs/REFACTOR_POLICY.md @@ -1,6 +1,6 @@ # D3RO-VOICE 리팩토링 정책 (SSOT) -> 마지막 갱신: 2026-11-04 — Wave 4 전체 모노레포 위생 점검 정책 확정 +> 마지막 갱신: 2026-11-14 — Wave 6 전 표면 코드 위생 · 최적화 · 버그 헌팅 정책 보완 > 적용 범위: `apps/*` + `packages/*` + `server/*` + `site/` + 빌드·배포 스크립트 (기능 변경은 별도 요청) ## 0. 전제: 기존 3계층 규칙 SSOT와의 관계 @@ -154,3 +154,11 @@ DRY 원칙 보강: Deno처럼 정본을 직접 import할 수 없는 런타임은 - 그룹마다 잔여 식별자 grep, 최소 표적 테스트, 변경 파일 lint를 먼저 실행하고, 통합 후 루트 `typecheck`·`test`·`lint`, 모바일 `typecheck`·`test`·`lint`, 영향받은 빌드와 `version:check`·`contract:check`를 실행한다. - packages 공유 계약 변경은 모든 소비 앱을 검사한다. UI 시각 변경은 원칙적으로 제외하며, 예외가 생기면 별도 합의와 시각 증거가 필요하다. 에이전트 서브쉘에서 Electron GUI를 백그라운드 실행하지 않는다. - 커밋·푸시는 사용자가 별도로 명시할 때만 수행한다. 이번 Wave는 패치 그룹별 diff와 검증 증거를 보존하고, `docs/REFACTOR_WAVE4_REPORT.md`에 변경/검증/SKIP/잔여 위험을 기록한다. + +--- + +## Wave 6 (2026-11-14) — 4-워크스트림 병렬 코드 위생 · 최적화 · 버그 헌팅 + +- 파일 소유 경계가 겹치지 않는 4개 워크스트림(`WS1` desktop main/sidecar, `WS2` shared packages + desktop renderer/popups, `WS3` mobile-rn, `WS4` web/admin/site/Edge/Cloudflare/.NET)을 병렬 실행한다. +- 중복 제거(SSOT 통합)와 리소스/메모리 최적화 및 동시성/보안 버그 수정을 함께 수행하되, Deno 계약(`contract:check`), API/IPC 시그니처, 도메인 오류 클래스·코드, fail-closed 동작, 보호 테스트, 런타임 `[~]`/`[!]` 상태 경계를 보존한다. +- 통합 후 `npm run verify:all`, `contract:check`, `check:migrations`, `version:check`, `security:secrets`, `dotnet test`, sidecar Python `unittest`, Edge + Worker Deno 테스트, `npm run build` + `check:desktop-renderer`, `test:metrics:write` 및 `docs/REFACTOR_WAVE6_REPORT.md` · `docs/map/*` 갱신을 완료한다. diff --git a/docs/REFACTOR_WAVE5_REPORT.md b/docs/REFACTOR_WAVE5_REPORT.md new file mode 100644 index 0000000..dcab7b9 --- /dev/null +++ b/docs/REFACTOR_WAVE5_REPORT.md @@ -0,0 +1,87 @@ +# Refactor Wave 5 Report — 전 표면 최적화 · 소스 위생 · 잔여 백로그 전수 해소 (Waves 0–12) + +> 기준일: 2026-11-13 +> 기준 버전: 1.16.5 (버전 변경 없음) +> 범위: `apps/*`, `packages/*`, `server/supabase`, `site/`, `scripts/ci/*`, `.forgejo/workflows/*`, 아키텍처 맵(`docs/map/*`) +> 선행 감사·정책: [`REFACTOR_POLICY.md`](./REFACTOR_POLICY.md), [`REFACTOR_WAVE5_AUDIT.md`](./REFACTOR_WAVE5_AUDIT.md), [`tdd-red/07-revamp-plan.md`](./tdd-red/07-revamp-plan.md) + +## 1. 결론 + +Wave 5 및 이어진 Waves 0–12 통합 작업은 [`REFACTOR_WAVE5_AUDIT.md`](./REFACTOR_WAVE5_AUDIT.md)가 식별한 계약·위생 과제(`G1`~`G7`)와 [`docs/map/11-gap-backlog.md`](./map/11-gap-backlog.md)에 남아 있던 모든 저장소 내 코드·게이트 백로그(`GAP-PERF-01` 잔여, `GAP-PERF-02`, `GAP-PERF-03`, `GAP-HYGIENE-01`, `GAP-I18N-03`, `GAP-UX-08`, `GAP-SYNC-08`, `GAP-MTG-02`, `GAP-QA-06`, TDD v2.0 Phase 2~5)를 전수 구현하고 자동화 검증을 마쳤다. + +커밋, 태그, 푸시, 배포, 운영 DB `supabase db push`는 수행하지 않았다. 물리 기기 시각 확인(`Fold6`/`Tab S11` 펼침·접힘, 비-한/영 로케일 실기기 렌더)과 대화형 Windows 데스크톱 GUI 눈 확인(`run-desktop.bat`)이 필요한 항목은 코드·자동화 검증 완료 사실을 기록하되 `AGENTS.md §4` 규칙에 따라 `[~]` 경계를 유지했다. + +## 2. 불변 조건과 실행 원칙 + +- 보호 수용 여정 6종(`apps/desktop/tests/e2e/{navigation,settings,onboarding,customer-support,records}.spec.ts`, `apps/web/e2e/smoke.spec.ts`)은 한 줄도 수정·약화하지 않았다(`check:protected-tests` GREEN). +- 신규 동작·계약은 실패 조건을 먼저 확인한 뒤(TDD RED → GREEN) 행동 기반 단정으로 고정했다. +- `test:quality` 래칫 기준선(약한 단정 `128`, ambient 시계/난수 `203`) 증가 0건을 유지했으며, `scripts/ci/lib/test-files.mjs`가 미추적 신규 테스트 파일(`git ls-files --cached --others --exclude-standard`)까지 스캔하도록 보강했다. +- 에이전트 서브셸에서 Electron GUI를 백그라운드 실행하지 않았다(`AGENTS.md §3`). + +## 3. Changed + +### 3-1. 번들 다이어트 · 런타임/SQLite 최적화 · 저장소 위생 (Waves 0–5) + +- **번들 & 로케일 분리 (`GAP-PERF-02`):** `@d3ro/i18n`을 동적 로케일 청크(`index.tsx`), 무-React 동기 로더(`@d3ro/i18n/main`), 모바일 Metro `inlineRequires` 엔트리(`index.native.tsx`)로 분리하고, 데스크톱 `AppLayout.tsx`(7페이지·6모달 `React.lazy`), 모바일 `App.tsx`(20+ 보조 화면 `getComponent`), 웹 `MarkdownPreview`(`next/dynamic` + 다이어그램 존재 시에만 `mermaid` 임포트)를 적용했다. 데스크톱 초기 부팅 JS가 **`8.79 MB` → `3.63 MB`(`main 2,085.73 KB` + `renderer 1,549.25 KB`, `-58.6%`)**로 감소했다. +- **데스크톱 SQLite · 프로세스 · 메모리 (`GAP-PERF-01` 잔여, `GAP-PERF-03`):** + - SQLite WAL 성능 PRAGMA(`synchronous=NORMAL`, `mmap_size=64MB`, `cache_size=-16000`), FTS5 `tokenize = 'trigram'` 전문 검색(`history_fts`, `meeting_sessions_fts`, `meeting_memos_fts`), `SqliteChunkStore` `Float32Array` 바이너리 `embedding_blob` + `WeakMap` 캐시, `PersonalGraphService` 단일 트랜잭션 배치 처리. + - Windows `koffi` `SendInput` 일원화(`NutKeyboardPort`, `ScreenContextService`), 기본 모드 1,000Hz `mousemove`/`wheel` 훅 미구독, 부팅 시 4개 팝업 선생성 제거, `LocalSTTService.releasePrimaryModel`(클라우드 전환·15분 유휴 시 주 Whisper 모델 언로드, UIA 브리지 유지). + - 장시간 회의 녹음 PCM을 메모리에 누적하지 않고 44바이트 WAV 헤더 스풀로 디스크에 직접 스트리밍하는 `DiskWavAudioSink`(`O(1)` RAM) 배선. +- **패키징 · 스크립트 · 모바일 R8 · `.NET` 정리 (`GAP-HYGIENE-01`):** + - 루트 중복 `resources/sox/`(5.21 MB) 및 불필요 바이너리 10종 제거, 미구현 데스크톱 광고 어댑터 9종 단일화(`UNAVAILABLE_AD_NETWORK_SPECS`), `scripts/local/` 109개 및 루트 미참조 스크립트 16개 삭제 + `scripts/ci/clean-deep.mjs`(`npm run clean:deep`) 추가. + - `apps/mobile-rn` 루트 순환 의존성(`d3ro-voice-monorepo`)·NTFS 정션 제거, Android 릴리스 R8(`enableProguardInReleaseBuilds=true`) + `shrinkResources` + 12개 로케일 `localeFilters` 및 `proguard-rules.pro` 보강(`verify-mobile-build-config.mjs` 검증). + - `.NET` `SttController` 무호출 레거시 라우트(`GET /api/stt/providers`, `POST /api/stt/test`) 제거. + +### 3-2. 코어 SSOT 공용화 & PII/ZDR 프로덕션 배선 (Wave 6 — `G3`, `G4`) + +- **`G3` (`W5-01`):** `@d3ro/core`의 `redactPII`/`redactPIIMessages`/`rehydrateText`를 데스크톱 `OnlineLLMService`(클라우드 LLM 전송 전 PII 마스킹 및 응답 복원)와 `support-handlers.ts`(진단 번들 내보내기 마스킹)에 배선하고, `secureWipeAudioChunks`/`secureZeroBuffer`를 `VoiceModeService`·`AudioCaptureService` 오디오 버퍼 정리 경로에 연결했다(`pii-zdr-wiring.test.ts` 4/4 PASS). +- **`G4` (`W5-05..07`):** `packages/core/src/{guards,csv,format,unified-search,admin-roles}.ts`를 추출해 앱·서버 간 중복 검증/파서/포매터/검색 스니펫·랭킹/관리자 권한 계층을 단일 SSOT로 통합하고 `core-contract.generated.ts`를 동기화했다(`contract:check` GREEN). + +### 3-3. i18n 고아 키 정리 · 계약 게이트 · 전 표면 12개 로케일 노출 (Wave 7 — `G5`, `GAP-I18N-03`) + +- 코드 전체 정적/동적 참조 감사를 거쳐 미참조 죽은 키 **253개**를 제거해 **`2,500`키 × 12로케일**로 정리하고, `scripts/ci/sync-i18n-locales.mjs`의 하드코딩 번역값을 모두 제거해 `--check` 전용 검증기로 전환했다. +- `scripts/ci/check-i18n-contract.mjs`(`npm run check:i18n[:test]`)와 `packages/i18n/__tests__/locale-contract.test.ts`(15/15 PASS)를 추가했다. +- 웹(`LocaleSwitcher`, `I18nProvider`, `locale-switcher.test.tsx` 3/3 PASS)과 모바일(`index.native.tsx` 12개 로케일 ESM + Metro `inlineRequires`, `OnboardingScreen`/`SettingsScreen`/`AccountScreen` 12개 언어 선택기, Android 12개 `localeFilters`, `mobile-i18n-locales.test.tsx`) 전 표면에 12개 언어 선택을 개방했다. + +### 3-4. `site/` 정적·CI 게이트 편입 & Web 팀원 수 집계 (Wave 8 — `G6`) + +- `.eslintignore`에서 `site/` 제외를 해제하고 `typecheck:site`·`lint:site`(`--max-warnings=0`)·CI `site` 프로덕션 빌드를 루트 `verify:all` 및 `.forgejo/workflows/ci.yml`에 편입했다. +- 웹 `apps/web/src/lib/team-client.ts` 및 `team-card-grid.tsx`를 통해 `team_members` 실제 인원수(`member_count`)를 집계·렌더링하도록 수정했다(`team-client.test.ts` 3/3 PASS). + +### 3-5. 모바일 대화면 반응형 · 메모 `revision` CAS · 전 표면 화자 분리 · 대형 파일 분리 (Waves 9–11) + +- **`GAP-UX-08` (태블릿·폴더블 `>=600dp`):** `packages/ui-native/src/responsive.tsx`(`resolveResponsiveLayout`, `useResponsiveLayout`, `useContentWidth`, `ContentColumn`) 및 `FreeTierBanner` `90dp` 슬롯 예약을 추가하고 모바일 10개 주요 화면에 2열 그리드·본문 폭 상한(`880dp`/`520dp`)·인라인 액션 버튼 폭 제한을 적용했다(`responsive-layout.test.tsx` 4/4 PASS). +- **`GAP-SYNC-08` (`meeting_memos.revision` CAS):** 74번째 마이그레이션 `server/supabase/migrations/20261113000001_meeting_memos_revision_cas.sql`로 단조 증가 `revision` 컬럼·트리거를 추가하고 `@d3ro/api-client`, 모바일 `meetings-service.ts`(`A→B→A` 충돌 차단), 데스크톱 SQLite 스키마·`sync-adapters.ts`를 갱신했다. +- **`GAP-MTG-02` (전 표면 화자 분리):** 데스크톱 사이드카 `POST /diarize`(`pyannote.audio` + 무의존 음향 에너지 VAD 폴백, Python `unittest` 30/30 PASS)를 `LocalSTTService.sidecarBaseUrl` → `MeetingModeService._diarizeTranscript`에 배선하고, `@d3ro/core/meeting-transcript` 화자 추출/필터 유틸과 화자 배지·다중 화자 필터 칩을 데스크톱(`TranscriptTab`/`EditableSegment`), 웹(`live-transcript-list.tsx`), 모바일(`MeetingDetailScreen.tsx`)에 일관되게 구현했다. +- **`G7` (`W5-11` 대형 파일 분해):** `SettingsModal.tsx`(`951` → `349`줄)에서 `GeneralSettingsTab`·`AudioSettingsTab`·`LlmSettingsTab`·`AboutSettingsTab`·`settings-model-helpers.ts`를 추출하고, `SuggestionService`에서 순수 정책 헬퍼 `suggestion-policy-helpers.ts`를 분리했다. + +### 3-6. TDD v2.0 Phase 2~5 완결 & 설치 산출물 스모크 (Wave 12 — `GAP-QA-06`) + +- `@d3ro/core/ports`(`Clock`, `FakeClock`, `Random`, `createFakeClock`, `createSeededRandom`) 추가 (`ports.test.ts` 4/4 PASS). +- `packages/ui` `SegmentControl` ARIA 탭 계약(`role="tablist"`, `role="tab"`, `aria-selected`, 키보드 `Enter`/`Space`) 보강 및 `ds-contract.test.tsx`(4/4 PASS) + `scripts/ci/check-ds-contract.mjs`(`check:ds-contract[:test]`) 추가. +- `scripts/ci/run-affected-tests.mjs`(`test:affected[:test]`) 및 `scripts/ci/verify-desktop-installer-smoke.mjs`(`release:installer:smoke[:test]`, 음성 케이스 8종) 작성 후 `package.json`, `release-desktop.mjs`, `verify-release-metadata.mjs`, `.forgejo/workflows/{ci,release}.yml`에 배선. +- 최신 테스트 포트폴리오 지표를 [`docs/tdd-red/metrics/2026-11-13.md`](./tdd-red/metrics/2026-11-13.md)에 기록했다(`422` 스위트 파일 / `3,558` 케이스 / `9,224` 단정). + +## 4. KEEP / DEFER 결정 + +- **Stryker 뮤테이션 러너 미설치 유지:** `@d3ro/core/ports` 결정성 포트는 도입했으나, Stryker 패키지 설치는 모노레포 lockfile 비대화 및 네이티브 모듈 트리에 영향을 주므로 설치하지 않고 선택적 외부 실험으로 남겼다. +- **대화형 데스크톱 GUI 수용 테스트(`test:acceptance:desktop`):** Forgejo Linux 러너에는 Windows/X 디스플레이 세션이 없으므로 CI에서는 `release:installer:smoke`(산출물·서명·ASAR·렌더러 번들·네이티브 ABI 무결성)를 강제하고, 실제 창 렌더링 E2E는 로컬/Windows 릴리스 전 실행으로 유지한다. +- **외부 계정·콘솔 차단(`EXT-*`):** Authenticode 코드 서명 인증서, Payple 가맹점 계약·키, Firebase `google-services.json`, AdMob 콘솔 승인, Google Play 비공개 테스트(12명×14일), macOS 러너는 저장소 밖 조건이므로 `[!]` 상태를 유지한다. + +## 5. Verification + +| Gate | Result | +|---|---| +| CI `--self-test` 16종 (`test:hygiene:test`, `check:protected-tests:test`, `test:quality:test`, `check:i18n:test`, `check:ds-contract:test`, `test:affected:test`, `check:design:test`, `check:desktop-renderer:test`, `check:migrations:test` [74], `security:secrets:test`, `release:metadata:test` [18], `release:installer:smoke:test` [1+8], `release:mobile:*:test` 4종) | **PASS (16/16)** | +| 정적·계약 게이트 17종 (`test:hygiene` [415], `check:protected-tests`, `test:quality` [434, weak 128 / ambient 203], `check:i18n` [2,500×12], `check:ds-contract` [13], `check:design` [0], `check:migrations` [74], `security:secrets`, `version:check` [1.16.5], `contract:check`, `sync-i18n-locales --check`, `typecheck`, `typecheck:mobile`, `typecheck:site`, `lint`, `lint:mobile`, `lint:site`) | **PASS — 0 errors, 0 warnings** | +| 워크스페이스 전체 Vitest (`npm run test`) | **PASS — 254 files / 3,525 tests, 0 failed** (`desktop` 204/2,825 · `core` 38/618 · `web` 6/32 · `api-client` 4/31 · `i18n` 1/15 · `ui` 1/4) | +| 모바일 전체 Jest (`npm run test:mobile`) | **PASS — 89 suites / 605 tests, 0 failed** | +| `.NET` API 서버 (`dotnet test`) | **PASS — 28/28, 0 failed, 0 skipped** | +| 데스크톱 Python 사이드카 (`python -m unittest`) | **PASS — 30/30 OK** | +| 프로덕션 빌드 (`apps/desktop` + `check:desktop-renderer` + `site`) | **PASS** — desktop main `2,085.73 kB` + renderer `1,549.25 kB` (7 pages verified on disk); `site` 10 locales + `sitemap`/`robots`/`llms` | + +## 6. 검증 경계와 남은 수동/운영 단계 + +1. **운영 Supabase 마이그레이션 반영:** 신규 `20261113000001_meeting_memos_revision_cas.sql`(74번)은 정적 검증 및 클라이언트 하위 호환 폴백이 검증되었으나, 운영 DB 반영(`supabase db push`)은 배포 시점에 수행해야 한다. +2. **실기기 모바일 눈 확인:** `GAP-UX-08`(`>=600dp` 2열 그리드·배너 슬롯 고정) 및 `GAP-I18N-03`(모바일 12개 로케일 전환)은 Jest·빌드 설정 검증을 마쳤으며, 실제 Fold6/태블릿 `open`/`closed` Maestro 시각 확인이 남아 있다. +3. **대화형 Windows Electron 실행 확인:** `run-desktop.bat`을 통한 다중 화자 실음성 회의 녹음(`DiskWavAudioSink` + `POST /diarize`) 및 UI 눈 확인은 사용자 데스크톱 세션에서 수행한다. diff --git a/docs/REFACTOR_WAVE6_REPORT.md b/docs/REFACTOR_WAVE6_REPORT.md new file mode 100644 index 0000000..01e324b --- /dev/null +++ b/docs/REFACTOR_WAVE6_REPORT.md @@ -0,0 +1,96 @@ +# Refactor Wave 6 Report — 전 표면 코드 위생 · 최적화 · 버그 헌팅 (WS1–WS4 병렬) + +> 기준일: 2026-11-14 +> 기준 버전: 1.16.5 (`1160500`, 버전 변경 없음) +> 범위: `apps/{desktop,web,mobile-rn,admin,api-server}`, `packages/{core,i18n,ui,ui-native,api-client}`, `server/{supabase,cloudflare-worker}`, `site/` +> 정책: [`REFACTOR_POLICY.md`](./REFACTOR_POLICY.md) Wave 6 + +--- + +## 1. 결론 + +Wave 6는 4개 파일 소유 경계(`WS1`–`WS4`)를 겹치지 않게 분할하여 병렬로 **코드 위생(중복 SSOT 통합)**, **성능/메모리/리소스 누수 최적화**, **동시성·보안·비동기 경합 버그 헌팅 및 회귀 테스트 고정**을 완료했다. + +- **전 표면 자동화 게이트 GREEN:** `npm run verify:all`, `npm run version:check`, `npm run contract:check`, `npm run check:migrations`, `npm run security:secrets`, `dotnet test`, Python `unittest`, Deno `server/supabase/functions` + `server/cloudflare-worker`, `npm run build` + `npm run check:desktop-renderer`가 모두 통과했다. +- **실행하지 않은 경계 유지:** `git commit`/`push`/`tag`/`publish`, Electron GUI 백그라운드 기동, 실기기 Android(`Fold6`)/iOS Maestro, 운영 Supabase `db push`는 수행하지 않았으며 `docs/map/*` 및 `docs/v3/MOBILE_APP_COMPLETION_SSOT.md`의 `[~]`·`[!]`·`RED` 판정을 유지했다. + +--- + +## 2. 워크스트림별 변경 요약 + +### WS1 — Desktop Main & Sidecar (`apps/desktop/src/main/**`, `apps/desktop/sidecar/**`) +- **IPC 브로드캐스트 SSOT 통합:** 9개 IPC/부트스트랩 파일의 중복 전송 로직을 `apps/desktop/src/main/ipc/renderer-broadcast.ts` (`safeSendToRenderer`, `broadcastToAllWindows`)로 단일화했다. +- **온라인 LLM 스트림 취소/예외 방어 (`OnlineLLMService.ts`):** `_postOnlineRequest` 추출, `this._abortController`를 `chatStream`에 연결(`cancelGeneration()`/`dispose()` 시 진행 중인 스트림 중단), `401` 수신 시 토큰 초기화, 빈/누락 `data.text` 가드, fetch/JSON/abort 예외의 `D3ROError` 래핑, `resetOnlineLLMServiceForTests()` 내 `instance.dispose()` 호출을 적용했다. +- **통합 검색 정확도·FTS5 폴백 (`UnifiedSearchService.ts`, `db/index.ts`, `db/schema.ts`):** `anyMeetingWhere`로 회의/메모 조건 통합, 메모 스니펫 `createdAt desc`·회의 `startedAt desc` 정렬 일관화, `meetingTotal` 이중 집계 버그 수정, `hasAllFtsTables` + 런타임 FTS5→`LIKE` 폴백 추가, `idx_meeting_sessions_started_at` 및 `idx_meeting_memos_created_at` 인덱스를 추가했다. +- **RAG 벡터 캐시 메모리·정합성 (`services/rag/chunk-store.ts`, `retrieval.ts`, `sync/sync-adapters.ts`, `db/index.ts`):** `invalidateEmbeddedChunksCache`를 내보내 `knowledgeAdapter.applyRemote`/`deleteLocal`, DB close/import/테스트 바인드 헬퍼 및 변경 `try/finally` 경로에 연결했다. `Float32Array` `vector` 디코드 이후 캐시된 `StoredChunk`의 중복 `embedding` JSON 문자열을 제거하고, `decodeFloat32Buffer`/`resolveChunkVector`에서 손상/비유한 JSON 행을 방어했다. +- **회의 WAV 싱크·타이머/윈도우 누수 (`services/meeting/disk-wav-audio-sink.ts`, `AdMediationEngine`, `AudioCaptureService`, `LocalLLMService`, `audio-handlers`, `bootstrap.ts`, `WindowManager.ts`):** `MAX_WAV_DATA_BYTES = 0xffffffff - 36` uint32 오버플로 상한 내보내기 및 가드, `openSync` 직후 44B 헤더 write 실패 시 `_fd`와 `.wav.part` cleanup을 추가했다. 광고 경매/오디오 테스트/로컬 LLM 서버 폴링/종료 핸들러 타이머 누수 및 팝업 `hide`/`show`/`alwaysOnTop` 경합을 수정했다. +- **Python 사이드카 (`apps/desktop/sidecar/main.py`):** `finally`에서 `UploadFile.close()` 보장, `<2`바이트(HTTP 400)·홀수 바이트 PCM 절단 방지, `_watch_disconnect` 취소 처리, `/shutdown` 시 `_download_thread` join을 추가했다. +- **회귀 테스트:** `online-llm-service.test.ts` (10), `rag-chunk-store-cache.test.ts` (8), `renderer-broadcast.test.ts` (2), `bug-hunt-timer-cleanup.test.ts` (3), `popup-hide-show-race.test.ts` (2), `apps/desktop/sidecar/tests/test_transcribe_hygiene.py` (3) 추가 및 `UnifiedSearchService.test.ts` (17), `disk-wav-audio-sink.test.ts` (6) 보강. + +### WS2 — Shared Packages & Desktop Renderer (`packages/*`, `apps/desktop/src/renderer/**`) +- **Deno 동기화 계약 무변경:** `packages/core/src/{plan-catalog,web-urls,guards,admin-roles}.ts` 미변경(`contract:check` GREEN). +- **`@d3ro/i18n` 비동기 레이스 차단 (`packages/i18n/src/{shared.ts,index.tsx,index.native.tsx}`):** `I18nStorage`, `noopI18nStorage`, `safeLoadStoredLocale`, `safeSaveStoredLocale`, 비유한 날짜 가드를 `shared.ts`로 통합하고, `cancelled` + `userChangedLocaleRef` + `localeRevisionRef` 가드로 지연된 `storage.load()`가 사용자 `setLocale()` 선택을 덮어쓰거나 언마운트 후 상태를 갱신하는 경합을 차단했다 (`__tests__/i18n-provider.test.tsx` 10). +- **`@d3ro/core`, `@d3ro/ui`, `@d3ro/ui-native`, `@d3ro/api-client`:** `utils/pii-redactor.ts` 플레이스홀더 충돌 회피·정규식 인덱스 리셋·길이 정렬 단일 패스 `rehydrateText`, `csv.ts` UTF-8 BOM + `\r` 이스케이프, `unified-search.ts`, `utils/meeting-markdown.ts`, `meeting-transcript.ts`(`formatDurationClockFromMs` 재사용·유한 날짜 가드) 보강 (`__tests__/pii-redactor.test.ts` 5, `__tests__/shared-utilities.test.ts` 10). `@d3ro/ui` `wave-math.ts` 분리 + `AudioVisualizerBar.tsx`/`GradientWave.tsx` 캔버스 `LinearGradient` 캐싱(`__tests__/wave-visualizer.test.tsx` 3), `@d3ro/ui-native` `resolveContentMaxWidth` 및 `WaveBars.tsx` 비유한 가드, `@d3ro/api-client/src/transcribe.ts` 음수 지연 클램핑. +- **데스크톱 렌더러 & Vanilla JS 팝업 6종:** `utils/error-message.ts` (`toErrorMessage`) 신설, `meeting-format.ts`/`meeting-documents-model.ts`/`meeting-transcript-model.ts`/`ollamaModelPullController.ts` 정리, `formatters.ts`/`UnifiedSearchPage.tsx` 비유한 날짜 가드, 주요 페이지·모달·훅(`App.tsx`, `AppLayout.tsx`, `SettingsModal.tsx`, `HomePage.tsx`, `MeetingModePage.tsx`, `MeetingDetailTabs.tsx`, `MeetingChatPanel.tsx`, `VoiceConversationPage.tsx`, `KnowledgeBasePage.tsx`, `CloudSyncSection.tsx`, `TemplateSection.tsx`, `AdBanner.tsx`, `RewardedQuotaModal.tsx`, `TitleBar.tsx`, `FileDropZone.tsx`, `OnboardingModal.tsx`, `OllamaGuideModal.tsx`, `CodexOAuthGuideModal.tsx`, `InputConsentPanel.tsx`, `useLicenseState`, `useKeyBindingMap`, `useAppUpdateStatus`)의 언마운트/시퀀스/리스너/타이머를 정리했다. 6개 팝업(`beforeunload` 리스너·타이머 해제, `textContent = ''`, `result-popup` `prepareVersion`/`isVisible`/rAF 취소, `caption-overlay` 라인별 `fadeTimer`, `recording-tip`·`suggestion-overlay` 클램핑)과 `renderer-popups-and-helpers.test.ts` (7) 추가. + +### WS3 — Mobile RN (`apps/mobile-rn/src/**`, `apps/mobile-rn/__tests__/**`) +- **서비스 가드·오류·음성 태그 SSOT 통합:** `features/shared/service-guards.ts`, `features/shared/owned-cache-files.ts`, `features/import/abort-guard.ts`, `lib/locale-speech.ts`(`toSpeechLanguageTag` 12개 로케일), `features/meetings/meeting-error-message.ts`를 신설하고, 26개 이상 서비스/화면의 `requireUuid`(14회), `requireUserId`(8회), `client()`(5회), `uuid`/`toServiceError`(각 4회), `record`/`stringValue`/`nonNegativeInteger`/`throwIfCancelled`(각 3회), 소유 캐시 정리(4회), `formatDuration`(`@d3ro/core/format` `formatDurationClockFromMs` 재사용)을 도메인 오류 클래스·코드·메시지 보존 상태로 단일화했다. +- **라이프사이클·동시성·UI 결함 수정:** + - `FreeTierBanner.tsx`: 광고 슬롯 변경(`90dp`->`50dp`) 시 `measuredHeight` 고착 초기화. + - `durable-processing-queue.ts`: `FileSystem.exists` 대기 전 `AbortController` 등록 및 `try/finally` 정리로 조기 폐기 경합 차단. + - `RecordScreen.tsx`: 권한/세션 전환 중 녹음 세션 리스 누수 차단. + - `TalkScreen.tsx`: 12개 로케일 TTS 언어 태그 및 실시간 인사말 로케일 동기화. + - `HistoryDetailScreen.tsx`, `SettingsScreen.tsx`, `OnboardingScreen.tsx`, `AccountScreen.tsx`, `MeetingDetailScreen.tsx`: 언마운트 시 오디오 정지, 지연 비동기 응답 차단, 로케일 동기화 바운스 방지 및 `try/finally` 저장 잠금, 타이머/요청 시퀀스/임시 내보내기 정리. +- **회귀 테스트:** 9개 Jest 스위트 추가(`durable-queue-early-discard.test.ts`, `free-tier-banner-resize.test.tsx`, `history-detail-unmount-regression.test.tsx`, `meeting-detail-unmount-regression.test.tsx`, `onboarding-locale-regression.test.tsx`, `record-permission-session-regression.test.tsx`, `service-guards.test.ts`, `settings-locale-sync-regression.test.tsx`, `talk-locale-recorder-regression.test.tsx`) → `98` suites / `625` tests 통과. + +### WS4 — Web, Admin, Site, Supabase Edge, Cloudflare Worker, .NET API +- **Supabase Edge (`server/supabase/functions`):** `_shared/json-response.ts`(`jsonResponse`/`json`/스트리밍 바이트 상한 `readJsonBody`)를 20개 Edge 핸들러에 CORS/`Cache-Control`/헤더 계약 유지 상태로 적용하고 비보호 `req.json()` 예외를 400/413 fail-closed로 전환했다. `account-delete`(`SAFE_INTERNAL_CODES`), `llm-proxy`(비정상 프로바이더 JSON 시 502 + 쿼터 환불), `_shared/payple.ts`(`postPaypleJson` `AbortSignal.timeout`), `realtime-token/openai-provider.ts`(`AbortSignal.timeout`) 보강 및 `_shared/json-response.test.ts` 외 단위 테스트 추가. +- **.NET API (`apps/api-server/**`, `apps/api-server.Tests/**`):** `SttProxyService.DecodeAudioBase64`에서 `Convert.FromBase64String` 이전 `MaxAudioBytes = 26 * 1024 * 1024` `MaxBase64Length` 상한을 강제하고, `SttController`/`LlmController`/`AdminController` → `SttProxyService`/`LlmProxyService` → EF/HTTP/AssemblyAI 폴링까지 `HttpContext.RequestAborted` (`CancellationToken`)를 전파해 클라이언트 중단 시 유료 failover를 즉시 중단하도록 수정(`SttControllerSecurityTests.cs`, `SttFailClosedTests.cs` 보강). +- **Cloudflare Worker (`server/cloudflare-worker/src/`):** `resolveBackendTargetUrl`로 `//host`/`\host` SSRF 차단, `/worker-health`에서 `backendOrigin` 제거, `Host`/hop-by-hop 헤더 제거, `redirect: 'manual'`, `AbortSignal.timeout(30_000)`, 502/504 JSON 정리, `console.log` 제거, `push-drain.ts` `!response.ok` 본문 취소 및 `index.test.ts` 테스트 4건 추가. +- **Web (`apps/web`):** `markdown-preview.tsx` (`useId()` + 시퀀스 + `replaceChildren` `
`로 `innerHTML` XSS 제거, `isConnected` 확인, 로드 실패 시 `mermaidReady` 재설정), `web-push-control.tsx` (`mountedRef`/`activeUserIdRef`/`activeToggleSeqRef` + `runWebPushToggle`), `web-push.ts`/`web-push-session.ts` (`withWebPushTimeout`), `dashboard/page.tsx` (`mountedRef`+`requestSeqRef`), `team-client.ts` (`teamIds` 중복 제거, `memberCountError` fail-closed) + `apps/web/tests/{markdown-preview,web-push-control,team-client-edge}.test.ts` 추가.
+- **Admin (`apps/admin`):** `lib/request-security.ts` (`isSameOriginRequest`, `ADMIN_UUID_PATTERN`, 바이트 상한 JSON 리더) 및 `components/detail-row.tsx` (`Row` SSOT) 신설, `logout`(`sameSite: 'strict'`, CSRF, `no-store`), `license`/`login`/`backend`/`supabase` 라우트, `users/[id]`·`subscriptions/[id]` (`requireManager()` + UUID `notFound()`), `payment-history`/`checksum-copy`/`license-issuer-dialog`/`models/page.tsx` (언마운트 가드, 타이머 정리, `sttMemo` 리셋, `NaN`/음수 비용 거부) 보강.
+- **Site (`site/`):** `AppLoopDemo.tsx` `isHidden`/`isOutOfViewport` 분리 + `IntersectionObserver` 가드, `Download.tsx`·`Footer.tsx` `rel="noopener noreferrer"` 상향.
+
+---
+
+## 3. 전 표면 검증 결과 (실측)
+
+### 통합 검증 (`npm run verify:all` 및 부속 게이트)
+
+| 게이트 / 스위트 | 결과 | 비고 |
+|---|---|---|
+| `npm run test:hygiene` | 통과 (`438 test files`) | `.only`/무사유 `.skip`/`waitForTimeout` 0건 |
+| `npm run check:protected-tests` | GREEN (`변경된 보호 파일 0개`) | base `HEAD` 대비 |
+| `npm run test:quality` | GREEN (`457 test files`) | 기준선(약한 단정 `128`, ambient `203`) 대비 증가 0 |
+| `npm run check:i18n` | GREEN (`2500 keys × 12 locales`, `unreferenced=8/35`) | 카탈로그 정합 |
+| `npm run check:ds-contract` | GREEN (`13 components`) | 디자인 시스템 계약 |
+| `npm run check:design` | 통과 (`design-token violations: 0`) | 하드코딩 토큰/스타일 0 |
+| `npm run contract:check` | GREEN | `core-contract.generated.ts` 일치 |
+| `npm run check:migrations` | GREEN (`count: 74, errors: []`) | 마이그레이션 정합 |
+| `npm run version:check` | GREEN (`1.16.5 (1160500/1160500)`) | 버전 SSOT 일치 |
+| `npm run security:secrets` | 통과 | 런타임 파일 하드코딩 시크릿 0 |
+| `typecheck` / `typecheck:mobile` / `typecheck:site` | exit `0` | 전 표면 TS strict |
+| `lint` / `lint:mobile` / `lint:site` | exit `0` (`--max-warnings=0`) | 경고 0건 |
+| `@d3ro/desktop` Vitest | `210` files / `2865` tests passed | main + unit + red |
+| `@d3ro/web` Vitest | `9` files / `42` tests passed | SSR/컴포넌트/팀/푸시 |
+| `@d3ro/api-client` Vitest | `4` files / `31` tests passed | |
+| `@d3ro/core` Vitest | `39` files / `626` tests passed | PII/CSV/포맷/검색 포함 |
+| `@d3ro/i18n` Vitest | `2` files / `25` tests passed | 비동기 레이스 포함 |
+| `@d3ro/ui` Vitest | `2` files / `7` tests passed | 파형 캐싱 포함 |
+| `@d3ro/mobile-rn` Jest | `98` suites / `625` tests passed (`21.171 s`) | 9개 회귀 스위트 추가 |
+| `.NET` xUnit (`D3ROVoice.Api.Tests.csproj`) | `전체: 32, 통과: 32, 실패: 0, 건너뜀: 0` | Base64·CancellationToken 포함 |
+| Desktop Sidecar Python (`unittest`) | `Ran 33 tests in 2.131s`, `OK` | `test_transcribe_hygiene.py` 포함 |
+| Supabase Edge Deno (`deno test`) | `ok \| 270 passed \| 0 failed` | `_shared/json-response` 등 포함 |
+| Cloudflare Worker Deno (`deno check` + `deno test`) | `ok \| 9 passed \| 0 failed` | SSRF·타임아웃 포함 |
+| `npm run build` + `check:desktop-renderer` | exit `0` (`✓ built in 4.73s`, `7 page(s)`) | 프로덕션 렌더러 에셋 무결 |
+
+### TDD v2.0 정적 메트릭 (`docs/tdd-red/metrics/2026-11-14.md`)
+- 합계: `445 files` / `3655 cases` / `9549 assertions` / 약한 단정 `128` / ambient `203` / skip·todo `3` / `2500 keys × 12 locales` (생성: `npm run test:metrics:write`, 게이트 아님).
+
+---
+
+## 4. SKIP 및 잔여 위험
+
+- **런타임 GUI / 실기기 경계 유지 (`[~]`/`RED`):** Electron 실앱 `Ctrl+K`/팝업/오버레이 확인, Android Fold6 `open`/`closed` 실기기 Maestro·TalkBack·신규 설치(first-run)·비한/영 로케일 눈 확인, Play/Firebase/AdMob/Payple 외부 자격증명·운영 `supabase db push`는 이번 Wave 범위 밖으로 `[~]`/`[!]`/`RED`를 유지했다.
+- **문서·맵 동기화:** [`docs/map/00-index.md`](./map/00-index.md), [`docs/map/03`](./map/03-shared-packages.md)–[`11`](./map/11-gap-backlog.md), [`MOBILE_APP_COMPLETION_SSOT.md`](./v3/MOBILE_APP_COMPLETION_SSOT.md), [`REFACTOR_POLICY.md`](./REFACTOR_POLICY.md), [`.claude/skills/refactor-wave/SKILL.md`](../.claude/skills/refactor-wave/SKILL.md)에 Wave 6 변경과 최신 테스트 수치를 반영했다.
+- **미커밋 작업 트리:** 사용자 명시 전까지 `git commit`/`push`/`release`를 수행하지 않으며, 작업 트리 상태로 리뷰 대기한다.
diff --git a/docs/map/00-index.md b/docs/map/00-index.md
index 679c861..ea67b8e 100644
--- a/docs/map/00-index.md
+++ b/docs/map/00-index.md
@@ -2,7 +2,11 @@
 
 > Status: ACTIVE
 > Last full audit: 2026-09-13
-> Last update: 2026-11-04 — **테스트 위생 재편.** 버그헌팅 E2E(red-team cycle) 스펙과 중복·죽은 스펙 11개를 삭제하고, 데스크톱 E2E 를 공용 Electron 픽스처 + 5개 보호 여정으로 통합했다. 루트 `tests/e2e` 와 일회성 Playwright 러너 7개도 제거. 새 게이트 `npm run test:hygiene`(+`:test`)를 CI 두 파이프라인에 넣어 `.only`/이유 없는 skip/가짜 단정/머신 경로/`waitForTimeout`/`.e2e.test.ts` 를 막는다. 정본: [`docs/tdd-red/06-repo-application.md`](../tdd-red/06-repo-application.md).
+> Last update: 2026-11-14 — **전 표면 코드 위생 · 최적화 · 버그 헌팅 완결(Wave 6, WS1–WS4 병렬).** (1) **Desktop Main & Sidecar (`WS1`):** `ipc/renderer-broadcast.ts`(`safeSendToRenderer`/`broadcastToAllWindows`) 9개 파일 단일화, `OnlineLLMService` 스트림 abort/401/예외 래핑, `UnifiedSearchService` FTS5→`LIKE` 런타임 폴백·집계·정렬·인덱스(`started_at`/`created_at`) 보강, `rag/chunk-store.ts` 캐시 무효화·중복 `embedding` JSON 제거·손상 Float32 방어, `disk-wav-audio-sink.ts` uint32 오버플로·헤더 write 실패 fd 정리, `AdMediationEngine`/`AudioCaptureService`/`LocalLLMService`/`WindowManager` 타이머·팝업 레이스 수정, `sidecar/main.py` `UploadFile.close()`·PCM 바이트 경계·`/shutdown` 스레드 join 완료. (2) **Shared Packages & Desktop Renderer (`WS2`):** `@d3ro/i18n` `shared.ts` 및 지연 로드/언마운트 레이스 차단(`25/25`), `@d3ro/core` PII 플레이스홀더·CSV BOM/CR·타임스탬프·검색 경계값(`626/626`), `@d3ro/ui` `wave-math.ts` + 캔버스 `LinearGradient` 캐싱(`7/7`), `@d3ro/ui-native`/`api-client` 경계 가드, 렌더러 `utils/error-message.ts`·훅/컴포넌트 언마운트·타이머 정리 및 Vanilla JS 팝업 6종 `beforeunload`/DOM 안전화 완료. (3) **Mobile RN (`WS3`):** `features/shared/{service-guards,owned-cache-files}.ts`, `features/import/abort-guard.ts`, `lib/locale-speech.ts`(12개 로케일), `features/meetings/meeting-error-message.ts`로 26+ 파일 중복 가드·오류·포맷 통합, `FreeTierBanner` 슬롯 전환 시 높이 고착 수정·내구성 큐 조기 폐기 경합 차단·녹음 리스 누수·언마운트 재생/로케일 레이스 해결(Jest `98 suites / 625 tests PASS`). (4) **Web · Admin · Site · Edge · Worker · .NET (`WS4`):** Edge 20개 엔드포인트 `_shared/json-response.ts`(스트리밍 바이트 상한 포함 `readJsonBody`·`jsonResponse`) 통합 및 `account-delete`/`llm-proxy`/`payple`/`realtime-token` fail-closed 강화(Deno `270/270`), `.NET` `SttProxyService` Base64 상한 + `CancellationToken` 전파(xUnit `32/32`), Cloudflare Worker `resolveBackendTargetUrl` SSRF·타임아웃·`/worker-health` 정보 노출 차단(Deno `9/9`), 웹 `MarkdownPreview` DOM XSS/레이스·`WebPush` 재진입·`team-client` fail-closed(`42/42`), 어드민 `request-security.ts`/`detail-row.tsx`·CSRF/`ADMIN_UUID_PATTERN`/비용 검증, 사이트 `AppLoopDemo`/`rel="noopener noreferrer"` 보강 완료. 상세: [`REFACTOR_WAVE6_REPORT.md`](../REFACTOR_WAVE6_REPORT.md).
+>
+> Previous update: 2026-11-13 — **전 표면 성능 최적화 · 코드 위생 완결(Wave 5) · 백로그 일괄 구현 · TDD v2.0 게이트 완성.** (1) **소스·패키징 위생:** 루트 중복 `resources/sox/`(5.21 MB) 및 `apps/desktop/resources/sox/` 불필요 바이너리 10종 제거 + `electron-builder.yml` 필터 적용, 데스크톱 미구현 광고 어댑터 9종 단일화(`UNAVAILABLE_AD_NETWORK_SPECS`), `scripts/local/` 109개 및 미참조 루트 스크립트 16개 삭제 + `npm run clean:deep`(`scripts/ci/clean-deep.mjs`), `apps/mobile-rn` 루트 순환 의존성(`d3ro-voice-monorepo`)·NTFS 정션 제거, `.NET` `SttController` 무호출 중복 라우트(`GET /providers`, `POST /test`) 삭제. (2) **번들·코드 스플리팅 & 대형 모듈 분리:** `@d3ro/i18n`을 렌더러/웹 동적 로케일 청크(`index.tsx`), 무-React 동기 로더(`@d3ro/i18n/main`), 모바일 지연 엔트리(`index.native.tsx`, Metro `inlineRequires`)로 3분할하고, 데스크톱 `AppLayout.tsx`(7페이지·6모달 `React.lazy`), 모바일 `App.tsx`(`getComponent`), 웹 `MarkdownPreview`(`next/dynamic` + 조건부 `mermaid`) 스플리팅으로 데스크톱 초기 부팅 JS를 `8.79 MB` → `3.62 MB`(`-58.8%`)로 축소했으며, `SettingsModal.tsx`(`951`→`349`줄, 탭 4종 + `settings-model-helpers.ts`)와 `SuggestionService.ts`(`suggestion-policy-helpers.ts`) 순수 모듈 분리를 완료했다. (3) **데스크톱 SQLite · 프로세스 · 오디오 디스크 스트리밍:** SQLite WAL PRAGMA(`synchronous=NORMAL`, `mmap_size=64MB`, `cache_size=-16000`), FTS5 trigram 전문 검색, RAG `embedding_blob`(`Float32Array`) + `WeakMap` 캐시, `PersonalGraphService` 단일 트랜잭션, Windows `koffi` `SendInput` 일원화, 기본 모드 `mousemove`/`wheel` 훅 차단, 백그라운드 팝업 지연 생성, `LocalSTTService` 주 Whisper 모델 유휴/클라우드 언로드, 회의 녹음 PCM 디스크 스트리밍(`DiskWavAudioSink`, 메모리 상주 `O(N)→O(1)`)을 적용했다. (4) **Wave 5 계약·보안 & 기능 백로그 해소:** `@d3ro/core`에 `guards`/`csv`/`format`/`unified-search`/`admin-roles`/`ports` 6개 SSOT 모듈을 추출해 앱 간 중복을 제거하고, 클라우드 LLM·고객지원 `redactPII`/`rehydrateText` 및 녹음 폐기 시 `secureWipeAudioChunks`/`secureZeroBuffer`를 실배선했으며, 고아 키 253개를 정리한 `2,500`키 × 12개 언어를 데스크톱·웹(`LocaleSwitcher`)·모바일(온보딩/설정/계정 + Android `localeFilters` 12개, R8/`shrinkResources`) 전 표면에 노출했다. 또한 `site/` 정적·빌드 CI 게이트(`typecheck:site`/`lint:site`), 웹 `teams` 실 멤버 수 집계(`team-client.ts`), 모바일 `>=600dp` 태블릿/폴더블 반응형 레이아웃(`@d3ro/ui-native/responsive`, 10개 화면 + `FreeTierBanner` `90dp` 슬롯 예약), `meeting_memos.revision` 불변 CAS(마이그레이션 #74 `20261113000001`), 사이드카 `POST /diarize` + 데스크톱·웹·모바일 화자 배지·필터 바(`MTG-08`)를 완성했다. (5) **TDD v2.0 Phase 2~5 자동화 게이트:** `check:i18n`, `check:ds-contract`(`SegmentControl` ARIA `tablist`/`tab` + `@d3ro/ui` 테스트), `test:affected`, `release:installer:smoke`(`verify-desktop-installer-smoke.mjs`: PE64·blockmap·SHA-512·`app-update.yml`·ASAR Pickle·Ed25519 `.sig`)를 `verify:all` 및 `.forgejo/workflows/{ci,release}.yml`에 연결했다. 상세: [`REFACTOR_WAVE5_REPORT.md`](../REFACTOR_WAVE5_REPORT.md).
+>
+> Previous update: 2026-11-04 — **테스트 위생 재편.** 버그헌팅 E2E(red-team cycle) 스펙과 중복·죽은 스펙 11개를 삭제하고, 데스크톱 E2E 를 공용 Electron 픽스처 + 5개 보호 여정으로 통합했다. 루트 `tests/e2e` 와 일회성 Playwright 러너 7개도 제거. 새 게이트 `npm run test:hygiene`(+`:test`)를 CI 두 파이프라인에 넣어 `.only`/이유 없는 skip/가짜 단정/머신 경로/`waitForTimeout`/`.e2e.test.ts` 를 막는다. 정본: [`docs/tdd-red/06-repo-application.md`](../tdd-red/06-repo-application.md).
 >
 > Previous update: 2026-11-04 — **Wave 4 모노레포 위생 점검.** 사용되지 않는 chart/recharts·feature gate·내부 선언·Turbo/pnpm 잔여를 제거하고, mobile navigation 타입/로깅, push·quota 계약, embedding quota SSOT, updater dialog i18n, CI web build·migration metadata gate, `audio-purge` 함수 설정을 정합화했다. Web Push production call site, 12-locale 표면 노출, meeting memo ABA conflict, audio-purge 배포/pg_cron은 완료로 올리지 않고 `11`에 남겼다. 제품 버전은 1.16.1 그대로이며 커밋·푸시·배포·릴리스는 수행하지 않았다. 상세: [`REFACTOR_WAVE4_REPORT.md`](../REFACTOR_WAVE4_REPORT.md).
 >
@@ -33,7 +37,7 @@
 > Previous update: 2026-09-22 — **Gemma/Ollama 폭주 방어 계약을 기록했다.** 19:14:12 부팅 워밍업이 `keep_alive: 30m`으로 `gemma4:e4b`를 19:44:12까지 VRAM 3,226,342,521 bytes / context 4096으로 강제 상주시킨 것이 관측됐으며, 같은 시점 Windows GPU Engine PID 표본에는 Ollama의 활성 compute가 없었다. 즉 당시 상태는 무한 추론이 아니라 강제 residency였다. 19:11:17~19:11:58의 자동 제안 연속 생성은 기존 900 ms·12/min·5 candidates·128 tokens·한 글자 재생성 정책이 허용한 burst였다. 현재 구현 계약은 부팅 warmup 제거, `keep_alive: 2m`, 제안 600 ms / 최소 5 s 간격 / 기본 6회·hard max 12회 per min / 3 candidates / 64 tokens / 12-char growth / 8 s timeout, 그리고 요청별 취소·상한·종료 정리다. 독립 표적 검증은 6 test files / 69 tests passed / 0 failed, 변경 코드·테스트 ESLint와 `git diff --check`도 exit 0이다. Raw Ollama에서는 cold bounded 요청이 client hard timeout 15.044 s에 취소된 뒤 `/api/ps`가 비었고 `/api/version`은 80 ms에 회복했다. 명시 warmup은 HTTP 200 / 16.639 s, 후속 warm 요청은 body `options.num_predict=1`, `keep_alive='2m'`로 553 ms HTTP 200 / `done:true` / `eval_count:1` / `done_reason:length`였고 `/api/ps` expiry는 약 119.9 s였다. **19:48:59 +09:00에는 새 generate/unload/kill/retry 없이 충분히 지난 뒤 한 번의 `/api/ps`가 HTTP 200 / 45.8 ms / `{models:[]}`였고 `/api/version`은 HTTP 200 / 7.3 ms / `0.32.13`이었다.** 이는 raw API 수준의 expiry 뒤 unload 확인일 뿐 앱 재시작·GUI·실제 타이핑 증거는 아니므로 상태는 `[~]`로 유지한다 (`11` GAP-LLM-04, GAP-INPUT-06).
 >
 > Previous update: 2026-09-21 — **Input intelligence (입력 레메트리 + 다음 문장 제안) 신규**. 데스크톱에 입력 수집기(`InputTelemetryService`), UIA 컨텍스트 브리지(사이드카 `GET /uia/focus`), 제안 서비스(`SuggestionService`), 어렛 커 오버레이, 설정 > 입력 탭(동의·정책·주간 인사이트·개인 문구)을 추가했다. 카탈로그에 `INPUT-01`~`INPUT-08`(전부 데스크톱 `[~]` — 유닛 48건은 GREEN 이지만 **실앱 타이핑 검증 전**), 백로그에 GAP-INPUT-01~05 + GAP-LLM-03, §7 에 CONSTRAINT-INPUT-01(키 내용 미저장 — ActivityWatch 정책 채택)을 기록. 설계 근거는 조사 기반이다: 어렛은 `GetGUIThreadInfo` 가 아니라 UIA `TextPattern.GetSelection`(Chromium 은 `TextPattern2` 미구현), 타이핑 스트는 키코드 복원이 아니라 UIA 스냅샷 diff(한/일 IME 대응), 디바운스/토큰 한도는 인라인 컴플리션 실측값(Continue 350 / Tabby 250 / twinny 300 ms, 출력 64~256 토큰). 의존성: `koffi` 3.3.1(포그라운드 창 FFI), 사이드카 `uiautomation` 2.0.29 + `comtypes`. 데스크톱 유닛 총계 1409(+49), Electron ABI 실행에서 신규 실패 0건. 당시의 24.7초/4.9초 지연 설명과 `keep_alive: 30m`·부팅 워밍업 처방은 **현재 상태가 아닌 과거 가설/완화 이력**이며, 최신 운영 결론은 위 2026-09-22 항목과 `11` GAP-LLM-04를 따른다. 직전: LLM instruction-prompt fix (`9c2b4d4`): the custom-instruction path inserted the instruction's own wording instead of the processed result and had **never worked in any shipped release** (`v0.1.0-alpha`..`v1.4.0`, introduced `fea923d` 2026-04-05, not a regression). `llm-prompts.ts` is now the SSOT for prompt resolution and placeholder substitution, shared by `VoiceModeService` / `ChainService` / `LLM.PROCESS`. AI-04/05/06/07 are demoted to `[~]` on desktop — fixed with unit tests, but **not verified in a running app** and the four related `tests/red/*.usecase.test.ts` could not execute (`better-sqlite3` ABI). New: GAP-LLM-01 (no target-language setting), GAP-LLM-02 (this fix unverified); GAP-INFRA-06 amended (the ABI masks verification, not just dev-env switching cost); GAP-I18N-01 amended (`popup.error.default` missing in 10 locales). Earlier the same day: CAP-16 (desktop key bindings rebuilt on one `@d3ro/core/keybinding` SSOT — multiple bindings per action, mouse buttons, `HOTKEY` → `KEYBINDING` IPC group), verified on Windows by a manual run, so CAP-16 and CAP-02 are `[x]` and GAP-KEY-01 is closed. Still open: GAP-KEY-02/03, GAP-QA-02, GAP-I18N-01/02, GAP-INFRA-06, GAP-LLM-01/02, GAP-INPUT-01~05; `11` §7 holds accepted design constraints (things deliberately kept, not gaps)
-> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.16.1` (`release/product-version.json`, released 2026-11-04)
+> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.16.5` (`release/product-version.json`)
 > Purpose: let any agent (or human) answer two questions in under a minute:
 > 1. **What infrastructure exists?** (build, CI, services, APIs, data, packages, deploy)
 > 2. **How far is each feature developed?** (per surface, with file anchors and status)
diff --git a/docs/map/02-infrastructure.md b/docs/map/02-infrastructure.md
index eb98a1e..182212e 100644
--- a/docs/map/02-infrastructure.md
+++ b/docs/map/02-infrastructure.md
@@ -1,7 +1,7 @@
 # 02 — Repository & Infrastructure Map
 
 > Surface: whole repo
-> Last updated: 2026-11-08 — TDD 2.0 Phase 0-1 gates (test metrics, protected acceptance, quality ratchet) added to CI quality
+> Last updated: 2026-11-13 — Source/packaging hygiene (`clean:deep`, trimmed `apps/desktop/resources/sox`, macOS-only `@nut-tree-fork` `asarUnpack`, Android R8 + `shrinkResources` + 12-locale `localeFilters`), `@d3ro/i18n` 2,500-key split, `site/` static/build CI gate, and TDD v2.0 Phase 2–5 gates (`check:i18n`, `check:ds-contract`, `test:affected`, `release:installer:smoke`)
 > Source of truth for: layout, workspaces, build/test commands, CI/CD, Docker, deploy, scripts, resources
 
 ---
@@ -29,9 +29,8 @@ D:/workspace/D3ROVoice
 │   ├── cloudflare-worker/ Edge gateway (wrangler.toml + src/index.ts)
 │   └── cloudflare-site-bridge/ Site bridge worker: forwards `/app/*` to WEB_APP_ORIGIN, rewrites upstream redirects, else proxies to Pages
 ├── site/                 Vite landing site (deployed to Cloudflare Pages; GitHub Pages removed 2026-09-26, Wave 3)
-├── resources/            icons/ (empty), sox/ (bundled Windows SoX binaries)
 ├── release/              Version identity SSOT + license/evidence public keys
-├── scripts/              ~145 automation scripts + scripts/ci/ (31) + scripts/lib/
+├── scripts/              Automation scripts + scripts/ci/ (32, incl. clean-deep.mjs) + scripts/lib/ + scripts/verification/
 ├── docs/                 Design, phases, v2/v3 plans, deployment, map/ (this map)
 ├── memory/               Project status, handoffs, archive
 ├── test-results/         Last-run artifacts (root tests/e2e removed 2026-11-04 — orphaned duplicates)
@@ -81,28 +80,35 @@ npm run build:all | npm run ci  # typecheck + test + desktop/admin/web productio
 npm run checksum                # scripts/ci/generate-checksums.mjs
 npm run version:check | version:sync
 npm run release:metadata[:test]
+npm run release:installer:smoke[:test] # PE64, gzip blockmap, SHA-512, app-update.yml, ASAR Pickle, Ed25519 .sig smoke gate
 npm run release:forgejo[:check]  # canonical Forgejo publisher/feed
 npm run release:tag             # annotated/signed immutable release tag
 npm run security:secrets[:test] # hardcoded-secret scanner
 npm run check:desktop-renderer[:test] # built renderer pages reference only assets on disk
-npm run check:migrations[:test] # Supabase migration filename/order/non-empty metadata checks; no DB replay or remote drift
+npm run check:migrations[:test] # Supabase migration filename/order/non-empty metadata checks (74 migrations); no DB replay or remote drift
+npm run check:i18n[:test]       # 12-locale 2,500-key parity, placeholder consistency, literal t() existence & orphan budget
+npm run check:ds-contract[:test] # @d3ro/ui DS exports, theme-token purity, ARIA roles, and contract test coverage
 npm run rebuild:app             # rebuild better-sqlite3 in-place for Electron ABI
 npm run rebuild:test            # rebuild better-sqlite3 in-place for host Node ABI (Vitest)
 node scripts/ci/verify-native-abi.mjs --self-test # required packaged N-API prebuild missing/present fixture
-node scripts/ci/sync-i18n-locales.mjs # synchronize 12 locales against ko/en SSOT
+node scripts/ci/sync-i18n-locales.mjs [--check] # verify/sync 12 locales against ko/en SSOT (zero hardcoded translations)
 npm run test:e2e:red            # content-report red e2e
 npm run release:mobile:boundary[:test]
 npm run release:mobile:config[:test]
 npm run release:mobile:build-config:test
 npm run release:play:assets[:test]
 npm run typecheck               # all workspaces; web/admin run `next typegen` before `tsc`
-npm run test                    # all workspaces
+npm run typecheck:site          # site/ tsc --noEmit (outside npm workspaces)
+npm run test                    # all workspaces (desktop, web, api-client, core, i18n, ui)
+npm run test:affected[:test]    # affected test selector over git diff (falls back to full suite on unknown paths)
 npm run lint                    # eslint apps/desktop apps/web apps/admin packages
+npm run lint:site               # eslint site/src --max-warnings=0
 npm run format                  # prettier
 npm run typecheck:mobile        # apps/mobile-rn tsc (outside npm workspaces)
 npm run lint:mobile             # apps/mobile-rn eslint --max-warnings=0
 npm run test:mobile             # apps/mobile-rn test:ci (jest --runInBand)
-npm run verify:all              # aggregate: workspaces + mobile (typecheck/lint/test)
+npm run verify:all              # aggregate: hygiene + protected-tests + quality + i18n + ds-contract + workspaces + mobile + site
+npm run clean:deep              # remove build outputs, caches, temp browser profiles, dangling symlinks (--dry-run supported)
 ```
 
 Per-app commands that matter:
@@ -155,11 +161,11 @@ See [`03-shared-packages.md`](./03-shared-packages.md). Summary:
 
 | Package | Provides |
 |---|---|
-| `@d3ro/core` | Domain types, `D3ROError`/`ErrorCode`, IPC channel SSOT, key-binding SSOT (`./keybinding`), plan/quota catalog including `knowledge_embedding`, constants, `crypto-license`, `pii-redactor`, `secure-memory`, `supabase-config`, `meeting-markdown`, `markdown-to-docx`; Deno consumes the generated contract checked by `contract:check`; has vitest tests (`packages/core/vitest.config.ts`, `npm run test --workspace=@d3ro/core`) |
-| `@d3ro/ui` | Theme tokens, CSS vars, MUI DS components (web/desktop) |
-| `@d3ro/ui-native` | RN design system (MetalCard, PhosphorText, Led, PhysicalButton, WaveBars, …) |
-| `@d3ro/i18n` | 12 locales / 2,742 parity-checked keys, `I18nProvider`, `t()`, date/number/relative formatters; includes native updater-dialog keys |
-| `@d3ro/api-client` | Supabase browser/server clients, meetings/history/usage/transcribe wrappers, canonical push-token/provider + push/quota RPC types; has vitest tests |
+| `@d3ro/core` | Domain types, `D3ROError`/`ErrorCode`, IPC channel SSOT, key-binding SSOT (`./keybinding`), plan/quota catalog including `knowledge_embedding`, constants, `crypto-license`, `pii-redactor`, `secure-memory`, `supabase-config`, `meeting-markdown`, `markdown-to-docx`, plus cross-surface `guards`, `csv`, `format`, `unified-search`, `admin-roles`, speaker diarization helpers (`meeting-transcript`), and deterministic `Clock`/`Random` `ports`; Deno consumes the generated contract checked by `contract:check`; has vitest tests (`packages/core/vitest.config.ts`, 38 files / 618 tests) |
+| `@d3ro/ui` | Theme tokens, CSS vars, MUI DS components (web/desktop), ARIA-accessible `SegmentControl` (`tablist`/`tab`), and DS contract tests (`packages/ui/__tests__/ds-contract.test.tsx`, guarded by `check:ds-contract`) |
+| `@d3ro/ui-native` | RN design system (MetalCard, PhosphorText, Led, PhysicalButton, WaveBars, …) + `>=600dp` tablet/foldable responsive primitives (`responsive.tsx`: `resolveResponsiveLayout`, `useResponsiveLayout`, `useContentWidth`, ``) |
+| `@d3ro/i18n` | 12 locales / 2,500 parity-checked keys (253 orphan keys pruned on 2026-11-13), `I18nProvider`, `t()`, date/number/relative formatters; guarded by `check:i18n` and `packages/i18n/__tests__/locale-contract.test.ts` (15 tests) |
+| `@d3ro/api-client` | Supabase browser/server clients, meetings/history/usage/transcribe wrappers, canonical push-token/provider + push/quota RPC types, `meeting_memos.revision` CAS shape; has vitest tests (4 files / 31 tests) |
 
 ---
 
@@ -174,7 +180,7 @@ See [`03-shared-packages.md`](./03-shared-packages.md). Summary:
 Stages `validate → test → build → e2e → package → publish → deploy`. Primary pipeline for desktop Windows/macOS releases (Forgejo Generic Registry is the canonical updater feed; GitLab project 1172 is a legacy mirror) and production mobile releases (`mobile-production-release`, manual/protected). Admin NAS deploy job is intentionally **disabled**. `package-windows`/`package-macos` build the faster-whisper sidecar (`sidecar:setup` → `sidecar:build`) and run `scripts/ci/verify-sidecar-bundle.mjs` before electron-builder, so a release can never ship without the local STT engine. Every pipeline that runs `npm run build --workspace=@d3ro/desktop` (`.forgejo` CI/release/portable) then runs `scripts/ci/verify-desktop-renderer-bundles.mjs`, which fails packaging when a renderer page references an asset the build did not emit (GAP-INFRA-05).
 
 ### Forgejo Actions (`.forgejo/workflows/`)
-`ci.yml` — CI is now Forgejo-only (`.github/workflows` deleted 2026-09-26, Wave 3, dc43884). Jobs: `quality` (`version:check`, `contract:check`, `release:metadata:test`, migration checker self-test + actual filename/order/non-empty check, secret scan, mobile release/config/build-config self-tests, Play asset contract, lint, typecheck, Vitest), `build-validation` (desktop renderer verification + admin + web production builds), `mobile-quality`, `edge-functions` (Deno), `api-server-tests`. Web/admin typecheck runs Next 16 `typegen` before `tsc`, so a clean checkout generates and checks route/root-param declarations instead of relying on a prior dev/build artifact. The migration checks are file metadata/order gates only; Supabase replay, shadow DB, and remote drift remain separate runtime/integration gates. A separate isolated local run on 2026-11-04 applied all 73 migrations from empty and after reset, then returned an empty `pg-delta --strict-coverage` shadow diff; that runtime gate is not yet part of CI and says nothing about linked remote drift.
+`ci.yml` — CI is now Forgejo-only (`.github/workflows` deleted 2026-09-26, Wave 3, dc43884). Jobs: `quality` (`version:check`, `contract:check`, `release:metadata:test`, `release:installer:smoke:test`, migration checker self-test + actual 74-migration filename/order/non-empty check, secret scan, mobile release/config/build-config self-tests, Play asset contract, `test:hygiene[:test]`, `check:protected-tests[:test]`, `test:quality[:test]`, `check:i18n[:test]`, `check:ds-contract[:test]`, `test:affected:test`, `lint`, `lint:site`, `typecheck`, `typecheck:site`, Vitest across desktop/web/api-client/core/i18n/ui), `build-validation` (desktop renderer verification + admin + web + `site/` production builds), `mobile-quality`, `edge-functions` (Deno), `api-server-tests`. Web/admin typecheck runs Next 16 `typegen` before `tsc`, so a clean checkout generates and checks route/root-param declarations instead of relying on a prior dev/build artifact. The migration checks are file metadata/order gates only; Supabase replay, shadow DB, and remote drift remain separate runtime/integration gates. A separate isolated local run on 2026-11-04 applied all 73 prior migrations from empty and after reset, then returned an empty `pg-delta --strict-coverage` shadow diff; that runtime gate is not yet part of CI and says nothing about linked remote drift.
 
 `payple-renew.yml` — daily cron (+ manual dispatch) → `payple-renew` edge function; ported from the never-run `.github/workflows/payple-renew.yml` because the repository has no GitHub remote. Requires Forgejo secrets `SUPABASE_URL`, `CRON_SECRET`. 2026-09-26~10-11 `SUPABASE_URL` 시크릿이 로컬 주소(`127.0.0.1:55321`)라 한 번도 성공하지 못했다(GAP-OPS-03).
 
@@ -185,7 +191,7 @@ Stages `validate → test → build → e2e → package → publish → deploy`.
 `portable.yml` — 태그/수동 실행으로 **서명 없이** portable 채널(95MiB 7z 분할 볼륨 + Scoop 매니페스트 + 설치 스크립트)을 게시한다. `WIN_CSC_*` 불필요, updater feed는 건드리지 않는다.
 
 `deploy-site.yml` — 유일한 사이트 배포 경로(Linux, Cloudflare Pages). Windows 수동 중복 워크플로(`deploy-site-windows.yml`)는 2026-09-26 삭제됐다(dc43884). build `site`, write release identity, deploy to Cloudflare Pages `d3ro` (`d3ro.pages.dev`), verify live commit/version, app-links, legal URLs. 커스텀 도메인 `d3ro.chanpaca.net` 은 Pages 커스텀 도메인이 DNS CNAME을 요구하므로, DNS를 건드릴 수 없는 동안은 Workers 라우트 브리지 `server/cloudflare-site-bridge/`(`d3ro.chanpaca.net/*` → Pages 프록시, 수동 `npx wrangler deploy`)가 서빙한다. CNAME을 추가한 뒤 브리지를 삭제하면 Pages 커스텀 도메인으로 직접 서빙된다(GAP-REL-09b).
-`release.yml` — tag-triggered Windows build (signed) + `publish-forgejo-release.mjs` to the canonical Forgejo feed/release hub.
+`release.yml` — tag-triggered Windows build + `verify-desktop-installer-smoke.mjs` (PE64/blockmap/SHA-512/ASAR/feed smoke gate) + `publish-forgejo-release.mjs` to the canonical Forgejo feed/release hub.
 
 ---
 
@@ -208,7 +214,7 @@ Public endpoints (production): `https://d3ro.chanpaca.net` — **랜딩/다운
 ## 7. `server/supabase` (backend)
 
 - `config.toml` — project `d3ro-voice`, ports 55321-55324, DB major 17, Supabase CLI 3.x `[local_smtp]`, auth redirects (localhost, `d3ro.chanpaca.net`, `d3ro-voice://auth-callback`), providers Google/GitHub/Apple. `audio-purge` has an explicit function stanza with gateway JWT verification disabled because its handler verifies the exact pg_cron service credential. An isolated local stack proved missing/non-service key 401, service 200, and pg_cron/Vault/pg_net removal of the queue row, `audio_files` row, and Storage object; deployment and the production schedule remain unverified.
-- `migrations/` — **73 SQL migrations** (schema, RLS, auth triggers, storage, team invites, knowledge/pgvector, push outbox, Payple billing (legacy Stripe columns/provider values kept for history), admin roles, mobile platform/monetization, atomic command reorder, device revocation, content reporting, audit log, meeting documents, STT quota reservations, ad reward replay protection, team activity feed).
+- `migrations/` — **74 SQL migrations** (schema, RLS, auth triggers, storage, team invites, knowledge/pgvector, push outbox, Payple billing (legacy Stripe columns/provider values kept for history), admin roles, mobile platform/monetization, atomic command reorder, device revocation, content reporting, audit log, meeting documents, STT quota reservations, ad reward replay protection, team activity feed, cross-device sync parity & tombstones, and immutable `meeting_memos.revision` CAS `20261113000001`).
 - `functions/` — **24 Deno Edge Functions** (`stt-proxy`, `llm-proxy`, `content-report`, `generate-meeting-document`, `embed-chunks`, `search-knowledge`, `realtime-token`, `team-invite`, `team-accept`, `send-push`, `audio-purge`, `account-delete`, `admin-users`, `admin-subscriptions`, `admin-payments`, `admin-audit-log`, billing `billing-catalog`/`payple-checkout`/`payple-manage`/`payple-renew`/`payple-webhook`, `iap-verify`, `admob-ssv`, `google-play-rtdn`; Stripe functions removed 2026-09-26). Shared contracts in `functions/_shared/` — push transports now include `webpush.ts` (VAPID + RFC 8291) and `apns.ts` (.p8 token) alongside FCM. CI (`edge-functions`) runs `deno check` + `deno test` and also the Cloudflare worker drain test.
 - `tests/` — integration/E2E for content report, mobile platform/recording/reward-race, payments, mobile release preflight, push, team push security, STT quota.
 
@@ -223,7 +229,8 @@ Full detail: [`09-supabase-backend.md`](./09-supabase-backend.md).
 - **Deploy/release:** `deploy-nas.ps1/.sh`, `nas-control.sh`, `publish-gh.ps1`, `gen-keystore.js` (`deploy-site-to-nas.js` deleted 2026-09-26, Wave 3, cd9d199 — site deploy is Cloudflare Pages only).
 - **Android artifact verification (2026-11-01):** `verify-android-artifact.mjs` parses both legacy `Signer #1` and Build Tools 37 `V2/V3.x Signer` certificate output. Self-test and the actual universal E2E APK verification pass with Build Tools `37.0.0`.
 - **GCP/Google OAuth automation + inspection (~70 `*.mjs`):** `auto-configure-oauth`, `automate-google-oauth`, `setup-consent`, `create-*-client`, `check-*`, `inspect-*` — mostly one-off/browser-driven console automation.
-- **AdMob console automation:** `admob-probe.mjs` (read-only login/app/ad-unit probe), `admob-login.mjs` + `run-admob-login.bat` (one interactive headful Chrome login into a persistent profile), `admob-automate.mjs` (dry-run by default; `--apply` creates/verifies banner+rewarded units and reports Play-store link). Uses `playwright` with `channel: 'chrome'` and the gitignored `.chrome-playwright-profile`.
+- **AdMob console automation:** `admob-probe.mjs` (read-only login/app/ad-unit probe), `admob-login.mjs` (one interactive headful Chrome login into a persistent profile), `admob-automate.mjs` (dry-run by default; `--apply` creates/verifies banner+rewarded units and reports Play-store link). Uses `playwright` with `channel: 'chrome'` and the gitignored `.chrome-playwright-profile`.
+- **Clean-up:** `scripts/ci/clean-deep.mjs` (`npm run clean:deep`, `--dry-run`) strips monorepo `out`/`dist`/`.next`/`bin`/`obj`/Android `build`/`.maestro-output`, temp `.chrome-*`/`.playwright-*` profiles, and any dangling `apps/mobile-rn/node_modules/d3ro-voice-monorepo` reparse point. The untracked `scripts/local/` dump directory (109 one-off probe scripts) and 16 unreferenced loose root scripts were deleted on 2026-11-13.
 - **E2E / verification:** `test-and-capture-all-10-ad-services.js`, `verify-live-production-d3ro.js`. The old ad-hoc `e2e-desktop-*.js` / `real-app-multi-tab-e2e.js` / `run_e2e_*.cjs` runners were deleted 2026-11-04 (machine-specific paths, no references); Playwright specs under `apps/desktop/tests/e2e` are the E2E path.
 - **Screenshots/captures:** `capture-*.js`.
 - **Forgejo ops:** `check-forgejo-actions-runs.js`, `capture-forgejo-*.js`.
@@ -236,11 +243,11 @@ Full detail: [`09-supabase-backend.md`](./09-supabase-backend.md).
 
 | File | Purpose |
 |---|---|
-| `release/product-version.json` | version `1.16.1`, `androidVersionCode`/`iosBuildNumber` `1160100`, releaseDate `2026-11-04`, desktop license keyId |
+| `release/product-version.json` | version `1.16.5`, `androidVersionCode`/`iosBuildNumber` `1160500`, desktop license keyId |
 | `release/android-release-identity.json` | package `com.d3ro.voice`, Play app ID, app-signing SHA-256, upload cert SHA-256, evidence keyId, AdMob unit IDs |
 | `release/desktop-license-public.pem` | Ed25519 public key for desktop offline licenses |
 | `release/mobile-release-evidence-public.pem` | Ed25519 public key for mobile release evidence |
-| `apps/desktop/electron-builder.yml` | appId `com.d3ro.voice`, NSIS x64 (forced code signing), macOS DMG/ZIP arm64, generic Forgejo publish feed, asarUnpack native modules + `@ffmpeg-installer`, extraResources (icons, sounds, sox, **sidecar**, ffmpeg, ollama) |
+| `apps/desktop/electron-builder.yml` | appId `com.d3ro.voice`, NSIS x64 (forced code signing), macOS DMG/ZIP arm64, generic Forgejo publish feed, asarUnpack native modules (`better-sqlite3`, `uiohook-napi`, `koffi`, `@koromix`, `@ffmpeg-installer`; `@nut-tree-fork` unpacked on macOS only), extraResources (icons, sounds, filtered `sox.exe`+`zlib1.dll`+`LICENSE.GPL.txt`, **sidecar**, ffmpeg, ollama) |
 | `apps/desktop/src/main/update-feed.ts` | Auto-update feed SSOT (canonical Forgejo + legacy GitLab mirror, channels) |
 | `release/update-policy.json` | Update policy SSOT (channels, minimum supported version, forced update, delta/full, staged rollout, kill switch) |
 | `site/src/release.ts` | Download-center desktop release contract (installer filename + release date); version and date are kept on the SSOT by `npm run version:sync` (drifted to 1.2.0 once — GAP-REL-08). `apps/web/src/lib/desktop-release.ts` and the `apps/web` download/releases pages were deleted 2026-09-26 (Wave 3, cd9d199) — `site/` is the only download surface, and `/download`/`/releases` on `apps/web` now redirect to it |
@@ -253,18 +260,22 @@ Version sync is enforced by `scripts/ci/sync-version.mjs` and `verify-release-me
 
 ## 10. Resources & tests
 
-- `resources/sox/` — bundled Windows SoX (`sox.exe` + DLLs) for audio capture.
+- `apps/desktop/resources/sox/` — canonical bundled Windows SoX (`sox.exe`, `zlib1.dll`, `LICENSE.GPL.txt`; PE-verified, unused `wget.exe`/`pthreadgc2.dll`/PDFs and duplicate root `resources/sox/` removed 2026-11-13) for audio capture.
 - `resources/ffmpeg/` — optional bundled ffmpeg (CI or manual); `getFfmpegPath()` also resolves the `@ffmpeg-installer/ffmpeg` binary from `app.asar.unpacked`.
 - `apps/desktop/sidecar-dist/` — PyInstaller sidecar bundle consumed by `extraResources` (gitignored; built by `npm --prefix apps/desktop run sidecar:build`).
 - `resources/icons/` — empty; electron-builder falls back to `build/icon.ico|png`.
 - Desktop tests: `apps/desktop/tests/` — `unit/`, `main/`, `red/`, `shared/`, `integration/`, `eval/` run under Vitest; `e2e/` holds Playwright specs plus the shared `e2e/support/electron-app.ts` fixture (per-test temp user-data dir). Artifacts in `apps/desktop/test-results/`.
 - Test taxonomy + hygiene gate: `docs/tdd-red/06-repo-application.md`. `npm run test:hygiene` (+ `:test`) rejects `.only`, reason-less `.skip()`, trivial assertions, `isVisible()`-gated assertions, machine-specific paths, `waitForTimeout`, and `.e2e.test.ts` names; wired into CI `quality`.
-- Test-system gates (TDD 2.0 Phase 0-1, 2026-11-08):
-  - `npm run test:metrics` / `test:metrics:write` — suite/file/case/assertion counts plus weak-assertion and ambient-time totals; writes `docs/tdd-red/metrics/.md`. Metric only, never fails.
+- Test-system gates (TDD 2.0 Phases 0–5, 2026-11-08..13):
+  - `npm run test:metrics` / `test:metrics:write` — suite/file/case/assertion counts across all 10 suites (incl. `@d3ro/i18n` and `@d3ro/ui`) plus weak-assertion and ambient-time totals; writes `docs/tdd-red/metrics/.md`. Metric only, never fails.
   - `npm run check:protected-tests` (+ `:test`) — `scripts/ci/check-protected-tests.mjs` diffs the six protected acceptance specs (`06 §5`) against a base revision and fails when tests, assertions, or `.only`/`.skip` change without an `allow-protected-change:` commit marker. CI runs it against `HEAD^` (the quality job fetches depth 2).
-  - `npm run test:quality` (+ `:test`, `:update`) — ratchet over `scripts/ci/test-quality-baseline.json`: per-file weak-assertion and ambient-time counts may only go down. `--update` is a reviewed action.
-  - Shared file-detection helpers live in `scripts/ci/lib/test-files.mjs` so all three gates see the same test files.
-- Mobile tests: `apps/mobile-rn/__tests__/` (57 suites / 353 tests per mobile SSOT), `.maestro/` + `.maestro-output/` E2E evidence. Note: a full parallel Jest run can hit the 5s render timeout on slow machines; re-run the failing spec in isolation before treating it as a regression.
+  - `npm run test:quality` (+ `:test`, `:update`) — ratchet over `scripts/ci/test-quality-baseline.json`: per-file weak-assertion and ambient-time counts may only go down (scans both tracked and untracked working-tree test files). `--update` is a reviewed action.
+  - `npm run check:i18n` (+ `:test`) — `scripts/ci/check-i18n-contract.mjs` verifies 12-locale 2,500-key set equality, non-empty strings, `{{placeholder}}` parity, literal `t('...')` key existence, and unreferenced-key budget (`<=35`).
+  - `npm run check:ds-contract` (+ `:test`) — `scripts/ci/check-ds-contract.mjs` verifies `@d3ro/ui` DS component exports, zero raw hex outside `theme.ts`/`theme-raw.ts`, required ARIA roles (`SegmentControl` `tablist`/`tab`), and DS contract test references.
+  - `npm run test:affected` (+ `:test`) — `scripts/ci/run-affected-tests.mjs` maps git diffs to targeted Vitest/Jest/Deno/.NET test commands and safely falls back to the full suite on unmapped paths (CI continues to run full suites).
+  - `npm run release:installer:smoke` (+ `:test`) — `scripts/ci/verify-desktop-installer-smoke.mjs` validates NSIS `.exe` PE64 headers, gzip `.blockmap` magic, `latest.yml` SHA-512 & byte size, `win-unpacked` `D3RO Voice.exe` PE64, `resources/app-update.yml` feed URL, `resources/app.asar` Chromium Pickle JSON header, and optional Ed25519 `.sig` manifest signature inside `release-desktop.mjs` and `.forgejo/workflows/release.yml`.
+  - Shared file-detection helpers live in `scripts/ci/lib/test-files.mjs` so `test:metrics` and `test:quality` inspect the exact same test files.
+- Mobile tests: `apps/mobile-rn/__tests__/` (89 suites / 605 tests PASS on 2026-11-13), `.maestro/` + `.maestro-output/` E2E evidence. Note: a full parallel Jest run can hit the 5s render timeout on slow machines; `test:mobile` uses `--runInBand`.
 - Web tests: `apps/web/tests/` (vitest pure-logic contracts: billing catalog, Web Push client, web STT client — now part of root `npm test`) and `apps/web/e2e/` (playwright: `smoke.spec.ts` owns the unauthenticated surface contract; billing/payple/dashboard/history are fixture-based browser journeys). Web declares its own `@playwright/test` + `vitest` devDeps (2026-11-04) instead of relying on the desktop workspace's hoisted copies.
 - API tests: `apps/api-server.Tests/` (xUnit).
 - Root: `test-results/.last-run.json` (no root-level e2e suite).
diff --git a/docs/map/03-shared-packages.md b/docs/map/03-shared-packages.md
index e216e60..5a6cfbf 100644
--- a/docs/map/03-shared-packages.md
+++ b/docs/map/03-shared-packages.md
@@ -22,8 +22,13 @@ The canonical place for types and cross-surface logic. Both desktop and web/mobi
 | Dictation cleaner | `./dictation-cleaner` | **SSOT** for deterministic zero-latency speech disfluency & dictation cleanup (`cleanDictatedText`, added 2026-10-29): strips standalone spoken fillers (`어`, `음`, `그 쓸데없는` while preserving quoted mentions like `어라든가`, `아라든가` and demonstratives), mid-sentence self-corrections (`X 아니 X이 아니라 Y` → `Y`), word stutters (`내가 내가` → `내가`), colloquial suffixes (`예를 들자면은` → `예를 들어`, `보면은` → `보면`), redundant expressions (`쓸데없는 의미없는` → `불필요한`), and clear contextual STT homophones (`스시가 영어로 변경되지` → `PC가 영어로 변경되지`, `그 길을 쓸 이유가` → `그 기능을 쓸 이유가`) while preserving speaker register. |
 | Personal graph & n-gram | `./personal-graph`, `./personal-ngram` | **SSOT** for relational personalization and n-gram continuation (upgraded 2026-10-28): exact & particle-invariant stemmed continuations (`continuationsFrom`/`stemContinuationsFrom`), IDF-weighted related node scoring (`scoreRelatedNodes`), 2-hop graph path ranking (`rankTwoHopGraphTargets` across `shares_terms→follows` and `follows→follows`), personalized candidate reranking (`scoreCandidatePersonalization`), and frequency-weighted n-gram indexing with Korean stemmed-word bigram fallback (`PersonalNgramModel`). |
 | Constants | `./constants` | Shared constants |
+| Guards, CSV & formatters | `./guards`, `./csv`, `./format` | Cross-surface predicate & codec SSOT (2026-11-13, Wave 5 `W5-05`): `isRecord`, `isNonEmptyString`, `isUuid`, `escapeLikePattern`; RFC 4180 `csvCell` / `parseCsvRows`; `formatDurationSec` / `formatDurationMs` / `formatClockTimestampMs` |
+| Unified search helpers | `./unified-search` | Cross-surface unified search normalization, snippet extraction (`buildSearchSnippet`), and newest-first ranker (`sortUnifiedSearchResults`) shared by desktop `UnifiedSearchService` and mobile `unified-search-service` (2026-11-13, `W5-06`) |
+| Admin role hierarchy | `./admin-roles` | `ADMIN_ROLE_RANK`, `hasMinimumAdminRole`, `canManageTargetRole` shared across `apps/admin` and Supabase `_shared/admin-auth.ts` via `core-contract.generated.ts` (2026-11-13, `W5-07`) |
+| Meeting transcript & speakers | `./meeting-transcript` | Timestamped/speaker segment parser & serializer (`toTranscriptSegments`, `parseSegmentText`), `formatPyannoteSpeakerLabel` (`SPEAKER_00` → `화자 1`), `resolveSpeakerColorIndex`, and `extractDistinctSpeakers` (2026-11-13, `GAP-MTG-02`) |
+| Determinism ports | `./ports` | Injectable `Clock`, `FakeClock` (`createFakeClock`), `Random`, `systemClock`, `systemRandom`, and `createSeededRandom` (Mulberry32) for deterministic tests (2026-11-13, TDD v2.0 Phase 4) |
 | Crypto license | `./utils/crypto-license` | Ed25519 license sign/verify (used by admin issuer + desktop verifier) |
-| PII | `pii-redactor`, `secure-memory` | Redaction + secure memory helpers |
+| PII & ZDR | `pii-redactor`, `secure-memory` | `redactPII`/`redactPIIMessages`/`rehydrateText` (wired into `OnlineLLMService` and `support-handlers`) + `secureZeroBuffer`/`secureWipeAudioChunks` (wired into `VoiceModeService` and `AudioCaptureService`, 2026-11-13 `W5-01`) |
 | Supabase config | `supabase-config` | Shared Supabase config shape |
 | Entitlement | `./entitlement` | `EntitlementTier`, `AdminRole`, `EntitlementSnapshot`, `resolveEntitlement`, `normalizeEntitlementTier`/`normalizeAdminRole` — canonical tier/role contract across Supabase, desktop license, and .NET |
 | Plan catalog | `./plan-catalog` | Tier/price/quota SSOT. `knowledge_embedding` is explicit per tier (Free 5,000/week; Pro 50,000/day; Pro+ 150,000/day; Team 300,000/day; Enterprise unlimited), generated into `server/supabase/functions/_shared/core-contract.generated.ts`, and guarded by `contract:check` |
@@ -40,7 +45,7 @@ The canonical place for types and cross-surface logic. Both desktop and web/mobi
 | `.` | Barrel |
 | `./theme` | `theme.ts` — `d3roPalette`, `d3roTypo` (13 steps), `d3roShadow` (10), `d3roRadius` (7); 6 themes (dark/Midnight, light, nord, solarized, catppuccin, dracula) + build helpers |
 | `./theme-vars` | CSS variable map for popups/vanilla surfaces |
-| `./components/ds` | MUI/Emotion DS components: CrtDisplay, InstrumentPanel, Led, PhysicalButton, MetalCard, PhosphorText (13 variants), MetalDial, ScreenPanel, ButtonGroup, TiltCard, GradientWave, StatRing |
+| `./components/ds` | MUI/Emotion DS components: CrtDisplay, InstrumentPanel, Led, PhysicalButton, MetalCard, PhosphorText (13 variants), MetalDial, ScreenPanel, SegmentControl (ARIA `tablist`/`tab` + roving `tabIndex` + keyboard `Enter`/`Space`), ButtonGroup, TiltCard, GradientWave, StatRing. Verified by `packages/ui/__tests__/ds-contract.test.tsx` and `npm run check:ds-contract` |
 
 Peers: React 19, MUI 7, Emotion 11. Depends on `@d3ro/core`.
 
@@ -54,6 +59,7 @@ Peers: React 19, MUI 7, Emotion 11. Depends on `@d3ro/core`.
 |---|
 | `NativeThemeProvider` / `useNativePalette`; dark/light/get-palette, raw/status, typo/radius/fonts/space/control/weight/motion/numeral tokens. The v4 semantic colors mirror `packages/ui/src/theme-raw.ts`; `d3roNativeControl.h` is the 48dp control floor |
 | Components: `MetalCard`, `PhosphorText`, `Led`, `PhysicalButton`, `ScreenPanel`, `WaveBars`, `FilterChip` |
+| Responsive layout (`./responsive`, 2026-11-13 `GAP-UX-08`): `resolveResponsiveLayout` (`>=600dp` tablet/unfolded foldable vs `<600dp` phone, `contentMaxWidth: 880`, `formMaxWidth: 520`, `gridColumns: 2`, `adaptiveBannerHeight: 90`), `useResponsiveLayout`, `useContentWidth`, `` |
 
 Peers: `react`, `react-native`. Consumed by `apps/mobile-rn` via file: workspace dependencies.
 App-specific `ScreenHeader`, `RecordFab`, and `UnifiedSearchResultRow` stay under `apps/mobile-rn/src/components`; they are not shared package exports.
@@ -64,7 +70,8 @@ App-specific `ScreenHeader`, `RecordFab`, and `UnifiedSearchResultRow` stay unde
 
 | Provides | Notes |
 |---|---|
-| 12 locales | `ko` (master), `en`, `ja`, `zh`, `zh-TW`, `es`, `fr`, `de`, `pt`, `ru`, `vi`, `th` in `src/locales/`; 2,742 parity-checked keys, including the 16 native `update.dialog.*` keys |
+| 12 locales | `ko` (master), `en`, `ja`, `zh`, `zh-TW`, `es`, `fr`, `de`, `pt`, `ru`, `vi`, `th` in `src/locales/`; 2,500 parity-checked keys (253 unreferenced keys pruned on 2026-11-13), guarded by `npm run check:i18n` and `__tests__/locale-contract.test.ts` (15/15 PASS) |
+| Multi-entry architecture (2026-11-13) | `src/shared.ts` (zero-React/zero-JSON types & `Intl` formatters), `src/index.tsx` (`@d3ro/i18n` — web/desktop renderer entry: `ko`+`en` eager, 10 secondary locales loaded on demand via literal dynamic `import('./locales/.json')`), `src/main.ts` (`@d3ro/i18n/main` — zero-React Node/Electron main entry reading only the active `locales/.json` synchronously from disk with per-locale cache), and `src/index.native.tsx` (React Native Metro `.native.tsx` entry supporting all 12 locales with Metro `inlineRequires: true` lazy evaluation on `switch` branch entry) |
 | Type-safe keys | `TranslationKey` derived from `ko.json` |
 | React context | `I18nProvider`, `useI18n`, `TFunction` |
 | Fallback chain | locale → `en` → `ko` → key |
@@ -87,7 +94,7 @@ Electron-independent. Rule: no hardcoded Korean/English strings in UI; use `t()`
 | `transcribe` | STT calls |
 | `supabase-browser` | Browser client (`getSupabaseBrowserClient`, `isSupabaseConfigured`) |
 | `supabase-server` | Server client (`createSupabaseServerClient`) |
-| `types` | Shared DB/domain types — **canonical; do not redefine table types per app**. Includes `PushProvider`, device-bound `PushToken`, `push_tokens` row/insert/update shapes, `register_push_registration`/`unregister_push_registration`, and period-aware `consume_quota` RPC contracts |
+| `types` | Shared DB/domain types — **canonical; do not redefine table types per app**. Includes `PushProvider`, device-bound `PushToken`, `push_tokens` row/insert/update shapes, `register_push_registration`/`unregister_push_registration`, period-aware `consume_quota` RPC contracts, and immutable `meeting_memos.revision` CAS shape (`20261113000001`) |
 
 Deps: `@supabase/supabase-js`; optional peer `@supabase/ssr`. The unused `@d3ro/core` dependency was removed in Wave 4. Tests: `__tests__/` (client, transcribe, types) via vitest.
 
@@ -113,3 +120,11 @@ Apps depend on packages, never the reverse. Shared package changes ripple to all
 
 - `apps/mobile-rn` is not an npm workspace member, so root `typecheck`/`test` skip it; use `typecheck:mobile`/`lint:mobile`/`test:mobile` from the repo root.
 - No versioned publishing of packages (private, source-only); all consumers are in-repo.
+
+---
+
+## 8. Wave 6 hardening (2026-11-14)
+
+- **`@d3ro/core` (Vitest 39 files / 626 tests PASS):** `utils/pii-redactor.ts` hardens placeholder collision avoidance, stateful regex index resets, and length-sorted single-pass `rehydrateText`; `csv.ts` adds UTF-8 BOM and `\r` line-ending escaping; `unified-search.ts`, `utils/meeting-markdown.ts`, and `meeting-transcript.ts` (reusing `formatDurationClockFromMs` and finite date guards) harden boundary inputs (`pii-redactor.test.ts` 5, `shared-utilities.test.ts` 10). Deno-synced contracts (`plan-catalog`, `web-urls`, `guards`, `admin-roles`) untouched (`contract:check` GREEN).
+- **`@d3ro/i18n` (Vitest 2 files / 25 tests PASS):** extracted `src/shared.ts` (`I18nStorage`, `noopI18nStorage`, `safeLoadStoredLocale`, `safeSaveStoredLocale`, non-finite date guard) shared by `index.tsx` and `index.native.tsx`, with `cancelled`, `userChangedLocaleRef`, and `localeRevisionRef` guards blocking stale async storage loads from overwriting explicit `setLocale()` changes (`__tests__/i18n-provider.test.tsx` 10).
+- **`@d3ro/ui` & `@d3ro/ui-native` & `@d3ro/api-client`:** `@d3ro/ui` extracted `src/components/ds/wave-math.ts` and cached canvas `LinearGradient` instances in `AudioVisualizerBar.tsx` and `GradientWave.tsx` (`__tests__/wave-visualizer.test.tsx` 3, Vitest 2 files / 7 tests PASS); `@d3ro/ui-native` extracted `resolveContentMaxWidth` (`responsive.tsx`) and guarded non-finite bars (`WaveBars.tsx`); `@d3ro/api-client/src/transcribe.ts` clamped negative latencies (Vitest 4 files / 31 tests PASS).
diff --git a/docs/map/04-desktop-app.md b/docs/map/04-desktop-app.md
index fdd7a64..abb3f76 100644
--- a/docs/map/04-desktop-app.md
+++ b/docs/map/04-desktop-app.md
@@ -16,7 +16,7 @@
 
 **Main entry** `src/main/index.ts`: sets app name/AppUserModelId, disables GPU acceleration, EPIPE/uncaught handlers, registers `d3ro-voice://` deep-link protocol (Supabase OAuth implicit + PKCE), single-instance lock, then `bootstrap()` + `setupLifecycle()`. The explicit manual-QA argument `--preview-update-dialogs` is isolated before protocol registration/bootstrap: it bypasses the single-instance lock, invokes the real update-dialog prompter for four consent/restart variants, touches no feed/download/install/settings state, then quits. This path is unit-tested, but its packaged native dialogs still require an external-terminal visual run.
 
-**Bootstrap** `src/main/bootstrap.ts`: ordered `BootstrapStep[]` — logger, config, **database (critical)**, license, create-windows (critical), tray, **ipc-handlers (critical)**, custom-instructions, voice-commands, sound-effects, auto-launch, popup-preload, key-bindings, voice-mode, stt-warmup, llm-polling, meeting-summary-wiring, meeting-mode, cloud-sync, auto-update. Wires VoiceMode events to sound + history persistence, and subscribes to `KeyBindingService` `triggered` for the `history-popup` / `command-popup` actions (`bootstrap.ts:159`) — those two were hardcoded accelerators before and are now rebindable like everything else.
+**Bootstrap** `src/main/bootstrap.ts`: ordered `BootstrapStep[]` — logger, config, **database (critical)**, license, create-windows (critical), tray, **ipc-handlers (critical)**, custom-instructions, voice-commands, sound-effects, auto-launch, popup-preload (no-op at boot since 2026-11-13; popups are created lazily on first demand), key-bindings, voice-mode, stt-warmup (only when `sttProvider === 'local'`), llm-polling, meeting-summary-wiring, meeting-mode, cloud-sync, auto-update. Wires VoiceMode events to sound + history persistence, and subscribes to `KeyBindingService` `triggered` for the `history-popup` / `command-popup` actions (`bootstrap.ts:159`) — those two were hardcoded accelerators before and are now rebindable like everything else. `ConfigEffects` also propagates `inputTelemetryEnabled` / `inputTelemetryPaused` dynamically to `InputTelemetryService.applyConfig`.
 
 ---
 
@@ -27,11 +27,11 @@ Singleton + `EventEmitter` pattern (`getXService()` accessors).
 ### Core voice pipeline
 | Service | Purpose |
 |---|---|
-| `VoiceModeService` | Orchestrator: 9-state `RecognitionState` + 4-state `AudioState`, dual-condition flush, action queue. Events: session-started/completed/cancelled, transcription-update, audio-level, recognition/audio-state-changed, premium-llm-fallback, error |
-| `AudioCaptureService` | Mic PCM16 16kHz mono (bundled SoX on Windows, node-record-lpcm16 elsewhere). Spawns hidden (`windowsHide`); a missing SoX fails with the exact fix command |
-| `LocalSTTService` | faster-whisper Python sidecar manager (state machine, dual-flush, model download/cancel, background warm-up, live partial transcription). Connects over IPv4 loopback (`getSidecarBaseUrl`) and fails fast with an actionable message when the bundled engine or virtualenv is missing |
+| `VoiceModeService` | Orchestrator: 9-state `RecognitionState` + 4-state `AudioState`, dual-condition flush, action queue, and secure audio buffer zeroing (`secureWipeAudioChunks` / `secureZeroBuffer`) on cancel/cleanup (2026-11-13 `W5-01`). Events: session-started/completed/cancelled, transcription-update, audio-level, recognition/audio-state-changed, premium-llm-fallback, error |
+| `AudioCaptureService` | Mic PCM16 16kHz mono (bundled SoX on Windows, node-record-lpcm16 elsewhere) with `secureWipeAudioChunks` on stop/dispose. Spawns hidden (`windowsHide`); a missing SoX fails with the exact fix command |
+| `LocalSTTService` | faster-whisper Python sidecar manager (state machine, dual-flush, model download/cancel, background warm-up, live partial transcription, `sidecarBaseUrl` getter for `POST /diarize`, and **2026-11-13** `releasePrimaryModel()` / 15-min `IDLE_MODEL_UNLOAD_MS` timer via `POST /unload` `{ slot: "primary" }` so switching to cloud STT or going idle frees the 1.6–3.1 GB Whisper model while keeping the sidecar HTTP server alive for `/uia/focus`). Connects over IPv4 loopback (`getSidecarBaseUrl`) and fails fast with an actionable message when the bundled engine or virtualenv is missing |
 | `KeyBindingService` | uiohook-napi global hooking for **keyboard and mouse**, driven by the `@d3ro/core/keybinding` contract: 6 rebindable actions (dictation, hands-free, command, caption, history-popup, command-popup), several bindings per action, structural reserved-combo checks. Events: `triggered` (in-process payload carries `actionId`, `type` (`pressed`/`released`), `isDoublePress`, `holdMode`, `timestamp`; the renderer-facing `keybinding:triggered` event is the narrower `KeyBindingTriggeredEvent`, `keybinding.ts:1092`), `changed`, `error`. `globalShortcut` is used only to mute the macOS system beep, and only for accelerators it registered itself. Mouse events cannot be suppressed by uiohook, so a bound button also performs its native action |
-| `TextInsertService` | Clipboard save→set→Ctrl+V→restore via nut-js |
+| `TextInsertService` | Clipboard save→set→Ctrl+V→restore (`NutKeyboardPort`: uses native `koffi` Win32 `SendInput` via `utils/win32-unicode-input.ts` on Windows without loading `@nut-tree-fork/nut-js`; `nut-js` used on macOS/Linux) |
 | `SoundEffectService` | Preloaded WAV feedback (start/stop/error/cancel/chime) |
 
 ### STT engine layer (`services/stt/`)
@@ -47,21 +47,21 @@ Singleton + `EventEmitter` pattern (`getXService()` accessors).
 |---|---|
 | `LocalLLMService` | Ollama REST (models, pull w/ progress, server start, NDJSON streaming). The 2026-09-22 runaway guard gives each request its own `AbortController` (external caller signals are relayed and detached on completion), requires `done` before an NDJSON stream succeeds, and clears incomplete streams. Generation/stream requests are bounded to 2048 tokens / 120 s; chat is bounded to 512 / 60 s. Ollama server spawn and polling are deduplicated, and lifecycle dispose terminates owned work. |
 | `PremiumLLMService` | Claude via Supabase `llm-proxy`, local fallback |
-| `OnlineLLMService` | JWT-authenticated .NET backend client |
+| `OnlineLLMService` | JWT-authenticated .NET backend client; **2026-11-13 (`W5-01`):** applies reversible `redactPII` / `redactPIIMessages` before cloud dispatch and `rehydrateText` on completion (`pii-zdr-wiring.test.ts` 3/3 PASS) |
 | `llm-prompts.ts` | **SSOT for prompt resolution, placeholder substitution, and argument placement.** `resolveSystemPrompt` (`:118`) maps an `LLMAction` to its base prompt and handles `custom` explicitly instead of dropping silently to `refine`. `renderInstructionPrompt` (`:78`) substitutes `{{text}}` / `{{userPrompt}}` / `{{targetLanguage}}` and **warns by name** for any placeholder left standing rather than letting it reach the model. `buildInstructionInvocation` (`:101`) decides where an instruction goes in `processText(text, action, targetLanguage, customPrompt)`: the instruction becomes the **system prompt** and the transcript the **text**, except for instructions that spell out `{{text}}`, which keep the old meaning for backward compatibility. `resolveTargetLanguage` (`:50`) is the one place translate targets are decided (still `English`, see `11` GAP-LLM-01). **All three LLM entry paths call the same functions** — `VoiceModeService` (`:838`), `ChainService` (`:196`), and the `LLM.PROCESS` IPC handler (`llm-handlers.ts:96`) — so no caller re-implements the rules |
 
 ### Memory & knowledge
 | Service | Purpose |
 |---|---|
 | `HistoryService` | SQLite history CRUD/search/stats |
-| `UnifiedSearchService` | Read-only SQLite search across history title/content and meeting title/transcript; merges newest-first results without changing either schema |
+| `UnifiedSearchService` | Read-only SQLite search across history title/content and meeting title/transcript/memos; **2026-11-13:** uses FTS5 `tokenize = 'trigram'` virtual tables (`history_fts`, `meeting_sessions_fts`, `meeting_memos_fts`) for queries of ≥3 characters with automatic trigger sync and `<3`-char `LIKE` fallback |
 | `DictionaryService` | Custom vocabulary CRUD/search + cloud sync hooks + JSON/CSV import/export (`dictionary:import`/`export`, save/open dialogs) |
 | `MemoService` | Memo tags over history (`memo_tags`) |
-| `RAGService` | Local RAG: `nomic-embed-text` embeddings, cosine search over `rag_chunks` |
+| `RAGService` | Local RAG: `nomic-embed-text` embeddings, cosine search over `rag_chunks` (**2026-11-13:** `SqliteChunkStore` persists binary `Float32Array` `embedding_blob` alongside JSON fallback, caches `StoredChunk[]` in a DB-scoped `WeakMap` for zero-`JSON.parse` queries, and wraps `removeDocument` in a transaction) |
 | `CustomInstructionService` | User LLM commands (5 built-ins) |
 | `VoiceCommandService` | Keyword → command rule matching |
 | `ChainService` | Multi-step LLM pipelines (LLMChain). Each step resolves its instruction through `llm-prompts.ts` (`ChainService.ts:196`); before that, chain steps sent placeholders through unsubstituted |
-| `ScreenContextService` | Active-window + selected-text context |
+| `ScreenContextService` | Active-window + selected-text context (on Windows uses `sendWin32CopyChord()` via `koffi` `SendInput` without loading `nut-js`) |
 
 ### Phase 10+ features
 | Service | Purpose |
@@ -78,7 +78,7 @@ Singleton + `EventEmitter` pattern (`getXService()` accessors).
 ### Phase 12–15
 | Service | Purpose |
 |---|---|
-| `MeetingModeService` | Meeting recording and existing-media import: live/file transcript, normalized meeting audio, timestamp memos, doc generation/export, diarization. `meeting/imported-recording.ts` maps file-transcription segments to the canonical meeting transcript. Account revision checks before/after WAV copy and after transcription reject even A→B→A changes; unsuccessful imports remove only their own generated audio. Since 2026-11-05 refined caption lines reach the meeting transcript (`meetingMode:segmentUpdated`) instead of the raw text, and auto-polish receives the learned-vocabulary block |
+| `MeetingModeService` | Meeting recording and existing-media import: live/file transcript, normalized meeting audio (`meeting/disk-wav-audio-sink.ts` `DiskWavAudioSink` streams PCM16 directly to disk with `O(1)` memory and backpatches the 44-byte RIFF/WAV header on `finalize()`, 2026-11-13 `GAP-PERF-01`), timestamp memos (`meeting_memos.revision` CAS synced), doc generation/export, and speaker diarization (`diarizeSession` calls sidecar `POST /diarize` via `LocalSTTService.sidecarBaseUrl` — pyannote.audio when installed + energy-VAD acoustic turn segmentation — and falls back to LLM speaker estimation while preserving `[화자 N]` markers across `polishTranscript`, `GAP-MTG-02`). `meeting/imported-recording.ts` maps file-transcription segments to the canonical meeting transcript. Account revision checks before/after WAV copy and after transcription reject even A→B→A changes; unsuccessful imports remove only their own generated audio. Since 2026-11-05 refined caption lines reach the meeting transcript (`meetingMode:segmentUpdated`) instead of the raw text, and auto-polish receives the learned-vocabulary block |
 | `MeetingDocTemplateService` | Meeting-doc templates (built-ins + CRUD) |
 
 ### Input intelligence (2026-09-21; Local Flow Intelligence extension 2026-09-22)
@@ -92,7 +92,7 @@ Singleton + `EventEmitter` pattern (`getXService()` accessors).
 | `utils/win32-foreground.ts` | Foreground window title/pid/exe/bounds and active thread Korean IME state (`isForegroundKoreanIme` via `GetGUIThreadInfo` + `ImmGetDefaultIMEWnd` + `SendMessageTimeoutW(WM_IME_CONTROL)`) via `koffi` FFI into user32/kernel32/imm32 (chosen over `get-windows`, which needs an install script this repo does not run). |
 | `sidecar/uia_bridge.py` | Windows UIA snapshot (`uiautomation` 2.0.29, comtypes) on a dedicated COM-initialised thread with a 1.5 s budget; never walks the UIA tree (Chrome/VS Code tree walks take 10-30 s). Uses `GetVisibleRanges()` / tail slicing `[-MAX_TEXT_CHARS:]` for large terminal scrollback buffers and `ExpandToEnclosingUnit(..., waitTime=0)` to avoid `uiautomation.py`'s default 500 ms sleep on Windows Terminal. Warm calls measure 0-15 ms. |
 
-**2026-10-31 구조 경계:** `suggestion/SuggestionModelRequest.ts`가 prefill/지시형 모델 요청 구성, 후보 파싱, 지어낸 사실·문맥 복사 검증을 소유한다. `suggestion/FirstCandidateRunner.ts`는 첫 후보의 최대 2회 요청, 빈 prefill·사실 검증 재시도와 내용을 노출하지 않는 진단 로그를 담당한다. `_handleGenerationFailure`는 오류·시간 초과·빈 후보의 개인 후보 유지 → 로컬 기억 폭백 → 실패 종료 순서를 한 곳에서 보장한다. `_startGenerationSession`은 취소기·세대 토큰·타임아웃을 포함한 `GenerationSession`을 반환하고, `_prepareFirstCandidate`는 기억 수집·오타 교정·모델 요청과 첫 응답을 `FirstCandidatePreparation`으로 반환하며 실패 시에도 폭백용 기억 문맥을 보존한다. `_isGenerationResultCurrent`는 세대 불일치·문맥 경과·접두 변경을 순서대로 검사하고, `_publishFirstCandidate`는 개인 후보 병합·성공 기록·후속 채우기 시작을 담당하고, `_appendFilledCandidate`는 후속 후보의 추가·개인화 재정렬·표시·세션 행 후보 수 갱신을 한 곳에서 처리한다. `SuggestionService`는 입력 정책, 세대/취소, 표시, 수락만 조율한다. 모델 요청과 로컬 기억 게시는 각각 `SuggestionModelRequestInput`·`LocalMemoryPublication` 객체를 사용하며, 동작 변경 없는 순수 리팩토링이다.
+**2026-10-31..11-13 구조 경계:** `suggestion/SuggestionModelRequest.ts`가 prefill/지시형 모델 요청 구성, 후보 파싱, 지어낸 사실·문맥 복사 검증을 소유한다. `suggestion/FirstCandidateRunner.ts`는 첫 후보의 최대 2회 요청, 빈 prefill·사실 검증 재시도와 내용을 노출하지 않는 진단 로그를 담당한다. `suggestion/suggestion-policy-helpers.ts`(2026-11-13 `W5-11`/`G7`)는 오타 교정 문맥 적용(`applyCorrectionToContext`), 중복 판정(`sameCandidateText`/`isDuplicateCandidateText`), 개인화 후보 재정렬(`rerankFilledCandidates`), 정책 정규화(`normalizeSuggestionPolicyConfig`), 결정 입력 시그니처(`buildDecisionInputSignature`), 터미널 커서 연속성 복원(`resolveTerminalTypingContext`) 등 순수 함수를 소유한다. `_handleGenerationFailure`는 오류·시간 초과·빈 후보의 개인 후보 유지 → 로컬 기억 폴백 → 실패 종료 순서를 한 곳에서 보장한다. `_startGenerationSession`은 취소기·세대 토큰·타임아웃을 포함한 `GenerationSession`을 반환하고, `_prepareFirstCandidate`는 기억 수집·오타 교정·모델 요청과 첫 응답을 `FirstCandidatePreparation`으로 반환하며 실패 시에도 폴백용 기억 문맥을 보존한다. `_isGenerationResultCurrent`는 세대 불일치·문맥 경과·접두 변경을 순서대로 검사하고, `_publishFirstCandidate`는 개인 후보 병합·성공 기록·후속 채우기 시작을 담당하고, `_appendFilledCandidate`는 후속 후보의 추가·개인화 재정렬·표시·세션 행 후보 수 갱신을 한 곳에서 처리한다. `SuggestionService`는 입력 정책, 세대/취소, 표시, 수락만 조율한다. 모델 요청과 로컬 기억 게시는 각각 `SuggestionModelRequestInput`·`LocalMemoryPublication` 객체를 사용하며, 동작 변경 없는 순수 리팩토링이다.
 
 The existing `input-telemetry-handlers` and `suggestion-handlers` IPC extensions expose the receipt and the flow/suggestion summaries. Receipt reads or deletes report an IPC error when storage access fails; they do not return invented counts or claim a purge succeeded. The receipt is local-only: `input_activity`, `typing_samples`, and `suggestions` retain 30 days; `personal_phrases` has no age-based automatic expiry and is removed by individual deletion, delete-all, or consent withdrawal. Smart Exclusion never records password evidence and recommends only the current app after at least four observations, zero readable results, and a problematic ratio of at least 75%; its one-click action adds an exclusion and never auto-excludes. Shortcut Safety Audit is core `auditKeyBindingMap` applied by the Settings UI; it surfaces invalid/conflict issues while preserving the existing hold/double-press exceptions.
 
@@ -114,9 +114,9 @@ The existing `input-telemetry-handlers` and `suggestion-handlers` IPC extensions
 |---|---|
 | `AdMediationEngine` | Multi-ad mediation + header bidding |
 | `AdSettlementService` | Revenue settlement, withholding, payout ledger |
-| `BaseAdAdapter` / `UnavailableAdAdapter` | Adapter contract + fail-closed base |
+| `BaseAdAdapter` / `UnavailableAdAdapter` | Adapter contract + fail-closed base + declarative `UNAVAILABLE_AD_NETWORK_SPECS` / `createUnavailableAdAdapters()` registry (2026-11-13: consolidated 9 empty subclass files into one table-driven registry) |
 | `DirectHouseSponsorAdapter` | **Real configurable adapter**: bids/reports against an operator HTTPS `endpointUrl` (`AdNetworkConfig.endpointUrl`), validates creatives, fail-closed (`adapter_not_configured`) when unconfigured |
-| 9 placeholder adapters (AppLovin, Carbon, EthicalAds, GoogleAdManager, InMobi, Mintegral, Playwire, PubMatic, Unity) | Extend `UnavailableAdAdapter` — registered, no live bids (`provider_not_integrated`) |
+| 9 unavailable network specs (AppLovin, Carbon, EthicalAds, GoogleAdManager, InMobi, Mintegral, Playwire, PubMatic, Unity) | Instantiated via `createUnavailableAdAdapters()` — registered, no live bids (`provider_not_integrated`) |
 
 ---
 
@@ -149,7 +149,7 @@ Registry: `src/main/ipc/index.ts` calls 31 `registerXHandlers()` in fixed order.
 | `rag-handlers` | RAG |
 | `stt-handlers` | STT |
 | `suggestion-handlers` | SUGGESTION + POPUP_SUGGESTION |
-| `support-handlers` | SUPPORT |
+| `support-handlers` | SUPPORT (`redactPII(..., 'mask')` applied to diagnostic descriptions and logs before ticket creation, 2026-11-13 `W5-01`) |
 | `system-handlers` | SYSTEM |
 | `template-handlers` | DICTATION_TEMPLATE |
 | `voice-action-handlers` | VOICE_ACTION |
@@ -168,7 +168,7 @@ Preload exposes **`window.electronAPI`** with 37 namespaces: `platform, audio, c
 
 ## 4. Windows & popups
 
-`windows/WindowManager.ts` creates 7 windows: main (borderless, custom TitleBar; macOS `hiddenInset`), recording-tip, result-popup, history-popup, command-popup, caption-overlay, suggestion-overlay. Injects popup theme CSS + i18n strings; 2-phase resize. `windows/TrayManager.ts` — tray icon + menu + double-click show.
+`windows/WindowManager.ts` manages 7 windows: main (borderless, custom TitleBar; macOS `hiddenInset`) created at boot, and 6 vanilla popups (`recording-tip`, `result-popup`, `history-popup`, `command-popup`, `caption-overlay`, `suggestion-overlay`) created **lazily on first demand** (`peekHistoryPopupWindow` / `peekCommandPopupWindow` inspect existing windows without instantiating hidden Chromium renderers at startup). Injects popup theme CSS + i18n strings via `@d3ro/i18n/main`; 2-phase resize. `windows/TrayManager.ts` — tray icon + menu + double-click show.
 
 **Popup invariants** (each shipped broken once — do not regress):
 
@@ -191,7 +191,7 @@ Vanilla popups (`src/renderer/popups/`):
 
 ## 5. Renderer IA
 
-Routing is state-based in `renderer/navigation/app-navigation.tsx` (`AppRoute`, params, history/back), no react-router. `Ctrl+K` opens the search route and `Ctrl+1..3` opens Home/Records/Meetings.
+Routing is state-based in `renderer/navigation/app-navigation.tsx` (`AppRoute`, params, history/back), no react-router. `Ctrl+K` opens the search route and `Ctrl+1..3` opens Home/Records/Meetings. **Since 2026-11-13**, `AppLayout.tsx` keeps `HomePage` eager for instant first paint and code-splits the 7 secondary pages (`UnifiedSearchPage`, `HistoryPage`, `MeetingModePage`, `VoiceConversationPage`, `CommandsPage`, `DictionaryPage`, `KnowledgeBasePage`) plus 6 modals (`SettingsModal`, `OnboardingModal`, `OllamaGuideModal`, `SupportModal`, `LicenseModal`, `RewardedQuotaModal`) via `React.lazy` + conditional mounting, cutting the initial renderer JS chunk from `4,596.8 KB` to `1,591.3 KB` (`-65.4%`).
 
 | Page | Route | Feature |
 |---|---|---|
@@ -204,7 +204,7 @@ Routing is state-based in `renderer/navigation/app-navigation.tsx` (`AppRoute`,
 | `KnowledgeBasePage` | knowledge | Local RAG: add/index docs, semantic query, reindex/remove |
 | `MeetingModePage` | meetings | Meeting studio: live or imported-media transcript with progress/cancel, linked audio, memos, minutes/doc generation/export, diarization |
 
-Modals/components: `SettingsModal` (tabs General/Audio/STT/LLM/Input/License/Cloud/About), `LicenseModal`, `LicenseTab`, `CloudSyncSection`, `InputInsightsPanel` (consent + suggestion policy + weekly insights + learned phrases), `InputConsentPanel` (receipt + current-app exclusion recommendation), `InputInsightsView` (flow, friction and app-quality summaries), `OnboardingModal`, `UpgradePromptModal`, `ProBadge`, `TemplateSection`, `FileDropZone`, `OllamaGuideModal`, `CodexOAuthGuideModal`, `TitleBar`, `StatusBar`, meeting components (9), voice-conversation, payment (`CheckoutModal`, `checkout-flow.ts`), support (`SupportModal`), ads (`AdBanner`, `RewardedQuotaModal`), shared cards.
+Modals/components: `SettingsModal` (`349` lines after 2026-11-13 `W5-11`/`G7` extraction into `components/settings/{GeneralSettingsTab,AudioSettingsTab,LlmSettingsTab,AboutSettingsTab,settings-model-helpers}.ts(x)` alongside `SttSettingsTab`, `InputInsightsPanel`, `LicenseTab`, `CloudSyncSection`), `LicenseModal`, `InputConsentPanel` (receipt + current-app exclusion recommendation), `InputInsightsView` (flow, friction and app-quality summaries), `OnboardingModal`, `UpgradePromptModal`, `TemplateSection`, `FileDropZone`, `OllamaGuideModal`, `CodexOAuthGuideModal`, `TitleBar`, meeting components (`TranscriptTab` + `EditableSegment` include color-coded speaker badges and multi-speaker filter chips, 2026-11-13 `GAP-MTG-02`), voice-conversation, support (`SupportModal`), ads (`AdBanner`, `RewardedQuotaModal`), shared cards.
 
 Key-binding UI lives in `components/keybinding/` (`Keycap`, `KeyBindingPicker`, `KeyBindingField`, `translation-key`), embedded in the Settings **General** tab (`SettingsModal.tsx:239`) — one field per action plus a global on/off switch. The picker offers both key recording and a searchable grouped dropdown (MUI `Autocomplete` over `KEY_CATALOG`, `KeyBindingPicker.tsx:536`). It replaced `HotkeyRecordModal`. `renderer/utils/format-hotkey.ts` is now a 17-line platform adapter only; key names, modifier glyphs, and join rules come from `@d3ro/core/keybinding`.
 
@@ -212,7 +212,7 @@ Hooks: `useRealtimeConversation` (OpenAI Realtime WebRTC), `useLicenseState`, `u
 
 Test-facing surface (stable, Playwright E2E depends on these): `AppSidebar` `nav-*` buttons expose `data-testid="nav-${route}"` + `aria-current="page"`; `SettingsModal` tabs expose `data-testid="settings-tab-${id}"`; onboarding mode cards expose `onboarding-mode-local|online`; `EmptyStateCard` exposes `empty-state-card`. Add a testid before writing an E2E journey; do not select by MUI classes.
 
-DB schema (`src/main/db/schema.ts`, drizzle SQLite): `history`, `dictionary`, `stats`, `memo_tags`, `daily_usage`, `rag_documents`, `rag_chunks`, `meeting_sessions`, `meeting_memos`, `meeting_documents`, `input_activity` (hour × app counters), `typing_samples`, `personal_phrases`, `suggestions`.
+DB schema (`src/main/db/schema.ts`, drizzle SQLite): `history`, `dictionary`, `stats`, `memo_tags`, `daily_usage`, `rag_documents`, `rag_chunks` (incl. `embedding_blob` Float32 binary vector), `meeting_sessions`, `meeting_memos` (incl. immutable `revision` CAS counter, 2026-11-13 `GAP-SYNC-08`), `meeting_documents`, `input_activity` (hour × app counters), `typing_samples`, `personal_phrases`, `suggestions`, `phrase_edges`, `sync_outbox`, `sync_state`, plus FTS5 `tokenize = 'trigram'` virtual tables `history_fts`, `meeting_sessions_fts`, and `meeting_memos_fts` (`db/index.ts`: WAL + `synchronous = NORMAL` + `temp_store = MEMORY` + `cache_size = -16000` + `mmap_size = 67108864`). `PersonalGraphService.indexText` and `runMaintenance` execute inside single SQLite transactions, and `InputTelemetryService` only attaches high-frequency `mousemove`/`wheel` hooks and `_flushTimer` when `inputTelemetryEnabled && !inputTelemetryPaused`.
 
 ---
 
@@ -253,7 +253,7 @@ DB schema (`src/main/db/schema.ts`, drizzle SQLite): `history`, `dictionary`, `s
 |---|---|
 | App entry / deep links | `src/main/index.ts` |
 | Bootstrap order | `src/main/bootstrap.ts` |
-| IPC registry | `src/main/ipc/index.ts` |
+| IPC registry | `src/main/ipc/index.ts`, `src/main/ipc/renderer-broadcast.ts` (`safeSendToRenderer`, `broadcastToAllWindows` SSOT across 9 IPC/bootstrap modules) |
 | IPC channel SSOT | `packages/core/src/ipc-channels.ts` |
 | Key-binding contract SSOT | `packages/core/src/keybinding.ts` (catalog, actions, validation, conflicts, formatting, parsing) |
 | Input intelligence domain SSOT | `packages/core/src/input-intelligence.ts` (key classification, typed delta, suggestion policy, overlay anchoring, flow/friction aggregation, phrase decay/ranking, provenance and exclusion recommendation) |
@@ -269,7 +269,7 @@ DB schema (`src/main/db/schema.ts`, drizzle SQLite): `history`, `dictionary`, `s
 | LLM prompt / placeholder SSOT | `src/main/services/llm-prompts.ts` (shared by `VoiceModeService`, `ChainService`, `ipc/llm-handlers.ts`) |
 | DB schema | `src/main/db/schema.ts` |
 | Renderer shell / routes | `src/renderer/components/AppLayout.tsx` |
-| Unified search | `src/main/services/UnifiedSearchService.ts`, `src/main/ipc/unified-search-handlers.ts`, `src/renderer/pages/UnifiedSearchPage.tsx` |
+| Unified search & hardening anchors | `src/main/services/UnifiedSearchService.ts` (FTS5→`LIKE` fallback + sort indexes), `src/main/ipc/unified-search-handlers.ts`, `src/renderer/pages/UnifiedSearchPage.tsx`, `src/main/services/rag/chunk-store.ts`, `src/main/services/meeting/disk-wav-audio-sink.ts`, `src/renderer/utils/error-message.ts` |
 | Update feed SSOT | `src/main/update-feed.ts` |
 | Update policy SSOT | `release/update-policy.json` + `src/main/update-policy.ts` |
 | Path/loopback resolution | `src/main/utils/paths.ts`, `src/main/utils/loopback.ts` |
@@ -278,3 +278,5 @@ DB schema (`src/main/db/schema.ts`, drizzle SQLite): `history`, `dictionary`, `s
 2026-11-01 verification: source A/B 2/17 before vs 17/17 current; real MP3/M4A conversion 2/2; account-switch regression 3/3 after reproducing all three failures; local packaged STT transcribed the synthetic 8.498 s fixture exactly. Windows 1.16.0 installer, portable and runtime are published; the rebuilt sidecar passed separate-process startup/health and the packaged Windows keyboard N-API binding loaded successfully without starting hooks. Required sidecar minimum 1.16.0 delivers CPU budgeting and terminal UIA changes. [Recovery evidence](../evidence/2026-11-01-completion.md).
 
 2026-11-02 verification: installed 1.16.0 passed the actual Electron picker→timestamped transcript→local minutes/action-item journey. Native Korean IME passed 7/7 under bounded 100% CPU and 7/7 with a direct 9.389 s `gemma4:e4b` cold-load request overlapping two typing cases. The Latin-layout control exposed next-key/backspace interleaving; source now waits 140 ms at boundaries and batches the current trailing correction region after a 650 ms pause. Full desktop 2,773 tests and production build pass. The fix was published as Windows v1.16.1 on 2026-11-04; the installed-app Latin control still needs a new GUI run. Synthetic WinForms input is not physical-keyboard/Chromium/terminal proof. [Verification evidence](../evidence/2026-11-02-verification.md).
+
+2026-11-14 verification (Wave 6 WS1/WS2 hygiene, optimization & bug hunt): unified `safeSendToRenderer` and `broadcastToAllWindows` across 9 IPC/bootstrap modules into `src/main/ipc/renderer-broadcast.ts`; wired `OnlineLLMService` stream abort (`_abortController` in `chatStream`), `401` token reset, empty `data.text` guard, and `D3ROError` wrapping; fixed `UnifiedSearchService` `meetingTotal` double-counting, `startedAt`/`createdAt desc` sort order, runtime FTS5-to-`LIKE` fallback (`hasAllFtsTables`), and DB indexes (`idx_meeting_sessions_started_at`, `idx_meeting_memos_created_at`); exported `invalidateEmbeddedChunksCache` across `rag/chunk-store.ts`, `rag/retrieval.ts`, `sync/sync-adapters.ts`, and `db/index.ts`, cleared redundant cached `embedding` JSON strings after `Float32Array` decode, and guarded malformed Float32 buffers; added `MAX_WAV_DATA_BYTES = 0xffffffff - 36` uint32 guard and post-`openSync` fd cleanup in `disk-wav-audio-sink.ts`; closed timer/popup hide-show races across `AdMediationEngine`, `AudioCaptureService`, `LocalLLMService`, `disposeAudioHandlers`, `bootstrap.ts`, and `WindowManager.ts`; hardened `sidecar/main.py` (`UploadFile.close()`, `<2`/odd-byte PCM handling, `_watch_disconnect`, `/shutdown` `_download_thread` join). Renderer added `src/renderer/utils/error-message.ts` (`toErrorMessage`), unified meeting/pull models, guarded non-finite dates (`formatters.ts`, `UnifiedSearchPage.tsx`), cleaned unmount/sequence/timer/listener paths across pages/modals/hooks, and hardened all 6 vanilla JS popups (`beforeunload` listener/timer cleanup, `textContent = ''`, `result-popup` `prepareVersion`/`isVisible`/rAF cancel, `caption-overlay` per-line `fadeTimer`, bounds clamps). `@d3ro/desktop` Vitest **210 files / 2,865 tests PASS**, sidecar Python `unittest` **33/33 PASS**, `npm run build` + `npm run check:desktop-renderer` (`7 page(s)`) PASS; interactive Electron GUI checks remain `[~]`.
diff --git a/docs/map/05-web-app.md b/docs/map/05-web-app.md
index 1c1cd84..3bd53a8 100644
--- a/docs/map/05-web-app.md
+++ b/docs/map/05-web-app.md
@@ -44,12 +44,12 @@ Root layout: `ThemeProvider → I18nProvider → AuthProvider`.
 | `actions/` | `action-runner.tsx` (LLM parse → action: create_meeting/search_knowledge/create_memo/send_team_invite) |
 | `record/` | `mic-recorder.tsx` (MediaRecorder + level analyser → `transcribeWebAudio`) |
 | `billing/` | `billing-checkout-options`, `payple-checkout-button`, `payple-client`, `payple-manage-button` |
-| `meetings/` | `document-editor`, `generate-document-button`, `live-transcript-list` (Realtime), `markdown-preview` (Mermaid), `meeting-audio-player` (signed URL), `memo-form` |
+| `meetings/` | `document-editor` (`MarkdownPreview` lazy-loaded client-only via `next/dynamic`), `generate-document-button`, `live-transcript-list` (Realtime + color-coded speaker badges & multi-speaker filter chips, 2026-11-13 `GAP-MTG-02`), `markdown-preview` (Mermaid loaded only when `` ```mermaid `` blocks exist; Wave 6 `useId()` + render-seq + `replaceChildren` `
` XSS fix, `isConnected` check, `mermaidReady` reset on error), `meeting-audio-player` (signed URL), `memo-form` |
 | `chat/` | `chat-panel.tsx` |
-| `teams/` | `create-team-form`, `invite-member-form`, `activity-feed` (team notes + realtime) |
+| `teams/` | `create-team-form`, `invite-member-form`, `activity-feed` (team notes + realtime), `team-card-grid` (renders real aggregated `member_count` with localized badge) |
 | `knowledge/` | `add-knowledge-form` (text or `.txt`/`.md` file, newline-aware chunking, `embed-chunks` on submit), `knowledge-search` (semantic via `search-knowledge`) |
-| `layout/` | `sidebar.tsx` (nav, theme selector, logout, i18n) + `web-push-control.tsx` (permission/subscription status and explicit opt-in/out switch) |
-| `providers/` | `auth-provider`, `i18n-provider`, `theme-mode-context`, `theme-provider` |
+| `layout/` | `sidebar.tsx` (nav, theme selector, logout, i18n) + `locale-switcher.tsx` (12-locale selector across sidebar & login, 2026-11-13 `GAP-I18N-03`) + `web-push-control.tsx` (permission/subscription status and explicit opt-in/out switch; Wave 6 `mountedRef`/`activeUserIdRef`/`activeToggleSeqRef` + `runWebPushToggle` + `withWebPushTimeout` timeout/re-entry guards) |
+| `providers/` | `auth-provider`, `i18n-provider` (persists locale in `localStorage` `d3ro.web.locale`, auto-detects browser language across all 12 locales, updates `document.documentElement.lang`), `theme-mode-context`, `theme-provider` |
 
 ---
 
@@ -64,6 +64,7 @@ Root layout: `ThemeProvider → I18nProvider → AuthProvider`.
 | `history-client.ts` | History list/get/update/delete, revision-safe |
 | `supabase-browser.ts` | Re-export `@d3ro/api-client/supabase-browser` |
 | `supabase-server.ts` | Next `cookies()` wrapper |
+| `team-client.ts` | Aggregates `team_members` rows into `TeamSummary.member_count` (`aggregateTeamsWithMemberCounts`, 2026-11-13; Wave 6 deduplicates `teamIds` and fails closed on `memberCountError`, `@d3ro/web` Vitest 9 files / 42 tests PASS; `dashboard/page.tsx` adds `mountedRef`/`requestSeqRef` stale-response guard) |
 | `web-device.ts` | Stable browser installation identity + active `platform='web'` device lookup/create/check-in; revoked rows are never resurrected |
 | `web-push.ts` | Web Push service-worker/VAPID subscribe/unsubscribe helper. Requires a valid active `deviceId`, persists only through register/unregister RPCs, rolls back a failed registration, re-registers an existing browser subscription before reporting it connected, and runs bounded server cleanup independently from local unsubscribe |
 | `web-push-session.ts` | Production orchestration boundary used by the sidebar and logout: user-gesture permission → device registration → subscription, plus per-user disabled intent, fail-closed reconciliation, and non-blocking logout cleanup |
@@ -75,7 +76,7 @@ Root layout: `ThemeProvider → I18nProvider → AuthProvider`.
 
 Two layers:
 
-- **Vitest** (`apps/web/tests/`, `npm --prefix apps/web run test`, part of root `npm test`): pure-logic contracts — `billing-catalog`, `web-push` (device/RPC/rollback/reconciliation/logout, 17 cases), `web-stt-client`.
+- **Vitest** (`apps/web/tests/`, `npm --prefix apps/web run test`, part of root `npm test`): pure-logic & SSR contracts — `billing-catalog`, `web-push` (device/RPC/rollback/reconciliation/logout, 17 cases), `web-stt-client`, `team-client` (3 cases), `locale-switcher` (3 cases), `live-transcript-speakers` (2 cases) — 6 files / 32 tests PASS.
 - **Playwright** (`apps/web/e2e/`): `smoke.spec.ts` (unauthenticated surface + fail-closed redirects + `/download` handoff), `billing`, `payple-checkout`, `dashboard-dictionary-commands`, `history` (fixture-based browser journeys).
 
 ---
@@ -85,9 +86,8 @@ Two layers:
 - Full App Router console: auth (email + OAuth), record/STT, history (list+detail), commands, actions, meetings (list+detail+docs), knowledge (add+search), teams (list+detail+invite), chat, dictionary, billing, download/releases.
 - Backed by Supabase tables + Edge Functions (`stt-proxy`, `llm-proxy`, `team-invite`, `team-accept`, `payple-checkout`, `payple-manage`, `search-knowledge`, `generate-meeting-document`).
 - No literal `TODO`/`FIXME` markers; remaining smaller items (see [`11-gap-backlog.md`](./11-gap-backlog.md) `WEB-*`):
-  - Teams `member_count` is `0` in MVP (separate query needed) — `teams/page.tsx`.
   - Action runner team-invite uses a manual redirect safety path instead of a live invite (`action-runner.tsx`).
-  - `/download` shows "artifact not yet published" for the current desktop release.
-- Knowledge file upload, semantic search, dictionary import/export, and the team activity feed are now implemented (`[x]` in the catalog).
+  - `/download` shows "artifact not yet published" when the feed lacks the current version.
+- Teams `member_count` aggregation (`team-client.ts`), 12-locale `LocaleSwitcher` + `I18nProvider` persistence, speaker badges/filter chips on `LiveTranscriptList`, knowledge file upload, semantic search, dictionary import/export, and the team activity feed are implemented and unit-tested.
 - **2026-11-04 Wave 4 hygiene:** Removed the unreferenced dashboard trend chart and the web `recharts` dependency. Web Push now has a production sidebar opt-in/out flow, stable web-device registration, device-bound register/unregister RPCs, disabled-intent reconciliation, bounded local/server cleanup, logout-independent sign-out, and a Docker-copied service worker. An isolated local browser run with ephemeral VAPID proved one active web device, one `webpush` token, one pending outbox attempt, a completed drain, and a `delivered` provider result; that result proves provider acceptance, not service-worker/browser receipt. A later production-standalone run built and served successfully but timed out during throwaway login navigation before the dashboard, so production-rendered 1440/390, accessibility-tree, hit-target, permission/subscription, and receipt gates remain open. No production secrets or deployment were changed.
 - **2026-10-28 designpaca audit (`SHELL-15`):** All 15 routes and shared components aligned with `design.md` v4 ("조용한 계기"): undefined `--d3-text-inverse` replaced with `--d3-accent-ink`, minimum font size raised to `11px` (`0.6875rem`), `uppercase` and positive `letterSpacing` removed from Korean UI copy, raw `monospace` replaced with `var(--d3-font-mono)`, single `component="h1"` hierarchy enforced per route, and native form controls equipped with `:focus-visible` rings and `