7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
Stream Playground responses for every model (#942)
Tashfeen51f888c65383
diff --git a/client/src/lib/playground-stream.test.ts b/client/src/lib/playground-stream.test.tsnew file mode 100644index 00000000..6a36d8c8--- /dev/null+++ b/client/src/lib/playground-stream.test.ts@@ -0,0 +1,224 @@+import { describe, it, expect, vi } from 'vitest'+import { frameData, readChatStream, type ChatStreamHandlers } from './playground-stream'++/** A stream that hands out exactly these byte chunks, in order. */+function streamOf(...chunks: string[]): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder()+ return new ReadableStream<Uint8Array>({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(encoder.encode(chunk))+ controller.close()+ },+ })+}++/** One `data:` frame, framed the way the proxy writes it. */+const frame = (payload: unknown) => `data: ${JSON.stringify(payload)}\n\n`++/** A content delta chunk, shaped like the proxy's `mkChunk`. */+const contentFrame = (content: string) => frame({+ id: 'chatcmpl-1', object: 'chat.completion.chunk', created: 1, model: 'llama-3.3-70b',+ choices: [{ index: 0, delta: { content }, finish_reason: null }],+})++const collect = () => {+ const deltas: string[] = []+ const reasoning: string[] = []+ const errors: string[] = []+ const handlers: ChatStreamHandlers = {+ onDelta: t => deltas.push(t),+ onReasoning: t => reasoning.push(t),+ onError: m => errors.push(m),+ }+ return { deltas, reasoning, errors, handlers }+}++describe('frameData', () => {+ it('pulls the payload out of a single-line frame', () => {+ expect(frameData('data: {"a":1}')).toBe('{"a":1}')+ })++ it('joins the multiple data lines of one event, per the SSE spec', () => {+ expect(frameData('data: line one\ndata: line two')).toBe('line one\nline two')+ })++ it('ignores comment/keepalive lines and other SSE fields', () => {+ expect(frameData(': keepalive')).toBeNull()+ expect(frameData('event: message\nid: 7')).toBeNull()+ expect(frameData('event: message\ndata: {"a":1}')).toBe('{"a":1}')+ })+})++describe('readChatStream', () => {+ it('assembles content from several frames delivered in one read', async () => {+ const { deltas, handlers } = collect()+ const result = await readChatStream(+ streamOf(contentFrame('Hello') + contentFrame(', ') + contentFrame('world') + 'data: [DONE]\n\n'),+ handlers,+ )+ expect(result.content).toBe('Hello, world')+ expect(result.done).toBe(true)+ expect(deltas).toEqual(['Hello', ', ', 'world'])+ })++ it('reassembles a frame whose JSON is split across two reads', async () => {+ const whole = contentFrame('split me')+ const cut = Math.floor(whole.length / 2)+ const result = await readChatStream(+ streamOf(whole.slice(0, cut), whole.slice(cut) + 'data: [DONE]\n\n'),+ )+ expect(result.content).toBe('split me')+ })++ it('reassembles a frame split at every single byte offset', async () => {+ // The reader must never depend on where the network happened to cut.+ const whole = contentFrame('abc') + contentFrame('def') + 'data: [DONE]\n\n'+ for (let cut = 1; cut < whole.length; cut++) {+ const result = await readChatStream(streamOf(whole.slice(0, cut), whole.slice(cut)))+ expect(result.content).toBe('abcdef')+ }+ })++ it('accumulates reasoning_content separately from the answer', async () => {+ const { deltas, reasoning, handlers } = collect()+ const result = await readChatStream(streamOf(+ frame({ choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] }),+ frame({ choices: [{ index: 0, delta: { reasoning_content: 'Let me ' }, finish_reason: null }] }),+ frame({ choices: [{ index: 0, delta: { reasoning_content: 'think.' }, finish_reason: null }] }),+ contentFrame('42'),+ 'data: [DONE]\n\n',+ ), handlers)+ expect(result.reasoning).toBe('Let me think.')+ expect(result.content).toBe('42')+ expect(reasoning).toEqual(['Let me ', 'think.'])+ expect(deltas).toEqual(['42'])+ })++ it('also accepts the Ollama-style `reasoning` key', async () => {+ const result = await readChatStream(streamOf(+ frame({ choices: [{ index: 0, delta: { reasoning: 'hmm' }, finish_reason: null }] }),+ ))+ expect(result.reasoning).toBe('hmm')+ })++ it('takes the finish reason and the trailing choice-less usage frame', async () => {+ const result = await readChatStream(streamOf(+ contentFrame('done'),+ frame({ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }),+ frame({ id: 'chatcmpl-1', object: 'chat.completion.chunk', choices: [], usage: { prompt_tokens: 9, completion_tokens: 2, total_tokens: 11 } }),+ 'data: [DONE]\n\n',+ ))+ expect(result.content).toBe('done')+ expect(result.finishReason).toBe('stop')+ expect(result.usage).toEqual({ prompt_tokens: 9, completion_tokens: 2, total_tokens: 11 })+ })++ it('stops at [DONE] and ignores anything written after it', async () => {+ const { deltas, handlers } = collect()+ const result = await readChatStream(+ streamOf(contentFrame('kept') + 'data: [DONE]\n\n' + contentFrame('ignored')),+ handlers,+ )+ expect(result.content).toBe('kept')+ expect(result.done).toBe(true)+ expect(deltas).toEqual(['kept'])+ })++ it('surfaces an in-band stream_error frame', async () => {+ const { errors, handlers } = collect()+ const result = await readChatStream(streamOf(+ contentFrame('partial '),+ frame({ error: { message: 'Provider error (Groq): stream interrupted', type: 'stream_error' } }),+ 'data: [DONE]\n\n',+ ), handlers)+ expect(result.error).toBe('Provider error (Groq): stream interrupted')+ expect(errors).toEqual(['Provider error (Groq): stream interrupted'])+ // Whatever already streamed is still there — the error explains the cut.+ expect(result.content).toBe('partial ')+ expect(result.done).toBe(true)+ })++ it('falls back to a generic message when the error frame has no message', async () => {+ const result = await readChatStream(streamOf(frame({ error: { type: 'stream_error' } })))+ expect(result.error).toBe('Stream error')+ })++ it('skips unparseable frames instead of throwing', async () => {+ const { errors, handlers } = collect()+ const result = await readChatStream(streamOf(+ contentFrame('one'),+ 'data: {not json at all\n\n',+ 'data: null\n\n',+ ': keepalive\n\n',+ 'garbage without a data prefix\n\n',+ contentFrame(' two'),+ 'data: [DONE]\n\n',+ ), handlers)+ expect(result.content).toBe('one two')+ expect(errors).toEqual([])+ })++ it('handles CRLF frame separators, including a CRLF split across reads', async () => {+ const crlf = (payload: unknown) => `data: ${JSON.stringify(payload)}\r\n\r\n`+ const first = crlf({ choices: [{ index: 0, delta: { content: 'a' }, finish_reason: null }] })+ const result = await readChatStream(streamOf(+ // Cut the stream between the \r and the \n of the frame terminator.+ first.slice(0, -1),+ '\n' + crlf({ choices: [{ index: 0, delta: { content: 'b' }, finish_reason: null }] }) + 'data: [DONE]\r\n\r\n',+ ))+ expect(result.content).toBe('ab')+ expect(result.done).toBe(true)+ })++ it('resolves with what it got when the stream ends without [DONE]', async () => {+ const result = await readChatStream(streamOf(contentFrame('cut short')))+ expect(result.content).toBe('cut short')+ expect(result.done).toBe(false)+ })++ it('reads a last frame that never got its terminating blank line', async () => {+ const result = await readChatStream(streamOf(+ contentFrame('first'),+ 'data: {"choices":[{"index":0,"delta":{"content":" last"},"finish_reason":null}]}',+ ))+ expect(result.content).toBe('first last')+ expect(result.done).toBe(false)+ })++ it('ignores tool_call deltas rather than rendering them', async () => {+ const { deltas, handlers } = collect()+ const result = await readChatStream(streamOf(+ frame({ choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: 'call_1', type: 'function', function: { name: 'get_weather', arguments: '{"city":"Oslo"}' } }] }, finish_reason: null }] }),+ frame({ choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] }),+ 'data: [DONE]\n\n',+ ), handlers)+ expect(result.content).toBe('')+ expect(deltas).toEqual([])+ expect(result.finishReason).toBe('tool_calls')+ })++ it('survives an empty stream', async () => {+ const result = await readChatStream(streamOf())+ expect(result).toEqual({ content: '', reasoning: '', done: false })+ })++ it('calls onDone exactly once, with the assembled result', async () => {+ const onDone = vi.fn()+ const result = await readChatStream(+ streamOf(contentFrame('hi') + 'data: [DONE]\n\n'),+ { onDone },+ )+ expect(onDone).toHaveBeenCalledTimes(1)+ expect(onDone).toHaveBeenCalledWith(result)+ })++ it('propagates a reader failure so the caller can show an error bubble', async () => {+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode(contentFrame('partial')))+ controller.error(new Error('network went away'))+ },+ })+ await expect(readChatStream(stream)).rejects.toThrow('network went away')+ })+})diff --git a/client/src/lib/playground-stream.ts b/client/src/lib/playground-stream.tsnew file mode 100644index 00000000..a8715cc5--- /dev/null+++ b/client/src/lib/playground-stream.ts@@ -0,0 +1,187 @@+// SSE reader for the Playground's non-fusion chat streams.+//+// Every Playground request now asks for `stream: true`, so the standard+// OpenAI chat-completion stream has to be assembled in the browser. The proxy+// frames it as `data: {...}` blocks separated by a blank line and terminated by+// `data: [DONE]`, but the details vary per provider: a role-only preamble+// frame, tool_call deltas we don't render, a finish chunk, and a trailing+// usage-only frame whose `choices` array is empty. Network reads also split+// frames at arbitrary byte offsets, so a frame can arrive half at a time.+//+// Kept as a pure function over a ReadableStream so all of that is unit-testable+// without a component or a live provider.++/** Token accounting from the trailing usage frame (shape passed through as-is). */+export interface ChatStreamUsage {+ prompt_tokens?: number+ completion_tokens?: number+ total_tokens?: number+}++export interface ChatStreamResult {+ /** Everything accumulated from `choices[0].delta.content`. */+ content: string+ /** Everything accumulated from `choices[0].delta.reasoning_content`. */+ reasoning: string+ /** The last non-null `choices[0].finish_reason`, when the stream sent one. */+ finishReason?: string+ /** Usage from the finish chunk or the trailing choice-less frame. */+ usage?: ChatStreamUsage+ /** Message from an in-band `{ error: {...} }` frame, if one arrived. */+ error?: string+ /** True when the stream ended with an explicit `data: [DONE]`. */+ done: boolean+}++export interface ChatStreamHandlers {+ /** A visible answer delta. Called once per frame that carries content. */+ onDelta?: (text: string) => void+ /** A reasoning/thinking delta, kept separate from the answer. */+ onReasoning?: (text: string) => void+ /** An in-band stream error. The stream may still send `[DONE]` after it. */+ onError?: (message: string) => void+ /** Called once, after the stream ends, with the assembled result. */+ onDone?: (result: ChatStreamResult) => void+}++interface ChunkChoice {+ delta?: {+ content?: unknown+ reasoning_content?: unknown+ reasoning?: unknown+ tool_calls?: unknown+ }+ finish_reason?: unknown+}++/**+ * Pull the payload out of one SSE event block. An event may carry several+ * `data:` lines (they concatenate with newlines, per the SSE spec); comment+ * lines (`: keepalive`) and any other field are ignored. Returns null when the+ * block has no data at all.+ */+export function frameData(frame: string): string | null {+ const parts: string[] = []+ for (const rawLine of frame.split(/\r\n|\r|\n/)) {+ const line = rawLine.trim()+ if (!line || line.startsWith(':')) continue+ if (!line.startsWith('data:')) continue+ parts.push(line.slice(5).trim())+ }+ return parts.length > 0 ? parts.join('\n') : null+}++/**+ * Read a chat-completion SSE stream to the end, reporting deltas as they land.+ *+ * Tolerant by design: unparseable frames are skipped rather than thrown,+ * choice-less frames (the trailing usage frame) are fine, and a stream that+ * simply ends without `[DONE]` still resolves with whatever it produced. Only+ * a reader failure — an aborted fetch, a dropped socket — rejects.+ */+export async function readChatStream(+ stream: ReadableStream<Uint8Array>,+ handlers: ChatStreamHandlers = {},+): Promise<ChatStreamResult> {+ const reader = stream.getReader()+ const decoder = new TextDecoder()+ const result: ChatStreamResult = { content: '', reasoning: '', done: false }+ let buffer = ''++ // Returns true once `[DONE]` says there is nothing left to read.+ const handleFrame = (frame: string): boolean => {+ const data = frameData(frame)+ if (data === null) return false+ if (data === '[DONE]') return true++ let obj: Record<string, unknown>+ try {+ obj = JSON.parse(data) as Record<string, unknown>+ } catch {+ // Garbage or a partial frame the server flushed: skip it, keep reading.+ return false+ }+ if (!obj || typeof obj !== 'object') return false++ const error = obj.error as { message?: unknown } | undefined+ if (error) {+ const message = typeof error.message === 'string' ? error.message : 'Stream error'+ result.error = message+ handlers.onError?.(message)+ return false+ }++ const usage = obj.usage as ChatStreamUsage | null | undefined+ if (usage && typeof usage === 'object') result.usage = usage++ // A usage-only frame carries `choices: []`, and some providers omit the+ // key entirely on keepalive frames — neither is an error.+ const choices = obj.choices as ChunkChoice[] | undefined+ if (!Array.isArray(choices) || choices.length === 0) return false+ const choice = choices[0]+ if (!choice || typeof choice !== 'object') return false++ if (typeof choice.finish_reason === 'string') result.finishReason = choice.finish_reason++ const delta = choice.delta+ if (!delta || typeof delta !== 'object') return false++ // delta.tool_calls is deliberately ignored: the Playground renders prose,+ // and a half-assembled tool call is not something to show mid-stream.+ const reasoning = typeof delta.reasoning_content === 'string'+ ? delta.reasoning_content+ : typeof delta.reasoning === 'string' ? delta.reasoning : ''+ if (reasoning) {+ result.reasoning += reasoning+ handlers.onReasoning?.(reasoning)+ }+ if (typeof delta.content === 'string' && delta.content.length > 0) {+ result.content += delta.content+ handlers.onDelta?.(delta.content)+ }+ return false+ }++ try {+ reading: for (;;) {+ const { done, value } = await reader.read()+ if (done) break+ // Normalising the whole buffer (not just the new bytes) keeps a CRLF+ // that straddles two reads from looking like a blank-line boundary.+ buffer = (buffer + decoder.decode(value, { stream: true })).replace(/\r\n/g, '\n')+ for (;;) {+ const boundary = buffer.indexOf('\n\n')+ if (boundary === -1) break+ const frame = buffer.slice(0, boundary)+ buffer = buffer.slice(boundary + 2)+ if (handleFrame(frame)) {+ result.done = true+ break reading+ }+ }+ }++ if (!result.done) {+ // Streams that end without a trailing blank line (or without [DONE] at+ // all) still leave a usable frame in the buffer.+ buffer = (buffer + decoder.decode()).replace(/\r\n/g, '\n')+ for (const frame of buffer.split('\n\n')) {+ if (handleFrame(frame)) {+ result.done = true+ break+ }+ }+ }+ } finally {+ // Releases the socket when we stopped early at [DONE]; a no-op once the+ // stream is already exhausted or the fetch was aborted.+ try {+ await reader.cancel()+ } catch {+ // The stream is already errored or closed — nothing to clean up.+ }+ }++ handlers.onDone?.(result)+ return result+}diff --git a/client/src/pages/PlaygroundPage.tsx b/client/src/pages/PlaygroundPage.tsxindex e8155be9..81658abd 100644--- a/client/src/pages/PlaygroundPage.tsx+++ b/client/src/pages/PlaygroundPage.tsx@@ -26,6 +26,7 @@ import {toMessageContent,type Attachment,} from '@/lib/attachments'+import { readChatStream } from '@/lib/playground-stream'import { useI18n } from '@/i18n'interface FallbackEntry {@@ -51,6 +52,11 @@ interface ChatMessage {// Request-level failure rendered as a distinct error bubble, not a fake// assistant reply.isError?: boolean+ // Thinking tokens (`delta.reasoning_content`) accumulated separately from the+ // answer, shown as a collapsible aside above it.+ reasoning?: string+ // True while this bubble is still being filled in by an open stream.+ streaming?: booleanmeta?: {platform?: stringmodel?: string@@ -133,6 +139,42 @@ function FusionTrace({ panel, judge, streaming, answerStarted }: {)}+// Thinking tokens, shown INSIDE the assistant bubble above the answer. Same+// visual language as FusionTrace (minimal font, muted, hanging rule, chevron+// toggle) and the same behaviour: open while it streams so you can watch the+// model work, auto-collapsing once the answer itself starts.+function ReasoningTrace({ text, answerStarted }: { text: string; answerStarted?: boolean }) {+ const { t } = useI18n()+ const [open, setOpen] = useState(true)+ const touched = useRef(false)+ useEffect(() => {+ if (answerStarted && !touched.current) setOpen(false)+ }, [answerStarted])+ return (+ <div className="mb-2 text-[10px] leading-snug text-muted-foreground/80">+ <button+ type="button"+ onClick={() => { touched.current = true; setOpen(o => !o) }}+ className="inline-flex items-center gap-1 font-mono hover:text-foreground transition-colors"+ >+ <ChevronRight className={`size-3 transition-transform ${open ? 'rotate-90' : ''}`} />+ {open ? t('common.hide') : t('common.show')}+ </button>+ {open && (+ <div className="mt-1 whitespace-pre-wrap border-l border-border/60 pl-2.5 italic opacity-80">+ {text}+ </div>+ )}+ </div>+ )+}++// How close to the bottom of the transcript still counts as "reading the live+// answer", in pixels. Slack is needed either way — sub-pixel scroll positions+// mean an exact comparison never matches — and a couple of lines' worth of it+// keeps the follow from dropping out on a stray trackpad nudge.+const SCROLL_FOLLOW_SLACK = 40+export default function PlaygroundPage() {const { t } = useI18n()const [messages, setMessages] = useState<ChatMessage[]>([])@@ -159,8 +201,17 @@ export default function PlaygroundPage() {const [attachments, setAttachments] = useState<Attachment[]>([])const [dragging, setDragging] = useState(false)const messagesEndRef = useRef<HTMLDivElement>(null)+ const transcriptRef = useRef<HTMLDivElement>(null)const inputRef = useRef<HTMLTextAreaElement>(null)const fileInputRef = useRef<HTMLInputElement>(null)+ // Whether the transcript should keep itself pinned to the bottom. Every model+ // streams now, so a message can grow for a minute straight — scrolling up to+ // re-read something must not be undone by the next token.+ const followRef = useRef(true)+ const lastScrollTopRef = useRef(0)+ // Cancels the in-flight completion when the user clears the chat, sends+ // again, or navigates away mid-stream.+ const abortRef = useRef<AbortController | null>(null)const { data: keyData } = useQuery<{ apiKey: string }>({queryKey: ['unified-key'],@@ -193,10 +244,33 @@ export default function PlaygroundPage() {&& selectedModel !== 'auto' && selectedModel !== 'fusion'&& !visionValues.has(selectedModel)+ // Follow the stream only while the reader is parked at the bottom. Judging+ // by direction (rather than position alone) keeps our own smooth-scroll+ // animation — which always travels downwards — from being mistaken for the+ // user taking over, whatever they used to scroll: wheel, keys, or the bar.+ useEffect(() => {+ const el = transcriptRef.current+ if (!el) return+ lastScrollTopRef.current = el.scrollTop+ const onScroll = () => {+ const top = el.scrollTop+ const movedUp = top < lastScrollTopRef.current - 1+ lastScrollTopRef.current = top+ if (el.scrollHeight - top - el.clientHeight <= SCROLL_FOLLOW_SLACK) followRef.current = true+ else if (movedUp) followRef.current = false+ }+ el.addEventListener('scroll', onScroll, { passive: true })+ return () => el.removeEventListener('scroll', onScroll)+ }, [])+useEffect(() => {- messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })+ if (followRef.current) messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })}, [messages])+ // A stream left running after the page goes away would keep calling+ // setMessages on an unmounted tree (and hold the socket open).+ useEffect(() => () => abortRef.current?.abort(), [])+// Read a fusion SSE stream, updating the assistant message in place as panel// answers + the judge arrive (additive `_fusion` frames) and the final answer// streams as content deltas.@@ -249,6 +323,55 @@ export default function PlaygroundPage() {flush(false)}+ // Read a plain (non-fusion) OpenAI chat stream, filling the assistant bubble+ // in place as content and reasoning deltas land. The routing metadata is+ // already known — it rides on the response headers, which arrive before the+ // first frame — so the only thing the stream adds is the latency, measured+ // to the last frame rather than to the first.+ const streamChat = async (+ stream: ReadableStream<Uint8Array>,+ baseMessages: ChatMessage[],+ start: number,+ routedVia: string | null,+ fallbackAttempts: string | null,+ ) => {+ const via = routedVia+ ? { platform: routedVia.split('/')[0], model: routedVia.split('/').slice(1).join('/') }+ : undefined+ let content = ''+ let reasoning = ''+ let failure: string | null = null++ const flush = (streaming: boolean) => {+ const next: ChatMessage[] = [...baseMessages]+ // A stream that broke before the first token has nothing to show but the+ // error; one that broke halfway keeps what it managed to say.+ if (content || reasoning || failure === null) {+ next.push({+ role: 'assistant',+ content,+ ...(reasoning ? { reasoning } : {}),+ ...(streaming ? { streaming: true } : {}),+ meta: {+ platform: via?.platform,+ model: via?.model,+ latency: Date.now() - start,+ fallbackAttempts: fallbackAttempts ? parseInt(fallbackAttempts) : undefined,+ },+ })+ }+ if (failure !== null) next.push({ role: 'assistant', isError: true, content: failure })+ setMessages(next)+ }++ await readChatStream(stream, {+ onDelta: text => { content += text; flush(true) },+ onReasoning: text => { reasoning += text; flush(true) },+ onError: message => { failure = message; flush(true) },+ })+ flush(false)+ }+// Stage dropped/pasted/picked files. Every rejection is reported by name so a// silently missing attachment is impossible; accepted files are added in one// batch after the async reads settle.@@ -307,6 +430,9 @@ export default function PlaygroundPage() {...(pendingImages.length > 0 ? { images: pendingImages } : {}),}const newMessages = [...messages, userMsg]+ // Your own message always brings the transcript back down, however far up+ // you had scrolled to read.+ followRef.current = truesetMessages(newMessages)setInput('')setAttachments([])@@ -326,9 +452,14 @@ export default function PlaygroundPage() {],}if (selectedModel !== 'auto') body.model = selectedModel- // Fusion streams its panel + judge trace; ask for a stream so the- // Playground can show the other models arriving before the final answer.- if (isFusion) body.stream = true+ // Everything streams: fusion so you can watch the panel and the judge+ // arrive, every other model so the answer appears token by token instead+ // of after a silent minute.+ body.stream = true++ abortRef.current?.abort()+ const controller = new AbortController()+ abortRef.current = controllerconst base = import.meta.env.BASE_URL.replace(/\/$/, '')const start = Date.now()@@ -336,6 +467,7 @@ export default function PlaygroundPage() {method: 'POST',headers,body: JSON.stringify(body),+ signal: controller.signal,})const latency = Date.now() - start@@ -357,6 +489,15 @@ export default function PlaygroundPage() {return}+ // The proxy answers a streamed request with SSE or not at all (every+ // pre-commit failure is a non-2xx JSON body, already handled above), but+ // fall back to the buffered path rather than trusting that: a proxy in+ // front of us, or a future non-streaming route, can still hand back JSON.+ if (!isFusion && res.body && (res.headers.get('Content-Type') ?? '').includes('text/event-stream')) {+ await streamChat(res.body, newMessages, start, routedVia, fallbackAttempts)+ return+ }+const data = await res.json()const content = data.choices?.[0]?.message?.content ?? JSON.stringify(data, null, 2)const via = data._routed_via ?? (routedVia ? {@@ -384,6 +525,10 @@ export default function PlaygroundPage() {},}])} catch (err: any) {+ // Clearing the chat (or leaving the page) aborts the stream on purpose —+ // that is not a failure to report, and the transcript it belonged to is+ // already gone.+ if (err?.name === 'AbortError') returnsetMessages([...newMessages, {role: 'assistant',isError: true,@@ -403,8 +548,13 @@ export default function PlaygroundPage() {}const handleClear = () => {+ // Clearing mid-stream has to stop the stream too, or its next frame would+ // paste the half-finished answer back into the empty transcript.+ abortRef.current?.abort()+ abortRef.current = nullsetMessages([])setAttachments([])+ followRef.current = trueinputRef.current?.focus()}@@ -478,7 +628,7 @@ export default function PlaygroundPage() {/><div className="flex-1 flex flex-col rounded-3xl border bg-card overflow-hidden min-h-0">- <div className="flex-1 overflow-y-auto p-6 space-y-4">+ <div ref={transcriptRef} className="flex-1 overflow-y-auto p-6 space-y-4">{messages.length === 0 ? (<div className="flex items-center justify-center h-full text-center"><div className="space-y-2 max-w-sm">@@ -495,7 +645,9 @@ export default function PlaygroundPage() {const okPanel = fusionPanel?.filter(p => p.status !== 'failed') ?? []// Skip an empty assistant bubble while the fusion trace is still// streaming in (no final answer yet) — the trace shows below.- const showBubble = msg.role === 'user' || msg.content.length > 0+ // Reasoning that arrives before the first answer token counts:+ // that IS the bubble's content for the moment.+ const showBubble = msg.role === 'user' || msg.content.length > 0 || !!msg.reasoningreturn (<div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}><div className={`flex flex-col gap-1 max-w-[80%] ${msg.role === 'user' ? 'items-end' : 'items-start'}`}>@@ -525,7 +677,12 @@ export default function PlaygroundPage() {</div></div>) : msg.role === 'assistant' ? (- <Markdown>{msg.content}</Markdown>+ <>+ {msg.reasoning && (+ <ReasoningTrace text={msg.reasoning} answerStarted={msg.content.length > 0} />+ )}+ <Markdown>{msg.content}</Markdown>+ </>) : (<div className="whitespace-pre-wrap">{msg.content}</div>)}@@ -558,7 +715,11 @@ export default function PlaygroundPage() {<>{msg.meta.platform && <span>{msg.meta.platform}</span>}{msg.meta.model && <span className="font-mono">· {msg.meta.model}</span>}- {msg.meta.latency != null && <span>· {msg.meta.latency} ms</span>}+ {/* Which provider served it is known from the+ response headers straight away; the timing+ only means something once the last frame+ has landed. */}+ {msg.meta.latency != null && !msg.streaming && <span>· {msg.meta.latency} ms</span>}{msg.meta.fallbackAttempts != null && msg.meta.fallbackAttempts > 0 && (<span>· {msg.meta.fallbackAttempts} {msg.meta.fallbackAttempts > 1 ? t('playground.fallbacks') : t('playground.fallback')}</span>)}@@ -580,7 +741,10 @@ export default function PlaygroundPage() {</div>)})}- {loading && !messages[messages.length - 1]?.meta?.fusionStreaming && (+ {/* Typing dots until the reply starts materialising — which is+ the first fusion frame, the first token of a stream, or the+ whole message on the buffered path. */}+ {loading && messages[messages.length - 1]?.role === 'user' && (<div className="flex justify-start"><div className="bg-muted rounded-2xl px-4 py-3"><div className="flex gap-1">