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
10 changes: 10 additions & 0 deletions .changeset/39507-cite-records-envelope-read.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/plugin-chatbot': patch
---

chore(chatbot): a stored `cite_records` result is read through `parseResultEnvelope` alone

Clause-②: no
Metadata-protocol: none

No behaviour change. Reading a stored message's verified citations back off its last `cite_records` result had a second unwrap of the `{ type: 'text', value }` envelope. `parseResultEnvelope` already removes that envelope, so the extra unwrap is gone.
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,39 @@ describe('AiChatPage hydration — the turn a reloaded message was stored under
expect('turnId' in chat[3]).toBe(false);
});
});

describe('AiChatPage hydration — a turn\'s citations land on its answer (objectstack#39507)', () => {
const CITATION = { object: 'policy', id: 'pol_7', quote: 'Applies to every contractor on site.' };
const citeRow = (id: string, output: unknown): HydratedUIMessage => ({
id,
role: 'assistant',
parts: [{ type: 'tool-cite_records', toolCallId: `c-${id}`, toolName: 'cite_records', state: 'output-available', output }],
});

it('the stored cite_records step\'s list moves to the turn\'s last assistant message, and the next turn carries none', () => {
const chat = hydratedMessagesToChatMessages([
{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'Who does the policy cover?' }] },
citeRow('a1', { type: 'text', value: JSON.stringify({ citations: [CITATION] }) }),
{ id: 'a2', role: 'assistant', parts: [{ type: 'text', text: 'Every contractor on site.' }] },
{ id: 'u2', role: 'user', parts: [{ type: 'text', text: 'Thanks' }] },
{ id: 'a3', role: 'assistant', parts: [{ type: 'text', text: 'You are welcome.' }] },
]);
const byId = Object.fromEntries(chat.map((m) => [m.id, m]));
expect('recordCitations' in byId.a1).toBe(false);
expect(byId.a2.recordCitations).toEqual([CITATION]);
expect('recordCitations' in byId.a3).toBe(false);
});

it('a turn\'s last message that carries its own list keeps it; CONTROL: a single cited answer is unchanged', () => {
const own = { ...CITATION, quote: 'Revision 3 published 2026-10-01' };
const chat = hydratedMessagesToChatMessages([
{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'q' }] },
citeRow('a1', { citations: [CITATION] }),
citeRow('a2', { citations: [own] }),
]);
expect('recordCitations' in chat[1]).toBe(false);
expect(chat[2].recordCitations).toEqual([own]);
const [single] = hydratedMessagesToChatMessages([citeRow('a9', { citations: [CITATION] })]);
expect(single.recordCitations).toEqual([CITATION]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
*/

import '@testing-library/jest-dom/vitest';
// ChatPane reaches `import('@object-ui/plugin-grid')`; load it here so collection pays
// that transform, not a clocked case (check-test-source-alias).
import '@object-ui/plugin-grid';
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';
Expand All @@ -30,7 +33,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: '', recordCitations: undefined as unknown }));
const answerNow = vi.hoisted(() => ({ content: '', recordCitations: undefined as unknown, toolInvocations: undefined as unknown }));

vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
Expand All @@ -44,6 +47,7 @@ vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => {
role: 'assistant',
content: answerNow.content || ANSWER,
...(answerNow.recordCitations ? { recordCitations: answerNow.recordCitations } : {}),
...(answerNow.toolInvocations ? { toolInvocations: answerNow.toolInvocations } : {}),
},
],
isLoading: false,
Expand All @@ -69,6 +73,7 @@ vi.mock('../../../providers/AdapterProvider', async (importOriginal) => {
import { I18nProvider } from '@object-ui/i18n';
import type { AgentDescriptor } from '@object-ui/plugin-chatbot';
import { ChatPane } from '../AiChatPage';
import { RecordReaderContext, type RecordReaderApi } from '../recordReader';

window.matchMedia = ((query: string) => ({
matches: false,
Expand All @@ -83,11 +88,12 @@ window.matchMedia = ((query: string) => ({

const AGENTS = [{ name: 'ask', label: 'Ask' }] as unknown as AgentDescriptor[];

function renderPane(basename: string) {
function renderPane(basename: string, reader?: RecordReaderApi) {
window.history.replaceState(null, '', `${basename === '/' ? '' : basename}/ai/ask/conv-1`);
render(
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}>
<BrowserRouter basename={basename}>
<RecordReaderContext.Provider value={reader ?? null}>
<ChatPane
agents={AGENTS}
agentsLoading={false}
Expand All @@ -101,6 +107,7 @@ function renderPane(basename: string) {
onSent={vi.fn()}
onShare={vi.fn()}
/>
</RecordReaderContext.Provider>
</BrowserRouter>
</I18nProvider>,
);
Expand Down Expand Up @@ -131,6 +138,7 @@ beforeEach(() => {
afterEach(() => {
answerNow.content = '';
answerNow.recordCitations = undefined;
answerNow.toolInvocations = undefined;
cleanup();
vi.unstubAllGlobals();
window.history.replaceState(null, '', '/');
Expand Down Expand Up @@ -239,3 +247,81 @@ describe('objectstack#37365 — a record citation opens the record at the cited
expect(window.location.search).toBe('');
});
});

/**
* objectstack#39507 — with a body reader mounted (`RecordReaderContext`), only
* a record opened FOR a passage goes to it: a cited quote, or a record link of
* an answer that cites passages of that record. A plain record link and the
* `open_record` card still open the record page.
*/
describe('objectstack#39507 — only a cited open reaches the body reader', () => {
const CITATION = { object: 'policy', id: 'pol_7', context: 'policy_document', anchor: 'scope', quote: 'Applies to every contractor on site.' };
const reader = () => ({ open: vi.fn() });

it('a quoted cited passage opens in the reader at the passage, and the page does not move', async () => {
answerNow.content = `- Scope: "${CITATION.quote}"`;
answerNow.recordCitations = [CITATION];
const r = reader();
renderPane('/', r);
await waitFor(() => expect(document.querySelector('[data-cited-passage]')).not.toBeNull());
await act(async () => {
fireEvent.click(document.querySelector('[data-cited-passage]')!);
});
expect(r.open).toHaveBeenCalledTimes(1);
expect(r.open.mock.calls[0][0]).toEqual({
objectName: 'policy',
recordId: 'pol_7',
anchor: 'scope',
quote: CITATION.quote,
context: 'policy_document',
});
expect(window.location.pathname).toBe('/ai/ask/conv-1');
});

it('a cited answer\'s record link opens in the reader with the passages it cites', async () => {
answerNow.content = `- Scope: "${CITATION.quote}"\n\n**出处**\n- [Site safety policy](/record/policy/pol_7)`;
answerNow.recordCitations = [CITATION];
const r = reader();
renderPane('/', r);
await waitFor(() => expect(document.querySelector('[data-cited-passage]')).not.toBeNull());
await act(async () => {
fireEvent.click(await screen.findByRole('button', { name: 'Site safety policy' }));
});
expect(r.open).toHaveBeenCalledTimes(1);
expect(r.open.mock.calls[0][0]).toEqual({ objectName: 'policy', recordId: 'pol_7', siblingQuotes: [CITATION.quote] });
});

it('a plain record link still opens the record page; the reader is not called', async () => {
const r = reader();
renderPane('/', r);
await act(async () => {
fireEvent.click(await screen.findByRole('button', { name: 'Wayne Enterprises' }));
});
await waitFor(() => expect(window.location.pathname).toBe('/apps/com.acme.crm/account/record/acc_42'));
expect(r.open).not.toHaveBeenCalled();
});

it('the open_record card still opens the record page; the reader is not called', async () => {
answerNow.content = 'Here is the record.';
answerNow.toolInvocations = [
{
toolCallId: 't1',
toolName: 'open_record',
state: 'output-available',
recordHandoff: { objectName: 'account', recordId: 'acc_42', label: 'Wayne Enterprises' },
},
];
const r = reader();
renderPane('/', r);
let open = screen.queryByTestId('record-handoff-open');
if (!open) {
fireEvent.click(await screen.findByText(/open_record|Open this record|Open the record/i));
open = await screen.findByTestId('record-handoff-open');
}
await act(async () => {
fireEvent.click(open!);
});
await waitFor(() => expect(window.location.pathname).toBe('/apps/com.acme.crm/account/record/acc_42'));
expect(r.open).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#39507 — the body reader draws the field a context pack declares
* as `body.field` (ADR-0160 D1), the field the citation was verified against,
* before any other long-text field of the record.
*/

import { describe, expect, it } from 'vitest';
import { declaredBodyFields, pickBodyField } from '../recordReader';

const SCHEMA = {
fields: {
summary: { type: 'markdown', label: 'Summary' },
notes: { type: 'textarea', label: 'Notes' },
content: { type: 'markdown', label: 'Content' },
},
};
const RECORD = {
summary: 'A short summary that also says: no ladder may stand on a pallet.',
notes: 'Internal notes.',
content: 'Article 10. No ladder may stand on a pallet. Article 11. Hard hats on site.',
};

describe('objectstack#39507 — pickBodyField', () => {
it('prefers the declared body field over an earlier long-text field; CONTROL: with no pack, the first markdown field', () => {
expect(pickBodyField(SCHEMA, RECORD, undefined, ['content'])?.name).toBe('content');
expect(pickBodyField(SCHEMA, RECORD, 'no ladder may stand on a pallet', ['content'])?.name).toBe('content');
expect(pickBodyField(SCHEMA, RECORD, undefined)?.name).toBe('summary');
});

it('a declared body that does not hold the quote yields to a field that does', () => {
expect(pickBodyField(SCHEMA, RECORD, 'Hard hats on site', ['summary'])?.name).toBe('content');
});

it('the citation\'s own pack comes first among the packs declaring a body for the object', () => {
const packs = [
{ name: 'policy_summary', object: 'policy', body: { field: 'summary' } },
{ name: 'policy_document', object: 'policy', body: { field: 'content' } },
{ name: 'other', object: 'account', body: { field: 'notes' } },
];
expect(declaredBodyFields(packs, 'policy', 'com.acme-policy_document')).toEqual(['content', 'summary']);
expect(pickBodyField(SCHEMA, RECORD, undefined, declaredBodyFields(packs, 'policy', 'policy_document'))?.name).toBe('content');
});
});
10 changes: 4 additions & 6 deletions ui/packages/plugin-chatbot/src/mapMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,12 +290,10 @@ function citationsFromToolResults(parts: readonly AnyPart[]): unknown {
const p = parts[i];
const toolName = p.type === 'dynamic-tool' ? p.toolName : p.type?.replace(/^tool-/, '');
if (toolName !== 'cite_records') continue;
let envelope = parseResultEnvelope(p.output ?? p.result);
// A stored tool row keeps its output as the model message part does:
// `{ type: 'text', value: '<the JSON the tool returned>' }`.
if (envelope && envelope.type === 'text' && typeof envelope.value === 'string') {
envelope = parseResultEnvelope(envelope.value);
}
// A stored tool row keeps its output as the model message part does,
// `{ type: 'text', value: '<the JSON the tool returned>' }`, which
// `parseResultEnvelope` peels.
const envelope = parseResultEnvelope(p.output ?? p.result);
if (Array.isArray(envelope?.citations)) return envelope.citations;
}
return undefined;
Expand Down
Loading