fix(web): propagate mounted timeouts across chat stream and edge-fetch awaits

This commit is contained in:
Yun Chan 2026-11-14 15:23:28 +09:00
parent c68e81e0aa
commit 4bf0f0df12
7 changed files with 363 additions and 106 deletions

View file

@ -3,7 +3,11 @@ 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 } from '@/components/chat/chat-panel'
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 {
@ -11,6 +15,7 @@ import {
createTimedAbortSignal,
resolveSupabaseFunctionUrl,
scheduleTrackedTimeout,
shouldExitAfterAwait,
} from '@/lib/edge-fetch'
import { safeReturnPath } from '@/lib/web-app-url'
@ -217,9 +222,16 @@ describe('Web URL 안전성 및 OAuth 콜백 보안', () => {
vi.advanceTimersByTime(1000)
expect(handle.didTimeout()).toBe(true)
expect(handle.controller.signal.aborted).toBe(true)
expect(() => shouldExitAfterAwait(handle, () => true)).toThrow('Request timed out')
expect(shouldExitAfterAwait(handle, () => false)).toBe(true)
handle.dispose()
expect(activeRef.current).toBe(null)
const manualHandle = createTimedAbortSignal(1000, activeRef)
manualHandle.controller.abort()
expect(shouldExitAfterAwait(manualHandle, () => true)).toBe(true)
manualHandle.dispose()
const timerRef: { current: ReturnType<typeof setTimeout> | null } = { current: null }
const calls: string[] = []
scheduleTrackedTimeout(timerRef, () => calls.push('first'), 500)
@ -232,4 +244,172 @@ describe('Web URL 안전성 및 OAuth 콜백 보안', () => {
vi.advanceTimersByTime(1000)
expect(calls).toEqual(['second'])
})
it('executeChatSendTurn_스트림응답중45초타임아웃_부분메시지롤백과입력복구및시간초과오류를표시한다', async () => {
vi.useFakeTimers()
const encoder = new TextEncoder()
let streamCancelled = false
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(
encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"부분응답"}}\n\n'),
)
},
cancel() {
streamCancelled = true
},
})
let currentMessages: ChatMessage[] = [
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
]
let restoredInput = ''
let latestError: string | null = null
let busyState = false
const activeRef: { current: AbortController | null } = { current: null }
const pendingTurn = executeChatSendTurn({
text: '회의 요약해줘',
messages: currentMessages,
activeControllerRef: activeRef,
isMounted: () => true,
isConfigured: () => true,
getAccessToken: async () => 'access-token',
endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy',
fetchImpl: async () =>
new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }),
onMessagesUpdate: (updater) => {
currentMessages = updater(currentMessages)
},
onInputChange: (val) => {
restoredInput = val
},
onErrorChange: (err) => {
latestError = err
},
onBusyChange: (busy) => {
busyState = busy
},
})
await vi.advanceTimersByTimeAsync(100)
expect(currentMessages.some((m) => m.role === 'assistant' && m.content === '부분응답')).toBe(true)
await vi.advanceTimersByTimeAsync(45_000)
await pendingTurn
expect(streamCancelled).toBe(true)
expect(currentMessages).toEqual([
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
])
expect(restoredInput).toBe('회의 요약해줘')
expect(latestError).toBe('AI 응답 시간이 초과되었습니다.')
expect(busyState).toBe(false)
})
it('executeChatSendTurn_세션조회중45초타임아웃_조용히종료하지않고입력복구와시간초과오류를표시한다', async () => {
vi.useFakeTimers()
let currentMessages: ChatMessage[] = [
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
]
let restoredInput = ''
let latestError: string | null = null
let busyState = false
let resolveSession!: (token: string | null) => void
const activeRef: { current: AbortController | null } = { current: null }
const pendingTurn = executeChatSendTurn({
text: '다시 시도할 질문',
messages: currentMessages,
activeControllerRef: activeRef,
isMounted: () => true,
isConfigured: () => true,
getAccessToken: () =>
new Promise((resolve) => {
resolveSession = resolve
}),
endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy',
fetchImpl: async () => new Response(null, { status: 500 }),
onMessagesUpdate: (updater) => {
currentMessages = updater(currentMessages)
},
onInputChange: (val) => {
restoredInput = val
},
onErrorChange: (err) => {
latestError = err
},
onBusyChange: (busy) => {
busyState = busy
},
})
await vi.advanceTimersByTimeAsync(45_000)
resolveSession('late-token')
await pendingTurn
expect(currentMessages).toEqual([
{ id: 'welcome', role: 'assistant', content: '초기 안내', timestamp: '09:00' },
])
expect(restoredInput).toBe('다시 시도할 질문')
expect(latestError).toBe('AI 응답 시간이 초과되었습니다.')
expect(busyState).toBe(false)
})
it('executeChatSendTurn_스트림중언마운트_reader를취소하고오류나롤백을갱신하지않는다', async () => {
const encoder = new TextEncoder()
let mounted = true
let streamCancelled = false
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(
encoder.encode('data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"부분"}}\n\n'),
)
},
cancel() {
streamCancelled = true
},
})
let currentMessages: ChatMessage[] = []
let inputCalls = 0
let errorCalls = 0
const activeRef: { current: AbortController | null } = { current: null }
const pendingTurn = executeChatSendTurn({
text: '언마운트 테스트',
messages: currentMessages,
activeControllerRef: activeRef,
isMounted: () => mounted,
isConfigured: () => true,
getAccessToken: async () => 'access-token',
endpointUrl: 'https://proj.supabase.co/functions/v1/llm-proxy',
fetchImpl: async () =>
new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }),
onMessagesUpdate: (updater) => {
currentMessages = updater(currentMessages)
},
onInputChange: () => {
inputCalls += 1
},
onErrorChange: () => {
errorCalls += 1
},
onBusyChange: () => undefined,
})
await vi.waitFor(() => {
expect(currentMessages.some((m) => m.content === '부분')).toBe(true)
})
const countBeforeUnmount = currentMessages.length
mounted = false
activeRef.current?.abort()
await pendingTurn
expect(streamCancelled).toBe(true)
expect(currentMessages.length).toBe(countBeforeUnmount)
expect(inputCalls).toBe(1)
expect(errorCalls).toBe(1)
})
})