Compare commits

..
1 Commits
Author SHA1 Message Date
Nicolas Mowen a74b1e9f55 fix chat reasoning not splitting after tool calls 2026-12-02 16:58:38 -07:00
7 changed files with 214 additions and 329 deletions
+12
View File
@@ -1667,6 +1667,18 @@ async def chat_completion(
yield _emit_chain() yield _emit_chain()
yield _emit_chain() yield _emit_chain()
if stream_iterations >= max_iterations:
# Without this the turn ends on tool results with no answer,
# and the client has nothing to tell the user.
logger.warning(
"Max tool iterations (%d) reached in chat stream", max_iterations
)
yield _emit(
{
"type": "error",
"error": "I reached the maximum number of tool call iterations. Please try rephrasing your question.",
}
)
yield _emit({"type": "done"}) yield _emit({"type": "done"})
return StreamingResponse( return StreamingResponse(
+104
View File
@@ -219,6 +219,110 @@ test.describe("Chat — streaming @medium", () => {
).toBeVisible({ timeout: 5_000 }); ).toBeVisible({ timeout: 5_000 });
}); });
test("each model call's reasoning renders with its own message", async ({
frigateApp,
}) => {
const toolTurn = [
{ role: "system", content: "sys" },
{ role: "user", content: "find people" },
{
role: "assistant",
content: null,
tool_calls: [
{
id: "call_1",
type: "function",
function: {
name: "search_objects",
arguments: '{"label":"person"}',
},
},
],
},
{ role: "tool", tool_call_id: "call_1", content: "[]" },
];
await installChatStreamOverride(frigateApp, [
{ type: "reasoning", delta: "first thought" },
{ type: "messages", messages: toolTurn },
{ type: "reasoning", delta: "second thought" },
{ type: "content", delta: "No people found." },
{
type: "messages",
messages: [
...toolTurn,
{ role: "assistant", content: "No people found." },
],
},
{ type: "done" },
]);
await frigateApp.goto("/chat");
const input = frigateApp.page.getByPlaceholder(/ask/i);
await expect(input).toBeVisible({ timeout: 10_000 });
await input.fill("find people");
await input.press("Enter");
await expect(frigateApp.page.getByText("No people found.")).toBeVisible({
timeout: 10_000,
});
// Two separate, collapsed reasoning bubbles; expanding both shows each
// trace on its own rather than one concatenated block.
const toggles = frigateApp.page.getByRole("button", {
name: /show reasoning/i,
});
await expect(toggles).toHaveCount(2);
// Expanding one relabels it to "Hide reasoning", so click the first
// remaining "Show" toggle twice.
await toggles.first().click();
await expect(toggles).toHaveCount(1);
await toggles.first().click();
await expect(
frigateApp.page.locator("pre", { hasText: /^first thought$/ }),
).toHaveCount(1);
await expect(
frigateApp.page.locator("pre", { hasText: /^second thought$/ }),
).toHaveCount(1);
});
test("a turn that ends without a final answer keeps its tool calls", async ({
frigateApp,
}) => {
const toolTurn = [
{ role: "system", content: "sys" },
{ role: "user", content: "find people" },
{
role: "assistant",
content: null,
tool_calls: [
{
id: "call_1",
type: "function",
function: {
name: "search_objects",
arguments: '{"label":"person"}',
},
},
],
},
{ role: "tool", tool_call_id: "call_1", content: "[]" },
];
await installChatStreamOverride(frigateApp, [
{ type: "messages", messages: toolTurn },
{ type: "messages", messages: toolTurn },
{ type: "error", error: "iteration limit" },
{ type: "done" },
]);
await frigateApp.goto("/chat");
const input = frigateApp.page.getByPlaceholder(/ask/i);
await expect(input).toBeVisible({ timeout: 10_000 });
await input.fill("find people");
await input.press("Enter");
await expect(
frigateApp.page.getByRole("alert").filter({ hasText: /iteration limit/ }),
).toBeVisible({ timeout: 10_000 });
await expect(frigateApp.page.getByText(/search objects/i)).toBeVisible();
});
test("assistant markdown renders only same-origin images", async ({ test("assistant markdown renders only same-origin images", async ({
frigateApp, frigateApp,
}) => { }) => {
+2 -247
View File
@@ -1,16 +1,13 @@
/** /**
* FFmpeg args widget -- MEDIUM tier. * Hardware acceleration args widget -- MEDIUM tier.
* *
* Global hwaccel offers Auto (writes "auto") and Disabled (writes []). * Global hwaccel offers Auto (writes "auto") and Disabled (writes []).
* Cameras offer Disabled next to "Inherit from global setting". * Cameras offer Disabled next to "Inherit from global setting".
* Global input and record args offer Default, and record_sub offers
* "Same as record" (writes []).
*/ */
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { resolve, dirname } from "node:path"; import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import type { Locator } from "@playwright/test";
import { test, expect, type FrigateApp } from "../../fixtures/frigate-test"; import { test, expect, type FrigateApp } from "../../fixtures/frigate-test";
import { import {
configFactory, configFactory,
@@ -52,10 +49,7 @@ async function openSettings(
json: { json: {
hwaccel_args: ["preset-vaapi", "preset-nvidia"], hwaccel_args: ["preset-vaapi", "preset-nvidia"],
input_args: ["preset-rtsp-generic"], input_args: ["preset-rtsp-generic"],
output_args: { output_args: { record: ["preset-record-generic"], detect: [] },
record: ["preset-record-generic", "preset-record-generic-audio-aac"],
detect: [],
},
}, },
}), }),
); );
@@ -582,242 +576,3 @@ test.describe("hwaccel args widget @medium", () => {
).toBeChecked(); ).toBeChecked();
}); });
}); });
const DEFAULT_MODE = "default";
const DEFAULTED_FIELDS = ["root_input_args", "root_output_args_record"];
const RECORD_SUB = "root_output_args_record_sub";
// Sections also open on their own when a field inside them has a pending
// change, so a blind click can close one again. Clicks inside a section
// wait for its open animation to finish.
const expand = async (trigger: Locator) => {
await expect(async () => {
if ((await trigger.getAttribute("aria-expanded")) !== "true") {
await trigger.click();
}
await expect(trigger).toHaveAttribute("aria-expanded", "true", {
timeout: 1_000,
});
}).toPass();
await trigger.page().waitForFunction(() =>
document
.getAnimations()
.filter((animation) =>
(animation as CSSAnimation).animationName?.startsWith("collapsible"),
)
.every((animation) => animation.playState === "finished"),
);
};
const showOutputArgs = (app: FrigateApp) =>
expand(
app.page
.locator("[aria-expanded]")
.filter({ has: app.page.getByText("Output arguments", { exact: true }) }),
);
// A sidebar switch lands after a delay, so wait for the FFmpeg form before
// opening its sections.
const showGlobalArgs = async (app: FrigateApp) => {
await expect(radio(app, "root_hwaccel_args", "auto")).toBeVisible();
await expand(app.page.getByRole("button", { name: /Advanced/ }).first());
await showOutputArgs(app);
};
const switchSection = (app: FrigateApp, name: string) =>
app.page
.locator('[data-sidebar="menu-sub-button"]', {
hasText: new RegExp(`^${name}$`),
})
.click();
// The sidebar commits a switch after a delay, and a second click before
// then cancels the first, so wait for the FFmpeg form to unmount.
const leaveFfmpegAndReturn = async (app: FrigateApp) => {
await switchSection(app, "Recording");
await expect(radio(app, "root_hwaccel_args", "auto")).toHaveCount(0);
await switchSection(app, "FFmpeg");
};
test.describe("ffmpeg default args @medium", () => {
test("global defaults show Default", async ({ frigateApp }) => {
await openSettings(frigateApp, "/settings?page=globalFfmpeg");
await showGlobalArgs(frigateApp);
for (const field of DEFAULTED_FIELDS) {
await expect(radio(frigateApp, field, DEFAULT_MODE)).toBeChecked();
}
});
test("global Default on defaults sends no delete", async ({ frigateApp }) => {
const capture = await openSettings(
frigateApp,
"/settings?page=globalFfmpeg",
);
await showGlobalArgs(frigateApp);
for (const field of DEFAULTED_FIELDS) {
const unset = radio(frigateApp, field, DEFAULT_MODE);
await radio(frigateApp, field, "manual").click();
await manualInput(frigateApp, field).fill("-x 1");
await unset.click();
await expect(unset).toBeChecked();
}
await frigateApp.page
.getByRole("switch", { name: "Apple compatibility" })
.click();
await save(frigateApp).click();
await expect.poll(capture.saved, { timeout: 5_000 }).toMatchObject({
config_data: { ffmpeg: { apple_compatibility: true } },
});
const { ffmpeg } = (
capture.saved() as { config_data: { ffmpeg: Record<string, unknown> } }
).config_data;
expect(ffmpeg).not.toHaveProperty("input_args");
expect(ffmpeg).not.toHaveProperty("output_args");
});
test("Default then Manual starts with an empty box", async ({
frigateApp,
}) => {
await openSettings(frigateApp, "/settings?page=globalFfmpeg");
await showGlobalArgs(frigateApp);
for (const field of DEFAULTED_FIELDS) {
const manual = radio(frigateApp, field, "manual");
await manual.click();
await expect(manual).toBeChecked();
await expect(manualInput(frigateApp, field)).toHaveValue("");
}
await expect(save(frigateApp)).toBeDisabled();
});
test("global Default on defaults stays across a section switch", async ({
frigateApp,
}) => {
test.skip(frigateApp.isMobile, "the section sidebar is desktop only");
await openSettings(frigateApp, "/settings?page=globalFfmpeg");
await showGlobalArgs(frigateApp);
for (const field of DEFAULTED_FIELDS) {
await radio(frigateApp, field, "manual").click();
await manualInput(frigateApp, field).fill("-x 1");
await radio(frigateApp, field, DEFAULT_MODE).click();
}
await leaveFfmpegAndReturn(frigateApp);
await showGlobalArgs(frigateApp);
for (const field of DEFAULTED_FIELDS) {
await expect(radio(frigateApp, field, DEFAULT_MODE)).toBeChecked();
}
await expect(save(frigateApp)).toBeDisabled();
});
test("global Default on saved args deletes them", async ({ frigateApp }) => {
test.skip(frigateApp.isMobile, "the section sidebar is desktop only");
const capture = await openSettings(
frigateApp,
"/settings?page=globalFfmpeg",
{ ffmpeg: { input_args: "-in 1", output_args: { record: "-out 1" } } },
);
await showGlobalArgs(frigateApp);
for (const field of DEFAULTED_FIELDS) {
await radio(frigateApp, field, DEFAULT_MODE).click();
}
await leaveFfmpegAndReturn(frigateApp);
await showGlobalArgs(frigateApp);
for (const field of DEFAULTED_FIELDS) {
await expect(radio(frigateApp, field, DEFAULT_MODE)).toBeChecked();
}
await save(frigateApp).click();
await expect.poll(capture.saved, { timeout: 5_000 }).toMatchObject({
config_data: {
ffmpeg: { input_args: "", output_args: { record: "" } },
},
});
});
test("Same as record on defaults leaves nothing to save", async ({
frigateApp,
}) => {
await openSettings(frigateApp, "/settings?page=globalFfmpeg");
await showGlobalArgs(frigateApp);
const sameAsRecord = radio(frigateApp, RECORD_SUB, "inherit");
await expect(sameAsRecord).toBeChecked();
await radio(frigateApp, RECORD_SUB, "preset").click();
await expect(save(frigateApp)).toBeEnabled();
await sameAsRecord.click();
await expect(sameAsRecord).toBeChecked();
await expect(save(frigateApp)).toBeDisabled();
});
test("global Same as record on saved args saves an empty list", async ({
frigateApp,
}) => {
const capture = await openSettings(
frigateApp,
"/settings?page=globalFfmpeg",
{ ffmpeg: { output_args: { record_sub: "preset-record-generic" } } },
);
await showGlobalArgs(frigateApp);
await radio(frigateApp, RECORD_SUB, "inherit").click();
await save(frigateApp).click();
await expect.poll(capture.saved, { timeout: 5_000 }).toMatchObject({
config_data: { ffmpeg: { output_args: { record_sub: [] } } },
});
});
test("camera Same as record over a global value saves an empty list", async ({
frigateApp,
}) => {
const recordSub = { output_args: { record_sub: "preset-record-generic" } };
const capture = await openSettings(
frigateApp,
"/settings?page=cameraFfmpeg&camera=front_door",
{
ffmpeg: recordSub,
cameras: {
front_door: { ffmpeg: recordSub },
backyard: { ffmpeg: { input_args: "-backyard 1" } },
},
},
);
// Only Backyard has manual input args, which shows which camera's form
// is on screen.
const inputArgs = (mode: string) =>
radio(frigateApp, "root_input_args", mode);
const sameAsRecord = radio(frigateApp, RECORD_SUB, "inherit");
await expect(inputArgs("inherit")).toBeChecked();
await showOutputArgs(frigateApp);
await sameAsRecord.click();
await frigateApp.page
.getByRole("button", { name: "Select a camera" })
.click();
await frigateApp.page.getByRole("switch", { name: "Backyard" }).click();
await expect(inputArgs("manual")).toBeChecked();
await frigateApp.page
.getByRole("button", { name: "Select a camera" })
.click();
await frigateApp.page.getByRole("switch", { name: "Front Door" }).click();
await expect(inputArgs("inherit")).toBeChecked();
await showOutputArgs(frigateApp);
await expect(sameAsRecord).toBeChecked();
await save(frigateApp).click();
await expect.poll(capture.saved, { timeout: 5_000 }).toMatchObject({
config_data: {
cameras: {
front_door: { ffmpeg: { output_args: { record_sub: [] } } },
},
},
});
});
});
+1 -1
View File
@@ -1607,7 +1607,7 @@
"preset": "Preset", "preset": "Preset",
"manual": "Manual arguments", "manual": "Manual arguments",
"inherit": "Inherit from camera setting", "inherit": "Inherit from camera setting",
"default": "Default", "none": "None",
"auto": "Auto", "auto": "Auto",
"autoDescription": "Frigate detects Nvidia or VAAPI hardware. After saving, this field shows the detected preset, or Disabled if none is found. Other hardware needs a preset.", "autoDescription": "Frigate detects Nvidia or VAAPI hardware. After saving, this field shows the detected preset, or Disabled if none is found. Other hardware needs a preset.",
"disabled": "Disabled", "disabled": "Disabled",
+4 -2
View File
@@ -34,9 +34,10 @@ export function ReasoningBubble({
const { t } = useTranslation(["views/chat"]); const { t } = useTranslation(["views/chat"]);
// Open while the model is still mid-thought (no answer tokens yet); // Open while the model is still mid-thought (no answer tokens yet);
// once the answer begins, collapse on its own but let the user reopen. // once the answer begins, collapse on its own but let the user reopen.
const [open, setOpen] = useState(true); // Reasoning that is already finished on mount starts collapsed.
const [open, setOpen] = useState(!answerStarted);
const userInteractedRef = useRef(false); const userInteractedRef = useRef(false);
const lastAutoState = useRef(true); const lastAutoState = useRef(!answerStarted);
useEffect(() => { useEffect(() => {
if (userInteractedRef.current) return; if (userInteractedRef.current) return;
@@ -66,6 +67,7 @@ export function ReasoningBubble({
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
aria-label={label}
className="h-auto w-full min-w-0 justify-start gap-2 whitespace-normal p-0 text-left text-xs hover:bg-transparent" className="h-auto w-full min-w-0 justify-start gap-2 whitespace-normal p-0 text-left text-xs hover:bg-transparent"
> >
<Tooltip> <Tooltip>
@@ -1,4 +1,4 @@
import type { RJSFSchema, WidgetProps } from "@rjsf/utils"; import type { WidgetProps } from "@rjsf/utils";
import useSWR from "swr"; import useSWR from "swr";
import { useCallback, useEffect, useMemo, useState } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -25,7 +25,7 @@ type FfmpegPresetResponse = {
}; };
type FfmpegArgsMode = type FfmpegArgsMode =
"preset" | "manual" | "inherit" | "default" | "auto" | "disabled"; "preset" | "manual" | "inherit" | "none" | "auto" | "disabled";
// RJSF remounts the widget when the value flips between a string and a list, // RJSF remounts the widget when the value flips between a string and a list,
// so the user's mode choice lives outside the component. It applies only // so the user's mode choice lives outside the component. It applies only
@@ -68,20 +68,6 @@ const getPresetOptions = (
return []; return [];
}; };
// AnyOfField hands the widget a branch without the default, so read it
// from the section schema, which arrives with its $refs resolved.
const getSchemaDefault = (
rootSchema: RJSFSchema | undefined,
fieldPath: string | undefined,
): unknown => {
if (!rootSchema || !fieldPath) {
return undefined;
}
const schemaPath = fieldPath.split(".").flatMap((key) => ["properties", key]);
return get(rootSchema, [...schemaPath, "default"]);
};
const resolveMode = ( const resolveMode = (
value: unknown, value: unknown,
presets: string[], presets: string[],
@@ -91,7 +77,7 @@ const resolveMode = (
): FfmpegArgsMode => { ): FfmpegArgsMode => {
if (value === null || value === undefined) { if (value === null || value === undefined) {
if (allowInherit) return "inherit"; if (allowInherit) return "inherit";
return hwaccelModes ? "auto" : "default"; return hwaccelModes ? "auto" : "none";
} }
if (allowInherit && Array.isArray(value) && value.length === 0) { if (allowInherit && Array.isArray(value) && value.length === 0) {
@@ -171,27 +157,15 @@ export function FfmpegArgsWidget(props: WidgetProps) {
const useSplitLayout = options?.splitLayout !== false; const useSplitLayout = options?.splitLayout !== false;
// Detect camera-level top-level fields (not inside inputs array). // Detect camera-level top-level fields (not inside inputs array).
// These should show "Use global setting" instead of "Default". // These should show "Use global setting" instead of "None".
const isInputScoped = id.includes("_inputs_"); const isInputScoped = id.includes("_inputs_");
const showUseGlobalSetting = isCameraLevel && !isInputScoped && !allowInherit; const showUseGlobalSetting = isCameraLevel && !isInputScoped && !allowInherit;
// Hardware acceleration offers Auto and Disabled in place of Default. Auto // Hardware acceleration offers Auto and Disabled in place of None. Auto
// sends the literal "auto" because the form holds the resolved value, so a // sends the literal "auto" because the form holds the resolved value, so a
// delete could target a key that is absent from the YAML. // delete could target a key that is absent from the YAML.
const hwaccelModes = presetField === "hwaccel_args" && !allowInherit; const hwaccelModes = presetField === "hwaccel_args" && !allowInherit;
const unsetMode: FfmpegArgsMode =
showUseGlobalSetting || allowInherit
? "inherit"
: hwaccelModes
? "auto"
: "default";
const schemaDefault =
unsetMode === "default"
? getSchemaDefault(props.registry?.rootSchema, globalFieldPath)
: undefined;
// Extract the global value for this specific field to detect inheritance // Extract the global value for this specific field to detect inheritance
const globalFieldValue = useMemo(() => { const globalFieldValue = useMemo(() => {
if ( if (
@@ -259,9 +233,6 @@ export function FfmpegArgsWidget(props: WidgetProps) {
if (hwaccelModes && value === "" && !isEqual(savedValue, "")) { if (hwaccelModes && value === "" && !isEqual(savedValue, "")) {
return "manual" as FfmpegArgsMode; return "manual" as FfmpegArgsMode;
} }
if (schemaDefault !== undefined && isEqual(value, schemaDefault)) {
return "default" as FfmpegArgsMode;
}
return resolveMode( return resolveMode(
value, value,
presetOptions, presetOptions,
@@ -278,7 +249,6 @@ export function FfmpegArgsWidget(props: WidgetProps) {
allowInherit, allowInherit,
hwaccelModes, hwaccelModes,
savedValue, savedValue,
schemaDefault,
]); ]);
const modeKey = [ const modeKey = [
@@ -354,27 +324,15 @@ export function FfmpegArgsWidget(props: WidgetProps) {
const handleModeChange = useCallback( const handleModeChange = useCallback(
(nextMode: FfmpegArgsMode) => { (nextMode: FfmpegArgsMode) => {
// An empty record_sub is the backend's "same as record" at both levels. // Restoring an inherited saved value leaves the form clean. Sending
// Deleting it could target a key absent from the YAML, and a camera // undefined would delete a key that may be absent from the YAML.
// would fall back to the global value instead.
if (nextMode === "inherit" && presetField === "output_args.record_sub") {
choose(nextMode, []);
return;
}
// Restoring an inherited or default saved value leaves the form clean.
// Sending undefined would delete a key that may be absent from the
// YAML. A global value that differs from the default must be in it.
if (nextMode === "inherit") { if (nextMode === "inherit") {
choose(nextMode, isInherited(savedValue) ? savedValue : undefined); choose(nextMode, isInherited(savedValue) ? savedValue : undefined);
return; return;
} }
if (nextMode === "default") { if (nextMode === "none") {
choose( choose(nextMode, undefined);
nextMode,
isEqual(savedValue, schemaDefault) ? savedValue : undefined,
);
return; return;
} }
@@ -404,12 +362,7 @@ export function FfmpegArgsWidget(props: WidgetProps) {
// Start from the saved manual args, if any, so a switch back to Manual // Start from the saved manual args, if any, so a switch back to Manual
// shows them instead of an empty box. // shows them instead of an empty box.
if ( if (mode === "preset" || mode === "auto" || mode === "disabled") {
mode === "preset" ||
mode === "default" ||
mode === "auto" ||
mode === "disabled"
) {
const savedIsManual = const savedIsManual =
resolveMode( resolveMode(
savedValue, savedValue,
@@ -431,10 +384,8 @@ export function FfmpegArgsWidget(props: WidgetProps) {
hwaccelModes, hwaccelModes,
isInherited, isInherited,
mode, mode,
presetField,
presetOptions, presetOptions,
savedValue, savedValue,
schemaDefault,
value, value,
], ],
); );
@@ -503,6 +454,12 @@ export function FfmpegArgsWidget(props: WidgetProps) {
? schema.description ? schema.description
: translatedDescription; : translatedDescription;
const unsetMode: FfmpegArgsMode =
showUseGlobalSetting || allowInherit
? "inherit"
: hwaccelModes
? "auto"
: "none";
const unsetLabel = showUseGlobalSetting const unsetLabel = showUseGlobalSetting
? t("configForm.ffmpegArgs.useGlobalSetting", { ns: "views/settings" }) ? t("configForm.ffmpegArgs.useGlobalSetting", { ns: "views/settings" })
: allowInherit : allowInherit
@@ -513,7 +470,7 @@ export function FfmpegArgsWidget(props: WidgetProps) {
? t(unsetLabelKey ?? "configForm.ffmpegArgs.auto", { ? t(unsetLabelKey ?? "configForm.ffmpegArgs.auto", {
ns: "views/settings", ns: "views/settings",
}) })
: t(unsetLabelKey ?? "configForm.ffmpegArgs.default", { : t(unsetLabelKey ?? "configForm.ffmpegArgs.none", {
ns: "views/settings", ns: "views/settings",
}); });
@@ -571,7 +528,7 @@ export function FfmpegArgsWidget(props: WidgetProps) {
</p> </p>
) : mode === "auto" || ) : mode === "auto" ||
mode === "inherit" || mode === "inherit" ||
mode === "default" || mode === "none" ||
mode === "disabled" ? null : mode === "preset" && canUsePresets ? ( mode === "disabled" ? null : mode === "preset" && canUsePresets ? (
<Select <Select
value={presetValue} value={presetValue}
+73 -18
View File
@@ -30,6 +30,12 @@ import {
toolResponsesById, toolResponsesById,
} from "@/utils/chatUtil"; } from "@/utils/chatUtil";
/**
* The in-flight turn. `content`, `reasoning`, and `stats` cover only the
* current model call; each time the backend emits the chain they are attached
* to the assistant message that call produced and reset, so every round of
* reasoning stays with its own tool calls.
*/
type StreamingTurn = { type StreamingTurn = {
content: string; content: string;
reasoning: string; reasoning: string;
@@ -152,10 +158,34 @@ export default function ChatPage() {
abortRef.current = controller; abortRef.current = controller;
let chain: ChatMessage[] = []; let chain: ChatMessage[] = [];
let stats: ChatStats | undefined;
let reasoning = "";
let hadError = false; let hadError = false;
let approvals: PendingToolCall[] | null = null; let approvals: PendingToolCall[] | null = null;
// Reasoning and stats for the current model call, attached to the
// assistant message it produces once that message shows up in the chain.
let segmentReasoning = "";
let segmentStats: ChatStats | undefined;
let seenChainLength = 0;
const extrasByIndex = new Map<
number,
Pick<ChatMessage, "reasoning" | "stats">
>();
// The backend never sees reasoning or stats, so the chain it returns
// lacks them. Restore them from earlier turns and from this turn's
// model calls. The backend prepends a system message on the first turn.
const decorate = (raw: ChatMessage[]): ChatMessage[] => {
const offset =
raw[0]?.role === "system" && messagesToSend[0]?.role !== "system"
? 1
: 0;
return raw.map((m, i) => {
const prior = i >= offset ? messagesToSend[i - offset] : undefined;
const extras = extrasByIndex.get(i);
const reasoning = extras?.reasoning ?? prior?.reasoning;
const stats = extras?.stats ?? prior?.stats;
return reasoning || stats ? { ...m, reasoning, stats } : m;
});
};
await streamChatCompletion( await streamChatCompletion(
url, url,
@@ -165,17 +195,43 @@ export default function ChatPage() {
onContentDelta: (delta) => onContentDelta: (delta) =>
setStreaming((s) => (s ? { ...s, content: s.content + delta } : s)), setStreaming((s) => (s ? { ...s, content: s.content + delta } : s)),
onReasoningDelta: (delta) => { onReasoningDelta: (delta) => {
reasoning += delta; segmentReasoning += delta;
setStreaming((s) => setStreaming((s) =>
s ? { ...s, reasoning: s.reasoning + delta } : s, s ? { ...s, reasoning: s.reasoning + delta } : s,
); );
}, },
onChain: (fullChain) => { onChain: (fullChain) => {
chain = fullChain; // Credit the current call's reasoning to the newest assistant
setStreaming((s) => (s ? { ...s, chain: fullChain } : s)); // message added since the last chain, then start a new segment.
for (let i = fullChain.length - 1; i >= seenChainLength; i--) {
if (fullChain[i].role !== "assistant") continue;
if (segmentReasoning || segmentStats) {
extrasByIndex.set(i, {
reasoning: segmentReasoning || undefined,
stats: segmentStats,
});
}
segmentReasoning = "";
segmentStats = undefined;
break;
}
seenChainLength = fullChain.length;
chain = decorate(fullChain);
const decorated = chain;
setStreaming((s) =>
s
? {
...s,
chain: decorated,
content: "",
reasoning: segmentReasoning,
stats: segmentStats,
}
: s,
);
}, },
onStats: (s) => { onStats: (s) => {
stats = s; segmentStats = s;
setStreaming((cur) => (cur ? { ...cur, stats: s } : cur)); setStreaming((cur) => (cur ? { ...cur, stats: s } : cur));
}, },
onApprovalRequired: (toolCalls) => { onApprovalRequired: (toolCalls) => {
@@ -190,14 +246,14 @@ export default function ChatPage() {
loadingRef.current = false; loadingRef.current = false;
setIsLoading(false); setIsLoading(false);
setStreaming(null); setStreaming(null);
const lastMsg = chain[chain.length - 1]; // Keep whatever the backend got through, even when the turn ends
if (!hadError && lastMsg?.role === "assistant") { // without a final answer (error, stop, or tool iteration limit).
const committed = chain.map((m, i) => // Dropping it would make the tool calls and reasoning vanish.
i === chain.length - 1 if (chain.length === 0) return;
? { ...m, reasoning: reasoning || undefined, stats } const committed = chain;
: m,
);
setMessages(committed); setMessages(committed);
const lastMsg = committed[committed.length - 1];
if (!hadError && lastMsg?.role === "assistant") {
if (approvals?.length) { if (approvals?.length) {
// Calls to always-allowed tools are answered here without // Calls to always-allowed tools are answered here without
// prompting; anything else waits for the user. // prompting; anything else waits for the user.
@@ -377,13 +433,12 @@ export default function ChatPage() {
return ( return (
<div key={i} className="flex flex-col gap-2"> <div key={i} className="flex flex-col gap-2">
{calls.length > 0 && <ToolCallsGroup toolCalls={calls} />} {/* Messages in the chain are finished model calls, so their
reasoning is complete even when they ended in tool calls. */}
{hasText(msg.reasoning) && ( {hasText(msg.reasoning) && (
<ReasoningBubble <ReasoningBubble reasoning={msg.reasoning} answerStarted />
reasoning={msg.reasoning}
answerStarted={!!contentText}
/>
)} )}
{calls.length > 0 && <ToolCallsGroup toolCalls={calls} />}
{contentText && ( {contentText && (
<MessageBubble <MessageBubble
role="assistant" role="assistant"