Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/37487-citations-survive-reload.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion content/docs/frontend/plugins/plugin-chatbot.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.<tool_name>` entry, a
short sentence in the user's language ("List the existing objects"). A tool
Expand Down
9 changes: 7 additions & 2 deletions ui/packages/app-shell/src/console/ai/AiChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -420,6 +424,7 @@ export function hydratedMessagesToChatMessages(messages: HydratedUIMessage[]): C
...(toolInvocations.length > 0 ? { toolInvocations } : {}),
...(buildProgress ? { buildProgress } : {}),
...(charts ? { charts } : {}),
...(recordCitations ? { recordCitations } : {}),
};
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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(<ChatbotEnhanced messages={messages as never} />);
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([]);
});
});
16 changes: 12 additions & 4 deletions ui/packages/app-shell/src/hooks/useChatConversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -272,7 +273,9 @@ interface CacheableChatMessage {
content?: string;
toolInvocations?: CacheableChatToolInvocation[];
/** The answer's charts, each at its `textOffset` into `content`. */
charts?: Parameters<typeof chartAnswerParts>[1];
charts?: StoredAnswerData['charts'];
/** objectstack#37487 — the answer's verified record citations, cached as persisted. */
recordCitations?: StoredAnswerData['recordCitations'];
}

/**
Expand Down Expand Up @@ -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 ?? []) {
Expand Down
Loading
Loading