OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat: add dashboard context ai
Carl-Gerhard Lindesvärd2f4d35cda423
diff --git a/apps/api/src/agents/tools/dashboard.ts b/apps/api/src/agents/tools/dashboard.tsnew file mode 100644index 000000000..c140b2c51--- /dev/null+++ b/apps/api/src/agents/tools/dashboard.ts@@ -0,0 +1,138 @@+import {+ AggregateChartEngine,+ ChartEngine,+ funnelService,+ getChartStartEndDate,+ getDashboardById,+ getReportsByDashboardId,+ getSettingsForProject,+} from '@openpanel/db';+import type { IChartRange, IInterval } from '@openpanel/validation';+import { z } from 'zod';+import { chatTool, dashboardUrl } from './helpers';++// Cap on parallel report execution. Real dashboards rarely exceed this,+// but we don't want a runaway 100-report dashboard to blow our 30s tool+// timeout or hammer ClickHouse with one request.+const MAX_REPORTS_PER_SUMMARY = 30;++export const summarizeDashboard = chatTool(+ {+ name: 'summarize_dashboard',+ description: [+ 'Run every report on the current dashboard in parallel and return their data so you can summarize, compare, or explain the dashboard as a whole. Reads dashboardId from the active page context — only works when the user is viewing a dashboard.',+ '',+ 'Honors the dashboard-level range/interval picker (the OverviewRange + OverviewInterval at the top of the page) so each report runs against the window the user is currently looking at, not its saved default.',+ '',+ 'Returns: { dashboard, reports: [{ id, name, chartType, startDate, endDate, data | error }] }. Use this once and synthesize across the results — do NOT also call get_report_data for the same reports.',+ ].join('\n'),+ schema: z.object({}),+ },+ async (_input, context) => {+ const dashboardId = context.pageContext?.ids?.dashboardId;+ if (!dashboardId) {+ return {+ error:+ 'No dashboard in current page context. Ask the user to open a dashboard, or use list_dashboards + list_reports + get_report_data instead.',+ };+ }++ const dashboard = await getDashboardById(dashboardId, context.projectId);+ if (!dashboard) {+ return { error: 'Dashboard not found', dashboardId };+ }++ const allReports = await getReportsByDashboardId(dashboardId);+ const meta = {+ id: dashboard.id,+ name: dashboard.name,+ dashboard_url: dashboardUrl(+ context.organizationId,+ context.projectId,+ `/dashboards/${dashboard.id}`,+ ),+ };++ if (allReports.length === 0) {+ return { dashboard: meta, reports: [], note: 'Dashboard has no reports.' };+ }++ const reports = allReports.slice(0, MAX_REPORTS_PER_SUMMARY);+ const truncated = allReports.length > MAX_REPORTS_PER_SUMMARY;++ const { timezone } = await getSettingsForProject(context.projectId);++ const filters = context.pageContext?.filters;+ const overrideRange = filters?.range as IChartRange | undefined;+ const overrideStart = filters?.startDate;+ const overrideEnd = filters?.endDate;+ const overrideInterval = filters?.interval as IInterval | undefined;++ const results = await Promise.all(+ reports.map(async (report) => {+ try {+ // Apply the dashboard's global range picker to each report.+ // If both startDate + endDate are set, that wins; otherwise+ // the preset range is used. Mirrors how ReportItem behaves+ // when the page-level range/interval flow into a report.+ const useCustom = !!(overrideStart && overrideEnd);+ const merged = {+ ...report,+ ...(useCustom+ ? {+ range: 'custom' as IChartRange,+ startDate: overrideStart,+ endDate: overrideEnd,+ }+ : overrideRange+ ? { range: overrideRange, startDate: null, endDate: null }+ : {}),+ ...(overrideInterval ? { interval: overrideInterval } : {}),+ };++ const { startDate, endDate } = getChartStartEndDate(merged, timezone);+ const chartInput = { ...merged, startDate, endDate, timezone };++ let data: unknown;+ if (report.chartType === 'funnel') {+ data = await funnelService.getFunnel(+ chartInput as Parameters<typeof funnelService.getFunnel>[0],+ );+ } else if (report.chartType === 'metric') {+ data = await AggregateChartEngine.execute(chartInput);+ } else {+ data = await ChartEngine.execute(chartInput);+ }++ return {+ id: report.id,+ name: report.name,+ chartType: report.chartType,+ interval: chartInput.interval,+ startDate,+ endDate,+ data,+ };+ } catch (err) {+ return {+ id: report.id,+ name: report.name,+ chartType: report.chartType,+ error: err instanceof Error ? err.message : String(err),+ };+ }+ }),+ );++ return {+ dashboard: meta,+ reports: results,+ ...(truncated+ ? {+ _truncated: true,+ note: `Dashboard has ${allReports.length} reports; only the first ${MAX_REPORTS_PER_SUMMARY} were summarized.`,+ }+ : {}),+ };+ },+);diff --git a/apps/api/src/agents/tools/index.ts b/apps/api/src/agents/tools/index.tsindex c87f4116f..5ad7ef94b 100644--- a/apps/api/src/agents/tools/index.ts+++ b/apps/api/src/agents/tools/index.ts@@ -1,6 +1,7 @@import type { AgentToolDefinition } from '@better-agent/core';import type { ChatAgentContext } from '../context';import * as base from './base';+import * as dashboard from './dashboard';import * as events from './events';import * as groups from './groups';import * as insights from './insights';@@ -120,6 +121,10 @@ const GROUP_TOOLS: ToolList = [groups.compareGroups,] as AgentToolDefinition[];+const DASHBOARD_TOOLS: ToolList = [+ dashboard.summarizeDashboard,+] as AgentToolDefinition[];+// Client-side UI mutators. Available on pages that have user-// settable filters (date range, event names, property filters) so// the assistant can act on requests like "filter to last 7 days",@@ -167,6 +172,10 @@ export function composeChatTools(context: ChatAgentContext) {return [...BASE_TOOLS, ...INSIGHTS_TOOLS, ...UI_TOOLS];case 'groupDetail':return ids?.groupId ? [...BASE_TOOLS, ...GROUP_TOOLS] : BASE_TOOLS;+ case 'dashboard':+ return ids?.dashboardId+ ? [...BASE_TOOLS, ...DASHBOARD_TOOLS, ...UI_TOOLS]+ : [...BASE_TOOLS, ...UI_TOOLS];case 'overview':return [...BASE_TOOLS, ...UI_TOOLS];default:diff --git a/apps/start/src/components/chat/chat-context-widget.tsx b/apps/start/src/components/chat/chat-context-widget.tsxindex 394420e49..adefe5826 100644--- a/apps/start/src/components/chat/chat-context-widget.tsx+++ b/apps/start/src/components/chat/chat-context-widget.tsx@@ -4,6 +4,7 @@ import {Building2Icon,GanttChartIcon,LayersIcon,+ LayoutDashboardIcon,LayoutPanelTopIcon,type LucideIcon,SearchIcon,@@ -118,6 +119,7 @@ const PAGE_META: Record<profileDetail: { label: 'Profile detail', icon: UserCircleIcon },groupDetail: { label: 'Group detail', icon: Building2Icon },reportEditor: { label: 'Report editor', icon: LayoutPanelTopIcon },+ dashboard: { label: 'Dashboard', icon: LayoutDashboardIcon },};function formatRange(range: string): string {diff --git a/apps/start/src/components/chat/chat-drawer-empty.tsx b/apps/start/src/components/chat/chat-drawer-empty.tsxindex 4ff1b130d..952462abe 100644--- a/apps/start/src/components/chat/chat-drawer-empty.tsx+++ b/apps/start/src/components/chat/chat-drawer-empty.tsx@@ -181,6 +181,19 @@ function getSuggestionsForContext(],};+ case 'dashboard':+ return {+ headline: 'Ask about this dashboard',+ description:+ 'I can summarize every report on this dashboard at once, flag what changed, or zoom into a single chart.',+ prompts: [+ 'Summarize this dashboard',+ "What's underperforming here?",+ 'Compare this dashboard to the previous period',+ 'Which report has the biggest change?',+ ],+ };+default:return {headline: 'Ask about your data',diff --git a/apps/start/src/components/chat/sidebar-chat-composer.tsx b/apps/start/src/components/chat/sidebar-chat-composer.tsxindex ea2eb4bce..b309cb571 100644--- a/apps/start/src/components/chat/sidebar-chat-composer.tsx+++ b/apps/start/src/components/chat/sidebar-chat-composer.tsx@@ -34,20 +34,20 @@ export function SidebarChatComposer() {<formonSubmit={submit}className={cn(- 'mb-4 flex items-center gap-1.5 rounded-md border bg-card pl-2 pr-1',- 'focus-within:ring-1 focus-within:ring-ring transition-shadow',+ 'mb-4 flex items-center gap-2 rounded-md border border-border bg-def-100 pl-3 pr-2',+ 'transition-all focus-within:border-def-400 focus-within:ring-1 focus-within:ring-ring',)}>- <SparklesIcon className="size-4 text-muted-foreground shrink-0" />+ <SparklesIcon className="size-5 shrink-0 text-muted-foreground" /><inputtype="text"value={text}onChange={(e) => setText(e.target.value)}placeholder="Ask AI anything…"className={cn(- 'flex-1 min-w-0 bg-transparent text-sm py-2 text-foreground',- 'placeholder:text-muted-foreground/70',- 'border-0 outline-none ring-0 shadow-none',+ 'min-w-0 flex-1 bg-transparent py-2 text-[13px] font-medium text-foreground',+ 'placeholder:font-normal placeholder:text-muted-foreground',+ 'border-0 shadow-none outline-none ring-0','focus:outline-none focus:ring-0 focus-visible:outline-none focus-visible:ring-0',)}onKeyDown={(e) => {@@ -62,18 +62,19 @@ export function SidebarChatComposer() {type="submit"size="icon"variant="default"- className="size-6 rounded-sm shrink-0"+ className="size-6 shrink-0 rounded-sm"aria-label="Send to AI">- <ArrowUpIcon className="size-3" />+ <ArrowUpIcon className="size-3.5" /></Button>) : (<kbdclassName={cn(- 'shrink-0 rounded border bg-muted px-1.5 py-0.5 font-mono text-[11px]',- 'text-muted-foreground',+ 'shrink-0 rounded border border-border bg-def-200 px-1.5 py-0.5 font-mono text-[11px]',+ 'text-muted-foreground cursor-pointer',)}aria-label="Keyboard shortcut: Cmd+J"+ onClick={() => openNewChat()}>⌘J</kbd>diff --git a/apps/start/src/components/sidebar-organization-menu.tsx b/apps/start/src/components/sidebar-organization-menu.tsxindex a6dfa1caf..1bb74a760 100644--- a/apps/start/src/components/sidebar-organization-menu.tsx+++ b/apps/start/src/components/sidebar-organization-menu.tsx@@ -17,7 +17,6 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from './ui/dropdown-menu';-import { Button } from '@/components/ui/button';import { useAppContext } from '@/hooks/use-app-context';import { pushModal } from '@/modals';import type { RouterOutputs } from '@/trpc/client';@@ -134,31 +133,37 @@ export function ActionCTAButton() {<div className="mb-4"><DropdownMenu><DropdownMenuTrigger asChild>- <Button className="w-full justify-between" size="default">- <div className="flex items-center gap-2">- <PlusIcon size={16} />- <div className="relative flex h-5 items-center">- <AnimatePresence mode="popLayout">- <motion.span- animate={{ y: 0, opacity: 1 }}- className="absolute whitespace-nowrap"- exit={{ y: -20, opacity: 0 }}- initial={{ y: 20, opacity: 0 }}- key={currentActionIndex}- transition={{- type: 'spring',- stiffness: 300,- damping: 25,- duration: 0.3,- }}- >- {ACTIONS[currentActionIndex].label}- </motion.span>- </AnimatePresence>- </div>+ <button+ type="button"+ className={cn(+ 'group flex w-full items-center gap-2 rounded-md border border-border bg-def-200 px-3 py-2 text-left',+ 'text-[13px] font-medium text-foreground',+ 'transition-colors hover:bg-def-300',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',+ )}+ >+ <PlusIcon className="size-5 shrink-0" />+ <div className="relative flex h-5 flex-1 items-center overflow-hidden">+ <AnimatePresence mode="popLayout">+ <motion.span+ animate={{ y: 0, opacity: 1 }}+ className="absolute whitespace-nowrap"+ exit={{ y: -16, opacity: 0 }}+ initial={{ y: 16, opacity: 0 }}+ key={currentActionIndex}+ transition={{+ type: 'spring',+ stiffness: 300,+ damping: 25,+ duration: 0.3,+ }}+ >+ {ACTIONS[currentActionIndex].label}+ </motion.span>+ </AnimatePresence></div>- <ChevronDownIcon size={16} />- </Button>+ <ChevronDownIcon className="size-4 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />+ </button></DropdownMenuTrigger><DropdownMenuContent align="start" className="w-56">{ACTIONS.map((action) => (@@ -167,7 +172,7 @@ export function ActionCTAButton() {key={action.label}onClick={action.onClick}>- <action.icon className="mr-2 h-4 w-4" />+ <action.icon className="mr-2 size-4" />{action.label}</DropdownMenuItem>))}diff --git a/apps/start/src/components/sidebar-project-menu.tsx b/apps/start/src/components/sidebar-project-menu.tsxindex 364fb9144..7b8d92e08 100644--- a/apps/start/src/components/sidebar-project-menu.tsx+++ b/apps/start/src/components/sidebar-project-menu.tsx@@ -31,10 +31,10 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from './ui/dropdown-menu';-import { Button } from '@/components/ui/button';import { useChatState } from '@/components/chat/chat-context';import { SidebarChatComposer } from '@/components/chat/sidebar-chat-composer';import { pushModal } from '@/modals';+import { cn } from '@/utils/cn';interface SidebarProjectMenuProps {dashboards: IServiceDashboards;@@ -146,34 +146,40 @@ export function ActionCTAButton() {}, []);return (- <div className="mb-4">+ <div className="mb-2"><DropdownMenu><DropdownMenuTrigger asChild>- <Button className="w-full justify-between" size="default">- <div className="flex items-center gap-2">- <PlusIcon size={16} />- <div className="relative flex h-5 items-center">- <AnimatePresence mode="popLayout">- <motion.span- animate={{ y: 0, opacity: 1 }}- className="absolute whitespace-nowrap"- exit={{ y: -20, opacity: 0 }}- initial={{ y: 20, opacity: 0 }}- key={currentActionIndex}- transition={{- type: 'spring',- stiffness: 300,- damping: 25,- duration: 0.3,- }}- >- {ACTIONS[currentActionIndex].label}- </motion.span>- </AnimatePresence>- </div>+ <button+ type="button"+ className={cn(+ 'group flex w-full items-center gap-2 rounded-md border border-border bg-def-200 px-3 py-2 text-left',+ 'text-[13px] font-medium text-foreground',+ 'transition-colors hover:bg-def-300',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',+ )}+ >+ <PlusIcon className="size-5 shrink-0" />+ <div className="relative flex h-5 flex-1 items-center overflow-hidden">+ <AnimatePresence mode="popLayout">+ <motion.span+ animate={{ y: 0, opacity: 1 }}+ className="absolute whitespace-nowrap"+ exit={{ y: -16, opacity: 0 }}+ initial={{ y: 16, opacity: 0 }}+ key={currentActionIndex}+ transition={{+ type: 'spring',+ stiffness: 300,+ damping: 25,+ duration: 0.3,+ }}+ >+ {ACTIONS[currentActionIndex].label}+ </motion.span>+ </AnimatePresence></div>- <ChevronDownIcon size={16} />- </Button>+ <ChevronDownIcon className="size-4 shrink-0 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />+ </button></DropdownMenuTrigger><DropdownMenuContent align="start" className="w-56">{ACTIONS.map((action) => (@@ -182,7 +188,7 @@ export function ActionCTAButton() {key={action.label}onClick={action.onClick}>- <action.icon className="mr-2 h-4 w-4" />+ <action.icon className="mr-2 size-4" />{action.label}</DropdownMenuItem>))}diff --git a/apps/start/src/contexts/page-context.tsx b/apps/start/src/contexts/page-context.tsxindex 00a173b9c..41508dd6c 100644--- a/apps/start/src/contexts/page-context.tsx+++ b/apps/start/src/contexts/page-context.tsx@@ -34,7 +34,8 @@ export type PageContextPage =| 'profileDetail'| 'reportEditor'| 'events'- | 'groupDetail';+ | 'groupDetail'+ | 'dashboard';export type PageContext = {page: PageContextPage;@@ -44,6 +45,7 @@ export type PageContext = {profileId?: string;reportId?: string;groupId?: string;+ dashboardId?: string;};filters?: {range?: IChartRange;diff --git a/apps/start/src/hooks/use-page-context-helpers.ts b/apps/start/src/hooks/use-page-context-helpers.tsindex 926a90459..f753db0a2 100644--- a/apps/start/src/hooks/use-page-context-helpers.ts+++ b/apps/start/src/hooks/use-page-context-helpers.ts@@ -62,6 +62,34 @@ export function useEntityPageContext(});}+/**+ * For the Dashboard detail page. Sends the dashboardId + the active+ * range/interval picker (so `summarize_dashboard` runs each report+ * against whatever window the user is currently viewing) plus an+ * optional primer with the dashboard name + report list, so the model+ * can answer "what's on this dashboard?" without an extra tool call.+ */+export function useDashboardPageContext(+ dashboardId: string,+ primer?: Record<string, unknown>,+) {+ const { projectId, organizationId } = useAppParams();+ const { range, startDate, endDate, interval } = useOverviewOptions();++ usePageContext({+ page: 'dashboard',+ route: { projectId, organizationId },+ ids: { dashboardId },+ filters: {+ range,+ startDate: startDate ?? undefined,+ endDate: endDate ?? undefined,+ interval: interval ?? undefined,+ },+ ...(primer ? { primer } : {}),+ });+}+/*** For the Report Editor page. Sends the full live report draft so the* model can propose concrete edits via `preview_report_with_changes`.diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsxindex db92f35a9..c7c6143a3 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx@@ -33,11 +33,12 @@ import {ReportItem,ReportItemSkeleton,} from '@/components/report/report-item';+import { useDashboardPageContext } from '@/hooks/use-page-context-helpers';import { handleErrorToastOptions, useTRPC } from '@/integrations/trpc/react';import { pushModal, showConfirm } from '@/modals';import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { createFileRoute, useRouter } from '@tanstack/react-router';-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';export const Route = createFileRoute('/_app/$organizationId/$projectId/dashboards_/$dashboardId',@@ -182,6 +183,21 @@ function Component() {// Convert reports to grid layout format for all breakpointsconst layouts = useReportLayouts(reports);+ const dashboardPrimer = useMemo(+ () => ({+ name: dashboard?.name,+ reportCount: reports.length,+ reports: reports.map((r) => ({+ id: r.id,+ name: r.name,+ chartType: r.chartType,+ })),+ }),+ [dashboard?.name, reports],+ );++ useDashboardPageContext(dashboardId, dashboardPrimer);+const handleLayoutChange = useCallback((newLayout: Layout[]) => {// This is called during dragging/resizing, we'll save on drag/resize stop}, []);diff --git a/packages/validation/src/chat.ts b/packages/validation/src/chat.tsindex 9fe6ecb3c..9288169c7 100644--- a/packages/validation/src/chat.ts+++ b/packages/validation/src/chat.ts@@ -30,6 +30,7 @@ export const pageContextPageSchema = z.enum(['reportEditor','events','groupDetail',+ 'dashboard',]);export const pageContextSchema = z.object({@@ -44,6 +45,7 @@ export const pageContextSchema = z.object({profileId: z.string().optional(),reportId: z.string().optional(),groupId: z.string().optional(),+ dashboardId: z.string().optional(),}).optional(),filters: z