Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agents): render dynamic UI in agent sessions (#6471)
Eric Hayesd8002b0ad423
diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.ymlindex 4d6f382043..2c404658aa 100644--- a/.github/workflows/web-app-check-main.yml+++ b/.github/workflows/web-app-check-main.yml@@ -38,6 +38,7 @@ jobs:- 'Cargo.lock'- 'rust-toolchain.toml'- 'services/lexical-service/**'+ - 'crates/ai_tools/src/display_results/schema.generated.json'- '.github/actions/setup-reqs-web/**'api_changed:- 'crates/**/*.rs'@@ -104,6 +105,9 @@ jobs:- name: show sccache statsif: always() && needs.path-check.outputs.api_changed == 'true'run: sccache --show-stats || true+ - name: Check Dynamic UI Schema+ run: bun run check-dynamic-ui-schema+ working-directory: apps/web- name: Check Typesrun: bun run --bun --silent tsc --project ./tsconfig.jsonworking-directory: apps/webdiff --git a/apps/web/package.json b/apps/web/package.jsonindex b5982fbab5..1f455529df 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -24,10 +24,12 @@"gen-graphql-cache-schema": "bun scripts/generate-graphql-cache-entity-resolver-schema.ts","check-graphql-cache-schema": "bun scripts/generate-graphql-cache-entity-resolver-schema.ts --check","gen-tools": "bun scripts/generate-dcs-tools.ts",+ "gen-dynamic-ui-schema": "bun scripts/generate-dynamic-ui-schema.ts",+ "check-dynamic-ui-schema": "bun scripts/generate-dynamic-ui-schema.ts --check","ui-audit": "bun scripts/ui-audit.ts","gen-agent-fold-types": "just gen-agent-fold-types","type-check": "tsc --noEmit --skipLibCheck --project tsconfig.json",- "check": "bun check-graphql-cache-schema && bun type-check && bun biome check",+ "check": "bun check-graphql-cache-schema && bun check-dynamic-ui-schema && bun type-check && bun biome check","preview": "vite preview -c vite.config.ts --outDir dist --base /app","preview:dev": "vite preview -c vite.config.ts --outDir dist --base /app","preview:prod": "vite preview -c vite.config.ts --outDir dist --base /app",diff --git a/apps/web/scripts/generate-dynamic-ui-schema.ts b/apps/web/scripts/generate-dynamic-ui-schema.tsnew file mode 100644index 0000000000..f55d094ae8--- /dev/null+++ b/apps/web/scripts/generate-dynamic-ui-schema.ts@@ -0,0 +1,38 @@+/**+ * Generates the complete DisplayResults tool schema from the frontend Zod+ * contract. Run `bun run gen-dynamic-ui-schema` to write it, or add `--check`+ * to verify the committed schema is current.+ */++import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { displayResultsToolSchema } from '../src/features/dynamic-ui/toolSchema';++async function main(): Promise<void> {+ const scriptDirectory = dirname(fileURLToPath(import.meta.url));+ const outputPath = resolve(+ scriptDirectory,+ '../../../crates/ai_tools/src/display_results/schema.generated.json'+ );+ const output = `${JSON.stringify(displayResultsToolSchema(), null, 2)}\n`;++ if (process.argv.includes('--check')) {+ let current: string | undefined;+ try {+ current = await Bun.file(outputPath).text();+ } catch {+ current = undefined;+ }+ if (current !== output) {+ throw new Error(+ 'crates/ai_tools/src/display_results/schema.generated.json is stale; run `bun run gen-dynamic-ui-schema`'+ );+ }+ return;+ }+ await Bun.write(outputPath, output);+}++if (import.meta.main) {+ await main();+}diff --git a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsxindex ff4b225080..c799497824 100644--- a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx@@ -19,6 +19,7 @@ import {deserializeToolResponse,} from '@service-cognition/generated/tools/tool';import { createMemo, ErrorBoundary, type JSX, Show } from 'solid-js';+import { DashboardToolView } from '../../../dynamic-ui/DashboardToolView.lazy';import { FoldedExchange, ToolCard } from '../../ui';import type { ToolCallCommon, ToolCallContext } from './shared';@@ -31,12 +32,24 @@ export function MacroToolCall(props: {}): JSX.Element {const finished = () =>props.common.status === 'completed' || props.common.status === 'failed';+ const displayResults = () =>+ props.common.label === 'DisplayResults' &&+ props.common.status !== 'failed' &&+ props.detail.error == null;+ const dashboardView = () => {+ const input = props.detail.input;+ return input != null && typeof input === 'object' && 'view' in input+ ? input.view+ : undefined;+ };// The chat renderer renders nothing for a tool it has no component for or// arguments that do not fit the tool's schema, and it shows a *completed*// call whose response it cannot read as failed. A call it would drop or// misreport keeps the generic card, so no row vanishes or lies.const chatRenders = createMemo(() => {- if (props.detail.error != null) return false;+ if (props.detail.error != null || props.common.status === 'failed') {+ return false;+ }const call = deserializeToolCall({id: props.common.id,name: props.common.label,@@ -52,25 +65,39 @@ export function MacroToolCall(props: {});return (- <Show when={chatRenders()} fallback={<GenericMacroToolCall {...props} />}>+ <Show+ when={displayResults()}+ fallback={+ <Show+ when={chatRenders()}+ fallback={<GenericMacroToolCall {...props} />}+ >+ <ErrorBoundary fallback={<GenericMacroToolCall {...props} />}>+ <RenderTool+ tool_id={props.common.id}+ name={props.common.label}+ json={props.detail.input}+ response={+ props.detail.output == null+ ? undefined+ : { json: props.detail.output, name: props.common.label }+ }+ chat_id={props.context?.sessionId ?? ''}+ message_id={props.context?.messageId ?? ''}+ part_index={props.context?.partIndex ?? 0}+ isComplete={finished()}+ renderContext={{+ renderContext: { isStreaming: !finished(), grouped: false },+ }}+ />+ </ErrorBoundary>+ </Show>+ }+ >+ {/* The view is the tool's user-facing result. Keep its streamed input+ reactive and let the dashboard validate it, even without a response. */}<ErrorBoundary fallback={<GenericMacroToolCall {...props} />}>- <RenderTool- tool_id={props.common.id}- name={props.common.label}- json={props.detail.input}- response={- props.detail.output == null- ? undefined- : { json: props.detail.output, name: props.common.label }- }- chat_id={props.context?.sessionId ?? ''}- message_id={props.context?.messageId ?? ''}- part_index={props.context?.partIndex ?? 0}- isComplete={finished()}- renderContext={{- renderContext: { isStreaming: !finished(), grouped: false },- }}- />+ <DashboardToolView view={dashboardView()} pending={!finished()} /></ErrorBoundary></Show>);diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsxindex 85e6bc53ca..188c5c1fc1 100644--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx@@ -5,7 +5,9 @@import type { MessagePart } from '@service-agent-fold/generated/types';import { render } from '@solidjs/testing-library';import type { JSX } from 'solid-js';+import { createStore, reconcile } from 'solid-js/store';import { describe, expect, it, vi } from 'vitest';+import type { View } from '../../../dynamic-ui/schema';import type { ToolCallContext } from './shared';import { ToolCallPart } from './ToolCallPart';@@ -35,6 +37,34 @@ vi.mock('@core/component/AI/component/tool/handler', () => ({),}));+// Exercise the dashboard's validation and streaming behavior, while replacing+// the entity-heavy widgets and Lexical context with presentation markers.+vi.mock('@app/features/dynamic-ui/DashboardToolView.lazy', async () => ({+ DashboardToolView: (+ await import('@app/features/dynamic-ui/DashboardToolView')+ ).default,+}));++vi.mock('@app/features/dynamic-ui/widget', () => ({+ Widget: {+ Compose: (props: { view: View }) => (+ <div data-testid="dashboard">{JSON.stringify(props.view)}</div>+ ),+ },+}));++vi.mock(+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',+ () => ({+ StaticMarkdownContext: (props: { children?: JSX.Element }) =>+ props.children,+ })+);++vi.mock('@core/component/LexicalMarkdown/theme', () => ({+ aiChatTheme: {},+}));+// The entity link a finished email's outcome carries needs the query client// and the split layout; a marker carrying the id is enough here.vi.mock('@core/component/ItemPreview', () => ({@@ -348,6 +378,101 @@ describe('ToolCallPart Macro tools', () => {expect(rendered.getByTestId('macro-tool').dataset.hasResponse).toBe('true');});+ it('renders the displayResults view as a dashboard', () => {+ const view = {+ title: 'This week',+ widgets: [{ type: 'md', markdown: 'hi' }],+ };+ const rendered = render(() => (+ <ToolCallPart+ part={toolUse(+ {+ kind: 'macro',+ input: { view },+ output: { message: 'The results have been displayed to the user.' },+ error: null,+ },+ { name: 'DisplayResults', status: 'completed' }+ )}+ />+ ));+ expect(rendered.getByTestId('dashboard').textContent).toBe(+ JSON.stringify(view)+ );+ expect(rendered.queryByTestId('tool-card')).toBeNull();+ });++ it('renders a view as its arguments arrive and keeps it when no response arrives', () => {+ const displayResults = (+ input: unknown,+ status: ToolUsePart['status'] = 'running'+ ) =>+ toolUse(+ { kind: 'macro', input, output: null, error: null },+ { name: 'DisplayResults', status }+ );+ const [part, setPart] = createStore(displayResults(null));+ const rendered = render(() => (+ <ToolCallPart part={part} context={context(true)} />+ ));++ for (const input of [null, {}, { view: null }, { view: {} }]) {+ setPart(reconcile(displayResults(input)));+ expect(rendered.container.textContent).toBe('');+ }++ const view = {+ title: 'This week',+ widgets: [{ type: 'md', markdown: 'First results' }],+ };+ setPart(reconcile(displayResults({ view })));+ expect(rendered.getByTestId('dashboard').textContent).toBe(+ JSON.stringify(view)+ );++ const finalView = {+ title: 'All results',+ widgets: [{ type: 'md', markdown: 'Final results' }],+ };+ setPart(reconcile(displayResults({ view: finalView }, 'completed')));+ expect(rendered.getByTestId('dashboard').textContent).toBe(+ JSON.stringify(finalView)+ );+ expect(rendered.queryByTestId('tool-card')).toBeNull();+ });++ it.each([null, {}, { view: null }, { view: { widgets: 'invalid' } }])(+ 'reports malformed completed dashboard input: %j',+ (input) => {+ const rendered = render(() => (+ <ToolCallPart+ part={toolUse(+ { kind: 'macro', input, output: null, error: null },+ { name: 'DisplayResults' }+ )}+ />+ ));+ expect(rendered.container.textContent).toContain(+ "Couldn't render dashboard"+ );+ expect(rendered.queryByTestId('dashboard')).toBeNull();+ }+ );++ it('keeps a failed displayResults call on a faded card', () => {+ const rendered = render(() => (+ <ToolCallPart+ part={toolUse(+ { kind: 'macro', input: { view: null }, output: null, error: null },+ { name: 'DisplayResults', status: 'failed' }+ )}+ />+ ));+ expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');+ expect(rendered.getByTestId('trailing').textContent).toBe('Failed');+ expect(rendered.queryByTestId('dashboard')).toBeNull();+ });+it('keeps a Macro tool the chat has no component for on a labelled card', () => {const rendered = render(() => (<ToolCallPartdiff --git a/apps/web/src/features/block-agent/state/tool-groups.test.ts b/apps/web/src/features/block-agent/state/tool-groups.test.tsindex 11ac23df05..305a30cd66 100644--- a/apps/web/src/features/block-agent/state/tool-groups.test.ts+++ b/apps/web/src/features/block-agent/state/tool-groups.test.ts@@ -1,6 +1,6 @@import type { MessagePart } from '@service-agent-fold/generated/types';import { describe, expect, it } from 'vitest';-import { segmentParts } from './tool-groups';+import { rendersOwnView, segmentParts } from './tool-groups';const text = (): MessagePart => ({ kind: 'text', text: 'hi' });const tool = (): MessagePart => ({@@ -11,6 +11,22 @@ const tool = (): MessagePart => ({detail: { kind: 'read', paths: ['a.rs'] },});const thought = (): MessagePart => ({ kind: 'thought', text: 'thinking...' });+/**+ * `displayResults`: the model composes a dynamic-UI view and the call renders+ * it. The answer itself, not a card about one.+ */+const displayResults = (): Extract<MessagePart, { kind: 'tool_use' }> => ({+ kind: 'tool_use',+ id: 'view',+ name: { kind: 'native', name: 'DisplayResults' },+ status: 'completed',+ detail: {+ kind: 'macro',+ input: { view: { widgets: [] } },+ output: { message: 'done' },+ error: null,+ },+});const permission = (): MessagePart => ({kind: 'permission',requestId: 'permission-test',@@ -119,4 +135,85 @@ describe('segmentParts', () => {{ kind: 'tools', start: 3, end: 5 },]);});+ // A collapsed group would put the composed view behind a closed caret,+ // indented in a row of muted chips — the one part of the turn the reader+ // actually came for.+ it('keeps a view-rendering call out of the run it interrupts', () => {+ expect(+ segmentParts([tool(), tool(), displayResults(), tool(), tool()])+ ).toEqual([+ { kind: 'tools', start: 0, end: 2 },+ { kind: 'part', start: 2, end: 3 },+ { kind: 'tools', start: 3, end: 5 },+ ]);+ });++ it('keeps a view-rendering call alone even between single calls', () => {+ expect(segmentParts([tool(), displayResults(), tool()])).toEqual([+ { kind: 'part', start: 0, end: 1 },+ { kind: 'part', start: 1, end: 2 },+ { kind: 'part', start: 2, end: 3 },+ ]);+ });++ it('does not fold two view-rendering calls into each other', () => {+ expect(segmentParts([displayResults(), displayResults()])).toEqual([+ { kind: 'part', start: 0, end: 1 },+ { kind: 'part', start: 1, end: 2 },+ ]);+ });++ it('keeps the last thought and the dashboard visible after grouped tools', () => {+ expect(+ segmentParts([thought(), tool(), thought(), displayResults()])+ ).toEqual([+ { kind: 'tools', start: 0, end: 2 },+ { kind: 'part', start: 2, end: 3 },+ { kind: 'part', start: 3, end: 4 },+ ]);+ });+});++describe('rendersOwnView', () => {+ it('is true for a Macro displayResults call', () => {+ expect(rendersOwnView(displayResults())).toBe(true);+ });++ it('recognizes a Macro displayResults call with an MCP namespace', () => {+ const part = displayResults();+ expect(+ rendersOwnView({+ ...part,+ name: { kind: 'mcp', server: 'macro', tool: 'DisplayResults' },+ })+ ).toBe(true);+ });++ it('is false for any other tool call, and for a non-tool part', () => {+ expect(rendersOwnView(tool())).toBe(false);+ expect(rendersOwnView(text())).toBe(false);+ expect(rendersOwnView(undefined)).toBe(false);+ });++ // A harness tool that happens to share the name is not Macro's: the fold+ // decides whose shape a call is in, and only a `macro` detail carries the+ // tool's own arguments.+ it('is false for a same-named call the fold did not read as a Macro tool', () => {+ expect(+ rendersOwnView({+ kind: 'tool_use',+ id: 'other',+ name: { kind: 'native', name: 'DisplayResults' },+ status: 'completed',+ detail: {+ kind: 'other',+ acpKind: 'other',+ output: null,+ input: null,+ result: null,+ error: null,+ },+ })+ ).toBe(false);+ });});diff --git a/apps/web/src/features/block-agent/state/tool-groups.ts b/apps/web/src/features/block-agent/state/tool-groups.tsindex d6924d49cd..066ead2750 100644--- a/apps/web/src/features/block-agent/state/tool-groups.ts+++ b/apps/web/src/features/block-agent/state/tool-groups.ts@@ -22,8 +22,36 @@ export type PartSegment = {end: number;};+/**+ * Macro tools whose call renders the answer itself rather than a card about+ * it: `DisplayResults` renders the dynamic-UI view the model composed, the+ * same full-width dashboard the chat shows.+ *+ * Folding one of these into a group would put the answer behind a closed+ * caret, indented inside a row of muted tool chips — so they break the run+ * and stand on their own, like a paragraph of the reply.+ */+const SELF_RENDERING_TOOLS: ReadonlySet<string> = new Set(['DisplayResults']);++/**+ * Whether a part is a tool call that renders its own view (see+ * {@link SELF_RENDERING_TOOLS}). Only Macro's own tools do: the fold names+ * them, and the chat component library is what renders them.+ */+export function rendersOwnView(part: MessagePart | undefined): boolean {+ if (part?.kind !== 'tool_use' || part.detail.kind !== 'macro') return false;+ // The tool's own name, without the MCP server namespace the fold already+ // separated out (mirrors `toolLabel` in `component/parts/shared.ts`).+ const name = part.name.kind === 'mcp' ? part.name.tool : part.name.name;+ return SELF_RENDERING_TOOLS.has(name);+}++/** Whether a part may be folded into a collapsed run with its neighbours. */function isGroupable(part: MessagePart | undefined): boolean {- return part?.kind === 'tool_use' || part?.kind === 'thought';+ return (+ (part?.kind === 'tool_use' || part?.kind === 'thought') &&+ !rendersOwnView(part)+ );}export function segmentParts(parts: readonly MessagePart[]): PartSegment[] {diff --git a/apps/web/src/features/dynamic-ui/DashboardToolView.tsx b/apps/web/src/features/dynamic-ui/DashboardToolView.tsxindex a29f764b24..dac285d454 100644--- a/apps/web/src/features/dynamic-ui/DashboardToolView.tsx+++ b/apps/web/src/features/dynamic-ui/DashboardToolView.tsx@@ -7,15 +7,21 @@ import { Widget } from './widget';/*** Renders a `displayResults` tool call's `view` argument as a dashboard.*- * The backend tool input is `any`, so the view arrives as unknown JSON — we- * validate it against the Zod {@link ViewSchema} here (the schema's source of- * truth lives on the frontend) and render it with the dynamic-ui component lib.+ * The wire input remains unknown JSON so streamed or malformed arguments can+ * reach the renderer. Validate it against the Zod {@link ViewSchema}, which+ * also generates the model-facing tool schema, before composing the widgets.** Lives in the `app` package (not `core`) because the dynamic-ui lib depends on* `app` internals; the core tool handler lazy-imports this to avoid a circular* dependency. Default export so it can be `lazy()`-loaded.*/-export default function DashboardToolView(props: { view: unknown }) {+export default function DashboardToolView(props: {+ view: unknown;+ pending?: boolean;+}) {+ // Agent calls open before their input arrives. Render any valid view as it+ // streams in, but only report malformed or missing input once the call ends.+ const pending = () => props.pending ?? props.view == null;const parsed = createMemo(() => ViewSchema.safeParse(props.view));const view = () => {const r = parsed();@@ -26,9 +32,11 @@ export default function DashboardToolView(props: { view: unknown }) {<Showwhen={view()}fallback={- <div class="text-ink-extra-muted rounded-lg border border-edge-muted p-3 text-xs">- Couldn't render dashboard — the view didn't match the schema.- </div>+ <Show when={!pending()}>+ <div class="text-ink-extra-muted rounded-lg border border-edge-muted p-3 text-xs">+ Couldn't render dashboard — the view didn't match the schema.+ </div>+ </Show>}>{(v) => (diff --git a/apps/web/src/features/dynamic-ui/toolSchema.test.ts b/apps/web/src/features/dynamic-ui/toolSchema.test.tsnew file mode 100644index 0000000000..65d741a3ee--- /dev/null+++ b/apps/web/src/features/dynamic-ui/toolSchema.test.ts@@ -0,0 +1,97 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';+import { z } from 'zod';+import { ViewSchema } from './schema';+import { displayResultsToolSchema } from './toolSchema';++const GENERATED = resolve(+ import.meta.dirname,+ '../../../../../crates/ai_tools/src/display_results/schema.generated.json'+);++describe('DisplayResults tool contract', () => {+ it('matches the complete schema included by the Rust tool', () => {+ expect(readFileSync(GENERATED, 'utf8')).toBe(+ `${JSON.stringify(displayResultsToolSchema(), null, 2)}\n`+ );+ });++ it('resolves recursive widgets from the tool root and accepts renderer views', () => {+ // Read the artifact the backend sends, rather than relying on the original+ // Zod object: broken or misplaced $defs must fail this round trip.+ const contract = z.fromJSONSchema(+ JSON.parse(readFileSync(GENERATED, 'utf8'))+ );+ const view = {+ title: 'Project overview',+ widgets: [+ {+ type: 'container',+ direction: 'row',+ children: [+ {+ type: 'container',+ children: [{ type: 'md', markdown: 'Hello' }],+ },+ {+ type: 'list',+ source: {+ kind: 'items',+ entities: [{ type: 'document', id: 'doc-1' }],+ },+ },+ {+ type: 'timeline',+ events: [+ {+ time: 'Today',+ title: 'Reviewed',+ entity: { type: 'document', id: 'doc-1' },+ },+ ],+ },+ {+ type: 'channelMessage',+ channelId: 'channel-1',+ messageId: 'message-1',+ },+ ],+ },+ ],+ };+ expect(ViewSchema.safeParse(view).success).toBe(true);+ expect(contract.safeParse({ view }).success).toBe(true);+ });++ it.each([+ {},+ { view: {} },+ { view: { widgets: [{ type: 'unknown' }] } },+ { view: { widgets: [{ type: 'container', children: [{ type: 'md' }] }] } },+ {+ view: {+ widgets: [+ {+ type: 'list',+ source: {+ kind: 'items',+ entities: [{ id: 'doc-1', type: 'invented' }],+ },+ },+ ],+ },+ },+ ])('rejects malformed tool arguments: %j', (args) => {+ const contract = z.fromJSONSchema(displayResultsToolSchema());+ expect(contract.safeParse(args).success).toBe(false);+ });++ it('advertises rendering guidance on the tool itself', () => {+ const schema = displayResultsToolSchema();+ expect(schema.title).toBe('DisplayResults');+ expect(schema.description).toContain('ReadActivity');+ expect(schema.description).toContain('never invent ids');+ expect(schema.required).toEqual(['view']);+ });+});diff --git a/apps/web/src/features/dynamic-ui/toolSchema.ts b/apps/web/src/features/dynamic-ui/toolSchema.tsindex bca717c6d0..8bef1b078b 100644--- a/apps/web/src/features/dynamic-ui/toolSchema.ts+++ b/apps/web/src/features/dynamic-ui/toolSchema.ts@@ -2,33 +2,26 @@ import { z } from 'zod';import { ViewSchema } from './schema';/**- * Prompt text describing the `displayResults` tool's `view` argument.- *- * The backend tool input is `any` (so the schema isn't duplicated in Rust), so- * the model learns the shape from here instead: we convert the Zod `ViewSchema`- * to JSON Schema and embed it in the chat request's `additional_instructions`- * (see `buildRequest.ts`). Kept in its own module so importing it only pulls the- * Zod schema, not the dynamic-ui component tree.- *- * `unrepresentable: "any"` lets opaque schemas (the soup `Query` `z.custom`) fall- * back to "accepts anything" rather than throwing during conversion.+ * The complete model-facing DisplayResults contract, generated from the same+ * Zod schema the renderer validates. The Rust tool includes the generated JSON+ * directly, so every host that advertises the tool also supplies its schema.*/-let cached: string | undefined;--export function displayResultsInstructions(): string {- if (cached !== undefined) return cached;- const jsonSchema = z.toJSONSchema(ViewSchema, { unrepresentable: 'any' });- cached = [- '# displayResults',- '`displayResults` renders a rich, interactive view (lists, timelines, channel messages) directly in the chat. PREFER it over a plain-text answer whenever your response is largely about the user\'s workspace data — summaries of tasks/docs/activity, lists of entities, anything you would otherwise format as a markdown table or a long bulleted list. You do NOT need the user to ask for a "dashboard" or a "view": proactively call `displayResults` whenever it presents the information more clearly than text would.',- 'Typical triggers — call it even though the user never said "dashboard": "what did I get done this week?", "what\'s <teammate> working on?", "show me my open tasks", "summarize this project", "what happened in <channel>?". When in doubt and the answer is mostly workspace entities or metrics, render a view.',- '`ReadActivity` is the exception: it already renders its complete, entity-resolved response as a rich user-facing activity timeline. After calling `ReadActivity`, do NOT call `displayResults` to restate or summarize those events. Add at most one short textual takeaway.',- 'When you DO render a view, keep any accompanying chat text short (a one-line lead-in at most) — the view IS the answer; do not also restate it in prose.',- 'Its `view` argument MUST be a JSON object matching this JSON Schema (a `title` plus an ordered `widgets` array; layout is flexbox via the `container` widget):',- '```json',- JSON.stringify(jsonSchema, null, 2),- '```',- 'Entity-backed widgets (`list`, `timeline`, `channelMessage`) take real workspace entity ids — use ids you obtained from other tools (ListEntities, search, etc.), never invented ones.',- ].join('\n');- return cached;+export function displayResultsToolSchema() {+ return z.toJSONSchema(+ z.object({ view: ViewSchema }).meta({+ title: 'DisplayResults',+ description: [+ 'Present results as a rich, interactive view (lists, timelines, channel messages) directly in the conversation.',+ 'Prefer this tool when answering questions about workspace data: summaries of tasks/docs/activity, lists of entities, and information that would otherwise need a markdown table or long bulleted list. The user does not need to ask for a dashboard.',+ 'Typical triggers: "what did I get done this week?", "what is a teammate working on?", "show my open tasks", "summarize this project", and "what happened in this channel?".',+ 'ReadActivity already renders a complete activity timeline: do not call DisplayResults to repeat its events; add at most one short textual takeaway.',+ 'The view is the answer. Keep accompanying prose to a one-line lead-in at most and do not restate the same data.',+ 'Entity-backed widgets take real workspace entity ids obtained from other tools such as ListEntities or search; never invent ids. Prefer list sources with kind "items" and those entity references.',+ 'The frontend renders the view from the tool arguments immediately; this tool only acknowledges it.',+ ].join(' '),+ }),+ // The existing soup Query schema is an opaque pass-through owned by the+ // filter store. All widget/layout/entity fields retain their full schema.+ { unrepresentable: 'any' }+ );}diff --git a/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts b/apps/web/src/lib/core/component/AI/component/input/buildRequest.tsindex d3178f5b5a..7b196559e0 100644--- a/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts+++ b/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts@@ -1,4 +1,3 @@-import { displayResultsInstructions } from '@app/features/dynamic-ui/toolSchema';import { analytics } from '@app/lib/analytics';import { DEFAULT_MODEL } from '@core/component/AI/constant';import { useAdditionalInstructions } from '@core/component/AI/constant/prompts';@@ -31,19 +30,13 @@ export function useSendChatMessage() {attachments,toolset,}: ChatSendInput & { chatId?: string }): Promise<SendChatMessageResult> {- // Append the dynamic-UI (displayResults) JSON schema so the model knows the- // shape of the tool's `any` `view` argument.- const base = additionalInstructions(chatId);- const dashboard = displayResultsInstructions();- const merged = base ? `${base}\n\n${dashboard}` : dashboard;-const response = await cognitionApiServiceClient.sendStreamChatMessage({content,model: model ?? DEFAULT_MODEL,chat_id: chatId,attachments: attachments.length > 0 ? attachments : undefined,toolset,- additional_instructions: merged,+ additional_instructions: additionalInstructions(chatId),});if (isPaymentError(response)) {diff --git a/crates/ai_tools/src/display_results.rs b/crates/ai_tools/src/display_results.rsindex 82fa6220ae..b053ae4051 100644--- a/crates/ai_tools/src/display_results.rs+++ b/crates/ai_tools/src/display_results.rs@@ -1,8 +1,9 @@use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};use ai_toolset::{ToolAnnotated, ToolAnnotations};use async_trait::async_trait;-use schemars::JsonSchema;+use schemars::{JsonSchema, Schema, SchemaGenerator};use serde::{Deserialize, Serialize};+use std::borrow::Cow;use crate::ToolServiceContext;@@ -11,27 +12,52 @@ pub struct DisplayResultsResponse {pub message: String,}-/// `displayResults` is intentionally a thin pass-through tool: the model emits-/// a dynamic-UI "view" as the `view` argument, the FRONTEND renders that view-/// from the tool call arguments (using the dynamic-ui component library), and the-/// backend does no work — it just acknowledges so the model can continue.+#[cfg(test)]+mod test;++/// A view rendered by the frontend directly from the tool-call arguments.///-/// The input is arbitrary JSON (`view`) because the dynamic-UI schema is owned by-/// the frontend (a Zod schema) and conveyed to the model out-of-band rather than-/// duplicated here in Rust.-#[derive(Debug, Deserialize, JsonSchema)]+/// The AI input schema is generated from the renderer's Zod schema. Keeping it+/// on the tool means agent sessions do not depend on frontend instructions.+#[derive(Debug, Deserialize)]+pub struct DisplayResults {+ /// Kept opaque so the renderer can handle partial and malformed views.+ #[expect(dead_code, reason = "the frontend consumes the tool-call arguments")]+ pub view: serde_json::Value,+}++// Frontend wire typegen must remain permissive: streamed arguments are incomplete+// until the call finishes, and DashboardToolView owns validation/error rendering.+// Preserve this contract separately from the model-facing recursive input schema.+#[derive(JsonSchema)]#[schemars(title = "DisplayResults",description = "Present results to the user as a rich view. The `view` argument is a dynamic-UI view object (a title plus an ordered list of widgets) following the dynamic-UI schema provided to you. The view is rendered immediately in the chat; this tool returns as soon as it is dispatched.")]-pub struct DisplayResults {- // The frontend renders the view from the tool-call arguments; the backend- // never reads it (hence allow(dead_code)).- #[allow(dead_code)]+struct DisplayResultsWire {+ #[expect(dead_code, reason = "only used to generate the frontend wire schema")]#[schemars(description = "The dynamic-UI view to render: an object with an optional `title` and a `widgets` array, per the provided dynamic-UI schema.")]- pub view: serde_json::Value,+ view: serde_json::Value,+}++impl JsonSchema for DisplayResults {+ fn schema_name() -> Cow<'static, str> {+ "DisplayResults".into()+ }++ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ if generator.settings().inline_subschemas {+ // The AI pipeline requests a complete root schema. Its recursive+ // widget refs and $defs must stay together at that root; nesting+ // this schema below `view` would break their JSON-pointer targets.+ serde_json::from_str(include_str!("display_results/schema.generated.json"))+ .expect("the generated DisplayResults tool schema must be valid JSON Schema")+ } else {+ DisplayResultsWire::json_schema(generator)+ }+ }}impl ToolAnnotated for DisplayResults {diff --git a/crates/ai_tools/src/display_results/schema.generated.json b/crates/ai_tools/src/display_results/schema.generated.jsonnew file mode 100644index 0000000000..77d3f85ebb--- /dev/null+++ b/crates/ai_tools/src/display_results/schema.generated.json@@ -0,0 +1,314 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "view": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string"+ },+ "widgets": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/__schema0"+ }+ }+ },+ "required": [+ "widgets"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "view"+ ],+ "additionalProperties": false,+ "title": "DisplayResults",+ "description": "Present results as a rich, interactive view (lists, timelines, channel messages) directly in the conversation. Prefer this tool when answering questions about workspace data: summaries of tasks/docs/activity, lists of entities, and information that would otherwise need a markdown table or long bulleted list. The user does not need to ask for a dashboard. Typical triggers: \"what did I get done this week?\", \"what is a teammate working on?\", \"show my open tasks\", \"summarize this project\", and \"what happened in this channel?\". ReadActivity already renders a complete activity timeline: do not call DisplayResults to repeat its events; add at most one short textual takeaway. The view is the answer. Keep accompanying prose to a one-line lead-in at most and do not restate the same data. Entity-backed widgets take real workspace entity ids obtained from other tools such as ListEntities or search; never invent ids. Prefer list sources with kind \"items\" and those entity references. The frontend renders the view from the tool arguments immediately; this tool only acknowledges it.",+ "$defs": {+ "__schema0": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "md"+ },+ "markdown": {+ "type": "string"+ }+ },+ "required": [+ "type",+ "markdown"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "timeline"+ },+ "title": {+ "type": "string"+ },+ "events": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "time": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "entity": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder",+ "skill",+ "agent_session",+ "scheduled_action",+ "initiative",+ "email",+ "automation",+ "channel_thread"+ ]+ }+ },+ "required": [+ "id",+ "type"+ ],+ "additionalProperties": false+ },+ "future": {+ "type": "boolean"+ }+ },+ "required": [+ "time",+ "title"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "type",+ "events"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "list"+ },+ "title": {+ "type": "string"+ },+ "source": {+ "oneOf": [+ {+ "type": "object",+ "properties": {+ "kind": {+ "type": "string",+ "const": "query"+ },+ "query": {}+ },+ "required": [+ "kind",+ "query"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "kind": {+ "type": "string",+ "const": "items"+ },+ "entities": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "enum": [+ "user",+ "chat",+ "channel",+ "channel_message",+ "document",+ "project",+ "email_thread",+ "calendar_event",+ "team",+ "call",+ "foreign_entity",+ "static_file",+ "crm_company",+ "crm_contact",+ "reminder",+ "skill",+ "agent_session",+ "scheduled_action",+ "initiative",+ "email",+ "automation",+ "channel_thread"+ ]+ }+ },+ "required": [+ "id",+ "type"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "kind",+ "entities"+ ],+ "additionalProperties": false+ }+ ]+ },+ "groupBy": {+ "type": "string",+ "enum": [+ "date",+ "entity_type",+ "project"+ ]+ },+ "limit": {+ "type": "number"+ }+ },+ "required": [+ "type",+ "source"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "channelMessage"+ },+ "channelId": {+ "type": "string"+ },+ "messageId": {+ "type": "string"+ }+ },+ "required": [+ "type",+ "channelId",+ "messageId"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "const": "container"+ },+ "direction": {+ "type": "string",+ "enum": [+ "row",+ "col"+ ]+ },+ "gap": {+ "type": "number"+ },+ "wrap": {+ "type": "boolean"+ },+ "align": {+ "type": "string",+ "enum": [+ "start",+ "center",+ "end",+ "stretch"+ ]+ },+ "justify": {+ "type": "string",+ "enum": [+ "start",+ "center",+ "end",+ "between"+ ]+ },+ "title": {+ "type": "string"+ },+ "children": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/__schema0"+ }+ }+ },+ "required": [+ "type",+ "children"+ ],+ "additionalProperties": false+ }+ ]+ }+ }+}diff --git a/crates/ai_tools/src/display_results/test.rs b/crates/ai_tools/src/display_results/test.rsnew file mode 100644index 0000000000..ec07ec505e--- /dev/null+++ b/crates/ai_tools/src/display_results/test.rs@@ -0,0 +1,111 @@+use super::DisplayResults;+use crate::{AiHost, tools_for};+use ai_toolset::{+ ToolSet,+ schema::{frontend_schemas_builder, generate_validated_input_schema},+};+use serde_json::{Value, json};++fn assert_local_refs_resolve(root: &Value, node: &Value) {+ match node {+ Value::Object(fields) => {+ if let Some(reference) = fields.get("$ref").and_then(Value::as_str) {+ let pointer = reference.strip_prefix('#').expect("local schema reference");+ assert!(+ root.pointer(pointer).is_some(),+ "unresolved reference {reference}"+ );+ }+ for child in fields.values() {+ assert_local_refs_resolve(root, child);+ }+ }+ Value::Array(items) => {+ for child in items {+ assert_local_refs_resolve(root, child);+ }+ }+ _ => {}+ }+}++#[test]+fn provider_schema_contains_the_recursive_view_contract_at_the_tool_root() {+ let validated = generate_validated_input_schema::<DisplayResults>().expect("valid schema");+ assert_eq!(validated.name, "DisplayResults");+ assert!(validated.description.contains("ReadActivity"));+ let schema = serde_json::to_value(validated.schema).expect("serialize schema");+ assert_eq!(schema["required"], json!(["view"]));+ assert_eq!(schema["properties"]["view"]["required"], json!(["widgets"]));+ assert_local_refs_resolve(&schema, &schema);++ let reference = schema["properties"]["view"]["properties"]["widgets"]["items"]["$ref"]+ .as_str()+ .expect("recursive widget reference");+ let variants = schema+ .pointer(reference.strip_prefix('#').unwrap())+ .and_then(|widget| widget["anyOf"].as_array())+ .expect("widget variants");+ let names = variants+ .iter()+ .map(|variant| variant["properties"]["type"]["const"].as_str().unwrap())+ .collect::<Vec<_>>();+ assert_eq!(+ names,+ ["md", "timeline", "list", "channelMessage", "container"]+ );+ let container = variants.last().unwrap();+ assert_eq!(+ container["properties"]["children"]["items"]["$ref"],+ reference+ );+}++#[test]+fn agent_sessions_advertise_the_same_complete_contract_as_chat() {+ for host in [AiHost::Chat, AiHost::AgentSession] {+ let toolset = tools_for(host);+ let display = toolset+ .toolset+ .request_schemas()+ .expect("request schemas")+ .into_iter()+ .find(|tool| tool.name == "DisplayResults")+ .expect("DisplayResults available");+ let schema = serde_json::to_value(display.schema).expect("serialize schema");+ assert!(schema["properties"]["view"]["properties"]["widgets"].is_object());+ assert!(schema["$defs"].is_object());+ assert_local_refs_resolve(&schema, &schema);+ }+}++#[test]+fn display_results_is_omitted_on_hosts_without_a_view_renderer() {+ for host in [AiHost::ChannelBot, AiHost::Mcp] {+ let toolset = tools_for(host);+ assert!(+ !toolset.toolset.tools.contains_key("DisplayResults"),+ "{host:?}"+ );+ }++ let channel_tools = tools_for(AiHost::ChannelBot);+ assert!(channel_tools.toolset.tools.contains_key("SearchTools"));+ assert!(channel_tools.toolset.tools.contains_key("LoadTools"));+}++#[test]+fn frontend_wire_schema_leaves_view_validation_to_the_renderer() {+ let schemas = frontend_schemas_builder()+ .merge(&tools_for(AiHost::Chat))+ .build()+ .to_json_pretty()+ .expect("serialize frontend schemas");+ let schemas: Value = serde_json::from_str(&schemas).expect("frontend schemas JSON");+ let json = &schemas["$defs"]["DisplayResults"];+ assert_eq!(json["title"], "DisplayResults");+ assert_eq!(json["required"], json!(["view"]));+ assert!(json["properties"]["view"]["properties"].is_null());+ assert!(json["properties"]["view"]["type"].is_null());+ assert!(json.get("$defs").is_none());+}diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex f82cb21160..5659080575 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -117,7 +117,8 @@ pub(crate) fn subagent_toolset() -> AiToolSet {/// two register `SendEmail` and the deferring `CreateCalendarEvent` — on any/// other host those registrations would return `PendingUserExecution`/// forever while reading to the model as success. Second, whether the host-/// runs the chat frontend's tool discovery and display tools.+/// supports tool discovery and can render tool-call views. Channel bots keep+/// discovery, but only chat and agent-session transcripts render rich views.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum AiHost {/// The AI chat, and any host whose conversation is stored as a chat the@@ -131,7 +132,8 @@ pub enum AiHost {/// waits on, never a pending composer.AgentSession,/// The channel-mention bot: no composer, so `CreateCalendarEvent`- /// executes directly in the agent loop and `SendEmail` is omitted.+ /// executes directly in the agent loop and `SendEmail` is omitted. Replies+ /// contain text only, so this host also omits `DisplayResults`.ChannelBot,/// The MCP server: like [`AiHost::ChannelBot`] for user tools — MCP/// clients apply their own confirmation policy from tool annotations —@@ -159,10 +161,15 @@ pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {let toolset = match host {AiHost::Chat | AiHost::AgentSession | AiHost::ChannelBot => toolset.add_tool::<SearchTools, ToolServiceContext>()- .add_tool::<LoadTools, ToolServiceContext>()- .add_tool::<DisplayResults, ToolServiceContext>(),+ .add_tool::<LoadTools, ToolServiceContext>(),AiHost::Mcp => toolset,};+ let toolset = match host {+ AiHost::Chat | AiHost::AgentSession => {+ toolset.add_tool::<DisplayResults, ToolServiceContext>()+ }+ AiHost::ChannelBot | AiHost::Mcp => toolset,+ };let prompt: Box<dyn std::fmt::Display + Send + Sync> = match host {AiHost::Chat => Box::new(&prompt::TOOL_USE_PROMPT),AiHost::AgentSession => Box::new(&prompt::SESSION_TOOL_USE_PROMPT),diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex c1040ce309..32266fbbcb 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -411,6 +411,17 @@ agent as working, every Thinking label, **Calling N tools** row, shimmeringtool title, and working row settles — earlier turns never shimmer, even onesthe runtime cut off mid-call. At most one shimmering row is ever expected.+A `displayResults` call is the exception: it renders the dynamic-UI view the+model composed — the same dashboard (markdown, timelines, entity lists, channel+messages) that AI chat shows — full width in the transcript, and never folded+into a tool group or behind a card. Expect the view itself, not a `DisplayResults`+row. Incomplete arguments stay hidden while streaming, and a valid view updates+as its arguments change. A completed call whose JSON does not match the schema+shows `Couldn't render dashboard`; a failed call keeps its error card.+Macro's built-in agents receive the complete view schema with the tool definition.+External coding agents connected through Macro's MCP server do not currently+receive this tool.+### Sharing a sessionIn the Agents workspace, saved sessions use the shared top-bar controls: sessiondiff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rsindex 232c2136a8..4cb89afd5c 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs@@ -79,6 +79,7 @@ fn typescript() -> Job {)).add_step(generate_api_types()).add_step(show_sccache_stats())+ .add_step(check_dynamic_ui_schema()).add_step(check_types()).add_step(check_collaboration_types()).add_step(check_lexical_service_types())@@ -187,7 +188,7 @@ fn paths_filter() -> Step<Use> {.add_with(("filters",format!(- "should_run:\n{artifact_paths} - 'services/lexical-service/**'\n - '.github/actions/setup-reqs-web/**'\napi_changed:\n - 'crates/**/*.rs'\n - 'services/**/*.rs'\n - 'Cargo.toml'\n - 'Cargo.lock'\n - 'apps/web/scripts/generate-api-schema.ts'\n - 'apps/web/scripts/services.ts'\n - '.github/actions/setup-reqs-web/**'\n"+ "should_run:\n{artifact_paths} - 'services/lexical-service/**'\n - 'crates/ai_tools/src/display_results/schema.generated.json'\n - '.github/actions/setup-reqs-web/**'\napi_changed:\n - 'crates/**/*.rs'\n - 'services/**/*.rs'\n - 'Cargo.toml'\n - 'Cargo.lock'\n - 'apps/web/scripts/generate-api-schema.ts'\n - 'apps/web/scripts/services.ts'\n - '.github/actions/setup-reqs-web/**'\n"),))}@@ -215,6 +216,12 @@ fn check_types() -> Step<Run> {.working_directory(xtask_paths::repo_dir!("apps/web"))}+fn check_dynamic_ui_schema() -> Step<Run> {+ Step::new("Check Dynamic UI Schema")+ .run("bun run check-dynamic-ui-schema")+ .working_directory(xtask_paths::repo_dir!("apps/web"))+}+fn check_collaboration_types() -> Step<Run> {Step::new("Check Collaboration Package Types").run("bun run type-check")