feat(chat): surface streamed model thinking in the dashboard (#1907) #1910

Merged
sam merged 3 commits from feat/1907-chat-thinking into main 2026-11-12 13:25:51 +00:00
9 changed files with 489 additions and 125 deletions

No files matched your search

+1 -120
View File
@@ -2,13 +2,9 @@ package archiegateway
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"path/filepath"
"strings"
"time"
"unicode/utf8"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
@@ -220,7 +216,7 @@ func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, op
if err != nil {
return "", chat.Usage{}, fmt.Errorf("llm chat stream: %w", err)
}
text := drainChatStream(stream.FullStream, turn, icons)
text := gateway.DrainStreamParts(stream.FullStream, turn, icons)
var used chat.Usage
if stream.Usage != nil {
used, _ = stream.Usage()
@@ -231,121 +227,6 @@ func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, op
return text, used, nil
}
// pendingToolCall is a tool invocation awaiting its result.
type pendingToolCall struct {
name string
parameters string
started time.Time
offset int
}
// took is the call's running time so far, zero for a result with no
// recorded invocation.
func (c pendingToolCall) took() int64 {
if c.started.IsZero() {
return 0
}
return time.Since(c.started).Milliseconds()
}
// drainChatStream consumes a model stream to close, reporting assistant text
// and each completed tool call to turn, and returns the assembled reply.
//
// FullStream is authoritative and its writes are synchronous, so it must be
// drained to close even when turn is nil -- an unread stream stalls the
// generating goroutine.
//
// A tool is reported on its result, never on its call: the call part carries
// no outcome yet, so reporting both would show every tool twice, once with
// nothing to say.
func drainChatStream(parts <-chan core.StreamPart, turn gateway.TurnStream, icons map[string]string) string {
var sb strings.Builder
pending := make(map[string]pendingToolCall)
runes := 0
for part := range parts {
switch part.Type {
case core.StreamPartTextDelta:
if part.TextDelta == "" {
continue
}
sb.WriteString(part.TextDelta)
runes += utf8.RuneCountInString(part.TextDelta)
if turn != nil {
turn.Delta(part.TextDelta)
}
case core.StreamPartToolCall:
if part.ToolCall == nil || part.ToolCall.ToolCallID == "" {
continue
}
pending[part.ToolCall.ToolCallID] = pendingToolCall{
name: part.ToolCall.ToolName,
parameters: gateway.SummarizeToolParameters(part.ToolCall.Input),
started: time.Now(),
offset: runes,
}
case core.StreamPartToolResult:
if part.ToolResult == nil || turn == nil {
continue
}
call := pending[part.ToolResult.ToolCallID]
delete(pending, part.ToolResult.ToolCallID)
name := part.ToolResult.ToolName
if name == "" {
name = call.name
}
turn.ToolCall(gateway.ToolCallEvent{
ID: part.ToolResult.ToolCallID,
Name: name,
Emoji: icons[name],
Parameters: call.parameters,
Output: part.ToolResult.Output,
Err: part.ToolResult.Error,
DurationMS: call.took(),
TextOffset: call.offset,
})
for _, ref := range multimodalMediaRefs(part.ToolResult.Output) {
// Path and URL are alternatives, not a pair: the channel
// uploads one and fetches the other. A ref carrying
// neither names nothing deliverable, so it is dropped
// rather than sent as an empty attachment.
if ref.URL == "" && ref.Path == "" {
continue
}
turn.Media(gateway.MediaEvent{
ToolName: name,
Attachment: gateway.MediaAttachment{
Type: ref.Type,
URL: ref.URL,
Path: ref.Path,
FileName: ref.FileName,
},
})
}
}
}
return sb.String()
}
// multimodalMediaRefs extracts the URLs a tool result carries when its
// output is a tools.MultimodalResult, so drainChatStream can report each as
// a gateway.MediaEvent alongside the ordinary ToolCall event.
//
// output is decoded with json.Unmarshal directly rather than checked
// against a schema first: most tool output is plain text or unrelated
// JSON, and unmarshalling into MultimodalResult simply leaves IsMultimodal
// false for anything that doesn't match, which is exactly "not multimodal"
// -- no separate detection step earns its keep here.
func multimodalMediaRefs(output string) []tools.MediaRef {
if output == "" {
return nil
}
var result tools.MultimodalResult
if err := json.Unmarshal([]byte(output), &result); err != nil || !result.IsMultimodal {
return nil
}
return result.URLs
}
// chatTitleGenerator proposes session titles through the chat model. It
// is a pure proposal: it persists nothing, so a failed or slow title
// call can never corrupt conversation history or fail the turn. The
+6
View File
@@ -331,6 +331,12 @@ func (s localChatStream) Delta(text string) {
s.send(ChatEvent{Kind: "delta", Text: text})
}
// Reasoning forwards one fragment of the model's thinking as its own event
// kind; the dashboard renders it as the live turn's thinking trace.
func (s localChatStream) Reasoning(text string) {
s.send(ChatEvent{Kind: "reasoning", Text: text})
}
func (s localChatStream) ToolCall(event ToolCallEvent) {
s.send(ChatEvent{Kind: "tool", Tool: event})
}
+124
View File
@@ -0,0 +1,124 @@
package gateway
import (
"reflect"
"testing"
"github.com/samcharles93/ai-sdk/core"
)
// A fake ai-sdk FullStream drives the drain: every part must reach the turn
// stream in order, and a reasoning delta must surface as a Kind "reasoning"
// ChatEvent carrying its text. Text deltas and tool results keep working.
func TestDrainStreamPartsForwardsStreamParts(t *testing.T) {
cases := []struct {
name string
parts []core.StreamPart
want []ChatEvent
wantText string
}{
{
name: "reasoning deltas become reasoning events",
parts: []core.StreamPart{
{Type: core.StreamPartReasoningDelta, ReasoningDelta: "considering "},
{Type: core.StreamPartReasoningDelta, ReasoningDelta: "the request"},
},
want: []ChatEvent{
{Kind: "reasoning", Text: "considering ", SessionID: "s1"},
{Kind: "reasoning", Text: "the request", SessionID: "s1"},
},
},
{
name: "text deltas still stream and assemble the reply",
parts: []core.StreamPart{
{Type: core.StreamPartTextDelta, TextDelta: "Hello, "},
{Type: core.StreamPartTextDelta, TextDelta: "world"},
},
want: []ChatEvent{
{Kind: "delta", Text: "Hello, ", SessionID: "s1"},
{Kind: "delta", Text: "world", SessionID: "s1"},
},
wantText: "Hello, world",
},
{
name: "reasoning ahead of the answer text",
parts: []core.StreamPart{
{Type: core.StreamPartReasoningDelta, ReasoningDelta: "hmm"},
{Type: core.StreamPartTextDelta, TextDelta: "answer"},
},
want: []ChatEvent{
{Kind: "reasoning", Text: "hmm", SessionID: "s1"},
{Kind: "delta", Text: "answer", SessionID: "s1"},
},
wantText: "answer",
},
{
name: "an empty reasoning delta is dropped",
parts: []core.StreamPart{
{Type: core.StreamPartReasoningDelta, ReasoningDelta: ""},
{Type: core.StreamPartTextDelta, TextDelta: "hi"},
},
want: []ChatEvent{{Kind: "delta", Text: "hi", SessionID: "s1"}},
wantText: "hi",
},
{
name: "a completed tool call still reports its tool event",
parts: []core.StreamPart{
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "t1", ToolName: "search", Input: `{"q":"archie"}`}},
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolCallID: "t1", ToolName: "search", Output: "42"}},
},
want: []ChatEvent{{
Kind: "tool",
SessionID: "s1",
Tool: ToolCallEvent{
ID: "t1",
Name: "search",
Emoji: "🔍",
Parameters: SummarizeToolParameters(`{"q":"archie"}`),
Output: "42",
},
}},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
parts := make(chan core.StreamPart, len(tc.parts))
for _, part := range tc.parts {
parts <- part
}
close(parts)
events := make(chan ChatEvent, len(tc.parts)+1)
stream := localChatStream{done: make(chan struct{}), events: events, sessionID: "s1"}
text := DrainStreamParts(parts, stream, map[string]string{"search": "🔍"})
var got []ChatEvent
for {
select {
case event := <-events:
got = append(got, event)
default:
if !reflect.DeepEqual(got, tc.want) {
t.Fatalf("events = %+v, want %+v", got, tc.want)
}
if text != tc.wantText {
t.Fatalf("reply text = %q, want %q", text, tc.wantText)
}
return
}
}
})
}
}
// A stream nobody renders still has to be drained to close: an unread
// FullStream stalls the generating goroutine, reasoning included.
func TestDrainStreamPartsWithoutStreamStillDrains(t *testing.T) {
parts := make(chan core.StreamPart, 3)
parts <- core.StreamPart{Type: core.StreamPartReasoningDelta, ReasoningDelta: "thinking"}
parts <- core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "reply"}
close(parts)
if text := DrainStreamParts(parts, nil, nil); text != "reply" {
t.Fatalf("reply text = %q, want %q", text, "reply")
}
}
+161 -1
View File
@@ -1,12 +1,30 @@
package gateway
import "github.com/samcharles93/archie-core/internal/domain/messaging"
import (
"encoding/json"
"strings"
"time"
"unicode/utf8"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/tools"
)
// SummarizeToolParameters returns a bounded JSON shape of tool input.
func SummarizeToolParameters(input string) string {
return messaging.SummarizeToolParameters(input)
}
// ReasoningStream is the optional TurnStream extension for the model's
// thinking. It is separate from TurnStream so streams that cannot render
// reasoning keep satisfying TurnStream unchanged; producers type-assert.
type ReasoningStream interface {
// Reasoning appends the next fragment of the model's reasoning.
Reasoning(text string)
}
type toolCallRecorder struct {
next TurnStream
events []ToolCallEvent
@@ -18,6 +36,12 @@ func (r *toolCallRecorder) Delta(text string) {
}
}
func (r *toolCallRecorder) Reasoning(text string) {
if rs, ok := r.next.(ReasoningStream); ok {
rs.Reasoning(text)
}
}
func (r *toolCallRecorder) ToolCall(event ToolCallEvent) {
r.events = append(r.events, event)
if r.next != nil {
@@ -30,3 +54,139 @@ func (r *toolCallRecorder) Media(event MediaEvent) {
r.next.Media(event)
}
}
// pendingToolCall is a tool invocation awaiting its result.
type pendingToolCall struct {
name string
parameters string
started time.Time
offset int
}
// took is the call's running time so far, zero for a result with no
// recorded invocation.
func (c pendingToolCall) took() int64 {
if c.started.IsZero() {
return 0
}
return time.Since(c.started).Milliseconds()
}
// DrainStreamParts consumes an ai-sdk FullStream to close, reporting the
// model's reasoning, assistant text and each completed tool call to turn,
// and returns the assembled reply.
//
// The parts channel is authoritative and its writes are synchronous, so it
// must be drained to close even when turn is nil -- an unread stream stalls
// the generating goroutine.
//
// A tool is reported on its result, never on its call: the call part carries
// no outcome yet, so reporting both would show every tool twice, once with
// nothing to say.
func DrainStreamParts(parts <-chan core.StreamPart, turn TurnStream, icons map[string]string) string {
var sb strings.Builder
pending := make(map[string]pendingToolCall)
runes := 0
for part := range parts {
switch part.Type {
case core.StreamPartReasoningDelta:
reportReasoning(turn, part.ReasoningDelta)
case core.StreamPartTextDelta:
if part.TextDelta == "" {
continue
}
sb.WriteString(part.TextDelta)
runes += utf8.RuneCountInString(part.TextDelta)
if turn != nil {
turn.Delta(part.TextDelta)
}
case core.StreamPartToolCall:
if part.ToolCall == nil || part.ToolCall.ToolCallID == "" {
continue
}
pending[part.ToolCall.ToolCallID] = pendingToolCall{
name: part.ToolCall.ToolName,
parameters: SummarizeToolParameters(part.ToolCall.Input),
started: time.Now(),
offset: runes,
}
case core.StreamPartToolResult:
reportToolResult(turn, part.ToolResult, pending, icons)
}
}
return sb.String()
}
// reportReasoning forwards one reasoning fragment to a stream that can
// render thinking. Reasoning is not part of the reply text, so it travels on
// its own stream method; a stream without that method simply gets none.
func reportReasoning(turn TurnStream, delta string) {
if delta == "" {
return
}
if rs, ok := turn.(ReasoningStream); ok {
rs.Reasoning(delta)
}
}
// reportToolResult reports one finished tool invocation, plus any media
// attachment its output carries, to the turn.
func reportToolResult(turn TurnStream, result *core.ToolResult, pending map[string]pendingToolCall, icons map[string]string) {
if result == nil || turn == nil {
return
}
call := pending[result.ToolCallID]
delete(pending, result.ToolCallID)
name := result.ToolName
if name == "" {
name = call.name
}
turn.ToolCall(ToolCallEvent{
ID: result.ToolCallID,
Name: name,
Emoji: icons[name],
Parameters: call.parameters,
Output: result.Output,
Err: result.Error,
DurationMS: call.took(),
TextOffset: call.offset,
})
for _, ref := range multimodalMediaRefs(result.Output) {
// Path and URL are alternatives, not a pair: the channel uploads one
// and fetches the other. A ref carrying neither names nothing
// deliverable, so it is dropped rather than sent as an empty
// attachment.
if ref.URL == "" && ref.Path == "" {
continue
}
turn.Media(MediaEvent{
ToolName: name,
Attachment: MediaAttachment{
Type: ref.Type,
URL: ref.URL,
Path: ref.Path,
FileName: ref.FileName,
},
})
}
}
// multimodalMediaRefs extracts the URLs a tool result carries when its
// output is a tools.MultimodalResult, so DrainStreamParts can report each as
// a MediaEvent alongside the ordinary ToolCall event.
//
// output is decoded with json.Unmarshal directly rather than checked
// against a schema first: most tool output is plain text or unrelated
// JSON, and unmarshalling into MultimodalResult simply leaves IsMultimodal
// false for anything that doesn't match, which is exactly "not multimodal"
// -- no separate detection step earns its keep here.
func multimodalMediaRefs(output string) []tools.MediaRef {
if output == "" {
return nil
}
var result tools.MultimodalResult
if err := json.Unmarshal([]byte(output), &result); err != nil || !result.IsMultimodal {
return nil
}
return result.URLs
}
+11 -1
View File
@@ -7,6 +7,7 @@ import { CodeBlockCopyButton } from "@/components/ui/code-block";
import { Message, MessageContent, MessageFooter } from "@/components/ui/message";
import ChatAttachment from "./ChatAttachment.vue";
import ChatMarkdown from "./ChatMarkdown.vue";
import ChatThinking from "./ChatThinking.vue";
import ChatToolCall from "./ChatToolCall.vue";
import ChatToolGroup from "./ChatToolGroup.vue";
import type { ChatMedia, ChatToolCall as ToolCall } from "./state";
@@ -27,8 +28,12 @@ const props = withDefaults(
assistant?: boolean;
/** The turn is still arriving: a tool call with no outcome is running. */
streaming?: boolean;
/** The live turn's thinking so far, rendered as a collapsible trace. */
reasoning?: string;
/** The live turn is still arriving and has not reasoned yet. */
thinkingPending?: boolean;
}>(),
{ tools: () => [], media: () => [], assistant: false, streaming: false },
{ tools: () => [], media: () => [], assistant: false, streaming: false, reasoning: "", thinkingPending: false },
);
// The reply in the order it happened: text up to each call's offset, then the
@@ -73,6 +78,11 @@ const segments = computed(() => {
/>
</div>
<template v-if="assistant">
<ChatThinking
v-if="reasoning || thinkingPending"
:text="reasoning"
:pending="thinkingPending"
/>
<template v-for="(segment, i) in segments" :key="i">
<ChatMarkdown v-if="'text' in segment" :text="segment.text" />
<Trace v-else class="my-2">
+47
View File
@@ -0,0 +1,47 @@
<script setup lang="ts">
import { BrainIcon } from "@lucide/vue";
import { Spinner } from "@/components/ui/spinner";
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace";
/**
* The live turn's thinking: the model's reasoning as it streams, in the same
* collapsible trace a tool call uses. While the turn has not produced any
* reasoning yet, the icon spins and the title shimmers; once text arrives it
* streams into the open trace. A turn that never reasons renders nothing,
* which the caller decides by not mounting this at all.
*/
withDefaults(
defineProps<{
text?: string;
/** The turn is still arriving and has not reasoned yet. */
pending?: boolean;
}>(),
{ text: "", pending: false },
);
</script>
<template>
<Trace class="my-2">
<TraceCollapsible default-open>
<TraceCollapsibleTrigger>
<TraceLine :status="pending && !text ? 'running' : undefined">
<TraceIcon>
<Spinner v-if="pending && !text" />
<BrainIcon v-else />
</TraceIcon>
<TraceTitle>Thinking</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent v-if="text" class="whitespace-pre-wrap [overflow-wrap:anywhere]">{{ text }}</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
</template>
+21 -2
View File
@@ -61,9 +61,21 @@ const bubbles = computed(() => messages.value.map(parts));
// the scroller sees one row grow and settle, not one leave and another arrive.
const rows = computed(() => {
const turn = streamingTurn.value;
if (!turn) return bubbles.value.map((bubble) => ({ ...bubble, live: false }));
if (!turn) {
return bubbles.value.map((bubble) => ({
...bubble,
live: false,
reasoning: "",
thinkingPending: false,
}));
}
return [
...bubbles.value.map((bubble) => ({ ...bubble, live: false })),
...bubbles.value.map((bubble) => ({
...bubble,
live: false,
reasoning: "",
thinkingPending: false,
})),
{
id: `m${bubbles.value.length}`,
text: turn.text || "…",
@@ -73,6 +85,11 @@ const rows = computed(() => {
update: undefined,
choose: undefined,
live: true,
reasoning: turn.reasoning ?? "",
// Nothing said and nothing reasoned yet: the turn may still be thinking,
// so the row shows the pending thinking trace. Once the answer's text
// arrives without any reasoning, the trace is not rendered at all.
thinkingPending: !turn.text && !(turn.reasoning ?? ""),
},
];
});
@@ -115,6 +132,8 @@ const rows = computed(() => {
:media="row.media"
:assistant="row.assistant"
:streaming="row.live"
:reasoning="row.reasoning"
:thinking-pending="row.thinkingPending"
>
<template v-if="row.live && streamingTurn">
<Button
+15 -1
View File
@@ -124,6 +124,8 @@ export interface StreamingTurn {
isError: boolean;
turn?: ChatTurn;
isRetry: boolean;
/** The model's thinking so far, streamed on `reasoning` frames. */
reasoning?: string;
/** A question the turn waits on until the operator answers it. */
ask?: ChatAsk;
}
@@ -731,10 +733,11 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
}
let activeTools: ChatToolCall[] = [];
streamingTurn.value = { text: "", tools: [], isError: false, turn, isRetry };
streamingTurn.value = { text: "", tools: [], isError: false, turn, isRetry, reasoning: "" };
askError.value = "";
let streamedText = "";
let streamedReasoning = "";
let finished = false;
let timedOut = false;
let detached = false;
@@ -806,6 +809,15 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
? { ...streamingTurn.value, text: streamedText }
: null;
}
// The model's thinking streams ahead of the answer on its own frame
// kind; it accumulates like the text, but renders as the live turn's
// thinking trace rather than as reply text.
if (event.type === "reasoning") {
streamedReasoning += event.text;
streamingTurn.value = streamingTurn.value
? { ...streamingTurn.value, reasoning: streamedReasoning }
: null;
}
// A navigate result is appended to the same list as the tool calls: it
// is one more thing the turn did, and it renders as a chip rather than
// a tool line.
@@ -873,6 +885,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
isError: false,
turn,
isRetry,
reasoning: streamedReasoning,
};
statusText.value = "Stopped";
} else {
@@ -886,6 +899,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
isError: true,
turn: turn ? retryChatTurn(turn) : undefined,
isRetry,
reasoning: streamedReasoning,
};
statusText.value = "Error. Retry available.";
}
+103
View File
@@ -0,0 +1,103 @@
import assert from "node:assert/strict";
import test from "node:test";
import { register } from "node:module";
import { pathToFileURL } from "node:url";
import { resolve as resolvePath } from "node:path";
// state.ts reads the dashboard through "@/lib/api" and "@/router", which node
// cannot resolve on its own (and which pull in the whole SPA). A resolve hook
// maps the alias into src/ for the pure modules and stubs the two browser-only
// ones, so the real frame handling in state.ts runs under node.
const srcRoot = resolvePath(import.meta.dirname, "../src");
const apiStub =
"data:text/javascript," +
encodeURIComponent(
"export const api = new Proxy({}, { get: (_, p) => globalThis.__archieChatTestApi[p] });",
);
const routerStub =
"data:text/javascript," +
encodeURIComponent(
"export const router = { currentRoute: { value: { fullPath: '/', name: 'home', meta: {}, params: {} } } };",
);
register(
"data:text/javascript," +
encodeURIComponent(`
const SRC = ${JSON.stringify(pathToFileURL(srcRoot + "/").href)};
export async function resolve(specifier, context, next) {
if (specifier === "@/lib/api") return { url: ${JSON.stringify(apiStub)}, shortCircuit: true };
if (specifier === "@/router") return { url: ${JSON.stringify(routerStub)}, shortCircuit: true };
if (specifier.startsWith("@/")) return { url: SRC + specifier.slice(2) + ".ts", shortCircuit: true };
if ((specifier.startsWith("./") || specifier.startsWith("../")) && !/\\.[a-z0-9]+$/i.test(specifier)) {
return { url: new URL(specifier + ".ts", context.parentURL).href, shortCircuit: true };
}
return next(specifier, context);
}
`),
);
interface Frame {
type: string;
text?: string;
session_id?: string;
}
/** One SSE body: each frame as the server writes it, `data: {...}\n\n`. */
function sseBody(frames: Frame[]): ReadableStream<Uint8Array> {
const encoder = new TextEncoder();
const payload = frames.map((frame) => `data: ${JSON.stringify(frame)}\n\n`).join("");
return new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(payload));
controller.close();
},
});
}
const started = { type: "started", session_id: "s1" };
// The stream stub: chatStream answers with the given frames, sessions reads
// back an empty list so the finished turn does not trigger a reload.
function stubApi(frames: Frame[]): void {
(globalThis as Record<string, unknown>).__archieChatTestApi = {
chatStream: () => ({ body: sseBody(frames) }),
chatSessions: () => ({ sessions: [], commands: [] }),
};
}
const state = await import("../src/chat/state.ts");
test("reasoning frames accumulate on the live turn as its thinking", async () => {
stubApi([
started,
{ type: "reasoning", text: "considering " },
{ type: "reasoning", text: "the request" },
{ type: "error", text: "provider exploded" },
]);
await state.sendMessage({ textOverride: "hello" });
const turn = state.streamingTurn.value;
assert.ok(turn, "the failed turn stays on the panel");
assert.equal(turn.isError, true);
assert.equal(turn.reasoning, "considering the request");
});
test("reasoning never leaks into the reply text", async () => {
stubApi([
started,
{ type: "reasoning", text: "secret chain of thought" },
{ type: "delta", text: "Hello" },
{ type: "done", text: "Hello", session_id: "s1" },
]);
await state.sendMessage({ textOverride: "hi" });
assert.equal(state.streamingTurn.value, null);
const last = state.messages.value.at(-1);
assert.equal(last?.from, "assistant");
assert.equal(last?.text, "Hello");
});
test("a turn without reasoning frames completes normally", async () => {
stubApi([started, { type: "delta", text: "Hi" }, { type: "done", text: "Hi", session_id: "s1" }]);
await state.sendMessage({ textOverride: "hey" });
assert.equal(state.streamingTurn.value, null);
assert.equal(state.messages.value.at(-1)?.text, "Hi");
assert.equal(state.statusText.value, "Ready");
});