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(ai): dynamic UI (#4224)
Eric Hayes7a471b462a4a
diff --git a/js/app/packages/app/component/dynamic-ui/DashboardToolView.lazy.ts b/js/app/packages/app/component/dynamic-ui/DashboardToolView.lazy.tsnew file mode 100644index 0000000000..726fbc935a--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/DashboardToolView.lazy.ts@@ -0,0 +1,18 @@+import { lazy } from 'solid-js';++/**+ * Lazy boundary for the dashboard view.+ *+ * The dynamic-ui tree is entity-heavy and sits inside a module-init cycle+ * (`entity.ts` ⇄ `DocumentPreview`/`StaticMarkdown` ⇄ the `@entity` barrel).+ * Importing it *eagerly* from the chat startup bundle enters that cycle in the+ * wrong order and throws a TDZ `ReferenceError` ("Cannot access 'EntityTitle'+ * before initialization").+ *+ * Like the split-layout component registry (which `lazy(() => import())`s every+ * heavy block UI), we keep the boundary here in `@app` and dynamic-import the+ * real component. Eager consumers in `core` (the AI tool handler) then reference+ * this with a normal STATIC import — the heavy tree stays behind the dynamic+ * import, so it never lands in the startup graph and the cycle never bites.+ */+export const DashboardToolView = lazy(() => import('./DashboardToolView'));diff --git a/js/app/packages/app/component/dynamic-ui/DashboardToolView.tsx b/js/app/packages/app/component/dynamic-ui/DashboardToolView.tsxnew file mode 100644index 0000000000..a29f764b24--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/DashboardToolView.tsx@@ -0,0 +1,41 @@+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { aiChatTheme } from '@core/component/LexicalMarkdown/theme';+import { createMemo, Show } from 'solid-js';+import { ViewSchema } from './schema';+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.+ *+ * 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 }) {+ const parsed = createMemo(() => ViewSchema.safeParse(props.view));+ const view = () => {+ const r = parsed();+ return r.success ? r.data : undefined;+ };++ return (+ <Show+ when={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>+ }+ >+ {(v) => (+ <StaticMarkdownContext theme={aiChatTheme}>+ <Widget.Compose view={v()} />+ </StaticMarkdownContext>+ )}+ </Show>+ );+}diff --git a/js/app/packages/app/component/dynamic-ui/Gallery.tsx b/js/app/packages/app/component/dynamic-ui/Gallery.tsxnew file mode 100644index 0000000000..5f1b999ce4--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/Gallery.tsx@@ -0,0 +1,440 @@+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { aiChatTheme } from '@core/component/LexicalMarkdown/theme';+import { ErrorBoundary, For, Suspense } from 'solid-js';+import type { View, Widget } from './schema';+import { Widget as WidgetNS } from './widget';++/**+ * Debug gallery for the dynamic-ui widget library.+ *+ * Mounted under the LOCAL_ONLY debug registry as `dynamic-ui`+ * (navigate to `/component/dynamic-ui` in dev). Shows every widget in isolation+ * plus a few composed views — the same data shape the eventual `compose_view` AI+ * tool will emit. No AI involved: everything below is hand-written fixtures.+ *+ * The `card`/`list`/`timeline` entity refs below are REAL ids from dev-assets+ * (the macro-db-dev RDS the running app talks to), owned by [email protected],+ * so they resolve to real previews via ItemPreview. Swap them for other ids as+ * needed.+ */++// --- real entity refs from dev-assets (macro-db-dev RDS), owned by+// macro|[email protected] — the account logged into the running app — so they+// resolve to real previews via ItemPreview.+const DOC_SHOWCASE = '019e943b-ffbd-7a2b-b81d-7fe694f493b2'; // "Mentions and Citations Showcase"+const DOC_STABILIZE = '019e8f7d-2105-7d37-b4fd-8a5e35caff90'; // "Stabilize the tool render component during chat streaming"+const TASK_GROUP_TOOLS = '019e8f7f-283a-7d61-99c3-7f94033ec73e'; // "Group tool calls like claude code"+const TASK_LINK_MSG = '019e84b9-b21a-724a-80c8-8e26374779f7'; // "should be able to link to specific message"+const TASK_GEN_BUTTON = '019e839e-1d90-7731-92a8-bed4f25116ee'; // "add generate task button to messages"+const TASK_REVIEW_PR = '019e8f72-7699-7a45-aa3c-c7d5c2a8e7f4'; // "review guys pr"+const CH_MACRO = '0194671b-3624-747a-840e-69d944fe411a'; // "macro" channel++const SAMPLE_ENTITIES = [+ { id: TASK_GROUP_TOOLS, type: 'document' as const },+ { id: TASK_LINK_MSG, type: 'document' as const },+ { id: TASK_GEN_BUTTON, type: 'document' as const },+ { id: DOC_SHOWCASE, type: 'document' as const },+ { id: CH_MACRO, type: 'channel' as const },+];++// --- individual widget catalog: ONE section per widget ----------------------+const CATALOG: Array<{ label: string; widget: Widget }> = [+ {+ label: 'md',+ widget: {+ type: 'md',+ markdown:+ '## Weekly summary\n\nYou shipped **4 PRs** and closed *6 tickets*. See the [tracker](https://macro.com) for the full breakdown.\n\n- Auth race fix\n- Tool render stabilization\n\n> Nice momentum this week.',+ },+ },+ {+ label: 'stat',+ widget: {+ type: 'stat',+ label: 'PRs merged',+ value: 12,+ unit: 'PRs',+ delta: { value: 40, direction: 'up', label: 'vs last week' },+ },+ },+ {+ label: 'timeline',+ widget: {+ type: 'timeline',+ title: "Yesterday's activity",+ events: [+ {+ time: '9:12am',+ title: 'Edited a document',+ description: 'Mentions & Citations Showcase',+ entity: { id: DOC_SHOWCASE, type: 'document' },+ },+ {+ time: '11:40am',+ title: "Reviewed a teammate's PR",+ entity: { id: TASK_REVIEW_PR, type: 'document' },+ },+ {+ time: 'Tomorrow',+ title: 'Sync on the migration',+ entity: { id: CH_MACRO, type: 'channel' },+ future: true,+ },+ {+ time: 'Friday',+ title: 'Ship the dynamic-ui widgets',+ entity: { id: DOC_STABILIZE, type: 'document' },+ future: true,+ },+ ],+ },+ },+ {+ label: 'list',+ widget: {+ type: 'list',+ title: 'Pinned items',+ source: { kind: 'items', entities: SAMPLE_ENTITIES },+ },+ },+ {+ // Both card kinds (a task and an md doc) in one labeled section.+ label: 'card',+ widget: {+ type: 'container',+ direction: 'col',+ gap: 3,+ children: [+ { type: 'card', entity: { id: TASK_REVIEW_PR, type: 'document' } },+ { type: 'card', entity: { id: DOC_SHOWCASE, type: 'document' } },+ ],+ },+ },+ {+ label: 'channelMessage',+ widget: {+ type: 'channelMessage',+ channelId: '019467c2-49d0-7d99-b0b9-d535811a337d',+ messageId: '019eb2e2-c4f5-730e-8aee-70794417ddbd',+ },+ },+ {+ // Container demo: a row laying out two *different* widgets side by side.+ label: 'container',+ widget: {+ type: 'container',+ direction: 'row',+ gap: 3,+ children: [+ {+ type: 'stat',+ label: 'Throughput',+ value: 14,+ unit: '/day',+ delta: { value: 3, direction: 'up', label: 'vs last week' },+ },+ {+ type: 'md',+ markdown:+ '### Notes\n\nLayout is flexbox — child **order** sets position. This row places a stat and notes side by side.',+ },+ ],+ },+ },+];++// --- composed views ----------------------------------------------------------+const COMPOSED: View[] = [+ {+ title: 'What did I get done yesterday?',+ widgets: [+ {+ type: 'container',+ direction: 'row',+ gap: 3,+ children: [+ {+ type: 'stat',+ label: 'PRs merged',+ value: 4,+ delta: { value: 2, direction: 'up', label: 'vs avg' },+ },+ {+ type: 'stat',+ label: 'Tickets closed',+ value: 6,+ },+ {+ type: 'stat',+ label: 'Messages sent',+ value: 28,+ },+ ],+ },+ {+ type: 'timeline',+ title: 'Highlights',+ events: [+ { time: '9:12am', title: 'Shipped auth race fix (PR #482)' },+ { time: '1:30pm', title: 'Closed Sprint 14 carryover tickets' },+ { time: '4:50pm', title: 'Unblocked a teammate on the migration' },+ ],+ },+ ],+ },+ {+ title: 'My current work',+ widgets: [+ {+ type: 'card',+ entity: { id: DOC_STABILIZE, type: 'document' },+ },+ {+ type: 'container',+ direction: 'row',+ gap: 3,+ children: [+ {+ type: 'stat',+ label: 'In review',+ value: 3,+ },+ {+ type: 'stat',+ label: 'Blocked',+ value: 1,+ },+ ],+ },+ {+ type: 'list',+ title: 'Active tasks',+ source: { kind: 'items', entities: SAMPLE_ENTITIES },+ },+ ],+ },+ {+ title: 'Project health snapshot',+ widgets: [+ {+ type: 'md',+ markdown:+ '### Tool render stabilization\n\nA compact project readout that mixes narrative, metrics, trends, and the source document driving the work.',+ },+ {+ type: 'container',+ direction: 'row',+ gap: 3,+ wrap: true,+ children: [+ {+ type: 'stat',+ label: 'Ready checks',+ value: '7/9',+ delta: { value: 3, direction: 'up', label: 'since standup' },+ },+ {+ type: 'stat',+ label: 'Open risks',+ value: 2,+ delta: { value: 1, direction: 'down', label: 'from yesterday' },+ },+ {+ type: 'stat',+ label: 'Confidence',+ value: 82,+ unit: '%',+ delta: { value: 6, direction: 'up', label: 'this week' },+ },+ ],+ },+ {+ type: 'card',+ entity: { id: DOC_STABILIZE, type: 'document' },+ },+ ],+ },+ {+ title: 'Review queue',+ widgets: [+ {+ type: 'container',+ direction: 'row',+ gap: 3,+ children: [+ {+ type: 'stat',+ label: 'In queue',+ value: 6,+ delta: { value: 2, direction: 'down', label: 'since 9a' },+ },+ {+ type: 'md',+ markdown:+ '### Triage notes\n\n- Prioritize items with product impact\n- Pull docs into review comments\n- Leave owners with one clear next action',+ },+ ],+ },+ {+ type: 'list',+ title: 'Items to revisit',+ source: {+ kind: 'items',+ entities: [+ { id: TASK_REVIEW_PR, type: 'document' },+ { id: TASK_GROUP_TOOLS, type: 'document' },+ { id: TASK_LINK_MSG, type: 'document' },+ { id: DOC_SHOWCASE, type: 'document' },+ ],+ },+ limit: 4,+ },+ {+ type: 'timeline',+ title: 'Review windows',+ events: [+ { time: '10:00am', title: 'Scan stale review threads' },+ {+ time: '1:30pm',+ title: 'Pair on linked message follow-up',+ entity: { id: TASK_LINK_MSG, type: 'document' },+ },+ {+ time: '4:00pm',+ title: 'Send final notes to #macro',+ entity: { id: CH_MACRO, type: 'channel' },+ future: true,+ },+ ],+ },+ ],+ },+ {+ title: 'Message follow-up',+ widgets: [+ {+ type: 'channelMessage',+ channelId: '019467c2-49d0-7d99-b0b9-d535811a337d',+ messageId: '019eb2e2-c4f5-730e-8aee-70794417ddbd',+ },+ {+ type: 'container',+ direction: 'row',+ gap: 3,+ children: [+ {+ type: 'stat',+ label: 'Replies needed',+ value: 3,+ },+ {+ type: 'stat',+ label: 'Linked tasks',+ value: 2,+ },+ {+ type: 'stat',+ label: 'ETA',+ value: 'Today',+ },+ ],+ },+ {+ type: 'md',+ markdown:+ '### Draft response checklist\n\n- Confirm the owner\n- Link the relevant task\n- Call out the next checkpoint',+ },+ ],+ },+];++function DemoCell(props: { label: string; children: any }) {+ return (+ <div class="flex flex-col gap-2 rounded-lg border border-edge-muted p-3">+ <span class="text-ink-extra-muted text-xxs font-medium uppercase tracking-wide">+ {props.label}+ </span>+ {/* Isolate each widget: a single widget that throws or suspends shows+ its own error/loading here instead of blanking the whole gallery. */}+ <div class="w-full">+ <ErrorBoundary+ fallback={(err) => (+ <div class="text-warning text-xxs">render error: {String(err)}</div>+ )}+ >+ <Suspense+ fallback={<div class="text-ink-muted text-xxs">loading…</div>}+ >+ {props.children}+ </Suspense>+ </ErrorBoundary>+ </div>+ </div>+ );+}++export default function Gallery() {+ return (+ <ErrorBoundary+ fallback={(err) => (+ <div class="size-full overflow-auto bg-surface p-6">+ <pre class="whitespace-pre-wrap rounded border border-edge-muted p-4 text-sm text-warning">+ Gallery crashed: {String(err?.stack ?? err)}+ </pre>+ </div>+ )}+ >+ <Suspense+ fallback={+ <div class="text-ink-muted p-6 text-sm">Loading widgets…</div>+ }+ >+ <GalleryBody />+ </Suspense>+ </ErrorBoundary>+ );+}++function GalleryBody() {+ return (+ <StaticMarkdownContext theme={aiChatTheme}>+ <div class="size-full overflow-auto bg-surface">+ <div class="mx-auto flex w-full max-w-3xl flex-col gap-8 p-6">+ <header class="flex flex-col gap-1">+ <h1 class="text-ink text-xl font-semibold">+ Dynamic UI — Widget Gallery+ </h1>+ <p class="text-ink-muted text-sm">+ Every widget rendered from a hand-written schema fixture (no AI).+ The same shapes the <code>compose_view</code> tool will emit.+ </p>+ </header>++ <section class="flex flex-col gap-3">+ <h2 class="text-ink text-base font-semibold">Catalog</h2>+ <div class="flex flex-col gap-3">+ <For each={CATALOG}>+ {(entry) => (+ <DemoCell label={entry.label}>+ <WidgetNS.Render node={entry.widget} />+ </DemoCell>+ )}+ </For>+ </div>+ </section>++ <section class="flex flex-col gap-4">+ <h2 class="text-ink text-base font-semibold">Composed views</h2>+ <For each={COMPOSED}>+ {(view) => (+ <div class="rounded-lg border border-edge-muted p-4">+ <WidgetNS.Compose view={view} />+ </div>+ )}+ </For>+ </section>+ </div>+ </div>+ </StaticMarkdownContext>+ );+}diff --git a/js/app/packages/app/component/dynamic-ui/core/Layout.tsx b/js/app/packages/app/component/dynamic-ui/core/Layout.tsxnew file mode 100644index 0000000000..96c0a3f1a7--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/core/Layout.tsx@@ -0,0 +1,121 @@+import { cn } from '@ui';+import { type JSX, Show, splitProps } from 'solid-js';++type Align = 'start' | 'center' | 'end' | 'stretch';+type Justify = 'start' | 'center' | 'end' | 'between';++const GAP = [+ 'gap-0',+ 'gap-1',+ 'gap-1.5',+ 'gap-3',+ 'gap-4',+ 'gap-6',+ 'gap-8',+] as const;++const gapClass = (step: number | undefined): string =>+ GAP[Math.min(Math.max(step ?? 3, 0), GAP.length - 1)];++const alignClass = (align: Align | undefined): string | undefined =>+ align === 'start'+ ? 'items-start'+ : align === 'center'+ ? 'items-center'+ : align === 'end'+ ? 'items-end'+ : align === 'stretch'+ ? 'items-stretch'+ : undefined;++const justifyClass = (justify: Justify | undefined): string | undefined =>+ justify === 'start'+ ? 'justify-start'+ : justify === 'center'+ ? 'justify-center'+ : justify === 'end'+ ? 'justify-end'+ : justify === 'between'+ ? 'justify-between'+ : undefined;++export function View(props: {+ title?: string;+ class?: string;+ children: JSX.Element;+}) {+ const [local] = splitProps(props, ['title', 'class', 'children']);++ return (+ <div class={cn('flex w-full flex-col gap-3', local.class)}>+ <Show when={local.title}>+ <h2 class="text-ink text-base font-semibold">{local.title}</h2>+ </Show>+ {local.children}+ </div>+ );+}++export function Row(props: {+ gap?: number;+ align?: Align;+ justify?: Justify;+ wrap?: boolean;+ class?: string;+ children: JSX.Element;+}) {+ const [local] = splitProps(props, [+ 'gap',+ 'align',+ 'justify',+ 'wrap',+ 'class',+ 'children',+ ]);++ return (+ <div+ class={cn(+ 'flex flex-row',+ '[&>*]:min-w-0 [&>*]:flex-1',+ gapClass(local.gap),+ alignClass(local.align),+ justifyClass(local.justify),+ local.wrap && 'flex-wrap',+ local.class+ )}+ >+ {local.children}+ </div>+ );+}++export function Col(props: {+ gap?: number;+ align?: Align;+ justify?: Justify;+ class?: string;+ children: JSX.Element;+}) {+ const [local] = splitProps(props, [+ 'gap',+ 'align',+ 'justify',+ 'class',+ 'children',+ ]);++ return (+ <div+ class={cn(+ 'flex flex-col',+ gapClass(local.gap),+ alignClass(local.align),+ justifyClass(local.justify),+ local.class+ )}+ >+ {local.children}+ </div>+ );+}diff --git a/js/app/packages/app/component/dynamic-ui/index.ts b/js/app/packages/app/component/dynamic-ui/index.tsnew file mode 100644index 0000000000..5eacea045a--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/index.ts@@ -0,0 +1,2 @@+export * from './schema';+export { Widget } from './widget';diff --git a/js/app/packages/app/component/dynamic-ui/render.tsx b/js/app/packages/app/component/dynamic-ui/render.tsxnew file mode 100644index 0000000000..71c5874c17--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/render.tsx@@ -0,0 +1,138 @@+import { createMemo, ErrorBoundary, For, type JSX, Suspense } from 'solid-js';+import { match } from 'ts-pattern';+import { Col, Row, View } from './core/Layout';+import type {+ View as ComposedView,+ Widget,+ WidgetOf,+ WidgetType,+} from './schema';+import { Card } from './widgets/Card';+import { ChannelMessage } from './widgets/ChannelMessage';+import { List } from './widgets/List';+import { Md } from './widgets/Md';+import { Stat } from './widgets/Stat';+import { Timeline } from './widgets/Timeline';++/**+ * The single, exhaustive node renderer. One `match()` arm per widget `type`+ * dispatches to its real-props component, spreading the schema node directly.+ * The `container` arm recurses through {@link Container}. There is no registry+ * and no `<Dynamic>`: adding a widget means adding one arm here (and the+ * `.exhaustive()` keeps it honest).+ */+export function Render(props: { node: Widget }): JSX.Element {+ return match(props.node)+ .with({ type: 'md' }, (n) => <Md {...n} />)+ .with({ type: 'stat' }, (n) => <Stat {...n} />)+ .with({ type: 'timeline' }, (n) => <Timeline {...n} />)+ .with({ type: 'card' }, (n) => <Card {...n} />)+ .with({ type: 'channelMessage' }, (n) => <ChannelMessage {...n} />)+ .with({ type: 'list' }, (n) => <List {...n} />)+ .with({ type: 'container' }, (n) => <Container node={n} />)+ .exhaustive();+}++/**+ * Widgets that must always span the full width of their container — they never+ * share a horizontal row, so e.g. a `list` dropped into a `row` still renders+ * full-width on its own line instead of being squished into a column.+ */+const FULL_WIDTH_TYPES: ReadonlySet<WidgetType> = new Set<WidgetType>(['list']);++/**+ * Renders a `container` node: picks {@link RowLayout} or {@link Col} by+ * `direction` (defaulting to a column) and recurses each child through+ * {@link Render}. In a column every child is already full width.+ */+function Container(props: { node: WidgetOf<'container'> }): JSX.Element {+ const node = () => props.node;+ return match(node().direction)+ .with('row', () => <RowLayout node={node()} />)+ .otherwise(() => (+ <Col gap={node().gap} align={node().align} justify={node().justify}>+ <For each={node().children}>{(child) => <Render node={child} />}</For>+ </Col>+ ));+}++type RowSegment =+ | { full: true; item: Widget }+ | { full: false; items: Widget[] };++/**+ * Lays out a `row` container: full-width-only widgets ({@link FULL_WIDTH_TYPES})+ * break onto their own full-width line, while runs of normal widgets share a+ * row. Segments stack in a column.+ */+function RowLayout(props: { node: WidgetOf<'container'> }): JSX.Element {+ const segments = createMemo<RowSegment[]>(() => {+ const out: RowSegment[] = [];+ let run: Widget[] = [];+ const flush = () => {+ if (run.length > 0) {+ out.push({ full: false, items: run });+ run = [];+ }+ };+ for (const child of props.node.children) {+ if (FULL_WIDTH_TYPES.has(child.type)) {+ flush();+ out.push({ full: true, item: child });+ } else {+ run.push(child);+ }+ }+ flush();+ return out;+ });++ return (+ <Col gap={props.node.gap}>+ <For each={segments()}>+ {(seg) =>+ seg.full ? (+ <Render node={seg.item} />+ ) : (+ <Row+ gap={props.node.gap}+ align={props.node.align}+ justify={props.node.justify}+ wrap={props.node.wrap}+ >+ <For each={seg.items}>{(item) => <Render node={item} />}</For>+ </Row>+ )+ }+ </For>+ </Col>+ );+}++/**+ * Renders a composed view: the layout {@link View} shell with each top-level+ * widget mapped through {@link Render}. The whole tree is wrapped in ONE+ * ErrorBoundary + Suspense (per the entity-lib idiom — the exhaustive match+ * makes per-widget boundaries unnecessary).+ */+export function Compose(props: { view: ComposedView }): JSX.Element {+ return (+ <ErrorBoundary+ fallback={(err) => (+ <div class="border-edge-muted text-ink-extra-muted rounded border border-dashed p-3 text-xs">+ Failed to render view: {String(err)}+ </div>+ )}+ >+ <Suspense+ fallback={<div class="text-ink-muted p-3 text-sm">Loading…</div>}+ >+ <View title={props.view.title}>+ <For each={props.view.widgets}>+ {(widget) => <Render node={widget} />}+ </For>+ </View>+ </Suspense>+ </ErrorBoundary>+ );+}diff --git a/js/app/packages/app/component/dynamic-ui/schema.ts b/js/app/packages/app/component/dynamic-ui/schema.tsnew file mode 100644index 0000000000..723bc8a10a--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/schema.ts@@ -0,0 +1,183 @@+/**+ * Dynamic UI widget schema.+ *+ * This is the single source of truth for the `compose_view` contract: the+ * discriminated union below is both (a) what the renderer consumes and (b) the+ * shape that AI will eventually emit as tool-call arguments. Keep it serialisable+ * — every field must survive a JSON round-trip (no functions, no class instances).+ *+ * A `View` is a flex container of widgets. Layout is order-driven; nesting is+ * achieved with the `container` widget.+ *+ * The schemas below are the runtime source of truth; every exported type is+ * derived from its schema with `z.infer`.+ */++import type { Query } from '@app/component/next-soup/filters/filter-store/types';+import { EntityType } from '@core/types';+import { z } from 'zod';++/** A reference to a workspace entity (document, channel, task, PR, person, …). */+export const EntityRefSchema = z.object({+ id: z.string(),+ type: z.enum(Object.values(EntityType) as [EntityType, ...EntityType[]]),+});+export type EntityRef = z.infer<typeof EntityRefSchema>;++/**+ * A SoupView filter query. This lives in (and is owned by) the next-soup filter+ * store; re-deriving its full shape in zod is out of scope, so we validate it as+ * an opaque pass-through while keeping the precise `Query` type.+ */+export const QuerySchema = z.custom<Query>();++// ---------------------------------------------------------------------------+// Widgets+// ---------------------------------------------------------------------------++/** Static markdown — the narrative glue between data widgets. Supports the full+ * markdown feature set (headings, lists, bold/italic, links, blockquotes, …). */+export const MdWidgetSchema = z.object({+ type: z.literal('md'),+ markdown: z.string(),+});+export type MdWidget = z.infer<typeof MdWidgetSchema>;++/** A single labelled metric, optionally with a trend delta. */+export const StatWidgetSchema = z.object({+ type: z.literal('stat'),+ label: z.string(),+ value: z.union([z.string(), z.number()]),+ /** e.g. "PRs", "%", "ms" — rendered next to the value. */+ unit: z.string().optional(),+ /** Change vs a prior period. */+ delta: z+ .object({+ value: z.number(),+ direction: z.enum(['up', 'down', 'neutral']),+ /** e.g. "vs last week". */+ label: z.string().optional(),+ })+ .optional(),+});+export type StatWidget = z.infer<typeof StatWidgetSchema>;++/** A chronological sequence of events. Great for "what happened" answers. */+export const TimelineWidgetSchema = z.object({+ type: z.literal('timeline'),+ title: z.string().optional(),+ events: z.array(+ z.object({+ /** Human-readable timestamp, e.g. "9:32am" or "Yesterday". */+ time: z.string(),+ title: z.string(),+ description: z.string().optional(),+ /** Links the event to a workspace entity. */+ entity: EntityRefSchema.optional(),+ /** true = upcoming/future event, rendered gray; omitted/false = past, rendered accent. */+ future: z.boolean().optional(),+ })+ ),+});+export type TimelineWidget = z.infer<typeof TimelineWidgetSchema>;++/**+ * A list of workspace items. Two input modes:+ * - `query`: hand the list a filter and it fetches matching items itself.+ * - `items`: pre-populate with a fixed set of entity refs.+ * Reuses the existing SoupView engine (filtering, grouping, virtualization).+ */+export const ListWidgetSchema = z.object({+ type: z.literal('list'),+ title: z.string().optional(),+ source: z.discriminatedUnion('kind', [+ z.object({ kind: z.literal('query'), query: QuerySchema }),+ z.object({ kind: z.literal('items'), entities: z.array(EntityRefSchema) }),+ ]),+ /** Group rows by a facet. Maps onto SoupView's GroupByField. */+ groupBy: z.enum(['date', 'entity_type', 'project']).optional(),+ /** Cap the number of rows shown. */+ limit: z.number().optional(),+});+export type ListWidget = z.infer<typeof ListWidgetSchema>;++/** A rich preview card for a single entity (task, md doc, …) — the same rich+ * body shown on hover, rendered inline. */+export const CardWidgetSchema = z.object({+ type: z.literal('card'),+ entity: EntityRefSchema,+});+export type CardWidget = z.infer<typeof CardWidgetSchema>;++/** Render a single channel message with surrounding context. */+export const ChannelMessageWidgetSchema = z.object({+ type: z.literal('channelMessage'),+ /** The channel the message belongs to. */+ channelId: z.string(),+ /** The message to render. */+ messageId: z.string(),+});+export type ChannelMessageWidget = z.infer<typeof ChannelMessageWidgetSchema>;++/**+ * A nestable flex container. This is what makes real dashboards composable.+ *+ * `ContainerWidget` and `Widget` are mutually recursive, so their types are+ * declared explicitly (TS can't infer across the cycle) and the schemas are+ * annotated to match. A getter defers `WidgetSchema` resolution until parse time.+ */+export type ContainerWidget = {+ type: 'container';+ direction?: 'row' | 'col';+ /** Tailwind-ish gap step, 0–8. Defaults to 3. */+ gap?: number;+ wrap?: boolean;+ align?: 'start' | 'center' | 'end' | 'stretch';+ justify?: 'start' | 'center' | 'end' | 'between';+ title?: string;+ children: Widget[];+};++export const ContainerWidgetSchema: z.ZodType<ContainerWidget> = z.object({+ type: z.literal('container'),+ direction: z.enum(['row', 'col']).optional(),+ gap: z.number().optional(),+ wrap: z.boolean().optional(),+ align: z.enum(['start', 'center', 'end', 'stretch']).optional(),+ justify: z.enum(['start', 'center', 'end', 'between']).optional(),+ title: z.string().optional(),+ get children() {+ return z.array(WidgetSchema);+ },+});++export type Widget =+ | MdWidget+ | StatWidget+ | TimelineWidget+ | ListWidget+ | CardWidget+ | ChannelMessageWidget+ | ContainerWidget;++export const WidgetSchema: z.ZodType<Widget> = z.union([+ MdWidgetSchema,+ StatWidgetSchema,+ TimelineWidgetSchema,+ ListWidgetSchema,+ CardWidgetSchema,+ ChannelMessageWidgetSchema,+ ContainerWidgetSchema,+]);++export type WidgetType = Widget['type'];++/** Narrow a `Widget` to a specific variant by its `type`. */+export type WidgetOf<T extends WidgetType> = Extract<Widget, { type: T }>;++/** A top-level composed view: a flex column of widgets. */+export const ViewSchema = z.object({+ title: z.string().optional(),+ widgets: z.array(WidgetSchema),+});+export type View = z.infer<typeof ViewSchema>;diff --git a/js/app/packages/app/component/dynamic-ui/tokens.ts b/js/app/packages/app/component/dynamic-ui/tokens.tsnew file mode 100644index 0000000000..62f858fe36--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/tokens.ts@@ -0,0 +1,22 @@+/**+ * Shared design tokens for dynamic-ui widgets.+ *+ * Use these instead of hand-picking Tailwind classes so every widget matches the+ * app theme. The palette is "ink" (foreground) / "edge" (borders) / "surface"+ * (backgrounds) / "accent", per the existing component library.+ */++/** Foreground text colours. */+export const TEXT = {+ primary: 'text-ink',+ secondary: 'text-ink-muted',+ tertiary: 'text-ink-extra-muted',+ accent: 'text-accent',+} as const;++/** Borders + surfaces. */+export const SURFACE = {+ panel: 'bg-surface',+ border: 'border-edge',+ borderMuted: 'border-edge-muted',+} as const;diff --git a/js/app/packages/app/component/dynamic-ui/toolSchema.ts b/js/app/packages/app/component/dynamic-ui/toolSchema.tsnew file mode 100644index 0000000000..69307d5e99--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/toolSchema.ts@@ -0,0 +1,33 @@+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.+ */+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 (cards, lists, timelines, stats, 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.',+ '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 (`card`, `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;+}diff --git a/js/app/packages/app/component/dynamic-ui/widget.ts b/js/app/packages/app/component/dynamic-ui/widget.tsnew file mode 100644index 0000000000..ee1437f016--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/widget.ts@@ -0,0 +1,27 @@+import { Col, Row, View } from './core/Layout';+import { Compose, Render } from './render';+import { Card } from './widgets/Card';+import { ChannelMessage } from './widgets/ChannelMessage';+import { List } from './widgets/List';+import { Md } from './widgets/Md';+import { Stat } from './widgets/Stat';+import { Timeline } from './widgets/Timeline';++/**+ * The public dynamic-ui API: a namespace of composable components plus the two+ * renderers. Consumers either compose primitives directly (`<Widget.Stat …/>`)+ * or hand a schema node / view to `<Widget.Render>` / `<Widget.Compose>`.+ */+export const Widget = {+ Render,+ Compose,+ View,+ Row,+ Col,+ Md,+ Stat,+ Timeline,+ Card,+ ChannelMessage,+ List,+};diff --git a/js/app/packages/app/component/dynamic-ui/widgets/Card.tsx b/js/app/packages/app/component/dynamic-ui/widgets/Card.tsxnew file mode 100644index 0000000000..d141af95ec--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/widgets/Card.tsx@@ -0,0 +1,96 @@+import type { BlockName } from '@core/block';+import { DocumentPreviewContent } from '@core/component/DocumentPreview';+import { useItemPreviewData } from '@core/component/ItemPreview';+import { fileTypeToBlockName } from '@core/constant/allBlocks';+import type { ItemEntity } from '@queries/preview';+import { cn } from '@ui';+import { Suspense } from 'solid-js';+import type { EntityRef, WidgetOf } from '../schema';+import { SURFACE } from '../tokens';++/**+ * A rich preview card for a single entity — a task, an md document, or anything+ * else with a preview — by rendering the SAME rich body the list's hover card+ * shows, but+ * INLINE (always visible, not on hover) and inside a NORMAL border instead of+ * the floating hover-card's highlighted chrome.+ *+ * The hover card in {@link import('@core/component/ItemPreview').ItemPreview}+ * renders {@link import('@core/component/DocumentPreview').PopupPreview}, whose+ * outer shell bakes in a colored highlight border + drop shadow. Rather than+ * suppress that chrome with a flag, we COMPOSE: we render the extracted+ * {@link DocumentPreviewContent} body directly and wrap it in our own ordinary+ * card border.+ *+ * Picking `documentInfo.type` is the crux of making BOTH a task and an md doc+ * look like their hover card. `DocumentPreviewContent` gates its body branches+ * (the task status/priority/assignee block, the image cover strip, the+ * copy-branch button) on `documentInfo.type` LITERALLY — it does NOT use the+ * block type it re-resolves internally for those. So a static default like+ * `'document'` would render an md doc fine but would never show a task's task+ * body. We therefore derive the block name from the FETCHED item exactly the+ * way the hover card does — `fileTypeToBlockName(targetType() ?? itemType)`+ * (see ItemPreviewInner's `blockName()`), which resolves the document subType+ * `task` to the `task` block and a plain md doc to `md`. That makes each entity+ * render identically to its hover card. Until the item resolves we fall back to+ * the caller's EntityRef type; the body re-renders once it loads.+ */++export type CardProps = Omit<WidgetOf<'card'>, 'type'>;++/** Map a schema EntityType onto the ItemType string the preview query expects. */+function toItemType(type: EntityRef['type']): string {+ switch (type) {+ case 'email_thread':+ return 'email';+ case 'foreign_entity':+ return 'foreign';+ default:+ return type;+ }+}++export function Card(props: CardProps) {+ const itemEntity = () =>+ ({+ id: props.entity.id,+ type: toItemType(props.entity.type),+ }) as ItemEntity;++ const { item, targetType } = useItemPreviewData(itemEntity);++ // Mirror ItemPreviewInner's `blockName()`: resolve the real block (task / md+ // / …) from the fetched item so the body branches in DocumentPreviewContent+ // match the hover card. Falls back to the caller's EntityRef type pre-load.+ const blockName = (): BlockName => {+ const i = item();+ const resolved =+ !i.loading && i.access === 'access'+ ? fileTypeToBlockName(targetType() ?? i.type)+ : fileTypeToBlockName(props.entity.type);+ return (resolved || props.entity.type) as BlockName;+ };++ const documentInfo = () => ({+ id: props.entity.id,+ type: blockName(),+ params: {},+ isOpenable: true,+ });++ return (+ // DocumentPreviewContent fetches preview + property data; guard with our own+ // boundary so a suspending fetch can't bubble past this widget.+ <Suspense>+ <div+ class={cn(+ 'w-full max-w-sm overflow-hidden rounded-lg border text-ink',+ SURFACE.borderMuted,+ SURFACE.panel+ )}+ >+ <DocumentPreviewContent documentInfo={documentInfo()} />+ </div>+ </Suspense>+ );+}diff --git a/js/app/packages/app/component/dynamic-ui/widgets/ChannelMessage.tsx b/js/app/packages/app/component/dynamic-ui/widgets/ChannelMessage.tsxnew file mode 100644index 0000000000..43eaac8e0b--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/widgets/ChannelMessage.tsx@@ -0,0 +1,10 @@+import { ReadonlyThread } from '@channel/StandaloneThread';+import type { WidgetOf } from '../schema';++export type ChannelMessageProps = Omit<WidgetOf<'channelMessage'>, 'type'>;++export function ChannelMessage(props: ChannelMessageProps) {+ return (+ <ReadonlyThread channelId={props.channelId} messageId={props.messageId} />+ );+}diff --git a/js/app/packages/app/component/dynamic-ui/widgets/List.tsx b/js/app/packages/app/component/dynamic-ui/widgets/List.tsxnew file mode 100644index 0000000000..b1ef8bc33a--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/widgets/List.tsx@@ -0,0 +1,205 @@+import {+ compileToAst,+ defineQueryFilters,+ type Query,+ queryStateFrom,+} from '@app/component/next-soup/filters/filter-store';+import type { FieldFilters } from '@app/component/next-soup/filters/filter-store/types';+import { CollapsibleList } from '@entity/components/CollapsibleList';+import { ListEntity, ListLayoutProvider } from '@entity/composed/ListEntity';+import type { EntityData } from '@entity/types/entity';+import type { WithNotification } from '@entity/types/notification';+import type { GroupByField } from '@queries/soup/grouped/types';+import {+ type SoupAstItemsQueryArgs,+ useSoupAstItemsQuery,+} from '@queries/soup/items';+import { cn } from '@ui';+import { createMemo, Show, Suspense } from 'solid-js';+import type { EntityRef, WidgetOf } from '../schema';+import { SURFACE, TEXT } from '../tokens';++/**+ * A list of workspace items, styled to match SoupView's grouped "card view":+ * a bold group header above a rounded card of rows, with a "Show N More" footer.+ *+ * ── Real unified-list rows ───────────────────────────────────────────────────+ * Rows render via {@link ListEntity} — the very same component the soup list uses+ * — so each row shows icon + title + meta + timestamp and, for TASKS, the live+ * status / priority / assignee pills (`Entity.Properties` inside the wide layout).+ *+ * `ListEntity` takes a full `EntityData` (not a bare `{ id, type }` ref) and the+ * task pills read `entity.properties`. Both come from the soup item query: we+ * compile the widget's source into a soup AST and let `useSoupAstItemsQuery`+ * return ready-to-render `EntityData[]` (properties pre-attached). The only+ * provider `ListEntity` needs for the wide layout is `ListLayoutProvider`+ * (width detection); `Entity.Properties` brings its own `PropertiesProvider`,+ * and the split-panel / soup-view contexts are read optionally so they degrade+ * gracefully when absent. We render inside the gallery's split-panel anyway.+ *+ * - `items` mode: resolve the supplied refs → EntityData via an id-filtered AST.+ * - `query` mode: drive the same query straight from `source.query`.+ */++export type ListProps = Omit<WidgetOf<'list'>, 'type'>;++/** The `FieldFilters` keys whose value is a `string[]` id list. */+type IdFieldName = {+ [K in keyof FieldFilters]: FieldFilters[K] extends string[] | undefined+ ? K+ : never;+}[keyof FieldFilters];++/** Map a schema `EntityRef.type` onto the soup `FieldFilters` id field. */+const ID_FIELD_BY_TYPE: Partial<Record<EntityRef['type'], IdFieldName>> = {+ document: 'documentId',+ chat: 'chatId',+ channel: 'channelId',+ project: 'folderId',+ email_thread: 'threadId',+ call: 'callId',+ foreign_entity: 'foreignEntityRecordId',+ crm_company: 'crmCompanyId',+ // user / team / crm_contact / static_file have no soup item filter — skipped.+};++/** Build a soup `Query` that fetches exactly the given refs by id. */+function refsToQuery(refs: EntityRef[]): Query {+ const include: FieldFilters = {};+ for (const ref of refs) {+ const field = ID_FIELD_BY_TYPE[ref.type];+ if (!field) continue;+ include[field] ??= [];+ (include[field] as string[]).push(ref.id);+ }+ return { include };+}++/** Compile a widget `Query` into the soup AST body the items query expects. */+function compileQuery(query: Query): SoupAstItemsQueryArgs['body'] {+ // `defineQueryFilters` NIL-fills the entity targets the query doesn't+ // reference, so soup doesn't fan out and fetch every document/channel/etc.+ return compileToAst(queryStateFrom(defineQueryFilters(query)));+}++const GROUP_BY_BY_NAME: Record<+ NonNullable<ListProps['groupBy']>,+ GroupByField+> = {+ date: { type: 'date' },+ entity_type: { type: 'entity_type' },+ project: { type: 'project' },+};++/**+ * One row: a real `ListEntity`, rendered flush the way SoupView / the unified+ * list do. The row's own `Entity.Root` supplies its height, the rounded inset+ * `bg-hover/30` highlight pill (`w-[calc(100%-0.5rem)] mx-1`), and hover state —+ * so it must sit in a flush container, NOT a bordered/`divide-y` card, or the+ * pill ends up boxed in by per-row dividers. `hideCheckbox` drops the+ * multi-select checkbox (read-only embed), leaving just the icon / unread dot.+ */+function Row(props: { entity: EntityData }) {+ return (+ <ListEntity+ entity={props.entity as WithNotification<EntityData>}+ hideCheckbox+ />+ );+}++function Rows(props: {+ source: ListProps['source'];+ limit?: number;+ groupBy?: ListProps['groupBy'];+}) {+ const query = createMemo<Query>(() => {+ const src = props.source;+ return src.kind === 'items' ? refsToQuery(src.entities) : src.query;+ });++ // `items` mode with zero resolvable refs would otherwise NIL-fill everything+ // and return nothing — which is the correct "No items." outcome anyway.+ // `groupBy` orders the returned entities by the requested facet (the grouped+ // select flattens groups into `data.entities` in group order).+ const itemsQuery = useSoupAstItemsQuery(() => ({+ params: { limit: 200 },+ body: compileQuery(query()),+ groupBy: props.groupBy ? GROUP_BY_BY_NAME[props.groupBy] : undefined,+ }));++ const entities = createMemo<EntityData[]>(() => {+ const all = itemsQuery.data?.entities ?? [];+ return props.limit != null ? all.slice(0, props.limit) : all;+ });++ return (+ <Show+ when={entities().length > 0}+ fallback={+ <div class={cn('px-3 py-6 text-center text-sm', TEXT.tertiary)}>+ No items.+ </div>+ }+ >+ <CollapsibleList+ items={entities()}+ visibleCount={3}+ togglePosition="bottom"+ >+ {(entity) => <Row entity={entity} />}+ </CollapsibleList>+ </Show>+ );+}++export function List(props: ListProps) {+ return (+ <ListLayoutProvider ref={() => undefined}>+ <div class="flex w-full min-w-0 flex-col gap-2">+ {/* Group header, soup-style: bold title above the card. */}+ <Show when={props.title}>+ {(title) => (+ <div+ class={cn(+ 'flex items-center gap-2 px-1 text-sm font-semibold',+ TEXT.primary+ )}+ >+ {title()}+ </div>+ )}+ </Show>++ {/*+ * Flush row container (mirrors SoupView's unified list): no+ * per-row dividers/borders. Each `ListEntity` brings its own+ * rounded inset highlight pill (`mx-1`), so the card just needs a+ * hair of vertical padding for the pills to breathe — adding+ * `divide-y`/per-row borders here would box those highlights in.+ */}+ <div+ class={cn(+ 'overflow-hidden rounded-lg border py-1',+ SURFACE.borderMuted+ )}+ >+ {/* Soup fetches suspend; guard so it can't blank the surrounding view. */}+ <Suspense+ fallback={+ <div class={cn('px-3 py-6 text-center text-sm', TEXT.tertiary)}>+ Loading…+ </div>+ }+ >+ <Rows+ source={props.source}+ limit={props.limit}+ groupBy={props.groupBy}+ />+ </Suspense>+ </div>+ </div>+ </ListLayoutProvider>+ );+}diff --git a/js/app/packages/app/component/dynamic-ui/widgets/Md.tsx b/js/app/packages/app/component/dynamic-ui/widgets/Md.tsxnew file mode 100644index 0000000000..fff243dd90--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/widgets/Md.tsx@@ -0,0 +1,20 @@+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { aiChatTheme } from '@core/component/LexicalMarkdown/theme';+import type { WidgetOf } from '../schema';++export type MdProps = Omit<WidgetOf<'md'>, 'type'>;++/**+ * Renders static markdown via the app's Lexical static renderer. For best+ * results (and to avoid a per-instance editor), render inside a+ * <StaticMarkdownContext> — the gallery/ComposeView provides one.+ */+export function Md(props: MdProps) {+ return (+ <StaticMarkdown+ markdown={props.markdown}+ theme={aiChatTheme}+ target="internal"+ />+ );+}diff --git a/js/app/packages/app/component/dynamic-ui/widgets/Stat.tsx b/js/app/packages/app/component/dynamic-ui/widgets/Stat.tsxnew file mode 100644index 0000000000..723d6c0e81--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/widgets/Stat.tsx@@ -0,0 +1,44 @@+import { cn } from '@ui';+import { Show } from 'solid-js';+import type { WidgetOf } from '../schema';+import { TEXT } from '../tokens';++export type StatProps = Omit<WidgetOf<'stat'>, 'type'>;++/** Arrow glyph for a delta direction. */+const DELTA_GLYPH: Record<'up' | 'down' | 'neutral', string> = {+ up: '▲',+ down: '▼',+ neutral: '—',+};++/** A compact stat card: label, prominent value (+unit), optional delta. */+export function Stat(props: StatProps) {+ return (+ <div class="w-full gap-1 rounded-lg border border-edge-muted bg-surface p-3">+ <span class="text-ink-extra-muted text-xxs font-medium uppercase tracking-wide">+ {props.label}+ </span>+ <div class="flex items-baseline gap-1">+ <span class={cn('text-2xl font-semibold leading-none', TEXT.primary)}>+ {props.value}+ </span>+ <Show when={props.unit}>+ <span class="text-ink-muted text-sm">{props.unit}</span>+ </Show>+ </div>++ <Show when={props.delta}>+ {(delta) => (+ <span class={cn('flex items-center gap-1 text-xs', TEXT.accent)}>+ <span aria-hidden="true">{DELTA_GLYPH[delta().direction]}</span>+ <span class="font-medium">{delta().value}</span>+ <Show when={delta().label}>+ <span class="text-ink-extra-muted">{delta().label}</span>+ </Show>+ </span>+ )}+ </Show>+ </div>+ );+}diff --git a/js/app/packages/app/component/dynamic-ui/widgets/Timeline.tsx b/js/app/packages/app/component/dynamic-ui/widgets/Timeline.tsxnew file mode 100644index 0000000000..fe40b93693--- /dev/null+++ b/js/app/packages/app/component/dynamic-ui/widgets/Timeline.tsx@@ -0,0 +1,168 @@+import { ItemPreview } from '@core/component/ItemPreview';+import type { ItemType } from '@service-storage/client';+import { cn } from '@ui';+import { For, Show } from 'solid-js';+import type { EntityRef, WidgetOf } from '../schema';+import { TEXT } from '../tokens';++export type TimelineProps = Omit<WidgetOf<'timeline'>, 'type'>;++type TimelineEvent = TimelineProps['events'][number];++/** Map a schema EntityType onto the ItemType string ItemPreview expects. */+function toItemType(type: EntityRef['type']): string {+ switch (type) {+ case 'email_thread':+ return 'email';+ case 'foreign_entity':+ return 'foreign';+ default:+ return type;+ }+}++/**+ * Left gutter for a single timeline item: a dot offset down to line up with the+ * item's first text line, with two in-flow connector segments around it so the+ * rail reads as one continuous dot-to-dot line with no gaps.+ *+ * The top connector both pushes the dot down to the time text's baseline and+ * connects upward to the previous row's line (drawn only when not the first+ * item; a transparent spacer of the same height otherwise). The bottom connector+ * fills the remaining row height down to the next dot, suppressed on the last+ * item. Colours are driven by each row's own `future` flag: past events use the+ * accent colour, future events use muted edge.+ *+ * The column stretches to the full item height (via the parent flex row), so the+ * bottom connector reaches through the content's bottom padding to the next dot.+ */+/**+ * Each connecting segment is coloured by the dot it leads INTO (the lower dot):+ * a segment ending at a future dot is gray, so only segments between two past+ * events are accent. The top connector leads into THIS dot (own `future`); the+ * bottom connector leads into the NEXT dot (`nextFuture`).+ *+ * Lines are filled 1px `bg` spans, not `border-l` — a border-left on a `w-0` box+ * doesn't paint its full height, which left a gap above each dot.+ */+function Rail(props: {+ future?: boolean;+ nextFuture?: boolean;+ isFirst: boolean;+ isLast: boolean;+}) {+ const lineColor = (gray?: boolean) => (gray ? 'bg-edge-muted' : 'bg-accent');+ return (+ <div+ aria-hidden="true"+ class="flex w-3 shrink-0 flex-col items-center self-stretch"+ >+ {/* Top connector: offsets the dot down to the first text line and+ connects up from the previous dot (line only when not the first). */}+ <span class={cn('h-1 w-px', !props.isFirst && lineColor(props.future))} />+ <span+ class={cn(+ 'size-[9px] shrink-0 rounded-full',+ props.future ? 'bg-edge' : 'bg-accent'+ )}+ />+ {/* Bottom connector: runs down to the next dot, coloured by that dot. */}+ <Show when={!props.isLast}>+ <span class={cn('w-px flex-1', lineColor(props.nextFuture))} />+ </Show>+ </div>+ );+}++/**+ * One timeline row: the {@link Rail} gutter plus a content column. Spacing+ * between items lives ONLY here, as bottom padding on the content column (omitted+ * on the last item). Because the flex row stretches the rail to match the padded+ * content height, the rail line extends through that padding down to the next dot.+ */+function TimeLineItem(props: {+ event: TimelineEvent;+ nextFuture?: boolean;+ isFirst: boolean;+ isLast: boolean;+}) {+ return (+ <li class="flex gap-3">+ <Rail+ future={props.event.future}+ nextFuture={props.nextFuture}+ isFirst={props.isFirst}+ isLast={props.isLast}+ />++ <div class={cn('flex min-w-0 flex-col', props.isLast ? '' : 'pb-4')}>+ <span class={cn('text-xxs', TEXT.tertiary)}>{props.event.time}</span>+ <span class={cn('text-sm font-medium', TEXT.primary)}>+ {props.event.title}+ </span>+ <Show when={props.event.description}>+ <span class={cn('text-xs', TEXT.secondary)}>+ {props.event.description}+ </span>+ </Show>++ {/* Real, clickable + hoverable entity mention — a compact ItemPreview+ (icon + resolved title + hover card). The rich `card` widget is too+ large for an inline timeline mention, so we render ItemPreview+ directly instead. */}+ <Show when={props.event.entity}>+ {(entity) => (+ <div class="mt-0.5 w-fit max-w-full">+ <ItemPreview+ id={entity().id}+ type={toItemType(entity().type) as ItemType}+ class="ring-0"+ />+ </div>+ )}+ </Show>+ </div>+ </li>+ );+}++/**+ * A vertical timeline of events. Each event sits on a left-hand rail; the rails+ * touch with zero gap so they form one continuous vertical line down the list.+ */+export function Timeline(props: TimelineProps) {+ const events = () => props.events;++ return (+ <div class="flex w-full flex-col gap-2">+ <Show when={props.title}>+ <span+ class={cn(+ 'text-xxs font-medium uppercase tracking-wide',+ TEXT.tertiary+ )}+ >+ {props.title}+ </span>+ </Show>++ <Show+ when={events().length > 0}+ fallback={<span class={cn('text-xs', TEXT.secondary)}>No events.</span>}+ >+ <ol class="flex w-full flex-col gap-0">+ <For each={events()}>+ {(event, index) => (+ <TimeLineItem+ event={event}+ nextFuture={events()[index() + 1]?.future}+ isFirst={index() === 0}+ isLast={index() === events().length - 1}+ />+ )}+ </For>+ </ol>+ </Show>+ </div>+ );+}diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsxindex 8766a6f03a..b0a47ef3e4 100644--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx@@ -441,6 +441,11 @@ if (LOCAL_ONLY) {'user-icon',lazy(() => import('@core/internal/UserIconDemo')));++ registerComponent(+ 'dynamic-ui',+ lazy(() => import('@app/component/dynamic-ui/Gallery'))+ );}if (DEV_MODE_ENV) {diff --git a/js/app/packages/core/component/AI/component/input/buildRequest.ts b/js/app/packages/core/component/AI/component/input/buildRequest.tsindex 19e5918ecf..5826124d70 100644--- a/js/app/packages/core/component/AI/component/input/buildRequest.ts+++ b/js/app/packages/core/component/AI/component/input/buildRequest.ts@@ -1,3 +1,4 @@+import { displayResultsInstructions } from '@app/component/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';@@ -30,13 +31,19 @@ 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();+ 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: additionalInstructions(),+ additional_instructions: merged,});if (isPaymentError(response)) {diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessageParts.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessageParts.tsxindex 473aaaf5bf..2d08b4e0a2 100644--- a/js/app/packages/core/component/AI/component/message/AssistantMessageParts.tsx+++ b/js/app/packages/core/component/AI/component/message/AssistantMessageParts.tsx@@ -50,8 +50,21 @@ type RenderItem =key: string;part: AssistantMessagePart;index: number;+ }+ | {+ type: 'standaloneTool';+ key: string;+ part: Extract<AssistantMessagePart, { type: 'toolCall' }>;+ index: number;};+/**+ * Tools rendered OUTSIDE the standard grouped tool chrome (no `Tool.Group`+ * background) — they own their full presentation. The dashboard renders as a+ * full-bleed view, not a tool row.+ */+const STANDALONE_TOOLS: ReadonlySet<string> = new Set(['DisplayResults']);+export function AssistantMessageParts(props: {parts: AssistantMessagePart[];message: ChatMessageWithAttachments;@@ -137,6 +150,20 @@ export function AssistantMessageParts(props: {const part = keyedParts().partsByKey.get(key);if (!part) return;+ // Standalone tools (e.g. the dashboard) break out of the tool group and+ // render full-bleed on their own.+ if (part.type === 'toolCall' && STANDALONE_TOOLS.has(part.name)) {+ flushToolGroup();+ orderedKeys.push(key);+ itemByKey.set(key, {+ type: 'standaloneTool',+ key,+ part,+ index,+ });+ return;+ }+if (part.type === 'toolCall' || part.type === 'mcpToolCall') {pendingToolEntries.push({ key, part, index });return;@@ -244,6 +271,31 @@ export function AssistantMessageParts(props: {return <Tool.Group>{entries()}</Tool.Group>;}+ /** Renders a standalone tool (e.g. the dashboard) with no group chrome. */+ function StandaloneToolView(props: {+ item: Accessor<Extract<RenderItem, { type: 'standaloneTool' }>>;+ }) {+ const part = () => props.item().part;+ return (+ <RenderTool+ tool_id={part().id}+ chat_id={chat.chatId()}+ json={part().json}+ name={part().name}+ response={responseById().get(part().id)}+ message_id={outer.message.id}+ part_index={props.item().index}+ isComplete={isCompleteSelector(part().id)}+ renderContext={{+ renderContext: {+ isStreaming: outer.isStreaming,+ grouped: false,+ },+ }}+ />+ );+ }+function PartView(props: {item: Accessor<Extract<RenderItem, { type: 'part' }>>;}) {@@ -304,6 +356,15 @@ export function AssistantMessageParts(props: {item={props.item as Accessor<Extract<RenderItem, { type: 'part' }>>}/></Match>+ <Match when={type() === 'standaloneTool'}>+ <StandaloneToolView+ item={+ props.item as Accessor<+ Extract<RenderItem, { type: 'standaloneTool' }>+ >+ }+ />+ </Match></Switch>);}diff --git a/js/app/packages/core/component/AI/component/tool/DisplayResults.tsx b/js/app/packages/core/component/AI/component/tool/DisplayResults.tsxnew file mode 100644index 0000000000..cef09967a1--- /dev/null+++ b/js/app/packages/core/component/AI/component/tool/DisplayResults.tsx@@ -0,0 +1,19 @@+import { DashboardToolView } from '@app/component/dynamic-ui/DashboardToolView.lazy';+import { createToolRenderer } from './ToolRenderer';++/**+ * `displayResults` renders the AI-composed view from the tool CALL arguments+ * (`ctx.tool.data.view`) using the dynamic-ui component library. The tool+ * RESPONSE is intentionally not rendered.+ *+ * `DashboardToolView` is imported from `@app` already wrapped in `lazy()` — the+ * dynamic-ui tree is entity-heavy and lives in a module-init cycle, so the lazy+ * boundary (owned by `@app`, like the split-layout component registry) keeps it+ * out of the eager startup graph. See `DashboardToolView.lazy.ts`.+ */+const handler = createToolRenderer({+ name: 'DisplayResults',+ render: (ctx) => <DashboardToolView view={ctx.tool.data.view} />,+});++export const displayResultsHandler = handler;diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsxindex 873a0fc000..b019ba4478 100644--- a/js/app/packages/core/component/AI/component/tool/handler.tsx+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx@@ -6,6 +6,7 @@ import {import { Dynamic } from 'solid-js/web';import { bashCodeExecutionHandler } from './BashCodeExecution';import { createDocumentHandler } from './CreateDocument';+import { displayResultsHandler } from './DisplayResults';import { getThreadHandler } from './GetThread';import { listCallRecordsHandler } from './ListCallRecords';import { listEntitiesHandler } from './ListEntities';@@ -55,6 +56,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {MarkNotificationsDone: markNotificationsDoneHandler,MarkNotificationsSeen: markNotificationsSeenHandler,BashCodeExecution: bashCodeExecutionHandler,+ DisplayResults: displayResultsHandler,ContentSearch: contentSearchHandler,CreateDocument: createDocumentHandler,GetThread: getThreadHandler,diff --git a/js/app/packages/core/component/DocumentPreview.tsx b/js/app/packages/core/component/DocumentPreview.tsxindex a133a6000b..5b5c2a797b 100644--- a/js/app/packages/core/component/DocumentPreview.tsx+++ b/js/app/packages/core/component/DocumentPreview.tsx@@ -452,9 +452,13 @@ function PreviewPropertyPill(props: {);}-export function PopupPreview(props: {- mouseEnter: () => void;- mouseLeave: () => void;+/**+ * Props for the reusable document-preview body. These are everything+ * {@link PopupPreview} needs EXCEPT the floating-hover-card concerns+ * (`mouseEnter` / `mouseLeave`), which only matter while the preview lives+ * inside a floating card.+ */+export type DocumentPreviewContentProps = {delete?: () => void;collapseInfo?: {isCollapsable: boolean;@@ -478,7 +482,20 @@ export function PopupPreview(props: {characterCount?: number;};useFallbackData?: boolean;-}) {+};++/**+ * The inner preview body shared by every document/task preview: the header+ * (icon + filename + action buttons), the task body+ * ({@link TaskPropertiesPreview}), the image cover strip, the owner/updated+ * footer, and the loading / no_access / does_not_exist states.+ *+ * It renders NO floating/highlighted chrome — no colored highlight border, no+ * shadow, no rounded floating shell. Wrap it in your own container to control+ * the surrounding appearance. {@link PopupPreview} wraps it in the floating+ * hover-card shell; other callers can wrap it in a normal border.+ */+export function DocumentPreviewContent(props: DocumentPreviewContentProps) {// Hooksconst navigate = useNavigate();@@ -748,196 +765,214 @@ export function PopupPreview(props: {};return (- <div- class="select-none overflow-hidden w-80 text-ink"- onMouseEnter={props.mouseEnter}- onMouseLeave={props.mouseLeave}- >- <Surface active depth={3} class="rounded-xl shadow-lg shadow-drop-shadow">- <Switch>- {/* Loading state */}- <Match when={item().loading}>- <div class="p-3 flex items-center justify-center">- <Loading />- </div>- </Match>-- {/* Accessible preview */}- <Match when={matches(item(), isAccessiblePreviewItem)}>- {(accessibleItem) => {- const accessories = () =>- mentionsAccessories(- props.documentInfo.type,- props.documentInfo.params- );- const messageContext = () => {- const item = accessibleItem();- return isChannelPreviewItem(item)- ? item.messageContext- : undefined;- };-- return (- <div class="w-full flex flex-col">- {/* Header: icon + filename + action buttons */}- <div class="flex items-center justify-between gap-2 p-2">- <div class="flex items-center gap-2 min-w-0">- <ItemEntityIcon size="sm" />- <div class="text-sm font-semibold select-text min-w-0">- <Show when={accessories()}>- {(acc) => (- <div class="text-[0.8em] text-ink-muted mt-1 select-none">- {`${acc().note} `}- {getMentionsIcon(acc().icon)}- </div>- )}- </Show>- </div>- </div>- <div class="flex shrink-0">{renderActionButtons()}</div>- </div>-- <div class="line-clamp-2 wrap-break-word px-2 mb-2">- {props.documentInfo.name || accessibleItem().name}+ <Switch>+ {/* Loading state */}+ <Match when={item().loading}>+ <div class="p-3 flex items-center justify-center">+ <Loading />+ </div>+ </Match>++ {/* Accessible preview */}+ <Match when={matches(item(), isAccessiblePreviewItem)}>+ {(accessibleItem) => {+ const accessories = () =>+ mentionsAccessories(+ props.documentInfo.type,+ props.documentInfo.params+ );+ const messageContext = () => {+ const item = accessibleItem();+ return isChannelPreviewItem(item) ? item.messageContext : undefined;+ };++ return (+ <div class="w-full flex flex-col">+ {/* Header: icon + filename + action buttons */}+ <div class="flex items-center justify-between gap-2 p-2">+ <div class="flex items-center gap-2 min-w-0">+ <ItemEntityIcon size="sm" />+ <div class="text-sm font-semibold select-text min-w-0">+ <Show when={accessories()}>+ {(acc) => (+ <div class="text-[0.8em] text-ink-muted mt-1 select-none">+ {`${acc().note} `}+ {getMentionsIcon(acc().icon)}+ </div>+ )}+ </Show></div>+ </div>+ <div class="flex shrink-0">{renderActionButtons()}</div>+ </div>++ <div class="line-clamp-2 wrap-break-word px-2 mb-2">+ {props.documentInfo.name || accessibleItem().name}+ </div>++ {/* Task properties: status, priority, assignees */}+ <Show when={props.documentInfo.type === 'task'}>+ <Suspense fallback={<div class="w-full bg-active h-4 m-2" />}>+ <TaskPropertiesPreview taskId={props.documentInfo.id} />+ </Suspense>+ </Show>- {/* Task properties: status, priority, assignees */}- <Show when={props.documentInfo.type === 'task'}>- <Suspense- fallback={<div class="w-full bg-active h-4 m-2" />}- >- <TaskPropertiesPreview taskId={props.documentInfo.id} />- </Suspense>- </Show>+ {/* Visual preview for images */}+ <Show when={props.documentInfo.type === 'image'}>+ <ImageCoverStrip+ documentId={accessibleItem().id}+ fileType={accessibleItem().fileType}+ class="shrink-0 h-32"+ />+ </Show>- {/* Visual preview for images */}- <Show when={props.documentInfo.type === 'image'}>- <ImageCoverStrip- documentId={accessibleItem().id}- fileType={accessibleItem().fileType}- class="shrink-0 h-32"- />+ {/* Footer: message context + owner/timestamp */}+ <Show+ when={+ messageContext() ||+ accessibleItem().owner ||+ accessibleItem().updatedAt ||+ props.snapshotInfo+ }+ >+ <div class="p-2 border-t border-edge-muted">+ <Show when={messageContext()}>+ {(context) => (+ <div class="mb-2 text-sm text-ink-muted border-l-2 border-edge pl-3 py-1">+ <div class="line-clamp-3 wrap-break-word">+ <StaticMarkdown+ markdown={context().content}+ theme={channelTheme}+ target="internal"+ />+ </div>+ </div>+ )}</Show>- {/* Footer: message context + owner/timestamp */}- <Show- when={- messageContext() ||- accessibleItem().owner ||- accessibleItem().updatedAt ||- props.snapshotInfo- }- >- <div class="p-2 border-t border-edge-muted">- <Show when={messageContext()}>- {(context) => (- <div class="mb-2 text-sm text-ink-muted border-l-2 border-edge pl-3 py-1">- <div class="line-clamp-3 wrap-break-word">- <StaticMarkdown- markdown={context().content}- theme={channelTheme}- target="internal"- />- </div>- </div>- )}- </Show>-- <div class="flex justify-between items-center text-sm font-medium">- <Show- when={messageContext()}- fallback={- <Show when={accessibleItem().owner}>- {(owner) => <UserInfo userId={owner()} />}- </Show>- }- >- {(context) => (- <UserInfo userId={context().sender_id} />- )}+ <div class="flex justify-between items-center text-sm font-medium">+ <Show+ when={messageContext()}+ fallback={+ <Show when={accessibleItem().owner}>+ {(owner) => <UserInfo userId={owner()} />}</Show>-- <Show- when={messageContext()}- fallback={- <Show when={accessibleItem().updatedAt}>- {(time) => (- <MetadataInfo icon={ClockIcon} align="right">- <span class="text-xxs font-mono uppercase">- {formatDate(time())}- </span>- </MetadataInfo>- )}- </Show>- }- >- {(context) => (+ }+ >+ {(context) => <UserInfo userId={context().sender_id} />}+ </Show>++ <Show+ when={messageContext()}+ fallback={+ <Show when={accessibleItem().updatedAt}>+ {(time) => (<MetadataInfo icon={ClockIcon} align="right">- {formatDate(context().created_at)}+ <span class="text-xxs font-mono uppercase">+ {formatDate(time())}+ </span></MetadataInfo>)}</Show>- </div>+ }+ >+ {(context) => (+ <MetadataInfo icon={ClockIcon} align="right">+ {formatDate(context().created_at)}+ </MetadataInfo>+ )}+ </Show>+ </div>- <Show when={props.snapshotInfo}>- {(snapshot) => (- <div class="mt-2 pt-2 border-t border-edge">- <div class="flex items-center gap-1.5 text-ink-muted">- <ClockIcon class="size-3" />- <span class="text-xxs font-medium font-mono uppercase">- Snapshot from{' '}- {formatDate(new Date(snapshot().date), {- showTime: true,- })}- </span>- </div>- </div>- )}- </Show>- </div>+ <Show when={props.snapshotInfo}>+ {(snapshot) => (+ <div class="mt-2 pt-2 border-t border-edge">+ <div class="flex items-center gap-1.5 text-ink-muted">+ <ClockIcon class="size-3" />+ <span class="text-xxs font-medium font-mono uppercase">+ Snapshot from{' '}+ {formatDate(new Date(snapshot().date), {+ showTime: true,+ })}+ </span>+ </div>+ </div>+ )}</Show></div>- );- }}- </Match>+ </Show>+ </div>+ );+ }}+ </Match>- {/* No access / does not exist errors */}- <Match when={matches(item(), isPreviewItemNoAccess)}>- {(noAccessItem) => (- <Show- when={- noAccessItem().access === 'does_not_exist' &&- props.useFallbackData &&- props.documentInfo.name- }- fallback={- <div class="text-sm p-4">- {noAccessItem().access === 'no_access' ? (- <Unauthorized />- ) : (- <NotFound />- )}- </div>- }- >- <div class="w-full flex flex-col">- <div class="flex items-center justify-between gap-2 px-3 pt-3 pb-2">- <div class="flex items-center gap-2 min-w-0">- <EntityIcon- targetType={props.documentInfo.type}- size="sm"- />- </div>- <div class="flex shrink-0">{renderActionButtons()}</div>- </div>- <div class="line-clamp-2 wrap-break-word px-2 mb-2">- {props.documentInfo.name}- </div>+ {/* No access / does not exist errors */}+ <Match when={matches(item(), isPreviewItemNoAccess)}>+ {(noAccessItem) => (+ <Show+ when={+ noAccessItem().access === 'does_not_exist' &&+ props.useFallbackData &&+ props.documentInfo.name+ }+ fallback={+ <div class="text-sm p-4">+ {noAccessItem().access === 'no_access' ? (+ <Unauthorized />+ ) : (+ <NotFound />+ )}+ </div>+ }+ >+ <div class="w-full flex flex-col">+ <div class="flex items-center justify-between gap-2 px-3 pt-3 pb-2">+ <div class="flex items-center gap-2 min-w-0">+ <EntityIcon targetType={props.documentInfo.type} size="sm" /></div>- </Show>- )}- </Match>- </Switch>+ <div class="flex shrink-0">{renderActionButtons()}</div>+ </div>+ <div class="line-clamp-2 wrap-break-word px-2 mb-2">+ {props.documentInfo.name}+ </div>+ </div>+ </Show>+ )}+ </Match>+ </Switch>+ );+}++/**+ * Floating hover-card preview for document references. This is the shell used by+ * {@link import('./ItemPreview').ItemPreview} hover cards: a fixed-width,+ * floating, rounded surface with a highlighted (colored) border and drop+ * shadow, plus mouse-enter/leave handling to keep the card alive while hovered.+ *+ * The reusable body lives in {@link DocumentPreviewContent}; this component only+ * adds the floating/highlight chrome around it.+ */+export function PopupPreview(+ props: DocumentPreviewContentProps & {+ mouseEnter: () => void;+ mouseLeave: () => void;+ }+) {+ return (+ <div+ class="select-none w-80 text-ink"+ onMouseEnter={props.mouseEnter}+ onMouseLeave={props.mouseLeave}+ >+ <Surface active depth={3} class="rounded-xl shadow-lg shadow-drop-shadow">+ <DocumentPreviewContent+ delete={props.delete}+ collapseInfo={props.collapseInfo}+ documentInfo={props.documentInfo}+ previewInfo={props.previewInfo}+ snapshotInfo={props.snapshotInfo}+ useFallbackData={props.useFallbackData}+ /></Surface></div>);diff --git a/js/app/packages/entity/src/composed/ListEntity.tsx b/js/app/packages/entity/src/composed/ListEntity.tsxindex 37a769e075..04462c3512 100644--- a/js/app/packages/entity/src/composed/ListEntity.tsx+++ b/js/app/packages/entity/src/composed/ListEntity.tsx@@ -133,6 +133,7 @@ export function ListEntity(props: ListEntityProps) {const layoutProps = (): LayoutProps => ({entity: props.entity,checked: props.checked,+ hideCheckbox: props.hideCheckbox,onChecked: props.onChecked,unread: unread(),isShared: isShared(),diff --git a/js/app/packages/entity/src/composed/list-entity/wide-layout.tsx b/js/app/packages/entity/src/composed/list-entity/wide-layout.tsxindex ef54334dc5..c4366fe992 100644--- a/js/app/packages/entity/src/composed/list-entity/wide-layout.tsx+++ b/js/app/packages/entity/src/composed/list-entity/wide-layout.tsx@@ -39,31 +39,40 @@ export function WideLayout(props: LayoutProps) {<Entity.Layoutclass={cn('w-full min-h-[inherit] items-center text-sm px-2',- 'gap-2 grid grid-cols-[1rem_1fr_auto_8ch] grid-rows-[1fr]',+ 'gap-2 grid grid-rows-[1fr]',+ // Drop the indicator column entirely when the checkbox is hidden so the+ // content isn't indented by an empty 1rem gutter.+ props.hideCheckbox+ ? 'grid-cols-[1fr_auto_8ch]'+ : 'grid-cols-[1rem_1fr_auto_8ch]','[--title-width:10rem]')}style={{- 'grid-template-areas': '"indicator content meta timestamp"',+ 'grid-template-areas': props.hideCheckbox+ ? '"content meta timestamp"'+ : '"indicator content meta timestamp"',}}>- <Entity.Slot placement="indicator" class="relative size-full group">- <div class="absolute inset-0 grid place-items-center group-hover:opacity-0">- <UnreadIndicator active={props.unread} />- </div>- <div- class={cn(- 'absolute inset-0 grid place-items-center opacity-0 group-hover:opacity-100',- {- 'opacity-100': props.checked,- }- )}- >- <MultiSelectCheckbox- checked={props.checked}- onChecked={props.onChecked}- />- </div>- </Entity.Slot>+ <Show when={!props.hideCheckbox}>+ <Entity.Slot placement="indicator" class="relative size-full group">+ <div class="absolute inset-0 grid place-items-center group-hover:opacity-0">+ <UnreadIndicator active={props.unread} />+ </div>+ <div+ class={cn(+ 'absolute inset-0 grid place-items-center opacity-0 group-hover:opacity-100',+ {+ 'opacity-100': props.checked,+ }+ )}+ >+ <MultiSelectCheckbox+ checked={props.checked}+ onChecked={props.onChecked}+ />+ </div>+ </Entity.Slot>+ </Show><Entity.Slotplacement="content"class="ph-no-capture font-semibold truncate items-center gap-2 flex"diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex aae507e41c..eb4a62bd65 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -469,6 +469,10 @@ export const CreateDocumentResponse = z.object({documentId: z.string().uuid(),});+export const DisplayResults = z.object({ view: z.any() });++export const DisplayResultsResponse = z.object({ message: z.string() });+export const GetEntityProperties = z.object({entity_id: z.string(),entity_type: z.enum([diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.tsindex 763fdeb27c..9bb6f991af 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts@@ -20,6 +20,10 @@ type ToolParserMap = {call: types.CreateDocument;response: types.CreateDocumentResponse;};+ DisplayResults: {+ call: types.DisplayResults;+ response: types.DisplayResultsResponse;+ };GetEntityProperties: {call: types.GetEntityProperties;response: types.GetEntityPropertiesResponse;@@ -105,6 +109,10 @@ const toolParserMap = {call: schemas.CreateDocument,response: schemas.CreateDocumentResponse,},+ DisplayResults: {+ call: schemas.DisplayResults,+ response: schemas.DisplayResultsResponse,+ },GetEntityProperties: {call: schemas.GetEntityProperties,response: schemas.GetEntityPropertiesResponse,@@ -207,6 +215,10 @@ type ToolDataMap = {call: types.CreateDocument;response: types.CreateDocumentResponse;};+ DisplayResults: {+ call: types.DisplayResults;+ response: types.DisplayResultsResponse;+ };GetEntityProperties: {call: types.GetEntityProperties;response: types.GetEntityPropertiesResponse;diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex f2fc2fbef9..ceb256a131 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -962,6 +962,20 @@ export interface CrmCompanySearchResponseItem {*/updatedAt: string;}+/**+ * 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.+ */+export interface DisplayResults {+ /**+ * The dynamic-UI view to render: an object with an optional `title` and a `widgets` array, per the provided dynamic-UI schema.+ */+ view: {+ [k: string]: unknown;+ };+}+export interface DisplayResultsResponse {+ message: string;+}/*** API-visible content lifecycle and location metadata.*/diff --git a/js/bun.lock b/js/bun.lockindex 45fbe5b6ac..35ce168379 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -265,7 +265,6 @@"name": "observability","dependencies": {"@datadog/browser-logs": "^6.22.0",- "@datadog/browser-rum": "^6.22.0",},},"app/packages/tauri": {diff --git a/rust/cloud-storage/ai_tools/src/display_results.rs b/rust/cloud-storage/ai_tools/src/display_results.rsnew file mode 100644index 0000000000..763ab089f0--- /dev/null+++ b/rust/cloud-storage/ai_tools/src/display_results.rs@@ -0,0 +1,52 @@+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};++use crate::ToolServiceContext;++#[derive(Debug, Serialize, JsonSchema)]+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.+///+/// 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)]+#[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)]+ #[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,+}++#[async_trait]+impl AsyncTool<ToolServiceContext> for DisplayResults {+ type Output = DisplayResultsResponse;++ #[tracing::instrument(skip_all, err)]+ async fn call(+ &self,+ _service_context: ServiceContext<ToolServiceContext>,+ _request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ // The view is rendered on the frontend from the tool call arguments.+ // The backend has nothing to do; acknowledge immediately.+ Ok(DisplayResultsResponse {+ message: "The results have been displayed to the user.".to_string(),+ })+ }+}diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rsindex 5ddd6594fb..29e1b2ffbc 100644--- a/rust/cloud-storage/ai_tools/src/lib.rs+++ b/rust/cloud-storage/ai_tools/src/lib.rs@@ -3,6 +3,7 @@use ai_toolset::AsyncToolCollection;use ai_toolset::schema::{FrontendSchemas, ToolSchemaGenerator, frontend_schemas_builder};mod build_context;+mod display_results;mod schemas;pub mod search;pub mod serde_utils;@@ -14,6 +15,7 @@ use anthropic::toolset::anthropic_toolset;use call::inbound::toolset::call_toolset;use channels::inbound::toolset::channel_toolset;use chat::inbound::toolset::chat_toolset;+use display_results::DisplayResults;use documents::inbound::toolset::document_toolset;use email::inbound::toolset::{email_toolset, mcp_toolset as email_mcp_toolset};use notification::inbound::ai_tool::notification_toolset;@@ -80,7 +82,8 @@ pub fn all_tools() -> ToolSetWithPrompt {let toolset = subagent_toolset().add_subtoolset::<ToolNotificationToolContext>(notification_toolset()).add_subtoolset::<ToolEmailToolContext>(email_toolset())- .add_tool::<Subagent, ToolServiceContext>();+ .add_tool::<Subagent, ToolServiceContext>()+ .add_tool::<DisplayResults, ToolServiceContext>();let toolset = Arc::new(toolset);ToolSetWithPrompt {toolset,