From 67fc8b3317c62dd84200c4530b8dc6b9c5491c2b Mon Sep 17 00:00:00 2001 From: yuanyyt <1375417741@qq.com> Date: Fri, 30 Oct 2026 14:11:56 +0800 Subject: [PATCH] fix: keep side-chat anchors in sync with the message entry Detaching a thread from its message cleared only the server preference, so an open tab still sent the old quoted_message_id and filed the thread back under the message. Clear the tab's anchor once the server confirms, unless a newer selection already moved it. A new side chat is matched through its live thread state too: its first send binds a session before the tab records a followupSessionId. A selection whose message is still optimistic has no persisted id; it now leaves the thread unattached instead of keeping the previous message. --- .../chat/home/LazySessionViewerPanel.tsx | 4 + .../chat/home/SessionViewerPanel.tsx | 62 +++++- .../chat/components/ChatWorkspace.tsx | 8 + web/tests/chat/ChatWorkspace.smoke.spec.tsx | 65 ++++++ web/tests/lazy-session-viewer-panel.spec.tsx | 2 + web/tests/side-chat-anchor.spec.tsx | 210 ++++++++++++++++++ 6 files changed, 348 insertions(+), 3 deletions(-) create mode 100644 web/tests/side-chat-anchor.spec.tsx diff --git a/web/components/chat/home/LazySessionViewerPanel.tsx b/web/components/chat/home/LazySessionViewerPanel.tsx index 67c265efb..d6b896482 100644 --- a/web/components/chat/home/LazySessionViewerPanel.tsx +++ b/web/components/chat/home/LazySessionViewerPanel.tsx @@ -95,6 +95,10 @@ const LazySessionViewerPanel = forwardRef< callPanel((panel) => panel.openSideChatThread(thread)), closeSideChatThread: (threadSessionId) => callPanel((panel) => panel.closeSideChatThread(threadSessionId)), + clearSideChatSource: (threadSessionId, sourceMessageId) => + callPanel((panel) => + panel.clearSideChatSource(threadSessionId, sourceMessageId), + ), openGeogebraTab: (payload) => callPanel((panel) => panel.openGeogebraTab(payload)), openSubagentTab: (callId, label, events, focus) => diff --git a/web/components/chat/home/SessionViewerPanel.tsx b/web/components/chat/home/SessionViewerPanel.tsx index 8a2ea57a3..f51d86450 100644 --- a/web/components/chat/home/SessionViewerPanel.tsx +++ b/web/components/chat/home/SessionViewerPanel.tsx @@ -224,6 +224,14 @@ export interface SessionViewerPanelHandle { openSideChatThread(thread: SessionSummary): void; /** Closes the tab showing ``sessionId``, if it is open. */ closeSideChatThread(sessionId: string): void; + /** + * Forgets ``sourceMessageId`` on the open tab showing ``sessionId`` after + * that anchor was cleared on the server, so its next send does not file the + * thread back under the message. The tab is found by the thread id it + * recorded or the session its live thread bound on the first send. A tab + * that has since moved to another passage keeps the newer anchor. + */ + clearSideChatSource(sessionId: string, sourceMessageId: number | string | null): void; /** Opens (or focuses) an interactive GeoGebra applet tab. */ openGeogebraTab(payload: GeogebraTabPayload): void; /** Opens (first time) or live-updates a connected subagent's run tab. */ @@ -236,7 +244,9 @@ export interface SessionViewerPanelHandle { export interface SideChatOpenOptions { responder?: SideChatResponder; quote?: string; - /** The message the quote came from; omitted for a bare side chat. */ + /** The message the quote came from. Omitted for a bare side chat, which + * keeps the anchor the thread already has; null when the passage has no + * persisted message yet (an optimistic row), which leaves it unattached. */ sourceMessageId?: number | string | null; } @@ -703,8 +713,14 @@ function SessionViewerPanelInner( if (target) { const existingSource = target.context.sideChat?.sourceMessageId ?? null; // A new selection is an explicit move: the thread follows the passage - // the learner just asked about. Opening it bare keeps its anchor. - const nextSource = sourceMessageId ?? existingSource ?? null; + // the learner just asked about, and a passage without a persisted + // message (an optimistic row) leaves it unattached rather than on the + // old message. Opening the side chat bare keeps whatever anchor it had. + const nextSource = seedQuote + ? (sourceMessageId ?? null) + : sourceMessageId === undefined + ? existingSource + : sourceMessageId; if (seedQuote || nextSource !== existingSource) { setTabs((prev) => prev.map((tab) => @@ -918,6 +934,44 @@ function SessionViewerPanelInner( [closeTab, tabs], ); + /** + * The thread's anchor was cleared on the server: an open tab must forget it + * too, or the next send would file the thread back under the message the + * learner just detached. A tab already pointing at another passage keeps it + * — the newest selection wins over the entry point that was detached. + */ + const clearSideChatSource = useCallback( + (threadSessionId: string, sourceMessageId: number | string | null) => { + setTabs((prev) => + prev.map((tab) => { + if (tab.kind !== "side-chat" || !tab.context.sideChat) return tab; + // A brand-new side chat sends before it is ever reopened, so its tab + // has no followupSessionId yet; the session its first turn bound + // lives in the live thread state instead. + const liveSessionId = + followups?.getThread(tab.context.questionKey).sessionId ?? null; + if ( + tab.context.followupSessionId !== threadSessionId && + liveSessionId !== threadSessionId + ) { + return tab; + } + const side = tab.context.sideChat; + const current = String(side.sourceMessageId ?? ""); + if (current !== String(sourceMessageId ?? "")) return tab; + return { + ...tab, + context: { + ...tab.context, + sideChat: { ...side, sourceMessageId: null }, + }, + }; + }), + ); + }, + [followups], + ); + useImperativeHandle( ref, () => ({ @@ -928,6 +982,7 @@ function SessionViewerPanelInner( openSideChatTab, openSideChatThread, closeSideChatThread, + clearSideChatSource, openGeogebraTab, openSubagentTab, focusActivityHome, @@ -940,6 +995,7 @@ function SessionViewerPanelInner( openSideChatTab, openSideChatThread, closeSideChatThread, + clearSideChatSource, openGeogebraTab, openSubagentTab, focusActivityHome, diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsx index be08632c8..f031dd044 100644 --- a/web/features/chat/components/ChatWorkspace.tsx +++ b/web/features/chat/components/ChatWorkspace.tsx @@ -976,6 +976,14 @@ export default function ChatWorkspace() { { tutor_source_message_id: null }, state.workspaceId || undefined, ); + // The tab showing this thread may still hold the old anchor; left + // alone, its next send would file the thread back under the message + // the learner just detached. A tab already moved by a newer selection + // keeps that anchor. + viewerPanelRef.current?.clearSideChatSource( + thread.session_id, + thread.preferences?.tutor_source_message_id ?? null, + ); } catch (error) { notify( error instanceof Error diff --git a/web/tests/chat/ChatWorkspace.smoke.spec.tsx b/web/tests/chat/ChatWorkspace.smoke.spec.tsx index c0cf8ecfc..d4c63bc0a 100644 --- a/web/tests/chat/ChatWorkspace.smoke.spec.tsx +++ b/web/tests/chat/ChatWorkspace.smoke.spec.tsx @@ -4,6 +4,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { initI18n } from '@/i18n/init' import type { ChatState, MessageItem } from '@/features/chat/ChatStateAdapter' import type { StreamEvent } from '@/features/chat/model/protocol' +import { updateSessionOrganization } from '@/lib/session-api' +import type { SessionSummary } from '@/lib/session-api' initI18n('en') @@ -55,8 +57,22 @@ const fixture = vi.hoisted(() => ({ messages: MessageItem[] isStreaming: boolean canResendLastTurn: boolean + onDetachThread?: (thread: SessionSummary) => Promise } | null, setActiveSessionId: vi.fn(), + viewer: { + openFileTab: vi.fn(), + openWebTab: vi.fn(), + openMarkdownNoteTab: vi.fn(), + openQuizFollowupTab: vi.fn(), + openSideChatTab: vi.fn(), + openSideChatThread: vi.fn(), + closeSideChatThread: vi.fn(), + clearSideChatSource: vi.fn(), + openGeogebraTab: vi.fn(), + openSubagentTab: vi.fn(), + focusActivityHome: vi.fn(), + }, })) vi.mock('@/features/chat/ChatStateAdapter', () => ({ @@ -84,6 +100,18 @@ vi.mock('next/dynamic', () => ({ default: () => () => null, })) +// The viewer is a separate surface with its own suite; here its imperative +// handle is a spy so ChatWorkspace's calls into it stay observable. +vi.mock('@/components/chat/home/LazySessionViewerPanel', async () => { + const { forwardRef, useImperativeHandle } = await import('react') + return { + default: forwardRef(function StubViewer(_props: unknown, ref) { + useImperativeHandle(ref, () => fixture.viewer as never, []) + return null + }), + } +}) + vi.mock('@/features/capabilities/useCapabilityCatalog', () => ({ useCapabilityCatalog: () => ({ capabilities: [ @@ -478,4 +506,41 @@ describe('ChatWorkspace smoke', () => { await waitFor(() => expect(fixture.adapter.loadSession).toHaveBeenCalledTimes(2)) view.unmount() }) + + it('clears an open side chat when its thread is detached from a message', async () => { + const view = renderWorkspace() + await waitFor(() => expect(fixture.adapter.newSession).toHaveBeenCalled()) + + applyState({ + sessionId: 's-1', + messages: [{ id: 1, role: 'user', content: 'Explain photosynthesis' }], + }) + view.rerender() + await waitFor(() => expect(fixture.listProps?.onDetachThread).toBeTypeOf('function')) + + const thread = { + id: 'thread-1', + session_id: 'thread-1', + title: 'Why fork returns twice', + created_at: 1, + updated_at: 1, + message_count: 2, + last_message: '', + preferences: { tutor_source_message_id: 7 }, + } satisfies SessionSummary + + await act(async () => { + await fixture.listProps!.onDetachThread!(thread) + }) + + expect(updateSessionOrganization).toHaveBeenCalledWith( + 'thread-1', + { tutor_source_message_id: null }, + undefined + ) + // The tab must forget the anchor too, or its next send would file the + // thread back under the message the learner just detached. + expect(fixture.viewer.clearSideChatSource).toHaveBeenCalledWith('thread-1', 7) + view.unmount() + }) }) diff --git a/web/tests/lazy-session-viewer-panel.spec.tsx b/web/tests/lazy-session-viewer-panel.spec.tsx index 5b16b745d..88ab2a429 100644 --- a/web/tests/lazy-session-viewer-panel.spec.tsx +++ b/web/tests/lazy-session-viewer-panel.spec.tsx @@ -28,6 +28,8 @@ vi.mock("next/dynamic", async () => { openSideChatThread: (thread) => fixture.calls.push(`thread:${thread.session_id}`), closeSideChatThread: (threadSessionId) => fixture.calls.push(`close-thread:${threadSessionId}`), + clearSideChatSource: (threadSessionId, sourceMessageId) => + fixture.calls.push(`clear-source:${threadSessionId}:${String(sourceMessageId)}`), openGeogebraTab: () => fixture.calls.push("geogebra"), openSubagentTab: () => fixture.calls.push("subagent"), focusActivityHome: () => fixture.calls.push("activity"), diff --git a/web/tests/side-chat-anchor.spec.tsx b/web/tests/side-chat-anchor.spec.tsx new file mode 100644 index 000000000..409ebb58a --- /dev/null +++ b/web/tests/side-chat-anchor.spec.tsx @@ -0,0 +1,210 @@ +import { act, cleanup, render, screen } from "@testing-library/react"; +import { createRef, useEffect } from "react"; +import { afterEach, expect, it, vi } from "vitest"; + +import SessionViewerPanel, { + type SessionViewerPanelHandle, + type SessionViewerPanelProps, +} from "@/components/chat/home/SessionViewerPanel"; +import { + QuizFollowupProvider, + useQuizFollowupController, + type QuizFollowupController, + type QuizFollowupTabContext, +} from "@/context/QuizFollowupContext"; +import { initI18n } from "@/i18n/init"; +import { buildSessionActivity } from "@/lib/session-activity"; +import type { SessionSummary } from "@/lib/session-api"; + +vi.mock("@/components/tasks/TaskPanelSection", () => ({ default: () => null })); +vi.mock("@/hooks/usePartnerRoster", () => ({ + usePartnerRoster: () => ({ + partners: [{ partner_id: "ada", name: "Ada" }], + loading: false, + error: false, + }), +})); +vi.mock("@/hooks/usePartnerGroups", () => ({ + usePartnerGroups: () => ({ groups: [], loading: false, error: false }), +})); + +// The composer is where the next send's quoted_message_id is decided; the +// probe shows the anchor the tab would submit, without mounting the composer. +vi.mock("@/components/quiz/FollowupChatComposer", () => ({ + default: ({ context }: { context: QuizFollowupTabContext }) => ( +
+ {String(context.sideChat?.sourceMessageId ?? "none")} +
+ ), +})); + +const api = vi.hoisted(() => ({ + listSessionThreads: vi.fn(async () => [] as unknown[]), + getSession: vi.fn(async () => ({ messages: [] as unknown[] })), +})); +vi.mock("@/lib/session-api", async (importOriginal) => ({ + ...(await importOriginal()), + listSessionThreads: api.listSessionThreads, + getSession: api.getSession, +})); + +initI18n("en"); + +afterEach(() => { + cleanup(); + api.listSessionThreads.mockReset().mockResolvedValue([]); + api.getSession.mockReset().mockResolvedValue({ messages: [] }); +}); + +const conversation = { title: "Fork and exec", leafMessageId: 12, language: "en" }; +const ada = { kind: "partner" as const, id: "ada", name: "Ada" }; + +function renderPanel(onController?: (controller: QuizFollowupController) => void) { + const ref = createRef(); + const props: SessionViewerPanelProps = { + open: true, + sessionId: "session-a", + sessionKey: "session-a", + conversation, + activity: buildSessionActivity([]), + onClose: () => {}, + onAutoOpen: () => {}, + }; + render( + + + {onController ? : null} + , + ); + return ref; +} + +/** Reaches the live thread state a side chat's first send writes into. */ +function ControllerProbe({ + onReady, +}: { + onReady: (controller: QuizFollowupController) => void; +}) { + const controller = useQuizFollowupController(); + useEffect(() => onReady(controller), [controller, onReady]); + return null; +} + +function threadRow(sourceMessageId: number | string | null): SessionSummary { + return { + id: "thread-1", + session_id: "thread-1", + title: "Why fork returns twice", + created_at: 1, + updated_at: 1_700_000_000, + message_count: 0, + last_message: "", + preferences: { + parent_session_id: "session-a", + session_kind: "selection_tutor", + answer_by: "partner:ada", + tutor_source_message_id: sourceMessageId, + }, + }; +} + +const anchor = () => screen.getByTestId("side-chat-anchor"); + +it("moves the anchor with a new selection but keeps it when opened bare", async () => { + const ref = renderPanel(); + + act(() => + ref.current!.openSideChatTab({ + responder: ada, + quote: "rc = fork()", + sourceMessageId: 7, + }), + ); + expect(await screen.findByTestId("side-chat-anchor")).toHaveTextContent("7"); + + // Bare open: nothing new is being asked about, so the thread stays put. + act(() => ref.current!.openSideChatTab({ responder: ada })); + expect(anchor()).toHaveTextContent("7"); +}); + +it("leaves the thread unattached when a new selection has no persisted message", async () => { + const ref = renderPanel(); + + act(() => + ref.current!.openSideChatTab({ + responder: ada, + quote: "rc = fork()", + sourceMessageId: 7, + }), + ); + expect(await screen.findByTestId("side-chat-anchor")).toHaveTextContent("7"); + + // The passage comes from an optimistic row: its negative temporary id is + // not a message the thread can be filed under, so the old anchor must go. + act(() => + ref.current!.openSideChatTab({ + responder: ada, + quote: "A draft passage", + sourceMessageId: null, + }), + ); + expect(anchor()).toHaveTextContent("none"); +}); + +it("forgets an open tab's anchor when its thread is detached", async () => { + const ref = renderPanel(); + + act(() => ref.current!.openSideChatThread(threadRow(7))); + expect(await screen.findByTestId("side-chat-anchor")).toHaveTextContent("7"); + + act(() => ref.current!.clearSideChatSource("thread-1", 7)); + expect(anchor()).toHaveTextContent("none"); +}); + +it("forgets a new side chat's anchor once its first send binds a session", async () => { + let controller: QuizFollowupController | null = null; + const ref = renderPanel((ready) => { + controller = ready; + }); + + act(() => + ref.current!.openSideChatTab({ + responder: ada, + quote: "rc = fork()", + sourceMessageId: 7, + }), + ); + expect(await screen.findByTestId("side-chat-anchor")).toHaveTextContent("7"); + + // A brand-new side chat has sent its first turn: the message-level entry + // exists, but the tab still has no followupSessionId — the bound session + // only lives in the thread state the send wrote. + const key = anchor().getAttribute("data-question-key")!; + act(() => + controller!.updateThread(key, (prev) => ({ ...prev, sessionId: "thread-1" })), + ); + + act(() => ref.current!.clearSideChatSource("thread-1", 7)); + expect(anchor()).toHaveTextContent("none"); +}); + +it("keeps an anchor the learner moved after the detached one", async () => { + const ref = renderPanel(); + + act(() => ref.current!.openSideChatThread(threadRow(7))); + expect(await screen.findByTestId("side-chat-anchor")).toHaveTextContent("7"); + + act(() => + ref.current!.openSideChatTab({ + responder: ada, + quote: "execve()", + sourceMessageId: 9, + }), + ); + expect(anchor()).toHaveTextContent("9"); + + // The marker under message 7 was detached, but the tab already points at 9: + // the newest selection wins over the entry point that was removed. + act(() => ref.current!.clearSideChatSource("thread-1", 7)); + expect(anchor()).toHaveTextContent("9"); +});