From cf2ddd5b0413bd6749f2e6dced4b6ac60dcc36f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:14:54 +0000 Subject: [PATCH 1/3] feat(plugin-chatbot): draw query_dataset provenance in the answer source block The answer source block now lifts and draws the provenance block a query_dataset answer carries (DatasetProvenanceSchema, ADR-0149 D3): the dataset, each metric by label with its name beside it, the grouping and the caller's filter. The object-query rendering is unchanged, and the message cache writes a dataset lift back under provenance. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5kWtEXh64E1jg6WPCD --- .../__tests__/useChatConversation.test.tsx | 22 ++ .../src/hooks/useChatConversation.ts | 13 +- 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/AnswerSource.tsx | 165 ++++++++++--- .../plugin-chatbot/src/ChatbotEnhanced.tsx | 4 +- ...hanced.answerSource-dataset-33734.test.tsx | 232 ++++++++++++++++++ ui/packages/plugin-chatbot/src/index.tsx | 7 +- ui/packages/plugin-chatbot/src/mapMessages.ts | 30 ++- 18 files changed, 456 insertions(+), 50 deletions(-) create mode 100644 ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.answerSource-dataset-33734.test.tsx diff --git a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx index f58c104d16a..64cc7a60f59 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useChatConversation.test.tsx @@ -622,6 +622,28 @@ describe('sanitizeChatMessagesForCache — the answer source survives a cache ro expect(tool?.pendingActionId).toBe('pa_31868'); expect(tool?.answerSource).toEqual(answerSource); }); + + // objectstack#33734 — `query_dataset`'s `provenance` is written back under + // its own key, so the same reader lifts it on reload. + it('keeps a query_dataset provenance through sanitize → localStorage → hydration', () => { + const provenance: AnswerSource = { + kind: 'dataset', + dataset: { name: 'sales_analysis', label: 'Sales analysis' }, + measures: [{ name: 'total_amount', label: 'Revenue', description: 'Closed-won amount' }], + dimensions: [{ name: 'stage', label: 'Stage' }], + runtimeFilter: { region: 'EMEA' }, + }; + const persisted = roundTrip([ + { toolCallId: 'tc-ds', toolName: 'query_dataset', state: 'output-available', answerSource: provenance }, + ]); + const toolPart = persisted[0]?.parts.find((p) => p.type === 'tool-query_dataset') as + | { output?: Record } + | undefined; + expect(toolPart?.output).toEqual({ provenance }); + + expect(hydratedMessagesToChatMessages(persisted)[0]?.toolInvocations?.[0]?.answerSource).toEqual(provenance); + expect(uiMessageToChatMessage(persisted[0]).toolInvocations?.[0]?.answerSource).toEqual(provenance); + }); }); // The server persists conversations in ModelMessage format, where an assistant diff --git a/ui/packages/app-shell/src/hooks/useChatConversation.ts b/ui/packages/app-shell/src/hooks/useChatConversation.ts index 11d71dbaf43..8a712bf9092 100644 --- a/ui/packages/app-shell/src/hooks/useChatConversation.ts +++ b/ui/packages/app-shell/src/hooks/useChatConversation.ts @@ -252,7 +252,8 @@ interface CacheableChatToolInvocation { pendingActionId?: string; /** * objectstack#31868 — the data tool's `source` block ("How this was - * computed"), as `detectAnswerSource` lifted it. It rides INSIDE the cached + * computed"), or `query_dataset`'s `provenance` (objectstack#33734), as + * `detectAnswerSource` lifted it. It rides INSIDE the cached * `output`, beside whichever envelope took it, because `output` is the one * carrier both hydration paths re-parse (see `sanitizeChatMessagesForCache`). */ @@ -588,8 +589,16 @@ export function sanitizeChatMessagesForCache( // carries a pending approval keeps `status` / `pendingActionId` and // gains `source`, and `detectPendingApproval` and // `detectAnswerSource` each read their own keys back. + // objectstack#33734 — a `query_dataset` lift (`kind: 'dataset'`) + // goes back under `provenance`, the key that tool answers it under, + // so the same reader lifts it on reload. const output = tool.answerSource - ? { ...(cachedOutput ?? {}), source: tool.answerSource } + ? { + ...(cachedOutput ?? {}), + ...('kind' in tool.answerSource + ? { provenance: tool.answerSource } + : { source: tool.answerSource }), + } : cachedOutput; parts.push({ type: `tool-${tool.toolName}`, diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index e3a102c9712..ac1e346bbd5 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -4343,6 +4343,9 @@ const ar = { aggregations: 'التجميعات', records: 'السجلات', visibleToYou: 'فقط السجلات التي يمكنك رؤيتها', + dataset: 'مجموعة البيانات', + metrics: 'المقاييس', + noAddedFilter: 'لا يوجد عامل تصفية مضاف إلى تعريف مجموعة البيانات', }, tool: { aggregate_data: "تجميع البيانات ذات الصلة", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index df3ae81f7ba..d9610dadebe 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4006,6 +4006,9 @@ const de = { aggregations: 'Aggregationen', records: 'Datensätze', visibleToYou: 'Nur Datensätze, die Sie sehen können', + dataset: 'Datenset', + metrics: 'Kennzahlen', + noAddedFilter: 'Kein zusätzlicher Filter zur Datenset-Definition', }, tool: { aggregate_data: "Die Daten zusammenfassen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 80dffeee05e..3958675534f 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4932,6 +4932,9 @@ const en = { aggregations: 'Aggregations', records: 'Records', visibleToYou: 'Only records visible to you', + dataset: 'Dataset', + metrics: 'Metrics', + noAddedFilter: 'No filter added to the dataset definition', }, tool: { aggregate_data: 'Aggregate the data', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 27438ca224e..757f01cf044 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4091,6 +4091,9 @@ const es = { aggregations: 'Agregaciones', records: 'Registros', visibleToYou: 'Solo los registros que puede ver', + dataset: 'Conjunto de datos', + metrics: 'Métricas', + noAddedFilter: 'Sin filtro añadido a la definición del conjunto de datos', }, tool: { aggregate_data: "Resumir los datos", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index c3d986f0996..be892b7d31f 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4087,6 +4087,9 @@ const fr = { aggregations: 'Agrégations', records: 'Enregistrements', visibleToYou: 'Uniquement les enregistrements que vous pouvez voir', + dataset: 'Jeu de données', + metrics: 'Indicateurs', + noAddedFilter: 'Aucun filtre ajouté à la définition du jeu de données', }, tool: { aggregate_data: "Synthétiser les données", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 1fa591c4de7..3258ac2c7b0 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4008,6 +4008,9 @@ const ja = { aggregations: '集計', records: 'レコード', visibleToYou: 'あなたが閲覧できるレコードのみ', + dataset: 'データセット', + metrics: '指標', + noAddedFilter: 'データセットの定義に追加されたフィルターなし', }, tool: { aggregate_data: "関連データを集計する", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 5b213de3c67..9614ef8a73f 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4005,6 +4005,9 @@ const ko = { aggregations: '집계', records: '레코드', visibleToYou: '내가 볼 수 있는 레코드만', + dataset: '데이터셋', + metrics: '지표', + noAddedFilter: '데이터셋 정의에 추가된 필터 없음', }, tool: { aggregate_data: "관련 데이터 집계하기", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 67909629f7e..0948a1282ea 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4086,6 +4086,9 @@ const pt = { aggregations: 'Agregações', records: 'Registros', visibleToYou: 'Somente os registros que você pode ver', + dataset: 'Conjunto de dados', + metrics: 'Métricas', + noAddedFilter: 'Nenhum filtro adicionado à definição do conjunto de dados', }, tool: { aggregate_data: "Resumir os dados", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 7780830e051..69869b09125 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4185,6 +4185,9 @@ const ru = { aggregations: 'Агрегаты', records: 'Записи', visibleToYou: 'Только записи, которые вам доступны', + dataset: 'Набор данных', + metrics: 'Метрики', + noAddedFilter: 'Без фильтров сверх определения набора данных', }, tool: { aggregate_data: "Агрегировать данные", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 4283294a7c7..687e8683e63 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -4254,6 +4254,9 @@ const zh = { aggregations: '汇总', records: '记录', visibleToYou: '仅包含你可见的记录', + dataset: '数据集', + metrics: '指标', + noAddedFilter: '未在数据集定义之外添加筛选条件', }, tool: { aggregate_data: '汇总相关数据', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index ba55b6265d3..bbd73434e56 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -4254,6 +4254,9 @@ const zhHant = { aggregations: '彙總', records: '記錄', visibleToYou: '僅包含你可見的記錄', + dataset: '資料集', + metrics: '指標', + noAddedFilter: '未在資料集定義之外新增篩選條件', }, tool: { aggregate_data: '彙總相關資料', diff --git a/ui/packages/plugin-chatbot/src/AnswerSource.tsx b/ui/packages/plugin-chatbot/src/AnswerSource.tsx index 83d10ab2c86..05e1229d04f 100644 --- a/ui/packages/plugin-chatbot/src/AnswerSource.tsx +++ b/ui/packages/plugin-chatbot/src/AnswerSource.tsx @@ -9,12 +9,14 @@ /** * "How this was computed": one collapsed block per answer turn that draws the * `source` block each data tool answered beside its result (object, filter, - * grouping, aggregations, how many records, and whose records were read), so - * a reader can check an answer's number. + * grouping, aggregations, how many records, and whose records were read), or + * the `provenance` block `query_dataset` answered (the dataset, each metric, + * the grouping and the caller's filter; ADR-0149 D3), so a reader can check + * an answer's number. * - * The block receives only the lifted `ObjectQuerySource` copies - * (`detectAnswerSource`), never a tool's `result` or `args`, so nothing else - * of a tool payload can reach this face in any visibility mode. + * The block receives only the lifted copies (`detectAnswerSource`), never a + * tool's `result` or `args`, so nothing else of a tool payload can reach this + * face in any visibility mode. */ import * as React from 'react'; import { @@ -25,7 +27,8 @@ import { } from '@object-ui/components'; import { builtinAggregateLabels, useObjectTranslation, useSafeTranslate } from '@object-ui/i18n'; import { CalculatorIcon, ChevronDownIcon } from 'lucide-react'; -import type { ObjectQuerySource } from '@objectstack/spec/ai'; +import type { DatasetProvenance, ObjectQuerySource } from '@objectstack/spec/ai'; +import type { AnswerSource } from './mapMessages'; /** The scope value the block states in words; any other value draws nothing. */ const SCOPE_VISIBLE_TO_YOU = 'visible_to_you'; @@ -210,10 +213,14 @@ function AnswerSourceRow({ label, children }: { label: string; children: React.R ); } -function AnswerSourceSection({ source }: { source: ObjectQuerySource }) { +/** + * A filter in the query dialect as flat rows (field, operator words, + * comparands), or as served when it does not lower. Shared by the object-query + * `filter` and the dataset `runtimeFilter`. + */ +function AnswerSourceFilter({ filter }: { filter: Record }) { const { t } = useObjectTranslation(); const tt = useSafeTranslate(); - const aggregateWords = builtinAggregateLabels(tt) as Record; const word = (v: FilterScalar): string => typeof v === 'boolean' ? v @@ -221,11 +228,43 @@ function AnswerSourceSection({ source }: { source: ObjectQuerySource }) { : t('filterBuilder.falseLabel', { defaultValue: 'False' }) : String(v); - const lowered = source.filter !== undefined ? lowerSourceFilter(source.filter) : null; + const lowered = lowerSourceFilter(filter); const joiner = lowered?.logic === 'or' ? t('filterBuilder.or', { defaultValue: 'OR' }) : t('filterBuilder.and', { defaultValue: 'AND' }); + return lowered ? ( +
    + {lowered.rows.map((row, i) => ( +
  • + {i > 0 ? {joiner} : null} + {row.field}{' '} + + {tt(`filterBuilder.operators.${row.operator}`, OPERATOR_WORDS_EN[row.operator])} + + {row.values.length > 0 ? ( + <> + {' '} + {row.range + ? `${word(row.values[0])} – ${word(row.values[1])}` + : row.values.map(word).join(', ')} + + ) : null} +
  • + ))} +
+ ) : ( + + {servedFilterText(filter)} + + ); +} + +function AnswerSourceSection({ source }: { source: ObjectQuerySource }) { + const { t } = useObjectTranslation(); + const tt = useSafeTranslate(); + const aggregateWords = builtinAggregateLabels(tt) as Record; + return (
@@ -234,30 +273,8 @@ function AnswerSourceSection({ source }: { source: ObjectQuerySource }) { {source.filter === undefined ? ( t('chatbot.answerSource.allRecords', { defaultValue: 'All records' }) - ) : lowered ? ( -
    - {lowered.rows.map((row, i) => ( -
  • - {i > 0 ? {joiner} : null} - {row.field}{' '} - - {tt(`filterBuilder.operators.${row.operator}`, OPERATOR_WORDS_EN[row.operator])} - - {row.values.length > 0 ? ( - <> - {' '} - {row.range - ? `${word(row.values[0])} – ${word(row.values[1])}` - : row.values.map(word).join(', ')} - - ) : null} -
  • - ))} -
) : ( - - {servedFilterText(source.filter)} - + )}
{source.groupBy?.length ? ( @@ -293,9 +310,83 @@ function AnswerSourceSection({ source }: { source: ObjectQuerySource }) { ); } +/** A member's label, or its name where the dataset sends an empty label. */ +const memberLabel = (m: { name: string; label: string }): string => m.label || m.name; + +/** + * A `query_dataset` answer's provenance (ADR-0149 D3): the dataset, each + * metric by its label with its name beside it (and its business definition + * when it declares one), the grouping, and the caller's filter. The dataset's + * own filter is never served, so "no filter" here means none was added to it. + */ +function DatasetSourceSection({ source }: { source: DatasetProvenance }) { + const { t } = useObjectTranslation(); + + return ( +
+ + {memberLabel(source.dataset)} + + {source.measures.length > 0 ? ( + +
    + {source.measures.map((m, i) => ( +
  • + + {memberLabel(m)} + + {m.label && m.label !== m.name ? ( + <> + {' '} + + {m.name} + + + ) : null} + {m.description ? ( +

    {m.description}

    + ) : null} +
  • + ))} +
+
+ ) : null} + {source.dimensions.length > 0 ? ( + + {source.dimensions.map(memberLabel).join(', ')} + + ) : null} + + {source.runtimeFilter === undefined ? ( + + {t('chatbot.answerSource.noAddedFilter', { + defaultValue: 'No filter added to the dataset definition', + })} + + ) : ( + + )} + +
+ ); +} + +const isDatasetProvenance = (source: AnswerSource): source is DatasetProvenance => + 'kind' in source && source.kind === 'dataset'; + export interface AnswerSourceBlockProps { - /** The turn's lifted sources, one per tool that answered one, in call order. */ - sources: ReadonlyArray<{ key: string; source: ObjectQuerySource }>; + /** + * The turn's lifted sources, one per tool that answered one, in call order: + * an object query's `source` or `query_dataset`'s `provenance`. + */ + sources: ReadonlyArray<{ key: string; source: AnswerSource }>; className?: string; } @@ -322,7 +413,11 @@ export function AnswerSourceBlock({ sources, className }: AnswerSourceBlockProps {sources.map(({ key, source }, i) => ( {i > 0 ?
: null} - + {isDatasetProvenance(source) ? ( + + ) : ( + + )}
))} diff --git a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx index 43c4fae37f1..63903db0179 100644 --- a/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx +++ b/ui/packages/plugin-chatbot/src/ChatbotEnhanced.tsx @@ -120,7 +120,7 @@ import { type PackageRemoval, type ReplayOutcome, } from './mapMessages'; -import type { ObjectQuerySource } from '@objectstack/spec/ai'; +import type { DatasetProvenance, ObjectQuerySource } from '@objectstack/spec/ai'; import { AnswerSourceBlock } from './AnswerSource'; /** @@ -417,7 +417,7 @@ export interface ChatbotEnhancedToolInvocation { * "How this was computed" block. Only this lifted copy is drawn there, never * `result` itself. */ - answerSource?: ObjectQuerySource; + answerSource?: ObjectQuerySource | DatasetProvenance; /** * cloud#3565 — 「清理示例数据」: the tables and counts the seed ledger * recorded, listed on the card before the user confirms (the generic diff --git a/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.answerSource-dataset-33734.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.answerSource-dataset-33734.test.tsx new file mode 100644 index 00000000000..bd700c0cfe2 --- /dev/null +++ b/ui/packages/plugin-chatbot/src/__tests__/ChatbotEnhanced.answerSource-dataset-33734.test.tsx @@ -0,0 +1,232 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * objectstack#33734 — an answer computed through `query_dataset` draws its + * `provenance` block (`DatasetProvenanceSchema`, ADR-0149 D3) in the turn's + * "How this was computed" block: the dataset, each metric, the grouping and + * the caller's filter. The object-query `source` block draws as it did. + * + * The turns are built from wire parts through `uiMessageToChatMessage`, so + * the lift (`detectAnswerSource`) and the draw are pinned together, the way a + * streamed or reloaded conversation reaches the chat. The fixture is a + * `query_dataset` answer the published output contract accepts. + */ +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it } from 'vitest'; +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { I18nProvider } from '@object-ui/i18n'; +import { ChatbotEnhanced } from '../ChatbotEnhanced'; +import { DatasetProvenanceSchema, QUERY_DATASET_TOOL_NAME, QueryDatasetOutputSchema } from '@objectstack/spec/ai'; +import { detectAnswerSource, uiMessageToChatMessage } from '../mapMessages'; + +afterEach(cleanup); + +/** A value that sits in the tool payload beside `provenance` and must never be drawn. */ +const SENTINEL = 'PAYLOAD_SENTINEL_33734'; + +const PROVENANCE = { + kind: 'dataset', + dataset: { name: 'sales_analysis', label: 'Sales analysis' }, + measures: [ + { + name: 'total_amount', + label: 'Revenue', + description: 'Closed-won amount, before refunds', + }, + { name: 'deal_count', label: '' }, + ], + dimensions: [ + { name: 'stage', label: 'Stage' }, + { name: 'owner', label: 'Owner' }, + ], + runtimeFilter: { region: 'EMEA', amount: { $gte: 1000 } }, +} as const; + +/** A `query_dataset` answer: rows and fields, then `provenance`, `rowCount`, `truncated`. */ +const ANSWER = { + rows: [{ stage: SENTINEL, owner: 'u1', total_amount: 1200, deal_count: 2 }], + fields: [ + { name: 'stage', type: 'string', label: 'Stage' }, + { name: 'total_amount', type: 'number', label: 'Revenue' }, + ], + provenance: PROVENANCE, + rowCount: 1, + truncated: false, +}; + +/** The service-ai wire form: the tool's JSON inside a `{ type: 'text', value }` wrapper. */ +const wrapped = (body: unknown) => ({ type: 'text', value: JSON.stringify(body) }); + +const toolPart = (toolCallId: string, toolName: string, output: unknown) => ({ + type: `tool-${toolName}`, + toolCallId, + state: 'output-available', + input: { datasetName: 'sales_analysis', note: SENTINEL }, + output, +}); + +const turn = (parts: unknown[]) => + uiMessageToChatMessage({ + id: 'a1', + role: 'assistant', + parts: [...parts, { type: 'text', text: 'Revenue in EMEA is 1,200.' }], + } as never); + +const question = { id: 'u1', role: 'user' as const, content: 'What is our EMEA revenue by stage?' }; + +const datasetPart = (answer: unknown = ANSWER) => toolPart('t1', QUERY_DATASET_TOOL_NAME, wrapped(answer)); + +const renderTurn = (parts: unknown[]) => + render(); + +const openBlock = () => fireEvent.click(screen.getByRole('button', { name: 'How this was computed' })); + +describe('objectstack#33734 — the fixture is a query_dataset answer the contract accepts', () => { + it('QueryDatasetOutputSchema accepts the answer', () => { + expect(QueryDatasetOutputSchema.safeParse(ANSWER).success).toBe(true); + }); +}); + +describe('objectstack#33734 — detectAnswerSource lifts a dataset provenance block', () => { + it('lifts the provenance alone, through the published contract', () => { + const lifted = detectAnswerSource( + wrapped({ ...ANSWER, provenance: { ...PROVENANCE, secret: SENTINEL } }), + ); + expect(lifted).toEqual(PROVENANCE); + expect(JSON.stringify(lifted)).not.toContain(SENTINEL); + }); + + it('a provenance the contract refuses lifts nothing', () => { + expect(detectAnswerSource(wrapped({ ...ANSWER, provenance: { ...PROVENANCE, kind: 'object' } }))).toBeUndefined(); + expect(detectAnswerSource(wrapped({ ...ANSWER, provenance: { ...PROVENANCE, measures: 'Revenue' } }))).toBeUndefined(); + expect(DatasetProvenanceSchema.safeParse({ ...PROVENANCE, dataset: 'sales_analysis' }).success).toBe(false); + expect(detectAnswerSource(wrapped({ ...ANSWER, provenance: { ...PROVENANCE, dataset: 'sales_analysis' } }))).toBeUndefined(); + }); +}); + +describe('objectstack#33734 — a query_dataset answer draws its provenance', () => { + it('shows the dataset, each metric, the grouping and the filter', () => { + renderTurn([datasetPart()]); + openBlock(); + const section = screen.getByTestId('answer-source-dataset-section'); + expect(section).toHaveAttribute('data-dataset', 'sales_analysis'); + + expect(within(section).getByTestId('answer-source-dataset')).toHaveTextContent(/^Sales analysis$/); + + const metrics = within(within(section).getByTestId('answer-source-metrics')).getAllByRole('listitem'); + // The label, with the name beside it; the name alone where the label is empty. + expect(metrics.map((m) => m.querySelector('[data-testid="answer-source-metric-label"]')?.textContent)).toEqual([ + 'Revenue', + 'deal_count', + ]); + expect(metrics.map((m) => m.querySelector('[data-testid="answer-source-metric-name"]')?.textContent ?? null)).toEqual([ + 'total_amount', + null, + ]); + expect(metrics[0]).toHaveTextContent('Closed-won amount, before refunds'); + + expect(section).toHaveTextContent('Grouped byStage, Owner'); + + const rows = within(within(section).getByTestId('answer-source-filter')).getAllByRole('listitem'); + expect(rows.map((r) => r.textContent)).toEqual([ + 'region Equals EMEA', + 'AND amount Greater than or equal 1000', + ]); + + // An object-query section is not drawn for a dataset answer, and nothing + // of the rows or the arguments reaches the block. + expect(screen.queryByTestId('answer-source-section')).toBeNull(); + expect(screen.queryByTestId('answer-source-scope')).toBeNull(); + expect(document.body).not.toHaveTextContent(SENTINEL); + }); + + it('a selection with no filter and no dimensions says no filter was added and draws no grouping', () => { + const { runtimeFilter: _omit, ...bare } = PROVENANCE; + renderTurn([datasetPart({ ...ANSWER, provenance: { ...bare, dimensions: [] } })]); + openBlock(); + const section = screen.getByTestId('answer-source-dataset-section'); + expect(within(section).queryByTestId('answer-source-filter')).toBeNull(); + expect(within(section).getByTestId('answer-source-no-added-filter')).toHaveTextContent( + 'No filter added to the dataset definition', + ); + expect(section).not.toHaveTextContent('Grouped by'); + // A dataset answer is not "all records": the dataset's own definition still applies. + expect(section).not.toHaveTextContent('All records'); + }); + + it('a filter that does not lower to flat rows is drawn as served', () => { + const nested = { $or: [{ region: 'EMEA' }, { $and: [{ amount: { $gt: 1 } }] }] }; + renderTurn([datasetPart({ ...ANSWER, provenance: { ...PROVENANCE, runtimeFilter: nested } })]); + openBlock(); + const section = screen.getByTestId('answer-source-dataset-section'); + expect(within(section).getByTestId('answer-source-filter-served')).toHaveTextContent(JSON.stringify(nested)); + }); + + it('a turn with a dataset answer and an object-query answer draws one block with both, in call order', () => { + renderTurn([ + datasetPart(), + toolPart( + 't2', + 'query_records', + wrapped({ source: { object: 'crm_opportunity', scope: 'visible_to_you', line: 'Read the matching records' } }), + ), + ]); + openBlock(); + expect(screen.getAllByTestId('answer-source')).toHaveLength(1); + const block = screen.getByTestId('answer-source'); + const sections = block.querySelectorAll('[data-testid="answer-source-dataset-section"], [data-testid="answer-source-section"]'); + expect(Array.from(sections).map((s) => s.getAttribute('data-testid'))).toEqual([ + 'answer-source-dataset-section', + 'answer-source-section', + ]); + }); + + it('CONTROL: an object-query answer draws as it did, with no dataset section', () => { + renderTurn([ + toolPart( + 't1', + 'aggregate_data', + wrapped({ + rows: [], + source: { + object: 'crm_opportunity', + label: 'Opportunities', + filter: { stage: 'open' }, + scope: 'visible_to_you', + records: 7, + line: 'Summed the amount of 7 open opportunities', + }, + }), + ), + ]); + openBlock(); + expect(screen.queryByTestId('answer-source-dataset-section')).toBeNull(); + const section = screen.getByTestId('answer-source-section'); + expect(section).toHaveTextContent('ObjectOpportunities'); + expect(within(section).getAllByRole('listitem').map((r) => r.textContent)).toEqual(['stage Equals open']); + expect(screen.getByTestId('answer-source-records')).toHaveTextContent(/^7$/); + expect(screen.getByTestId('answer-source-scope')).toHaveTextContent('Only records visible to you'); + }); + + it('CONTROL: a query_dataset result with no provenance (a refusal) draws no block', () => { + renderTurn([ + datasetPart({ error: { code: 'NOT_FOUND', status: 404, message: 'Dataset not found' } }), + ]); + expect(screen.getByText('Revenue in EMEA is 1,200.')).toBeInTheDocument(); + expect(screen.queryByTestId('answer-source')).toBeNull(); + expect(screen.queryByRole('button', { name: 'How this was computed' })).toBeNull(); + }); + + it('reads the shipped zh pack', async () => { + render( + + + , + ); + fireEvent.click(await screen.findByRole('button', { name: '计算方式' })); + const section = screen.getByTestId('answer-source-dataset-section'); + expect(section).toHaveTextContent('数据集Sales analysis'); + expect(section).toHaveTextContent('指标'); + }); +}); diff --git a/ui/packages/plugin-chatbot/src/index.tsx b/ui/packages/plugin-chatbot/src/index.tsx index daa8e2b9442..53803cbd184 100644 --- a/ui/packages/plugin-chatbot/src/index.tsx +++ b/ui/packages/plugin-chatbot/src/index.tsx @@ -374,9 +374,10 @@ export type { ProposedChanges, ReplayOutcome, } from './mapMessages'; -// The answer-source block's type is the published contract's; the package -// keeps exporting it under the name its consumers already import. -export type { ObjectQuerySource as AnswerSource } from '@objectstack/spec/ai'; +// The answer-source block's type: the union of the two published contracts it +// is lifted through (an object query's `source`, `query_dataset`'s +// `provenance`), under the name its consumers already import. +export type { AnswerSource } from './mapMessages'; // `@object-ui/types` ChatMessage (the JSON/SDUI AUTHORING contract) → the // runtime `ChatbotEnhancedMessage` above. Exported for the same reason as the diff --git a/ui/packages/plugin-chatbot/src/mapMessages.ts b/ui/packages/plugin-chatbot/src/mapMessages.ts index b934dbe6eca..451109f9571 100644 --- a/ui/packages/plugin-chatbot/src/mapMessages.ts +++ b/ui/packages/plugin-chatbot/src/mapMessages.ts @@ -14,8 +14,8 @@ * apps that drive `useChat` themselves (e.g. Studio, which needs a custom * `prepareSendMessagesRequest` transport). */ -import type { BUILD_PROGRESS_FRAME_TYPE, BuildProgressPhase, ObjectQuerySource } from '@objectstack/spec/ai'; -import { ObjectQuerySourceSchema } from '@objectstack/spec/ai'; +import type { BUILD_PROGRESS_FRAME_TYPE, BuildProgressPhase, DatasetProvenance, ObjectQuerySource } from '@objectstack/spec/ai'; +import { DatasetProvenanceSchema, ObjectQuerySourceSchema } 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'; @@ -763,10 +763,19 @@ export function detectRecordWrite(result: unknown): RecordWrite | undefined { } /** - * The `source` block a data tool answers beside its result (the tools - * `OBJECT_QUERY_SOURCE_TOOL_NAMES` names), read through the published - * contract, `ObjectQuerySourceSchema` (`@objectstack/spec/ai`). The chat draws - * it as the turn's "How this was computed" block. + * What a turn's "How this was computed" block draws for one tool call: an + * object query's `source` block (`ObjectQuerySourceSchema`), or the + * `provenance` block `query_dataset` answers (`DatasetProvenanceSchema`, + * ADR-0149 D3), told apart by the latter's `kind: 'dataset'`. + */ +export type AnswerSource = ObjectQuerySource | DatasetProvenance; + +/** + * The block a data tool answers beside its result, read through the published + * contract (`@objectstack/spec/ai`): `query_dataset`'s top-level `provenance` + * (`DatasetProvenanceSchema`), else the `source` block the object-query tools + * answer (`OBJECT_QUERY_SOURCE_TOOL_NAMES`, `ObjectQuerySourceSchema`). The + * chat draws it as the turn's "How this was computed" block. * * The lift is the schema's parse of the block: a key the schema does not * declare is stripped, so nothing else of the tool payload rides along, and a @@ -775,8 +784,13 @@ export function detectRecordWrite(result: unknown): RecordWrite | undefined { * whole parsed block is kept, the members the block does not draw included, * because the message cache stores this copy and lifts it again on reload. */ -export function detectAnswerSource(result: unknown): ObjectQuerySource | undefined { - const raw = parseResultEnvelope(result)?.source; +export function detectAnswerSource(result: unknown): AnswerSource | undefined { + const envelope = parseResultEnvelope(result); + if (envelope?.provenance !== undefined) { + const provenance = DatasetProvenanceSchema.safeParse(envelope.provenance); + if (provenance.success) return provenance.data; + } + const raw = envelope?.source; if (raw === undefined) return undefined; const parsed = ObjectQuerySourceSchema.safeParse(raw); return parsed.success ? parsed.data : undefined; From 65c45905b8518fe321cb57f772fed5539869c256 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:15:12 +0000 Subject: [PATCH 2/3] chore(changeset): answer source block draws dataset provenance Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5kWtEXh64E1jg6WPCD --- .../33734-answer-source-dataset-provenance.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .changeset/33734-answer-source-dataset-provenance.md diff --git a/.changeset/33734-answer-source-dataset-provenance.md b/.changeset/33734-answer-source-dataset-provenance.md new file mode 100644 index 00000000000..1e1bbd9730b --- /dev/null +++ b/.changeset/33734-answer-source-dataset-provenance.md @@ -0,0 +1,16 @@ +--- +'@object-ui/plugin-chatbot': patch +'@object-ui/i18n': patch +'@object-ui/app-shell': patch +'@object-ui/console': patch +--- + +feat(plugin-chatbot): an AI chat answer computed from a dataset shows which dataset and metrics it used + +Clause-②: yes (widening) — `@object-ui/plugin-chatbot` exports `detectAnswerSource`, whose return type grows from `ObjectQuerySource` to `AnswerSource` (`ObjectQuerySource | DatasetProvenance`); the exported `AnswerSource` type, which was `ObjectQuerySource`, is now that union; and a chat tool invocation's `answerSource` member widens to the same union. `AnswerSourceBlock`'s `sources` prop (package-internal) takes the union too. Code that reads an object-query member (`object`, `filter`, `scope`) off an `AnswerSource` first checks it has no `kind: 'dataset'`. +Metadata-protocol: none + +- **"How this was computed" now covers dataset answers.** When the AI answers a business question through `query_dataset` (ADR-0149 D3), the collapsed block under the answer lists the dataset, each metric by its label with its name beside it and its business definition when it has one, what the figures were grouped by, and the filter the question added. A filter that cannot be shown as rows is shown as sent. When the question added no filter, the block says so, because the dataset's own definition still applies. +- **Object-query answers draw as before.** The object, filter, grouping, aggregations, record count and "Only records visible to you" lines are unchanged, and a turn whose tools answered neither block shows no block. +- **The block survives a reload.** A conversation restored from the browser cache keeps the dataset block. +- New strings `chatbot.answerSource.dataset`, `chatbot.answerSource.metrics` and `chatbot.answerSource.noAddedFilter` ship in every locale pack. From ee612b495075f4521a23f28b1d733da3a5782f86 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 09:32:52 +0000 Subject: [PATCH 3/3] docs(plugin-chatbot): the answer source block draws a dataset answer's provenance Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5kWtEXh64E1jg6WPCD --- content/docs/frontend/plugins/plugin-chatbot.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/frontend/plugins/plugin-chatbot.mdx b/content/docs/frontend/plugins/plugin-chatbot.mdx index 6c80c1e4f75..015d1d303f0 100644 --- a/content/docs/frontend/plugins/plugin-chatbot.mdx +++ b/content/docs/frontend/plugins/plugin-chatbot.mdx @@ -491,7 +491,7 @@ Tool messages represent results from tool invocations during AI streaming. They By default, `ChatbotEnhanced` renders tool invocations as a compact agent activity summary. Repeated calls are grouped, raw tool names are hidden, and reasoning text is not shown. Use `processVisibility="debug"` for developer/admin views that need the full reasoning panel, raw tool names, parameters, and results. Use `processVisibility="hidden"` to suppress non-interactive activity entirely; approval and draft-review actions remain visible. -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. It draws that block alone, never the rest of the tool payload. +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. 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