diff --git a/frigate/api/chat.py b/frigate/api/chat.py index 80c065e55f..8749302b26 100644 --- a/frigate/api/chat.py +++ b/frigate/api/chat.py @@ -1667,6 +1667,18 @@ async def chat_completion( 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"}) return StreamingResponse( diff --git a/web/e2e/specs/chat.spec.ts b/web/e2e/specs/chat.spec.ts index 956bf15ccd..0ef74d1127 100644 --- a/web/e2e/specs/chat.spec.ts +++ b/web/e2e/specs/chat.spec.ts @@ -26,6 +26,10 @@ async function installChatStreamOverride( await app.page.addInitScript( ({ chunks, chunkDelayMs, status }) => { (window as unknown as { __chatRequests: unknown[] }).__chatRequests = []; + // Count of mocked streams that emitted every chunk, so tests can wait + // for a stream to finish instead of sleeping. + (window as unknown as { __chatStreamsDone: number }).__chatStreamsDone = + 0; const origFetch = window.fetch; window.fetch = async (input, init) => { const url = @@ -57,6 +61,9 @@ async function installChatStreamOverride( ); } controller.close(); + ( + window as unknown as { __chatStreamsDone: number } + ).__chatStreamsDone += 1; }, }); return new Response(stream, { status: 200 }); @@ -219,6 +226,110 @@ test.describe("Chat — streaming @medium", () => { ).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 ({ frigateApp, }) => { @@ -307,6 +418,80 @@ test.describe("Chat — stop @medium", () => { }); }); +test.describe("Chat — new chat @medium", () => { + test("New chat during a tool-call turn stays cleared", 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: "[]" }, + ]; + // The mocked stream ignores the abort signal, so its remaining chunks + // and onDone still arrive after New chat: the stale request must not + // write them into the cleared chat. + await installChatStreamOverride( + frigateApp, + [ + { type: "messages", messages: toolTurn }, + { type: "content", delta: "Still answering" }, + { + type: "messages", + messages: [ + ...toolTurn, + { role: "assistant", content: "Still answering" }, + ], + }, + { type: "done" }, + ], + { chunkDelayMs: 400 }, + ); + 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(/search objects/i)).toBeVisible({ + timeout: 10_000, + }); + await frigateApp.page.getByRole("button", { name: "New chat" }).click(); + + // Wait for the stale stream to deliver its last chunk, then confirm + // nothing came back. + await expect + .poll( + () => + frigateApp.page.evaluate( + () => + (window as unknown as { __chatStreamsDone: number }) + .__chatStreamsDone, + ), + { timeout: 10_000 }, + ) + .toBe(1); + await expect( + frigateApp.page.getByRole("heading", { level: 1 }), + ).toBeVisible(); + await expect(frigateApp.page.getByText(/search objects/i)).toHaveCount(0); + await expect(frigateApp.page.getByText("find people")).toHaveCount(0); + }); +}); + test.describe("Chat — error @medium", () => { test("non-OK response renders an error banner", async ({ frigateApp }) => { await installChatStreamOverride(frigateApp, [], { status: 500 }); diff --git a/web/src/components/chat/ReasoningBubble.tsx b/web/src/components/chat/ReasoningBubble.tsx index 07dc7f5bec..9e15d1f48f 100644 --- a/web/src/components/chat/ReasoningBubble.tsx +++ b/web/src/components/chat/ReasoningBubble.tsx @@ -34,9 +34,10 @@ export function ReasoningBubble({ const { t } = useTranslation(["views/chat"]); // 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. - const [open, setOpen] = useState(true); + // Reasoning that is already finished on mount starts collapsed. + const [open, setOpen] = useState(!answerStarted); const userInteractedRef = useRef(false); - const lastAutoState = useRef(true); + const lastAutoState = useRef(!answerStarted); useEffect(() => { if (userInteractedRef.current) return; @@ -66,6 +67,7 @@ export function ReasoningBubble({