diff --git a/.changeset/39507-cited-passage-reader.md b/.changeset/39507-cited-passage-reader.md new file mode 100644 index 00000000000..c6fc6bb8262 --- /dev/null +++ b/.changeset/39507-cited-passage-reader.md @@ -0,0 +1,17 @@ +--- +'@object-ui/plugin-chatbot': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): a cited passage opens where the answer quotes it, in a body reader beside the conversation + +Clause-②: yes (widening) +Metadata-protocol: none + +Who sees it: anyone reading an AI answer that cites records (ADR-0160 D9, as amended for objectstack-ai/objectstack#39505). What is drawn as a citation is the turn's verified list, no more and no fewer: a passage the answer quotes that the turn did not cite stays plain text. + +- **The passages the answer quotes are the links** (`@object-ui/plugin-chatbot`, inside `ChatbotEnhanced`). Once the answer has finished, each passage of the answer that quotes a verified citation, whole or as an excerpt inside quotation marks, is underlined; a click opens that citation's record at the passage through the host's `onOpenRecord`, which now also receives `quote`, `context` and `siblingQuotes` (the answer's other cited passages of the same record). An ellipsis, or the `|` of a quoted table row, splits an excerpt into pieces that each must be in the passage; the block quoting the most of a passage is the one marked. A record link in a cited answer opens its record with every passage of it the answer cites. A citation the answer does not quote is listed as a chip under it, as before. A turn's citations are drawn once, under its answer. +- **Citations survive a reload.** The chat (`@object-ui/plugin-chatbot`, internally) reads a stored message's verified list back off its last `cite_records` result when the message carries no citation part. The exported `hydratedMessagesToChatMessages` (`@object-ui/app-shell`) now moves a turn's `recordCitations` to the turn's last assistant message and removes them from the turn's earlier rows. +- **The body reader** (`@object-ui/app-shell`, internal to the console's chat). A cited open shows the record's body alone, beside the conversation: the field its context pack declares as `body` (else a long-text field that holds the passage), scrolled to the passage and marked, with the answer's other cited passages of that record marked lightly. Its inner edge resizes it (remembered per browser), and it closes when the page changes. The `ai:chat` page opens it on the right, the assistant drawer's rail on the left (the right in its full window); on a phone there is no reader. Only a cited open goes to the reader; every other record link and the `open_record` card open as before. +- `@object-ui/i18n`: `chatbot.recordReader.*` and `chatbot.toolCalls.cite_records` in every pack. diff --git a/ui/packages/app-shell/src/console/ai/AppAskPage.tsx b/ui/packages/app-shell/src/console/ai/AppAskPage.tsx index e42c4d7af60..cbc627cd0e2 100644 --- a/ui/packages/app-shell/src/console/ai/AppAskPage.tsx +++ b/ui/packages/app-shell/src/console/ai/AppAskPage.tsx @@ -353,6 +353,10 @@ export function AppAskPage() { // objectstack#38463 — an answer's links open in a new tab, so the // question asked here stays on the page (ruling 7302940124). openLinksInNewTab + // A record opened for a cited passage opens beside the conversation, its body alone + // (RecordReaderDrawer.tsx); on a phone there is no reader, and a record + // opens as it always has. + recordReaderSide={phone ? undefined : 'right'} presentation={presentation} historyOpen={phone && historyOver} onHistoryOpenChange={phone ? setHistoryOver : undefined} diff --git a/ui/packages/app-shell/src/console/ai/ChatPane.tsx b/ui/packages/app-shell/src/console/ai/ChatPane.tsx index 29079d6d2df..6e812b11bb1 100644 --- a/ui/packages/app-shell/src/console/ai/ChatPane.tsx +++ b/ui/packages/app-shell/src/console/ai/ChatPane.tsx @@ -88,6 +88,7 @@ import { useComposerDraftHandoff, type PendingFirstMessage, } from './useDeferredFirstSend.js'; +import { useRecordReader } from './recordReader.js'; interface ChatPaneProps { /** @@ -262,8 +263,31 @@ export function ChatPane({ }, [routerRootHref], ); + // The `ai:chat` page's body reader (`RecordReaderDrawer.tsx`): where the + // host offers one, a record an answer cites or links opens in it, the body + // alone at the cited passage, and the conversation stays where it is. + const recordReader = useRecordReader(); const openRecord = useCallback( - async (handoff: { objectName: string; recordId: string; anchor?: string }) => { + async (handoff: { objectName: string; recordId: string; anchor?: string; quote?: string; siblingQuotes?: string[]; context?: string }) => { + // Only a record opened FOR a passage (a cited quote, or a 出处 link whose + // answer cites passages of it) goes to the body reader; any other + // record link or `open_record` card opens the record as before. + if (recordReader && (handoff.quote || handoff.siblingQuotes?.length)) { + recordReader.open( + { + objectName: handoff.objectName, + recordId: handoff.recordId, + ...(handoff.anchor ? { anchor: handoff.anchor } : {}), + ...(handoff.quote ? { quote: handoff.quote } : {}), + ...(handoff.siblingQuotes?.length ? { siblingQuotes: handoff.siblingQuotes } : {}), + ...(handoff.context ? { context: handoff.context } : {}), + }, + () => { + void appOfObject(handoff.objectName).then((app) => openInNewTab(recordOpenTarget(app, handoff))); + }, + ); + return; + } const app = await appOfObject(handoff.objectName); const to = recordOpenTarget(app, handoff); if (openLinksInNewTab) { @@ -272,7 +296,7 @@ export function ChatPane({ } navigate(to, handoff.anchor ? { state: { [RECORD_SECTION_OPENED_STATE]: nextSectionOpening() } } : undefined); }, - [navigate, openLinksInNewTab, openInNewTab], + [navigate, openLinksInNewTab, openInNewTab, recordReader], ); // objectstack#31869 — a `/list/OBJECT` link in an answer opens that list. diff --git a/ui/packages/app-shell/src/console/ai/RecordReaderDrawer.tsx b/ui/packages/app-shell/src/console/ai/RecordReaderDrawer.tsx new file mode 100644 index 00000000000..c5b12d9d888 --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/RecordReaderDrawer.tsx @@ -0,0 +1,419 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The body reader beside an AI conversation: a record opened for a passage + * (a cited quote, or a 出处 link of an answer that cites passages of that + * record) opens in a drawer that shows the record's BODY alone and, for a + * citation, scrolls to the cited passage and marks it. The conversation stays + * where it is beside it. The host names the side: the `ai:chat` page opens it + * on the right, the assistant drawer's rail on the left (the right in its full + * window); on a phone there is no reader. + * + * - **Which field is the body.** The field a context pack declares for the + * object as `body.field` (ADR-0160 D1), the citation's own pack first, when + * the record holds the quote there. Otherwise the record's long-text fields + * (`markdown`, `html`, `richtext`, `textarea`), in the object's field order: + * with a quote, the first one that holds it; without one, the first that has + * text, a `markdown` / `html` / `richtext` field before a `textarea`. + * - **How the passage is found.** By reading, not by source: the drawn text of + * the body's blocks (paragraphs, list items, cells, headings) and the quote + * are both read as their letters and digits only, so markdown markup + * (`**第五条**`), entities and line breaks do not stop a match. The blocks + * the quote spans are marked and the first is scrolled to the middle. A quote + * that is not found as a whole is looked for by its first 24 letters and + * digits; not found either, the body opens at its top with a notice. + * - **What it reads.** One `findOne` and the object's schema through the + * console's adapter, and the context packs this user is served + * (`GET /meta/ai_context`, once per client), as the signed-in user: a field + * the user may not read is not drawn. + * + * Nothing here verifies a citation: what the chip carries was verified when + * the answer was produced (ADR-0160 D9). + */ + +import * as React from 'react'; +import { ExternalLink, FileText } from 'lucide-react'; +import { + Button, + Sheet, + SheetContent, + SheetDescription, + SheetHeader, + SheetTitle, +} from '@object-ui/components'; +import { HtmlCellRenderer, MarkdownCellRenderer } from '@object-ui/fields'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { useAdapter } from '@object-ui/react'; +import { useLocation } from 'react-router-dom'; +import { declaredBodyFields, locateQuote, pickBodyField, readPacks, RecordReaderContext, type BodyType, type ReaderPack, type RecordReaderApi, type RecordReaderTarget } from './recordReader.js'; + +/** The record's title, as the console names a record: its display field, else a usual name field. */ +function titleOf(schema: unknown, record: Record): string { + const s = (schema ?? {}) as { titleFormat?: unknown; nameField?: unknown; displayNameField?: unknown }; + for (const key of [s.displayNameField, s.nameField, 'display_name', 'name', 'title']) { + const v = typeof key === 'string' ? record[key] : undefined; + if (typeof v === 'string' && v.trim()) return v; + } + return String(record.id ?? ''); +} + +/** The attribute a marked block carries. */ +const MARK_ATTR = 'data-record-reader-mark'; +/** The passage the click opened at. */ +const MARK_CLASSES = ['rounded-sm', 'bg-yellow-200/70', 'dark:bg-yellow-500/30', 'ring-4', 'ring-yellow-200/70', 'dark:ring-yellow-500/30']; +/** The answer's other passages of the record: the same colour, lighter, so the cited places read at a glance. */ +const SIBLING_MARK_CLASSES = ['rounded-sm', 'bg-yellow-200/30', 'dark:bg-yellow-500/15']; + +/** How long the reader waits for the body to be drawn before it settles. */ +const SETTLE_MS = 4000; + +/** Where the reader's dragged width is remembered, per browser. */ +const READER_WIDTH_KEY = 'objectstack:record-reader-width'; +const READER_MIN_WIDTH = 360; + +function readStoredWidth(): number | null { + try { + const raw = window.localStorage.getItem(READER_WIDTH_KEY); + const n = raw ? Number.parseInt(raw, 10) : NaN; + return Number.isFinite(n) && n >= READER_MIN_WIDTH ? n : null; + } catch { + return null; + } +} + +/** The widest the reader may be: most of the window, so the conversation stays in reach. */ +function maxReaderWidth(): number { + return Math.max(READER_MIN_WIDTH, Math.round(window.innerWidth * 0.85)); +} + +/** + * The reader's width: dragged on its inner edge, remembered across visits; + * `null` until the reader is dragged (the sheet's own width applies). + * A double click on the edge goes back to that width. + */ +function useReaderWidth(side: 'left' | 'right') { + const [width, setWidth] = React.useState(() => (typeof window === 'undefined' ? null : readStoredWidth())); + // The drag in progress, ended on unmount too, so no listener or body style outlives the reader. + const endDrag = React.useRef<(() => void) | null>(null); + React.useEffect(() => () => endDrag.current?.(), []); + const onPointerDown = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return; + e.preventDefault(); + const handle = e.currentTarget; + const sheet = (handle.parentElement as HTMLElement | null) ?? null; + const pointerId = e.pointerId; + const startX = e.clientX; + const startWidth = sheet?.getBoundingClientRect().width ?? width ?? 576; + let latest = startWidth; + let moved = false; + const prevCursor = document.body.style.cursor; + const prevSelect = document.body.style.userSelect; + document.body.style.cursor = 'col-resize'; + document.body.style.userSelect = 'none'; + try { + handle.setPointerCapture(pointerId); + } catch { + // A pointer that cannot be captured still drags through the window listeners. + } + const onMove = (ev: PointerEvent) => { + if (ev.pointerId !== pointerId) return; + const delta = side === 'right' ? startX - ev.clientX : ev.clientX - startX; + if (Math.abs(delta) >= 2) moved = true; + latest = Math.min(maxReaderWidth(), Math.max(READER_MIN_WIDTH, Math.round(startWidth + delta))); + if (moved) setWidth(latest); + }; + const finish = (keep: boolean) => { + window.removeEventListener('pointermove', onMove); + window.removeEventListener('pointerup', onUp); + window.removeEventListener('pointercancel', onCancel); + document.body.style.cursor = prevCursor; + document.body.style.userSelect = prevSelect; + endDrag.current = null; + // A plain click on the edge changes nothing and remembers nothing. + if (!keep || !moved) return; + try { + window.localStorage.setItem(READER_WIDTH_KEY, String(latest)); + } catch { + // Private mode or a full store: the width lasts until the page reloads. + } + }; + const onUp = (ev: PointerEvent) => { + if (ev.pointerId === pointerId) finish(true); + }; + const onCancel = (ev: PointerEvent) => { + if (ev.pointerId === pointerId) finish(false); + }; + window.addEventListener('pointermove', onMove); + window.addEventListener('pointerup', onUp); + window.addEventListener('pointercancel', onCancel); + endDrag.current = () => finish(false); + }, + [side, width], + ); + const onDoubleClick = React.useCallback(() => { + setWidth(null); + try { + window.localStorage.removeItem(READER_WIDTH_KEY); + } catch { + // Nothing remembered to forget. + } + }, []); + return { width, onPointerDown, onDoubleClick }; +} + +type Loaded = + | { state: 'loading' } + | { state: 'failed' } + | { state: 'ready'; title: string; objectLabel?: string; field?: { name: string; type: BodyType; label?: string }; value?: string }; + +/** One record's read: what the body is picked from on every click. */ +type RecordRead = + | { key: string; state: 'ready'; record: Record; schema: unknown; packs: ReaderPack[] } + | { key: string; state: 'failed' }; + +/** + * The reader's host: provides {@link RecordReaderContext} to the chat below + * it and draws the drawer. + */ +export function RecordReaderHost({ + children, + side = 'right', +}: { + children: React.ReactNode; + /** + * The edge the reader opens from: `right` beside a full-page conversation + * (the `ai:chat` page), `left` where the assistant's drawer already holds + * the right edge, so the body opens over the page, facing the conversation. + */ + side?: 'left' | 'right'; +}) { + const { t } = useObjectTranslation(); + const adapter = useAdapter() as unknown as { + findOne?: (object: string, id: string) => Promise; + getObjectSchema?: (object: string) => Promise; + } | null; + const [target, setTarget] = React.useState<(RecordReaderTarget & { openFull: () => void; seq: number }) | null>(null); + const [read, setRead] = React.useState(null); + // The click (`seq`) whose passage could not be found; the notice shows for that click only. + const [missedSeq, setMissedSeq] = React.useState(-1); + const bodyRef = React.useRef(null); + const seqRef = React.useRef(0); + const resize = useReaderWidth(side); + + // The reader belongs to the page it was opened on: moving to another page + // (a menu entry, a record link, Back) closes it, so it never lies over a + // page it was not opened for. The query string is not a move: the chat page + // writes its own (`?c=`) as a conversation starts. + const { pathname } = useLocation(); + const openedOn = React.useRef(pathname); + React.useEffect(() => { + if (openedOn.current === pathname) return; + openedOn.current = pathname; + setTarget(null); + }, [pathname]); + + const api = React.useMemo( + () => ({ + open(next, openFull) { + seqRef.current += 1; + setTarget({ ...next, openFull, seq: seqRef.current }); + }, + }), + [], + ); + + // Read the record, its schema and the packs whenever another record is opened. + const recordKey = target ? `${target.objectName}:${target.recordId}` : ''; + React.useEffect(() => { + if (!target || !adapter?.findOne) return; + let live = true; + const key = recordKey; + (async () => { + try { + const [record, schema, packs] = await Promise.all([ + adapter.findOne!(target.objectName, target.recordId), + adapter.getObjectSchema ? adapter.getObjectSchema(target.objectName).catch(() => null) : Promise.resolve(null), + readPacks(adapter), + ]); + if (live) setRead({ key, state: 'ready', record: (record ?? {}) as Record, schema, packs }); + } catch { + if (live) setRead({ key, state: 'failed' }); + } + })(); + return () => { + live = false; + }; + // A new click on the same record keeps the read; the body is picked again below. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [recordKey, adapter]); + + // The body for THIS click: a later citation of the same record may sit in + // another field. A read of another record is never drawn under this one. + const loaded = React.useMemo(() => { + if (!target || !read || read.key !== recordKey) return { state: 'loading' }; + if (read.state === 'failed') return { state: 'failed' }; + const field = pickBodyField(read.schema, read.record, target.quote, declaredBodyFields(read.packs, target.objectName, target.context)); + const objectLabel = (read.schema as { label?: unknown } | null)?.label; + return { + state: 'ready', + title: titleOf(read.schema, read.record), + ...(typeof objectLabel === 'string' ? { objectLabel } : {}), + ...(field ? { field, value: read.record[field.name] as string } : {}), + }; + }, [read, recordKey, target]); + + // Locate the passage once the body is drawn; again on every click. + const seq = target?.seq ?? 0; + React.useEffect(() => { + if (!target || loaded.state !== 'ready' || !loaded.field) return; + const quote = target.quote; + const root = bodyRef.current; + if (!root) return; + for (const el of Array.from(root.querySelectorAll(`[${MARK_ATTR}]`))) { + el.removeAttribute(MARK_ATTR); + el.classList.remove(...MARK_CLASSES, ...SIBLING_MARK_CLASSES); + } + const siblings = target.siblingQuotes ?? []; + if (!quote) { + // Opened as the record (a 出处 link): from its top, with the answer's + // cited passages of it marked lightly, so they read at a glance. + root.scrollTop = 0; + if (siblings.length === 0) return; + } + let done = false; + const tryLocate = (): boolean => { + if (!quote) { + let marked = false; + for (const other of siblings) { + for (const el of locateQuote(root, other) ?? []) { + el.setAttribute(MARK_ATTR, 'sibling'); + el.classList.add(...SIBLING_MARK_CLASSES); + marked = true; + } + } + return marked; + } + const hit = locateQuote(root, quote); + if (!hit) return false; + // The other passages first, so the clicked one's stronger mark wins where they share a block. + for (const other of siblings) { + for (const el of locateQuote(root, other) ?? []) { + if (hit.includes(el)) continue; + el.setAttribute(MARK_ATTR, 'sibling'); + el.classList.add(...SIBLING_MARK_CLASSES); + } + } + for (const el of hit) { + el.setAttribute(MARK_ATTR, 'active'); + el.classList.add(...MARK_CLASSES); + } + // Scrolled to, not jumped to, so the reader sees where the passage sits; + // a reader who asked the system for less motion gets the jump. + const reduce = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches; + hit[0].scrollIntoView({ block: 'center', behavior: reduce ? 'auto' : 'smooth' }); + return true; + }; + if (tryLocate()) return; + const observer = new MutationObserver(() => { + if (!done && tryLocate()) { + done = true; + observer.disconnect(); + } + }); + observer.observe(root, { childList: true, subtree: true, characterData: true }); + const timer = window.setTimeout(() => { + observer.disconnect(); + // Only a clicked passage that cannot be found is said; a record opened whole has nothing to miss. + if (!done && quote) setMissedSeq(target.seq); + }, SETTLE_MS); + return () => { + done = true; + observer.disconnect(); + window.clearTimeout(timer); + }; + }, [seq, loaded, target]); + + const open = target !== null; + return ( + + {children} + (next ? undefined : setTarget(null))} modal={false}> + e.preventDefault()} + style={ + resize.width != null && typeof window !== 'undefined' && window.innerWidth >= 640 + ? { width: Math.min(resize.width, maxReaderWidth()), maxWidth: 'none' } + : undefined + } + > + {/* The inner edge drags the reader wider or narrower; a double click restores its width. */} +