From 2e82bebca9c8c849d4c54e447c9d7f2c5d6f2480 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:00:28 +0000 Subject: [PATCH 1/5] feat(chatbot): draw an answer's verified record citations and open the record at the cited section Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .../app-shell/src/console/ai/AiChatPage.tsx | 28 ++- ui/packages/app-shell/src/urlParams.ts | 16 ++ .../app-shell/src/views/RecordDetailView.tsx | 18 +- .../src/views/recordSectionAnchor.ts | 201 ++++++++++++++++++ ui/packages/i18n/src/locales/ar.ts | 3 + ui/packages/i18n/src/locales/de.ts | 3 + ui/packages/i18n/src/locales/en.ts | 3 + ui/packages/i18n/src/locales/es.ts | 3 + ui/packages/i18n/src/locales/fr.ts | 3 + ui/packages/i18n/src/locales/ja.ts | 3 + ui/packages/i18n/src/locales/ko.ts | 3 + ui/packages/i18n/src/locales/pt-BR.ts | 3 + ui/packages/i18n/src/locales/ru.ts | 3 + ui/packages/i18n/src/locales/zh-Hans.ts | 3 + ui/packages/i18n/src/locales/zh-Hant.ts | 3 + .../plugin-chatbot/src/ChatbotEnhanced.tsx | 23 +- .../plugin-chatbot/src/RecordCitations.tsx | 90 ++++++++ .../plugin-chatbot/src/chatMessageAdapter.ts | 2 +- ui/packages/plugin-chatbot/src/mapMessages.ts | 37 +++- .../plugin-detail/src/DetailSection.tsx | 4 + 20 files changed, 441 insertions(+), 11 deletions(-) create mode 100644 ui/packages/app-shell/src/views/recordSectionAnchor.ts create mode 100644 ui/packages/plugin-chatbot/src/RecordCitations.tsx diff --git a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx index 0d535a47ce7..2a9d55c5937 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -169,6 +169,7 @@ import { type OutboundAgentTextKey, } from './outboundAgentText.js'; import { resolveApiBase } from './resolveApiBase.js'; +import { RECORD_SECTION_PARAM } from '../../urlParams.js'; import { AiUnavailable } from './AiUnavailable.js'; import { recordWriteFormTarget } from '../../utils/recordFormAiDraft.js'; import { useUpload } from '@object-ui/fields'; @@ -216,6 +217,22 @@ export function listLinkTarget( return `/apps/${encodeURIComponent(app)}/${encodeURIComponent(target.objectName)}${query ? `?${query}` : ''}`; } +/** + * cloud#1658, ADR-0160 D9 — the console address of a record the chat opens: + * `/apps/APP/OBJECT/record/ID`, plus `?section=ANCHOR` (`RECORD_SECTION_PARAM`) + * when a record citation names a section of the record's body. A link with no + * anchor (an `open_record` hand-off, a record link in an answer) opens the + * record as before. + */ +export function recordOpenTarget( + app: string, + target: { objectName: string; recordId: string; anchor?: string }, +): string { + const path = `/apps/${encodeURIComponent(app)}/${encodeURIComponent(target.objectName)}/record/${encodeURIComponent(target.recordId)}`; + if (!target.anchor) return path; + return `${path}?${new URLSearchParams({ [RECORD_SECTION_PARAM]: target.anchor }).toString()}`; +} + function partString(part: HydratedUIMessagePart, key: string): string | undefined { const value = part[key]; return typeof value === 'string' && value.length > 0 ? value : undefined; @@ -1917,12 +1934,15 @@ export function ChatPane({ // owning package on click — one same-origin metadata read — instead of // burdening the agent with an id it may not know. `setup` is the fallback // shell for an object no package claims. + // + // ADR-0160 D9 — a record citation's chip passes the `anchor` of the body + // section it cites; it rides as `?section=` (`RECORD_SECTION_PARAM`), and + // the record page opens at that heading. The record opened is always the + // citation's own `object`/`id`, the pack's root record. const openRecord = useCallback( - async (handoff: { objectName: string; recordId: string }) => { + async (handoff: { objectName: string; recordId: string; anchor?: string }) => { const app = await appOfObject(handoff.objectName); - navigate( - `/apps/${encodeURIComponent(app)}/${encodeURIComponent(handoff.objectName)}/record/${encodeURIComponent(handoff.recordId)}`, - ); + navigate(recordOpenTarget(app, handoff)); }, [navigate], ); diff --git a/ui/packages/app-shell/src/urlParams.ts b/ui/packages/app-shell/src/urlParams.ts index 0d37e4abbe6..cc222610daa 100644 --- a/ui/packages/app-shell/src/urlParams.ts +++ b/ui/packages/app-shell/src/urlParams.ts @@ -63,6 +63,10 @@ import { STUDIO_RETURN_PARAM } from './views/studio-design/studioAddress.js'; * | | at it (a comment notice's link, #36410). | | * | `comment` | With `comments`: the comment in that thread to | with | * | | scroll to (objectstack#36410). | `comments` | + * | `section` | On a record route: the body heading to open at | with the | + * | | and mark, by the anchor the body outline | record link | + * | | issued (ADR-0160 D9; a cited passage opened | | + * | | from the assistant). A stale one opens the top.| | * | `from` | Ancestor breadcrumb trail for a record route, | push (with | * | | so drilling record→related-record keeps a | the drill-in) | * | | clickable path back (`Account → #p → Invoice`).| | @@ -164,6 +168,17 @@ export const RECORD_COMMENTS_PARAM = 'comments'; */ export const RECORD_COMMENT_PARAM = 'comment'; +/** + * On a record route (ADR-0160 D9): the heading of the record's body to open + * at, scrolled to and marked — by the `anchor` the body outline issued, which + * the spec's `headingsOf` derives from the body on the server and here alike. + * Written by the assistant's citation chips (`onOpenRecord`'s `anchor`). An + * anchor that names no heading of the record opens it at its top; a + * `textarea` body, or a heading the field does not draw, opens at the field. + * Read by `RecordDetailView` (`recordSectionAnchor.ts`). + */ +export const RECORD_SECTION_PARAM = 'section'; + /** * History-state flag beside {@link RECORD_COMMENTS_PARAM}: the record view * pushed this `?comments=` entry, so 「‹」 pops it. Not a URL parameter; an @@ -224,6 +239,7 @@ export const RESERVED_URL_PARAMS: readonly string[] = [ RECORD_RELATED_ENLARGE_PARAM, RECORD_COMMENTS_PARAM, RECORD_COMMENT_PARAM, + RECORD_SECTION_PARAM, COMMAND_PALETTE_PARAM, KEYBOARD_SHORTCUTS_PARAM, RECORD_TRAIL_PARAM, diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 39af152e45f..968912964e7 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -66,7 +66,8 @@ import { import { applySavedRecordEcho } from './recordSaveEcho.js'; import { authoredRecordPageApplies } from './recordPageSurface.js'; import { withPageTabsUrlSync } from '../utils/pageTabsUrlSync.js'; -import { RECORD_COMMENT_PARAM, RECORD_COMMENTS_PARAM, RECORD_COMMENTS_PUSHED_STATE as COMMENTS_PUSHED, RECORD_DETAIL_TAB_PARAM, RECORD_DRAWER_PARAM, RECORD_RELATED_ENLARGE_PARAM, RECORD_RELATED_ENLARGE_PUSHED_STATE as RELATED_ENLARGE_PUSHED, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js'; +import { RECORD_COMMENT_PARAM, RECORD_COMMENTS_PARAM, RECORD_SECTION_PARAM, RECORD_COMMENTS_PUSHED_STATE as COMMENTS_PUSHED, RECORD_DETAIL_TAB_PARAM, RECORD_DRAWER_PARAM, RECORD_RELATED_ENLARGE_PARAM, RECORD_RELATED_ENLARGE_PUSHED_STATE as RELATED_ENLARGE_PUSHED, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js'; +import { focusRecordSection, sectionCandidates } from './recordSectionAnchor.js'; import { resolveActionParams } from '@object-ui/fields'; import { createConsoleServerActionHandler } from '../utils/consoleServerAction.js'; import { withNewTabUrlFastPath } from '../utils/newTabUrlFastPath.js'; @@ -4939,6 +4940,21 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // only for a loaded record with nothing to be named by. const holdsRouteRecord = pageRecordFor === routeRecordKey && !!readablePageRecord && typeof readablePageRecord === 'object'; + // ADR-0160 D9 — `?section=ANCHOR`, a passage the assistant cited: once the + // record is held, the body heading the anchor names is scrolled to and + // marked (`recordSectionAnchor.ts`); a stale anchor leaves the page at its + // top. Judged once per record and anchor. + const sectionAnchor = tabSearchParams.get(RECORD_SECTION_PARAM) || null; + const citedSectionCandidates = holdsRouteRecord + ? sectionCandidates(objectDef?.fields, readablePageRecord as Record, sectionAnchor) + : []; + const citedSectionKey = citedSectionCandidates.length > 0 ? `${routeRecordKey}\n${sectionAnchor}` : null; + const citedSectionCandidatesRef = useRef(citedSectionCandidates); + citedSectionCandidatesRef.current = citedSectionCandidates; + useEffect(() => { + if (!pageRootEl || !citedSectionKey) return undefined; + return focusRecordSection(pageRootEl, citedSectionCandidatesRef.current); + }, [pageRootEl, citedSectionKey]); 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 new file mode 100644 index 00000000000..7f6c6f1658e --- /dev/null +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.ts @@ -0,0 +1,201 @@ +/** + * 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. + */ + +/** + * Opening a record at a cited section (`?section=ANCHOR`, ADR-0160 D9; the + * param is `RECORD_SECTION_PARAM` in `../urlParams.ts`). + * + * An anchor names a heading of a record's body, as the server's body outline + * issued it. The anchor is derived here by the same function the server uses, + * the spec's `headingsOf` (`record-body-anchor.ts`), run on the raw value of + * each long-text field the record holds, so a surface and the server never + * disagree on which heading an anchor names. The first field, in the object's + * field order, whose headings include the anchor is the body that is opened. + * + * The heading element is then found in that field's drawn face: among the + * field's heading elements, the ones whose letters and digits read the same as + * the outline's heading, counted in document order. Counting by reading rather + * than by bare position keeps a heading the outline does not list (a setext + * heading, an empty one, one inside a quote) from shifting every later one onto + * the wrong section. + * + * - A `textarea` body draws no heading elements, so the field is scrolled to. + * - A heading that is not drawn (the face has not rendered it, or reads it + * differently) also scrolls to the field, with no error. + * - An anchor no field resolves (a stale one: the heading was renamed or + * removed) opens the record at its top, as if no section were named. + * + * Nothing here re-verifies a citation: the anchor is only a place to open at. + */ +import { headingsOf } from '@objectstack/spec/ai'; + +/** The attribute a marked heading carries. */ +export const RECORD_SECTION_TARGET_ATTR = 'data-record-section-target'; + +/** The attribute that names the field a detail row draws (`@object-ui/plugin-detail`'s `DetailSection`). */ +export const DETAIL_FIELD_ATTR = 'data-detail-field'; + +/** + * How a marked heading is drawn: the marking a linked comment takes + * (`CommentItem`'s `targeted`), so one look means "the place a link named". + */ +export const RECORD_SECTION_MARK_CLASSES = ['rounded-md', 'bg-accent/60', 'ring-4', 'ring-accent/60'] as const; + +/** + * How long the page waits for the cited section to be drawn (the record's + * read, the lazily loaded rich-text face) before it settles for the field, or + * for the top. + */ +export const RECORD_SECTION_SETTLE_MS = 4000; + +/** + * The long-text field types a body can be, by how each one draws: markdown + * headings drawn as elements, HTML headings drawn as elements, and a + * `textarea` drawn as plain text, whose headings are never elements. + */ +const BODY_FACES: Readonly> = { + markdown: 'markdown', + html: 'html', + richtext: 'html', + textarea: 'text', +}; + +type SectionFace = 'markdown' | 'html' | 'text'; + +/** A field whose body holds the anchor, and which of its headings it names. */ +export interface SectionCandidate { + field: string; + face: SectionFace; + /** The heading's letters and digits, lowercased: how a drawn heading is matched. */ + reading: string; + /** How many of the field's earlier headings read the same. */ + ordinal: number; +} + +/** What a drawn section resolved to: the field's row, and the heading when it is drawn. */ +export interface SectionTarget { + field: HTMLElement; + face: SectionFace; + heading?: HTMLElement; +} + +/** `text`'s letters and digits of every script, lowercased. */ +export function headingReading(text: string): string { + return text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ''); +} + +/** + * The fields of `record` whose body holds `anchor`, in `fields`' order. Empty + * when the anchor is stale, or names no long-text field the record holds. + */ +export function sectionCandidates( + fields: Readonly> | null | undefined, + record: Readonly> | null | undefined, + anchor: string | null | undefined, +): SectionCandidate[] { + if (!anchor || !fields || !record) return []; + const out: SectionCandidate[] = []; + for (const [field, def] of Object.entries(fields)) { + const face = typeof def?.type === 'string' ? BODY_FACES[def.type] : undefined; + const value = record[field]; + if (!face || typeof value !== 'string' || value.length === 0) continue; + const headings = headingsOf(value, face === 'html'); + const at = headings.findIndex((h) => h.anchor === anchor); + if (at < 0) continue; + const reading = headingReading(headings[at].heading); + const ordinal = headings.slice(0, at).filter((h) => headingReading(h.heading) === reading).length; + out.push({ field, face, reading, ordinal }); + } + return out; +} + +function escapeAttr(value: string): string { + return value.replace(/["\\]/g, '\\$&'); +} + +/** + * The drawn place of the first candidate whose field is on the page: the + * field's row, with the heading when the face draws it. `undefined` when no + * candidate's field is drawn. + */ +export function locateSection(root: ParentNode, candidates: readonly SectionCandidate[]): SectionTarget | undefined { + for (const candidate of candidates) { + const field = root.querySelector(`[${DETAIL_FIELD_ATTR}="${escapeAttr(candidate.field)}"]`); + if (!field) continue; + const { face } = candidate; + if (face === 'text') return { field, face }; + const heading = Array.from(field.querySelectorAll('h1, h2, h3, h4, h5, h6')).filter( + (el) => headingReading(el.textContent ?? '') === candidate.reading, + )[candidate.ordinal]; + return heading ? { field, face, heading } : { field, face }; + } + return undefined; +} + +/** Marks `heading` as the cited section. */ +export function markSection(heading: HTMLElement): void { + heading.setAttribute(RECORD_SECTION_TARGET_ATTR, 'true'); + heading.classList.add(...RECORD_SECTION_MARK_CLASSES); +} + +function scrollTo(el: HTMLElement): void { + if (typeof el.scrollIntoView === 'function') el.scrollIntoView({ block: 'start' }); +} + +/** + * Opens the page at the cited section once it is drawn: the heading scrolled + * to and marked, or the field scrolled to (a `textarea` body at once, any + * other once {@link RECORD_SECTION_SETTLE_MS} pass without the heading). With + * no candidate, or no candidate field drawn by then, nothing moves. Answers + * the cleanup. + */ +export function focusRecordSection( + root: HTMLElement, + candidates: readonly SectionCandidate[], + settleMs: number = RECORD_SECTION_SETTLE_MS, +): () => void { + if (candidates.length === 0) return () => {}; + let done = false; + let observer: MutationObserver | undefined; + let timer: ReturnType | undefined; + const finish = (): void => { + done = true; + observer?.disconnect(); + if (timer !== undefined) clearTimeout(timer); + }; + const attempt = (): void => { + if (done) return; + const target = locateSection(root, candidates); + if (target?.heading) { + finish(); + markSection(target.heading); + scrollTo(target.heading); + } else if (target?.face === 'text') { + finish(); + scrollTo(target.field); + } + }; + attempt(); + if (done) return finish; + if (typeof MutationObserver === 'function') { + observer = new MutationObserver(attempt); + observer.observe(root, { childList: true, subtree: true, characterData: true }); + } + timer = setTimeout(() => { + if (done) return; + const target = locateSection(root, candidates); + finish(); + if (target?.heading) { + markSection(target.heading); + scrollTo(target.heading); + } else if (target) { + scrollTo(target.field); + } + }, settleMs); + return finish; +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 040ffe0ca80..3cf647b8482 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5068,6 +5068,9 @@ const ar = { metrics: 'المقاييس', noAddedFilter: 'لا يوجد عامل تصفية مضاف إلى تعريف مجموعة البيانات', }, + recordCitations: { + title: 'مقتبس من السجلات', + }, tool: { aggregate_data: "تجميع البيانات ذات الصلة", get_record: "قراءة هذا السجل", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index b581fe53706..d804f2f07e7 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4682,6 +4682,9 @@ const de = { metrics: 'Kennzahlen', noAddedFilter: 'Kein zusätzlicher Filter zur Datenset-Definition', }, + recordCitations: { + title: 'Zitiert aus Datensätzen', + }, tool: { aggregate_data: "Die Daten zusammenfassen", get_record: "Den Datensatz lesen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index e4a76084830..9ea88fe3b4c 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5653,6 +5653,9 @@ const en = { metrics: 'Metrics', noAddedFilter: 'No filter added to the dataset definition', }, + recordCitations: { + title: 'Cited from records', + }, tool: { aggregate_data: 'Aggregate the data', get_record: 'Read the record', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index c879e9508ec..120acaab624 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4779,6 +4779,9 @@ const es = { metrics: 'Métricas', noAddedFilter: 'Sin filtro añadido a la definición del conjunto de datos', }, + recordCitations: { + title: 'Citado de registros', + }, tool: { aggregate_data: "Resumir los datos", get_record: "Leer el registro", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 5bf4039eab7..0ddd6d4f073 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4775,6 +4775,9 @@ const fr = { metrics: 'Indicateurs', noAddedFilter: 'Aucun filtre ajouté à la définition du jeu de données', }, + recordCitations: { + title: 'Cité depuis les enregistrements', + }, tool: { aggregate_data: "Synthétiser les données", get_record: "Lire l’enregistrement", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 5b689d2ef4e..0abf78fc895 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4684,6 +4684,9 @@ const ja = { metrics: '指標', noAddedFilter: 'データセットの定義に追加されたフィルターなし', }, + recordCitations: { + title: 'レコードからの引用', + }, tool: { aggregate_data: "関連データを集計する", get_record: "このレコードを読み込む", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6d159da8f17..824351d7117 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4681,6 +4681,9 @@ const ko = { metrics: '지표', noAddedFilter: '데이터셋 정의에 추가된 필터 없음', }, + recordCitations: { + title: '레코드에서 인용', + }, tool: { aggregate_data: "관련 데이터 집계하기", get_record: "이 레코드 읽기", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 09c1cc0730a..df1670eceb9 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4774,6 +4774,9 @@ const pt = { metrics: 'Métricas', noAddedFilter: 'Nenhum filtro adicionado à definição do conjunto de dados', }, + recordCitations: { + title: 'Citado de registros', + }, tool: { aggregate_data: "Resumir os dados", get_record: "Ler o registro", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index c1281b7a05c..3b3732188e4 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4885,6 +4885,9 @@ const ru = { metrics: 'Метрики', noAddedFilter: 'Без фильтров сверх определения набора данных', }, + recordCitations: { + title: 'Цитаты из записей', + }, tool: { aggregate_data: "Агрегировать данные", get_record: "Прочитать запись", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 832015de466..31506176dbb 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -4943,6 +4943,9 @@ const zh = { metrics: '指标', noAddedFilter: '未在数据集定义之外添加筛选条件', }, + recordCitations: { + title: '引自记录', + }, tool: { aggregate_data: '汇总相关数据', get_record: '读取这条记录', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index d397fc1bf28..aa77a0d7f78 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -4943,6 +4943,9 @@ const zhHant = { metrics: '指標', noAddedFilter: '未在資料集定義之外新增篩選條件', }, + recordCitations: { + title: '引自記錄', + }, tool: { aggregate_data: '彙總相關資料', get_record: '讀取這條記錄', diff --git a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx index 9b5524547c7..87c4fe6cd69 100644 --- a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx +++ b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx @@ -121,8 +121,9 @@ import { type PackageRemoval, type ReplayOutcome, } from './mapMessages'; -import type { DatasetProvenance, ObjectQuerySource } from '@objectstack/spec/ai'; +import type { DatasetProvenance, ObjectQuerySource, RecordCitationParsed } from '@objectstack/spec/ai'; import { AnswerSourceBlock } from './AnswerSource'; +import { RecordCitations } from './RecordCitations'; /** * One chat message as `` RENDERS it — the runtime contract of @@ -176,6 +177,13 @@ export interface ChatbotEnhancedMessage { * only a wall of text. */ charts?: ChatChart[]; + /** + * The answer's verified record citations (ADR-0160 D9), lifted from the + * message's `data-record-citations` part by `extractRecordCitations`. Drawn + * as chips beside the "How this was computed" block; a click opens the + * cited record at its section through `onOpenRecord`. + */ + recordCitations?: RecordCitationParsed[]; } /** @@ -875,8 +883,13 @@ export interface ChatbotEnhancedProps extends React.HTMLAttributes void; - /** cloud#1658 — open the record an `open_record` hand-off points at. */ - onOpenRecord?: (handoff: { objectName: string; recordId: string; label?: string; reason?: string }) => void; + /** + * cloud#1658 — open the record an `open_record` hand-off points at. A + * record citation's chip calls it too (ADR-0160 D9), with the `anchor` of + * the body section it cites when it names one; the host opens the record at + * that section. + */ + onOpenRecord?: (handoff: { objectName: string; recordId: string; label?: string; reason?: string; anchor?: string }) => void; /** * objectstack#31869 — open the list a `/list/OBJECT` link in an answer * names: the object, and optionally a view and the Filter panel conditions. @@ -5659,6 +5672,10 @@ const ChatbotEnhanced = React.forwardRef( )} /> ) : null} + {/* ADR-0160 D9 — the records the answer rests on. */} + {!isUser && message.recordCitations ? ( + + ) : null} {!isUser && sources.length > 0 ? ( diff --git a/ui/packages/plugin-chatbot/src/RecordCitations.tsx b/ui/packages/plugin-chatbot/src/RecordCitations.tsx new file mode 100644 index 00000000000..4eac659d501 --- /dev/null +++ b/ui/packages/plugin-chatbot/src/RecordCitations.tsx @@ -0,0 +1,90 @@ +/** + * 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. + */ + +/** + * The records an answer rests on (ADR-0160 D9): one chip per verified + * citation, showing the passage relied on. A click opens the citation's + * record — the pack's root record, even when the passage came from a + * related-list row — at the cited section of its body, through the host's + * `onOpenRecord` with the citation's `anchor`. + * + * The block receives only the list `extractRecordCitations` lifted: the one + * the platform verified when the answer was produced and persisted with the + * message. It draws that list as it is and never verifies it again. + */ +import * as React from 'react'; +import { cn } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { QuoteIcon } from 'lucide-react'; +import type { RecordCitationParsed } from '@objectstack/spec/ai'; + +/** The record a chip opens, and the section of its body to open at. */ +export interface RecordCitationTarget { + objectName: string; + recordId: string; + anchor?: string; +} + +export interface RecordCitationsProps { + /** The answer's verified citations, in the order the answer gave them. */ + citations: readonly RecordCitationParsed[]; + /** The host's record opener. Absent, the chips are drawn but open nothing. */ + onOpenRecord?: (target: RecordCitationTarget) => void; + className?: string; +} + +/** What a citation opens: its `object` and `id` (the root record), and its `anchor` when it names one. */ +export function recordCitationTarget(citation: RecordCitationParsed): RecordCitationTarget { + return { + objectName: citation.object, + recordId: citation.id, + ...(citation.anchor ? { anchor: citation.anchor } : {}), + }; +} + +const CHIP_CLASS = + 'inline-flex max-w-full items-start gap-1 rounded-md border bg-muted/30 px-2 py-1 text-left text-foreground'; + +/** The answer's cited records; draws nothing for an answer with no citation. */ +export function RecordCitations({ citations, onOpenRecord, className }: RecordCitationsProps) { + const { t } = useObjectTranslation(); + const titleId = React.useId(); + if (citations.length === 0) return null; + return ( +
+
+
+
    + {citations.map((citation, i) => ( +
  • + {onOpenRecord ? ( + + ) : ( + + {citation.quote} + + )} +
  • + ))} +
+
+ ); +} diff --git a/ui/packages/plugin-chatbot/src/chatMessageAdapter.ts b/ui/packages/plugin-chatbot/src/chatMessageAdapter.ts index e9c0ec8cfed..999adb98875 100644 --- a/ui/packages/plugin-chatbot/src/chatMessageAdapter.ts +++ b/ui/packages/plugin-chatbot/src/chatMessageAdapter.ts @@ -91,7 +91,7 @@ import type { */ type RuntimeOnlyMessageKeys = Pick< RuntimeChatMessage, - 'buildProgress' | 'blueprintProgress' | 'charts' + 'buildProgress' | 'blueprintProgress' | 'charts' | 'recordCitations' >; /** diff --git a/ui/packages/plugin-chatbot/src/mapMessages.ts b/ui/packages/plugin-chatbot/src/mapMessages.ts index 4268370a303..0354c5b73c2 100644 --- a/ui/packages/plugin-chatbot/src/mapMessages.ts +++ b/ui/packages/plugin-chatbot/src/mapMessages.ts @@ -14,8 +14,19 @@ * apps that drive `useChat` themselves (e.g. Studio, which needs a custom * `prepareSendMessagesRequest` transport). */ -import type { BUILD_PROGRESS_FRAME_TYPE, BuildProgressPhase, DatasetProvenance, ObjectQuerySource } from '@objectstack/spec/ai'; -import { DatasetProvenanceSchema, ObjectQuerySourceSchema } from '@objectstack/spec/ai'; +import type { + BUILD_PROGRESS_FRAME_TYPE, + BuildProgressPhase, + DatasetProvenance, + ObjectQuerySource, + RecordCitationParsed, +} from '@objectstack/spec/ai'; +import { + DatasetProvenanceSchema, + ObjectQuerySourceSchema, + RECORD_CITATIONS_PART_TYPE, + 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'; @@ -828,6 +839,25 @@ export function detectAnswerSource(result: unknown): AnswerSource | undefined { return parsed.success ? parsed.data : undefined; } +/** + * The verified record citations an answer carries (ADR-0160 D9), read off the + * message's `data-record-citations` part ({@link RECORD_CITATIONS_PART_TYPE}) + * through the published contract (`RecordCitationsSchema`). + * + * The list is the one the platform verified when the answer was produced and + * persisted with the message; the chat draws it as it is and never verifies it + * again. As with {@link detectAnswerSource}, a part the schema refuses is no + * list at all, so a producer that drifts from the contract is seen as a turn + * without citations rather than drawn half-right. With a stable part id the + * stream keeps one part, so the last one is read. An empty list draws nothing. + */ +export function extractRecordCitations(parts: readonly AnyPart[]): RecordCitationParsed[] | undefined { + const part = parts.filter((p) => p.type === RECORD_CITATIONS_PART_TYPE).pop(); + if (!part) return undefined; + const parsed = RecordCitationsSchema.safeParse(part.data); + return parsed.success && parsed.data.length > 0 ? parsed.data : undefined; +} + /** * cloud#3565 — 「清理示例数据」: the chat's `remove_sample_data` queues a HITL * pending action and answers `{ status:'pending_approval', pendingActionId, @@ -1677,6 +1707,7 @@ export function uiMessageToChatMessage( // The verification line rides on the tree it verifies (objectui#11988). const verify = extractBuildVerify(parts); const buildProgress = tree && verify ? { ...tree, verify } : tree; + const recordCitations = extractRecordCitations(parts); return { id: (msg.id ?? `msg-${Math.random().toString(36).slice(2, 8)}`) as string, role: (msg.role ?? 'assistant') as ChatMessage['role'], @@ -1690,6 +1721,8 @@ export function uiMessageToChatMessage( // card (from the persisted tool result) is the post-reload record. blueprintProgress: extractBlueprintProgress(parts), charts: extractCharts(parts, { anchored: typeof msg.content !== 'string' }), + // ADR-0160 D9 — the answer's verified record citations, drawn as chips. + ...(recordCitations ? { recordCitations } : {}), streaming: opts.streaming, }; } diff --git a/ui/packages/plugin-detail/src/DetailSection.tsx b/ui/packages/plugin-detail/src/DetailSection.tsx index 42111f04454..61b4685bc2c 100644 --- a/ui/packages/plugin-detail/src/DetailSection.tsx +++ b/ui/packages/plugin-detail/src/DetailSection.tsx @@ -952,6 +952,7 @@ export const DetailSection: React.FC = ({ } : undefined} role={copyOffered ? 'button' : undefined} tabIndex={copyOffered ? 0 : undefined} + data-detail-field={field.name} > {fieldLabelText} {displayValue} @@ -978,6 +979,9 @@ export const DetailSection: React.FC = ({ listFace && 'border-b border-border/50 py-1.5 last:border-b-0', )} data-detail-field-row={frameless ? '' : undefined} + // The field this row draws: how a page finds a field's place, e.g. to + // open a record at a cited section of its body (ADR-0160 D9). + data-detail-field={field.name} > {/* The label as authored, in the header highlights' style: no case transform, which only Latin text takes, so a translated label and From e581d1410508e24e43ab082725da664fedfb935c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:04:40 +0000 Subject: [PATCH 2/5] test: pin the record citation chips and the cited-section opening Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .../AiChatPage.recordLink-13037.test.tsx | 55 ++++- ...cordDetailView.citedSection-37365.test.tsx | 196 ++++++++++++++++++ .../src/views/recordSectionAnchor.test.tsx | 184 ++++++++++++++++ ...botEnhanced.recordCitations-37365.test.tsx | 148 +++++++++++++ 4 files changed, 580 insertions(+), 3 deletions(-) create mode 100644 ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx create mode 100644 ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx create mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.recordCitations-37365.test.tsx diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordLink-13037.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordLink-13037.test.tsx index 8cb2eec04ed..c09ba2c37ad 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordLink-13037.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordLink-13037.test.tsx @@ -29,7 +29,7 @@ const ANSWER = 'Top customer: [Wayne Enterprises](/record/account/acc_42).'; */ const LIST_FILTER = { logic: 'and', conditions: [{ field: 'stage', operator: 'equals', value: 'open' }] }; const LIST_ANSWER = `There are [12 open opportunities](/list/opportunity?view=all&uf__filter=${encodeURIComponent(JSON.stringify(LIST_FILTER))}).`; -const answerNow = vi.hoisted(() => ({ content: '' })); +const answerNow = vi.hoisted(() => ({ content: '', recordCitations: undefined as unknown })); vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { const actual = await importOriginal>(); @@ -38,7 +38,12 @@ vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => { useObjectChat: () => ({ messages: [ { id: 'u1', role: 'user', content: 'analyse my customers' }, - { id: 'a1', role: 'assistant', content: answerNow.content || ANSWER }, + { + id: 'a1', + role: 'assistant', + content: answerNow.content || ANSWER, + ...(answerNow.recordCitations ? { recordCitations: answerNow.recordCitations } : {}), + }, ], isLoading: false, error: undefined, @@ -112,7 +117,9 @@ beforeEach(() => { ? { item: { name: 'account', _packageId: 'com.acme.crm' } } : String(input).endsWith('/api/v1/meta/object/opportunity') ? { item: { name: 'opportunity', _packageId: 'com.acme.crm' } } - : { success: true, data: [] }; + : String(input).endsWith('/api/v1/meta/object/policy') + ? { item: { name: 'policy', _packageId: 'com.acme.compliance' } } + : { success: true, data: [] }; return new Response(JSON.stringify(body), { status: 200, headers: { 'Content-Type': 'application/json' }, @@ -122,6 +129,7 @@ beforeEach(() => { }); afterEach(() => { answerNow.content = ''; + answerNow.recordCitations = undefined; cleanup(); vi.unstubAllGlobals(); window.history.replaceState(null, '', '/'); @@ -168,3 +176,44 @@ describe('objectstack#31869 — a list link in an answer opens the filtered list }); } }); + +/** + * objectstack#37365 (ADR-0160 D9) — a record citation's chip opens the cited + * record through the same opener, at the cited section: `?section=ANCHOR`. + * The console's assistant dock draws this same `ChatPane`, so the dock and + * the `/ai` page open a citation alike. A quote from a related row opens the + * root record the citation names, with no section. + */ +describe('objectstack#37365 — a record citation opens the record at the cited section', () => { + const CITATIONS = [ + { object: 'policy', id: 'pol_7', context: 'policy_document', anchor: 'scope', quote: 'Applies to every contractor.' }, + { object: 'policy', id: 'pol_7', context: 'policy_document', quote: 'Revision 3 published' }, + ]; + + for (const [mount, basename, prefix] of [ + ['a /_console/ mount', '/_console', '/_console'], + ['a root mount', '/', ''], + ] as const) { + it(`under ${mount}: the chip opens /apps/APP/OBJ/record/ID?section=ANCHOR`, async () => { + answerNow.recordCitations = CITATIONS; + renderPane(basename); + const chip = await screen.findByRole('button', { name: 'Applies to every contractor.' }); + await act(async () => { + fireEvent.click(chip); + }); + await waitFor(() => expect(window.location.pathname).toBe(`${prefix}/apps/com.acme.compliance/policy/record/pol_7`)); + expect(window.location.search).toBe('?section=scope'); + }); + } + + it('a quote from a related row opens the root record, with no section', async () => { + answerNow.recordCitations = CITATIONS; + renderPane('/'); + const chip = await screen.findByRole('button', { name: 'Revision 3 published' }); + await act(async () => { + fireEvent.click(chip); + }); + await waitFor(() => expect(window.location.pathname).toBe('/apps/com.acme.compliance/policy/record/pol_7')); + expect(window.location.search).toBe(''); + }); +}); 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 new file mode 100644 index 00000000000..373d7f6a5dc --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.citedSection-37365.test.tsx @@ -0,0 +1,196 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37365 (ADR-0160 D9) — a record opened from an assistant citation + * (`/apps/APP/OBJ/record/ID?section=ANCHOR`) opens at the cited section of its + * body, through the REAL `RecordDetailView` and the real markdown face: + * + * - the heading the anchor names (the spec's `headingsOf`, as the server + * issued it) is scrolled to and marked, a repeated heading by its `-2`; + * - a `textarea` body is scrolled to as a field, and nothing is marked; + * - a stale anchor opens the record at its top: nothing scrolls, nothing is + * marked. CONTROL: the same record with a live anchor scrolls and marks. + */ + +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 } from 'react-router-dom'; + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u-ada', name: 'Ada', image: null }, activeOrganization: null }), + createAuthenticatedFetch: () => vi.fn(), +})); +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecordPresence: () => [], + PresenceAvatars: () => null, +})); +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), + error: vi.fn(), + info: vi.fn(), + warning: vi.fn(), + loading: vi.fn(), + dismiss: vi.fn(), + }), +})); +vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null })); +vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null })); +vi.mock('./FlowRunner', () => ({ FlowRunner: () => null })); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); + +// The markdown face is lazily loaded by the cell renderer; importing it here +// moves its load into the import phase (ui/AGENTS.md, flaky-test discipline). +import '../../../fields/src/widgets/MarkdownContent'; +import { I18nProvider } from '@object-ui/i18n'; +import { MetadataCtx } from '@object-ui/react'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; +import { RecordDetailView } from './RecordDetailView'; +import { RECORD_SECTION_TARGET_ATTR } from './recordSectionAnchor'; + +const OBJECT_NAME = 'policy'; +const RECORD_ID = 'pol_7'; + +const BODY = ['# Intro', '', 'Hello.', '', '## Scope', '', 'Everyone.', '', '## Scope', '', 'Contractors too.'].join('\n'); +const NOTES = ['# Steps', '', 'Sign the sheet.'].join('\n'); + +const FIELDS = { + id: { type: 'text', label: 'Id' }, + title: { type: 'text', label: 'Title' }, + content: { type: 'markdown', label: 'Content' }, + notes: { type: 'textarea', label: 'Notes' }, +}; +const OBJECTS = [{ name: OBJECT_NAME, label: 'Policy', fields: FIELDS, enable: { feeds: false } }]; + +function makeDataSource() { + return { + find: vi.fn(async () => ({ data: [] })), + findOne: vi.fn(async (_o: string, id: string) => ({ id, title: `Policy ${id}`, content: BODY, notes: NOTES })), + create: vi.fn(async (_o: string, data: any) => ({ id: 'x', ...data })), + update: vi.fn(async (_o: string, id: string, patch: any) => ({ id, ...patch })), + delete: vi.fn(async () => true), + } as any; +} + +function metadata() { + return { + objects: OBJECTS, + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async () => null, + getItemsByType: (type: string) => (type === 'object' ? OBJECTS : []), + getTypeStatus: () => 'ready', + } as any; +} + +const FULL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; +const PERMS = { + authenticated: true, + userId: 'u-ada', + tenantId: null, + positions: ['member'], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: ['member'], + objects: { [OBJECT_NAME]: FULL }, + fields: {}, +} as MePermissionsAuthenticatedResponse; + +async function mount(search: string) { + const rendered = render( + + + + + {}} + objectNameOverride={OBJECT_NAME} + recordIdOverride={RECORD_ID} + /> + + + + , + ); + await within(rendered.container) + .findAllByText(`Policy ${RECORD_ID}`, undefined, { timeout: 4000 }) + .catch(() => undefined); + await act(async () => {}); + return rendered; +} + +let scrolled: HTMLElement[] = []; +const originalScroll = HTMLElement.prototype.scrollIntoView; + +beforeEach(() => { + scrolled = []; + HTMLElement.prototype.scrollIntoView = function (this: HTMLElement) { + scrolled.push(this); + }; + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } })), + ); +}); + +afterEach(() => { + cleanup(); + HTMLElement.prototype.scrollIntoView = originalScroll; + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +const marked = (root: HTMLElement) => Array.from(root.querySelectorAll(`[${RECORD_SECTION_TARGET_ATTR}]`)); +const headingsNamed = (root: HTMLElement, text: string) => + Array.from(root.querySelectorAll('[data-detail-field="content"] h2')).filter((h) => h.textContent === text); + +describe('a record opened at a cited section (objectstack#37365)', () => { + it('scrolls to the heading the anchor names and marks it', async () => { + const { container } = await mount('?section=scope'); + await waitFor(() => expect(marked(container)).toHaveLength(1), { timeout: 4000 }); + const [first] = headingsNamed(container, 'Scope'); + expect(marked(container)[0]).toBe(first); + expect(scrolled).toEqual([first]); + }); + + it('a repeated heading is told apart by its `-2`', async () => { + const { container } = await mount('?section=scope-2'); + await waitFor(() => expect(marked(container)).toHaveLength(1), { timeout: 4000 }); + const [, second] = headingsNamed(container, 'Scope'); + expect(marked(container)[0]).toBe(second); + expect(scrolled).toEqual([second]); + }); + + it('a `textarea` body scrolls to the field, and marks nothing', async () => { + const { container } = await mount('?section=steps'); + await waitFor(() => expect(scrolled).toHaveLength(1), { timeout: 4000 }); + expect(scrolled[0].getAttribute('data-detail-field')).toBe('notes'); + expect(marked(container)).toHaveLength(0); + }); + + it('a stale anchor opens the record at its top; CONTROL: a live anchor on the same record scrolls and marks', async () => { + const stale = await mount('?section=renamed-heading'); + await waitFor(() => expect(headingsNamed(stale.container, 'Scope')).toHaveLength(2), { timeout: 4000 }); + await act(async () => {}); + expect(scrolled).toEqual([]); + expect(marked(stale.container)).toHaveLength(0); + cleanup(); + const live = await mount('?section=intro'); + await waitFor(() => expect(marked(live.container)).toHaveLength(1), { timeout: 4000 }); + expect(marked(live.container)[0].textContent).toBe('Intro'); + expect(scrolled).toHaveLength(1); + }); +}); diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx new file mode 100644 index 00000000000..0d540648051 --- /dev/null +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx @@ -0,0 +1,184 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37365 (ADR-0160 D9) — `?section=ANCHOR` names a heading of the + * record's body by the anchor the server's body outline issued. The surface + * derives it with the same spec function (`headingsOf`), and finds the heading + * element among the field's drawn headings by reading, counting repeats. + * + * The DOM here is written by hand, so the matching is pinned apart from any + * renderer: a heading the outline does not list (a setext heading) must not + * shift a later one onto the wrong section. + */ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { headingsOf } from '@objectstack/spec/ai'; +import { + RECORD_SECTION_TARGET_ATTR, + focusRecordSection, + locateSection, + sectionCandidates, +} from './recordSectionAnchor'; +import { RECORD_SECTION_PARAM, RESERVED_URL_PARAMS } from '../urlParams'; + +const MARKDOWN = ['# Intro', '', 'Hello.', '', '## Scope', '', 'Everyone.', '', '## Scope', '', 'Again.'].join('\n'); +const HTML = '

Intro

x

Data & privacy

y

'; + +const FIELDS = { + title: { type: 'text' }, + summary: { type: 'textarea' }, + content: { type: 'markdown' }, + legal: { type: 'richtext' }, +}; + +const RECORD = { + title: '# Scope', + summary: 'Plain text, no headings.', + content: MARKDOWN, + legal: HTML, +}; + +function row(field: string, inner: string): string { + return `
${inner}
`; +} + +afterEach(() => { + document.body.innerHTML = ''; + vi.useRealTimers(); +}); + +describe('objectstack#37365 — the section param', () => { + it('is the reserved `section`', () => { + expect(RECORD_SECTION_PARAM).toBe('section'); + expect(RESERVED_URL_PARAMS).toContain(RECORD_SECTION_PARAM); + }); +}); + +describe('objectstack#37365 — sectionCandidates derives the anchor as the server does', () => { + it("answers the body field whose spec outline issues the anchor, the server's anchors included", () => { + const server = headingsOf(MARKDOWN, false).map((h) => h.anchor); + expect(server).toEqual(['intro', 'scope', 'scope-2']); + expect(sectionCandidates(FIELDS, RECORD, 'scope')).toEqual([ + { field: 'content', face: 'markdown', reading: 'scope', ordinal: 0 }, + ]); + expect(sectionCandidates(FIELDS, RECORD, 'scope-2')).toEqual([ + { field: 'content', face: 'markdown', reading: 'scope', ordinal: 1 }, + ]); + }); + + it('reads an html body as html', () => { + expect(headingsOf(HTML, true).map((h) => h.anchor)).toContain('data-privacy'); + expect(sectionCandidates(FIELDS, RECORD, 'data-privacy')).toEqual([ + { field: 'legal', face: 'html', reading: 'dataprivacy', ordinal: 0 }, + ]); + }); + + it('a `textarea` body is a candidate drawn as text', () => { + const record = { ...RECORD, summary: '# Steps\n\nDo it.' }; + expect(sectionCandidates(FIELDS, record, 'steps')).toEqual([ + { field: 'summary', face: 'text', reading: 'steps', ordinal: 0 }, + ]); + }); + + it('a stale anchor, a non-text field, or no anchor answers none', () => { + expect(sectionCandidates(FIELDS, RECORD, 'renamed-heading')).toEqual([]); + // `title` is a `text` field: never a body, whatever it holds. + expect(sectionCandidates({ title: { type: 'text' } }, RECORD, 'scope')).toEqual([]); + expect(sectionCandidates(FIELDS, RECORD, null)).toEqual([]); + expect(sectionCandidates(undefined, RECORD, 'scope')).toEqual([]); + }); +}); + +describe('objectstack#37365 — locateSection finds the drawn heading', () => { + it('takes the Nth heading that reads the same, so an unlisted heading shifts nothing', () => { + // A setext heading the outline does not list is drawn first; a bare + // position (the second heading for `scope`) would land on the first Scope. + document.body.innerHTML = row( + 'content', + '

Preface

Intro

Scope

Everyone.

Scope

', + ); + const target = locateSection(document.body, sectionCandidates(FIELDS, RECORD, 'scope-2')); + expect(target?.heading?.id).toBe('second'); + }); + + it('matches an html heading by its drawn text', () => { + document.body.innerHTML = row('legal', '

Intro

Data & privacy

'); + expect(locateSection(document.body, sectionCandidates(FIELDS, RECORD, 'data-privacy'))?.heading?.id).toBe('dp'); + }); + + it('a heading the face does not draw answers the field alone; no drawn field answers nothing', () => { + document.body.innerHTML = row('content', '

still loading

'); + const candidates = sectionCandidates(FIELDS, RECORD, 'scope'); + const target = locateSection(document.body, candidates); + expect(target?.field.getAttribute('data-detail-field')).toBe('content'); + expect(target?.heading).toBeUndefined(); + document.body.innerHTML = row('summary', 'x'); + expect(locateSection(document.body, candidates)).toBeUndefined(); + }); +}); + +describe('objectstack#37365 — focusRecordSection', () => { + it('scrolls to the heading and marks it', () => { + document.body.innerHTML = row('content', '

Intro

Scope

'); + const scroll = vi.fn(); + const heading = document.getElementById('s')!; + heading.scrollIntoView = scroll; + focusRecordSection(document.body, sectionCandidates(FIELDS, RECORD, 'scope')); + expect(scroll).toHaveBeenCalledTimes(1); + expect(heading.getAttribute(RECORD_SECTION_TARGET_ATTR)).toBe('true'); + }); + + it('waits for the heading to be drawn', async () => { + document.body.innerHTML = row('content', 'loading'); + const candidates = sectionCandidates(FIELDS, RECORD, 'scope'); + focusRecordSection(document.body, candidates); + const field = document.querySelector('[data-detail-field="content"]')!; + const heading = document.createElement('h2'); + heading.textContent = 'Scope'; + const scroll = vi.fn(); + heading.scrollIntoView = scroll; + field.appendChild(heading); + await new Promise((r) => setTimeout(r, 0)); + expect(scroll).toHaveBeenCalledTimes(1); + expect(heading.getAttribute(RECORD_SECTION_TARGET_ATTR)).toBe('true'); + }); + + it('a `textarea` body scrolls to the field at once, and marks nothing', () => { + document.body.innerHTML = row('summary', '# Steps
Do it.'); + const field = document.querySelector('[data-detail-field="summary"]')!; + const scroll = vi.fn(); + field.scrollIntoView = scroll; + focusRecordSection(document.body, sectionCandidates(FIELDS, { ...RECORD, summary: '# Steps\n\nDo it.' }, 'steps')); + expect(scroll).toHaveBeenCalledTimes(1); + expect(document.querySelector(`[${RECORD_SECTION_TARGET_ATTR}]`)).toBeNull(); + }); + + it('a heading never drawn settles on the field, with no error', () => { + vi.useFakeTimers(); + document.body.innerHTML = row('content', '

Scope is not a heading here

'); + const field = document.querySelector('[data-detail-field="content"]')!; + const scroll = vi.fn(); + field.scrollIntoView = scroll; + focusRecordSection(document.body, sectionCandidates(FIELDS, RECORD, 'scope'), 50); + expect(scroll).not.toHaveBeenCalled(); + vi.advanceTimersByTime(60); + expect(scroll).toHaveBeenCalledTimes(1); + expect(document.querySelector(`[${RECORD_SECTION_TARGET_ATTR}]`)).toBeNull(); + }); + + it('a stale anchor moves nothing; CONTROL: the live anchor on the same page does', () => { + vi.useFakeTimers(); + document.body.innerHTML = row('content', '

Intro

Scope

'); + const heading = document.getElementById('s')!; + const field = document.querySelector('[data-detail-field="content"]')!; + const scroll = vi.fn(); + heading.scrollIntoView = scroll; + field.scrollIntoView = scroll; + focusRecordSection(document.body, sectionCandidates(FIELDS, RECORD, 'renamed-heading'), 50); + vi.advanceTimersByTime(60); + expect(scroll).not.toHaveBeenCalled(); + expect(heading.hasAttribute(RECORD_SECTION_TARGET_ATTR)).toBe(false); + focusRecordSection(document.body, sectionCandidates(FIELDS, RECORD, 'scope'), 50); + expect(scroll).toHaveBeenCalledTimes(1); + expect(heading.getAttribute(RECORD_SECTION_TARGET_ATTR)).toBe('true'); + }); +}); diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.recordCitations-37365.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.recordCitations-37365.test.tsx new file mode 100644 index 00000000000..70f530881d9 --- /dev/null +++ b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.recordCitations-37365.test.tsx @@ -0,0 +1,148 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * objectstack#37365 (ADR-0160 D9) — an answer draws its verified record + * citations as chips, and a chip opens the cited record at its section. + * + * The turns are built from wire parts through `uiMessageToChatMessage`, so the + * lift (`extractRecordCitations`, through the spec's `RecordCitationsSchema`) + * and the draw are pinned together, the way a streamed conversation reaches + * the chat. + * + * - A chip shows the quote; a click calls `onOpenRecord` with the citation's + * `object` / `id` and its `anchor`. + * - A quote taken from a related row still opens the root record: the chip + * opens the citation's `object` / `id`, nothing else. + * - The list is drawn as persisted: nothing is fetched to verify it again. + * - A part the parse refuses draws nothing, and the CONTROL (the same turn + * with a part that parses) draws its chips. + * - The record-link grammar is unchanged: a fragment is still refused. + */ +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { RECORD_CITATIONS_MAX, RECORD_CITATIONS_PART_TYPE } from '@objectstack/spec/ai'; +import { ChatbotEnhanced } from '../ChatbotEnhanced'; +import { extractRecordCitations, uiMessageToChatMessage } from '../mapMessages'; +import { parseRecordLink } from '../recordLink'; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +/** A citation to a section of the root record's body. */ +const SECTION_CITATION = { + object: 'policy', + id: 'pol_7', + context: 'policy_document', + anchor: 'scope', + quote: 'Applies to every contractor on site.', +}; + +/** A citation whose quote came from a related-list cell: it still names the root record. */ +const RELATED_ROW_CITATION = { + object: 'policy', + id: 'pol_7', + context: 'policy_document', + quote: 'Revision 3 published 2026-10-01', +}; + +const citationsPart = (data: unknown) => ({ type: RECORD_CITATIONS_PART_TYPE, id: 'record-citations', data }); + +const turn = (parts: unknown[]) => + uiMessageToChatMessage({ + id: 'a1', + role: 'assistant', + parts: [{ type: 'text', text: 'The policy covers contractors.' }, ...parts], + } as never); + +const question = { id: 'u1', role: 'user' as const, content: 'Who does the policy cover?' }; + +function renderTurn(parts: unknown[], onOpenRecord = vi.fn()) { + render(); + return onOpenRecord; +} + +const chips = () => screen.queryAllByTestId('record-citation'); + +describe('objectstack#37365 — extractRecordCitations reads the part through the spec schema', () => { + it('lifts the parsed list', () => { + expect(extractRecordCitations([citationsPart([SECTION_CITATION, RELATED_ROW_CITATION])] as never)).toEqual([ + SECTION_CITATION, + RELATED_ROW_CITATION, + ]); + }); + + it('reads the last part of the type', () => { + const parts = [citationsPart([SECTION_CITATION]), citationsPart([RELATED_ROW_CITATION])]; + expect(extractRecordCitations(parts as never)).toEqual([RELATED_ROW_CITATION]); + }); + + it.each([ + ['an alias the schema refuses by name (`section` for `anchor`)', [{ ...RELATED_ROW_CITATION, section: 'scope' }]], + ['a key the schema does not declare', [{ ...SECTION_CITATION, field: 'content' }]], + ['a citation with no quote', [{ object: 'policy', id: 'pol_7' }]], + ['more citations than the bound', Array.from({ length: RECORD_CITATIONS_MAX + 1 }, () => SECTION_CITATION)], + ['data that is not a list', { citations: [SECTION_CITATION] }], + ])('a part the parse refuses is no list: %s', (_label, data) => { + expect(extractRecordCitations([citationsPart(data)] as never)).toBeUndefined(); + }); + + it('an empty list, or no part at all, is no list', () => { + expect(extractRecordCitations([citationsPart([])] as never)).toBeUndefined(); + expect(extractRecordCitations([{ type: 'text', text: 'hi' }] as never)).toBeUndefined(); + }); +}); + +describe('objectstack#37365 — the chips under an answer', () => { + it('each chip shows its quote, and a click opens the record at the cited section', () => { + const onOpenRecord = renderTurn([citationsPart([SECTION_CITATION])]); + expect(screen.getByTestId('record-citations')).toHaveTextContent('Cited from records'); + expect(chips()).toHaveLength(1); + expect(chips()[0]).toHaveTextContent(SECTION_CITATION.quote); + fireEvent.click(chips()[0]); + expect(onOpenRecord).toHaveBeenCalledTimes(1); + expect(onOpenRecord).toHaveBeenCalledWith({ objectName: 'policy', recordId: 'pol_7', anchor: 'scope' }); + }); + + it('a quote from a related row opens the root record, with no anchor', () => { + const onOpenRecord = renderTurn([citationsPart([RELATED_ROW_CITATION])]); + fireEvent.click(chips()[0]); + expect(onOpenRecord).toHaveBeenCalledWith({ objectName: 'policy', recordId: 'pol_7' }); + }); + + it('draws the persisted list as it is: nothing is fetched to verify it again', () => { + const fetchSpy = vi.fn(async () => new Response('{}')); + vi.stubGlobal('fetch', fetchSpy); + renderTurn([citationsPart([SECTION_CITATION, RELATED_ROW_CITATION])]); + expect(chips()).toHaveLength(2); + fireEvent.click(chips()[1]); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it('a part that fails the parse draws nothing; CONTROL: the same turn with a part that parses draws its chips', () => { + renderTurn([citationsPart([{ ...SECTION_CITATION, section: 'scope' }])]); + expect(screen.queryByTestId('record-citations')).toBeNull(); + expect(chips()).toHaveLength(0); + cleanup(); + renderTurn([citationsPart([SECTION_CITATION])]); + expect(screen.getByTestId('record-citations')).toBeInTheDocument(); + expect(chips()).toHaveLength(1); + }); + + it('with no record opener the chips are drawn and open nothing', () => { + render(); + expect(chips()).toHaveLength(1); + expect(chips()[0].tagName).not.toBe('BUTTON'); + }); +}); + +describe('objectstack#37365 — the record-link grammar is unchanged', () => { + it('refuses a fragment; CONTROL: the bare record form is read', () => { + expect(parseRecordLink('/record/policy/pol_7#scope')).toBeNull(); + expect(parseRecordLink('/record/policy/pol_7?section=scope')).toBeNull(); + expect(parseRecordLink('/record/policy/pol_7')).toEqual({ objectName: 'policy', recordId: 'pol_7' }); + }); +}); From f0d2e0080dcd74646b2a38fda9d79722c8c9c6b2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:09:57 +0000 Subject: [PATCH 3/5] docs: the record citation chips and the section param, with a changeset Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .changeset/37365-record-citation-chips.md | 19 +++++++++++++++++++ .../docs/frontend/plugins/plugin-chatbot.mdx | 2 ++ ui/packages/plugin-chatbot/README.md | 8 ++++++++ 3 files changed, 29 insertions(+) create mode 100644 .changeset/37365-record-citation-chips.md diff --git a/.changeset/37365-record-citation-chips.md b/.changeset/37365-record-citation-chips.md new file mode 100644 index 00000000000..47462ca9472 --- /dev/null +++ b/.changeset/37365-record-citation-chips.md @@ -0,0 +1,19 @@ +--- +'@object-ui/plugin-chatbot': patch +'@object-ui/app-shell': patch +'@object-ui/plugin-detail': patch +'@object-ui/i18n': patch +--- + +feat(chatbot): an answer draws its verified record citations as chips, and a chip opens the record at the cited section + +Clause-②: yes (a new reserved URL parameter `section`) +Metadata-protocol: none + +An assistant answer that rests on records now draws the citations the platform verified when the answer was produced (ADR-0160 D9): the message's `data-record-citations` part, read through `@objectstack/spec/ai`'s `RecordCitationsSchema`, becomes one chip per citation beside the "How this was computed" block, each showing the quoted passage (`extractRecordCitations` in `@object-ui/plugin-chatbot`, `RecordCitations`). The list is drawn as it was persisted and is never verified again on display. A part the schema refuses draws nothing. + +A chip calls the chat's `onOpenRecord` with the citation's `object` and `id` (the context pack's root record, also when the passage came from a related-list row) and its `anchor`; `onOpenRecord`'s argument gains an optional `anchor`. The console's assistant (the `/ai` page and the dock) opens `/apps/APP/OBJECT/record/ID?section=ANCHOR`. + +`section` is a new reserved console URL parameter (`RECORD_SECTION_PARAM`, listed in `RESERVED_URL_PARAMS`). The record page reads it: the spec's `headingsOf` runs on each long-text field of the record (`markdown`, `html`, `richtext`, `textarea`), the first field whose outline issues the anchor is the body, and its heading is scrolled to and marked. A `textarea` body, or a heading the field does not draw, opens at the field; an anchor no heading issues any more opens the record at its top. A record detail row now carries `data-detail-field` with the field's name, which is how the page finds the field. + +The record-link grammar in answers is unchanged: a fragment or a query string is still refused. diff --git a/content/docs/frontend/plugins/plugin-chatbot.mdx b/content/docs/frontend/plugins/plugin-chatbot.mdx index 015d1d303f0..53605b10dc7 100644 --- a/content/docs/frontend/plugins/plugin-chatbot.mdx +++ b/content/docs/frontend/plugins/plugin-chatbot.mdx @@ -493,6 +493,8 @@ 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. +An answer that rests on records carries the list of citations the platform verified when the answer was produced (the `data-record-citations` part, `RecordCitationsSchema` in `@objectstack/spec/ai`). It is drawn beside that block as one chip per citation, each showing the quoted passage, and is never verified again on display; a part that does not parse draws nothing. 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 the pack has no entry for falls back to its name, title-cased. diff --git a/ui/packages/plugin-chatbot/README.md b/ui/packages/plugin-chatbot/README.md index a3e3c1d5631..c1bff169ab8 100644 --- a/ui/packages/plugin-chatbot/README.md +++ b/ui/packages/plugin-chatbot/README.md @@ -470,6 +470,14 @@ the grouping, the aggregations, how many records the figures cover, and whether only the reader's visible records were read. It draws that block alone, never the rest of the tool payload. +An answer that rests on records draws its verified citations (the +`data-record-citations` part, `RecordCitationsSchema` in `@objectstack/spec/ai`) +beside that block, one chip per citation showing the quoted passage. The list is +drawn as the platform verified it when the answer was produced, never verified +again; a part that does not parse draws nothing. A chip calls +`onOpenRecord({ objectName, recordId, anchor })`, and the console opens the +record at the cited body section (`?section=ANCHOR`). + Console hosts also keep a sanitized browser-side display cache for the active conversation. If the backend conversation record is available but returns no message rows on refresh, the UI can restore user/assistant text plus grouped From 60981028c1462e71f9b72f08ef312e4c0c0d98d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:11:17 +0000 Subject: [PATCH 4/5] fix: lint the section focus helper and keep the chip target local Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- ui/packages/app-shell/src/views/recordSectionAnchor.ts | 6 +++--- ui/packages/plugin-chatbot/src/RecordCitations.tsx | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.ts b/ui/packages/app-shell/src/views/recordSectionAnchor.ts index 7f6c6f1658e..07c76318ba6 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.ts +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.ts @@ -162,11 +162,11 @@ export function focusRecordSection( if (candidates.length === 0) return () => {}; let done = false; let observer: MutationObserver | undefined; - let timer: ReturnType | undefined; + const pending: { timer?: ReturnType } = {}; const finish = (): void => { done = true; observer?.disconnect(); - if (timer !== undefined) clearTimeout(timer); + if (pending.timer !== undefined) clearTimeout(pending.timer); }; const attempt = (): void => { if (done) return; @@ -186,7 +186,7 @@ export function focusRecordSection( observer = new MutationObserver(attempt); observer.observe(root, { childList: true, subtree: true, characterData: true }); } - timer = setTimeout(() => { + pending.timer = setTimeout(() => { if (done) return; const target = locateSection(root, candidates); finish(); diff --git a/ui/packages/plugin-chatbot/src/RecordCitations.tsx b/ui/packages/plugin-chatbot/src/RecordCitations.tsx index 4eac659d501..1243808d6d1 100644 --- a/ui/packages/plugin-chatbot/src/RecordCitations.tsx +++ b/ui/packages/plugin-chatbot/src/RecordCitations.tsx @@ -39,7 +39,7 @@ export interface RecordCitationsProps { } /** What a citation opens: its `object` and `id` (the root record), and its `anchor` when it names one. */ -export function recordCitationTarget(citation: RecordCitationParsed): RecordCitationTarget { +function recordCitationTarget(citation: RecordCitationParsed): RecordCitationTarget { return { objectName: citation.object, recordId: citation.id, From c1b30e6a0b0c2548b331de1711581d9749459203 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:48:50 +0000 Subject: [PATCH 5/5] fix(app-shell): open a cited section only where the drawn count agrees, and move the mark The record page's section locator now carries the outline's count of same-titled headings and opens the field, not a heading, when the drawn face draws a different number of them (a setext, quoted or listed duplicate, or an outline heading the face does not draw), and when the heading has no letter or digit. The focus cleanup takes the mark off, so a second citation leaves only its own section marked; each chip click carries a fresh history-state value, so the same chip opens its section again. The changeset and the two doc pages now say the console draws a verified citations part when an answer carries one, not yet after a reload. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .changeset/37365-record-citation-chips.md | 6 +- .../docs/frontend/plugins/plugin-chatbot.mdx | 2 +- .../app-shell/src/console/ai/AiChatPage.tsx | 19 +++- .../AiChatPage.recordLink-13037.test.tsx | 22 +++++ ui/packages/app-shell/src/urlParams.ts | 8 ++ ...cordDetailView.citedSection-37365.test.tsx | 79 +++++++++++++-- .../app-shell/src/views/RecordDetailView.tsx | 23 +++-- .../src/views/recordSectionAnchor.test.tsx | 95 +++++++++++++++++-- .../src/views/recordSectionAnchor.ts | 67 +++++++++---- ui/packages/plugin-chatbot/README.md | 11 ++- 10 files changed, 279 insertions(+), 53 deletions(-) diff --git a/.changeset/37365-record-citation-chips.md b/.changeset/37365-record-citation-chips.md index 47462ca9472..69b3b3215f1 100644 --- a/.changeset/37365-record-citation-chips.md +++ b/.changeset/37365-record-citation-chips.md @@ -5,15 +5,15 @@ '@object-ui/i18n': patch --- -feat(chatbot): an answer draws its verified record citations as chips, and a chip opens the record at the cited section +feat(chatbot): when an answer carries a verified record-citations part, the console draws it as chips, and a chip opens the record at the cited section Clause-②: yes (a new reserved URL parameter `section`) Metadata-protocol: none -An assistant answer that rests on records now draws the citations the platform verified when the answer was produced (ADR-0160 D9): the message's `data-record-citations` part, read through `@objectstack/spec/ai`'s `RecordCitationsSchema`, becomes one chip per citation beside the "How this was computed" block, each showing the quoted passage (`extractRecordCitations` in `@object-ui/plugin-chatbot`, `RecordCitations`). The list is drawn as it was persisted and is never verified again on display. A part the schema refuses draws nothing. +When an assistant answer carries a `data-record-citations` part (ADR-0160 D9), the console draws it: the part, read through `@objectstack/spec/ai`'s `RecordCitationsSchema`, becomes one chip per citation beside the "How this was computed" block, each showing the quoted passage (`extractRecordCitations` in `@object-ui/plugin-chatbot`, `RecordCitations`). The chips draw the part as it arrives and verify nothing again on display. A part the schema refuses draws nothing. Nothing in this release emits the part yet, and a conversation reloaded from history does not redraw it yet: the chips appear on a live answer whose stream carries the part. A chip calls the chat's `onOpenRecord` with the citation's `object` and `id` (the context pack's root record, also when the passage came from a related-list row) and its `anchor`; `onOpenRecord`'s argument gains an optional `anchor`. The console's assistant (the `/ai` page and the dock) opens `/apps/APP/OBJECT/record/ID?section=ANCHOR`. -`section` is a new reserved console URL parameter (`RECORD_SECTION_PARAM`, listed in `RESERVED_URL_PARAMS`). The record page reads it: the spec's `headingsOf` runs on each long-text field of the record (`markdown`, `html`, `richtext`, `textarea`), the first field whose outline issues the anchor is the body, and its heading is scrolled to and marked. A `textarea` body, or a heading the field does not draw, opens at the field; an anchor no heading issues any more opens the record at its top. A record detail row now carries `data-detail-field` with the field's name, which is how the page finds the field. +`section` is a new reserved console URL parameter (`RECORD_SECTION_PARAM`, listed in `RESERVED_URL_PARAMS`). The record page reads it: the spec's `headingsOf` runs on each long-text field of the record (`markdown`, `html`, `richtext`, `textarea`), the first field whose outline issues the anchor is the body, and its heading is scrolled to and marked; opening another section moves the mark, and the same chip clicked again opens the section again. A `textarea` body, a heading the field does not draw, or a body that draws a different number of headings of that title than its outline lists, opens at the field; an anchor no heading issues any more opens the record at its top. A record detail row now carries `data-detail-field` with the field's name, which is how the page finds the field. The record-link grammar in answers is unchanged: a fragment or a query string is still refused. diff --git a/content/docs/frontend/plugins/plugin-chatbot.mdx b/content/docs/frontend/plugins/plugin-chatbot.mdx index 53605b10dc7..6faad747a84 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. -An answer that rests on records carries the list of citations the platform verified when the answer was produced (the `data-record-citations` part, `RecordCitationsSchema` in `@objectstack/spec/ai`). It is drawn beside that block as one chip per citation, each showing the quoted passage, and is never verified again on display; a part that does not parse draws nothing. 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; 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. 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 2a9d55c5937..3ec954cd3e3 100644 --- a/ui/packages/app-shell/src/console/ai/AiChatPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AiChatPage.tsx @@ -169,7 +169,7 @@ import { type OutboundAgentTextKey, } from './outboundAgentText.js'; import { resolveApiBase } from './resolveApiBase.js'; -import { RECORD_SECTION_PARAM } from '../../urlParams.js'; +import { RECORD_SECTION_OPENED_STATE, RECORD_SECTION_PARAM } from '../../urlParams.js'; import { AiUnavailable } from './AiUnavailable.js'; import { recordWriteFormTarget } from '../../utils/recordFormAiDraft.js'; import { useUpload } from '@object-ui/fields'; @@ -233,6 +233,14 @@ export function recordOpenTarget( return `${path}?${new URLSearchParams({ [RECORD_SECTION_PARAM]: target.anchor }).toString()}`; } +let sectionOpenings = 0; + +/** A history-state value no earlier chip click of this page load carried. */ +function nextSectionOpening(): string { + sectionOpenings += 1; + return `${Date.now().toString(36)}.${sectionOpenings}`; +} + function partString(part: HydratedUIMessagePart, key: string): string | undefined { const value = part[key]; return typeof value === 'string' && value.length > 0 ? value : undefined; @@ -1938,11 +1946,16 @@ export function ChatPane({ // ADR-0160 D9 — a record citation's chip passes the `anchor` of the body // section it cites; it rides as `?section=` (`RECORD_SECTION_PARAM`), and // the record page opens at that heading. The record opened is always the - // citation's own `object`/`id`, the pack's root record. + // citation's own `object`/`id`, the pack's root record. Each click carries a + // fresh `RECORD_SECTION_OPENED_STATE`, so clicking the same chip again opens + // the section again. const openRecord = useCallback( async (handoff: { objectName: string; recordId: string; anchor?: string }) => { const app = await appOfObject(handoff.objectName); - navigate(recordOpenTarget(app, handoff)); + navigate( + recordOpenTarget(app, handoff), + handoff.anchor ? { state: { [RECORD_SECTION_OPENED_STATE]: nextSectionOpening() } } : undefined, + ); }, [navigate], ); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordLink-13037.test.tsx b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordLink-13037.test.tsx index c09ba2c37ad..10844f4ac18 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordLink-13037.test.tsx +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.recordLink-13037.test.tsx @@ -19,6 +19,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { BrowserRouter } from 'react-router-dom'; import React from 'react'; +import { RECORD_SECTION_OPENED_STATE } from '../../../urlParams'; const ANSWER = 'Top customer: [Wayne Enterprises](/record/account/acc_42).'; @@ -206,6 +207,27 @@ describe('objectstack#37365 — a record citation opens the record at the cited }); } + it('each click of a chip carries a fresh opened-state value, so the same chip opens the section again', async () => { + answerNow.recordCitations = CITATIONS; + renderPane('/'); + const opened = () => (window.history.state?.usr as Record | undefined)?.[RECORD_SECTION_OPENED_STATE]; + const click = async () => { + await act(async () => { + fireEvent.click(await screen.findByRole('button', { name: 'Applies to every contractor.' })); + }); + await waitFor(() => expect(typeof opened()).toBe('string')); + return opened(); + }; + const first = await click(); + expect(window.location.search).toBe('?section=scope'); + await act(async () => { + window.history.replaceState(null, '', window.location.href); + }); + const second = await click(); + expect(window.location.search).toBe('?section=scope'); + expect(second).not.toBe(first); + }); + it('a quote from a related row opens the root record, with no section', async () => { answerNow.recordCitations = CITATIONS; renderPane('/'); diff --git a/ui/packages/app-shell/src/urlParams.ts b/ui/packages/app-shell/src/urlParams.ts index cc222610daa..e51f792912f 100644 --- a/ui/packages/app-shell/src/urlParams.ts +++ b/ui/packages/app-shell/src/urlParams.ts @@ -179,6 +179,14 @@ export const RECORD_COMMENT_PARAM = 'comment'; */ export const RECORD_SECTION_PARAM = 'section'; +/** + * History-state value beside {@link RECORD_SECTION_PARAM}: a distinct value per + * chip click, so a second click of the same citation (the same URL) opens the + * section again. Not a URL parameter; an entry reached by a reload or a shared + * link carries none and opens the section once. + */ +export const RECORD_SECTION_OPENED_STATE = '__sectionOpened'; + /** * History-state flag beside {@link RECORD_COMMENTS_PARAM}: the record view * pushed this `?comments=` entry, so 「‹」 pops it. Not a URL parameter; an 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 373d7f6a5dc..fa09c2c4e80 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 @@ -9,14 +9,21 @@ * issued it) is scrolled to and marked, a repeated heading by its `-2`; * - a `textarea` body is scrolled to as a field, and nothing is marked; * - a stale anchor opens the record at its top: nothing scrolls, nothing is - * marked. CONTROL: the same record with a live anchor scrolls and marks. + * marked. CONTROL: the same record with a live anchor scrolls and marks; + * - a setext `Scope` drawn above the cited `# Scope` (a same-titled heading the + * outline does not list) opens the field and marks nothing. CONTROL: the + * setext heading titled otherwise; the cited heading is marked; + * - a second chip on the open record moves the mark (only the new section is + * 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. */ 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 } from 'react-router-dom'; +import { MemoryRouter, useNavigate, type NavigateFunction } from 'react-router-dom'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), @@ -54,12 +61,15 @@ import { MetadataCtx } from '@object-ui/react'; import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; import { RecordDetailView } from './RecordDetailView'; import { RECORD_SECTION_TARGET_ATTR } from './recordSectionAnchor'; +import { RECORD_SECTION_OPENED_STATE } from '../urlParams'; const OBJECT_NAME = 'policy'; const RECORD_ID = 'pol_7'; const BODY = ['# Intro', '', 'Hello.', '', '## Scope', '', 'Everyone.', '', '## Scope', '', 'Contractors too.'].join('\n'); const NOTES = ['# Steps', '', 'Sign the sheet.'].join('\n'); +const SETEXT_BODY = ['Scope', '=====', '', 'Lead.', '', '# Scope', '', 'Everyone.'].join('\n'); +const SETEXT_CONTROL = ['Preface', '=======', '', 'Lead.', '', '# Scope', '', 'Everyone.'].join('\n'); const FIELDS = { id: { type: 'text', label: 'Id' }, @@ -69,10 +79,10 @@ const FIELDS = { }; const OBJECTS = [{ name: OBJECT_NAME, label: 'Policy', fields: FIELDS, enable: { feeds: false } }]; -function makeDataSource() { +function makeDataSource(content = BODY) { return { find: vi.fn(async () => ({ data: [] })), - findOne: vi.fn(async (_o: string, id: string) => ({ id, title: `Policy ${id}`, content: BODY, notes: NOTES })), + findOne: vi.fn(async (_o: string, id: string) => ({ id, title: `Policy ${id}`, content, notes: NOTES })), create: vi.fn(async (_o: string, data: any) => ({ id: 'x', ...data })), update: vi.fn(async (_o: string, id: string, patch: any) => ({ id, ...patch })), delete: vi.fn(async () => true), @@ -107,14 +117,25 @@ const PERMS = { fields: {}, } as MePermissionsAuthenticatedResponse; -async function mount(search: string) { +let navigateTo: NavigateFunction | undefined; +const keepNavigate = (navigate: NavigateFunction) => { + navigateTo = navigate; +}; +function NavigateProbe({ onNavigate }: { onNavigate: (navigate: NavigateFunction) => void }) { + const navigate = useNavigate(); + React.useEffect(() => onNavigate(navigate), [navigate, onNavigate]); + return null; +} + +async function mount(search: string, content = BODY) { const rendered = render( + {}} objectNameOverride={OBJECT_NAME} @@ -193,4 +214,50 @@ describe('a record opened at a cited section (objectstack#37365)', () => { expect(marked(live.container)[0].textContent).toBe('Intro'); expect(scrolled).toHaveLength(1); }); + + it('a same-titled heading the outline does not list opens the field, never that heading; CONTROL: titled otherwise, the cited heading is marked', async () => { + const dup = await mount('?section=scope', SETEXT_BODY); + const field = () => dup.container.querySelector('[data-detail-field="content"]'); + await waitFor(() => expect(field()?.querySelectorAll('h1')).toHaveLength(2), { timeout: 4000 }); + // Both drawn headings read `Scope`; the outline lists one. Nothing is + // marked, and once the settle (RECORD_SECTION_SETTLE_MS) passes the field + // is scrolled to. + expect(marked(dup.container)).toHaveLength(0); + await waitFor(() => expect(scrolled).toEqual([field()]), { timeout: 7000 }); + expect(marked(dup.container)).toHaveLength(0); + cleanup(); + scrolled = []; + const control = await mount('?section=scope', SETEXT_CONTROL); + await waitFor(() => expect(marked(control.container)).toHaveLength(1), { timeout: 4000 }); + expect(marked(control.container)[0].textContent).toBe('Scope'); + expect(marked(control.container)[0].tagName).toBe('H1'); + expect(scrolled).toEqual([marked(control.container)[0]]); + }, 20000); + + it('a second chip moves the mark, and the same chip clicked again scrolls again; CONTROL: a navigation keeping the state does not', 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}`; + // A second chip on the open record: only its section is marked. + await act(async () => { + navigateTo!(`${path}?section=scope-2`, { state: { [RECORD_SECTION_OPENED_STATE]: 'click-2' } }); + }); + await waitFor(() => expect(marked(container)).toEqual([second]), { timeout: 4000 }); + expect(first.hasAttribute(RECORD_SECTION_TARGET_ATTR)).toBe(false); + expect(scrolled).toEqual([first, second]); + // The same chip again: same URL, a fresh state value. + await act(async () => { + navigateTo!(`${path}?section=scope-2`, { state: { [RECORD_SECTION_OPENED_STATE]: 'click-3' } }); + }); + await waitFor(() => expect(scrolled).toEqual([first, second, second]), { timeout: 4000 }); + expect(marked(container)).toEqual([second]); + // CONTROL: a replace that keeps the state (how a tab switch writes the URL). + await act(async () => { + navigateTo!(`${path}?section=scope-2`, { replace: true, state: { [RECORD_SECTION_OPENED_STATE]: 'click-3' } }); + }); + await act(async () => {}); + expect(scrolled).toEqual([first, second, second]); + expect(marked(container)).toEqual([second]); + }); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 968912964e7..8f3ed00cd5f 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -66,7 +66,7 @@ import { import { applySavedRecordEcho } from './recordSaveEcho.js'; import { authoredRecordPageApplies } from './recordPageSurface.js'; import { withPageTabsUrlSync } from '../utils/pageTabsUrlSync.js'; -import { RECORD_COMMENT_PARAM, RECORD_COMMENTS_PARAM, RECORD_SECTION_PARAM, RECORD_COMMENTS_PUSHED_STATE as COMMENTS_PUSHED, RECORD_DETAIL_TAB_PARAM, RECORD_DRAWER_PARAM, RECORD_RELATED_ENLARGE_PARAM, RECORD_RELATED_ENLARGE_PUSHED_STATE as RELATED_ENLARGE_PUSHED, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js'; +import { RECORD_COMMENT_PARAM, RECORD_COMMENTS_PARAM, RECORD_SECTION_PARAM, RECORD_SECTION_OPENED_STATE, RECORD_COMMENTS_PUSHED_STATE as COMMENTS_PUSHED, RECORD_DETAIL_TAB_PARAM, RECORD_DRAWER_PARAM, RECORD_RELATED_ENLARGE_PARAM, RECORD_RELATED_ENLARGE_PUSHED_STATE as RELATED_ENLARGE_PUSHED, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js'; import { focusRecordSection, sectionCandidates } from './recordSectionAnchor.js'; import { resolveActionParams } from '@object-ui/fields'; import { createConsoleServerActionHandler } from '../utils/consoleServerAction.js'; @@ -4943,12 +4943,23 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // ADR-0160 D9 — `?section=ANCHOR`, a passage the assistant cited: once the // record is held, the body heading the anchor names is scrolled to and // marked (`recordSectionAnchor.ts`); a stale anchor leaves the page at its - // top. Judged once per record and anchor. + // top. Judged once per record, anchor and chip click: a click carries a + // 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. const sectionAnchor = tabSearchParams.get(RECORD_SECTION_PARAM) || null; - const citedSectionCandidates = holdsRouteRecord - ? sectionCandidates(objectDef?.fields, readablePageRecord as Record, sectionAnchor) - : []; - const citedSectionKey = citedSectionCandidates.length > 0 ? `${routeRecordKey}\n${sectionAnchor}` : null; + const sectionOpened = (location.state as Record | null)?.[RECORD_SECTION_OPENED_STATE]; + const citedSectionCandidates = useMemo( + () => + holdsRouteRecord + ? sectionCandidates(objectDef?.fields, readablePageRecord as Record, sectionAnchor) + : [], + [holdsRouteRecord, objectDef?.fields, readablePageRecord, sectionAnchor], + ); + const citedSectionKey = + citedSectionCandidates.length > 0 + ? `${routeRecordKey}\n${sectionAnchor}\n${typeof sectionOpened === 'string' ? sectionOpened : ''}` + : null; const citedSectionCandidatesRef = useRef(citedSectionCandidates); citedSectionCandidatesRef.current = citedSectionCandidates; useEffect(() => { diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx index 0d540648051..788137c615a 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.test.tsx @@ -7,8 +7,10 @@ * element among the field's drawn headings by reading, counting repeats. * * The DOM here is written by hand, so the matching is pinned apart from any - * renderer: a heading the outline does not list (a setext heading) must not - * shift a later one onto the wrong section. + * renderer: a heading of another title the outline does not list (a setext + * heading) must not shift a later one onto the wrong section, and when the face + * draws a different number of same-titled headings than the outline lists, the + * field is opened rather than a heading that may be another one. */ import { afterEach, describe, expect, it, vi } from 'vitest'; import { headingsOf } from '@objectstack/spec/ai'; @@ -58,24 +60,24 @@ describe('objectstack#37365 — sectionCandidates derives the anchor as the serv const server = headingsOf(MARKDOWN, false).map((h) => h.anchor); expect(server).toEqual(['intro', 'scope', 'scope-2']); expect(sectionCandidates(FIELDS, RECORD, 'scope')).toEqual([ - { field: 'content', face: 'markdown', reading: 'scope', ordinal: 0 }, + { field: 'content', face: 'markdown', reading: 'scope', ordinal: 0, count: 2 }, ]); expect(sectionCandidates(FIELDS, RECORD, 'scope-2')).toEqual([ - { field: 'content', face: 'markdown', reading: 'scope', ordinal: 1 }, + { field: 'content', face: 'markdown', reading: 'scope', ordinal: 1, count: 2 }, ]); }); it('reads an html body as html', () => { expect(headingsOf(HTML, true).map((h) => h.anchor)).toContain('data-privacy'); expect(sectionCandidates(FIELDS, RECORD, 'data-privacy')).toEqual([ - { field: 'legal', face: 'html', reading: 'dataprivacy', ordinal: 0 }, + { field: 'legal', face: 'html', reading: 'dataprivacy', ordinal: 0, count: 1 }, ]); }); it('a `textarea` body is a candidate drawn as text', () => { const record = { ...RECORD, summary: '# Steps\n\nDo it.' }; expect(sectionCandidates(FIELDS, record, 'steps')).toEqual([ - { field: 'summary', face: 'text', reading: 'steps', ordinal: 0 }, + { field: 'summary', face: 'text', reading: 'steps', ordinal: 0, count: 1 }, ]); }); @@ -100,6 +102,50 @@ describe('objectstack#37365 — locateSection finds the drawn heading', () => { expect(target?.heading?.id).toBe('second'); }); + it('a same-titled heading the outline does not list opens the field, never that heading; CONTROL: titled otherwise, the cited heading is marked', () => { + // A setext `Scope` above `# Scope`: the outline lists only the ATX one + // (`scope`), the face draws both. Index 0 of the drawn `Scope`s would be + // the setext heading. + const body = ['Scope', '=====', '', 'x', '', '# Scope', '', 'y'].join('\n'); + expect(headingsOf(body, false).map((h) => h.anchor)).toEqual(['scope']); + const candidates = sectionCandidates(FIELDS, { content: body }, 'scope'); + expect(candidates).toEqual([{ field: 'content', face: 'markdown', reading: 'scope', ordinal: 0, count: 1 }]); + document.body.innerHTML = row('content', '

Scope

x

Scope

y

'); + const target = locateSection(document.body, candidates); + expect(target?.field.getAttribute('data-detail-field')).toBe('content'); + expect(target?.heading).toBeUndefined(); + // CONTROL: the setext heading titled otherwise; the ATX `Scope` is found. + const control = ['Preface', '=======', '', 'x', '', '# Scope', '', 'y'].join('\n'); + document.body.innerHTML = row('content', '

Preface

x

Scope

y

'); + expect(locateSection(document.body, sectionCandidates(FIELDS, { content: control }, 'scope'))?.heading?.id).toBe('atx'); + }); + + it('a listed heading the face does not draw opens the field, for either anchor; CONTROL: without it, the heading is marked', () => { + // `# Scope` inside a raw HTML block: the outline lists it (`scope`) and the + // real heading after it (`scope-2`); the face draws only the real one. + const body = ['
', '# Scope', '
', '', '# Scope', '', 'y'].join('\n'); + expect(headingsOf(body, false).map((h) => h.anchor)).toEqual(['scope', 'scope-2']); + document.body.innerHTML = row('content', '
# Scope

Scope

y

'); + for (const anchor of ['scope', 'scope-2']) { + const target = locateSection(document.body, sectionCandidates(FIELDS, { content: body }, anchor)); + expect(target?.field.getAttribute('data-detail-field')).toBe('content'); + expect(target?.heading).toBeUndefined(); + } + // CONTROL: the body without the HTML block; `scope` is the drawn heading. + const control = ['# Scope', '', 'y'].join('\n'); + expect(locateSection(document.body, sectionCandidates(FIELDS, { content: control }, 'scope'))?.heading?.id).toBe('real'); + }); + + it('a heading with no letter or digit opens the field; CONTROL: a titled heading beside it is marked', () => { + const body = ['# ???', '', 'x', '', '# Intro', '', 'y'].join('\n'); + const [blank, intro] = headingsOf(body, false); + document.body.innerHTML = row('content', '

???

x

Intro

'); + const target = locateSection(document.body, sectionCandidates(FIELDS, { content: body }, blank.anchor)); + expect(target?.field.getAttribute('data-detail-field')).toBe('content'); + expect(target?.heading).toBeUndefined(); + expect(locateSection(document.body, sectionCandidates(FIELDS, { content: body }, intro.anchor))?.heading?.id).toBe('intro'); + }); + it('matches an html heading by its drawn text', () => { document.body.innerHTML = row('legal', '

Intro

Data & privacy

'); expect(locateSection(document.body, sectionCandidates(FIELDS, RECORD, 'data-privacy'))?.heading?.id).toBe('dp'); @@ -118,7 +164,7 @@ describe('objectstack#37365 — locateSection finds the drawn heading', () => { describe('objectstack#37365 — focusRecordSection', () => { it('scrolls to the heading and marks it', () => { - document.body.innerHTML = row('content', '

Intro

Scope

'); + document.body.innerHTML = row('content', '

Intro

Scope

Scope

'); const scroll = vi.fn(); const heading = document.getElementById('s')!; heading.scrollIntoView = scroll; @@ -136,7 +182,9 @@ describe('objectstack#37365 — focusRecordSection', () => { heading.textContent = 'Scope'; const scroll = vi.fn(); heading.scrollIntoView = scroll; - field.appendChild(heading); + const second = document.createElement('h2'); + second.textContent = 'Scope'; + field.append(heading, second); await new Promise((r) => setTimeout(r, 0)); expect(scroll).toHaveBeenCalledTimes(1); expect(heading.getAttribute(RECORD_SECTION_TARGET_ATTR)).toBe('true'); @@ -167,7 +215,7 @@ describe('objectstack#37365 — focusRecordSection', () => { it('a stale anchor moves nothing; CONTROL: the live anchor on the same page does', () => { vi.useFakeTimers(); - document.body.innerHTML = row('content', '

Intro

Scope

'); + document.body.innerHTML = row('content', '

Intro

Scope

Scope

'); const heading = document.getElementById('s')!; const field = document.querySelector('[data-detail-field="content"]')!; const scroll = vi.fn(); @@ -181,4 +229,33 @@ describe('objectstack#37365 — focusRecordSection', () => { expect(scroll).toHaveBeenCalledTimes(1); expect(heading.getAttribute(RECORD_SECTION_TARGET_ATTR)).toBe('true'); }); + + it('the cleanup takes the mark off, so a second section leaves only itself marked', () => { + document.body.innerHTML = row('content', '

Intro

Scope

Scope

'); + const [a, b] = [document.getElementById('a')!, document.getElementById('b')!]; + a.scrollIntoView = vi.fn(); + b.scrollIntoView = vi.fn(); + const first = focusRecordSection(document.body, sectionCandidates(FIELDS, RECORD, 'scope')); + expect(a.getAttribute(RECORD_SECTION_TARGET_ATTR)).toBe('true'); + expect(a.classList.contains('ring-4')).toBe(true); + first(); + focusRecordSection(document.body, sectionCandidates(FIELDS, RECORD, 'scope-2')); + expect(Array.from(document.querySelectorAll(`[${RECORD_SECTION_TARGET_ATTR}]`))).toEqual([b]); + expect(a.classList.contains('ring-4')).toBe(false); + // A class the heading carried before the mark is left on it. + expect(a.classList.contains('rounded-md')).toBe(true); + }); + + it('the same section opened again scrolls and marks again', () => { + document.body.innerHTML = row('content', '

Intro

Scope

Scope

'); + const a = document.getElementById('a')!; + const scroll = vi.fn(); + a.scrollIntoView = scroll; + const candidates = sectionCandidates(FIELDS, RECORD, 'scope'); + focusRecordSection(document.body, candidates)(); + expect(a.hasAttribute(RECORD_SECTION_TARGET_ATTR)).toBe(false); + focusRecordSection(document.body, candidates); + expect(scroll).toHaveBeenCalledTimes(2); + expect(a.getAttribute(RECORD_SECTION_TARGET_ATTR)).toBe('true'); + }); }); diff --git a/ui/packages/app-shell/src/views/recordSectionAnchor.ts b/ui/packages/app-shell/src/views/recordSectionAnchor.ts index 07c76318ba6..20eec4db25e 100644 --- a/ui/packages/app-shell/src/views/recordSectionAnchor.ts +++ b/ui/packages/app-shell/src/views/recordSectionAnchor.ts @@ -20,13 +20,19 @@ * The heading element is then found in that field's drawn face: among the * field's heading elements, the ones whose letters and digits read the same as * the outline's heading, counted in document order. Counting by reading rather - * than by bare position keeps a heading the outline does not list (a setext - * heading, an empty one, one inside a quote) from shifting every later one onto - * the wrong section. + * than by bare position keeps a heading of another title that the outline does + * not list (a setext heading, an empty one, one inside a quote) from shifting + * every later one onto the wrong section. The count is trusted only when the + * face draws exactly as many headings of that reading as the outline lists: a + * same-titled heading the outline does not list, or a listed one the face does + * not draw, would move the index onto another heading, so then the field is + * opened instead. * * - A `textarea` body draws no heading elements, so the field is scrolled to. - * - A heading that is not drawn (the face has not rendered it, or reads it - * differently) also scrolls to the field, with no error. + * - A heading that is not drawn (the face has not rendered it, reads it + * differently, or draws a different number of same-titled headings than the + * outline lists) also scrolls to the field, with no error. So does a heading + * with no letter or digit, which no reading tells apart. * - An anchor no field resolves (a stale one: the heading was renamed or * removed) opens the record at its top, as if no section were named. * @@ -75,6 +81,8 @@ export interface SectionCandidate { reading: string; /** How many of the field's earlier headings read the same. */ ordinal: number; + /** How many of the field's headings, in all, read the same: what the drawn face must match. */ + count: number; } /** What a drawn section resolved to: the field's row, and the heading when it is drawn. */ @@ -108,19 +116,23 @@ export function sectionCandidates( const at = headings.findIndex((h) => h.anchor === anchor); if (at < 0) continue; const reading = headingReading(headings[at].heading); - const ordinal = headings.slice(0, at).filter((h) => headingReading(h.heading) === reading).length; - out.push({ field, face, reading, ordinal }); + const readings = headings.map((h) => headingReading(h.heading)); + const ordinal = readings.slice(0, at).filter((r) => r === reading).length; + const count = readings.filter((r) => r === reading).length; + out.push({ field, face, reading, ordinal, count }); } return out; } function escapeAttr(value: string): string { + if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(value); return value.replace(/["\\]/g, '\\$&'); } /** * The drawn place of the first candidate whose field is on the page: the - * field's row, with the heading when the face draws it. `undefined` when no + * field's row, with the heading when the face draws it, and draws as many + * headings of its reading as the outline lists. `undefined` when no * candidate's field is drawn. */ export function locateSection(root: ParentNode, candidates: readonly SectionCandidate[]): SectionTarget | undefined { @@ -128,19 +140,28 @@ export function locateSection(root: ParentNode, candidates: readonly SectionCand const field = root.querySelector(`[${DETAIL_FIELD_ATTR}="${escapeAttr(candidate.field)}"]`); if (!field) continue; const { face } = candidate; - if (face === 'text') return { field, face }; - const heading = Array.from(field.querySelectorAll('h1, h2, h3, h4, h5, h6')).filter( + if (face === 'text' || candidate.reading === '') return { field, face }; + const drawn = Array.from(field.querySelectorAll('h1, h2, h3, h4, h5, h6')).filter( (el) => headingReading(el.textContent ?? '') === candidate.reading, - )[candidate.ordinal]; + ); + const heading = drawn.length === candidate.count ? drawn[candidate.ordinal] : undefined; return heading ? { field, face, heading } : { field, face }; } return undefined; } -/** Marks `heading` as the cited section. */ -export function markSection(heading: HTMLElement): void { +/** + * Marks `heading` as the cited section. Answers the unmark, which takes off + * the attribute and only the classes the mark added. + */ +export function markSection(heading: HTMLElement): () => void { + const added = RECORD_SECTION_MARK_CLASSES.filter((c) => !heading.classList.contains(c)); heading.setAttribute(RECORD_SECTION_TARGET_ATTR, 'true'); - heading.classList.add(...RECORD_SECTION_MARK_CLASSES); + heading.classList.add(...added); + return () => { + heading.removeAttribute(RECORD_SECTION_TARGET_ATTR); + heading.classList.remove(...added); + }; } function scrollTo(el: HTMLElement): void { @@ -152,7 +173,8 @@ function scrollTo(el: HTMLElement): void { * to and marked, or the field scrolled to (a `textarea` body at once, any * other once {@link RECORD_SECTION_SETTLE_MS} pass without the heading). With * no candidate, or no candidate field drawn by then, nothing moves. Answers - * the cleanup. + * 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. */ export function focusRecordSection( root: HTMLElement, @@ -162,18 +184,23 @@ export function focusRecordSection( if (candidates.length === 0) return () => {}; let done = false; let observer: MutationObserver | undefined; - const pending: { timer?: ReturnType } = {}; + const pending: { timer?: ReturnType; unmark?: () => void } = {}; const finish = (): void => { done = true; observer?.disconnect(); if (pending.timer !== undefined) clearTimeout(pending.timer); }; + const cleanup = (): void => { + finish(); + pending.unmark?.(); + pending.unmark = undefined; + }; const attempt = (): void => { if (done) return; const target = locateSection(root, candidates); if (target?.heading) { finish(); - markSection(target.heading); + pending.unmark = markSection(target.heading); scrollTo(target.heading); } else if (target?.face === 'text') { finish(); @@ -181,7 +208,7 @@ export function focusRecordSection( } }; attempt(); - if (done) return finish; + if (done) return cleanup; if (typeof MutationObserver === 'function') { observer = new MutationObserver(attempt); observer.observe(root, { childList: true, subtree: true, characterData: true }); @@ -191,11 +218,11 @@ export function focusRecordSection( const target = locateSection(root, candidates); finish(); if (target?.heading) { - markSection(target.heading); + pending.unmark = markSection(target.heading); scrollTo(target.heading); } else if (target) { scrollTo(target.field); } }, settleMs); - return finish; + return cleanup; } diff --git a/ui/packages/plugin-chatbot/README.md b/ui/packages/plugin-chatbot/README.md index c1bff169ab8..26859066be0 100644 --- a/ui/packages/plugin-chatbot/README.md +++ b/ui/packages/plugin-chatbot/README.md @@ -470,11 +470,12 @@ the grouping, the aggregations, how many records the figures cover, and whether only the reader's visible records were read. It draws that block alone, never the rest of the tool payload. -An answer that rests on records draws its verified citations (the -`data-record-citations` part, `RecordCitationsSchema` in `@objectstack/spec/ai`) -beside that block, one chip per citation showing the quoted passage. The list is -drawn as the platform verified it when the answer was produced, never verified -again; a part that does not parse draws nothing. A chip calls +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 `onOpenRecord({ objectName, recordId, anchor })`, and the console opens the record at the cited body section (`?section=ANCHOR`).