diff --git a/.claude/skills/refactor-wave/SKILL.md b/.claude/skills/refactor-wave/SKILL.md
index d2758a01..ce22926f 100644
--- a/.claude/skills/refactor-wave/SKILL.md
+++ b/.claude/skills/refactor-wave/SKILL.md
@@ -224,8 +224,5 @@ 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 735d0057..08316ec6 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -12,9 +12,8 @@ build/
!apps/desktop/build/entitlements.mac.plist
*.tsbuildinfo
-# 별개 서브 프로젝트 (Deno 런타임)
-site/dist/
-site/dist-ssr/
+# 별개 서브 프로젝트 (자체 lint 설정 사용)
+site/
server/supabase/functions/
# 환경
diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml
index 1e3e82e7..81be11dc 100644
--- a/.forgejo/workflows/ci.yml
+++ b/.forgejo/workflows/ci.yml
@@ -40,8 +40,7 @@ jobs:
[ -d .git ] || git init -q .
git remote remove origin 2>/dev/null || true
git remote add origin "$url"
- # depth 2: 보호 수용 테스트 게이트가 HEAD^ 와 비교한다 (얕은 클론 1이면 비교 불가).
- git fetch -q --depth 2 origin "$GITHUB_REF"
+ git fetch -q --depth 1 origin "$GITHUB_REF"
git checkout -q -f FETCH_HEAD
git clean -qfdx
@@ -85,27 +84,6 @@ jobs:
npm run test:hygiene:test
npm run test:hygiene
- - 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
@@ -152,17 +130,8 @@ jobs:
- name: 어드민 빌드
run: npm run build --workspace=@d3ro/admin
- - 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
+ - name: 웹앱 프로덕션 빌드
+ run: npm run build --workspace=@d3ro/web
mobile-quality:
name: 모바일 린트·타입·Jest
diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml
index df65a581..19e3d4f3 100644
--- a/.forgejo/workflows/release.yml
+++ b/.forgejo/workflows/release.yml
@@ -76,13 +76,7 @@ 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
- 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
- }
+ run: node scripts/ci/build-desktop-installer.mjs
- name: Forgejo 피드 게시 (latest.yml Ed25519 서명 + 공개 URL 검증)
if: steps.feed.outputs.published != 'true'
diff --git a/.gitignore b/.gitignore
index 92571907..5d2919aa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -33,7 +33,9 @@ apps/desktop/build/sidecar.spec
!apps/desktop/build/entitlements.mac.plist
sidecar-dist/
-# Bundled binaries (SoX는 apps/desktop/resources/sox에 필수 런타임만 커밋)
+# Bundled binaries (download via scripts; SoX는 직접 커밋)
+resources/sox/*.exe
+resources/sox/*.dll
apps/desktop/resources/ollama/
apps/desktop/build/installer.nsh
!apps/desktop/build/installer.nsh
@@ -133,4 +135,3 @@ site/dist-ssr/
# Local reference clones
/araso/
/.codex/
-/.pi/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f85ebe41..7ee72d98 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,34 +13,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Plugin system for custom pipelines
-## [1.17.1] - 2026-11-14
-
-> Supersedes unpublished `1.17.0` with the full-length ASAR Pickle header smoke verification fix and ships the full `1.17.0` multi-surface release.
-
-### Fixed
-- Read the full declared JSON byte length (up to 32 MiB) instead of a fixed 64 KiB prefix in `verify-desktop-installer-smoke.mjs` when validating `resources/app.asar`.
-
-## [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-swagger/openapi.json b/apps/admin-swagger/openapi.json
index 3b9a742d..6aa26193 100644
--- a/apps/admin-swagger/openapi.json
+++ b/apps/admin-swagger/openapi.json
@@ -3,7 +3,7 @@
"info": {
"title": "D3RO-VOICE Admin API",
"description": "Admin CRM Edge Functions for user management, subscription CRUD, payment history, and audit logs.",
- "version": "1.17.1"
+ "version": "1.16.5"
},
"servers": [
{
diff --git a/apps/admin/package.json b/apps/admin/package.json
index 169d37fa..26fceb81 100644
--- a/apps/admin/package.json
+++ b/apps/admin/package.json
@@ -1,6 +1,6 @@
{
"name": "@d3ro/admin",
- "version": "1.17.1",
+ "version": "1.16.5",
"private": true,
"description": "D3RO Voice Admin CRM — SaaS 관리 도구",
"scripts": {
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 8b392652..e205a5ac 100644
--- a/apps/admin/src/app/(admin)/audit-log/[id]/page.tsx
+++ b/apps/admin/src/app/(admin)/audit-log/[id]/page.tsx
@@ -10,7 +10,6 @@ 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 {
@@ -115,11 +114,11 @@ export default async function AuditLogDetailPage({ params }: PageProps): Promise
Transaction Metadata
-
-
-
-
-
+
+
+
+
+
@@ -165,3 +164,14 @@ 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 7b094fd3..8a322b24 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, useRef } from 'react'
+import React, { useState, useEffect } from 'react'
import {
Box,
Typography,
@@ -111,29 +111,19 @@ 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(() => {
- mountedRef.current = true
- void loadData()
- return () => {
- mountedRef.current = false
- }
+ loadData()
}, [])
// ── STT Handlers ──────────────────────────────────────────────────────────
@@ -170,17 +160,11 @@ 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 {
@@ -194,8 +178,8 @@ export default function ServiceModelsPage(): React.ReactElement {
language: sttLanguage,
prompt: sttPrompt ? sttPrompt : undefined,
temperature: 0.0,
- costPerMinute: parsedCostPerMinute,
- costPerSecond: parsedCostPerMinute / 60,
+ costPerMinute: parseFloat(sttCostPerMinute),
+ costPerSecond: parseFloat(sttCostPerMinute) / 60,
isDefault: sttIsDefault,
isActive: true,
fallbackPriority: sttFallbackPriority,
@@ -209,13 +193,11 @@ export default function ServiceModelsPage(): React.ReactElement {
}
await loadData()
- if (mountedRef.current) setSttModalOpen(false)
+ setSttModalOpen(false)
} catch (err) {
- if (mountedRef.current) {
- alert('Error saving STT endpoint: ' + (err instanceof Error ? err.message : String(err)))
- }
+ alert('Error saving STT endpoint: ' + (err instanceof Error ? err.message : String(err)))
} finally {
- if (mountedRef.current) setSttLoading(false)
+ setSttLoading(false)
}
}
@@ -224,7 +206,6 @@ 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,
@@ -232,9 +213,7 @@ export default function ServiceModelsPage(): React.ReactElement {
}))
)
} catch (err) {
- if (mountedRef.current) {
- alert('Error: ' + (err instanceof Error ? err.message : String(err)))
- }
+ alert('Error: ' + (err instanceof Error ? err.message : String(err)))
}
}
@@ -242,13 +221,11 @@ 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'}`
@@ -261,21 +238,19 @@ 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 {
- if (mountedRef.current) setTestingInModal(false)
+ setTestingInModal(false)
}
}
@@ -285,13 +260,9 @@ export default function ServiceModelsPage(): React.ReactElement {
if (memo.length < 3) return
try {
await deleteSttEndpointClient(id, memo)
- if (mountedRef.current) {
- setSttEndpoints((prev) => prev.filter((ep) => ep.id !== id))
- }
+ setSttEndpoints((prev) => prev.filter((ep) => ep.id !== id))
} catch (err) {
- if (mountedRef.current) {
- alert('Error: ' + (err instanceof Error ? err.message : String(err)))
- }
+ alert('Error: ' + (err instanceof Error ? err.message : String(err)))
}
}
@@ -311,15 +282,6 @@ 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 {
@@ -329,12 +291,11 @@ export default function ServiceModelsPage(): React.ReactElement {
provider: llmProvider,
endpointUrl: llmEndpointUrl,
apiKey: llmApiKey,
- costPer1kPromptTokens: parsedPromptCost,
- costPer1kCompletionTokens: parsedCompletionCost,
+ costPer1kPromptTokens: parseFloat(llmPromptCost),
+ costPer1kCompletionTokens: parseFloat(llmCompletionCost),
memo: llmMemo.trim(),
})
await loadData()
- if (!mountedRef.current) return
setLlmModalOpen(false)
setLlmModelId('')
setLlmModelName('')
@@ -342,11 +303,9 @@ export default function ServiceModelsPage(): React.ReactElement {
setLlmApiKey('')
setLlmMemo('')
} catch (err) {
- if (mountedRef.current) {
- alert('Error: ' + (err instanceof Error ? err.message : String(err)))
- }
+ alert('Error: ' + (err instanceof Error ? err.message : String(err)))
} finally {
- if (mountedRef.current) setLlmLoading(false)
+ setLlmLoading(false)
}
}
@@ -356,13 +315,9 @@ export default function ServiceModelsPage(): React.ReactElement {
if (memo.length < 3) return
try {
await deleteModelEndpointClient(id, memo)
- if (mountedRef.current) {
- setLlmEndpoints((current) => current.filter((endpoint) => endpoint.id !== id))
- }
+ setLlmEndpoints((current) => current.filter((endpoint) => endpoint.id !== id))
} catch (error) {
- if (mountedRef.current) {
- alert('Error: ' + (error instanceof Error ? error.message : String(error)))
- }
+ 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 275a1d7f..7d97fefa 100644
--- a/apps/admin/src/app/(admin)/subscriptions/[id]/page.tsx
+++ b/apps/admin/src/app/(admin)/subscriptions/[id]/page.tsx
@@ -7,8 +7,6 @@ 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'
@@ -18,7 +16,6 @@ interface PageProps {
}
export default async function SubscriptionDetailPage({ params }: PageProps): Promise {
- const admin = await requireManager()
if (!isSupabaseAdminConfigured()) {
return (
-
-
-
+
+
+
@@ -138,11 +135,11 @@ export default async function SubscriptionDetailPage({ params }: PageProps): Pro
Contract Status & Pricing
-
-
-
-
-
+
+
+
+
+
@@ -218,3 +215,14 @@ 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 9fc6bd39..650a43ed 100644
--- a/apps/admin/src/app/(admin)/users/[id]/page.tsx
+++ b/apps/admin/src/app/(admin)/users/[id]/page.tsx
@@ -7,8 +7,6 @@ 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'
@@ -19,7 +17,6 @@ interface PageProps {
}
export default async function AdminUserDetailPage({ params }: PageProps): Promise {
- const admin = await requireManager()
if (!isSupabaseAdminConfigured()) {
return (
-
-
-
-
-
+
+
+
+
+
@@ -184,10 +181,10 @@ export default async function AdminUserDetailPage({ params }: PageProps): Promis
-
-
-
-
+
+
+
+
@@ -283,3 +280,19 @@ 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 332cda5a..1645186c 100644
--- a/apps/admin/src/app/api/admin/backend/[...segments]/route.ts
+++ b/apps/admin/src/app/api/admin/backend/[...segments]/route.ts
@@ -1,7 +1,6 @@
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'
@@ -41,6 +40,26 @@ 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[] }> }
@@ -49,19 +68,15 @@ 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' && !isSameOriginRequest(request)) {
+ if (request.method !== 'GET' && !isSameOrigin(request)) {
return NextResponse.json({ error: 'cross_site_request_rejected' }, { status: 403 })
}
let body: string | undefined
if (request.method !== 'GET') {
- 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 })
+ body = await request.text()
+ if (new TextEncoder().encode(body).byteLength > 64 * 1024) {
+ return NextResponse.json({ error: 'request_too_large' }, { status: 413 })
}
}
diff --git a/apps/admin/src/app/api/admin/license/route.ts b/apps/admin/src/app/api/admin/license/route.ts
index 7f5cb73c..27459af0 100644
--- a/apps/admin/src/app/api/admin/license/route.ts
+++ b/apps/admin/src/app/api/admin/license/route.ts
@@ -6,7 +6,6 @@ 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'
@@ -33,12 +32,19 @@ 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 (!isSameOriginRequest(request)) {
- return NextResponse.json(
- { error: 'cross_site_request_rejected' },
- { status: 403, headers: { 'Cache-Control': 'no-store' } }
- )
+ if (!isSameOrigin(request)) {
+ return NextResponse.json({ error: 'cross_site_request_rejected' }, { status: 403 })
}
try {
@@ -46,24 +52,20 @@ 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, headers: { 'Cache-Control': 'no-store' } })
+ return NextResponse.json({ error: message }, { status })
}
- let candidate: Record
+ let body: unknown
try {
- 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' } }
- )
+ body = await request.json()
+ } catch {
+ return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
}
+ 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 : ''
@@ -137,5 +139,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 cea6ada2..1af74b63 100644
--- a/apps/admin/src/app/api/admin/supabase/[operation]/route.ts
+++ b/apps/admin/src/app/api/admin/supabase/[operation]/route.ts
@@ -1,17 +1,46 @@
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 = ADMIN_UUID_PATTERN
+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 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> {
- return await readBoundedJsonObject(request, 32 * 1024, { requireJsonContentType: true })
+ 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)
+ }
}
function onlyKeys(body: Record, allowed: readonly string[]): void {
@@ -191,7 +220,7 @@ async function handlePayments(request: NextRequest): Promise {
}
async function route(request: NextRequest, context: { params: Promise<{ operation: string }> }): Promise {
- if (request.method !== 'GET' && !isSameOriginRequest(request)) {
+ if (request.method !== 'GET' && !sameOrigin(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 454b0224..48747510 100644
--- a/apps/admin/src/app/api/auth/login/route.ts
+++ b/apps/admin/src/app/api/auth/login/route.ts
@@ -1,6 +1,4 @@
import { NextResponse } from 'next/server'
-import { AdminBackendError } from '@/lib/backend-session'
-import { readBoundedJsonObject } from '@/lib/request-security'
import {
checkRateLimit,
recordFailedAttempt,
@@ -54,24 +52,23 @@ function failure(key: string, status: number, retryAfterSeconds?: number): NextR
},
{
status,
- headers: {
- 'Cache-Control': 'no-store',
- ...(retryAfterSeconds ? { 'Retry-After': String(retryAfterSeconds) } : {})
- }
+ headers: retryAfterSeconds ? { 'Retry-After': String(retryAfterSeconds) } : undefined
}
)
}
export async function POST(request: Request): Promise {
- let candidate: Record
+ let body: unknown
try {
- candidate = await readBoundedJsonObject(request, 16 * 1024)
- } catch (error) {
- if (error instanceof AdminBackendError) {
- return failure(error.message, error.status)
- }
+ body = await request.json()
+ } catch {
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'
@@ -135,13 +132,10 @@ export async function POST(request: Request): Promise {
expiresAt
})
- const response = NextResponse.json(
- {
- success: true,
- user: { email: authenticatedEmail, role }
- },
- { headers: { 'Cache-Control': 'no-store' } }
- )
+ const response = NextResponse.json({
+ success: true,
+ user: { email: authenticatedEmail, role }
+ })
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 d5399d61..9bf6e13c 100644
--- a/apps/admin/src/app/api/auth/logout/route.ts
+++ b/apps/admin/src/app/api/auth/logout/route.ts
@@ -1,49 +1,40 @@
// apps/admin/src/app/api/auth/logout/route.ts
// D3RO Voice — Admin Session Logout Handler
-import { NextRequest, NextResponse } from 'next/server'
+import { NextResponse } from 'next/server'
import { adminCookieSecure } from '@/lib/admin-session'
-import { isSameOriginRequest } from '@/lib/request-security'
-function clearAdminSessionCookie(response: NextResponse): NextResponse {
+export async function POST(): Promise {
+ const response = NextResponse.json({ success: true, message: 'Logged out successfully' })
+
response.cookies.set({
name: 'd3ro_admin_session',
value: '',
httpOnly: true,
secure: adminCookieSecure(),
- sameSite: 'strict',
+ sameSite: 'lax',
path: '/',
maxAge: 0,
expires: new Date(0),
})
+
return response
}
-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' } }
- )
- }
-
+export async function GET(request: Request): Promise {
const url = new URL(request.url)
const response = NextResponse.redirect(new URL('/login', url.origin))
- response.headers.set('Cache-Control', 'no-store')
- return clearAdminSessionCookie(response)
+
+ response.cookies.set({
+ name: 'd3ro_admin_session',
+ value: '',
+ httpOnly: true,
+ secure: adminCookieSecure(),
+ sameSite: 'lax',
+ path: '/',
+ maxAge: 0,
+ expires: new Date(0),
+ })
+
+ return response
}
diff --git a/apps/admin/src/components/checksum-copy.tsx b/apps/admin/src/components/checksum-copy.tsx
index 36c32aab..9f4af04c 100644
--- a/apps/admin/src/components/checksum-copy.tsx
+++ b/apps/admin/src/components/checksum-copy.tsx
@@ -1,6 +1,6 @@
'use client'
-import { useEffect, useRef, useState } from 'react'
+import { useState } from 'react'
import { Box, Tooltip } from '@mui/material'
import { Check, Copy } from 'lucide-react'
import { C, FONT_MONO } from '@/lib/console-theme'
@@ -11,33 +11,12 @@ 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 => {
- 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)
+ void navigator.clipboard.writeText(value).then(() => {
+ setCopied(true)
+ setTimeout(() => setCopied(false), 2000)
+ })
}
return (
diff --git a/apps/admin/src/components/detail-row.tsx b/apps/admin/src/components/detail-row.tsx
deleted file mode 100644
index 0011f712..00000000
--- a/apps/admin/src/components/detail-row.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-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 55655d24..7594ef7d 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 { useEffect, useRef, useState } from 'react'
+import { useState } from 'react'
import {
Dialog,
DialogTitle,
@@ -52,19 +52,6 @@ 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)
@@ -91,31 +78,20 @@ 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) {
- if (mountedRef.current) {
- setError(err instanceof Error ? err.message : 'Failed to generate license key')
- }
+ setError(err instanceof Error ? err.message : 'Failed to generate license key')
} finally {
- if (mountedRef.current) setLoading(false)
+ setLoading(false)
}
}
const handleCopy = (): void => {
- if (!generatedKey || !navigator.clipboard?.writeText) return
+ if (!generatedKey) return
void navigator.clipboard.writeText(generatedKey)
- .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)
+ setCopied(true)
+ setTimeout(() => setCopied(false), 3000)
}
const inputSx = {
diff --git a/apps/admin/src/components/payment-history.tsx b/apps/admin/src/components/payment-history.tsx
index c62aad73..66101220 100644
--- a/apps/admin/src/components/payment-history.tsx
+++ b/apps/admin/src/components/payment-history.tsx
@@ -36,25 +36,17 @@ 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=${encodeURIComponent(userId)}`)
- if (!active) return
+ const result = await callAdminApi(`admin-payments?userId=${userId}`)
setData(result)
} catch (caught) {
- if (!active) return
setError(caught instanceof Error ? caught.message : 'Failed to load payment data')
} finally {
- if (active) setLoading(false)
+ 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 cca94e98..07bdcdcb 100644
--- a/apps/admin/src/lib/admin-guard.ts
+++ b/apps/admin/src/lib/admin-guard.ts
@@ -3,7 +3,6 @@
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'
@@ -58,7 +57,9 @@ export async function requireSuperAdmin(): Promise {
export function hasMinRole(user?: AdminUser | null, minRole: AdminRole = 'manager'): boolean {
if (!user) return false
- return hasMinimumAdminRole(user.role, minRole)
+ if (user.role === 'super_admin') return true
+ if (user.role === 'admin' && minRole !== 'super_admin') return true
+ return 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
deleted file mode 100644
index f95a5900..00000000
--- a/apps/admin/src/lib/request-security.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-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/admin/src/lib/supabase-server.ts b/apps/admin/src/lib/supabase-server.ts
new file mode 100644
index 00000000..e935a120
--- /dev/null
+++ b/apps/admin/src/lib/supabase-server.ts
@@ -0,0 +1,10 @@
+// apps/admin/src/lib/supabase-server.ts
+// Next.js cookies() 주입 래퍼 — 실제 로직은 @d3ro/api-client
+
+import { cookies } from 'next/headers'
+import { createSupabaseServerClient } from '@d3ro/api-client/supabase-server'
+
+export async function getSupabaseServerClient() {
+ const cookieStore = await cookies()
+ return createSupabaseServerClient(cookieStore)
+}
diff --git a/apps/api-server.Tests/SttControllerSecurityTests.cs b/apps/api-server.Tests/SttControllerSecurityTests.cs
index dfc4eac1..6c5039e0 100644
--- a/apps/api-server.Tests/SttControllerSecurityTests.cs
+++ b/apps/api-server.Tests/SttControllerSecurityTests.cs
@@ -91,24 +91,6 @@ 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,
@@ -116,8 +98,7 @@ public sealed class SttControllerSecurityTests
string? email = null,
string configuredGatewayToken = GatewayToken,
string? suppliedGatewayToken = null,
- bool includeAudioForm = false,
- CancellationToken requestAborted = default)
+ bool includeAudioForm = false)
{
var claims = new List();
if (userId != null) claims.Add(new Claim(ClaimTypes.NameIdentifier, userId));
@@ -125,8 +106,7 @@ public sealed class SttControllerSecurityTests
var identity = new ClaimsIdentity(claims, isAuthenticated ? "test-auth" : null);
var context = new DefaultHttpContext
{
- User = new ClaimsPrincipal(identity),
- RequestAborted = requestAborted
+ User = new ClaimsPrincipal(identity)
};
if (includeAudioForm)
{
@@ -172,7 +152,6 @@ 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,
@@ -181,25 +160,19 @@ public sealed class SttControllerSecurityTests
byte[]? audioBytes = null,
string? contentType = null,
string? fileName = null,
- bool recordUsage = true,
- CancellationToken cancellationToken = default)
+ bool recordUsage = true)
{
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,
- CancellationToken cancellationToken = default) =>
+ public Task TestEndpointAsync(int endpointId, string? testApiKey = null, string? testEndpointUrl = null) =>
throw new NotSupportedException();
public Task> GetAllEndpointsAsync() =>
diff --git a/apps/api-server.Tests/SttFailClosedTests.cs b/apps/api-server.Tests/SttFailClosedTests.cs
index 37063072..3ed359b3 100644
--- a/apps/api-server.Tests/SttFailClosedTests.cs
+++ b/apps/api-server.Tests/SttFailClosedTests.cs
@@ -121,108 +121,6 @@ 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 aee54ad2..26d7ab93 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, cancellationToken: HttpContext.RequestAborted);
+ var result = await _sttService.TestEndpointAsync(id);
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, HttpContext.RequestAborted);
+ var result = await _sttService.TestEndpointAsync(0, dto.ApiKey, endpointUri.AbsoluteUri);
return Ok(result);
}
diff --git a/apps/api-server/Controllers/LlmController.cs b/apps/api-server/Controllers/LlmController.cs
index 98ae3ec8..d44c8f0b 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, HttpContext.RequestAborted);
+ var result = await _llmService.GenerateAsync(userId, userEmail, request);
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, HttpContext.RequestAborted);
+ var result = await _llmService.ChatAsync(userId, userEmail, request);
return Ok(result);
}
}
diff --git a/apps/api-server/Controllers/SttController.cs b/apps/api-server/Controllers/SttController.cs
index 90b9aae7..12dafedc 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(HttpContext.RequestAborted);
+ var form = await Request.ReadFormAsync();
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, HttpContext.RequestAborted);
+ await file.CopyToAsync(memoryStream);
var language = form["language"].ToString();
var prompt = form["prompt"].ToString();
var request = new SttTranscribeRequest(
@@ -89,14 +89,9 @@ public class SttController : ControllerBase
memoryStream.ToArray(),
file.ContentType ?? "application/octet-stream",
file.FileName ?? "recording.bin",
- recordUsage: false,
- cancellationToken: HttpContext.RequestAborted);
+ recordUsage: false);
return Ok(result);
}
- catch (OperationCanceledException) when (HttpContext.RequestAborted.IsCancellationRequested)
- {
- return StatusCode(499);
- }
catch (SttProviderUnavailableException)
{
return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "stt_provider_unavailable" });
@@ -117,4 +112,20 @@ 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/D3ROVoice.Api.csproj b/apps/api-server/D3ROVoice.Api.csproj
index 6a0e06f3..2a09a3a3 100644
--- a/apps/api-server/D3ROVoice.Api.csproj
+++ b/apps/api-server/D3ROVoice.Api.csproj
@@ -2,7 +2,7 @@
net10.0
- 1.17.1
+ 1.16.5
enable
enable
diff --git a/apps/api-server/Services/LlmProxyService.cs b/apps/api-server/Services/LlmProxyService.cs
index 000156ba..3e828ef5 100644
--- a/apps/api-server/Services/LlmProxyService.cs
+++ b/apps/api-server/Services/LlmProxyService.cs
@@ -4,7 +4,6 @@ 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;
@@ -15,8 +14,8 @@ namespace D3ROVoice.Api.Services;
public interface ILlmProxyService
{
- Task GenerateAsync(int userId, string userEmail, LlmGenerateRequest request, CancellationToken cancellationToken = default);
- Task ChatAsync(int userId, string userEmail, LlmChatRequest request, CancellationToken cancellationToken = default);
+ Task GenerateAsync(int userId, string userEmail, LlmGenerateRequest request);
+ Task ChatAsync(int userId, string userEmail, LlmChatRequest request);
}
public class LlmProxyService : ILlmProxyService
@@ -32,16 +31,15 @@ public class LlmProxyService : ILlmProxyService
_logger = logger;
}
- public async Task GenerateAsync(int userId, string userEmail, LlmGenerateRequest request, CancellationToken cancellationToken = default)
+ public async Task GenerateAsync(int userId, string userEmail, LlmGenerateRequest request)
{
- 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, cancellationToken);
+ var endpoint = await _db.ModelEndpoints.FirstOrDefaultAsync(m => m.ModelId == modelId && m.IsActive);
if (endpoint == null)
{
// fallback: first active model endpoint or create default mockup endpoint
- endpoint = await _db.ModelEndpoints.FirstOrDefaultAsync(m => m.IsActive, cancellationToken);
+ endpoint = await _db.ModelEndpoints.FirstOrDefaultAsync(m => m.IsActive);
if (endpoint == null)
{
endpoint = new ServiceModelEndpoint
@@ -73,7 +71,7 @@ public class LlmProxyService : ILlmProxyService
{
try
{
- using var client = _httpClientFactory.CreateClient();
+ var client = _httpClientFactory.CreateClient();
client.Timeout = TimeSpan.FromSeconds(60);
var payload = new
@@ -88,7 +86,7 @@ public class LlmProxyService : ILlmProxyService
max_tokens = request.MaxTokens
};
- using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
+ var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
{
Content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json")
};
@@ -98,12 +96,12 @@ public class LlmProxyService : ILlmProxyService
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey);
}
- using var httpResponse = await client.SendAsync(httpRequest, cancellationToken);
+ var httpResponse = await client.SendAsync(httpRequest);
sw.Stop();
if (httpResponse.IsSuccessStatusCode)
{
- var jsonStr = await httpResponse.Content.ReadAsStringAsync(cancellationToken);
+ var jsonStr = await httpResponse.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(jsonStr);
var root = doc.RootElement;
@@ -126,10 +124,6 @@ public class LlmProxyService : ILlmProxyService
completionTokens = Math.Max(15, responseText.Length / 4);
}
}
- catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
- {
- throw;
- }
catch (Exception ex)
{
sw.Stop();
@@ -171,7 +165,7 @@ public class LlmProxyService : ILlmProxyService
};
_db.UsageLogs.Add(usageLog);
- await _db.SaveChangesAsync(cancellationToken);
+ await _db.SaveChangesAsync();
return new LlmGenerateResponse(
responseText,
@@ -183,9 +177,9 @@ public class LlmProxyService : ILlmProxyService
);
}
- public async Task ChatAsync(int userId, string userEmail, LlmChatRequest request, CancellationToken cancellationToken = default)
+ public async Task ChatAsync(int userId, string userEmail, LlmChatRequest request)
{
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), cancellationToken);
+ return await GenerateAsync(userId, userEmail, new LlmGenerateRequest(lastMsg, request.Model, null, request.Temperature, request.MaxTokens));
}
}
diff --git a/apps/api-server/Services/SttProxyService.cs b/apps/api-server/Services/SttProxyService.cs
index aa4bc3aa..5ce276a7 100644
--- a/apps/api-server/Services/SttProxyService.cs
+++ b/apps/api-server/Services/SttProxyService.cs
@@ -7,7 +7,6 @@ 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;
@@ -25,15 +24,10 @@ public interface ISttProxyService
byte[]? audioBytes = null,
string? contentType = null,
string? fileName = null,
- bool recordUsage = true,
- CancellationToken cancellationToken = default
+ bool recordUsage = true
);
- Task TestEndpointAsync(
- int endpointId,
- string? testApiKey = null,
- string? testEndpointUrl = null,
- CancellationToken cancellationToken = default);
+ Task TestEndpointAsync(int endpointId, string? testApiKey = null, string? testEndpointUrl = null);
Task> GetAllEndpointsAsync();
Task CreateEndpointAsync(CreateSttEndpointDto dto);
Task UpdateEndpointAsync(int id, UpdateSttEndpointDto dto);
@@ -55,9 +49,6 @@ 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;
@@ -76,25 +67,32 @@ public class SttProxyService : ISttProxyService
byte[]? audioBytes = null,
string? contentType = null,
string? fileName = null,
- bool recordUsage = true,
- CancellationToken cancellationToken = default
+ bool recordUsage = true
)
{
- 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))
{
- finalAudioBytes = DecodeAudioBase64(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);
+ }
}
else
{
@@ -106,7 +104,7 @@ public class SttProxyService : ISttProxyService
var durationSeconds = EstimateAudioDuration(finalAudioBytes, effectiveContentType);
// 2. Resolve Candidate Endpoints (Primary + Fallbacks)
- var candidates = await GetCandidateEndpointsAsync(request.Provider, request.ModelId, cancellationToken);
+ var candidates = await GetCandidateEndpointsAsync(request.Provider, request.ModelId);
if (candidates.Count == 0)
{
throw new SttProviderUnavailableException(providerAttempted: false);
@@ -119,7 +117,6 @@ public class SttProxyService : ISttProxyService
// 3. Failover Execution Chain
foreach (var endpoint in candidates)
{
- cancellationToken.ThrowIfCancellationRequested();
var epSw = Stopwatch.StartNew();
try
{
@@ -139,8 +136,7 @@ public class SttProxyService : ISttProxyService
finalAudioBytes,
effectiveContentType,
effectiveFileName,
- request,
- cancellationToken
+ request
);
epSw.Stop();
@@ -171,11 +167,7 @@ public class SttProxyService : ISttProxyService
CreatedAt = DateTime.UtcNow
};
_db.SttUsageLogs.Add(usageLog);
- await _db.SaveChangesAsync(cancellationToken);
- }
- catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
- {
- throw;
+ await _db.SaveChangesAsync();
}
catch (Exception dbEx)
{
@@ -194,10 +186,6 @@ public class SttProxyService : ISttProxyService
Cost: cost
);
}
- catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
- {
- throw;
- }
catch (Exception ex)
{
epSw.Stop();
@@ -217,11 +205,7 @@ public class SttProxyService : ISttProxyService
Endpoint = null,
CreatedAt = DateTime.UtcNow
});
- await _db.SaveChangesAsync(cancellationToken);
- }
- catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
- {
- throw;
+ await _db.SaveChangesAsync();
}
catch
{
@@ -236,67 +220,15 @@ 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,
- CancellationToken cancellationToken
+ SttTranscribeRequest request
)
{
- using var client = _httpClientFactory.CreateClient();
+ var client = _httpClientFactory.CreateClient();
client.Timeout = TimeSpan.FromSeconds(90);
var providerType = endpoint.ProviderType.ToLowerInvariant();
@@ -313,31 +245,31 @@ public class SttProxyService : ISttProxyService
case "openai":
case "custom":
{
- return await CallOpenAiCompatibleSttAsync(client, endpoint, audioBytes, contentType, fileName, request, cancellationToken);
+ return await CallOpenAiCompatibleSttAsync(client, endpoint, audioBytes, contentType, fileName, request);
}
case "deepgram":
{
- return await CallDeepgramSttAsync(client, endpoint, audioBytes, contentType, request, cancellationToken);
+ return await CallDeepgramSttAsync(client, endpoint, audioBytes, contentType, request);
}
case "google":
{
- return await CallGoogleSttAsync(client, endpoint, audioBytes, contentType, request, cancellationToken);
+ return await CallGoogleSttAsync(client, endpoint, audioBytes, contentType, request);
}
case "assemblyai":
{
- return await CallAssemblyAiSttAsync(client, endpoint, audioBytes, contentType, request, cancellationToken);
+ return await CallAssemblyAiSttAsync(client, endpoint, audioBytes, contentType, request);
}
case "azure":
{
- return await CallAzureSttAsync(client, endpoint, audioBytes, contentType, request, cancellationToken);
+ return await CallAzureSttAsync(client, endpoint, audioBytes, contentType, request);
}
case "local-sidecar":
{
- return await CallLocalSidecarSttAsync(client, endpoint, audioBytes, contentType, fileName, request, cancellationToken);
+ return await CallLocalSidecarSttAsync(client, endpoint, audioBytes, contentType, fileName, request);
}
default:
{
- return await CallOpenAiCompatibleSttAsync(client, endpoint, audioBytes, contentType, fileName, request, cancellationToken);
+ return await CallOpenAiCompatibleSttAsync(client, endpoint, audioBytes, contentType, fileName, request);
}
}
}
@@ -348,8 +280,7 @@ public class SttProxyService : ISttProxyService
byte[] audioBytes,
string contentType,
string fileName,
- SttTranscribeRequest request,
- CancellationToken cancellationToken
+ SttTranscribeRequest request
)
{
using var form = new MultipartFormDataContent();
@@ -376,7 +307,7 @@ public class SttProxyService : ISttProxyService
form.Add(new StringContent(temp.ToString("0.0")), "temperature");
form.Add(new StringContent("verbose_json"), "response_format");
- using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
+ var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
{
Content = form
};
@@ -388,7 +319,13 @@ public class SttProxyService : ISttProxyService
ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson);
- var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
+ var httpResponse = await client.SendAsync(httpRequest);
+ var responseBody = await httpResponse.Content.ReadAsStringAsync();
+
+ if (!httpResponse.IsSuccessStatusCode)
+ {
+ throw new HttpRequestException($"STT upstream returned HTTP {httpResponse.StatusCode}.");
+ }
using var doc = JsonDocument.Parse(responseBody);
var root = doc.RootElement;
@@ -419,8 +356,7 @@ public class SttProxyService : ISttProxyService
SttProviderEndpoint endpoint,
byte[] audioBytes,
string contentType,
- SttTranscribeRequest request,
- CancellationToken cancellationToken
+ SttTranscribeRequest request
)
{
var lang = request.Language ?? endpoint.Language ?? "ko";
@@ -430,7 +366,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";
- using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
+ var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new ByteArrayContent(audioBytes)
};
@@ -443,7 +379,13 @@ public class SttProxyService : ISttProxyService
ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson);
- var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
+ var response = await client.SendAsync(httpRequest);
+ var responseBody = await response.Content.ReadAsStringAsync();
+
+ if (!response.IsSuccessStatusCode)
+ {
+ throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}.");
+ }
using var doc = JsonDocument.Parse(responseBody);
var root = doc.RootElement;
@@ -479,8 +421,7 @@ public class SttProxyService : ISttProxyService
SttProviderEndpoint endpoint,
byte[] audioBytes,
string contentType,
- SttTranscribeRequest request,
- CancellationToken cancellationToken
+ SttTranscribeRequest request
)
{
var base64Audio = Convert.ToBase64String(audioBytes);
@@ -516,13 +457,19 @@ public class SttProxyService : ISttProxyService
}
};
- using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
+ 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 responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
+ var response = await client.SendAsync(httpRequest);
+ var responseBody = await response.Content.ReadAsStringAsync();
+
+ if (!response.IsSuccessStatusCode)
+ {
+ throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}.");
+ }
using var doc = JsonDocument.Parse(responseBody);
var root = doc.RootElement;
@@ -560,13 +507,19 @@ public class SttProxyService : ISttProxyService
}
};
- using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
+ 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 responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
+ var response = await client.SendAsync(httpRequest);
+ var responseBody = await response.Content.ReadAsStringAsync();
+
+ if (!response.IsSuccessStatusCode)
+ {
+ throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}.");
+ }
using var doc = JsonDocument.Parse(responseBody);
var root = doc.RootElement;
@@ -602,18 +555,22 @@ public class SttProxyService : ISttProxyService
SttProviderEndpoint endpoint,
byte[] audioBytes,
string contentType,
- SttTranscribeRequest request,
- CancellationToken cancellationToken
+ SttTranscribeRequest request
)
{
// 1. Upload audio
- using var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.assemblyai.com/v2/upload")
+ var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.assemblyai.com/v2/upload")
{
Content = new ByteArrayContent(audioBytes)
};
uploadRequest.Headers.Add("Authorization", endpoint.ApiKey);
- var uploadBody = await SendForStringAsync(client, uploadRequest, cancellationToken);
+ 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}.");
+ }
using var uploadDoc = JsonDocument.Parse(uploadBody);
var uploadUrl = uploadDoc.RootElement.GetProperty("upload_url").GetString()!;
@@ -628,13 +585,18 @@ public class SttProxyService : ISttProxyService
format_text = true
};
- using var transRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.assemblyai.com/v2/transcript")
+ 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 transBody = await SendForStringAsync(client, transRequest, cancellationToken);
+ 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}.");
+ }
using var transDoc = JsonDocument.Parse(transBody);
var id = transDoc.RootElement.GetProperty("id").GetString()!;
@@ -642,11 +604,17 @@ public class SttProxyService : ISttProxyService
// 3. Poll for result (up to 20 seconds)
for (int i = 0; i < 20; i++)
{
- await Task.Delay(1000, cancellationToken);
- using var pollReq = new HttpRequestMessage(HttpMethod.Get, $"https://api.assemblyai.com/v2/transcript/{id}");
+ await Task.Delay(1000);
+ var pollReq = new HttpRequestMessage(HttpMethod.Get, $"https://api.assemblyai.com/v2/transcript/{id}");
pollReq.Headers.Add("Authorization", endpoint.ApiKey);
- var pollBody = await SendForStringAsync(client, pollReq, cancellationToken);
+ 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}.");
+ }
using var pollDoc = JsonDocument.Parse(pollBody);
var status = pollDoc.RootElement.GetProperty("status").GetString();
@@ -679,8 +647,7 @@ public class SttProxyService : ISttProxyService
SttProviderEndpoint endpoint,
byte[] audioBytes,
string contentType,
- SttTranscribeRequest request,
- CancellationToken cancellationToken
+ SttTranscribeRequest request
)
{
var lang = request.Language ?? endpoint.Language ?? "ko-KR";
@@ -690,7 +657,7 @@ public class SttProxyService : ISttProxyService
? $"{endpoint.EndpointUrl}&language={lang}&format=detailed"
: $"{endpoint.EndpointUrl}?language={lang}&format=detailed";
- using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
+ var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new ByteArrayContent(audioBytes)
};
@@ -701,7 +668,13 @@ public class SttProxyService : ISttProxyService
httpRequest.Headers.Add("Ocp-Apim-Subscription-Key", endpoint.ApiKey);
}
- var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
+ var response = await client.SendAsync(httpRequest);
+ var responseBody = await response.Content.ReadAsStringAsync();
+
+ if (!response.IsSuccessStatusCode)
+ {
+ throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}.");
+ }
using var doc = JsonDocument.Parse(responseBody);
var root = doc.RootElement;
@@ -736,8 +709,7 @@ public class SttProxyService : ISttProxyService
byte[] audioBytes,
string contentType,
string fileName,
- SttTranscribeRequest request,
- CancellationToken cancellationToken
+ SttTranscribeRequest request
)
{
using var form = new MultipartFormDataContent();
@@ -748,7 +720,7 @@ public class SttProxyService : ISttProxyService
form.Add(new StringContent(endpoint.ModelId), "model");
form.Add(new StringContent(request.Language ?? endpoint.Language ?? "ko"), "language");
- using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
+ var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
{
Content = form
};
@@ -758,7 +730,13 @@ public class SttProxyService : ISttProxyService
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey);
}
- var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
+ var response = await client.SendAsync(httpRequest);
+ var responseBody = await response.Content.ReadAsStringAsync();
+
+ if (!response.IsSuccessStatusCode)
+ {
+ throw new HttpRequestException($"STT upstream returned HTTP {response.StatusCode}.");
+ }
using var doc = JsonDocument.Parse(responseBody);
var root = doc.RootElement;
@@ -774,16 +752,12 @@ public class SttProxyService : ISttProxyService
return (text, 0.99, endpoint.Language, duration);
}
- public async Task TestEndpointAsync(
- int endpointId,
- string? testApiKey = null,
- string? testEndpointUrl = null,
- CancellationToken cancellationToken = default)
+ public async Task TestEndpointAsync(int endpointId, string? testApiKey = null, string? testEndpointUrl = null)
{
SttProviderEndpoint? endpoint = null;
if (endpointId > 0)
{
- endpoint = await _db.SttProviderEndpoints.FindAsync(new object[] { endpointId }, cancellationToken);
+ endpoint = await _db.SttProviderEndpoints.FindAsync(endpointId);
}
if (endpoint == null)
@@ -818,8 +792,7 @@ public class SttProxyService : ISttProxyService
syntheticWav,
"audio/wav",
"test_audio.wav",
- new SttTranscribeRequest(Language: endpoint.Language ?? "ko"),
- cancellationToken
+ new SttTranscribeRequest(Language: endpoint.Language ?? "ko")
);
sw.Stop();
@@ -832,10 +805,6 @@ public class SttProxyService : ISttProxyService
ModelId: endpoint.ModelId
);
}
- catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
- {
- throw;
- }
catch (Exception ex)
{
sw.Stop();
@@ -999,19 +968,16 @@ public class SttProxyService : ISttProxyService
);
}
- private async Task> GetCandidateEndpointsAsync(
- string? requestedProvider,
- string? requestedModel,
- CancellationToken cancellationToken)
+ private async Task> GetCandidateEndpointsAsync(string? requestedProvider, string? requestedModel)
{
var query = _db.SttProviderEndpoints.Where(e => e.IsActive);
if (!string.IsNullOrWhiteSpace(requestedProvider))
{
- var match = await query.FirstOrDefaultAsync(e => e.ProviderType.ToLower() == requestedProvider.ToLower(), cancellationToken);
+ var match = await query.FirstOrDefaultAsync(e => e.ProviderType.ToLower() == requestedProvider.ToLower());
if (match != null)
{
- var others = await query.Where(e => e.Id != match.Id).OrderBy(e => e.FallbackPriority).ToListAsync(cancellationToken);
+ var others = await query.Where(e => e.Id != match.Id).OrderBy(e => e.FallbackPriority).ToListAsync();
others.Insert(0, match);
return others;
}
@@ -1019,10 +985,10 @@ public class SttProxyService : ISttProxyService
if (!string.IsNullOrWhiteSpace(requestedModel))
{
- var match = await query.FirstOrDefaultAsync(e => e.ModelId.ToLower() == requestedModel.ToLower(), cancellationToken);
+ var match = await query.FirstOrDefaultAsync(e => e.ModelId.ToLower() == requestedModel.ToLower());
if (match != null)
{
- var others = await query.Where(e => e.Id != match.Id).OrderBy(e => e.FallbackPriority).ToListAsync(cancellationToken);
+ var others = await query.Where(e => e.Id != match.Id).OrderBy(e => e.FallbackPriority).ToListAsync();
others.Insert(0, match);
return others;
}
@@ -1032,7 +998,7 @@ public class SttProxyService : ISttProxyService
return await query
.OrderByDescending(e => e.IsDefault)
.ThenBy(e => e.FallbackPriority)
- .ToListAsync(cancellationToken);
+ .ToListAsync();
}
private static bool HasRequiredProviderConfiguration(SttProviderEndpoint endpoint)
diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.yml
index 3f61199b..00bf6fb6 100644
--- a/apps/desktop/electron-builder.yml
+++ b/apps/desktop/electron-builder.yml
@@ -22,6 +22,8 @@ files:
- "!out/**/*.map"
# ffmpeg 정적 바이너리(61MB)는 설치본에 넣지 않는다 — 필요할 때 런타임으로 내려받는다
- "!node_modules/@ffmpeg-installer/**"
+ # ffmpeg 정적 바이너리(61MB)는 설치본에 넣지 않는다 — 필요할 때 런타임으로 내려받는다
+ - "!node_modules/@ffmpeg-installer/**"
# ────────────────────────────────────────────────────────────────────
# 자동 업데이트 feed — 이 설정이 있어야 electron-builder가
@@ -39,11 +41,12 @@ publish:
# electron-updater(기본 채널 latest)가 latest.yml을 찾으므로 항상 latest 채널로 고정.
detectUpdateChannel: false
-# native 모듈은 asar 외부에 배치 (Windows 는 koffi SendInput 으로 단일화되어 @nut-tree-fork 불필요)
+# native 모듈은 asar 외부에 배치
asarUnpack:
- "node_modules/better-sqlite3/**"
- "node_modules/uiohook-napi/**"
- # koffi — 포그라운드 창 제목/프로세스 조회 및 SendInput(User32 FFI). prebuilt 바이너리 포함.
+ - "node_modules/@nut-tree-fork/**"
+ # koffi — 포그라운드 창 제목/프로세스 조회(User32 FFI). prebuilt 바이너리 포함.
- "node_modules/koffi/**"
- "node_modules/@koromix/**"
@@ -65,9 +68,6 @@ 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,17 +120,11 @@ extraResources:
filter:
- "*.wav"
- # SoX 바이너리 (평면 파일만 허용 — wget.exe/PDF/문서 등 불필요 파일 유입 차단.
- # 주의: "**/*" 패턴은 하위 디렉토리 누락 버그가 있으므로 평면 글롭만 사용한다)
+ # SoX 바이너리
+ # 주의: filter에 "**/*"를 쓰면 하위 디렉토리가 통째로 누락된다(실측).
+ # 디렉토리를 그대로 복사할 때는 filter를 지정하지 않는다.
- 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 dee49331..6b8b6b1a 100644
--- a/apps/desktop/electron.vite.config.ts
+++ b/apps/desktop/electron.vite.config.ts
@@ -1,29 +1,13 @@
import { createPublicKey } from 'crypto'
-import { copyFileSync, mkdirSync, readdirSync, readFileSync } from 'fs'
+import { readFileSync } from 'fs'
import { resolve } from 'path'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import react from '@vitejs/plugin-react'
-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 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 workspaceExclude = ['@d3ro/core', '@d3ro/ui', '@d3ro/i18n']
@@ -43,8 +27,7 @@ export default defineConfig({
plugins: [
externalizeDepsPlugin({
exclude: ['electron-store', ...workspaceExclude]
- }),
- copyMainLocalesPlugin
+ })
],
resolve: { alias: sharedAlias }
},
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index b54fb5cf..93b7dacd 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -1,6 +1,6 @@
{
"name": "@d3ro/desktop",
- "version": "1.17.1",
+ "version": "1.16.5",
"productName": "d3ro-voice",
"description": "로컬 AI 음성 어시스턴트 (Electron)",
"main": "./out/main/index.js",
diff --git a/apps/desktop/resources/sox/ChangeLog.txt b/apps/desktop/resources/sox/ChangeLog.txt
new file mode 100644
index 00000000..8a947ea4
--- /dev/null
+++ b/apps/desktop/resources/sox/ChangeLog.txt
@@ -0,0 +1,1703 @@
+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
new file mode 100644
index 00000000..268ba1e4
--- /dev/null
+++ b/apps/desktop/resources/sox/README.txt
@@ -0,0 +1,197 @@
+ 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
new file mode 100644
index 00000000..0ed7815a
--- /dev/null
+++ b/apps/desktop/resources/sox/README.win32.txt
@@ -0,0 +1,167 @@
+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
new file mode 100644
index 00000000..65d88764
--- /dev/null
+++ b/apps/desktop/resources/sox/batch-example.bat
@@ -0,0 +1,14 @@
+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
new file mode 100644
index 00000000..5f4b7011
Binary files /dev/null and b/apps/desktop/resources/sox/pthreadgc2.dll differ
diff --git a/apps/desktop/resources/sox/sox.pdf b/apps/desktop/resources/sox/sox.pdf
new file mode 100644
index 00000000..2447e9d1
Binary files /dev/null and b/apps/desktop/resources/sox/sox.pdf differ
diff --git a/apps/desktop/resources/sox/soxformat.pdf b/apps/desktop/resources/sox/soxformat.pdf
new file mode 100644
index 00000000..3981ceb0
Binary files /dev/null and b/apps/desktop/resources/sox/soxformat.pdf differ
diff --git a/apps/desktop/resources/sox/soxi.pdf b/apps/desktop/resources/sox/soxi.pdf
new file mode 100644
index 00000000..63b61964
Binary files /dev/null and b/apps/desktop/resources/sox/soxi.pdf differ
diff --git a/apps/desktop/resources/sox/wget.exe b/apps/desktop/resources/sox/wget.exe
new file mode 100644
index 00000000..f2a11c17
Binary files /dev/null and b/apps/desktop/resources/sox/wget.exe differ
diff --git a/apps/desktop/resources/sox/wget.ini b/apps/desktop/resources/sox/wget.ini
new file mode 100644
index 00000000..7aeacc74
--- /dev/null
+++ b/apps/desktop/resources/sox/wget.ini
@@ -0,0 +1,112 @@
+###
+### 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 1d3b3ae4..0976ce13 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, zlib1.dll, LICENSE.GPL.txt"
+ Write-Host " sox.exe, rec.exe, libmad-0.dll, libmp3lame-0.dll, libsox-3.dll"
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, zlib1.dll, LICENSE.GPL.txt"
+ Write-Host " sox.exe, rec.exe, libmad-0.dll, libmp3lame-0.dll, libsox-3.dll"
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", "zlib1.dll", "LICENSE.GPL.txt")
+$filesToCopy = @("sox.exe", "rec.exe", "libmad-0.dll", "libmp3lame-0.dll", "libsox-3.dll")
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 fd66bf86..e9d42ed8 100644
--- a/apps/desktop/sidecar/main.py
+++ b/apps/desktop/sidecar/main.py
@@ -29,10 +29,9 @@ import logging
import os
import signal
import sys
-import tempfile
import threading
import time
-from contextlib import asynccontextmanager, suppress
+from contextlib import asynccontextmanager
from pathlib import Path
from typing import AsyncGenerator
@@ -600,40 +599,28 @@ async def load_model(body: dict) -> JSONResponse: # noqa: ANN001
@app.post("/unload")
async def unload_model(request: Request) -> JSONResponse:
- """보조 자리 또는 기본(primary) 자리 모델을 내려 VRAM/RAM 을 돌려준다.
+ """보조 자리 모델을 내려 VRAM/RAM 을 돌려준다.
- 사이드카 HTTP 프로세스 자체는 UIA 브리지(/uia/focus)가 계속 쓰므로 살려 둔 채,
- 클라우드 STT 전환·장시간 유휴·자막 종료 시 Whisper CTranslate2 모델 메모리만 회수한다.
+ 자막·회의가 끝난 뒤에도 보조 모델(예: large-v3-turbo)이 받아쓰기 모델과 함께 상주하면
+ GPU 여유가 줄어 Ollama 모델 로드가 느려지거나 OOM 이 난다. 기본(primary) 모델은 받아쓰기
+ 지연을 막기 위해 내리지 않는다.
- Request body: { "slot": "aux" | "primary" | "all" }
+ Request body: { "slot": "aux" }
"""
- global _model, _model_id
-
body = await request.json()
slot: str = body.get("slot", "aux")
- if slot not in ("aux", "primary", "all"):
+ if slot != "aux":
return JSONResponse(
status_code=400,
- content={"status": "error", "message": "slot must be aux, primary, or all"},
+ content={"status": "error", "message": "only the aux slot can be unloaded"},
)
- released: list[str] = []
async with _inference_lock:
- 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()
-
+ released = list(_aux_models)
+ _aux_models.clear()
if released:
gc.collect()
- logger.info("모델 언로드(%s): %s", slot, ", ".join(released))
+ logger.info("보조 모델 언로드: %s", ", ".join(released))
return JSONResponse(content={"status": "unloaded", "models": released})
@@ -721,21 +708,14 @@ async def transcribe(
start_time = time.monotonic()
try:
- try:
- pcm_bytes = await audio.read()
- finally:
- await audio.close()
+ pcm_bytes = await audio.read()
- if len(pcm_bytes) < 2:
+ if len(pcm_bytes) == 0:
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
)
@@ -776,8 +756,6 @@ async def transcribe(
finally:
cancel.set()
watcher.cancel()
- with suppress(asyncio.CancelledError, Exception):
- await watcher
processing_time = int((time.monotonic() - start_time) * 1000)
@@ -894,134 +872,11 @@ 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
deleted file mode 100644
index 2efc4989..00000000
--- a/apps/desktop/sidecar/tests/test_diarize_endpoint.py
+++ /dev/null
@@ -1,115 +0,0 @@
-"""
-사이드카 /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
deleted file mode 100644
index 1bbb75c1..00000000
--- a/apps/desktop/sidecar/tests/test_transcribe_hygiene.py
+++ /dev/null
@@ -1,87 +0,0 @@
-"""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 550dbc3c..717e7227 100644
--- a/apps/desktop/src/main/bootstrap.ts
+++ b/apps/desktop/src/main/bootstrap.ts
@@ -35,6 +35,7 @@ import { openStartupDatabase } from './db/startup-database'
import {
createMainWindow,
getMainWindow,
+ preloadPopupWindows,
showHistoryPopup,
hideHistoryPopup,
sendKeyToHistoryPopup,
@@ -43,8 +44,8 @@ import {
hideCommandPopup,
sendKeyToCommandPopup,
isCommandPopupVisible,
- peekHistoryPopupWindow,
- peekCommandPopupWindow,
+ getHistoryPopupWindow,
+ getCommandPopupWindow,
reapplyThemeToAllPopups,
} from './windows/WindowManager'
import { createTray } from './windows/TrayManager'
@@ -56,8 +57,6 @@ 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'
@@ -129,7 +128,6 @@ 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() })
}
@@ -171,9 +169,7 @@ 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()
@@ -212,12 +208,10 @@ async function initInputIntelligence(): Promise {
const telemetry = getInputTelemetryService()
const suggestion = getSuggestionService()
- // macOS 등 nut-js 를 쓰는 환경에서만 부팅 뒤 미리 불러 둔다 (Windows 는 koffi SendInput 즉시 로드).
- if (process.platform !== 'win32') {
- setTimeout(() => {
- void getTextInsertService().preload()
- }, 5_000).unref?.()
- }
+ // 첫 제안 수락·받아쓰기 삽입이 키 입력 모듈 로딩(수 초)을 기다리지 않게, 부팅이 끝난 뒤 미리 불러 둔다.
+ setTimeout(() => {
+ void getTextInsertService().preload()
+ }, 5_000).unref?.()
// 오타 교정이 먼저 본다 — 고치는 중이면 텍스트가 곧 바뀌니 제안으로 넘기지 않고(교정 뒤 새
// 스냅샷이 온다), 모델로 검사 중이면 끝날 때('settled') 넘긴다. 제안이 고친 문장을 기준으로
@@ -390,8 +384,7 @@ async function initAutoUpdate(): Promise {
}
async function initPopupWindows(): Promise {
- // 팝업 창(녹음 팁·결과·기록·명령)은 부팅 시 숨긴 Chromium 프로세스 4개를 선점하지 않고,
- // 실제 핫키/이벤트가 발생해 표시할 때 처음 생성한 뒤 재사용한다 (~180-260MB 초기 메모리 절감).
+ preloadPopupWindows()
// 시스템 테마를 따르는 설정이면 OS 다크/라이트 전환 때 팝업도 다시 칠한다(언어가 바뀌면 lang 도 함께)
const onNativeThemeUpdated = (): void => {
@@ -451,10 +444,7 @@ function createPopupNavigationController(): PopupNavigationController {
hide: () => hideHistoryPopup(),
isVisible: () => isHistoryPopupVisible(),
sendKey: (key) => sendKeyToHistoryPopup(key),
- containsPoint: (point) => {
- const win = peekHistoryPopupWindow()
- return win ? windowContains(win, point) : false
- },
+ containsPoint: (point) => windowContains(getHistoryPopupWindow(), point),
},
command: {
show: () => {
@@ -465,10 +455,7 @@ function createPopupNavigationController(): PopupNavigationController {
hide: () => hideCommandPopup(),
isVisible: () => isCommandPopupVisible(),
sendKey: (key) => sendKeyToCommandPopup(key),
- containsPoint: (point) => {
- const win = peekCommandPopupWindow()
- return win ? windowContains(win, point) : false
- },
+ containsPoint: (point) => windowContains(getCommandPopupWindow(), point),
},
},
shortcuts: {
@@ -564,7 +551,10 @@ async function initVoiceMode(): Promise {
/** 메인 윈도우 렌더러에 UI 갱신 이벤트 전송 */
function notifyRenderer(channel: IPCChannel, data?: Record): void {
- safeSendToRenderer(channel, data ?? {})
+ const win = getMainWindow()
+ if (win && !win.isDestroyed()) {
+ win.webContents.send(channel, data ?? {})
+ }
}
async function initLLMPolling(): Promise {
@@ -578,11 +568,6 @@ 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 cced388b..c2a9b08b 100644
--- a/apps/desktop/src/main/db/index.ts
+++ b/apps/desktop/src/main/db/index.ts
@@ -15,7 +15,6 @@ 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')
@@ -89,12 +88,8 @@ 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 (
@@ -192,12 +187,11 @@ 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,
- embedding_blob BLOB,
- chunk_index INTEGER NOT NULL
+ id TEXT PRIMARY KEY,
+ document_id TEXT NOT NULL,
+ content TEXT NOT NULL,
+ embedding TEXT NOT NULL,
+ chunk_index INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_rag_chunks_document_id ON rag_chunks(document_id);
`)
@@ -223,7 +217,6 @@ 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 (
@@ -235,7 +228,6 @@ 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 테이블
@@ -391,8 +383,6 @@ 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,
@@ -413,150 +403,6 @@ 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(
@@ -662,15 +508,7 @@ export function openLocal(): OpenForUserResult {
* 현재 열려있는 DB 닫기. 아무 것도 안 열려 있으면 no-op.
*/
export function closeCurrent(): void {
- const prevDb = db
- if (!sqlite) {
- if (prevDb) {
- invalidateEmbeddedChunksCache(prevDb)
- db = null
- currentUserId = null
- }
- return
- }
+ if (!sqlite) return
const prevUserId = currentUserId
try {
@@ -680,7 +518,6 @@ export function closeCurrent(): void {
`Database close error: ${err instanceof Error ? err.message : String(err)}`
)
}
- if (prevDb) invalidateEmbeddedChunksCache(prevDb)
sqlite = null
db = null
currentUserId = null
@@ -794,9 +631,6 @@ 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 {
@@ -819,8 +653,6 @@ export function bindTestDatabase(
testDb: BetterSQLite3Database,
userId: string = LOCAL_USER_ID,
): void {
- if (db) invalidateEmbeddedChunksCache(db)
- invalidateEmbeddedChunksCache(testDb)
db = testDb
currentUserId = userId
emitAccountScopeChanged(userId)
@@ -828,7 +660,6 @@ 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 900fa9c5..70aec3cf 100644
--- a/apps/desktop/src/main/db/like-pattern.ts
+++ b/apps/desktop/src/main/db/like-pattern.ts
@@ -5,11 +5,13 @@
// '100%' 는 '100' 이 들어간 모든 행과 일치했다. 메타문자를 이스케이프하고 ESCAPE 절을 붙인다.
import { sql, type AnyColumn, type SQL } from 'drizzle-orm'
-import { escapeLikePattern } from '@d3ro/core/guards'
const LIKE_ESCAPE_CHAR = '\\'
-export { escapeLikePattern }
+/** LIKE 메타문자(%, _, 이스케이프 문자 자체)를 글자 그대로 찾도록 이스케이프한다. */
+export function escapeLikePattern(text: string): string {
+ return text.replace(/[\\%_]/g, (char) => `${LIKE_ESCAPE_CHAR}${char}`)
+}
export interface ContainsPattern {
/** 바인딩될 LIKE 패턴 (`%…%`, 이스케이프됨) */
diff --git a/apps/desktop/src/main/db/schema.ts b/apps/desktop/src/main/db/schema.ts
index 9b8ec690..77a3371e 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, blob, index, uniqueIndex, primaryKey } from 'drizzle-orm/sqlite-core'
+import { sqliteTable, text, integer, real, index, uniqueIndex, primaryKey } from 'drizzle-orm/sqlite-core'
// ── history ──────────────────────────────────────────────
export const history = sqliteTable(
@@ -141,10 +141,8 @@ 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) => [
@@ -183,7 +181,6 @@ 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),
]
)
@@ -196,7 +193,6 @@ 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'),
@@ -204,7 +200,6 @@ 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 1faae3c8..f3ddb486 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,10 +44,6 @@ 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 {
@@ -107,13 +103,19 @@ export function registerAudioHandlers(): void {
// level 0은 "무음/초기화 중"일 뿐 종료가 아님 — 종료는 done:true로만 알린다.
testLevelInterval = setInterval(() => {
const level = testLastRms > 0 ? Math.min(1.0, Math.pow(testLastRms, 0.28)) : 0
- safeSendToRenderer(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level, done: false })
+ const win = getMainWindow()
+ if (win && !win.isDestroyed()) {
+ win.webContents.send(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level, done: false })
+ }
}, 100)
// durationMs(기본 5초) 후 자동 중지
testTimer = setTimeout(() => {
void stopAudioTest()
- safeSendToRenderer(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level: 0, done: true })
+ const win = getMainWindow()
+ if (win && !win.isDestroyed()) {
+ win.webContents.send(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level: 0, done: true })
+ }
}, durationMs)
return ipcSuccess({ averageLevel: 0, peakLevel: 0, hasAudio: true })
@@ -129,7 +131,10 @@ export function registerAudioHandlers(): void {
// 테스트 수동 중지 (STOP 버튼)
ipcMain.handle(IPC_CHANNELS.AUDIO.STOP_TEST, async () => {
await stopAudioTest()
- safeSendToRenderer(IPC_CHANNELS.AUDIO.TEST_LEVEL, { level: 0, done: true })
+ const win = getMainWindow()
+ if (win && !win.isDestroyed()) {
+ win.webContents.send(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 80cae2ff..334b9c75 100644
--- a/apps/desktop/src/main/ipc/cloud-sync-handlers.ts
+++ b/apps/desktop/src/main/ipc/cloud-sync-handlers.ts
@@ -1,14 +1,13 @@
// src/main/ipc/cloud-sync-handlers.ts
// Phase V2-4: CloudSync IPC 핸들러
-import { ipcMain } from 'electron'
+import { ipcMain, BrowserWindow } 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')
@@ -96,28 +95,37 @@ 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) => {
- broadcastToAllWindows(IPC_CHANNELS.CLOUD_SYNC.AUTH_CHANGED, payload)
+ broadcast(IPC_CHANNELS.CLOUD_SYNC.AUTH_CHANGED, payload)
})
sync.on('sync-progress', (payload) => {
- broadcastToAllWindows(IPC_CHANNELS.CLOUD_SYNC.SYNC_PROGRESS, payload)
+ broadcast(IPC_CHANNELS.CLOUD_SYNC.SYNC_PROGRESS, payload)
})
sync.on('sync-complete', (payload) => {
- broadcastToAllWindows(IPC_CHANNELS.CLOUD_SYNC.SYNC_COMPLETE, payload)
+ broadcast(IPC_CHANNELS.CLOUD_SYNC.SYNC_COMPLETE, payload)
})
sync.on('sync-error', (payload) => {
- broadcastToAllWindows(IPC_CHANNELS.CLOUD_SYNC.SYNC_ERROR, payload)
+ broadcast(IPC_CHANNELS.CLOUD_SYNC.SYNC_ERROR, payload)
})
// 다른 기기의 변경이 반영되면 앱 공통 새로고침 신호로 알린다 (이력·사전·회의·명령 화면이 구독).
// 동기화가 메인에서 바꾼 설정(언어·테마 등)을 화면에도 알린다 — IPC로 바꿀 때만 방송되던 경로.
// (팝업 테마 등 키별 부수효과는 config-effects 레지스트리가 모든 경로에 한 번씩 적용한다)
onConfigChanged((event) => {
if (!isApplyingRemoteSettings()) return
- broadcastToAllWindows(IPC_CHANNELS.CONFIG.CHANGED, event)
+ broadcast(IPC_CHANNELS.CONFIG.CHANGED, event)
})
sync.on('data-changed', (payload) => {
- broadcastToAllWindows(IPC_CHANNELS.APP.DATA_CHANGED, { type: 'cloud-sync', entities: payload.entities })
+ broadcast(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 b71573ba..91202eaf 100644
--- a/apps/desktop/src/main/ipc/config-handlers.ts
+++ b/apps/desktop/src/main/ipc/config-handlers.ts
@@ -1,14 +1,15 @@
// src/main/ipc/config-handlers.ts
-import { ipcMain } from 'electron'
+import { ipcMain, BrowserWindow } 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 {
- broadcastToAllWindows(IPC_CHANNELS.CONFIG.CHANGED, { key, value, previousValue })
+ for (const win of BrowserWindow.getAllWindows()) {
+ win.webContents.send(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 bef1e66d..18307262 100644
--- a/apps/desktop/src/main/ipc/keybinding-handlers.ts
+++ b/apps/desktop/src/main/ipc/keybinding-handlers.ts
@@ -3,9 +3,8 @@
// 키바인딩 IPC. 액션을 파라미터로 받는 단일 채널 집합이며,
// 검증·충돌 판정은 전부 `packages/core/src/keybinding.ts` 의 함수를 쓴다.
-import { ipcMain } from 'electron'
+import { ipcMain, BrowserWindow } 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,
@@ -38,7 +37,9 @@ import type {
} from '@d3ro/core/types'
function broadcast(channel: string, payload: unknown): void {
- broadcastToAllWindows(channel, payload)
+ for (const win of BrowserWindow.getAllWindows()) {
+ win.webContents.send(channel, payload)
+ }
}
/** 바인딩 맵 변경을 모든 창에 알린다 (창 간 동기화). */
diff --git a/apps/desktop/src/main/ipc/license-handlers.ts b/apps/desktop/src/main/ipc/license-handlers.ts
index 2905d3b7..9c5c33ee 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 } from 'electron'
+import { app, ipcMain, BrowserWindow } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
import { getLicenseService } from '../services/LicenseService'
@@ -13,19 +13,22 @@ 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 {
- broadcastToAllWindows(IPC_CHANNELS.LICENSE.UPGRADE_PROMPT, event)
+ for (const win of BrowserWindow.getAllWindows()) {
+ win.webContents.send(IPC_CHANNELS.LICENSE.UPGRADE_PROMPT, event)
+ }
}
/** 티어 변경을 모든 렌더러에 broadcast */
function broadcastTierChanged(info: LicenseInfo): void {
- broadcastToAllWindows(IPC_CHANNELS.LICENSE.TIER_CHANGED, info)
+ for (const win of BrowserWindow.getAllWindows()) {
+ win.webContents.send(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 0268a88c..5392a8a1 100644
--- a/apps/desktop/src/main/ipc/llm-handlers.ts
+++ b/apps/desktop/src/main/ipc/llm-handlers.ts
@@ -10,13 +10,15 @@ 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 { safeSendToRenderer } from './renderer-broadcast'
-import type {
- SetLLMModelParams,
- SetServerUrlParams,
- LLMProcessParams,
- PullModelParams
-} from '@d3ro/core/types'
+import { getMainWindow } from '../windows/WindowManager'
+import type { SetLLMModelParams, SetServerUrlParams, LLMProcessParams } 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()
@@ -27,7 +29,7 @@ export function registerLLMHandlers(): void {
safeSendToRenderer(IPC_CHANNELS.LLM.PULL_PROGRESS, payload)
})
- ipcMain.handle(IPC_CHANNELS.LLM.PULL_MODEL, async (_event, params: PullModelParams) => {
+ ipcMain.handle(IPC_CHANNELS.LLM.PULL_MODEL, async (_event, params: { modelId: string }) => {
try {
await getLocalLLMService().pullModel(params.modelId)
return ipcSuccess(undefined)
diff --git a/apps/desktop/src/main/ipc/renderer-broadcast.ts b/apps/desktop/src/main/ipc/renderer-broadcast.ts
deleted file mode 100644
index 09a88bdb..00000000
--- a/apps/desktop/src/main/ipc/renderer-broadcast.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-// 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 6e8b861c..443f2770 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 { safeSendToRenderer } from './renderer-broadcast'
+import { getMainWindow } from '../windows/WindowManager'
import type {
SetSTTModelParams,
SetSTTLanguageParams,
@@ -21,6 +21,13 @@ 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 23765525..48f232c3 100644
--- a/apps/desktop/src/main/ipc/support-handlers.ts
+++ b/apps/desktop/src/main/ipc/support-handlers.ts
@@ -5,7 +5,6 @@ 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,
@@ -89,16 +88,6 @@ 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',
@@ -107,9 +96,9 @@ export function registerSupportHandlers(): void {
category: ticketData.category || 'general',
priority: ticketData.priority || 'normal',
status: 'open',
- subject: redactPII(ticketData.subject || '고객 지원 문의', 'mask').redactedText,
- description: redactPII(ticketData.description || '', 'mask').redactedText,
- diagnostics: sanitizedDiagnostics,
+ subject: ticketData.subject || '고객 지원 문의',
+ description: ticketData.description || '',
+ diagnostics: ticketData.diagnostics ?? ticketData.diagnosticsSnapshot,
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 f2aa665f..30ad9ba9 100644
--- a/apps/desktop/src/main/ipc/voice-handlers.ts
+++ b/apps/desktop/src/main/ipc/voice-handlers.ts
@@ -4,9 +4,16 @@ 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 { safeSendToRenderer } from './renderer-broadcast'
+import { getMainWindow } from '../windows/WindowManager'
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/ipc/window-handlers.ts b/apps/desktop/src/main/ipc/window-handlers.ts
index 27e5d302..866f943a 100644
--- a/apps/desktop/src/main/ipc/window-handlers.ts
+++ b/apps/desktop/src/main/ipc/window-handlers.ts
@@ -2,7 +2,6 @@
import { ipcMain } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
-import type { OpenExternalParams } from '@d3ro/core/types'
import { ErrorCode, ipcError, ipcSuccess } from '@d3ro/core/errors'
import { getMainWindow, hideResultPopup, hideRecordingTip } from '../windows/WindowManager'
import { isTrustedIpcSender, openExternalSafe } from '../windows/web-contents-hardening'
@@ -41,7 +40,7 @@ export function registerWindowHandlers(): void {
})
// 외부 URL 열기 — 앱 페이지가 보낸 요청만, 허용 scheme(https/mailto)만 연다.
- ipcMain.handle(IPC_CHANNELS.SYSTEM.OPEN_EXTERNAL, async (event, params: OpenExternalParams) => {
+ ipcMain.handle(IPC_CHANNELS.SYSTEM.OPEN_EXTERNAL, async (event, params: { url: string }) => {
if (!isTrustedIpcSender(event)) {
return ipcError(ErrorCode.ConfigInvalidValue, 'openExternal: untrusted sender')
}
diff --git a/apps/desktop/src/main/services/AudioCaptureService.ts b/apps/desktop/src/main/services/AudioCaptureService.ts
index e1cfc916..828ff93a 100644
--- a/apps/desktop/src/main/services/AudioCaptureService.ts
+++ b/apps/desktop/src/main/services/AudioCaptureService.ts
@@ -12,7 +12,6 @@ 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')
@@ -523,22 +522,15 @@ class AudioCaptureService extends EventEmitter {
if (rms > peakRms) peakRms = rms
})
- 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}`))
})
+ setTimeout(() => {
+ proc.kill()
+ }, durationMs)
+
proc.on('close', () => {
- if (settled) return
- settled = true
- clearTimeout(durationTimer)
if (buffers.length === 0) {
resolve({ averageLevel: 0, peakLevel: 0, hasAudio: false })
return
@@ -653,9 +645,8 @@ 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 56685fc3..3a24e4b4 100644
--- a/apps/desktop/src/main/services/InputTelemetryService.ts
+++ b/apps/desktop/src/main/services/InputTelemetryService.ts
@@ -380,16 +380,24 @@ 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._syncCollectionMode()
+ this._flushTimer = setInterval(
+ () => this._flush(),
+ INPUT_TELEMETRY_DEFAULTS.flushIntervalMs
+ )
+ this._flushTimer.unref?.()
// 주기 샘플러.
//
@@ -403,6 +411,9 @@ class InputTelemetryService extends EventEmitter {
)
this._sampleTimer.unref?.()
+ if (this._isTelemetryCollectionEnabled()) {
+ this._pruneOldData()
+ }
logger.info(
this._isTelemetryCollectionEnabled()
? '입력 텔레메트리 시작 (키/마우스 집계)'
@@ -465,52 +476,9 @@ 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()
@@ -611,6 +579,11 @@ 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
@@ -618,12 +591,9 @@ class InputTelemetryService extends EventEmitter {
: 'ime'
: classifyKeyStroke(vk, this._modifiers)
- if (this._isTelemetryCollectionEnabled()) {
- const bucket = this._bucket()
- if (keyClass === 'shortcut') bucket.shortcuts += 1
- else bucket.keystrokes += 1
- if (keyClass === 'backspace') bucket.backspaces += 1
- }
+ if (keyClass === 'shortcut') bucket.shortcuts += 1
+ else bucket.keystrokes += 1
+ if (keyClass === 'backspace') bucket.backspaces += 1
this._lastKeyAt = Date.now()
this._lastKeyClass = keyClass
@@ -680,11 +650,9 @@ class InputTelemetryService extends EventEmitter {
this._lastClickPos !== null &&
manhattanDistance(this._lastClickPos, position) < 6
- if (this._isTelemetryCollectionEnabled()) {
- const bucket = this._bucket()
- if (isDoubleClick) bucket.doubleClicks += 1
- else bucket.clicks += 1
- }
+ const bucket = this._bucket()
+ if (isDoubleClick) bucket.doubleClicks += 1
+ else bucket.clicks += 1
this._lastClickAt = now
this._lastClickButton = button
@@ -738,12 +706,10 @@ class InputTelemetryService extends EventEmitter {
const now = Date.now()
const gap = this._lastEventAt === 0 ? 0 : now - this._lastEventAt
- 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 (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
@@ -1274,12 +1240,10 @@ class InputTelemetryService extends EventEmitter {
return
}
- if (this._isTelemetryCollectionEnabled()) {
- const bucket = this._bucket()
- bucket.chars += delta.insertedChars
- bucket.words += delta.insertedWords
- bucket.sentences += delta.insertedSentences
- }
+ 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)
@@ -1529,43 +1493,41 @@ class InputTelemetryService extends EventEmitter {
try {
const db = getDatabase()
- 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
+ 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)
- tx.insert(inputActivity)
- .values({
- id: crypto.randomUUID(),
- date,
- hour,
- appName: appName ?? '',
- ...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}`,
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}`,
- updatedAt: now
- }
- })
- .run()
- }
- })
+ }
+ })
+ .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 ef0ce6d6..cb722898 100644
--- a/apps/desktop/src/main/services/LocalLLMService.ts
+++ b/apps/desktop/src/main/services/LocalLLMService.ts
@@ -185,7 +185,6 @@ 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 {
@@ -201,17 +200,10 @@ class LocalLLMService extends EventEmitter {
*/
async startServer(): Promise<'running' | 'starting' | 'not-installed' | 'failed'> {
const result = await this.ensureRunning()
- 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)
- }
+ if (result === 'starting' || result === 'running') {
+ // 1초 뒤 빠른 재확인
+ setTimeout(() => this._checkAvailability(), 1000)
+ setTimeout(() => this._checkAvailability(), 3000)
}
return result
}
@@ -985,10 +977,6 @@ 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 b4aa32e7..fe961464 100644
--- a/apps/desktop/src/main/services/LocalSTTService.ts
+++ b/apps/desktop/src/main/services/LocalSTTService.ts
@@ -128,8 +128,6 @@ 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[] = [
@@ -242,7 +240,6 @@ class LocalSTTService extends EventEmitter {
private _initializing: { modelId: string; promise: Promise } | null = null
// errorEmitted 플래그로 이벤트 중복 방지
private _errorEmitted: boolean = false
- private _idleUnloadTimer: NodeJS.Timeout | null = null
// ── 상태 접근자 ──
@@ -259,11 +256,6 @@ class LocalSTTService extends EventEmitter {
return this._supervisor.baseUrl
}
- /** 실행 중인 sidecar HTTP 기본 URL (기동되지 않았으면 null) */
- get sidecarBaseUrl(): string | null {
- return this._supervisor.isHealthy ? this._supervisor.baseUrl : null
- }
-
// ── 공개 메서드 ──
/**
@@ -310,7 +302,6 @@ class LocalSTTService extends EventEmitter {
}
private async _loadInitial(targetModel: string): Promise {
- this._clearIdleUnload()
this._setState(STTState.Loading)
this._errorEmitted = false
@@ -325,7 +316,6 @@ class LocalSTTService extends EventEmitter {
this._setState(STTState.Ready)
// 모델까지 올라갔으면 사이드카는 안정적이다 — 크래시 재시작 카운트 초기화
this._supervisor.markStable()
- this._scheduleIdleUnload()
logger.info(`STT 초기화 완료: 모델=${targetModel}`)
} catch (err) {
@@ -636,7 +626,6 @@ class LocalSTTService extends EventEmitter {
logger.info('LocalSTTService dispose 시작')
- this._clearIdleUnload()
this._initializing = null
this._modelReady = false
this._auxModelId = null
@@ -647,60 +636,6 @@ 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,
@@ -803,7 +738,6 @@ class LocalSTTService extends EventEmitter {
}
const isPartial = options?.partial === true
- this._clearIdleUnload()
if (!isPartial) {
this._setState(STTState.Transcribing)
@@ -923,10 +857,6 @@ class LocalSTTService extends EventEmitter {
ErrorCode.STTTranscriptionFailed,
`전사 실패: ${message}`,
)
- } finally {
- if (this._modelReady) {
- this._scheduleIdleUnload()
- }
}
}
@@ -934,7 +864,6 @@ 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 f9f45c67..0e377179 100644
--- a/apps/desktop/src/main/services/MeetingModeService.ts
+++ b/apps/desktop/src/main/services/MeetingModeService.ts
@@ -14,10 +14,7 @@ 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,
@@ -54,7 +51,6 @@ import {
applySpeakerLabels,
buildTranscriptFromSegments,
chunkTranscriptByLines,
- formatPyannoteSpeakerLabel,
formatTranscriptLines,
looksTruncatedRewrite,
parseTranscriptLines,
@@ -393,10 +389,6 @@ 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)
@@ -755,11 +747,7 @@ class MeetingModeService extends EventEmitter {
this._captionFailures.delete(snapshot.id)
this._clearLocalRecording(snapshot.id)
- 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) {
+ if (snapshot.pcm.length > 0) {
try {
const wavPath = meetingAudioFilePathSync(snapshot.id)
fs.mkdirSync(pathDirname(wavPath), { recursive: true })
@@ -1011,7 +999,27 @@ class MeetingModeService extends EventEmitter {
/** PCM16 버퍼를 WAV 파일로 저장 (16kHz mono 16-bit) */
private _saveWav(filePath: string, pcmBuffer: Buffer): void {
- const header = writeWavHeader16kMonoPcm16(Buffer.alloc(44), pcmBuffer.length)
+ 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)
// 헤더와 PCM 을 이어 붙이지 않고 따로 쓴다 — 3시간 회의면 concat 사본만 350MB 가 더 생긴다
const fd = fs.openSync(filePath, 'w')
@@ -1480,11 +1488,8 @@ class MeetingModeService extends EventEmitter {
maxTokens: REWRITE_CHUNK_MAX_TOKENS,
})
const rawText = carry ? stripEchoedContext(result.text, previousTail) : result.text.trim()
- // 교열(!carry)에서는 모델이 원문에 없던 시각·화자 표기를 붙였으면 지우고, 화자 구분(carry)에서는 화자 표기를 허용한다.
- const text = restoreProtectedQualifiers(
- chunk,
- stripInventedMarkers(chunk, rawText, { allowSpeakerMarkers: carry }),
- )
+ // 모델이 원문에 없던 시각·화자 표기를 붙였으면 지우고, 지운 한정 부사(거의 등)는 되돌린다.
+ const text = restoreProtectedQualifiers(chunk, stripInventedMarkers(chunk, rawText))
if (looksTruncatedRewrite(chunk, text)) {
throw new D3ROError(
failureCode,
@@ -1636,7 +1641,7 @@ ${excerpt.text}`
try {
const audioBuffer = fs.readFileSync(audioPath)
- const serverUrl = getLocalSTTService().sidecarBaseUrl ?? getSidecarBaseUrl(18765)
+ const serverUrl = `http://127.0.0.1:18765`
const formData = new FormData()
formData.append('audio', new Blob([audioBuffer]), 'audio.wav')
@@ -1670,7 +1675,7 @@ ${excerpt.text}`
const labeledLines = applySpeakerLabels(
parseTranscriptLines(transcript),
diarResult.segments,
- (raw) => formatPyannoteSpeakerLabel(raw),
+ (raw) => raw.replace('SPEAKER_', '화자 '),
)
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 ad8924cb..911fb194 100644
--- a/apps/desktop/src/main/services/OnlineLLMService.ts
+++ b/apps/desktop/src/main/services/OnlineLLMService.ts
@@ -7,7 +7,6 @@ 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 {
@@ -42,38 +41,35 @@ class OnlineLLMService extends EventEmitter {
return token
}
- private async _postOnlineRequest(
- endpoint: string,
- payload: Record,
- externalSignal?: AbortSignal
+ async processText(
+ text: string,
+ action: LLMAction,
+ targetLanguage?: string,
+ customPrompt?: string
): 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}${endpoint}`, {
+ const response = await fetch(`${apiUrl}/api/llm/generate`, {
signal: controller.signal,
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
- body: JSON.stringify(payload)
+ body: JSON.stringify({
+ prompt: text,
+ systemPrompt,
+ model: configGet('llmModelId') ?? 'd3ro-gpt4o-mini',
+ temperature: 0.7,
+ maxTokens: 2048
+ })
})
if (response.status === 401) {
@@ -91,11 +87,11 @@ class OnlineLLMService extends EventEmitter {
)
}
- const data = (await response.json()) as Partial | null
- if (typeof data?.text !== 'string' || data.text.trim().length === 0) {
+ const data = (await response.json()) as OnlineGenerateResponse
+ if (!data.text || !data.text.trim()) {
throw new D3ROError(ErrorCode.LLMProcessingFailed, 'Online LLM returned empty text')
}
- return data.text
+ return data.text.trim()
} catch (err) {
if (err instanceof D3ROError) throw err
if (controller.signal.aborted) {
@@ -106,48 +102,37 @@ 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; signal?: AbortSignal }
+ options?: { model?: string; temperature?: number }
): AsyncGenerator {
- 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 })),
+ 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 })),
model: options?.model ?? configGet('llmModelId') ?? 'd3ro-gpt4o-mini',
temperature: options?.temperature ?? 0.7
- },
- options?.signal
- )
- const restored = rehydrateText(rawText, redactedBatch.tokens)
- yield restored
- return restored
+ })
+ })
+
+ 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
}
cancelGeneration(): void {
@@ -167,7 +152,7 @@ class OnlineLLMService extends EventEmitter {
let instance: OnlineLLMService | null = null
export function resetOnlineLLMServiceForTests(): void {
- if (instance) instance.dispose()
+ if (instance) instance.removeAllListeners()
instance = null
}
diff --git a/apps/desktop/src/main/services/PersonalGraphService.ts b/apps/desktop/src/main/services/PersonalGraphService.ts
index 0eebf7d9..23ac7e6f 100644
--- a/apps/desktop/src/main/services/PersonalGraphService.ts
+++ b/apps/desktop/src/main/services/PersonalGraphService.ts
@@ -76,101 +76,82 @@ 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)
- const preparedSentences = sentences.map((sentence) => {
+ for (const sentence of sentences) {
const terms = extractTerms(sentence)
- return { sentence, terms, termsJson: JSON.stringify(terms) }
- })
-
- db.transaction((tx) => {
- for (const entry of preparedSentences) {
- tx.insert(personalPhrases)
- .values({
- id: crypto.randomUUID(),
- phrase: entry.sentence,
- count: 1,
- source: meta.source,
+ 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,
- createdAt: at,
- terms: entry.termsJson,
+ terms: JSON.stringify(terms),
appName: meta.appName ?? null
- })
- .onConflictDoUpdate({
- target: personalPhrases.phrase,
- set: {
- count: sql`${personalPhrases.count} + 1`,
- lastUsedAt: at,
- terms: entry.termsJson,
- appName: meta.appName ?? null
- }
- })
- .run()
+ }
+ })
+ .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)
- }
+ 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')
}
}
}
+ }
- // 같은 앱에서 직전 세션(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)
- }
- }
- })
-
+ // 같은 앱에서 직전 세션(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')
+ }
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',
- executor: Pick, 'insert'> = getDatabase(),
- now = Date.now()
- ): void {
- executor
- .insert(phraseEdges)
+ private _upsertEdge(from: string, to: string, kind: 'follows' | 'shares_terms'): void {
+ const db = getDatabase()
+ const now = Date.now()
+ db.insert(phraseEdges)
.values({
id: crypto.randomUUID(),
fromPhrase: from,
@@ -440,29 +421,26 @@ class PersonalGraphService {
runMaintenance(limit = MAINTENANCE_NODE_LIMIT): number {
try {
const db = getDatabase()
- const parsedNodes = db
- .select({ phrase: personalPhrases.phrase, terms: personalPhrases.terms })
+ const nodes = db
+ .select()
.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
- 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
- }
+ 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
}
- })
+ }
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 35ba1237..6e2455f9 100644
--- a/apps/desktop/src/main/services/ScreenContextService.ts
+++ b/apps/desktop/src/main/services/ScreenContextService.ts
@@ -16,7 +16,6 @@ import {
isTerminalHost,
type ForegroundWindowPort,
} from './foreground-window-port'
-import { sendWin32CopyChord } from '../utils/win32-unicode-input'
const logger = getLogger('screen-context')
@@ -44,8 +43,6 @@ export interface ScreenContextServiceDeps {
foreground?: ForegroundWindowPort
/** 복사 단축키 수정자 결정용 플랫폼 (기본: process.platform) */
platform?: NodeJS.Platform
- /** 네이티브 복사 단축키 주입기 (성공 시 true 반환하여 nut-js 로드를 생략) */
- sendCopyShortcut?: () => Promise
}
// ============================================================
@@ -57,16 +54,10 @@ 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)
}
/**
@@ -243,6 +234,7 @@ export class ScreenContextService {
* TextInsertService의 역방향: clipboard save → 복사 단축키 simulate → clipboard read → clipboard restore
*/
private async _captureSelectedText(): Promise {
+ const nut = await this._ensureNut()
const port = electronClipboardPort
// 1. 기존 클립보드 저장 + 온전히 되돌릴 수 있는지 판정 (삽입과 같은 정책)
@@ -258,14 +250,10 @@ export class ScreenContextService {
// 2. 클립보드 비우기 (이전 내용이 남아있으면 "선택 없음"을 감지할 수 없으므로)
port.clear()
- // 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)
- }
+ // 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)
// 4. 클립보드에 텍스트가 복사될 때까지 대기
await this._sleep(150)
diff --git a/apps/desktop/src/main/services/SuggestionService.ts b/apps/desktop/src/main/services/SuggestionService.ts
index 7a8c62d1..e2b06f94 100644
--- a/apps/desktop/src/main/services/SuggestionService.ts
+++ b/apps/desktop/src/main/services/SuggestionService.ts
@@ -15,6 +15,7 @@ import {
COMPOSING_IDLE_MULTIPLIER,
isAppScopedLearning,
SUGGESTION_DEFAULTS,
+ SUGGESTION_MAX_OUTPUT_CHARS,
buildLocalSuggestionCandidateEntries,
decideInFlightGeneration,
decideSuggestion,
@@ -27,6 +28,7 @@ import {
selectPhraseHints,
shouldPersistSuggestionPrefix,
isTerminalApp,
+ extractTerminalPromptPrefix,
type AnchorKind,
type PhysicalRect,
type SuggestionCandidate,
@@ -37,7 +39,7 @@ import {
type SuggestionState,
type SuggestionStep
} from '@d3ro/core/input-intelligence'
-import { buildQueryTerms } from '@d3ro/core/personal-graph'
+import { buildQueryTerms, scoreCandidatePersonalization } 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'
@@ -65,17 +67,6 @@ 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'
@@ -112,6 +103,17 @@ 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
@@ -141,7 +143,16 @@ export function createDefaultSuggestionServiceDeps(): SuggestionServiceDeps {
}
}
-type PolicyConfig = SuggestionPolicyConfig
+/** 설정에서 읽은 정책 값 (SSOT 기본값과 상한 적용 후). */
+interface PolicyConfig {
+ triggerDelayMs: number
+ minPrefixChars: number
+ maxRequestsPerMinute: number
+ dailyBudget: number
+ maxCandidates: number
+ maxChars: number
+ excludedApps: string[]
+}
export interface SuggestionRequestResult {
ok: boolean
@@ -222,6 +233,25 @@ 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
/** "제안 사항 없음" 을 보여 주는 시간 */
@@ -965,13 +995,38 @@ export class SuggestionService extends EventEmitter {
* (끝에서 치거나 지움) 커서는 입력 줄 끝이다. 중간을 고친 모양이면 다음 입력까지 막는다.
*/
private _terminalContext(input: TypingContext): TypingContext {
- const { context, nextState } = resolveTerminalTypingContext(input, {
- lastPrompt: this._lastTerminalPrompt,
- promptTyped: this._terminalPromptTyped
- })
- this._lastTerminalPrompt = nextState.lastPrompt
- this._terminalPromptTyped = nextState.promptTyped
- return context
+ 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
+ }
}
/** 로컬 기억은 모델과 무관하다 — 같은 정책을 "모델 있음 · 표시 없음" 으로 평가한다. */
@@ -1549,7 +1604,13 @@ export class SuggestionService extends EventEmitter {
if (!this._typoProposer) return null
try {
const plan = await this._typoProposer.propose(context, signal, { thorough })
- return toSuggestionCorrectionFromPlan(context.prefix, plan) ?? null
+ 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 }))
+ }
} catch (error) {
logger.debug(`제안용 오타 교정 실패 — 교정 없이 제안한다: ${error instanceof Error ? error.message : String(error)}`)
return null
@@ -1659,13 +1720,30 @@ 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) {
- this._candidates = rerankFilledCandidates(this._candidates, candidate.text, {
+ const personalContext = {
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()
@@ -1713,7 +1791,15 @@ export class SuggestionService extends EventEmitter {
/** 정규화 후 완전 중복이거나 기존 후보의 접두/확장이면 중복으로 본다. */
private _isDuplicateCandidate(candidate: string): boolean {
- return isDuplicateCandidateText(candidate, this._candidates)
+ 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)
+ )
+ })
}
/**
@@ -1747,9 +1833,17 @@ export class SuggestionService extends EventEmitter {
/** 판단 입력을 서명이 바뀔 때만 남긴다. */
private _logDecisionInputs(context: TypingContext): void {
- const modelAvailable = getLocalLLMService().isAvailable()
- const enabled = this.isEnabled()
- const signature = buildDecisionInputSignature(context, { modelAvailable, enabled })
+ const signature = [
+ context.available,
+ context.isEditable,
+ context.isPassword,
+ context.isComposing,
+ context.anchor ? 'A' : '-',
+ context.editedSinceFocus,
+ context.typedRecently,
+ getLocalLLMService().isAvailable(),
+ this.isEnabled()
+ ].join('|')
if (signature === this._lastDecisionSignature) return
this._lastDecisionSignature = signature
@@ -1757,8 +1851,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=${enabled} ` +
- `model=${modelAvailable} anchor=${context.anchor ? 'yes' : 'no'}`
+ `app=${context.appName ?? '-'} enabled=${this.isEnabled()} ` +
+ `model=${getLocalLLMService().isAvailable()} anchor=${context.anchor ? 'yes' : 'no'}`
)
}
@@ -2234,13 +2328,24 @@ export class SuggestionService extends EventEmitter {
// ── 내부 ──────────────────────────────────────────────
private readPolicyConfig(): PolicyConfig {
- return normalizeSuggestionPolicyConfig({
- triggerDelayMs: configGet('suggestionTriggerDelayMs'),
- minPrefixChars: configGet('suggestionMinPrefixChars'),
- maxRequestsPerMinute: configGet('suggestionMaxRequestsPerMinute'),
- dailyBudget: configGet('suggestionDailyBudget'),
- excludedApps: configGet('inputExcludedApps')
- })
+ 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')]
+ }
}
/**
diff --git a/apps/desktop/src/main/services/UnifiedSearchService.ts b/apps/desktop/src/main/services/UnifiedSearchService.ts
index 74a139fe..88af554b 100644
--- a/apps/desktop/src/main/services/UnifiedSearchService.ts
+++ b/apps/desktop/src/main/services/UnifiedSearchService.ts
@@ -1,14 +1,8 @@
-// 기록과 회의를 FTS5 trigram 역색인(3자 이상) + 정확한 부분 문자열 검증으로 함께 찾는 로컬 통합 검색.
+// 기록과 회의를 스키마 변경 없이 함께 찾는 로컬 통합 검색.
import { EventEmitter } from 'events'
-import { and, count, desc, inArray, or, sql } from 'drizzle-orm'
+import { count, desc, inArray, or } 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,
@@ -27,19 +21,18 @@ 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 (!isRecord(value)) {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new D3ROError(ErrorCode.ConfigInvalidValue, 'Unified search parameters are required')
}
- const candidate = value
+ const candidate = value as Record
if (typeof candidate.query !== 'string') {
throw new D3ROError(ErrorCode.ConfigInvalidValue, 'Unified search query must be a string', {
field: 'query',
@@ -63,45 +56,32 @@ export function normalizeUnifiedSearchQuery(value: string): string {
return value.slice(0, MAX_QUERY_LENGTH).trim().replace(/\s+/g, ' ')
}
-/**
- * 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('"', '""')}"`
+function includesQuery(value: string | null | undefined, query: string): boolean {
+ return value?.toLocaleLowerCase().includes(query.toLocaleLowerCase()) === true
}
-interface SqliteMasterClient {
- prepare?: (sql: string) => { all: (...args: unknown[]) => Array<{ name: string }> }
-}
+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
-const REQUIRED_FTS_TABLES = [
- 'history_fts',
- 'meeting_sessions_fts',
- 'meeting_memos_fts',
-] as const
+ const matchAt = text.toLocaleLowerCase().indexOf(query.toLocaleLowerCase())
+ if (matchAt < 0) return `${text.slice(0, maxLength - 1).trimEnd()}…`
-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
- }
+ 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 recordResult(row: History, query: string): UnifiedSearchResult {
- const titleMatched = includesSearchQuery(row.title, query)
+ const titleMatched = includesQuery(row.title, query)
const matchingContent = [row.polishedText, row.originalText, row.summaryText]
- .find((value) => includesSearchQuery(value, query))
+ .find((value) => includesQuery(value, query))
const displayContent = matchingContent ?? row.polishedText ?? row.originalText ?? row.summaryText ?? row.title
return {
@@ -120,7 +100,7 @@ function findMatchingTranscriptSegmentSnippet(
): string | null {
const lines = parseTranscriptLines(transcript)
for (const line of lines) {
- if (includesSearchQuery(line.text, query) || includesSearchQuery(line.speaker, query)) {
+ if (includesQuery(line.text, query) || includesQuery(line.speaker, query)) {
if (!line.timed) return line.text
const speakerPrefix = line.speaker ? `[${line.speaker}] ` : ''
return `[${formatTranscriptTimestamp(line.timestampMs)}] ${speakerPrefix}${line.text}`
@@ -138,9 +118,9 @@ function meetingResult(
query: string,
memoMatch?: MeetingMemoRow,
): UnifiedSearchResult {
- const titleMatched = includesSearchQuery(row.title, query)
+ const titleMatched = includesQuery(row.title, query)
const matchingTranscript = [row.editedTranscript, row.rawTranscript]
- .find((value) => includesSearchQuery(value, query))
+ .find((value) => includesQuery(value, query))
const segmentSnippet = findMatchingTranscriptSegmentSnippet(
matchingTranscript ?? row.editedTranscript ?? row.rawTranscript,
query,
@@ -171,78 +151,14 @@ function meetingResult(
}
}
-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,
+export function mergeUnifiedSearchResults(
+ records: readonly UnifiedSearchResult[],
+ meetings: readonly UnifiedSearchResult[],
limit: number,
- 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 }
+): UnifiedSearchResult[] {
+ return [...records, ...meetings]
+ .sort((left, right) => right.occurredAt - left.occurredAt || left.id.localeCompare(right.id))
+ .slice(0, limit)
}
class UnifiedSearchService extends EventEmitter {
@@ -255,51 +171,73 @@ class UnifiedSearchService extends EventEmitter {
try {
const db = getDatabase()
const pattern = containsPattern(query)
- 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 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 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 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 memoBySessionId = new Map()
- for (const memo of queryRows.memoRows) {
+ for (const memo of 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(
- queryRows.recordRows.map((row) => recordResult(row, query)),
- queryRows.meetingRows.map((row) => meetingResult(row, query, memoBySessionId.get(row.id))),
+ recordRows.map((row) => recordResult(row, query)),
+ combinedMeetingRows.map((row) => meetingResult(row, query, memoBySessionId.get(row.id))),
limit,
)
return {
query,
results,
- total: queryRows.recordTotal + queryRows.meetingTotal,
+ total: recordTotal + meetingTotal + memoMatchedMeetings.length,
}
} 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 19f0a478..aa73893e 100644
--- a/apps/desktop/src/main/services/VoiceModeService.ts
+++ b/apps/desktop/src/main/services/VoiceModeService.ts
@@ -31,7 +31,6 @@ 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'
@@ -888,7 +887,7 @@ class VoiceModeService extends EventEmitter {
const merged = Buffer.concat(run.audioBuffer)
run.lastAudio = merged // WAV 저장용 (run 소유)
- secureWipeAudioChunks(run.audioBuffer)
+ run.audioBuffer = []
run.audioBufferBytes = 0
// Bug 13: 너무 짧은 오디오는 STT 호출 전에 에러 피드백.
@@ -1248,9 +1247,6 @@ 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 d9024b5a..05fda5f2 100644
--- a/apps/desktop/src/main/services/ads/AdMediationEngine.ts
+++ b/apps/desktop/src/main/services/ads/AdMediationEngine.ts
@@ -11,8 +11,16 @@ 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'
@@ -32,7 +40,15 @@ export class AdMediationEngine {
// integrated. No adapter may fabricate a bid or creative.
const adapterList: IAdNetworkAdapter[] = [
new DirectHouseSponsorAdapter(),
- ...createUnavailableAdAdapters(),
+ new PlaywireAdapter(),
+ new EthicalAdsAdapter(),
+ new CarbonAdsAdapter(),
+ new UnityAdsAdapter(),
+ new AppLovinAdapter(),
+ new GoogleAdManagerAdapter(),
+ new InMobiAdapter(),
+ new PubMaticAdapter(),
+ new MintegralAdapter(),
]
for (const adapter of adapterList) {
@@ -136,15 +152,12 @@ 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) => {
- bidTimer = setTimeout(() => reject(new Error('Bid Timeout')), timeoutMs)
- }),
- ]).finally(() => {
- if (bidTimer !== undefined) clearTimeout(bidTimer)
- })
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('Bid Timeout')), timeoutMs)
+ ),
+ ])
if (
bidResult.hasBid
diff --git a/apps/desktop/src/main/services/ads/AppLovinAdapter.ts b/apps/desktop/src/main/services/ads/AppLovinAdapter.ts
new file mode 100644
index 00000000..443a1da8
--- /dev/null
+++ b/apps/desktop/src/main/services/ads/AppLovinAdapter.ts
@@ -0,0 +1,12 @@
+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
new file mode 100644
index 00000000..394e2a27
--- /dev/null
+++ b/apps/desktop/src/main/services/ads/CarbonAdsAdapter.ts
@@ -0,0 +1,7 @@
+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
new file mode 100644
index 00000000..616a1305
--- /dev/null
+++ b/apps/desktop/src/main/services/ads/EthicalAdsAdapter.ts
@@ -0,0 +1,7 @@
+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
new file mode 100644
index 00000000..7b061c09
--- /dev/null
+++ b/apps/desktop/src/main/services/ads/GoogleAdManagerAdapter.ts
@@ -0,0 +1,12 @@
+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
new file mode 100644
index 00000000..d065bbd5
--- /dev/null
+++ b/apps/desktop/src/main/services/ads/InMobiAdapter.ts
@@ -0,0 +1,7 @@
+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
new file mode 100644
index 00000000..d20c4b6e
--- /dev/null
+++ b/apps/desktop/src/main/services/ads/MintegralAdapter.ts
@@ -0,0 +1,7 @@
+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
new file mode 100644
index 00000000..d5fec5fb
--- /dev/null
+++ b/apps/desktop/src/main/services/ads/PlaywireAdapter.ts
@@ -0,0 +1,12 @@
+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
new file mode 100644
index 00000000..18bb5c83
--- /dev/null
+++ b/apps/desktop/src/main/services/ads/PubMaticAdapter.ts
@@ -0,0 +1,7 @@
+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 419c26ba..b742113d 100644
--- a/apps/desktop/src/main/services/ads/UnavailableAdAdapter.ts
+++ b/apps/desktop/src/main/services/ads/UnavailableAdAdapter.ts
@@ -1,70 +1,6 @@
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
@@ -99,15 +35,3 @@ 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
new file mode 100644
index 00000000..ce3a3395
--- /dev/null
+++ b/apps/desktop/src/main/services/ads/UnityAdsAdapter.ts
@@ -0,0 +1,7 @@
+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 62ed3f3f..b338e294 100644
--- a/apps/desktop/src/main/services/dictionary/dictionary-file-codec.ts
+++ b/apps/desktop/src/main/services/dictionary/dictionary-file-codec.ts
@@ -2,8 +2,6 @@
// 사전 내보내기/가져오기 파일 형식(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'
@@ -18,6 +16,56 @@ 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]
@@ -86,7 +134,9 @@ function parseJson(raw: string): Array> {
} else {
throw new Error('expected an array or an object with an "entries" array')
}
- return (list as unknown[]).filter(isRecord)
+ return (list as unknown[]).filter(
+ (item): item is Record => !!item && typeof item === 'object'
+ )
}
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 a7475026..7807e512 100644
--- a/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts
+++ b/apps/desktop/src/main/services/meeting/MeetingRecordingSession.ts
@@ -11,7 +11,6 @@
// Electron·DB 를 모른다. 자막/오디오는 포트로 받는다(테스트는 가짜 포트).
import type { CaptionSegment, MeetingMemo } from '@d3ro/core/types'
-import type { RecordingAudioSinkPort } from './disk-wav-audio-sink'
/** 자막 엔진(CaptionService)에 대한 최소 계약 */
export interface RecordingCaptionPort {
@@ -31,8 +30,6 @@ export interface RecordingAudioPort {
export interface MeetingRecordingSessionPorts {
caption: RecordingCaptionPort
audio: RecordingAudioPort
- /** 디스크 스트리밍 싱크 — 주입 시 PCM 을 메모리에 쌓지 않고 임시 파일로 곧장 기록한다 */
- audioSink?: RecordingAudioSinkPort
now?: () => number
/** 세그먼트가 이 녹음에 추가될 때(구독으로 받은 것만) */
onSegment?: (segment: CaptionSegment) => void
@@ -40,8 +37,6 @@ export interface MeetingRecordingSessionPorts {
onSegmentUpdated?: (update: { id: string; text: string }) => void
/** 자막 정지 실패 — 정지는 계속 진행된다(스냅샷은 그때까지의 세그먼트로 만든다) */
onStopError?: (error: unknown) => void
- /** 디스크 스트리밍 쓰기/마무리 오류 — 전사 저장을 막지 않고 경고만 남긴다 */
- onAudioSinkError?: (error: unknown) => void
}
/** 정지 시점의 불변 스냅샷 — 후처리·저장은 이것만 읽는다 */
@@ -52,12 +47,8 @@ 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 {
@@ -65,7 +56,6 @@ 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
@@ -103,18 +93,7 @@ export class MeetingRecordingSession {
if (this._unsubscribeAudio || this._stopPromise) return
this._unsubscribeAudio = this._ports.audio.onChunk((buffer) => {
this._lastRms = this._measureLevel(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))
- }
+ this._audio.push(Buffer.from(buffer))
})
}
@@ -126,9 +105,6 @@ export class MeetingRecordingSession {
this._unsubscribeSegmentUpdated = null
this._unsubscribeAudio?.()
this._unsubscribeAudio = null
- if (!this._stopPromise) {
- this._ports.audioSink?.discard()
- }
}
get isStopping(): boolean {
@@ -212,31 +188,6 @@ 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,
@@ -244,9 +195,7 @@ 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,
- audioSavedToDisk,
- pcmByteLength,
+ pcm: includeAudio && this._audio.length > 0 ? Buffer.concat(this._audio) : Buffer.alloc(0),
})
}
}
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
deleted file mode 100644
index 40cc1dda..00000000
--- a/apps/desktop/src/main/services/meeting/disk-wav-audio-sink.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-// 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 f72b3f63..25bab764 100644
--- a/apps/desktop/src/main/services/rag/chunk-store.ts
+++ b/apps/desktop/src/main/services/rag/chunk-store.ts
@@ -1,15 +1,11 @@
// src/main/services/rag/chunk-store.ts
-// 지식 문서·청크 저장소 포트와 SQLite(drizzle) 구현.
-// 임베딩은 Float32 바이너리 BLOB 으로 직렬화하고 DB 인스턴스별 WeakMap 에 캐시해 질의 시 JSON.parse 를 0회로 줄인다.
+// 지식 문서·청크 저장소 포트와 SQLite(drizzle) 구현. RAGService는 getDatabase()를 직접 부르지 않는다.
-import { asc, eq, isNotNull, ne, or, sql } from 'drizzle-orm'
-import { getDatabase, isDatabaseOpen } from '../../db'
+import { asc, eq } from 'drizzle-orm'
+import { getDatabase } 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 {
@@ -19,8 +15,6 @@ export interface StoredChunk {
/** JSON 직렬화 float[]. 아직 임베딩하지 않았으면 빈 문자열. */
embedding: string
chunkIndex: number
- /** 디코딩된 Float32 벡터 (listEmbeddedChunks 캐시에서 채워진다) */
- vector?: Float32Array
}
export interface ChunkStore {
@@ -42,68 +36,6 @@ export interface ChunkStore {
counts(): { documentCount: number; totalChunks: number }
}
-/** DB 인스턴스(계정별·테스트별)마다 자동 격리되는 임베딩 청크 메모리 캐시 */
-const embeddedChunksCache = new WeakMap
@@ -234,19 +219,15 @@ function Shell(): React.ReactElement {
-
- {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' })}
- />
- )}
-
+ setLicenseModalOpen(false)} />
+ setOnboardingOpen(false)} />
+ setSupportModalOpen(false)} />
+ setOllamaGuideOpen(false)} />
+ 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 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
- }
+ const r = await window.electronAPI.cloudSync.getState()
+ if (r.success) setState(r.data)
}, [])
// 초기 상태 로드 + 이벤트 구독
useEffect(() => {
- mountedRef.current = true
- let cancelled = false
void refreshState()
- void window.electronAPI.config
- .get({ key: 'cloudSyncAudio' })
- .then((r) => {
- if (!cancelled && r.success) setAudioSync(r.data !== false)
- })
- .catch(() => {})
+ void window.electronAPI.config.get({ key: 'cloudSyncAudio' }).then((r) => {
+ if (r.success) setAudioSync(r.data !== false)
+ })
const unsubAuth = window.electronAPI.cloudSync.onAuthChanged(() => {
void refreshState()
@@ -73,8 +60,6 @@ export function CloudSyncSection(): React.ReactElement {
void refreshState()
})
return () => {
- cancelled = true
- mountedRef.current = false
unsubAuth()
unsubComplete()
unsubError()
@@ -91,16 +76,13 @@ 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 {
- if (mountedRef.current) setBusy(false)
+ setBusy(false)
}
}
@@ -108,14 +90,10 @@ export function CloudSyncSection(): React.ReactElement {
setBusy(true)
try {
await window.electronAPI.cloudSync.signOut()
- if (mountedRef.current) setInfo(t('cloudSync.signedOut'))
- } catch {
- // ignore sign-out IPC rejection
+ setInfo(t('cloudSync.signedOut'))
} finally {
- if (mountedRef.current) {
- setBusy(false)
- void refreshState()
- }
+ setBusy(false)
+ void refreshState()
}
}
@@ -127,19 +105,14 @@ 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 {
- if (mountedRef.current) {
- setBusy(false)
- void refreshState()
- }
+ setBusy(false)
+ void refreshState()
}
}
diff --git a/apps/desktop/src/renderer/components/CodexOAuthGuideModal.tsx b/apps/desktop/src/renderer/components/CodexOAuthGuideModal.tsx
index ae80c05d..2d8bf22b 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 { useEffect, useRef, useState } from 'react'
+import { useState } from 'react'
import {
Dialog,
DialogTitle,
@@ -78,25 +78,11 @@ 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) => {
- void navigator.clipboard.writeText(text).catch(() => {})
+ navigator.clipboard.writeText(text)
setCopied(true)
- if (copyTimerRef.current) clearTimeout(copyTimerRef.current)
- copyTimerRef.current = setTimeout(() => {
- copyTimerRef.current = null
- setCopied(false)
- }, 2000)
+ setTimeout(() => 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 7906321b..6c56c9a3 100644
--- a/apps/desktop/src/renderer/components/FileDropZone.tsx
+++ b/apps/desktop/src/renderer/components/FileDropZone.tsx
@@ -28,16 +28,6 @@ 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) => {
@@ -146,13 +136,9 @@ export function FileDropZone(): React.ReactElement {
const handleCopy = useCallback(() => {
if (result?.fullText) {
- void navigator.clipboard.writeText(result.fullText).catch(() => {})
+ navigator.clipboard.writeText(result.fullText)
setCopied(true)
- if (copyTimerRef.current) clearTimeout(copyTimerRef.current)
- copyTimerRef.current = setTimeout(() => {
- copyTimerRef.current = null
- setCopied(false)
- }, 2000)
+ setTimeout(() => setCopied(false), 2000)
}
}, [result])
diff --git a/apps/desktop/src/renderer/components/OllamaGuideModal.tsx b/apps/desktop/src/renderer/components/OllamaGuideModal.tsx
index eb04c935..2349c317 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, useRef } from 'react'
+import { useState, useEffect, useCallback } from 'react'
import {
Dialog,
DialogTitle,
@@ -52,25 +52,11 @@ 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(() => {
- void navigator.clipboard.writeText(code).catch(() => {})
+ navigator.clipboard.writeText(code)
setCopied(true)
- if (copyTimerRef.current) clearTimeout(copyTimerRef.current)
- copyTimerRef.current = setTimeout(() => {
- copyTimerRef.current = null
- setCopied(false)
- }, 2000)
+ setTimeout(() => setCopied(false), 2000)
}, [code])
return (
@@ -129,45 +115,24 @@ 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 {
- if (isFresh()) setChecking(false)
+ setChecking(false)
}
}, [])
@@ -202,27 +167,20 @@ 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'))
- if (startTimerRef.current) clearTimeout(startTimerRef.current)
- startTimerRef.current = setTimeout(() => {
- startTimerRef.current = null
- if (mountedRef.current) void refreshStatus()
- }, 2000)
+ setTimeout(() => 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 {
- if (mountedRef.current) setStarting(false)
+ setStarting(false)
}
}, [refreshStatus, t])
diff --git a/apps/desktop/src/renderer/components/OnboardingModal.tsx b/apps/desktop/src/renderer/components/OnboardingModal.tsx
index 0948322b..43cd20c3 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, useRef } from 'react'
+import { useState, useEffect, useCallback } from 'react'
import {
Dialog,
DialogTitle,
@@ -139,58 +139,32 @@ 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 {
- if (mountedRef.current && ollamaSeqRef.current === seq) setCheckingOllama(false)
+ setCheckingOllama(false)
}
}, [])
useEffect(() => {
- 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
- }
+ window.electronAPI.config.getAll().then((res) => {
+ if (!res.success) return
+ setOnboardingCompleted(res.data.onboardingCompleted)
+ if (!res.data.onboardingCompleted) {
+ setInternalOpen(true)
+ setPhase('select_mode')
+ }
+ })
}, [])
// 모델 받기 — 받기에 성공한 경우에만 활성 모델로 저장 (autoSelect)
@@ -218,17 +192,10 @@ 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()
- if (!mountedRef.current) return
- if (ollamaTimerRef.current) clearTimeout(ollamaTimerRef.current)
- ollamaTimerRef.current = setTimeout(() => {
- ollamaTimerRef.current = null
- if (mountedRef.current) void checkOllama()
- }, 1500)
+ setTimeout(() => checkOllama(), 1500)
}
const handleStartOllama = async () => {
@@ -236,27 +203,20 @@ 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'))
- if (ollamaTimerRef.current) clearTimeout(ollamaTimerRef.current)
- ollamaTimerRef.current = setTimeout(() => {
- ollamaTimerRef.current = null
- if (mountedRef.current) void checkOllama()
- }, 2000)
+ setTimeout(() => 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 {
- if (mountedRef.current) setStartingOllama(false)
+ setStartingOllama(false)
}
}
diff --git a/apps/desktop/src/renderer/components/ProBadge.tsx b/apps/desktop/src/renderer/components/ProBadge.tsx
new file mode 100644
index 00000000..4eb778a6
--- /dev/null
+++ b/apps/desktop/src/renderer/components/ProBadge.tsx
@@ -0,0 +1,65 @@
+// src/renderer/components/ProBadge.tsx
+// Feature gate badge: renders children normally if unlocked,
+// shows lock overlay with PRO badge if locked.
+// v4(2026-09-28): 덮개는 키보드로도 누를 수 있는 버튼. 모노 글꼴·강조색 글자 제거 — 잠김은 강조가 아니다.
+
+import { Box, ButtonBase, Typography } from '@mui/material'
+import { Lock } from 'lucide-react'
+import { d3roPalette, d3roRadius, d3roTransition, typoSx } from '@d3ro/ui/theme'
+import { useProFeature } from '../hooks/useProFeature'
+import { useI18n } from '@d3ro/i18n'
+import type { Feature } from '@d3ro/core/types'
+
+interface ProBadgeProps {
+ feature: Feature
+ children: React.ReactNode
+}
+
+export function ProBadge({ feature, children }: ProBadgeProps): React.ReactElement {
+ const { t } = useI18n()
+ const { unlocked, loading, showUpgrade } = useProFeature(feature)
+
+ // While loading or if unlocked, render children normally
+ if (loading || unlocked) {
+ return <>{children}>
+ }
+
+ return (
+
+ {/* 잠긴 내용은 흐리게, 조작 불가 */}
+
+ {children}
+
+
+
+
+
+
+ {t('license.pro.required')}
+
+
+
+
+ )
+}
diff --git a/apps/desktop/src/renderer/components/SettingsModal.tsx b/apps/desktop/src/renderer/components/SettingsModal.tsx
index d6411932..8c5b45d9 100644
--- a/apps/desktop/src/renderer/components/SettingsModal.tsx
+++ b/apps/desktop/src/renderer/components/SettingsModal.tsx
@@ -3,22 +3,37 @@
// open 은 "이 화면이 현재 보이는가" — 보일 때만 설정·장치·모델을 불러온다. onClose 는 이전 화면으로 돌아간다.
// 본문 문법: 구획(h3 + 1px 선) 안에 설정 행(왼쪽 라벨·설명, 오른쪽 컨트롤) — settings/SettingsRows.
-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 { 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 { LicenseTab } from './LicenseTab'
import { CloudSyncSection } from './CloudSyncSection'
import { STTTab } from './STTTab'
+import { CaptionModelSelect } from './CaptionModelSelect'
import { InputConsentPanel } from './input-insights/InputConsentPanel'
-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 { 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 type { Locale } from '@d3ro/i18n'
-import { auditKeyBindingMap } from '@d3ro/core/keybinding'
-import type { AppConfig, AudioDevice, LLMModel, LLMStatus, STTModel } from '@d3ro/core/types'
+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 { useKeyBindingMap } from '../hooks/useKeyBindingMap'
import { DEFAULT_SETTINGS_TAB, SETTINGS_TAB_ORDER } from '../navigation/settingsTabs'
import type { SettingsTabId } from '../navigation/settingsTabs'
@@ -40,12 +55,45 @@ function TabPanel({ children, value, tab }: TabPanelProps): React.ReactElement |
return {children}
}
-export function SettingsModal({
- open,
- initialTab = DEFAULT_SETTINGS_TAB,
- onClose
-}: SettingsModalProps): React.ReactElement {
- const { t, setLocale } = useI18n()
+/** 행 오른쪽 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()
const [activeTab, setActiveTab] = useState(initialTab)
const tabMeta = useMemo>(
() => ({
@@ -56,9 +104,9 @@ export function SettingsModal({
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)
@@ -79,8 +127,7 @@ export function SettingsModal({
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)
})
@@ -93,68 +140,26 @@ export function SettingsModal({
}
}, [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([])
- 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])
+ if (!open) return
+ window.electronAPI.stt.getModels().then((res) => {
+ if (res.success && res.data) setDownloadedSttModels(res.data.filter((m) => m.downloaded))
+ })
+ }, [open])
+ // Ollama 상태 — null 은 "아직 조회하지 않음"(연결됨/오프라인으로 단정하지 않는다)
const [ollamaStatus, setOllamaStatus] = useState(null)
const [ollamaModels, setOllamaModels] = useState([])
const [checkingOllama, setCheckingOllama] = useState(false)
@@ -162,63 +167,46 @@ export function SettingsModal({
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 {
- if (mountedRef.current && ollamaSeqRef.current === seq) {
- setCheckingOllama(false)
- }
+ setCheckingOllama(false)
}
}, [])
+ // 설정 로드
useEffect(() => {
if (!open) return
- let cancelled = false
setLoading(true)
- void refreshOllama()
+ 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)
})
- .catch(() => {})
- .finally(() => {
- if (!cancelled) setLoading(false)
- })
+ .finally(() => setLoading(false))
Promise.all([
window.electronAPI.audio.getDevices(),
- 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(() => {})
+ window.electronAPI.audio.getSelectedDevice(),
+ ]).then(([devicesResult, selectedResult]) => {
+ if (devicesResult.success) setAudioDevices(devicesResult.data)
+ if (selectedResult.success && selectedResult.data) setSelectedDeviceId(selectedResult.data)
+ })
- return () => {
- cancelled = true
- }
}, [open, refreshOllama])
- const updateConfig = useCallback((key: K, value: AppConfig[K]) => {
+ const updateConfig = useCallback((key: keyof AppConfig, value: AppConfig[keyof AppConfig]) => {
setConfig((prev) => ({ ...prev, [key]: value }))
window.electronAPI.config.set({ key, value })
}, [])
@@ -228,107 +216,60 @@ export function SettingsModal({
void window.electronAPI.keybinding.setEnabled({ enabled })
}, [])
- 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 handleLanguageChange = useCallback((newLocale: string) => {
+ setLocale(newLocale as Locale)
+ setConfig((prev) => ({ ...prev, language: newLocale }))
+ }, [setLocale])
const handleMicTest = useCallback(async () => {
if (micTesting) {
- cleanupMicTest(true)
+ // 메인 프로세스 캡처까지 실제로 중지 — done 이벤트가 구독 해제를 마무리
+ await window.electronAPI.audio.stopTest()
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()
}
})
- 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)
- }
+ const result = await window.electronAPI.audio.testDevice({ deviceId: selectedDeviceId })
+ if (!result.success) {
+ setMicTesting(false)
+ setMicLevel(0)
+ setMicTestFailed(true)
+ unsub()
}
- }, [micTesting, selectedDeviceId, cleanupMicTest])
+ }, [micTesting, selectedDeviceId])
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') })
- if (ollamaRefreshTimerRef.current) clearTimeout(ollamaRefreshTimerRef.current)
- ollamaRefreshTimerRef.current = setTimeout(() => {
- ollamaRefreshTimerRef.current = null
- if (mountedRef.current) void refreshOllama()
- }, 2000)
+ setTimeout(() => 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 {
- if (mountedRef.current) setStartingOllama(false)
+ 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 (
@@ -337,122 +278,673 @@ export function SettingsModal({
)
}
+ 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={
+ <>
+ }
+ onClick={refreshOllama}
+ disabled={checkingOllama}
+ >
+ {t('settings.llm.checkConnection')}
+
+ {ollamaStatus !== null && !ollamaConnected && (
+ }
+ onClick={handleStartOllama}
+ disabled={startingOllama}
+ >
+ {startingOllama ? t('settings.llm.startingOllama') : t('settings.llm.startOllama')}
+
+ )}
+ >
+ }
+ >
+ {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 98677ed4..25a3cd4f 100644
--- a/apps/desktop/src/renderer/components/TemplateSection.tsx
+++ b/apps/desktop/src/renderer/components/TemplateSection.tsx
@@ -41,34 +41,17 @@ 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)
- 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)
- }
+ 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)
}, [])
- useEffect(() => {
- mountedRef.current = true
- void loadData()
- return () => {
- mountedRef.current = false
- }
- }, [loadData])
+ useEffect(() => { loadData() }, [loadData])
// 다른 기기에서 바뀐 템플릿이 반영되면 다시 불러온다.
useEffect(
diff --git a/apps/desktop/src/renderer/components/TitleBar.tsx b/apps/desktop/src/renderer/components/TitleBar.tsx
index efe86210..e4e4fdd9 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, useRef } from 'react'
+import { useState, useEffect, useCallback } from 'react'
import { Box } from '@mui/material'
import { Minus, Square, Copy, X } from 'lucide-react'
import { d3roPalette, d3roRadius } from '@d3ro/ui/theme'
@@ -15,38 +15,16 @@ 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(() => {
- 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
- }
- }
+ window.electronAPI.window.isMaximized().then((r) => { if (r.success) setIsMaximized(r.data) })
}, [])
const handleMaximize = useCallback(() => {
window.electronAPI.window.maximize()
// 토글 후 상태 재조회 (이벤트 채널이 없어 폴링 1회)
- 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(() => {})
+ setTimeout(() => {
+ window.electronAPI.window.isMaximized().then((r) => { if (r.success) setIsMaximized(r.data) })
}, 120)
}, [])
diff --git a/apps/desktop/src/renderer/components/ads/AdBanner.tsx b/apps/desktop/src/renderer/components/ads/AdBanner.tsx
index ce19f417..ecbf71b7 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, useRef } from 'react'
+import React, { useState, useEffect, useCallback } from 'react'
import { Box, Typography, Button, Link } from '@mui/material'
import { ExternalLink } from 'lucide-react'
import { d3roPalette, d3roRadius, typoSx } from '@d3ro/ui/theme'
@@ -19,16 +19,10 @@ 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 () => {
- const seq = ++auctionSeqRef.current
- if (tier !== 'free') {
- setCreative(null)
- return
- }
+ if (tier !== 'free') return
setCreative(null)
try {
if (window.electronAPI?.ads?.requestAuction) {
@@ -37,7 +31,6 @@ 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
@@ -51,30 +44,16 @@ export function AdBanner({ tier, onUpgrade }: AdBannerProps): React.ReactElement
}
}
} catch {
- if (mountedRef.current && auctionSeqRef.current === seq) setCreative(null)
+ setCreative(null)
}
}, [tier])
useEffect(() => {
- mountedRef.current = true
- if (tier !== 'free') {
- auctionSeqRef.current += 1
- setCreative(null)
- return () => {
- mountedRef.current = false
- }
- }
- void fetchAdAuction()
+ fetchAdAuction()
// Auto-refresh ad creative every 45s for free tier
- const interval = setInterval(() => {
- void fetchAdAuction()
- }, 45000)
- return () => {
- mountedRef.current = false
- auctionSeqRef.current += 1
- clearInterval(interval)
- }
- }, [fetchAdAuction, tier])
+ const interval = setInterval(fetchAdAuction, 45000)
+ return () => clearInterval(interval)
+ }, [fetchAdAuction])
// 유료 등급(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 5639bcbf..b49aed30 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, useRef } from 'react'
+import React, { useState, useEffect, useCallback } 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,13 +27,8 @@ 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)
@@ -44,7 +39,6 @@ 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)
@@ -59,37 +53,24 @@ export function RewardedQuotaModal({
return
}
}
- if (mountedRef.current && openRef.current && auctionSeqRef.current === seq) {
- setErrorMessage(t('ads.rewarded.notAvailable'))
- }
+ setErrorMessage(t('ads.rewarded.notAvailable'))
} catch {
- if (mountedRef.current && openRef.current && auctionSeqRef.current === seq) {
- setErrorMessage(t('ads.rewarded.unreachable'))
- }
+ setErrorMessage(t('ads.rewarded.unreachable'))
} finally {
- if (mountedRef.current && auctionSeqRef.current === seq) setLoading(false)
+ setLoading(false)
}
}, [t])
useEffect(() => {
- mountedRef.current = true
if (!open) {
- auctionSeqRef.current += 1
setCreative(null)
setTimeLeft(0)
setCompleted(false)
- setLoading(false)
setErrorMessage(null)
- return () => {
- mountedRef.current = false
- }
+ return
}
void fetchRewardedAuction()
- return () => {
- mountedRef.current = false
- auctionSeqRef.current += 1
- }
}, [open, fetchRewardedAuction])
useEffect(() => {
@@ -110,23 +91,18 @@ export function RewardedQuotaModal({
const handleClaim = async () => {
if (creative === null || !completed) 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
- }
+ 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
}
- } catch {
- // fall through to verification error message
}
- if (mountedRef.current) setErrorMessage(t('ads.rewarded.verifyFailed'))
+ 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 caebfbea..a7c4dc12 100644
--- a/apps/desktop/src/renderer/components/input-insights/InputConsentPanel.tsx
+++ b/apps/desktop/src/renderer/components/input-insights/InputConsentPanel.tsx
@@ -104,32 +104,19 @@ 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)
- })
- .catch(() => {})
+ void window.electronAPI.llm.getModels().then((result) => {
+ if (!cancelled && result.success) setModels(result.data)
+ })
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 })
- if (feedbackTimerRef.current) clearTimeout(feedbackTimerRef.current)
- feedbackTimerRef.current = setTimeout(() => {
- feedbackTimerRef.current = null
- setFeedback(null)
- }, 2500)
+ setTimeout(() => 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 75dafa63..b782361d 100644
--- a/apps/desktop/src/renderer/components/meeting/EditableSegment.tsx
+++ b/apps/desktop/src/renderer/components/meeting/EditableSegment.tsx
@@ -3,22 +3,24 @@
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 — 하드코딩 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
+// Phase 15.5: 화자별 색상 매핑 (d3roPalette SSOT)
+const SPEAKER_COLORS = [
+ d3roPalette.tag.purple,
+ d3roPalette.tag.green,
+ d3roPalette.tag.orange,
+ d3roPalette.tag.red,
+ d3roPalette.tag.blue,
+]
-function getSpeakerStyle(speaker: string): (typeof SPEAKER_STYLES)[number] {
- return SPEAKER_STYLES[resolveSpeakerColorIndex(speaker, SPEAKER_STYLES.length)]
+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]
}
interface EditableSegmentProps {
@@ -81,8 +83,7 @@ export function EditableSegment({
[handleCommit],
)
- const speakerStyle = speaker ? getSpeakerStyle(speaker) : undefined
- const speakerColor = speakerStyle?.color
+ const speakerColor = speaker ? getSpeakerColor(speaker) : undefined
if (editing) {
return (
@@ -199,7 +200,7 @@ export function EditableSegment({
>
{formatTimestamp(timestamp)}
- {speaker && speakerStyle && (
+ {speaker && (
diff --git a/apps/desktop/src/renderer/components/meeting/MeetingChatPanel.tsx b/apps/desktop/src/renderer/components/meeting/MeetingChatPanel.tsx
index 9badae83..772468db 100644
--- a/apps/desktop/src/renderer/components/meeting/MeetingChatPanel.tsx
+++ b/apps/desktop/src/renderer/components/meeting/MeetingChatPanel.tsx
@@ -144,21 +144,6 @@ 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()
@@ -175,9 +160,7 @@ export function MeetingChatPanel({ sessionId, onClose }: MeetingChatPanelProps):
setStreaming(true)
window.electronAPI.meetingChat.send({ sessionId, message: text })
inputRef.current?.focus()
- if (sendResetTimerRef.current) clearTimeout(sendResetTimerRef.current)
- sendResetTimerRef.current = setTimeout(() => {
- sendResetTimerRef.current = null
+ setTimeout(() => {
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 1f6ed096..ea0e8481 100644
--- a/apps/desktop/src/renderer/components/meeting/MeetingDetailTabs.tsx
+++ b/apps/desktop/src/renderer/components/meeting/MeetingDetailTabs.tsx
@@ -24,7 +24,6 @@ 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'
@@ -167,25 +166,15 @@ export function MeetingDetailTabs({
// 템플릿 로드 (다른 기기에서 바뀐 템플릿이 반영되면 다시)
useEffect(() => {
- let cancelled = false
- let loadSeq = 0
const load = (): void => {
- const seq = ++loadSeq
- void window.electronAPI.meetingDocTemplate
- .getAll()
- .then((resp) => {
- if (!cancelled && seq === loadSeq && resp.success) setTemplates(resp.data)
- })
- .catch(() => {})
+ window.electronAPI.meetingDocTemplate.getAll().then((resp) => {
+ if (resp.success) setTemplates(resp.data)
+ })
}
load()
- const unsub = window.electronAPI.app.onDataChanged((data) => {
+ return window.electronAPI.app.onDataChanged((data) => {
if (data.type === 'cloud-sync' && data.entities?.includes('user_templates')) load()
})
- return () => {
- cancelled = true
- unsub()
- }
}, [])
// ── 제목 저장 ── (저장이 확정된 뒤에만 반영한다)
@@ -197,7 +186,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 = toErrorMessage(err)
+ failure = err instanceof Error ? err.message : String(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 e59488a4..55031dfe 100644
--- a/apps/desktop/src/renderer/components/meeting/TranscriptTab.tsx
+++ b/apps/desktop/src/renderer/components/meeting/TranscriptTab.tsx
@@ -2,9 +2,8 @@
// Phase 14.5: 전사 편집 탭 (상세 페이지용) — 요약의 근거.
// 복사·내보내기는 상세 머리의 행동 줄 한 곳에 있다(예전 "전사 다운로드" 버튼은 거기로 옮겼다).
-import { useEffect, useMemo, useState } from 'react'
-import { Box, Switch, FormControlLabel, LinearProgress, Typography, Chip } from '@mui/material'
-import { extractDistinctSpeakers } from '@d3ro/core/meeting-transcript'
+import { useEffect, useMemo } from 'react'
+import { Box, Switch, FormControlLabel, LinearProgress, Typography } from '@mui/material'
import { EditableSegment } from './EditableSegment'
import { PhysicalButton } from '@d3ro/ui/components/ds'
import { d3roPalette, d3roFontMono, typoSx } from '@d3ro/ui/theme'
@@ -49,23 +48,10 @@ 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[] = [
- ...filteredSegments.map((s) => ({
+ ...segments.map((s) => ({
kind: 'segment' as const,
id: s.id,
timestamp: s.timestamp,
@@ -153,48 +139,6 @@ 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 7e58d931..1244ed66 100644
--- a/apps/desktop/src/renderer/components/meeting/meeting-documents-model.ts
+++ b/apps/desktop/src/renderer/components/meeting/meeting-documents-model.ts
@@ -11,7 +11,6 @@
import type { IPCResult } from '@d3ro/core/errors'
import type { MeetingDocument } from '@d3ro/core/types'
-import { toErrorMessage } from '../../utils/error-message'
// ── 상세 탭 · 문서 선택 ─────────────────────────────────────────────
@@ -135,6 +134,10 @@ 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>()
@@ -223,7 +226,7 @@ export class MeetingDocumentsStore {
try {
outcome = await this.port.remove(documentId)
} catch (err: unknown) {
- outcome = { ok: false, message: toErrorMessage(err) }
+ outcome = { ok: false, message: errorMessage(err) }
}
if (!outcome.ok) {
this.setState({ ...this.state, error: outcome.message })
@@ -294,7 +297,7 @@ export class MeetingDocumentsStore {
try {
outcome = await this.port.saveContent(documentId, content)
} catch (err: unknown) {
- outcome = { ok: false, message: toErrorMessage(err) }
+ outcome = { ok: false, message: errorMessage(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 7598fd62..915d5646 100644
--- a/apps/desktop/src/renderer/components/meeting/meeting-format.ts
+++ b/apps/desktop/src/renderer/components/meeting/meeting-format.ts
@@ -1,13 +1,17 @@
// 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 {
- return formatDurationClockFromMs(ms, { padMinutes: true, showHours: true })
+ 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
}
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 bfe9f9b6..faa42764 100644
--- a/apps/desktop/src/renderer/components/meeting/meeting-transcript-model.ts
+++ b/apps/desktop/src/renderer/components/meeting/meeting-transcript-model.ts
@@ -7,7 +7,6 @@
// 영속화는 SaveEditedTranscript 포트로 주입받아 IPC 없이도 검증할 수 있다.
import type { IPCResult } from '@d3ro/core/errors'
-import { toErrorMessage } from '../../utils/error-message'
import {
applyTranscriptSegmentEdit,
isTranscriptViewEditable,
@@ -34,6 +33,10 @@ 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>,
@@ -96,7 +99,7 @@ export class MeetingTranscriptModel {
try {
outcome = await this.save(next)
} catch (err: unknown) {
- outcome = { ok: false, message: toErrorMessage(err) }
+ outcome = { ok: false, message: errorMessage(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
deleted file mode 100644
index f2282350..00000000
--- a/apps/desktop/src/renderer/components/settings/AboutSettingsTab.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-// 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
deleted file mode 100644
index a38e17d3..00000000
--- a/apps/desktop/src/renderer/components/settings/AudioSettingsTab.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-// 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
deleted file mode 100644
index c83d4cdd..00000000
--- a/apps/desktop/src/renderer/components/settings/GeneralSettingsTab.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-// 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
deleted file mode 100644
index 0cebdbff..00000000
--- a/apps/desktop/src/renderer/components/settings/LlmSettingsTab.tsx
+++ /dev/null
@@ -1,310 +0,0 @@
-// 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={
- <>
- }
- onClick={onRefreshOllama}
- disabled={checkingOllama}
- >
- {t('settings.llm.checkConnection')}
-
- {ollamaStatus !== null && !ollamaConnected && (
- }
- onClick={onStartOllama}
- disabled={startingOllama}
- >
- {startingOllama ? t('settings.llm.startingOllama') : t('settings.llm.startOllama')}
-
- )}
- >
- }
- >
- {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 abd798be..8bff0d50 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, Switch, Typography } from '@mui/material'
+import { Box, Typography } from '@mui/material'
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
interface SettingsSectionProps {
@@ -93,23 +93,3 @@ 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
deleted file mode 100644
index f5e573dd..00000000
--- a/apps/desktop/src/renderer/components/settings/settings-model-helpers.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-// 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 20b033a0..ca23564f 100644
--- a/apps/desktop/src/renderer/components/voice-conversation/VoiceRecordingPanel.tsx
+++ b/apps/desktop/src/renderer/components/voice-conversation/VoiceRecordingPanel.tsx
@@ -12,12 +12,16 @@ 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
-const formatDuration = (ms: number): string => formatDurationClockFromMs(ms)
+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}`
+}
/**
* Voice Conversation이 listening 상태일 때만 렌더되는 몰입 녹음 패널.
diff --git a/apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts b/apps/desktop/src/renderer/hooks/useAppUpdateStatus.ts
index 8f273e2f..500176f2 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, useRef, useState } from 'react'
+import { useCallback, useEffect, useState } from 'react'
import type { AppUpdateStatus } from '@d3ro/core/types'
export interface AppUpdateControls {
@@ -16,26 +16,15 @@ 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(() => {
- 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)
+ let alive = true
+ void window.electronAPI.appUpdate.getStatus().then((result) => {
+ if (alive && result.success) setStatus(result.data)
})
+ const unsubscribe = window.electronAPI.appUpdate.onStatusChanged((next) => setStatus(next))
return () => {
- aliveRef.current = false
+ alive = false
unsubscribe()
}
}, [])
@@ -44,12 +33,9 @@ export function useAppUpdateStatus(): AppUpdateControls {
setBusy(true)
void request()
.then((result) => {
- if (aliveRef.current && result.success) setStatus(result.data)
- })
- .catch(() => {})
- .finally(() => {
- if (aliveRef.current) setBusy(false)
+ if (result.success) setStatus(result.data)
})
+ .finally(() => setBusy(false))
}, [])
return {
diff --git a/apps/desktop/src/renderer/hooks/useKeyBindingMap.ts b/apps/desktop/src/renderer/hooks/useKeyBindingMap.ts
index 0d5f278f..74ecb680 100644
--- a/apps/desktop/src/renderer/hooks/useKeyBindingMap.ts
+++ b/apps/desktop/src/renderer/hooks/useKeyBindingMap.ts
@@ -22,12 +22,9 @@ 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)
- })
- .catch(() => {})
+ void window.electronAPI.keybinding.getMap().then((result) => {
+ if (result.success) publish(result.data)
+ })
}
/** 맵이 아직 도착하지 않았으면 null. */
diff --git a/apps/desktop/src/renderer/hooks/useLicenseState.ts b/apps/desktop/src/renderer/hooks/useLicenseState.ts
index cf3c6042..375a01dd 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, useRef } from 'react'
+import { useState, useEffect, useCallback } from 'react'
import type {
LicenseInfo,
LicenseTier,
@@ -33,52 +33,30 @@ 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(() => {
- 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(() => {})
+ 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 })
+ })
}, [])
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 () => {
- mountedRef.current = false
- unsubTier()
- unsubAuth()
- }
+ return () => { 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 1b768b96..877d2ba6 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, useRef, useState } from 'react'
+import React, { useCallback, useEffect, 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,90 +129,45 @@ 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(() => {
- 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(() => {})
+ 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)
+ })
}, [])
useEffect(() => {
- mountedRef.current = true
loadData()
const unsubData = window.electronAPI.app.onDataChanged(() => loadData())
- 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 unsubLlm = window.electronAPI.llm.onStatusChanged((e) => setLlmConnected(e.status.connectionState === 'connected'))
+ const unsubCaption = window.electronAPI.caption.onStateChanged((e) => 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 0cef6d03..38088308 100644
--- a/apps/desktop/src/renderer/pages/KnowledgeBasePage.tsx
+++ b/apps/desktop/src/renderer/pages/KnowledgeBasePage.tsx
@@ -53,29 +53,17 @@ 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 {
- if (mountedRef.current && docsSeqRef.current === seq) setLoadError(true)
+ setLoadError(true)
} finally {
- if (mountedRef.current && docsSeqRef.current === seq) setLoading(false)
+ setLoading(false)
}
}, [])
@@ -93,16 +81,12 @@ export function KnowledgeBasePage(): React.ReactElement {
// 색인 실행이 끝나면(성공·실패 무관) 진행 표시를 내리고, 문서가 끝내 색인되지 않았으면 알린다.
const unsubComplete = window.electronAPI.rag.onIndexComplete((data) => {
setIndexProgress(null)
- 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(() => {})
+ 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'))
+ })
})
return () => {
unsubProgress()
@@ -119,20 +103,17 @@ 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 {
- if (mountedRef.current) setAdding(false)
+ setAdding(false)
isAddingRef.current = false
}
- }, [adding, loadDocuments, t])
+ }, [adding, loadDocuments])
const handleRemoveDocument = (doc: RAGDocument) => {
remove({
@@ -145,36 +126,27 @@ export function KnowledgeBasePage(): React.ReactElement {
const handleReindex = useCallback(async (docId: string) => {
setAddError(null)
- 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])
+ const resp = await window.electronAPI.rag.reindex(docId)
+ // 임베딩 실패는 rag:indexComplete 뒤 문서 상태로 알린다. 그 밖의 실패(문서 없음·파싱 실패)만 여기서 보인다.
+ if (!resp.success && resp.error.code !== ErrorCode.RAGEmbeddingFailed) setAddError(resp.error.message)
+ }, [])
/** 질문할 문장을 인자로 받는다 — 예시 칩이 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 {
- if (mountedRef.current && querySeqRef.current === seq) {
- setQueryError(t('tools.knowledge.queryFailed'))
- }
+ setQueryError(t('tools.knowledge.queryFailed'))
} finally {
- if (mountedRef.current && querySeqRef.current === seq) setQuerying(false)
+ setQuerying(false)
}
},
[t],
diff --git a/apps/desktop/src/renderer/pages/MeetingModePage.tsx b/apps/desktop/src/renderer/pages/MeetingModePage.tsx
index eab2e386..f571681c 100644
--- a/apps/desktop/src/renderer/pages/MeetingModePage.tsx
+++ b/apps/desktop/src/renderer/pages/MeetingModePage.tsx
@@ -98,21 +98,6 @@ 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(() => {
@@ -167,29 +152,21 @@ export function MeetingModePage(): React.ReactElement {
// 다른 기기(모바일·웹)에서 보고 있던 회의가 지워졌으면 목록으로 돌아간다(편집 중인 상세는 덮어쓰지 않는다).
// 목록의 다시 불러오기는 MeetingListView 가 맡는다.
- 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
+ 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) => {
if (!resp.success) {
setDetail(null)
setView('list')
}
})
- .catch(() => {})
- })
- return () => {
- cancelled = true
- unsub()
- }
- }, [setView])
+ }),
+ [detail, setView],
+ )
// ── IPC 이벤트 구독 ──
useEffect(() => {
@@ -203,9 +180,7 @@ export function MeetingModePage(): React.ReactElement {
const unsubSegment = window.electronAPI.meetingMode.onSegment((seg) => {
setSegments((prev) => [...prev, seg])
- if (segmentScrollTimerRef.current) clearTimeout(segmentScrollTimerRef.current)
- segmentScrollTimerRef.current = setTimeout(() => {
- segmentScrollTimerRef.current = null
+ setTimeout(() => {
if (transcriptRef.current) {
transcriptRef.current.scrollTop = transcriptRef.current.scrollHeight
}
@@ -433,7 +408,6 @@ 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')
@@ -441,9 +415,7 @@ export function MeetingModePage(): React.ReactElement {
notify({ message: t('meeting.viewDetailError'), severity: 'error' })
}
} catch {
- if (mountedRef.current) {
- notify({ message: t('meeting.viewDetailError'), severity: 'error' })
- }
+ 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 a30f3914..82930246 100644
--- a/apps/desktop/src/renderer/pages/UnifiedSearchPage.tsx
+++ b/apps/desktop/src/renderer/pages/UnifiedSearchPage.tsx
@@ -24,16 +24,6 @@ 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' ? :
}
@@ -158,7 +148,6 @@ 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 (
@@ -212,10 +201,10 @@ export function UnifiedSearchPage(): React.ReactElement {
- {searchDate.label}
+ {new Date(result.occurredAt).toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' })}
diff --git a/apps/desktop/src/renderer/pages/VoiceConversationPage.tsx b/apps/desktop/src/renderer/pages/VoiceConversationPage.tsx
index 4dd5e985..1947c1a8 100644
--- a/apps/desktop/src/renderer/pages/VoiceConversationPage.tsx
+++ b/apps/desktop/src/renderer/pages/VoiceConversationPage.tsx
@@ -78,21 +78,12 @@ export function VoiceConversationPage(): React.ReactElement {
const streamingText = isRealtime ? realtime.streamingText : localStreamingText
const streamingMsgId = isRealtime ? realtime.streamingMsgId : localStreamingMsgId
- const scrollTimerRef = useRef | null>(null)
-
useEffect(() => {
- let cancelled = false
- window.electronAPI.config
- .getAll()
- .then((r) => {
- if (!cancelled && r.success && r.data.conversationBackend === 'realtime') {
- setBackend('realtime')
- }
- })
- .catch(() => {})
- return () => {
- cancelled = true
- }
+ window.electronAPI.config.getAll().then((r) => {
+ if (r.success && r.data.conversationBackend === 'realtime') {
+ setBackend('realtime')
+ }
+ })
}, [])
useEffect(() => {
@@ -105,86 +96,58 @@ 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)
- scheduleScrollToBottom()
+ setTimeout(scrollToBottom, 50)
})
const unsubDelta = window.electronAPI.voiceConversation.onAssistantDelta(
(data: ConversationAssistantDelta) => {
- receivedLiveEvent = true
setLocalStreamingMsgId(data.messageId)
setLocalStreamingText(data.accumulated)
- scheduleScrollToBottom()
+ setTimeout(scrollToBottom, 50)
},
)
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)
- scheduleScrollToBottom()
+ setTimeout(scrollToBottom, 50)
})
const unsubError = window.electronAPI.voiceConversation.onError((err: ConversationError) => {
setErrorBanner(err)
})
- window.electronAPI.voiceConversation
- .getState()
- .then((r) => {
- if (!cancelled && !receivedLiveEvent && r.success) {
- setLocalState(r.data.state)
- setLocalMessages(r.data.messages)
- setLocalActive(r.data.isActive)
- }
- })
- .catch(() => {})
+ window.electronAPI.voiceConversation.getState().then((r) => {
+ if (r.success) {
+ setLocalState(r.data.state)
+ setLocalMessages(r.data.messages)
+ setLocalActive(r.data.isActive)
+ }
+ })
return () => {
- cancelled = true
unsubState()
unsubUser()
unsubDelta()
unsubComplete()
unsubError()
}
- }, [scheduleScrollToBottom])
+ }, [scrollToBottom])
useEffect(() => {
- if (isRealtime) scheduleScrollToBottom()
- }, [isRealtime, realtime.messages, realtime.streamingText, scheduleScrollToBottom])
+ if (isRealtime) setTimeout(scrollToBottom, 50)
+ }, [isRealtime, realtime.messages, realtime.streamingText, scrollToBottom])
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 e354f424..5e990827 100644
--- a/apps/desktop/src/renderer/popups/caption-overlay/script.js
+++ b/apps/desktop/src/renderer/popups/caption-overlay/script.js
@@ -21,11 +21,10 @@
var i18nStrings = {}
// ── 상태 ──────────────────────────────────────────────
- /** @type {Array<{el: HTMLElement, timer: number|null, fadeTimer: number|null, id: string}>} */
+ /** @type {Array<{el: HTMLElement, timer: number|null, id: string}>} */
var lines = []
/** @type {HTMLElement|null} */
var deltaLine = null
- var unsubs = []
// ── 자막 줄 추가 ──────────────────────────────────────
@@ -34,7 +33,6 @@
* @param {{id: string, text: string, timestamp: number, isFinal: boolean}} segment
*/
function addSegment(segment) {
- if (!segment || typeof segment.text !== 'string') return
// 첫 자막이 오면 준비 안내를 걷는다 (그 전까지는 계속 보여 빈 화면을 만들지 않는다).
removeStatusLine()
// delta 줄이 있으면 제거 (확정 줄로 교체)
@@ -47,11 +45,11 @@
linesContainer.appendChild(el)
// auto-clear 타이머 설정
- var entry = { el: el, timer: null, fadeTimer: null, id: segment.id }
- entry.timer = setTimeout(function () {
+ var timer = setTimeout(function () {
fadeAndRemoveLine(entry)
}, config.autoClearMs)
+ var entry = { el: el, timer: timer, id: segment.id }
lines.push(entry)
// maxLines 초과 시 가장 오래된 줄 제거
@@ -59,7 +57,6 @@
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)
}
@@ -72,7 +69,6 @@
* @param {{text: string, isFinal: boolean}} data
*/
function updateDelta(data) {
- if (!data || typeof data !== 'object') return
if (data.isFinal) {
// isFinal이면 segment로 처리
removeDeltaLine()
@@ -109,7 +105,6 @@
* @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
@@ -136,10 +131,8 @@
* @param {{el: HTMLElement, timer: number|null, id: string}} entry
*/
function fadeAndRemoveLine(entry) {
- entry.timer = null
entry.el.classList.add('fading')
- entry.fadeTimer = setTimeout(function () {
- entry.fadeTimer = null
+ setTimeout(function () {
if (entry.el.parentNode) {
entry.el.parentNode.removeChild(entry.el)
}
@@ -156,7 +149,6 @@
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)
}
@@ -170,11 +162,10 @@
* @param {object} newConfig
*/
function applyConfig(newConfig) {
- 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
+ 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
// 기존 줄에 폰트 크기 반영
for (var i = 0; i < lines.length; i++) {
@@ -192,45 +183,37 @@
// ── 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) {
// 확정된 자막 세그먼트
- registerIpc('caption:segment', function (segment) {
+ window.popupAPI.on('caption:segment', function (segment) {
addSegment(segment)
})
// 중간 전사 결과 (delta)
- registerIpc('caption:delta', function (data) {
+ window.popupAPI.on('caption:delta', function (data) {
updateDelta(data)
})
// 문맥 다듬기 결과
- registerIpc('caption:segmentUpdated', function (update) {
+ window.popupAPI.on('caption:segmentUpdated', function (update) {
updateSegment(update)
})
// 설정 업데이트
- registerIpc('caption:config', function (newConfig) {
+ window.popupAPI.on('caption:config', function (newConfig) {
applyConfig(newConfig)
})
// 숨기기 (세션 종료)
- registerIpc('caption:hide', function () {
+ window.popupAPI.on('caption:hide', function () {
clearAllLines()
- removeStatusLine()
})
// 상태 변경
// starting: 음성 모델을 준비하는 중
// active : 듣고 있지만 첫 자막은 아직 — 소리를 모아 첫 인식을 마칠 때까지 몇 초 걸린다.
// active 가 되자마자 안내를 지우면 그 몇 초가 빈 화면이라 "고장" 처럼 보였다.
- registerIpc('caption:stateChanged', function (data) {
- if (!data || typeof data !== 'object') return
+ window.popupAPI.on('caption:stateChanged', function (data) {
if (data._i18n) {
i18nStrings = data._i18n
if (handleHint) handleHint.textContent = i18nStrings.captionDragHint || ''
@@ -242,7 +225,6 @@
if (lines.length === 0) showStatusLine(i18nStrings.captionWaiting)
} else if (data.state === 'inactive' || data.state === 'stopping') {
clearAllLines()
- removeStatusLine()
}
})
}
@@ -281,30 +263,13 @@
if (window.popupAPI) window.popupAPI.send(channel, value)
}
- function onDocumentMouseMove() {
+ document.addEventListener('mousemove', function () {
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 c812f141..796ba29f 100644
--- a/apps/desktop/src/renderer/popups/command-popup/script.js
+++ b/apps/desktop/src/renderer/popups/command-popup/script.js
@@ -12,7 +12,6 @@
var selectedIndex = 0
var currentCommands = []
var i18n = {}
- var unsubs = []
function tr(key) {
return (i18n && i18n[key]) || ''
@@ -60,8 +59,8 @@
}
function renderItems(commands, activeId) {
- currentCommands = Array.isArray(commands) ? commands : []
- itemsContainer.textContent = ''
+ currentCommands = commands
+ itemsContainer.innerHTML = ''
items = []
var activeIds = String(activeId || '')
.split(',')
@@ -74,16 +73,15 @@
itemsContainer.appendChild(none)
items.push(none)
- if (currentCommands.length === 0) {
+ if (commands.length === 0) {
var empty = document.createElement('div')
empty.className = 'list-empty'
empty.textContent = tr('commandEmpty')
itemsContainer.appendChild(empty)
} else {
- 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)
+ 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)
itemsContainer.appendChild(row)
items.push(row)
})
@@ -115,21 +113,7 @@
window.popupAPI.send('command:selected', { id: cmd.id, name: cmd.name })
}
- 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
+ window.popupAPI.on('command:showItems', function (data) {
selectedIndex = 0
if (data._i18n) i18n = data._i18n
applyI18nToHtml()
@@ -137,18 +121,17 @@
container.classList.remove('hiding')
})
- registerIpc('command:show', function () {
+ window.popupAPI.on('command:show', function () {
container.classList.add('visible')
container.classList.remove('hiding')
})
- registerIpc('command:hide', function () {
+ window.popupAPI.on('command:hide', function () {
container.classList.add('hiding')
container.classList.remove('visible')
})
- registerIpc('command:keyEvent', function (data) {
- if (!data || typeof data.key !== 'string') return
+ window.popupAPI.on('command:keyEvent', function (data) {
var key = data.key
if (key === 'ArrowUp') updateSelection(selectedIndex - 1)
else if (key === 'ArrowDown') updateSelection(selectedIndex + 1)
@@ -159,6 +142,4 @@
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 5dca30f1..196bc9c7 100644
--- a/apps/desktop/src/renderer/popups/history-popup/script.js
+++ b/apps/desktop/src/renderer/popups/history-popup/script.js
@@ -12,7 +12,6 @@
var selectedIndex = 0
var currentEntries = []
var i18n = {}
- var unsubs = []
function tr(key) {
return (i18n && i18n[key]) || ''
@@ -25,8 +24,7 @@
}
function relativeTime(timestamp) {
- if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) return ''
- var sec = Math.max(0, Math.floor((Date.now() - timestamp) / 1000))
+ var sec = 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)
@@ -36,11 +34,11 @@
}
function renderItems(entries) {
- currentEntries = Array.isArray(entries) ? entries : []
- itemsContainer.textContent = ''
+ currentEntries = entries
+ itemsContainer.innerHTML = ''
items = []
- if (currentEntries.length === 0) {
+ if (entries.length === 0) {
var empty = document.createElement('div')
empty.className = 'list-empty'
empty.textContent = tr('historyEmpty')
@@ -48,8 +46,7 @@
return
}
- currentEntries.forEach(function (entry, index) {
- if (!entry) return
+ entries.forEach(function (entry, index) {
var row = document.createElement('div')
row.className = 'd3-item d3-list-item' + (index === selectedIndex ? ' selected' : '')
row.id = 'history-item-' + index
@@ -62,7 +59,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'
@@ -99,21 +96,7 @@
window.popupAPI.send('history:itemSelected', { id: entry.id, text: entry.polishedText || entry.originalText })
}
- 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
+ window.popupAPI.on('history:showItems', function (data) {
selectedIndex = 0
if (data._i18n) i18n = data._i18n
applyI18nToHtml()
@@ -121,18 +104,17 @@
container.classList.remove('hiding')
})
- registerIpc('history:show', function () {
+ window.popupAPI.on('history:show', function () {
container.classList.add('visible')
container.classList.remove('hiding')
})
- registerIpc('history:hide', function () {
+ window.popupAPI.on('history:hide', function () {
container.classList.add('hiding')
container.classList.remove('visible')
})
- registerIpc('history:keyEvent', function (data) {
- if (!data || typeof data.key !== 'string') return
+ window.popupAPI.on('history:keyEvent', function (data) {
var key = data.key
if (key === 'ArrowUp') updateSelection(selectedIndex - 1)
else if (key === 'ArrowDown') updateSelection(selectedIndex + 1)
@@ -143,6 +125,4 @@
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 3e47ebe3..f0e143b3 100644
--- a/apps/desktop/src/renderer/popups/recording-tip/script.js
+++ b/apps/desktop/src/renderer/popups/recording-tip/script.js
@@ -44,7 +44,6 @@
var recordingStartTime = 0
var currentState = 'idle'
var i18n = {}
- var unsubs = []
function tr(key, fallback) {
return (i18n && i18n[key]) || fallback || ''
@@ -72,7 +71,7 @@
}
function updateDuration() {
- var elapsed = Math.max(0, Math.floor((Date.now() - recordingStartTime) / 1000))
+ var elapsed = Math.floor((Date.now() - recordingStartTime) / 1000)
var minutes = Math.floor(elapsed / 60)
var seconds = elapsed % 60
durationText.textContent = minutes + ':' + (seconds < 10 ? '0' : '') + seconds
@@ -162,9 +161,8 @@
}
function applyState(data) {
- if (!data || typeof data !== 'object') return
- if (data._i18n) i18n = data._i18n
- var state = data.state
+ if (data && data._i18n) i18n = data._i18n
+ var state = data && data.state
if (state === 'recording') showRecording()
else if (state === 'thinking') showThinking()
else if (state === 'done') showDone()
@@ -172,25 +170,13 @@
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() {
- 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
+ window.popupAPI.on('voice:audioLevel', function (data) {
+ audioLevel = (data && data.level) || 0
})
// 실시간 부분 전사 — 녹음 중 말하는 내용 미리보기. 최근 문장이 보이도록 아래쪽을 남긴다(CSS: flex-end).
- registerIpc('voice:partialTranscript', function (data) {
+ window.popupAPI.on('voice:partialTranscript', function (data) {
if (currentState !== 'recording') return
var text = (data && data.text) || ''
if (text.length === 0) return
@@ -198,25 +184,17 @@
show(partialText, true)
})
- registerIpc('window:tipStateChanged', applyState)
+ window.popupAPI.on('window:tipStateChanged', applyState)
// 클릭 취소는 녹음 중에만 — 처리 중 클릭이 받아쓴 글을 버리던 사고 방지
- container.addEventListener('click', onContainerClick)
- }
-
- function cleanup() {
- stopTimers()
- container.removeEventListener('click', onContainerClick)
- while (unsubs.length > 0) {
- var unsub = unsubs.pop()
- if (typeof unsub === 'function') unsub()
- }
+ container.addEventListener('click', function () {
+ if (currentState !== 'recording') return
+ window.popupAPI.send('voice:cancelRecording', {})
+ })
}
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 61d2c975..5fe87769 100644
--- a/apps/desktop/src/renderer/popups/result-popup/script.js
+++ b/apps/desktop/src/renderer/popups/result-popup/script.js
@@ -18,11 +18,6 @@
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]) || ''
@@ -61,21 +56,9 @@
}
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')
@@ -103,35 +86,8 @@
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 — 결과 텍스트 세팅 + 크기 측정
- registerIpc('result:prepare', function (data) {
- if (!data || typeof data !== 'object') return
- isVisible = false
- prepareVersion += 1
- var seq = prepareVersion
- cancelPendingMeasure()
- pauseAutoClose()
- remainingTime = 0
-
+ window.popupAPI.on('result:prepare', function (data) {
if (data._i18n) i18n = data._i18n
applyI18nToHtml()
resetCopied()
@@ -139,12 +95,8 @@
resultText.scrollTop = 0
container.classList.remove('visible')
- rafId1 = requestAnimationFrame(function () {
- rafId1 = null
- if (seq !== prepareVersion) return
- rafId2 = requestAnimationFrame(function () {
- rafId2 = null
- if (seq !== prepareVersion) return
+ requestAnimationFrame(function () {
+ requestAnimationFrame(function () {
var rect = container.getBoundingClientRect()
window.popupAPI.send('result:measured', {
width: Math.ceil(rect.width) + 4,
@@ -155,21 +107,15 @@
})
// Phase 2: show — 리사이즈 완료 후 표시
- registerIpc('result:show', function (data) {
- isVisible = true
+ window.popupAPI.on('result:show', function (data) {
container.classList.add('visible')
- var autoHideMs = data && typeof data.autoHideMs === 'number' ? data.autoHideMs : 5000
+ var autoHideMs = (data && data.autoHideMs) || 5000
if (autoHideMs > 0) startAutoCloseTimer(autoHideMs)
})
- registerIpc('result:hide', function () {
- isVisible = false
- prepareVersion += 1
- cancelPendingMeasure()
+ window.popupAPI.on('result:hide', function () {
container.classList.remove('visible')
- pauseAutoClose()
- remainingTime = 0
+ clearInterval(autoCloseTimer)
+ autoCloseTimer = null
})
-
- 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 e616c1f0..c807254f 100644
--- a/apps/desktop/src/renderer/popups/suggestion-overlay/script.js
+++ b/apps/desktop/src/renderer/popups/suggestion-overlay/script.js
@@ -39,7 +39,6 @@
var correction = null
var generatingSince = 0
var tickTimer = null
- var unsubs = []
// 후보 없이 끝났을 때 잠깐 보이는 알림 ('no-suggestion') — 메인이 1초 뒤 창을 닫는다
var notice = null
@@ -243,25 +242,17 @@
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
- var rawCandidates = Array.isArray(payload.candidates) ? payload.candidates : []
- candidates = rawCandidates.map(function (candidate) {
- return candidate && typeof candidate.text === 'string' ? candidate.text : String(candidate)
+ candidates = (payload.candidates || []).map(function (candidate) {
+ return candidate && candidate.text ? candidate.text : String(candidate)
})
- 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))
- }
+ activeIndex = payload.activeIndex || 0
if (payload.targetTotal !== undefined) targetTotal = payload.targetTotal || 0
if (payload.generating !== undefined) generating = payload.generating === true
if (payload.warmingUp !== undefined) warmingUp = payload.warmingUp === true
@@ -271,23 +262,13 @@
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) {
- stopTick()
+ clearInterval(tickTimer)
+ tickTimer = null
+ generatingSince = 0
return
}
render()
@@ -343,25 +324,9 @@
})
}
- 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.popupAPI.on('suggestionPopup:show', handleShow)
+ window.popupAPI.on('suggestionPopup:update', handleUpdate)
+ window.popupAPI.on('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 1715ee50..cd3372b4 100644
--- a/apps/desktop/src/renderer/services/ollamaModelPullController.ts
+++ b/apps/desktop/src/renderer/services/ollamaModelPullController.ts
@@ -11,7 +11,6 @@
// - 상태는 불변 스냅샷으로 노출해 useSyncExternalStore로 구독할 수 있다.
import type { IPCResult } from '@d3ro/core/errors'
-import { toErrorMessage } from '../utils/error-message'
export interface OllamaPullProgressEvent {
modelId: string
@@ -85,6 +84,10 @@ 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 {
@@ -92,7 +95,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: toErrorMessage(err) }
+ return { ok: false, message: errorMessage(err) }
}
}
diff --git a/apps/desktop/src/renderer/utils/error-message.ts b/apps/desktop/src/renderer/utils/error-message.ts
deleted file mode 100644
index ae300903..00000000
--- a/apps/desktop/src/renderer/utils/error-message.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-// 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 dca6f113..ebb327b2 100644
--- a/apps/desktop/src/renderer/utils/formatters.ts
+++ b/apps/desktop/src/renderer/utils/formatters.ts
@@ -1,34 +1,21 @@
// src/renderer/utils/formatters.ts
// 공유 포맷팅 유틸리티 — SSOT, 중복 제거
-import { formatDurationClockFromSeconds } from '@d3ro/core/format'
-
/** 초 단위 duration → "M:SS" 형식 */
export function formatDuration(sec: number): string {
- 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)
+ const m = Math.floor(sec / 60)
+ const s = Math.round(sec % 60)
+ return `${m}:${s.toString().padStart(2, '0')}`
}
/** 타임스탬프 → "YYYY-MM-DD" 날짜 키 (그룹핑용) */
export function getDateKey(ts: number): string {
- const d = toSafeTimestampDate(ts)
- if (!d) return ''
+ const d = new Date(ts)
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}`
@@ -36,7 +23,7 @@ export function formatNumber(n: number): string {
/** ms → 녹음 시간 수치 ("12" 또는 "1:30") */
export function formatRecordingTime(ms: number): string {
- const totalMin = toTotalMinutes(ms)
+ const totalMin = Math.round(ms / 60000)
if (totalMin >= 60) {
const h = Math.floor(totalMin / 60)
const m = totalMin % 60
@@ -47,7 +34,8 @@ export function formatRecordingTime(ms: number): string {
/** ms → 녹음 시간 단위 ("HR" 또는 "MIN") */
export function formatRecordingTimeUnit(ms: number): string {
- return toTotalMinutes(ms) >= 60 ? 'HR' : 'MIN'
+ const totalMin = Math.round(ms / 60000)
+ return totalMin >= 60 ? 'HR' : 'MIN'
}
/**
@@ -55,7 +43,7 @@ export function formatRecordingTimeUnit(ms: number): string {
* "MIN"/"HR" 영문 대문자 단위를 한국어 화면에 그대로 찍던 문제를 대신한다(2026-09-28).
*/
export function formatDurationLong(ms: number, locale: string): string {
- const totalMin = toTotalMinutes(ms)
+ const totalMin = Math.max(0, Math.round(ms / 60000))
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')
@@ -66,12 +54,10 @@ export function formatDurationLong(ms: number, locale: string): string {
/** 타임스탬프 → 로케일 시:분 ("오후 3:04" / "3:04 PM") */
export function formatClockTime(ts: number, locale: string): string {
- const d = toSafeTimestampDate(ts)
- return d ? d.toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' }) : ''
+ return new Date(ts).toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' })
}
/** 타임스탬프 → 로케일 날짜 ("9월 28일 (일)" / "Sun, Sep 28") */
export function formatDayLabel(ts: number, locale: string): string {
- const d = toSafeTimestampDate(ts)
- return d ? d.toLocaleDateString(locale, { month: 'long', day: 'numeric', weekday: 'short' }) : ''
+ return new Date(ts).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 0ec87a50..8b739396 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, revision: 1, created_at: at, updated_at: at, ...row }
+ const full = { user_id: this.userId, created_at: at, updated_at: at, ...row }
this.rows(table).push(full)
return full
}
@@ -56,11 +56,7 @@ 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 {
@@ -236,9 +232,7 @@ 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' || table === 'meeting_memos') && changed) {
- existing.revision = Number(existing.revision ?? 1) + 1
- }
+ if (table === 'history' && 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
deleted file mode 100644
index 1695be89..00000000
--- a/apps/desktop/tests/main/db/sqlite-optimizations.test.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-// 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
deleted file mode 100644
index ab9cb4ef..00000000
--- a/apps/desktop/tests/main/ipc/renderer-broadcast.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-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 8f4f1de5..09c23bc1 100644
--- a/apps/desktop/tests/main/services/UnifiedSearchService.test.ts
+++ b/apps/desktop/tests/main/services/UnifiedSearchService.test.ts
@@ -1,134 +1,129 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import { ErrorCode } from '@d3ro/core/errors'
-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'
+import type { History, MeetingMemoRow, MeetingSessionRow } from '../../../src/main/db/schema'
-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,
- }
+interface MockBuilderOptions {
+ get?: unknown
+ all?: unknown[]
+ error?: Error
}
-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,
+function createMockBuilder(options: MockBuilderOptions = {}) {
+ const builder = {
+ from: vi.fn(),
+ where: vi.fn(),
+ orderBy: vi.fn(),
+ limit: vi.fn(),
+ get: vi.fn(),
+ all: vi.fn(),
}
+ 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
}
-function makeMemoRow(
- overrides: Partial & { id: string; sessionId: string },
-): NewMeetingMemoRow {
- return {
- content: '기본 메모 내용',
- timestampMs: 10_000,
- revision: 1,
- createdAt: 210,
- updatedAt: 210,
- ...overrides,
- }
+const selectQueue: ReturnType[] = []
+const mockDb = {
+ select: vi.fn(() => selectQueue.shift() ?? createMockBuilder()),
+}
+
+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,
}
describe('UnifiedSearchService', () => {
- let closeDb: (() => void) | null = null
-
- function useFreshTestDb() {
- const testDb = createTestDb()
- closeDb = testDb.close
- bindTestDatabase(testDb.db)
- return testDb
- }
-
beforeEach(() => {
- resetUnifiedSearchServiceForTests()
- unbindTestDatabase()
+ selectQueue.length = 0
+ vi.clearAllMocks()
})
- afterEach(() => {
- resetUnifiedSearchServiceForTests()
- unbindTestDatabase()
- if (closeDb) {
- closeDb()
- closeDb = null
- }
- vi.restoreAllMocks()
- })
-
- it('normalizes input and creates a bounded excerpt around the match', () => {
+ it('normalizes input and creates a bounded excerpt around the match', async () => {
+ const { createUnifiedSearchExcerpt, normalizeUnifiedSearchQuery } = await import(
+ '../../../src/main/services/UnifiedSearchService'
+ )
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', () => {
- 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()
+ 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()
const response = getUnifiedSearchService().search({ query: '계획', limit: 10 })
@@ -144,12 +139,17 @@ describe('UnifiedSearchService', () => {
expect(response.results[1]).toMatchObject({ matchedField: 'content' })
})
- it('returns immediately for an empty query without opening DB', () => {
+ it('returns immediately for an empty query', async () => {
+ const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import(
+ '../../../src/main/services/UnifiedSearchService'
+ )
+ resetUnifiedSearchServiceForTests()
expect(getUnifiedSearchService().search({ query: ' ' })).toEqual({
query: '',
results: [],
total: 0,
})
+ expect(mockDb.select).not.toHaveBeenCalled()
})
it.each([
@@ -160,43 +160,58 @@ describe('UnifiedSearchService', () => {
{ query: '계획', limit: Number.NaN },
{ query: '계획', limit: Number.POSITIVE_INFINITY },
{ query: '계획', limit: '10' },
- ])('rejects malformed runtime parameters with ConfigInvalidValue: %o', (params) => {
+ ])('rejects malformed runtime parameters with ConfigInvalidValue: %o', async (params) => {
+ const { getUnifiedSearchService, resetUnifiedSearchServiceForTests } = await import(
+ '../../../src/main/services/UnifiedSearchService'
+ )
+ resetUnifiedSearchServiceForTests()
+
expect(() => getUnifiedSearchService().search(params)).toThrowError(
expect.objectContaining({ code: ErrorCode.ConfigInvalidValue }),
)
+ expect(mockDb.select).not.toHaveBeenCalled()
})
- it('maps database failures to the IPC error contract', () => {
+ 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()
expect(() => getUnifiedSearchService().search({ query: '계획' })).toThrowError(
expect.objectContaining({ code: ErrorCode.DBQueryFailed }),
)
})
- 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()
+ 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()
const response = getUnifiedSearchService().search({ query: '체크리스트', limit: 10 })
@@ -211,246 +226,4 @@ 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
deleted file mode 100644
index 520ebebf..00000000
--- a/apps/desktop/tests/main/services/bug-hunt-timer-cleanup.test.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-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
deleted file mode 100644
index 97377a00..00000000
--- a/apps/desktop/tests/main/services/disk-wav-audio-sink.test.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-// 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
deleted file mode 100644
index 4c9d2492..00000000
--- a/apps/desktop/tests/main/services/meeting-diarization.test.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-// 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
deleted file mode 100644
index 278c20d3..00000000
--- a/apps/desktop/tests/main/services/online-llm-service.test.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-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
deleted file mode 100644
index b8af5e6a..00000000
--- a/apps/desktop/tests/main/services/pii-zdr-wiring.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-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
deleted file mode 100644
index d75bf0fb..00000000
--- a/apps/desktop/tests/main/services/rag-chunk-store-cache.test.ts
+++ /dev/null
@@ -1,227 +0,0 @@
-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
deleted file mode 100644
index 5dca33c1..00000000
--- a/apps/desktop/tests/main/services/runtime-hygiene-optimizations.test.ts
+++ /dev/null
@@ -1,198 +0,0 @@
-// 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
deleted file mode 100644
index 508bb732..00000000
--- a/apps/desktop/tests/main/windows/popup-hide-show-race.test.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-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 12c12fad..47d2010d 100644
--- a/apps/desktop/tests/red/ads/ads-mediation.test.ts
+++ b/apps/desktop/tests/red/ads/ads-mediation.test.ts
@@ -6,8 +6,16 @@
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 = {
@@ -25,8 +33,16 @@ const FX = {
} as const
const ADAPTER_CASES = [
- ...createUnavailableAdAdapters().map((adapter) => [adapter.networkName, adapter] as const),
- ['Direct sponsor', new DirectHouseSponsorAdapter()] as const,
+ ['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()],
] 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 1fe264e4..876663ac 100644
--- a/apps/desktop/tests/unit/AdMediationEngine.test.ts
+++ b/apps/desktop/tests/unit/AdMediationEngine.test.ts
@@ -3,12 +3,28 @@ 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 = createUnavailableAdAdapters().map(
- (adapter) => [adapter.networkName, adapter] as const,
-)
+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
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
deleted file mode 100644
index 4021e578..00000000
--- a/apps/desktop/tests/unit/renderer-popups-and-helpers.test.ts
+++ /dev/null
@@ -1,500 +0,0 @@
-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
deleted file mode 100644
index f4c2c67b..00000000
--- a/apps/desktop/tests/unit/settings-and-suggestion-helpers.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-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 d4a1b9e0..74c86472 100644
--- a/apps/desktop/tsconfig.node.json
+++ b/apps/desktop/tsconfig.node.json
@@ -14,8 +14,7 @@
"@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/main": ["../../packages/i18n/src/main.ts"]
+ "@d3ro/i18n": ["../../packages/i18n/src/index.tsx"]
},
"strict": true,
"noImplicitAny": true,
diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.ts
index 3b57f7ca..488d99f1 100644
--- a/apps/desktop/vitest.config.ts
+++ b/apps/desktop/vitest.config.ts
@@ -28,11 +28,10 @@ export default defineConfig(({ mode }) => ({
}
},
resolve: {
- 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` },
- ]
+ alias: {
+ '@d3ro/core': resolve(__dirname, '../../packages/core/src'),
+ '@d3ro/ui': resolve(__dirname, '../../packages/ui/src'),
+ '@d3ro/i18n': resolve(__dirname, '../../packages/i18n/src/index.tsx')
+ }
}
}))
diff --git a/apps/mobile-rn/App.tsx b/apps/mobile-rn/App.tsx
index 46860414..5abf3072 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}
+ component={OnboardingScreen}
options={{ presentation: 'fullScreenModal' }}
/>
ProPaywallScreen}
+ component={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
deleted file mode 100644
index 975f0e6e..00000000
--- a/apps/mobile-rn/__tests__/durable-queue-early-discard.test.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-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
deleted file mode 100644
index fc7ed28e..00000000
--- a/apps/mobile-rn/__tests__/free-tier-banner-resize.test.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-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
deleted file mode 100644
index 04605035..00000000
--- a/apps/mobile-rn/__tests__/history-detail-unmount-regression.test.tsx
+++ /dev/null
@@ -1,184 +0,0 @@
-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
deleted file mode 100644
index a0502096..00000000
--- a/apps/mobile-rn/__tests__/meeting-detail-speakers.test.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-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
deleted file mode 100644
index ba0ddc78..00000000
--- a/apps/mobile-rn/__tests__/meeting-detail-unmount-regression.test.tsx
+++ /dev/null
@@ -1,156 +0,0 @@
-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 59e4bc9e..af0d02ad 100644
--- a/apps/mobile-rn/__tests__/meetings.test.ts
+++ b/apps/mobile-rn/__tests__/meetings.test.ts
@@ -40,7 +40,6 @@ import {
computeMemoTimestamp,
createMeetingCreationIdempotencyKey,
createMeetingWorkspaceWithMetadata,
- deleteMeetingMemoConflictSafe,
findActiveTranscriptSegmentId,
getMeetingRecordingLanguage,
MeetingServiceError,
@@ -400,46 +399,6 @@ 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
deleted file mode 100644
index 32651b08..00000000
--- a/apps/mobile-rn/__tests__/onboarding-locale-regression.test.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-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 752f3f45..dca71754 100644
--- a/apps/mobile-rn/__tests__/preferences.test.ts
+++ b/apps/mobile-rn/__tests__/preferences.test.ts
@@ -47,11 +47,6 @@ 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
deleted file mode 100644
index 190dd26c..00000000
--- a/apps/mobile-rn/__tests__/record-permission-session-regression.test.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-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
deleted file mode 100644
index def06051..00000000
--- a/apps/mobile-rn/__tests__/responsive-layout.test.tsx
+++ /dev/null
@@ -1,195 +0,0 @@
-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
deleted file mode 100644
index b34a0e85..00000000
--- a/apps/mobile-rn/__tests__/service-guards.test.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-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
deleted file mode 100644
index 5d721ec3..00000000
--- a/apps/mobile-rn/__tests__/settings-locale-sync-regression.test.tsx
+++ /dev/null
@@ -1,152 +0,0 @@
-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
deleted file mode 100644
index ee32a985..00000000
--- a/apps/mobile-rn/__tests__/talk-locale-recorder-regression.test.tsx
+++ /dev/null
@@ -1,217 +0,0 @@
-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 602a1e9b..ca8acac6 100644
--- a/apps/mobile-rn/android/app/build.gradle
+++ b/apps/mobile-rn/android/app/build.gradle
@@ -151,8 +151,8 @@ def versionSettingsValid = configuredVersionName != null &&
configuredVersionName ==~ strictSemver &&
configuredVersionCodeValue != null &&
configuredVersionCodeValue <= 2100000000L
-def resolvedVersionName = versionSettingsValid ? configuredVersionName : "1.17.1"
-def resolvedVersionCode = versionSettingsValid ? configuredVersionCodeValue.toInteger() : 1170100
+def resolvedVersionName = versionSettingsValid ? configuredVersionName : "1.16.5"
+def resolvedVersionCode = versionSettingsValid ? configuredVersionCodeValue.toInteger() : 1160500
def requiredReleaseSettings = [
D3RO_RELEASE_STORE_FILE: releaseStoreFilePath,
@@ -278,7 +278,7 @@ react {
debuggableVariants = ["debug"]
}
-def enableProguardInReleaseBuilds = true
+def enableProguardInReleaseBuilds = false
def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+'
android {
@@ -294,7 +294,6 @@ android {
androidResources {
noCompress += ["bin"]
- localeFilters += ["ko", "en", "ja", "zh", "b+zh+TW", "es", "fr", "de", "pt", "ru", "vi", "th"]
}
defaultConfig {
@@ -384,8 +383,7 @@ android {
abiFilters "arm64-v8a"
}
minifyEnabled enableProguardInReleaseBuilds
- shrinkResources enableProguardInReleaseBuilds
- proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
+ proguardFiles getDefaultProguardFile("proguard-android.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 07e24b59..c874f1af 100644
--- a/apps/mobile-rn/android/app/proguard-rules.pro
+++ b/apps/mobile-rn/android/app/proguard-rules.pro
@@ -1,80 +1,12 @@
-# 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 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
+# 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/ios/D3ROVoice.xcodeproj/project.pbxproj b/apps/mobile-rn/ios/D3ROVoice.xcodeproj/project.pbxproj
index ac77b4d7..46157161 100644
--- a/apps/mobile-rn/ios/D3ROVoice.xcodeproj/project.pbxproj
+++ b/apps/mobile-rn/ios/D3ROVoice.xcodeproj/project.pbxproj
@@ -257,7 +257,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
- CURRENT_PROJECT_VERSION = 1170100;
+ CURRENT_PROJECT_VERSION = 1160500;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = D3ROVoice/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
@@ -265,7 +265,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
- MARKETING_VERSION = 1.17.1;
+ MARKETING_VERSION = 1.16.5;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
@@ -287,14 +287,14 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
- CURRENT_PROJECT_VERSION = 1170100;
+ CURRENT_PROJECT_VERSION = 1160500;
INFOPLIST_FILE = D3ROVoice/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
- MARKETING_VERSION = 1.17.1;
+ MARKETING_VERSION = 1.16.5;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
diff --git a/apps/mobile-rn/jest.config.js b/apps/mobile-rn/jest.config.js
index 888efab1..9b95ec00 100644
--- a/apps/mobile-rn/jest.config.js
+++ b/apps/mobile-rn/jest.config.js
@@ -12,7 +12,6 @@ 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/metadata/android/en-US/changelogs/1170000.txt b/apps/mobile-rn/metadata/android/en-US/changelogs/1170000.txt
deleted file mode 100644
index a6c57884..00000000
--- a/apps/mobile-rn/metadata/android/en-US/changelogs/1170000.txt
+++ /dev/null
@@ -1 +0,0 @@
-Stability and performance improvements.
diff --git a/apps/mobile-rn/metadata/android/en-US/changelogs/1170100.txt b/apps/mobile-rn/metadata/android/en-US/changelogs/1170100.txt
deleted file mode 100644
index a6c57884..00000000
--- a/apps/mobile-rn/metadata/android/en-US/changelogs/1170100.txt
+++ /dev/null
@@ -1 +0,0 @@
-Stability and performance improvements.
diff --git a/apps/mobile-rn/metadata/android/ko-KR/changelogs/1170000.txt b/apps/mobile-rn/metadata/android/ko-KR/changelogs/1170000.txt
deleted file mode 100644
index 183fbc16..00000000
--- a/apps/mobile-rn/metadata/android/ko-KR/changelogs/1170000.txt
+++ /dev/null
@@ -1 +0,0 @@
-안정성과 성능을 개선했습니다.
diff --git a/apps/mobile-rn/metadata/android/ko-KR/changelogs/1170100.txt b/apps/mobile-rn/metadata/android/ko-KR/changelogs/1170100.txt
deleted file mode 100644
index 183fbc16..00000000
--- a/apps/mobile-rn/metadata/android/ko-KR/changelogs/1170100.txt
+++ /dev/null
@@ -1 +0,0 @@
-안정성과 성능을 개선했습니다.
diff --git a/apps/mobile-rn/metro.config.js b/apps/mobile-rn/metro.config.js
index 8f1859f1..0260c61d 100644
--- a/apps/mobile-rn/metro.config.js
+++ b/apps/mobile-rn/metro.config.js
@@ -5,14 +5,6 @@ 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 73edac53..e33f8f34 100644
--- a/apps/mobile-rn/package-lock.json
+++ b/apps/mobile-rn/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@d3ro/mobile-rn",
- "version": "1.17.1",
+ "version": "1.16.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@d3ro/mobile-rn",
- "version": "1.17.1",
+ "version": "1.16.5",
"dependencies": {
"@d3ro/api-client": "file:../../packages/api-client",
"@d3ro/core": "file:../../packages/core",
@@ -19,6 +19,7 @@
"@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",
@@ -61,11 +62,8 @@
},
"../..": {
"name": "d3ro-voice-monorepo",
- "version": "1.17.1",
- "dev": true,
+ "version": "1.16.5",
"license": "MIT",
- "optional": true,
- "peer": true,
"workspaces": [
"apps/desktop",
"apps/web",
@@ -83,7 +81,7 @@
},
"../../packages/api-client": {
"name": "@d3ro/api-client",
- "version": "1.17.1",
+ "version": "1.16.5",
"license": "MIT",
"dependencies": {
"@supabase/supabase-js": "^2.45.0"
@@ -99,7 +97,7 @@
},
"../../packages/core": {
"name": "@d3ro/core",
- "version": "1.17.1",
+ "version": "1.16.5",
"license": "MIT",
"dependencies": {
"docx": "^9.6.1"
@@ -110,7 +108,7 @@
},
"../../packages/i18n": {
"name": "@d3ro/i18n",
- "version": "1.17.1",
+ "version": "1.16.5",
"license": "MIT",
"devDependencies": {
"@types/react": "^19.0.0"
@@ -121,7 +119,7 @@
},
"../../packages/ui-native": {
"name": "@d3ro/ui-native",
- "version": "1.17.1",
+ "version": "1.16.5",
"license": "MIT",
"devDependencies": {
"@types/react": "*"
@@ -5417,6 +5415,10 @@
"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 41326829..e9e46499 100644
--- a/apps/mobile-rn/package.json
+++ b/apps/mobile-rn/package.json
@@ -1,6 +1,6 @@
{
"name": "@d3ro/mobile-rn",
- "version": "1.17.1",
+ "version": "1.16.5",
"private": true,
"scripts": {
"android": "react-native run-android",
@@ -24,6 +24,7 @@
"@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 67ee4bac..93deac5a 100644
--- a/apps/mobile-rn/src/components/FreeTierBanner.tsx
+++ b/apps/mobile-rn/src/components/FreeTierBanner.tsx
@@ -4,7 +4,6 @@ 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'
@@ -17,12 +16,10 @@ 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)
@@ -31,10 +28,6 @@ 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(
@@ -52,20 +45,11 @@ 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 3eb4ed74..d97e2f33 100644
--- a/apps/mobile-rn/src/features/actions/action-service.ts
+++ b/apps/mobile-rn/src/features/actions/action-service.ts
@@ -1,4 +1,3 @@
-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 {
@@ -148,6 +147,7 @@ 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,6 +171,9 @@ 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
@@ -224,7 +227,7 @@ export function parseActionJson(text: string): ParsedMobileAction {
const content = normalizeBoundedString(value.args.content, MAX_MEMO_CHARS)
if (
meetingId === null
- || !isUuid(meetingId)
+ || !UUID_PATTERN.test(meetingId)
|| content === null
|| !hasOnlyKeys(value.args, ['meeting_id', 'content'])
) {
@@ -243,7 +246,7 @@ export function parseActionJson(text: string): ParsedMobileAction {
const role = value.args.role === undefined ? 'member' : value.args.role
if (
teamId === null
- || !isUuid(teamId)
+ || !UUID_PATTERN.test(teamId)
|| email === null
|| !EMAIL_PATTERN.test(email)
|| (role !== 'admin' && role !== 'member')
@@ -341,7 +344,7 @@ export async function parseActionCommand(
)
}
const generationId = response.headers?.get('X-D3RO-Generation-Id')?.trim() ?? ''
- if (!isUuid(generationId)) {
+ if (!UUID_PATTERN.test(generationId)) {
throw new ActionServiceError('INVALID_RESPONSE', true)
}
const snapshot = extractLlmText(body)
@@ -364,7 +367,7 @@ export async function parseActionCommand(
}
function actionHistoryKey(userId: string): string {
- if (!isUuid(userId)) throw new ActionServiceError('AUTH_REQUIRED', false, 401)
+ if (!UUID_PATTERN.test(userId)) throw new ActionServiceError('AUTH_REQUIRED', false, 401)
return `${HISTORY_KEY_PREFIX}.${userId}`
}
@@ -595,7 +598,7 @@ async function performAllowedAction(options: ExecuteActionOptions): Promise {
- if (!isUuid(options.userId) || options.accessToken.trim().length === 0) {
+ if (!UUID_PATTERN.test(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 ad9e53df..83c0904b 100644
--- a/apps/mobile-rn/src/features/admin/admin-service.ts
+++ b/apps/mobile-rn/src/features/admin/admin-service.ts
@@ -1,12 +1,4 @@
-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
@@ -138,6 +130,7 @@ 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
@@ -146,7 +139,10 @@ const TIER_SET = new Set(ADMIN_TIERS)
const STATUS_SET = new Set(ADMIN_SUBSCRIPTION_STATUSES)
function recordValue(value: unknown): Record {
- return assertRecordWith(value, invalidResponse)
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ throw invalidResponse()
+ }
+ return value as Record
}
function assertOnlyKeys(value: Record, allowed: readonly string[]): void {
@@ -155,7 +151,8 @@ function assertOnlyKeys(value: Record, allowed: readonly string
}
function requiredString(value: unknown, maximum = 2048): string {
- return parseBoundedStringWith(value, invalidResponse, { maxLength: maximum })
+ if (typeof value !== 'string' || value.length < 1 || value.length > maximum) throw invalidResponse()
+ return value
}
function nullableString(value: unknown, maximum = 4096): string | null {
@@ -164,11 +161,15 @@ function nullableString(value: unknown, maximum = 4096): string | null {
}
function uuid(value: unknown): string {
- return parseUuidWith(requiredString(value, 36), invalidResponse)
+ const normalized = requiredString(value, 36)
+ if (!UUID_PATTERN.test(normalized)) throw invalidResponse()
+ return normalized.toLowerCase()
}
function isoDateTime(value: unknown): string {
- return parseIsoTimestampWith(requiredString(value, 40), invalidResponse, { maxLength: 40 })
+ const normalized = requiredString(value, 40)
+ if (!Number.isFinite(Date.parse(normalized))) throw invalidResponse()
+ return normalized
}
function nullableIsoDateTime(value: unknown): string | null {
@@ -176,11 +177,13 @@ function nullableIsoDateTime(value: unknown): string | null {
}
function nonNegativeInteger(value: unknown, maximum = 1_000_000): number {
- return parseSafeIntegerWith(value, invalidResponse, { min: 0, max: maximum })
+ if (!Number.isSafeInteger(value) || Number(value) < 0 || Number(value) > maximum) throw invalidResponse()
+ return Number(value)
}
function positiveInteger(value: unknown, maximum = Number.MAX_SAFE_INTEGER): number {
- return parseSafeIntegerWith(value, invalidResponse, { min: 1, max: maximum })
+ if (!Number.isSafeInteger(value) || Number(value) < 1 || Number(value) > maximum) throw invalidResponse()
+ return Number(value)
}
function role(value: unknown): AdminRole {
@@ -514,7 +517,7 @@ export async function getAdminUser(
userId: string,
signal?: AbortSignal,
): Promise {
- if (!isUuid(userId)) throw new AdminServiceError('validation', null, false)
+ if (!UUID_PATTERN.test(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'])
@@ -563,7 +566,7 @@ export async function listAdminAudit(options: {
const page = options.page ?? 1
const limit = options.limit ?? 20
validatedPage(page, limit)
- if (options.targetId !== undefined && !isUuid(options.targetId)) {
+ if (options.targetId !== undefined && !UUID_PATTERN.test(options.targetId)) {
throw new AdminServiceError('validation', null, false)
}
const payload = await requestAdmin(`admin-audit-log${queryString({
@@ -580,7 +583,7 @@ export async function getAdminPaymentHistory(
userId: string,
signal?: AbortSignal,
): Promise {
- if (!isUuid(userId)) throw new AdminServiceError('validation', null, false)
+ if (!UUID_PATTERN.test(userId)) throw new AdminServiceError('validation', null, false)
const payload = await requestAdmin(`admin-payments${queryString({ userId, source: 'db' })}`, {
accessToken,
signal,
@@ -606,7 +609,7 @@ export async function getAdminPaymentHistory(
}
function validatedIdempotencyKey(value: string): string {
- if (!isUuid(value)) throw new AdminServiceError('validation', null, false)
+ if (!UUID_PATTERN.test(value)) throw new AdminServiceError('validation', null, false)
return value.toLowerCase()
}
@@ -624,7 +627,7 @@ export async function changeAdminUserRole(options: {
memo: string
signal?: AbortSignal
}): Promise<{ userId: string; newRole: AdminRole }> {
- if (!isUuid(options.userId) || !ROLE_SET.has(options.newRole)) {
+ if (!UUID_PATTERN.test(options.userId) || !ROLE_SET.has(options.newRole)) {
throw new AdminServiceError('validation', null, false)
}
const idempotencyKey = validatedIdempotencyKey(options.idempotencyKey)
@@ -694,7 +697,7 @@ async function mutateAdminSubscription(
signal?: AbortSignal
},
): Promise {
- if (!isUuid(options.userId)) throw new AdminServiceError('validation', null, false)
+ if (!UUID_PATTERN.test(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 7acfe57c..65d0c115 100644
--- a/apps/mobile-rn/src/features/audio/linked-audio-cleanup.ts
+++ b/apps/mobile-rn/src/features/audio/linked-audio-cleanup.ts
@@ -1,6 +1,5 @@
-import type { AudioFileUploadStatus } from '@d3ro/api-client'
+import type { AudioFileUploadStatus, D3roSupabaseClient } from '@d3ro/api-client'
import { supabase } from '../../lib/supabase'
-import { getTypedSupabaseClient } from '../shared/service-guards'
/**
* 기록·회의를 지울 때 거기에 연결된 원본 음성(audio 버킷 객체 + audio_files 행)을 함께 정리한다.
@@ -131,6 +130,10 @@ 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[] {
@@ -145,7 +148,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 getTypedSupabaseClient()
+ const { data, error } = await database()
.from('audio_files')
.select('id, storage_key, upload_status')
.eq('user_id', userId)
@@ -155,7 +158,7 @@ export function createSupabaseLinkedAudioStore(): LinkedAudioStore {
return toRefs(data)
},
async claimUnlinked(userId, ids) {
- const { data, error } = await getTypedSupabaseClient()
+ const { data, error } = await database()
.from('audio_files')
.update({ upload_status: 'deleted' })
.eq('user_id', userId)
@@ -169,7 +172,7 @@ export function createSupabaseLinkedAudioStore(): LinkedAudioStore {
},
async findReferencedKeys(userId, keys, excludeIds) {
if (keys.length === 0) return []
- const { data, error } = await getTypedSupabaseClient()
+ const { data, error } = await database()
.from('audio_files')
.select('id, storage_key')
.eq('user_id', userId)
@@ -186,7 +189,7 @@ export function createSupabaseLinkedAudioStore(): LinkedAudioStore {
if (error !== null) throw error
},
async deleteRows(userId, ids) {
- const { error } = await getTypedSupabaseClient()
+ const { error } = await database()
.from('audio_files')
.delete()
.eq('user_id', userId)
@@ -195,7 +198,7 @@ export function createSupabaseLinkedAudioStore(): LinkedAudioStore {
if (error !== null) throw error
},
async restoreStatus(userId, id, status) {
- const { error } = await getTypedSupabaseClient()
+ const { error } = await database()
.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 9cf92c26..a973f293 100644
--- a/apps/mobile-rn/src/features/chat/chat-service.ts
+++ b/apps/mobile-rn/src/features/chat/chat-service.ts
@@ -1,4 +1,3 @@
-import { isRecord, isUuid } from '@d3ro/core/guards'
import { SUPABASE_URL } from '@d3ro/core/supabase-config'
export type ChatRole = 'user' | 'assistant'
@@ -45,7 +44,11 @@ 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) {
@@ -132,7 +135,7 @@ async function sendChatRequest(
: response.headers?.get('X-D3RO-Generation-Id')?.trim() ?? ''
if (
generationPurpose !== null
- && (typeof generationId !== 'string' || !isUuid(generationId))
+ && (typeof generationId !== 'string' || !UUID_PATTERN.test(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 7e0dbad1..04dfeb7e 100644
--- a/apps/mobile-rn/src/features/commands/command-service.ts
+++ b/apps/mobile-rn/src/features/commands/command-service.ts
@@ -1,4 +1,3 @@
-import { isUuid } from '@d3ro/core/guards'
import {
ChatServiceError,
sendReportableCommandMessage,
@@ -6,11 +5,6 @@ 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'
@@ -176,20 +170,23 @@ 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 {
- return assertRecordWith(value, () => new CommandSyncError('server'))
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ throw new CommandSyncError('server')
+ }
+ return value as Record
}
function timestamp(value: unknown): string {
- return parseIsoTimestampWith(
- value,
- () => new CommandSyncError('server'),
- { normalizeToIso: true },
- )
+ if (typeof value !== 'string' || !Number.isFinite(Date.parse(value))) {
+ throw new CommandSyncError('server')
+ }
+ return new Date(value).toISOString()
}
export function normalizeSyncedCommand(value: unknown, expectedUserId?: string): SyncedCommand {
@@ -200,8 +197,10 @@ export function normalizeSyncedCommand(value: unknown, expectedUserId?: string):
? row.builtin_key as CommandBuiltinKey
: undefined
if (
- !isUuid(row.id)
- || !isUuid(row.user_id)
+ typeof row.id !== 'string'
+ || !UUID_PATTERN.test(row.id)
+ || typeof row.user_id !== 'string'
+ || !UUID_PATTERN.test(row.user_id)
|| (expectedUserId !== undefined && row.user_id !== expectedUserId)
|| builtinKey === undefined
|| typeof row.name !== 'string'
@@ -238,7 +237,9 @@ export function normalizeSyncedCommand(value: unknown, expectedUserId?: string):
}
}
-const requireUserId = createUuidAssert(() => new CommandSyncError('auth'))
+function requireUserId(userId: string): void {
+ if (!UUID_PATTERN.test(userId)) throw new CommandSyncError('auth')
+}
function validateCustomFields(input: {
name: string
@@ -278,7 +279,7 @@ export async function loadSyncedCommandCatalog(userId: string): Promise {
requireUserId(userId)
- if (instructionId !== null && !isUuid(instructionId)) {
+ if (instructionId !== null && !UUID_PATTERN.test(instructionId)) {
throw new CommandSyncError('validation')
}
const result = await supabase.rpc('set_active_custom_instruction', {
@@ -373,7 +374,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' || !isUuid(active))) {
+ if (active !== null && (typeof active !== 'string' || !UUID_PATTERN.test(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 db160d75..91ad7cf8 100644
--- a/apps/mobile-rn/src/features/dashboard/dashboard-service.ts
+++ b/apps/mobile-rn/src/features/dashboard/dashboard-service.ts
@@ -1,6 +1,4 @@
-import { isRecord } from '@d3ro/core/guards'
import { supabase } from '../../lib/supabase'
-import { requireUuidWith } from '../shared/service-guards'
export interface DashboardRecentEntry {
id: string
@@ -30,6 +28,9 @@ 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)
@@ -103,7 +104,9 @@ export function normalizeDashboardStats(value: unknown): MobileDashboardStats {
}
export async function loadDashboardStats(userId: string): Promise {
- requireUuidWith(userId, () => new DashboardServiceError('auth'))
+ 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')
+ }
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 85c7ac28..4d0e3351 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,7 +7,6 @@ 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,
@@ -37,9 +36,15 @@ export interface AccountImportResult {
detectedFormat: string;
}
-const requireUserId = createUuidAssert(
- () => new PortabilityError('auth', 'A valid signed-in account is required'),
-);
+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');
+ }
+}
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 be767953..18f35105 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,11 +5,7 @@ import {
pick,
types,
} from '@react-native-documents/picker';
-import { FileSystem } from 'react-native-file-access';
-import {
- localPathFromCacheUri,
- removeOwnedCacheFile,
-} from '../shared/owned-cache-files';
+import { Dirs, FileSystem } from 'react-native-file-access';
import { PortabilityError } from './portability-error';
import { PORTABILITY_MAX_BYTES } from './portability-types';
@@ -32,17 +28,32 @@ const ALLOWED_MIME_TYPES = new Set([
'',
]);
-const localPathFromUri = localPathFromCacheUri;
+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('..')
+ );
+}
async function removeOwnedCopy(path: string): Promise {
- await removeOwnedCacheFile(
- path,
- () =>
- new PortabilityError(
- 'file-read',
- 'Refusing to remove a file outside the import cache',
- ),
- );
+ 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);
}
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 8e2ecd2b..157ab7e3 100644
--- a/apps/mobile-rn/src/features/data-portability/legacy-import.ts
+++ b/apps/mobile-rn/src/features/data-portability/legacy-import.ts
@@ -1,5 +1,3 @@
-import { isUuid } from '@d3ro/core/guards';
-import { assertRecordWith, requireUuidWith } from '../shared/service-guards';
import {
createPortableArchive,
sha256Hex,
@@ -24,6 +22,9 @@ 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;
@@ -46,10 +47,10 @@ interface LegacyContext {
type UnknownRecord = Record;
function record(value: unknown, label: string): UnknownRecord {
- return assertRecordWith(
- value,
- () => new PortabilityError('format', `${label} must be an object`),
- );
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ throw new PortabilityError('format', `${label} must be an object`);
+ }
+ return value as UnknownRecord;
}
function deterministicUuid(
@@ -76,7 +77,7 @@ function legacyId(
namespace: string,
identity: string,
): string {
- if (isUuid(value))
+ if (typeof value === 'string' && UUID_PATTERN.test(value))
return value.toLowerCase();
return deterministicUuid(context.ownerId, namespace, identity);
}
@@ -642,10 +643,8 @@ export function parseImportedPortableFile(
ownerId: string,
now = new Date().toISOString(),
): ImportedPortableFile {
- requireUuidWith(
- ownerId,
- () => new PortabilityError('auth', 'A valid signed-in account is required'),
- );
+ if (!UUID_PATTERN.test(ownerId))
+ throw 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 dc7408bd..7f0e5fb1 100644
--- a/apps/mobile-rn/src/features/data-portability/meeting-export.ts
+++ b/apps/mobile-rn/src/features/data-portability/meeting-export.ts
@@ -1,4 +1,3 @@
-import { formatDurationClockFromMs } from '@d3ro/core/format';
import type {
Meeting,
MeetingDocument,
@@ -25,10 +24,18 @@ function formatDuration(milliseconds: number | null): string {
}
function formatElapsed(milliseconds: number): string {
- return formatDurationClockFromMs(milliseconds, {
- padMinutes: true,
- showHours: true,
- });
+ 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',
+ )}`;
}
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 3ef5cce4..5bf40cce 100644
--- a/apps/mobile-rn/src/features/data-portability/portability-schema.ts
+++ b/apps/mobile-rn/src/features/data-portability/portability-schema.ts
@@ -1,9 +1,3 @@
-import {
- assertRecordWith,
- parseBoundedStringWith,
- parseIsoTimestampWith,
- parseUuidWith,
-} from '../shared/service-guards'
import { createPortableArchive, utf8ByteLength } from './canonical-json';
import { PortabilityError } from './portability-error';
import {
@@ -29,6 +23,8 @@ 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;
@@ -39,15 +35,14 @@ function fail(message: string): never {
}
function record(value: unknown, label: string): UnknownRecord {
- const parsed = assertRecordWith(
- value,
- () => new PortabilityError('format', `${label} must be an object`),
- );
- const prototype = Object.getPrototypeOf(parsed);
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ return fail(`${label} must be an object`);
+ }
+ const prototype = Object.getPrototypeOf(value);
if (prototype !== Object.prototype && prototype !== null) {
return fail(`${label} has an unsupported prototype`);
}
- return parsed;
+ return value as UnknownRecord;
}
function exactKeys(
@@ -71,15 +66,16 @@ function stringValue(
maxLength: number,
allowEmpty = false,
): string {
- return parseBoundedStringWith(
- value,
- () =>
- new PortabilityError(
- 'format',
- `${label} must be ${allowEmpty ? '0' : '1'}-${maxLength} characters`,
- ),
- { minLength: allowEmpty ? 0 : 1, maxLength },
- );
+ if (
+ typeof value !== 'string' ||
+ (!allowEmpty && value.length === 0) ||
+ value.length > maxLength
+ ) {
+ return fail(
+ `${label} must be ${allowEmpty ? '0' : '1'}-${maxLength} characters`,
+ );
+ }
+ return value;
}
function nullableString(
@@ -92,19 +88,21 @@ function nullableString(
}
function uuid(value: unknown, label: string): string {
- return parseUuidWith(
- value,
- () => new PortabilityError('format', `${label} must be a UUID`),
- );
+ if (typeof value !== 'string' || !UUID_PATTERN.test(value)) {
+ return fail(`${label} must be a UUID`);
+ }
+ return value.toLowerCase();
}
function timestamp(value: unknown, label: string): string {
const parsed = stringValue(value, label, 40);
- return parseIsoTimestampWith(
- parsed,
- () => new PortabilityError('format', `${label} must be an ISO-8601 timestamp`),
- { requireTimePrefix: true },
- );
+ 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;
}
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 60f43fef..8dbdda68 100644
--- a/apps/mobile-rn/src/features/data-portability/portable-text.ts
+++ b/apps/mobile-rn/src/features/data-portability/portable-text.ts
@@ -1,4 +1,3 @@
-import { csvCell as coreCsvCell } from '@d3ro/core/csv';
import { PortabilityError } from './portability-error';
import type {
PortableDictionaryRow,
@@ -6,8 +5,14 @@ import type {
PortablePayload,
} from './portability-types';
-const formatPortableCsvCell = (value: unknown): string =>
- coreCsvCell(value, { prefixFormulaWithApostrophe: true });
+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;
+}
export function parseCsv(
input: string,
@@ -108,7 +113,7 @@ export function buildDictionaryCsv(rows: PortableDictionaryRow[]): string {
row.created_at,
row.updated_at,
]
- .map(formatPortableCsvCell)
+ .map(csvCell)
.join(','),
);
return `\uFEFF${header.join(',')}\r\n${body.join('\r\n')}\r\n`;
@@ -154,7 +159,7 @@ export function buildHistoryCsv(rows: PortableHistoryRow[]): string {
row.created_at,
row.updated_at,
]
- .map(formatPortableCsvCell)
+ .map(csvCell)
.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 ed7e9ac1..b05d8fa6 100644
--- a/apps/mobile-rn/src/features/devices/device-service.ts
+++ b/apps/mobile-rn/src/features/devices/device-service.ts
@@ -1,7 +1,5 @@
-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
@@ -33,6 +31,9 @@ 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))
@@ -77,7 +78,11 @@ export function normalizeRegisteredDevice(value: unknown): RegisteredDevice {
}
}
-const requireUserId = createUuidAssert(() => new DeviceServiceError('auth'))
+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 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 fcb6d282..91652995 100644
--- a/apps/mobile-rn/src/features/dictionary/dictionary-service.ts
+++ b/apps/mobile-rn/src/features/dictionary/dictionary-service.ts
@@ -1,14 +1,6 @@
import type { RealtimeChannel } from '@supabase/supabase-js'
-import type { DictionaryEntry } from '@d3ro/api-client'
-import { escapeLikePattern } from '@d3ro/core/guards'
+import type { D3roSupabaseClient, DictionaryEntry } from '@d3ro/api-client'
import { supabase } from '../../lib/supabase'
-import {
- createLabeledUuidAssert,
- extractSupabaseErrorInfo,
- getTypedSupabaseClient,
- isSupabaseAuthFailure,
- isSupabaseNetworkFailure,
-} from '../shared/service-guards'
export type DictionaryCategory = DictionaryEntry['category']
@@ -66,11 +58,18 @@ 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']
-const requireUuid = createLabeledUuidAssert(
- (label) => new DictionaryServiceError('auth', `A valid ${label} is required`),
-)
+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`)
+ }
+}
function assertOwnedEntry(userId: string, entry: DictionaryEntry): void {
requireUuid(userId, 'authenticated user')
@@ -122,16 +121,27 @@ export function normalizeDictionaryDraft(
function dictionaryError(error: unknown): DictionaryServiceError {
if (error instanceof DictionaryServiceError) return error
- 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)
+ 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)
}
- if (isSupabaseAuthFailure(info, { include42501: true })) {
- return new DictionaryServiceError('auth', info.message)
+ if (code === 'PGRST301' || code === '42501' || lower.includes('jwt')) {
+ return new DictionaryServiceError('auth', message)
}
- if (info.code.startsWith('22')) return new DictionaryServiceError('validation', info.message)
- return new DictionaryServiceError('server', info.message)
+ if (code.startsWith('22')) return new DictionaryServiceError('validation', message)
+ return new DictionaryServiceError('server', message)
}
function validateCursor(cursor: DictionaryCursor): void {
@@ -141,12 +151,16 @@ 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 = getTypedSupabaseClient()
+ let query = client()
.from('dictionary')
.select('id')
.eq('user_id', userId)
@@ -185,7 +199,7 @@ export async function listDictionaryPage(
if (options.cursor !== null && options.cursor !== undefined) validateCursor(options.cursor)
try {
- let query = getTypedSupabaseClient()
+ let query = client()
.from('dictionary')
.select('*', { count: 'exact' })
.eq('user_id', options.userId)
@@ -236,7 +250,7 @@ export async function createDictionaryEntry(
throw new DictionaryServiceError('duplicate', 'This word already exists in the category')
}
- const { data, error } = await getTypedSupabaseClient()
+ const { data, error } = await client()
.from('dictionary')
.insert({
user_id: userId,
@@ -267,7 +281,7 @@ export async function updateDictionaryEntry(
throw new DictionaryServiceError('duplicate', 'This word already exists in the category')
}
- const { data, error } = await getTypedSupabaseClient()
+ const { data, error } = await client()
.from('dictionary')
.update({
word: normalized.word,
@@ -301,7 +315,7 @@ export async function deleteDictionaryEntry(
assertOwnedEntry(userId, current)
try {
- const { data, error } = await getTypedSupabaseClient()
+ const { data, error } = await client()
.from('dictionary')
.delete()
.eq('user_id', userId)
@@ -333,7 +347,7 @@ export async function getDictionaryPromptHints(
const limit = Math.min(requestedLimit, 50)
try {
- const { data, error } = await getTypedSupabaseClient()
+ const { data, error } = await client()
.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 e5702cd8..2c8a29c5 100644
--- a/apps/mobile-rn/src/features/history/history-cache.ts
+++ b/apps/mobile-rn/src/features/history/history-cache.ts
@@ -1,4 +1,3 @@
-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'
@@ -24,6 +23,9 @@ 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 d713c8fc..96f107e2 100644
--- a/apps/mobile-rn/src/features/history/history-service.ts
+++ b/apps/mobile-rn/src/features/history/history-service.ts
@@ -1,19 +1,13 @@
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,
@@ -76,9 +70,15 @@ const PAGE_SIZE = 20
const MAX_PAGE_SIZE = 50
const ACTIVE_JOB_STATUSES = ['queued', 'running'] as const
-const requireUserId = createUuidAssert(
- () => new HistoryServiceError('auth', 'A valid authenticated user is required'),
-)
+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')
+ }
+}
export function sanitizeHistorySearch(value: string): string {
return value
@@ -91,18 +91,28 @@ export function sanitizeHistorySearch(value: string): string {
function historyError(error: unknown): HistoryServiceError {
if (error instanceof HistoryServiceError) return error
- const info = extractSupabaseErrorInfo(error, 'History request failed')
- if (isSupabaseNetworkFailure(error, info)) {
- return new HistoryServiceError('network', info.message)
+
+ 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)
}
- if (isSupabaseAuthFailure(info, { include42501: true })) {
- return new HistoryServiceError('auth', info.message)
+ if (code === 'PGRST301' || code === '42501' || lower.includes('jwt')) {
+ return new HistoryServiceError('auth', message)
}
- return new HistoryServiceError('server', info.message)
+ return new HistoryServiceError('server', message)
}
async function activeHistoryIds(userId: string): Promise {
- const { data, error } = await getTypedSupabaseClient()
+ const { data, error } = await client()
.from('processing_jobs')
.select('history_id')
.eq('user_id', userId)
@@ -124,7 +134,7 @@ async function activeJobsByHistory(
): Promise