fix(web): propagate mounted timeouts across chat stream and edge-fetch awaits
This commit is contained in:
parent
c68e81e0aa
commit
4bf0f0df12
7 changed files with 363 additions and 106 deletions
|
|
@ -9,7 +9,11 @@ import { Box, Button, TextField, Stack, Alert, CircularProgress, Chip } from '@m
|
||||||
import PlayArrowIcon from '@mui/icons-material/PlayArrow'
|
import PlayArrowIcon from '@mui/icons-material/PlayArrow'
|
||||||
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
|
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
|
||||||
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
|
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
|
||||||
import { createTimedAbortSignal, resolveSupabaseFunctionUrl } from '@/lib/edge-fetch'
|
import {
|
||||||
|
createTimedAbortSignal,
|
||||||
|
resolveSupabaseFunctionUrl,
|
||||||
|
shouldExitAfterAwait,
|
||||||
|
} from '@/lib/edge-fetch'
|
||||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||||
|
|
||||||
type ActionType =
|
type ActionType =
|
||||||
|
|
@ -78,7 +82,7 @@ export function ActionRunner(): React.ReactElement {
|
||||||
const {
|
const {
|
||||||
data: { session }
|
data: { session }
|
||||||
} = await supabase.auth.getSession()
|
} = await supabase.auth.getSession()
|
||||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
|
||||||
if (!session) {
|
if (!session) {
|
||||||
throw new Error('로그인이 필요합니다')
|
throw new Error('로그인이 필요합니다')
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import {
|
||||||
createTimedAbortSignal,
|
createTimedAbortSignal,
|
||||||
resolveSupabaseFunctionUrl,
|
resolveSupabaseFunctionUrl,
|
||||||
scheduleTrackedTimeout,
|
scheduleTrackedTimeout,
|
||||||
|
shouldExitAfterAwait,
|
||||||
} from '@/lib/edge-fetch'
|
} from '@/lib/edge-fetch'
|
||||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||||
|
|
||||||
|
|
@ -43,7 +44,7 @@ export function PaypleManageButton(): React.ReactElement {
|
||||||
try {
|
try {
|
||||||
const supabase = getSupabaseBrowserClient()
|
const supabase = getSupabaseBrowserClient()
|
||||||
const { data: { session }, error: sessionError } = await supabase.auth.getSession()
|
const { data: { session }, error: sessionError } = await supabase.auth.getSession()
|
||||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
|
||||||
|
|
||||||
if (sessionError || !session) {
|
if (sessionError || !session) {
|
||||||
setError('로그인이 필요합니다')
|
setError('로그인이 필요합니다')
|
||||||
|
|
|
||||||
|
|
@ -8,16 +8,148 @@ import { useRef, useState, useEffect } from 'react'
|
||||||
import { Alert, Box, Typography, IconButton } from '@mui/material'
|
import { Alert, Box, Typography, IconButton } from '@mui/material'
|
||||||
import { Send, Trash2 } from 'lucide-react'
|
import { Send, Trash2 } from 'lucide-react'
|
||||||
import { d3roFontMono } from '@d3ro/ui/theme'
|
import { d3roFontMono } from '@d3ro/ui/theme'
|
||||||
import { createTimedAbortSignal, resolveSupabaseFunctionUrl } from '@/lib/edge-fetch'
|
import {
|
||||||
|
createTimedAbortSignal,
|
||||||
|
resolveSupabaseFunctionUrl,
|
||||||
|
shouldExitAfterAwait,
|
||||||
|
} from '@/lib/edge-fetch'
|
||||||
import { getSupabaseBrowserClient, isSupabaseConfigured } from '@/lib/supabase-browser'
|
import { getSupabaseBrowserClient, isSupabaseConfigured } from '@/lib/supabase-browser'
|
||||||
|
|
||||||
interface Message {
|
export interface ChatMessage {
|
||||||
id: string
|
id: string
|
||||||
role: 'user' | 'assistant'
|
role: 'user' | 'assistant'
|
||||||
content: string
|
content: string
|
||||||
timestamp: string
|
timestamp: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function executeChatSendTurn(options: {
|
||||||
|
text: string
|
||||||
|
messages: ChatMessage[]
|
||||||
|
activeControllerRef: { current: AbortController | null }
|
||||||
|
isMounted: () => boolean
|
||||||
|
isConfigured: () => boolean
|
||||||
|
getAccessToken: () => Promise<string | null>
|
||||||
|
endpointUrl?: string
|
||||||
|
fetchImpl?: typeof fetch
|
||||||
|
timeoutMs?: number
|
||||||
|
onMessagesUpdate: (updater: (prev: ChatMessage[]) => ChatMessage[]) => void
|
||||||
|
onInputChange: (value: string) => void
|
||||||
|
onErrorChange: (error: string | null) => void
|
||||||
|
onBusyChange: (busy: boolean) => void
|
||||||
|
}): Promise<void> {
|
||||||
|
const {
|
||||||
|
text,
|
||||||
|
messages,
|
||||||
|
activeControllerRef,
|
||||||
|
isMounted,
|
||||||
|
isConfigured,
|
||||||
|
getAccessToken,
|
||||||
|
endpointUrl,
|
||||||
|
fetchImpl = fetch,
|
||||||
|
timeoutMs = 45_000,
|
||||||
|
onMessagesUpdate,
|
||||||
|
onInputChange,
|
||||||
|
onErrorChange,
|
||||||
|
onBusyChange,
|
||||||
|
} = options
|
||||||
|
|
||||||
|
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를 해제한다.
|
* SSE 응답 스트림에서 text_delta 토큰을 누적하고, 취소·종료 시 reader를 해제한다.
|
||||||
*/
|
*/
|
||||||
|
|
@ -81,7 +213,7 @@ export async function consumeChatSseStream(options: {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ChatPanel(): React.ReactElement {
|
export function ChatPanel(): React.ReactElement {
|
||||||
const [messages, setMessages] = useState<Message[]>([
|
const [messages, setMessages] = useState<ChatMessage[]>([
|
||||||
{
|
{
|
||||||
id: 'welcome',
|
id: 'welcome',
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
|
|
@ -125,102 +257,22 @@ export function ChatPanel(): React.ReactElement {
|
||||||
const text = input.trim()
|
const text = input.trim()
|
||||||
if (!text || busy) return
|
if (!text || busy) return
|
||||||
|
|
||||||
const userMsg: Message = {
|
await executeChatSendTurn({
|
||||||
id: 'u_' + Date.now(),
|
text,
|
||||||
role: 'user',
|
messages,
|
||||||
content: text,
|
activeControllerRef,
|
||||||
timestamp: new Date().toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' })
|
isMounted: () => mountedRef.current,
|
||||||
}
|
isConfigured: isSupabaseConfigured,
|
||||||
const nextMessages = [...messages, userMsg]
|
getAccessToken: async () => {
|
||||||
const assistantId = 'a_' + Date.now()
|
const supabase = getSupabaseBrowserClient()
|
||||||
setMessages(nextMessages)
|
const { data: { session } } = await supabase.auth.getSession()
|
||||||
setInput('')
|
return session?.access_token ?? null
|
||||||
setError(null)
|
},
|
||||||
setBusy(true)
|
onMessagesUpdate: setMessages,
|
||||||
const timedAbort = createTimedAbortSignal(45_000, activeControllerRef)
|
onInputChange: setInput,
|
||||||
|
onErrorChange: setError,
|
||||||
try {
|
onBusyChange: setBusy,
|
||||||
if (!isSupabaseConfigured()) {
|
})
|
||||||
throw new Error('Supabase 미설정')
|
|
||||||
}
|
|
||||||
|
|
||||||
const supabase = getSupabaseBrowserClient()
|
|
||||||
const { data: { session } } = await supabase.auth.getSession()
|
|
||||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
|
||||||
|
|
||||||
if (!session) {
|
|
||||||
throw new Error('로그인 필요')
|
|
||||||
}
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
messages: nextMessages.map((m) => ({ role: m.role, content: m.content })),
|
|
||||||
max_tokens: 1024,
|
|
||||||
stream: true
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch(
|
|
||||||
resolveSupabaseFunctionUrl('llm-proxy'),
|
|
||||||
{
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
Authorization: 'Bearer ' + session.access_token,
|
|
||||||
'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 (!mountedRef.current) return
|
|
||||||
setMessages((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 (!mountedRef.current) return
|
|
||||||
setMessages((prev) =>
|
|
||||||
prev.map((m) => (m.id === assistantId ? { ...m, content: partial } : m))
|
|
||||||
)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
|
||||||
if (!accumulated.trim()) throw new Error('empty_response')
|
|
||||||
} catch (candidate) {
|
|
||||||
if (!mountedRef.current) return
|
|
||||||
setMessages((prev) => prev.filter((m) => m.id !== userMsg.id && m.id !== assistantId))
|
|
||||||
setInput(text)
|
|
||||||
const timedOut = timedAbort.didTimeout() || (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 {
|
|
||||||
timedAbort.dispose()
|
|
||||||
if (mountedRef.current) {
|
|
||||||
setBusy(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,11 @@ import {
|
||||||
Box
|
Box
|
||||||
} from '@mui/material'
|
} from '@mui/material'
|
||||||
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome'
|
import AutoAwesomeIcon from '@mui/icons-material/AutoAwesome'
|
||||||
import { createTimedAbortSignal, resolveSupabaseFunctionUrl } from '@/lib/edge-fetch'
|
import {
|
||||||
|
createTimedAbortSignal,
|
||||||
|
resolveSupabaseFunctionUrl,
|
||||||
|
shouldExitAfterAwait,
|
||||||
|
} from '@/lib/edge-fetch'
|
||||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||||
|
|
||||||
type TemplateType = 'minutes' | 'report' | 'idea-note' | 'mindmap'
|
type TemplateType = 'minutes' | 'report' | 'idea-note' | 'mindmap'
|
||||||
|
|
@ -99,7 +103,7 @@ export function GenerateDocumentButton({
|
||||||
const {
|
const {
|
||||||
data: { session }
|
data: { session }
|
||||||
} = await supabase.auth.getSession()
|
} = await supabase.auth.getSession()
|
||||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
|
||||||
if (!session) {
|
if (!session) {
|
||||||
setError('로그인이 필요합니다')
|
setError('로그인이 필요합니다')
|
||||||
return
|
return
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,7 @@ import {
|
||||||
createTimedAbortSignal,
|
createTimedAbortSignal,
|
||||||
resolveSupabaseFunctionUrl,
|
resolveSupabaseFunctionUrl,
|
||||||
scheduleTrackedTimeout,
|
scheduleTrackedTimeout,
|
||||||
|
shouldExitAfterAwait,
|
||||||
} from '@/lib/edge-fetch'
|
} from '@/lib/edge-fetch'
|
||||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||||
|
|
||||||
|
|
@ -73,7 +74,7 @@ export function InviteMemberForm({ teamId }: InviteMemberFormProps): React.React
|
||||||
const {
|
const {
|
||||||
data: { session }
|
data: { session }
|
||||||
} = await supabase.auth.getSession()
|
} = await supabase.auth.getSession()
|
||||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
|
||||||
if (!session) {
|
if (!session) {
|
||||||
setError('로그인이 필요합니다')
|
setError('로그인이 필요합니다')
|
||||||
return
|
return
|
||||||
|
|
|
||||||
|
|
@ -86,3 +86,18 @@ export function scheduleTrackedTimeout(
|
||||||
callback()
|
callback()
|
||||||
}, delayMs)
|
}, 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
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,11 @@ import path from 'node:path'
|
||||||
import vm from 'node:vm'
|
import vm from 'node:vm'
|
||||||
import { NextRequest } from 'next/server'
|
import { NextRequest } from 'next/server'
|
||||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
import { consumeChatSseStream } from '@/components/chat/chat-panel'
|
import {
|
||||||
|
consumeChatSseStream,
|
||||||
|
executeChatSendTurn,
|
||||||
|
type ChatMessage,
|
||||||
|
} from '@/components/chat/chat-panel'
|
||||||
import { bindAuthSession } from '@/components/providers/auth-provider'
|
import { bindAuthSession } from '@/components/providers/auth-provider'
|
||||||
import { acquireGuardedMediaStream } from '@/components/record/mic-recorder'
|
import { acquireGuardedMediaStream } from '@/components/record/mic-recorder'
|
||||||
import {
|
import {
|
||||||
|
|
@ -11,6 +15,7 @@ import {
|
||||||
createTimedAbortSignal,
|
createTimedAbortSignal,
|
||||||
resolveSupabaseFunctionUrl,
|
resolveSupabaseFunctionUrl,
|
||||||
scheduleTrackedTimeout,
|
scheduleTrackedTimeout,
|
||||||
|
shouldExitAfterAwait,
|
||||||
} from '@/lib/edge-fetch'
|
} from '@/lib/edge-fetch'
|
||||||
import { safeReturnPath } from '@/lib/web-app-url'
|
import { safeReturnPath } from '@/lib/web-app-url'
|
||||||
|
|
||||||
|
|
@ -217,9 +222,16 @@ describe('Web URL 안전성 및 OAuth 콜백 보안', () => {
|
||||||
vi.advanceTimersByTime(1000)
|
vi.advanceTimersByTime(1000)
|
||||||
expect(handle.didTimeout()).toBe(true)
|
expect(handle.didTimeout()).toBe(true)
|
||||||
expect(handle.controller.signal.aborted).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()
|
handle.dispose()
|
||||||
expect(activeRef.current).toBe(null)
|
expect(activeRef.current).toBe(null)
|
||||||
|
|
||||||
|
const manualHandle = createTimedAbortSignal(1000, activeRef)
|
||||||
|
manualHandle.controller.abort()
|
||||||
|
expect(shouldExitAfterAwait(manualHandle, () => true)).toBe(true)
|
||||||
|
manualHandle.dispose()
|
||||||
|
|
||||||
const timerRef: { current: ReturnType<typeof setTimeout> | null } = { current: null }
|
const timerRef: { current: ReturnType<typeof setTimeout> | null } = { current: null }
|
||||||
const calls: string[] = []
|
const calls: string[] = []
|
||||||
scheduleTrackedTimeout(timerRef, () => calls.push('first'), 500)
|
scheduleTrackedTimeout(timerRef, () => calls.push('first'), 500)
|
||||||
|
|
@ -232,4 +244,172 @@ describe('Web URL 안전성 및 OAuth 콜백 보안', () => {
|
||||||
vi.advanceTimersByTime(1000)
|
vi.advanceTimersByTime(1000)
|
||||||
expect(calls).toEqual(['second'])
|
expect(calls).toEqual(['second'])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('executeChatSendTurn_스트림응답중45초타임아웃_부분메시지롤백과입력복구및시간초과오류를표시한다', async () => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
const encoder = new TextEncoder()
|
||||||
|
let streamCancelled = false
|
||||||
|
const body = new ReadableStream<Uint8Array>({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(
|
||||||
|
encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"부분응답"}}\n\n'),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
cancel() {
|
||||||
|
streamCancelled = true
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
let currentMessages: ChatMessage[] = [
|
||||||
|
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
|
||||||
|
]
|
||||||
|
let restoredInput = ''
|
||||||
|
let latestError: string | null = null
|
||||||
|
let busyState = false
|
||||||
|
const activeRef: { current: AbortController | null } = { current: null }
|
||||||
|
|
||||||
|
const pendingTurn = executeChatSendTurn({
|
||||||
|
text: '회의 요약해줘',
|
||||||
|
messages: currentMessages,
|
||||||
|
activeControllerRef: activeRef,
|
||||||
|
isMounted: () => true,
|
||||||
|
isConfigured: () => true,
|
||||||
|
getAccessToken: async () => 'access-token',
|
||||||
|
endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy',
|
||||||
|
fetchImpl: async () =>
|
||||||
|
new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }),
|
||||||
|
onMessagesUpdate: (updater) => {
|
||||||
|
currentMessages = updater(currentMessages)
|
||||||
|
},
|
||||||
|
onInputChange: (val) => {
|
||||||
|
restoredInput = val
|
||||||
|
},
|
||||||
|
onErrorChange: (err) => {
|
||||||
|
latestError = err
|
||||||
|
},
|
||||||
|
onBusyChange: (busy) => {
|
||||||
|
busyState = busy
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(100)
|
||||||
|
expect(currentMessages.some((m) => m.role === 'assistant' && m.content === '부분응답')).toBe(true)
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(45_000)
|
||||||
|
await pendingTurn
|
||||||
|
|
||||||
|
expect(streamCancelled).toBe(true)
|
||||||
|
expect(currentMessages).toEqual([
|
||||||
|
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
|
||||||
|
])
|
||||||
|
expect(restoredInput).toBe('회의 요약해줘')
|
||||||
|
expect(latestError).toBe('AI 응답 시간이 초과되었습니다.')
|
||||||
|
expect(busyState).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('executeChatSendTurn_세션조회중45초타임아웃_조용히종료하지않고입력복구와시간초과오류를표시한다', async () => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
let currentMessages: ChatMessage[] = [
|
||||||
|
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
|
||||||
|
]
|
||||||
|
let restoredInput = ''
|
||||||
|
let latestError: string | null = null
|
||||||
|
let busyState = false
|
||||||
|
let resolveSession!: (token: string | null) => void
|
||||||
|
const activeRef: { current: AbortController | null } = { current: null }
|
||||||
|
|
||||||
|
const pendingTurn = executeChatSendTurn({
|
||||||
|
text: '다시 시도할 질문',
|
||||||
|
messages: currentMessages,
|
||||||
|
activeControllerRef: activeRef,
|
||||||
|
isMounted: () => true,
|
||||||
|
isConfigured: () => true,
|
||||||
|
getAccessToken: () =>
|
||||||
|
new Promise((resolve) => {
|
||||||
|
resolveSession = resolve
|
||||||
|
}),
|
||||||
|
endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy',
|
||||||
|
fetchImpl: async () => new Response(null, { status: 500 }),
|
||||||
|
onMessagesUpdate: (updater) => {
|
||||||
|
currentMessages = updater(currentMessages)
|
||||||
|
},
|
||||||
|
onInputChange: (val) => {
|
||||||
|
restoredInput = val
|
||||||
|
},
|
||||||
|
onErrorChange: (err) => {
|
||||||
|
latestError = err
|
||||||
|
},
|
||||||
|
onBusyChange: (busy) => {
|
||||||
|
busyState = busy
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(45_000)
|
||||||
|
resolveSession('late-token')
|
||||||
|
await pendingTurn
|
||||||
|
|
||||||
|
expect(currentMessages).toEqual([
|
||||||
|
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
|
||||||
|
])
|
||||||
|
expect(restoredInput).toBe('다시 시도할 질문')
|
||||||
|
expect(latestError).toBe('AI 응답 시간이 초과되었습니다.')
|
||||||
|
expect(busyState).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('executeChatSendTurn_스트림중언마운트_reader를취소하고오류나롤백을갱신하지않는다', async () => {
|
||||||
|
const encoder = new TextEncoder()
|
||||||
|
let mounted = true
|
||||||
|
let streamCancelled = false
|
||||||
|
const body = new ReadableStream<Uint8Array>({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(
|
||||||
|
encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"부분"}}\n\n'),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
cancel() {
|
||||||
|
streamCancelled = true
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
let currentMessages: ChatMessage[] = []
|
||||||
|
let inputCalls = 0
|
||||||
|
let errorCalls = 0
|
||||||
|
const activeRef: { current: AbortController | null } = { current: null }
|
||||||
|
|
||||||
|
const pendingTurn = executeChatSendTurn({
|
||||||
|
text: '언마운트 테스트',
|
||||||
|
messages: currentMessages,
|
||||||
|
activeControllerRef: activeRef,
|
||||||
|
isMounted: () => mounted,
|
||||||
|
isConfigured: () => true,
|
||||||
|
getAccessToken: async () => 'access-token',
|
||||||
|
endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy',
|
||||||
|
fetchImpl: async () =>
|
||||||
|
new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }),
|
||||||
|
onMessagesUpdate: (updater) => {
|
||||||
|
currentMessages = updater(currentMessages)
|
||||||
|
},
|
||||||
|
onInputChange: () => {
|
||||||
|
inputCalls += 1
|
||||||
|
},
|
||||||
|
onErrorChange: () => {
|
||||||
|
errorCalls += 1
|
||||||
|
},
|
||||||
|
onBusyChange: () => undefined,
|
||||||
|
})
|
||||||
|
|
||||||
|
await vi.waitFor(() => {
|
||||||
|
expect(currentMessages.some((m) => m.content === '부분')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
const countBeforeUnmount = currentMessages.length
|
||||||
|
mounted = false
|
||||||
|
activeRef.current?.abort()
|
||||||
|
await pendingTurn
|
||||||
|
|
||||||
|
expect(streamCancelled).toBe(true)
|
||||||
|
expect(currentMessages.length).toBe(countBeforeUnmount)
|
||||||
|
expect(inputCalls).toBe(1)
|
||||||
|
expect(errorCalls).toBe(1)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue