diff --git a/.changeset/39507-cite-records-envelope-read.md b/.changeset/39507-cite-records-envelope-read.md new file mode 100644 index 00000000000..7e7bb81c286 --- /dev/null +++ b/.changeset/39507-cite-records-envelope-read.md @@ -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. diff --git a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts index 35ff65b74fc..c790f877407 100644 --- a/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts +++ b/ui/packages/app-shell/src/console/ai/__tests__/AiChatPage.hydration.test.ts @@ -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]); + }); +}); 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 10844f4ac18..8728efc82b2 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 @@ -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'; @@ -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>(); @@ -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, @@ -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, @@ -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( + + , ); @@ -131,6 +138,7 @@ beforeEach(() => { afterEach(() => { answerNow.content = ''; answerNow.recordCitations = undefined; + answerNow.toolInvocations = undefined; cleanup(); vi.unstubAllGlobals(); window.history.replaceState(null, '', '/'); @@ -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(); + }); +}); diff --git a/ui/packages/app-shell/src/console/ai/__tests__/recordReader.pickBodyField-39507.test.ts b/ui/packages/app-shell/src/console/ai/__tests__/recordReader.pickBodyField-39507.test.ts new file mode 100644 index 00000000000..d0b56e87bab --- /dev/null +++ b/ui/packages/app-shell/src/console/ai/__tests__/recordReader.pickBodyField-39507.test.ts @@ -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'); + }); +}); diff --git a/ui/packages/plugin-chatbot/src/mapMessages.ts b/ui/packages/plugin-chatbot/src/mapMessages.ts index db3160de628..3657c74175d 100644 --- a/ui/packages/plugin-chatbot/src/mapMessages.ts +++ b/ui/packages/plugin-chatbot/src/mapMessages.ts @@ -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: '' }`. - 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: '' }`, which + // `parseResultEnvelope` peels. + const envelope = parseResultEnvelope(p.output ?? p.result); if (Array.isArray(envelope?.citations)) return envelope.citations; } return undefined;