diff --git a/.changeset/37487-citations-survive-reload.md b/.changeset/37487-citations-survive-reload.md new file mode 100644 index 00000000000..1545f19c023 --- /dev/null +++ b/.changeset/37487-citations-survive-reload.md @@ -0,0 +1,13 @@ +--- +'@object-ui/plugin-chatbot': patch +'@object-ui/app-shell': patch +--- + +fix(chatbot): an answer's record-citation chips are drawn again after a reload or when a conversation is reopened, and a navigation on the cited record no longer scrolls back to the cited heading + +Clause-②: yes (widening) +Metadata-protocol: none + +The history rebuild of the `/ai` page, the console's browser-side message cache and the `useObjectChat` store rebuild kept only an answer's charts, so a persisted `data-record-citations` part was not drawn again after a reload. All three now keep the data parts named by one allow-list, `STORED_ANSWER_DATA_PARTS` (charts and record citations), written by `storedAnswerParts` and read back by `storedAnswerData`. `@object-ui/plugin-chatbot` exports five new names: `storedAnswerParts`, `STORED_ANSWER_DATA_PARTS` and the types `StoredAnswerData` and `StoredAnswerPart` from the package root and from `@object-ui/plugin-chatbot/core`, and `storedAnswerData` from the package root. The citations list comes back as it was persisted: it is read through the same `RecordCitationsSchema` parse as a live part, so a list the schema refuses still draws nothing, and nothing is verified again. + +A record opened from a chip (`?section=ANCHOR`) scrolls to the cited heading once per click. A navigation that drops the history state, such as the command palette or a record form opened over the page and closed with Back, no longer counts as a new click, so the page stays where the reader scrolled it. diff --git a/content/docs/frontend/plugins/plugin-chatbot.mdx b/content/docs/frontend/plugins/plugin-chatbot.mdx index 6faad747a84..e1e5a6e6c75 100644 --- a/content/docs/frontend/plugins/plugin-chatbot.mdx +++ b/content/docs/frontend/plugins/plugin-chatbot.mdx @@ -493,7 +493,7 @@ By default, `ChatbotEnhanced` renders tool invocations as a compact agent activi In every mode, an answer whose data tools returned a `source` block ends with one collapsed "How this was computed" block: per tool, the object, the filter, the grouping, the aggregations, how many records the figures cover, and whether only the reader's visible records were read. An answer computed through `query_dataset` draws that tool's `provenance` block in the same place instead: the dataset, each metric by its label with its name beside it, the grouping, and the filter the question added (a dataset's own filter is never shown, so no added filter reads as such rather than as all records). It draws that block alone, never the rest of the tool payload. -When an answer carries a verified record-citations part (the `data-record-citations` part, `RecordCitationsSchema` in `@objectstack/spec/ai`), the console draws it beside that block as one chip per citation, each showing the quoted passage, and verifies nothing again on display; a part that does not parse draws nothing. The chips appear on a live answer whose stream carries the part; a conversation reloaded from history does not redraw them yet. A chip calls `onOpenRecord({ objectName, recordId, anchor })` with the citation's own record (the root record, even when the passage came from a related-list row) and the body section it cites. The console opens the record at `/apps/APP/OBJECT/record/ID?section=ANCHOR`: the record page scrolls to that heading of the body and marks it, opens a `textarea` body at the field, and opens at the top when the anchor names no heading any more. +When an answer carries a verified record-citations part (the `data-record-citations` part, `RecordCitationsSchema` in `@objectstack/spec/ai`), the console draws it beside that block as one chip per citation, each showing the quoted passage, and verifies nothing again on display; a part that does not parse draws nothing. The chips appear on a live answer whose stream carries the part, and are drawn again when the conversation is reloaded or reopened: the history rebuild, the display cache and the `useObjectChat` store rebuild keep the data parts one allow-list names (`STORED_ANSWER_DATA_PARTS`: charts and record citations), and read the list back through the same parse, verifying nothing again. A chip calls `onOpenRecord({ objectName, recordId, anchor })` with the citation's own record (the root record, even when the passage came from a related-list row) and the body section it cites. The console opens the record at `/apps/APP/OBJECT/record/ID?section=ANCHOR`: the record page scrolls to that heading of the body and marks it, opens a `textarea` body at the field, and opens at the top when the anchor names no heading any more. Each step is named by the locale pack's `chatbot.tool.` entry, a short sentence in the user's language ("List the existing objects"). A tool diff --git a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx index 3ec954cd3e3..86eafe6ee84 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -77,7 +77,7 @@ import { detectAuthoringVerdict, detectBuiltAppPackage, buildProgressFromDraftReview, - chartsFromParts, + storedAnswerData, // The authoring/honest -> runtime message seam (objectui#4399 / PR #4416), // consumed here one hop up from the plugin's own renderers (objectui#4437). // See `runtimeMessages` below for why this host calls it exactly once. @@ -411,7 +411,11 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C // persisted, each at the offset into `content` where its part sat. The // live stream's chart part is never stored, so this is the only way a // chart survives a reload. - const charts = message.role === 'assistant' ? chartsFromParts(message.parts) : undefined; + // objectstack#37487 — with every other kept data part + // (`STORED_ANSWER_DATA_PARTS`): the persisted, already-verified + // `data-record-citations` list, drawn again as chips, never re-verified. + const { charts, recordCitations } = + message.role === 'assistant' ? storedAnswerData(message.parts) : {}; return { id: message.id, @@ -420,6 +424,7 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C ...(toolInvocations.length > 0 ? { toolInvocations } : {}), ...(buildProgress ? { buildProgress } : {}), ...(charts ? { charts } : {}), + ...(recordCitations ? { recordCitations } : {}), }; }); } diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordCitationsReload-37487.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordCitationsReload-37487.test.tsx new file mode 100644 index 00000000000..37a20af28b9 --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordCitationsReload-37487.test.tsx @@ -0,0 +1,113 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37487 — an answer's verified record citations are drawn again + * after a reload, from either place a reload restores a conversation from: + * + * - Server history: rows → `toUIMessages` → `hydratedMessagesToChatMessages`. + * The persisted `data-record-citations` part is read back as it was stored, + * never verified again (ruling Q1 on objectstack#37144). + * - Cache fallback: the live map → `sanitizeChatMessagesForCache` → JSON → + * `hydratedMessagesToChatMessages`. + * + * Both rebuilds go through the one allow-list of kept data parts + * (`STORED_ANSWER_DATA_PARTS`). The reference is the chips the live answer + * draws; CONTROL: a part the contract refuses draws nothing on either path. + * The API-mode store rebuild is pinned in plugin-chatbot's + * `useObjectChat.recordCitationsReload-37487.test.tsx`. + */ +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import { RECORD_CITATIONS_PART_TYPE } from '@objectstack/spec/ai'; +import { ChatbotEnhanced, uiMessageToChatMessage } from '@object-ui/plugin-chatbot'; +import { hydratedMessagesToChatMessages } from '../AiChatPage'; +import { sanitizeChatMessagesForCache, toUIMessages } from '../../../hooks/useChatConversation'; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +const TEXT = 'The policy covers contractors.'; +const CITATIONS = [ + { object: 'policy', id: 'pol_7', context: 'policy_document', anchor: 'scope', quote: 'Applies to every contractor on site.' }, + { object: 'policy', id: 'pol_7', quote: 'Revision 3 published 2026-10-01' }, +]; +/** An alias the contract refuses by name (`section` for `anchor`). */ +const REFUSED = [{ ...CITATIONS[0], section: 'scope' }]; + +const citationsPart = (data: unknown) => ({ type: RECORD_CITATIONS_PART_TYPE, id: 'record-citations', data }); + +const liveAnswer = (data: unknown) => + uiMessageToChatMessage({ + id: 'a1', + role: 'assistant', + parts: [{ type: 'text', text: TEXT }, citationsPart(data)], + } as never); + +/** The stored turn, as the server persists the answer's parts. */ +const serverHistory = (data: unknown) => + toUIMessages([ + { id: 'u1', role: 'user', content: 'Who does the policy cover?' }, + { id: 'a1', role: 'assistant', content: [{ type: 'text', text: TEXT }, citationsPart(data)] }, + ] as never); + +const chipQuotes = () => screen.queryAllByTestId('record-citation').map((chip) => chip.textContent); + +function chipsOf(messages: unknown[]) { + render(); + const quotes = chipQuotes(); + cleanup(); + return quotes; +} + +const LIVE_CHIPS = () => chipsOf([liveAnswer(CITATIONS)]); + +describe('a reloaded answer draws its citation chips again (objectstack#37487)', () => { + it('the live answer draws two chips (the reference)', () => { + expect(LIVE_CHIPS()).toHaveLength(2); + }); + + it('server history: the persisted part draws the same chips, and nothing is fetched', () => { + const fetchSpy = vi.fn(async () => new Response('{}')); + vi.stubGlobal('fetch', fetchSpy); + const [, answer] = hydratedMessagesToChatMessages(serverHistory(CITATIONS)); + expect(answer.content).toBe(TEXT); + expect(answer.recordCitations).toEqual(CITATIONS); + expect(chipsOf([answer])).toEqual(LIVE_CHIPS()); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('server history CONTROL: a refused part draws nothing', () => { + const [, answer] = hydratedMessagesToChatMessages(serverHistory(REFUSED)); + expect(answer.content).toBe(TEXT); + expect(answer.recordCitations).toBeUndefined(); + expect(chipsOf([answer])).toEqual([]); + }); + + it('cache fallback: the live answer is cached and restored with the same chips', () => { + const cached = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([liveAnswer(CITATIONS)]))); + expect(cached[0].parts.map((p: { type: string }) => p.type)).toEqual(['text', RECORD_CITATIONS_PART_TYPE]); + const [restored] = hydratedMessagesToChatMessages(cached); + expect(restored.content).toBe(TEXT); + expect(chipsOf([restored])).toEqual(LIVE_CHIPS()); + }); + + it('cache fallback: a restored server answer is re-cached without losing its chips', () => { + const [, answer] = hydratedMessagesToChatMessages(serverHistory(CITATIONS)); + const cached = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([answer]))); + const [restored] = hydratedMessagesToChatMessages(cached); + expect(restored.recordCitations).toEqual(answer.recordCitations); + }); + + it('cache fallback CONTROL: a refused part is not cached and draws nothing', () => { + const live = liveAnswer(REFUSED); + expect(live.recordCitations).toBeUndefined(); + const cached = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([live]))); + expect(cached[0].parts.map((p: { type: string }) => p.type)).toEqual(['text']); + const [restored] = hydratedMessagesToChatMessages(cached); + expect(chipsOf([restored])).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useChatConversation.ts b/ui/packages/app-shell/src/hooks/useChatConversation.ts index d819a5b9dcb..15f033132fe 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.ts @@ -22,7 +22,8 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react // `@object-ui/plugin-chatbot` is already a static member of this package's // barrel closure (`index.ts` re-exports `AiChatPage`, which imports it), so // this adds no package edge and no eager bundle weight. -import { chartAnswerParts, detectPendingApproval } from '@object-ui/plugin-chatbot/core'; +import { detectPendingApproval, storedAnswerParts } from '@object-ui/plugin-chatbot/core'; +import type { StoredAnswerData } from '@object-ui/plugin-chatbot/core'; // Type-only, so it is erased and pulls no barrel closure into the hook. import type { AnswerSource } from '@object-ui/plugin-chatbot'; import { createAuthenticatedFetch } from '@object-ui/auth'; @@ -272,7 +273,9 @@ interface CacheableChatMessage { content?: string; toolInvocations?: CacheableChatToolInvocation[]; /** The answer's charts, each at its `textOffset` into `content`. */ - charts?: Parameters[1]; + charts?: StoredAnswerData['charts']; + /** objectstack#37487 — the answer's verified record citations, cached as persisted. */ + recordCitations?: StoredAnswerData['recordCitations']; } /** @@ -515,9 +518,14 @@ export function sanitizeChatMessagesForCache( // the stream's own chart part is never stored, and a tool part carries // no position, so this is the one record that keeps both the chart and // its place. `hydratedMessagesToChatMessages` reads them back. - const parts: HydratedUIMessagePart[] = chartAnswerParts( + // objectstack#37487 — with every other kept data part + // (`STORED_ANSWER_DATA_PARTS`): the verified citations list is cached as + // the `data-record-citations` part, so its chips survive a cache reload. + const parts: HydratedUIMessagePart[] = storedAnswerParts( message.content ?? '', - message.role === 'assistant' ? message.charts : undefined, + message.role === 'assistant' + ? { charts: message.charts, recordCitations: message.recordCitations } + : {}, ); if (message.role === 'assistant') { for (const tool of message.toolInvocations ?? []) { diff --git a/ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx index fa09c2c4e80..6c47e78a154 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx @@ -17,13 +17,19 @@ * marked), and the same chip clicked again (a fresh opened-state value) * scrolls again. CONTROL: a navigation that keeps the state (a tab switch) * does not scroll. + * - objectstack#37487 (S5): a navigation that DROPS the state is no new click + * either: a state-dropping `replace` (how `useUrlOverlay` opens the command + * palette) and a pushed form overlay followed by Back leave the page where + * it is. CONTROL: a new string value after them scrolls again. The same + * holds when the overlay redraws the page from scratch (a remount without + * the state): the section is marked again and nothing scrolls. */ import * as React from 'react'; import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, cleanup, within, act, waitFor } from '@testing-library/react'; -import { MemoryRouter, useNavigate, type NavigateFunction } from 'react-router-dom'; +import { MemoryRouter, useLocation, useNavigate, type NavigateFunction } from 'react-router-dom'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), @@ -127,20 +133,30 @@ function NavigateProbe({ onNavigate }: { onNavigate: (navigate: NavigateFunction return null; } -async function mount(search: string, content = BODY) { +/** Draws the page again from scratch whenever the query string changes, the way an overlay redraw can. */ +function RemountOnSearch({ children }: { children: (key: string) => React.ReactElement }) { + const { search } = useLocation(); + return children(search); +} + +async function mount(search: string, content = BODY, opts: { remountOnSearch?: boolean } = {}) { + const view = (key?: string) => ( + {}} + objectNameOverride={OBJECT_NAME} + recordIdOverride={RECORD_ID} + /> + ); const rendered = render( - {}} - objectNameOverride={OBJECT_NAME} - recordIdOverride={RECORD_ID} - /> + {opts.remountOnSearch ? {(key) => view(key)} : view()} @@ -167,8 +183,10 @@ beforeEach(() => { ); }); -afterEach(() => { +afterEach(async () => { cleanup(); + // The page forgets the section it opened once it has stayed unmounted (objectstack#37487 S5). + await new Promise((resolve) => setTimeout(resolve, 0)); HTMLElement.prototype.scrollIntoView = originalScroll; vi.unstubAllGlobals(); vi.clearAllMocks(); @@ -209,6 +227,7 @@ describe('a record opened at a cited section (objectstack#37365)', () => { expect(scrolled).toEqual([]); expect(marked(stale.container)).toHaveLength(0); cleanup(); + await new Promise((resolve) => setTimeout(resolve, 0)); const live = await mount('?section=intro'); await waitFor(() => expect(marked(live.container)).toHaveLength(1), { timeout: 4000 }); expect(marked(live.container)[0].textContent).toBe('Intro'); @@ -226,6 +245,7 @@ describe('a record opened at a cited section (objectstack#37365)', () => { await waitFor(() => expect(scrolled).toEqual([field()]), { timeout: 7000 }); expect(marked(dup.container)).toHaveLength(0); cleanup(); + await new Promise((resolve) => setTimeout(resolve, 0)); scrolled = []; const control = await mount('?section=scope', SETEXT_CONTROL); await waitFor(() => expect(marked(control.container)).toHaveLength(1), { timeout: 4000 }); @@ -260,4 +280,63 @@ describe('a record opened at a cited section (objectstack#37365)', () => { expect(scrolled).toEqual([first, second, second]); expect(marked(container)).toEqual([second]); }); + + it('a navigation dropping the state does not scroll back (objectstack#37487 S5); CONTROL: a new click after it does', async () => { + const { container } = await mount('?section=scope'); + await waitFor(() => expect(marked(container)).toHaveLength(1), { timeout: 4000 }); + const [first, second] = headingsNamed(container, 'Scope'); + const path = `/apps/compliance/${OBJECT_NAME}/record/${RECORD_ID}`; + await act(async () => { + navigateTo!(`${path}?section=scope-2`, { state: { [RECORD_SECTION_OPENED_STATE]: 'click-1' } }); + }); + await waitFor(() => expect(scrolled).toEqual([first, second]), { timeout: 4000 }); + // A state-dropping replace: an overlay param written over the URL with no state. + await act(async () => { + navigateTo!(`${path}?section=scope-2&palette=1`, { replace: true }); + }); + await act(async () => {}); + expect(scrolled).toEqual([first, second]); + // A pushed overlay (no state), then Back to the entry the click wrote. + await act(async () => { + navigateTo!(`${path}?section=scope-2&form=edit`); + }); + await act(async () => {}); + await act(async () => { + navigateTo!(-1); + }); + await act(async () => {}); + expect(scrolled).toEqual([first, second]); + expect(marked(container)).toEqual([second]); + // CONTROL: a new click after them still opens the section. + await act(async () => { + navigateTo!(`${path}?section=scope-2`, { state: { [RECORD_SECTION_OPENED_STATE]: 'click-2' } }); + }); + await waitFor(() => expect(scrolled).toEqual([first, second, second]), { timeout: 4000 }); + }); + + it('a remount by a pushed overlay, and Back, marks the section again and does not scroll (objectstack#37487 S5); CONTROL: a new click scrolls', async () => { + const { container } = await mount('?section=scope', BODY, { remountOnSearch: true }); + await waitFor(() => expect(marked(container)).toHaveLength(1), { timeout: 4000 }); + const path = `/apps/compliance/${OBJECT_NAME}/record/${RECORD_ID}`; + await act(async () => { + navigateTo!(`${path}?section=scope-2`, { state: { [RECORD_SECTION_OPENED_STATE]: 'click-1' } }); + }); + await waitFor(() => expect(scrolled).toHaveLength(2), { timeout: 4000 }); + // The pushed form redraws the page from scratch, without the click's state. + await act(async () => { + navigateTo!(`${path}?section=scope-2&form=edit`); + }); + const second = () => headingsNamed(container, 'Scope')[1]; + await waitFor(() => expect(marked(container)).toEqual([second()]), { timeout: 4000 }); + await act(async () => { + navigateTo!(-1); + }); + await waitFor(() => expect(marked(container)).toEqual([second()]), { timeout: 4000 }); + expect(scrolled).toHaveLength(2); + // CONTROL: a new click after them scrolls. + await act(async () => { + navigateTo!(`${path}?section=scope-2`, { state: { [RECORD_SECTION_OPENED_STATE]: 'click-2' } }); + }); + await waitFor(() => expect(scrolled).toHaveLength(3), { timeout: 4000 }); + }); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 8f3ed00cd5f..a937419169e 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -914,6 +914,25 @@ function ApprovalGroupBeacon({ onHosted }: { onHosted: (update: (n: number) => n /** The reader's arrangement is not written while the design mode's tab editor previews the default (objectstack#36499, objectstack#36737). */ const ignoreArrangementChange = (): void => {}; +/** + * objectstack#37487 (S5) — the cited section the record page last opened, as + * `{ target: RECORD\nANCHOR, opened: CLICK }`, kept beside the component so it + * outlives a remount or a swapped page root: a record-form overlay pushed over + * the page (and Back after it) redraws the page without the click's history + * state, and that redraw is no new click. It is dropped once no record page is + * mounted any more, so a later visit to the same link opens its section again. + */ +let lastCitedSectionOpen: { target: string; opened: string } | null = null; +let mountedRecordPages = 0; + +/** Whether a cited-section open is a new one, and record it when it is. */ +function claimCitedSectionOpen(target: string, opened: string): boolean { + const last = lastCitedSectionOpen; + if (last && last.target === target && (opened === '' || opened === last.opened)) return false; + lastCitedSectionOpen = { target, opened }; + return true; +} + export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverride, recordIdOverride, embedded }: RecordDetailViewProps) { const params = useParams<{ @@ -4947,8 +4966,18 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // fresh `RECORD_SECTION_OPENED_STATE`, so the same chip clicked again opens // the section again, while a tab switch (which keeps the state) does not. // Opening another section takes the earlier mark off. + // objectstack#37487 (S5) — the click is the last string value the state + // carried, kept until a NEW one arrives: a navigation that drops the history + // state (an overlay's `replace`, a pushed form and Back) is no new click, so + // it neither re-runs the effect nor scrolls the page back to the heading; + // `claimCitedSectionOpen` carries the same judgement across a redraw of the + // page itself (the record-form overlay remounts it without the state). const sectionAnchor = tabSearchParams.get(RECORD_SECTION_PARAM) || null; - const sectionOpened = (location.state as Record | null)?.[RECORD_SECTION_OPENED_STATE]; + const sectionOpenedState = (location.state as Record | null)?.[RECORD_SECTION_OPENED_STATE]; + const [sectionOpened, setSectionOpened] = useState(''); + if (typeof sectionOpenedState === 'string' && sectionOpenedState !== sectionOpened) { + setSectionOpened(sectionOpenedState); + } const citedSectionCandidates = useMemo( () => holdsRouteRecord @@ -4958,14 +4987,32 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri ); const citedSectionKey = citedSectionCandidates.length > 0 - ? `${routeRecordKey}\n${sectionAnchor}\n${typeof sectionOpened === 'string' ? sectionOpened : ''}` + ? `${routeRecordKey}\n${sectionAnchor}\n${sectionOpened}` : null; const citedSectionCandidatesRef = useRef(citedSectionCandidates); citedSectionCandidatesRef.current = citedSectionCandidates; useEffect(() => { if (!pageRootEl || !citedSectionKey) return undefined; - return focusRecordSection(pageRootEl, citedSectionCandidatesRef.current); + // Claimed when the page would move, so a re-run before that does not spend + // it; a redraw at a section already opened marks it again and scrolls nothing. + const target = `${routeRecordKey}\n${sectionAnchor}`; + const opened = sectionOpened; + return focusRecordSection(pageRootEl, citedSectionCandidatesRef.current, undefined, () => + claimCitedSectionOpen(target, opened), + ); + // The key spells the record, anchor and click; the effect reads them through it. + // eslint-disable-next-line react-hooks/exhaustive-deps }, [pageRootEl, citedSectionKey]); + useEffect(() => { + mountedRecordPages += 1; + return () => { + mountedRecordPages -= 1; + // A remount mounts the next page in the same commit, before this runs. + setTimeout(() => { + if (mountedRecordPages === 0) lastCitedSectionOpen = null; + }, 0); + }; + }, []); const landedRecordName = holdsRouteRecord && !recordTitle && objectDef ? getRecordDisplayName(objectDef, readablePageRecord) : undefined; diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.ts b/ui/packages/app-shell/src/views/recordSectionAnchor.ts index 20eec4db25e..f7629ec5c42 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.ts +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.ts @@ -164,7 +164,7 @@ export function markSection(heading: HTMLElement): () => void { }; } -function scrollTo(el: HTMLElement): void { +function scrollIntoStart(el: HTMLElement): void { if (typeof el.scrollIntoView === 'function') el.scrollIntoView({ block: 'start' }); } @@ -175,12 +175,19 @@ function scrollTo(el: HTMLElement): void { * no candidate, or no candidate field drawn by then, nothing moves. Answers * the cleanup, which also takes the mark off: a page opened at another * section, or at the same one again, marks only the section it opens. + * `mayScroll` is asked at the moment the page would move; when it answers + * false the heading is still marked and nothing moves: the page is redrawn at + * a section it already opened (objectstack#37487 S5). */ export function focusRecordSection( root: HTMLElement, candidates: readonly SectionCandidate[], settleMs: number = RECORD_SECTION_SETTLE_MS, + mayScroll: () => boolean = () => true, ): () => void { + const scrollTo = (el: HTMLElement): void => { + if (mayScroll()) scrollIntoStart(el); + }; if (candidates.length === 0) return () => {}; let done = false; let observer: MutationObserver | undefined; diff --git a/ui/packages/plugin-chatbot/README.md b/ui/packages/plugin-chatbot/README.md index 26859066be0..fa72a3001b9 100644 --- a/ui/packages/plugin-chatbot/README.md +++ b/ui/packages/plugin-chatbot/README.md @@ -474,8 +474,11 @@ When an answer carries a verified record-citations part (the `data-record-citations` part, `RecordCitationsSchema` in `@objectstack/spec/ai`), the console draws it beside that block, one chip per citation showing the quoted passage, and verifies nothing again; a part that does not parse draws nothing. -The chips appear on a live answer whose stream carries the part; a conversation -reloaded from history does not redraw them yet. A chip calls +The chips appear on a live answer whose stream carries the part, and are drawn +again when the conversation is reloaded or reopened: the history rebuild, the +display cache and the `useObjectChat` store rebuild keep the data parts one +allow-list names (`STORED_ANSWER_DATA_PARTS`: charts and record citations). A +chip calls `onOpenRecord({ objectName, recordId, anchor })`, and the console opens the record at the cited body section (`?section=ANCHOR`). diff --git a/ui/packages/plugin-chatbot/src/__tests__/useObjectChat.recordCitationsReload-37487.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/useObjectChat.recordCitationsReload-37487.test.tsx new file mode 100644 index 00000000000..b9e755bd5d7 --- /dev/null +++ b/ui/packages/plugin-chatbot/src/__tests__/useObjectChat.recordCitationsReload-37487.test.tsx @@ -0,0 +1,107 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37487 — an answer's verified record citations survive API mode's + * store rebuild. + * + * app-shell hands `useObjectChat` the hydrated thread with each answer's + * `recordCitations` lifted off its stored `data-record-citations` part. API + * mode rebuilds each message into the AI SDK store and maps the store back on + * every render, so the list has to go back in as that part, through the one + * allow-list of kept data parts (`STORED_ANSWER_DATA_PARTS`), for its chips to + * draw again. The mock stands in for the store, as in + * `useObjectChat.persistedChart-25908.test.tsx`. + * + * - The restored answer draws the same chips the live one drew. + * - CONTROL: a list the contract refuses draws nothing: the store part is read + * back through the same parse as a live one, so the rebuild is no way round it. + * - The allow-list's citations entry is the spec's part type. + */ +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, renderHook, screen } from '@testing-library/react'; +import { RECORD_CITATIONS_PART_TYPE } from '@objectstack/spec/ai'; +import { ChatbotEnhanced } from '../ChatbotEnhanced'; +import { toRuntimeMessages } from '../chatMessageAdapter'; +import { STORED_ANSWER_DATA_PARTS, uiMessageToChatMessage } from '../mapMessages'; +import { useObjectChat, type UseObjectChatOptions } from '../useObjectChat'; + +vi.mock('@ai-sdk/react', () => ({ + useChat: (opts: { messages?: unknown[] }) => ({ + messages: opts.messages ?? [], + status: 'ready', + error: undefined, + sendMessage: vi.fn(), + regenerate: vi.fn(), + stop: vi.fn(), + setMessages: vi.fn(), + }), +})); + +afterEach(cleanup); + +const API = 'https://example.test/api/v1/ai/agents/ask/chat'; +const TEXT = 'The policy covers contractors.'; + +const CITATIONS = [ + { object: 'policy', id: 'pol_7', context: 'policy_document', anchor: 'scope', quote: 'Applies to every contractor on site.' }, + { object: 'policy', id: 'pol_7', quote: 'Revision 3 published 2026-10-01' }, +]; + +/** The chips the live stream draws: the reference a restored answer must equal. */ +const LIVE = uiMessageToChatMessage({ + id: 'a1', + role: 'assistant', + parts: [ + { type: 'text', text: TEXT }, + { type: RECORD_CITATIONS_PART_TYPE, id: 'record-citations', data: CITATIONS }, + ], +} as never); + +const hydrated = (recordCitations: unknown[]): NonNullable => [ + { id: 'u1', role: 'user', content: 'Who does the policy cover?' }, + { id: 'a1', role: 'assistant', content: TEXT, recordCitations } as never, +]; + +function restore(recordCitations: unknown[]) { + const { result } = renderHook(() => + useObjectChat({ api: API, conversationId: 'c1', initialMessages: hydrated(recordCitations) }), + ); + return result.current.messages; +} + +const chipQuotes = () => screen.queryAllByTestId('record-citation').map((chip) => chip.textContent); + +describe('restored citations survive the API-mode store (objectstack#37487)', () => { + it('the allow-list names the spec part type', () => { + expect(STORED_ANSWER_DATA_PARTS.recordCitations).toBe(RECORD_CITATIONS_PART_TYPE); + expect(STORED_ANSWER_DATA_PARTS.charts).toBe('data-chart'); + }); + + it('the restored answer draws the chips the live one drew', () => { + render(); + const live = chipQuotes(); + expect(live).toHaveLength(2); + cleanup(); + const messages = restore(CITATIONS); + expect(messages[1].content).toBe(TEXT); + expect(messages[1].recordCitations).toEqual(LIVE.recordCitations); + render(); + expect(chipQuotes()).toEqual(live); + }); + + it('CONTROL: a list the contract refuses draws nothing', () => { + const messages = restore([{ ...CITATIONS[0], section: 'scope' }]); + expect(messages[1].content).toBe(TEXT); + expect(messages[1].recordCitations).toBeUndefined(); + render(); + expect(chipQuotes()).toEqual([]); + }); +}); diff --git a/ui/packages/plugin-chatbot/src/core.ts b/ui/packages/plugin-chatbot/src/core.ts index 48126bc5bab..5548806fc7b 100644 --- a/ui/packages/plugin-chatbot/src/core.ts +++ b/ui/packages/plugin-chatbot/src/core.ts @@ -58,6 +58,12 @@ export { detectPendingApproval } from './toolResultParsers'; export { chartsFromParts, chartAnswerParts } from './toolResultParsers'; export type { ChartAnswerPart } from './toolResultParsers'; +// objectstack#37487 — the one allow-list of the data parts a stored answer +// keeps (charts + verified record citations), and its writer, which the +// message cache shares with the `useObjectChat` store rebuild. +export { storedAnswerParts, STORED_ANSWER_DATA_PARTS } from './toolResultParsers'; +export type { StoredAnswerData, StoredAnswerPart } from './toolResultParsers'; + // objectstack#30223 — the HITL continuation marker. The chat transcript, the // conversation list preview and the conversation-language probe all skip a // user turn that `useHitlInChat` composed for the model. diff --git a/ui/packages/plugin-chatbot/src/index.tsx b/ui/packages/plugin-chatbot/src/index.tsx index bc49ffc9b91..a2fff24bab8 100644 --- a/ui/packages/plugin-chatbot/src/index.tsx +++ b/ui/packages/plugin-chatbot/src/index.tsx @@ -361,9 +361,14 @@ export { buildProgressFromDraftReview, chartsFromParts, chartAnswerParts, + storedAnswerParts, + storedAnswerData, + STORED_ANSWER_DATA_PARTS, } from './mapMessages'; export type { ChartAnswerPart, + StoredAnswerData, + StoredAnswerPart, DraftReview, ProposedPlan, BuilderHandoff, diff --git a/ui/packages/plugin-chatbot/src/mapMessages.ts b/ui/packages/plugin-chatbot/src/mapMessages.ts index 0354c5b73c2..e02aaa1170a 100644 --- a/ui/packages/plugin-chatbot/src/mapMessages.ts +++ b/ui/packages/plugin-chatbot/src/mapMessages.ts @@ -28,7 +28,7 @@ import { RecordCitationsSchema, } from '@objectstack/spec/ai'; import type { ChatbotEnhancedMessage as ChatMessage, ChatbotEnhancedToolInvocation as ChatToolInvocation, ChatSource, ChatBuildProgress, ChatBlueprintProgress } from './ChatbotEnhanced'; -import { detectPendingApproval, extractCharts, parseResultEnvelope, type AnyPart } from './toolResultParsers'; +import { chartsFromParts, detectPendingApproval, extractCharts, parseResultEnvelope, type AnyPart } from './toolResultParsers'; // The parsers the eager `/core` entry shares live in `./toolResultParsers`, so // this module (and the spec schema it parses with) loads only with the chat. @@ -37,9 +37,11 @@ export { detectPendingApproval, chartsFromParts, chartAnswerParts, + storedAnswerParts, + STORED_ANSWER_DATA_PARTS, VISUALIZE_DATA_TOOL, } from './toolResultParsers'; -export type { ChartAnswerPart } from './toolResultParsers'; +export type { ChartAnswerPart, StoredAnswerData, StoredAnswerPart } from './toolResultParsers'; interface AnyUIMessage { @@ -858,6 +860,22 @@ export function extractRecordCitations(parts: readonly AnyPart[]): RecordCitatio return parsed.success && parsed.data.length > 0 ? parsed.data : undefined; } +/** + * objectstack#37487 — the reading half of `STORED_ANSWER_DATA_PARTS`: every + * kept data part of a stored message, read back into the message fields the + * chat draws. A history or cache rebuild calls this once; a part added to the + * allow-list is read here, beside its write in `storedAnswerParts`. The citations list is taken + * as persisted (ruling Q1): parsed through the contract, never verified again. + */ +export function storedAnswerData(parts: readonly AnyPart[]): { + charts?: ChatMessage['charts']; + recordCitations?: RecordCitationParsed[]; +} { + const charts = chartsFromParts(parts); + const recordCitations = extractRecordCitations(parts); + return { ...(charts ? { charts } : {}), ...(recordCitations ? { recordCitations } : {}) }; +} + /** * cloud#3565 — 「清理示例数据」: the chat's `remove_sample_data` queues a HITL * pending action and answers `{ status:'pending_approval', pendingActionId, diff --git a/ui/packages/plugin-chatbot/src/toolResultParsers.ts b/ui/packages/plugin-chatbot/src/toolResultParsers.ts index a5f650e0551..9c667345034 100644 --- a/ui/packages/plugin-chatbot/src/toolResultParsers.ts +++ b/ui/packages/plugin-chatbot/src/toolResultParsers.ts @@ -302,3 +302,65 @@ export function chartAnswerParts( if (cursor < content.length) parts.push({ type: 'text', text: content.slice(cursor) }); return parts; } + +/** + * objectstack#37487 — the ONE allow-list of the data parts a stored answer + * keeps when a rebuild turns it back into parts: the app-shell message cache + * (`sanitizeChatMessagesForCache`) and the `useObjectChat` `initialMessages` + * store rebuild both write through {@link storedAnswerParts}, and app-shell's + * history rebuild reads the same fields back (`storedAnswerData` in + * `./mapMessages`). Every other data part a live stream gave is transient + * (progress frames, build trees) and is not kept. Keyed by the message field + * that carries the part's payload between rebuilds. + * + * The table names the kept parts; it does not drive the code. A further kept + * part takes three edits: an entry here, its write in + * {@link storedAnswerParts}, and its read in `storedAnswerData`. + * + * `recordCitations` is spelled here rather than imported so this eager module + * stays free of `@objectstack/spec/ai` and the schemas it loads; + * `useObjectChat.recordCitationsReload-37487.test.tsx` pins it to the spec's + * `RECORD_CITATIONS_PART_TYPE`. + */ +export const STORED_ANSWER_DATA_PARTS = { + /** Positional: written between the text runs at each chart's `textOffset`. */ + charts: 'data-chart', + /** + * The answer's verified record citations (ADR-0160 D9), kept as the list + * that was verified when the answer was produced and never verified again + * (ruling Q1 on objectstack#37144). Not positional: it follows the text. + */ + recordCitations: 'data-record-citations', +} as const; + +/** The part id the live stream gives the citations part, so a rebuilt store holds one part as the stream did. */ +const RECORD_CITATIONS_PART_ID = 'record-citations'; + +/** The payloads {@link storedAnswerParts} keeps, read off a rendered message. */ +export interface StoredAnswerData { + charts?: readonly ChatChart[]; + /** The already-parsed list the message carries; written as it is. */ + recordCitations?: readonly unknown[]; +} + +/** One part {@link storedAnswerParts} writes. */ +export type StoredAnswerPart = + | ChartAnswerPart + | { type: typeof STORED_ANSWER_DATA_PARTS.recordCitations; id: string; data: unknown[] }; + +/** + * An answer's text with every data part {@link STORED_ANSWER_DATA_PARTS} + * keeps: the charts at their offsets ({@link chartAnswerParts}), then the + * citations list. An empty or absent list writes no part. + */ +export function storedAnswerParts(content: string, data: StoredAnswerData): StoredAnswerPart[] { + const parts: StoredAnswerPart[] = chartAnswerParts(content, data.charts); + if (data.recordCitations && data.recordCitations.length > 0) { + parts.push({ + type: STORED_ANSWER_DATA_PARTS.recordCitations, + id: RECORD_CITATIONS_PART_ID, + data: [...data.recordCitations], + }); + } + return parts; +} diff --git a/ui/packages/plugin-chatbot/src/useObjectChat.ts b/ui/packages/plugin-chatbot/src/useObjectChat.ts index 928647ee9ba..e5a15961113 100644 --- a/ui/packages/plugin-chatbot/src/useObjectChat.ts +++ b/ui/packages/plugin-chatbot/src/useObjectChat.ts @@ -12,7 +12,7 @@ import { useChat } from '@ai-sdk/react'; import { DefaultChatTransport } from 'ai'; import { generateUniqueId } from './utils'; import { emitAiUsageRefresh } from './aiUsageEvents'; -import { chartAnswerParts, uiMessagesToChatMessages } from './mapMessages'; +import { storedAnswerParts, uiMessagesToChatMessages } from './mapMessages'; import { toRuntimeRole, toRuntimeTimestamp } from './chatMessageAdapter'; import type { SeamChatMessage, SeamToolInvocation } from './chatMessageAdapter'; @@ -790,7 +790,13 @@ export function useObjectChat(options: UseObjectChatOptions = {}): UseObjectChat // objectstack#25908 — a hydrated answer's charts go back into the store // as the `data-chart` parts the live stream gave, between the text runs // they sat between, so `mapMessages` reads them at the same offsets. - const parts: SdkChatMessage['parts'] = chartAnswerParts(normalized.content, msg.charts); + // objectstack#37487 — with every other kept data part + // (`STORED_ANSWER_DATA_PARTS`): the verified citations list goes back + // as the `data-record-citations` part, so its chips draw again. + const parts: SdkChatMessage['parts'] = storedAnswerParts(normalized.content, { + charts: msg.charts, + recordCitations: msg.recordCitations, + }); if (msg.reasoning) { parts.push({ type: 'reasoning', text: msg.reasoning }); }