fix(frontend): 修复 API Playground SSE 终态处理

main
T3L000 2026-08-13 19:44:58 +08:00 committed by lyingbug
parent 236d8c098f
commit abe96981c7
3 changed files with 291 additions and 31 deletions

View File

@ -701,6 +701,7 @@ import {
type ApiKeyCapabilityGroup,
} from '@/config/apiKeyCapabilities'
import { normalizeAPIKeyKnowledgeBaseIDs } from './apiKeyScope'
import { consumeApiPlaygroundSSE } from './apiPlaygroundSSE'
const { t } = useI18n()
@ -1610,26 +1611,6 @@ function formatJSON(value: unknown) {
}
}
function extractAnswerFromSSE(raw: string) {
const chunks: string[] = []
raw.split('\n').forEach((line) => {
if (!line.startsWith('data:')) return
const payload = line.slice(5).trim()
if (!payload || payload === '[DONE]') return
try {
const parsed = JSON.parse(payload)
const type = parsed?.response_type || parsed?.type
const content = parsed?.content
if (type === 'answer' && typeof content === 'string') {
chunks.push(content)
}
} catch {
// Keep raw stream visible even when an event is not JSON.
}
})
return chunks.join('')
}
async function readResponseBody(resp: Response) {
const text = await resp.text()
if (!text) return ''
@ -1718,19 +1699,16 @@ async function runPlayground() {
throw new Error(t('integrations.api.playgroundNoStream'))
}
const reader = chatResp.body.getReader()
const decoder = new TextDecoder()
let raw = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
raw += decoder.decode(value, { stream: true })
const result = await consumeApiPlaygroundSSE(chatResp.body, ({ raw, answer }) => {
playground.stream_output = compactText(raw)
playground.final_answer = extractAnswerFromSSE(raw)
playground.final_answer = answer
})
playground.stream_output = compactText(result.raw)
playground.final_answer = result.answer
if (result.status === 'failed') {
playground.chat_status = 'failed'
throw new Error(result.error || t('integrations.api.playgroundFailed'))
}
raw += decoder.decode()
playground.stream_output = compactText(raw)
playground.final_answer = extractAnswerFromSSE(raw)
playground.chat_status = 'success'
MessagePlugin.success(t('integrations.api.playgroundSuccess', {
ms: Math.round(performance.now() - startedAt),

View File

@ -0,0 +1,133 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { consumeApiPlaygroundSSE } from './apiPlaygroundSSE.ts'
const encoder = new TextEncoder()
function streamFromChunks(chunks: string[], keepOpen = false) {
let index = 0
let cancelled = false
const stream = new ReadableStream<Uint8Array>({
pull(controller) {
if (index < chunks.length) {
controller.enqueue(encoder.encode(chunks[index++]))
} else if (!keepOpen) {
controller.close()
}
},
cancel() {
cancelled = true
},
})
return { stream, wasCancelled: () => cancelled }
}
test('fails on a terminal error without waiting for the connection to close', async () => {
const fixture = streamFromChunks([
'event: message\ndata: {"response_type":"error","content":"synthetic provider failure","done":true}\n\n',
], true)
const result = await Promise.race([
consumeApiPlaygroundSSE(fixture.stream),
new Promise<never>((_, reject) => setTimeout(() => reject(new Error('timed out')), 200)),
])
assert.equal(result.status, 'failed')
assert.equal(result.error, 'synthetic provider failure')
assert.equal(fixture.wasCancelled(), true)
})
test('accepts current, legacy, and sentinel completion events', async (t) => {
const cases = [
{
name: 'complete event',
sse: 'data: {"response_type":"answer","content":"current","done":false}\n\ndata: {"response_type":"complete","content":"","done":true}\n\n',
answer: 'current',
},
{
name: 'legacy done event',
sse: 'data: {"response_type":"answer","content":"legacy","done":true}\n\n',
answer: 'legacy',
},
{
name: 'DONE sentinel',
sse: 'data: {"response_type":"answer","content":"sentinel","done":false}\n\ndata: [DONE]\n\n',
answer: 'sentinel',
},
]
for (const fixture of cases) {
await t.test(fixture.name, async () => {
const result = await consumeApiPlaygroundSSE(streamFromChunks([fixture.sse], true).stream)
assert.equal(result.status, 'success')
assert.equal(result.answer, fixture.answer)
})
}
})
test('does not treat another event type done marker as stream completion', async () => {
const result = await consumeApiPlaygroundSSE(streamFromChunks([
'data: {"response_type":"thinking","content":"thought","done":true}\n\n'
+ 'data: {"response_type":"answer","content":"answer","done":false}\n\n'
+ 'data: {"response_type":"complete","content":"","done":true}\n\n',
]).stream)
assert.equal(result.status, 'success')
assert.equal(result.answer, 'answer')
})
test('ignores frames after a terminal event', async () => {
const fixture = streamFromChunks([
'data: {"response_type":"answer","content":"before","done":false}\n\n'
+ 'data: {"response_type":"complete","content":"","done":true}\n\n',
'data: {"response_type":"answer","content":"after","done":false}\n\n',
], true)
const result = await consumeApiPlaygroundSSE(fixture.stream)
assert.equal(result.status, 'success')
assert.equal(result.answer, 'before')
assert.equal(fixture.wasCancelled(), true)
})
test('reports EOF without a business terminal event as failure', async () => {
const result = await consumeApiPlaygroundSSE(streamFromChunks([
'data: {"response_type":"answer","content":"partial","done":false}\n\n',
]).stream)
assert.equal(result.status, 'failed')
assert.equal(result.reason, 'unexpected-eof')
assert.equal(result.answer, 'partial')
})
test('keeps valid non-object JSON visible without crashing the parser', async () => {
const result = await consumeApiPlaygroundSSE(streamFromChunks([
'data: null\n\ndata: {"response_type":"complete","content":"","done":true}\n\n',
]).stream)
assert.equal(result.status, 'success')
assert.match(result.raw, /data: null/)
})
test('reassembles an SSE frame split across network chunks', async () => {
const result = await consumeApiPlaygroundSSE(streamFromChunks([
'event: message\ndata: {"response_type":"ans',
'wer","content":"split","done":false}\n',
'\ndata: {"response_type":"complete","content":"","done":tr',
'ue}\n\n',
]).stream)
assert.equal(result.status, 'success')
assert.equal(result.answer, 'split')
})
test('supports CRLF frames and joins multiple data lines', async () => {
const result = await consumeApiPlaygroundSSE(streamFromChunks([
'event: message\r\ndata: {"response_type":"answer",\r\n'
+ 'data: "content":"multiline","done":false}\r\n\r\n'
+ 'data: {"response_type":"complete","content":"","done":true}\r\n\r\n',
]).stream)
assert.equal(result.status, 'success')
assert.equal(result.answer, 'multiline')
})

View File

@ -0,0 +1,149 @@
export interface ApiPlaygroundSSEProgress {
raw: string
answer: string
}
export type ApiPlaygroundSSEResult = ApiPlaygroundSSEProgress & (
| { status: 'success' }
| { status: 'failed'; reason: 'terminal-error' | 'unexpected-eof'; error?: string }
)
interface TerminalState {
status: 'success' | 'failed'
error?: string
}
interface StreamEventPayload {
response_type?: unknown
type?: unknown
content?: unknown
message?: unknown
error?: unknown
done?: unknown
}
function readErrorMessage(payload: StreamEventPayload): string | undefined {
if (typeof payload.content === 'string' && payload.content.trim()) return payload.content
if (typeof payload.message === 'string' && payload.message.trim()) return payload.message
if (typeof payload.error === 'string' && payload.error.trim()) return payload.error
if (
payload.error
&& typeof payload.error === 'object'
&& 'message' in payload.error
&& typeof payload.error.message === 'string'
&& payload.error.message.trim()
) {
return payload.error.message
}
return undefined
}
function readEventData(frame: string): string | undefined {
const dataLines: string[] = []
for (const line of frame.split(/\r?\n/)) {
if (line === 'data') {
dataLines.push('')
} else if (line.startsWith('data:')) {
const value = line.slice(5)
dataLines.push(value.startsWith(' ') ? value.slice(1) : value)
}
}
return dataLines.length ? dataLines.join('\n') : undefined
}
function applyFrame(frame: string, answerChunks: string[]): TerminalState | undefined {
const data = readEventData(frame)
if (data === undefined) return undefined
if (data.trim() === '[DONE]') return { status: 'success' }
let payload: StreamEventPayload
try {
const parsed: unknown = JSON.parse(data)
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
payload = parsed as StreamEventPayload
} catch {
return undefined
}
const responseType = payload.response_type ?? payload.type
if (responseType === 'answer' && typeof payload.content === 'string') {
answerChunks.push(payload.content)
}
if (responseType === 'error') {
return { status: 'failed', error: readErrorMessage(payload) }
}
if (responseType === 'complete' || (responseType === 'answer' && payload.done === true)) {
return { status: 'success' }
}
return undefined
}
/**
* Consume an API Playground SSE stream until its business-level terminal event.
* The parser owns chunk buffering and terminal-state reduction so callers never
* need to infer success from the transport reaching EOF.
*/
export async function consumeApiPlaygroundSSE(
stream: ReadableStream<Uint8Array>,
onProgress?: (progress: ApiPlaygroundSSEProgress) => void,
): Promise<ApiPlaygroundSSEResult> {
const reader = stream.getReader()
const decoder = new TextDecoder()
const answerChunks: string[] = []
let raw = ''
let buffer = ''
const progress = () => {
const value = { raw, answer: answerChunks.join('') }
onProgress?.(value)
return value
}
const consumeFrames = (flush = false): TerminalState | undefined => {
while (true) {
const boundary = buffer.match(/\r?\n\r?\n/)
if (!boundary || boundary.index === undefined) break
const frame = buffer.slice(0, boundary.index)
buffer = buffer.slice(boundary.index + boundary[0].length)
const terminal = applyFrame(frame, answerChunks)
if (terminal) return terminal
}
if (flush && buffer) {
const terminal = applyFrame(buffer, answerChunks)
buffer = ''
return terminal
}
return undefined
}
const finish = (terminal: TerminalState): ApiPlaygroundSSEResult => {
const value = progress()
if (terminal.status === 'failed') {
return { ...value, status: 'failed', reason: 'terminal-error', error: terminal.error }
}
return { ...value, status: 'success' }
}
while (true) {
const { done, value } = await reader.read()
if (done) {
const tail = decoder.decode()
raw += tail
buffer += tail
const terminal = consumeFrames(true)
if (terminal) return finish(terminal)
const value = progress()
return { ...value, status: 'failed', reason: 'unexpected-eof' }
}
const chunk = decoder.decode(value, { stream: true })
raw += chunk
buffer += chunk
const terminal = consumeFrames()
if (terminal) {
void reader.cancel().catch(() => undefined)
return finish(terminal)
}
progress()
}
}