Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(streaming): Code and Agent stream on every transport, Hermes included

purple560fe7634cf3
diff --git a/src/api/providers/anthropic-provider.ts b/src/api/providers/anthropic-provider.ts
index 2f9deabf..206aaf1b 100644
--- a/src/api/providers/anthropic-provider.ts
+++ b/src/api/providers/anthropic-provider.ts
@@ -109,6 +109,17 @@ export class AnthropicProvider implements ProviderClient {
body.thinking = { type: 'enabled', budget_tokens: 5000 }
}
+ // Streaming tool turn (same conversion as chatWithTools below). The
+ // stream parser already accumulates tool_use blocks via input_json_delta
+ // and flushes them into the done-chunk's toolCalls.
+ if (options?.tools?.length) {
+ body.tools = options.tools.map(t => ({
+ name: t.function.name,
+ description: t.function.description,
+ input_schema: t.function.parameters,
+ }))
+ }
+
let res = await fetch(this.messagesUrl(), {
method: 'POST',
headers: this.headers,
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index bea0d4e5..33bc2e11 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -272,6 +272,12 @@ export class OpenAIProvider implements ProviderClient {
if (options?.temperature !== undefined) body.temperature = options.temperature
if (options?.topP !== undefined) body.top_p = options.topP
+ // Streaming tool turn: same wire shape as chatWithTools, but the calls
+ // come back as deltas which the accumulator below already merges.
+ if (options?.tools?.length) {
+ body.tools = options.tools
+ body.tool_choice = 'auto'
+ }
await this.applyMaxTokens(model, body, options)
// Reasoning-model knob (o1, o3, gpt-5-thinking, etc.). Toggle OFF →
// "minimal" (least reasoning the API allows). Toggle ON → "high".
diff --git a/src/api/providers/types.ts b/src/api/providers/types.ts
index d7cb8c26..9021f881 100644
--- a/src/api/providers/types.ts
+++ b/src/api/providers/types.ts
@@ -124,6 +124,13 @@ export interface ChatOptions {
// provider use its default.
contextWindow?: number
signal?: AbortSignal
+ // Tool definitions for a STREAMING tool turn. chatStream implementations
+ // that support tools include these in the request and stream tool-call
+ // deltas into the done-chunk's toolCalls; providers that cannot stream
+ // tools ignore the field, and their callers keep using chatWithTools.
+ // This is what lets Code/Agent mode stream on every transport instead of
+ // sitting silent until the whole call returns (David 2026-07-31).
+ tools?: ToolDefinition[]
}
// ── Streaming Chunk (unified output) ──────────────────────────
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index a64a3fdd..7a887e6e 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -1,6 +1,7 @@
import { useRef, useState, useCallback } from 'react'
import { v4 as uuid } from 'uuid'
-import { chatNonStreaming } from '../api/agents'
+import { streamProviderTurn } from '../lib/provider-stream'
+import { createHermesDisplayFilter } from '../lib/hermes-stream'
import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, renderWorkspaceSection, setChatArtifactMode, takeChatArtifacts } from '../api/agent-context'
import { isOllamaLocal } from '../api/backend'
import { requestGenerationCancel } from '../api/vram-handoff'
@@ -818,23 +819,47 @@ export function useAgentChat() {
}
dropThinkingBlock()
} else {
- // Connection-failure retry for openai-compat providers — parity with
- // the Ollama branch above. A LOCAL LM Studio model gets unloaded +
- // JIT-reloaded around an image/video VRAM hand-off (detectLmsTextModel
- // juggling, v2.5.3); a request that races that reload window dies as
- // "LM Studio: Request failed". Without a retry that surfaced as a bare
- // "Agent error" on the very next tool turn (ship-gate find 2026-06-11,
- // chat-tools image on LM Studio). Retry transient failures a couple of
- // times; a 4xx is deterministic and still surfaces immediately.
+ // ── Streaming path for openai-compat / Anthropic / LU Cloud ──
+ // Parity with the Ollama branch above: chatStream carries the
+ // tool defs (ChatOptions.tools), tool-call deltas accumulate in
+ // the provider and arrive on the done chunk. Until 2.6.0 this
+ // branch waited on chatWithTools and painted the whole turn at
+ // once (David 2026-07-31).
+ //
+ // Connection-failure retry kept from the non-streaming days: a
+ // LOCAL LM Studio model gets unloaded + JIT-reloaded around an
+ // image/video VRAM hand-off (detectLmsTextModel juggling,
+ // v2.5.3); a request that races that reload window dies as
+ // "LM Studio: Request failed". Retry transient failures a couple
+ // of times; a 4xx is deterministic and still surfaces.
+ let thinkingBlockRemoved = false
+ const dropThinkingBlock = () => {
+ if (!thinkingBlockRemoved) {
+ thinkingBlockRemoved = true
+ removeBlock(convId!, assistantMessage.id, thinkingBlockId)
+ }
+ }
+ const onLiveContent = (c: string) => {
+ dropThinkingBlock()
+ contentRef.current = c
+ scheduleUIUpdate()
+ }
+ const onLiveThinking = (t: string) => {
+ dropThinkingBlock()
+ if (settings.thinkingEnabled === true) {
+ thinkingRef.current = t
+ scheduleUIUpdate()
+ }
+ }
+ const streamOpts = { ...chatOptions, tools }
let connRetries = 0
for (;;) {
try {
- turn = await provider.chatWithTools(modelToUse, agentMessages, tools, chatOptions)
+ turn = await streamProviderTurn(provider, modelToUse, agentMessages, streamOpts, onLiveContent, onLiveThinking)
break
} catch (thinkErr: any) {
if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {
- const retryOptions = { ...chatOptions, thinking: undefined as unknown as boolean }
- turn = await provider.chatWithTools(modelToUse, agentMessages, tools, retryOptions)
+ turn = await streamProviderTurn(provider, modelToUse, agentMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, onLiveContent, () => {})
break
}
const sc = typeof thinkErr?.statusCode === 'number' ? thinkErr.statusCode : 0
@@ -848,7 +873,7 @@ export function useAgentChat() {
throw thinkErr
}
}
- removeBlock(convId!, assistantMessage.id, thinkingBlockId)
+ dropThinkingBlock()
}
toolCalls = turn.toolCalls
@@ -870,12 +895,33 @@ export function useAgentChat() {
if (turn.thinking) turnThinking = turn.thinking
} else {
- // ── Hermes XML prompt-based tool calling (Ollama fallback) ──
- const rawContent = await chatNonStreaming(
+ // ── Hermes XML prompt-based tool calling ──
+ // Streamed like every other transport now (David 2026-07-31): the
+ // display filter keeps <tool_call> XML from ever flashing into the
+ // bubble while prose lands token by token. The parse below still
+ // runs on the FULL raw text, so extraction cannot differ from the
+ // old non-streaming path. This also retires chatNonStreaming here,
+ // which spoke Ollama's /api/chat and quietly mis-routed hermes
+ // turns on every other provider.
+ const display = createHermesDisplayFilter()
+ let shown = ''
+ const hermesTurn = await streamProviderTurn(
+ provider,
modelToUse,
agentMessages.map(m => ({ role: m.role, content: m.content })),
- abort.signal,
+ { ...chatOptions, thinking: undefined as unknown as boolean },
+ (_full, delta) => {
+ shown += display.feed(delta)
+ contentRef.current = shown
+ scheduleUIUpdate()
+ },
)
+ shown += display.flush()
+ if (shown) {
+ contentRef.current = shown
+ scheduleUIUpdate()
+ }
+ const rawContent = hermesTurn.content
if (hasToolCallTags(rawContent)) {
toolCalls = parseHermesToolCalls(rawContent).map(tc => ({
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index ce8565e5..8a95a38f 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -15,7 +15,8 @@ import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { useAgentLoopStore } from '../stores/agentLoopStore'
import { CODEX_CONFIRM_TOOLS, codexConfirmEnabled } from './codexShellGate'
import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
-import { chatNonStreaming } from '../api/agents'
+import { streamProviderTurn, type StreamedProviderTurn } from '../lib/provider-stream'
+import { createHermesDisplayFilter } from '../lib/hermes-stream'
import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel } from '../api/agent-context'
import { resolveWorkspace } from '../api/agents/workspace-resolve'
import { useAgentModeStore } from '../stores/agentModeStore'
@@ -741,6 +742,19 @@ export function useCodex() {
// Compaction is best-effort; fall through with raw history.
}
+ // Live paint for EVERY transport branch below (Ollama, openai-compat
+ // stream, Hermes). Takes the cumulative content of the current model
+ // call. Echo guard: while a turn is streaming we keep updating the
+ // visible message — but if the partial content already matches the
+ // system-prompt echo pattern we stop pushing updates so the "Hello,
+ // I am the Coding Agent…" line never lands in the chat. The
+ // post-stream echoDetected branch then drops the buffer entirely and
+ // forces a silent retry.
+ const liveContent = (c: string) => {
+ if (echoRetriesRemaining > 0 && isSystemPromptEcho(c)) return
+ useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, fullContent ? fullContent + '\n\n' + c : c)
+ }
+
if (strategy === 'native') {
const lastUserMsg = messages.filter(m => m.role === 'user').pop()?.content || ''
// CODEX_CATEGORIES filter: Codex is a CODING agent — screenshot,
@@ -811,17 +825,8 @@ export function useCodex() {
// Shows live content/thinking tokens so the user isn't staring
// at an empty bubble for 2+ minutes while the model generates.
//
- // Echo guard: while a turn is streaming we keep updating the
- // visible message — but if the partial content already
- // matches the system-prompt echo pattern we stop pushing
- // updates so the "Hello, I am the Coding Agent…" line never
- // lands in the chat. The post-stream echoDetected branch then drops
- // the buffer entirely and forces a silent retry.
+ // Echo guard lives in the shared liveContent above.
let turn: { content: string; toolCalls: ToolCall[]; thinking: string; promptEvalCount?: number; evalCount?: number }
- const liveContent = (c: string) => {
- if (echoRetriesRemaining > 0 && isSystemPromptEcho(c)) return
- useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, fullContent ? fullContent + '\n\n' + c : c)
- }
// Token counter (David 2026-06-12): reflect the REAL prompt size —
// system prompt + tool defs + repo map + history — immediately, not a
// char/4 guess of just the visible messages. Provisional estimate that
@@ -944,21 +949,41 @@ export function useCodex() {
// Only drop it when nothing but punctuation/whitespace remains.
if (extractedFromContent && !/[A-Za-z0-9]/.test(turnContent)) turnContent = ''
} else {
- // ── Non-streaming fallback for OpenAI/Anthropic providers ──
- let turn: { content: string; toolCalls: ToolCall[] }
+ // ── Streaming path for OpenAI-compat / Anthropic / LU Cloud ──
+ // chatStream carries the tool defs (ChatOptions.tools) and the
+ // provider accumulates tool-call deltas into the done chunk.
+ // Until 2.6.0 this branch waited on chatWithTools and painted the
+ // whole turn in one tick — 22k chars after 40 s of dead air on
+ // the built-in engine (David 2026-07-31).
+ let turn: StreamedProviderTurn
+ const streamOpts = { ...chatOptions, tools }
+ const liveThinking = (t: string) => {
+ if (keepThinking) {
+ const combined = thinkingContent ? thinkingContent + '\n\n' + t : t
+ useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, combined)
+ }
+ }
try {
- turn = await provider.chatWithTools(modelToUse, messages, tools, chatOptions)
+ turn = await streamProviderTurn(provider, modelToUse, messages, streamOpts, liveContent, liveThinking)
} catch (thinkErr: any) {
if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {
- turn = await provider.chatWithTools(modelToUse, messages, tools, { ...chatOptions, thinking: undefined as unknown as boolean })
+ turn = await streamProviderTurn(provider, modelToUse, messages, { ...streamOpts, thinking: undefined as unknown as boolean }, liveContent, () => {})
} else {
throw thinkErr
}
}
toolCalls = turn.toolCalls
turnContent = turn.content || ''
- if (keepThinking && (turn as any).thinking) {
- thinkingContent += (thinkingContent ? '\n\n' : '') + (turn as any).thinking
+ if (turn.promptEvalCount || turn.evalCount) {
+ useChatStore.getState().updateMessageUsage(convId!, assistantMsg.id, {
+ promptTokens: turn.promptEvalCount || 0,
+ completionTokens: turn.evalCount || 0,
+ totalTokens: (turn.promptEvalCount || 0) + (turn.evalCount || 0),
+ estimated: false,
+ })
+ }
+ if (keepThinking && turn.thinking) {
+ thinkingContent += (thinkingContent ? '\n\n' : '') + turn.thinking
useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
}
}
@@ -977,11 +1002,28 @@ export function useCodex() {
)
const hermesSystem = buildHermesToolPrompt(hermesTools) + `\n\n${systemPrompt}`
messages[0] = { role: 'system', content: hermesSystem }
- const raw = await chatNonStreaming(
+ // Streamed prompt-transport turn (David 2026-07-31): prose renders
+ // token by token while the display filter keeps <tool_call> XML
+ // from ever flashing into the bubble. The parse below still runs
+ // on the FULL raw text, so extraction cannot differ from the old
+ // non-streaming path. This also retires chatNonStreaming here,
+ // which spoke Ollama's /api/chat and quietly mis-routed hermes
+ // turns on every other provider.
+ const display = createHermesDisplayFilter()
+ let shown = ''
+ const hermesTurn = await streamProviderTurn(
+ provider,
modelToUse,
messages.map(m => ({ role: m.role, content: m.content })),
- abort.signal,
+ { ...chatOptions, thinking: undefined as unknown as boolean, contextWindow: numCtx },
+ (_full, delta) => {
+ shown += display.feed(delta)
+ liveContent(shown)
+ },
)
+ shown += display.flush()
+ if (shown) liveContent(shown)
+ const raw = hermesTurn.content
if (hasToolCallTags(raw)) {
toolCalls = parseHermesToolCalls(raw).map(tc => ({
function: { name: tc.name, arguments: tc.arguments },
diff --git a/src/lib/__tests__/hermes-stream.test.ts b/src/lib/__tests__/hermes-stream.test.ts
new file mode 100644
index 00000000..71274423
--- /dev/null
+++ b/src/lib/__tests__/hermes-stream.test.ts
@@ -0,0 +1,77 @@
+import { describe, it, expect } from 'vitest'
+import { createHermesDisplayFilter } from '../hermes-stream'
+
+function run(deltas: string[]): { shown: string; f: ReturnType<typeof createHermesDisplayFilter> } {
+ const f = createHermesDisplayFilter()
+ let shown = ''
+ for (const d of deltas) shown += f.feed(d)
+ return { shown, f }
+}
+
+describe('hermes display filter', () => {
+ it('passes plain prose through unchanged', () => {
+ const { shown, f } = run(['Hello ', 'world', '!'])
+ expect(shown + f.flush()).toBe('Hello world!')
+ })
+
+ it('swallows a complete tool call and keeps surrounding text', () => {
+ const { shown, f } = run([
+ 'Before. ',
+ '<tool_call>{"name":"file_write","arguments":{"path":"a"}}</tool_call>',
+ ' After.',
+ ])
+ expect(shown + f.flush()).toBe('Before. After.')
+ })
+
+ it('swallows a call whose tags are split across many deltas', () => {
+ const { shown, f } = run([
+ 'Text <tool_',
+ 'call>{"name":"x"',
+ ',"arguments":{}}</tool_',
+ 'call> more',
+ ])
+ expect(shown + f.flush()).toBe('Text more')
+ })
+
+ it('does not flash any part of the call body mid-stream', () => {
+ const f = createHermesDisplayFilter()
+ let shown = ''
+ shown += f.feed('ok <tool_call>{"name":"secret_tool"')
+ expect(shown).toBe('ok ')
+ expect(f.inToolCall()).toBe(true)
+ shown += f.feed(',"arguments":{}}</tool_call> done')
+ expect(shown + f.flush()).toBe('ok done')
+ })
+
+ it('releases a tag-lookalike that never completes', () => {
+ const { shown, f } = run(['a < b and <tool', '_x is not a tag'])
+ expect(shown + f.flush()).toBe('a < b and <tool_x is not a tag')
+ })
+
+ it('flushes a trailing opening-tag prefix as prose at stream end', () => {
+ const { shown, f } = run(['ends with <tool_ca'])
+ expect(shown).toBe('ends with ')
+ expect(f.flush()).toBe('<tool_ca')
+ })
+
+ it('keeps an unclosed call swallowed at stream end', () => {
+ const { shown, f } = run(['x <tool_call>{"name":"y"'])
+ expect(shown).toBe('x ')
+ expect(f.flush()).toBe('')
+ })
+
+ it('handles several calls in one turn', () => {
+ const { shown, f } = run([
+ 'one <tool_call>{"a":1}</tool_call> two <tool_call>{"b":2}</tool_call> three',
+ ])
+ expect(shown + f.flush()).toBe('one two three')
+ })
+
+ it('handles a close tag split exactly at the angle bracket', () => {
+ const { shown, f } = run([
+ '<tool_call>{"n":"x"}<',
+ '/tool_call>after',
+ ])
+ expect(shown + f.flush()).toBe('after')
+ })
+})
diff --git a/src/lib/__tests__/provider-stream.test.ts b/src/lib/__tests__/provider-stream.test.ts
new file mode 100644
index 00000000..0bb65d27
--- /dev/null
+++ b/src/lib/__tests__/provider-stream.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect } from 'vitest'
+import { streamProviderTurn } from '../provider-stream'
+import type { ChatStreamChunk, ProviderClient } from '../../api/providers/types'
+
+function fakeProvider(chunks: ChatStreamChunk[]): ProviderClient {
+ return {
+ id: 'openai',
+ async *chatStream() {
+ for (const c of chunks) yield c
+ },
+ chatWithTools: async () => ({ content: '', toolCalls: [] }),
+ listModels: async () => [],
+ checkConnection: async () => true,
+ getContextLength: async () => 8192,
+ } as unknown as ProviderClient
+}
+
+describe('streamProviderTurn', () => {
+ it('accumulates content deltas and reports cumulative text to the callback', async () => {
+ const provider = fakeProvider([
+ { content: 'Hel', done: false },
+ { content: 'lo', done: false },
+ { content: '', done: true, finishReason: 'stop' },
+ ])
+ const seen: string[] = []
+ const turn = await streamProviderTurn(provider, 'm', [], {}, (full) => seen.push(full))
+ expect(seen).toEqual(['Hel', 'Hello'])
+ expect(turn.content).toBe('Hello')
+ expect(turn.finishReason).toBe('stop')
+ expect(turn.toolCalls).toEqual([])
+ })
+
+ it('hands the raw delta to the callback as second argument', async () => {
+ const provider = fakeProvider([
+ { content: 'a', done: false },
+ { content: 'bc', done: false },
+ { content: '', done: true },
+ ])
+ const deltas: string[] = []
+ await streamProviderTurn(provider, 'm', [], {}, (_full, delta) => deltas.push(delta))
+ expect(deltas).toEqual(['a', 'bc'])
+ })
+
+ it('collects tool calls and usage from the done chunk', async () => {
+ const calls = [{ id: '1', function: { name: 'file_read', arguments: { path: 'a' } } }]
+ const provider = fakeProvider([
+ { content: 'ok', done: false },
+ { content: '', done: true, toolCalls: calls, promptEvalCount: 120, evalCount: 34, finishReason: 'tool_calls' },
+ ])
+ const turn = await streamProviderTurn(provider, 'm', [], {})
+ expect(turn.toolCalls).toEqual(calls)
+ expect(turn.promptEvalCount).toBe(120)
+ expect(turn.evalCount).toBe(34)
+ expect(turn.finishReason).toBe('tool_calls')
+ })
+
+ it('accumulates thinking separately from content', async () => {
+ const provider = fakeProvider([
+ { content: '', thinking: 'hm', done: false },
+ { content: '', thinking: 'm…', done: false },
+ { content: 'answer', done: false },
+ { content: '', done: true },
+ ])
+ const thinks: string[] = []
+ const turn = await streamProviderTurn(provider, 'm', [], {}, undefined, (full) => thinks.push(full))
+ expect(thinks).toEqual(['hm', 'hmm…'])
+ expect(turn.thinking).toBe('hmm…')
+ expect(turn.content).toBe('answer')
+ })
+
+ it('propagates a mid-stream error to the caller', async () => {
+ const provider = {
+ id: 'openai',
+ // eslint-disable-next-line require-yield
+ async *chatStream(): AsyncGenerator<ChatStreamChunk> {
+ throw Object.assign(new Error('boom'), { statusCode: 500 })
+ },
+ } as unknown as ProviderClient
+ await expect(streamProviderTurn(provider, 'm', [], {})).rejects.toThrow('boom')
+ })
+})
diff --git a/src/lib/hermes-stream.ts b/src/lib/hermes-stream.ts
new file mode 100644
index 00000000..6b0e5611
--- /dev/null
+++ b/src/lib/hermes-stream.ts
@@ -0,0 +1,91 @@
+/**
+ * Display filter for streaming a Hermes-XML tool turn.
+ *
+ * The prompt-transport models answer with prose that may contain
+ * `<tool_call>{...}</tool_call>` blocks. When such a turn is streamed, the
+ * raw XML must never flash into the chat bubble — but everything around it
+ * should appear token by token. This filter decides, per delta, which part
+ * of the text is SAFE to show: it withholds the longest tail that could
+ * still turn into an opening tag, and swallows everything between a
+ * confirmed opening tag and its close.
+ *
+ * It is UI-only. The caller still accumulates the FULL raw text and runs
+ * parseHermesToolCalls / stripToolCallTags on it at the end, exactly like
+ * the non-streaming path — so call extraction cannot behave differently
+ * just because the turn was streamed.
+ */
+
+const OPEN_TAG = '<tool_call>'
+const CLOSE_TAG = '</tool_call>'
+
+export interface HermesDisplayFilter {
+ /** Feed one stream delta; returns the text that is safe to display now. */
+ feed(delta: string): string
+ /** Stream is over: returns whatever held-back text turned out to be prose. */
+ flush(): string
+ /** True while inside an unclosed <tool_call> block (UI can show a hint). */
+ inToolCall(): boolean
+}
+
+/** Longest suffix of `text` that is a prefix of `tag` (possible cut tag). */
+function cutTagSuffix(text: string, tag: string): number {
+ const max = Math.min(text.length, tag.length - 1)
+ for (let len = max; len > 0; len--) {
+ if (text.endsWith(tag.slice(0, len))) return len
+ }
+ return 0
+}
+
+export function createHermesDisplayFilter(): HermesDisplayFilter {
+ let pending = ''
+ let inCall = false
+
+ return {
+ feed(delta: string): string {
+ pending += delta
+ let out = ''
+ while (true) {
+ if (inCall) {
+ const close = pending.indexOf(CLOSE_TAG)
+ if (close === -1) {
+ // Keep only what could still be part of the close tag; the call
+ // body itself is never shown, so it can be dropped from pending.
+ const keep = cutTagSuffix(pending, CLOSE_TAG)
+ pending = keep > 0 ? pending.slice(pending.length - keep) : ''
+ return out
+ }
+ pending = pending.slice(close + CLOSE_TAG.length)
+ inCall = false
+ continue
+ }
+ const open = pending.indexOf(OPEN_TAG)
+ if (open !== -1) {
+ out += pending.slice(0, open)
+ pending = pending.slice(open + OPEN_TAG.length)
+ inCall = true
+ continue
+ }
+ // No full opening tag: emit everything except a tail that might
+ // still become one ("<tool_ca" at the end of this delta).
+ const hold = cutTagSuffix(pending, OPEN_TAG)
+ out += pending.slice(0, pending.length - hold)
+ pending = pending.slice(pending.length - hold)
+ return out
+ }
+ },
+
+ flush(): string {
+ // An unfinished opening-tag prefix was ordinary prose after all. An
+ // unclosed call stays swallowed — the raw-text parse at turn end is
+ // what decides how a malformed call is handled, not the display.
+ const rest = inCall ? '' : pending
+ pending = ''
+ inCall = false
+ return rest
+ },
+
+ inToolCall(): boolean {
+ return inCall
+ },
+ }
+}
diff --git a/src/lib/provider-stream.ts b/src/lib/provider-stream.ts
new file mode 100644
index 00000000..a23b2ece
--- /dev/null
+++ b/src/lib/provider-stream.ts
@@ -0,0 +1,63 @@
+/**
+ * Consume one provider.chatStream turn into the same result shape that
+ * chatWithTools returns, while feeding live callbacks along the way.
+ *
+ * This is the shared piece of the 2.6.0 streaming normalisation (David
+ * 2026-07-31): Code and Agent mode used to stream only on the Ollama
+ * transport and sat silent on every other provider until the whole call
+ * returned. Every transport now goes through chatStream — tool defs travel
+ * in ChatOptions.tools, tool-call deltas accumulate inside the provider and
+ * arrive on the done chunk.
+ *
+ * Callbacks receive the CUMULATIVE text first (what the existing UI paths
+ * paint directly) and the raw delta second (what the Hermes display filter
+ * feeds on).
+ */
+
+import type {
+ ChatMessage,
+ ChatOptions,
+ ProviderClient,
+ ToolCall,
+} from '../api/providers/types'
+
+export interface StreamedProviderTurn {
+ content: string
+ toolCalls: ToolCall[]
+ thinking: string
+ promptEvalCount?: number
+ evalCount?: number
+ finishReason?: string
+}
+
+export async function streamProviderTurn(
+ provider: ProviderClient,
+ model: string,
+ messages: ChatMessage[],
+ options: ChatOptions,
+ onContent?: (full: string, delta: string) => void,
+ onThinking?: (full: string, delta: string) => void,
+): Promise<StreamedProviderTurn> {
+ let content = ''
+ let thinking = ''
+ const turn: StreamedProviderTurn = { content: '', toolCalls: [], thinking: '' }
+ for await (const chunk of provider.chatStream(model, messages, options)) {
+ if (chunk.content) {
+ content += chunk.content
+ onContent?.(content, chunk.content)
+ }
+ if (chunk.thinking) {
+ thinking += chunk.thinking
+ onThinking?.(thinking, chunk.thinking)
+ }
+ if (chunk.done) {
+ if (chunk.toolCalls?.length) turn.toolCalls = chunk.toolCalls
+ turn.promptEvalCount = chunk.promptEvalCount
+ turn.evalCount = chunk.evalCount
+ turn.finishReason = chunk.finishReason
+ }
+ }
+ turn.content = content
+ turn.thinking = thinking
+ return turn
+}