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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/37365-record-citation-chips.md
Original file line number Diff line number Diff line change
@@ -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): 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

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; 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.
2 changes: 2 additions & 0 deletions content/docs/frontend/plugins/plugin-chatbot.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

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.<tool_name>` 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.
Expand Down
37 changes: 35 additions & 2 deletions ui/packages/app-shell/src/console/ai/AiChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ import {
type OutboundAgentTextKey,
} from './outboundAgentText.js';
import { resolveApiBase } from './resolveApiBase.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';
Expand Down Expand Up @@ -216,6 +217,30 @@ 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()}`;
}

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;
Expand Down Expand Up @@ -1917,11 +1942,19 @@ 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. 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 }) => {
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)}`,
recordOpenTarget(app, handoff),
handoff.anchor ? { state: { [RECORD_SECTION_OPENED_STATE]: nextSectionOpening() } } : undefined,
);
},
[navigate],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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).';

Expand All @@ -29,7 +30,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<Record<string, unknown>>();
Expand All @@ -38,7 +39,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,
Expand Down Expand Up @@ -112,7 +118,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' },
Expand All @@ -122,6 +130,7 @@ beforeEach(() => {
});
afterEach(() => {
answerNow.content = '';
answerNow.recordCitations = undefined;
cleanup();
vi.unstubAllGlobals();
window.history.replaceState(null, '', '/');
Expand Down Expand Up @@ -168,3 +177,65 @@ 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('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<string, unknown> | 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('/');
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('');
});
});
24 changes: 24 additions & 0 deletions ui/packages/app-shell/src/urlParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`).| |
Expand Down Expand Up @@ -164,6 +168,25 @@ 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 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
Expand Down Expand Up @@ -224,6 +247,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,
Expand Down
Loading
Loading