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 { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
|
||||
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'
|
||||
|
||||
type ActionType =
|
||||
|
|
@ -78,7 +82,7 @@ export function ActionRunner(): React.ReactElement {
|
|||
const {
|
||||
data: { session }
|
||||
} = await supabase.auth.getSession()
|
||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
||||
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
|
||||
if (!session) {
|
||||
throw new Error('로그인이 필요합니다')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
createTimedAbortSignal,
|
||||
resolveSupabaseFunctionUrl,
|
||||
scheduleTrackedTimeout,
|
||||
shouldExitAfterAwait,
|
||||
} from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
|
||||
|
|
@ -43,7 +44,7 @@ export function PaypleManageButton(): React.ReactElement {
|
|||
try {
|
||||
const supabase = getSupabaseBrowserClient()
|
||||
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) {
|
||||
setError('로그인이 필요합니다')
|
||||
|
|
|
|||
|
|
@ -8,16 +8,148 @@ 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 } from '@/lib/edge-fetch'
|
||||
import {
|
||||
createTimedAbortSignal,
|
||||
resolveSupabaseFunctionUrl,
|
||||
shouldExitAfterAwait,
|
||||
} from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient, isSupabaseConfigured } from '@/lib/supabase-browser'
|
||||
|
||||
interface Message {
|
||||
export interface ChatMessage {
|
||||
id: string
|
||||
role: 'user' | 'assistant'
|
||||
content: string
|
||||
timestamp: string
|
||||
}
|
||||
|
||||
export 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를 해제한다.
|
||||
*/
|
||||
|
|
@ -81,7 +213,7 @@ export async function consumeChatSseStream(options: {
|
|||
}
|
||||
|
||||
export function ChatPanel(): React.ReactElement {
|
||||
const [messages, setMessages] = useState<Message[]>([
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([
|
||||
{
|
||||
id: 'welcome',
|
||||
role: 'assistant',
|
||||
|
|
@ -125,102 +257,22 @@ export function ChatPanel(): React.ReactElement {
|
|||
const text = input.trim()
|
||||
if (!text || busy) return
|
||||
|
||||
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]
|
||||
const assistantId = 'a_' + Date.now()
|
||||
setMessages(nextMessages)
|
||||
setInput('')
|
||||
setError(null)
|
||||
setBusy(true)
|
||||
const timedAbort = createTimedAbortSignal(45_000, activeControllerRef)
|
||||
|
||||
try {
|
||||
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)
|
||||
}
|
||||
}
|
||||
await executeChatSendTurn({
|
||||
text,
|
||||
messages,
|
||||
activeControllerRef,
|
||||
isMounted: () => mountedRef.current,
|
||||
isConfigured: isSupabaseConfigured,
|
||||
getAccessToken: async () => {
|
||||
const supabase = getSupabaseBrowserClient()
|
||||
const { data: { session } } = await supabase.auth.getSession()
|
||||
return session?.access_token ?? null
|
||||
},
|
||||
onMessagesUpdate: setMessages,
|
||||
onInputChange: setInput,
|
||||
onErrorChange: setError,
|
||||
onBusyChange: setBusy,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -14,7 +14,11 @@ import {
|
|||
Box
|
||||
} from '@mui/material'
|
||||
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'
|
||||
|
||||
type TemplateType = 'minutes' | 'report' | 'idea-note' | 'mindmap'
|
||||
|
|
@ -99,7 +103,7 @@ export function GenerateDocumentButton({
|
|||
const {
|
||||
data: { session }
|
||||
} = await supabase.auth.getSession()
|
||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
||||
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
|
||||
if (!session) {
|
||||
setError('로그인이 필요합니다')
|
||||
return
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import {
|
|||
createTimedAbortSignal,
|
||||
resolveSupabaseFunctionUrl,
|
||||
scheduleTrackedTimeout,
|
||||
shouldExitAfterAwait,
|
||||
} from '@/lib/edge-fetch'
|
||||
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
|
||||
|
||||
|
|
@ -73,7 +74,7 @@ export function InviteMemberForm({ teamId }: InviteMemberFormProps): React.React
|
|||
const {
|
||||
data: { session }
|
||||
} = await supabase.auth.getSession()
|
||||
if (!mountedRef.current || timedAbort.controller.signal.aborted) return
|
||||
if (shouldExitAfterAwait(timedAbort, () => mountedRef.current)) return
|
||||
if (!session) {
|
||||
setError('로그인이 필요합니다')
|
||||
return
|
||||
|
|
|
|||
|
|
@ -86,3 +86,18 @@ export function scheduleTrackedTimeout(
|
|||
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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue