Skip to content

Commit ebe35f4

Browse files
fix(chatbot): redraw record-citation chips after a reload; keep the cited-section scroll to new clicks (#37539)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg6tp7ABZkjrcw3mEU2eHGpS)_ Fixes #37487 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:使用应用内 AI 的用户,刷新页面或重新打开对话后,回答下方的“引自记录”引用条仍然显示;从引用条打开记录后,再打开命令面板或编辑表单、返回,页面不再被拉回被引的那一节。 - 为什么做:记录 AI 问询专题的引用条跟进卡,原先引用条只在回答当场可见,刷新就消失,无法回头核对出处。 - 出错会怎样:引用条刷新后不显示,或页面多滚一次;记录和对话数据不受影响,撤回本次合并即可恢复原样。 - 要你做什么:无。 ## What changes Governing text: ruling Q1 on #37144 (draw the persisted, already-verified list; never verify it again); PR #37485 (merged 276174a) and its scope notes on #37487 (S4 on the card, S5 in 7190147175). - **One allow-list of kept data parts** (`plugin-chatbot/src/toolResultParsers.ts`): `STORED_ANSWER_DATA_PARTS` names the data parts a stored answer keeps through a rebuild, keyed by the message field that carries each between rebuilds: `charts` (`data-chart`, positional) and `recordCitations` (`data-record-citations`). `storedAnswerParts(content, data)` writes them (the charts through the existing `chartAnswerParts`, then the citations list as one part with the stream's part id). It stays in the eager `/core` closure, so the part type is spelled there, not imported from `@objectstack/spec/ai`; a test pins it to `RECORD_CITATIONS_PART_TYPE`. - **Reader** (`plugin-chatbot/src/mapMessages.ts`): `storedAnswerData(parts)` reads every kept part back (`chartsFromParts` + `extractRecordCitations`, the same `RecordCitationsSchema` parse a live part goes through). A refused list is no list. - **The three rebuilds** now go through those two: the `/ai` history rebuild `hydratedMessagesToChatMessages` (`app-shell/src/console/ai/AiChatPage.tsx`, reader), the message cache `sanitizeChatMessagesForCache` (`app-shell/src/hooks/useChatConversation.ts`, writer; `CacheableChatMessage` gains `recordCitations`), and the `useObjectChat` `initialMessages` store rebuild (`plugin-chatbot/src/useObjectChat.ts`, writer). The table names the kept parts; a further kept part takes three edits (the entry, its write in `storedAnswerParts`, its read in `storedAnswerData`). - **S5** (`app-shell/src/views/RecordDetailView.tsx`, `recordSectionAnchor.ts`): the cited-section effect was keyed on the opened-state value or `''`, so any navigation that dropped history state re-ran it and scrolled back. Two parts: - within one mount, the key holds the last string value the state carried, replaced only when a new string arrives (state adjusted during render); - the booted console showed the record-form overlay (`?form=`) **remounts** the record page without the state, so a component-local memory is not enough. The page now keeps the section it last opened beside the component (`claimCitedSectionOpen`, `{ target: RECORD+ANCHOR, opened: CLICK }`), claimed at the moment the page would move (`focusRecordSection` gains an optional `mayScroll` callback, asked right before scrolling, so an effect re-run before that does not spend it). A redraw at a section already opened marks it again and scrolls nothing. The memory is dropped once no record page has stayed mounted (a zero-delay check after unmount), so a later visit to the same link opens its section again. - Exports (Clause-②: yes (widening), per seat record 7193217253 S1; level stays patch): `storedAnswerParts`, `STORED_ANSWER_DATA_PARTS` and the types `StoredAnswerData`, `StoredAnswerPart` from `@object-ui/plugin-chatbot/core` and the root; `storedAnswerData` from the root. Named in the changeset. - Docs: the sentence "a conversation reloaded from history does not redraw them yet" in `content/docs/frontend/plugins/plugin-chatbot.mdx` and `ui/packages/plugin-chatbot/README.md` was made false by this change and is rewritten. Changeset `.changeset/37487-citations-survive-reload.md` (patch, `@object-ui/plugin-chatbot`, `@object-ui/app-shell`). Read first, by risk: 1. `ui/packages/plugin-chatbot/src/toolResultParsers.ts`: `STORED_ANSWER_DATA_PARTS` and `storedAnswerParts`. 2. `ui/packages/app-shell/src/views/RecordDetailView.tsx`: `claimCitedSectionOpen` (module level, above the component) and the `sectionOpened` state and effect beside `holdsRouteRecord`. 3. `ui/packages/app-shell/src/hooks/useChatConversation.ts`: `sanitizeChatMessagesForCache`. ## Tests - `app-shell/src/console/ai/__tests__/AiChatPage.recordCitationsReload-37487.test.tsx` (6): server history and cache fallback each restore the chips the live answer draws (same quotes, same order; nothing fetched); a restored server answer re-caches with its list; CONTROL on both paths: a refused part (an alias key) draws nothing and is not cached. - `plugin-chatbot/src/__tests__/useObjectChat.recordCitationsReload-37487.test.tsx` (3): the `initialMessages` store rebuild draws the live chips; CONTROL: a refused list draws nothing (the store part is re-parsed, so the rebuild is no way round the contract); the allow-list entry equals the spec part type. - `app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx` (+2, 8 total): after a chip click, a state-dropping `replace` (the `useUrlOverlay` shape) and a pushed overlay followed by Back do not scroll; a pushed overlay that **remounts** the page, and Back, marks the section again and does not scroll; CONTROL in both: a new click after them scrolls. `afterEach` waits one macrotask after `cleanup()` so the page's memory is dropped between cases. `recordSectionAnchor.test.tsx` unchanged, 18/18. - Ablation, shared allow-list: writer and reader of the citations entry disabled → the three positive path tests fail (3 failed, 6 passed), restored → 9/9. Ablation, S5 in-mount: the key read back off the state as before → that test fails (1 failed, 6 passed). Ablation, S5 remount: `claimCitedSectionOpen` always claims → the remount test fails (1 failed, 7 passed); restored → 8/8. ## Acceptance notes - N6 / N7 of 7190147175 (the count check, and the empty-reading case opening the field only after the 4 s settle) live in `recordSectionAnchor.ts`'s `locateSection` and are not one line each; they stay open and are carried by #37562. - On a phone, a chip in the dock sheet opens the record underneath and the sheet stays open over it, so the cited heading is scrolled and marked but hidden until the reader dismisses the sheet. Present since #37485, not changed here; carried by #37556. - On this boot `/ai/ask/CONVERSATION` resolves into the dock over the app's home page, so the dock and `/ai` were one surface in the browser check. - N1 of 7193217253: the allow-list jsdoc now says it names the kept parts without driving the code, and cites the test file that pins it. ## Verification - Local: `pnpm run type-check` in `ui/packages/plugin-chatbot` and `ui/packages/app-shell`, exit 0. The local whole-suite run of both packages (`vitest run packages/plugin-chatbot/ packages/app-shell/`) was stopped after 61 min with one failure, which was my own ablation edit made while it ran; the narrowing is declared, and CI's `Test UI` (all shards) is green on e2833f9. Rework head 40bb8ee (changeset, jsdoc only): CI check-runs 46 success, 10 skipped before this body edit; the PR-body guards rerun on the edit. - Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/console/ai/__tests__/AiChatPage.recordCitationsReload-37487.test.tsx packages/plugin-chatbot/src/__tests__/useObjectChat.recordCitationsReload-37487.test.tsx`, expected 9 passed. - S4 booted-console check, done on head 039bbc3 (the later head e2833f9 changes one test file only). Showcase app (`objectstack dev --seed-admin`) with the `ui/` console dev server pointed at it, driven by Playwright at 1360x900 and as an iPhone 13. **Injected, not produced**: no producer emits the part before cloud 10c, so the run serves the conversation-history read (`GET /api/v1/ai/conversations/ID`) with an answer carrying a `data-record-citations` part, and, because this boot has no model, serves a one-agent catalog (`GET /api/v1/ai/agents`) so the assistant shows. The cited record is a Field Zoo record whose `markdown`, `html` and `richtext` bodies each hold a cited heading below several screens of text. - Chips drawn: 3 (the three quotes), desktop and phone. After a page reload: the same 3, same order. - A chip click opens `/apps/com.example.showcase/showcase_field_zoo/record/ID?section=ANCHOR`; the cited heading is the one marked and sits just under the sticky record header (top 89 px desktop, 45 px phone): `contractor-scope` (markdown), `html-retention` (html), `rich-escalation` (richtext). - Refused part (an alias key): 0 chips. - S5: scrolled back to the top of the record, opening the command palette (`?palette=1`, replace) and closing it leaves the page there; opening the record form (`?form=ID`, push) and Back leaves the page there (before the remount fix it scrolled back, which is how the remount was found). A probe on `scrollIntoView` records no call. - Screenshots: `objectstack-seat5/ai-36996/shots-37487/` in the project files (9 images plus the script). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CY3qzEGtLEnwjFyRXG --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CY3qzEGtLEnwjFyRXG)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CY3qzEGtLEnwjFyRXG --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a6e258c commit ebe35f4

15 files changed

Lines changed: 506 additions & 27 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@object-ui/plugin-chatbot': patch
3+
'@object-ui/app-shell': patch
4+
---
5+
6+
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
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
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.
12+
13+
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.

‎content/docs/frontend/plugins/plugin-chatbot.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ By default, `ChatbotEnhanced` renders tool invocations as a compact agent activi
495495

496496
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.
497497

498-
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.
498+
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.
499499

500500
Each step is named by the locale pack's `chatbot.tool.<tool_name>` entry, a
501501
short sentence in the user's language ("List the existing objects"). A tool

‎ui/packages/app-shell/src/console/ai/AiChatPage.tsx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ import {
7777
detectAuthoringVerdict,
7878
detectBuiltAppPackage,
7979
buildProgressFromDraftReview,
80-
chartsFromParts,
80+
storedAnswerData,
8181
// The authoring/honest -> runtime message seam (objectui#4399 / PR #4416),
8282
// consumed here one hop up from the plugin's own renderers (objectui#4437).
8383
// See `runtimeMessages` below for why this host calls it exactly once.
@@ -411,7 +411,11 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C
411411
// persisted, each at the offset into `content` where its part sat. The
412412
// live stream's chart part is never stored, so this is the only way a
413413
// chart survives a reload.
414-
const charts = message.role === 'assistant' ? chartsFromParts(message.parts) : undefined;
414+
// objectstack#37487 — with every other kept data part
415+
// (`STORED_ANSWER_DATA_PARTS`): the persisted, already-verified
416+
// `data-record-citations` list, drawn again as chips, never re-verified.
417+
const { charts, recordCitations } =
418+
message.role === 'assistant' ? storedAnswerData(message.parts) : {};
415419

416420
return {
417421
id: message.id,
@@ -420,6 +424,7 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C
420424
...(toolInvocations.length > 0 ? { toolInvocations } : {}),
421425
...(buildProgress ? { buildProgress } : {}),
422426
...(charts ? { charts } : {}),
427+
...(recordCitations ? { recordCitations } : {}),
423428
};
424429
});
425430
}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#37487 — an answer's verified record citations are drawn again
5+
* after a reload, from either place a reload restores a conversation from:
6+
*
7+
* - Server history: rows → `toUIMessages` → `hydratedMessagesToChatMessages`.
8+
* The persisted `data-record-citations` part is read back as it was stored,
9+
* never verified again (ruling Q1 on objectstack#37144).
10+
* - Cache fallback: the live map → `sanitizeChatMessagesForCache` → JSON →
11+
* `hydratedMessagesToChatMessages`.
12+
*
13+
* Both rebuilds go through the one allow-list of kept data parts
14+
* (`STORED_ANSWER_DATA_PARTS`). The reference is the chips the live answer
15+
* draws; CONTROL: a part the contract refuses draws nothing on either path.
16+
* The API-mode store rebuild is pinned in plugin-chatbot's
17+
* `useObjectChat.recordCitationsReload-37487.test.tsx`.
18+
*/
19+
import '@testing-library/jest-dom/vitest';
20+
import * as React from 'react';
21+
import { afterEach, describe, expect, it, vi } from 'vitest';
22+
import { cleanup, render, screen } from '@testing-library/react';
23+
import { RECORD_CITATIONS_PART_TYPE } from '@objectstack/spec/ai';
24+
import { ChatbotEnhanced, uiMessageToChatMessage } from '@object-ui/plugin-chatbot';
25+
import { hydratedMessagesToChatMessages } from '../AiChatPage';
26+
import { sanitizeChatMessagesForCache, toUIMessages } from '../../../hooks/useChatConversation';
27+
28+
afterEach(() => {
29+
cleanup();
30+
vi.unstubAllGlobals();
31+
});
32+
33+
const TEXT = 'The policy covers contractors.';
34+
const CITATIONS = [
35+
{ object: 'policy', id: 'pol_7', context: 'policy_document', anchor: 'scope', quote: 'Applies to every contractor on site.' },
36+
{ object: 'policy', id: 'pol_7', quote: 'Revision 3 published 2026-10-01' },
37+
];
38+
/** An alias the contract refuses by name (`section` for `anchor`). */
39+
const REFUSED = [{ ...CITATIONS[0], section: 'scope' }];
40+
41+
const citationsPart = (data: unknown) => ({ type: RECORD_CITATIONS_PART_TYPE, id: 'record-citations', data });
42+
43+
const liveAnswer = (data: unknown) =>
44+
uiMessageToChatMessage({
45+
id: 'a1',
46+
role: 'assistant',
47+
parts: [{ type: 'text', text: TEXT }, citationsPart(data)],
48+
} as never);
49+
50+
/** The stored turn, as the server persists the answer's parts. */
51+
const serverHistory = (data: unknown) =>
52+
toUIMessages([
53+
{ id: 'u1', role: 'user', content: 'Who does the policy cover?' },
54+
{ id: 'a1', role: 'assistant', content: [{ type: 'text', text: TEXT }, citationsPart(data)] },
55+
] as never);
56+
57+
const chipQuotes = () => screen.queryAllByTestId('record-citation').map((chip) => chip.textContent);
58+
59+
function chipsOf(messages: unknown[]) {
60+
render(<ChatbotEnhanced messages={messages as never} />);
61+
const quotes = chipQuotes();
62+
cleanup();
63+
return quotes;
64+
}
65+
66+
const LIVE_CHIPS = () => chipsOf([liveAnswer(CITATIONS)]);
67+
68+
describe('a reloaded answer draws its citation chips again (objectstack#37487)', () => {
69+
it('the live answer draws two chips (the reference)', () => {
70+
expect(LIVE_CHIPS()).toHaveLength(2);
71+
});
72+
73+
it('server history: the persisted part draws the same chips, and nothing is fetched', () => {
74+
const fetchSpy = vi.fn(async () => new Response('{}'));
75+
vi.stubGlobal('fetch', fetchSpy);
76+
const [, answer] = hydratedMessagesToChatMessages(serverHistory(CITATIONS));
77+
expect(answer.content).toBe(TEXT);
78+
expect(answer.recordCitations).toEqual(CITATIONS);
79+
expect(chipsOf([answer])).toEqual(LIVE_CHIPS());
80+
expect(fetchSpy).not.toHaveBeenCalled();
81+
});
82+
83+
it('server history CONTROL: a refused part draws nothing', () => {
84+
const [, answer] = hydratedMessagesToChatMessages(serverHistory(REFUSED));
85+
expect(answer.content).toBe(TEXT);
86+
expect(answer.recordCitations).toBeUndefined();
87+
expect(chipsOf([answer])).toEqual([]);
88+
});
89+
90+
it('cache fallback: the live answer is cached and restored with the same chips', () => {
91+
const cached = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([liveAnswer(CITATIONS)])));
92+
expect(cached[0].parts.map((p: { type: string }) => p.type)).toEqual(['text', RECORD_CITATIONS_PART_TYPE]);
93+
const [restored] = hydratedMessagesToChatMessages(cached);
94+
expect(restored.content).toBe(TEXT);
95+
expect(chipsOf([restored])).toEqual(LIVE_CHIPS());
96+
});
97+
98+
it('cache fallback: a restored server answer is re-cached without losing its chips', () => {
99+
const [, answer] = hydratedMessagesToChatMessages(serverHistory(CITATIONS));
100+
const cached = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([answer])));
101+
const [restored] = hydratedMessagesToChatMessages(cached);
102+
expect(restored.recordCitations).toEqual(answer.recordCitations);
103+
});
104+
105+
it('cache fallback CONTROL: a refused part is not cached and draws nothing', () => {
106+
const live = liveAnswer(REFUSED);
107+
expect(live.recordCitations).toBeUndefined();
108+
const cached = JSON.parse(JSON.stringify(sanitizeChatMessagesForCache([live])));
109+
expect(cached[0].parts.map((p: { type: string }) => p.type)).toEqual(['text']);
110+
const [restored] = hydratedMessagesToChatMessages(cached);
111+
expect(chipsOf([restored])).toEqual([]);
112+
});
113+
});

