DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): let the closing answer stream where it will stay
Bingxi Zhao (Frank)9f3990463f14
diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsxindex 26d19b299..a7ee54d5e 100644--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@ -742,18 +742,31 @@ export const AssistantMessage = memo(function AssistantMessage({// layers: the process stays open and streams live, then folds itself into// one line the moment the turn settles into its closing answer.//- // The boundary is the trailing run of prose — the text after the last step.- // It is only trusted once a round has actually completed as the terminal- // one, because mid-turn every paragraph is briefly "trailing" and treating- // it as the answer would fold the process shut on every line.- const settledIntoAnswer =- !isStreaming || hasSettledFinalRound(events);+ // The boundary is the trailing run of prose — the text after the last step —+ // and it is structural, not timed: whatever is being written right now is+ // always placed as the answer, from its first character.+ //+ // Waiting for the terminal round before promoting it is what an earlier cut+ // did, and it meant the closing answer streamed INSIDE the collapsible+ // process and jumped out of it once finished. That leaks a question the+ // reader should never have been asked to hold — "is this the answer yet?" —+ // and it is a question we cannot answer at that point anyway: a round only+ // reveals whether it called tools after its prose is complete.+ //+ // Placing it optimistically inverts which case pays. Commentary is demoted+ // into the process when its round turns out to have called a tool, and that+ // costs one 14px slide at the exact moment the tool row appears below it —+ // motion that reads as the two being grouped. The answer, which is the text+ // the reader actually came for, never moves at all.const answerStart = useMemo(() => {- if (!settledIntoAnswer) return messageSegments.length;let idx = messageSegments.length;while (idx > 0 && messageSegments[idx - 1].kind === "text") idx -= 1;return idx;- }, [messageSegments, settledIntoAnswer]);+ }, [messageSegments]);+ // Separately: whether the working-out folds itself away. This is the one+ // thing that does need the terminal-round signal, since it is the claim+ // that there is no more work coming.+ const settledIntoAnswer = !isStreaming || hasSettledFinalRound(events);// Cards are not process: a question the reader was asked (and answered) is// part of the exchange, not working-out to be folded away. So they break// the process into runs, each of which folds on its own.@@ -764,10 +777,9 @@ export const AssistantMessage = memo(function AssistantMessage({// The leading run rides in the activity header, which is already pinned at// the top and already is a disclosure — giving it the process keeps the// message to ONE line of chrome instead of a status line plus a fold.- // Only the segment layout hands its process to the header. A message with- // nothing but prose renders through the plain body branch below, and before- // its first tool call every paragraph is still "process" — so without this- // gate a turn's opening sentence rendered twice, once in each place.+ // Only the segment layout hands its process to the header; a message with+ // nothing but prose renders through the plain body branch below, which would+ // otherwise draw the same opening sentence a second time.const headerProcess =useSegmentLayout && messageBlocks[0]?.kind === "process"? messageBlocks[0]diff --git a/web/tests/integration/chat-messages.spec.tsx b/web/tests/integration/chat-messages.spec.tsxindex f992297a4..ace8f0447 100644--- a/web/tests/integration/chat-messages.spec.tsx+++ b/web/tests/integration/chat-messages.spec.tsx@@ -1,92 +1,163 @@-import { render, screen } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { describe, expect, it, vi } from "vitest";-import { ChatMessageList } from "@/features/chat/messages";-import { initI18n } from "@/i18n/init";+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { describe, expect, it, vi } from 'vitest'+import { ChatMessageList } from '@/features/chat/messages'+import type { StreamEvent } from '@/features/chat/model/protocol'+import { WatchingProvider } from '@/context/WatchingContext'+import { initI18n } from '@/i18n/init'-initI18n("en");+initI18n('en')-describe("chat message feature", () => {- it("renders a user row with keyboard-accessible message actions", async () => {- const copy = vi.fn(async () => undefined);- const user = userEvent.setup();+describe('chat message feature', () => {+ it('renders a user row with keyboard-accessible message actions', async () => {+ const copy = vi.fn(async () => undefined)+ const user = userEvent.setup()render(<ChatMessageListmessages={[{id: 1,- role: "user",- content: "Explain eigenvectors",+ role: 'user',+ content: 'Explain eigenvectors',parentMessageId: null,},]}isStreaming={false}onCopyAssistantMessage={copy}onRegenerateMessage={() => undefined}- />,- );- expect(screen.getByText("Explain eigenvectors")).toBeVisible();- await user.click(screen.getByRole("button", { name: "Copy" }));- expect(copy).toHaveBeenCalledWith("Explain eigenvectors");- expect(await screen.findByRole("button", { name: "Copied" })).toBeVisible();- });+ />+ )+ expect(screen.getByText('Explain eigenvectors')).toBeVisible()+ await user.click(screen.getByRole('button', { name: 'Copy' }))+ expect(copy).toHaveBeenCalledWith('Explain eigenvectors')+ expect(await screen.findByRole('button', { name: 'Copied' })).toBeVisible()+ })// The button used to infer success from the handler's promise *resolving*,// so a swallowed clipboard error rendered 已复制 — and, because the label is// the aria-label on an aria-live element, announced it to screen readers.- it("reports a failed copy instead of claiming success", async () => {+ it('reports a failed copy instead of claiming success', async () => {const copy = vi.fn(async () => {- throw new Error("clipboard unavailable");- });- const user = userEvent.setup();+ throw new Error('clipboard unavailable')+ })+ const user = userEvent.setup()render(<ChatMessageListmessages={[{id: 1,- role: "user",- content: "Explain eigenvectors",+ role: 'user',+ content: 'Explain eigenvectors',parentMessageId: null,},]}isStreaming={false}onCopyAssistantMessage={copy}onRegenerateMessage={() => undefined}- />,- );- await user.click(screen.getByRole("button", { name: "Copy" }));- expect(- await screen.findByRole("button", { name: "Could not copy" }),- ).toBeVisible();- expect(screen.queryByRole("button", { name: "Copied" })).toBeNull();- });+ />+ )+ await user.click(screen.getByRole('button', { name: 'Copy' }))+ expect(await screen.findByRole('button', { name: 'Could not copy' })).toBeVisible()+ expect(screen.queryByRole('button', { name: 'Copied' })).toBeNull()+ })++ // The closing answer used to stream INSIDE the collapsible working-out and+ // hop out of it once the round completed, because where the prose was placed+ // was gated on the same "this round was terminal" signal that decides+ // whether to fold. A round only reveals whether it called tools after its+ // prose is done, so that gate could never be satisfied in time — it just+ // meant the reader watched the answer arrive dressed as reasoning.+ //+ // Placement is structural now: whatever is being written is the answer.+ it('streams the closing answer outside the fold, not inside it', () => {+ const event = (+ type: StreamEvent['type'],+ metadata: Record<string, unknown>,+ content = ''+ ): StreamEvent => ({+ type,+ source: 'chat',+ stage: 'responding',+ content,+ metadata,+ session_id: 's1',+ turn_id: 't1',+ seq: 0,+ timestamp: 0,+ })++ const { container } = render(+ <WatchingProvider>+ <ChatMessageList+ messages={[+ {+ id: 1,+ role: 'assistant',+ content: 'Let me look that up.\n\nIt was 1957.',+ parentMessageId: null,+ events: [+ event(+ 'content',+ { call_id: 'round-1', call_kind: 'agent_loop_round' },+ 'Let me look that up.'+ ),+ // Round one turned out to have called a tool, so its prose is+ // commentary and belongs to the working-out.+ event('progress', {+ call_id: 'round-1',+ trace_kind: 'call_status',+ call_state: 'complete',+ call_role: 'narration',+ answer_visible: true,+ }),+ event('tool_call', { call_id: 'tool-1' }, 'web_search'),+ event('tool_result', { call_id: 'tool-1' }, 'three results'),+ // Round two is still being written — no completion marker yet.+ event(+ 'content',+ { call_id: 'round-2', call_kind: 'agent_loop_round' },+ 'It was 1957.'+ ),+ ],+ },+ ]}+ isStreaming+ onCopyAssistantMessage={async () => undefined}+ onRegenerateMessage={() => undefined}+ />+ </WatchingProvider>+ )++ const fold = container.querySelector('div.grid')+ expect(fold).not.toBeNull()+ expect(fold!.contains(screen.getByText('Let me look that up.'))).toBe(true)+ expect(fold!.contains(screen.getByText('It was 1957.'))).toBe(false)+ })// A synchronous throw is what reading `navigator.clipboard.writeText` does// on an insecure origin, and `Promise.resolve(onCopy(content))` ran the// handler outside the chain, so that throw escaped the button entirely.- it("catches a handler that throws synchronously", async () => {+ it('catches a handler that throws synchronously', async () => {const copy = vi.fn(() => {- throw new Error("navigator.clipboard is undefined");- }) as unknown as (content: string) => Promise<void>;- const user = userEvent.setup();+ throw new Error('navigator.clipboard is undefined')+ }) as unknown as (content: string) => Promise<void>+ const user = userEvent.setup()render(<ChatMessageListmessages={[{id: 1,- role: "user",- content: "Explain eigenvectors",+ role: 'user',+ content: 'Explain eigenvectors',parentMessageId: null,},]}isStreaming={false}onCopyAssistantMessage={copy}onRegenerateMessage={() => undefined}- />,- );- await user.click(screen.getByRole("button", { name: "Copy" }));- expect(- await screen.findByRole("button", { name: "Could not copy" }),- ).toBeVisible();- });-});+ />+ )+ await user.click(screen.getByRole('button', { name: 'Copy' }))+ expect(await screen.findByRole('button', { name: 'Could not copy' })).toBeVisible()+ })+})