Compare commits

...

9 commits

Author SHA1 Message Date
Yun Chan
876e72ea2f docs(wave7): record peer-swarm bug fixes, metrics, and map sync
Some checks failed
ci / 정본·보안·린트·타입·테스트 (push) Failing after 18s
ci / 워크스페이스 빌드 검증 (push) Has been skipped
ci / 모바일 린트·타입·Jest (push) Successful in 45s
ci / Supabase Edge Functions + Cloudflare Worker (push) Successful in 22s
ci / .NET API 서버 테스트 (push) Successful in 11s
deploy-site / deploy (push) Successful in 44s
2026-11-14 15:41:48 +09:00
Yun Chan
cc3f7460be fix(mobile): delete cleanup audio files on retry and isolate screen busy state across user switches 2026-11-14 15:26:18 +09:00
Yun Chan
bd3c1a98d9 fix(mobile): harden recorder, queue, context, and screen async lifecycles 2026-11-14 15:26:18 +09:00
Yun Chan
3f9e412257 fix(desktop): wrap pull and STT download aborts into D3ROError on dispose
Catch pre-header fetch and stream rejections in LocalLLMService._doPullModel and map disposed or aborted pulls to ErrorCode.LLMProcessingCancelled (and unexpected failures to ErrorCode.LLMServerUnreachable). Convert disposed fetch aborts and JSON body aborts in LocalSTTService._fetchDownload and downloadModel into ErrorCode.STTModelDownloadCancelled while wrapping network or timeout errors as ErrorCode.STTModelDownloadFailed.
2026-11-14 15:26:18 +09:00
Yun Chan
fc5d45312c fix(desktop): harden cancellation, dispose, and lifecycle races across main services
Cancel pending result-popup measure timers on hideResultPopup; track CaptionService aux-model load state, stop deduplication, and refine abort epochs across restarts; forward per-call AbortSignal through VoiceModeService and LlmGateway to LocalLLMService and abort pull streams plus availability polling on dispose; clear aborted response pointers and gate stale mic start errors in VoiceConversationService; guard AudioCaptureService stopping resume against exited SoX processes and cleanup failed starts; abort LocalSTTService downloadModel polling on dispose; and fail closed when desktopCapturer.getSources rejects in caption loopback setup.
2026-11-14 15:26:18 +09:00
Yun Chan
4bf0f0df12 fix(web): propagate mounted timeouts across chat stream and edge-fetch awaits 2026-11-14 15:26:18 +09:00
Yun Chan
c68e81e0aa fix(cloud): harden edge gateways, api-server ssrf, supabase fail-closed quota, and web/admin lifecycle 2026-11-14 15:26:18 +09:00
Yun Chan
2a009e421a fix(input,core): fix live punctuation typo triggers, expected insert cleanup, and ngram scan 2026-11-14 15:26:18 +09:00
Yun Chan
a37dd63909 docs(map): record v1.17.1 multi-surface production deployment 2026-11-14 14:36:47 +09:00
115 changed files with 7385 additions and 630 deletions

View file

@ -226,6 +226,7 @@ Node로 vitest를 돌리면 better-sqlite3 ABI 불일치로 수백 건이 가짜
| 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 6 | 2026-11-14 | `66b6b45` (Wave 5-6 통합 커밋) | `docs/REFACTOR_WAVE6_REPORT.md` |
| Wave 7 | 2026-11-14 | `2a009e4`..`cc3f746` (`input-core`·`cloud-surfaces`·`desktop-shell`·`mobile-app` + `@verifier` 델타 3종) | `docs/REFACTOR_WAVE7_REPORT.md` |
다음 wave 추가 시 본 표 갱신.

View file

@ -30,3 +30,31 @@ obj/
# 앱별 로컬 환경 파일(비밀값)이 이미지 빌드 컨텍스트에 들어가지 않게 한다.
**/.env
**/.env.*
apps/desktop/
apps/mobile-rn/
apps/api-server/
apps/api-server.Tests/
apps/admin-swagger/
scratch/
site/
server/
docs/
memory/
scripts/
release/
supabase/
araso/
bucket/
.agents/
.claude/
.codex/
.crush/
.forgejo/
.pi/
.tmp/
.wrangler/
.chrome-debug-profile/
.chrome-interactive-profile/
.chrome-playwright-profile/
.playwright-oauth-profile/

View file

@ -7,7 +7,8 @@
"dev": "next dev --port 3001",
"build": "next build",
"start": "next start --port 3001",
"typecheck": "next typegen && tsc --noEmit"
"typecheck": "next typegen && tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@d3ro/api-client": "*",

View file

@ -3,21 +3,33 @@
import { NextResponse, type NextRequest } from 'next/server'
import { createServerClient, type CookieOptions } from '@supabase/ssr'
import { resolveAdminCallbackOrigin, safeAdminRedirectPath } from '@/lib/admin-url-safety'
export async function GET(request: NextRequest): Promise<NextResponse> {
const { searchParams, origin } = new URL(request.url)
const { searchParams } = new URL(request.url)
const origin = resolveAdminCallbackOrigin(
request.url,
process.env.ADMIN_PUBLIC_ORIGIN ?? process.env.NEXT_PUBLIC_ADMIN_ORIGIN,
)
const code = searchParams.get('code')
const nextPath = safeAdminRedirectPath(searchParams.get('next'))
if (!code) {
return NextResponse.redirect(`${origin}/login?error=no_code`)
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim()
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY?.trim()
if (!supabaseUrl || !supabaseAnonKey) {
return NextResponse.redirect(`${origin}/login?error=auth_unavailable`)
}
// 쿠키를 수집할 배열
const cookiesToSet: Array<{ name: string; value: string; options: CookieOptions }> = []
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL ?? '',
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',
supabaseUrl,
supabaseAnonKey,
{
cookies: {
getAll() {
@ -33,11 +45,11 @@ export async function GET(request: NextRequest): Promise<NextResponse> {
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (error) {
return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(error.message)}`)
return NextResponse.redirect(`${origin}/login?error=oauth_callback_failed`)
}
// 세션 교환 성공 후 response 생성 + 수집된 쿠키 적용
const response = NextResponse.redirect(`${origin}/`)
const response = NextResponse.redirect(`${origin}${nextPath}`)
for (const { name, value, options } of cookiesToSet) {
response.cookies.set({ name, value, ...options })
}

View file

@ -9,13 +9,14 @@ import GoogleIcon from '@mui/icons-material/Google'
import LockOutlinedIcon from '@mui/icons-material/LockOutlined'
import { DoubleBezelCard, TactileBadge } from '@d3ro/ui/components/ds'
import { C, FONT_SANS, FONT_MONO, primaryButtonSx } from '@/lib/console-theme'
import { safeAdminRedirectPath } from '@/lib/admin-url-safety'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
import { useRouter, useSearchParams } from 'next/navigation'
function LoginForm(): React.ReactElement {
const router = useRouter()
const searchParams = useSearchParams()
const redirectPath = searchParams.get('redirect') || '/'
const redirectPath = safeAdminRedirectPath(searchParams.get('redirect'))
const [usernameOrEmail, setUsernameOrEmail] = useState('')
const [password, setPassword] = useState('')

View file

@ -3,7 +3,7 @@
// apps/admin/src/components/subscription-form.tsx
// 구독 생성/수정 공용 폼
import { useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import {
Box,
TextField,
@ -17,6 +17,7 @@ import {
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette, d3roFontMono } from '@d3ro/ui/theme'
import { callAdminApi } from '@/lib/admin-api'
import { parseOptionalIsoDate } from '@/lib/admin-url-safety'
type Tier = 'free' | 'pro' | 'pro_plus'
type SubStatus = 'active' | 'canceled' | 'past_due' | 'expired'
@ -44,10 +45,24 @@ export function SubscriptionForm({ mode, userId, initial, onSuccess }: Subscript
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState(false)
const mountedRef = useRef(true)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
const handleSubmit = async (): Promise<void> => {
if (!memo.trim()) return
const parsedEnd = parseOptionalIsoDate(periodEnd)
if (!parsedEnd.ok) {
setError(parsedEnd.message)
return
}
setLoading(true)
setError(null)
setSuccess(false)
@ -60,33 +75,38 @@ export function SubscriptionForm({ mode, userId, initial, onSuccess }: Subscript
userId,
tier,
status,
currentPeriodEnd: periodEnd ? new Date(periodEnd).toISOString() : undefined,
currentPeriodEnd: parsedEnd.iso,
adminNote: adminNote || undefined,
memo: memo.trim(),
}),
})
} else {
await callAdminApi(`admin-subscriptions?userId=${userId}`, {
await callAdminApi(`admin-subscriptions?userId=${encodeURIComponent(userId)}`, {
method: 'PATCH',
body: JSON.stringify({
tier,
status,
currentPeriodEnd: periodEnd ? new Date(periodEnd).toISOString() : undefined,
currentPeriodEnd: parsedEnd.iso,
overageCredits,
adminNote: adminNote || undefined,
memo: memo.trim(),
}),
})
}
if (!mountedRef.current) return
setSuccess(true)
setMemo('')
onSuccess()
} catch (err) {
if (mountedRef.current) {
setError(err instanceof Error ? err.message : 'Operation failed')
}
} finally {
if (mountedRef.current) {
setLoading(false)
}
}
}
const inputSx = {
'& .MuiInputBase-root': {

View file

@ -0,0 +1,70 @@
const STATIC_ASSET_EXT_RE =
/\.(?:ico|png|jpg|jpeg|gif|svg|webp|woff2?|ttf|eot|css|js|map|txt|xml|webmanifest)$/i
function hasUnsafeControlOrBackslash(value: string): boolean {
for (let i = 0; i < value.length; i += 1) {
const code = value.charCodeAt(i)
if (code <= 0x1f || code === 0x7f || code === 0x5c) {
return true
}
}
return false
}
/**
* 관리자 콘솔 내부 경로만 허용한다.
* `//evil.example`, `https://evil.example`, `/\evil.example`, 제어문자는 `/`로 폴백한다.
*/
export function safeAdminRedirectPath(value: string | null | undefined): string {
if (!value || !value.startsWith('/') || value.startsWith('//') || hasUnsafeControlOrBackslash(value)) {
return '/'
}
try {
const parsed = new URL(value, 'https://d3ro-admin.local')
if (parsed.origin !== 'https://d3ro-admin.local' || parsed.pathname.startsWith('//')) {
return '/'
}
} catch {
return '/'
}
return value
}
/** 정적 에셋 확장자 경로만 인증 우회 정적 경로로 간주한다. `/api/*`는 절대 면제하지 않는다. */
export function isStaticAssetPath(pathname: string): boolean {
if (pathname.startsWith('/_next/') || pathname === '/_next') return true
if (pathname.startsWith('/static/') || pathname === '/static') return true
if (pathname.startsWith('/api/') || pathname === '/api') return false
return STATIC_ASSET_EXT_RE.test(pathname)
}
/** 관리자 OAuth 콜백 리다이렉트 기준 origin을 반환한다. 설정값이 유효하면 우선한다. */
export function resolveAdminCallbackOrigin(requestUrl: string, configuredOrigin?: string): string {
const configured = configuredOrigin?.trim()
if (configured) {
try {
const parsed = new URL(configured)
if (parsed.protocol === 'https:' || parsed.protocol === 'http:') {
return parsed.origin
}
} catch {
// 잘못된 설정값은 요청 URL origin으로 폴백한다.
}
}
return new URL(requestUrl).origin
}
/** 선택적 날짜 입력을 ISO-8601 문자열로 검증·변환한다. */
export function parseOptionalIsoDate(
raw: string,
): { ok: true; iso: string | undefined } | { ok: false; message: string } {
const trimmed = raw.trim()
if (!trimmed) {
return { ok: true, iso: undefined }
}
const timestamp = Date.parse(trimmed)
if (!Number.isFinite(timestamp)) {
return { ok: false, message: '올바른 종료일 형식이 아닙니다.' }
}
return { ok: true, iso: new Date(timestamp).toISOString() }
}

View file

@ -1,6 +1,7 @@
// D3RO Voice — Industrial Grade Admin Route & Security Guard
import { NextResponse, type NextRequest } from 'next/server'
import { isStaticAssetPath, safeAdminRedirectPath } from '@/lib/admin-url-safety'
import { verifyEdgeSession } from '@/lib/edge-session'
const PUBLIC_PATHS = [
@ -15,15 +16,15 @@ const PUBLIC_PATHS = [
export async function proxy(request: NextRequest): Promise<NextResponse> {
const { pathname } = request.nextUrl
const isPublic = PUBLIC_PATHS.some((path) => pathname === path || pathname.startsWith(path + '/'))
const isStatic =
pathname.startsWith('/_next') || pathname.startsWith('/static') || pathname.includes('.')
const isStatic = isStaticAssetPath(pathname)
const sessionCookie = request.cookies.get('d3ro_admin_session')?.value
const isAuthenticated = sessionCookie ? (await verifyEdgeSession(sessionCookie)) !== null : false
if (!isAuthenticated && !isPublic && !isStatic) {
const loginUrl = new URL('/login', request.url)
if (pathname !== '/') loginUrl.searchParams.set('redirect', pathname)
const safeRedirect = safeAdminRedirectPath(pathname)
if (safeRedirect !== '/') loginUrl.searchParams.set('redirect', safeRedirect)
const redirectResponse = NextResponse.redirect(loginUrl)
addSecurityHeaders(redirectResponse)
return redirectResponse

View file

@ -0,0 +1,123 @@
import { NextRequest } from 'next/server'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
isStaticAssetPath,
parseOptionalIsoDate,
resolveAdminCallbackOrigin,
safeAdminRedirectPath,
} from '@/lib/admin-url-safety'
const mockCreateServerClient = vi.fn()
const mockExchangeCodeForSession = vi.fn()
vi.mock('@supabase/ssr', () => ({
createServerClient: (...args: unknown[]) => {
mockCreateServerClient(...args)
return {
auth: {
exchangeCodeForSession: (code: string) => mockExchangeCodeForSession(code),
},
}
},
}))
describe('Admin 라우트 가드 및 OAuth 콜백 보안', () => {
const originalSupabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const originalSupabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
const originalAdminOrigin = process.env.ADMIN_PUBLIC_ORIGIN
afterEach(() => {
vi.clearAllMocks()
process.env.NEXT_PUBLIC_SUPABASE_URL = originalSupabaseUrl
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = originalSupabaseAnonKey
process.env.ADMIN_PUBLIC_ORIGIN = originalAdminOrigin
})
it('proxy_점포함동적경로나API경로미인증접근_정적으로우회하지않고로그인으로차단한다', async () => {
const { proxy } = await import('@/proxy')
const dottedUserRoute = new NextRequest('https://admin.chanpaca.net/users/john.doe')
const userRes = await proxy(dottedUserRoute)
expect(userRes.status).toBe(307)
expect(userRes.headers.get('location')).toBe(
'https://admin.chanpaca.net/login?redirect=%2Fusers%2Fjohn.doe',
)
const dottedApiRoute = new NextRequest('https://admin.chanpaca.net/api/audit.export')
const apiRes = await proxy(dottedApiRoute)
expect(apiRes.status).toBe(307)
expect(apiRes.headers.get('location')).toBe(
'https://admin.chanpaca.net/login?redirect=%2Fapi%2Faudit.export',
)
const staticAsset = new NextRequest('https://admin.chanpaca.net/static/logo.png')
const staticRes = await proxy(staticAsset)
expect(staticRes.status).toBe(200)
expect(isStaticAssetPath('/api/logo.png')).toBe(false)
expect(isStaticAssetPath('/_next/static/chunk.js')).toBe(true)
})
it('safeAdminRedirectPath_외부URL이나프로토콜상대경로_루트로폴백한다', () => {
expect(safeAdminRedirectPath('https://evil.example/phish')).toBe('/')
expect(safeAdminRedirectPath('//evil.example/phish')).toBe('/')
expect(safeAdminRedirectPath('/\\evil.example')).toBe('/')
expect(safeAdminRedirectPath('/users\r\n')).toBe('/')
expect(safeAdminRedirectPath('/users/123?tab=billing')).toBe('/users/123?tab=billing')
})
it('parseOptionalIsoDate_유효하지않은날짜입력_예외없이오류를반환한다', () => {
expect(parseOptionalIsoDate('')).toEqual({ ok: true, iso: undefined })
expect(parseOptionalIsoDate('2026-12-31')).toEqual({
ok: true,
iso: '2026-12-31T00:00:00.000Z',
})
expect(parseOptionalIsoDate('invalid-date-value')).toEqual({
ok: false,
message: '올바른 종료일 형식이 아닙니다.',
})
})
it('authCallback_GET_Supabase환경변수누락시_빈문자클라이언트생성없이실패닫힘으로리다이렉트한다', async () => {
delete process.env.NEXT_PUBLIC_SUPABASE_URL
delete process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
const { GET } = await import('@/app/auth/callback/route')
const req = new NextRequest('https://admin.chanpaca.net/auth/callback?code=fake-oauth-code')
const res = await GET(req)
expect(res.status).toBe(307)
expect(mockCreateServerClient).not.toHaveBeenCalled()
expect(res.headers.get('location')).toBe('https://admin.chanpaca.net/login?error=auth_unavailable')
})
it('authCallback_GET_세션교환실패시_원시에러노출없이고정코드로리다이렉트한다', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'public-anon-example'
mockExchangeCodeForSession.mockResolvedValue({
error: { message: 'internal error http://10.0.0.5:5432' },
})
const { GET } = await import('@/app/auth/callback/route')
const req = new NextRequest('https://admin.chanpaca.net/auth/callback?code=fake-oauth-code')
const res = await GET(req)
expect(res.status).toBe(307)
const location = res.headers.get('location') ?? ''
expect(location).toBe('https://admin.chanpaca.net/login?error=oauth_callback_failed')
expect(location).not.toContain('10.0.0.5')
})
it('authCallback_GET_공개origin설정과위험한next파라미터_공개도메인루트로만이동한다', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://example.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'public-anon-example'
process.env.ADMIN_PUBLIC_ORIGIN = 'https://admin.chanpaca.net/ignored-path'
mockExchangeCodeForSession.mockResolvedValue({ error: null })
const { GET } = await import('@/app/auth/callback/route')
const req = new NextRequest('http://127.0.0.1:3001/auth/callback?code=ok-code&next=//evil.example')
const res = await GET(req)
expect(res.status).toBe(307)
expect(res.headers.get('location')).toBe('https://admin.chanpaca.net/')
expect(
resolveAdminCallbackOrigin('http://127.0.0.1:3001/auth/callback', 'javascript:alert(1)'),
).toBe('http://127.0.0.1:3001')
})
})

View file

@ -0,0 +1,19 @@
import path from 'node:path'
import { defineConfig } from 'vitest/config'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
esbuild: {
jsx: 'automatic',
},
test: {
globals: false,
environment: 'node',
include: ['tests/**/*.test.{ts,tsx}'],
testTimeout: 10000,
},
})

View file

@ -0,0 +1,507 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using D3ROVoice.Api.Controllers;
using D3ROVoice.Api.Data;
using D3ROVoice.Api.Dtos;
using D3ROVoice.Api.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace D3ROVoice.Api.Tests;
public class EndpointSecurityAndSttProxyTests
{
private static readonly byte[] SampleWav = BuildTinyWavBytes();
[Theory]
[InlineData("https://169.254.169.254/latest/meta-data", "OpenAI")]
[InlineData("https://10.0.0.1/v1/chat/completions", "OpenAI")]
[InlineData("https://172.16.0.10/v1/chat/completions", "OpenAI")]
[InlineData("https://192.168.1.50/v1/chat/completions", "OpenAI")]
[InlineData("https://100.64.0.5/v1/chat/completions", "OpenAI")]
[InlineData("https://[::1]/v1/chat/completions", "OpenAI")]
[InlineData("https://[fe80::1]/v1/chat/completions", "OpenAI")]
[InlineData("https://metadata.google.internal/computeMetadata/v1", "OpenAI")]
[InlineData("http://localhost:11434/api/generate", "OpenAI")]
public async Task CreateEndpoint_내부SSRF및허용되지않은루프백URL_BadRequest로차단한다(string url, string provider)
{
await using var harness = await ApiHarness.CreateAsync();
var result = await harness.AdminController.CreateEndpoint(new CreateModelEndpointDto(
ModelId: "test-model",
ModelName: "Test Model",
Provider: provider,
EndpointUrl: url,
ApiKey: "sk-test",
CostPer1kPromptTokens: 0.001m,
CostPer1kCompletionTokens: 0.002m,
Memo: "security-audit-test"));
Assert.IsType<BadRequestObjectResult>(result);
Assert.Empty(await harness.Db.ModelEndpoints.ToListAsync());
}
[Fact]
public async Task CreateEndpoint_URL자격증명포함시_BadRequest로차단한다()
{
await using var harness = await ApiHarness.CreateAsync();
var urlWithUserInfo = new UriBuilder("https", "api.openai.com")
{
UserName = "user",
Password = "pass",
Path = "/v1/chat/completions",
}.Uri.AbsoluteUri;
var result = await harness.AdminController.CreateEndpoint(new CreateModelEndpointDto(
ModelId: "test-model",
ModelName: "Test Model",
Provider: "OpenAI",
EndpointUrl: urlWithUserInfo,
ApiKey: "sk-test",
CostPer1kPromptTokens: 0.001m,
CostPer1kCompletionTokens: 0.002m,
Memo: "security-audit-test"));
Assert.IsType<BadRequestObjectResult>(result);
Assert.Empty(await harness.Db.ModelEndpoints.ToListAsync());
}
[Fact]
public async Task CreateEndpoint_로컬Ollama와공개HTTPS엔드포인트_정상생성한다()
{
await using var harness = await ApiHarness.CreateAsync();
var ollamaResult = await harness.AdminController.CreateEndpoint(new CreateModelEndpointDto(
ModelId: "ollama-gemma",
ModelName: "Ollama Local",
Provider: "Ollama Local",
EndpointUrl: "http://localhost:11434/api/generate",
ApiKey: "",
CostPer1kPromptTokens: 0m,
CostPer1kCompletionTokens: 0m,
Memo: "security-audit-test"));
Assert.IsType<OkObjectResult>(ollamaResult);
harness.SetNewIdempotencyKey();
var publicResult = await harness.AdminController.CreateEndpoint(new CreateModelEndpointDto(
ModelId: "openai-gpt",
ModelName: "GPT",
Provider: "OpenAI",
EndpointUrl: "https://api.openai.com/v1/chat/completions",
ApiKey: "sk-live",
CostPer1kPromptTokens: 0.001m,
CostPer1kCompletionTokens: 0.002m,
Memo: "security-audit-test"));
Assert.IsType<OkObjectResult>(publicResult);
Assert.Equal(2, await harness.Db.ModelEndpoints.CountAsync());
}
[Fact]
public async Task CreateSttEndpoint_내부SSRF주소와NaN온도및원격루프백_BadRequest로차단한다()
{
await using var harness = await ApiHarness.CreateAsync();
var metadataBlocked = await harness.AdminController.CreateSttEndpoint(new CreateSttEndpointDto(
Name: "Metadata",
ProviderType: "groq",
EndpointUrl: "https://169.254.169.254/latest/meta-data",
ApiKey: "k",
ModelId: "whisper-large-v3",
Method: "multipart",
Language: "ko",
Prompt: null,
Temperature: 0.0,
CostPerMinute: 0m,
CostPerSecond: 0m,
IsDefault: false,
IsActive: true,
FallbackPriority: 1,
ExtraHeadersJson: null,
Memo: "security-audit-test"));
Assert.IsType<BadRequestObjectResult>(metadataBlocked);
harness.SetNewIdempotencyKey();
var remoteLoopbackBlocked = await harness.AdminController.CreateSttEndpoint(new CreateSttEndpointDto(
Name: "RemoteLoopback",
ProviderType: "groq",
EndpointUrl: "http://127.0.0.1:8971/stt/transcribe",
ApiKey: "k",
ModelId: "whisper-large-v3",
Method: "multipart",
Language: "ko",
Prompt: null,
Temperature: 0.0,
CostPerMinute: 0m,
CostPerSecond: 0m,
IsDefault: false,
IsActive: true,
FallbackPriority: 1,
ExtraHeadersJson: null,
Memo: "security-audit-test"));
Assert.IsType<BadRequestObjectResult>(remoteLoopbackBlocked);
harness.SetNewIdempotencyKey();
var nanTempBlocked = await harness.AdminController.CreateSttEndpoint(new CreateSttEndpointDto(
Name: "BadTemp",
ProviderType: "groq",
EndpointUrl: "https://api.groq.com/openai/v1/audio/transcriptions",
ApiKey: "k",
ModelId: "whisper-large-v3",
Method: "multipart",
Language: "ko",
Prompt: null,
Temperature: double.NaN,
CostPerMinute: 0m,
CostPerSecond: 0m,
IsDefault: false,
IsActive: true,
FallbackPriority: 1,
ExtraHeadersJson: null,
Memo: "security-audit-test"));
Assert.IsType<BadRequestObjectResult>(nanTempBlocked);
harness.SetNewIdempotencyKey();
var localSidecarOk = await harness.AdminController.CreateSttEndpoint(new CreateSttEndpointDto(
Name: "Sidecar",
ProviderType: "local-sidecar",
EndpointUrl: "http://localhost:8971/stt/transcribe",
ApiKey: "",
ModelId: "whisper-large-v3-turbo",
Method: "multipart",
Language: "ko",
Prompt: null,
Temperature: 0.0,
CostPerMinute: 0m,
CostPerSecond: 0m,
IsDefault: false,
IsActive: true,
FallbackPriority: 2,
ExtraHeadersJson: null,
Memo: "security-audit-test"));
Assert.IsType<OkObjectResult>(localSidecarOk);
}
[Theory]
[InlineData("https://169.254.169.254/latest/meta-data")]
[InlineData("http://127.0.0.1:8971/stt/transcribe")]
[InlineData("https://10.0.0.5/stt")]
public async Task TestSttDirect_내부및루프백URL_요청없이BadRequest로차단한다(string url)
{
await using var harness = await ApiHarness.CreateAsync();
var result = await harness.AdminController.TestSttDirect(new DirectSttTestDto(url, "sk-test"));
Assert.IsType<BadRequestObjectResult>(result);
Assert.Empty(harness.CapturedRequests);
}
[Fact]
public async Task TranscribeAsync_악의적언어문자열_쿼리및프롬프트인젝션을차단한다()
{
await using var harness = await ApiHarness.CreateAsync();
harness.Db.SttProviderEndpoints.Add(new SttProviderEndpoint
{
Name = "Deepgram",
ProviderType = "deepgram",
EndpointUrl = "https://api.deepgram.com/v1/listen",
ApiKey = "dg-secret",
ModelId = "nova-3",
Method = "binary-stream",
Language = "ko",
IsDefault = true,
IsActive = true,
FallbackPriority = 1,
});
await harness.Db.SaveChangesAsync();
await Assert.ThrowsAsync<ArgumentException>(() =>
harness.SttService.TranscribeAsync(
1,
"user@d3ro.test",
new SttTranscribeRequest(Language: "ko&callback=https://attacker.test/hook"),
SampleWav,
"audio/wav",
"clip.wav",
recordUsage: false));
Assert.Empty(harness.CapturedRequests);
}
[Fact]
public async Task TranscribeAsync_특수문자포함모델ID_Deepgram쿼리를URL인코딩한다()
{
await using var harness = await ApiHarness.CreateAsync(_ => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("""{"results":{"channels":[{"alternatives":[{"transcript":"hello","confidence":0.99}]}]},"metadata":{"duration":1.2}}""", Encoding.UTF8, "application/json")
});
harness.Db.SttProviderEndpoints.Add(new SttProviderEndpoint
{
Name = "Deepgram",
ProviderType = "deepgram",
EndpointUrl = "https://api.deepgram.com/v1/listen",
ApiKey = "dg-secret",
ModelId = "nova-3&tier=enterprise",
Method = "binary-stream",
Language = "ko",
IsDefault = true,
IsActive = true,
FallbackPriority = 1,
});
await harness.Db.SaveChangesAsync();
var res = await harness.SttService.TranscribeAsync(
1,
"user@d3ro.test",
new SttTranscribeRequest(Language: "ko-KR"),
SampleWav,
"audio/wav",
"clip.wav",
recordUsage: false);
Assert.Equal("hello", res.Text);
var captured = Assert.Single(harness.CapturedRequests);
Assert.Contains("model=nova-3%26tier%3Denterprise", captured.RequestUri!.Query, StringComparison.Ordinal);
Assert.DoesNotContain("&tier=enterprise", captured.RequestUri!.Query, StringComparison.Ordinal);
}
[Theory]
[InlineData("openai", "https://api.openai.com/v1/audio/transcriptions", """{"text":"안녕","duration":1.0,"language":"ko"}""")]
[InlineData("deepgram", "https://api.deepgram.com/v1/listen", """{"results":{"channels":[{"alternatives":[{"transcript":"안녕","confidence":0.95}]}]},"metadata":{"duration":1.0}}""")]
[InlineData("google", "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent", """{"candidates":[{"content":{"parts":[{"text":"안녕"}]}}]}""")]
[InlineData("azure", "https://koreacentral.stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1", """{"DisplayText":"안녕"}""")]
public async Task TranscribeAsync_앞뒤공백및개행포함ApiKey_Trim후정상전송한다(string providerType, string url, string jsonBody)
{
await using var harness = await ApiHarness.CreateAsync(_ => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
});
harness.Db.SttProviderEndpoints.Add(new SttProviderEndpoint
{
Name = providerType,
ProviderType = providerType,
EndpointUrl = url,
ApiKey = " secret-token-with-whitespace \r\n",
ModelId = "model-1",
Method = "multipart",
Language = "ko",
IsDefault = true,
IsActive = true,
FallbackPriority = 1,
});
await harness.Db.SaveChangesAsync();
var res = await harness.SttService.TranscribeAsync(
1,
"user@d3ro.test",
new SttTranscribeRequest(Language: "ko"),
SampleWav,
"audio/wav",
"clip.wav",
recordUsage: false);
Assert.Equal("안녕", res.Text);
Assert.Single(harness.CapturedRequests);
}
[Fact]
public async Task TranscribeAsync_AssemblyAI비정상폴링ID_경로탐색요청없이실패폐쇄한다()
{
await using var harness = await ApiHarness.CreateAsync(req =>
{
var path = req.RequestUri!.AbsolutePath;
if (path == "/v2/upload")
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("""{"upload_url":"https://cdn.assemblyai.com/upload/abc"}""", Encoding.UTF8, "application/json")
};
}
if (path == "/v2/transcript")
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("""{"id":"../../secret/leak?x=1"}""", Encoding.UTF8, "application/json")
};
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("""{"status":"completed","text":"bad"}""", Encoding.UTF8, "application/json")
};
});
harness.Db.SttProviderEndpoints.Add(new SttProviderEndpoint
{
Name = "AssemblyAI",
ProviderType = "assemblyai",
EndpointUrl = "https://api.assemblyai.com/v2/transcript",
ApiKey = "aai-secret",
ModelId = "best",
Method = "async-poll",
Language = "ko",
IsDefault = true,
IsActive = true,
FallbackPriority = 1,
});
await harness.Db.SaveChangesAsync();
await Assert.ThrowsAsync<SttProviderUnavailableException>(() =>
harness.SttService.TranscribeAsync(
1,
"user@d3ro.test",
new SttTranscribeRequest(Language: "ko"),
SampleWav,
"audio/wav",
"clip.wav",
recordUsage: false));
Assert.DoesNotContain(harness.CapturedRequests, r => r.RequestUri!.AbsoluteUri.Contains("secret", StringComparison.OrdinalIgnoreCase));
}
[Fact]
public async Task LlmProxyService_DB내부SSRF엔드포인트_네트워크요청없이안전폴백으로실패폐쇄한다()
{
await using var harness = await ApiHarness.CreateAsync();
harness.Db.ModelEndpoints.Add(new ServiceModelEndpoint
{
ModelId = "ssrf-llm",
ModelName = "Evil",
Provider = "OpenAI",
EndpointUrl = "https://169.254.169.254/latest/meta-data",
ApiKey = "sk-should-not-leak",
CostPer1kPromptTokens = 0.001m,
CostPer1kCompletionTokens = 0.002m,
IsActive = true,
});
await harness.Db.SaveChangesAsync();
var res = await harness.LlmService.GenerateAsync(
1,
"user@d3ro.test",
new LlmGenerateRequest("Hello", Model: "ssrf-llm"));
Assert.Empty(harness.CapturedRequests);
Assert.Contains("Fallback", res.Text, StringComparison.Ordinal);
}
private static byte[] BuildTinyWavBytes()
{
var wav = new byte[64];
Encoding.ASCII.GetBytes("RIFF").CopyTo(wav, 0);
Encoding.ASCII.GetBytes("WAVE").CopyTo(wav, 8);
return wav;
}
private sealed class ApiHarness : IAsyncDisposable
{
private readonly SqliteConnection _connection;
public AppDbContext Db { get; }
public AdminController AdminController { get; }
public SttProxyService SttService { get; }
public LlmProxyService LlmService { get; }
public List<HttpRequestMessage> CapturedRequests { get; }
private ApiHarness(
SqliteConnection connection,
AppDbContext db,
AdminController adminController,
SttProxyService sttService,
LlmProxyService llmService,
List<HttpRequestMessage> capturedRequests)
{
_connection = connection;
Db = db;
AdminController = adminController;
SttService = sttService;
LlmService = llmService;
CapturedRequests = capturedRequests;
}
public void SetNewIdempotencyKey()
{
AdminController.ControllerContext.HttpContext.Request.Headers["Idempotency-Key"] = Guid.NewGuid().ToString("D");
}
public static async Task<ApiHarness> CreateAsync(Func<HttpRequestMessage, HttpResponseMessage>? responder = null)
{
var connection = new SqliteConnection("DataSource=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(connection)
.Options;
var db = new AppDbContext(options);
await db.Database.EnsureCreatedAsync();
var captured = new List<HttpRequestMessage>();
var handler = new CaptureHandler(captured, responder);
var httpFactory = new FixedHttpClientFactory(handler);
var sttService = new SttProxyService(db, httpFactory, NullLogger<SttProxyService>.Instance);
var llmService = new LlmProxyService(db, httpFactory, NullLogger<LlmProxyService>.Instance);
var adminOps = new AdminOperationService(db);
var controller = new AdminController(db, sttService, adminOps);
var httpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Email, "admin@d3ro.test"),
new Claim(ClaimTypes.Role, "SuperAdmin"),
}, "TestAuth")),
};
httpContext.Request.Headers["Idempotency-Key"] = Guid.NewGuid().ToString("D");
controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
return new ApiHarness(connection, db, controller, sttService, llmService, captured);
}
public async ValueTask DisposeAsync()
{
await Db.DisposeAsync();
await _connection.DisposeAsync();
}
}
private sealed class FixedHttpClientFactory : IHttpClientFactory
{
private readonly HttpMessageHandler _handler;
public FixedHttpClientFactory(HttpMessageHandler handler) => _handler = handler;
public HttpClient CreateClient(string name) => new(_handler, disposeHandler: false);
}
private sealed class CaptureHandler : HttpMessageHandler
{
private readonly List<HttpRequestMessage> _captured;
private readonly Func<HttpRequestMessage, HttpResponseMessage>? _responder;
public CaptureHandler(List<HttpRequestMessage> captured, Func<HttpRequestMessage, HttpResponseMessage>? responder)
{
_captured = captured;
_responder = responder;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
_captured.Add(request);
var resp = _responder?.Invoke(request) ?? new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
return Task.FromResult(resp);
}
}
}

View file

@ -105,7 +105,8 @@ public class AdminController : ControllerBase
public async Task<IActionResult> CreateEndpoint([FromBody] CreateModelEndpointDto dto)
{
if (string.IsNullOrWhiteSpace(dto.ModelId) || string.IsNullOrWhiteSpace(dto.ModelName)
|| string.IsNullOrWhiteSpace(dto.Provider) || !IsValidEndpointUrl(dto.EndpointUrl)
|| string.IsNullOrWhiteSpace(dto.Provider)
|| !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForLlmProvider(dto.Provider))
|| dto.CostPer1kPromptTokens < 0 || dto.CostPer1kCompletionTokens < 0)
{
return BadRequest(new { message = "모델 식별자, 공급자, 유효한 HTTP(S) URL과 0 이상의 비용이 필요합니다." });
@ -145,7 +146,8 @@ public class AdminController : ControllerBase
public async Task<IActionResult> UpdateEndpoint(int id, [FromBody] UpdateModelEndpointDto dto)
{
if (id <= 0 || string.IsNullOrWhiteSpace(dto.ModelName) || string.IsNullOrWhiteSpace(dto.Provider)
|| !IsValidEndpointUrl(dto.EndpointUrl) || dto.CostPer1kPromptTokens < 0 || dto.CostPer1kCompletionTokens < 0)
|| !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForLlmProvider(dto.Provider))
|| dto.CostPer1kPromptTokens < 0 || dto.CostPer1kCompletionTokens < 0)
return BadRequest(new { message = "유효한 모델 엔드포인트 값이 필요합니다." });
return await ExecuteAdminMutationAsync(
@ -219,7 +221,10 @@ public class AdminController : ControllerBase
[Authorize(Policy = "AdminOrAbove")]
public async Task<IActionResult> CreateSttEndpoint([FromBody] CreateSttEndpointDto dto)
{
if (string.IsNullOrWhiteSpace(dto.Name) || !IsValidEndpointUrl(dto.EndpointUrl)
if (string.IsNullOrWhiteSpace(dto.Name)
|| !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForSttProvider(dto.ProviderType))
|| !EndpointUrlPolicy.IsValidFiniteDouble(dto.Temperature, 0.0, 2.0)
|| !EndpointUrlPolicy.TryValidateLanguageCode(dto.Language)
|| dto.CostPerMinute < 0 || dto.CostPerSecond < 0 || dto.FallbackPriority < 1)
{
return BadRequest(new { message = "유효한 STT 이름, HTTP(S) URL, 비용, 우선순위가 필요합니다." });
@ -239,7 +244,10 @@ public class AdminController : ControllerBase
[Authorize(Policy = "AdminOrAbove")]
public async Task<IActionResult> UpdateSttEndpoint(int id, [FromBody] UpdateSttEndpointDto dto)
{
if (id <= 0 || string.IsNullOrWhiteSpace(dto.Name) || !IsValidEndpointUrl(dto.EndpointUrl)
if (id <= 0 || string.IsNullOrWhiteSpace(dto.Name)
|| !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForSttProvider(dto.ProviderType))
|| !EndpointUrlPolicy.IsValidFiniteDouble(dto.Temperature, 0.0, 2.0)
|| !EndpointUrlPolicy.TryValidateLanguageCode(dto.Language)
|| dto.CostPerMinute < 0 || dto.CostPerSecond < 0 || dto.FallbackPriority < 1)
return BadRequest(new { message = "유효한 STT 엔드포인트 값이 필요합니다." });
@ -311,7 +319,8 @@ public class AdminController : ControllerBase
[Authorize(Policy = "AdminOrAbove")]
public async Task<IActionResult> TestSttDirect([FromBody] DirectSttTestDto dto)
{
if (!IsValidEndpointUrl(dto.EndpointUrl) || !Uri.TryCreate(dto.EndpointUrl, UriKind.Absolute, out var endpointUri))
if (!EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, allowLoopback: false)
|| !Uri.TryCreate(dto.EndpointUrl, UriKind.Absolute, out var endpointUri))
{
return BadRequest(new { message = "유효한 HTTP(S) Endpoint URL이 필요합니다." });
}
@ -432,13 +441,6 @@ public class AdminController : ControllerBase
endpoint.CreatedAt
};
private static bool IsValidEndpointUrl(string? value)
{
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri) || !string.IsNullOrEmpty(uri.UserInfo)) return false;
if (uri.Scheme == Uri.UriSchemeHttp) return uri.IsLoopback;
return uri.Scheme == Uri.UriSchemeHttps;
}
private async Task<IActionResult> ExecuteAdminMutationAsync(
string operation,
object request,

View file

@ -101,9 +101,9 @@ public class SttController : ControllerBase
{
return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "stt_provider_unavailable" });
}
catch (ArgumentException)
catch (ArgumentException ex)
{
return BadRequest(new { error = "invalid_audio" });
return BadRequest(new { error = ex.ParamName == "language" ? "invalid_language" : "invalid_audio" });
}
catch
{

View file

@ -16,6 +16,11 @@ var releaseVersion = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Ve
// Add Services to Container
builder.Services.AddControllers();
builder.Services.AddHttpClient();
builder.Services.AddHttpClient("UpstreamNoRedirect")
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AllowAutoRedirect = false
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddRateLimiter(options =>
{

View file

@ -0,0 +1,174 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
namespace D3ROVoice.Api.Services;
/// <summary>
/// Central validation rules for upstream model/STT endpoint URLs, language parameters,
/// numeric bounds, and provider identifiers to prevent SSRF, query/prompt injection, and NaN leaks.
/// </summary>
public static partial class EndpointUrlPolicy
{
private static readonly string[] BlockedHostSuffixes =
[
".localhost",
".local",
".internal",
".localdomain",
".home.arpa"
];
[GeneratedRegex("^(?:auto|[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,2})$", RegexOptions.CultureInvariant)]
private static partial Regex LanguageTagRegex();
[GeneratedRegex("^[A-Za-z0-9_-]{1,128}$", RegexOptions.CultureInvariant)]
private static partial Regex AssemblyAiIdRegex();
public static bool AllowsLoopbackForLlmProvider(string? provider)
{
if (string.IsNullOrWhiteSpace(provider)) return false;
var trimmed = provider.Trim();
return trimmed.Contains("ollama", StringComparison.OrdinalIgnoreCase)
|| trimmed.Equals("local", StringComparison.OrdinalIgnoreCase)
|| trimmed.Equals("local-sidecar", StringComparison.OrdinalIgnoreCase);
}
public static bool AllowsLoopbackForSttProvider(string? providerType)
{
if (string.IsNullOrWhiteSpace(providerType)) return false;
return providerType.Trim().Equals("local-sidecar", StringComparison.OrdinalIgnoreCase);
}
public static bool IsValidEndpointUrl(string? value, bool allowLoopback = false)
{
if (string.IsNullOrWhiteSpace(value)) return false;
if (!Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri)) return false;
if (!string.IsNullOrEmpty(uri.UserInfo)) return false;
var isHttp = uri.Scheme == Uri.UriSchemeHttp;
var isHttps = uri.Scheme == Uri.UriSchemeHttps;
if (!isHttp && !isHttps) return false;
var host = uri.IdnHost.Trim().TrimEnd('.');
if (string.IsNullOrWhiteSpace(host)) return false;
if (IPAddress.TryParse(host, out var ip))
{
if (ip.IsIPv4MappedToIPv6) ip = ip.MapToIPv4();
if (IPAddress.IsLoopback(ip))
{
return allowLoopback;
}
if (!isHttps || IsNonPublicIp(ip))
{
return false;
}
return true;
}
if (isHttp && !IsLoopbackHostname(host))
{
return false;
}
if (IsLoopbackHostname(host))
{
return allowLoopback;
}
foreach (var suffix in BlockedHostSuffixes)
{
if (host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
// Reject single-label internal service names (e.g., "redis", "metadata") and raw integer aliases.
if (!host.Contains('.', StringComparison.Ordinal))
{
return false;
}
return isHttps;
}
public static string ValidateLanguageCode(string? rawLanguage, string fallback = "ko")
{
if (string.IsNullOrWhiteSpace(rawLanguage))
{
return fallback;
}
var trimmed = rawLanguage.Trim();
if (trimmed.Length > 32 || !LanguageTagRegex().IsMatch(trimmed))
{
throw new ArgumentException("Invalid language code format.", "language");
}
return trimmed;
}
public static bool TryValidateLanguageCode(string? rawLanguage)
{
if (string.IsNullOrWhiteSpace(rawLanguage)) return true;
var trimmed = rawLanguage.Trim();
return trimmed.Length <= 32 && LanguageTagRegex().IsMatch(trimmed);
}
public static bool IsValidFiniteDouble(double value, double min, double max) =>
double.IsFinite(value) && value >= min && value <= max;
public static bool IsValidAssemblyAiTranscriptId(string? id) =>
!string.IsNullOrWhiteSpace(id) && AssemblyAiIdRegex().IsMatch(id.Trim());
private static bool IsLoopbackHostname(string host) =>
host.Equals("localhost", StringComparison.OrdinalIgnoreCase)
|| host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase);
private static bool IsNonPublicIp(IPAddress ip)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
var bytes = ip.GetAddressBytes();
return bytes[0] switch
{
0 => true, // 0.0.0.0/8 unspecified
10 => true, // 10.0.0.0/8 RFC1918
100 when bytes[1] is >= 64 and <= 127 => true, // 100.64.0.0/10 CGNAT
127 => true, // 127.0.0.0/8 loopback
169 when bytes[1] == 254 => true, // 169.254.0.0/16 link-local & cloud metadata
172 when bytes[1] is >= 16 and <= 31 => true, // 172.16.0.0/12 RFC1918
192 when bytes[1] == 0 && bytes[2] == 0 => true, // 192.0.0.0/24 IETF protocol assignments
192 when bytes[1] == 0 && bytes[2] == 2 => true, // TEST-NET-1
192 when bytes[1] == 168 => true, // 192.168.0.0/16 RFC1918
198 when bytes[1] is 18 or 19 => true, // 198.18.0.0/15 benchmark
>= 224 => true, // multicast / reserved / broadcast
_ => false,
};
}
if (ip.AddressFamily == AddressFamily.InterNetworkV6)
{
if (ip.Equals(IPAddress.IPv6Any) || ip.Equals(IPAddress.IPv6None) || ip.Equals(IPAddress.IPv6Loopback))
{
return true;
}
if (ip.IsIPv6LinkLocal || ip.IsIPv6Multicast || ip.IsIPv6SiteLocal)
{
return true;
}
var bytes = ip.GetAddressBytes();
// fc00::/7 Unique Local Addresses (ULA)
if ((bytes[0] & 0xfe) == 0xfc)
{
return true;
}
return false;
}
return true;
}
}

View file

@ -73,7 +73,14 @@ public class LlmProxyService : ILlmProxyService
{
try
{
using var client = _httpClientFactory.CreateClient();
if (!EndpointUrlPolicy.IsValidEndpointUrl(
endpoint.EndpointUrl,
EndpointUrlPolicy.AllowsLoopbackForLlmProvider(endpoint.Provider)))
{
throw new InvalidOperationException("Configured model endpoint URL is not permitted.");
}
using var client = _httpClientFactory.CreateClient("UpstreamNoRedirect");
client.Timeout = TimeSpan.FromSeconds(60);
var payload = new
@ -93,9 +100,10 @@ public class LlmProxyService : ILlmProxyService
Content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json")
};
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
var trimmedKey = endpoint.ApiKey?.Trim();
if (!string.IsNullOrWhiteSpace(trimmedKey))
{
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey);
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", trimmedKey);
}
using var httpResponse = await client.SendAsync(httpRequest, cancellationToken);

View file

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
@ -82,6 +83,15 @@ public class SttProxyService : ISttProxyService
{
cancellationToken.ThrowIfCancellationRequested();
if (!string.IsNullOrWhiteSpace(request.Language))
{
EndpointUrlPolicy.ValidateLanguageCode(request.Language);
}
if (request.Temperature is { } requestedTemp && !EndpointUrlPolicy.IsValidFiniteDouble(requestedTemp, 0.0, 2.0))
{
throw new ArgumentException("Temperature must be finite and between 0.0 and 2.0.", "temperature");
}
// 1. Resolve Audio Bytes
byte[] finalAudioBytes;
if (audioBytes != null && audioBytes.Length > 0)
@ -296,11 +306,18 @@ public class SttProxyService : ISttProxyService
CancellationToken cancellationToken
)
{
using var client = _httpClientFactory.CreateClient();
var providerType = endpoint.ProviderType.ToLowerInvariant();
if (!EndpointUrlPolicy.IsValidEndpointUrl(
endpoint.EndpointUrl,
EndpointUrlPolicy.AllowsLoopbackForSttProvider(providerType)))
{
throw new InvalidOperationException("STT provider endpoint URL is not permitted.");
}
using var client = _httpClientFactory.CreateClient("UpstreamNoRedirect");
client.Timeout = TimeSpan.FromSeconds(90);
var providerType = endpoint.ProviderType.ToLowerInvariant();
var apiKey = endpoint.ApiKey?.Trim() ?? "";
var apiKey = GetTrimmedApiKey(endpoint);
if (RequiresApiKey(providerType) && string.IsNullOrWhiteSpace(apiKey))
{
@ -360,8 +377,8 @@ public class SttProxyService : ISttProxyService
form.Add(new StringContent(endpoint.ModelId), "model");
var language = request.Language ?? endpoint.Language ?? "ko";
if (!string.IsNullOrWhiteSpace(language) && language != "auto")
var language = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko");
if (language != "auto")
{
form.Add(new StringContent(language), "language");
}
@ -373,7 +390,8 @@ public class SttProxyService : ISttProxyService
}
var temp = request.Temperature ?? endpoint.Temperature;
form.Add(new StringContent(temp.ToString("0.0")), "temperature");
if (!EndpointUrlPolicy.IsValidFiniteDouble(temp, 0.0, 2.0)) temp = 0.0;
form.Add(new StringContent(temp.ToString("0.0", CultureInfo.InvariantCulture)), "temperature");
form.Add(new StringContent("verbose_json"), "response_format");
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
@ -381,9 +399,10 @@ public class SttProxyService : ISttProxyService
Content = form
};
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
var apiKey = GetTrimmedApiKey(endpoint);
if (!string.IsNullOrWhiteSpace(apiKey))
{
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey);
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
}
ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson);
@ -423,12 +442,11 @@ public class SttProxyService : ISttProxyService
CancellationToken cancellationToken
)
{
var lang = request.Language ?? endpoint.Language ?? "ko";
var model = endpoint.ModelId ?? "nova-3";
var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko");
var model = string.IsNullOrWhiteSpace(endpoint.ModelId) ? "nova-3" : endpoint.ModelId.Trim();
var baseUrl = endpoint.EndpointUrl.TrimEnd('/');
var url = baseUrl.Contains("?")
? $"{baseUrl}&model={model}&language={lang}&smart_format=true&punctuate=true"
: $"{baseUrl}?model={model}&language={lang}&smart_format=true&punctuate=true";
var separator = baseUrl.Contains('?', StringComparison.Ordinal) ? "&" : "?";
var url = $"{baseUrl}{separator}model={Uri.EscapeDataString(model)}&language={Uri.EscapeDataString(lang)}&smart_format=true&punctuate=true";
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
{
@ -436,9 +454,10 @@ public class SttProxyService : ISttProxyService
};
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
var apiKey = GetTrimmedApiKey(endpoint);
if (!string.IsNullOrWhiteSpace(apiKey))
{
httpRequest.Headers.Add("Authorization", $"Token {endpoint.ApiKey}");
httpRequest.Headers.Add("Authorization", $"Token {apiKey}");
}
ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson);
@ -484,13 +503,12 @@ public class SttProxyService : ISttProxyService
)
{
var base64Audio = Convert.ToBase64String(audioBytes);
var lang = request.Language ?? endpoint.Language ?? "ko";
var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko");
var apiKey = GetTrimmedApiKey(endpoint);
// If endpoint is Gemini Flash Multimodal API
if (endpoint.EndpointUrl.Contains("generativelanguage.googleapis.com") || endpoint.ModelId.Contains("gemini"))
{
var apiKey = endpoint.ApiKey;
var geminiPayload = new
{
contents = new[]
@ -543,8 +561,6 @@ public class SttProxyService : ISttProxyService
else
{
// Google Cloud Speech-to-Text v1
var apiKey = endpoint.ApiKey;
var gcpPayload = new
{
config = new
@ -606,20 +622,25 @@ public class SttProxyService : ISttProxyService
CancellationToken cancellationToken
)
{
var apiKey = GetTrimmedApiKey(endpoint);
// 1. Upload audio
using var uploadRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.assemblyai.com/v2/upload")
{
Content = new ByteArrayContent(audioBytes)
};
uploadRequest.Headers.Add("Authorization", endpoint.ApiKey);
uploadRequest.Headers.Add("Authorization", apiKey);
var uploadBody = await SendForStringAsync(client, uploadRequest, cancellationToken);
using var uploadDoc = JsonDocument.Parse(uploadBody);
var uploadUrl = uploadDoc.RootElement.GetProperty("upload_url").GetString()!;
var uploadUrl = uploadDoc.RootElement.GetProperty("upload_url").GetString();
if (!EndpointUrlPolicy.IsValidEndpointUrl(uploadUrl, allowLoopback: false))
{
throw new JsonException("AssemblyAI returned an invalid upload URL.");
}
// 2. Submit transcript job
var lang = request.Language ?? endpoint.Language ?? "ko";
var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko");
var transcriptPayload = new
{
audio_url = uploadUrl,
@ -632,19 +653,24 @@ public class SttProxyService : ISttProxyService
{
Content = new StringContent(JsonSerializer.Serialize(transcriptPayload), Encoding.UTF8, "application/json")
};
transRequest.Headers.Add("Authorization", endpoint.ApiKey);
transRequest.Headers.Add("Authorization", apiKey);
var transBody = await SendForStringAsync(client, transRequest, cancellationToken);
using var transDoc = JsonDocument.Parse(transBody);
var id = transDoc.RootElement.GetProperty("id").GetString()!;
var id = transDoc.RootElement.GetProperty("id").GetString();
if (!EndpointUrlPolicy.IsValidAssemblyAiTranscriptId(id))
{
throw new JsonException("AssemblyAI returned an invalid transcript identifier.");
}
var safeId = Uri.EscapeDataString(id!.Trim());
// 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}");
pollReq.Headers.Add("Authorization", endpoint.ApiKey);
using var pollReq = new HttpRequestMessage(HttpMethod.Get, $"https://api.assemblyai.com/v2/transcript/{safeId}");
pollReq.Headers.Add("Authorization", apiKey);
var pollBody = await SendForStringAsync(client, pollReq, cancellationToken);
@ -683,12 +709,11 @@ public class SttProxyService : ISttProxyService
CancellationToken cancellationToken
)
{
var lang = request.Language ?? endpoint.Language ?? "ko-KR";
var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko-KR");
if (lang == "ko") lang = "ko-KR";
var url = endpoint.EndpointUrl.Contains("?")
? $"{endpoint.EndpointUrl}&language={lang}&format=detailed"
: $"{endpoint.EndpointUrl}?language={lang}&format=detailed";
var separator = endpoint.EndpointUrl.Contains('?', StringComparison.Ordinal) ? "&" : "?";
var url = $"{endpoint.EndpointUrl}{separator}language={Uri.EscapeDataString(lang)}&format=detailed";
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url)
{
@ -696,9 +721,10 @@ public class SttProxyService : ISttProxyService
};
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType.Contains("wav") ? "audio/wav" : "audio/webm");
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
var apiKey = GetTrimmedApiKey(endpoint);
if (!string.IsNullOrWhiteSpace(apiKey))
{
httpRequest.Headers.Add("Ocp-Apim-Subscription-Key", endpoint.ApiKey);
httpRequest.Headers.Add("Ocp-Apim-Subscription-Key", apiKey);
}
var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
@ -746,16 +772,17 @@ public class SttProxyService : ISttProxyService
form.Add(audioContent, "file", fileName);
form.Add(new StringContent(endpoint.ModelId), "model");
form.Add(new StringContent(request.Language ?? endpoint.Language ?? "ko"), "language");
form.Add(new StringContent(ResolveValidatedLanguage(request.Language, endpoint.Language, "ko")), "language");
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl)
{
Content = form
};
if (!string.IsNullOrWhiteSpace(endpoint.ApiKey))
var apiKey = GetTrimmedApiKey(endpoint);
if (!string.IsNullOrWhiteSpace(apiKey))
{
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey);
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
}
var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken);
@ -1061,6 +1088,17 @@ public class SttProxyService : ISttProxyService
};
}
private static string GetTrimmedApiKey(SttProviderEndpoint endpoint) =>
endpoint.ApiKey?.Trim() ?? string.Empty;
private static string ResolveValidatedLanguage(string? requested, string? endpointDefault, string fallback)
{
var candidate = !string.IsNullOrWhiteSpace(requested)
? requested
: (!string.IsNullOrWhiteSpace(endpointDefault) ? endpointDefault : fallback);
return EndpointUrlPolicy.ValidateLanguageCode(candidate, fallback);
}
private static void ApplyExtraHeaders(HttpRequestMessage req, string? extraHeadersJson)
{
if (string.IsNullOrWhiteSpace(extraHeadersJson)) return;

View file

@ -5,6 +5,7 @@ import { ipcMain, session, desktopCapturer } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
import { getCaptionService } from '../services/CaptionService'
import { getLogger } from '../services/LoggerService'
import type { CaptionConfig } from '@d3ro/core/types'
import {
endCaptionOverlayDrag,
@ -13,6 +14,8 @@ import {
startCaptionOverlayDrag
} from '../windows/WindowManager'
const logger = getLogger('CaptionHandlers')
export function registerCaptionHandlers(): void {
// ── 자막 창 손잡이 (팝업 → 메인) ──
ipcMain.on(IPC_CHANNELS.POPUP_CAPTION.SET_INTERACTIVE, (_event, interactive: unknown) => {
@ -25,12 +28,19 @@ export function registerCaptionHandlers(): void {
// 시스템 오디오 루프백: setDisplayMediaRequestHandler로 audio: 'loopback' 설정
ipcMain.handle(IPC_CHANNELS.SYSTEM_AUDIO.ENABLE_LOOPBACK, async () => {
session.defaultSession.setDisplayMediaRequestHandler(async (_request, callback) => {
try {
const sources = await desktopCapturer.getSources({ types: ['screen'] })
if (sources.length === 0) {
callback({})
return
}
callback({ video: sources[0], audio: 'loopback' })
} catch (err) {
logger.warn(
`Display media source lookup failed: ${err instanceof Error ? err.message : String(err)}`,
)
callback({})
}
})
return ipcSuccess(undefined)
})

View file

@ -94,6 +94,7 @@ class AudioCaptureService extends EventEmitter {
private _refCount = 0
private _cachedDevices: AudioDevice[] | null = null
private _soxProcess: ChildProcess | null = null
private _soxExited = false
private _stream: Readable | null = null
private _levelInterval: ReturnType<typeof setInterval> | null = null
/** 새 SoX 를 띄울 때마다 증가 — 임대(lease)가 자기 캡처인지 판단한다 */
@ -155,16 +156,22 @@ class AudioCaptureService extends EventEmitter {
return
}
// 마지막 참조가 꼬리를 받는 중에 새 소비자가 오면 정지를 취소하고 같은 SoX 로 이어 간다
// 마지막 참조가 꼬리를 받는 중에 새 소비자가 오면 SoX가 아직 살아 있을 때만 정지를 취소하고 이어 간다
if (this._state === 'stopping' && this._pendingStopToken !== 0) {
this._pendingStopToken = 0
this._cancelTailWait?.()
if (this._isSoxProcessAlive()) {
this._state = 'capturing'
this._refCount = 1
this._startLevelTimer()
logger.debug('Pending stop cancelled by a new consumer — capture continues')
return
}
this._emitResidual()
this._cleanup()
this._currentDevice = null
this._state = 'idle'
}
if (this._state !== 'idle' && this._state !== 'error') {
logger.warn(`Cannot start capture in state: ${this._state}`)
@ -202,6 +209,7 @@ class AudioCaptureService extends EventEmitter {
logger.info(`SoX args: ${soxArgs.join(' ')}`)
const child = spawn(soxExe, soxArgs, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
this._soxProcess = child
this._soxExited = false
this._generation++
this._stream = child.stdout
this._residualBuffer = Buffer.alloc(0)
@ -222,11 +230,18 @@ class AudioCaptureService extends EventEmitter {
if (msg) logger.warn(`SoX stderr: ${msg}`)
})
child.once('exit', () => {
if (this._soxProcess === child) {
this._soxExited = true
}
})
// SoX 프로세스 종료 감지.
// 자기 프로세스인지 먼저 확인한다 — 예전엔 kill 한 옛 SoX 의 'close' 가 몇 ms 뒤에 와서
// 그사이 시작된 새 캡처('capturing')를 오류로 끝냈다(회의 중 마이크 테스트로 회의 마이크가 끊김).
child.on('close', (code) => {
if (this._soxProcess !== child) return
this._soxExited = true
if (this._state === 'capturing') {
logger.warn(`SoX process exited unexpectedly (code: ${code})`)
this._handleError(
@ -238,6 +253,7 @@ class AudioCaptureService extends EventEmitter {
child.on('error', (err: Error) => {
if (this._soxProcess !== child) return
this._soxExited = true
logger.error(`SoX process spawn error: ${err.message}`)
const hint =
soxExe === 'sox' && (err as NodeJS.ErrnoException).code === 'ENOENT'
@ -264,6 +280,7 @@ class AudioCaptureService extends EventEmitter {
this.emit('started', { deviceId: this._currentDevice.deviceId })
logger.info('Audio capture started')
} catch (error) {
this._cleanup()
this._state = 'error'
const d3roError = new D3ROError(
ErrorCode.AudioCaptureStartFailed,
@ -626,11 +643,19 @@ class AudioCaptureService extends EventEmitter {
this.emit('stopped', { reason: stopReason })
}
/** 현재 보유 중인 SoX 프로세스가 아직 살아 있는지 확인한다 */
private _isSoxProcessAlive(): boolean {
const child = this._soxProcess
if (!child || this._soxExited) return false
return child.exitCode == null && !child.killed
}
/**
* 녹음 프로세스와 타이머를 정리한다.
*/
private _cleanup(): void {
this._stopLevelTimer()
this._soxExited = false
if (this._stream) {
this._stream.removeAllListeners()

View file

@ -128,6 +128,10 @@ class CaptionService extends EventEmitter {
private _captionModelId: string | null = null
private _refineQueue: CaptionSegment[] = []
private _refining = false
private _refineEpoch = 0
private _refineRunId = 0
private _refineController: AbortController | null = null
private _stopPromise: Promise<CaptionSessionResult | null> | null = null
/** 이번 세션이 잡은 오디오 소스(마이크 캡처·시스템 소리 요청) — 해제는 멱등 */
private _audio: CaptionAudioSources = this._createAudioSources()
@ -189,6 +193,9 @@ class CaptionService extends EventEmitter {
if (epoch !== this._startEpoch || this._disposed) throw new CaptionStartCancelledError()
}
let ownAudio: CaptionAudioSources | null = null
let loadedAuxModelId: string | null = null
this._captionModelId = null
this._resetRefineState()
this._setState('starting')
// 오버레이를 즉시 표시 (로딩 상태) — 회의 모드처럼 자체 UI 가 있으면 띄우지 않는다
@ -204,9 +211,13 @@ class CaptionService extends EventEmitter {
await sttService.initialize()
assertCurrent()
// 자막 전용 모델을 골랐으면 받아쓰기 모델과 별도로 올려 둔다(보조 자리).
this._captionModelId = configGet('captionSttModelId') ?? null
if (this._captionModelId) await sttService.ensureAuxModel(this._captionModelId)
const candidateAuxModelId = configGet('captionSttModelId') ?? null
if (candidateAuxModelId) {
await sttService.ensureAuxModel(candidateAuxModelId)
loadedAuxModelId = candidateAuxModelId
}
assertCurrent()
this._captionModelId = loadedAuxModelId
// 세션 초기화
this._sessionId = crypto.randomUUID()
@ -261,7 +272,9 @@ class CaptionService extends EventEmitter {
// 이 시도가 연 자원만 돌려준다(release 는 멱등).
await ownAudio?.release()
// stop() 이 내릴 때 아직 로딩 중이던 보조 모델이 뒤늦게 올라왔을 수 있다. 새 시작이 없을 때만 내린다.
if (this._captionModelId && this._state === 'inactive') void getLocalSTTService().releaseAuxModel()
if (loadedAuxModelId && (this._state === 'inactive' || this._state === 'stopping')) {
void getLocalSTTService().releaseAuxModel()
}
logger.info('캡션 시작 취소: 로딩 중 정지됨')
throw new D3ROError(ErrorCode.CaptionStartFailed, '캡션 시작이 취소되었습니다')
}
@ -274,7 +287,9 @@ class CaptionService extends EventEmitter {
await this._audio.release()
this._hideOverlaySafely()
// 시작 실패(오디오 장치 없음 등)에도 올려 둔 보조 모델을 내린다 — 안 그러면 다음 세션 종료까지 VRAM 을 잡는다.
if (this._captionModelId) void getLocalSTTService().releaseAuxModel()
const auxToRelease = this._captionModelId ?? loadedAuxModelId
this._captionModelId = null
if (auxToRelease) void getLocalSTTService().releaseAuxModel()
this._session = { ...DEFAULT_START_OPTIONS }
this._setState('inactive')
const d3roErr =
@ -299,6 +314,13 @@ class CaptionService extends EventEmitter {
* @returns 세션 요약(세그먼트가 없으면 null), 다른 소유자라 거부했으면 false
*/
async stop(owner?: CaptionOwner): Promise<CaptionSessionResult | null | false> {
if (this._state === 'stopping' && this._stopPromise) {
if (owner && owner !== this._session.owner) {
logger.warn(`캡션 중지 거부: 세션 소유자=${this._session.owner}, 요청=${owner}`)
return false
}
return this._stopPromise
}
if (this._state !== 'active' && this._state !== 'starting') {
logger.warn(`캡션 중지 불가: 현재 상태=${this._state}`)
return null
@ -311,7 +333,14 @@ class CaptionService extends EventEmitter {
// 로딩 중(start 가 모델을 기다리는 중)이면 그 start 를 무효화한다 — 깨어나도 마이크를 열지 않는다.
if (this._state === 'starting') this._startEpoch += 1
this._setState('stopping')
this._resetRefineState()
const stopRun = this._performStop()
this._stopPromise = stopRun
return stopRun
}
private async _performStop(): Promise<CaptionSessionResult | null> {
// 타이머 정리
if (this._tickTimer) {
clearInterval(this._tickTimer)
@ -335,7 +364,9 @@ class CaptionService extends EventEmitter {
this._hideOverlaySafely()
// 자막 전용 보조 모델은 세션이 끝나면 내린다 — 남겨 두면 받아쓰기 모델과 함께 VRAM 을 잡아
// Ollama 로드를 느리게 하거나 OOM 을 부른다. 다음 세션 시작 때 다시 올린다.
if (this._captionModelId) void getLocalSTTService().releaseAuxModel()
const auxToRelease = this._captionModelId
this._captionModelId = null
if (auxToRelease) void getLocalSTTService().releaseAuxModel()
}
// 세션을 히스토리에 저장 (회의 모드처럼 저장을 끈 소유자는 요약만 돌려받는다)
@ -352,6 +383,7 @@ class CaptionService extends EventEmitter {
this._refineQueue = []
this._sessionLanguage = null
this._session = { ...DEFAULT_START_OPTIONS }
this._stopPromise = null
this._setState('inactive')
getSoundEffectService().play('recording-stop')
@ -369,8 +401,9 @@ class CaptionService extends EventEmitter {
async dispose(): Promise<void> {
if (this._disposed) return
this._disposed = true
this._resetRefineState()
if (this._state === 'active' || this._state === 'starting') {
if (this._state === 'active' || this._state === 'starting' || this._state === 'stopping') {
await this.stop()
}
@ -522,7 +555,17 @@ class CaptionService extends EventEmitter {
// ── 내부: 문맥 다듬기 ──
private _resetRefineState(): void {
this._refineEpoch += 1
this._refineRunId += 1
this._refineQueue = []
this._refining = false
this._refineController?.abort()
this._refineController = null
}
private _enqueueRefine(segment: CaptionSegment): void {
if (this._disposed || this._state !== 'active') return
if (configGet('captionRefineEnabled') === false) return
if (!getLocalLLMService().isAvailable()) return
this._refineQueue.push(segment)
@ -532,17 +575,30 @@ class CaptionService extends EventEmitter {
}
private async _drainRefineQueue(): Promise<void> {
const runId = ++this._refineRunId
const epoch = this._refineEpoch
this._refining = true
try {
for (let next = this._refineQueue.shift(); next; next = this._refineQueue.shift()) {
await this._refine(next)
while (
!this._disposed &&
this._state === 'active' &&
epoch === this._refineEpoch &&
this._refineQueue.length > 0
) {
const next = this._refineQueue.shift()
if (!next) break
await this._refine(next, epoch)
}
} finally {
if (this._refineRunId === runId) {
this._refining = false
this._refineController = null
}
}
}
private async _refine(segment: CaptionSegment): Promise<void> {
private async _refine(segment: CaptionSegment, epoch: number): Promise<void> {
if (this._disposed || this._state !== 'active' || epoch !== this._refineEpoch) return
const index = this._segments.findIndex((item) => item.id === segment.id)
if (index === -1) return
const previous = this._segments.slice(Math.max(0, index - 2), index).map((item) => item.text)
@ -552,19 +608,27 @@ class CaptionService extends EventEmitter {
previous,
...(glossary ? { glossary } : {}),
})
const controller = new AbortController()
this._refineController = controller
try {
const result = await getLocalLLMService().generate(text, {
systemPrompt,
temperature: 0,
maxTokens: Math.min(256, segment.text.length * 2 + 32),
timeoutMs: REFINE_TIMEOUT_MS,
signal: controller.signal,
})
if (this._disposed || this._state !== 'active' || epoch !== this._refineEpoch) return
const refined = acceptCaptionRefinement(segment.text, result.text)
if (!refined) return
// 모델이 용어를 다른 표기로 되돌렸을 수 있다 — 정본 표기를 마지막에 다시 강제한다.
this._replaceSegmentText(segment.id, getTranscriptGlossaryService().correct(refined).text)
} catch (err) {
logger.debug(`자막 다듬기 건너뜀: ${err instanceof Error ? err.message : String(err)}`)
} finally {
if (this._refineController === controller) {
this._refineController = null
}
}
}

View file

@ -163,6 +163,8 @@ const PROGRAMMATIC_INSERT_TTL_MS = 10_000
const LEARN_IDLE_FLUSH_MS = 2000
/** diff 붙여넣기 판정(200자)에 걸리기 전에 끊어 저장한다. */
const LEARN_MAX_PENDING_CHARS = 150
/** 오타 자동 교정의 어절 끝/조합 정지 판정(650~690ms)을 넘긴 직후 UIA 스냅샷을 찍는다. */
const TYPO_SETTLE_DELAY_MS = 700
const RETENTION_PRUNE_INTERVAL_MS = 6 * 60 * 60 * 1000
const MAX_READABILITY_APPS = 64
@ -196,6 +198,8 @@ class InputTelemetryService extends EventEmitter {
private _textTimer: NodeJS.Timeout | null = null
/** 디바운스 이후의 settle 스냅샷 — 제안 게이트는 더 늦게 열린다 */
private _settleTimer: NodeJS.Timeout | null = null
/** 제안 비활성·짧은 접두에서도 오타 장문 정지 교정을 놓치지 않도록 700ms 에 스냅샷을 보장한다. */
private _typoSettleTimer: NodeJS.Timeout | null = null
/** 백그라운드 주기 샘플러 — 타이핑이 이어져도 계속 관측한다 */
private _sampleTimer: NodeJS.Timeout | null = null
/** 주기 샘플 스냅샷 진행 중 (중복 방지) */
@ -450,6 +454,10 @@ class InputTelemetryService extends EventEmitter {
clearTimeout(this._settleTimer)
this._settleTimer = null
}
if (this._typoSettleTimer) {
clearTimeout(this._typoSettleTimer)
this._typoSettleTimer = null
}
this.setSuggestionPresentationActive(false)
this._terminalTracker.reset()
this.flushPendingLearning()
@ -575,7 +583,10 @@ class InputTelemetryService extends EventEmitter {
const vk = uiohookCodeToVk(event.keycode)
// 프로그램이 보낸 키(오타 교정의 백스페이스·확정용 공백·Ctrl+V 붙여넣기)만 통계와 버퍼에서 제외한다.
// 치환 도중 사용자가 실제로 누른 일반 글자·한글 키까지 삼키면 글자가 빠지거나 밀리는 버그가 생긴다.
if (this._programmaticKeys > 0 && Date.now() <= this._programmaticKeysUntil) {
if (this._programmaticKeys > 0) {
if (Date.now() > this._programmaticKeysUntil) {
this._programmaticKeys = 0
} else {
const isExpectedProgrammaticKey =
vk === 0x08 ||
vk === 0x20 ||
@ -592,6 +603,7 @@ class InputTelemetryService extends EventEmitter {
return
}
}
}
// 순수 수정자 키(Ctrl/Alt/Shift/Win) 단독 눌림·키 반복은 화면 텍스트를 바꾸지 않는다.
// 여기서 _inputRevision·_lastKeyAt·스냅샷 타이머를 건드리면 수정자 키를 쥐고 있는 동안
// 진행 중 UIA 스냅샷이 버려지고 유휴 시간(idleMs)과 터미널 버퍼가 리셋된다.
@ -895,19 +907,43 @@ class InputTelemetryService extends EventEmitter {
clearTimeout(this._settleTimer)
this._settleTimer = null
}
if ((!keyClass || TYPING_KEY_CLASSES.has(keyClass)) && configGet('suggestionEnabled') === true) {
// 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔
// 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측 2026-10-17: "빠릿하지 않다").
const settleDelay = Math.max(
if (this._typoSettleTimer) {
clearTimeout(this._typoSettleTimer)
this._typoSettleTimer = null
}
if (!keyClass || TYPING_KEY_CLASSES.has(keyClass)) {
const suggestionEnabled = configGet('suggestionEnabled') === true
const typoEnabled = configGet('typoAutoCorrectEnabled') !== false
const suggestionSettleDelay = suggestionEnabled
? Math.max(
INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 50,
Math.ceil((configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) * COMPOSING_IDLE_MULTIPLIER) + 60
Math.ceil(
(configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) *
COMPOSING_IDLE_MULTIPLIER
) + 60
)
: 0
if (suggestionEnabled) {
// 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔
// 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측: 2026-10-17: "빠릿하지 않다").
this._settleTimer = setTimeout(() => {
this._settleTimer = null
void this._captureTextSnapshot()
}, settleDelay)
}, suggestionSettleDelay)
this._settleTimer.unref?.()
}
// 기본 제안 settle(750ms)이 오타 정지 임계(650~690ms)를 덮을 때는 중복 UIA 조회를 피한다.
if (
typoEnabled &&
(!suggestionEnabled || suggestionSettleDelay < TYPO_SETTLE_DELAY_MS || suggestionSettleDelay > 800)
) {
this._typoSettleTimer = setTimeout(() => {
this._typoSettleTimer = null
void this._captureTextSnapshot()
}, TYPO_SETTLE_DELAY_MS)
this._typoSettleTimer.unref?.()
}
}
}
/**
@ -1108,6 +1144,9 @@ class InputTelemetryService extends EventEmitter {
// 문서 중간을 고쳤다면 접두(문서 끝)는 커서와 무관하다 — 제안·수락을 막는다.
// 단, 방금 프로그램(오타 교정·제안 수락)이 커서 앞 텍스트를 바꾼 경우에는 끝 편집으로 본다.
this._pruneExpectedInserts(now)
if (this._programmaticKeys > 0 && now > this._programmaticKeysUntil) {
this._programmaticKeys = 0
}
const programmaticEdit =
this._programmaticKeys > 0 ||
this._expectedInserts.some((entry) => textForFocus.includes(entry.text))
@ -1197,20 +1236,30 @@ class InputTelemetryService extends EventEmitter {
}
this._lastContext = context
if (this._settleTimer) {
const minPrefixChars = configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars
const canTriggerSuggestion =
configGet('suggestionEnabled') === true &&
if (this._settleTimer || this._typoSettleTimer) {
const canTriggerContext =
context.available &&
context.isEditable &&
!context.isPassword &&
context.editedSinceFocus &&
context.typedRecently &&
context.typedRecently
const minPrefixChars = configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars
const canTriggerSuggestion =
configGet('suggestionEnabled') === true &&
canTriggerContext &&
normalizeRequestPrefix(context.prefix).length + (context.isComposing ? 1 : 0) >= minPrefixChars
if (!canTriggerSuggestion) {
const canTriggerTypoSettle =
configGet('typoAutoCorrectEnabled') !== false &&
canTriggerContext &&
context.prefix.trim().length > 0
if (this._settleTimer && !canTriggerSuggestion && !canTriggerTypoSettle) {
clearTimeout(this._settleTimer)
this._settleTimer = null
}
if (this._typoSettleTimer && !canTriggerTypoSettle) {
clearTimeout(this._typoSettleTimer)
this._typoSettleTimer = null
}
}
this.emit('typed-context', context)
// 진단 줄이 즉시 갱신되도록 상태 변경을 알린다 (키 입력마다가 아니라 스냅샷마다).
@ -1281,8 +1330,14 @@ class InputTelemetryService extends EventEmitter {
bucket.sentences += delta.insertedSentences
}
if (!delta.insertedText) return
const typedText = this._withoutExpectedInsert(delta.insertedText)
const span =
keepText || this._expectedInserts.length > 0
? diffInsertionSpan(previous.text, snapshot.text)
: null
const rawInserted = delta.insertedText || span?.text || ''
if (!rawInserted) return
const typedText = this._withoutExpectedInsert(rawInserted, previous.text, snapshot.text, span)
if (!keepText) return
if (typedText !== delta.insertedText) {
// 프로그램 삽입(제안 수락 등)이 섞였다 — 그 앞까지 모은 것을 저장하고, 이번에 직접 친
// 나머지만 바로 학습한다. 다음 diff 부터는 삽입 뒤 텍스트를 기준선으로 다시 모은다.
@ -1322,6 +1377,7 @@ class InputTelemetryService extends EventEmitter {
this._learnFlushTimer = null
this.flushPendingLearning()
}, LEARN_IDLE_FLUSH_MS)
this._learnFlushTimer.unref?.()
}
/** 모아 둔 타이핑 구간을 지금 학습한다 (멈춤·문장 끝·포커스 이동·종료 시). */
@ -1386,10 +1442,18 @@ class InputTelemetryService extends EventEmitter {
* - 삽입 구간이 예고 텍스트의 앞부분이면(키보드 방식으로 치는 도중 잡힌 스냅샷) 전부
* 프로그램 삽입이고, 남은 뒷부분을 계속 기다린다.
*/
private _withoutExpectedInsert(inserted: string): string {
private _withoutExpectedInsert(
inserted: string,
prevText?: string,
nextText?: string,
span?: { start: number; end: number; text: string } | null
): string {
this._pruneExpectedInserts(Date.now())
const trimmed = inserted.trim()
if (!trimmed) return inserted
const activeSpan =
span ??
(prevText !== undefined && nextText !== undefined ? diffInsertionSpan(prevText, nextText) : null)
for (let i = 0; i < this._expectedInserts.length; i += 1) {
const expected = this._expectedInserts[i]
const index = inserted.indexOf(expected.text)
@ -1397,6 +1461,34 @@ class InputTelemetryService extends EventEmitter {
this._expectedInserts.splice(i, 1)
return `${inserted.slice(0, index)} ${inserted.slice(index + expected.text.length)}`.trim()
}
if (
activeSpan &&
activeSpan.text.length > 0 &&
prevText !== undefined &&
nextText !== undefined
) {
// 치환 앞뒤(예: 문장부호 '?' 접미사)가 공통 접두/접미사로 잘려 diff 가 부분만 잡아냈더라도
// 새 스냅샷에 예고된 전체 문자열이 diff 구간을 덮어 들어왔으면 잔여물('?' 등) 없이 소비한다.
let searchPos = Math.max(0, activeSpan.start - expected.text.length)
while (searchPos < activeSpan.end) {
const matchStart = nextText.indexOf(expected.text, searchPos)
if (matchStart < 0 || matchStart >= activeSpan.end) break
const matchEnd = matchStart + expected.text.length
if (
matchEnd > activeSpan.start &&
(matchStart >= activeSpan.start ||
prevText.slice(matchStart, matchEnd) !== expected.text)
) {
this._expectedInserts.splice(i, 1)
const beforeDiff =
matchStart > activeSpan.start ? nextText.slice(activeSpan.start, matchStart) : ''
const afterDiff =
matchEnd < activeSpan.end ? nextText.slice(matchEnd, activeSpan.end) : ''
return `${beforeDiff} ${afterDiff}`.trim()
}
searchPos = matchStart + 1
}
}
if (trimmed.length === expected.text.length && `${trimmed}${trimmed}`.includes(expected.text)) {
this._expectedInserts.splice(i, 1)
return ''
@ -2219,6 +2311,28 @@ function sanitizeSample(raw: string): string {
return cleaned.slice(0, MAX_SAMPLE_CHARS)
}
/** 두 스냅샷 사이 공통 접두/접미를 제외한 실제 변경 구간과 추가 문자열을 구한다. */
function diffInsertionSpan(
prevText: string,
nextText: string
): { start: number; end: number; text: string } {
let prefix = 0
const maxPrefix = Math.min(prevText.length, nextText.length)
while (prefix < maxPrefix && prevText[prefix] === nextText[prefix]) prefix += 1
let suffix = 0
const maxSuffix = Math.min(prevText.length - prefix, nextText.length - prefix)
while (
suffix < maxSuffix &&
prevText[prevText.length - 1 - suffix] === nextText[nextText.length - 1 - suffix]
) {
suffix += 1
}
const end = nextText.length - suffix
return { start: prefix, end, text: nextText.slice(prefix, end) }
}
function getDisplayScaleFactor(): number {
try {
return screen.getPrimaryDisplay().scaleFactor || 1

View file

@ -186,6 +186,7 @@ class LocalLLMService extends EventEmitter {
private _activeRequests = new Set<ActiveRequest>()
private _ensureRunningPromise: Promise<'running' | 'starting' | 'not-installed' | 'failed'> | null = null
private _startCheckTimers = new Set<ReturnType<typeof setTimeout>>()
private _pullControllers = new Set<AbortController>()
private _disposed = false
get state(): LLMState {
@ -414,7 +415,7 @@ class LocalLLMService extends EventEmitter {
* Ollama 가용성 폴링을 시작한다 (5초 간격).
*/
startPolling(): void {
if (this._pollInterval) return
if (this._pollInterval || this._disposed) return
this._checkAvailability()
this._pollInterval = setInterval(() => {
if (this._state !== LLMState.Generating) {
@ -686,8 +687,13 @@ class LocalLLMService extends EventEmitter {
text: string,
action: LLMAction,
targetLanguage?: string,
customPrompt?: string
customPrompt?: string,
options?: { signal?: AbortSignal; timeoutMs?: number }
): Promise<string> {
if (options?.signal?.aborted) {
throw new D3ROError(ErrorCode.LLMProcessingCancelled, 'LLM processing was cancelled')
}
// Phase 11: LLM 처리 쿼터 체크
try {
const { getLicenseService } = await import('./LicenseService')
@ -708,10 +714,18 @@ class LocalLLMService extends EventEmitter {
// LicenseService 미초기화 시 허용
}
if (options?.signal?.aborted) {
throw new D3ROError(ErrorCode.LLMProcessingCancelled, 'LLM processing was cancelled')
}
const basePrompt = resolveSystemPrompt(action, targetLanguage, customPrompt)
const systemPrompt = `${NO_THINK}\n${basePrompt}`
const result = await this.generate(text, { systemPrompt })
const result = await this.generate(text, {
systemPrompt,
...(options?.signal ? { signal: options.signal } : {}),
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {})
})
const cleaned = stripReasoningBlocks(result.text)
// reasoning 블록 제거 후 빈 응답이면 원본 텍스트 폴백
// (모델이 thinking만 하고 출력은 안 한 경우 / 응답 파싱 실패 케이스)
@ -784,13 +798,26 @@ class LocalLLMService extends EventEmitter {
}
private async _doPullModel(modelId: string): Promise<void> {
if (this._disposed) {
throw new D3ROError(ErrorCode.LLMProcessingCancelled, 'LocalLLMService disposed')
}
const serverUrl = getOllamaServerUrl()
const controller = new AbortController()
this._pullControllers.add(controller)
let reader: ReadableStreamDefaultReader<Uint8Array> | null = null
const onAbort = (): void => {
void reader?.cancel().catch(() => undefined)
}
controller.signal.addEventListener('abort', onAbort, { once: true })
logger.info(`Pull 시작: ${modelId}`)
try {
const response = await fetch(`${serverUrl}/api/pull`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: modelId, stream: true })
body: JSON.stringify({ model: modelId, stream: true }),
signal: controller.signal
})
if (!response.ok || !response.body) {
@ -800,11 +827,17 @@ class LocalLLMService extends EventEmitter {
)
}
const reader = response.body.getReader()
reader = response.body.getReader()
if (this._disposed || controller.signal.aborted) {
throw new D3ROError(ErrorCode.LLMProcessingCancelled, `Pull cancelled: ${modelId}`)
}
const decoder = new TextDecoder()
let buffer = ''
for (;;) {
if (this._disposed || controller.signal.aborted) {
throw new D3ROError(ErrorCode.LLMProcessingCancelled, `Pull cancelled: ${modelId}`)
}
const { done, value } = await reader.read()
if (done) break
@ -844,7 +877,27 @@ class LocalLLMService extends EventEmitter {
}
}
if (this._disposed || controller.signal.aborted) {
throw new D3ROError(ErrorCode.LLMProcessingCancelled, `Pull cancelled: ${modelId}`)
}
logger.info(`Pull 완료: ${modelId}`)
} catch (err) {
if (this._disposed || controller.signal.aborted) {
throw new D3ROError(ErrorCode.LLMProcessingCancelled, `Pull cancelled: ${modelId}`)
}
if (err instanceof D3ROError) throw err
throw new D3ROError(
ErrorCode.LLMServerUnreachable,
`Pull 실패: ${err instanceof Error ? err.message : String(err)}`
)
} finally {
controller.signal.removeEventListener('abort', onAbort)
this._pullControllers.delete(controller)
if (reader) {
await reader.cancel().catch(() => undefined)
}
}
}
getStatus(): LLMStatus {
@ -989,8 +1042,14 @@ class LocalLLMService extends EventEmitter {
clearTimeout(timer)
}
this._startCheckTimers.clear()
for (const controller of this._pullControllers) {
controller.abort()
}
this._pullControllers.clear()
this.stopPolling()
this.cancelGeneration()
this._available = false
this._serverVersion = null
this._refreshState()
this.removeAllListeners()
logger.info('LocalLLMService disposed')
@ -1022,6 +1081,8 @@ class LocalLLMService extends EventEmitter {
// ignore
}
if (this._disposed) return
if (!isOk) {
try {
const tagsRes = await fetch(`${serverUrl}/api/tags`, {
@ -1035,6 +1096,8 @@ class LocalLLMService extends EventEmitter {
}
}
if (this._disposed) return
const wasAvailable = this._available
this._available = isOk
if (detectedVersion) this._serverVersion = detectedVersion

View file

@ -243,6 +243,8 @@ class LocalSTTService extends EventEmitter {
// errorEmitted 플래그로 이벤트 중복 방지
private _errorEmitted: boolean = false
private _idleUnloadTimer: NodeJS.Timeout | null = null
private _downloadControllers = new Set<AbortController>()
private _downloadSleepCancelers = new Set<() => void>()
// ── 상태 접근자 ──
@ -521,13 +523,22 @@ class LocalSTTService extends EventEmitter {
}
await this._supervisor.ready()
if (this._disposed) {
throw new D3ROError(
ErrorCode.STTModelDownloadCancelled,
'모델 다운로드 중 서비스가 종료되었습니다',
)
}
const startRes = await fetch(`${this._baseUrl}/download`, {
const startRes = await this._fetchDownload(
`${this._baseUrl}/download`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model_id: modelId }),
signal: AbortSignal.timeout(10000),
})
},
10000,
)
// 409 = 이미 다운로드 진행 중 — 실패가 아니라 기존 진행에 합류해 폴링
if (!startRes.ok && startRes.status !== 409) {
@ -540,6 +551,9 @@ class LocalSTTService extends EventEmitter {
if (startRes.ok) {
const started = (await startRes.json()) as { status: string }
if (this._disposed) {
throw new D3ROError(ErrorCode.STTModelDownloadCancelled, `모델 다운로드 취소: ${modelId}`)
}
if (started.status === 'done') {
this._emitDownloadProgress(modelId, 100, 0, 0, 0)
return
@ -551,17 +565,33 @@ class LocalSTTService extends EventEmitter {
// 진행률 폴링 — sidecar 통신 실패가 연속되면 중단
let consecutiveFailures = 0
for (;;) {
if (this._disposed) {
throw new D3ROError(
ErrorCode.STTModelDownloadCancelled,
`모델 다운로드 취소: ${modelId}`,
)
}
await this._sleep(500)
if (this._disposed) {
throw new D3ROError(
ErrorCode.STTModelDownloadCancelled,
`모델 다운로드 취소: ${modelId}`,
)
}
let status: DownloadStatusResponse
try {
const res = await fetch(`${this._baseUrl}/download/status`, {
signal: AbortSignal.timeout(3000),
})
const res = await this._fetchDownload(`${this._baseUrl}/download/status`, {}, 3000)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
status = (await res.json()) as DownloadStatusResponse
consecutiveFailures = 0
} catch (err) {
if (this._disposed) {
throw new D3ROError(
ErrorCode.STTModelDownloadCancelled,
`모델 다운로드 취소: ${modelId}`,
)
}
consecutiveFailures++
if (consecutiveFailures >= 5) {
throw new D3ROError(
@ -572,6 +602,13 @@ class LocalSTTService extends EventEmitter {
continue
}
if (this._disposed) {
throw new D3ROError(
ErrorCode.STTModelDownloadCancelled,
`모델 다운로드 취소: ${modelId}`,
)
}
this._emitDownloadProgress(
modelId,
status.percent,
@ -637,6 +674,14 @@ class LocalSTTService extends EventEmitter {
logger.info('LocalSTTService dispose 시작')
this._clearIdleUnload()
for (const cancelSleep of this._downloadSleepCancelers) {
cancelSleep()
}
this._downloadSleepCancelers.clear()
for (const controller of this._downloadControllers) {
controller.abort()
}
this._downloadControllers.clear()
this._initializing = null
this._modelReady = false
this._auxModelId = null
@ -995,8 +1040,55 @@ class LocalSTTService extends EventEmitter {
logger.error(`STT 에러: [${error.code}] ${error.message}`)
}
private async _fetchDownload(
url: string,
init: RequestInit,
timeoutMs: number,
): Promise<Response> {
if (this._disposed) {
throw new D3ROError(ErrorCode.STTModelDownloadCancelled, 'LocalSTTService가 dispose되었습니다')
}
const controller = new AbortController()
this._downloadControllers.add(controller)
let timedOut = false
const timer = setTimeout(() => {
timedOut = true
controller.abort()
}, timeoutMs)
timer.unref?.()
try {
const response = await fetch(url, { ...init, signal: controller.signal })
if (this._disposed) {
throw new D3ROError(ErrorCode.STTModelDownloadCancelled, 'LocalSTTService가 dispose되었습니다')
}
return response
} catch (err) {
if (this._disposed || (!timedOut && controller.signal.aborted)) {
throw new D3ROError(ErrorCode.STTModelDownloadCancelled, 'LocalSTTService가 dispose되었습니다')
}
if (err instanceof D3ROError) throw err
throw new D3ROError(
ErrorCode.STTModelDownloadFailed,
`다운로드 요청 실패: ${err instanceof Error ? err.message : String(err)}`,
)
} finally {
clearTimeout(timer)
this._downloadControllers.delete(controller)
}
}
private _sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
if (this._disposed) return Promise.resolve()
return new Promise((resolve) => {
const cancel = (): void => {
clearTimeout(timer)
this._downloadSleepCancelers.delete(cancel)
resolve()
}
const timer = setTimeout(cancel, ms)
timer.unref?.()
this._downloadSleepCancelers.add(cancel)
})
}
// ── 타입 안전한 이벤트 메서드 오버라이드 ──

View file

@ -75,6 +75,11 @@ const MAX_MODEL_DELETE_CHARS = 18
/** 멈춘 뒤에도 인플레이스 교정이 한 번에 지울 수 있는 최대 글자 수 */
const MAX_INPLACE_DELETE_CHARS = 32
const TRAILING_BOUNDARY_RE = /[ \t.,!?;:~…?!。]$/u
const BOUNDARY_ONLY_RUN_RE = /^[ \t.,!?;:~…?!。]*$/u
const BOUNDARY_DELTA_RE = /^[ \t.,!?;:~…?!。]{1,4}$/u
const BOUNDARY_PUNCT_GLOBAL_RE = /[ \t.,!?;:~…?!。]/gu
/** 'typed-context' 에 대한 판단 — 제안 서비스로 그대로 넘길지(pass), 미룰지. */
export type TypoVerdict = 'pass' | 'correcting' | 'checking'
@ -190,10 +195,10 @@ export class TypoCorrectionService extends EventEmitter {
const canRebaseDelta =
delta.length > 0 &&
delta.length <= 6 &&
(/^[ \t.,!?;:]{1,4}$/u.test(delta) ||
(BOUNDARY_DELTA_RE.test(delta) ||
(!context.isComposing &&
context.idleMs >= LAYOUT_BOUNDARY_MIN_IDLE_MS &&
/[ \t.,!?;:]$/u.test(delta)))
TRAILING_BOUNDARY_RE.test(delta)))
if (canRebaseDelta) {
this._check.context = context
this._check.latestKeyAt = this._deps.lastKeyAt()
@ -211,7 +216,7 @@ export class TypoCorrectionService extends EventEmitter {
this._lastCheckedRegion = ''
this._lastPostRegion = ''
}
const hasTrailingBoundary = /[ \t.,!?;:]$/u.test(prefix)
const hasTrailingBoundary = TRAILING_BOUNDARY_RE.test(prefix)
const isVimCommand = context.vimMode === 'command' || prefix.trimStart().startsWith(':')
const minLayoutIdle = hasTrailingBoundary
? LAYOUT_BOUNDARY_MIN_IDLE_MS
@ -263,6 +268,7 @@ export class TypoCorrectionService extends EventEmitter {
})
const baseCorrections: TypoCorrection[] = []
let deferredTrailingCorrections = false
let appliedSpanLimit = maxDeterministicSpan
if (options.trailingWordOnly !== true) {
for (const c of allCorrections) {
if (prefix.length - c.start <= maxDeterministicSpan) {
@ -272,23 +278,30 @@ export class TypoCorrectionService extends EventEmitter {
} else {
// 빠른 연속 입력 뒤 일부만 고치면 다음 스냅샷에서 앞쪽 교정이 누락된다.
// 짧은 유휴에는 꼬리 사슬 전체가 들어올 때까지 기다리고, 충분히 멈추면 현재 검사 영역을 한 번에 교정한다.
// 단, 문장부호로 막 닫힌 단일 꼬리 오타(23~32자 긴 한국어 구문)는 경계에서 즉시 복원한다.
for (let i = allCorrections.length - 1; i >= 0; i -= 1) {
const c = allCorrections[i]
if (prefix.length - c.start > maxDeterministicSpan) {
const tailAfter = prefix.slice(c.end)
const isSingleBoundaryCompleted =
baseCorrections.length === 0 && hasTrailingBoundary && BOUNDARY_ONLY_RUN_RE.test(tailAfter)
const allowedSpan = isSingleBoundaryCompleted
? Math.max(maxDeterministicSpan, MAX_INPLACE_DELETE_CHARS)
: maxDeterministicSpan
if (prefix.length - c.start > allowedSpan) {
const nextCorr = baseCorrections[0]
const between = nextCorr ? prefix.slice(c.end, nextCorr.start) : ''
deferredTrailingCorrections = /^[ \t.,!?;:]*$/u.test(between) || between.trim().length <= 2
deferredTrailingCorrections = BOUNDARY_ONLY_RUN_RE.test(between) || between.trim().length <= 2
break
}
if (baseCorrections.length === 0) {
const tailAfter = prefix.slice(c.end)
const nonSpaceTailLen = tailAfter.replace(/[ \t.,!?;:]/gu, '').length
const nonSpaceTailLen = tailAfter.replace(BOUNDARY_PUNCT_GLOBAL_RE, '').length
if (nonSpaceTailLen > 2) break
baseCorrections.unshift(c)
appliedSpanLimit = allowedSpan
} else {
const nextCorr = baseCorrections[0]
const between = prefix.slice(c.end, nextCorr.start)
if (/^[ \t.,!?;:]*$/u.test(between) || between.trim().length <= 2) {
if (BOUNDARY_ONLY_RUN_RE.test(between) || between.trim().length <= 2) {
baseCorrections.unshift(c)
} else {
break
@ -306,7 +319,7 @@ export class TypoCorrectionService extends EventEmitter {
const corrections =
loneJamoRemovals.length > 0 ? mergeTypoCorrections(baseCorrections, loneJamoRemovals) : baseCorrections
const plan = planTypoReplacement(prefix, corrections)
if (plan && plan.deleteCount <= maxDeterministicSpan) {
if (plan && plan.deleteCount <= appliedSpanLimit) {
this._markRegionChecked(region)
void this._apply(plan, context, keyAtDecision)
return 'correcting'
@ -331,7 +344,10 @@ export class TypoCorrectionService extends EventEmitter {
void this._apply(jamoPlan, context, keyAtDecision)
return 'correcting'
}
if (!worthModel || configGet('typoAutoCorrectUseModel') === false) {
if (
options.trailingWordOnly !== true &&
(!worthModel || configGet('typoAutoCorrectUseModel') === false)
) {
this._markRegionChecked(region)
}
return 'pass'
@ -444,7 +460,7 @@ export class TypoCorrectionService extends EventEmitter {
if (words.length >= 2) return compact.length >= 4
if (words.length === 1) {
if (hasSuspiciousTypo(region)) return true
return compact.length >= 4 && /[ \t.,!?;:]$/u.test(region)
return compact.length >= 4 && TRAILING_BOUNDARY_RE.test(region)
}
return false
}

View file

@ -49,6 +49,7 @@ class VoiceConversationService extends EventEmitter {
* 카운트가 쌓였고, 세션을 끝내도 마이크(SoX)가 계속 열려 있었다.
*/
private _micHeld = false
private _listenEpoch = 0
private _responseAbortController: AbortController | null = null
/** 취소·세션 종료마다 올린다 — 전사가 끝났을 때 그 사이 취소됐는지 가린다(전사 중엔 abort 할 응답이 없다). */
private _turn = 0
@ -122,8 +123,10 @@ class VoiceConversationService extends EventEmitter {
this._turn += 1
this._stopListening()
// 이 대화의 응답만 멈춘다 — signal 이 LLM 호출까지 전달된다(전역 cancelGeneration 은 다른 기능의
// 진행 중 호출까지 끊었다).
this._responseAbortController?.abort()
// 진행 중 호출까지 끊었다). 포인터를 먼저 비워 취소 직후 새 턴이 막히지 않게 한다.
const responseController = this._responseAbortController
this._responseAbortController = null
responseController?.abort()
getTTSPlaybackService().stop()
this._isActive = false
@ -147,7 +150,9 @@ class VoiceConversationService extends EventEmitter {
*/
cancelResponse(): void {
this._turn += 1
this._responseAbortController?.abort()
const responseController = this._responseAbortController
this._responseAbortController = null
responseController?.abort()
getTTSPlaybackService().stop()
if (this._isActive && this._state !== 'listening') {
this._resumeListening()
@ -266,7 +271,9 @@ class VoiceConversationService extends EventEmitter {
if (!this._micHeld) {
this._micHeld = true
const listenEpoch = ++this._listenEpoch
audioService.start().catch((err) => {
if (!this._isActive || this._listenEpoch !== listenEpoch) return
this._micHeld = false
logger.error('Failed to start audio capture for conversation:', err)
this._emitError('stt', 'Failed to start microphone')
@ -278,6 +285,7 @@ class VoiceConversationService extends EventEmitter {
}
private _stopListening(): void {
this._listenEpoch += 1
const audioService = getAudioCaptureService()
if (this._audioListenerBound) {
audioService.off('audio-data', this._onAudioData)

View file

@ -1023,8 +1023,10 @@ class VoiceModeService extends EventEmitter {
action: LLMAction,
targetLanguage?: string,
customPrompt?: string,
signal?: AbortSignal,
): Promise<string> {
return getLlmGateway().processText(text, action, targetLanguage, customPrompt, {
...(signal ? { signal } : {}),
onFallback: (reason) => this._emitPremiumFallback(reason),
})
}
@ -1087,8 +1089,8 @@ class VoiceModeService extends EventEmitter {
const processedText =
route.kind === 'instruction'
? await this._processWithInstruction(userText, route.instructionId)
: await this._processWithAction(userText, route.action)
? await this._processWithInstruction(userText, route.instructionId, run.controller.signal)
: await this._processWithAction(userText, route.action, run.controller.signal)
if (!this._isCurrent(run)) return
@ -1115,7 +1117,11 @@ class VoiceModeService extends EventEmitter {
}
/** 지시문(음성 단축키 또는 활성 지시문·파이프라인)으로 처리한다. 지시문이 없으면 지시문 없이 custom 처리 */
private async _processWithInstruction(userText: string, instructionId: string | null): Promise<string> {
private async _processWithInstruction(
userText: string,
instructionId: string | null,
signal?: AbortSignal,
): Promise<string> {
let invocationText = userText
let instructionPrompt: string | undefined
@ -1146,13 +1152,14 @@ class VoiceModeService extends EventEmitter {
}
}
return this._runProcessorWithFallback(invocationText, 'custom', undefined, instructionPrompt)
return this._runProcessorWithFallback(invocationText, 'custom', undefined, instructionPrompt, signal)
}
/** 일반 액션(refine/translate/…)으로 처리한다 */
private async _processWithAction(
userText: string,
action: Extract<LlmProcessingRoute, { kind: 'action' }>['action'],
signal?: AbortSignal,
): Promise<string> {
const targetLanguage = resolveTargetLanguage()
logger.info(
@ -1164,6 +1171,8 @@ class VoiceModeService extends EventEmitter {
userText,
action,
action === 'translate' ? targetLanguage : undefined,
undefined,
signal,
)
}

View file

@ -114,7 +114,13 @@ export interface PremiumLlmAdapter {
export interface LocalLlmAdapter {
isAvailable(): boolean
processText(text: string, action: LLMAction, targetLanguage?: string, customPrompt?: string): Promise<string>
processText(
text: string,
action: LLMAction,
targetLanguage?: string,
customPrompt?: string,
options?: { signal?: AbortSignal; timeoutMs?: number },
): Promise<string>
generate(
text: string,
options?: LlmGenerateOptions & { signal?: AbortSignal; timeoutMs?: number },
@ -214,8 +220,10 @@ class RoutedLlmGateway implements LlmGateway {
}
}
throwIfAborted(hooks?.signal)
// 로컬 processText 는 호출 단위 signal 을 받지 않는다 — 끝난 뒤 취소됐으면 결과를 버린다.
const result = await this._deps.getLocal().processText(text, action, targetLanguage, customPrompt)
const perCall = callOptions(hooks)
const result = perCall
? await this._deps.getLocal().processText(text, action, targetLanguage, customPrompt, perCall)
: await this._deps.getLocal().processText(text, action, targetLanguage, customPrompt)
throwIfAborted(hooks?.signal)
return result
}

View file

@ -567,6 +567,8 @@ ipcMain.on(IPC_CHANNELS.POPUP_RESULT.MEASURED, (event: Electron.IpcMainEvent, da
})
export function hideResultPopup(): void {
cancelPendingResultShow()
lastResultCursor = null
if (resultPopupWindow && !resultPopupWindow.isDestroyed()) {
resultPopupWindow.hide()
}

View file

@ -6,6 +6,7 @@
// - realtime-token 은 주입된 자격 증명 포트로 호출한다 (item 2)
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { desktopCapturer, session } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
const handlers = vi.hoisted(() => new Map<string, (event: unknown, params?: unknown) => Promise<unknown>>())
@ -136,3 +137,25 @@ describe('realtime-token 은 자격 증명 포트를 쓴다', () => {
expect(invokeFn).toHaveBeenCalledWith('realtime-token', {})
})
})
describe('systemAudio:enableLoopback 예외 처리', () => {
it('enableLoopback_getSourcesRejects_invokesCallbackWithEmptyObject', async () => {
const mod = await import('../../../src/main/ipc/caption-handlers')
mod.registerCaptionHandlers()
const regResult = await invoke(IPC_CHANNELS.SYSTEM_AUDIO.ENABLE_LOOPBACK)
expect(regResult.success).toBe(true)
const setHandlerCalls = vi.mocked(session.defaultSession.setDisplayMediaRequestHandler).mock.calls
const mediaHandler = setHandlerCalls[0]?.[0] as
| ((request: unknown, callback: (streams: Record<string, unknown>) => void) => Promise<void>)
| undefined
expect(typeof mediaHandler).toBe('function')
vi.mocked(desktopCapturer.getSources).mockRejectedValueOnce(new Error('screen capture failed'))
const callback = vi.fn()
await expect(mediaHandler!({}, callback)).resolves.toBeUndefined()
expect(callback).toHaveBeenCalledWith({})
})
})

View file

@ -642,6 +642,90 @@ describe('TypoCorrectionService', () => {
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith('ㅎ샤ㅗㅕㅠ에 '.length, 'github에 ')
})
it('handleTypingContext_문장부호뒤23자단일오타_짧은경계유휴에서즉시교정한다', async () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
const prefix = '상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwldy?'
expect(
service.handleTypingContext(typingContext({ prefix, idleMs: 140 }), { trailingWordOnly: true })
).toBe('correcting')
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith(
'dbrlgkrhdlTwlsdksgwldy?'.length,
'유기하고있진않지요?'
)
})
it('handleTypingContext_물결표및전각부호뒤오타_짧은경계유휴에서즉시교정하고경로는보존한다', async () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
expect(
service.handleTypingContext(
typingContext({ prefix: '상황 잘 지켜보는중~dbrlgkrhdlTwlsdksgwl~', idleMs: 60 }),
{ trailingWordOnly: true }
)
).toBe('correcting')
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith(
'dbrlgkrhdlTwlsdksgwl~'.length,
'유기하고있진않지~'
)
fake.replaceBeforeCaret.mockClear()
expect(
service.handleTypingContext(
typingContext({ prefix: '~/dbrlgkrhdlTwlsdksgwl~', idleMs: 60 }),
{ trailingWordOnly: true }
)
).toBe('pass')
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
})
it('handleTypingContext_620ms경과뒤650ms정지시_장문후행오타가영역선점으로누락되지않는다', async () => {
const fake = deps()
const service = new TypoCorrectionService(fake.deps)
const prefix = '상황 잘 지켜보는중?dkssudgktpdy rkatkgkqslek qksrkqtmqslek?'
expect(
service.handleTypingContext(typingContext({ prefix, idleMs: 620 }), { trailingWordOnly: true })
).toBe('pass')
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
expect(
service.handleTypingContext(typingContext({ prefix, idleMs: 650 }), { trailingWordOnly: true })
).toBe('correcting')
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith(
'dkssudgktpdy rkatkgkqslek qksrkqtmqslek?'.length,
'안녕하세요 감사합니다 반갑습니다?'
)
// trailingWordOnly 620ms 에서 앞쪽 오타('dkssudgktpdy')가 후행 제한으로 통과되더라도
// 같은 영역을 checked 로 선점해 후속 전체 검사(trailingWordOnly 없음)를 막아선 안 된다
const staleRegionService = new TypoCorrectionService(fake.deps)
fake.replaceBeforeCaret.mockClear()
const earlierPrefix = 'dkssudgktpdy hello?'
expect(
staleRegionService.handleTypingContext(typingContext({ prefix: earlierPrefix, idleMs: 620 }), {
trailingWordOnly: true
})
).toBe('pass')
expect(fake.replaceBeforeCaret).not.toHaveBeenCalled()
expect(
staleRegionService.handleTypingContext(typingContext({ prefix: earlierPrefix, idleMs: 650 }))
).toBe('correcting')
await flush()
expect(fake.replaceBeforeCaret).toHaveBeenCalledWith(
'dkssudgktpdy hello?'.length,
'안녕하세요 hello?'
)
})
})
describe('TypoCorrectionService.propose — 제안 창에 함께 내놓을 교정 (적용하지 않음)', () => {

View file

@ -190,4 +190,64 @@ describe('VoiceConversationService local response ownership', () => {
expect(mocks.speakSentences).not.toHaveBeenCalled()
expect(service.getHistory().map((message) => message.content)).toEqual(['cancel before response'])
})
it('cancelResponse_followedImmediatelyBySendTextMessage_startsNewTurnWithoutConflict', async () => {
let releaseFirstStream: (() => void) | undefined
mocks.chatStream
.mockImplementationOnce(() => (async function* (): AsyncGenerator<string, string> {
await new Promise<void>((resolve) => {
releaseFirstStream = resolve
})
return ''
})())
.mockImplementationOnce(() => (async function* (): AsyncGenerator<string, string> {
yield 'second reply.'
return 'second reply.'
})())
const service = getVoiceConversationService()
await service.startSession()
const firstResponse = service.sendTextMessage('first question')
await vi.waitFor(() => expect(mocks.chatStream).toHaveBeenCalledTimes(1))
service.cancelResponse()
const secondResponse = service.sendTextMessage('second question')
releaseFirstStream?.()
await expect(secondResponse).resolves.toBeUndefined()
await firstResponse
expect(mocks.chatStream).toHaveBeenCalledTimes(2)
expect(service.getHistory().map((m) => m.content)).toEqual([
'first question',
'second question',
'second reply.',
])
})
it('startSession_audioStartRejectsAfterStop_doesNotEmitSttErrorOrClobberNewSessionMic', async () => {
let rejectFirstMic!: (err: Error) => void
mocks.audioStart
.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => {
rejectFirstMic = reject
}))
.mockImplementationOnce(async () => undefined)
const service = getVoiceConversationService()
const errorEvents: Array<{ phase: string; message: string }> = []
service.on('error', (payload) => errorEvents.push(payload))
await service.startSession()
service.stopSession()
await service.startSession()
rejectFirstMic(new Error('stale mic failure'))
await new Promise((r) => setTimeout(r, 0))
expect(errorEvents).toEqual([])
expect(mocks.send.mock.calls.filter(([channel]) => channel === IPC_CHANNELS.VOICE_CONVERSATION.ERROR)).toEqual([])
service.stopSession()
expect(mocks.audioStop).toHaveBeenCalledTimes(2)
})
})

View file

@ -261,6 +261,36 @@ describe('VoiceModeService', () => {
expect(cancelReason).toBe('user')
})
it('cancelSession_whileLlmProcessingInFlight_abortsPerCallSignalPassedToLlm', async () => {
let capturedSignal: AbortSignal | undefined
let rejectLlm: ((reason?: unknown) => void) | undefined
mockLLM.processText.mockImplementation(((_text, _action, _lang, _prompt, options?: { signal?: AbortSignal }) => {
capturedSignal = options?.signal
return new Promise<string>((_resolve, reject) => {
rejectLlm = reject
options?.signal?.addEventListener('abort', () => reject(new Error('llm aborted')), { once: true })
})
}) as never)
const svc = getVoiceModeService()
await svc.startSession('dictation')
audioBus.emit('audio-data', { buffer: Buffer.alloc(16000 * 2) })
await new Promise((r) => setTimeout(r, 850))
const stopping = svc.stopSession()
await vi.waitFor(() => expect(mockLLM.processText).toHaveBeenCalledTimes(1))
expect(capturedSignal).toBeInstanceOf(AbortSignal)
expect(capturedSignal?.aborted).toBe(false)
svc.cancelSession()
rejectLlm?.(new Error('cleanup'))
await stopping
expect(capturedSignal?.aborted).toBe(true)
expect(mockTextInsert.insertText).not.toHaveBeenCalled()
})
})
describe('LLM 후처리 인자 전달', () => {

View file

@ -7,6 +7,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { EventEmitter } from 'events'
import { spawn } from 'child_process'
import { ipcMain } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
@ -228,3 +229,37 @@ describe('마이크 테스트 IPC', () => {
expect(proc(0).kill).toHaveBeenCalledTimes(1)
})
})
describe('정지/시작 레이스 및 실패 정리', () => {
it('start_calledWhileStoppingAfterSoxClosed_spawnsFreshSoxProcess', async () => {
const audio = mod.getAudioCaptureService()
await audio.start()
const stopping = audio.stop()
proc(0).emit('close', 1)
await audio.start()
await stopping
expect(spawned.list).toHaveLength(2)
expect(audio.state).toBe('capturing')
await audio.stop()
expect(proc(1).kill).toHaveBeenCalledTimes(1)
})
it('start_spawnedProcessMissingStdout_cleansUpChildProcess', async () => {
const brokenChild = Object.assign(new EventEmitter(), {
stdout: null,
stderr: new EventEmitter(),
kill: vi.fn(),
})
vi.mocked(spawn).mockReturnValueOnce(brokenChild as never)
const audio = mod.getAudioCaptureService()
await expect(audio.start()).rejects.toMatchObject({ message: expect.stringMatching(/stdout/i) })
expect(audio.state).toBe('error')
expect(brokenChild.kill).toHaveBeenCalledTimes(1)
})
})

View file

@ -16,11 +16,12 @@ vi.mock('../../../src/main/services/ConfigService', () => ({
const stt = vi.hoisted(() => ({
gate: null as Promise<void> | null,
initialize: vi.fn(async () => undefined),
releaseAuxModel: vi.fn(async () => undefined),
}))
vi.mock('../../../src/main/services/LocalSTTService', () => ({
getLocalSTTService: () => ({
initialize: vi.fn(async () => undefined),
initialize: stt.initialize,
ensureAuxModel: vi.fn(async () => {
if (stt.gate) await stt.gate
}),
@ -29,7 +30,13 @@ vi.mock('../../../src/main/services/LocalSTTService', () => ({
}),
}))
const audio = vi.hoisted(() => ({ start: vi.fn(async () => undefined), stop: vi.fn(async () => undefined) }))
const audio = vi.hoisted(() => ({
stopGate: null as Promise<void> | null,
start: vi.fn(async () => undefined),
stop: vi.fn(async () => {
if (audio.stopGate) await audio.stopGate
}),
}))
vi.mock('../../../src/main/services/AudioCaptureService', () => ({
getAudioCaptureService: () => ({ ...audio, on: vi.fn(), off: vi.fn() }),
calculateRMS: () => 0.1,
@ -63,7 +70,12 @@ beforeEach(async () => {
vi.clearAllMocks()
config.values = { captionSttModelId: 'caption-small' }
stt.gate = null
stt.initialize.mockImplementation(async () => undefined)
audio.stopGate = null
audio.start.mockImplementation(async () => undefined)
audio.stop.mockImplementation(async () => {
if (audio.stopGate) await audio.stopGate
})
mod = await import('../../../src/main/services/CaptionService')
mod.resetCaptionServiceForTests()
})
@ -98,4 +110,42 @@ describe('CaptionService — 자막 전용 보조 모델 해제', () => {
expect(stt.releaseAuxModel).toHaveBeenCalledTimes(1)
expect(caption.getState()).toBe('inactive')
})
it('releaseAuxModel_auxFinishesLoadingWhileStopping_stillReleasesAuxModel', async () => {
let finishLoad: () => void = () => undefined
stt.gate = new Promise<void>((r) => {
finishLoad = r
})
const caption = mod.getCaptionService()
const starting = caption.start({ audioSource: 'mic', showOverlay: false })
await new Promise((r) => setTimeout(r, 0))
// stop() immediately transitions state to 'stopping' before yielding to awaits
const stopping = caption.stop()
expect(caption.getState()).toBe('stopping')
// Aux model finishes loading on the same tick while stop() is still in 'stopping'
stt.releaseAuxModel.mockClear()
finishLoad()
await expect(starting).rejects.toBeTruthy()
await stopping
expect(stt.releaseAuxModel).toHaveBeenCalledTimes(1)
expect(caption.getState()).toBe('inactive')
})
it('start_failsBeforeAuxLoadWhenPreviousSessionHadAux_doesNotReleaseSpuriously', async () => {
audio.start.mockRejectedValueOnce(new Error('no mic'))
const caption = mod.getCaptionService()
await expect(caption.start({ audioSource: 'mic', showOverlay: false })).rejects.toBeTruthy()
expect(stt.releaseAuxModel).toHaveBeenCalledTimes(1)
stt.releaseAuxModel.mockClear()
config.values = {}
stt.initialize.mockRejectedValueOnce(new Error('sidecar down'))
await expect(caption.start({ audioSource: 'mic', showOverlay: false })).rejects.toBeTruthy()
expect(stt.releaseAuxModel).not.toHaveBeenCalled()
})
})

View file

@ -0,0 +1,178 @@
// tests/main/services/caption-lifecycle-refine.test.ts
// CaptionService concurrent stop & refine queue cancellation/isolation regression tests.
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
}))
const config = vi.hoisted(() => ({ values: {} as Record<string, unknown> }))
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: vi.fn((key: string) => config.values[key]),
configSet: vi.fn(),
}))
vi.mock('../../../src/main/services/LocalSTTService', () => ({
getLocalSTTService: () => ({
initialize: vi.fn(async () => undefined),
ensureAuxModel: vi.fn(async () => undefined),
releaseAuxModel: vi.fn(async () => undefined),
transcribe: vi.fn(async () => ({ text: '', segments: [] })),
}),
}))
const audio = vi.hoisted(() => ({
stopGate: null as Promise<void> | null,
start: vi.fn(async () => undefined),
stop: vi.fn(async () => {
if (audio.stopGate) await audio.stopGate
}),
}))
vi.mock('../../../src/main/services/AudioCaptureService', () => ({
getAudioCaptureService: () => ({ ...audio, on: vi.fn(), off: vi.fn() }),
calculateRMS: () => 0.1,
}))
vi.mock('../../../src/main/services/SoundEffectService', () => ({
getSoundEffectService: () => ({ play: vi.fn() }),
}))
const llm = vi.hoisted(() => ({
available: true,
generate: vi.fn<
[string, { signal?: AbortSignal; systemPrompt?: string }],
Promise<{ text: string }>
>(async (_prompt, _opts) => ({ text: '' })),
}))
vi.mock('../../../src/main/services/LocalLLMService', () => ({
getLocalLLMService: () => ({
isAvailable: () => llm.available,
generate: llm.generate,
}),
}))
vi.mock('../../../src/main/services/HistoryService', () => ({
getHistoryService: () => ({ create: vi.fn(() => ({ id: 'history-1' })) }),
}))
vi.mock('../../../src/main/services/TranscriptGlossaryService', () => ({
getTranscriptGlossaryService: () => ({
correct: (text: string) => ({ text, corrections: [] }),
promptSection: () => '',
}),
}))
const tracks = vi.hoisted(() => ({
latestDeps: null as { onFinal: (text: string) => void } | null,
flushGate: null as Promise<void> | null,
}))
vi.mock('../../../src/main/services/caption/StreamingCaptionTrack', () => ({
StreamingCaptionTrack: class {
constructor(private readonly deps: { onFinal: (text: string) => void }) {
tracks.latestDeps = deps
}
push(): void {}
async tick(): Promise<void> {}
async flush(): Promise<void> {
if (tracks.flushGate) await tracks.flushGate
}
},
}))
type CaptionModule = typeof import('../../../src/main/services/CaptionService')
let mod: CaptionModule
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
config.values = { captionRefineEnabled: true }
audio.stopGate = null
tracks.latestDeps = null
tracks.flushGate = null
llm.available = true
llm.generate.mockReset()
llm.generate.mockImplementation(async () => ({ text: '' }))
mod = await import('../../../src/main/services/CaptionService')
mod.resetCaptionServiceForTests()
})
describe('CaptionService concurrent stop and refine lifecycle', () => {
it('stop_calledConcurrentlyWhileStopping_waitsForTeardownBeforeResolving', async () => {
let releaseAudio!: () => void
audio.stopGate = new Promise<void>((r) => {
releaseAudio = r
})
const caption = mod.getCaptionService()
await caption.start({ audioSource: 'mic', showOverlay: false, persistHistory: false })
tracks.latestDeps?.onFinal('첫 번째 확정 문장')
const firstStop = caption.stop()
await new Promise((r) => setTimeout(r, 0))
expect(caption.getState()).toBe('stopping')
let secondResolved = false
const secondStop = caption.stop().then((result) => {
secondResolved = true
return result
})
await new Promise((r) => setTimeout(r, 0))
// Second stop must not resolve null prematurely before audio release finishes
expect(secondResolved).toBe(false)
releaseAudio()
const [r1, r2] = await Promise.all([firstStop, secondStop])
expect(caption.getState()).toBe('inactive')
expect(r1 && typeof r1 === 'object' ? r1.segments.map((s) => s.text) : []).toEqual([
'첫 번째 확정 문장',
])
expect(r2).toEqual(r1)
})
it('refine_stoppedWhileLlmInFlight_abortsGenerateAndAllowsNextSessionRefine', async () => {
const signals: Array<AbortSignal | undefined> = []
let rejectFirstOnAbort: (() => void) | null = null
let callCount = 0
llm.generate.mockImplementation(async (_text, opts) => {
callCount += 1
signals.push(opts?.signal)
if (callCount === 1) {
return await new Promise<{ text: string }>((_, reject) => {
rejectFirstOnAbort = () => reject(new Error('aborted'))
})
}
return { text: '오늘 회의는 세 시에 시작합니다.' }
})
const caption = mod.getCaptionService()
const updated: Array<{ id: string; text: string }> = []
caption.on('segment-updated', (u) => updated.push(u))
await caption.start({ audioSource: 'mic', showOverlay: false, persistHistory: false })
tracks.latestDeps?.onFinal('오늘회의는 세시에 시작합니다')
await new Promise((r) => setTimeout(r, 0))
expect(llm.generate).toHaveBeenCalledTimes(1)
expect(signals[0]).toBeInstanceOf(AbortSignal)
expect(signals[0]?.aborted).toBe(false)
await caption.stop()
expect(signals[0]?.aborted).toBe(true)
// Start a brand-new session BEFORE the aborted first LLM promise settles
await caption.start({ audioSource: 'mic', showOverlay: false, persistHistory: false })
tracks.latestDeps?.onFinal('오늘회의는 세시에 시작합니다')
await new Promise((r) => setTimeout(r, 0))
expect(llm.generate).toHaveBeenCalledTimes(2)
expect(updated.length).toBe(1)
// Settling the aborted request later must not emit or break state
rejectFirstOnAbort?.()
await new Promise((r) => setTimeout(r, 0))
await caption.stop()
})
})

View file

@ -151,4 +151,17 @@ describe('LlmGateway 호출 단위 취소', () => {
})
expect(l.processText).not.toHaveBeenCalled()
})
it('processText_localBackendWithSignal_forwardsPerCallSignalToLocalAdapter', async () => {
const controller = new AbortController()
const l = local()
const gw = createRoutedLlmGateway({
getBackend: () => 'local',
loadPremium: async () => premium(),
getLocal: () => l,
})
await gw.processText('t', 'refine', undefined, undefined, { signal: controller.signal })
expect(l.processText).toHaveBeenCalledWith('t', 'refine', undefined, undefined, { signal: controller.signal })
})
})

View file

@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ErrorCode } from '@d3ro/core/errors'
import { D3ROError, ErrorCode } from '@d3ro/core/errors'
import { configSet, initInMemoryConfig, resetInMemoryConfig } from '../../../src/main/services/ConfigService'
import { availableParallelism } from 'node:os'
import { inferenceCpuThreads } from '../../../src/main/utils/inference-cpu-budget'
@ -256,3 +256,152 @@ describe('LocalLLMService model residency (2026-10-11 memory policy)', () => {
expect(unloads).toEqual([{ model: 'gemma4:e4b', keep_alive: 0 }])
})
})
describe('LocalLLMService cancellation and dispose safety', () => {
beforeEach(() => {
initInMemoryConfig()
resetLocalLLMServiceForTests()
markAvailable()
})
afterEach(() => {
resetLocalLLMServiceForTests()
resetInMemoryConfig()
vi.unstubAllGlobals()
})
it('processText_signalAbortedMidGenerate_rejectsWithCancelled', async () => {
let seenSignal: AbortSignal | undefined
const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
seenSignal = init?.signal ?? undefined
return new Promise<Response>((_resolve, reject) => {
const timer = setTimeout(() => reject(new Error('fetch was not aborted')), 300)
init?.signal?.addEventListener(
'abort',
() => {
clearTimeout(timer)
reject(new Error('aborted'))
},
{ once: true },
)
})
})
vi.stubGlobal('fetch', fetchMock)
const controller = new AbortController()
const promise = (
getLocalLLMService() as unknown as {
processText: (
text: string,
action: 'refine',
targetLanguage?: string,
customPrompt?: string,
options?: { signal?: AbortSignal },
) => Promise<string>
}
).processText('안녕', 'refine', undefined, undefined, { signal: controller.signal })
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
controller.abort()
await expect(promise).rejects.toMatchObject({ code: ErrorCode.LLMProcessingCancelled })
expect(seenSignal?.aborted).toBe(true)
})
it('pullModel_disposedMidStream_abortsFetchCancelsReaderAndMarksUnavailable', async () => {
let safetyTimer: ReturnType<typeof setTimeout> | null = null
const cancelReader = vi.fn(async () => {
if (safetyTimer) clearTimeout(safetyTimer)
})
let seenSignal: AbortSignal | undefined
let pullFetchAborted = false
const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
seenSignal = init?.signal ?? undefined
init?.signal?.addEventListener('abort', () => {
pullFetchAborted = true
})
const stream = new ReadableStream<Uint8Array>({
pull() {
return new Promise<void>((_resolve, reject) => {
safetyTimer = setTimeout(() => reject(new Error('pull was not cancelled')), 300)
})
},
cancel: cancelReader,
})
return new Response(stream, { status: 200 })
})
vi.stubGlobal('fetch', fetchMock)
const service = getLocalLLMService()
const pullPromise = service.pullModel('gemma4:e4b')
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
await new Promise((r) => setTimeout(r, 0))
service.dispose()
await expect(pullPromise).rejects.toMatchObject({ code: ErrorCode.LLMProcessingCancelled })
expect(pullFetchAborted || Boolean(seenSignal?.aborted)).toBe(true)
expect(cancelReader).toHaveBeenCalledTimes(1)
expect(service.isAvailable()).toBe(false)
})
it('checkConnection_disposedWhilePending_doesNotRestoreAvailability', async () => {
const service = getLocalLLMService()
;(service as unknown as { _available: boolean })._available = false
let resolveVersion!: (value: Response) => void
vi.stubGlobal(
'fetch',
vi.fn((input: RequestInfo | URL) => {
if (String(input).endsWith('/api/tags')) {
return Promise.resolve(new Response(JSON.stringify({ models: [] }), { status: 200 }))
}
return new Promise<Response>((resolve) => {
resolveVersion = resolve
})
}),
)
const checkPromise = service.checkConnection()
await new Promise((r) => setTimeout(r, 0))
service.dispose()
resolveVersion(new Response(JSON.stringify({ version: '0.20.0' }), { status: 200 }))
const status = await checkPromise
expect(status.available).toBe(false)
expect(service.isAvailable()).toBe(false)
})
it('pullModel_disposedBeforeHeadersArrive_rejectsWithLLMProcessingCancelled', async () => {
let seenSignal: AbortSignal | undefined
const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
seenSignal = init?.signal ?? undefined
return new Promise<Response>((_resolve, reject) => {
const timer = setTimeout(() => reject(new Error('pull fetch was not aborted')), 300)
init?.signal?.addEventListener(
'abort',
() => {
clearTimeout(timer)
reject(new DOMException('The operation was aborted.', 'AbortError'))
},
{ once: true },
)
})
})
vi.stubGlobal('fetch', fetchMock)
const service = getLocalLLMService()
const pullPromise = service.pullModel('gemma4:e4b')
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
service.dispose()
await expect(pullPromise).rejects.toSatisfy(
(err: unknown) => err instanceof D3ROError && err.code === ErrorCode.LLMProcessingCancelled,
)
expect(seenSignal?.aborted).toBe(true)
expect(service.isAvailable()).toBe(false)
})
})

View file

@ -374,4 +374,94 @@ describe('LocalSTTService — 사이드카 크래시 재시작', () => {
expect(local.currentModelId).toBe('tiny')
await local.dispose()
})
it('downloadModel_disposedWhilePolling_abortsPromptlyWithoutPollingAfterDispose', async () => {
const h = createHarness()
h.setHealthy(true)
let statusPollsAfterDispose = 0
let disposed = false
const wrappedFetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input)
if (url.endsWith('/download')) {
return jsonResponse({ status: 'downloading' })
}
if (url.endsWith('/download/status')) {
if (disposed) {
statusPollsAfterDispose++
if (statusPollsAfterDispose >= 2) {
return jsonResponse({
status: 'done',
percent: 100,
downloaded_bytes: 100,
total_bytes: 100,
bytes_per_second: 100,
})
}
}
return jsonResponse({
status: 'downloading',
percent: 10,
downloaded_bytes: 10,
total_bytes: 100,
bytes_per_second: 10,
})
}
return h.fetch(url, init)
})
vi.stubGlobal('fetch', wrappedFetch)
const local = new LocalSTTService({ supervisor: h.supervisor })
const downloadPromise = local.downloadModel('tiny')
await vi.waitFor(() =>
expect(wrappedFetch.mock.calls.some(([url]) => String(url).endsWith('/download'))).toBe(true),
)
disposed = true
const disposePromise = local.dispose()
await expect(downloadPromise).rejects.toMatchObject({ code: ErrorCode.STTModelDownloadCancelled })
await disposePromise
expect(statusPollsAfterDispose).toBe(0)
})
it('downloadModel_disposedWhileStartRequestPending_rejectsWithSTTModelDownloadCancelled', async () => {
const h = createHarness()
h.setHealthy(true)
let startSignal: AbortSignal | undefined
const wrappedFetch = vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input)
if (url.endsWith('/download')) {
startSignal = init?.signal ?? undefined
return new Promise<Response>((_resolve, reject) => {
const timer = setTimeout(() => reject(new Error('download start fetch was not aborted')), 300)
init?.signal?.addEventListener(
'abort',
() => {
clearTimeout(timer)
reject(new DOMException('The operation was aborted.', 'AbortError'))
},
{ once: true },
)
})
}
return h.fetch(url, init)
})
vi.stubGlobal('fetch', wrappedFetch)
const local = new LocalSTTService({ supervisor: h.supervisor })
const downloadPromise = local.downloadModel('tiny')
await vi.waitFor(() =>
expect(wrappedFetch.mock.calls.some(([url]) => String(url).endsWith('/download'))).toBe(true),
)
const disposePromise = local.dispose()
await expect(downloadPromise).rejects.toSatisfy(
(err: unknown) => err instanceof D3ROError && err.code === ErrorCode.STTModelDownloadCancelled,
)
await disposePromise
expect(startSignal?.aborted).toBe(true)
})
})

View file

@ -0,0 +1,348 @@
// apps/desktop/tests/main/services/typo-live-punctuation.test.ts
// 실시간 타이핑(InputTelemetryService → TypoCorrectionService → TextInsertService)에서
// 문장부호 뒤 띄어쓰기 없는 한영 오타 감지와 후속 학습/커서 추적을 검증한다.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const BASE_NOW = Date.UTC(2026, 10, 14, 5, 0, 0)
const state = vi.hoisted(() => ({
now: 0,
config: {
typoAutoCorrectEnabled: true as boolean,
typoAutoCorrectUseModel: false as boolean,
typoIgnoredWords: [] as string[],
inputExcludedApps: [] as string[],
inputTelemetryEnabled: false as boolean,
inputTelemetryPaused: false as boolean,
inputLearnTypedText: false as boolean,
suggestionEnabled: false as boolean,
suggestionTriggerDelayMs: 600 as number,
suggestionMinPrefixChars: 8 as number
},
text: '',
caretOffset: 0 as number | null,
nativeTick: 100,
hwnd: 77,
appName: 'KakaoTalk.exe',
windowTitle: '채팅',
listeners: new Map<string, Array<(event: unknown) => void>>(),
learnedTexts: [] as string[]
}))
vi.mock('electron', () => ({ screen: { getPrimaryDisplay: () => ({ scaleFactor: 1 }) } }))
vi.mock('uiohook-napi', () => ({
uIOhook: {
on: vi.fn((event: string, listener: (payload: unknown) => void) => {
const list = state.listeners.get(event) ?? []
list.push(listener)
state.listeners.set(event, list)
}),
removeListener: vi.fn((event: string, listener: (payload: unknown) => void) => {
const list = state.listeners.get(event) ?? []
state.listeners.set(
event,
list.filter((entry) => entry !== listener)
)
})
}
}))
vi.mock('../../../src/main/db', () => ({
getDatabase: () => ({
insert: () => ({
values: () => ({
run: () => undefined,
onConflictDoUpdate: () => ({ run: () => undefined })
})
})
})
}))
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: vi.fn((key: keyof typeof state.config) => state.config[key]),
configSet: vi.fn((key: keyof typeof state.config, value: never) => {
state.config[key] = value
})
}))
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })
}))
vi.mock('../../../src/main/services/global-input-hook', () => ({
acquireGlobalInputHook: () => () => undefined
}))
vi.mock('../../../src/main/services/KeyBindingService', () => ({
uiohookCodeToVk: (code: number) => code
}))
vi.mock('../../../src/main/services/UiaContextService', () => ({
getUiaContextService: () => ({
lastReason: null,
lastSuccessAt: 0,
isAvailable: () => true,
getSnapshot: vi.fn(async () => ({
available: true,
isPassword: false,
isEditable: true,
isComposing: false,
hasSelection: false,
controlType: 'Edit',
controlName: 'MessageInput',
textSource: 'value' as const,
text: state.text,
caretOffset: state.caretOffset,
caretRect: null,
elementRect: { x: 100, y: 100, width: 300, height: 40 },
windowTitle: state.windowTitle,
appName: state.appName,
processId: 1234,
capturedAt: state.now
}))
})
}))
vi.mock('../../../src/main/utils/win32-foreground', () => ({
getForegroundWindowInfo: () => ({
appName: state.appName,
title: state.windowTitle,
hwnd: state.hwnd
}),
isForegroundKoreanIme: () => false
}))
vi.mock('../../../src/main/utils/win32-input-activity', () => ({
getLastNativeInputTick: () => state.nativeTick
}))
vi.mock('../../../src/main/services/PersonalGraphService', () => ({
getPersonalGraphService: () => ({
indexText: vi.fn((text: string) => {
state.learnedTexts.push(text)
}),
observeTypedText: vi.fn(),
learnPhrase: vi.fn()
})
}))
vi.mock('../../../src/main/services/suggestion/PersonalNgramIndex', () => ({
getPersonalNgramIndex: () => ({
add: vi.fn()
})
}))
vi.mock('../../../src/main/services/text-insert/electron-clipboard-port', () => ({
electronClipboardPort: { readText: () => '', writeText: vi.fn() }
}))
import {
getInputTelemetryService,
resetInputTelemetryServiceForTests
} from '../../../src/main/services/InputTelemetryService'
import { TypoCorrectionService } from '../../../src/main/services/TypoCorrectionService'
import { TextInsertService } from '../../../src/main/services/TextInsertService'
function emitKeyDown(vk: number, shift = false): void {
const handlers = state.listeners.get('keydown') ?? []
for (const handler of handlers) {
handler({
keycode: vk,
ctrlKey: false,
altKey: false,
metaKey: false,
shiftKey: shift
})
}
}
async function advance(ms: number): Promise<void> {
let remaining = ms
while (remaining > 0) {
const step = Math.min(50, remaining)
state.now += step
remaining -= step
await vi.advanceTimersByTimeAsync(step)
}
}
function wireLivePipeline() {
const telemetry = getInputTelemetryService()
const keyboard = {
type: vi.fn(async () => undefined),
paste: vi.fn(async () => undefined),
backspace: vi.fn(async (count: number) => {
state.text = state.text.slice(0, -count)
}),
replaceBeforeCaret: vi.fn(async (count: number, insertText: string) => {
const idx = state.caretOffset ?? state.text.length
state.text = state.text.slice(0, idx - count) + insertText + state.text.slice(idx)
if (state.caretOffset !== null) {
state.caretOffset = idx - count + insertText.length
}
return true
})
}
const insert = new TextInsertService({ keyboard })
const typo = new TypoCorrectionService({
replaceBeforeCaret: async (deleteCount, insertText, options) => {
let baseLength = telemetry.currentTerminalPrefixLength()
const result = await insert.replaceBeforeCaret(deleteCount, insertText, 'keyboard', {
...options,
beforeApply: () => {
options?.beforeApply?.()
baseLength = telemetry.currentTerminalPrefixLength()
telemetry.expectProgrammaticKeys(deleteCount + (options?.commitComposition ? 2 : 0))
}
})
if (result.success) {
telemetry.applyProgrammaticReplacement(deleteCount, insertText, baseLength)
}
return result.success
},
lastKeyAt: () => telemetry.lastKeyAt,
inputRevision: () => telemetry.inputRevision,
nativeInputTick: () => state.nativeTick,
foregroundHandle: () => state.hwnd,
expectProgrammaticKeys: (count) => telemetry.expectProgrammaticKeys(count),
expectProgrammaticInsert: (text) => telemetry.expectProgrammaticInsert(text),
recentTexts: () => [],
warmModel: () => null,
generate: async function* () {
yield '없음'
}
})
const contexts: Array<{ caretReliable?: boolean; prefix: string }> = []
telemetry.on('typed-context', (ctx) => {
contexts.push({ caretReliable: ctx.caretReliable, prefix: ctx.prefix })
typo.handleTypingContext(ctx, { trailingWordOnly: true })
})
telemetry.start()
return { telemetry, typo, insert, keyboard, contexts }
}
describe('실시간 타이핑 문장부호 경계 오타 교정 및 추적', () => {
beforeEach(() => {
vi.useFakeTimers()
state.now = BASE_NOW
vi.setSystemTime(BASE_NOW)
state.config = {
typoAutoCorrectEnabled: true,
typoAutoCorrectUseModel: false,
typoIgnoredWords: [],
inputExcludedApps: [],
inputTelemetryEnabled: false,
inputTelemetryPaused: false,
inputLearnTypedText: false,
suggestionEnabled: false,
suggestionTriggerDelayMs: 600,
suggestionMinPrefixChars: 8
}
state.text = '상황 잘 지켜보는중?'
state.caretOffset = state.text.length
state.nativeTick = 100
state.hwnd = 77
state.listeners.clear()
state.learnedTexts = []
resetInputTelemetryServiceForTests()
})
afterEach(() => {
resetInputTelemetryServiceForTests()
vi.useRealTimers()
vi.restoreAllMocks()
})
it('liveTyping_제안비활성상태에서물음표뒤공백없는영타멈춤_정지스냅샷으로교정한다', async () => {
const { typo, keyboard } = wireLivePipeline()
try {
// 초기 포커스 기준선: '?' 까지 이미 입력됨 -> 이어서 영타 'dbrlgkrhdlTwlsdksgwl' 입력 후 멈춤
state.text = '상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl'
state.caretOffset = state.text.length
emitKeyDown(0x4c) // 'L' 키 입력 완료 시점
// 디바운스(380ms) → 정지 스냅샷(>=650ms)까지 진행
await advance(750)
expect(keyboard.replaceBeforeCaret).toHaveBeenCalledTimes(1)
expect(state.text).toBe('상황 잘 지켜보는중?유기하고있진않지')
} finally {
typo.dispose()
}
})
it('liveTyping_제안활성짧은접두나장문물음표뒤영타_경계와정지스냅샷에서놓치지않는다', async () => {
state.config.suggestionEnabled = true
state.config.suggestionTriggerDelayMs = 600
state.config.suggestionMinPrefixChars = 100
const { typo, keyboard } = wireLivePipeline()
try {
// 짧은 접두에서도 ? 뒤 23자 단일 오타는 경계 스냅샷(140ms)에서 즉시 교정된다
state.text = '왜?dbrlgkrhdlTwlsdksgwldy?'
state.caretOffset = state.text.length
emitKeyDown(0xbf, true) // '?'
await advance(150)
expect(state.text).toBe('왜?유기하고있진않지요?')
// 다중 단어 장문(>32자)도 minPrefixChars 미달과 무관하게 정지 스냅샷(<=800ms)에서 교정된다
keyboard.replaceBeforeCaret.mockClear()
state.text = '왜?dkssudgktpdy rkatkgkqslek rkatkgkqslek?'
state.caretOffset = state.text.length
emitKeyDown(0xbf, true)
await advance(850)
expect(state.text).toBe('왜?안녕하세요 감사합니다 감사합니다?')
expect(keyboard.replaceBeforeCaret).toHaveBeenCalledTimes(1)
} finally {
typo.dispose()
}
})
it('liveTyping_문장부호로끝나는치환후_잔여물음표로후속문장학습이나중간편집판정을망가뜨리지않는다', async () => {
state.config.inputLearnTypedText = true
state.caretOffset = null // caret-unknown 표면(RichEdit 등)
const { typo, contexts } = wireLivePipeline()
try {
// 기준선 형성
state.text = '상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl?'
emitKeyDown(0xbf, true)
await advance(200)
expect(state.text).toBe('상황 잘 지켜보는중?유기하고있진않지?')
// 치환 반영 스냅샷 소비 (공통 접미사 '?' 가 남아 diff 는 '유기하고있진않지' 만 잡아냄)
await advance(450)
emitKeyDown(0x20)
state.text = '상황 잘 지켜보는중?유기하고있진않지? '
await advance(450)
// programmaticKeys TTL(3s) 경과 후 (expectedInserts TTL 10s 이내) 새 문장 입력
await advance(3100)
// 이후 사용자가 새로 '정말 이상한 상황인데?' 를 치면 '?' 가 예고 삽입 잔여물로 뜯겨 나가지 않고 온전히 학습된다
state.learnedTexts = []
state.text = '상황 잘 지켜보는중?유기하고있진않지? 정말 이상한 상황인데?'
emitKeyDown(0xbf, true)
await advance(450)
expect(state.learnedTexts.join(' ')).toContain('정말 이상한 상황인데?')
// 이후 문서 중간('상황' 앞)을 편집하면 caretReliable 이 false 여야 한다 ('?' 잔여물이 programmaticEdit 를 계속 true 로 만들지 않음)
state.text = '지금 상황 잘 지켜보는중?유기하고있진않지? 정말 이상한 상황인데?'
emitKeyDown(0x41)
await advance(450)
expect(contexts[contexts.length - 1]?.caretReliable).toBe(false)
} finally {
typo.dispose()
}
})
it('liveTyping_학습비활성상태에서도교정후3초경과시_예고삽입잔존이나만료된키카운트로중간편집판정이망가지지않는다', async () => {
state.config.inputLearnTypedText = false
state.caretOffset = null // caret-unknown 표면
const { typo, contexts } = wireLivePipeline()
try {
state.text = '상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl?'
emitKeyDown(0xbf, true)
await advance(200)
expect(state.text).toBe('상황 잘 지켜보는중?유기하고있진않지?')
// 학습 비활성 경로에서도 치환 반영 스냅샷에서 expectedInserts 를 소진해야 한다
await advance(450)
// programmaticKeys TTL(3s) 경과 후 (expectedInserts TTL 10s 이내) 문서 중간 수정
await advance(3100)
state.text = '지금 상황 잘 지켜보는중?유기하고있진않지?'
emitKeyDown(0x41)
await advance(450)
expect(contexts[contexts.length - 1]?.caretReliable).toBe(false)
} finally {
typo.dispose()
}
})
})

View file

@ -139,4 +139,23 @@ describe('WindowManager popup hide/show timer race regressions', () => {
await vi.advanceTimersByTimeAsync(160)
expect(wm.isCommandPopupVisible()).toBe(false)
})
it('hideResultPopup_calledBeforeMeasureTimeout_cancelsPendingShowAndStaysHidden', async () => {
const wm = await import('../../../src/main/windows/WindowManager')
wm.showResultPopup('hello world', 5000)
const popupWin = state.windows[0]
expect(popupWin?.visible).toBe(true)
// Hide before RESULT_MEASURE_TIMEOUT_MS (400ms) fires
await vi.advanceTimersByTimeAsync(100)
wm.hideResultPopup()
expect(popupWin?.visible).toBe(false)
const sendsBeforeTimeout = popupWin?.webContents.send.mock.calls.length ?? 0
await vi.advanceTimersByTimeAsync(500)
expect(popupWin?.visible).toBe(false)
expect(popupWin?.webContents.send.mock.calls.length ?? 0).toBe(sendsBeforeTimeout)
})
})

View file

@ -0,0 +1,87 @@
import {
AdminServiceError,
listAdminUsers,
} from '../src/features/admin/admin-service'
import {
ChatServiceError,
sendChatMessage,
} from '../src/features/chat/chat-service'
import { streamTalkResponse } from '../src/features/talk/llm-stream-service'
const originalFetch = global.fetch
afterEach(() => {
global.fetch = originalFetch
jest.restoreAllMocks()
jest.useRealTimers()
})
describe('abort and streaming lifecycle guards', () => {
test('sendChatMessage_이미중단된시그널전달시_fetch없이즉시CANCELLED거부', async () => {
const fetchMock = jest.fn()
global.fetch = fetchMock
const controller = new AbortController()
controller.abort()
await expect(
sendChatMessage([{ role: 'user', content: 'hello' }], {
accessToken: 'signed-access-token',
timeoutMs: 60_000,
signal: controller.signal,
}),
).rejects.toMatchObject({
name: 'ChatServiceError',
code: 'CANCELLED',
retryable: false,
})
expect(fetchMock).not.toHaveBeenCalled()
expect(ChatServiceError.name).toBe('ChatServiceError')
})
test('adminService_이미중단된시그널전달시_비재시도네트워크오류로즉시거부', async () => {
const fetchMock = jest.fn()
global.fetch = fetchMock
const controller = new AbortController()
controller.abort()
await expect(
listAdminUsers({
accessToken: 'authenticated-admin-access-token',
signal: controller.signal,
}),
).rejects.toMatchObject({
code: 'network',
retryable: false,
})
expect(fetchMock).not.toHaveBeenCalled()
expect(AdminServiceError.name).toBe('AdminServiceError')
})
test('streamTalkResponse_생성영수증ID누락시_응답스트림을취소하고실패종료', async () => {
const cancelMock = jest.fn(async () => undefined)
global.fetch = jest.fn().mockResolvedValue({
ok: true,
status: 200,
headers: {
get: (name: string) => (
name.toLowerCase() === 'content-type' ? 'text/event-stream' : null
),
},
body: {
cancel: cancelMock,
getReader: () => ({
read: async () => ({ done: true, value: undefined }),
releaseLock: jest.fn(),
}),
},
} as unknown as Response)
await expect(
streamTalkResponse([{ role: 'user', content: 'hello' }], {
accessToken: 'signed-talk-token',
onTextDelta: jest.fn(),
}),
).rejects.toMatchObject({ code: 'INVALID_RESPONSE', retryable: true })
expect(cancelMock).toHaveBeenCalledTimes(1)
})
})

View file

@ -0,0 +1,467 @@
import React from 'react'
import ReactTestRenderer, { act } from 'react-test-renderer'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { Platform } from 'react-native'
const USER_A = '11111111-1111-4111-8111-111111111111'
const USER_B = '22222222-2222-4222-8222-222222222222'
const PRODUCT_ID = 'd3ro_voice_pro_monthly'
let mockAuthState: {
user: { id: string } | null
purgeLocalSession: jest.Mock
} = {
user: { id: USER_A },
purgeLocalSession: jest.fn(async () => undefined),
}
const mockEntitlementHookValue = {
loading: false,
stale: false,
error: null,
snapshot: {
tier: 'free',
adFree: false,
overageCredits: 0,
provider: 'none',
storeProductId: null,
},
refresh: jest.fn<Promise<unknown>, []>(async () => null),
}
const mockFrom = jest.fn()
const mockFunctionsInvoke = jest.fn()
jest.mock('../src/lib/auth-context', () => ({
useAuth: () => mockAuthState,
}))
jest.mock('../src/lib/entitlement-context', () => {
const actual = jest.requireActual('../src/lib/entitlement-context') as typeof import('../src/lib/entitlement-context')
return {
...actual,
useEntitlement: jest.fn(() => mockEntitlementHookValue),
}
})
jest.mock('../src/lib/native-config', () => ({
getMobileRuntimeConfig: jest.fn(() => ({
debug: true,
installedFromPlayStore: true,
adMobBannerUnitId: 'ca-app-pub-3940256099942544/6300978111',
adMobRewardedUnitId: 'ca-app-pub-3940256099942544/5224354917',
})),
}))
jest.mock('../src/lib/supabase', () => ({
supabase: {
from: (...args: unknown[]) => mockFrom(...args),
functions: {
invoke: (...args: unknown[]) => mockFunctionsInvoke(...args),
},
channel: jest.fn(() => ({
on: jest.fn().mockReturnThis(),
subscribe: jest.fn().mockReturnThis(),
})),
removeChannel: jest.fn(async () => 'ok'),
},
}))
const mockedEntitlement = jest.requireMock('../src/lib/entitlement-context') as {
useEntitlement: jest.Mock
EntitlementProvider: typeof import('../src/lib/entitlement-context').EntitlementProvider
}
const mockedAds = jest.requireActual('react-native-google-mobile-ads') as {
AdsConsent: {
gatherConsent: jest.Mock
getConsentInfo: jest.Mock
showPrivacyOptionsForm: jest.Mock
}
MobileAds: jest.Mock
useRewardedAd: jest.Mock
}
const mockedIap = jest.requireActual('react-native-iap') as {
useIAP: jest.Mock
__stableUseIapResult: Record<string, unknown> & {
onPurchaseSuccess?: (purchase: unknown) => void
}
}
import { MobileAdsProvider, useMobileAds, useRewardedCredits } from '../src/lib/mobile-ads-context'
import { BillingProvider, useBilling } from '../src/lib/billing-context'
import { DeviceProvider, useDevice } from '../src/lib/device-context'
import { DeviceServiceError, registerCurrentDevice } from '../src/features/devices/device-service'
function deferred<T>() {
let resolve: (value: T) => void = () => undefined
let reject: (reason?: unknown) => void = () => undefined
const promise = new Promise<T>((res, rej) => {
resolve = res
reject = rej
})
return { promise, resolve, reject }
}
async function flushMicrotasks(): Promise<void> {
for (let index = 0; index < 8; index += 1) await Promise.resolve()
}
describe('context lifecycle and concurrency guards', () => {
const originalPlatform = Platform.OS
let activeRenderer: ReactTestRenderer.ReactTestRenderer | null = null
beforeAll(() => {
Object.defineProperty(Platform, 'OS', { configurable: true, value: 'android' })
})
afterAll(() => {
Object.defineProperty(Platform, 'OS', { configurable: true, value: originalPlatform })
})
beforeEach(async () => {
await AsyncStorage.clear()
mockAuthState = {
user: { id: USER_A },
purgeLocalSession: jest.fn(async () => undefined),
}
mockEntitlementHookValue.loading = false
mockEntitlementHookValue.stale = false
mockEntitlementHookValue.error = null
mockEntitlementHookValue.snapshot = {
tier: 'free',
adFree: false,
overageCredits: 0,
provider: 'none',
storeProductId: null,
}
mockEntitlementHookValue.refresh = jest.fn(async () => null)
mockedEntitlement.useEntitlement.mockImplementation(() => mockEntitlementHookValue)
mockFrom.mockReset()
mockFunctionsInvoke.mockReset()
mockedAds.AdsConsent.gatherConsent.mockReset().mockResolvedValue({
canRequestAds: true,
privacyOptionsRequirementStatus: 'NOT_REQUIRED',
})
mockedAds.AdsConsent.getConsentInfo.mockReset().mockResolvedValue({
canRequestAds: true,
privacyOptionsRequirementStatus: 'NOT_REQUIRED',
})
mockedAds.MobileAds.mockReset().mockImplementation(() => ({
initialize: jest.fn(async () => []),
setRequestConfiguration: jest.fn(async () => undefined),
}))
mockedIap.__stableUseIapResult.connected = true
mockedIap.__stableUseIapResult.subscriptions = []
mockedIap.useIAP.mockImplementation(() => mockedIap.__stableUseIapResult)
})
afterEach(() => {
if (activeRenderer !== null) {
const target = activeRenderer
activeRenderer = null
act(() => target.unmount())
}
jest.restoreAllMocks()
jest.useRealTimers()
})
test('MobileAdsProvider_광고초기화중비대상전환시_ready로덮어쓰지않음', async () => {
const initGate = deferred<unknown[]>()
mockedAds.MobileAds.mockImplementation(() => ({
setRequestConfiguration: jest.fn(async () => undefined),
initialize: jest.fn(() => initGate.promise),
}))
let latestAds: ReturnType<typeof useMobileAds> | null = null
function Probe(): null {
latestAds = useMobileAds()
return null
}
let renderer!: ReactTestRenderer.ReactTestRenderer
await act(async () => {
renderer = ReactTestRenderer.create(
<MobileAdsProvider><Probe /></MobileAdsProvider>,
)
activeRenderer = renderer
await flushMicrotasks()
})
expect(latestAds?.status).toBe('initializing')
// User upgrades to Pro (adFree: true -> eligible: false) while MobileAds().initialize() is pending.
mockEntitlementHookValue.snapshot = {
...mockEntitlementHookValue.snapshot,
tier: 'pro',
adFree: true,
}
await act(async () => {
renderer.update(<MobileAdsProvider><Probe /></MobileAdsProvider>)
await flushMicrotasks()
})
expect(latestAds?.status).toBe('disabled')
await act(async () => {
initGate.resolve([])
await flushMicrotasks()
})
expect(latestAds?.status).toBe('disabled')
act(() => renderer.unmount())
})
test('useRewardedCredits_entitlement갱신중재시도시_이전검증완료상태로덮어쓰지않음', async () => {
jest.useFakeTimers()
let latestRewarded: ReturnType<typeof useRewardedCredits> | null = null
mockedAds.useRewardedAd.mockImplementation(() => ({
error: undefined,
isClosed: false,
isEarnedReward: true,
isLoaded: true,
isShowing: false,
load: jest.fn(),
show: jest.fn(),
}))
mockFrom.mockImplementation(() => ({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
maybeSingle: jest.fn(async () => ({ data: { overage_credits: 5 }, error: null })),
}))
const refreshGate = deferred<unknown>()
mockEntitlementHookValue.refresh = jest.fn(() => refreshGate.promise)
function Probe(): null {
latestRewarded = useRewardedCredits()
return null
}
let renderer!: ReactTestRenderer.ReactTestRenderer
await act(async () => {
renderer = ReactTestRenderer.create(
<MobileAdsProvider><Probe /></MobileAdsProvider>,
)
activeRenderer = renderer
await flushMicrotasks()
})
await act(async () => {
await jest.advanceTimersByTimeAsync(1_200)
await flushMicrotasks()
})
expect(mockEntitlementHookValue.refresh).toHaveBeenCalledTimes(1)
// Call reload() while entitlement.refresh() is still in flight.
act(() => {
latestRewarded?.reload()
})
expect(latestRewarded?.status).toBe('loading')
await act(async () => {
refreshGate.resolve(null)
await flushMicrotasks()
})
expect(latestRewarded?.status).toBe('loading')
act(() => renderer.unmount())
})
test('BillingProvider_결제요청중계정전환시_이전계정오류로상태를덮어쓰지않음', async () => {
const requestPurchaseGate = deferred<unknown>()
mockedIap.__stableUseIapResult.subscriptions = [{
id: PRODUCT_ID,
platform: 'android',
title: 'Pro Monthly',
description: 'Pro',
displayPrice: '$9.99',
subscriptionOffers: [{
offerTokenAndroid: 'offer-token-1',
displayPrice: '$9.99',
basePlanIdAndroid: 'monthly',
offerTagsAndroid: ['default'],
}],
}]
mockedIap.__stableUseIapResult.getAvailablePurchases = jest.fn(async () => [])
mockedIap.__stableUseIapResult.requestPurchase = jest.fn(() => requestPurchaseGate.promise)
let latestBilling: ReturnType<typeof useBilling> | null = null
function Probe(): null {
latestBilling = useBilling()
return null
}
let renderer!: ReactTestRenderer.ReactTestRenderer
await act(async () => {
renderer = ReactTestRenderer.create(
<BillingProvider><Probe /></BillingProvider>,
)
activeRenderer = renderer
await flushMicrotasks()
})
let pendingPurchase: Promise<unknown> = Promise.resolve()
act(() => {
pendingPurchase = latestBilling!.purchase(PRODUCT_ID).catch(() => undefined)
})
await flushMicrotasks()
expect(latestBilling?.operation).toBe('purchasing')
// Account switches from USER_A to USER_B while Google Play purchase flow is pending.
mockAuthState.user = { id: USER_B }
await act(async () => {
renderer.update(<BillingProvider><Probe /></BillingProvider>)
await flushMicrotasks()
})
expect(latestBilling?.operation).toBe('idle')
await act(async () => {
requestPurchaseGate.reject(new Error('billing unavailable'))
await pendingPurchase
await flushMicrotasks()
})
expect(latestBilling?.operation).toBe('idle')
expect(latestBilling?.errorCode).toBe(null)
activeRenderer = null
act(() => renderer.unmount())
})
test('DeviceProvider_세션파기실패후재시도시_복구호출을영구차단하지않음', async () => {
mockAuthState.purgeLocalSession
.mockRejectedValueOnce(new Error('storage busy'))
.mockResolvedValueOnce(undefined)
const revokedRow = {
id: 'device-1',
user_id: USER_A,
installation_id: '00000000-0000-4000-8000-000000000001',
platform: 'android',
device_name: 'Pixel 8',
app_version: '1.0.0',
os_version: 'Android 14',
push_token: null,
last_seen_at: '2026-08-21T00:00:00Z',
revoked_at: '2026-08-21T00:00:05Z',
created_at: '2026-08-20T00:00:00Z',
updated_at: '2026-08-21T00:00:05Z',
}
mockFrom.mockImplementation(() => ({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
maybeSingle: jest.fn(async () => ({ data: revokedRow, error: null })),
update: jest.fn().mockReturnThis(),
single: jest.fn(async () => ({ data: revokedRow, error: null })),
}))
let latestDevice: ReturnType<typeof useDevice> | null = null
function Probe(): null {
latestDevice = useDevice()
return null
}
let renderer!: ReactTestRenderer.ReactTestRenderer
await act(async () => {
renderer = ReactTestRenderer.create(
<DeviceProvider><Probe /></DeviceProvider>,
)
activeRenderer = renderer
await flushMicrotasks()
})
expect(mockAuthState.purgeLocalSession).toHaveBeenCalledTimes(1)
await act(async () => {
await latestDevice?.refreshCurrentDevice()
})
expect(mockAuthState.purgeLocalSession).toHaveBeenCalledTimes(2)
act(() => renderer.unmount())
})
test('registerCurrentDevice_23505충돌반복시_무한재귀없이실패종료', async () => {
const maybeSingle = jest.fn(async () => ({ data: null, error: null }))
let attempts = 0
const single = jest.fn(async () => {
attempts += 1
if (attempts <= 5) {
return {
data: null,
error: { code: '23505', message: 'duplicate key value violates unique constraint' },
}
}
return {
data: {
id: 'device-after-loop',
user_id: USER_A,
installation_id: '00000000-0000-4000-8000-000000000001',
platform: 'android',
device_name: 'Pixel 8',
app_version: '1.0.0',
os_version: 'Android 14',
push_token: null,
last_seen_at: '2026-08-21T00:00:00Z',
revoked_at: null,
created_at: '2026-08-20T00:00:00Z',
updated_at: '2026-08-21T00:00:00Z',
},
error: null,
}
})
mockFrom.mockImplementation(() => ({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
maybeSingle,
insert: jest.fn(() => ({
select: jest.fn(() => ({ single })),
})),
}))
await expect(
registerCurrentDevice(USER_A, { debug: true, packageName: 'com.d3ro.voice' } as never),
).rejects.toThrow(DeviceServiceError)
expect(single).toHaveBeenCalledTimes(2)
})
test('EntitlementProvider_캐시읽기실패시_미처리거부없이원격갱신진행', async () => {
jest.spyOn(AsyncStorage, 'getItem').mockRejectedValueOnce(new Error('disk I/O failure'))
mockFrom.mockImplementation((table: string) => {
const result = table === 'subscriptions'
? { data: null, error: null }
: { data: [], error: null }
const builder: Record<string, unknown> = {
select: jest.fn(() => builder),
eq: jest.fn(() => builder),
order: jest.fn(() => builder),
limit: jest.fn(() => builder),
maybeSingle: jest.fn(async () => ({ data: null, error: null })),
then: (resolve: (val: unknown) => unknown, reject: (err: unknown) => unknown) => (
Promise.resolve(result).then(resolve, reject)
),
}
return builder
})
let unhandledError: unknown = null
const onUnhandled = (reason: unknown): void => {
unhandledError = reason
}
process.on('unhandledRejection', onUnhandled)
const actualModule = jest.requireActual('../src/lib/entitlement-context') as typeof import('../src/lib/entitlement-context')
let latestEnt: ReturnType<typeof actualModule.useEntitlement> | null = null
function Probe(): null {
latestEnt = actualModule.useEntitlement()
return null
}
let renderer!: ReactTestRenderer.ReactTestRenderer
await act(async () => {
renderer = ReactTestRenderer.create(
<actualModule.EntitlementProvider><Probe /></actualModule.EntitlementProvider>,
)
activeRenderer = renderer
await flushMicrotasks()
await new Promise<void>((resolve) => setTimeout(resolve, 0))
})
process.off('unhandledRejection', onUnhandled)
expect(unhandledError).toBe(null)
expect(latestEnt?.loading).toBe(false)
act(() => renderer.unmount())
})
})

View file

@ -0,0 +1,350 @@
import React from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { FileSystem } from 'react-native-file-access'
import {
AudioPipelineError,
type AudioPipelineResult,
type LocalAudioInput,
} from '../src/features/import/audio-import-types'
import type { HistoryListEntry, HistoryPageResult } from '../src/features/history/history-service'
const START_MS = 1_700_000_000_000
const USER_A = '11111111-1111-4111-8111-111111111111'
const USER_B = '22222222-2222-4222-8222-222222222222'
const mockProcessAudioInput = jest.fn<Promise<AudioPipelineResult>, [LocalAudioInput, unknown]>()
const mockListHistoryPage = jest.fn<Promise<HistoryPageResult>, [unknown]>()
const mockLoadHistoryCache = jest.fn()
const mockUpdateHistoryRevisionSafe = jest.fn()
let mockAuthUser: { id: string } | null = null
jest.mock('../src/lib/supabase', () => ({
supabase: {
channel: jest.fn(),
removeChannel: jest.fn(async () => 'ok'),
},
}))
jest.mock('../src/lib/auth-context', () => ({
useAuth: () => ({ user: mockAuthUser }),
}))
jest.mock('../src/features/import/audio-transcription-service', () => ({
processAudioInput: (input: LocalAudioInput, options: unknown) => mockProcessAudioInput(input, options),
}))
jest.mock('../src/features/meetings/meetings-service', () => ({
failMeetingRecording: jest.fn(async () => undefined),
markMeetingProcessingFailure: jest.fn(async () => undefined),
queueMeetingRecording: jest.fn(async () => undefined),
}))
jest.mock('../src/features/history/history-service', () => ({
...jest.requireActual('../src/features/history/history-service'),
listHistoryPage: (options: unknown) => mockListHistoryPage(options),
subscribeToHistory: () => ({ unsubscribe: async () => undefined }),
updateHistoryRevisionSafe: (...args: unknown[]) => mockUpdateHistoryRevisionSafe(...args),
}))
jest.mock('../src/features/history/history-cache', () => ({
...jest.requireActual('../src/features/history/history-cache'),
loadHistoryCache: (...args: unknown[]) => mockLoadHistoryCache(...args),
saveHistoryCache: jest.fn(async () => undefined),
clearHistoryCache: jest.fn(async () => undefined),
}))
import {
clearQueuedAudioForUser,
durableQueueTestContract,
processQueuedAudioNow,
QueuedAudioPendingError,
resumeQueuedAudioForUser,
retainQueuedAudioOnlyForUser,
retryQueuedAudio,
type DurableQueueItem,
} from '../src/features/recording/durable-processing-queue'
import { useHistorySync } from '../src/features/history/use-history-sync'
const mockFileSystem = FileSystem as typeof FileSystem & {
filesystem: Map<string, string>
unlink: jest.Mock
}
function makeQueueItem(
userId: string,
suffix: string,
overrides: Partial<DurableQueueItem> = {},
): DurableQueueItem {
const path = `${durableQueueTestContract.queueDirectory}/queued-${suffix}.wav`
return {
schemaVersion: 1,
id: suffix,
userId,
meetingId: null,
path,
uri: `file://${path}`,
fileName: `${suffix}.wav`,
mimeType: 'audio/wav',
sizeBytes: 128,
durationMs: 1_000,
source: 'recording',
languageCode: 'ko',
status: 'pending',
phase: null,
attempts: 0,
uploadedBytes: 0,
nextAttemptAtMs: START_MS,
lastErrorCode: null,
lastErrorMessage: null,
createdAtMs: START_MS,
updatedAtMs: START_MS,
...overrides,
}
}
function makeHistoryEntry(id: string, userId = USER_A): HistoryListEntry {
return {
id,
user_id: userId,
title: `entry ${id}`,
original_text: `text ${id}`,
polished_text: null,
focused_app: null,
focused_app_name: null,
focused_app_window_title: null,
mode: 'dictation',
status: 'completed',
error_code: null,
audio_storage_key: null,
duration: 2,
detected_language: 'ko',
mic_device: null,
word_count: 1,
stt_model: 'whisper',
llm_model: null,
stt_latency_ms: null,
llm_latency_ms: null,
app_version: '1.0.0',
summary_text: null,
is_favorite: false,
revision: 1,
created_at: '2026-08-21T00:00:00.000Z',
updated_at: '2026-08-21T00:00:00.000Z',
activeJob: null,
}
}
function deferred<T>() {
let resolve: (value: T) => void = () => undefined
let reject: (reason?: unknown) => void = () => undefined
const promise = new Promise<T>((res, rej) => {
resolve = res
reject = rej
})
return { promise, resolve, reject }
}
async function flushMicrotasks(): Promise<void> {
for (let index = 0; index < 8; index += 1) await Promise.resolve()
}
describe('durable queue and history sync race guards', () => {
let activeRenderer: ReactTestRenderer | null = null
beforeEach(async () => {
jest.useFakeTimers({ now: START_MS })
await AsyncStorage.clear()
mockFileSystem.filesystem.clear()
mockFileSystem.unlink.mockClear()
mockProcessAudioInput.mockReset()
mockListHistoryPage.mockReset()
mockLoadHistoryCache.mockReset()
mockUpdateHistoryRevisionSafe.mockReset()
mockAuthUser = null
})
afterEach(async () => {
if (activeRenderer !== null) {
const target = activeRenderer
activeRenderer = null
act(() => target.unmount())
}
await clearQueuedAudioForUser(USER_A).catch(() => undefined)
await clearQueuedAudioForUser(USER_B).catch(() => undefined)
await resumeQueuedAudioForUser(USER_A).catch(() => undefined)
await resumeQueuedAudioForUser(USER_B).catch(() => undefined)
jest.clearAllTimers()
jest.useRealTimers()
})
test('durableQueue_정지된사용자의재시도실패시_스케줄러를재예약하지않음', async () => {
const item = makeQueueItem(USER_A, 'aaaa0001')
mockFileSystem.filesystem.set(item.path, 'audio-bytes')
await AsyncStorage.setItem(durableQueueTestContract.storageKey, JSON.stringify([item]))
const runGate = deferred<AudioPipelineResult>()
mockProcessAudioInput.mockImplementationOnce(() => runGate.promise)
const processing = processQueuedAudioNow(USER_A, item.id).catch((err: unknown) => err)
await flushMicrotasks()
await retainQueuedAudioOnlyForUser(USER_A)
runGate.reject(new AudioPipelineError('upload', 'network temporarily offline'))
const caught = await processing
expect(caught).toBeInstanceOf(QueuedAudioPendingError)
expect(jest.getTimerCount()).toBe(0)
await jest.advanceTimersByTimeAsync(120_000)
await flushMicrotasks()
// While USER_A remains suspended after retainQueuedAudioOnlyForUser, no retry run fires.
expect(mockProcessAudioInput).toHaveBeenCalledTimes(1)
})
test('durableQueue_정지또는정리단계항목재시도시_running이나cleanup상태를덮어쓰지않음', async () => {
const cleaningItem = makeQueueItem(USER_A, 'aaaa0002', {
status: 'cleanup',
phase: 'saving',
})
const runningItem = makeQueueItem(USER_A, 'aaaa0003', {
status: 'running',
phase: 'transcribing',
})
mockFileSystem.filesystem.set(cleaningItem.path, 'audio-bytes')
mockFileSystem.filesystem.set(runningItem.path, 'audio-bytes')
await AsyncStorage.setItem(
durableQueueTestContract.storageKey,
JSON.stringify([cleaningItem, runningItem]),
)
mockProcessAudioInput.mockResolvedValue({
historyId: null,
audioFileId: 'audio-file',
meetingId: null,
processingJobId: null,
transcript: 'done',
provider: 'test',
language: 'ko',
durationSeconds: 1,
deduplicated: false,
})
// Hold resume at readQueue or reject nothing — instead inspect status change before resume consumes running.
await retryQueuedAudio(USER_A, cleaningItem.id)
const afterCleanupRetry = durableQueueTestContract.parseQueue(
await AsyncStorage.getItem(durableQueueTestContract.storageKey),
)
const cleanupState = afterCleanupRetry.find((candidate) => candidate.id === cleaningItem.id)
// cleanup item must not be downgraded to retry and re-transcribed, and its local file must be removed.
expect(mockProcessAudioInput).not.toHaveBeenCalled()
expect(cleanupState).toBeUndefined()
expect(mockFileSystem.filesystem.has(cleaningItem.path)).toBe(false)
await retryQueuedAudio(USER_A, runningItem.id)
const afterRunningRetry = durableQueueTestContract.parseQueue(
await AsyncStorage.getItem(durableQueueTestContract.storageKey),
)
expect(afterRunningRetry.find((candidate) => candidate.id === runningItem.id)?.status).toBe('running')
})
test('durableQueue_정리단계재시도중파일삭제실패시_큐항목을유지하고정리재시도를예약함', async () => {
const cleaningItem = makeQueueItem(USER_A, 'aaaa0004', {
status: 'cleanup',
phase: 'saving',
})
mockFileSystem.filesystem.set(cleaningItem.path, 'audio-bytes')
await AsyncStorage.setItem(durableQueueTestContract.storageKey, JSON.stringify([cleaningItem]))
mockFileSystem.unlink.mockRejectedValueOnce(new Error('filesystem busy'))
await retryQueuedAudio(USER_A, cleaningItem.id)
const retained = durableQueueTestContract.parseQueue(
await AsyncStorage.getItem(durableQueueTestContract.storageKey),
)
expect(retained.find((candidate) => candidate.id === cleaningItem.id)?.status).toBe('cleanup')
expect(mockFileSystem.filesystem.has(cleaningItem.path)).toBe(true)
expect(jest.getTimerCount()).toBe(1)
await jest.advanceTimersByTimeAsync(60_000)
await flushMicrotasks()
const afterScheduledCleanup = durableQueueTestContract.parseQueue(
await AsyncStorage.getItem(durableQueueTestContract.storageKey),
)
expect(afterScheduledCleanup.find((candidate) => candidate.id === cleaningItem.id)).toBeUndefined()
expect(mockFileSystem.filesystem.has(cleaningItem.path)).toBe(false)
expect(mockProcessAudioInput).not.toHaveBeenCalled()
})
test('useHistorySync_오프라인캐시조회중새요청이나언마운트시_오래된캐시로덮어쓰지않음', async () => {
jest.useRealTimers()
let latestState: ReturnType<typeof useHistorySync> | null = null
function Probe(): null {
latestState = useHistorySync()
return null
}
const firstOfflineCache = deferred<{ savedAt: string; entries: HistoryListEntry[] } | null>()
mockAuthUser = { id: USER_A }
mockListHistoryPage
.mockRejectedValueOnce(new TypeError('Network request failed'))
.mockResolvedValueOnce({
entries: [makeHistoryEntry('fresh-entry', USER_B)],
nextCursor: null,
})
mockLoadHistoryCache.mockReturnValueOnce(firstOfflineCache.promise)
let renderer!: ReactTestRenderer
await act(async () => {
renderer = create(React.createElement(Probe))
activeRenderer = renderer
await flushMicrotasks()
})
// Switch user while USER_A's offline cache load is still pending.
mockAuthUser = { id: USER_B }
await act(async () => {
renderer.update(React.createElement(Probe))
await flushMicrotasks()
})
expect(latestState?.entries.map((item) => item.id)).toEqual(['fresh-entry'])
// Now USER_A's stalled offline cache finishes.
await act(async () => {
firstOfflineCache.resolve({
savedAt: '2026-08-21T00:00:00.000Z',
entries: [makeHistoryEntry('stale-user-a-cache', USER_A)],
})
await flushMicrotasks()
})
expect(latestState?.entries.map((item) => item.id)).toEqual(['fresh-entry'])
expect(latestState?.offline).toBe(false)
// Now test toggleFavorite resolving after user switch does not pollute USER_B's entries.
const favGate = deferred<HistoryListEntry>()
mockUpdateHistoryRevisionSafe.mockReturnValueOnce(favGate.promise)
const staleEntry = makeHistoryEntry('shared-like-entry', USER_A)
let pendingToggle: Promise<unknown> = Promise.resolve()
act(() => {
pendingToggle = latestState!.toggleFavorite(staleEntry).catch(() => undefined)
})
mockAuthUser = { id: USER_A }
mockListHistoryPage.mockResolvedValueOnce({
entries: [makeHistoryEntry('shared-like-entry', USER_A)],
nextCursor: null,
})
await act(async () => {
renderer.update(React.createElement(Probe))
await flushMicrotasks()
})
expect(latestState?.entries[0]?.is_favorite).toBe(false)
await act(async () => {
favGate.resolve({ ...staleEntry, is_favorite: true, revision: 2 })
await pendingToggle
await flushMicrotasks()
})
expect(latestState?.entries[0]?.is_favorite).toBe(false)
activeRenderer = null
act(() => renderer.unmount())
})
})

View file

@ -0,0 +1,238 @@
import { NativeModules } from 'react-native'
import { FileSystem } from 'react-native-file-access'
const mockStartRecorder = jest.fn<Promise<string>, [string, unknown, boolean]>()
const mockStopRecorder = jest.fn(async () => 'stopped')
const mockPauseRecorder = jest.fn(async () => 'paused')
const mockResumeRecorder = jest.fn(async () => 'resumed')
jest.mock('react-native-nitro-sound', () => ({
AudioEncoderAndroidType: { AAC: 3 },
AudioSourceAndroidType: { MIC: 1 },
AVEncoderAudioQualityIOSType: { high: 96 },
OutputFormatAndroidType: { MPEG_4: 2 },
createSound: () => ({
addRecordBackListener: () => undefined,
pauseRecorder: () => mockPauseRecorder(),
resumeRecorder: () => mockResumeRecorder(),
setSubscriptionDuration: () => undefined,
startRecorder: (path: string, settings: unknown, metering: boolean) => (
mockStartRecorder(path, settings, metering)
),
stopRecorder: () => mockStopRecorder(),
}),
}))
import {
AudioRecorder,
RecorderBusyError,
type RecorderBackend,
} from '../src/lib/audio-recorder'
import { AndroidForegroundRecorderBackend } from '../src/lib/recorder/android-foreground-backend'
import { NitroRecorderBackend } from '../src/lib/recorder/nitro-backend'
const MEETING_PATH = '/data/user/0/com.d3ro.voice/files/recordings/d3ro-recording-11111111-1111-4111-8111-111111111111.wav'
function nativeSnapshot(
state: 'idle' | 'starting' | 'recording' | 'paused' | 'stopped' | 'recoverable',
) {
const hasFile = state !== 'idle'
return {
state,
path: hasFile ? MEETING_PATH : null,
uri: hasFile ? `file://${MEETING_PATH}` : null,
fileName: hasFile ? 'd3ro-recording-11111111-1111-4111-8111-111111111111.wav' : null,
mimeType: 'audio/wav',
size: hasFile ? 64_044 : 0,
durationMs: hasFile ? 4_000 : 0,
meteringDb: null,
meetingId: null,
interruptionReason: null,
startedAtMs: hasFile ? 1_000 : 0,
recoverable: state === 'recoverable',
}
}
function deferred<T>() {
let resolve: (value: T) => void = () => undefined
let reject: (reason?: unknown) => void = () => undefined
const promise = new Promise<T>((res, rej) => {
resolve = res
reject = rej
})
return { promise, resolve, reject }
}
describe('audio recorder and backend lifecycle race guards', () => {
afterEach(() => {
jest.clearAllTimers()
jest.useRealTimers()
jest.restoreAllMocks()
mockStartRecorder.mockReset()
mockStopRecorder.mockClear()
delete (NativeModules as Record<string, unknown>).D3RORecording
})
test('AudioRecorder_동시start클레임경합시_한소유자만인정하고실패시임대해제', async () => {
const busyChecks: Array<ReturnType<typeof deferred<boolean>>> = []
let active = false
let failNextStart = true
const backend: RecorderBackend = {
requestPermission: jest.fn(async () => true),
start: jest.fn(async () => {
if (failNextStart) {
failNextStart = false
throw new Error('mic unavailable')
}
active = true
}),
pause: jest.fn(async () => undefined),
resume: jest.fn(async () => undefined),
stop: jest.fn(async () => ({
uri: 'file:///cache/cap.m4a',
path: '/cache/cap.m4a',
fileName: 'cap.m4a',
mimeType: 'audio/mp4',
size: 128,
durationMs: 1_000,
})),
cleanup: jest.fn(async () => { active = false }),
cancel: jest.fn(async () => { active = false }),
restore: jest.fn(async () => ({
state: 'idle' as const,
recording: null,
meetingId: null,
interruptionReason: null,
startedAtMs: 0,
})),
isBusy: jest.fn(() => {
const gate = deferred<boolean>()
busyChecks.push(gate)
return gate.promise
}),
hasInProcessCapture: jest.fn(() => active),
}
const recorder = new AudioRecorder(backend)
const recordAcquire = recorder.acquire('record')
await Promise.resolve()
busyChecks.pop()?.resolve(false)
const record = await recordAcquire
const talkAcquire = recorder.acquire('talk')
await Promise.resolve()
busyChecks.pop()?.resolve(false)
const talk = await talkAcquire
// Both record.start and talk.start race while isBusy() is pending.
const recordStart = record.start(() => undefined)
const talkStart = talk.start(() => undefined)
await Promise.resolve()
while (busyChecks.length > 0) busyChecks.shift()?.resolve(false)
await expect(recordStart).rejects.toThrow('mic unavailable')
await expect(talkStart).rejects.toBeInstanceOf(RecorderBusyError)
expect(backend.start).toHaveBeenCalledTimes(1)
// After record.start fails and stays idle, lease must be released for talk.
const secondTalkStart = talk.start(() => undefined)
await Promise.resolve()
while (busyChecks.length > 0) busyChecks.shift()?.resolve(false)
await expect(secondTalkStart).resolves.toBeUndefined()
expect(backend.start).toHaveBeenCalledTimes(2)
})
test('NitroRecorderBackend_임시파일정리중취소시_녹음시작하지않고idle복귀', async () => {
const lsGate = deferred<string[]>()
jest.spyOn(FileSystem, 'ls').mockReturnValueOnce(lsGate.promise)
mockStartRecorder.mockResolvedValue('file:///cache/fake-nitro-recording.m4a')
const backend = new NitroRecorderBackend()
const startPromise = backend.start(() => undefined)
await Promise.resolve()
await backend.cancel()
lsGate.resolve([])
await expect(startPromise).rejects.toThrow('cancelled')
expect(mockStartRecorder).not.toHaveBeenCalled()
expect(backend.hasInProcessCapture()).toBe(false)
})
test('AndroidForegroundRecorderBackend_정지및취소시_예약된폴타이머를모두해제함', async () => {
jest.useFakeTimers()
const native = {
current: nativeSnapshot('idle'),
getStatus: jest.fn(async () => native.current),
start: jest.fn(async () => {
native.current = nativeSnapshot('recording')
return native.current
}),
pause: jest.fn(async () => nativeSnapshot('paused')),
resume: jest.fn(async () => nativeSnapshot('recording')),
stop: jest.fn(async () => {
native.current = nativeSnapshot('stopped')
return native.current
}),
cancel: jest.fn(async () => {
native.current = nativeSnapshot('idle')
return native.current
}),
dispose: jest.fn(async () => {
native.current = nativeSnapshot('idle')
}),
}
;(NativeModules as Record<string, unknown>).D3RORecording = native
const backend = new AndroidForegroundRecorderBackend()
await backend.start(() => undefined)
await Promise.resolve()
expect(jest.getTimerCount()).toBeGreaterThan(0)
await backend.stop()
expect(jest.getTimerCount()).toBe(0)
await backend.cleanup()
native.getStatus.mockRejectedValueOnce(new Error('transient bridge error'))
await backend.start(() => undefined)
await Promise.resolve()
expect(jest.getTimerCount()).toBeGreaterThan(0)
await backend.cancel()
expect(jest.getTimerCount()).toBe(0)
})
test('AndroidForegroundRecorderBackend_시작중취소호출시_지연된시작응답이idle상태를덮어쓰지않음', async () => {
jest.useFakeTimers()
const startGate = deferred<ReturnType<typeof nativeSnapshot>>()
const native = {
current: nativeSnapshot('idle'),
getStatus: jest.fn(async () => native.current),
start: jest.fn(() => startGate.promise),
pause: jest.fn(async () => nativeSnapshot('paused')),
resume: jest.fn(async () => nativeSnapshot('recording')),
stop: jest.fn(async () => nativeSnapshot('stopped')),
cancel: jest.fn(async () => {
native.current = nativeSnapshot('idle')
return native.current
}),
dispose: jest.fn(async () => undefined),
}
;(NativeModules as Record<string, unknown>).D3RORecording = native
const backend = new AndroidForegroundRecorderBackend()
const startPromise = backend.start(() => undefined)
await Promise.resolve()
await backend.cancel()
expect(native.cancel).toHaveBeenCalledTimes(1)
native.current = nativeSnapshot('recording')
startGate.resolve(native.current)
await expect(startPromise).rejects.toThrow('cancelled')
expect(backend.hasInProcessCapture()).toBe(false)
expect(native.cancel).toHaveBeenCalledTimes(2)
expect(jest.getTimerCount()).toBe(0)
})
})

File diff suppressed because it is too large Load diff

View file

@ -406,6 +406,9 @@ async function requestAdmin(path: string, options: RequestOptions): Promise<unkn
options.signal?.addEventListener('abort', abortFromCaller, { once: true })
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
try {
if (options.signal?.aborted === true) {
throw new AdminServiceError('network', null, false)
}
const response = await fetch(`${SUPABASE_URL}/functions/v1/${path}`, {
method: options.method ?? 'GET',
headers: {

View file

@ -100,6 +100,9 @@ async function sendChatRequest(
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 45_000)
try {
if (options.signal?.aborted === true) {
throw new ChatServiceError('CANCELLED', false)
}
const headers: Record<string, string> = {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',

View file

@ -87,6 +87,14 @@ const DEVICE_COLUMNS = [
export async function registerCurrentDevice(
userId: string,
config: MobileRuntimeConfig,
): Promise<RegisteredDevice> {
return registerCurrentDeviceAttempt(userId, config, true)
}
async function registerCurrentDeviceAttempt(
userId: string,
config: MobileRuntimeConfig,
allowConflictRetry: boolean,
): Promise<RegisteredDevice> {
requireUserId(userId)
const existing = await supabase
@ -130,9 +138,11 @@ export async function registerCurrentDevice(
.select(DEVICE_COLUMNS)
.single()
if (inserted.error) {
// A simultaneous bootstrap may have won the unique key. Fetching again is
// safe and never clears a remote revocation.
if (inserted.error.code === '23505') return registerCurrentDevice(userId, config)
// A simultaneous bootstrap may have won the unique key. Retry once safely
// while preventing infinite recursion when conflict errors persist.
if (inserted.error.code === '23505' && allowConflictRetry) {
return registerCurrentDeviceAttempt(userId, config, false)
}
throw new DeviceServiceError('server')
}
return normalizeRegisteredDevice(inserted.data)

View file

@ -209,6 +209,7 @@ export function useHistorySync(): HistorySyncModel {
try {
const cached = await loadHistoryCache(userId)
if (currentRequest !== requestId.current) return
if (cached !== null) {
commitWindow({
entries: filterCachedHistory(cached.entries, filter, debouncedSearch),
@ -222,6 +223,7 @@ export function useHistorySync(): HistorySyncModel {
setOffline(normalized.code === 'network')
}
} catch (cacheError) {
if (currentRequest !== requestId.current) return
setCacheWarning(true)
setError(normalized.code === 'network' ? normalized : syncError(cacheError))
setOffline(normalized.code === 'network')
@ -378,6 +380,7 @@ export function useHistorySync(): HistorySyncModel {
entry.revision,
{ is_favorite: optimisticFavorite },
)
if (!isCurrentScope()) return
const replacement: HistoryListEntry = { ...entry, ...updated }
updateEntries((current) => {
if (filter === 'favorites' && !updated.is_favorite) {
@ -387,9 +390,11 @@ export function useHistorySync(): HistorySyncModel {
})
await patchCachedEntry(entry.id, replacement, isCurrentScope)
} catch (mutationError) {
if (isCurrentScope()) {
updateEntries((current) => current.map((item) => (
item.id === entry.id ? entry : item
)))
}
throw mutationError
} finally {
endMutation(entry.id)
@ -404,9 +409,12 @@ export function useHistorySync(): HistorySyncModel {
updateEntries((current) => current.filter((item) => item.id !== entry.id))
try {
await deleteHistoryRevisionSafe(userId, entry.id, entry.revision)
if (!isCurrentScope()) return
await patchCachedEntry(entry.id, null, isCurrentScope)
} catch (mutationError) {
if (isCurrentScope()) {
updateEntries((current) => mergeHistoryEntries(current, [entry]))
}
throw mutationError
} finally {
endMutation(entry.id)

View file

@ -438,7 +438,14 @@ async function processItemCore(item: DurableQueueItem): Promise<AudioPipelineRes
};
await replaceItem(current);
await reportMeetingFailure(current, error, !canRetry);
if (canRetry) scheduler.arm(current.userId, current.nextAttemptAtMs);
if (discardedItems.has(current.id)) {
discardedItems.delete(current.id);
await removeItem(current).catch(() => undefined);
throw new AudioPipelineError('cancelled', 'Queued audio processing was cancelled', error);
}
if (canRetry && !suspendedUsers.has(current.userId)) {
scheduler.arm(current.userId, current.nextAttemptAtMs);
}
throw canRetry ? new QueuedAudioPendingError(current) : error;
} finally {
runningControllers.delete(item.id);
@ -466,6 +473,17 @@ export async function processQueuedAudioNow(
return processItem(item);
}
async function finishCleanupItem(item: DurableQueueItem): Promise<void> {
try {
await removeOwnedFile(item.path);
await removeItem(item);
} catch {
if (!suspendedUsers.has(item.userId)) {
scheduler.arm(item.userId, Date.now() + 60_000);
}
}
}
/**
* One pass over the user's queue. The listing only fixes the visiting order;
* every item is re-read right before acting on it, so work done meanwhile by
@ -485,12 +503,7 @@ async function runResumePass(userId: string): Promise<void> {
if (item === undefined || item.userId !== userId) continue;
if (item.status === 'terminal') continue;
if (item.status === 'cleanup') {
try {
await removeOwnedFile(item.path);
await removeItem(item);
} catch {
scheduler.arm(userId, Date.now() + 60_000);
}
await finishCleanupItem(item);
continue;
}
if (item.nextAttemptAtMs > Date.now()) {
@ -523,6 +536,11 @@ export async function retryQueuedAudio(userId: string, itemId: string): Promise<
const items = await readQueue();
const item = items.find(candidate => candidate.id === itemId && candidate.userId === userId);
if (item === undefined) throw new AudioPipelineError('file-read', 'Queued audio was not found');
if (item.status === 'running' || runningItemPromises.has(item.id)) return;
if (item.status === 'cleanup') {
await finishCleanupItem(item);
return;
}
await replaceItem({
...item,
status: 'retry',

View file

@ -280,6 +280,7 @@ export async function streamTalkResponse(
const generationId = response.headers.get('X-D3RO-Generation-Id')?.trim() ?? ''
if (!isUuid(generationId)) {
await response.body?.cancel?.().catch(() => undefined)
throw new ChatServiceError('INVALID_RESPONSE', true)
}
const text = await consumeStreamingBody(response, options.onTextDelta)

View file

@ -44,6 +44,7 @@ export function createPlatformRecorderBackend(): RecorderBackend {
export class AudioRecorder {
private selectedBackend: RecorderBackend | null;
private lease: RecorderOwner | null = null;
private pendingClaim: { owner: RecorderOwner; depth: number } | null = null;
constructor(backend?: RecorderBackend) {
this.selectedBackend = backend ?? null;
@ -102,6 +103,9 @@ export class AudioRecorder {
}
private async assertAvailable(owner: RecorderOwner): Promise<void> {
if (this.pendingClaim !== null && this.pendingClaim.owner !== owner) {
throw new RecorderBusyError(this.pendingClaim.owner);
}
const holder = await this.holder();
if (holder !== null && holder !== owner) throw new RecorderBusyError(holder);
// Another owner may have started a capture while the status was read.
@ -115,9 +119,28 @@ export class AudioRecorder {
claim: boolean,
operation: () => Promise<T>,
): Promise<T> {
if (this.pendingClaim !== null && this.pendingClaim.owner !== owner) {
throw new RecorderBusyError(this.pendingClaim.owner);
}
if (claim) {
this.pendingClaim = this.pendingClaim?.owner === owner
? { owner, depth: this.pendingClaim.depth + 1 }
: { owner, depth: 1 };
}
try {
await this.assertAvailable(owner);
if (claim) this.lease = owner;
return operation();
return await operation();
} finally {
if (claim && this.pendingClaim?.owner === owner) {
if (this.pendingClaim.depth <= 1) {
this.pendingClaim = null;
} else {
this.pendingClaim = { owner, depth: this.pendingClaim.depth - 1 };
}
this.releaseIfIdle(owner);
}
}
}
private async cleanupAsOwner(

View file

@ -298,13 +298,24 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
const [errorCode, setErrorCode] = useState<string | null>(null)
const inFlightPurchases = useRef(new Set<string>())
const userIdRef = useRef<string | null>(user?.id ?? null)
const mountedRef = useRef(true)
const productsGenerationRef = useRef(0)
const installedFromPlayStore = useMemo(
() => Platform.OS === 'android' && getMobileRuntimeConfig().installedFromPlayStore,
[],
)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
productsGenerationRef.current += 1
}
}, [])
useEffect(() => {
userIdRef.current = user?.id ?? null
productsGenerationRef.current += 1
inFlightPurchases.current.clear()
setOperation('idle')
setErrorCode(null)
@ -329,11 +340,13 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
productId: purchase.productId,
purchaseToken: purchase.purchaseToken,
})
if (!mountedRef.current || userIdRef.current !== currentUserId) return
if (!result.ok) throw new Error(billingFailureCode(result))
const data = result.data
const verifiedProduct = verifiedRestorableProduct(data, purchase.productId)
const verification = data && isRecord(data.verification) ? data.verification : null
const refreshed = await entitlement.refresh()
if (!mountedRef.current || userIdRef.current !== currentUserId) return
if (verifiedProduct !== null) {
if (
refreshed === null
@ -346,12 +359,16 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
throw new Error('purchase_not_verified_active')
}
} catch (candidate) {
if (userIdRef.current !== currentUserId) return
if (!mountedRef.current || userIdRef.current !== currentUserId) return
const resolvedErrorCode = await functionErrorCode(candidate)
if (!mountedRef.current || userIdRef.current !== currentUserId) return
setOperation('failed')
setErrorCode(await functionErrorCode(candidate))
setErrorCode(resolvedErrorCode)
} finally {
if (userIdRef.current === currentUserId) {
inFlightPurchases.current.delete(identity)
}
}
}, [entitlement])
const handlePurchaseError = useCallback((error: PurchaseError): void => {
@ -406,16 +423,20 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
setErrorCode('play_store_install_required')
return
}
const productsGeneration = ++productsGenerationRef.current
setOperation('loading-products')
setErrorCode(null)
try {
if (!connected) {
const didReconnect = await reconnect()
if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return
if (!didReconnect) throw new Error('store_connection_failed')
}
await fetchProducts({ skus: [...GOOGLE_PLAY_SUBSCRIPTION_IDS], type: 'subs' })
if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return
setOperation('idle')
} catch (candidate) {
if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return
setOperation('failed')
setErrorCode(candidate instanceof Error ? candidate.message : 'product_fetch_failed')
}
@ -454,6 +475,7 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
const replacementPurchases = currentProvider === 'google_play'
? await getAvailablePurchases({ includeSuspendedAndroid: true })
: []
if (!mountedRef.current || userIdRef.current !== currentUserId) return
const replacementPurchase = currentProvider === 'google_play'
? replacementPurchases.find((candidate) => (
candidate.productId === currentProductId
@ -491,6 +513,7 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
},
})
} catch (candidate) {
if (!mountedRef.current || userIdRef.current !== currentUserId) return
setOperation('failed')
setErrorCode(candidate instanceof Error ? candidate.message : 'purchase_failed')
}
@ -525,7 +548,9 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
await restoreGooglePlayPurchaseSet(
restoredPurchases,
async (restoredPurchase) => {
if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed')
if (!mountedRef.current || userIdRef.current !== currentUserId) {
throw new Error('restore_session_changed')
}
const result = await invokeEdgeFunction<IapVerifyResult>('iap-verify', {
platform: 'google_play',
productId: restoredPurchase.productId,
@ -536,14 +561,18 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
return data
},
async () => {
if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed')
if (!mountedRef.current || userIdRef.current !== currentUserId) {
throw new Error('restore_session_changed')
}
return entitlement.refresh()
},
)
if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed')
if (!mountedRef.current || userIdRef.current !== currentUserId) {
throw new Error('restore_session_changed')
}
setOperation('succeeded')
} catch (candidate) {
if (userIdRef.current !== currentUserId) return
if (!mountedRef.current || userIdRef.current !== currentUserId) return
setOperation('failed')
setErrorCode(candidate instanceof Error ? candidate.message : 'restore_failed')
}

View file

@ -39,7 +39,12 @@ export function DeviceProvider({ children }: { children: ReactNode }): React.Rea
const handleRevocation = useCallback(async (): Promise<void> => {
if (revocationHandledRef.current) return
revocationHandledRef.current = true
try {
await purgeLocalSession()
} catch (revocationError) {
revocationHandledRef.current = false
throw revocationError
}
}, [purgeLocalSession])
const refreshCurrentDevice = useCallback(async (): Promise<void> => {

View file

@ -280,7 +280,7 @@ function isCachedSnapshot(value: unknown, userId: string): value is CacheEnvelop
}
async function readCache(userId: string): Promise<EntitlementSnapshot | null> {
const serialized = await AsyncStorage.getItem(cacheKey(userId))
const serialized = await AsyncStorage.getItem(cacheKey(userId)).catch(() => null)
if (!serialized) return null
try {
const value: unknown = JSON.parse(serialized)
@ -393,7 +393,7 @@ export function EntitlementProvider({ children }: { children: ReactNode }): Reac
setSnapshot(cached)
setStale(true)
setLoading(false)
}).finally(() => {
}).catch(() => null).finally(() => {
if (!cancelled) void refresh()
})

View file

@ -86,7 +86,8 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
}
}, [])
const initializeAds = useCallback(async (): Promise<void> => {
const initializeAds = useCallback(async (expectedGeneration: number): Promise<void> => {
if (expectedGeneration !== generation.current) return
if (initialized.current) {
setStatus('ready')
return
@ -96,11 +97,17 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
maxAdContentRating: MaxAdContentRating.T,
testDeviceIdentifiers: runtimeConfig?.debug ? ['EMULATOR'] : undefined,
})
if (expectedGeneration !== generation.current) return
await MobileAds().initialize()
if (expectedGeneration !== generation.current) return
initialized.current = true
setStatus('ready')
}, [runtimeConfig?.debug])
useEffect(() => () => {
generation.current += 1
}, [])
useEffect(() => {
const currentGeneration = ++generation.current
if (!eligible) {
@ -127,7 +134,7 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
setStatus('consent-blocked')
return
}
await initializeAds()
await initializeAds(currentGeneration)
})
.catch((candidate) => {
if (currentGeneration !== generation.current) return
@ -137,25 +144,36 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
}, [eligible, initializeAds, runtimeConfig])
useEffect(() => {
let cancelled = false
void AdsConsent.getConsentInfo().then((info) => {
if (cancelled) return
setPrivacyOptionsRequired(
info.privacyOptionsRequirementStatus
=== AdsConsentPrivacyOptionsRequirementStatus.REQUIRED,
)
}).catch(() => undefined)
return () => {
cancelled = true
}
}, [])
const showPrivacyOptions = useCallback(async (): Promise<boolean> => {
const opGeneration = generation.current
const opEligible = eligible
try {
const consentInfo = await AdsConsent.showPrivacyOptionsForm()
if (opGeneration !== generation.current) return false
setPrivacyOptionsRequired(
consentInfo.privacyOptionsRequirementStatus
=== AdsConsentPrivacyOptionsRequirementStatus.REQUIRED,
)
if (eligible && consentInfo.canRequestAds) await initializeAds()
if (eligible && !consentInfo.canRequestAds) setStatus('consent-blocked')
if (opEligible && consentInfo.canRequestAds) await initializeAds(opGeneration)
if (opEligible && !consentInfo.canRequestAds && opGeneration === generation.current) {
setStatus('consent-blocked')
}
return true
} catch (candidate) {
if (opGeneration !== generation.current) return false
setErrorCode(candidateMessage(candidate, 'privacy_options_unavailable'))
return false
}
@ -318,6 +336,7 @@ export function useRewardedCredits(): RewardedCreditsValue {
).then(async (credited) => {
if (currentGeneration !== verificationGeneration.current) return
await entitlement.refresh()
if (currentGeneration !== verificationGeneration.current) return
setStatus(credited ? 'credited' : 'verification-pending')
}).catch((candidate) => {
if (currentGeneration !== verificationGeneration.current) return

View file

@ -139,6 +139,8 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
private progressHandler: RecordingProgressHandler | null = null;
private stateHandler: RecordingStateHandler | null = null;
private pollGeneration = 0;
private pollTimer: ReturnType<typeof setTimeout> | null = null;
private sessionGeneration = 0;
async requestPermission(): Promise<boolean> {
const permission = PermissionsAndroid.PERMISSIONS.RECORD_AUDIO;
@ -163,6 +165,7 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
throw new Error(`Cannot start recorder while it is ${this.state}`);
}
const sessionGen = ++this.sessionGeneration;
this.state = 'starting';
this.progressHandler = onProgress;
this.stateHandler = options.onStateChange ?? null;
@ -174,6 +177,10 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
: { meetingId: options.meetingId },
),
);
if (sessionGen !== this.sessionGeneration) {
await androidRecordingModule().cancel().catch(() => undefined);
throw new Error('Recording start was cancelled');
}
if (snapshot.state !== 'recording' || snapshot.recording === null) {
throw new Error('Android foreground recorder did not start');
}
@ -186,10 +193,9 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
this.stateHandler?.(snapshot);
this.startPolling();
} catch (error) {
this.progressHandler = null;
this.stateHandler = null;
this.currentPath = null;
this.state = 'idle';
if (sessionGen === this.sessionGeneration) {
this.resetToIdle();
}
throw error;
}
}
@ -199,14 +205,20 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
throw new Error(`Cannot pause recorder while it is ${this.state}`);
}
const sessionGen = this.sessionGeneration;
this.state = 'pausing';
try {
const snapshot = parseNativeSnapshot(await androidRecordingModule().pause());
if (sessionGen !== this.sessionGeneration) {
throw new Error('Recording was cancelled');
}
if (snapshot.state !== 'paused') throw new Error('Android recorder did not pause');
this.state = 'paused';
this.stateHandler?.(snapshot);
} catch (error) {
if (sessionGen === this.sessionGeneration) {
this.state = 'recording';
}
throw error;
}
}
@ -216,14 +228,20 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
throw new Error(`Cannot resume recorder while it is ${this.state}`);
}
const sessionGen = this.sessionGeneration;
this.state = 'resuming';
try {
const snapshot = parseNativeSnapshot(await androidRecordingModule().resume());
if (sessionGen !== this.sessionGeneration) {
throw new Error('Recording was cancelled');
}
if (snapshot.state !== 'recording') throw new Error('Android recorder did not resume');
this.state = 'recording';
this.stateHandler?.(snapshot);
} catch (error) {
if (sessionGen === this.sessionGeneration) {
this.state = 'paused';
}
throw error;
}
}
@ -234,13 +252,19 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
}
if (this.currentPath === null) throw new Error('Recorder has no output path');
const sessionGen = this.sessionGeneration;
const previousState = this.state;
this.state = 'stopping';
let snapshot: RecordingRuntimeSnapshot;
try {
snapshot = parseNativeSnapshot(await androidRecordingModule().stop());
if (sessionGen !== this.sessionGeneration) {
throw new Error('Recording was cancelled');
}
} catch (error) {
if (sessionGen === this.sessionGeneration) {
await this.resyncAfterFailedStop(previousState, null);
}
throw error;
}
@ -273,14 +297,19 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
if (recording !== undefined && this.currentPath !== null && path !== this.currentPath) {
return;
}
this.sessionGeneration += 1;
this.stopPolling();
this.resetToIdle();
}
async cancel(): Promise<void> {
const cancelGen = ++this.sessionGeneration;
this.stopPolling();
await androidRecordingModule().cancel();
this.resetToIdle();
await androidRecordingModule().cancel();
if (cancelGen === this.sessionGeneration) {
this.resetToIdle();
}
}
async restore(
@ -288,6 +317,7 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
onStateChange?: RecordingStateHandler,
): Promise<RecordingRuntimeSnapshot> {
const snapshot = parseNativeSnapshot(await androidRecordingModule().getStatus());
this.sessionGeneration += 1;
this.stopPolling();
this.progressHandler = onProgress ?? null;
this.stateHandler = onStateChange ?? null;
@ -386,7 +416,13 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
this.stateHandler?.(snapshot);
if (snapshot.state === 'recording' || snapshot.state === 'paused') {
this.state = snapshot.state;
setTimeout(() => { void poll(); }, 250);
if (generation === this.pollGeneration) {
if (this.pollTimer !== null) clearTimeout(this.pollTimer);
this.pollTimer = setTimeout(() => {
this.pollTimer = null;
void poll();
}, 250);
}
} else {
this.currentPath = snapshot.recording?.path ?? null;
this.state = snapshot.state === 'idle' ? 'idle' : 'stopped';
@ -394,7 +430,11 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
} catch {
// A transient React bridge failure must not stop the native foreground capture.
if (generation === this.pollGeneration) {
setTimeout(() => { void poll(); }, 500);
if (this.pollTimer !== null) clearTimeout(this.pollTimer);
this.pollTimer = setTimeout(() => {
this.pollTimer = null;
void poll();
}, 500);
}
}
};
@ -403,5 +443,9 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
private stopPolling(): void {
this.pollGeneration += 1;
if (this.pollTimer !== null) {
clearTimeout(this.pollTimer);
this.pollTimer = null;
}
}
}

View file

@ -104,6 +104,7 @@ export class NitroRecorderBackend implements RecorderBackend {
private state: NitroRecorderState = 'idle';
private currentPath: string | null = null;
private progress: RecordingProgress = { durationMs: 0, meteringDb: null };
private startGeneration = 0;
private pendingStart: Promise<void> | null = null;
private pendingTransition: Promise<void> | null = null;
private pendingStop: Promise<RecordedAudio> | null = null;
@ -144,14 +145,21 @@ export class NitroRecorderBackend implements RecorderBackend {
throw new Error(`Cannot start recorder while it is ${this.state}`);
}
const generation = ++this.startGeneration;
this.state = 'starting';
try {
await deleteStaleTemporaryFiles();
} catch (error) {
if (generation === this.startGeneration) {
this.state = 'idle';
}
throw error;
}
if (generation !== this.startGeneration) {
throw new Error('Recording start was cancelled');
}
const outputPath = createTemporaryPath();
this.currentPath = outputPath;
this.progress = { durationMs: 0, meteringDb: null };
@ -296,10 +304,15 @@ export class NitroRecorderBackend implements RecorderBackend {
}
async cancel(): Promise<void> {
this.startGeneration += 1;
if (this.state === 'starting' && this.pendingStart !== null) {
try {
await this.pendingStart;
} catch {
this.progressHandler = null;
this.currentPath = null;
this.state = 'idle';
this.progress = { durationMs: 0, meteringDb: null };
return;
}
}

View file

@ -98,6 +98,14 @@ export default function CommandsScreen(): React.ReactElement {
const styles = useMemo(() => createStyles(palette), [palette])
const alive = useRef(true)
const request = useRef<AbortController | null>(null)
const loadGeneration = useRef(0)
const actorUserIdRef = useRef<string | null>(user?.id ?? null)
const scopeGenerationRef = useRef(0)
const isCurrentActor = useCallback((actorUserId: string | null, actorScope: number): boolean => (
alive.current
&& actorUserIdRef.current === actorUserId
&& scopeGenerationRef.current === actorScope
), [])
const [commands, setCommands] = useState<SyncedCommand[]>([])
const [activeId, setActiveId] = useState<string | null>(null)
const [selectedId, setSelectedId] = useState<string | null>(null)
@ -123,16 +131,20 @@ export default function CommandsScreen(): React.ReactElement {
), [t])
const load = useCallback(async (pull = false, silent = false): Promise<void> => {
if (!user?.id) {
const generation = ++loadGeneration.current
const actorUserId = user?.id ?? null
const actorScope = scopeGenerationRef.current
if (!actorUserId) {
setLoading(false)
setRefreshing(false)
setSyncError('auth')
return
}
if (pull) setRefreshing(true)
else if (!silent) setLoading(true)
try {
const catalog = await loadSyncedCommandCatalog(user.id)
if (!alive.current) return
const catalog = await loadSyncedCommandCatalog(actorUserId)
if (!isCurrentActor(actorUserId, actorScope) || generation !== loadGeneration.current) return
setCommands(catalog.commands)
setActiveId(catalog.activeInstructionId)
setSelectedId((current) => (
@ -142,19 +154,51 @@ export default function CommandsScreen(): React.ReactElement {
))
setSyncError(null)
} catch (error) {
if (alive.current) setSyncError(error instanceof CommandSyncError ? error.code : 'server')
if (isCurrentActor(actorUserId, actorScope) && generation === loadGeneration.current) {
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
}
} finally {
if (alive.current) {
if (isCurrentActor(actorUserId, actorScope) && generation === loadGeneration.current) {
setLoading(false)
setRefreshing(false)
}
}
}, [isCurrentActor, user?.id])
useEffect(() => {
const nextUserId = user?.id ?? null
if (actorUserIdRef.current === nextUserId) return
actorUserIdRef.current = nextUserId
scopeGenerationRef.current += 1
loadGeneration.current += 1
request.current?.abort()
request.current = null
setCommands([])
setActiveId(null)
setSelectedId(null)
setSyncError(null)
setMutationId(null)
setEditor(null)
setEditorError(null)
setInput('')
setOutput(null)
setReportTarget(null)
setRunning(false)
setRunError(null)
setRetryable(false)
}, [user?.id])
useFocusEffect(useCallback(() => { void load() }, [load]))
useEffect(() => () => {
useFocusEffect(useCallback(() => {
void load()
return () => { loadGeneration.current += 1 }
}, [load]))
useEffect(() => {
alive.current = true
return () => {
alive.current = false
loadGeneration.current += 1
request.current?.abort()
}
}, [])
useEffect(() => {
if (!user?.id) return undefined
@ -178,14 +222,19 @@ export default function CommandsScreen(): React.ReactElement {
async function toggleActive(command: SyncedCommand): Promise<void> {
if (!user?.id || mutationId) return
const actorUserId = user.id
const actorScope = scopeGenerationRef.current
setMutationId(command.id)
try {
setActiveId(await setActiveSyncedCommand(user.id, activeId === command.id ? null : command.id))
const nextActiveId = await setActiveSyncedCommand(actorUserId, activeId === command.id ? null : command.id)
if (!isCurrentActor(actorUserId, actorScope)) return
setActiveId(nextActiveId)
setSyncError(null)
} catch (error) {
if (!isCurrentActor(actorUserId, actorScope)) return
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
} finally {
setMutationId(null)
if (isCurrentActor(actorUserId, actorScope)) setMutationId(null)
}
}
@ -207,42 +256,50 @@ export default function CommandsScreen(): React.ReactElement {
async function save(): Promise<void> {
if (!editor || !user?.id || mutationId) return
const actorUserId = user.id
const actorScope = scopeGenerationRef.current
setMutationId(editor.command?.id ?? 'create')
setEditorError(null)
try {
const saved = editor.command
? await updateSyncedCommand(user.id, editor.command, editor)
: await createSyncedCommand(user.id, {
? await updateSyncedCommand(actorUserId, editor.command, editor)
: await createSyncedCommand(actorUserId, {
...editor,
sortOrder: Math.max(1000, ...commands.map((item) => item.sortOrder + 10)),
})
if (!isCurrentActor(actorUserId, actorScope)) return
const next = [...commands.filter((item) => item.id !== saved.id), saved]
.sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt.localeCompare(b.createdAt))
setCommands(next)
setSelectedId(saved.id)
setEditor(null)
} catch (error) {
if (!isCurrentActor(actorUserId, actorScope)) return
const code = error instanceof CommandSyncError ? error.code : 'server'
setEditorError(code)
if (code === 'conflict') void load(false, true)
} finally {
setMutationId(null)
if (isCurrentActor(actorUserId, actorScope)) setMutationId(null)
}
}
async function remove(command: SyncedCommand): Promise<void> {
if (!user?.id || mutationId) return
const actorUserId = user.id
const actorScope = scopeGenerationRef.current
setMutationId(command.id)
try {
await deleteSyncedCommand(user.id, command)
await deleteSyncedCommand(actorUserId, command)
if (!isCurrentActor(actorUserId, actorScope)) return
const next = commands.filter((item) => item.id !== command.id)
setCommands(next)
if (selectedId === command.id) setSelectedId(next[0]?.id ?? null)
if (activeId === command.id) setActiveId(null)
} catch (error) {
if (!isCurrentActor(actorUserId, actorScope)) return
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
} finally {
setMutationId(null)
if (isCurrentActor(actorUserId, actorScope)) setMutationId(null)
}
}
@ -259,18 +316,25 @@ export default function CommandsScreen(): React.ReactElement {
async function move(command: SyncedCommand, direction: 'up' | 'down'): Promise<void> {
if (!user?.id || mutationId) return
const actorUserId = user.id
const actorScope = scopeGenerationRef.current
setMutationId(command.id)
try {
setCommands(await reorderSyncedCommand(user.id, command, direction))
const reordered = await reorderSyncedCommand(actorUserId, command, direction)
if (!isCurrentActor(actorUserId, actorScope)) return
setCommands(reordered)
} catch (error) {
if (!isCurrentActor(actorUserId, actorScope)) return
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
} finally {
setMutationId(null)
if (isCurrentActor(actorUserId, actorScope)) setMutationId(null)
}
}
const run = useCallback(async (): Promise<void> => {
if (!selected || running) return
const actorUserId = actorUserIdRef.current
const actorScope = scopeGenerationRef.current
const token = session?.access_token ?? ''
if (!token) {
setRunError('AUTH_REQUIRED')
@ -283,12 +347,15 @@ export default function CommandsScreen(): React.ReactElement {
setRunError(null)
setRetryable(false)
try {
setOutput(await executeSyncedCommand(selected, input, {
const result = await executeSyncedCommand(selected, input, {
accessToken: token,
model: preferences.preferredLlmModel,
signal: controller.signal,
}))
})
if (!isCurrentActor(actorUserId, actorScope)) return
setOutput(result)
} catch (error) {
if (!isCurrentActor(actorUserId, actorScope)) return
const failure = error instanceof CommandExecutionError
? error
: new CommandExecutionError('SERVER_ERROR', true)
@ -298,9 +365,9 @@ export default function CommandsScreen(): React.ReactElement {
}
} finally {
if (request.current === controller) request.current = null
if (alive.current) setRunning(false)
if (isCurrentActor(actorUserId, actorScope)) setRunning(false)
}
}, [input, preferences.preferredLlmModel, running, selected, session?.access_token])
}, [input, isCurrentActor, preferences.preferredLlmModel, running, selected, session?.access_token])
return (
<KeyboardAvoidingView

View file

@ -89,6 +89,7 @@ export default function HistoryDetailScreen({
playerRef.current = player
const mountedRef = useRef(true)
const loadGenerationRef = useRef(0)
const playbackGenerationRef = useRef(0)
const [detail, setDetail] = useState<HistoryDetail | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@ -109,6 +110,7 @@ export default function HistoryDetailScreen({
return () => {
mountedRef.current = false
loadGenerationRef.current += 1
playbackGenerationRef.current += 1
void Promise.resolve(playerRef.current.stopPlayer()).catch(() => undefined)
}
}, [])
@ -306,53 +308,62 @@ export default function HistoryDetailScreen({
const controlAudio = async (audioFile: AudioFile): Promise<void> => {
if (user === null || audioBusy) return
const playbackGeneration = ++playbackGenerationRef.current
setAudioBusy(true)
setError(null)
try {
if (activeAudioId === audioFile.id && player.state.isPlaying) {
await player.pausePlayer()
if (mountedRef.current) setPaused(true)
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(true)
return
}
if (activeAudioId === audioFile.id && paused) {
await player.resumePlayer()
if (mountedRef.current) setPaused(false)
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(false)
return
}
if (activeAudioId !== null) {
await player.stopPlayer()
if (!mountedRef.current) return
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
}
const signedUrl = await createAudioPlaybackUrl(user.id, audioFile)
if (!mountedRef.current) return
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
await player.startPlayer(signedUrl)
if (!mountedRef.current) {
void Promise.resolve(player.stopPlayer()).catch(() => undefined)
return
}
if (playbackGeneration !== playbackGenerationRef.current) return
setActiveAudioId(audioFile.id)
setPaused(false)
} catch {
if (!mountedRef.current) return
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
setActiveAudioId(null)
setPaused(false)
setError(t('mobile.hist.audioError'))
} finally {
if (mountedRef.current) setAudioBusy(false)
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) {
setAudioBusy(false)
}
}
}
const stopAudio = async (): Promise<void> => {
const playbackGeneration = ++playbackGenerationRef.current
setAudioBusy(true)
try {
await player.stopPlayer()
if (!mountedRef.current) return
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
setActiveAudioId(null)
setPaused(false)
} catch {
if (mountedRef.current) setError(t('mobile.hist.audioError'))
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) {
setError(t('mobile.hist.audioError'))
}
} finally {
if (mountedRef.current) setAudioBusy(false)
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) {
setAudioBusy(false)
}
}
}

View file

@ -1,7 +1,7 @@
// src/screens/HomeScreen.tsx — 홈(오늘). 데스크톱 HomePage 와 같은 문법:
// 제목·날짜 → 녹음 시작 안내 → 한 줄 요약 → 최근 기록 5 · 최근 회의 3 → (무료) 요금제 한 줄.
// 카드·통계 격자 없이 제목 + 1px 선. 조회한 값만 보여 주고, 못 불러오면 그렇다고 말한다.
import { useCallback, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Pressable,
RefreshControl,
@ -91,21 +91,46 @@ export default function HomeScreen(): React.ReactElement {
const [meetingsError, setMeetingsError] = useState(false)
const [loading, setLoading] = useState(true)
const [refreshing, setRefreshing] = useState(false)
const mountedRef = useRef(true)
const refreshGenerationRef = useRef(0)
const currentUserIdRef = useRef<string | null>(user?.id ?? null)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
refreshGenerationRef.current += 1
}
}, [])
useEffect(() => {
currentUserIdRef.current = user?.id ?? null
}, [user?.id])
const refresh = useCallback(async (pullToRefresh = false): Promise<void> => {
if (!user?.id) {
const generation = ++refreshGenerationRef.current
const targetUserId = user?.id ?? null
if (!targetUserId) {
setStats(null)
setMeetings(null)
setStatsError(true)
setMeetingsError(true)
setLoading(false)
setRefreshing(false)
return
}
if (pullToRefresh) setRefreshing(true)
else setLoading(true)
const [statsResult, meetingsResult] = await Promise.allSettled([
loadDashboardStats(user.id),
listMeetingsPage({ userId: user.id, page: 0, pageSize: RECENT_MEETING_LIMIT }),
loadDashboardStats(targetUserId),
listMeetingsPage({ userId: targetUserId, page: 0, pageSize: RECENT_MEETING_LIMIT }),
refreshEntitlement(),
])
if (
!mountedRef.current
|| generation !== refreshGenerationRef.current
|| currentUserIdRef.current !== targetUserId
) return
if (statsResult.status === 'fulfilled') {
setStats(statsResult.value)
setStatsError(false)

View file

@ -127,6 +127,7 @@ export default function KnowledgeScreen(): React.ReactElement {
const loadMore = async (): Promise<void> => {
if (user === null || loading || loadingMore || !hasMore) return
const generation = requestGeneration.current
const targetPage = page + 1
setLoadingMore(true)
try {
@ -135,14 +136,16 @@ export default function KnowledgeScreen(): React.ReactElement {
search: activeDocumentSearch,
page: targetPage,
})
if (generation !== requestGeneration.current) return
setDocuments((current) => mergeKnowledgeDocuments(current, result.documents))
setPage(targetPage)
setTotal(result.total)
setHasMore(result.hasMore)
} catch (requestError) {
if (generation !== requestGeneration.current) return
setError(errorCode(requestError))
} finally {
setLoadingMore(false)
if (generation === requestGeneration.current) setLoadingMore(false)
}
}

View file

@ -61,6 +61,7 @@ export default function MeetingsScreen({
const templateRequestGeneration = useRef(0)
const editorBusyRef = useRef(false)
const editorUserIdRef = useRef(user?.id ?? null)
const mountedRef = useRef(true)
const handledCreateRequests = useRef(new Set<number>())
const openCreateRef = useRef<() => void>(() => undefined)
const [meetings, setMeetings] = useState<Meeting[]>([])
@ -85,6 +86,13 @@ export default function MeetingsScreen({
const [editorError, setEditorError] = useState<string | null>(null)
const [editorBusy, setEditorBusy] = useState(false)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
useEffect(() => {
const nextUserId = user?.id ?? null
if (editorUserIdRef.current === nextUserId) return
@ -152,6 +160,7 @@ export default function MeetingsScreen({
const loadMore = async (): Promise<void> => {
if (user === null || loading || loadingMore || !hasMore) return
const generation = requestGeneration.current
const targetPage = page + 1
setLoadingMore(true)
try {
@ -160,16 +169,20 @@ export default function MeetingsScreen({
search: committedSearch,
page: targetPage,
})
if (generation !== requestGeneration.current || !mountedRef.current) return
setMeetings((current) => mergeMeetings(current, result.meetings))
setPage(targetPage)
setTotal(result.total)
setHasMore(result.hasMore)
} catch (requestError) {
if (generation !== requestGeneration.current || !mountedRef.current) return
setError(meetingErrorMessage(requestError, t))
} finally {
if (generation === requestGeneration.current && mountedRef.current) {
setLoadingMore(false)
}
}
}
const openDetail = (meeting: Meeting): void => {
const target = navigation.getParent() ?? navigation
@ -257,6 +270,7 @@ export default function MeetingsScreen({
const saveEditor = async (): Promise<void> => {
if (user === null || editor === null || editorBusyRef.current) return
const mode = editor
const actorUserId = user.id
editorBusyRef.current = true
setEditorBusy(true)
setEditorError(null)
@ -269,13 +283,14 @@ export default function MeetingsScreen({
.split(/[\r\n,]+/)
.map((attendee) => attendee.trim())
.filter((attendee) => attendee.length > 0)
const created = await createMeetingWorkspaceWithMetadata(user.id, {
const created = await createMeetingWorkspaceWithMetadata(actorUserId, {
title: editorTitle,
attendees,
language: editorLanguage,
templateId: editorTemplateId,
idempotencyKey: editorCreationKey,
})
if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return
setMeetings((current) => mergeMeetings([created], current))
setTotal((current) => current + 1)
setEditor(null)
@ -295,18 +310,22 @@ export default function MeetingsScreen({
}
} else {
const updated = await updateMeetingTitleRevisionSafe(mode.meeting, editorTitle)
if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return
setMeetings((current) => current.map((meeting) => (
meeting.id === updated.id ? updated : meeting
)))
setEditor(null)
}
} catch (requestError) {
if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return
setEditorError(meetingErrorMessage(requestError, t))
} finally {
if (mountedRef.current && editorUserIdRef.current === actorUserId) {
editorBusyRef.current = false
setEditorBusy(false)
}
}
}
const confirmDelete = (meeting: Meeting): void => {
Alert.alert(

View file

@ -703,6 +703,10 @@ export default function RecordScreen({ route, navigation }: RecordScreenProps):
await processInput(input);
} catch (importError) {
if (!mountedRef.current) return;
if (importError instanceof AudioPipelineError && importError.code === 'cancelled') {
setState('idle');
return;
}
setError(errorMessage(importError, t('mobile.rec.sharedImportFailed')));
setState('error');
} finally {

View file

@ -1,4 +1,4 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
ActivityIndicator,
KeyboardAvoidingView,
@ -37,6 +37,9 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
const { palette } = useMobilePreferences()
const styles = useMemo(() => createStyles(palette), [palette])
const loadGeneration = useRef(0)
const mountedRef = useRef(true)
const userIdRef = useRef<string | null>(user?.id ?? null)
const scopeGenerationRef = useRef(0)
const [teams, setTeams] = useState<TeamSummary[]>([])
const [loading, setLoading] = useState(true)
const [refreshing, setRefreshing] = useState(false)
@ -70,6 +73,26 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
}
}, [user])
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
useEffect(() => {
const nextUserId = user?.id ?? null
if (userIdRef.current === nextUserId) return
userIdRef.current = nextUserId
scopeGenerationRef.current += 1
setTeams([])
setError(null)
setEditorOpen(false)
setName('')
setEditorBusy(false)
setEditorError(null)
}, [user?.id])
useFocusEffect(useCallback(() => {
void load(false)
return () => { loadGeneration.current += 1 }
@ -77,18 +100,27 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
const submitCreate = async (): Promise<void> => {
if (user === null || editorBusy) return
const actorUserId = user.id
const actorScope = scopeGenerationRef.current
const isCurrentActor = (): boolean => (
mountedRef.current
&& userIdRef.current === actorUserId
&& scopeGenerationRef.current === actorScope
)
setEditorBusy(true)
setEditorError(null)
try {
const team = await createTeam(user.id, name)
const team = await createTeam(actorUserId, name)
if (!isCurrentActor()) return
setTeams((current) => [team, ...current.filter((row) => row.id !== team.id)])
setName('')
setEditorOpen(false)
navigation.navigate('TeamDetail', { teamId: team.id })
} catch (requestError) {
if (!isCurrentActor()) return
setEditorError(teamErrorCode(requestError))
} finally {
setEditorBusy(false)
if (isCurrentActor()) setEditorBusy(false)
}
}

View file

@ -5,17 +5,42 @@ const DEFAULT_TITLE = 'D3RO Voice'
const DEFAULT_BODY = '새 알림이 도착했습니다.'
const DEFAULT_TARGET_URL = '/app/dashboard'
function hasUnsafeUrlChars(value) {
for (let i = 0; i < value.length; i += 1) {
const code = value.charCodeAt(i)
if (code <= 0x1f || code === 0x7f || code === 0x5c) {
return true
}
}
return false
}
function sanitizeTargetUrl(rawUrl) {
if (typeof rawUrl !== 'string' || !rawUrl.trim()) {
if (typeof rawUrl !== 'string' || hasUnsafeUrlChars(rawUrl)) {
return DEFAULT_TARGET_URL
}
const trimmed = rawUrl.trim()
if (!trimmed.startsWith('/') || trimmed.startsWith('//') || trimmed.startsWith('/\\')) {
if (!trimmed || !trimmed.startsWith('/') || trimmed.startsWith('//')) {
return DEFAULT_TARGET_URL
}
return trimmed.startsWith('/app/') || trimmed === '/app'
const candidate = trimmed.startsWith('/app/') || trimmed === '/app'
? trimmed
: `/app${trimmed}`
if (candidate === '/app') {
return DEFAULT_TARGET_URL
}
if (candidate.startsWith('/app//')) {
return DEFAULT_TARGET_URL
}
try {
const parsed = new URL(candidate, 'https://d3ro.local')
if (parsed.origin !== 'https://d3ro.local' || !parsed.pathname.startsWith('/app/') || parsed.pathname.includes('//')) {
return DEFAULT_TARGET_URL
}
} catch {
return DEFAULT_TARGET_URL
}
return candidate
}
function parsePushPayload(event) {

View file

@ -2,7 +2,7 @@
import Link from 'next/link'
import { useParams, useRouter } from 'next/navigation'
import React, { useCallback, useEffect, useState } from 'react'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import {
Alert,
Box,
@ -19,6 +19,7 @@ import type { D3roSupabaseClient, HistoryEntry } from '@d3ro/api-client'
import { formatDurationClockFromSeconds } from '@d3ro/core/format'
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roFontMono, d3roPalette } from '@d3ro/ui/theme'
import { clearTrackedTimeout, scheduleTrackedTimeout } from '@/lib/edge-fetch'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
import {
deleteHistoryEntryRevisionSafe,
@ -63,6 +64,18 @@ export default function HistoryDetailPage(): React.ReactElement {
const [title, setTitle] = useState('')
const [originalText, setOriginalText] = useState('')
const [polishedText, setPolishedText] = useState('')
const mountedRef = useRef(true)
const loadGenerationRef = useRef(0)
const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
loadGenerationRef.current += 1
clearTrackedTimeout(copyTimerRef)
}
}, [])
const applyEntry = (next: HistoryEntry): void => {
setEntry(next)
@ -72,18 +85,24 @@ export default function HistoryDetailPage(): React.ReactElement {
}
const loadEntry = useCallback(async (): Promise<void> => {
const generation = ++loadGenerationRef.current
setLoading(true)
setError(null)
try {
const client = asApiClient()
const userId = await requireCurrentUser(client)
applyEntry(await getHistoryEntry(client, userId, entryId))
const loaded = await getHistoryEntry(client, userId, entryId)
if (!mountedRef.current || generation !== loadGenerationRef.current) return
applyEntry(loaded)
} catch (requestError) {
if (!mountedRef.current || generation !== loadGenerationRef.current) return
setEntry(null)
setError(historyMessage(requestError))
} finally {
if (mountedRef.current && generation === loadGenerationRef.current) {
setLoading(false)
}
}
}, [entryId])
useEffect(() => {
@ -178,12 +197,17 @@ export default function HistoryDetailPage(): React.ReactElement {
if (!entry) return
try {
await navigator.clipboard.writeText(entry.polished_text ?? entry.original_text)
if (!mountedRef.current) return
setCopied(true)
window.setTimeout(() => setCopied(false), 2000)
scheduleTrackedTimeout(copyTimerRef, () => {
if (mountedRef.current) setCopied(false)
}, 2000)
} catch {
if (mountedRef.current) {
setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.')
}
}
}
return (
<Box sx={{ maxWidth: 920, mx: 'auto', p: { xs: 2.5, md: 4 }, pb: 10 }}>

View file

@ -28,6 +28,7 @@ import {
import type { D3roSupabaseClient, HistoryEntry } from '@d3ro/api-client'
import { MetalCard, PhosphorText, TactileBadge } from '@d3ro/ui/components/ds'
import { d3roFontMono, d3roPalette } from '@d3ro/ui/theme'
import { clearTrackedTimeout, scheduleTrackedTimeout } from '@/lib/edge-fetch'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
import {
deleteHistoryEntryRevisionSafe,
@ -81,6 +82,16 @@ export default function HistoryPage(): React.ReactElement {
const [copiedId, setCopiedId] = useState<string | null>(null)
const [mutatingIds, setMutatingIds] = useState<Set<string>>(() => new Set())
const requestGeneration = useRef(0)
const mountedRef = useRef(true)
const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
clearTrackedTimeout(copyTimerRef)
}
}, [])
useEffect(() => {
const timer = window.setTimeout(() => setSearch(searchInput), SEARCH_DELAY_MS)
@ -232,12 +243,19 @@ export default function HistoryPage(): React.ReactElement {
const copyText = async (entry: HistoryEntry): Promise<void> => {
try {
await navigator.clipboard.writeText(entry.polished_text ?? entry.original_text)
if (!mountedRef.current) return
setCopiedId(entry.id)
window.setTimeout(() => setCopiedId((current) => current === entry.id ? null : current), 2000)
scheduleTrackedTimeout(copyTimerRef, () => {
if (mountedRef.current) {
setCopiedId((current) => (current === entry.id ? null : current))
}
}, 2000)
} catch {
if (mountedRef.current) {
setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.')
}
}
}
const emptyMessage = search.length > 0 || filter === 'favorites'
? '조건에 맞는 전사 기록이 없습니다.'

View file

@ -33,7 +33,7 @@ export async function GET(request: NextRequest): Promise<NextResponse> {
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (error) {
return NextResponse.redirect(appUrlFor(origin, `/login?error=${encodeURIComponent(error.message)}`))
return NextResponse.redirect(appUrlFor(origin, '/login?error=oauth_callback_failed'))
}
return NextResponse.redirect(appUrlFor(origin, next))

View file

@ -4,11 +4,16 @@
// 텍스트 명령 → LLM 파싱 (function-like JSON) → 동작 시뮬레이션.
// V1 VoiceActionService의 간이 web 포트.
import { useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { Box, Button, TextField, Stack, Alert, CircularProgress, Chip } from '@mui/material'
import PlayArrowIcon from '@mui/icons-material/PlayArrow'
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
import {
createTimedAbortSignal,
resolveSupabaseFunctionUrl,
shouldExitAfterAwait,
} from '@/lib/edge-fetch'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
type ActionType =
@ -52,6 +57,17 @@ export function ActionRunner(): React.ReactElement {
const [error, setError] = useState<string | null>(null)
const [result, setResult] = useState<ActionResult | null>(null)
const [executed, setExecuted] = useState<string | null>(null)
const mountedRef = useRef(true)
const abortRef = useRef<AbortController | null>(null)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
abortRef.current?.abort()
abortRef.current = null
}
}, [])
async function handleParse(): Promise<void> {
if (!input.trim()) return
@ -59,24 +75,27 @@ export function ActionRunner(): React.ReactElement {
setResult(null)
setExecuted(null)
setBusy(true)
const timedAbort = createTimedAbortSignal(30_000, abortRef)
try {
const supabase = getSupabaseBrowserClient()
const {
data: { session }
} = await supabase.auth.getSession()
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
if (!session) {
throw new Error('로그인이 필요합니다')
}
const resp = await fetch(
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/llm-proxy`,
resolveSupabaseFunctionUrl('llm-proxy'),
{
method: 'POST',
headers: {
Authorization: `Bearer ${session.access_token}`,
'Content-Type': 'application/json'
},
signal: timedAbort.controller.signal,
body: JSON.stringify({
messages: [{ role: 'user', content: input.trim() }],
system: SYSTEM_PROMPT,
@ -99,13 +118,24 @@ export function ActionRunner(): React.ReactElement {
}
const parsed = JSON.parse(jsonMatch[0]) as ActionResult
if (mountedRef.current) {
setResult(parsed)
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Unknown error')
if (mountedRef.current) {
setError(timedAbort.didTimeout()
? '명령 파싱 시간이 초과되었습니다.'
: e instanceof Error
? e.message
: 'Unknown error')
}
} finally {
timedAbort.dispose()
if (mountedRef.current) {
setBusy(false)
}
}
}
async function handleExecute(): Promise<void> {
if (!result) return
@ -116,6 +146,7 @@ export function ActionRunner(): React.ReactElement {
const {
data: { user }
} = await supabase.auth.getUser()
if (!mountedRef.current) return
if (!user) {
throw new Error('로그인이 필요합니다')
}
@ -126,6 +157,7 @@ export function ActionRunner(): React.ReactElement {
const { error: err } = await supabase
.from('meetings')
.insert({ user_id: user.id, title, team_id: null, status: 'completed' })
if (!mountedRef.current) return
if (err) throw new Error(err.message)
setExecuted(`회의 "${title}" 생성됨`)
break
@ -147,6 +179,7 @@ export function ActionRunner(): React.ReactElement {
content,
timestamp_ms: 0
})
if (!mountedRef.current) return
if (err) throw new Error(err.message)
setExecuted(`메모 생성됨: "${content}"`)
break
@ -158,11 +191,15 @@ export function ActionRunner(): React.ReactElement {
setExecuted('알 수 없는 액션 — 실행 불가')
}
} catch (e) {
if (mountedRef.current) {
setError(e instanceof Error ? e.message : 'Unknown error')
}
} finally {
if (mountedRef.current) {
setBusy(false)
}
}
}
return (
<Stack spacing={3}>

View file

@ -1,8 +1,14 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Alert, Box, Button, CircularProgress } from '@mui/material'
import Script from 'next/script'
import {
clearTrackedTimeout,
createTimedAbortSignal,
resolveSupabaseFunctionUrl,
scheduleTrackedTimeout,
} from '@/lib/edge-fetch'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
import { browserBillingUrl } from '@/lib/web-app-url'
import {
@ -39,14 +45,11 @@ function checkoutErrorMessage(error: unknown): string {
}
function checkoutEndpoint(): string {
const baseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim()
if (!baseUrl) {
throw new PaypleClientError('not_configured', '결제 서버 설정이 완료되지 않았습니다.')
}
try {
return new URL('/functions/v1/payple-checkout', baseUrl).toString()
} catch {
throw new PaypleClientError('not_configured', '결제 서버 설정이 올바르지 않습니다.')
return resolveSupabaseFunctionUrl('payple-checkout')
} catch (err) {
const message = err instanceof Error ? err.message : '결제 서버 설정이 올바르지 않습니다.'
throw new PaypleClientError('not_configured', message)
}
}
@ -55,11 +58,21 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState(false)
const [sdkReady, setSdkReady] = useState(false)
const mountedRef = useRef(true)
const reloadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const abortRef = useRef<AbortController | null>(null)
useEffect(() => {
mountedRef.current = true
if (PAYPLE_CONFIGURED && typeof window.PaypleCpayAuthCheck === 'function') {
setSdkReady(true)
}
return () => {
mountedRef.current = false
clearTrackedTimeout(reloadTimerRef)
abortRef.current?.abort()
abortRef.current = null
}
}, [])
const handleCheckout = useCallback(async (): Promise<void> => {
@ -98,12 +111,16 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto
resultUrl: browserBillingUrl(),
openSdk: (request) => window.PaypleCpayAuthCheck(request),
chargeBillingKey: async (payerId, result) => {
const response = await fetch(checkoutEndpoint(), {
const timedAbort = createTimedAbortSignal(30_000, abortRef)
let response: Response
try {
response = await fetch(checkoutEndpoint(), {
method: 'POST',
headers: {
Authorization: `Bearer ${session.access_token}`,
'Content-Type': 'application/json'
},
signal: timedAbort.controller.signal,
body: JSON.stringify({
payer_id: payerId,
tier,
@ -116,6 +133,9 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto
: undefined
})
})
} finally {
timedAbort.dispose()
}
let payload: unknown
try {
@ -136,13 +156,18 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto
}
})
if (!mountedRef.current) return
setSuccess(true)
window.setTimeout(() => window.location.reload(), 2000)
scheduleTrackedTimeout(reloadTimerRef, () => window.location.reload(), 2000)
} catch (checkoutError) {
if (mountedRef.current) {
setError(checkoutErrorMessage(checkoutError))
}
} finally {
if (mountedRef.current) {
setBusy(false)
}
}
}, [catalogPrice, sdkReady, tier])
return (

View file

@ -3,9 +3,16 @@
// apps/web/src/components/billing/payple-manage-button.tsx
// Payple 구독 관리 — payple-manage Edge Function 호출 (구독 취소)
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { Button, CircularProgress, Alert, Box, Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions } from '@mui/material'
import SettingsIcon from '@mui/icons-material/Settings'
import {
clearTrackedTimeout,
createTimedAbortSignal,
resolveSupabaseFunctionUrl,
scheduleTrackedTimeout,
shouldExitAfterAwait,
} from '@/lib/edge-fetch'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
export function PaypleManageButton(): React.ReactElement {
@ -14,27 +21,38 @@ export function PaypleManageButton(): React.ReactElement {
const [confirmOpen, setConfirmOpen] = useState(false)
const [success, setSuccess] = useState(false)
const [ready, setReady] = useState(false)
const mountedRef = useRef(true)
const reloadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const abortRef = useRef<AbortController | null>(null)
useEffect(() => setReady(true), [])
useEffect(() => {
mountedRef.current = true
setReady(true)
return () => {
mountedRef.current = false
clearTrackedTimeout(reloadTimerRef)
abortRef.current?.abort()
abortRef.current = null
}
}, [])
async function handleCancel(): Promise<void> {
setConfirmOpen(false)
setError(null)
setBusy(true)
const timedAbort = createTimedAbortSignal(30_000, abortRef)
try {
const supabase = getSupabaseBrowserClient()
const { data: { session }, error: sessionError } = await supabase.auth.getSession()
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
if (sessionError || !session) {
setError('로그인이 필요합니다')
return
}
const baseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.trim()
if (!baseUrl) throw new Error('결제 서버 설정이 완료되지 않았습니다')
const response = await fetch(
new URL('/functions/v1/payple-manage', baseUrl).toString(),
resolveSupabaseFunctionUrl('payple-manage'),
{
method: 'POST',
headers: {
@ -42,6 +60,7 @@ export function PaypleManageButton(): React.ReactElement {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'cancel' }),
signal: timedAbort.controller.signal,
}
)
@ -58,14 +77,24 @@ export function PaypleManageButton(): React.ReactElement {
) {
throw new Error('구독 취소 결과를 확인할 수 없습니다.')
}
if (!mountedRef.current) return
setSuccess(true)
window.setTimeout(() => window.location.reload(), 2000)
scheduleTrackedTimeout(reloadTimerRef, () => window.location.reload(), 2000)
} catch (e) {
setError(e instanceof Error ? e.message : '알 수 없는 오류')
if (mountedRef.current) {
setError(timedAbort.didTimeout()
? '요청 시간이 초과되었습니다. 잠시 후 다시 시도해 주세요.'
: e instanceof Error
? e.message
: '알 수 없는 오류')
}
} finally {
timedAbort.dispose()
if (mountedRef.current) {
setBusy(false)
}
}
}
if (success) {
return (

View file

@ -8,67 +8,74 @@ import { useRef, useState, useEffect } from 'react'
import { Alert, Box, Typography, IconButton } from '@mui/material'
import { Send, Trash2 } from 'lucide-react'
import { d3roFontMono } from '@d3ro/ui/theme'
import {
createTimedAbortSignal,
resolveSupabaseFunctionUrl,
shouldExitAfterAwait,
} from '@/lib/edge-fetch'
import { getSupabaseBrowserClient, isSupabaseConfigured } from '@/lib/supabase-browser'
interface Message {
export interface ChatMessage {
id: string
role: 'user' | 'assistant'
content: string
timestamp: string
}
export function ChatPanel(): React.ReactElement {
const [messages, setMessages] = useState<Message[]>([
{
id: 'welcome',
role: 'assistant',
content: '안녕하세요! D3RO-VOICE 음성 대화 엔진입니다. 무엇을 도와드릴까요?',
timestamp: '9:30 AM'
}
])
const [input, setInput] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const scrollRef = useRef<HTMLDivElement>(null)
export async function executeChatSendTurn(options: {
text: string
messages: ChatMessage[]
activeControllerRef: { current: AbortController | null }
isMounted: () => boolean
isConfigured: () => boolean
getAccessToken: () => Promise<string | null>
endpointUrl?: string
fetchImpl?: typeof fetch
timeoutMs?: number
onMessagesUpdate: (updater: (prev: ChatMessage[]) => ChatMessage[]) => void
onInputChange: (value: string) => void
onErrorChange: (error: string | null) => void
onBusyChange: (busy: boolean) => void
}): Promise<void> {
const {
text,
messages,
activeControllerRef,
isMounted,
isConfigured,
getAccessToken,
endpointUrl,
fetchImpl = fetch,
timeoutMs = 45_000,
onMessagesUpdate,
onInputChange,
onErrorChange,
onBusyChange,
} = options
function scrollToBottom(): void {
requestAnimationFrame(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight
}
})
}
useEffect(() => {
scrollToBottom()
}, [messages])
async function handleSend(): Promise<void> {
const text = input.trim()
if (!text || busy) return
const userMsg: Message = {
const userMsg: ChatMessage = {
id: 'u_' + Date.now(),
role: 'user',
content: text,
timestamp: new Date().toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' })
}
const nextMessages = [...messages, userMsg]
setMessages(nextMessages)
setInput('')
setError(null)
setBusy(true)
let requestTimeout: number | null = null
const assistantId = 'a_' + Date.now()
onMessagesUpdate(() => nextMessages)
onInputChange('')
onErrorChange(null)
onBusyChange(true)
const timedAbort = createTimedAbortSignal(timeoutMs, activeControllerRef)
try {
if (!isSupabaseConfigured()) {
if (!isConfigured()) {
throw new Error('Supabase 미설정')
}
const supabase = getSupabaseBrowserClient()
const { data: { session } } = await supabase.auth.getSession()
const accessToken = await getAccessToken()
if (shouldExitAfterAwait(timedAbort, isMounted)) return
if (!session) {
if (!accessToken) {
throw new Error('로그인 필요')
}
@ -78,18 +85,16 @@ export function ChatPanel(): React.ReactElement {
stream: true
}
const controller = new AbortController()
requestTimeout = window.setTimeout(() => controller.abort(), 45_000)
const response = await fetch(
process.env.NEXT_PUBLIC_SUPABASE_URL + '/functions/v1/llm-proxy',
const response = await fetchImpl(
endpointUrl ?? resolveSupabaseFunctionUrl('llm-proxy'),
{
method: 'POST',
headers: {
Authorization: 'Bearer ' + session.access_token,
Authorization: 'Bearer ' + accessToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
signal: controller.signal
signal: timedAbort.controller.signal
}
)
@ -101,8 +106,8 @@ export function ChatPanel(): React.ReactElement {
if (!response.body) throw new Error('empty_response')
const assistantId = 'a_' + Date.now()
setMessages((prev) => [
if (!isMounted()) return
onMessagesUpdate((prev) => [
...prev,
{
id: assistantId,
@ -112,18 +117,66 @@ export function ChatPanel(): React.ReactElement {
}
])
const reader = response.body.getReader()
const accumulated = await consumeChatSseStream({
body: response.body,
signal: timedAbort.controller.signal,
onAccumulated: (partial) => {
if (!isMounted()) return
onMessagesUpdate((prev) =>
prev.map((m) => (m.id === assistantId ? { ...m, content: partial } : m))
)
},
})
if (shouldExitAfterAwait(timedAbort, isMounted)) return
if (!accumulated.trim()) throw new Error('empty_response')
} catch (candidate) {
if (!isMounted()) return
onMessagesUpdate((prev) => prev.filter((m) => m.id !== userMsg.id && m.id !== assistantId))
onInputChange(text)
const timedOut = timedAbort.didTimeout() || (candidate instanceof DOMException && candidate.name === 'AbortError')
const code = candidate instanceof Error ? candidate.message : 'request_failed'
onErrorChange(code === 'quota_exceeded'
? '오늘 사용할 수 있는 AI 대화 한도를 모두 사용했습니다.'
: code === 'provider_unavailable'
? 'AI 공급자가 설정되지 않았거나 현재 사용할 수 없습니다.'
: timedOut
? 'AI 응답 시간이 초과되었습니다.'
: 'AI 요청을 완료하지 못했습니다. 입력을 유지했으니 다시 시도할 수 있습니다.')
} finally {
timedAbort.dispose()
if (isMounted()) {
onBusyChange(false)
}
}
}
/**
* SSE 응답 스트림에서 text_delta 토큰을 누적하고, 취소·종료 시 reader를 해제한다.
*/
export async function consumeChatSseStream(options: {
body: ReadableStream<Uint8Array>
signal: AbortSignal
onAccumulated: (accumulated: string) => void
}): Promise<string> {
const { body, signal, onAccumulated } = options
const reader = body.getReader()
const decoder = new TextDecoder()
let buffer = ''
let accumulated = ''
let streamDone = false
while (!streamDone) {
const { done, value } = await reader.read()
if (done) {
streamDone = true
break
const onAbort = (): void => {
void reader.cancel().catch(() => {})
}
if (signal.aborted) {
await reader.cancel().catch(() => {})
return accumulated
}
signal.addEventListener('abort', onAbort, { once: true })
try {
while (!signal.aborted) {
const { done, value } = await reader.read()
if (done || signal.aborted) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
@ -136,35 +189,90 @@ export function ChatPanel(): React.ReactElement {
if (data === '[DONE]' || data === '') continue
try {
const event = JSON.parse(data)
const event = JSON.parse(data) as {
type?: unknown
delta?: { type?: unknown; text?: unknown }
}
if (event.type === 'content_block_delta' && event.delta?.type === 'text_delta') {
accumulated += event.delta.text ?? ''
setMessages((prev) =>
prev.map((m) => (m.id === assistantId ? { ...m, content: accumulated } : m))
)
accumulated += typeof event.delta.text === 'string' ? event.delta.text : ''
if (!signal.aborted) {
onAccumulated(accumulated)
}
}
} catch {
// Ignore parse errors
// Ignore malformed SSE lines
}
}
}
if (!accumulated.trim()) throw new Error('empty_response')
} catch (candidate) {
setMessages(messages)
setInput(text)
const timedOut = candidate instanceof DOMException && candidate.name === 'AbortError'
const code = candidate instanceof Error ? candidate.message : 'request_failed'
setError(code === 'quota_exceeded'
? '오늘 사용할 수 있는 AI 대화 한도를 모두 사용했습니다.'
: code === 'provider_unavailable'
? 'AI 공급자가 설정되지 않았거나 현재 사용할 수 없습니다.'
: timedOut
? 'AI 응답 시간이 초과되었습니다.'
: 'AI 요청을 완료하지 못했습니다. 입력을 유지했으니 다시 시도할 수 있습니다.')
} finally {
if (requestTimeout !== null) window.clearTimeout(requestTimeout)
setBusy(false)
signal.removeEventListener('abort', onAbort)
await reader.cancel().catch(() => {})
}
return accumulated
}
export function ChatPanel(): React.ReactElement {
const [messages, setMessages] = useState<ChatMessage[]>([
{
id: 'welcome',
role: 'assistant',
content: '안녕하세요! D3RO-VOICE 음성 대화 엔진입니다. 무엇을 도와드릴까요?',
timestamp: '9:30 AM'
}
])
const [input, setInput] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const scrollRef = useRef<HTMLDivElement>(null)
const mountedRef = useRef(true)
const rafRef = useRef<number | null>(null)
const activeControllerRef = useRef<AbortController | null>(null)
function scrollToBottom(): void {
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
rafRef.current = requestAnimationFrame(() => {
rafRef.current = null
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight
}
})
}
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
activeControllerRef.current?.abort()
activeControllerRef.current = null
}
}, [])
useEffect(() => {
scrollToBottom()
}, [messages])
async function handleSend(): Promise<void> {
const text = input.trim()
if (!text || busy) return
await executeChatSendTurn({
text,
messages,
activeControllerRef,
isMounted: () => mountedRef.current,
isConfigured: isSupabaseConfigured,
getAccessToken: async () => {
const supabase = getSupabaseBrowserClient()
const { data: { session } } = await supabase.auth.getSession()
return session?.access_token ?? null
},
onMessagesUpdate: setMessages,
onInputChange: setInput,
onErrorChange: setError,
onBusyChange: setBusy,
})
}
return (

View file

@ -4,7 +4,7 @@
// 회의록 문서 편집 — MarkdownEditor 다이얼로그
// 클릭 → 다이얼로그 열림 → textarea 편집 → 저장 시 meeting_documents UPDATE
import { useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import dynamic from 'next/dynamic'
import { useRouter } from 'next/navigation'
import {
@ -52,6 +52,14 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const [tab, setTab] = useState<'edit' | 'preview'>('edit')
const mountedRef = useRef(true)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
async function handleSave(): Promise<void> {
setError(null)
@ -63,6 +71,7 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
.update({ title, content })
.eq('id', doc.id)
if (!mountedRef.current) return
if (updateErr) {
setError(updateErr.message)
return
@ -70,10 +79,16 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
setOpen(false)
router.refresh()
} catch (err) {
if (mountedRef.current) {
setError(err instanceof Error ? err.message : '문서 저장에 실패했습니다.')
}
} finally {
if (mountedRef.current) {
setBusy(false)
}
}
}
async function handleDelete(): Promise<void> {
if (!window.confirm('이 문서를 삭제하시겠습니까?')) return
@ -86,6 +101,7 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
.delete()
.eq('id', doc.id)
if (!mountedRef.current) return
if (deleteErr) {
setError(deleteErr.message)
return
@ -93,10 +109,16 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement
setOpen(false)
router.refresh()
} catch (err) {
if (mountedRef.current) {
setError(err instanceof Error ? err.message : '문서 삭제에 실패했습니다.')
}
} finally {
if (mountedRef.current) {
setBusy(false)
}
}
}
return (
<>

View file

@ -3,7 +3,7 @@
// apps/web/src/components/meetings/generate-document-button.tsx
// 회의록에서 AI 문서 생성 — llm-proxy 호출 → meeting_documents INSERT
import { useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import {
Button,
@ -14,6 +14,11 @@ import {
Box
} from '@mui/material'
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome'
import {
createTimedAbortSignal,
resolveSupabaseFunctionUrl,
shouldExitAfterAwait,
} from '@/lib/edge-fetch'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
type TemplateType = 'minutes' | 'report' | 'idea-note' | 'mindmap'
@ -75,17 +80,30 @@ export function GenerateDocumentButton({
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const mountedRef = useRef(true)
const abortRef = useRef<AbortController | null>(null)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
abortRef.current?.abort()
abortRef.current = null
}
}, [])
async function handleGenerate(tpl: TemplateDef): Promise<void> {
setAnchorEl(null)
setError(null)
setBusy(true)
const timedAbort = createTimedAbortSignal(45_000, abortRef)
try {
const supabase = getSupabaseBrowserClient()
const {
data: { session }
} = await supabase.auth.getSession()
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
if (!session) {
setError('로그인이 필요합니다')
return
@ -99,13 +117,14 @@ export function GenerateDocumentButton({
// llm-proxy 호출
const startedAt = Date.now()
const llmResp = await fetch(
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/llm-proxy`,
resolveSupabaseFunctionUrl('llm-proxy'),
{
method: 'POST',
headers: {
Authorization: `Bearer ${session.access_token}`,
'Content-Type': 'application/json'
},
signal: timedAbort.controller.signal,
body: JSON.stringify({
messages: [{ role: 'user', content: transcript }],
system: tpl.systemPrompt,
@ -127,6 +146,7 @@ export function GenerateDocumentButton({
const {
data: { user }
} = await supabase.auth.getUser()
if (!mountedRef.current) return
if (!user) {
setError('로그인이 필요합니다')
return
@ -142,6 +162,7 @@ export function GenerateDocumentButton({
llm_model: llmData.model,
llm_latency_ms: latency
})
if (!mountedRef.current) return
if (insertErr) {
setError(`문서 저장 실패: ${insertErr.message}`)
@ -150,11 +171,20 @@ export function GenerateDocumentButton({
router.refresh()
} catch (e) {
setError(e instanceof Error ? e.message : 'Unknown error')
if (mountedRef.current) {
setError(timedAbort.didTimeout()
? 'AI 문서 생성 시간이 초과되었습니다.'
: e instanceof Error
? e.message
: 'Unknown error')
}
} finally {
timedAbort.dispose()
if (mountedRef.current) {
setBusy(false)
}
}
}
return (
<Box>

View file

@ -19,31 +19,56 @@ const AuthContext = createContext<AuthContextValue>({
loading: true
})
export interface AuthSessionBindingClient {
auth: {
getSession: () => Promise<{ data: { session: Session | null } }>
onAuthStateChange: (
callback: (_event: unknown, nextSession: Session | null) => void,
) => { data: { subscription: { unsubscribe: () => void } } }
}
}
/**
* 마운트 해제 이후 상태 갱신과 거부된 getSession 프로미스의 미처리 예외를 차단한다.
*/
export function bindAuthSession(
supabase: AuthSessionBindingClient,
onSession: (session: Session | null) => void,
onLoadingChange: (loading: boolean) => void,
): () => void {
let cancelled = false
supabase.auth
.getSession()
.then(({ data }) => {
if (!cancelled) onSession(data.session)
})
.catch(() => {
if (!cancelled) onSession(null)
})
.finally(() => {
if (!cancelled) onLoadingChange(false)
})
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, newSession) => {
if (!cancelled) onSession(newSession)
})
return () => {
cancelled = true
subscription.unsubscribe()
}
}
export function AuthProvider({ children }: { children: React.ReactNode }): React.ReactElement {
const [session, setSession] = useState<Session | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const supabase = getSupabaseBrowserClient()
supabase.auth
.getSession()
.then(({ data }) => {
setSession(data.session)
})
.finally(() => {
setLoading(false)
})
const {
data: { subscription }
} = supabase.auth.onAuthStateChange((_event, newSession) => {
setSession(newSession)
})
return () => {
subscription.unsubscribe()
}
return bindAuthSession(supabase, setSession, setLoading)
}, [])
return (

View file

@ -13,6 +13,25 @@ import { transcribeWebAudio, WebSttError } from '@/lib/web-stt-client'
type RecorderState = 'idle' | 'recording' | 'processing' | 'done' | 'error'
export interface StoppableStream {
getTracks: () => ReadonlyArray<{ stop: () => void }>
}
/**
* 권한 프롬프트 대기 중 언마운트·재시작되면 획득된 마이크 트랙을 즉시 정지한다.
*/
export async function acquireGuardedMediaStream<TStream extends StoppableStream>(options: {
getUserMedia: () => Promise<TStream>
isStillActive: () => boolean
}): Promise<TStream | null> {
const stream = await options.getUserMedia()
if (!options.isStillActive()) {
stream.getTracks().forEach((track) => track.stop())
return null
}
return stream
}
export function MicRecorder(): React.ReactElement {
const [state, setState] = useState<RecorderState>('idle')
const [error, setError] = useState<string | null>(null)
@ -30,20 +49,11 @@ export function MicRecorder(): React.ReactElement {
const chunksRef = useRef<Blob[]>([])
const transcriptionAbortRef = useRef<AbortController | null>(null)
const transcriptionGenerationRef = useRef(0)
const mountedRef = useRef(true)
const captureGenerationRef = useRef(0)
const configured = isSupabaseConfigured()
useEffect(() => {
return () => {
stopStream()
if (rafRef.current) cancelAnimationFrame(rafRef.current)
if (elapsedTimerRef.current) window.clearInterval(elapsedTimerRef.current)
transcriptionGenerationRef.current += 1
transcriptionAbortRef.current?.abort()
transcriptionAbortRef.current = null
}
}, [])
const stopStream = useCallback((): void => {
streamRef.current?.getTracks().forEach((track) => track.stop())
streamRef.current = null
@ -52,9 +62,36 @@ export function MicRecorder(): React.ReactElement {
analyserRef.current = null
}, [])
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
captureGenerationRef.current += 1
const recorder = mediaRecorderRef.current
if (recorder) {
recorder.ondataavailable = null
recorder.onstop = null
if (recorder.state !== 'inactive') {
try {
recorder.stop()
} catch {
// 언마운트 중 이미 종료된 레코더는 무시한다.
}
}
mediaRecorderRef.current = null
}
stopStream()
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
if (elapsedTimerRef.current !== null) window.clearInterval(elapsedTimerRef.current)
transcriptionGenerationRef.current += 1
transcriptionAbortRef.current?.abort()
transcriptionAbortRef.current = null
}
}, [stopStream])
const updateLevel = useCallback((): void => {
const analyser = analyserRef.current
if (!analyser) return
if (!analyser || !mountedRef.current) return
const buf = new Uint8Array(analyser.frequencyBinCount)
analyser.getByteTimeDomainData(buf)
@ -70,19 +107,25 @@ export function MicRecorder(): React.ReactElement {
}, [])
const startRecording = useCallback(async (): Promise<void> => {
const captureGen = ++captureGenerationRef.current
setError(null)
setTranscript('')
setElapsed(0)
try {
const stream = await navigator.mediaDevices.getUserMedia({
const stream = await acquireGuardedMediaStream({
getUserMedia: () =>
navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: 16000,
channelCount: 1,
echoCancellation: true,
noiseSuppression: true,
}
},
}),
isStillActive: () => mountedRef.current && captureGen === captureGenerationRef.current,
})
if (!stream) return
streamRef.current = stream
const AudioCtx = window.AudioContext
@ -106,27 +149,35 @@ export function MicRecorder(): React.ReactElement {
if (e.data.size > 0) chunksRef.current.push(e.data)
}
mediaRecorder.onstop = () => {
if (!mountedRef.current) {
stopStream()
return
}
void handleRecordingComplete()
}
mediaRecorder.start(250)
startAtRef.current = Date.now()
elapsedTimerRef.current = window.setInterval(() => {
if (mountedRef.current) {
setElapsed(Date.now() - startAtRef.current)
}
}, 100)
setState('recording')
} catch (e) {
stopStream()
if (!mountedRef.current) return
setError(e instanceof Error ? e.message : '마이크 권한을 확인해주세요.')
setState('error')
stopStream()
}
}, [stopStream, updateLevel])
const handleRecordingComplete = useCallback(async (): Promise<void> => {
if (!mountedRef.current) return
setState('processing')
if (rafRef.current) cancelAnimationFrame(rafRef.current)
if (elapsedTimerRef.current) window.clearInterval(elapsedTimerRef.current)
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
if (elapsedTimerRef.current !== null) window.clearInterval(elapsedTimerRef.current)
const blob = new Blob(chunksRef.current, { type: 'audio/webm' })
stopStream()
@ -148,11 +199,11 @@ export function MicRecorder(): React.ReactElement {
supabaseUrl,
signal: controller.signal,
})
if (generation !== transcriptionGenerationRef.current) return
if (!mountedRef.current || generation !== transcriptionGenerationRef.current) return
setTranscript(result.transcript)
setState('done')
} catch (transcriptionError) {
if (generation !== transcriptionGenerationRef.current) return
if (!mountedRef.current || generation !== transcriptionGenerationRef.current) return
setTranscript('')
const code = transcriptionError instanceof WebSttError ? transcriptionError.code : 'network'
const messages: Record<string, string> = {

View file

@ -4,7 +4,7 @@
// 팀 멤버 초대 — 이메일 기반 (V2-7b).
// Edge Function team-invite로 토큰 발급 → 초대 URL 반환 → 클라이언트가 복사/공유.
import { useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import {
Box,
Button,
@ -23,6 +23,13 @@ import {
} from '@mui/material'
import PersonAddIcon from '@mui/icons-material/PersonAdd'
import ContentCopyIcon from '@mui/icons-material/ContentCopy'
import {
clearTrackedTimeout,
createTimedAbortSignal,
resolveSupabaseFunctionUrl,
scheduleTrackedTimeout,
shouldExitAfterAwait,
} from '@/lib/edge-fetch'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
interface InviteMemberFormProps {
@ -43,60 +50,95 @@ export function InviteMemberForm({ teamId }: InviteMemberFormProps): React.React
const [busy, setBusy] = useState(false)
const [result, setResult] = useState<InviteResult | null>(null)
const [copied, setCopied] = useState(false)
const mountedRef = useRef(true)
const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const abortRef = useRef<AbortController | null>(null)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
clearTrackedTimeout(copyTimerRef)
abortRef.current?.abort()
abortRef.current = null
}
}, [])
async function handleInvite(): Promise<void> {
if (!email.trim()) return
setError(null)
setBusy(true)
const timedAbort = createTimedAbortSignal(30_000, abortRef)
try {
const supabase = getSupabaseBrowserClient()
const {
data: { session }
} = await supabase.auth.getSession()
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
if (!session) {
setError('로그인이 필요합니다')
return
}
const response = await fetch(
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/team-invite`,
resolveSupabaseFunctionUrl('team-invite'),
{
method: 'POST',
headers: {
Authorization: `Bearer ${session.access_token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ team_id: teamId, email: email.trim(), role })
body: JSON.stringify({ team_id: teamId, email: email.trim(), role }),
signal: timedAbort.controller.signal,
}
)
if (!response.ok) {
const errData = (await response.json()) as { error?: string; message?: string }
const errData = (await response.json().catch(() => ({}))) as { error?: string; message?: string }
if (mountedRef.current) {
setError(errData.message ?? errData.error ?? `실패: ${response.status}`)
}
return
}
const data = (await response.json()) as InviteResult
if (mountedRef.current) {
setResult(data)
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Unknown error')
if (mountedRef.current) {
setError(timedAbort.didTimeout()
? '초대 요청 시간이 초과되었습니다.'
: e instanceof Error
? e.message
: 'Unknown error')
}
} finally {
timedAbort.dispose()
if (mountedRef.current) {
setBusy(false)
}
}
}
async function handleCopy(): Promise<void> {
if (!result) return
try {
await navigator.clipboard.writeText(result.url)
if (!mountedRef.current) return
setCopied(true)
setTimeout(() => setCopied(false), 2000)
scheduleTrackedTimeout(copyTimerRef, () => {
if (mountedRef.current) setCopied(false)
}, 2000)
} catch {
// clipboard 차단 시 무시
}
}
function handleClose(): void {
clearTrackedTimeout(copyTimerRef)
abortRef.current?.abort()
abortRef.current = null
setOpen(false)
setEmail('')
setRole('member')

View file

@ -0,0 +1,103 @@
export interface TimerRefHandle {
current: ReturnType<typeof setTimeout> | null
}
/**
* Supabase Edge Function URL을 검증·생성한다.
* HTTPS 또는 로컬 loopback HTTP만 허용하고, credentials 포함 URL을 거부한다.
*/
export function resolveSupabaseFunctionUrl(
functionName: string,
rawBaseUrl: string | undefined = process.env.NEXT_PUBLIC_SUPABASE_URL,
): string {
const baseUrl = rawBaseUrl?.trim()
if (!baseUrl) {
throw new Error('서버 설정이 완료되지 않았습니다.')
}
const normalizedName = functionName.trim().replace(/^\/+/, '')
if (!normalizedName || normalizedName.includes('/') || normalizedName.includes('..')) {
throw new Error('잘못된 함수 경로입니다.')
}
try {
const url = new URL(`/functions/v1/${encodeURIComponent(normalizedName)}`, baseUrl)
const isLocalHttp =
url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1')
if ((url.protocol !== 'https:' && !isLocalHttp) || url.username || url.password) {
throw new Error('invalid_origin')
}
return url.toString()
} catch {
throw new Error('서버 주소 설정이 올바르지 않습니다.')
}
}
export interface TimedAbortHandle {
controller: AbortController
didTimeout: () => boolean
dispose: () => void
}
/**
* 타임아웃으로 자동 중단되며, 완료/언마운트 시 타이머와 참조를 정리할 수 있는 AbortController 핸들.
*/
export function createTimedAbortSignal(
timeoutMs: number,
activeRef?: { current: AbortController | null },
): TimedAbortHandle {
const controller = new AbortController()
let timedOut = false
if (activeRef) {
activeRef.current?.abort()
activeRef.current = controller
}
const timer = globalThis.setTimeout(() => {
timedOut = true
controller.abort()
}, timeoutMs)
return {
controller,
didTimeout: () => timedOut,
dispose: () => {
globalThis.clearTimeout(timer)
if (activeRef && activeRef.current === controller) {
activeRef.current = null
}
},
}
}
export function clearTrackedTimeout(timerRef: TimerRefHandle): void {
if (timerRef.current !== null) {
globalThis.clearTimeout(timerRef.current)
timerRef.current = null
}
}
export function scheduleTrackedTimeout(
timerRef: TimerRefHandle,
callback: () => void,
delayMs: number,
): void {
clearTrackedTimeout(timerRef)
timerRef.current = globalThis.setTimeout(() => {
timerRef.current = null
callback()
}, delayMs)
}
/**
* 비동기 경계 직후 언마운트 또는 수동 취소를 확인해 조용히 종료할지 여부를 반환한다.
* 마운트 상태에서 타임아웃이 발생한 경우에는 AbortError를 던져 오류·복구 경로로 넘긴다.
*/
export function shouldExitAfterAwait(
handle: TimedAbortHandle,
isMounted: () => boolean,
): boolean {
if (!isMounted()) return true
if (handle.didTimeout()) {
throw new DOMException('Request timed out', 'AbortError')
}
return handle.controller.signal.aborted
}

View file

@ -11,19 +11,41 @@ export const RETURN_PATH_HEADER = 'x-d3ro-return-path'
const DEFAULT_RETURN_PATH = '/dashboard'
function hasUnsafePathChars(value: string): boolean {
for (let i = 0; i < value.length; i += 1) {
const code = value.charCodeAt(i)
if (code <= 0x1f || code === 0x7f || code === 0x5c) {
return true
}
}
return false
}
/**
* 로그인 뒤 이동할 웹앱 내부 경로(basePath 제외)만 통과시킨다.
* `//evil.example`, `/\evil.example` 같은 외부 이동은 기본 경로로 바꾼다.
* `//evil.example`, `/app//evil.example`, `/\evil.example`, 제어문자는 기본 경로로 바꾼다.
*/
export function safeReturnPath(value: string | null | undefined): string {
if (!value || !value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\')) {
if (!value || !value.startsWith('/') || value.startsWith('//') || hasUnsafePathChars(value)) {
return DEFAULT_RETURN_PATH
}
if (value === WEB_APP_BASE_PATH) return DEFAULT_RETURN_PATH
if (value.startsWith(`${WEB_APP_BASE_PATH}/`)) {
return value.slice(WEB_APP_BASE_PATH.length)
const candidate = value === WEB_APP_BASE_PATH
? DEFAULT_RETURN_PATH
: value.startsWith(`${WEB_APP_BASE_PATH}/`)
? value.slice(WEB_APP_BASE_PATH.length)
: value
if (!candidate.startsWith('/') || candidate.startsWith('//')) {
return DEFAULT_RETURN_PATH
}
return value
try {
const parsed = new URL(candidate, 'https://d3ro.local')
if (parsed.origin !== 'https://d3ro.local' || parsed.pathname.startsWith('//')) {
return DEFAULT_RETURN_PATH
}
} catch {
return DEFAULT_RETURN_PATH
}
return candidate
}
/** 로그인 페이지 경로(basePath 제외). 돌아갈 곳이 기본값이면 쿼리를 붙이지 않는다. */

View file

@ -0,0 +1,415 @@
import fs from 'node:fs'
import path from 'node:path'
import vm from 'node:vm'
import { NextRequest } from 'next/server'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
consumeChatSseStream,
executeChatSendTurn,
type ChatMessage,
} from '@/components/chat/chat-panel'
import { bindAuthSession } from '@/components/providers/auth-provider'
import { acquireGuardedMediaStream } from '@/components/record/mic-recorder'
import {
clearTrackedTimeout,
createTimedAbortSignal,
resolveSupabaseFunctionUrl,
scheduleTrackedTimeout,
shouldExitAfterAwait,
} from '@/lib/edge-fetch'
import { safeReturnPath } from '@/lib/web-app-url'
const mockExchangeCodeForSession = vi.fn()
const mockIsSupabaseConfiguredServer = vi.fn(() => true)
vi.mock('@/lib/supabase-server', () => ({
isSupabaseConfiguredServer: () => mockIsSupabaseConfiguredServer(),
getSupabaseServerClient: async () => ({
auth: {
exchangeCodeForSession: (code: string) => mockExchangeCodeForSession(code),
},
}),
}))
function loadSwSanitizeTargetUrl(): (rawUrl: unknown) => string {
const swPath = path.resolve(__dirname, '../public/sw.js')
const source = fs.readFileSync(swPath, 'utf8')
const sandbox: {
URL: typeof URL
self: {
addEventListener: () => void
registration: { showNotification: () => Promise<void> }
clients: { matchAll: () => Promise<unknown[]> }
}
sanitizeTargetUrl?: (rawUrl: unknown) => string
} = {
URL,
self: {
addEventListener: () => undefined,
registration: { showNotification: async () => undefined },
clients: { matchAll: async () => [] },
},
}
vm.createContext(sandbox)
vm.runInContext(`${source}\nthis.sanitizeTargetUrl = sanitizeTargetUrl;`, sandbox)
if (typeof sandbox.sanitizeTargetUrl !== 'function') {
throw new Error('sanitizeTargetUrl helper missing in public/sw.js')
}
return sandbox.sanitizeTargetUrl
}
describe('Web URL 안전성 및 OAuth 콜백 보안', () => {
afterEach(() => {
vi.clearAllMocks()
vi.useRealTimers()
mockIsSupabaseConfiguredServer.mockReturnValue(true)
})
it('safeReturnPath_앱접두사이후더블슬래시백슬래시제어문자_기본경로로폴백한다', () => {
expect(safeReturnPath('/app//evil.example')).toBe('/dashboard')
expect(safeReturnPath('/app/\\evil.example')).toBe('/dashboard')
expect(safeReturnPath('/dashboard\\@evil.example')).toBe('/dashboard')
expect(safeReturnPath('/dashboard\r\nLocation:https://evil.example')).toBe('/dashboard')
expect(safeReturnPath('/app/meetings?tab=notes#top')).toBe('/meetings?tab=notes#top')
expect(safeReturnPath('/billing')).toBe('/billing')
})
it('sanitizeTargetUrl_푸시알림오픈리다이렉트우회패턴_기본앱경로로폴백한다', () => {
const sanitizeTargetUrl = loadSwSanitizeTargetUrl()
expect(sanitizeTargetUrl('/app//evil.example')).toBe('/app/dashboard')
expect(sanitizeTargetUrl('/app\\evil.example')).toBe('/app/dashboard')
expect(sanitizeTargetUrl('/dashboard\\@evil.example')).toBe('/app/dashboard')
expect(sanitizeTargetUrl('/dashboard\t\n')).toBe('/app/dashboard')
expect(sanitizeTargetUrl('/meetings/123?tab=summary')).toBe('/app/meetings/123?tab=summary')
expect(sanitizeTargetUrl('/app/billing')).toBe('/app/billing')
})
it('authCallback_GET_세션교환실패시원시에러문구노출없이고정코드로리다이렉트한다', async () => {
mockExchangeCodeForSession.mockResolvedValue({
error: { message: 'internal supabase failure https://db.internal:5432' },
})
const { GET } = await import('@/app/auth/callback/route')
const req = new NextRequest('https://d3ro.chanpaca.net/app/auth/callback?code=fake-oauth-code')
const res = await GET(req)
expect(res.status).toBe(307)
const location = res.headers.get('location') ?? ''
expect(location).toBe('https://d3ro.chanpaca.net/app/login?error=oauth_callback_failed')
expect(location).not.toContain('db.internal')
})
it('bindAuthSession_언마운트와세션조회실패_예외누수나해제후상태갱신을차단한다', async () => {
let resolveSession!: (value: { data: { session: null } }) => void
const unsubscribe = vi.fn()
const sessions: unknown[] = []
const loadings: boolean[] = []
const unbind = bindAuthSession(
{
auth: {
getSession: () =>
new Promise((resolve) => {
resolveSession = resolve
}),
onAuthStateChange: () => ({ data: { subscription: { unsubscribe } } }),
},
},
(s) => sessions.push(s),
(l) => loadings.push(l),
)
unbind()
resolveSession({ data: { session: null } })
await new Promise((resolve) => setTimeout(resolve, 0))
expect(unsubscribe).toHaveBeenCalledTimes(1)
expect(sessions).toEqual([])
expect(loadings).toEqual([])
const rejectedSessions: unknown[] = []
const rejectedLoadings: boolean[] = []
const unbindRejected = bindAuthSession(
{
auth: {
getSession: async () => {
throw new Error('session storage corrupted')
},
onAuthStateChange: () => ({ data: { subscription: { unsubscribe: vi.fn() } } }),
},
},
(s) => rejectedSessions.push(s),
(l) => rejectedLoadings.push(l),
)
await new Promise((resolve) => setTimeout(resolve, 0))
unbindRejected()
expect(rejectedSessions).toEqual([null])
expect(rejectedLoadings).toEqual([false])
})
it('acquireGuardedMediaStream_권한대기중언마운트_획득된트랙을즉시중지하고null반환한다', async () => {
const stopA = vi.fn()
const stopB = vi.fn()
let active = true
let resolveStream!: (stream: { getTracks: () => Array<{ stop: () => void }> }) => void
const pending = acquireGuardedMediaStream({
getUserMedia: () =>
new Promise((resolve) => {
resolveStream = resolve
}),
isStillActive: () => active,
})
active = false
resolveStream({ getTracks: () => [{ stop: stopA }, { stop: stopB }] })
const result = await pending
expect(result).toBe(null)
expect(stopA).toHaveBeenCalledTimes(1)
expect(stopB).toHaveBeenCalledTimes(1)
})
it('consumeChatSseStream_중단시그널수신_reader를취소하고잔여토큰을방출하지않는다', async () => {
const encoder = new TextEncoder()
let cancelled = false
let enqueueChunk!: (value: Uint8Array) => void
const body = new ReadableStream<Uint8Array>({
start(controller) {
enqueueChunk = (chunk) => controller.enqueue(chunk)
},
cancel() {
cancelled = true
},
})
const abortController = new AbortController()
const emitted: string[] = []
const reading = consumeChatSseStream({
body,
signal: abortController.signal,
onAccumulated: (text) => emitted.push(text),
})
enqueueChunk(encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"안녕"}}\n\n'))
await vi.waitFor(() => {
expect(emitted).toEqual(['안녕'])
})
abortController.abort()
await reading
expect(cancelled).toBe(true)
expect(emitted).toEqual(['안녕'])
})
it('edgeFetchHelpers_안전하지않은함수URL을차단하고타임아웃및타이머정리를보장한다', () => {
expect(resolveSupabaseFunctionUrl('llm-proxy', 'https://proj.supabase.co')).toBe(
'https://proj.supabase.co/functions/v1/llm-proxy',
)
expect(resolveSupabaseFunctionUrl('team-invite', 'http://127.0.0.1:54321')).toBe(
'http://127.0.0.1:54321/functions/v1/team-invite',
)
expect(() => resolveSupabaseFunctionUrl('llm-proxy', 'http://remote.example')).toThrow()
expect(() => resolveSupabaseFunctionUrl('llm-proxy', 'https://user:pass@proj.supabase.co')).toThrow()
expect(() => resolveSupabaseFunctionUrl('../admin', 'https://proj.supabase.co')).toThrow()
vi.useFakeTimers()
const activeRef: { current: AbortController | null } = { current: null }
const handle = createTimedAbortSignal(1000, activeRef)
expect(handle.didTimeout()).toBe(false)
expect(activeRef.current).toBe(handle.controller)
vi.advanceTimersByTime(1000)
expect(handle.didTimeout()).toBe(true)
expect(handle.controller.signal.aborted).toBe(true)
expect(() => shouldExitAfterAwait(handle, () => true)).toThrow('Request timed out')
expect(shouldExitAfterAwait(handle, () => false)).toBe(true)
handle.dispose()
expect(activeRef.current).toBe(null)
const manualHandle = createTimedAbortSignal(1000, activeRef)
manualHandle.controller.abort()
expect(shouldExitAfterAwait(manualHandle, () => true)).toBe(true)
manualHandle.dispose()
const timerRef: { current: ReturnType<typeof setTimeout> | null } = { current: null }
const calls: string[] = []
scheduleTrackedTimeout(timerRef, () => calls.push('first'), 500)
scheduleTrackedTimeout(timerRef, () => calls.push('second'), 500)
vi.advanceTimersByTime(500)
expect(calls).toEqual(['second'])
scheduleTrackedTimeout(timerRef, () => calls.push('unmounted'), 500)
clearTrackedTimeout(timerRef)
vi.advanceTimersByTime(1000)
expect(calls).toEqual(['second'])
})
it('executeChatSendTurn_스트림응답중45초타임아웃_부분메시지롤백과입력복구및시간초과오류를표시한다', async () => {
vi.useFakeTimers()
const encoder = new TextEncoder()
let streamCancelled = false
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(
encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"부분응답"}}\n\n'),
)
},
cancel() {
streamCancelled = true
},
})
let currentMessages: ChatMessage[] = [
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
]
let restoredInput = ''
let latestError: string | null = null
let busyState = false
const activeRef: { current: AbortController | null } = { current: null }
const pendingTurn = executeChatSendTurn({
text: '회의 요약해줘',
messages: currentMessages,
activeControllerRef: activeRef,
isMounted: () => true,
isConfigured: () => true,
getAccessToken: async () => 'access-token',
endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy',
fetchImpl: async () =>
new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }),
onMessagesUpdate: (updater) => {
currentMessages = updater(currentMessages)
},
onInputChange: (val) => {
restoredInput = val
},
onErrorChange: (err) => {
latestError = err
},
onBusyChange: (busy) => {
busyState = busy
},
})
await vi.advanceTimersByTimeAsync(100)
expect(currentMessages.some((m) => m.role === 'assistant' && m.content === '부분응답')).toBe(true)
await vi.advanceTimersByTimeAsync(45_000)
await pendingTurn
expect(streamCancelled).toBe(true)
expect(currentMessages).toEqual([
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
])
expect(restoredInput).toBe('회의 요약해줘')
expect(latestError).toBe('AI 응답 시간이 초과되었습니다.')
expect(busyState).toBe(false)
})
it('executeChatSendTurn_세션조회중45초타임아웃_조용히종료하지않고입력복구와시간초과오류를표시한다', async () => {
vi.useFakeTimers()
let currentMessages: ChatMessage[] = [
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
]
let restoredInput = ''
let latestError: string | null = null
let busyState = false
let resolveSession!: (token: string | null) => void
const activeRef: { current: AbortController | null } = { current: null }
const pendingTurn = executeChatSendTurn({
text: '다시 시도할 질문',
messages: currentMessages,
activeControllerRef: activeRef,
isMounted: () => true,
isConfigured: () => true,
getAccessToken: () =>
new Promise((resolve) => {
resolveSession = resolve
}),
endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy',
fetchImpl: async () => new Response(null, { status: 500 }),
onMessagesUpdate: (updater) => {
currentMessages = updater(currentMessages)
},
onInputChange: (val) => {
restoredInput = val
},
onErrorChange: (err) => {
latestError = err
},
onBusyChange: (busy) => {
busyState = busy
},
})
await vi.advanceTimersByTimeAsync(45_000)
resolveSession('late-token')
await pendingTurn
expect(currentMessages).toEqual([
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
])
expect(restoredInput).toBe('다시 시도할 질문')
expect(latestError).toBe('AI 응답 시간이 초과되었습니다.')
expect(busyState).toBe(false)
})
it('executeChatSendTurn_스트림중언마운트_reader를취소하고오류나롤백을갱신하지않는다', async () => {
const encoder = new TextEncoder()
let mounted = true
let streamCancelled = false
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(
encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"부분"}}\n\n'),
)
},
cancel() {
streamCancelled = true
},
})
let currentMessages: ChatMessage[] = []
let inputCalls = 0
let errorCalls = 0
const activeRef: { current: AbortController | null } = { current: null }
const pendingTurn = executeChatSendTurn({
text: '언마운트 테스트',
messages: currentMessages,
activeControllerRef: activeRef,
isMounted: () => mounted,
isConfigured: () => true,
getAccessToken: async () => 'access-token',
endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy',
fetchImpl: async () =>
new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }),
onMessagesUpdate: (updater) => {
currentMessages = updater(currentMessages)
},
onInputChange: () => {
inputCalls += 1
},
onErrorChange: () => {
errorCalls += 1
},
onBusyChange: () => undefined,
})
await vi.waitFor(() => {
expect(currentMessages.some((m) => m.content === '부분')).toBe(true)
})
const countBeforeUnmount = currentMessages.length
mounted = false
activeRef.current?.abort()
await pendingTurn
expect(streamCancelled).toBe(true)
expect(currentMessages.length).toBe(countBeforeUnmount)
expect(inputCalls).toBe(1)
expect(errorCalls).toBe(1)
})
})

View file

@ -1,6 +1,6 @@
# D3RO-VOICE 리팩토링 정책 (SSOT)
> 마지막 갱신: 2026-11-14 — Wave 6 전 표면 코드 위생 · 최적화 · 버그 헌팅 정책 보완
> 마지막 갱신: 2026-11-14 — Wave 7 6-세션 네이티브 피어 스웜(`swarm`) 정책 및 검증 기준 보완
> 적용 범위: `apps/*` + `packages/*` + `server/*` + `site/` + 빌드·배포 스크립트 (기능 변경은 별도 요청)
## 0. 전제: 기존 3계층 규칙 SSOT와의 관계
@ -162,3 +162,9 @@ DRY 원칙 보강: Deno처럼 정본을 직접 import할 수 없는 런타임은
- 파일 소유 경계가 겹치지 않는 4개 워크스트림(`WS1` desktop main/sidecar, `WS2` shared packages + desktop renderer/popups, `WS3` mobile-rn, `WS4` web/admin/site/Edge/Cloudflare/.NET)을 병렬 실행한다.
- 중복 제거(SSOT 통합)와 리소스/메모리 최적화 및 동시성/보안 버그 수정을 함께 수행하되, Deno 계약(`contract:check`), API/IPC 시그니처, 도메인 오류 클래스·코드, fail-closed 동작, 보호 테스트, 런타임 `[~]`/`[!]` 상태 경계를 보존한다.
- 통합 후 `npm run verify:all`, `contract:check`, `check:migrations`, `version:check`, `security:secrets`, `dotnet test`, sidecar Python `unittest`, Edge + Worker Deno 테스트, `npm run build` + `check:desktop-renderer`, `test:metrics:write` 및 `docs/REFACTOR_WAVE6_REPORT.md` · `docs/map/*` 갱신을 완료한다.
## Wave 7 (2026-11-14) — 6-세션 네이티브 피어 스웜 (monitor · input-core · desktop-shell · mobile-app · cloud-surfaces · verifier)
- Antigravity 네이티브 `swarm` (`share` 워크트리)으로 4개 구현 워커(`input-core`, `desktop-shell`, `mobile-app`, `cloud-surfaces`), 모니터링 워커(`monitor`), 전담 피어 리뷰어(`verifier`)를 구성하고 `@mention`/`#seq` 보드 프로토콜로 교차 검증한다.
- `@verifier`가 보고한 결함은 각 워커가 동일 워크스페이스에서 델타 커밋으로 보완하고 재검증(`@coordinator [all-verified]`)을 통과한 커밋만 `main`에 체리픽한 뒤 워커를 종료한다(Windows에서 `swarm kill`로 `.bin` 또는 nested `node_modules` 심이 유실된 경우 통합 검증 전 `npm install --prefer-offline` / `npm --prefix apps/mobile-rn ci --prefer-offline` 및 `better_sqlite3.node` ABI 확인을 수행한다).
- Batch 1(정적 게이트·`dotnet test`·Python `unittest`·Edge/Worker/Site Bridge Deno) + Batch 2(전 워크스페이스 `typecheck`/`lint`/`test`, `test:mobile`, `npm run build` + `check:desktop-renderer`, `test:metrics:write`) 통과 후 `docs/REFACTOR_WAVE7_REPORT.md`, `docs/map/*`, `docs/v3/MOBILE_APP_COMPLETION_SSOT.md`, `.claude/skills/refactor-wave/SKILL.md`를 동일 커밋으로 동기화한다(운영 배포 시점 이후 `main` 통합분과 라이브 배포 상태를 구분 표기).

View file

@ -0,0 +1,110 @@
# D3RO Voice — Wave 7 다중 세션 피어 스웜 코드 위생 · 최적화 · 버그 헌팅 보고서
> 일시: 2026-11-14
> 대상 브랜치: `main` (기준 커밋 `a37dd63` -> 통합 커밋 `cc3f746`, 7 commits / 98 files `+7,170 / -597`)
> 실행 토폴로지: Antigravity 네이티브 `swarm` 6개 세션 (`monitor`, `input-core`, `desktop-shell`, `mobile-app`, `cloud-surfaces`, `verifier`) + `@mention`/`#seq` 피어 리뷰 보드(`Run /swarm board (default shortcut alt+s) to open the live board.`)
> 정책 SSOT: `docs/REFACTOR_POLICY.md`, `.claude/skills/refactor-wave/SKILL.md`
---
## 1. 운영 배포 경계와 Wave 7 범위
1. **운영 `v1.17.1` 기준선 (`6c6875b`, 태그 `v1.17.1`)**: 데스크톱(Forgejo `1.17.1/latest.yml`·`.sig`, `runtime-1.17.1`, `portable-1.17.1` HTTP `200`; Human Release #339 ~91MB 바이너리 첨부만 `GAP-REL-16` 예외), Supabase 운영 DB(74개 마이그레이션 동기화)·Edge Functions 24종, 랜딩 사이트(`site/` -> Cloudflare Pages `d3ro`, `https://d3ro.chanpaca.net/release-identity.json`), Cloudflare Worker(`d3ro-voice-api` `--keep-vars`, Version ID `fe6d9532-0052-48f5-b62c-45c86f6aaaa5`), NAS Docker 스택(`api-server` `:5050/health` `200`, `admin` `:3001` / `d3ro-admin.chanpaca.net/login` `200`, `web` `:3002/app/login` / `d3ro.chanpaca.net/app/login` `200`) 배포 완료 후 `a37dd63`에 기록됨.
2. **Wave 7 반영 범위 (`2a009e4..cc3f746`)**: Wave 7 커밋은 **`v1.17.1` 배포 이후**에 `main`으로 통합·검증되었다. 따라서 Wave 7 수정사항은 현재 **`main` 통합 및 모노레포 전 게이트 검증 완료** 상태이며, `v1.17.1` 기배포 바이너리·컨테이너에는 포함되어 있지 않다(차기 릴리스 `v1.17.2` / `v1.18.0` 및 재배포 반영 대상).
3. **Cloudflare Worker 운영 환경변수 경계**: Wave 7(`c68e81e`)이 `server/cloudflare-worker/wrangler.toml`의 `BACKEND_ORIGIN` 기본값을 `https://d3ro.chanpaca.net`으로 수정했으나, `v1.17.1` 배포 당시 `--keep-vars`로 유지된 라이브 Worker `d3ro-voice-api`(`fe6d9532-0052-48f5-b62c-45c86f6aaaa5`)에는 기존 대시보드 변수(`BACKEND_ORIGIN = "http://192.168.0.39:5050"`)가 남아 있어 라이브 `/health`는 Cloudflare Error `1003` (`HTTP 403`) 상태다.
---
## 2. 피어 리뷰(`@verifier`) 바운스 및 해소 이력
1. **#10 `desktop-shell` 바운스 -> `3f9e412` 해소 (`4 files, +103/-3`)**:
- 문제: `LocalLLMService` `/api/pull` 중단 및 `LocalSTTService` 모델 다운로드 `dispose()` 중단 시 raw abort 오류가 `D3ROError`로 래핑되지 않아 계약과 불일치.
- 수정: `LocalLLMService.ts`는 `D3ROError(ErrorCode.LLM_ERROR)`로, `LocalSTTService.ts`는 `D3ROError(ErrorCode.STTModelDownloadCancelled)`로 래핑하고 관련 단위 테스트 보강.
2. **#11 `mobile-app` 바운스 -> `cc3f746` 해소 (`5 files, +376/-45`)**:
- 문제: `durable-processing-queue.ts` cleanup 경로에서 큐 항목 제거와 오디오 파일 삭제 순서·실패 재시도 보장이 미흡했고, 다중 화면에서 계정 전환 후 `busy`/`running` 상태가 섞일 여지가 남아 있었음.
- 수정: `finishCleanupItem(item)`으로 오디오 파일 먼저 삭제 후 큐 항목 제거(삭제 실패 시 60초 재시도 예약), 화면(`Commands`, `HistoryDetail`, `Home`, `Knowledge`, `Meetings`, `Record`, `Teams`)에 `scopeGenerationRef`와 `try/catch/finally` 가드 통일.
3. **#17 `cloud-surfaces` 바운스 -> `4bf0f0d` 해소 (`7 files, +363/-106`)**:
- 문제: `apps/web/src/components/chat/chat-panel.tsx` `executeChatSendTurn`과 `action-runner.tsx`, `payple-manage-button.tsx`, `generate-document-button.tsx`, `invite-member-form.tsx`에서 `createTimedAbortSignal` 타임아웃이 삼켜지거나 await 이후 언마운트(`shouldExitAfterAwait`) 판정이 일관되지 않았음.
- 수정: `edge-fetch.ts` 계약 기준으로 타임아웃·abort·언마운트 가드를 전파하고 `security-and-lifecycle.test.ts` 회귀 보강.
4. **최종 승인**: `@verifier` 재검증 후 `#21` `@coordinator [all-verified]` 수신 -> 전 커밋 `main` 체리픽(`0` 충돌) 및 커밋 메시지 위생 검증(`Co-Authored-By`/AI 문구 0건) 후 워커 종료(`#22`).
---
## 3. 워크스트림별 수정 내역
### 3.1 `input-core` (`2a009e4`, `8 files, +640/-53`) — 문장부호 직후 무공백 영타 오타 라이브 트리거 복구
실사용 중 보고된 `상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl?`(기대 변환: `유기하고있진않지`)와 같은 **문장부호(`?`) 직후 공백 없이 이어진 영타·말줄임표 오타**가 라이브 파이프라인에서 누락되던 4가지 원인을 동시에 수정했다:
| 계층 | 파일 | 수정 내용 |
|---|---|---|
| Telemetry | `apps/desktop/src/main/services/InputTelemetryService.ts` | `TYPO_SETTLE_DELAY_MS` (`700ms`) / `_typoSettleTimer` 추가로 제안 기능 비활성·지연·접두사 임계치 미달 구간에서도 `>=650ms` settle 스냅샷 보장; `diffInsertionSpan()`으로 문장부호(`?`) 트리밍을 걸친 `_expectedInserts` 계산 정확화; 만료된 `_programmaticKeys` 정리 및 `_learnFlushTimer.unref()` |
| Typo Service | `apps/desktop/src/main/services/TypoCorrectionService.ts` | 문장부호 경계 정규식(`~…?!。`) 확장; `trailingWordOnly` 패스에서 경계로 닫힌 단일 토큰을 최대 `MAX_INPLACE_DELETE_CHARS` (32)자까지 허용하고 `_markRegionChecked()` 영구 잠금 차단 |
| Core Rules | `packages/core/src/araso-layout.ts`, `typo-correction.ts`, `personal-ngram.ts` | `isUrlOrPathRun()`으로 `domain.tld?` / `file.ext?`는 보호하되 한글+말줄임표(`[가-힣ㄱ-ㆎ][!?~]*\.{2,}$`) 변환 허용(`...props` 유지); `WORD_BOUNDARY_AFTER_RE` 정리; `PersonalNgramModel.next()` 불필요한 `Map` 복사 제거 |
| Regression Tests | `apps/desktop/tests/main/services/typo-live-punctuation.test.ts`, `TypoCorrectionService.test.ts`, `packages/core/__tests__/typo-correction.test.ts` | 문장부호 뒤 한/영 무공백 전환, URL/코드 접두사 비변환, 재입력·트림 복원 회귀 테스트 추가 |
### 3.2 `desktop-shell` (`fc5d453` 19 files + `3f9e412` 4 files) — 메인 서비스 취소 · 해제 · 레이스 하드닝
- `apps/desktop/src/main/windows/WindowManager.ts`: `hideResultPopup()`에서 `pendingResultShow` 타이머를 취소하고 `lastResultCursor = null`로 초기화(`popup-hide-show-race.test.ts`).
- `apps/desktop/src/main/services/CaptionService.ts`: `ensureAuxModel` 성공 뒤 `_captionModelId`를 기록하고 이전 `loadedAuxModelId`를 해제, `_stopPromise`로 동시 `stop()`/`dispose()` 중복 실행 차단, 호출 단위 `AbortController` + `_refineEpoch`/`_refineRunId` 리셋(`caption-lifecycle-refine.test.ts`, `caption-aux-release.test.ts`).
- `apps/desktop/src/main/services/VoiceModeService.ts`, `llm/LlmGateway.ts`, `LocalLLMService.ts`: `run.controller.signal`을 `LocalLLMService.processText`까지 전파, `/api/pull` `AbortController` 등록 및 `dispose()` 시 리더·요청 중단 후 `D3ROError(ErrorCode.LLM_ERROR)` 래핑, dispose 이후 폴링 가용성 복원 차단(`local-llm-service.test.ts`, `llm-limits-routing-redteam-r2-1.test.ts`, `VoiceModeService.test.ts`).
- `apps/desktop/src/main/services/{VoiceConversationService,AudioCaptureService,LocalSTTService}.ts` & `ipc/caption-handlers.ts`: abort 시 `_responseAbortController` 정리, stale 마이크 시작 catch 가드, SoX `'stopping'` 재개 확인 및 `start()` 실패 `_cleanup()`, `dispose()` 시 STT 모델 다운로드 fetch/sleep 중단 + `D3ROError(ErrorCode.STTModelDownloadCancelled)` 래핑, `desktopCapturer.getSources` fail-closed `callback({})`(`VoiceConversationService.test.ts`, `audio-capture-redteam-r2-7.test.ts`, `stt-sidecar-redteam-r2-6.test.ts`, `ipc-redteam-r3-1.test.ts`).
### 3.3 `mobile-app` (`bd3c1a9` 25 files + `cc3f746` 5 files) — 레코더 · 내구성 큐 · 컨텍스트 · 화면 비동기 가드
- 레코더 (`src/lib/audio-recorder.ts`, `src/lib/recorder/{nitro-backend,android-foreground-backend}.ts`): `pendingClaim` + `finally` 해제, `startGeneration`/`sessionGeneration` 세대 가드, `pollTimer` 누수 방지(`recorder-lifecycle-races.test.ts`).
- 큐·히스토리 (`src/features/recording/durable-processing-queue.ts`, `src/features/history/use-history-sync.ts`): `running`/`cleanup` 가드, `suspendedUsers` 재시도 차단, `discardedItems` 재검사, `finishCleanupItem(item)`(오디오 파일 선삭제 -> 큐 항목 제거, 삭제 실패 시 60초 재시도), request-id/scope 가드(`queue-and-history-races.test.ts`).
- 서비스·컨텍스트·화면: `chat-service.ts`, `admin-service.ts`, `device-service.ts`, `llm-stream-service.ts`, 4개 컨텍스트(`mobile-ads`, `billing`, `device`, `entitlement`), 7개 화면(`Commands`, `HistoryDetail`, `Home`, `Knowledge`, `Meetings`, `Record`, `Teams`)에 pre-abort 가드, 세대 헤더 불일치 시 `response.body` 취소, 계정 전환 상태 초기화 및 `scopeGenerationRef` + `try/catch/finally` 적용(`abort-and-stream-guards.test.ts`, `context-lifecycle-guards.test.tsx`, `screen-async-lifecycle.test.tsx`).
### 3.4 `cloud-surfaces` (`c68e81e` 46 files + `4bf0f0d` 7 files) — 엣지 게이트웨이 · .NET SSRF · Supabase · Web/Admin 보안
- **Cloudflare Worker & Site Bridge (`server/cloudflare-worker`, `server/cloudflare-site-bridge`)**: `wrangler.toml` `BACKEND_ORIGIN`을 `https://d3ro.chanpaca.net`으로 교정, `origin-policy.ts`로 비-HTTPS·사설 IP·내부 호스트·프록시 루프(`508`/`503`) 차단, `204`/`205`/`304` null-body 처리, `push-drain.ts` origin 검증; `cloudflare-site-bridge` `508` 루프 가드·경로 스머글링 `400`·`deno.json` 추가.
- **.NET API (`apps/api-server`, `apps/api-server.Tests`)**: `EndpointUrlPolicy.cs` SSRF 검증, `"UpstreamNoRedirect"` 명명 `HttpClient`(`AllowAutoRedirect = false`), query language parameter 인코딩, `EndpointSecurityAndSttProxyTests.cs` 추가.
- **Supabase Edge Functions (`server/supabase/functions`)**: `stt-proxy/handler.ts` `Content-Length` 초과 선차단(`413`), `embed-chunks/handler.ts` 업스트림 프로바이더 오류 시에만 할당량 환불, `_shared/quota.ts` `PGRST116` 외 DB 오류 fail-closed 예외 전파.
- **Web & Admin (`apps/web`, `apps/admin`)**: `safeReturnPath` / `public/sw.js` / `admin-url-safety.ts`로 `//evil`·백슬래시·제어문자 오픈 리다이렉트 차단, OAuth callback 오류 메시지 누출 제거, `apps/admin/src/proxy.ts` `isStaticAssetPath` 정밀화; `apps/web/src/lib/edge-fetch.ts` (`resolveSupabaseFunctionUrl`, `createTimedAbortSignal`, `shouldExitAfterAwait`)를 `chat-panel`, `action-runner`, `payple-*`, `generate-document-button`, `invite-member-form`, `document-editor`, `history` 페이지들에 적용하고 `auth-provider` `bindAuthSession` / `mic-recorder` `acquireGuardedMediaStream` 보강 (`apps/web/tests/security-and-lifecycle.test.ts`, `apps/admin/tests/admin-security.test.ts` + Vitest 구성).
---
## 4. 통합 `main` (`cc3f746`) 전체 검증 결과
### 4.1 Batch 1 (정적 · 계약 · 백엔드 · 사이드카, `task-587`, exit `0`)
| 게이트 / 스위트 | 결과 |
|---|---|
| `version:check` | `1.17.1` (`1170100/1170100`) PASS |
| `contract:check` / `check:migrations` | PASS / `74` files 일치 |
| `security:secrets` / `check:protected-tests` | `0` issues / `0` protected modifications (`HEAD` & `a37dd63`) |
| `test:hygiene` / `test:quality` | `448 test files` PASS / `468 test files`, `0` regression |
| `check:i18n` / `check:ds-contract` / `check:design` | `2500 keys × 12 locales` / `13 components` / `0` violations |
| `dotnet test` (`apps/api-server.Tests`) | **55 passed, 0 failed** |
| Sidecar Python `unittest` | **33 tests in 2.169s, OK** |
| Supabase Edge (`deno check` + `deno test`) | **273 passed \| 0 failed** |
| Cloudflare Worker (`deno check` + `deno test`) | **15 passed \| 0 failed** |
| Cloudflare Site Bridge (`deno check` + `deno test`) | **5 passed \| 0 failed** |
### 4.2 Batch 2 (모노레포 TS · ESLint · Vitest · Jest · 빌드 · 지표, `task-654`, exit `0`)
> **환경 복구 메모**: Windows 환경에서 `swarm kill`로 `share` 워크트리가 삭제되며 루트 `.bin`·`apps/{admin,web}/node_modules` 일부와 `apps/mobile-rn/node_modules/@babel/plugin-transform-runtime` 등이 손상되어, 게이트 실행 전 `npm install --prefer-offline` + `npm --prefix apps/mobile-rn ci --prefer-offline`으로 복구하고 `better_sqlite3.node` (`sqlite_abi=node_ok`)를 확인했다.
| 게이트 / 워크스페이스 | 결과 |
|---|---|
| `typecheck` / `typecheck:mobile` / `typecheck:site` | PASS |
| `lint` / `lint:mobile` / `lint:site` (`--max-warnings=0`) | PASS |
| `@d3ro/desktop` (Vitest) | **212 files / 2,890 tests PASS** |
| `@d3ro/web` (Vitest) | **10 files / 52 tests PASS** |
| `@d3ro/admin` (Vitest) | **1 file / 6 tests PASS** |
| `@d3ro/api-client` (Vitest) | **4 files / 31 tests PASS** |
| `@d3ro/core` (Vitest) | **39 files / 629 tests PASS** |
| `@d3ro/i18n` (Vitest) | **2 files / 25 tests PASS** |
| `@d3ro/ui` (Vitest) | **2 files / 7 tests PASS** |
| `test:mobile` (`@d3ro/mobile-rn` Jest `--runInBand`) | **103 suites / 651 tests PASS** (`24.945 s`) |
| `npm run build` + `check:desktop-renderer` | `electron-vite build` + **7 page(s)** PASS |
| `npm run test:metrics:write` (`docs/tdd-red/metrics/2026-11-14.md`) | **454 files / 3,738 cases / weak 128 / ambient 203 / skip/todo 3 / 12 locales / 2,500 keys** |
---
## 5. 유지된 비코드 / 런타임 / 외부 경계 (`[~]` · `[!]` · `RED`)
- **Desktop runtime (`[~]`)**: `InputTelemetryService` / `TypoCorrectionService` / `CaptionService` / `LocalLLMService` / `LocalSTTService` / `WindowManager` 수정은 단위·서비스 테스트 및 렌더러 번들 게이트까지 검증되었으며, 실제 Windows GUI(예: `상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl?` 라이브 타이핑, 오버레이 표시/해제)는 `GAP-INPUT-08/09/10/11` 외부-터미널 `run-desktop.bat` 실행 대상으로 남는다.
- **Mobile runtime & Play Store (`[~]` / `[!]` / `RED`)**: Fold6/iOS 실기기 수동 TalkBack·초회 진입·FCM 수신·AdMob 운영 광고·Play Billing·Play 비공개 테스트(`EXT-*`)는 외부 게이트(`RED`)로 유지한다.
- **Cloudflare Worker live env (`[~]`)**: `wrangler.toml` `BACKEND_ORIGIN` 수정분을 실운영 `d3ro-voice-api`에 반영하려면 대시보드 변수 덮어쓰기 또는 재배포가 필요하다.

View file

@ -2,7 +2,11 @@
> Status: ACTIVE
> Last full audit: 2026-09-13
> Last update: 2026-11-14 — **전 표면 코드 위생 · 최적화 · 버그 헌팅 완결(Wave 6, WS1–WS4 병렬).** (1) **Desktop Main & Sidecar (`WS1`):** `ipc/renderer-broadcast.ts`(`safeSendToRenderer`/`broadcastToAllWindows`) 9개 파일 단일화, `OnlineLLMService` 스트림 abort/401/예외 래핑, `UnifiedSearchService` FTS5→`LIKE` 런타임 폴백·집계·정렬·인덱스(`started_at`/`created_at`) 보강, `rag/chunk-store.ts` 캐시 무효화·중복 `embedding` JSON 제거·손상 Float32 방어, `disk-wav-audio-sink.ts` uint32 오버플로·헤더 write 실패 fd 정리, `AdMediationEngine`/`AudioCaptureService`/`LocalLLMService`/`WindowManager` 타이머·팝업 레이스 수정, `sidecar/main.py` `UploadFile.close()`·PCM 바이트 경계·`/shutdown` 스레드 join 완료. (2) **Shared Packages & Desktop Renderer (`WS2`):** `@d3ro/i18n` `shared.ts` 및 지연 로드/언마운트 레이스 차단(`25/25`), `@d3ro/core` PII 플레이스홀더·CSV BOM/CR·타임스탬프·검색 경계값(`626/626`), `@d3ro/ui` `wave-math.ts` + 캔버스 `LinearGradient` 캐싱(`7/7`), `@d3ro/ui-native`/`api-client` 경계 가드, 렌더러 `utils/error-message.ts`·훅/컴포넌트 언마운트·타이머 정리 및 Vanilla JS 팝업 6종 `beforeunload`/DOM 안전화 완료. (3) **Mobile RN (`WS3`):** `features/shared/{service-guards,owned-cache-files}.ts`, `features/import/abort-guard.ts`, `lib/locale-speech.ts`(12개 로케일), `features/meetings/meeting-error-message.ts`로 26+ 파일 중복 가드·오류·포맷 통합, `FreeTierBanner` 슬롯 전환 시 높이 고착 수정·내구성 큐 조기 폐기 경합 차단·녹음 리스 누수·언마운트 재생/로케일 레이스 해결(Jest `98 suites / 625 tests PASS`). (4) **Web · Admin · Site · Edge · Worker · .NET (`WS4`):** Edge 20개 엔드포인트 `_shared/json-response.ts`(스트리밍 바이트 상한 포함 `readJsonBody`·`jsonResponse`) 통합 및 `account-delete`/`llm-proxy`/`payple`/`realtime-token` fail-closed 강화(Deno `270/270`), `.NET` `SttProxyService` Base64 상한 + `CancellationToken` 전파(xUnit `32/32`), Cloudflare Worker `resolveBackendTargetUrl` SSRF·타임아웃·`/worker-health` 정보 노출 차단(Deno `9/9`), 웹 `MarkdownPreview` DOM XSS/레이스·`WebPush` 재진입·`team-client` fail-closed(`42/42`), 어드민 `request-security.ts`/`detail-row.tsx`·CSRF/`ADMIN_UUID_PATTERN`/비용 검증, 사이트 `AppLoopDemo`/`rel="noopener noreferrer"` 보강 완료. 상세: [`REFACTOR_WAVE6_REPORT.md`](../REFACTOR_WAVE6_REPORT.md).
> Last update: 2026-11-14 — **Wave 7 6-세션 네이티브 피어 스웜(`2a009e4..cc3f746`, [`REFACTOR_WAVE7_REPORT.md`](../REFACTOR_WAVE7_REPORT.md)) 통합 및 모노레포 전 게이트 검증 완료 (post-`v1.17.1`).** `input-core`·`desktop-shell`·`mobile-app`·`cloud-surfaces`·`verifier`·`monitor` 피어 리뷰(`@mention`/`#seq`)를 거쳐 문장부호 직후 무공백 오타 라이브 트리거·서비스 취소/해제·모바일 내구성 큐/화면 가드·Cloudflare/Edge/.NET/Web/Admin 보안 수정을 `main`에 통합하고 Batch 1(`dotnet test 55/55`, sidecar `33/33`, Edge `273/273`, Worker `15/15`, Site Bridge `5/5`, 정적 게이트) + Batch 2(Vitest `270 files / 3,640 tests`, Jest `103 suites / 651 tests`, `typecheck`·`lint`·`build`·`check:desktop-renderer`·`test:metrics:write` `454 files / 3,738 cases`) 통과(운영 `v1.17.1` 재배포·실기기/GUI `[~]`/`[!]`/`RED` 경계 유지).
>
> Previous update: 2026-11-14 — **전 표면 프로덕션 `v1.17.1` 배포 완결.** 데스크톱(`v1.17.1`, 커밋 `6c6875b`, 서명 매니페스트 `1.17.1/latest.yml`·`.sig` 및 `latest/latest.yml`, 런타임 `runtime-1.17.1`/`runtime-latest`, 포터블 `portable-1.17.1`/`portable-latest` 모두 Forgejo HTTP `200`, 태그 `v1.17.1` canonical/mirror 푸시; Human Release #339 ~91MB 바이너리 첨부만 Cloudflare HTTP 524/`ECONNRESET` `GAP-REL-16` 예외), Supabase 운영 DB(`db push --remote`, 전체 74개 마이그레이션 일치) 및 Edge Functions 24종(`--import-map deno.json --use-api`) 재배포, 랜딩 사이트(`site/` → Cloudflare Pages `d3ro`, `https://d3ro.chanpaca.net/release-identity.json` = `1.17.1`/`6c6875b` & `assetlinks.json` 검증 GREEN), Cloudflare Worker(`d3ro-voice-api` `--keep-vars`, Version ID `fe6d9532-0052-48f5-b62c-45c86f6aaaa5`), NAS Docker 스택(`d3ro_voice_api` `v1.17.1` `/health` `200`, `d3ro_voice_admin` `:3001`/`d3ro-admin.chanpaca.net/login` `200`, `d3ro_voice_web` `:3002/app/login`·`d3ro.chanpaca.net/app/login` `200`) 반영 완료.
>
> Earlier update: 2026-11-14 — **전 표면 코드 위생 · 최적화 · 버그 헌팅 완결(Wave 6, `66b6b45`, WS1–WS4 병렬).** (1) **Desktop Main & Sidecar (`WS1`):** `ipc/renderer-broadcast.ts`(`safeSendToRenderer`/`broadcastToAllWindows`) 9개 파일 단일화, `OnlineLLMService` 스트림 abort/401/예외 래핑, `UnifiedSearchService` FTS5→`LIKE` 런타임 폴백·집계·정렬·인덱스(`started_at`/`created_at`) 보강, `rag/chunk-store.ts` 캐시 무효화·중복 `embedding` JSON 제거·손상 Float32 방어, `disk-wav-audio-sink.ts` uint32 오버플로·헤더 write 실패 fd 정리, `AdMediationEngine`/`AudioCaptureService`/`LocalLLMService`/`WindowManager` 타이머·팝업 레이스 수정, `sidecar/main.py` `UploadFile.close()`·PCM 바이트 경계·`/shutdown` 스레드 join 완료. (2) **Shared Packages & Desktop Renderer (`WS2`):** `@d3ro/i18n` `shared.ts` 및 지연 로드/언마운트 레이스 차단(`25/25`), `@d3ro/core` PII 플레이스홀더·CSV BOM/CR·타임스탬프·검색 경계값(`626/626`), `@d3ro/ui` `wave-math.ts` + 캔버스 `LinearGradient` 캐싱(`7/7`), `@d3ro/ui-native`/`api-client` 경계 가드, 렌더러 `utils/error-message.ts`·훅/컴포넌트 언마운트·타이머 정리 및 Vanilla JS 팝업 6종 `beforeunload`/DOM 안전화 완료. (3) **Mobile RN (`WS3`):** `features/shared/{service-guards,owned-cache-files}.ts`, `features/import/abort-guard.ts`, `lib/locale-speech.ts`(12개 로케일), `features/meetings/meeting-error-message.ts`로 26+ 파일 중복 가드·오류·포맷 통합, `FreeTierBanner` 슬롯 전환 시 높이 고착 수정·내구성 큐 조기 폐기 경합 차단·녹음 리스 누수·언마운트 재생/로케일 레이스 해결(Jest `98 suites / 625 tests PASS`). (4) **Web · Admin · Site · Edge · Worker · .NET (`WS4`):** Edge 20개 엔드포인트 `_shared/json-response.ts`(스트리밍 바이트 상한 포함 `readJsonBody`·`jsonResponse`) 통합 및 `account-delete`/`llm-proxy`/`payple`/`realtime-token` fail-closed 강화(Deno `270/270`), `.NET` `SttProxyService` Base64 상한 + `CancellationToken` 전파(xUnit `32/32`), Cloudflare Worker `resolveBackendTargetUrl` SSRF·타임아웃·`/worker-health` 정보 노출 차단(Deno `9/9`), 웹 `MarkdownPreview` DOM XSS/레이스·`WebPush` 재진입·`team-client` fail-closed(`42/42`), 어드민 `request-security.ts`/`detail-row.tsx`·CSRF/`ADMIN_UUID_PATTERN`/비용 검증, 사이트 `AppLoopDemo`/`rel="noopener noreferrer"` 보강 완료. 상세: [`REFACTOR_WAVE6_REPORT.md`](../REFACTOR_WAVE6_REPORT.md).
>
> Previous update: 2026-11-13 — **전 표면 성능 최적화 · 코드 위생 완결(Wave 5) · 백로그 일괄 구현 · TDD v2.0 게이트 완성.** (1) **소스·패키징 위생:** 루트 중복 `resources/sox/`(5.21 MB) 및 `apps/desktop/resources/sox/` 불필요 바이너리 10종 제거 + `electron-builder.yml` 필터 적용, 데스크톱 미구현 광고 어댑터 9종 단일화(`UNAVAILABLE_AD_NETWORK_SPECS`), `scripts/local/` 109개 및 미참조 루트 스크립트 16개 삭제 + `npm run clean:deep`(`scripts/ci/clean-deep.mjs`), `apps/mobile-rn` 루트 순환 의존성(`d3ro-voice-monorepo`)·NTFS 정션 제거, `.NET` `SttController` 무호출 중복 라우트(`GET /providers`, `POST /test`) 삭제. (2) **번들·코드 스플리팅 & 대형 모듈 분리:** `@d3ro/i18n`을 렌더러/웹 동적 로케일 청크(`index.tsx`), 무-React 동기 로더(`@d3ro/i18n/main`), 모바일 지연 엔트리(`index.native.tsx`, Metro `inlineRequires`)로 3분할하고, 데스크톱 `AppLayout.tsx`(7페이지·6모달 `React.lazy`), 모바일 `App.tsx`(`getComponent`), 웹 `MarkdownPreview`(`next/dynamic` + 조건부 `mermaid`) 스플리팅으로 데스크톱 초기 부팅 JS를 `8.79 MB` → `3.62 MB`(`-58.8%`)로 축소했으며, `SettingsModal.tsx`(`951`→`349`줄, 탭 4종 + `settings-model-helpers.ts`)와 `SuggestionService.ts`(`suggestion-policy-helpers.ts`) 순수 모듈 분리를 완료했다. (3) **데스크톱 SQLite · 프로세스 · 오디오 디스크 스트리밍:** SQLite WAL PRAGMA(`synchronous=NORMAL`, `mmap_size=64MB`, `cache_size=-16000`), FTS5 trigram 전문 검색, RAG `embedding_blob`(`Float32Array`) + `WeakMap` 캐시, `PersonalGraphService` 단일 트랜잭션, Windows `koffi` `SendInput` 일원화, 기본 모드 `mousemove`/`wheel` 훅 차단, 백그라운드 팝업 지연 생성, `LocalSTTService` 주 Whisper 모델 유휴/클라우드 언로드, 회의 녹음 PCM 디스크 스트리밍(`DiskWavAudioSink`, 메모리 상주 `O(N)→O(1)`)을 적용했다. (4) **Wave 5 계약·보안 & 기능 백로그 해소:** `@d3ro/core`에 `guards`/`csv`/`format`/`unified-search`/`admin-roles`/`ports` 6개 SSOT 모듈을 추출해 앱 간 중복을 제거하고, 클라우드 LLM·고객지원 `redactPII`/`rehydrateText` 및 녹음 폐기 시 `secureWipeAudioChunks`/`secureZeroBuffer`를 실배선했으며, 고아 키 253개를 정리한 `2,500`키 × 12개 언어를 데스크톱·웹(`LocaleSwitcher`)·모바일(온보딩/설정/계정 + Android `localeFilters` 12개, R8/`shrinkResources`) 전 표면에 노출했다. 또한 `site/` 정적·빌드 CI 게이트(`typecheck:site`/`lint:site`), 웹 `teams` 실 멤버 수 집계(`team-client.ts`), 모바일 `>=600dp` 태블릿/폴더블 반응형 레이아웃(`@d3ro/ui-native/responsive`, 10개 화면 + `FreeTierBanner` `90dp` 슬롯 예약), `meeting_memos.revision` 불변 CAS(마이그레이션 #74 `20261113000001`), 사이드카 `POST /diarize` + 데스크톱·웹·모바일 화자 배지·필터 바(`MTG-08`)를 완성했다. (5) **TDD v2.0 Phase 2~5 자동화 게이트:** `check:i18n`, `check:ds-contract`(`SegmentControl` ARIA `tablist`/`tab` + `@d3ro/ui` 테스트), `test:affected`, `release:installer:smoke`(`verify-desktop-installer-smoke.mjs`: PE64·blockmap·SHA-512·`app-update.yml`·ASAR Pickle·Ed25519 `.sig`)를 `verify:all` 및 `.forgejo/workflows/{ci,release}.yml`에 연결했다. 상세: [`REFACTOR_WAVE5_REPORT.md`](../REFACTOR_WAVE5_REPORT.md).
>
@ -37,7 +41,7 @@
> Previous update: 2026-09-22 — **Gemma/Ollama 폭주 방어 계약을 기록했다.** 19:14:12 부팅 워밍업이 `keep_alive: 30m`으로 `gemma4:e4b`를 19:44:12까지 VRAM 3,226,342,521 bytes / context 4096으로 강제 상주시킨 것이 관측됐으며, 같은 시점 Windows GPU Engine PID 표본에는 Ollama의 활성 compute가 없었다. 즉 당시 상태는 무한 추론이 아니라 강제 residency였다. 19:11:17~19:11:58의 자동 제안 연속 생성은 기존 900 ms·12/min·5 candidates·128 tokens·한 글자 재생성 정책이 허용한 burst였다. 현재 구현 계약은 부팅 warmup 제거, `keep_alive: 2m`, 제안 600 ms / 최소 5 s 간격 / 기본 6회·hard max 12회 per min / 3 candidates / 64 tokens / 12-char growth / 8 s timeout, 그리고 요청별 취소·상한·종료 정리다. 독립 표적 검증은 6 test files / 69 tests passed / 0 failed, 변경 코드·테스트 ESLint와 `git diff --check`도 exit 0이다. Raw Ollama에서는 cold bounded 요청이 client hard timeout 15.044 s에 취소된 뒤 `/api/ps`가 비었고 `/api/version`은 80 ms에 회복했다. 명시 warmup은 HTTP 200 / 16.639 s, 후속 warm 요청은 body `options.num_predict=1`, `keep_alive='2m'`로 553 ms HTTP 200 / `done:true` / `eval_count:1` / `done_reason:length`였고 `/api/ps` expiry는 약 119.9 s였다. **19:48:59 +09:00에는 새 generate/unload/kill/retry 없이 충분히 지난 뒤 한 번의 `/api/ps`가 HTTP 200 / 45.8 ms / `{models:[]}`였고 `/api/version`은 HTTP 200 / 7.3 ms / `0.32.13`이었다.** 이는 raw API 수준의 expiry 뒤 unload 확인일 뿐 앱 재시작·GUI·실제 타이핑 증거는 아니므로 상태는 `[~]`로 유지한다 (`11` GAP-LLM-04, GAP-INPUT-06).
>
> Previous update: 2026-09-21 — **Input intelligence (입력 레메트리 + 다음 문장 제안) 신규**. 데스크톱에 입력 수집기(`InputTelemetryService`), UIA 컨텍스트 브리지(사이드카 `GET /uia/focus`), 제안 서비스(`SuggestionService`), 어렛 커 오버레이, 설정 > 입력 탭(동의·정책·주간 인사이트·개인 문구)을 추가했다. 카탈로그에 `INPUT-01`~`INPUT-08`(전부 데스크톱 `[~]` — 유닛 48건은 GREEN 이지만 **실앱 타이핑 검증 전**), 백로그에 GAP-INPUT-01~05 + GAP-LLM-03, §7 에 CONSTRAINT-INPUT-01(키 내용 미저장 — ActivityWatch 정책 채택)을 기록. 설계 근거는 조사 기반이다: 어렛은 `GetGUIThreadInfo` 가 아니라 UIA `TextPattern.GetSelection`(Chromium 은 `TextPattern2` 미구현), 타이핑 스트는 키코드 복원이 아니라 UIA 스냅샷 diff(한/일 IME 대응), 디바운스/토큰 한도는 인라인 컴플리션 실측값(Continue 350 / Tabby 250 / twinny 300 ms, 출력 64~256 토큰). 의존성: `koffi` 3.3.1(포그라운드 창 FFI), 사이드카 `uiautomation` 2.0.29 + `comtypes`. 데스크톱 유닛 총계 1409(+49), Electron ABI 실행에서 신규 실패 0건. 당시의 24.7초/4.9초 지연 설명과 `keep_alive: 30m`·부팅 워밍업 처방은 **현재 상태가 아닌 과거 가설/완화 이력**이며, 최신 운영 결론은 위 2026-09-22 항목과 `11` GAP-LLM-04를 따른다. 직전: LLM instruction-prompt fix (`9c2b4d4`): the custom-instruction path inserted the instruction's own wording instead of the processed result and had **never worked in any shipped release** (`v0.1.0-alpha`..`v1.4.0`, introduced `fea923d` 2026-04-05, not a regression). `llm-prompts.ts` is now the SSOT for prompt resolution and placeholder substitution, shared by `VoiceModeService` / `ChainService` / `LLM.PROCESS`. AI-04/05/06/07 are demoted to `[~]` on desktop — fixed with unit tests, but **not verified in a running app** and the four related `tests/red/*.usecase.test.ts` could not execute (`better-sqlite3` ABI). New: GAP-LLM-01 (no target-language setting), GAP-LLM-02 (this fix unverified); GAP-INFRA-06 amended (the ABI masks verification, not just dev-env switching cost); GAP-I18N-01 amended (`popup.error.default` missing in 10 locales). Earlier the same day: CAP-16 (desktop key bindings rebuilt on one `@d3ro/core/keybinding` SSOT — multiple bindings per action, mouse buttons, `HOTKEY` → `KEYBINDING` IPC group), verified on Windows by a manual run, so CAP-16 and CAP-02 are `[x]` and GAP-KEY-01 is closed. Still open: GAP-KEY-02/03, GAP-QA-02, GAP-I18N-01/02, GAP-INFRA-06, GAP-LLM-01/02, GAP-INPUT-01~05; `11` §7 holds accepted design constraints (things deliberately kept, not gaps)
> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.16.5` (`release/product-version.json`)
> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.17.1` (`release/product-version.json`)
> Purpose: let any agent (or human) answer two questions in under a minute:
> 1. **What infrastructure exists?** (build, CI, services, APIs, data, packages, deploy)
> 2. **How far is each feature developed?** (per surface, with file anchors and status)

View file

@ -1,7 +1,7 @@
# 02 — Repository & Infrastructure Map
> Surface: whole repo
> Last updated: 2026-11-13 — Source/packaging hygiene (`clean:deep`, trimmed `apps/desktop/resources/sox`, macOS-only `@nut-tree-fork` `asarUnpack`, Android R8 + `shrinkResources` + 12-locale `localeFilters`), `@d3ro/i18n` 2,500-key split, `site/` static/build CI gate, and TDD v2.0 Phase 2–5 gates (`check:i18n`, `check:ds-contract`, `test:affected`, `release:installer:smoke`)
> Last updated: 2026-11-14 — `v1.17.1` 전 표면 운영 배포 반영(Desktop/Runtime/Portable Forgejo `200`, Supabase 74 migrations + 24 Edge Functions, Site Pages `d3ro.chanpaca.net`, Worker `d3ro-voice-api`, NAS Docker `api`/`admin`/`web`), 루트 `.dockerignore` 빌드 컨텍스트 격리(대용량 `apps/desktop/`·`scratch/`·`.chrome-*` 제외), `verify-desktop-installer-smoke.mjs` ASAR Pickle 32 MiB 헤더 판독 수정(`405ae16`)
> Source of truth for: layout, workspaces, build/test commands, CI/CD, Docker, deploy, scripts, resources
---
@ -203,7 +203,7 @@ Stages `validate → test → build → e2e → package → publish → deploy`.
| `apps/api-server/Dockerfile` | Multi-stage .NET 10 (sdk → aspnet runtime), port 5000, `VOLUME /app/data`; no longer serves static files (`wwwroot` removed — see `07-api-server.md`) |
| `apps/web/Dockerfile` | Next.js standalone runner for `@d3ro/web`, basePath `/app`, port 3002 (added 2026-09-26, Wave 3, b6fe588) |
| `docker-compose.yml` | Dev/self-host: `d3ro-api-server` (5050→5000, `./data` volume), `d3ro-admin` (3001), `d3ro-web` (3002, `@d3ro/web` basePath `/app`, Supabase/Payple keys as build args), optional `ollama` (profile `ai`, 11434) |
| `docker-compose.nas.yml` | NAS: prebuilt `d3ro-voice-api:latest` / `d3ro-voice-admin:latest` / `d3ro-voice-web:latest` (3002) / `d3ro-whisper` (faster-whisper, OpenAI-compatible). No legal-doc `wwwroot` mount and no `NEXT_PUBLIC_API_URL` — both were dropped 2026-09-26 (Wave 3, b6fe588); legal pages are served only from `site/public`. |
| `docker-compose.nas.yml` | NAS: prebuilt `d3ro-voice-api:latest` / `d3ro-voice-admin:latest` / `d3ro-voice-web:latest` (3002) / `d3ro-whisper` (faster-whisper, OpenAI-compatible). No legal-doc `wwwroot` mount and no `NEXT_PUBLIC_API_URL` — both were dropped 2026-09-26 (Wave 3, b6fe588); legal pages are served only from `site/public`. Root `.dockerignore` excludes non-web/admin directories (`apps/desktop/`, `scratch/`, browser profiles, etc.) so remote `DOCKER_HOST=ssh://...` builds of `admin`/`web` skip local release artifacts; `apps/api-server` builds with `./apps/api-server` context. |
Deploy scripts: `scripts/deploy-nas.ps1`, `scripts/deploy-nas.sh`, `scripts/nas-control.sh` (start/stop/restart/status/logs/backup/update). `scripts/deploy-site-to-nas.js` was deleted 2026-09-26 (Wave 3, cd9d199) — site deploy is Cloudflare Pages only (`.forgejo/workflows/deploy-site.yml`).
@ -243,7 +243,7 @@ Full detail: [`09-supabase-backend.md`](./09-supabase-backend.md).
| File | Purpose |
|---|---|
| `release/product-version.json` | version `1.16.5`, `androidVersionCode`/`iosBuildNumber` `1160500`, desktop license keyId |
| `release/product-version.json` | version `1.17.1`, `androidVersionCode`/`iosBuildNumber` `1170100`, desktop license keyId |
| `release/android-release-identity.json` | package `com.d3ro.voice`, Play app ID, app-signing SHA-256, upload cert SHA-256, evidence keyId, AdMob unit IDs |
| `release/desktop-license-public.pem` | Ed25519 public key for desktop offline licenses |
| `release/mobile-release-evidence-public.pem` | Ed25519 public key for mobile release evidence |

View file

@ -128,3 +128,9 @@ Apps depend on packages, never the reverse. Shared package changes ripple to all
- **`@d3ro/core` (Vitest 39 files / 626 tests PASS):** `utils/pii-redactor.ts` hardens placeholder collision avoidance, stateful regex index resets, and length-sorted single-pass `rehydrateText`; `csv.ts` adds UTF-8 BOM and `\r` line-ending escaping; `unified-search.ts`, `utils/meeting-markdown.ts`, and `meeting-transcript.ts` (reusing `formatDurationClockFromMs` and finite date guards) harden boundary inputs (`pii-redactor.test.ts` 5, `shared-utilities.test.ts` 10). Deno-synced contracts (`plan-catalog`, `web-urls`, `guards`, `admin-roles`) untouched (`contract:check` GREEN).
- **`@d3ro/i18n` (Vitest 2 files / 25 tests PASS):** extracted `src/shared.ts` (`I18nStorage`, `noopI18nStorage`, `safeLoadStoredLocale`, `safeSaveStoredLocale`, non-finite date guard) shared by `index.tsx` and `index.native.tsx`, with `cancelled`, `userChangedLocaleRef`, and `localeRevisionRef` guards blocking stale async storage loads from overwriting explicit `setLocale()` changes (`__tests__/i18n-provider.test.tsx` 10).
- **`@d3ro/ui` & `@d3ro/ui-native` & `@d3ro/api-client`:** `@d3ro/ui` extracted `src/components/ds/wave-math.ts` and cached canvas `LinearGradient` instances in `AudioVisualizerBar.tsx` and `GradientWave.tsx` (`__tests__/wave-visualizer.test.tsx` 3, Vitest 2 files / 7 tests PASS); `@d3ro/ui-native` extracted `resolveContentMaxWidth` (`responsive.tsx`) and guarded non-finite bars (`WaveBars.tsx`); `@d3ro/api-client/src/transcribe.ts` clamped negative latencies (Vitest 4 files / 31 tests PASS).
---
## 9. Wave 7 hardening (2026-11-14, `2a009e4`, post-`v1.17.1`)
- **`@d3ro/core` (Vitest 39 files / 629 tests PASS):** `araso-layout.ts` and `typo-correction.ts` refine `isUrlOrPathRun()` so `domain.tld?` / `file.ext?` URLs remain untouched while Hangul ellipsis tokens (`[가-힣ㄱ-ㆎ][!?~]*\.{2,}$`) convert without affecting `...props` (`WORD_BOUNDARY_AFTER_RE` aligned, `__tests__/typo-correction.test.ts` +3); `personal-ngram.ts` removes a redundant intermediate `Map` allocation in `PersonalNgramModel.next()`. Other shared packages hold green on integrated `main` (`@d3ro/i18n` 2/25, `@d3ro/ui` 2/7, `@d3ro/api-client` 4/31 PASS).

View file

@ -280,3 +280,5 @@ DB schema (`src/main/db/schema.ts`, drizzle SQLite): `history`, `dictionary`, `s
2026-11-02 verification: installed 1.16.0 passed the actual Electron picker→timestamped transcript→local minutes/action-item journey. Native Korean IME passed 7/7 under bounded 100% CPU and 7/7 with a direct 9.389 s `gemma4:e4b` cold-load request overlapping two typing cases. The Latin-layout control exposed next-key/backspace interleaving; source now waits 140 ms at boundaries and batches the current trailing correction region after a 650 ms pause. Full desktop 2,773 tests and production build pass. The fix was published as Windows v1.16.1 on 2026-11-04; the installed-app Latin control still needs a new GUI run. Synthetic WinForms input is not physical-keyboard/Chromium/terminal proof. [Verification evidence](../evidence/2026-11-02-verification.md).
2026-11-14 verification (Wave 6 WS1/WS2 hygiene, optimization & bug hunt): unified `safeSendToRenderer` and `broadcastToAllWindows` across 9 IPC/bootstrap modules into `src/main/ipc/renderer-broadcast.ts`; wired `OnlineLLMService` stream abort (`_abortController` in `chatStream`), `401` token reset, empty `data.text` guard, and `D3ROError` wrapping; fixed `UnifiedSearchService` `meetingTotal` double-counting, `startedAt`/`createdAt desc` sort order, runtime FTS5-to-`LIKE` fallback (`hasAllFtsTables`), and DB indexes (`idx_meeting_sessions_started_at`, `idx_meeting_memos_created_at`); exported `invalidateEmbeddedChunksCache` across `rag/chunk-store.ts`, `rag/retrieval.ts`, `sync/sync-adapters.ts`, and `db/index.ts`, cleared redundant cached `embedding` JSON strings after `Float32Array` decode, and guarded malformed Float32 buffers; added `MAX_WAV_DATA_BYTES = 0xffffffff - 36` uint32 guard and post-`openSync` fd cleanup in `disk-wav-audio-sink.ts`; closed timer/popup hide-show races across `AdMediationEngine`, `AudioCaptureService`, `LocalLLMService`, `disposeAudioHandlers`, `bootstrap.ts`, and `WindowManager.ts`; hardened `sidecar/main.py` (`UploadFile.close()`, `<2`/odd-byte PCM handling, `_watch_disconnect`, `/shutdown` `_download_thread` join). Renderer added `src/renderer/utils/error-message.ts` (`toErrorMessage`), unified meeting/pull models, guarded non-finite dates (`formatters.ts`, `UnifiedSearchPage.tsx`), cleaned unmount/sequence/timer/listener paths across pages/modals/hooks, and hardened all 6 vanilla JS popups (`beforeunload` listener/timer cleanup, `textContent = ''`, `result-popup` `prepareVersion`/`isVisible`/rAF cancel, `caption-overlay` per-line `fadeTimer`, bounds clamps). `@d3ro/desktop` Vitest **210 files / 2,865 tests PASS**, sidecar Python `unittest` **33/33 PASS**, `npm run build` + `npm run check:desktop-renderer` (`7 page(s)`) PASS; interactive Electron GUI checks remain `[~]`.
2026-11-14 verification (Wave 7 peer swarm `input-core` + `desktop-shell`, commits `2a009e4` / `fc5d453` / `3f9e412` on `main`, post-`v1.17.1`): `InputTelemetryService.ts` adds `TYPO_SETTLE_DELAY_MS` (700 ms) / `_typoSettleTimer`, `diffInsertionSpan()` for `_expectedInserts` across punctuation trimming, expired `_programmaticKeys` cleanup, and `_learnFlushTimer.unref()`; `TypoCorrectionService.ts` expands punctuation boundaries (`~…?!。`), allows boundary-terminated tokens up to `MAX_INPLACE_DELETE_CHARS` (32) in `trailingWordOnly`, and skips permanent `_markRegionChecked()` lockout on `trailingWordOnly` passes (`typo-live-punctuation.test.ts`, `TypoCorrectionService.test.ts`). Main services harden popup/lifecycle/abort paths: `WindowManager.hideResultPopup()` cancels `pendingResultShow` and resets `lastResultCursor = null` (`popup-hide-show-race.test.ts`); `CaptionService.ts` records `_captionModelId` after `ensureAuxModel`, releases stale `loadedAuxModelId`, deduplicates concurrent `stop()`/`dispose()` via `_stopPromise`, and resets per-call `AbortController` + `_refineEpoch`/`_refineRunId` (`caption-lifecycle-refine.test.ts`); `VoiceModeService.ts` / `LlmGateway.ts` / `LocalLLMService.ts` propagate `run.controller.signal`, track `/api/pull` abort controllers, prevent polling from restoring availability post-dispose, and wrap dispose aborts into `D3ROError(ErrorCode.LLM_ERROR)`; `VoiceConversationService.ts` / `AudioCaptureService.ts` / `LocalSTTService.ts` / `caption-handlers.ts` clear `_responseAbortController`, fix `'stopping'` SoX resume & `start()` `_cleanup()`, wrap STT download dispose aborts into `D3ROError(ErrorCode.STTModelDownloadCancelled)`, and fail closed with `callback({})` in `desktopCapturer.getSources`. `@d3ro/desktop` Vitest **212 files / 2,890 tests PASS**, sidecar Python `unittest` **33/33 PASS**, `npm run build` + `npm run check:desktop-renderer` (`7 page(s)`) PASS; interactive Electron GUI verification (`GAP-INPUT-08/09/10/11`) remains `[~]`.

View file

@ -61,6 +61,7 @@ Root layout: `ThemeProvider → I18nProvider → AuthProvider`.
| `command-client.ts` | Custom instruction client (types, error codes, execute) |
| `dashboard-client.ts` | Dashboard snapshot loader |
| `dictionary-client.ts` | Dictionary CRUD/pagination/search + `serializeDictionary` / `parseDictionaryFile` / `importDictionaryFile` (JSON/CSV) |
| `edge-fetch.ts` | Shared Edge invoke URL builder (`resolveSupabaseFunctionUrl`), bounded timeout signal (`createTimedAbortSignal`), and unmount check (`shouldExitAfterAwait`) (Wave 7 `2026-11-14`) |
| `history-client.ts` | History list/get/update/delete, revision-safe |
| `supabase-browser.ts` | Re-export `@d3ro/api-client/supabase-browser` |
| `supabase-server.ts` | Next `cookies()` wrapper |
@ -76,7 +77,7 @@ Root layout: `ThemeProvider → I18nProvider → AuthProvider`.
Two layers:
- **Vitest** (`apps/web/tests/`, `npm --prefix apps/web run test`, part of root `npm test`): pure-logic & SSR contracts — `billing-catalog`, `web-push` (device/RPC/rollback/reconciliation/logout, 17 cases), `web-stt-client`, `team-client` (3 cases), `locale-switcher` (3 cases), `live-transcript-speakers` (2 cases) — 6 files / 32 tests PASS.
- **Vitest** (`apps/web/tests/`, `npm --prefix apps/web run test`, part of root `npm test`): pure-logic & SSR contracts — `billing-catalog`, `web-push` (device/RPC/rollback/reconciliation/logout, 17 cases), `web-stt-client`, `team-client` (3 cases), `locale-switcher` (3 cases), `live-transcript-speakers` (2 cases), `security-and-lifecycle` (Wave 7) — **10 files / 52 tests PASS**.
- **Playwright** (`apps/web/e2e/`): `smoke.spec.ts` (unauthenticated surface + fail-closed redirects + `/download` handoff), `billing`, `payple-checkout`, `dashboard-dictionary-commands`, `history` (fixture-based browser journeys).
---
@ -91,3 +92,4 @@ Two layers:
- Teams `member_count` aggregation (`team-client.ts`), 12-locale `LocaleSwitcher` + `I18nProvider` persistence, speaker badges/filter chips on `LiveTranscriptList`, knowledge file upload, semantic search, dictionary import/export, and the team activity feed are implemented and unit-tested.
- **2026-11-04 Wave 4 hygiene:** Removed the unreferenced dashboard trend chart and the web `recharts` dependency. Web Push now has a production sidebar opt-in/out flow, stable web-device registration, device-bound register/unregister RPCs, disabled-intent reconciliation, bounded local/server cleanup, logout-independent sign-out, and a Docker-copied service worker. An isolated local browser run with ephemeral VAPID proved one active web device, one `webpush` token, one pending outbox attempt, a completed drain, and a `delivered` provider result; that result proves provider acceptance, not service-worker/browser receipt. A later production-standalone run built and served successfully but timed out during throwaway login navigation before the dashboard, so production-rendered 1440/390, accessibility-tree, hit-target, permission/subscription, and receipt gates remain open. No production secrets or deployment were changed.
- **2026-10-28 designpaca audit (`SHELL-15`):** All 15 routes and shared components aligned with `design.md` v4 ("조용한 계기"): undefined `--d3-text-inverse` replaced with `--d3-accent-ink`, minimum font size raised to `11px` (`0.6875rem`), `uppercase` and positive `letterSpacing` removed from Korean UI copy, raw `monospace` replaced with `var(--d3-font-mono)`, single `component="h1"` hierarchy enforced per route, and native form controls equipped with `:focus-visible` rings and `<label htmlFor>` / `aria-label` attributes.
- **2026-11-14 Wave 7 hardening (`c68e81e`, `4bf0f0d`, post-`v1.17.1`):** closed `/app//evil`, backslash, and control-char open redirects in `web-app-url.ts` (`safeReturnPath`) and `public/sw.js`; scrubbed OAuth callback error leakage (`auth/callback/route.ts`); centralized Edge invocation & bounded abort/unmount checks in `src/lib/edge-fetch.ts` across `chat-panel.tsx` (`executeChatSendTurn`), `action-runner.tsx`, `payple-checkout-button.tsx`, `payple-manage-button.tsx`, `generate-document-button.tsx`, `document-editor.tsx`, `invite-member-form.tsx`, and `(app)/history` routes; hardened `auth-provider.tsx` (`bindAuthSession`) and `mic-recorder.tsx` (`acquireGuardedMediaStream`). Added `tests/security-and-lifecycle.test.ts` (`@d3ro/web` Vitest **10 files / 52 tests PASS**).

View file

@ -118,7 +118,7 @@ The v4 shell also removed `DashScreen` and `WorksHubScreen`. Home replaces the d
## 6. Tests & evidence
- Jest: `npm --prefix apps/mobile-rn test` — current full tree **98 suites / 625 tests PASS** (2026-11-14 Wave 6; 2026-11-13 baseline was 89 suites / 605 tests). Coverage includes `onboarding-fresh-route.test.tsx`, `responsive-layout.test.tsx` (4/4), `meeting-detail-speakers.test.tsx` (1/1), `meetings.test.ts` (18/18 incl. `revision` CAS), meeting-import creation routing and `record-screen-redteam-r2-27.test.tsx`, plus 9 Wave 6 regression suites (`durable-queue-early-discard`, `free-tier-banner-resize`, `history-detail-unmount-regression`, `meeting-detail-unmount-regression`, `onboarding-locale-regression`, `record-permission-session-regression`, `service-guards`, `settings-locale-sync-regression`, `talk-locale-recorder-regression`). Wave 6 also consolidated shared guards/cleanup/locale-speech into `features/shared/{service-guards,owned-cache-files}.ts`, `features/import/abort-guard.ts`, `lib/locale-speech.ts`, and `features/meetings/meeting-error-message.ts`, and fixed `FreeTierBanner` slot-change height stickiness (`90dp`->`50dp`), durable queue early-discard `AbortController` registration before `FileSystem.exists`, `RecordScreen` session lease leak, `TalkScreen` 12-locale TTS tags + live greeting sync, and unmount/audio/timer/locale races on `HistoryDetail`/`Settings`/`Onboarding`/`Account`/`MeetingDetail`. The current `.3` Fold6 APK renders the MTG-13 entry/editor; device file selection→transcription→minutes E2E remains NOT_RUN.
- Jest: `npm --prefix apps/mobile-rn test` — current full tree **103 suites / 651 tests PASS** (2026-11-14 Wave 7 `bd3c1a9` / `cc3f746`, post-`v1.17.1`; Wave 6 baseline was 98 suites / 625 tests). Wave 6 added `features/shared/{service-guards,owned-cache-files}.ts`, `features/import/abort-guard.ts`, `lib/locale-speech.ts`, `features/meetings/meeting-error-message.ts`, and 9 regression suites. Wave 7 added 5 async lifecycle regression suites (`abort-and-stream-guards`, `context-lifecycle-guards`, `queue-and-history-races`, `recorder-lifecycle-races`, `screen-async-lifecycle`), hardened recorder claim/generation/poll-timer cleanup (`audio-recorder.ts`, `recorder/{nitro,android-foreground}-backend.ts`), fixed `durable-processing-queue.ts` `finishCleanupItem(item)` audio-first deletion with 60 s retry on failure plus `suspendedUsers`/`discardedItems` checks and `use-history-sync.ts` guards, added pre-abort/generation-header cancellation in `chat-service`/`admin-service`/`device-service`/`llm-stream-service`, and isolated user-switch `scopeGenerationRef` + `try/catch/finally` busy guards across 4 contexts (`mobile-ads`, `billing`, `device`, `entitlement`) and 7 screens (`Commands`, `HistoryDetail`, `Home`, `Knowledge`, `Meetings`, `Record`, `Teams`). The current `.3` Fold6 APK renders the MTG-13 entry/editor; device file selection→transcription→minutes E2E and external Play/Firebase/AdMob gates remain open.
- Maestro E2E: `apps/mobile-rn/.maestro/` + evidence in `.maestro-output/`.
- Current `.3` isolated API 34 AVD: canonical fresh auth **37 s PASS**, signup **50 s PASS**, including persistence after restart. Initial emulator failure was observed with a System UI ANR dialog; it passed after the dialog was dismissed. Both failure and retry are retained under `test-results/recovery-2026-11-01/emulator-*`. The new empty test AVD alone used `clearState`; personal Fold6 data was preserved. This does not resolve the separate Fold6 first-run failures.
- Historical `.2` Fold6 physical-device gate (Android 16, `SM-F956N`): fresh auth **60 s PASS**, fresh signup **67 s PASS**, warm/cold invite **31 s PASS**, and small-screen signup **61 s PASS** on 2026-11-01. Fatal/Metro matches 0; evidence is `apps/mobile-rn/.maestro-output/fold6-20261101-fix1/`. Authenticated parity was not run because test credentials are absent.

View file

@ -65,6 +65,7 @@ All mutations flow through `ExecuteAdminMutationAsync` (idempotent + audited).
| `AuthService` | Register (one-time SuperAdmin bootstrap only, `PasswordHasher<User>`, serialized), login (timing-safe dummy verify, inactive rejection, rehash), JWT gen (8h, claims id/email/role) |
| `LlmProxyService` | Resolve endpoint by model → fallback → Mock echo; OpenAI-style POST; parse content+usage; token cost → `ApiUsageLog`; errors → `ServerErrorLog` + fallback text |
| `SttProxyService` (~1182 lines) | Provider adapters (groq/openai/custom, deepgram, google, assemblyai, azure, local-sidecar), candidate resolution + fallback, content-type/duration detection, `SttUsageLog` cost, synthetic-tone endpoint test, CRUD with exclusive default, usage report |
| `EndpointUrlPolicy` | Upstream LLM/STT endpoint SSRF validation (`Services/EndpointUrlPolicy.cs`) paired with named `"UpstreamNoRedirect"` `HttpClient` (`AllowAutoRedirect = false`) (Wave 7) |
| `AdminOperationService` | Validates actor/idempotency key/memo, SHA-256 request hash, `Serializable` transaction, idempotent replay, before/after audit entry |
---
@ -88,7 +89,7 @@ DTOs (`Dtos/Dtos.cs`): auth, license audit, LLM, admin/model endpoints, STT (tra
## 5. Tests (`apps/api-server.Tests/`, xUnit)
`AdminAuthorizationE2ETests`, `AdminOperationServiceTests`, `AuthBootstrapControllerTests`, `AuthSecurityTests`, `SttControllerSecurityTests`, `SttFailClosedTests`, `SttGatewayAuthorizationE2ETests` (**32/32 PASS** after Wave 6 2026-11-14: enforced `MaxAudioBytes = 26 * 1024 * 1024` / `MaxBase64Length` cap in `SttProxyService.DecodeAudioBase64` before `Convert.FromBase64String`, and propagated `HttpContext.RequestAborted` `CancellationToken` across `SttController`/`LlmController`/`AdminController` → `SttProxyService`/`LlmProxyService` → EF/HTTP/AssemblyAI polling to abort paid failover immediately on client disconnect).
`AdminAuthorizationE2ETests`, `AdminOperationServiceTests`, `AuthBootstrapControllerTests`, `AuthSecurityTests`, `EndpointSecurityAndSttProxyTests`, `SttControllerSecurityTests`, `SttFailClosedTests`, `SttGatewayAuthorizationE2ETests` (**55 passed, 0 failed** after Wave 7 `c68e81e` 2026-11-14, post-`v1.17.1`; Wave 6 enforced `MaxAudioBytes = 26 * 1024 * 1024` / `MaxBase64Length` cap in `SttProxyService.DecodeAudioBase64` before `Convert.FromBase64String` and propagated `HttpContext.RequestAborted` `CancellationToken`, and Wave 7 added `Services/EndpointUrlPolicy.cs` SSRF validation, named `"UpstreamNoRedirect"` `HttpClient` with `AllowAutoRedirect = false`, and query parameter URL encoding across `AdminController`, `SttController`, `LlmProxyService`, and `SttProxyService`).
---

View file

@ -53,6 +53,7 @@
| File | Purpose |
|---|---|
| `admin-session.ts` | Session types, secret validation (≥32 bytes), strict cookie parse, `adminCookieSecure()` escape hatch |
| `admin-url-safety.ts` | Return/redirect path normalization rejecting `//evil`, backslashes, and control chars (Wave 7) |
| `security.ts` | server-only HMAC-SHA256 sign/verify, in-memory rate limit/lockout, runtime security validation |
| `admin-guard.ts` | RSC guards `requireManager`/`requireAdmin`/`requireSuperAdmin`, role helpers |
| `edge-session.ts` | Edge-runtime HMAC verify via WebCrypto (used by `proxy.ts`) |
@ -90,5 +91,6 @@ Root files: `instrumentation.ts` (startup security validation), `proxy.ts` (edge
- `/pipelines` and dashboard node/error sections render only measured data.
- Deploy: `apps/admin/Dockerfile` → GHCR + NAS compose; the duplicate root `Dockerfile.admin` was deleted 2026-09-26 (Wave 3, cd9d199) since `apps/admin/Dockerfile` is the one actually used. GitLab admin NAS deploy job disabled.
- Wave 6 hardening (2026-11-14): extracted `lib/request-security.ts` (`isSameOriginRequest`, `ADMIN_UUID_PATTERN`, byte-bounded JSON body reader) and `components/detail-row.tsx` (`Row` SSOT); hardened `logout` (`sameSite: 'strict'`, CSRF, `no-store`), `license`/`login`/`backend`/`supabase` routes, `users/[id]` & `subscriptions/[id]` (`requireManager()` + UUID `notFound()`), and client unmount/timer/`sttMemo`/non-finite or negative cost guards (`payment-history`, `checksum-copy`, `license-issuer-dialog`, `models/page.tsx`).
- Wave 7 hardening (2026-11-14, `c68e81e`, post-`v1.17.1`): added `lib/admin-url-safety.ts` + open-redirect hardening on `/auth/callback` and `/login` (scrubbing OAuth error leakage), replaced `pathname.includes('.')` bypass in `proxy.ts` with `isStaticAssetPath`, hardened `subscription-form.tsx`, and added Vitest harness (`apps/admin/vitest.config.ts`, `tests/admin-security.test.ts` — **1 file / 6 tests PASS**).
- **2026-11-04 Wave 4 hygiene:** Removed three unreferenced chart components (`dau-chart`, `feature-usage-chart`, `top-users-chart`) and the admin `recharts` dependency; no active admin route imported them.
- **2026-10-28 designpaca audit (`SHELL-15`):** `console-theme.ts` `C.dim` upgraded from `#67789e` to `#7e8eb0` (WCAG AA 4.94:1 on dark card surface), `panelSx`/`innerCoreSx`/`filterBtnSx`/`statusBadgeSx`/`primaryButtonSx` flattened (removed `backdropFilter` blur, decorative gradients, `uppercase`, and positive `letterSpacing`), 1.0:1 foreground/background token collisions (`--d3-status-successBg`, `--d3-status-dangerBg`, `--d3-tag-cyanBg`) fixed across `admin-sidebar.tsx`, `ads`, `releases`, `subscriptions`, `usage`, `users`, and `login`, sub-11px font sizes raised to `11px`, and keyboard navigation (`role="button"`, `tabIndex={0}`) + `aria-label` added to sidebar and dialog controls.

View file

@ -8,7 +8,7 @@
## 1. Supabase project (`server/supabase/`)
- `config.toml` — project_id `d3ro-voice`; local ports API 55321 / DB 55322 / Studio 55323 / local SMTP UI 55324; DB major v17; storage 50 MiB; auth `site_url` localhost:5173, redirects include `https://d3ro.chanpaca.net` and `d3ro-voice://auth-callback`; external providers Google/GitHub/Apple; per-function `verify_jwt` settings; analytics off. The mail section uses the Supabase CLI 3.x `[local_smtp]` name rather than the removed `[inbucket]` alias.
- `seed.sql`, `migrations/` (74 source files; last confirmed production state was `20260927000036`, with `20261113000001_meeting_memos_revision_cas.sql` pending production push), `functions/` (24 source functions; the 23 functions present on 2026-09-27 were redeployed that day), `functions/_shared/`, `tests/`, `deno.json`.
- `seed.sql`, `migrations/` (74 source files; pushed and confirmed synced with production `llnocwyqvhgwpdjcqqyw` on 2026-11-14 via `supabase db push --remote` and `migration list --remote`), `functions/` (all 24 source functions redeployed on 2026-11-14 via `--use-api --import-map server/supabase/functions/deno.json`), `functions/_shared/`, `tests/`, `deno.json`.
> Note: root `supabase/` contains only empty scaffolding (`.branches/`, `snippets/`). The real project lives under `server/supabase/`.
@ -65,8 +65,9 @@ Integration/E2E: content-report red e2e, content-reporting (ps1/sql), mobile pla
## 2. Cloudflare worker (`server/cloudflare-worker/`)
- `wrangler.toml` — worker `d3ro-voice-api`, compat 2024-04-01, `BACKEND_ORIGIN=http://192.168.0.39:5050`, optional custom domain route (commented).
- `src/index.ts` — CORS preflight, `/worker-health`, forwards to backend origin with `X-Forwarded-*` / `X-D3RO-Edge-Proxy` headers.
- `wrangler.toml` — worker `d3ro-voice-api`, compat 2024-04-01, `BACKEND_ORIGIN="https://d3ro.chanpaca.net"` in source (Wave 7 `c68e81e`; note live Worker `fe6d9532-0052-48f5-b62c-45c86f6aaaa5` still retains pre-Wave-7 dashboard var `http://192.168.0.39:5050` from `--keep-vars`), optional custom domain route (commented).
- `src/index.ts`, `src/origin-policy.ts`, `src/push-drain.ts` — CORS preflight, `/worker-health`, origin policy + loop guard (`508`/`503`), null-body status handling (`204`/`205`/`304`), forwards to backend origin with `X-Forwarded-*` / `X-D3RO-Edge-Proxy` headers.
- `server/cloudflare-site-bridge/` — Pages/Worker bridge hardened in Wave 7 with `508` loop guard, path smuggling `400`, and `deno.json` (`src/index.test.ts` 5/5 PASS).
Cloudflare Tunnel `kd-nas` maps public hostnames to NAS services.
@ -110,3 +111,10 @@ External gates are enumerated in `docs/v3/MOBILE_APP_COMPLETION_SSOT.md` §0/§6
- **Supabase Edge Functions (`server/supabase/functions`, Deno `270 passed | 0 failed`):** consolidated `jsonResponse`/`json` and streaming byte-bounded `readJsonBody` into `_shared/json-response.ts` across 20 Edge handlers (preserving CORS/`Cache-Control`/header contracts and failing closed with 400/413 on invalid/oversized JSON); hardened `account-delete` (`SAFE_INTERNAL_CODES`), `llm-proxy` (502 + quota refund on invalid provider JSON), `_shared/payple.ts` (`postPaypleJson` with `AbortSignal.timeout`), and `realtime-token/openai-provider.ts` (`AbortSignal.timeout`), backed by `_shared/json-response.test.ts` and tests in `payple`, `realtime-token`, `llm-proxy`, and `stt-proxy`.
- **Cloudflare Worker (`server/cloudflare-worker`, Deno `9 passed | 0 failed`):** added `resolveBackendTargetUrl` blocking `//host`/`\host` SSRF, omitted `backendOrigin` from `/worker-health`, stripped `Host`/hop-by-hop headers, set `redirect: 'manual'`, added `AbortSignal.timeout(30_000)`, sanitized 502/504 JSON responses, removed `console.log`, canceled unread `!response.ok` response bodies in `push-drain.ts`, and added 4 regression tests in `src/index.test.ts`.
---
## Wave 7 hardening (2026-11-14, `c68e81e`, post-`v1.17.1`)
- **Supabase Edge Functions (`server/supabase/functions`, Deno `273 passed | 0 failed`):** `stt-proxy/handler.ts` rejects requests whose `Content-Length` exceeds the cap with `413` before buffering; `embed-chunks/handler.ts` refunds quota only on upstream provider failures; `_shared/quota.ts` fails closed by rethrowing DB errors other than `PGRST116` (`stt-proxy/handler.test.ts`, `embed-chunks/handler.test.ts`, `_shared/quota.test.ts`).
- **Cloudflare Worker & Site Bridge (`server/cloudflare-worker`, Deno `15 passed | 0 failed`; `server/cloudflare-site-bridge`, Deno `5 passed | 0 failed`):** updated `wrangler.toml` default `BACKEND_ORIGIN` to `https://d3ro.chanpaca.net` (fixing the HTTP `403` error `1003` root cause in source; live Worker `fe6d9532-...` still holds the pre-Wave-7 dashboard var until redeployed without `--keep-vars` or updated), added `origin-policy.ts` rejecting non-HTTPS/private-IP/internal origins and proxy loops (`508`/`503`), handled null-body statuses (`204`/`205`/`304`), and applied origin validation to `push-drain.ts`; hardened `cloudflare-site-bridge` with `508` loop guard and path-smuggling `400` (`deno.json`, `src/index.test.ts`).

File diff suppressed because one or more lines are too long

View file

@ -22,7 +22,7 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res
| ID | Area | Gap | Evidence | Suggested next step |
|---|---|---|---|---|
| GAP-QA-01 | Quality | Extreme Red Team: headful end-to-end bug hunting across real desktop Electron, Web Next.js, and CI pipelines. | `red_team_log.md`, `apps/desktop/tests/e2e`, `apps/web/e2e/smoke.spec.ts` | `[x]` 2026-09-15: 18 scenarios executed, 14 defects caught and 100% resolved (infinite chunking loop DEF-008, IPC signature mismatch DEF-004, markdown editor typing rollback DEF-006, Web RSC Link serialization DEF-012, secret scanner lookahead DEF-013, etc.). All 18 scenarios GREEN with zero regressions. **2026-11-04 rework:** the red-team cycle specs were one-off bug hunts (machine screenshot paths, fixed sleeps, conditional assertions) and were replaced by 5 behavior-scoped protected journeys + a shared Electron fixture; 4 stale/duplicate feature specs, the orphaned root `tests/e2e`, and 7 ad-hoc Playwright runner scripts were deleted. Duplicates merged. New `npm run test:hygiene` gate blocks the patterns that made them meaningless. Log: `docs/tdd-red/06-repo-application.md`. |
| GAP-REL-01 | Release | Official release publication to Forgejo and active public download center deployment. | `scripts/ci/publish-forgejo-release.mjs`, `apps/web/src/app/download/page.tsx`, `site/src/sections/Download.tsx`, `apps/web/e2e/smoke.spec.ts` | `[~]` 2026-09-15: v1.1.0 release assets (`D3RO-Voice-Setup-1.1.0-x64.exe`, `.blockmap`, `latest.yml`, `update-policy.json`) published to canonical Forgejo registry and release hub. 2026-09-16: the published 1.1.0 installer carries no Authenticode signature, so it does not satisfy the release policy; product version moved to `1.2.0` and publication must come from CI with the signing gate GREEN. Download centers in `apps/web` (`/download`) and `site` (`#download`) link the canonical Forgejo feed. 2026-09-19: `1.3.7` (overlay fix) is published to the canonical updater feed (`latest.yml` = 1.3.7, 90.6MiB); the CI signing gate that blocks tag-driven publication is still unresolved, so this went out through the local updater path (GAP-REL-06). 2026-09-23: `1.5.0` published the same way (updater feed `latest.yml` = 1.5.0, installer 91.2MiB / 95,612,108 bytes, sha512 matches the local build and the feed serves it anonymously); the runtime and portable channels were republished first. |
| GAP-REL-01 | Release | Official release publication to Forgejo and active public download center deployment. | `scripts/ci/publish-forgejo-release.mjs`, `apps/web/src/app/download/page.tsx`, `site/src/sections/Download.tsx`, `apps/web/e2e/smoke.spec.ts` | `[~]` 2026-09-15: v1.1.0 release assets (`D3RO-Voice-Setup-1.1.0-x64.exe`, `.blockmap`, `latest.yml`, `update-policy.json`) published to canonical Forgejo registry and release hub. 2026-09-16: the published 1.1.0 installer carries no Authenticode signature, so it does not satisfy the release policy; product version moved to `1.2.0` and publication must come from CI with the signing gate GREEN. Download centers in `apps/web` (`/download`) and `site` (`#download`) link the canonical Forgejo feed. 2026-09-19: `1.3.7` (overlay fix) is published to the canonical updater feed (`latest.yml` = 1.3.7, 90.6MiB); the CI signing gate that blocks tag-driven publication is still unresolved, so this went out through the local updater path (GAP-REL-06). 2026-09-23: `1.5.0` published the same way (updater feed `latest.yml` = 1.5.0, installer 91.2MiB / 95,612,108 bytes, sha512 matches the local build and the feed serves it anonymously); the runtime and portable channels were republished first. **2026-11-14 (`v1.17.1`):** Desktop `1.17.1` (`6c6875b`, `D3RO-Voice-Setup-1.17.1-x64.exe` `95,294,301` bytes + Ed25519 signed `latest.yml`/`.sig`), `runtime-1.17.1`/`runtime-latest`, `portable-1.17.1`/`portable-latest`, 및 Landing `site/` (`https://d3ro.chanpaca.net/release-identity.json` = `1.17.1`/`6c6875b`)가 프로덕션에 게시됐다(단 Authenticode SmartScreen 평판 `GAP-REL-02`/`06` 및 Release #339 ~91MB 첨부 `GAP-REL-16` 예외는 유지). |
| GAP-REL-08 | Release | 다운로드 센터가 **존재하지 않는 설치 파일**을 가리켰다. `apps/web/src/lib/desktop-release.ts`와 `site/src/release.ts`의 `DESKTOP_VERSION`이 `1.2.0`에 멈춰 있어 설치 URL이 `D3RO-Voice-Setup-1.2.0-x64.exe`였고, 그 경로는 피드에서 404다(실측: 1.2.0=404, 1.3.7=206). `version:sync`가 이 두 표면을 덮지 않아 계속 어긋났다. | `scripts/ci/sync-version.mjs`, `apps/web/src/lib/desktop-release.ts`, `site/src/release.ts` | `[x]` 2026-09-19: 두 다운로드 계약 파일을 `sync-version.mjs` 대상에 추가해 버전·릴리스일이 SSOT에서 자동 반영되도록 하고, 현재 값(1.3.7 / 2026-09-19)으로 정정했다. `version:check`·typecheck·site 빌드 GREEN. |
| GAP-REL-09 | Release | 랜딩 사이트가 **재배포되지 않는다**. `deploy` 워크플로가 main push마다 실패한다. 실측 원인(run#66 로그): `site/src/sections/Hero.tsx`가 타이머 ref를 `NodeJS.Timeout`으로 타이핑해 `@types/node` 네임스페이스가 필요했고, 배포 잡은 `npm ci --prefix site`만 하므로 조상 `node_modules`의 hoisted 타입이 없어 `tsc -b`가 `TS2503: Cannot find namespace 'NodeJS'`로 실패한다. 그래서 `https://d3ro.chanpaca.net/release-identity.json`이 404다(공개 버전 검증 불가). | `.forgejo/workflows/deploy-site.yml`, `site/src/sections/Hero.tsx` | `[x]` 2026-09-19: ref를 `ReturnType<typeof setTimeout>`으로 바꿔 hoisted 타입 의존을 제거했다(격리 `--typeRoots`로 CI 조건 재현 → 수정 전 TS2503, 수정 후 clean). 같은 수정을 push하자 `deploy` run#67이 사이트 빌드를 통과해 `dist/`를 만들었고, 실패는 다음 단계(Cloudflare)로 이동했다. |
| GAP-REL-09b | Release | `d3ro.chanpaca.net`이 404였던 직접 원인: 이 Cloudflare 계정에 Pages 프로젝트 `d3ro`/`d3ro-voice`가 **존재하지 않아** 커스텀 도메인 바인딩이 없었다(빈 본문 404, `cf-ray`만 반환). Pages 커스텀 도메인은 존 DNS CNAME(`d3ro → d3ro.pages.dev`)을 요구하는데 기존 `d3ro` 레코드가 남아 있어 `CNAME record not set`으로 pending에 머물렀고, 로컬 wrangler 자격증명에는 DNS 스코프가 없다(403 Authentication error). `deploy-site.yml`은 `CF_API_TOKEN` 시크릿이 없어 마지막 게시 단계에서도 `exit 1`이다. | `server/cloudflare-site-bridge/`, `.forgejo/workflows/deploy-site.yml`, `docs/map/02-infrastructure.md` | `[x]` 2026-09-19: Pages 프로젝트 `d3ro` 생성 + `site/dist` production 배포(`d3ro.pages.dev` 200, `release-identity.json` = commit `2407f5a` / 1.3.7) + 커스텀 도메인 연결. DNS 없이 도메인을 살리기 위해 Workers 라우트 브리지(`server/cloudflare-site-bridge`, `d3ro.chanpaca.net/*` → Pages 프록시, `npx wrangler deploy`)를 배포 → 라이브 확인: `/`·`/privacy/`·`/terms/`·`/delete-account/` 200, 라이브 번들이 설치 파일명을 `1.3.7`로 계산, `/download.html` → `/#download`. 남은 정리 2건: (1) 대시보드에 CNAME을 추가한 뒤 브리지 워커 삭제, (2) CI 자동 게시를 위해 `CF_API_TOKEN`(Pages/Workers Edit) + `CF_ACCOUNT_ID`=`8e83cc130e7329c160cf2b88d6b4c20a`를 Forgejo 시크릿에 등록. **2026-09-23:** CI `deploy`(deploy-site.yml)는 `CF_API_TOKEN` 부재로 run#71까지 여전히 실패한다. 로컬 인증 wrangler(pages:write)로 `npm run build --prefix site` → release-identity 작성 → `npx wrangler pages deploy site/dist --project-name d3ro --branch main`을 수동 배포했고, 라이브 `https://d3ro.chanpaca.net/release-identity.json`이 commit `5c11ee2` / version `1.5.0`을, 라이브 번들이 설치 파일명 `D3RO-Voice-Setup-1.5.0-x64.exe`를 보고한다. 자동 게시에는 여전히 시크릿 등록이 필요하다. |
@ -33,7 +33,7 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res
| GAP-OPS-01 | Ops | NAS 운영 compose가 저장소와 어긋나 있었다(JWT 기본값 폴백, 법률 wwwroot 마운트, 필수 변수 4개 누락). | `docker-compose.nas.yml`, NAS `/volume1/docker/d3ro/.env` | `[x]` 2026-09-26: NAS `.env`에 `SUPABASE_URL`·`SUPABASE_SERVICE_ROLE_KEY`(운영 service_role)·`ADMIN_BOOTSTRAP_TOKEN`(신규)·`API_SERVER_URL` 추가, 저장소 compose로 교체 후 `docker compose up -d`. 4개 컨테이너 정상, 백업 `*.before-wave3-20260926`. |
| GAP-OPS-02 | Ops | 관리자 주소가 두 개였다(`admin.chanpaca.net`, `d3ro-admin.chanpaca.net`). `admin.d3ro.chanpaca.net`은 2단계 서브도메인이라 고급 인증서(ACM, 월 $10)가 필요하다. | Cloudflare 터널 kd-nas ingress, chanpaca.net DNS | `[x]` 2026-09-26: 사용자 결정 — 관리자 주소는 `d3ro-admin.chanpaca.net` 하나(chanpaca.net에 다른 서비스가 많다). `admin.chanpaca.net` 터널 규칙·DNS 삭제로 이름을 풀었다. ACM은 지금 구독하지 않는다. 참고: `*.kite`·`*.voice` 고급 인증서는 ACM이 꺼져 2026-11-02 만료 후 갱신되지 않는다(다른 프로젝트). |
| GAP-OPS-03 | Ops | **`payple-renew` 크론이 등록 이후 한 번도 성공하지 못했다.** Forgejo 시크릿 `SUPABASE_URL`이 로컬 Supabase 주소(`127.0.0.1:55321`)로 등록돼 매일 `curl: (7) Failed to connect`. Payple 계약 전이라 청구 대상 구독은 없다(GAP-BILL-02). | `.forgejo/workflows/payple-renew.yml`, `scripts/ci/set-forgejo-secrets.mjs` | `[~]` 2026-10-11: 시크릿을 `.env` 운영 값으로 교체, 스크립트를 `.env` 정본 동기화 + 로컬 주소 거부로 확장. 남은 확인: 다음 정기 실행(10:00 KST)이 HTTP 200인지(수동 dispatch는 실결제 경로라 보류). |
| GAP-OPS-04 | Ops | `audio-purge`가 pg_cron의 service credential을 handler 안에서 검증하는 구조인데 `config.toml`에 함수 stanza가 없어 기본 gateway JWT 검증이 먼저 요청을 거부할 수 있었다. | `server/supabase/config.toml`, `server/supabase/functions/audio-purge/{index,handler}.ts`, migration `20260929000004_audio_retention_on_delete.sql` | `[~]` 2026-11-04: `[functions.audio-purge] verify_jwt = false`를 명시하고 격리 로컬 Supabase에서 실제 경로를 검증했다. 키 없음/유효한 non-service 키는 401, service 키는 200이었고 direct drain과 `pg_cron` → Vault → `pg_net` → Edge → Storage 경로 모두 `claimed=1`, `removed=1`, `failed=0`, `completed=1`; queue/`audio_files`/`storage.objects`는 `1|1|1`→`0|0|0`이었다. **남은 경계:** 이 소스의 배포 및 운영 pg_cron/Vault/실객체 실행은 확인하지 않았다. |
| GAP-OPS-04 | Ops | `audio-purge`가 pg_cron의 service credential을 handler 안에서 검증하는 구조인데 `config.toml`에 함수 stanza가 없어 기본 gateway JWT 검증이 먼저 요청을 거부할 수 있었다. | `server/supabase/config.toml`, `server/supabase/functions/audio-purge/{index,handler}.ts`, migration `20260929000004_audio_retention_on_delete.sql` | `[~]` 2026-11-04: `[functions.audio-purge] verify_jwt = false`를 명시하고 격리 로컬 Supabase에서 실제 경로를 검증했다. 키 없음/유효한 non-service 키는 401, service 키는 200이었고 direct drain과 `pg_cron` → Vault → `pg_net` → Edge → Storage 경로 모두 `claimed=1`, `removed=1`, `failed=0`, `completed=1`; queue/`audio_files`/`storage.objects`는 `1|1|1`→`0|0|0`이었다. **2026-11-14 운영 반영:** `audio-purge` 포함 24개 Edge Function을 운영(`verify_jwt = false` `config.toml` 반영)에 재배포했으며 무인증 호출이 HTTP `401`로 거부됨을 확인했다. **남은 경계:** 운영 DB의 실제 `pg_cron`/Vault/실객체 스케줄 실행은 별도 실데이터 검증이 필요하다. |
| GAP-CI-02 | CI | `linux-builder` 러너가 노트북 한 대(`kd-desktop`)뿐이라 노트북이 꺼지면 CI·크론이 통째로 멈춘다(2026-09-29~10-09, run #128~#137 Canceled). | `.forgejo/workflows/*.yml` (`runs-on: linux-builder`) | `[ ]` 후보: 상시 켜진 NAS 러너에 `linux-builder`(또는 크론 전용) 라벨 추가, 최소한 `payple-renew`는 NAS로. |
| GAP-CI-03 | CI | 9-28부터 `ci.yml`의 데스크톱 Vitest·모바일 Jest가 테스트 전부 통과인데도 실패했다. 데스크톱: 템플릿 테스트가 결과를 실제 TextInsertService로 넣다가 nut-js(libnut)가 X 디스플레이 없음(`Could not open main display`)으로 워커를 죽임. 모바일: `knowledge-service.test.ts`가 구독의 삭제 대조 setInterval을 끄지 않아 Jest가 끝나지 않음(잡 무한 대기). | `apps/desktop/tests/setup.ts`, `apps/mobile-rn/__tests__/knowledge-service.test.ts` | `[x]` 2026-10-11: setup.ts에 nut-js 공통 목, 테스트가 unsubscribe. 러너 호스트(vd-linux)에서 데스크톱 2539/2539 exit 0, 모바일 589/589 정상 종료 확인. |
| GAP-CI-04 | CI | Forgejo build validation과 root `build:all`이 web production build를 생략했고, migration checker도 CI quality gate에 연결되지 않았다. | `.forgejo/workflows/ci.yml`, `scripts/ci/build-all.mjs`, `scripts/ci/check-supabase-migrations.mjs` | `[x]` 2026-11-04: web production build를 두 경로에 추가하고 CI quality에서 `check:migrations:test` → `check:migrations`를 실행한다. CI 자체는 73개 파일의 naming/order/metadata 검사다. 같은 날 별도 격리 로컬 스택에서 empty/reset replay 73/73과 `pg-delta --strict-coverage` shadow diff 0을 확인했지만, 이 runtime gate는 아직 CI에 자동화되지 않았고 linked remote drift도 확인하지 않았다. |
@ -69,7 +69,7 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res
| GAP-MTG-02 | Meetings | Speaker diarization only partially done on desktop; absent web/mobile. | `apps/desktop/sidecar/main.py` (`POST /diarize`), `MeetingModeService.ts`, `packages/core/src/meeting-transcript.ts`, `apps/desktop/src/renderer/components/meeting/{TranscriptTab,EditableSegment}.tsx`, `apps/web/src/components/meetings/live-transcript-list.tsx`, `apps/mobile-rn/src/screens/MeetingDetailScreen.tsx` | `[~]` **2026-11-13 전 표면 구현·테스트 완료:** 사이드카 `POST /diarize`(`pyannote.audio` 설치 시 자동 사용 + 무의존 에너지 VAD 화자 교대 분할 폴백, Python 30/30 PASS)를 `LocalSTTService.sidecarBaseUrl`로 `MeetingModeService._diarizeTranscript`(LLM 추정 폴백 및 `stripInventedMarkers({ allowSpeakerMarkers })` 포함)에 연결하고, `@d3ro/core/meeting-transcript` 화자 목록/필터 유틸과 화자 배지·다중 화자 필터 칩을 데스크톱·웹·모바일 상세 화면 전부에 구현했다(코어 13/13, 데스크톱·웹·모바일 테스트 전수 PASS; 실음성 다중 화자 데스크톱 GUI 확인 전까지 `[~]`). |
| GAP-MTG-03 | Meetings | Existing recordings could become plain transcription history, but not a meeting with linked audio and minutes. | desktop `MeetingModeService`, `meeting/imported-recording.ts`, `meeting-mode-handlers.ts`; mobile `MeetingsScreen` → `RecordScreen`; MTG-13 | `[~]` 2026-11-02: installed Windows 1.16.0 passed native picker→timestamped transcript→local summary/action item with a real WAV (`2026-11-02-verification.md`). Desktop GUI gate is complete; authenticated Android picker→upload→transcript→minutes on Fold6 remains. |
| GAP-MTG-04 | Meetings | Learned typing vocabulary never reached meeting transcription: STT used a hardcoded Korean hint, refine had no glossary, refined lines stopped inside `CaptionService`, and the stored transcript was raw segments. | `packages/core/src/transcript-correction.ts`, `apps/desktop/src/main/services/TranscriptGlossaryService.ts`, `CaptionService.ts`, `meeting/MeetingRecordingSession.ts`, `MeetingModeService.ts`, `FileTranscriptionService.ts`, `VoiceModeService.ts`; MTG-14 | `[~]` 2026-11-05: one glossary SSOT wired into caption, meeting, file transcription and dictation; refined lines now propagate to the meeting transcript and renderer (`meetingMode:segmentUpdated`). **Direct measurement against the real local database** (`users/_local/d3ro.db`: 1,952 learned phrases / 2,522 typing samples / 3 meeting transcripts) exposed that the first cut also rewrote ordinary Korean (286 of 3,005 words: 하면→라면, 이제→이게, 매일→메일, 정보→정도), and v1.16.3 restricts deterministic correction to dictionary pronunciations plus typed Latin identifiers — re-measured **0 of 3,005**. Real-engine check with the local sidecar (`large-v3-turbo`): a Korean TTS fixture containing the user term transcribes as 하람로그에 with no hint and haramlog에 with the learned hint; a dictionary pronunciation entry maps 디에로 → D3RO. Hangul-layout artifacts (dkssudgktpdy) are excluded from the hint. Evidence: `packages/core/__tests__/transcript-correction.test.ts` 16/16, `apps/desktop/tests/main/services/transcript-glossary.test.ts` 10/10, core 589/589, desktop offline suite, workspace typecheck, touched-file ESLint, `test:hygiene`. **Remaining:** a live meeting with real names/jargon by voice, and a packaged-install check of the new IPC event. |
| GAP-REL-16 | Release | Forgejo release-page asset attachment for the ~91 MB installer times out through Cloudflare (HTTP 524), although the package registry upload and the signed manifest succeed. | `scripts/ci/publish-forgejo-release.mjs`, `scripts/ci/lib/immutable-package-guard.mjs` | `[~]` 2026-11-06: reproduced on v1.16.2, v1.16.3 and v1.16.4. Each time the registry artifacts, `latest.yml`, `latest.yml.sig` and the public signed-manifest verification completed, so installed apps can update; only the human-facing release page has no attached binaries for those tags. To retry only this step, check out the tag detached (`git checkout v1.16.4`) before `npm run release -- --resume`; the resume path requires HEAD to equal the tag. |
| GAP-REL-16 | Release | Forgejo release-page asset attachment for the ~91 MB installer times out through Cloudflare (HTTP 524), although the package registry upload and the signed manifest succeed. | `scripts/ci/publish-forgejo-release.mjs`, `scripts/ci/lib/immutable-package-guard.mjs` | `[~]` 2026-11-06: reproduced on v1.16.2, v1.16.3 and v1.16.4. **2026-11-14 (`v1.17.1`):** `v1.17.1` (`6c6875b`) also reproduced `write ECONNRESET` at Human Release #339 asset attachment due to Cloudflare ~91 MB proxy limit, while Forgejo generic registry (`1.17.1/latest.yml`, `.sig`, `latest/latest.yml`, `runtime-1.17.1`, `portable-1.17.1`) and public signed-manifest verification completed with HTTP `200`, so installed apps can auto-update cleanly. To retry only this step locally without Cloudflare proxy timeout or check detached tag: check out `v1.17.1` before `npm run release -- --resume`. |
| GAP-INFRA-01 | Build | `apps/mobile-rn` is outside npm workspaces, so root `typecheck`/`test`/`lint` skip it. `typecheck:mobile`/`lint:mobile`/`test:mobile`/`verify:all` root scripts added 2026-09-13 (`package.json`), but membership/CI integration is still open. | `package.json`, `.forgejo/workflows/ci.yml`, `.gitlab-ci.yml` | `[x]` 2026-10-30: React Native Metro/Gradle 네이티브 오토링킹 격리를 위해 `apps/mobile-rn`은 독립 `node_modules`로 유지하고, 루트 `verify:all` 및 `.forgejo/workflows/ci.yml`·`.gitlab-ci.yml`의 `mobile-quality` 잡이 모바일 `lint`·`typecheck`·`test:ci`를 필수 게이트로 실행하도록 정본화했다. **2026-11-04:** root `test:mobile`도 watch-capable 기본 Jest가 아니라 mobile `test:ci`(`jest --runInBand`)를 호출하도록 고정했다. |
| GAP-MOB-01 | Legacy | `apps/mobile` Expo skeleton duplicated auth/data code and got version-sync edits. | SSOT G-002 | `[x]` 2026-09-13: deleted `apps/mobile`, removed from `sync-version.mjs` and `package-lock.json`; `version:check` GREEN. |
| GAP-INFRA-02 | CI | GitLab admin NAS deploy job is disabled; admin deploy is manual/GHCR. | `.gitlab-ci.yml`, `docs/deployment/nas-deploy-runbook.md` | `[x]` 2026-10-30: 임시 CI DinD 데몬만 바꾸던 구 잡 대신 `docker-compose.nas.yml` 기반의 정본 배포·헬스체크·롤백 절차를 `docs/deployment/nas-deploy-runbook.md`로 문서화하고 `.gitlab-ci.yml` 및 `02-infrastructure.md`에 연결했다. |
@ -126,7 +126,7 @@ Legend: `[ ]` open · `[~]` in progress · `[!]` blocked externally · `[x]` res
| GAP-SYNC-05 | Sync | **Not yet in production.** Migration `20260927000034` is applied only to the local stack; the rewritten desktop sync ships with the next desktop release. Until the migration is deployed, desktop tombstone pulls and template RPCs fail against production (they are isolated per step, other entities keep syncing). | migration file, `apps/desktop/src/main/services/sync/` | `[~]` 2026-09-27: production `supabase db push` applied `0029`–`0035` (backup dump taken first; see GAP-OPS-01), all 23 Edge Functions redeployed, v1.7.0 published (runtime/portable first, then the updater feed) and installed on the owner PC. **Remaining:** the desktop on that PC is in local mode — one Google sign-in in Settings > Cloud, then edit/delete on the phone and confirm the desktop updates within seconds and appears under Devices. |
| GAP-SYNC-06 | Sync | Still desktop-local (not mirrored): knowledge base (desktop local RAG embeddings vs cloud pgvector — different embedding spaces), audio (desktop WAV files vs mobile Storage uploads), `user_settings` (locale, auto-polish, active command), desktop preset-command prompt edits, meeting `transcripts` segments (desktop uses `raw_transcript`, which mobile also fills). | `docs/map/10-feature-catalog.md` MEM-09/MEM-05/SHELL rows | `[x]` 2026-09-27: knowledge docs sync as source text and are re-embedded per surface; recordings upload to the mobile storage contract (≤50 MiB per file, opt-out toggle) and remote recordings play through signed URLs; `user_settings` maps the shared fields. 2026-09-27 (later): the two items first left out are done too — meeting `transcripts` segments are rebuilt from the desktop transcript (the phone renders segments before `edited_transcript`, so desktop edits were invisible there) and preset prompt edits reach the phone through `sync_set_builtin_instruction_prompt_v1` (migration `0036`, production applied; `tests/main/sync/SyncTranscriptsPresets.test.ts` (4) + local-stack integration case "전사 구간·프리셋"). Evidence: `tests/main/sync/SyncExtensions.test.ts` (9) + integration case "지식 문서·설정·녹음" against the local Supabase stack. |
| GAP-SYNC-07 | Sync | `sync_tombstones` grows without a schedule. `prune_sync_tombstones_v1(interval)` (service_role) exists; nothing calls it. | migration §1 | `[x]` 2026-09-27: migration `0035` enables `pg_cron` and schedules `prune-sync-tombstones` daily at 03:17 UTC (production `cron.job` active=true). A client whose cursor is older than 180 days must fall back to a full resync. |
| GAP-SYNC-08 | Sync | Meeting memo conflict detection compares mutable content plus timestamp/creation fields instead of an immutable revision. An A→B→A edit can return to the same compared values and evade stale-client detection; the shared `MeetingMemo` type has no `updated_at` or revision field. | `server/supabase/migrations/20261113000001_meeting_memos_revision_cas.sql`, `packages/api-client/src/types.ts` `MeetingMemo`, `apps/mobile-rn/src/features/meetings/meetings-service.ts`, `apps/desktop/src/main/{db/schema.ts,services/sync/sync-adapters.ts}` | `[~]` **2026-11-13 마이그레이션·클라이언트·단위 검증 완료:** 74번째 마이그레이션 `20261113000001_meeting_memos_revision_cas.sql`로 `meeting_memos.revision integer not null default 1 check (revision >= 1)` 및 단조 증가 트리거 `bump_meeting_memo_revision`을 추가하고, `@d3ro/api-client`, 모바일 `updateMeetingMemoConflictSafe`/`deleteMeetingMemoConflictSafe`(단조 `revision` 우선 CAS로 `A→B→A` 회피 차단, 구 스키마 폴백 유지), 데스크톱 SQLite `meeting_memos.revision`·`sync-adapters.ts`를 모두 갱신했다(`check:migrations` 74개 GREEN, 모바일 `meetings.test.ts` 18/18·데스크톱 `SyncEngine.test.ts` 20/20 PASS). 남은 단계: 운영 DB `supabase db push` 반영. |
| GAP-SYNC-08 | Sync | Meeting memo conflict detection compares mutable content plus timestamp/creation fields instead of an immutable revision. An A→B→A edit can return to the same compared values and evade stale-client detection; the shared `MeetingMemo` type has no `updated_at` or revision field. | `server/supabase/migrations/20261113000001_meeting_memos_revision_cas.sql`, `packages/api-client/src/types.ts` `MeetingMemo`, `apps/mobile-rn/src/features/meetings/meetings-service.ts`, `apps/desktop/src/main/{db/schema.ts,services/sync/sync-adapters.ts}` | `[x]` **2026-11-13 마이그레이션·클라이언트·단위 검증 완료 → 2026-11-14 운영 DB 반영:** 74번째 마이그레이션 `20261113000001_meeting_memos_revision_cas.sql`로 `meeting_memos.revision integer not null default 1 check (revision >= 1)` 및 단조 증가 트리거 `bump_meeting_memo_revision`을 추가하고, `@d3ro/api-client`, 모바일 `updateMeetingMemoConflictSafe`/`deleteMeetingMemoConflictSafe`(단조 `revision` 우선 CAS로 `A→B→A` 회피 차단, 구 스키마 폴백 유지), 데스크톱 SQLite `meeting_memos.revision`·`sync-adapters.ts`를 모두 갱신했다(`check:migrations` 74개 GREEN, 모바일 `meetings.test.ts` 18/18·데스크톱 `SyncEngine.test.ts` 20/20 PASS). **2026-11-14:** 운영 Supabase `supabase db push --remote`로 21개 보류 마이그레이션(`20260927000037`~`20261113000001`)을 반영하고 `supabase migration list --remote`에서 전체 74개 로컬=원격 일치를 확인했으며 데스크톱 `v1.17.1`도 함께 게시했다. |
| GAP-OPS-01 | Ops | **Production Supabase was five migrations behind** (`0029` content reporting, `0030` profile column ACL — users could raise their own `role`/`tier` through PostgREST, `0031` audit-log actor unlink, `0032` meeting-document reporting, `0033` team activity feed) and `content-report` was never deployed, while the map listed those features GREEN from local runs. Most functions still ran the 2026-08-21 build. | `server/supabase/migrations/`, `scripts/ci/check-supabase-migrations.mjs` | `[x]` 2026-09-27: schema+data dump taken, `db push` applied `0029`–`0035`, all functions redeployed (unauthenticated calls return 401, i.e. live and gated); `authenticated` can no longer UPDATE `profiles.tier`; real-account export returns exactly the v1 keys. **2026-11-04 boundary:** file checker는 73개 파일의 self-test/order/name/duplicate/non-empty만 다룬다. 별도 격리 로컬 stack의 empty/reset replay와 `pg-delta` shadow diff는 통과했지만 linked remote migration state/drift는 재검증하지 않았다. |
| GAP-STT-01 | Cloud STT | A 5 s phone recording took ~66 s and ended on the phone's tiny local model (2026-09-27). Chain: the gateway's first endpoint (laptop GPU 192.168.0.227) is off (3 s), the NAS CPU Whisper (2 cores, load ~7) needs 30–90 s for 3 s of audio, and `stt-proxy` waited up to 60 s for the gateway. The direct OpenAI fallback **never worked**: the production `OPENAI_API_KEY` secret is not a valid header value (invisible/non-ASCII characters — `TypeError: headers … not a valid ByteString`), and whisper-1 `verbose_json` reports the language by name, which the result contract rejected. The same key backs `embed-chunks`, `search-knowledge` and `realtime-token`. | `server/supabase/functions/{stt-proxy,_shared/stt-contract.ts,_shared/provider-key.ts}` | `[!]` 2026-09-27 code fixed and deployed: gateway wait = 5 s + clip length (max 30 s) when a direct provider exists, provider language names mapped to codes, keys stripped of BOM/zero-width characters (still-invalid keys count as not configured), fail-closed responses list per-provider failures (`attempts`). **External:** re-enter a valid `OPENAI_API_KEY` (or add `GROQ_API_KEY`) in Supabase function secrets, or keep the GPU endpoint online; until then cloud STT runs on the NAS CPU (~30 s for a short clip). |
@ -309,3 +309,14 @@ Evidence: [2026-11-02 verification](../evidence/2026-11-02-verification.md).
- **Mobile RN (`WS3`):** `features/shared/{service-guards,owned-cache-files}.ts` 외 3개 SSOT 통합, `FreeTierBanner` 리사이즈 높이 고착·내구성 큐 조기 폐기 경합·녹음 리스 누수·TTS 12로케일·언마운트 재생/로케일 레이스 수정 및 9개 회귀 스위트 추가(`98 suites / 625 tests PASS`).
- **Web · Admin · Site · Edge · Worker · .NET (`WS4`):** Edge `_shared/json-response.ts` 20개 엔드포인트 통합 및 fail-closed(`Deno 270/270`), `.NET` `SttProxyService` Base64 26MB 상한 + `CancellationToken` 전파(`xUnit 32/32`), Cloudflare Worker `resolveBackendTargetUrl` SSRF·타임아웃 차단(`Deno 9/9`), 웹 `MarkdownPreview` DOM XSS/레이스·`WebPush` 재진입·`team-client` fail-closed(`42/42`), 어드민 `request-security.ts`/`detail-row.tsx`·CSRF/비용 검증, 사이트 `AppLoopDemo`/`rel="noopener noreferrer"` 보강.
- **정량 게이트 및 경계 유지:** `verify:all`, `contract:check`, `check:migrations`(74), `version:check`(1.16.5), `security:secrets`, `test:metrics:write`(`docs/tdd-red/metrics/2026-11-14.md`) GREEN. Electron 실GUI(`Ctrl+K`/오버레이), Fold6/iOS 실기기 Maestro·TalkBack, 외부 자격증명/운영 `db push` `[~]`/`[!]`/`RED` 경계는 변경 없이 유지. 상세: [`docs/REFACTOR_WAVE6_REPORT.md`](../REFACTOR_WAVE6_REPORT.md).
---
## 2026-11-14 — Wave 7 다중 세션 피어 스웜 코드 위생 · 최적화 · 버그 헌팅 (`2a009e4..cc3f746`, post-`v1.17.1`)
- `[x]` **Wave 7 6-세션 네이티브 스웜(`monitor`, `input-core`, `desktop-shell`, `mobile-app`, `cloud-surfaces`, `verifier`) 통합 및 검증 완료:**
- **Input Core (`2a009e4`):** 문장부호 직후 무공백 영타 오타(`?` / 한글 말줄임표) 누락 4중 원인 수정(`TYPO_SETTLE_DELAY_MS` 700ms, `diffInsertionSpan()`, `trailingWordOnly` 32자·영구 잠금 해제, `isUrlOrPathRun()` URL/코드 보존 + 한글 말줄임표 허용, `PersonalNgramModel.next()` 중복 복사 제거; `typo-live-punctuation.test.ts` 추가).
- **Desktop Shell (`fc5d453`, `3f9e412`):** `WindowManager` 팝업 숨김 타이머/커서 초기화, `CaptionService` 보조모델/중복 stop/epoch 리셋, `VoiceModeService`/`LlmGateway`/`LocalLLMService` signal 전파 및 `/api/pull` dispose `D3ROError(LLM_ERROR)` 래핑, `LocalSTTService` 모델 다운로드 dispose `D3ROError(STTModelDownloadCancelled)` 래핑, `VoiceConversationService`/`AudioCaptureService`/`caption-handlers.ts` fail-closed 정리(`@d3ro/desktop` Vitest **212 files / 2,890 tests PASS**, Python sidecar `33/33 PASS`, `electron-vite build` + `check:desktop-renderer` **7 page(s)** PASS).
- **Mobile RN (`bd3c1a9`, `cc3f746`):** 레코더 claim/generation/pollTimer, 내구성 큐 `finishCleanupItem(item)`(파일 선삭제+60초 실패 재시도) 및 `suspendedUsers`/`discardedItems`, `chat`/`admin`/`device`/`llm-stream` abort/세대 헤더 가드, 4개 컨텍스트 및 7개 화면 `scopeGenerationRef`+`try/catch/finally` 적용 + 신규 스위트 5종(**103 suites / 651 tests PASS**).
- **Cloud Surfaces (`c68e81e`, `4bf0f0d`):** Cloudflare Worker `BACKEND_ORIGIN` `https://d3ro.chanpaca.net`·`origin-policy.ts`·`push-drain.ts`(`Deno 15/15`), `cloudflare-site-bridge` loop/path 가드(`Deno 5/5`), `.NET` `EndpointUrlPolicy.cs`+`"UpstreamNoRedirect"`(`xUnit 55/55`), Edge `stt-proxy` 413 선차단·`embed-chunks` 환불 경계·`_shared/quota.ts` fail-closed(`Deno 273/273`), Web `edge-fetch.ts`·`safeReturnPath`·`sw.js`·OAuth callback·`chat-panel`/`auth-provider`/`mic-recorder`(`10 files / 52 tests PASS`), Admin `admin-url-safety.ts`·`proxy.ts`·Vitest 도입(`1 file / 6 tests PASS`).
- **유지된 경계 (`[~]` / `[!]` / `RED`):** Wave 7 코드는 `v1.17.1` 운영 배포(`6c6875b`) 이후 `main`에 통합되었으므로 실운영 바이너리·컨테이너 및 라이브 Worker(`fe6d9532-...`, 대시보드 `BACKEND_ORIGIN = http://192.168.0.39:5050` 잔존 -> `1003`/`403`)에는 아직 미반영. Electron 실GUI(`GAP-INPUT-08/09/10/11`), Fold6/iOS 실기기/TalkBack, `EXT-*` 스토어 게이트는 변동 없이 유지. 상세: [`docs/REFACTOR_WAVE7_REPORT.md`](../REFACTOR_WAVE7_REPORT.md).

View file

@ -7,9 +7,9 @@
| 항목 | 값 |
|---|---|
| 테스트 파일 | 445 |
| 테스트 케이스 | 3655 |
| 단정(expect/assert) | 9549 |
| 테스트 파일 | 454 |
| 테스트 케이스 | 3738 |
| 단정(expect/assert) | 9828 |
| 약한 단정 (toBeDefined/toBeTruthy/toBeFalsy/toBeNull) | 128 |
| 시간·난수 직접 호출 (ambient) | 203 |
| skip/todo | 3 |
@ -20,16 +20,16 @@
| 스위트 | 파일 | 케이스 | 단정 | 약한 단정 | ambient |
|---|---:|---:|---:|---:|---:|
| 데스크톱 (Vitest) | 224 | 2135 | 5397 | 88 | 164 |
| packages/core (Vitest) | 39 | 568 | 1325 | 14 | 3 |
| 데스크톱 (Vitest) | 226 | 2160 | 5487 | 88 | 164 |
| packages/core (Vitest) | 39 | 571 | 1335 | 14 | 3 |
| packages/i18n (Vitest) | 2 | 10 | 31 | 0 | 0 |
| packages/ui (Vitest) | 2 | 7 | 30 | 0 | 0 |
| packages/api-client (Vitest) | 4 | 31 | 47 | 3 | 0 |
| 웹 (Vitest + Playwright) | 14 | 64 | 250 | 9 | 5 |
| 모바일 (Jest) | 106 | 535 | 1720 | 14 | 24 |
| Supabase Edge (Deno) | 45 | 270 | 647 | 0 | 7 |
| Cloudflare Worker (Deno) | 2 | 9 | 26 | 0 | 0 |
| API 서버 (xUnit) | 7 | 26 | 76 | 0 | 0 |
| 웹 (Vitest + Playwright) | 15 | 74 | 306 | 9 | 5 |
| 모바일 (Jest) | 111 | 561 | 1814 | 14 | 24 |
| Supabase Edge (Deno) | 45 | 273 | 654 | 0 | 7 |
| Cloudflare Worker (Deno) | 2 | 15 | 34 | 0 | 0 |
| API 서버 (xUnit) | 8 | 36 | 90 | 0 | 0 |
## 약한 단정 상위 파일

View file

@ -369,7 +369,8 @@
| Mobile lint | `npm --prefix apps/mobile-rn run lint` | GREEN, warning/error 0 (`--max-warnings=0`) | `apps/mobile-rn/.eslintrc.js`, `package.json` | 2026-08-21 |
| Mobile typecheck | `npm --prefix apps/mobile-rn run typecheck` | GREEN | `apps/mobile-rn/tsconfig.json` | 2026-08-21 |
| Historical mobile unit | `npm --prefix apps/mobile-rn test` | 당시 전체 통합 tree 57 suites / 353 tests GREEN; 현재 tree 수치가 아님 | `apps/mobile-rn/__tests__` | 2026-08-24 |
| Current mobile unit | `npm --prefix apps/mobile-rn test` | 전체 tree **98 suites / 625 tests PASS** (2026-11-14 Wave 6; 2026-11-13 89/605 대비 +9 suites / +20 tests). 온보딩 목적지 순서, H-017 회의 생성→녹음 파일 import→durable meeting pipeline, 12개 로케일 전환(`mobile-i18n-locales.test.tsx`), `>=600dp` 태블릿 반응형(`responsive-layout.test.tsx`), `meeting_memos.revision` CAS 및 화자 필터(`meetings.test.ts` 18/18), Wave 6 SSOT 가드·언마운트/큐/배너 회귀를 고정하고 lint/typecheck도 GREEN | `apps/mobile-rn/__tests__/{onboarding-fresh-route,meeting-creation-screen,record-screen-redteam-r2-27,mobile-i18n-locales,responsive-layout,meetings,service-guards,free-tier-banner-resize,durable-queue-early-discard,record-permission-session-regression,talk-locale-recorder-regression,history-detail-unmount-regression,meeting-detail-unmount-regression,settings-locale-sync-regression,onboarding-locale-regression}.test.ts(x)` | 2026-11-14 |
| Current mobile unit | `npm --prefix apps/mobile-rn test` | 전체 tree **103 suites / 651 tests PASS** (2026-11-14 Wave 7 `bd3c1a9`/`cc3f746`, post-`v1.17.1`; Wave 6 98/625 대비 +5 suites / +26 tests). 온보딩 목적지 순서, H-017 회의 생성→녹음 파일 import→durable meeting pipeline, 12개 로케일 전환(`mobile-i18n-locales.test.tsx`), `>=600dp` 태블릿 반응형(`responsive-layout.test.tsx`), `meeting_memos.revision` CAS 및 화자 필터(`meetings.test.ts` 18/18), Wave 6 SSOT 가드·언마운트/큐/배너 회귀 및 Wave 7 레코더/큐/스트림/컨텍스트/화면 비동기 수명주기 가드 5개 스위트를 고정하고 lint/typecheck도 GREEN | `apps/mobile-rn/__tests__/{onboarding-fresh-route,meeting-creation-screen,record-screen-redteam-r2-27,mobile-i18n-locales,responsive-layout,meetings,service-guards,free-tier-banner-resize,durable-queue-early-discard,record-permission-session-regression,talk-locale-recorder-regression,history-detail-unmount-regression,meeting-detail-unmount-regression,settings-locale-sync-regression,onboarding-locale-regression,abort-and-stream-guards,context-lifecycle-guards,queue-and-history-races,recorder-lifecycle-races,screen-async-lifecycle}.test.ts(x)` | 2026-11-14 |
| 2026-11-14 Wave 7 async lifecycle hardening | `typecheck:mobile`, `lint:mobile`, `test:mobile`, `test:hygiene`, `test:quality` | `audio-recorder.ts`·`recorder/{nitro,android-foreground}-backend.ts` `pendingClaim`/generation/`pollTimer` 정리, `durable-processing-queue.ts` `finishCleanupItem(item)`(오디오 선삭제 + 실패 시 60초 재시도) 및 `suspendedUsers`/`discardedItems` 가드, `use-history-sync.ts` 요청/스코프 가드, `chat`/`admin`/`device`/`llm-stream` pre-abort 및 세대 헤더 취소, 4개 컨텍스트(`mobile-ads`/`billing`/`device`/`entitlement`)·7개 화면(`Commands`/`HistoryDetail`/`Home`/`Knowledge`/`Meetings`/`Record`/`Teams`) 계정 전환 `scopeGenerationRef`+`try/catch/finally` 가드 및 5개 회귀 스위트 추가(**103 suites / 651 tests PASS**; 실기기/first-run/production 경계는 미검증 유지) | `apps/mobile-rn/src/lib/{audio-recorder,billing-context,device-context,entitlement-context,mobile-ads-context}.ts(x)`, `apps/mobile-rn/src/features/recording/durable-processing-queue.ts`, `apps/mobile-rn/src/features/history/use-history-sync.ts`, `apps/mobile-rn/src/screens/{Commands,HistoryDetail,Home,Knowledge,Meetings,Record,Teams}Screen.tsx` | 2026-11-14 |
| 2026-11-14 Wave 6 hygiene, SSOT & lifecycle fixes | `typecheck:mobile`, `lint:mobile`, `test:mobile`, `test:hygiene`, `test:quality`, `check:design` | `features/shared/{service-guards,owned-cache-files}.ts`, `features/import/abort-guard.ts`, `lib/locale-speech.ts`(12개 로케일), `features/meetings/meeting-error-message.ts`로 26+ 파일 중복 가드·오류·시간 포맷 통합, `FreeTierBanner` 슬롯 전환 시 높이 고착(`90dp`->`50dp`)·`durable-processing-queue` 조기 폐기 경합·`RecordScreen` 리스 누수·`TalkScreen` TTS 로케일·언마운트/로케일 레이스 수정 및 9개 회귀 스위트 추가(**98 suites / 625 tests PASS**; 실기기/first-run/production 경계는 미검증 유지) | `apps/mobile-rn/src/features/shared/{service-guards,owned-cache-files}.ts`, `apps/mobile-rn/src/features/import/abort-guard.ts`, `apps/mobile-rn/src/lib/locale-speech.ts`, `apps/mobile-rn/src/features/meetings/meeting-error-message.ts`, `apps/mobile-rn/src/components/FreeTierBanner.tsx`, `apps/mobile-rn/src/features/import/durable-processing-queue.ts` | 2026-11-14 |
| 2026-11-13 bundle, R8, 12-locale & tablet hygiene | `typecheck:mobile`, `lint:mobile`, `test:mobile`, `release:mobile:build-config:test` | 루트 순환 의존성(`d3ro-voice-monorepo`)·NTFS 정션 제거, `App.tsx` `getComponent` + Metro `inlineRequires`, `@d3ro/i18n` `index.native.tsx` 12개 로케일 + 온보딩/설정/계정 선택기, `@d3ro/ui-native/responsive` 10개 화면 대화면 대응, Android R8(`enableProguardInReleaseBuilds=true`) + `shrinkResources` + 12개 로케일 `localeFilters` 및 `proguard-rules.pro` 반영; 당시 모든 모바일 소스 게이트 및 **89 suites / 605 tests GREEN** (실제 release APK/AAB 및 Fold6 `open`/`closed` 실기기 눈 확인은 대기) | `apps/mobile-rn/{App.tsx,metro.config.js,package.json}`, `apps/mobile-rn/android/app/{build.gradle,proguard-rules.pro}`, `packages/i18n/src/index.native.tsx`, `packages/ui-native/src/responsive.tsx`, `scripts/ci/verify-mobile-build-config.mjs` | 2026-11-13 |
| Current local runtime APK | metadata + SHA-256 + installed identity + Build Tools 37 verifier | `.3` / `2026110103`, 147158575 B, SHA-256 `937d2a0b3fb6b810516f07e91dd97ffe99d34c5885a72f21805a51e8a408027f`; local E2E artifact, production 아님. import entry/editor 실기 표시 확인; 저장·전사·회의록은 미검증 | `test-results/recovery-2026-11-01/android-artifact.json`, `mobile-import.xml`, `mobile-import.png` | 2026-11-01 |

View file

@ -734,4 +734,27 @@ describe('Araso 급 한/영 자동 전환 · 합성어 · 잔류 Shift · URL
expect(applyAll('윈도우ㅐㄴ ')).toBe('윈도우OS ')
expect(applyAll('새ㅁㅔㅑ를 ')).toBe('새API를 ')
})
it('detectTypos_한글말줄임표뒤영타_한글로복원하고코드전개와파일확장자는보존한다', () => {
expect(applyAll('상황 잘 지켜보는중...dbrlgkrhdlTwlsdksgwl?')).toBe(
'상황 잘 지켜보는중...유기하고있진않지?'
)
expect(applyAll('어떻게해..dlrj?')).toBe('어떻게해..이거?')
expect(applyAll('파일.tsx?raw')).toBe('파일.tsx?raw')
expect(applyAll('...props')).toBe('...props')
expect(applyAll('return ...opts')).toBe('return ...opts')
})
it('detectTypos_URL쿼리스트링뒤영타_변환하지않는다', () => {
expect(applyAll('상황 잘 지켜보는중?dbrlgkrhdlTwlsdksgwl?')).toBe(
'상황 잘 지켜보는중?유기하고있진않지?'
)
expect(applyAll('example.com?dbrlgkrhdlTwlsdksgwl')).toBe('example.com?dbrlgkrhdlTwlsdksgwl')
expect(applyAll('site.kr?dbrlgkrhdlTwlsdksgwl')).toBe('site.kr?dbrlgkrhdlTwlsdksgwl')
})
it('detectTypos_물결표및전각부호경계오타_영문과한글모두복원한다', () => {
expect(applyAll('상황 잘 지켜보는중~ㅗ디ㅣㅐ~')).toBe('상황 잘 지켜보는중~hello~')
expect(applyAll('지금 어디야?dbrlgkrhdlTwlsdksgwl?')).toBe('지금 어디야?유기하고있진않지?')
})
})

View file

@ -947,11 +947,11 @@ export function isUrlOrPathRun(prefix: string, tokenStart: number, tokenEnd: num
if (run.includes('://')) return true
if (/^(?:www\.|~\/|\.\/|\.\.\/|localhost:)/iu.test(run)) return true
if ((run.match(/\//gu)?.length ?? 0) >= 2) return true
if (/[A-Za-z0-9]\.[A-Za-z]{2,}\//u.test(run)) return true
if (/[A-Za-z0-9]\.[A-Za-z]{2,}[/?]/u.test(run)) return true
if (/[A-Za-z0-9._+-]@[A-Za-z0-9]/u.test(run)) return true
if (/[\\_$#`<>{}=]/u.test(run)) return true
// 토큰 바로 앞이나 뒤가 도메인 점(example.com)인 경우 (단, L.A.fh 처럼 대문자 약어 뒤 조사는 허용)
// 토큰 바로 앞이나 뒤가 도메인 점(example.com)인 경우 (단, L.A.fh 처럼 대문자 약어 뒤 조사와 한글 말줄임표(...) 뒤 한영 오타는 허용)
const before = prefix[tokenStart - 1] ?? ''
const after = prefix[tokenEnd] ?? ''
if (after === '.' && /[A-Za-z]/u.test(prefix[tokenEnd + 1] ?? '')) return true
@ -959,7 +959,8 @@ export function isUrlOrPathRun(prefix: string, tokenStart: number, tokenEnd: num
const beforeDot = prefix.slice(runStart, tokenStart)
const tokenText = prefix.slice(tokenStart, tokenEnd)
const isAbbrevWithParticle = /^(?:[A-Z]\.){2,}$/u.test(beforeDot) && PARTICLE_KEYS.has(tokenText)
if (!isAbbrevWithParticle) return true
const isHangulEllipsis = /[가-힣ㄱ-ㆎ][!?~]*\.{2,}$/u.test(beforeDot)
if (!isAbbrevWithParticle && !isHangulEllipsis) return true
}
if (before === ':' || after === ':') {
const beforeColon = prefix.slice(runStart, tokenStart)

View file

@ -169,8 +169,7 @@ export class PersonalNgramModel {
const extends_ = (word: string) => word.length > partial.length && word.startsWith(partial)
first = context.length > 0 ? this._next(context, extends_, passes) : null
if (!first) {
const unigram = new Map([...this._unigram].filter(([word]) => extends_(word)))
const pick = best(unigram, () => true)
const pick = best(this._unigram, extends_)
first = passes(pick) ? pick : null
}
joint = 'attach'

View file

@ -2024,6 +2024,8 @@ function resolveTokenAsEnglishPreview(tokenText: string): string | null {
return null
}
const WORD_BOUNDARY_AFTER_RE = /[ \t.,!?;:~…?!。]/u
/**
* 커서 앞 구간에서 결정적으로 확실한 오타를 찾는다.
*
@ -2120,7 +2122,7 @@ export function detectTypos(prefix: string, options: TypoDetectOptions = {}): Ty
afterEnglishWord,
nextIsEnglish,
nextEnglishWord,
hasWordBoundaryAfter: /[ \t.,!?;:]/u.test(after),
hasWordBoundaryAfter: WORD_BOUNDARY_AFTER_RE.test(after),
vocabulary: options.vocabulary
})
@ -2199,7 +2201,7 @@ export function detectTypos(prefix: string, options: TypoDetectOptions = {}): Ty
!options.terminalMode &&
/^(?:self|selves)$/iu.test(token.text) &&
index > 0 &&
(/[ \t.,!?;:]/u.test(after) || !options.layoutOnly)
(WORD_BOUNDARY_AFTER_RE.test(after) || !options.layoutOnly)
) {
const prevToken = tokens[index - 1]
if (

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