‎ui/packages/app-shell/src/hooks/useChatConversation.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react
2222
// `@object-ui/plugin-chatbot` is already a static member of this package's
2323
// barrel closure (`index.ts` re-exports `AiChatPage`, which imports it), so
2424
// this adds no package edge and no eager bundle weight.
25-
import { chartAnswerParts, detectPendingApproval } from '@object-ui/plugin-chatbot/core';
25+
import { detectPendingApproval, storedAnswerParts } from '@object-ui/plugin-chatbot/core';
26+
import type { StoredAnswerData } from '@object-ui/plugin-chatbot/core';
2627
// Type-only, so it is erased and pulls no barrel closure into the hook.
2728
import type { AnswerSource } from '@object-ui/plugin-chatbot';
2829
import { createAuthenticatedFetch } from '@object-ui/auth';
@@ -272,7 +273,9 @@ interface CacheableChatMessage {
272273
content?: string;
273274
toolInvocations?: CacheableChatToolInvocation[];
274275
/** The answer's charts, each at its `textOffset` into `content`. */
275-
charts?: Parameters<typeof chartAnswerParts>[1];
276+
charts?: StoredAnswerData['charts'];
277+
/** objectstack#37487 — the answer's verified record citations, cached as persisted. */
278+
recordCitations?: StoredAnswerData['recordCitations'];
276279
}
277280

278281
/**
@@ -515,9 +518,14 @@ export function sanitizeChatMessagesForCache(
515518
// the stream's own chart part is never stored, and a tool part carries
516519
// no position, so this is the one record that keeps both the chart and
517520
// its place. `hydratedMessagesToChatMessages` reads them back.
518-
const parts: HydratedUIMessagePart[] = chartAnswerParts(
521+
// objectstack#37487 — with every other kept data part
522+
// (`STORED_ANSWER_DATA_PARTS`): the verified citations list is cached as
523+
// the `data-record-citations` part, so its chips survive a cache reload.
524+
const parts: HydratedUIMessagePart[] = storedAnswerParts(
519525
message.content ?? '',
520-
message.role === 'assistant' ? message.charts : undefined,
526+
message.role === 'assistant'
527+
? { charts: message.charts, recordCitations: message.recordCitations }
528+
: {},
521529
);
522530
if (message.role === 'assistant') {
523531
for (const tool of message.toolInvocations ?? []) {

0 commit comments

Comments
 (0)