diff --git a/.claude/skills/refactor-wave/SKILL.md b/.claude/skills/refactor-wave/SKILL.md index 116ecd7a..d2758a01 100644 --- a/.claude/skills/refactor-wave/SKILL.md +++ b/.claude/skills/refactor-wave/SKILL.md @@ -226,7 +226,6 @@ 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 | `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 6 | 2026-11-14 | 워킹 트리 (미커밋) | `docs/REFACTOR_WAVE6_REPORT.md` | 다음 wave 추가 시 본 표 갱신. diff --git a/.dockerignore b/.dockerignore index 5f06e54c..23fef26f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -30,31 +30,3 @@ 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/ diff --git a/apps/admin/package.json b/apps/admin/package.json index 4378a306..169d37fa 100644 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -7,8 +7,7 @@ "dev": "next dev --port 3001", "build": "next build", "start": "next start --port 3001", - "typecheck": "next typegen && tsc --noEmit", - "test": "vitest run" + "typecheck": "next typegen && tsc --noEmit" }, "dependencies": { "@d3ro/api-client": "*", diff --git a/apps/admin/src/app/auth/callback/route.ts b/apps/admin/src/app/auth/callback/route.ts index 329cc08b..2b3935ab 100644 --- a/apps/admin/src/app/auth/callback/route.ts +++ b/apps/admin/src/app/auth/callback/route.ts @@ -3,33 +3,21 @@ 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 { - const { searchParams } = new URL(request.url) - const origin = resolveAdminCallbackOrigin( - request.url, - process.env.ADMIN_PUBLIC_ORIGIN ?? process.env.NEXT_PUBLIC_ADMIN_ORIGIN, - ) + const { searchParams, origin } = new URL(request.url) 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( - supabaseUrl, - supabaseAnonKey, + process.env.NEXT_PUBLIC_SUPABASE_URL ?? '', + process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '', { cookies: { getAll() { @@ -45,11 +33,11 @@ export async function GET(request: NextRequest): Promise { const { error } = await supabase.auth.exchangeCodeForSession(code) if (error) { - return NextResponse.redirect(`${origin}/login?error=oauth_callback_failed`) + return NextResponse.redirect(`${origin}/login?error=${encodeURIComponent(error.message)}`) } // 세션 교환 성공 후 response 생성 + 수집된 쿠키 적용 - const response = NextResponse.redirect(`${origin}${nextPath}`) + const response = NextResponse.redirect(`${origin}/`) for (const { name, value, options } of cookiesToSet) { response.cookies.set({ name, value, ...options }) } diff --git a/apps/admin/src/app/login/page.tsx b/apps/admin/src/app/login/page.tsx index 85c7a083..358a7d2e 100644 --- a/apps/admin/src/app/login/page.tsx +++ b/apps/admin/src/app/login/page.tsx @@ -9,14 +9,13 @@ 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 = safeAdminRedirectPath(searchParams.get('redirect')) + const redirectPath = searchParams.get('redirect') || '/' const [usernameOrEmail, setUsernameOrEmail] = useState('') const [password, setPassword] = useState('') diff --git a/apps/admin/src/components/subscription-form.tsx b/apps/admin/src/components/subscription-form.tsx index 14950f63..30c134ca 100644 --- a/apps/admin/src/components/subscription-form.tsx +++ b/apps/admin/src/components/subscription-form.tsx @@ -3,7 +3,7 @@ // apps/admin/src/components/subscription-form.tsx // 구독 생성/수정 공용 폼 -import { useEffect, useRef, useState } from 'react' +import { useState } from 'react' import { Box, TextField, @@ -17,7 +17,6 @@ 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' @@ -45,24 +44,10 @@ export function SubscriptionForm({ mode, userId, initial, onSuccess }: Subscript const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const [success, setSuccess] = useState(false) - const mountedRef = useRef(true) - - useEffect(() => { - mountedRef.current = true - return () => { - mountedRef.current = false - } - }, []) const handleSubmit = async (): Promise => { if (!memo.trim()) return - const parsedEnd = parseOptionalIsoDate(periodEnd) - if (!parsedEnd.ok) { - setError(parsedEnd.message) - return - } - setLoading(true) setError(null) setSuccess(false) @@ -75,36 +60,31 @@ export function SubscriptionForm({ mode, userId, initial, onSuccess }: Subscript userId, tier, status, - currentPeriodEnd: parsedEnd.iso, + currentPeriodEnd: periodEnd ? new Date(periodEnd).toISOString() : undefined, adminNote: adminNote || undefined, memo: memo.trim(), }), }) } else { - await callAdminApi(`admin-subscriptions?userId=${encodeURIComponent(userId)}`, { + await callAdminApi(`admin-subscriptions?userId=${userId}`, { method: 'PATCH', body: JSON.stringify({ tier, status, - currentPeriodEnd: parsedEnd.iso, + currentPeriodEnd: periodEnd ? new Date(periodEnd).toISOString() : undefined, 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') - } + setError(err instanceof Error ? err.message : 'Operation failed') } finally { - if (mountedRef.current) { - setLoading(false) - } + setLoading(false) } } diff --git a/apps/admin/src/lib/admin-url-safety.ts b/apps/admin/src/lib/admin-url-safety.ts deleted file mode 100644 index 8aeda856..00000000 --- a/apps/admin/src/lib/admin-url-safety.ts +++ /dev/null @@ -1,70 +0,0 @@ -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() } -} diff --git a/apps/admin/src/proxy.ts b/apps/admin/src/proxy.ts index ea2323a1..bfa80846 100644 --- a/apps/admin/src/proxy.ts +++ b/apps/admin/src/proxy.ts @@ -1,7 +1,6 @@ // 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 = [ @@ -16,15 +15,15 @@ const PUBLIC_PATHS = [ export async function proxy(request: NextRequest): Promise { const { pathname } = request.nextUrl const isPublic = PUBLIC_PATHS.some((path) => pathname === path || pathname.startsWith(path + '/')) - const isStatic = isStaticAssetPath(pathname) + const isStatic = + pathname.startsWith('/_next') || pathname.startsWith('/static') || pathname.includes('.') 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) - const safeRedirect = safeAdminRedirectPath(pathname) - if (safeRedirect !== '/') loginUrl.searchParams.set('redirect', safeRedirect) + if (pathname !== '/') loginUrl.searchParams.set('redirect', pathname) const redirectResponse = NextResponse.redirect(loginUrl) addSecurityHeaders(redirectResponse) return redirectResponse diff --git a/apps/admin/tests/admin-security.test.ts b/apps/admin/tests/admin-security.test.ts deleted file mode 100644 index 60d08987..00000000 --- a/apps/admin/tests/admin-security.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -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') - }) -}) diff --git a/apps/admin/vitest.config.ts b/apps/admin/vitest.config.ts deleted file mode 100644 index 9638defc..00000000 --- a/apps/admin/vitest.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -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, - }, -}) diff --git a/apps/api-server.Tests/EndpointSecurityAndSttProxyTests.cs b/apps/api-server.Tests/EndpointSecurityAndSttProxyTests.cs deleted file mode 100644 index 2c72afc3..00000000 --- a/apps/api-server.Tests/EndpointSecurityAndSttProxyTests.cs +++ /dev/null @@ -1,507 +0,0 @@ -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(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(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(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(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(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(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(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(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(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(() => - 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(() => - 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 CapturedRequests { get; } - - private ApiHarness( - SqliteConnection connection, - AppDbContext db, - AdminController adminController, - SttProxyService sttService, - LlmProxyService llmService, - List 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 CreateAsync(Func? responder = null) - { - var connection = new SqliteConnection("DataSource=:memory:"); - await connection.OpenAsync(); - var options = new DbContextOptionsBuilder() - .UseSqlite(connection) - .Options; - var db = new AppDbContext(options); - await db.Database.EnsureCreatedAsync(); - - var captured = new List(); - var handler = new CaptureHandler(captured, responder); - var httpFactory = new FixedHttpClientFactory(handler); - - var sttService = new SttProxyService(db, httpFactory, NullLogger.Instance); - var llmService = new LlmProxyService(db, httpFactory, NullLogger.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 _captured; - private readonly Func? _responder; - - public CaptureHandler(List captured, Func? responder) - { - _captured = captured; - _responder = responder; - } - - protected override Task 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); - } - } -} diff --git a/apps/api-server/Controllers/AdminController.cs b/apps/api-server/Controllers/AdminController.cs index d8ab7a50..aee54ad2 100644 --- a/apps/api-server/Controllers/AdminController.cs +++ b/apps/api-server/Controllers/AdminController.cs @@ -105,8 +105,7 @@ public class AdminController : ControllerBase public async Task CreateEndpoint([FromBody] CreateModelEndpointDto dto) { if (string.IsNullOrWhiteSpace(dto.ModelId) || string.IsNullOrWhiteSpace(dto.ModelName) - || string.IsNullOrWhiteSpace(dto.Provider) - || !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForLlmProvider(dto.Provider)) + || string.IsNullOrWhiteSpace(dto.Provider) || !IsValidEndpointUrl(dto.EndpointUrl) || dto.CostPer1kPromptTokens < 0 || dto.CostPer1kCompletionTokens < 0) { return BadRequest(new { message = "모델 식별자, 공급자, 유효한 HTTP(S) URL과 0 이상의 비용이 필요합니다." }); @@ -146,8 +145,7 @@ public class AdminController : ControllerBase public async Task UpdateEndpoint(int id, [FromBody] UpdateModelEndpointDto dto) { if (id <= 0 || string.IsNullOrWhiteSpace(dto.ModelName) || string.IsNullOrWhiteSpace(dto.Provider) - || !EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, EndpointUrlPolicy.AllowsLoopbackForLlmProvider(dto.Provider)) - || dto.CostPer1kPromptTokens < 0 || dto.CostPer1kCompletionTokens < 0) + || !IsValidEndpointUrl(dto.EndpointUrl) || dto.CostPer1kPromptTokens < 0 || dto.CostPer1kCompletionTokens < 0) return BadRequest(new { message = "유효한 모델 엔드포인트 값이 필요합니다." }); return await ExecuteAdminMutationAsync( @@ -221,10 +219,7 @@ public class AdminController : ControllerBase [Authorize(Policy = "AdminOrAbove")] public async Task CreateSttEndpoint([FromBody] CreateSttEndpointDto dto) { - 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) + if (string.IsNullOrWhiteSpace(dto.Name) || !IsValidEndpointUrl(dto.EndpointUrl) || dto.CostPerMinute < 0 || dto.CostPerSecond < 0 || dto.FallbackPriority < 1) { return BadRequest(new { message = "유효한 STT 이름, HTTP(S) URL, 비용, 우선순위가 필요합니다." }); @@ -244,10 +239,7 @@ public class AdminController : ControllerBase [Authorize(Policy = "AdminOrAbove")] public async Task UpdateSttEndpoint(int id, [FromBody] UpdateSttEndpointDto dto) { - 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) + if (id <= 0 || string.IsNullOrWhiteSpace(dto.Name) || !IsValidEndpointUrl(dto.EndpointUrl) || dto.CostPerMinute < 0 || dto.CostPerSecond < 0 || dto.FallbackPriority < 1) return BadRequest(new { message = "유효한 STT 엔드포인트 값이 필요합니다." }); @@ -319,8 +311,7 @@ public class AdminController : ControllerBase [Authorize(Policy = "AdminOrAbove")] public async Task TestSttDirect([FromBody] DirectSttTestDto dto) { - if (!EndpointUrlPolicy.IsValidEndpointUrl(dto.EndpointUrl, allowLoopback: false) - || !Uri.TryCreate(dto.EndpointUrl, UriKind.Absolute, out var endpointUri)) + if (!IsValidEndpointUrl(dto.EndpointUrl) || !Uri.TryCreate(dto.EndpointUrl, UriKind.Absolute, out var endpointUri)) { return BadRequest(new { message = "유효한 HTTP(S) Endpoint URL이 필요합니다." }); } @@ -441,6 +432,13 @@ 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 ExecuteAdminMutationAsync( string operation, object request, diff --git a/apps/api-server/Controllers/SttController.cs b/apps/api-server/Controllers/SttController.cs index 7e346a10..90b9aae7 100644 --- a/apps/api-server/Controllers/SttController.cs +++ b/apps/api-server/Controllers/SttController.cs @@ -101,9 +101,9 @@ public class SttController : ControllerBase { return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "stt_provider_unavailable" }); } - catch (ArgumentException ex) + catch (ArgumentException) { - return BadRequest(new { error = ex.ParamName == "language" ? "invalid_language" : "invalid_audio" }); + return BadRequest(new { error = "invalid_audio" }); } catch { diff --git a/apps/api-server/Program.cs b/apps/api-server/Program.cs index a1404637..31a0ed2a 100644 --- a/apps/api-server/Program.cs +++ b/apps/api-server/Program.cs @@ -16,11 +16,6 @@ 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 => { diff --git a/apps/api-server/Services/EndpointUrlPolicy.cs b/apps/api-server/Services/EndpointUrlPolicy.cs deleted file mode 100644 index 9199d55e..00000000 --- a/apps/api-server/Services/EndpointUrlPolicy.cs +++ /dev/null @@ -1,174 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; -using System.Text.RegularExpressions; - -namespace D3ROVoice.Api.Services; - -/// -/// 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. -/// -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; - } -} diff --git a/apps/api-server/Services/LlmProxyService.cs b/apps/api-server/Services/LlmProxyService.cs index fb8707e7..000156ba 100644 --- a/apps/api-server/Services/LlmProxyService.cs +++ b/apps/api-server/Services/LlmProxyService.cs @@ -73,14 +73,7 @@ public class LlmProxyService : ILlmProxyService { try { - 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"); + using var client = _httpClientFactory.CreateClient(); client.Timeout = TimeSpan.FromSeconds(60); var payload = new @@ -100,10 +93,9 @@ public class LlmProxyService : ILlmProxyService Content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json") }; - var trimmedKey = endpoint.ApiKey?.Trim(); - if (!string.IsNullOrWhiteSpace(trimmedKey)) + if (!string.IsNullOrWhiteSpace(endpoint.ApiKey)) { - httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", trimmedKey); + httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey); } using var httpResponse = await client.SendAsync(httpRequest, cancellationToken); diff --git a/apps/api-server/Services/SttProxyService.cs b/apps/api-server/Services/SttProxyService.cs index e5dbc677..aa4bc3aa 100644 --- a/apps/api-server/Services/SttProxyService.cs +++ b/apps/api-server/Services/SttProxyService.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; @@ -83,15 +82,6 @@ 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) @@ -306,18 +296,11 @@ public class SttProxyService : ISttProxyService CancellationToken cancellationToken ) { - 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"); + using var client = _httpClientFactory.CreateClient(); client.Timeout = TimeSpan.FromSeconds(90); - var apiKey = GetTrimmedApiKey(endpoint); + var providerType = endpoint.ProviderType.ToLowerInvariant(); + var apiKey = endpoint.ApiKey?.Trim() ?? ""; if (RequiresApiKey(providerType) && string.IsNullOrWhiteSpace(apiKey)) { @@ -377,8 +360,8 @@ public class SttProxyService : ISttProxyService form.Add(new StringContent(endpoint.ModelId), "model"); - var language = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko"); - if (language != "auto") + var language = request.Language ?? endpoint.Language ?? "ko"; + if (!string.IsNullOrWhiteSpace(language) && language != "auto") { form.Add(new StringContent(language), "language"); } @@ -390,8 +373,7 @@ public class SttProxyService : ISttProxyService } var temp = request.Temperature ?? endpoint.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(temp.ToString("0.0")), "temperature"); form.Add(new StringContent("verbose_json"), "response_format"); using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) @@ -399,10 +381,9 @@ public class SttProxyService : ISttProxyService Content = form }; - var apiKey = GetTrimmedApiKey(endpoint); - if (!string.IsNullOrWhiteSpace(apiKey)) + if (!string.IsNullOrWhiteSpace(endpoint.ApiKey)) { - httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); + httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey); } ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson); @@ -442,11 +423,12 @@ public class SttProxyService : ISttProxyService CancellationToken cancellationToken ) { - var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko"); - var model = string.IsNullOrWhiteSpace(endpoint.ModelId) ? "nova-3" : endpoint.ModelId.Trim(); + var lang = request.Language ?? endpoint.Language ?? "ko"; + var model = endpoint.ModelId ?? "nova-3"; var baseUrl = endpoint.EndpointUrl.TrimEnd('/'); - var separator = baseUrl.Contains('?', StringComparison.Ordinal) ? "&" : "?"; - var url = $"{baseUrl}{separator}model={Uri.EscapeDataString(model)}&language={Uri.EscapeDataString(lang)}&smart_format=true&punctuate=true"; + var url = baseUrl.Contains("?") + ? $"{baseUrl}&model={model}&language={lang}&smart_format=true&punctuate=true" + : $"{baseUrl}?model={model}&language={lang}&smart_format=true&punctuate=true"; using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url) { @@ -454,10 +436,9 @@ public class SttProxyService : ISttProxyService }; httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); - var apiKey = GetTrimmedApiKey(endpoint); - if (!string.IsNullOrWhiteSpace(apiKey)) + if (!string.IsNullOrWhiteSpace(endpoint.ApiKey)) { - httpRequest.Headers.Add("Authorization", $"Token {apiKey}"); + httpRequest.Headers.Add("Authorization", $"Token {endpoint.ApiKey}"); } ApplyExtraHeaders(httpRequest, endpoint.ExtraHeadersJson); @@ -503,12 +484,13 @@ public class SttProxyService : ISttProxyService ) { var base64Audio = Convert.ToBase64String(audioBytes); - var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko"); - var apiKey = GetTrimmedApiKey(endpoint); + var lang = request.Language ?? endpoint.Language ?? "ko"; // 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[] @@ -561,6 +543,8 @@ public class SttProxyService : ISttProxyService else { // Google Cloud Speech-to-Text v1 + var apiKey = endpoint.ApiKey; + var gcpPayload = new { config = new @@ -622,25 +606,20 @@ 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", apiKey); + uploadRequest.Headers.Add("Authorization", endpoint.ApiKey); var uploadBody = await SendForStringAsync(client, uploadRequest, cancellationToken); using var uploadDoc = JsonDocument.Parse(uploadBody); - var uploadUrl = uploadDoc.RootElement.GetProperty("upload_url").GetString(); - if (!EndpointUrlPolicy.IsValidEndpointUrl(uploadUrl, allowLoopback: false)) - { - throw new JsonException("AssemblyAI returned an invalid upload URL."); - } + var uploadUrl = uploadDoc.RootElement.GetProperty("upload_url").GetString()!; // 2. Submit transcript job - var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko"); + var lang = request.Language ?? endpoint.Language ?? "ko"; var transcriptPayload = new { audio_url = uploadUrl, @@ -653,24 +632,19 @@ public class SttProxyService : ISttProxyService { Content = new StringContent(JsonSerializer.Serialize(transcriptPayload), Encoding.UTF8, "application/json") }; - transRequest.Headers.Add("Authorization", apiKey); + transRequest.Headers.Add("Authorization", endpoint.ApiKey); var transBody = await SendForStringAsync(client, transRequest, cancellationToken); using var transDoc = JsonDocument.Parse(transBody); - 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()); + var id = transDoc.RootElement.GetProperty("id").GetString()!; // 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/{safeId}"); - pollReq.Headers.Add("Authorization", apiKey); + using var pollReq = new HttpRequestMessage(HttpMethod.Get, $"https://api.assemblyai.com/v2/transcript/{id}"); + pollReq.Headers.Add("Authorization", endpoint.ApiKey); var pollBody = await SendForStringAsync(client, pollReq, cancellationToken); @@ -709,11 +683,12 @@ public class SttProxyService : ISttProxyService CancellationToken cancellationToken ) { - var lang = ResolveValidatedLanguage(request.Language, endpoint.Language, "ko-KR"); + var lang = request.Language ?? endpoint.Language ?? "ko-KR"; if (lang == "ko") lang = "ko-KR"; - var separator = endpoint.EndpointUrl.Contains('?', StringComparison.Ordinal) ? "&" : "?"; - var url = $"{endpoint.EndpointUrl}{separator}language={Uri.EscapeDataString(lang)}&format=detailed"; + var url = endpoint.EndpointUrl.Contains("?") + ? $"{endpoint.EndpointUrl}&language={lang}&format=detailed" + : $"{endpoint.EndpointUrl}?language={lang}&format=detailed"; using var httpRequest = new HttpRequestMessage(HttpMethod.Post, url) { @@ -721,10 +696,9 @@ public class SttProxyService : ISttProxyService }; httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType.Contains("wav") ? "audio/wav" : "audio/webm"); - var apiKey = GetTrimmedApiKey(endpoint); - if (!string.IsNullOrWhiteSpace(apiKey)) + if (!string.IsNullOrWhiteSpace(endpoint.ApiKey)) { - httpRequest.Headers.Add("Ocp-Apim-Subscription-Key", apiKey); + httpRequest.Headers.Add("Ocp-Apim-Subscription-Key", endpoint.ApiKey); } var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken); @@ -772,17 +746,16 @@ public class SttProxyService : ISttProxyService form.Add(audioContent, "file", fileName); form.Add(new StringContent(endpoint.ModelId), "model"); - form.Add(new StringContent(ResolveValidatedLanguage(request.Language, endpoint.Language, "ko")), "language"); + form.Add(new StringContent(request.Language ?? endpoint.Language ?? "ko"), "language"); using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint.EndpointUrl) { Content = form }; - var apiKey = GetTrimmedApiKey(endpoint); - if (!string.IsNullOrWhiteSpace(apiKey)) + if (!string.IsNullOrWhiteSpace(endpoint.ApiKey)) { - httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); + httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.ApiKey); } var responseBody = await SendForStringAsync(client, httpRequest, cancellationToken); @@ -1088,17 +1061,6 @@ 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; diff --git a/apps/desktop/src/main/ipc/caption-handlers.ts b/apps/desktop/src/main/ipc/caption-handlers.ts index fa10cce0..c4c71e06 100644 --- a/apps/desktop/src/main/ipc/caption-handlers.ts +++ b/apps/desktop/src/main/ipc/caption-handlers.ts @@ -5,7 +5,6 @@ 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, @@ -14,8 +13,6 @@ import { startCaptionOverlayDrag } from '../windows/WindowManager' -const logger = getLogger('CaptionHandlers') - export function registerCaptionHandlers(): void { // ── 자막 창 손잡이 (팝업 → 메인) ── ipcMain.on(IPC_CHANNELS.POPUP_CAPTION.SET_INTERACTIVE, (_event, interactive: unknown) => { @@ -28,19 +25,12 @@ 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)}`, - ) + const sources = await desktopCapturer.getSources({ types: ['screen'] }) + if (sources.length === 0) { callback({}) + return } + callback({ video: sources[0], audio: 'loopback' }) }) return ipcSuccess(undefined) }) diff --git a/apps/desktop/src/main/services/AudioCaptureService.ts b/apps/desktop/src/main/services/AudioCaptureService.ts index 75bcfa65..e1cfc916 100644 --- a/apps/desktop/src/main/services/AudioCaptureService.ts +++ b/apps/desktop/src/main/services/AudioCaptureService.ts @@ -94,7 +94,6 @@ 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 | null = null /** 새 SoX 를 띄울 때마다 증가 — 임대(lease)가 자기 캡처인지 판단한다 */ @@ -156,21 +155,15 @@ 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' + this._state = 'capturing' + this._refCount = 1 + this._startLevelTimer() + logger.debug('Pending stop cancelled by a new consumer — capture continues') + return } if (this._state !== 'idle' && this._state !== 'error') { @@ -209,7 +202,6 @@ 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) @@ -230,18 +222,11 @@ 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( @@ -253,7 +238,6 @@ 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' @@ -280,7 +264,6 @@ 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, @@ -643,19 +626,11 @@ 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() diff --git a/apps/desktop/src/main/services/CaptionService.ts b/apps/desktop/src/main/services/CaptionService.ts index 489d0b21..c4ec7d13 100644 --- a/apps/desktop/src/main/services/CaptionService.ts +++ b/apps/desktop/src/main/services/CaptionService.ts @@ -128,10 +128,6 @@ 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 | null = null /** 이번 세션이 잡은 오디오 소스(마이크 캡처·시스템 소리 요청) — 해제는 멱등 */ private _audio: CaptionAudioSources = this._createAudioSources() @@ -193,9 +189,6 @@ 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 가 있으면 띄우지 않는다 @@ -211,13 +204,9 @@ class CaptionService extends EventEmitter { await sttService.initialize() assertCurrent() // 자막 전용 모델을 골랐으면 받아쓰기 모델과 별도로 올려 둔다(보조 자리). - const candidateAuxModelId = configGet('captionSttModelId') ?? null - if (candidateAuxModelId) { - await sttService.ensureAuxModel(candidateAuxModelId) - loadedAuxModelId = candidateAuxModelId - } + this._captionModelId = configGet('captionSttModelId') ?? null + if (this._captionModelId) await sttService.ensureAuxModel(this._captionModelId) assertCurrent() - this._captionModelId = loadedAuxModelId // 세션 초기화 this._sessionId = crypto.randomUUID() @@ -272,9 +261,7 @@ class CaptionService extends EventEmitter { // 이 시도가 연 자원만 돌려준다(release 는 멱등). await ownAudio?.release() // stop() 이 내릴 때 아직 로딩 중이던 보조 모델이 뒤늦게 올라왔을 수 있다. 새 시작이 없을 때만 내린다. - if (loadedAuxModelId && (this._state === 'inactive' || this._state === 'stopping')) { - void getLocalSTTService().releaseAuxModel() - } + if (this._captionModelId && this._state === 'inactive') void getLocalSTTService().releaseAuxModel() logger.info('캡션 시작 취소: 로딩 중 정지됨') throw new D3ROError(ErrorCode.CaptionStartFailed, '캡션 시작이 취소되었습니다') } @@ -287,9 +274,7 @@ class CaptionService extends EventEmitter { await this._audio.release() this._hideOverlaySafely() // 시작 실패(오디오 장치 없음 등)에도 올려 둔 보조 모델을 내린다 — 안 그러면 다음 세션 종료까지 VRAM 을 잡는다. - const auxToRelease = this._captionModelId ?? loadedAuxModelId - this._captionModelId = null - if (auxToRelease) void getLocalSTTService().releaseAuxModel() + if (this._captionModelId) void getLocalSTTService().releaseAuxModel() this._session = { ...DEFAULT_START_OPTIONS } this._setState('inactive') const d3roErr = @@ -314,13 +299,6 @@ class CaptionService extends EventEmitter { * @returns 세션 요약(세그먼트가 없으면 null), 다른 소유자라 거부했으면 false */ async stop(owner?: CaptionOwner): Promise { - 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 @@ -333,14 +311,7 @@ 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 { // 타이머 정리 if (this._tickTimer) { clearInterval(this._tickTimer) @@ -364,9 +335,7 @@ class CaptionService extends EventEmitter { this._hideOverlaySafely() // 자막 전용 보조 모델은 세션이 끝나면 내린다 — 남겨 두면 받아쓰기 모델과 함께 VRAM 을 잡아 // Ollama 로드를 느리게 하거나 OOM 을 부른다. 다음 세션 시작 때 다시 올린다. - const auxToRelease = this._captionModelId - this._captionModelId = null - if (auxToRelease) void getLocalSTTService().releaseAuxModel() + if (this._captionModelId) void getLocalSTTService().releaseAuxModel() } // 세션을 히스토리에 저장 (회의 모드처럼 저장을 끈 소유자는 요약만 돌려받는다) @@ -383,7 +352,6 @@ class CaptionService extends EventEmitter { this._refineQueue = [] this._sessionLanguage = null this._session = { ...DEFAULT_START_OPTIONS } - this._stopPromise = null this._setState('inactive') getSoundEffectService().play('recording-stop') @@ -401,9 +369,8 @@ class CaptionService extends EventEmitter { async dispose(): Promise { if (this._disposed) return this._disposed = true - this._resetRefineState() - if (this._state === 'active' || this._state === 'starting' || this._state === 'stopping') { + if (this._state === 'active' || this._state === 'starting') { await this.stop() } @@ -555,17 +522,7 @@ 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) @@ -575,30 +532,17 @@ class CaptionService extends EventEmitter { } private async _drainRefineQueue(): Promise { - const runId = ++this._refineRunId - const epoch = this._refineEpoch this._refining = true try { - 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) + for (let next = this._refineQueue.shift(); next; next = this._refineQueue.shift()) { + await this._refine(next) } } finally { - if (this._refineRunId === runId) { - this._refining = false - this._refineController = null - } + this._refining = false } } - private async _refine(segment: CaptionSegment, epoch: number): Promise { - if (this._disposed || this._state !== 'active' || epoch !== this._refineEpoch) return + private async _refine(segment: CaptionSegment): Promise { 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) @@ -608,27 +552,19 @@ 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 - } } } diff --git a/apps/desktop/src/main/services/InputTelemetryService.ts b/apps/desktop/src/main/services/InputTelemetryService.ts index f62a5d68..56685fc3 100644 --- a/apps/desktop/src/main/services/InputTelemetryService.ts +++ b/apps/desktop/src/main/services/InputTelemetryService.ts @@ -163,8 +163,6 @@ 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 @@ -198,8 +196,6 @@ 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 /** 주기 샘플 스냅샷 진행 중 (중복 방지) */ @@ -454,10 +450,6 @@ 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() @@ -583,25 +575,21 @@ class InputTelemetryService extends EventEmitter { const vk = uiohookCodeToVk(event.keycode) // 프로그램이 보낸 키(오타 교정의 백스페이스·확정용 공백·Ctrl+V 붙여넣기)만 통계와 버퍼에서 제외한다. // 치환 도중 사용자가 실제로 누른 일반 글자·한글 키까지 삼키면 글자가 빠지거나 밀리는 버그가 생긴다. - if (this._programmaticKeys > 0) { - if (Date.now() > this._programmaticKeysUntil) { - this._programmaticKeys = 0 - } else { - const isExpectedProgrammaticKey = - vk === 0x08 || - vk === 0x20 || - this._modifiers.ctrl || - vk === 0x11 || - vk === 0xa2 || - vk === 0xa3 - if (isExpectedProgrammaticKey) { - this._inputRevision += 1 - this._programmaticKeys -= 1 - if (this._programmaticKeys === 0) { - this._scheduleTextSnapshot() - } - return + if (this._programmaticKeys > 0 && Date.now() <= this._programmaticKeysUntil) { + const isExpectedProgrammaticKey = + vk === 0x08 || + vk === 0x20 || + this._modifiers.ctrl || + vk === 0x11 || + vk === 0xa2 || + vk === 0xa3 + if (isExpectedProgrammaticKey) { + this._inputRevision += 1 + this._programmaticKeys -= 1 + if (this._programmaticKeys === 0) { + this._scheduleTextSnapshot() } + return } } // 순수 수정자 키(Ctrl/Alt/Shift/Win) 단독 눌림·키 반복은 화면 텍스트를 바꾸지 않는다. @@ -907,42 +895,18 @@ class InputTelemetryService extends EventEmitter { clearTimeout(this._settleTimer) this._settleTimer = null } - 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 - ) - : 0 - if (suggestionEnabled) { - // 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔 - // 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측: 2026-10-17: "빠릿하지 않다"). - this._settleTimer = setTimeout(() => { - this._settleTimer = null - void this._captureTextSnapshot() - }, 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?.() - } + if ((!keyClass || TYPING_KEY_CLASSES.has(keyClass)) && configGet('suggestionEnabled') === true) { + // 조합 중(한글은 멈출 때 거의 늘 조합 중이다)에 필요한 유휴 시간을 막 넘긴 순간에 찍는다 — 예전엔 + // 지연+400ms(=1초)라 멈춘 뒤 제안이 그만큼 늦게 시작됐다(실측 2026-10-17: "빠릿하지 않다"). + const settleDelay = Math.max( + INPUT_TELEMETRY_DEFAULTS.textSnapshotDebounceMs + 50, + Math.ceil((configGet('suggestionTriggerDelayMs') || SUGGESTION_DEFAULTS.triggerDelayMs) * COMPOSING_IDLE_MULTIPLIER) + 60 + ) + this._settleTimer = setTimeout(() => { + this._settleTimer = null + void this._captureTextSnapshot() + }, settleDelay) + this._settleTimer.unref?.() } } @@ -1144,9 +1108,6 @@ 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)) @@ -1236,30 +1197,20 @@ class InputTelemetryService extends EventEmitter { } this._lastContext = context - if (this._settleTimer || this._typoSettleTimer) { - const canTriggerContext = + if (this._settleTimer) { + const minPrefixChars = configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars + const canTriggerSuggestion = + configGet('suggestionEnabled') === true && context.available && context.isEditable && !context.isPassword && context.editedSinceFocus && - context.typedRecently - const minPrefixChars = configGet('suggestionMinPrefixChars') || SUGGESTION_DEFAULTS.minPrefixChars - const canTriggerSuggestion = - configGet('suggestionEnabled') === true && - canTriggerContext && + context.typedRecently && normalizeRequestPrefix(context.prefix).length + (context.isComposing ? 1 : 0) >= minPrefixChars - const canTriggerTypoSettle = - configGet('typoAutoCorrectEnabled') !== false && - canTriggerContext && - context.prefix.trim().length > 0 - if (this._settleTimer && !canTriggerSuggestion && !canTriggerTypoSettle) { + if (!canTriggerSuggestion) { clearTimeout(this._settleTimer) this._settleTimer = null } - if (this._typoSettleTimer && !canTriggerTypoSettle) { - clearTimeout(this._typoSettleTimer) - this._typoSettleTimer = null - } } this.emit('typed-context', context) // 진단 줄이 즉시 갱신되도록 상태 변경을 알린다 (키 입력마다가 아니라 스냅샷마다). @@ -1330,14 +1281,8 @@ class InputTelemetryService extends EventEmitter { bucket.sentences += delta.insertedSentences } - 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 (!delta.insertedText) return + const typedText = this._withoutExpectedInsert(delta.insertedText) if (typedText !== delta.insertedText) { // 프로그램 삽입(제안 수락 등)이 섞였다 — 그 앞까지 모은 것을 저장하고, 이번에 직접 친 // 나머지만 바로 학습한다. 다음 diff 부터는 삽입 뒤 텍스트를 기준선으로 다시 모은다. @@ -1377,7 +1322,6 @@ class InputTelemetryService extends EventEmitter { this._learnFlushTimer = null this.flushPendingLearning() }, LEARN_IDLE_FLUSH_MS) - this._learnFlushTimer.unref?.() } /** 모아 둔 타이핑 구간을 지금 학습한다 (멈춤·문장 끝·포커스 이동·종료 시). */ @@ -1442,18 +1386,10 @@ class InputTelemetryService extends EventEmitter { * - 삽입 구간이 예고 텍스트의 앞부분이면(키보드 방식으로 치는 도중 잡힌 스냅샷) 전부 * 프로그램 삽입이고, 남은 뒷부분을 계속 기다린다. */ - private _withoutExpectedInsert( - inserted: string, - prevText?: string, - nextText?: string, - span?: { start: number; end: number; text: string } | null - ): string { + private _withoutExpectedInsert(inserted: string): 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) @@ -1461,34 +1397,6 @@ 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 '' @@ -2311,28 +2219,6 @@ 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 diff --git a/apps/desktop/src/main/services/LocalLLMService.ts b/apps/desktop/src/main/services/LocalLLMService.ts index 9b5e6251..ef0ce6d6 100644 --- a/apps/desktop/src/main/services/LocalLLMService.ts +++ b/apps/desktop/src/main/services/LocalLLMService.ts @@ -186,7 +186,6 @@ class LocalLLMService extends EventEmitter { private _activeRequests = new Set() private _ensureRunningPromise: Promise<'running' | 'starting' | 'not-installed' | 'failed'> | null = null private _startCheckTimers = new Set>() - private _pullControllers = new Set() private _disposed = false get state(): LLMState { @@ -415,7 +414,7 @@ class LocalLLMService extends EventEmitter { * Ollama 가용성 폴링을 시작한다 (5초 간격). */ startPolling(): void { - if (this._pollInterval || this._disposed) return + if (this._pollInterval) return this._checkAvailability() this._pollInterval = setInterval(() => { if (this._state !== LLMState.Generating) { @@ -687,13 +686,8 @@ class LocalLLMService extends EventEmitter { text: string, action: LLMAction, targetLanguage?: string, - customPrompt?: string, - options?: { signal?: AbortSignal; timeoutMs?: number } + customPrompt?: string ): Promise { - if (options?.signal?.aborted) { - throw new D3ROError(ErrorCode.LLMProcessingCancelled, 'LLM processing was cancelled') - } - // Phase 11: LLM 처리 쿼터 체크 try { const { getLicenseService } = await import('./LicenseService') @@ -714,18 +708,10 @@ 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, - ...(options?.signal ? { signal: options.signal } : {}), - ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}) - }) + const result = await this.generate(text, { systemPrompt }) const cleaned = stripReasoningBlocks(result.text) // reasoning 블록 제거 후 빈 응답이면 원본 텍스트 폴백 // (모델이 thinking만 하고 출력은 안 한 경우 / 응답 파싱 실패 케이스) @@ -798,106 +784,67 @@ class LocalLLMService extends EventEmitter { } private async _doPullModel(modelId: string): Promise { - if (this._disposed) { - throw new D3ROError(ErrorCode.LLMProcessingCancelled, 'LocalLLMService disposed') - } - const serverUrl = getOllamaServerUrl() - const controller = new AbortController() - this._pullControllers.add(controller) - let reader: ReadableStreamDefaultReader | 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 }), - signal: controller.signal - }) + const response = await fetch(`${serverUrl}/api/pull`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ model: modelId, stream: true }) + }) - if (!response.ok || !response.body) { - throw new D3ROError( - ErrorCode.LLMServerUnreachable, - `Pull 실패: HTTP ${response.status}` - ) - } - - 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 - - buffer += decoder.decode(value, { stream: true }) - const lines = buffer.split('\n') - buffer = lines.pop() ?? '' - - for (const line of lines) { - const trimmed = line.trim() - if (trimmed.length === 0) continue - try { - const chunk = JSON.parse(trimmed) as { - status: string - digest?: string - total?: number - completed?: number - error?: string - } - if (chunk.error) { - throw new D3ROError(ErrorCode.LLMServerUnreachable, chunk.error) - } - this.emit('pull-progress', { - modelId, - status: chunk.status, - digest: chunk.digest ?? null, - total: chunk.total ?? 0, - completed: chunk.completed ?? 0, - percent: - chunk.total && chunk.total > 0 - ? Math.min(100, Math.floor(((chunk.completed ?? 0) / chunk.total) * 100)) - : 0 - }) - } catch (err) { - if (err instanceof D3ROError) throw err - // JSON 파싱 실패한 부분 라인은 스킵 - } - } - } - - 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 + if (!response.ok || !response.body) { throw new D3ROError( ErrorCode.LLMServerUnreachable, - `Pull 실패: ${err instanceof Error ? err.message : String(err)}` + `Pull 실패: HTTP ${response.status}` ) - } finally { - controller.signal.removeEventListener('abort', onAbort) - this._pullControllers.delete(controller) - if (reader) { - await reader.cancel().catch(() => undefined) + } + + const reader = response.body.getReader() + const decoder = new TextDecoder() + let buffer = '' + + for (;;) { + const { done, value } = await reader.read() + if (done) break + + buffer += decoder.decode(value, { stream: true }) + const lines = buffer.split('\n') + buffer = lines.pop() ?? '' + + for (const line of lines) { + const trimmed = line.trim() + if (trimmed.length === 0) continue + try { + const chunk = JSON.parse(trimmed) as { + status: string + digest?: string + total?: number + completed?: number + error?: string + } + if (chunk.error) { + throw new D3ROError(ErrorCode.LLMServerUnreachable, chunk.error) + } + this.emit('pull-progress', { + modelId, + status: chunk.status, + digest: chunk.digest ?? null, + total: chunk.total ?? 0, + completed: chunk.completed ?? 0, + percent: + chunk.total && chunk.total > 0 + ? Math.min(100, Math.floor(((chunk.completed ?? 0) / chunk.total) * 100)) + : 0 + }) + } catch (err) { + if (err instanceof D3ROError) throw err + // JSON 파싱 실패한 부분 라인은 스킵 + } } } + + logger.info(`Pull 완료: ${modelId}`) } getStatus(): LLMStatus { @@ -1042,14 +989,8 @@ 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') @@ -1081,8 +1022,6 @@ class LocalLLMService extends EventEmitter { // ignore } - if (this._disposed) return - if (!isOk) { try { const tagsRes = await fetch(`${serverUrl}/api/tags`, { @@ -1096,8 +1035,6 @@ class LocalLLMService extends EventEmitter { } } - if (this._disposed) return - const wasAvailable = this._available this._available = isOk if (detectedVersion) this._serverVersion = detectedVersion diff --git a/apps/desktop/src/main/services/LocalSTTService.ts b/apps/desktop/src/main/services/LocalSTTService.ts index d0037ecc..b4aa32e7 100644 --- a/apps/desktop/src/main/services/LocalSTTService.ts +++ b/apps/desktop/src/main/services/LocalSTTService.ts @@ -243,8 +243,6 @@ class LocalSTTService extends EventEmitter { // errorEmitted 플래그로 이벤트 중복 방지 private _errorEmitted: boolean = false private _idleUnloadTimer: NodeJS.Timeout | null = null - private _downloadControllers = new Set() - private _downloadSleepCancelers = new Set<() => void>() // ── 상태 접근자 ── @@ -523,22 +521,13 @@ class LocalSTTService extends EventEmitter { } await this._supervisor.ready() - if (this._disposed) { - throw new D3ROError( - ErrorCode.STTModelDownloadCancelled, - '모델 다운로드 중 서비스가 종료되었습니다', - ) - } - const startRes = await this._fetchDownload( - `${this._baseUrl}/download`, - { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model_id: modelId }), - }, - 10000, - ) + const startRes = await fetch(`${this._baseUrl}/download`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ model_id: modelId }), + signal: AbortSignal.timeout(10000), + }) // 409 = 이미 다운로드 진행 중 — 실패가 아니라 기존 진행에 합류해 폴링 if (!startRes.ok && startRes.status !== 409) { @@ -551,9 +540,6 @@ 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 @@ -565,33 +551,17 @@ 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 this._fetchDownload(`${this._baseUrl}/download/status`, {}, 3000) + const res = await fetch(`${this._baseUrl}/download/status`, { + signal: AbortSignal.timeout(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( @@ -602,13 +572,6 @@ class LocalSTTService extends EventEmitter { continue } - if (this._disposed) { - throw new D3ROError( - ErrorCode.STTModelDownloadCancelled, - `모델 다운로드 취소: ${modelId}`, - ) - } - this._emitDownloadProgress( modelId, status.percent, @@ -674,14 +637,6 @@ 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 @@ -1040,55 +995,8 @@ class LocalSTTService extends EventEmitter { logger.error(`STT 에러: [${error.code}] ${error.message}`) } - private async _fetchDownload( - url: string, - init: RequestInit, - timeoutMs: number, - ): Promise { - 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 { - 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) - }) + return new Promise((resolve) => setTimeout(resolve, ms)) } // ── 타입 안전한 이벤트 메서드 오버라이드 ── diff --git a/apps/desktop/src/main/services/TypoCorrectionService.ts b/apps/desktop/src/main/services/TypoCorrectionService.ts index 76bd17a6..52a57a6d 100644 --- a/apps/desktop/src/main/services/TypoCorrectionService.ts +++ b/apps/desktop/src/main/services/TypoCorrectionService.ts @@ -75,11 +75,6 @@ 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' @@ -195,10 +190,10 @@ export class TypoCorrectionService extends EventEmitter { const canRebaseDelta = delta.length > 0 && delta.length <= 6 && - (BOUNDARY_DELTA_RE.test(delta) || + (/^[ \t.,!?;:]{1,4}$/u.test(delta) || (!context.isComposing && context.idleMs >= LAYOUT_BOUNDARY_MIN_IDLE_MS && - TRAILING_BOUNDARY_RE.test(delta))) + /[ \t.,!?;:]$/u.test(delta))) if (canRebaseDelta) { this._check.context = context this._check.latestKeyAt = this._deps.lastKeyAt() @@ -216,7 +211,7 @@ export class TypoCorrectionService extends EventEmitter { this._lastCheckedRegion = '' this._lastPostRegion = '' } - const hasTrailingBoundary = TRAILING_BOUNDARY_RE.test(prefix) + const hasTrailingBoundary = /[ \t.,!?;:]$/u.test(prefix) const isVimCommand = context.vimMode === 'command' || prefix.trimStart().startsWith(':') const minLayoutIdle = hasTrailingBoundary ? LAYOUT_BOUNDARY_MIN_IDLE_MS @@ -268,7 +263,6 @@ 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) { @@ -278,30 +272,23 @@ export class TypoCorrectionService extends EventEmitter { } else { // 빠른 연속 입력 뒤 일부만 고치면 다음 스냅샷에서 앞쪽 교정이 누락된다. // 짧은 유휴에는 꼬리 사슬 전체가 들어올 때까지 기다리고, 충분히 멈추면 현재 검사 영역을 한 번에 교정한다. - // 단, 문장부호로 막 닫힌 단일 꼬리 오타(23~32자 긴 한국어 구문)는 경계에서 즉시 복원한다. for (let i = allCorrections.length - 1; i >= 0; i -= 1) { const c = allCorrections[i] - 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) { + if (prefix.length - c.start > maxDeterministicSpan) { const nextCorr = baseCorrections[0] const between = nextCorr ? prefix.slice(c.end, nextCorr.start) : '' - deferredTrailingCorrections = BOUNDARY_ONLY_RUN_RE.test(between) || between.trim().length <= 2 + deferredTrailingCorrections = /^[ \t.,!?;:]*$/u.test(between) || between.trim().length <= 2 break } if (baseCorrections.length === 0) { - const nonSpaceTailLen = tailAfter.replace(BOUNDARY_PUNCT_GLOBAL_RE, '').length + const tailAfter = prefix.slice(c.end) + const nonSpaceTailLen = tailAfter.replace(/[ \t.,!?;:]/gu, '').length if (nonSpaceTailLen > 2) break baseCorrections.unshift(c) - appliedSpanLimit = allowedSpan } else { const nextCorr = baseCorrections[0] const between = prefix.slice(c.end, nextCorr.start) - if (BOUNDARY_ONLY_RUN_RE.test(between) || between.trim().length <= 2) { + if (/^[ \t.,!?;:]*$/u.test(between) || between.trim().length <= 2) { baseCorrections.unshift(c) } else { break @@ -319,7 +306,7 @@ export class TypoCorrectionService extends EventEmitter { const corrections = loneJamoRemovals.length > 0 ? mergeTypoCorrections(baseCorrections, loneJamoRemovals) : baseCorrections const plan = planTypoReplacement(prefix, corrections) - if (plan && plan.deleteCount <= appliedSpanLimit) { + if (plan && plan.deleteCount <= maxDeterministicSpan) { this._markRegionChecked(region) void this._apply(plan, context, keyAtDecision) return 'correcting' @@ -344,10 +331,7 @@ export class TypoCorrectionService extends EventEmitter { void this._apply(jamoPlan, context, keyAtDecision) return 'correcting' } - if ( - options.trailingWordOnly !== true && - (!worthModel || configGet('typoAutoCorrectUseModel') === false) - ) { + if (!worthModel || configGet('typoAutoCorrectUseModel') === false) { this._markRegionChecked(region) } return 'pass' @@ -460,7 +444,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 && TRAILING_BOUNDARY_RE.test(region) + return compact.length >= 4 && /[ \t.,!?;:]$/u.test(region) } return false } diff --git a/apps/desktop/src/main/services/VoiceConversationService.ts b/apps/desktop/src/main/services/VoiceConversationService.ts index f4228f19..c56c1dc5 100644 --- a/apps/desktop/src/main/services/VoiceConversationService.ts +++ b/apps/desktop/src/main/services/VoiceConversationService.ts @@ -49,7 +49,6 @@ class VoiceConversationService extends EventEmitter { * 카운트가 쌓였고, 세션을 끝내도 마이크(SoX)가 계속 열려 있었다. */ private _micHeld = false - private _listenEpoch = 0 private _responseAbortController: AbortController | null = null /** 취소·세션 종료마다 올린다 — 전사가 끝났을 때 그 사이 취소됐는지 가린다(전사 중엔 abort 할 응답이 없다). */ private _turn = 0 @@ -123,10 +122,8 @@ class VoiceConversationService extends EventEmitter { this._turn += 1 this._stopListening() // 이 대화의 응답만 멈춘다 — signal 이 LLM 호출까지 전달된다(전역 cancelGeneration 은 다른 기능의 - // 진행 중 호출까지 끊었다). 포인터를 먼저 비워 취소 직후 새 턴이 막히지 않게 한다. - const responseController = this._responseAbortController - this._responseAbortController = null - responseController?.abort() + // 진행 중 호출까지 끊었다). + this._responseAbortController?.abort() getTTSPlaybackService().stop() this._isActive = false @@ -150,9 +147,7 @@ class VoiceConversationService extends EventEmitter { */ cancelResponse(): void { this._turn += 1 - const responseController = this._responseAbortController - this._responseAbortController = null - responseController?.abort() + this._responseAbortController?.abort() getTTSPlaybackService().stop() if (this._isActive && this._state !== 'listening') { this._resumeListening() @@ -271,9 +266,7 @@ 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') @@ -285,7 +278,6 @@ class VoiceConversationService extends EventEmitter { } private _stopListening(): void { - this._listenEpoch += 1 const audioService = getAudioCaptureService() if (this._audioListenerBound) { audioService.off('audio-data', this._onAudioData) diff --git a/apps/desktop/src/main/services/VoiceModeService.ts b/apps/desktop/src/main/services/VoiceModeService.ts index a842e150..19f0a478 100644 --- a/apps/desktop/src/main/services/VoiceModeService.ts +++ b/apps/desktop/src/main/services/VoiceModeService.ts @@ -1023,10 +1023,8 @@ class VoiceModeService extends EventEmitter { action: LLMAction, targetLanguage?: string, customPrompt?: string, - signal?: AbortSignal, ): Promise { return getLlmGateway().processText(text, action, targetLanguage, customPrompt, { - ...(signal ? { signal } : {}), onFallback: (reason) => this._emitPremiumFallback(reason), }) } @@ -1089,8 +1087,8 @@ class VoiceModeService extends EventEmitter { const processedText = route.kind === 'instruction' - ? await this._processWithInstruction(userText, route.instructionId, run.controller.signal) - : await this._processWithAction(userText, route.action, run.controller.signal) + ? await this._processWithInstruction(userText, route.instructionId) + : await this._processWithAction(userText, route.action) if (!this._isCurrent(run)) return @@ -1117,11 +1115,7 @@ class VoiceModeService extends EventEmitter { } /** 지시문(음성 단축키 또는 활성 지시문·파이프라인)으로 처리한다. 지시문이 없으면 지시문 없이 custom 처리 */ - private async _processWithInstruction( - userText: string, - instructionId: string | null, - signal?: AbortSignal, - ): Promise { + private async _processWithInstruction(userText: string, instructionId: string | null): Promise { let invocationText = userText let instructionPrompt: string | undefined @@ -1152,14 +1146,13 @@ class VoiceModeService extends EventEmitter { } } - return this._runProcessorWithFallback(invocationText, 'custom', undefined, instructionPrompt, signal) + return this._runProcessorWithFallback(invocationText, 'custom', undefined, instructionPrompt) } /** 일반 액션(refine/translate/…)으로 처리한다 */ private async _processWithAction( userText: string, action: Extract['action'], - signal?: AbortSignal, ): Promise { const targetLanguage = resolveTargetLanguage() logger.info( @@ -1171,8 +1164,6 @@ class VoiceModeService extends EventEmitter { userText, action, action === 'translate' ? targetLanguage : undefined, - undefined, - signal, ) } diff --git a/apps/desktop/src/main/services/llm/LlmGateway.ts b/apps/desktop/src/main/services/llm/LlmGateway.ts index e3d2d7a6..51340a00 100644 --- a/apps/desktop/src/main/services/llm/LlmGateway.ts +++ b/apps/desktop/src/main/services/llm/LlmGateway.ts @@ -114,13 +114,7 @@ export interface PremiumLlmAdapter { export interface LocalLlmAdapter { isAvailable(): boolean - processText( - text: string, - action: LLMAction, - targetLanguage?: string, - customPrompt?: string, - options?: { signal?: AbortSignal; timeoutMs?: number }, - ): Promise + processText(text: string, action: LLMAction, targetLanguage?: string, customPrompt?: string): Promise generate( text: string, options?: LlmGenerateOptions & { signal?: AbortSignal; timeoutMs?: number }, @@ -220,10 +214,8 @@ class RoutedLlmGateway implements LlmGateway { } } throwIfAborted(hooks?.signal) - 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) + // 로컬 processText 는 호출 단위 signal 을 받지 않는다 — 끝난 뒤 취소됐으면 결과를 버린다. + const result = await this._deps.getLocal().processText(text, action, targetLanguage, customPrompt) throwIfAborted(hooks?.signal) return result } diff --git a/apps/desktop/src/main/windows/WindowManager.ts b/apps/desktop/src/main/windows/WindowManager.ts index 91d6a5e6..40a50381 100644 --- a/apps/desktop/src/main/windows/WindowManager.ts +++ b/apps/desktop/src/main/windows/WindowManager.ts @@ -567,8 +567,6 @@ ipcMain.on(IPC_CHANNELS.POPUP_RESULT.MEASURED, (event: Electron.IpcMainEvent, da }) export function hideResultPopup(): void { - cancelPendingResultShow() - lastResultCursor = null if (resultPopupWindow && !resultPopupWindow.isDestroyed()) { resultPopupWindow.hide() } diff --git a/apps/desktop/tests/main/ipc/ipc-redteam-r3-1.test.ts b/apps/desktop/tests/main/ipc/ipc-redteam-r3-1.test.ts index 73f2f6de..68679b59 100644 --- a/apps/desktop/tests/main/ipc/ipc-redteam-r3-1.test.ts +++ b/apps/desktop/tests/main/ipc/ipc-redteam-r3-1.test.ts @@ -6,7 +6,6 @@ // - 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 Promise>()) @@ -137,25 +136,3 @@ 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) => void) => Promise) - | 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({}) - }) -}) diff --git a/apps/desktop/tests/main/services/TypoCorrectionService.test.ts b/apps/desktop/tests/main/services/TypoCorrectionService.test.ts index d2ca3cf9..3f7f0c4c 100644 --- a/apps/desktop/tests/main/services/TypoCorrectionService.test.ts +++ b/apps/desktop/tests/main/services/TypoCorrectionService.test.ts @@ -642,90 +642,6 @@ 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 — 제안 창에 함께 내놓을 교정 (적용하지 않음)', () => { diff --git a/apps/desktop/tests/main/services/VoiceConversationService.test.ts b/apps/desktop/tests/main/services/VoiceConversationService.test.ts index dcae2def..2d587c43 100644 --- a/apps/desktop/tests/main/services/VoiceConversationService.test.ts +++ b/apps/desktop/tests/main/services/VoiceConversationService.test.ts @@ -190,64 +190,4 @@ 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 { - await new Promise((resolve) => { - releaseFirstStream = resolve - }) - return '' - })()) - .mockImplementationOnce(() => (async function* (): AsyncGenerator { - 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((_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) - }) }) diff --git a/apps/desktop/tests/main/services/VoiceModeService.test.ts b/apps/desktop/tests/main/services/VoiceModeService.test.ts index f3bf76d3..a5775cc5 100644 --- a/apps/desktop/tests/main/services/VoiceModeService.test.ts +++ b/apps/desktop/tests/main/services/VoiceModeService.test.ts @@ -261,36 +261,6 @@ 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((_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 후처리 인자 전달', () => { diff --git a/apps/desktop/tests/main/services/audio-capture-redteam-r2-7.test.ts b/apps/desktop/tests/main/services/audio-capture-redteam-r2-7.test.ts index 419f4840..c096513d 100644 --- a/apps/desktop/tests/main/services/audio-capture-redteam-r2-7.test.ts +++ b/apps/desktop/tests/main/services/audio-capture-redteam-r2-7.test.ts @@ -7,7 +7,6 @@ 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' @@ -229,37 +228,3 @@ 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) - }) -}) diff --git a/apps/desktop/tests/main/services/caption-aux-release.test.ts b/apps/desktop/tests/main/services/caption-aux-release.test.ts index 8e392fef..1bfdceec 100644 --- a/apps/desktop/tests/main/services/caption-aux-release.test.ts +++ b/apps/desktop/tests/main/services/caption-aux-release.test.ts @@ -16,12 +16,11 @@ vi.mock('../../../src/main/services/ConfigService', () => ({ const stt = vi.hoisted(() => ({ gate: null as Promise | null, - initialize: vi.fn(async () => undefined), releaseAuxModel: vi.fn(async () => undefined), })) vi.mock('../../../src/main/services/LocalSTTService', () => ({ getLocalSTTService: () => ({ - initialize: stt.initialize, + initialize: vi.fn(async () => undefined), ensureAuxModel: vi.fn(async () => { if (stt.gate) await stt.gate }), @@ -30,13 +29,7 @@ vi.mock('../../../src/main/services/LocalSTTService', () => ({ }), })) -const audio = vi.hoisted(() => ({ - stopGate: null as Promise | null, - start: vi.fn(async () => undefined), - stop: vi.fn(async () => { - if (audio.stopGate) await audio.stopGate - }), -})) +const audio = vi.hoisted(() => ({ start: vi.fn(async () => undefined), stop: vi.fn(async () => undefined) })) vi.mock('../../../src/main/services/AudioCaptureService', () => ({ getAudioCaptureService: () => ({ ...audio, on: vi.fn(), off: vi.fn() }), calculateRMS: () => 0.1, @@ -70,12 +63,7 @@ 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() }) @@ -110,42 +98,4 @@ 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((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() - }) }) diff --git a/apps/desktop/tests/main/services/caption-lifecycle-refine.test.ts b/apps/desktop/tests/main/services/caption-lifecycle-refine.test.ts deleted file mode 100644 index 2dda7c62..00000000 --- a/apps/desktop/tests/main/services/caption-lifecycle-refine.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -// 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 })) -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 | 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 | 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 {} - async flush(): Promise { - 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((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 = [] - 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() - }) -}) diff --git a/apps/desktop/tests/main/services/llm-limits-routing-redteam-r2-1.test.ts b/apps/desktop/tests/main/services/llm-limits-routing-redteam-r2-1.test.ts index b6678717..f86ab5c8 100644 --- a/apps/desktop/tests/main/services/llm-limits-routing-redteam-r2-1.test.ts +++ b/apps/desktop/tests/main/services/llm-limits-routing-redteam-r2-1.test.ts @@ -151,17 +151,4 @@ 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 }) - }) }) diff --git a/apps/desktop/tests/main/services/local-llm-service.test.ts b/apps/desktop/tests/main/services/local-llm-service.test.ts index c698b45d..881ae921 100644 --- a/apps/desktop/tests/main/services/local-llm-service.test.ts +++ b/apps/desktop/tests/main/services/local-llm-service.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { D3ROError, ErrorCode } from '@d3ro/core/errors' +import { 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,152 +256,3 @@ 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((_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 - } - ).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 | 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({ - pull() { - return new Promise((_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((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((_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) - }) -}) diff --git a/apps/desktop/tests/main/services/stt-sidecar-redteam-r2-6.test.ts b/apps/desktop/tests/main/services/stt-sidecar-redteam-r2-6.test.ts index ac165596..5aa5a14d 100644 --- a/apps/desktop/tests/main/services/stt-sidecar-redteam-r2-6.test.ts +++ b/apps/desktop/tests/main/services/stt-sidecar-redteam-r2-6.test.ts @@ -374,94 +374,4 @@ 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((_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) - }) }) diff --git a/apps/desktop/tests/main/services/typo-live-punctuation.test.ts b/apps/desktop/tests/main/services/typo-live-punctuation.test.ts deleted file mode 100644 index d398c1ce..00000000 --- a/apps/desktop/tests/main/services/typo-live-punctuation.test.ts +++ /dev/null @@ -1,348 +0,0 @@ -// 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 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 { - 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() - } - }) -}) diff --git a/apps/desktop/tests/main/windows/popup-hide-show-race.test.ts b/apps/desktop/tests/main/windows/popup-hide-show-race.test.ts index 1984e563..508bb732 100644 --- a/apps/desktop/tests/main/windows/popup-hide-show-race.test.ts +++ b/apps/desktop/tests/main/windows/popup-hide-show-race.test.ts @@ -139,23 +139,4 @@ 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) - }) }) diff --git a/apps/mobile-rn/__tests__/abort-and-stream-guards.test.ts b/apps/mobile-rn/__tests__/abort-and-stream-guards.test.ts deleted file mode 100644 index dbfab384..00000000 --- a/apps/mobile-rn/__tests__/abort-and-stream-guards.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -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) - }) -}) diff --git a/apps/mobile-rn/__tests__/context-lifecycle-guards.test.tsx b/apps/mobile-rn/__tests__/context-lifecycle-guards.test.tsx deleted file mode 100644 index 17eacb52..00000000 --- a/apps/mobile-rn/__tests__/context-lifecycle-guards.test.tsx +++ /dev/null @@ -1,467 +0,0 @@ -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, []>(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 & { - 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() { - let resolve: (value: T) => void = () => undefined - let reject: (reason?: unknown) => void = () => undefined - const promise = new Promise((res, rej) => { - resolve = res - reject = rej - }) - return { promise, resolve, reject } -} - -async function flushMicrotasks(): Promise { - 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() - mockedAds.MobileAds.mockImplementation(() => ({ - setRequestConfiguration: jest.fn(async () => undefined), - initialize: jest.fn(() => initGate.promise), - })) - - let latestAds: ReturnType | null = null - function Probe(): null { - latestAds = useMobileAds() - return null - } - - let renderer!: ReactTestRenderer.ReactTestRenderer - await act(async () => { - renderer = ReactTestRenderer.create( - , - ) - 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() - 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 | 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() - mockEntitlementHookValue.refresh = jest.fn(() => refreshGate.promise) - - function Probe(): null { - latestRewarded = useRewardedCredits() - return null - } - - let renderer!: ReactTestRenderer.ReactTestRenderer - await act(async () => { - renderer = ReactTestRenderer.create( - , - ) - 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() - 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 | null = null - function Probe(): null { - latestBilling = useBilling() - return null - } - - let renderer!: ReactTestRenderer.ReactTestRenderer - await act(async () => { - renderer = ReactTestRenderer.create( - , - ) - activeRenderer = renderer - await flushMicrotasks() - }) - - let pendingPurchase: Promise = 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() - 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 | null = null - function Probe(): null { - latestDevice = useDevice() - return null - } - - let renderer!: ReactTestRenderer.ReactTestRenderer - await act(async () => { - renderer = ReactTestRenderer.create( - , - ) - 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 = { - 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 | null = null - function Probe(): null { - latestEnt = actualModule.useEntitlement() - return null - } - - let renderer!: ReactTestRenderer.ReactTestRenderer - await act(async () => { - renderer = ReactTestRenderer.create( - , - ) - activeRenderer = renderer - await flushMicrotasks() - await new Promise((resolve) => setTimeout(resolve, 0)) - }) - - process.off('unhandledRejection', onUnhandled) - expect(unhandledError).toBe(null) - expect(latestEnt?.loading).toBe(false) - act(() => renderer.unmount()) - }) -}) diff --git a/apps/mobile-rn/__tests__/queue-and-history-races.test.ts b/apps/mobile-rn/__tests__/queue-and-history-races.test.ts deleted file mode 100644 index 92433869..00000000 --- a/apps/mobile-rn/__tests__/queue-and-history-races.test.ts +++ /dev/null @@ -1,350 +0,0 @@ -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, [LocalAudioInput, unknown]>() -const mockListHistoryPage = jest.fn, [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 - unlink: jest.Mock -} - -function makeQueueItem( - userId: string, - suffix: string, - overrides: Partial = {}, -): 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() { - let resolve: (value: T) => void = () => undefined - let reject: (reason?: unknown) => void = () => undefined - const promise = new Promise((res, rej) => { - resolve = res - reject = rej - }) - return { promise, resolve, reject } -} - -async function flushMicrotasks(): Promise { - 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() - 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 | 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() - mockUpdateHistoryRevisionSafe.mockReturnValueOnce(favGate.promise) - const staleEntry = makeHistoryEntry('shared-like-entry', USER_A) - let pendingToggle: Promise = 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()) - }) -}) diff --git a/apps/mobile-rn/__tests__/recorder-lifecycle-races.test.ts b/apps/mobile-rn/__tests__/recorder-lifecycle-races.test.ts deleted file mode 100644 index 8cf81084..00000000 --- a/apps/mobile-rn/__tests__/recorder-lifecycle-races.test.ts +++ /dev/null @@ -1,238 +0,0 @@ -import { NativeModules } from 'react-native' -import { FileSystem } from 'react-native-file-access' - -const mockStartRecorder = jest.fn, [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() { - let resolve: (value: T) => void = () => undefined - let reject: (reason?: unknown) => void = () => undefined - const promise = new Promise((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).D3RORecording - }) - - test('AudioRecorder_동시start클레임경합시_한소유자만인정하고실패시임대해제', async () => { - const busyChecks: Array>> = [] - 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() - 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() - 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).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>() - 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).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) - }) -}) diff --git a/apps/mobile-rn/__tests__/screen-async-lifecycle.test.tsx b/apps/mobile-rn/__tests__/screen-async-lifecycle.test.tsx deleted file mode 100644 index 80d8067e..00000000 --- a/apps/mobile-rn/__tests__/screen-async-lifecycle.test.tsx +++ /dev/null @@ -1,1063 +0,0 @@ -import React from 'react' -import { Modal, TextInput } from 'react-native' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import type { Meeting } from '@d3ro/api-client' -import { AudioPipelineError, type LocalAudioInput } from '../src/features/import/audio-import-types' -import { CommandSyncError, type SyncedCommand } from '../src/features/commands/command-service' -import type { HistoryDetail } from '../src/features/history/history-service' -import type { MobileDashboardStats } from '../src/features/dashboard/dashboard-service' - -const USER_A = '11111111-1111-4111-8111-111111111111' -const USER_B = '22222222-2222-4222-8222-222222222222' -const MEETING_ID_1 = '33333333-3333-4333-8333-333333333333' -const MEETING_ID_2 = '44444444-4444-4444-8444-444444444444' -const HISTORY_ID = '55555555-5555-4555-8555-555555555555' -const AUDIO_ID = '66666666-6666-4666-8666-666666666666' -const AUDIO_ID_2 = '66666666-6666-4666-8666-666666666667' -const COMMAND_ID = '77777777-7777-4777-8777-777777777777' -const TEAM_ID = '88888888-8888-4888-8888-888888888888' - -let mockCurrentUser: { id: string; email?: string } | null = { id: USER_A, email: 'a@example.com' } -const mockSession = { access_token: 'access-token' } -const mockNavigate = jest.fn() -const mockGoBack = jest.fn() -const mockNavigation = { - navigate: mockNavigate, - goBack: mockGoBack, - getParent: () => undefined, -} -const mockSafeInsets = { top: 0, bottom: 0, left: 0, right: 0 } -const mockI18nValue = { - t: (key: string) => key, - locale: 'ko', - formatDate: () => '2026-08-21', - formatRelativeDate: () => 'today', - formatTime: () => '10:00', -} -const mockRefreshEntitlement = jest.fn(async () => null) -const mockEntitlementValue = { - refresh: mockRefreshEntitlement, - snapshot: { tier: 'free', adFree: false, overageCredits: 0 }, -} -const { d3roNativeDarkPalette } = jest.requireActual('@d3ro/ui-native') as typeof import('@d3ro/ui-native') -const mockPreferencesValue = { - palette: d3roNativeDarkPalette, - preferences: { preferredLlmModel: 'claude-haiku-4-5-20251001' }, -} - -const mockLoadDashboardStats = jest.fn, [string]>() -const mockListMeetingsPage = jest.fn() -const mockListKnowledgeDocuments = jest.fn() -const mockConsumeIncomingMediaAudio = jest.fn, []>() -const mockEnqueueAudioProcessing = jest.fn() -const mockProcessQueuedAudioNow = jest.fn() -const mockGetHistoryDetail = jest.fn, [string, string]>() -const mockCreateAudioPlaybackUrl = jest.fn, [string, unknown]>() -const mockStartPlayer = jest.fn(async () => 'started') -const mockStopPlayer = jest.fn(async () => 'stopped') -const mockLoadSyncedCommandCatalog = jest.fn() -const mockCreateSyncedCommand = jest.fn() -const mockExecuteSyncedCommand = jest.fn() -const mockListTeams = jest.fn() -const mockCreateTeam = jest.fn() - -jest.mock('@react-navigation/native', () => { - const ReactValue = require('react') as typeof React - return { - useNavigation: () => mockNavigation, - useFocusEffect: (callback: () => void | (() => void)) => { - ReactValue.useEffect(callback, [callback]) - }, - } -}) -jest.mock('react-native-safe-area-context', () => ({ - useSafeAreaInsets: () => mockSafeInsets, -})) -jest.mock('../src/navigation/tab-layout', () => ({ - useTabScreenBottomPadding: () => 88, -})) -jest.mock('@d3ro/i18n', () => ({ - useI18n: () => mockI18nValue, -})) -jest.mock('../src/lib/auth-context', () => ({ - useAuth: () => ({ - user: mockCurrentUser, - session: mockSession, - loading: false, - }), -})) -jest.mock('../src/lib/entitlement-context', () => ({ - useEntitlement: () => mockEntitlementValue, -})) -jest.mock('../src/lib/preferences-context', () => ({ - useMobilePreferences: () => mockPreferencesValue, -})) -jest.mock('../src/lib/supabase', () => ({ - supabase: { - channel: jest.fn(() => ({ - on: jest.fn().mockReturnThis(), - subscribe: jest.fn().mockReturnThis(), - })), - removeChannel: jest.fn(async () => 'ok'), - }, -})) -jest.mock('../src/components/ScreenHeader', () => ({ - ScreenHeader: ({ rightContent }: { rightContent?: React.ReactNode }) => rightContent ?? null, -})) -jest.mock('../src/components/ContentReportSheet', () => () => null) -jest.mock('../src/features/dashboard/dashboard-service', () => ({ - loadDashboardStats: (userId: string) => mockLoadDashboardStats(userId), -})) -jest.mock('../src/features/meetings/meetings-service', () => { - class MockMeetingServiceError extends Error { - code: string - constructor(code: string, message: string) { - super(message) - this.code = code - } - } - return { - MeetingServiceError: MockMeetingServiceError, - createMeetingCreationIdempotencyKey: () => 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', - createMeetingWorkspaceWithMetadata: jest.fn(), - listMeetingsPage: (opts: unknown) => mockListMeetingsPage(opts), - updateMeetingTitleRevisionSafe: jest.fn(), - deleteMeetingRevisionSafe: jest.fn(), - beginMeetingRecording: jest.fn(async () => ({})), - cancelMeetingRecording: jest.fn(async () => ({})), - failMeetingRecording: jest.fn(async () => ({})), - getMeetingRecordingLanguage: jest.fn(async () => 'ko'), - } -}) -jest.mock('../src/features/templates', () => ({ - loadTemplateLibrary: jest.fn(async () => ({ templates: [], selections: {} })), -})) -jest.mock('../src/features/knowledge/knowledge-service', () => { - class MockKnowledgeServiceError extends Error { - code: string - constructor(code: string, message: string) { - super(message) - this.code = code - } - } - return { - KnowledgeServiceError: MockKnowledgeServiceError, - createKnowledgeDocument: jest.fn(), - deleteKnowledgeDocument: jest.fn(), - indexKnowledgeDocument: jest.fn(), - listKnowledgeDocuments: (opts: unknown) => mockListKnowledgeDocuments(opts), - mergeKnowledgeDocuments: (current: unknown[], next: unknown[]) => [...current, ...next], - searchKnowledge: jest.fn(), - subscribeToKnowledgeDocuments: () => ({ unsubscribe: async () => undefined }), - } -}) -jest.mock('../src/features/knowledge/knowledge-file-picker', () => ({ - pickKnowledgeFile: jest.fn(), -})) -jest.mock('../src/features/import/incoming-media-intent', () => ({ - consumeIncomingMediaAudio: () => mockConsumeIncomingMediaAudio(), -})) -jest.mock('../src/features/import/audio-validation', () => ({ - validateLocalAudio: jest.fn(), -})) -jest.mock('../src/features/import/audio-file-picker', () => ({ - pickAudioFile: jest.fn(), -})) -jest.mock('../src/features/notifications/notification-native', () => ({ - showLocalTranscriptionCompleted: jest.fn(async () => true), -})) -jest.mock('../src/lib/audio-recorder', () => ({ - RecorderBusyError: class extends Error {}, - audioRecorder: { - acquire: async () => ({ - restore: async () => ({ state: 'idle', recording: null, meetingId: null, interruptionReason: null }), - start: jest.fn(async () => undefined), - stop: jest.fn(), - cleanup: jest.fn(async () => undefined), - cancel: jest.fn(async () => undefined), - pause: jest.fn(async () => undefined), - resume: jest.fn(async () => undefined), - }), - requestPermission: async () => true, - }, -})) -jest.mock('../src/features/recording/durable-processing-queue', () => ({ - discardQueuedAudio: jest.fn(async () => undefined), - enqueueAudioProcessing: (...args: unknown[]) => mockEnqueueAudioProcessing(...args), - processQueuedAudioNow: (...args: unknown[]) => mockProcessQueuedAudioNow(...args), - QueuedAudioPendingError: class extends Error { item = { id: 'q-1' } }, - retryQueuedAudio: jest.fn(async () => undefined), - subscribeToDurableQueue: () => () => undefined, -})) -jest.mock('react-native-nitro-sound', () => ({ - useSoundWithStates: () => ({ - state: { isPlaying: false, playback: { position: 0, duration: 1_000 } }, - startPlayer: () => mockStartPlayer(), - stopPlayer: () => mockStopPlayer(), - pausePlayer: jest.fn(async () => 'paused'), - resumePlayer: jest.fn(async () => 'resumed'), - }), -})) -jest.mock('../src/features/history/history-cache', () => ({ - loadHistoryCache: jest.fn(async () => null), -})) -jest.mock('../src/features/history/history-service', () => ({ - HistoryServiceError: class extends Error { - code: string - constructor(code: string, message: string) { - super(message) - this.code = code - } - }, - getHistoryDetail: (userId: string, historyId: string) => mockGetHistoryDetail(userId, historyId), - createAudioPlaybackUrl: (userId: string, audioFile: unknown) => ( - mockCreateAudioPlaybackUrl(userId, audioFile) - ), - updateHistoryRevisionSafe: jest.fn(), - deleteHistoryRevisionSafe: jest.fn(), -})) -jest.mock('../src/features/commands/command-service', () => { - class MockCommandSyncError extends Error { - code: string - constructor(code: string, message: string) { - super(message) - this.code = code - } - } - return { - COMMAND_INPUT_MAX_CHARS: 4000, - CommandExecutionError: class extends Error { - code: string - retryable: boolean - constructor(code: string, retryable = false) { - super(code) - this.code = code - this.retryable = retryable - } - }, - CommandSyncError: MockCommandSyncError, - createSyncedCommand: (...args: unknown[]) => mockCreateSyncedCommand(...args), - deleteSyncedCommand: jest.fn(), - executeSyncedCommand: (...args: unknown[]) => mockExecuteSyncedCommand(...args), - loadSyncedCommandCatalog: (...args: unknown[]) => mockLoadSyncedCommandCatalog(...args), - reorderSyncedCommand: jest.fn(), - setActiveSyncedCommand: jest.fn(), - updateSyncedCommand: jest.fn(), - } -}) -jest.mock('../src/features/teams/team-service', () => { - class MockTeamServiceError extends Error { - code: string - constructor(code: string, message: string) { - super(message) - this.code = code - } - } - return { - TeamServiceError: MockTeamServiceError, - listTeams: (...args: unknown[]) => mockListTeams(...args), - createTeam: (...args: unknown[]) => mockCreateTeam(...args), - } -}) - -import HomeScreen from '../src/screens/HomeScreen' -import MeetingsScreen from '../src/screens/MeetingsScreen' -import KnowledgeScreen from '../src/screens/KnowledgeScreen' -import RecordScreen from '../src/screens/RecordScreen' -import HistoryDetailScreen from '../src/screens/HistoryDetailScreen' -import CommandsScreen from '../src/screens/CommandsScreen' -import TeamsScreen from '../src/screens/TeamsScreen' - -function deferred() { - let resolve: (value: T) => void = () => undefined - let reject: (reason?: unknown) => void = () => undefined - const promise = new Promise((res, rej) => { - resolve = res - reject = rej - }) - return { promise, resolve, reject } -} - -async function flush(): Promise { - for (let index = 0; index < 8; index += 1) await Promise.resolve() -} - -function findHostByTestId(renderer: ReactTestRenderer, testID: string) { - return renderer.root.findAll( - (node) => typeof node.type === 'string' && node.props.testID === testID, - ) -} - -function makeMeeting(id: string, title: string, userId = USER_A): Meeting { - return { - id, - user_id: userId, - team_id: null, - title, - status: 'completed', - started_at: '2026-08-21T00:00:00.000Z', - ended_at: '2026-08-21T00:05:00.000Z', - duration_ms: 300_000, - raw_transcript: 'transcript', - edited_transcript: null, - minutes_markdown: null, - minutes_json: null, - stt_model: null, - llm_model: null, - stt_latency_ms: null, - llm_latency_ms: null, - error_message: null, - audio_storage_key: null, - language: 'ko', - attendees: [], - template_id: null, - creation_idempotency_key: null, - creation_request_hash: null, - created_at: '2026-08-21T00:00:00.000Z', - updated_at: '2026-08-21T00:05:00.000Z', - } -} - -describe('screen async lifecycle and race guards', () => { - let activeRenderer: ReactTestRenderer | null = null - - beforeEach(() => { - mockCurrentUser = { id: USER_A, email: 'a@example.com' } - mockNavigate.mockReset() - mockGoBack.mockReset() - mockRefreshEntitlement.mockClear() - mockLoadDashboardStats.mockReset() - mockListMeetingsPage.mockReset() - mockListKnowledgeDocuments.mockReset() - mockConsumeIncomingMediaAudio.mockReset() - mockEnqueueAudioProcessing.mockReset() - mockProcessQueuedAudioNow.mockReset() - mockGetHistoryDetail.mockReset() - mockCreateAudioPlaybackUrl.mockReset() - mockStartPlayer.mockClear() - mockStopPlayer.mockClear() - mockLoadSyncedCommandCatalog.mockReset() - mockCreateSyncedCommand.mockReset() - mockExecuteSyncedCommand.mockReset() - mockListTeams.mockReset() - mockCreateTeam.mockReset() - }) - - afterEach(() => { - if (activeRenderer !== null) { - const target = activeRenderer - activeRenderer = null - act(() => target.unmount()) - } - jest.restoreAllMocks() - jest.clearAllTimers() - jest.useRealTimers() - }) - - test('HomeScreen_새로고침중계정변경시_이전계정응답으로화면을덮어쓰지않음', async () => { - const statsA = deferred() - const meetingsA = deferred<{ meetings: Meeting[]; total: number; page: number; pageSize: number; hasMore: boolean }>() - - mockLoadDashboardStats - .mockReturnValueOnce(statsA.promise) - .mockResolvedValueOnce({ - totalSessions: 1, - totalRecordingSeconds: 10, - totalWordCount: 5, - todaySessions: 1, - todayRecordingSeconds: 10, - todayWordCount: 5, - streakDays: 1, - recentHistory: [{ - id: 'user-b-rec', - title: 'User B record', - text: 'User B note', - durationSeconds: 10, - mode: 'dictation', - createdAt: '2026-08-21T00:00:00.000Z', - }], - generatedAt: '2026-08-21T00:00:00.000Z', - }) - mockListMeetingsPage - .mockReturnValueOnce(meetingsA.promise) - .mockResolvedValueOnce({ - meetings: [makeMeeting(MEETING_ID_2, 'User B Meeting', USER_B)], - total: 1, - page: 0, - pageSize: 3, - hasMore: false, - }) - - let renderer!: ReactTestRenderer - await act(async () => { - renderer = create() - activeRenderer = renderer - await flush() - }) - - // User switches from USER_A to USER_B while USER_A's dashboard request is still pending. - mockCurrentUser = { id: USER_B, email: 'b@example.com' } - await act(async () => { - renderer.update() - await flush() - }) - expect(findHostByTestId(renderer, `home-meeting-${MEETING_ID_2}`)).toHaveLength(1) - - await act(async () => { - statsA.resolve({ - totalSessions: 9, - totalRecordingSeconds: 90, - totalWordCount: 90, - todaySessions: 2, - todayRecordingSeconds: 20, - todayWordCount: 20, - streakDays: 3, - recentHistory: [{ - id: 'user-a-stale-rec', - title: 'Stale A', - text: 'Stale A', - durationSeconds: 20, - mode: 'dictation', - createdAt: '2026-08-21T00:00:00.000Z', - }], - generatedAt: '2026-08-21T00:00:00.000Z', - }) - meetingsA.resolve({ - meetings: [makeMeeting(MEETING_ID_1, 'Stale A Meeting', USER_A)], - total: 1, - page: 0, - pageSize: 3, - hasMore: false, - }) - await flush() - }) - - expect(findHostByTestId(renderer, `home-meeting-${MEETING_ID_1}`)).toHaveLength(0) - expect(findHostByTestId(renderer, `home-meeting-${MEETING_ID_2}`)).toHaveLength(1) - activeRenderer = null - act(() => renderer.unmount()) - }) - - test('MeetingsScreen_더보기조회중새검색실행시_이전페이지결과를병합하지않음', async () => { - jest.useFakeTimers({ now: 1_700_000_000_000 }) - const stalePage2 = deferred<{ meetings: Meeting[]; total: number; page: number; pageSize: number; hasMore: boolean }>() - mockListMeetingsPage.mockImplementation(async (opts: { page: number; search?: string }) => { - if (opts.search && opts.search.length > 0) { - return { - meetings: [makeMeeting(MEETING_ID_2, 'Filtered Search Result')], - total: 1, - page: 0, - pageSize: 30, - hasMore: false, - } - } - if (opts.page === 1) return stalePage2.promise - return { - meetings: [makeMeeting(MEETING_ID_1, 'Initial Meeting')], - total: 2, - page: 0, - pageSize: 30, - hasMore: true, - } - }) - - let renderer!: ReactTestRenderer - await act(async () => { - renderer = create() - activeRenderer = renderer - await flush() - }) - - const flatList = renderer.root.findAll((node) => typeof node.props.onEndReached === 'function')[0] - await act(async () => { - flatList.props.onEndReached() - await Promise.resolve() - }) - - // Trigger a new search (debounced 300ms) while page 1 (loadMore) is still in flight. - const searchInput = renderer.root.findByProps({ testID: 'meetings-search' }) - await act(async () => { - searchInput.props.onChangeText('Filtered') - }) - await act(async () => { - await jest.advanceTimersByTimeAsync(350) - await flush() - }) - - expect(findHostByTestId(renderer, `meeting-card-${MEETING_ID_2}`)).toHaveLength(1) - - await act(async () => { - stalePage2.resolve({ - meetings: [makeMeeting('99999999-9999-4999-8999-999999999999', 'Stale Page 2')], - total: 2, - page: 1, - pageSize: 30, - hasMore: false, - }) - await flush() - }) - - expect(findHostByTestId(renderer, 'meeting-card-99999999-9999-4999-8999-999999999999')).toHaveLength(0) - expect(findHostByTestId(renderer, `meeting-card-${MEETING_ID_2}`)).toHaveLength(1) - activeRenderer = null - act(() => renderer.unmount()) - }) - - test('KnowledgeScreen_더보기조회중새검색실행시_이전문서결과를병합하지않음', async () => { - const staleDocPage2 = deferred<{ documents: unknown[]; total: number; page: number; pageSize: number; hasMore: boolean }>() - const makeDoc = (id: string, title: string) => ({ - id, - user_id: USER_A, - team_id: null, - title, - file_name: `${id}.md`, - file_type: 'md', - source_url: null, - storage_key: null, - chunk_count: 1, - indexed: true, - indexed_at: '2026-08-21T00:00:00.000Z', - created_at: '2026-08-21T00:00:00.000Z', - updated_at: '2026-08-21T00:00:00.000Z', - }) - - mockListKnowledgeDocuments.mockImplementation(async (opts: { page: number; search?: string }) => { - if (opts.search && opts.search.length > 0) { - return { - documents: [makeDoc('doc-search', 'Filtered Doc')], - total: 1, - page: 0, - pageSize: 30, - hasMore: false, - } - } - if (opts.page === 1) return staleDocPage2.promise - return { - documents: [makeDoc('doc-1', 'Doc 1')], - total: 2, - page: 0, - pageSize: 30, - hasMore: true, - } - }) - - let renderer!: ReactTestRenderer - await act(async () => { - renderer = create() - activeRenderer = renderer - await flush() - }) - - const flatList = renderer.root.findAll((node) => typeof node.props.onEndReached === 'function')[0] - await act(async () => { - flatList.props.onEndReached() - await Promise.resolve() - }) - - const searchInput = renderer.root.findByProps({ testID: 'knowledge-document-search' }) - const searchSubmit = renderer.root.findByProps({ testID: 'knowledge-document-search-submit' }) - await act(async () => { - searchInput.props.onChangeText('Filtered') - await Promise.resolve() - }) - await act(async () => { - searchSubmit.props.onPress() - await flush() - }) - - expect(findHostByTestId(renderer, 'knowledge-document-doc-search')).toHaveLength(1) - - await act(async () => { - staleDocPage2.resolve({ - documents: [makeDoc('doc-stale', 'Stale Doc Page 2')], - total: 2, - page: 1, - pageSize: 30, - hasMore: false, - }) - await flush() - }) - - expect(findHostByTestId(renderer, 'knowledge-document-doc-stale')).toHaveLength(0) - activeRenderer = null - act(() => renderer.unmount()) - }) - - test('RecordScreen_공유미디어가져오기중단시_오류대신idle상태로복귀', async () => { - const input: LocalAudioInput = { - uri: 'file:///cache/shared.wav', - path: '/cache/shared.wav', - fileName: 'shared.wav', - mimeType: 'audio/wav', - sizeBytes: 1_024, - durationMs: 2_000, - source: 'share-intent', - dispose: jest.fn(async () => undefined), - } - mockConsumeIncomingMediaAudio.mockResolvedValueOnce(input) - mockEnqueueAudioProcessing.mockResolvedValueOnce({ id: 'queue-1' }) - mockProcessQueuedAudioNow.mockRejectedValueOnce(new AudioPipelineError('cancelled', 'Import cancelled')) - - let renderer!: ReactTestRenderer - await act(async () => { - renderer = create( - undefined, setParams: jest.fn() }} - />, - ) - activeRenderer = renderer - await flush() - }) - - expect(findHostByTestId(renderer, 'record-error')).toHaveLength(0) - activeRenderer = null - act(() => renderer.unmount()) - }) - - test('HistoryDetailScreen_오디오전환후이전URL응답시_오래된트랙재생을시작하지않음', async () => { - const detail: HistoryDetail = { - entry: { - id: HISTORY_ID, - user_id: USER_A, - title: 'Memo', - original_text: 'Body', - 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: 'audio/sample.wav', - duration: 12, - 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.16.5', - summary_text: null, - is_favorite: false, - revision: 1, - created_at: '2026-08-21T00:00:00.000Z', - updated_at: '2026-08-21T00:00:00.000Z', - }, - audioFiles: [ - { - id: AUDIO_ID, - user_id: USER_A, - history_id: HISTORY_ID, - meeting_id: null, - storage_bucket: 'audio-files', - storage_key: 'audio/sample-1.wav', - original_name: 'sample-1.wav', - mime_type: 'audio/wav', - size_bytes: 2_048, - duration_ms: 12_000, - checksum_sha256: 'abc', - upload_status: 'uploaded', - retention_until: null, - created_at: '2026-08-21T00:00:00.000Z', - updated_at: '2026-08-21T00:00:00.000Z', - }, - { - id: AUDIO_ID_2, - user_id: USER_A, - history_id: HISTORY_ID, - meeting_id: null, - storage_bucket: 'audio-files', - storage_key: 'audio/sample-2.wav', - original_name: 'sample-2.wav', - mime_type: 'audio/wav', - size_bytes: 2_048, - duration_ms: 12_000, - checksum_sha256: 'def', - upload_status: 'uploaded', - retention_until: null, - created_at: '2026-08-21T00:00:00.000Z', - updated_at: '2026-08-21T00:00:00.000Z', - }, - ], - jobs: [], - } - mockGetHistoryDetail.mockResolvedValueOnce(detail) - const slowUrlGate = deferred() - mockCreateAudioPlaybackUrl - .mockReturnValueOnce(slowUrlGate.promise) - .mockResolvedValueOnce('https://storage.example/track-2.wav') - - let renderer!: ReactTestRenderer - await act(async () => { - renderer = create( - , - ) - activeRenderer = renderer - await flush() - }) - - const row1 = renderer.root.findByProps({ testID: `history-audio-${AUDIO_ID}` }) - const row2 = renderer.root.findByProps({ testID: `history-audio-${AUDIO_ID_2}` }) - const play1 = row1.findAll( - (node) => typeof node.props.onPress === 'function' && node.props.accessibilityLabel === 'mobile.hist.audioPlay', - )[0] - const play2 = row2.findAll( - (node) => typeof node.props.onPress === 'function' && node.props.accessibilityLabel === 'mobile.hist.audioPlay', - )[0] - - await act(async () => { - // Simulate rapid tap on track 1 then track 2 before React disables buttons. - play1.props.onPress() - play2.props.onPress() - await flush() - }) - - await act(async () => { - slowUrlGate.resolve('https://storage.example/track-1.wav') - await flush() - }) - - expect(mockStartPlayer).toHaveBeenCalledTimes(1) - activeRenderer = null - act(() => renderer.unmount()) - }) - - test('CommandsScreen_저장충돌실패전언마운트시_카탈로그재조회를시작하지않음', async () => { - const command: SyncedCommand = { - id: COMMAND_ID, - userId: USER_A, - builtinKey: null, - name: 'Summarize', - description: '', - prompt: 'Summarize: {{text}}', - icon: 'bolt', - sortOrder: 0, - revision: 1, - createdAt: '2026-08-21T00:00:00.000Z', - updatedAt: '2026-08-21T00:00:00.000Z', - } - mockLoadSyncedCommandCatalog.mockResolvedValue({ - commands: [command], - activeCommandId: null, - }) - const saveGate = deferred() - mockCreateSyncedCommand.mockReturnValueOnce(saveGate.promise) - - let renderer!: ReactTestRenderer - await act(async () => { - renderer = create() - activeRenderer = renderer - await flush() - }) - expect(mockLoadSyncedCommandCatalog).toHaveBeenCalledTimes(1) - - act(() => { - renderer.root.findByProps({ testID: 'commands-add' }).props.onPress() - }) - const editor = renderer.root.findByProps({ testID: 'commands-editor' }) - const inputs = editor.findAllByType(TextInput) - act(() => { - inputs[0]?.props.onChangeText('New Command') - inputs[2]?.props.onChangeText('Prompt: {{text}}') - }) - - await act(async () => { - renderer.root.findByProps({ testID: 'commands-editor-save' }).props.onPress() - await Promise.resolve() - }) - - activeRenderer = null - act(() => renderer.unmount()) - - await act(async () => { - saveGate.reject(new CommandSyncError('conflict', 'stale revision')) - await flush() - }) - - expect(mockLoadSyncedCommandCatalog).toHaveBeenCalledTimes(1) - }) - - test('TeamsScreen_팀생성중언마운트시_상세화면으로이동하지않음', async () => { - mockListTeams.mockResolvedValueOnce([]) - const createGate = deferred<{ - id: string - name: string - ownerId: string - role: 'owner' - memberCount: number - createdAt: string - updatedAt: string - }>() - mockCreateTeam.mockReturnValueOnce(createGate.promise) - - let renderer!: ReactTestRenderer - await act(async () => { - renderer = create() - activeRenderer = renderer - await flush() - }) - - act(() => { - renderer.root.findByProps({ testID: 'teams-create' }).props.onPress() - }) - act(() => { - renderer.root.findByProps({ testID: 'team-name-input' }).props.onChangeText('Product Team') - }) - await act(async () => { - renderer.root.findByProps({ testID: 'team-create-submit' }).props.onPress() - await Promise.resolve() - }) - - activeRenderer = null - act(() => renderer.unmount()) - - await act(async () => { - createGate.resolve({ - id: TEAM_ID, - name: 'Product Team', - ownerId: USER_A, - role: 'owner', - memberCount: 1, - createdAt: '2026-08-21T00:00:00.000Z', - updatedAt: '2026-08-21T00:00:00.000Z', - }) - await flush() - }) - - expect(mockNavigate).not.toHaveBeenCalled() - }) - - test('TeamsScreen_팀생성중계정전환후신규계정생성시_이전계정완료가현재생성중상태를해제하지않음', async () => { - mockListTeams.mockResolvedValue([]) - const createGateA = deferred<{ - id: string - name: string - ownerId: string - role: 'owner' - memberCount: number - createdAt: string - updatedAt: string - }>() - const createGateB = deferred<{ - id: string - name: string - ownerId: string - role: 'owner' - memberCount: number - createdAt: string - updatedAt: string - }>() - mockCreateTeam - .mockReturnValueOnce(createGateA.promise) - .mockReturnValueOnce(createGateB.promise) - - let renderer!: ReactTestRenderer - await act(async () => { - renderer = create() - activeRenderer = renderer - await flush() - }) - - act(() => { - renderer.root.findByProps({ testID: 'teams-create' }).props.onPress() - }) - act(() => { - renderer.root.findByProps({ testID: 'team-name-input' }).props.onChangeText('Team A') - }) - await act(async () => { - renderer.root.findByProps({ testID: 'team-create-submit' }).props.onPress() - await Promise.resolve() - }) - expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.disabled).toBe(true) - - // Switch account from USER_A to USER_B while USER_A's createTeam is pending. - mockCurrentUser = { id: USER_B, email: 'b@example.com' } - await act(async () => { - renderer.update() - await flush() - }) - - expect(renderer.root.findAllByType(Modal)[0]?.props.visible).toBe(false) - - // User B opens modal and starts creating their own team. - act(() => { - renderer.root.findByProps({ testID: 'teams-create' }).props.onPress() - }) - expect(renderer.root.findByProps({ testID: 'team-name-input' }).props.value).toBe('') - expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.label).toBe('mobile.teams.create') - act(() => { - renderer.root.findByProps({ testID: 'team-name-input' }).props.onChangeText('Team B') - }) - await act(async () => { - renderer.root.findByProps({ testID: 'team-create-submit' }).props.onPress() - await Promise.resolve() - }) - expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.disabled).toBe(true) - expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.label).toBe('mobile.teams.creating') - - // Stale USER_A creation finishes now; must NOT clear USER_B's editorBusy or navigate. - await act(async () => { - createGateA.resolve({ - id: TEAM_ID, - name: 'Team A', - ownerId: USER_A, - role: 'owner', - memberCount: 1, - createdAt: '2026-08-21T00:00:00.000Z', - updatedAt: '2026-08-21T00:00:00.000Z', - }) - await flush() - }) - - expect(mockNavigate).not.toHaveBeenCalled() - expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.disabled).toBe(true) - expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.label).toBe('mobile.teams.creating') - - await act(async () => { - createGateB.resolve({ - id: '99999999-9999-4999-8999-999999999998', - name: 'Team B', - ownerId: USER_B, - role: 'owner', - memberCount: 1, - createdAt: '2026-08-21T00:00:00.000Z', - updatedAt: '2026-08-21T00:00:00.000Z', - }) - await flush() - }) - - expect(mockNavigate).toHaveBeenCalledWith('TeamDetail', { teamId: '99999999-9999-4999-8999-999999999998' }) - activeRenderer = null - act(() => renderer.unmount()) - }) - - test('CommandsScreen_명령변경및실행중계정전환시_이전계정완료가현재계정상태를해제하지않음', async () => { - const commandA: SyncedCommand = { - id: COMMAND_ID, - userId: USER_A, - builtinKey: null, - name: 'Cmd A', - description: '', - prompt: 'A: {{text}}', - icon: 'bolt', - sortOrder: 0, - revision: 1, - createdAt: '2026-08-21T00:00:00.000Z', - updatedAt: '2026-08-21T00:00:00.000Z', - } - const commandB: SyncedCommand = { - ...commandA, - id: '77777777-7777-4777-8777-777777777778', - userId: USER_B, - name: 'Cmd B', - } - mockLoadSyncedCommandCatalog - .mockResolvedValueOnce({ commands: [commandA], activeInstructionId: null }) - .mockResolvedValueOnce({ commands: [commandB], activeInstructionId: null }) - - const saveGateA = deferred() - const saveGateB = deferred() - mockCreateSyncedCommand - .mockReturnValueOnce(saveGateA.promise) - .mockReturnValueOnce(saveGateB.promise) - - const runGateA = deferred<{ text: string; generationId: string }>() - const runGateB = deferred<{ text: string; generationId: string }>() - mockExecuteSyncedCommand - .mockReturnValueOnce(runGateA.promise) - .mockReturnValueOnce(runGateB.promise) - - let renderer!: ReactTestRenderer - await act(async () => { - renderer = create() - activeRenderer = renderer - await flush() - }) - - // Start both a command execution and a create mutation as USER_A. - act(() => { - renderer.root.findByProps({ testID: 'commands-input' }).props.onChangeText('input A') - }) - await act(async () => { - renderer.root.findByProps({ testID: 'commands-run' }).props.onPress() - await Promise.resolve() - }) - act(() => { - renderer.root.findByProps({ testID: 'commands-add' }).props.onPress() - }) - const editorA = renderer.root.findByProps({ testID: 'commands-editor' }) - const inputsA = editorA.findAllByType(TextInput) - act(() => { - inputsA[0]?.props.onChangeText('New Cmd A') - inputsA[2]?.props.onChangeText('Prompt A: {{text}}') - }) - await act(async () => { - renderer.root.findByProps({ testID: 'commands-editor-save' }).props.onPress() - await Promise.resolve() - }) - expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.running') - expect(renderer.root.findByProps({ testID: 'commands-editor-save' }).props.label).toBe('mobile.commands.saving') - - // Switch account to USER_B while both USER_A requests are still pending. - mockCurrentUser = { id: USER_B, email: 'b@example.com' } - await act(async () => { - renderer.update() - await flush() - }) - - expect(renderer.root.findAllByProps({ testID: 'commands-editor' })).toHaveLength(0) - expect(renderer.root.findByProps({ testID: 'commands-add' }).props.disabled).toBe(false) - expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.run') - - // Start new execution and save as USER_B. - act(() => { - renderer.root.findByProps({ testID: 'commands-input' }).props.onChangeText('input B') - }) - await act(async () => { - renderer.root.findByProps({ testID: 'commands-run' }).props.onPress() - await Promise.resolve() - }) - act(() => { - renderer.root.findByProps({ testID: 'commands-add' }).props.onPress() - }) - const editorB = renderer.root.findByProps({ testID: 'commands-editor' }) - const inputsB = editorB.findAllByType(TextInput) - act(() => { - inputsB[0]?.props.onChangeText('New Cmd B') - inputsB[2]?.props.onChangeText('Prompt B: {{text}}') - }) - await act(async () => { - renderer.root.findByProps({ testID: 'commands-editor-save' }).props.onPress() - await Promise.resolve() - }) - expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.running') - expect(renderer.root.findByProps({ testID: 'commands-editor-save' }).props.label).toBe('mobile.commands.saving') - - // Stale USER_A save and run reject; USER_B's busy states must remain active. - await act(async () => { - saveGateA.reject(new CommandSyncError('server', 'late A failure')) - runGateA.reject(new Error('late A run failure')) - await flush() - }) - - expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.running') - expect(renderer.root.findByProps({ testID: 'commands-editor-save' }).props.label).toBe('mobile.commands.saving') - expect(renderer.root.findByProps({ testID: 'commands-add' }).props.disabled).toBe(true) - - await act(async () => { - saveGateB.resolve({ ...commandB, id: '77777777-7777-4777-8777-777777777779', name: 'New Cmd B' }) - runGateB.resolve({ text: 'ok B', generationId: 'gen-b' }) - await flush() - }) - - expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.run') - expect(renderer.root.findAllByProps({ testID: 'commands-editor' })).toHaveLength(0) - activeRenderer = null - act(() => renderer.unmount()) - }) -}) diff --git a/apps/mobile-rn/src/features/admin/admin-service.ts b/apps/mobile-rn/src/features/admin/admin-service.ts index 3c482a73..ad9e53df 100644 --- a/apps/mobile-rn/src/features/admin/admin-service.ts +++ b/apps/mobile-rn/src/features/admin/admin-service.ts @@ -406,9 +406,6 @@ async function requestAdmin(path: string, options: RequestOptions): Promise 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: { diff --git a/apps/mobile-rn/src/features/chat/chat-service.ts b/apps/mobile-rn/src/features/chat/chat-service.ts index 6e19a80e..9cf92c26 100644 --- a/apps/mobile-rn/src/features/chat/chat-service.ts +++ b/apps/mobile-rn/src/features/chat/chat-service.ts @@ -100,9 +100,6 @@ 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 = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', diff --git a/apps/mobile-rn/src/features/devices/device-service.ts b/apps/mobile-rn/src/features/devices/device-service.ts index eb01bd77..ed7e9ac1 100644 --- a/apps/mobile-rn/src/features/devices/device-service.ts +++ b/apps/mobile-rn/src/features/devices/device-service.ts @@ -87,14 +87,6 @@ const DEVICE_COLUMNS = [ export async function registerCurrentDevice( userId: string, config: MobileRuntimeConfig, -): Promise { - return registerCurrentDeviceAttempt(userId, config, true) -} - -async function registerCurrentDeviceAttempt( - userId: string, - config: MobileRuntimeConfig, - allowConflictRetry: boolean, ): Promise { requireUserId(userId) const existing = await supabase @@ -138,11 +130,9 @@ async function registerCurrentDeviceAttempt( .select(DEVICE_COLUMNS) .single() if (inserted.error) { - // 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) - } + // 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) throw new DeviceServiceError('server') } return normalizeRegisteredDevice(inserted.data) diff --git a/apps/mobile-rn/src/features/history/use-history-sync.ts b/apps/mobile-rn/src/features/history/use-history-sync.ts index edadce80..5e45de71 100644 --- a/apps/mobile-rn/src/features/history/use-history-sync.ts +++ b/apps/mobile-rn/src/features/history/use-history-sync.ts @@ -209,7 +209,6 @@ 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), @@ -223,7 +222,6 @@ 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') @@ -380,7 +378,6 @@ 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) { @@ -390,11 +387,9 @@ 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 - ))) - } + updateEntries((current) => current.map((item) => ( + item.id === entry.id ? entry : item + ))) throw mutationError } finally { endMutation(entry.id) @@ -409,12 +404,9 @@ 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])) - } + updateEntries((current) => mergeHistoryEntries(current, [entry])) throw mutationError } finally { endMutation(entry.id) diff --git a/apps/mobile-rn/src/features/recording/durable-processing-queue.ts b/apps/mobile-rn/src/features/recording/durable-processing-queue.ts index 0fb244d1..b7159afb 100644 --- a/apps/mobile-rn/src/features/recording/durable-processing-queue.ts +++ b/apps/mobile-rn/src/features/recording/durable-processing-queue.ts @@ -438,14 +438,7 @@ async function processItemCore(item: DurableQueueItem): Promise undefined); - throw new AudioPipelineError('cancelled', 'Queued audio processing was cancelled', error); - } - if (canRetry && !suspendedUsers.has(current.userId)) { - scheduler.arm(current.userId, current.nextAttemptAtMs); - } + if (canRetry) scheduler.arm(current.userId, current.nextAttemptAtMs); throw canRetry ? new QueuedAudioPendingError(current) : error; } finally { runningControllers.delete(item.id); @@ -473,17 +466,6 @@ export async function processQueuedAudioNow( return processItem(item); } -async function finishCleanupItem(item: DurableQueueItem): Promise { - 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 @@ -503,7 +485,12 @@ async function runResumePass(userId: string): Promise { if (item === undefined || item.userId !== userId) continue; if (item.status === 'terminal') continue; if (item.status === 'cleanup') { - await finishCleanupItem(item); + try { + await removeOwnedFile(item.path); + await removeItem(item); + } catch { + scheduler.arm(userId, Date.now() + 60_000); + } continue; } if (item.nextAttemptAtMs > Date.now()) { @@ -536,11 +523,6 @@ 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', diff --git a/apps/mobile-rn/src/features/talk/llm-stream-service.ts b/apps/mobile-rn/src/features/talk/llm-stream-service.ts index d2a715fe..7468eded 100644 --- a/apps/mobile-rn/src/features/talk/llm-stream-service.ts +++ b/apps/mobile-rn/src/features/talk/llm-stream-service.ts @@ -280,7 +280,6 @@ 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) diff --git a/apps/mobile-rn/src/lib/audio-recorder.ts b/apps/mobile-rn/src/lib/audio-recorder.ts index ae7dd8e2..971f5ced 100644 --- a/apps/mobile-rn/src/lib/audio-recorder.ts +++ b/apps/mobile-rn/src/lib/audio-recorder.ts @@ -44,7 +44,6 @@ 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; @@ -103,9 +102,6 @@ export class AudioRecorder { } private async assertAvailable(owner: RecorderOwner): Promise { - 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. @@ -119,28 +115,9 @@ export class AudioRecorder { claim: boolean, operation: () => Promise, ): Promise { - 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 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); - } - } + await this.assertAvailable(owner); + if (claim) this.lease = owner; + return operation(); } private async cleanupAsOwner( diff --git a/apps/mobile-rn/src/lib/billing-context.tsx b/apps/mobile-rn/src/lib/billing-context.tsx index 53f2d8e3..60bd3d77 100644 --- a/apps/mobile-rn/src/lib/billing-context.tsx +++ b/apps/mobile-rn/src/lib/billing-context.tsx @@ -298,24 +298,13 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re const [errorCode, setErrorCode] = useState(null) const inFlightPurchases = useRef(new Set()) const userIdRef = useRef(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) @@ -340,13 +329,11 @@ 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 @@ -359,15 +346,11 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re throw new Error('purchase_not_verified_active') } } catch (candidate) { - if (!mountedRef.current || userIdRef.current !== currentUserId) return - const resolvedErrorCode = await functionErrorCode(candidate) - if (!mountedRef.current || userIdRef.current !== currentUserId) return + if (userIdRef.current !== currentUserId) return setOperation('failed') - setErrorCode(resolvedErrorCode) + setErrorCode(await functionErrorCode(candidate)) } finally { - if (userIdRef.current === currentUserId) { - inFlightPurchases.current.delete(identity) - } + inFlightPurchases.current.delete(identity) } }, [entitlement]) @@ -423,20 +406,16 @@ 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') } @@ -475,7 +454,6 @@ 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 @@ -513,7 +491,6 @@ 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') } @@ -548,9 +525,7 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re await restoreGooglePlayPurchaseSet( restoredPurchases, async (restoredPurchase) => { - if (!mountedRef.current || userIdRef.current !== currentUserId) { - throw new Error('restore_session_changed') - } + if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed') const result = await invokeEdgeFunction('iap-verify', { platform: 'google_play', productId: restoredPurchase.productId, @@ -561,18 +536,14 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re return data }, async () => { - if (!mountedRef.current || userIdRef.current !== currentUserId) { - throw new Error('restore_session_changed') - } + if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed') return entitlement.refresh() }, ) - if (!mountedRef.current || userIdRef.current !== currentUserId) { - throw new Error('restore_session_changed') - } + if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed') setOperation('succeeded') } catch (candidate) { - if (!mountedRef.current || userIdRef.current !== currentUserId) return + if (userIdRef.current !== currentUserId) return setOperation('failed') setErrorCode(candidate instanceof Error ? candidate.message : 'restore_failed') } diff --git a/apps/mobile-rn/src/lib/device-context.tsx b/apps/mobile-rn/src/lib/device-context.tsx index 75986fbf..52b66478 100644 --- a/apps/mobile-rn/src/lib/device-context.tsx +++ b/apps/mobile-rn/src/lib/device-context.tsx @@ -39,12 +39,7 @@ export function DeviceProvider({ children }: { children: ReactNode }): React.Rea const handleRevocation = useCallback(async (): Promise => { if (revocationHandledRef.current) return revocationHandledRef.current = true - try { - await purgeLocalSession() - } catch (revocationError) { - revocationHandledRef.current = false - throw revocationError - } + await purgeLocalSession() }, [purgeLocalSession]) const refreshCurrentDevice = useCallback(async (): Promise => { diff --git a/apps/mobile-rn/src/lib/entitlement-context.tsx b/apps/mobile-rn/src/lib/entitlement-context.tsx index f9c2e02b..dff7d6b9 100644 --- a/apps/mobile-rn/src/lib/entitlement-context.tsx +++ b/apps/mobile-rn/src/lib/entitlement-context.tsx @@ -280,7 +280,7 @@ function isCachedSnapshot(value: unknown, userId: string): value is CacheEnvelop } async function readCache(userId: string): Promise { - const serialized = await AsyncStorage.getItem(cacheKey(userId)).catch(() => null) + const serialized = await AsyncStorage.getItem(cacheKey(userId)) 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) - }).catch(() => null).finally(() => { + }).finally(() => { if (!cancelled) void refresh() }) diff --git a/apps/mobile-rn/src/lib/mobile-ads-context.tsx b/apps/mobile-rn/src/lib/mobile-ads-context.tsx index 59a265fe..65ca648b 100644 --- a/apps/mobile-rn/src/lib/mobile-ads-context.tsx +++ b/apps/mobile-rn/src/lib/mobile-ads-context.tsx @@ -86,8 +86,7 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React. } }, []) - const initializeAds = useCallback(async (expectedGeneration: number): Promise => { - if (expectedGeneration !== generation.current) return + const initializeAds = useCallback(async (): Promise => { if (initialized.current) { setStatus('ready') return @@ -97,17 +96,11 @@ 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) { @@ -134,7 +127,7 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React. setStatus('consent-blocked') return } - await initializeAds(currentGeneration) + await initializeAds() }) .catch((candidate) => { if (currentGeneration !== generation.current) return @@ -144,36 +137,25 @@ 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 => { - 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 (opEligible && consentInfo.canRequestAds) await initializeAds(opGeneration) - if (opEligible && !consentInfo.canRequestAds && opGeneration === generation.current) { - setStatus('consent-blocked') - } + if (eligible && consentInfo.canRequestAds) await initializeAds() + if (eligible && !consentInfo.canRequestAds) setStatus('consent-blocked') return true } catch (candidate) { - if (opGeneration !== generation.current) return false setErrorCode(candidateMessage(candidate, 'privacy_options_unavailable')) return false } @@ -336,7 +318,6 @@ 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 diff --git a/apps/mobile-rn/src/lib/recorder/android-foreground-backend.ts b/apps/mobile-rn/src/lib/recorder/android-foreground-backend.ts index 12536741..17d6fd24 100644 --- a/apps/mobile-rn/src/lib/recorder/android-foreground-backend.ts +++ b/apps/mobile-rn/src/lib/recorder/android-foreground-backend.ts @@ -139,8 +139,6 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { private progressHandler: RecordingProgressHandler | null = null; private stateHandler: RecordingStateHandler | null = null; private pollGeneration = 0; - private pollTimer: ReturnType | null = null; - private sessionGeneration = 0; async requestPermission(): Promise { const permission = PermissionsAndroid.PERMISSIONS.RECORD_AUDIO; @@ -165,7 +163,6 @@ 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; @@ -177,10 +174,6 @@ 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'); } @@ -193,9 +186,10 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { this.stateHandler?.(snapshot); this.startPolling(); } catch (error) { - if (sessionGen === this.sessionGeneration) { - this.resetToIdle(); - } + this.progressHandler = null; + this.stateHandler = null; + this.currentPath = null; + this.state = 'idle'; throw error; } } @@ -205,20 +199,14 @@ 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'; - } + this.state = 'recording'; throw error; } } @@ -228,20 +216,14 @@ 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'; - } + this.state = 'paused'; throw error; } } @@ -252,19 +234,13 @@ 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); - } + await this.resyncAfterFailedStop(previousState, null); throw error; } @@ -297,19 +273,14 @@ 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 { - const cancelGen = ++this.sessionGeneration; this.stopPolling(); - this.resetToIdle(); await androidRecordingModule().cancel(); - if (cancelGen === this.sessionGeneration) { - this.resetToIdle(); - } + this.resetToIdle(); } async restore( @@ -317,7 +288,6 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { onStateChange?: RecordingStateHandler, ): Promise { const snapshot = parseNativeSnapshot(await androidRecordingModule().getStatus()); - this.sessionGeneration += 1; this.stopPolling(); this.progressHandler = onProgress ?? null; this.stateHandler = onStateChange ?? null; @@ -416,13 +386,7 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { this.stateHandler?.(snapshot); if (snapshot.state === 'recording' || snapshot.state === 'paused') { this.state = snapshot.state; - if (generation === this.pollGeneration) { - if (this.pollTimer !== null) clearTimeout(this.pollTimer); - this.pollTimer = setTimeout(() => { - this.pollTimer = null; - void poll(); - }, 250); - } + setTimeout(() => { void poll(); }, 250); } else { this.currentPath = snapshot.recording?.path ?? null; this.state = snapshot.state === 'idle' ? 'idle' : 'stopped'; @@ -430,11 +394,7 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { } catch { // A transient React bridge failure must not stop the native foreground capture. if (generation === this.pollGeneration) { - if (this.pollTimer !== null) clearTimeout(this.pollTimer); - this.pollTimer = setTimeout(() => { - this.pollTimer = null; - void poll(); - }, 500); + setTimeout(() => { void poll(); }, 500); } } }; @@ -443,9 +403,5 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { private stopPolling(): void { this.pollGeneration += 1; - if (this.pollTimer !== null) { - clearTimeout(this.pollTimer); - this.pollTimer = null; - } } } diff --git a/apps/mobile-rn/src/lib/recorder/nitro-backend.ts b/apps/mobile-rn/src/lib/recorder/nitro-backend.ts index 5b037dcf..d9f05739 100644 --- a/apps/mobile-rn/src/lib/recorder/nitro-backend.ts +++ b/apps/mobile-rn/src/lib/recorder/nitro-backend.ts @@ -104,7 +104,6 @@ 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 | null = null; private pendingTransition: Promise | null = null; private pendingStop: Promise | null = null; @@ -145,21 +144,14 @@ 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'; - } + 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 }; @@ -304,15 +296,10 @@ export class NitroRecorderBackend implements RecorderBackend { } async cancel(): Promise { - 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; } } diff --git a/apps/mobile-rn/src/screens/CommandsScreen.tsx b/apps/mobile-rn/src/screens/CommandsScreen.tsx index 6043e3b4..68dd52d2 100644 --- a/apps/mobile-rn/src/screens/CommandsScreen.tsx +++ b/apps/mobile-rn/src/screens/CommandsScreen.tsx @@ -98,14 +98,6 @@ export default function CommandsScreen(): React.ReactElement { const styles = useMemo(() => createStyles(palette), [palette]) const alive = useRef(true) const request = useRef(null) - const loadGeneration = useRef(0) - const actorUserIdRef = useRef(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([]) const [activeId, setActiveId] = useState(null) const [selectedId, setSelectedId] = useState(null) @@ -131,20 +123,16 @@ export default function CommandsScreen(): React.ReactElement { ), [t]) const load = useCallback(async (pull = false, silent = false): Promise => { - const generation = ++loadGeneration.current - const actorUserId = user?.id ?? null - const actorScope = scopeGenerationRef.current - if (!actorUserId) { + if (!user?.id) { setLoading(false) - setRefreshing(false) setSyncError('auth') return } if (pull) setRefreshing(true) else if (!silent) setLoading(true) try { - const catalog = await loadSyncedCommandCatalog(actorUserId) - if (!isCurrentActor(actorUserId, actorScope) || generation !== loadGeneration.current) return + const catalog = await loadSyncedCommandCatalog(user.id) + if (!alive.current) return setCommands(catalog.commands) setActiveId(catalog.activeInstructionId) setSelectedId((current) => ( @@ -154,51 +142,19 @@ export default function CommandsScreen(): React.ReactElement { )) setSyncError(null) } catch (error) { - if (isCurrentActor(actorUserId, actorScope) && generation === loadGeneration.current) { - setSyncError(error instanceof CommandSyncError ? error.code : 'server') - } + if (alive.current) setSyncError(error instanceof CommandSyncError ? error.code : 'server') } finally { - if (isCurrentActor(actorUserId, actorScope) && generation === loadGeneration.current) { + if (alive.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() - return () => { loadGeneration.current += 1 } - }, [load])) - useEffect(() => { - alive.current = true - return () => { - alive.current = false - loadGeneration.current += 1 - request.current?.abort() - } + useFocusEffect(useCallback(() => { void load() }, [load])) + useEffect(() => () => { + alive.current = false + request.current?.abort() }, []) useEffect(() => { if (!user?.id) return undefined @@ -222,19 +178,14 @@ export default function CommandsScreen(): React.ReactElement { async function toggleActive(command: SyncedCommand): Promise { if (!user?.id || mutationId) return - const actorUserId = user.id - const actorScope = scopeGenerationRef.current setMutationId(command.id) try { - const nextActiveId = await setActiveSyncedCommand(actorUserId, activeId === command.id ? null : command.id) - if (!isCurrentActor(actorUserId, actorScope)) return - setActiveId(nextActiveId) + setActiveId(await setActiveSyncedCommand(user.id, activeId === command.id ? null : command.id)) setSyncError(null) } catch (error) { - if (!isCurrentActor(actorUserId, actorScope)) return setSyncError(error instanceof CommandSyncError ? error.code : 'server') } finally { - if (isCurrentActor(actorUserId, actorScope)) setMutationId(null) + setMutationId(null) } } @@ -256,50 +207,42 @@ export default function CommandsScreen(): React.ReactElement { async function save(): Promise { 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(actorUserId, editor.command, editor) - : await createSyncedCommand(actorUserId, { + ? await updateSyncedCommand(user.id, editor.command, editor) + : await createSyncedCommand(user.id, { ...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 { - if (isCurrentActor(actorUserId, actorScope)) setMutationId(null) + setMutationId(null) } } async function remove(command: SyncedCommand): Promise { if (!user?.id || mutationId) return - const actorUserId = user.id - const actorScope = scopeGenerationRef.current setMutationId(command.id) try { - await deleteSyncedCommand(actorUserId, command) - if (!isCurrentActor(actorUserId, actorScope)) return + await deleteSyncedCommand(user.id, command) 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 { - if (isCurrentActor(actorUserId, actorScope)) setMutationId(null) + setMutationId(null) } } @@ -316,25 +259,18 @@ export default function CommandsScreen(): React.ReactElement { async function move(command: SyncedCommand, direction: 'up' | 'down'): Promise { if (!user?.id || mutationId) return - const actorUserId = user.id - const actorScope = scopeGenerationRef.current setMutationId(command.id) try { - const reordered = await reorderSyncedCommand(actorUserId, command, direction) - if (!isCurrentActor(actorUserId, actorScope)) return - setCommands(reordered) + setCommands(await reorderSyncedCommand(user.id, command, direction)) } catch (error) { - if (!isCurrentActor(actorUserId, actorScope)) return setSyncError(error instanceof CommandSyncError ? error.code : 'server') } finally { - if (isCurrentActor(actorUserId, actorScope)) setMutationId(null) + setMutationId(null) } } const run = useCallback(async (): Promise => { if (!selected || running) return - const actorUserId = actorUserIdRef.current - const actorScope = scopeGenerationRef.current const token = session?.access_token ?? '' if (!token) { setRunError('AUTH_REQUIRED') @@ -347,15 +283,12 @@ export default function CommandsScreen(): React.ReactElement { setRunError(null) setRetryable(false) try { - const result = await executeSyncedCommand(selected, input, { + setOutput(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) @@ -365,9 +298,9 @@ export default function CommandsScreen(): React.ReactElement { } } finally { if (request.current === controller) request.current = null - if (isCurrentActor(actorUserId, actorScope)) setRunning(false) + if (alive.current) setRunning(false) } - }, [input, isCurrentActor, preferences.preferredLlmModel, running, selected, session?.access_token]) + }, [input, preferences.preferredLlmModel, running, selected, session?.access_token]) return ( (null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) @@ -110,7 +109,6 @@ export default function HistoryDetailScreen({ return () => { mountedRef.current = false loadGenerationRef.current += 1 - playbackGenerationRef.current += 1 void Promise.resolve(playerRef.current.stopPlayer()).catch(() => undefined) } }, []) @@ -308,62 +306,53 @@ export default function HistoryDetailScreen({ const controlAudio = async (audioFile: AudioFile): Promise => { 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 && playbackGeneration === playbackGenerationRef.current) setPaused(true) + if (mountedRef.current) setPaused(true) return } if (activeAudioId === audioFile.id && paused) { await player.resumePlayer() - if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(false) + if (mountedRef.current) setPaused(false) return } if (activeAudioId !== null) { await player.stopPlayer() - if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return + if (!mountedRef.current) return } const signedUrl = await createAudioPlaybackUrl(user.id, audioFile) - if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return + if (!mountedRef.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 || playbackGeneration !== playbackGenerationRef.current) return + if (!mountedRef.current) return setActiveAudioId(null) setPaused(false) setError(t('mobile.hist.audioError')) } finally { - if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) { - setAudioBusy(false) - } + if (mountedRef.current) setAudioBusy(false) } } const stopAudio = async (): Promise => { - const playbackGeneration = ++playbackGenerationRef.current setAudioBusy(true) try { await player.stopPlayer() - if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return + if (!mountedRef.current) return setActiveAudioId(null) setPaused(false) } catch { - if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) { - setError(t('mobile.hist.audioError')) - } + if (mountedRef.current) setError(t('mobile.hist.audioError')) } finally { - if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) { - setAudioBusy(false) - } + if (mountedRef.current) setAudioBusy(false) } } diff --git a/apps/mobile-rn/src/screens/HomeScreen.tsx b/apps/mobile-rn/src/screens/HomeScreen.tsx index 24bd4131..8b71b97c 100644 --- a/apps/mobile-rn/src/screens/HomeScreen.tsx +++ b/apps/mobile-rn/src/screens/HomeScreen.tsx @@ -1,7 +1,7 @@ // src/screens/HomeScreen.tsx — 홈(오늘). 데스크톱 HomePage 와 같은 문법: // 제목·날짜 → 녹음 시작 안내 → 한 줄 요약 → 최근 기록 5 · 최근 회의 3 → (무료) 요금제 한 줄. // 카드·통계 격자 없이 제목 + 1px 선. 조회한 값만 보여 주고, 못 불러오면 그렇다고 말한다. -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useMemo, useState } from 'react' import { Pressable, RefreshControl, @@ -91,46 +91,21 @@ 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(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 => { - const generation = ++refreshGenerationRef.current - const targetUserId = user?.id ?? null - if (!targetUserId) { - setStats(null) - setMeetings(null) + if (!user?.id) { setStatsError(true) setMeetingsError(true) setLoading(false) - setRefreshing(false) return } if (pullToRefresh) setRefreshing(true) else setLoading(true) const [statsResult, meetingsResult] = await Promise.allSettled([ - loadDashboardStats(targetUserId), - listMeetingsPage({ userId: targetUserId, page: 0, pageSize: RECENT_MEETING_LIMIT }), + loadDashboardStats(user.id), + listMeetingsPage({ userId: user.id, 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) diff --git a/apps/mobile-rn/src/screens/KnowledgeScreen.tsx b/apps/mobile-rn/src/screens/KnowledgeScreen.tsx index c72db625..9a2abb2d 100644 --- a/apps/mobile-rn/src/screens/KnowledgeScreen.tsx +++ b/apps/mobile-rn/src/screens/KnowledgeScreen.tsx @@ -127,7 +127,6 @@ export default function KnowledgeScreen(): React.ReactElement { const loadMore = async (): Promise => { if (user === null || loading || loadingMore || !hasMore) return - const generation = requestGeneration.current const targetPage = page + 1 setLoadingMore(true) try { @@ -136,16 +135,14 @@ 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 { - if (generation === requestGeneration.current) setLoadingMore(false) + setLoadingMore(false) } } diff --git a/apps/mobile-rn/src/screens/MeetingsScreen.tsx b/apps/mobile-rn/src/screens/MeetingsScreen.tsx index cd90bee3..23f23a05 100644 --- a/apps/mobile-rn/src/screens/MeetingsScreen.tsx +++ b/apps/mobile-rn/src/screens/MeetingsScreen.tsx @@ -61,7 +61,6 @@ 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()) const openCreateRef = useRef<() => void>(() => undefined) const [meetings, setMeetings] = useState([]) @@ -86,13 +85,6 @@ export default function MeetingsScreen({ const [editorError, setEditorError] = useState(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 @@ -160,7 +152,6 @@ export default function MeetingsScreen({ const loadMore = async (): Promise => { if (user === null || loading || loadingMore || !hasMore) return - const generation = requestGeneration.current const targetPage = page + 1 setLoadingMore(true) try { @@ -169,18 +160,14 @@ 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) - } + setLoadingMore(false) } } @@ -270,7 +257,6 @@ export default function MeetingsScreen({ const saveEditor = async (): Promise => { if (user === null || editor === null || editorBusyRef.current) return const mode = editor - const actorUserId = user.id editorBusyRef.current = true setEditorBusy(true) setEditorError(null) @@ -283,14 +269,13 @@ export default function MeetingsScreen({ .split(/[\r\n,]+/) .map((attendee) => attendee.trim()) .filter((attendee) => attendee.length > 0) - const created = await createMeetingWorkspaceWithMetadata(actorUserId, { + const created = await createMeetingWorkspaceWithMetadata(user.id, { 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) @@ -310,20 +295,16 @@ 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) - } + editorBusyRef.current = false + setEditorBusy(false) } } diff --git a/apps/mobile-rn/src/screens/RecordScreen.tsx b/apps/mobile-rn/src/screens/RecordScreen.tsx index 4f56b166..5702d43f 100644 --- a/apps/mobile-rn/src/screens/RecordScreen.tsx +++ b/apps/mobile-rn/src/screens/RecordScreen.tsx @@ -703,10 +703,6 @@ 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 { diff --git a/apps/mobile-rn/src/screens/TeamsScreen.tsx b/apps/mobile-rn/src/screens/TeamsScreen.tsx index 956a005b..3782d48f 100644 --- a/apps/mobile-rn/src/screens/TeamsScreen.tsx +++ b/apps/mobile-rn/src/screens/TeamsScreen.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useMemo, useRef, useState } from 'react' import { ActivityIndicator, KeyboardAvoidingView, @@ -37,9 +37,6 @@ 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(user?.id ?? null) - const scopeGenerationRef = useRef(0) const [teams, setTeams] = useState([]) const [loading, setLoading] = useState(true) const [refreshing, setRefreshing] = useState(false) @@ -73,26 +70,6 @@ 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 } @@ -100,27 +77,18 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea const submitCreate = async (): Promise => { 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(actorUserId, name) - if (!isCurrentActor()) return + const team = await createTeam(user.id, name) 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 { - if (isCurrentActor()) setEditorBusy(false) + setEditorBusy(false) } } diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js index d15b7796..98d55479 100644 --- a/apps/web/public/sw.js +++ b/apps/web/public/sw.js @@ -5,42 +5,17 @@ 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' || hasUnsafeUrlChars(rawUrl)) { + if (typeof rawUrl !== 'string' || !rawUrl.trim()) { return DEFAULT_TARGET_URL } const trimmed = rawUrl.trim() - if (!trimmed || !trimmed.startsWith('/') || trimmed.startsWith('//')) { + if (!trimmed.startsWith('/') || trimmed.startsWith('//') || trimmed.startsWith('/\\')) { return DEFAULT_TARGET_URL } - const candidate = trimmed.startsWith('/app/') || trimmed === '/app' + return 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) { diff --git a/apps/web/src/app/(app)/history/[id]/page.tsx b/apps/web/src/app/(app)/history/[id]/page.tsx index 86becad9..ddf58503 100644 --- a/apps/web/src/app/(app)/history/[id]/page.tsx +++ b/apps/web/src/app/(app)/history/[id]/page.tsx @@ -2,7 +2,7 @@ import Link from 'next/link' import { useParams, useRouter } from 'next/navigation' -import React, { useCallback, useEffect, useRef, useState } from 'react' +import React, { useCallback, useEffect, useState } from 'react' import { Alert, Box, @@ -19,7 +19,6 @@ 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, @@ -64,18 +63,6 @@ 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 | null>(null) - - useEffect(() => { - mountedRef.current = true - return () => { - mountedRef.current = false - loadGenerationRef.current += 1 - clearTrackedTimeout(copyTimerRef) - } - }, []) const applyEntry = (next: HistoryEntry): void => { setEntry(next) @@ -85,23 +72,17 @@ export default function HistoryDetailPage(): React.ReactElement { } const loadEntry = useCallback(async (): Promise => { - const generation = ++loadGenerationRef.current setLoading(true) setError(null) try { const client = asApiClient() const userId = await requireCurrentUser(client) - const loaded = await getHistoryEntry(client, userId, entryId) - if (!mountedRef.current || generation !== loadGenerationRef.current) return - applyEntry(loaded) + applyEntry(await getHistoryEntry(client, userId, entryId)) } catch (requestError) { - if (!mountedRef.current || generation !== loadGenerationRef.current) return setEntry(null) setError(historyMessage(requestError)) } finally { - if (mountedRef.current && generation === loadGenerationRef.current) { - setLoading(false) - } + setLoading(false) } }, [entryId]) @@ -197,15 +178,10 @@ 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) - scheduleTrackedTimeout(copyTimerRef, () => { - if (mountedRef.current) setCopied(false) - }, 2000) + window.setTimeout(() => setCopied(false), 2000) } catch { - if (mountedRef.current) { - setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.') - } + setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.') } } diff --git a/apps/web/src/app/(app)/history/page.tsx b/apps/web/src/app/(app)/history/page.tsx index 9cbdda2a..840fa2f7 100644 --- a/apps/web/src/app/(app)/history/page.tsx +++ b/apps/web/src/app/(app)/history/page.tsx @@ -28,7 +28,6 @@ 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, @@ -82,16 +81,6 @@ export default function HistoryPage(): React.ReactElement { const [copiedId, setCopiedId] = useState(null) const [mutatingIds, setMutatingIds] = useState>(() => new Set()) const requestGeneration = useRef(0) - const mountedRef = useRef(true) - const copyTimerRef = useRef | null>(null) - - useEffect(() => { - mountedRef.current = true - return () => { - mountedRef.current = false - clearTrackedTimeout(copyTimerRef) - } - }, []) useEffect(() => { const timer = window.setTimeout(() => setSearch(searchInput), SEARCH_DELAY_MS) @@ -243,17 +232,10 @@ export default function HistoryPage(): React.ReactElement { const copyText = async (entry: HistoryEntry): Promise => { try { await navigator.clipboard.writeText(entry.polished_text ?? entry.original_text) - if (!mountedRef.current) return setCopiedId(entry.id) - scheduleTrackedTimeout(copyTimerRef, () => { - if (mountedRef.current) { - setCopiedId((current) => (current === entry.id ? null : current)) - } - }, 2000) + window.setTimeout(() => setCopiedId((current) => current === entry.id ? null : current), 2000) } catch { - if (mountedRef.current) { - setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.') - } + setError('클립보드에 복사하지 못했습니다. 브라우저 권한을 확인해 주세요.') } } diff --git a/apps/web/src/app/auth/callback/route.ts b/apps/web/src/app/auth/callback/route.ts index 911f77ed..b03e66c3 100644 --- a/apps/web/src/app/auth/callback/route.ts +++ b/apps/web/src/app/auth/callback/route.ts @@ -33,7 +33,7 @@ export async function GET(request: NextRequest): Promise { const { error } = await supabase.auth.exchangeCodeForSession(code) if (error) { - return NextResponse.redirect(appUrlFor(origin, '/login?error=oauth_callback_failed')) + return NextResponse.redirect(appUrlFor(origin, `/login?error=${encodeURIComponent(error.message)}`)) } return NextResponse.redirect(appUrlFor(origin, next)) diff --git a/apps/web/src/components/actions/action-runner.tsx b/apps/web/src/components/actions/action-runner.tsx index 6fdf7190..ca64f458 100644 --- a/apps/web/src/components/actions/action-runner.tsx +++ b/apps/web/src/components/actions/action-runner.tsx @@ -4,16 +4,11 @@ // 텍스트 명령 → LLM 파싱 (function-like JSON) → 동작 시뮬레이션. // V1 VoiceActionService의 간이 web 포트. -import { useEffect, useRef, useState } from 'react' +import { 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 = @@ -57,17 +52,6 @@ export function ActionRunner(): React.ReactElement { const [error, setError] = useState(null) const [result, setResult] = useState(null) const [executed, setExecuted] = useState(null) - const mountedRef = useRef(true) - const abortRef = useRef(null) - - useEffect(() => { - mountedRef.current = true - return () => { - mountedRef.current = false - abortRef.current?.abort() - abortRef.current = null - } - }, []) async function handleParse(): Promise { if (!input.trim()) return @@ -75,27 +59,24 @@ 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( - resolveSupabaseFunctionUrl('llm-proxy'), + `${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/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, @@ -118,22 +99,11 @@ export function ActionRunner(): React.ReactElement { } const parsed = JSON.parse(jsonMatch[0]) as ActionResult - if (mountedRef.current) { - setResult(parsed) - } + setResult(parsed) } catch (e) { - if (mountedRef.current) { - setError(timedAbort.didTimeout() - ? '명령 파싱 시간이 초과되었습니다.' - : e instanceof Error - ? e.message - : 'Unknown error') - } + setError(e instanceof Error ? e.message : 'Unknown error') } finally { - timedAbort.dispose() - if (mountedRef.current) { - setBusy(false) - } + setBusy(false) } } @@ -146,7 +116,6 @@ export function ActionRunner(): React.ReactElement { const { data: { user } } = await supabase.auth.getUser() - if (!mountedRef.current) return if (!user) { throw new Error('로그인이 필요합니다') } @@ -157,7 +126,6 @@ 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 @@ -179,7 +147,6 @@ export function ActionRunner(): React.ReactElement { content, timestamp_ms: 0 }) - if (!mountedRef.current) return if (err) throw new Error(err.message) setExecuted(`메모 생성됨: "${content}"`) break @@ -191,13 +158,9 @@ export function ActionRunner(): React.ReactElement { setExecuted('알 수 없는 액션 — 실행 불가') } } catch (e) { - if (mountedRef.current) { - setError(e instanceof Error ? e.message : 'Unknown error') - } + setError(e instanceof Error ? e.message : 'Unknown error') } finally { - if (mountedRef.current) { - setBusy(false) - } + setBusy(false) } } diff --git a/apps/web/src/components/billing/payple-checkout-button.tsx b/apps/web/src/components/billing/payple-checkout-button.tsx index efc0e7b3..145f2561 100644 --- a/apps/web/src/components/billing/payple-checkout-button.tsx +++ b/apps/web/src/components/billing/payple-checkout-button.tsx @@ -1,14 +1,8 @@ 'use client' -import { useCallback, useEffect, useRef, useState } from 'react' +import { useCallback, useEffect, 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 { @@ -45,11 +39,14 @@ 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 resolveSupabaseFunctionUrl('payple-checkout') - } catch (err) { - const message = err instanceof Error ? err.message : '결제 서버 설정이 올바르지 않습니다.' - throw new PaypleClientError('not_configured', message) + return new URL('/functions/v1/payple-checkout', baseUrl).toString() + } catch { + throw new PaypleClientError('not_configured', '결제 서버 설정이 올바르지 않습니다.') } } @@ -58,21 +55,11 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto const [error, setError] = useState(null) const [success, setSuccess] = useState(false) const [sdkReady, setSdkReady] = useState(false) - const mountedRef = useRef(true) - const reloadTimerRef = useRef | null>(null) - const abortRef = useRef(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 => { @@ -111,31 +98,24 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto resultUrl: browserBillingUrl(), openSdk: (request) => window.PaypleCpayAuthCheck(request), chargeBillingKey: async (payerId, result) => { - 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, - idempotency_key: idempotencyKey, - pcd_pay_cardname: typeof result['PCD_PAY_CARDNAME'] === 'string' - ? result['PCD_PAY_CARDNAME'] - : undefined, - pcd_pay_cardnum: typeof result['PCD_PAY_CARDNUM'] === 'string' - ? result['PCD_PAY_CARDNUM'] - : undefined - }) + const response = await fetch(checkoutEndpoint(), { + method: 'POST', + headers: { + Authorization: `Bearer ${session.access_token}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + payer_id: payerId, + tier, + idempotency_key: idempotencyKey, + pcd_pay_cardname: typeof result['PCD_PAY_CARDNAME'] === 'string' + ? result['PCD_PAY_CARDNAME'] + : undefined, + pcd_pay_cardnum: typeof result['PCD_PAY_CARDNUM'] === 'string' + ? result['PCD_PAY_CARDNUM'] + : undefined }) - } finally { - timedAbort.dispose() - } + }) let payload: unknown try { @@ -156,17 +136,12 @@ export function PaypleCheckoutButton({ tier, catalogPrice }: PaypleCheckoutButto } }) - if (!mountedRef.current) return setSuccess(true) - scheduleTrackedTimeout(reloadTimerRef, () => window.location.reload(), 2000) + window.setTimeout(() => window.location.reload(), 2000) } catch (checkoutError) { - if (mountedRef.current) { - setError(checkoutErrorMessage(checkoutError)) - } + setError(checkoutErrorMessage(checkoutError)) } finally { - if (mountedRef.current) { - setBusy(false) - } + setBusy(false) } }, [catalogPrice, sdkReady, tier]) diff --git a/apps/web/src/components/billing/payple-manage-button.tsx b/apps/web/src/components/billing/payple-manage-button.tsx index 28091e5b..5283af26 100644 --- a/apps/web/src/components/billing/payple-manage-button.tsx +++ b/apps/web/src/components/billing/payple-manage-button.tsx @@ -3,16 +3,9 @@ // apps/web/src/components/billing/payple-manage-button.tsx // Payple 구독 관리 — payple-manage Edge Function 호출 (구독 취소) -import { useEffect, useRef, useState } from 'react' +import { useEffect, 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 { @@ -21,38 +14,27 @@ 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 | null>(null) - const abortRef = useRef(null) - useEffect(() => { - mountedRef.current = true - setReady(true) - return () => { - mountedRef.current = false - clearTrackedTimeout(reloadTimerRef) - abortRef.current?.abort() - abortRef.current = null - } - }, []) + useEffect(() => setReady(true), []) async function handleCancel(): Promise { 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( - resolveSupabaseFunctionUrl('payple-manage'), + new URL('/functions/v1/payple-manage', baseUrl).toString(), { method: 'POST', headers: { @@ -60,7 +42,6 @@ export function PaypleManageButton(): React.ReactElement { 'Content-Type': 'application/json', }, body: JSON.stringify({ action: 'cancel' }), - signal: timedAbort.controller.signal, } ) @@ -77,22 +58,12 @@ export function PaypleManageButton(): React.ReactElement { ) { throw new Error('구독 취소 결과를 확인할 수 없습니다.') } - if (!mountedRef.current) return setSuccess(true) - scheduleTrackedTimeout(reloadTimerRef, () => window.location.reload(), 2000) + window.setTimeout(() => window.location.reload(), 2000) } catch (e) { - if (mountedRef.current) { - setError(timedAbort.didTimeout() - ? '요청 시간이 초과되었습니다. 잠시 후 다시 시도해 주세요.' - : e instanceof Error - ? e.message - : '알 수 없는 오류') - } + setError(e instanceof Error ? e.message : '알 수 없는 오류') } finally { - timedAbort.dispose() - if (mountedRef.current) { - setBusy(false) - } + setBusy(false) } } diff --git a/apps/web/src/components/chat/chat-panel.tsx b/apps/web/src/components/chat/chat-panel.tsx index 503463d0..f9d2cc33 100644 --- a/apps/web/src/components/chat/chat-panel.tsx +++ b/apps/web/src/components/chat/chat-panel.tsx @@ -8,212 +8,17 @@ 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' -export interface ChatMessage { +interface Message { id: string role: 'user' | 'assistant' content: string timestamp: string } -export async function executeChatSendTurn(options: { - text: string - messages: ChatMessage[] - activeControllerRef: { current: AbortController | null } - isMounted: () => boolean - isConfigured: () => boolean - getAccessToken: () => Promise - 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 { - const { - text, - messages, - activeControllerRef, - isMounted, - isConfigured, - getAccessToken, - endpointUrl, - fetchImpl = fetch, - timeoutMs = 45_000, - onMessagesUpdate, - onInputChange, - onErrorChange, - onBusyChange, - } = options - - 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] - const assistantId = 'a_' + Date.now() - onMessagesUpdate(() => nextMessages) - onInputChange('') - onErrorChange(null) - onBusyChange(true) - const timedAbort = createTimedAbortSignal(timeoutMs, activeControllerRef) - - try { - if (!isConfigured()) { - throw new Error('Supabase 미설정') - } - - const accessToken = await getAccessToken() - if (shouldExitAfterAwait(timedAbort, isMounted)) return - - if (!accessToken) { - throw new Error('로그인 필요') - } - - const payload = { - messages: nextMessages.map((m) => ({ role: m.role, content: m.content })), - max_tokens: 1024, - stream: true - } - - const response = await fetchImpl( - endpointUrl ?? resolveSupabaseFunctionUrl('llm-proxy'), - { - method: 'POST', - headers: { - Authorization: 'Bearer ' + accessToken, - 'Content-Type': 'application/json', - }, - body: JSON.stringify(payload), - signal: timedAbort.controller.signal - } - ) - - if (!response.ok) { - const body = await response.json().catch(() => null) as { error?: unknown } | null - const code = typeof body?.error === 'string' ? body.error : `http_${response.status}` - throw new Error(code) - } - - if (!response.body) throw new Error('empty_response') - - if (!isMounted()) return - onMessagesUpdate((prev) => [ - ...prev, - { - id: assistantId, - role: 'assistant', - content: '', - timestamp: new Date().toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' }) - } - ]) - - 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 - signal: AbortSignal - onAccumulated: (accumulated: string) => void -}): Promise { - const { body, signal, onAccumulated } = options - const reader = body.getReader() - const decoder = new TextDecoder() - let buffer = '' - let accumulated = '' - - 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') - buffer = lines.pop() ?? '' - - for (const line of lines) { - const trimmed = line.trim() - if (!trimmed.startsWith('data:')) continue - const data = trimmed.slice(5).trim() - if (data === '[DONE]' || data === '') continue - - try { - 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 += typeof event.delta.text === 'string' ? event.delta.text : '' - if (!signal.aborted) { - onAccumulated(accumulated) - } - } - } catch { - // Ignore malformed SSE lines - } - } - } - } finally { - signal.removeEventListener('abort', onAbort) - await reader.cancel().catch(() => {}) - } - - return accumulated -} - export function ChatPanel(): React.ReactElement { - const [messages, setMessages] = useState([ + const [messages, setMessages] = useState([ { id: 'welcome', role: 'assistant', @@ -225,30 +30,15 @@ export function ChatPanel(): React.ReactElement { const [busy, setBusy] = useState(false) const [error, setError] = useState(null) const scrollRef = useRef(null) - const mountedRef = useRef(true) - const rafRef = useRef(null) - const activeControllerRef = useRef(null) function scrollToBottom(): void { - if (rafRef.current !== null) cancelAnimationFrame(rafRef.current) - rafRef.current = requestAnimationFrame(() => { - rafRef.current = null + requestAnimationFrame(() => { 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]) @@ -257,22 +47,124 @@ export function ChatPanel(): React.ReactElement { 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, - }) + const userMsg: Message = { + 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 + + try { + if (!isSupabaseConfigured()) { + throw new Error('Supabase 미설정') + } + + const supabase = getSupabaseBrowserClient() + const { data: { session } } = await supabase.auth.getSession() + + if (!session) { + throw new Error('로그인 필요') + } + + const payload = { + messages: nextMessages.map((m) => ({ role: m.role, content: m.content })), + max_tokens: 1024, + 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', + { + method: 'POST', + headers: { + Authorization: 'Bearer ' + session.access_token, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(payload), + signal: controller.signal + } + ) + + if (!response.ok) { + const body = await response.json().catch(() => null) as { error?: unknown } | null + const code = typeof body?.error === 'string' ? body.error : `http_${response.status}` + throw new Error(code) + } + + if (!response.body) throw new Error('empty_response') + + const assistantId = 'a_' + Date.now() + setMessages((prev) => [ + ...prev, + { + id: assistantId, + role: 'assistant', + content: '', + timestamp: new Date().toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' }) + } + ]) + + const reader = response.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 + } + + buffer += decoder.decode(value, { stream: true }) + const lines = buffer.split('\n') + buffer = lines.pop() ?? '' + + for (const line of lines) { + const trimmed = line.trim() + if (!trimmed.startsWith('data:')) continue + const data = trimmed.slice(5).trim() + if (data === '[DONE]' || data === '') continue + + try { + const event = JSON.parse(data) + 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)) + ) + } + } catch { + // Ignore parse errors + } + } + } + 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) + } } return ( diff --git a/apps/web/src/components/meetings/document-editor.tsx b/apps/web/src/components/meetings/document-editor.tsx index c3bc529b..03aee94d 100644 --- a/apps/web/src/components/meetings/document-editor.tsx +++ b/apps/web/src/components/meetings/document-editor.tsx @@ -4,7 +4,7 @@ // 회의록 문서 편집 — MarkdownEditor 다이얼로그 // 클릭 → 다이얼로그 열림 → textarea 편집 → 저장 시 meeting_documents UPDATE -import { useEffect, useRef, useState } from 'react' +import { useState } from 'react' import dynamic from 'next/dynamic' import { useRouter } from 'next/navigation' import { @@ -52,14 +52,6 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement const [busy, setBusy] = useState(false) const [error, setError] = useState(null) const [tab, setTab] = useState<'edit' | 'preview'>('edit') - const mountedRef = useRef(true) - - useEffect(() => { - mountedRef.current = true - return () => { - mountedRef.current = false - } - }, []) async function handleSave(): Promise { setError(null) @@ -71,7 +63,6 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement .update({ title, content }) .eq('id', doc.id) - if (!mountedRef.current) return if (updateErr) { setError(updateErr.message) return @@ -79,14 +70,8 @@ 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) - } + setBusy(false) } } @@ -101,7 +86,6 @@ export function DocumentEditor({ doc }: DocumentEditorProps): React.ReactElement .delete() .eq('id', doc.id) - if (!mountedRef.current) return if (deleteErr) { setError(deleteErr.message) return @@ -109,14 +93,8 @@ 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) - } + setBusy(false) } } diff --git a/apps/web/src/components/meetings/generate-document-button.tsx b/apps/web/src/components/meetings/generate-document-button.tsx index ea4d8324..ec2de0ce 100644 --- a/apps/web/src/components/meetings/generate-document-button.tsx +++ b/apps/web/src/components/meetings/generate-document-button.tsx @@ -3,7 +3,7 @@ // apps/web/src/components/meetings/generate-document-button.tsx // 회의록에서 AI 문서 생성 — llm-proxy 호출 → meeting_documents INSERT -import { useEffect, useRef, useState } from 'react' +import { useState } from 'react' import { useRouter } from 'next/navigation' import { Button, @@ -14,11 +14,6 @@ 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' @@ -80,30 +75,17 @@ export function GenerateDocumentButton({ const [anchorEl, setAnchorEl] = useState(null) const [busy, setBusy] = useState(false) const [error, setError] = useState(null) - const mountedRef = useRef(true) - const abortRef = useRef(null) - - useEffect(() => { - mountedRef.current = true - return () => { - mountedRef.current = false - abortRef.current?.abort() - abortRef.current = null - } - }, []) async function handleGenerate(tpl: TemplateDef): Promise { 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 @@ -117,14 +99,13 @@ export function GenerateDocumentButton({ // llm-proxy 호출 const startedAt = Date.now() const llmResp = await fetch( - resolveSupabaseFunctionUrl('llm-proxy'), + `${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/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, @@ -146,7 +127,6 @@ export function GenerateDocumentButton({ const { data: { user } } = await supabase.auth.getUser() - if (!mountedRef.current) return if (!user) { setError('로그인이 필요합니다') return @@ -162,7 +142,6 @@ export function GenerateDocumentButton({ llm_model: llmData.model, llm_latency_ms: latency }) - if (!mountedRef.current) return if (insertErr) { setError(`문서 저장 실패: ${insertErr.message}`) @@ -171,18 +150,9 @@ export function GenerateDocumentButton({ router.refresh() } catch (e) { - if (mountedRef.current) { - setError(timedAbort.didTimeout() - ? 'AI 문서 생성 시간이 초과되었습니다.' - : e instanceof Error - ? e.message - : 'Unknown error') - } + setError(e instanceof Error ? e.message : 'Unknown error') } finally { - timedAbort.dispose() - if (mountedRef.current) { - setBusy(false) - } + setBusy(false) } } diff --git a/apps/web/src/components/providers/auth-provider.tsx b/apps/web/src/components/providers/auth-provider.tsx index d53e1ff0..2e3ae48b 100644 --- a/apps/web/src/components/providers/auth-provider.tsx +++ b/apps/web/src/components/providers/auth-provider.tsx @@ -19,56 +19,31 @@ const AuthContext = createContext({ 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(null) const [loading, setLoading] = useState(true) useEffect(() => { const supabase = getSupabaseBrowserClient() - return bindAuthSession(supabase, setSession, setLoading) + + 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 ( diff --git a/apps/web/src/components/record/mic-recorder.tsx b/apps/web/src/components/record/mic-recorder.tsx index de74d8be..29a7ef3d 100644 --- a/apps/web/src/components/record/mic-recorder.tsx +++ b/apps/web/src/components/record/mic-recorder.tsx @@ -13,25 +13,6 @@ 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(options: { - getUserMedia: () => Promise - isStillActive: () => boolean -}): Promise { - 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('idle') const [error, setError] = useState(null) @@ -49,11 +30,20 @@ export function MicRecorder(): React.ReactElement { const chunksRef = useRef([]) const transcriptionAbortRef = useRef(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 @@ -62,36 +52,9 @@ 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 || !mountedRef.current) return + if (!analyser) return const buf = new Uint8Array(analyser.frequencyBinCount) analyser.getByteTimeDomainData(buf) @@ -107,25 +70,19 @@ export function MicRecorder(): React.ReactElement { }, []) const startRecording = useCallback(async (): Promise => { - const captureGen = ++captureGenerationRef.current setError(null) setTranscript('') setElapsed(0) try { - const stream = await acquireGuardedMediaStream({ - getUserMedia: () => - navigator.mediaDevices.getUserMedia({ - audio: { - sampleRate: 16000, - channelCount: 1, - echoCancellation: true, - noiseSuppression: true, - }, - }), - isStillActive: () => mountedRef.current && captureGen === captureGenerationRef.current, + const stream = await navigator.mediaDevices.getUserMedia({ + audio: { + sampleRate: 16000, + channelCount: 1, + echoCancellation: true, + noiseSuppression: true, + } }) - if (!stream) return streamRef.current = stream const AudioCtx = window.AudioContext @@ -149,35 +106,27 @@ 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) - } + 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 => { - if (!mountedRef.current) return setState('processing') - if (rafRef.current !== null) cancelAnimationFrame(rafRef.current) - if (elapsedTimerRef.current !== null) window.clearInterval(elapsedTimerRef.current) + if (rafRef.current) cancelAnimationFrame(rafRef.current) + if (elapsedTimerRef.current) window.clearInterval(elapsedTimerRef.current) const blob = new Blob(chunksRef.current, { type: 'audio/webm' }) stopStream() @@ -199,11 +148,11 @@ export function MicRecorder(): React.ReactElement { supabaseUrl, signal: controller.signal, }) - if (!mountedRef.current || generation !== transcriptionGenerationRef.current) return + if (generation !== transcriptionGenerationRef.current) return setTranscript(result.transcript) setState('done') } catch (transcriptionError) { - if (!mountedRef.current || generation !== transcriptionGenerationRef.current) return + if (generation !== transcriptionGenerationRef.current) return setTranscript('') const code = transcriptionError instanceof WebSttError ? transcriptionError.code : 'network' const messages: Record = { diff --git a/apps/web/src/components/teams/invite-member-form.tsx b/apps/web/src/components/teams/invite-member-form.tsx index e9037bdf..a32bd041 100644 --- a/apps/web/src/components/teams/invite-member-form.tsx +++ b/apps/web/src/components/teams/invite-member-form.tsx @@ -4,7 +4,7 @@ // 팀 멤버 초대 — 이메일 기반 (V2-7b). // Edge Function team-invite로 토큰 발급 → 초대 URL 반환 → 클라이언트가 복사/공유. -import { useEffect, useRef, useState } from 'react' +import { useState } from 'react' import { Box, Button, @@ -23,13 +23,6 @@ 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 { @@ -50,74 +43,45 @@ export function InviteMemberForm({ teamId }: InviteMemberFormProps): React.React const [busy, setBusy] = useState(false) const [result, setResult] = useState(null) const [copied, setCopied] = useState(false) - const mountedRef = useRef(true) - const copyTimerRef = useRef | null>(null) - const abortRef = useRef(null) - - useEffect(() => { - mountedRef.current = true - return () => { - mountedRef.current = false - clearTrackedTimeout(copyTimerRef) - abortRef.current?.abort() - abortRef.current = null - } - }, []) async function handleInvite(): Promise { 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( - resolveSupabaseFunctionUrl('team-invite'), + `${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/team-invite`, { method: 'POST', headers: { Authorization: `Bearer ${session.access_token}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ team_id: teamId, email: email.trim(), role }), - signal: timedAbort.controller.signal, + body: JSON.stringify({ team_id: teamId, email: email.trim(), role }) } ) if (!response.ok) { - const errData = (await response.json().catch(() => ({}))) as { error?: string; message?: string } - if (mountedRef.current) { - setError(errData.message ?? errData.error ?? `실패: ${response.status}`) - } + const errData = (await response.json()) as { error?: string; message?: string } + setError(errData.message ?? errData.error ?? `실패: ${response.status}`) return } const data = (await response.json()) as InviteResult - if (mountedRef.current) { - setResult(data) - } + setResult(data) } catch (e) { - if (mountedRef.current) { - setError(timedAbort.didTimeout() - ? '초대 요청 시간이 초과되었습니다.' - : e instanceof Error - ? e.message - : 'Unknown error') - } + setError(e instanceof Error ? e.message : 'Unknown error') } finally { - timedAbort.dispose() - if (mountedRef.current) { - setBusy(false) - } + setBusy(false) } } @@ -125,20 +89,14 @@ export function InviteMemberForm({ teamId }: InviteMemberFormProps): React.React if (!result) return try { await navigator.clipboard.writeText(result.url) - if (!mountedRef.current) return setCopied(true) - scheduleTrackedTimeout(copyTimerRef, () => { - if (mountedRef.current) setCopied(false) - }, 2000) + setTimeout(() => setCopied(false), 2000) } catch { // clipboard 차단 시 무시 } } function handleClose(): void { - clearTrackedTimeout(copyTimerRef) - abortRef.current?.abort() - abortRef.current = null setOpen(false) setEmail('') setRole('member') diff --git a/apps/web/src/lib/edge-fetch.ts b/apps/web/src/lib/edge-fetch.ts deleted file mode 100644 index 22b8a399..00000000 --- a/apps/web/src/lib/edge-fetch.ts +++ /dev/null @@ -1,103 +0,0 @@ -export interface TimerRefHandle { - current: ReturnType | 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 -} diff --git a/apps/web/src/lib/web-app-url.ts b/apps/web/src/lib/web-app-url.ts index 93149643..01c13fb7 100644 --- a/apps/web/src/lib/web-app-url.ts +++ b/apps/web/src/lib/web-app-url.ts @@ -11,41 +11,19 @@ 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`, `/app//evil.example`, `/\evil.example`, 제어문자는 기본 경로로 바꾼다. + * `//evil.example`, `/\evil.example` 같은 외부 이동은 기본 경로로 바꾼다. */ export function safeReturnPath(value: string | null | undefined): string { - if (!value || !value.startsWith('/') || value.startsWith('//') || hasUnsafePathChars(value)) { + if (!value || !value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\')) { return DEFAULT_RETURN_PATH } - 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 + 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) } - 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 + return value } /** 로그인 페이지 경로(basePath 제외). 돌아갈 곳이 기본값이면 쿼리를 붙이지 않는다. */ diff --git a/apps/web/tests/security-and-lifecycle.test.ts b/apps/web/tests/security-and-lifecycle.test.ts deleted file mode 100644 index 039526a0..00000000 --- a/apps/web/tests/security-and-lifecycle.test.ts +++ /dev/null @@ -1,415 +0,0 @@ -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 } - clients: { matchAll: () => Promise } - } - 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({ - 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 | 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({ - 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({ - 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) - }) -}) diff --git a/docs/REFACTOR_POLICY.md b/docs/REFACTOR_POLICY.md index ff2ff83e..d700ed2f 100644 --- a/docs/REFACTOR_POLICY.md +++ b/docs/REFACTOR_POLICY.md @@ -1,6 +1,6 @@ # D3RO-VOICE 리팩토링 정책 (SSOT) -> 마지막 갱신: 2026-11-14 — Wave 7 6-세션 네이티브 피어 스웜(`swarm`) 정책 및 검증 기준 보완 +> 마지막 갱신: 2026-11-14 — Wave 6 전 표면 코드 위생 · 최적화 · 버그 헌팅 정책 보완 > 적용 범위: `apps/*` + `packages/*` + `server/*` + `site/` + 빌드·배포 스크립트 (기능 변경은 별도 요청) ## 0. 전제: 기존 3계층 규칙 SSOT와의 관계 @@ -162,9 +162,3 @@ 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` 통합분과 라이브 배포 상태를 구분 표기). diff --git a/docs/REFACTOR_WAVE7_REPORT.md b/docs/REFACTOR_WAVE7_REPORT.md deleted file mode 100644 index 8d1d3584..00000000 --- a/docs/REFACTOR_WAVE7_REPORT.md +++ /dev/null @@ -1,110 +0,0 @@ -# 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`에 반영하려면 대시보드 변수 덮어쓰기 또는 재배포가 필요하다. diff --git a/docs/map/00-index.md b/docs/map/00-index.md index e74c7db1..ea67b8ed 100644 --- a/docs/map/00-index.md +++ b/docs/map/00-index.md @@ -2,11 +2,7 @@ > Status: ACTIVE > Last full audit: 2026-09-13 -> 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). +> Last update: 2026-11-14 — **전 표면 코드 위생 · 최적화 · 버그 헌팅 완결(Wave 6, WS1–WS4 병렬).** (1) **Desktop Main & Sidecar (`WS1`):** `ipc/renderer-broadcast.ts`(`safeSendToRenderer`/`broadcastToAllWindows`) 9개 파일 단일화, `OnlineLLMService` 스트림 abort/401/예외 래핑, `UnifiedSearchService` FTS5→`LIKE` 런타임 폴백·집계·정렬·인덱스(`started_at`/`created_at`) 보강, `rag/chunk-store.ts` 캐시 무효화·중복 `embedding` JSON 제거·손상 Float32 방어, `disk-wav-audio-sink.ts` uint32 오버플로·헤더 write 실패 fd 정리, `AdMediationEngine`/`AudioCaptureService`/`LocalLLMService`/`WindowManager` 타이머·팝업 레이스 수정, `sidecar/main.py` `UploadFile.close()`·PCM 바이트 경계·`/shutdown` 스레드 join 완료. (2) **Shared Packages & Desktop Renderer (`WS2`):** `@d3ro/i18n` `shared.ts` 및 지연 로드/언마운트 레이스 차단(`25/25`), `@d3ro/core` PII 플레이스홀더·CSV BOM/CR·타임스탬프·검색 경계값(`626/626`), `@d3ro/ui` `wave-math.ts` + 캔버스 `LinearGradient` 캐싱(`7/7`), `@d3ro/ui-native`/`api-client` 경계 가드, 렌더러 `utils/error-message.ts`·훅/컴포넌트 언마운트·타이머 정리 및 Vanilla JS 팝업 6종 `beforeunload`/DOM 안전화 완료. (3) **Mobile RN (`WS3`):** `features/shared/{service-guards,owned-cache-files}.ts`, `features/import/abort-guard.ts`, `lib/locale-speech.ts`(12개 로케일), `features/meetings/meeting-error-message.ts`로 26+ 파일 중복 가드·오류·포맷 통합, `FreeTierBanner` 슬롯 전환 시 높이 고착 수정·내구성 큐 조기 폐기 경합 차단·녹음 리스 누수·언마운트 재생/로케일 레이스 해결(Jest `98 suites / 625 tests PASS`). (4) **Web · Admin · Site · Edge · Worker · .NET (`WS4`):** Edge 20개 엔드포인트 `_shared/json-response.ts`(스트리밍 바이트 상한 포함 `readJsonBody`·`jsonResponse`) 통합 및 `account-delete`/`llm-proxy`/`payple`/`realtime-token` fail-closed 강화(Deno `270/270`), `.NET` `SttProxyService` Base64 상한 + `CancellationToken` 전파(xUnit `32/32`), Cloudflare Worker `resolveBackendTargetUrl` SSRF·타임아웃·`/worker-health` 정보 노출 차단(Deno `9/9`), 웹 `MarkdownPreview` DOM XSS/레이스·`WebPush` 재진입·`team-client` fail-closed(`42/42`), 어드민 `request-security.ts`/`detail-row.tsx`·CSRF/`ADMIN_UUID_PATTERN`/비용 검증, 사이트 `AppLoopDemo`/`rel="noopener noreferrer"` 보강 완료. 상세: [`REFACTOR_WAVE6_REPORT.md`](../REFACTOR_WAVE6_REPORT.md). > > Previous update: 2026-11-13 — **전 표면 성능 최적화 · 코드 위생 완결(Wave 5) · 백로그 일괄 구현 · TDD v2.0 게이트 완성.** (1) **소스·패키징 위생:** 루트 중복 `resources/sox/`(5.21 MB) 및 `apps/desktop/resources/sox/` 불필요 바이너리 10종 제거 + `electron-builder.yml` 필터 적용, 데스크톱 미구현 광고 어댑터 9종 단일화(`UNAVAILABLE_AD_NETWORK_SPECS`), `scripts/local/` 109개 및 미참조 루트 스크립트 16개 삭제 + `npm run clean:deep`(`scripts/ci/clean-deep.mjs`), `apps/mobile-rn` 루트 순환 의존성(`d3ro-voice-monorepo`)·NTFS 정션 제거, `.NET` `SttController` 무호출 중복 라우트(`GET /providers`, `POST /test`) 삭제. (2) **번들·코드 스플리팅 & 대형 모듈 분리:** `@d3ro/i18n`을 렌더러/웹 동적 로케일 청크(`index.tsx`), 무-React 동기 로더(`@d3ro/i18n/main`), 모바일 지연 엔트리(`index.native.tsx`, Metro `inlineRequires`)로 3분할하고, 데스크톱 `AppLayout.tsx`(7페이지·6모달 `React.lazy`), 모바일 `App.tsx`(`getComponent`), 웹 `MarkdownPreview`(`next/dynamic` + 조건부 `mermaid`) 스플리팅으로 데스크톱 초기 부팅 JS를 `8.79 MB` → `3.62 MB`(`-58.8%`)로 축소했으며, `SettingsModal.tsx`(`951`→`349`줄, 탭 4종 + `settings-model-helpers.ts`)와 `SuggestionService.ts`(`suggestion-policy-helpers.ts`) 순수 모듈 분리를 완료했다. (3) **데스크톱 SQLite · 프로세스 · 오디오 디스크 스트리밍:** SQLite WAL PRAGMA(`synchronous=NORMAL`, `mmap_size=64MB`, `cache_size=-16000`), FTS5 trigram 전문 검색, RAG `embedding_blob`(`Float32Array`) + `WeakMap` 캐시, `PersonalGraphService` 단일 트랜잭션, Windows `koffi` `SendInput` 일원화, 기본 모드 `mousemove`/`wheel` 훅 차단, 백그라운드 팝업 지연 생성, `LocalSTTService` 주 Whisper 모델 유휴/클라우드 언로드, 회의 녹음 PCM 디스크 스트리밍(`DiskWavAudioSink`, 메모리 상주 `O(N)→O(1)`)을 적용했다. (4) **Wave 5 계약·보안 & 기능 백로그 해소:** `@d3ro/core`에 `guards`/`csv`/`format`/`unified-search`/`admin-roles`/`ports` 6개 SSOT 모듈을 추출해 앱 간 중복을 제거하고, 클라우드 LLM·고객지원 `redactPII`/`rehydrateText` 및 녹음 폐기 시 `secureWipeAudioChunks`/`secureZeroBuffer`를 실배선했으며, 고아 키 253개를 정리한 `2,500`키 × 12개 언어를 데스크톱·웹(`LocaleSwitcher`)·모바일(온보딩/설정/계정 + Android `localeFilters` 12개, R8/`shrinkResources`) 전 표면에 노출했다. 또한 `site/` 정적·빌드 CI 게이트(`typecheck:site`/`lint:site`), 웹 `teams` 실 멤버 수 집계(`team-client.ts`), 모바일 `>=600dp` 태블릿/폴더블 반응형 레이아웃(`@d3ro/ui-native/responsive`, 10개 화면 + `FreeTierBanner` `90dp` 슬롯 예약), `meeting_memos.revision` 불변 CAS(마이그레이션 #74 `20261113000001`), 사이드카 `POST /diarize` + 데스크톱·웹·모바일 화자 배지·필터 바(`MTG-08`)를 완성했다. (5) **TDD v2.0 Phase 2~5 자동화 게이트:** `check:i18n`, `check:ds-contract`(`SegmentControl` ARIA `tablist`/`tab` + `@d3ro/ui` 테스트), `test:affected`, `release:installer:smoke`(`verify-desktop-installer-smoke.mjs`: PE64·blockmap·SHA-512·`app-update.yml`·ASAR Pickle·Ed25519 `.sig`)를 `verify:all` 및 `.forgejo/workflows/{ci,release}.yml`에 연결했다. 상세: [`REFACTOR_WAVE5_REPORT.md`](../REFACTOR_WAVE5_REPORT.md). > @@ -41,7 +37,7 @@ > Previous update: 2026-09-22 — **Gemma/Ollama 폭주 방어 계약을 기록했다.** 19:14:12 부팅 워밍업이 `keep_alive: 30m`으로 `gemma4:e4b`를 19:44:12까지 VRAM 3,226,342,521 bytes / context 4096으로 강제 상주시킨 것이 관측됐으며, 같은 시점 Windows GPU Engine PID 표본에는 Ollama의 활성 compute가 없었다. 즉 당시 상태는 무한 추론이 아니라 강제 residency였다. 19:11:17~19:11:58의 자동 제안 연속 생성은 기존 900 ms·12/min·5 candidates·128 tokens·한 글자 재생성 정책이 허용한 burst였다. 현재 구현 계약은 부팅 warmup 제거, `keep_alive: 2m`, 제안 600 ms / 최소 5 s 간격 / 기본 6회·hard max 12회 per min / 3 candidates / 64 tokens / 12-char growth / 8 s timeout, 그리고 요청별 취소·상한·종료 정리다. 독립 표적 검증은 6 test files / 69 tests passed / 0 failed, 변경 코드·테스트 ESLint와 `git diff --check`도 exit 0이다. Raw Ollama에서는 cold bounded 요청이 client hard timeout 15.044 s에 취소된 뒤 `/api/ps`가 비었고 `/api/version`은 80 ms에 회복했다. 명시 warmup은 HTTP 200 / 16.639 s, 후속 warm 요청은 body `options.num_predict=1`, `keep_alive='2m'`로 553 ms HTTP 200 / `done:true` / `eval_count:1` / `done_reason:length`였고 `/api/ps` expiry는 약 119.9 s였다. **19:48:59 +09:00에는 새 generate/unload/kill/retry 없이 충분히 지난 뒤 한 번의 `/api/ps`가 HTTP 200 / 45.8 ms / `{models:[]}`였고 `/api/version`은 HTTP 200 / 7.3 ms / `0.32.13`이었다.** 이는 raw API 수준의 expiry 뒤 unload 확인일 뿐 앱 재시작·GUI·실제 타이핑 증거는 아니므로 상태는 `[~]`로 유지한다 (`11` GAP-LLM-04, GAP-INPUT-06). > > Previous update: 2026-09-21 — **Input intelligence (입력 레메트리 + 다음 문장 제안) 신규**. 데스크톱에 입력 수집기(`InputTelemetryService`), UIA 컨텍스트 브리지(사이드카 `GET /uia/focus`), 제안 서비스(`SuggestionService`), 어렛 커 오버레이, 설정 > 입력 탭(동의·정책·주간 인사이트·개인 문구)을 추가했다. 카탈로그에 `INPUT-01`~`INPUT-08`(전부 데스크톱 `[~]` — 유닛 48건은 GREEN 이지만 **실앱 타이핑 검증 전**), 백로그에 GAP-INPUT-01~05 + GAP-LLM-03, §7 에 CONSTRAINT-INPUT-01(키 내용 미저장 — ActivityWatch 정책 채택)을 기록. 설계 근거는 조사 기반이다: 어렛은 `GetGUIThreadInfo` 가 아니라 UIA `TextPattern.GetSelection`(Chromium 은 `TextPattern2` 미구현), 타이핑 스트는 키코드 복원이 아니라 UIA 스냅샷 diff(한/일 IME 대응), 디바운스/토큰 한도는 인라인 컴플리션 실측값(Continue 350 / Tabby 250 / twinny 300 ms, 출력 64~256 토큰). 의존성: `koffi` 3.3.1(포그라운드 창 FFI), 사이드카 `uiautomation` 2.0.29 + `comtypes`. 데스크톱 유닛 총계 1409(+49), Electron ABI 실행에서 신규 실패 0건. 당시의 24.7초/4.9초 지연 설명과 `keep_alive: 30m`·부팅 워밍업 처방은 **현재 상태가 아닌 과거 가설/완화 이력**이며, 최신 운영 결론은 위 2026-09-22 항목과 `11` GAP-LLM-04를 따른다. 직전: LLM instruction-prompt fix (`9c2b4d4`): the custom-instruction path inserted the instruction's own wording instead of the processed result and had **never worked in any shipped release** (`v0.1.0-alpha`..`v1.4.0`, introduced `fea923d` 2026-04-05, not a regression). `llm-prompts.ts` is now the SSOT for prompt resolution and placeholder substitution, shared by `VoiceModeService` / `ChainService` / `LLM.PROCESS`. AI-04/05/06/07 are demoted to `[~]` on desktop — fixed with unit tests, but **not verified in a running app** and the four related `tests/red/*.usecase.test.ts` could not execute (`better-sqlite3` ABI). New: GAP-LLM-01 (no target-language setting), GAP-LLM-02 (this fix unverified); GAP-INFRA-06 amended (the ABI masks verification, not just dev-env switching cost); GAP-I18N-01 amended (`popup.error.default` missing in 10 locales). Earlier the same day: CAP-16 (desktop key bindings rebuilt on one `@d3ro/core/keybinding` SSOT — multiple bindings per action, mouse buttons, `HOTKEY` → `KEYBINDING` IPC group), verified on Windows by a manual run, so CAP-16 and CAP-02 are `[x]` and GAP-KEY-01 is closed. Still open: GAP-KEY-02/03, GAP-QA-02, GAP-I18N-01/02, GAP-INFRA-06, GAP-LLM-01/02, GAP-INPUT-01~05; `11` §7 holds accepted design constraints (things deliberately kept, not gaps) -> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.17.1` (`release/product-version.json`) +> Scope: entire monorepo `D:/workspace/D3ROVoice` at product version `1.16.5` (`release/product-version.json`) > Purpose: let any agent (or human) answer two questions in under a minute: > 1. **What infrastructure exists?** (build, CI, services, APIs, data, packages, deploy) > 2. **How far is each feature developed?** (per surface, with file anchors and status) diff --git a/docs/map/02-infrastructure.md b/docs/map/02-infrastructure.md index 33e3350a..182212e3 100644 --- a/docs/map/02-infrastructure.md +++ b/docs/map/02-infrastructure.md @@ -1,7 +1,7 @@ # 02 — Repository & Infrastructure Map > Surface: whole repo -> Last updated: 2026-11-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`) +> Last updated: 2026-11-13 — Source/packaging hygiene (`clean:deep`, trimmed `apps/desktop/resources/sox`, macOS-only `@nut-tree-fork` `asarUnpack`, Android R8 + `shrinkResources` + 12-locale `localeFilters`), `@d3ro/i18n` 2,500-key split, `site/` static/build CI gate, and TDD v2.0 Phase 2–5 gates (`check:i18n`, `check:ds-contract`, `test:affected`, `release:installer:smoke`) > Source of truth for: layout, workspaces, build/test commands, CI/CD, Docker, deploy, scripts, resources --- @@ -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`. 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. | +| `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`. | 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.17.1`, `androidVersionCode`/`iosBuildNumber` `1170100`, desktop license keyId | +| `release/product-version.json` | version `1.16.5`, `androidVersionCode`/`iosBuildNumber` `1160500`, desktop license keyId | | `release/android-release-identity.json` | package `com.d3ro.voice`, Play app ID, app-signing SHA-256, upload cert SHA-256, evidence keyId, AdMob unit IDs | | `release/desktop-license-public.pem` | Ed25519 public key for desktop offline licenses | | `release/mobile-release-evidence-public.pem` | Ed25519 public key for mobile release evidence | diff --git a/docs/map/03-shared-packages.md b/docs/map/03-shared-packages.md index e240e5c7..5a6cfbf5 100644 --- a/docs/map/03-shared-packages.md +++ b/docs/map/03-shared-packages.md @@ -128,9 +128,3 @@ 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). diff --git a/docs/map/04-desktop-app.md b/docs/map/04-desktop-app.md index 65c3302a..abb3f76a 100644 --- a/docs/map/04-desktop-app.md +++ b/docs/map/04-desktop-app.md @@ -280,5 +280,3 @@ 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 `[~]`. diff --git a/docs/map/05-web-app.md b/docs/map/05-web-app.md index a6316be9..3bd53a84 100644 --- a/docs/map/05-web-app.md +++ b/docs/map/05-web-app.md @@ -61,7 +61,6 @@ 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 | @@ -77,7 +76,7 @@ Root layout: `ThemeProvider → I18nProvider → AuthProvider`. Two layers: -- **Vitest** (`apps/web/tests/`, `npm --prefix apps/web run test`, part of root `npm test`): pure-logic & 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**. +- **Vitest** (`apps/web/tests/`, `npm --prefix apps/web run test`, part of root `npm test`): pure-logic & SSR contracts — `billing-catalog`, `web-push` (device/RPC/rollback/reconciliation/logout, 17 cases), `web-stt-client`, `team-client` (3 cases), `locale-switcher` (3 cases), `live-transcript-speakers` (2 cases) — 6 files / 32 tests PASS. - **Playwright** (`apps/web/e2e/`): `smoke.spec.ts` (unauthenticated surface + fail-closed redirects + `/download` handoff), `billing`, `payple-checkout`, `dashboard-dictionary-commands`, `history` (fixture-based browser journeys). --- @@ -92,4 +91,3 @@ 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 `