OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): AI chat with its own page, inline charts and actions (#576)
Carl-Gerhard Lindesvärd7b42b1ea64b1
diff --git a/.gitignore b/.gitignoreindex 777f37ae0..c975683fe 100644--- a/.gitignore+++ b/.gitignore@@ -212,3 +212,4 @@ packages/db/src/code-migrations/*.sql# local working list of open issuesISSUES.md+test-results/diff --git a/apps/start/e2e/auth.setup.ts b/apps/start/e2e/auth.setup.tsindex 35576a927..d7a972f20 100644--- a/apps/start/e2e/auth.setup.ts+++ b/apps/start/e2e/auth.setup.ts@@ -11,8 +11,14 @@ setup('sign in as the seeded user', async ({ page }) => {await page.goto('/login');// The form is server-rendered; a click before hydration submits it natively as a GET.await page.waitForLoadState('networkidle');- await page.getByLabel('Email').fill(manifest.user.email);- await page.getByLabel('Password').fill(manifest.user.password);+ // Hydration can land after the fields are filled and reset them; fill+ // until the values stick, then submit.+ await expect(async () => {+ await page.getByLabel('Email').fill(manifest.user.email);+ await page.getByLabel('Password').fill(manifest.user.password);+ await page.waitForTimeout(500);+ await expect(page.getByLabel('Email')).toHaveValue(manifest.user.email);+ }).toPass({ timeout: 15_000 });await page.getByRole('button', { name: 'Sign in', exact: true }).click();await expect(page).toHaveURL(new RegExp(`/${manifest.organizationId}`), {timeout: 15_000,diff --git a/apps/start/e2e/chat.spec.ts b/apps/start/e2e/chat.spec.tsnew file mode 100644index 000000000..7f1a6d900--- /dev/null+++ b/apps/start/e2e/chat.spec.ts@@ -0,0 +1,82 @@+import { expect as baseExpect, test } from './fixtures';++// A real model answers the question, so the budget is generous.+const expect = baseExpect.configure({ timeout: 60_000 });+test.describe.configure({ timeout: 240_000 });++const CHAT = '/acme/acme-web/chat';+const NOT_CONFIGURED = 'AI chat is not configured';++test.describe('AI chat', () => {+ test('the chat page has a composer and suggestions', async ({ page }) => {+ await page.goto(CHAT);+ await expect(+ page.getByText(/What do you want to know\?|AI chat is not configured/)+ ).toBeVisible();+ if (await page.getByText(NOT_CONFIGURED).isVisible()) {+ return;+ }+ await expect(page.getByRole('textbox', { name: 'Message' })).toBeVisible();+ await expect(page.getByRole('button', { name: 'New chat' })).toBeVisible();+ });++ test('Cmd+J opens the chat from a project page', async ({ page }) => {+ await page.goto('/acme/acme-web', { waitUntil: 'networkidle' });+ await expect(page.getByPlaceholder('Ask AI anything…')).toBeVisible();+ // A key press before hydration is lost; press until the app answers.+ await expect(async () => {+ await page.keyboard.press('ControlOrMeta+j');+ await expect(page).toHaveURL(/\/acme\/acme-web\/chat/, { timeout: 1000 });+ }).toPass({ timeout: 30_000 });+ });++ test('the sidebar composer carries the question into the chat', async ({+ page,+ }) => {+ await page.goto('/acme/acme-web', { waitUntil: 'networkidle' });+ const composer = page.getByPlaceholder('Ask AI anything…');+ // Before hydration the form submits natively and hydration can clear a+ // typed value, so type and submit until the question shows up in the chat+ // (or the chat reports it is not configured).+ const question = page.getByText('What changed this week?');+ const notConfigured = page.getByText(NOT_CONFIGURED);+ await expect(async () => {+ await composer.fill('What changed this week?');+ await expect(composer).toHaveValue('What changed this week?');+ await composer.press('Enter');+ await expect(question.or(notConfigured)).toBeVisible({ timeout: 2000 });+ }).toPass({ timeout: 30_000 });+ if (await notConfigured.isVisible()) {+ test.skip();+ return;+ }+ // The URL settles on the new conversation.+ await expect(page).toHaveURL(/\/chat\?.*c=/);+ });++ test('a question gets an answer and the conversation is listed', async ({+ page,+ }) => {+ await page.goto(CHAT);+ if (await page.getByText(NOT_CONFIGURED).isVisible()) {+ test.skip();+ return;+ }+ const input = page.getByRole('textbox', { name: 'Message' });+ await input.fill('How many unique visitors did we have yesterday?');+ await input.press('Enter');+ await expect(page).toHaveURL(/\/chat\?.*c=/);+ // The send button comes back once the answer has streamed.+ await expect(+ page.getByRole('button', { name: 'Stop generating' })+ ).toBeVisible();+ await expect(+ page.getByRole('button', { name: 'Send message' })+ ).toBeVisible({+ timeout: 120_000,+ });+ await expect(page.getByText(/visitors/i).nth(1)).toBeVisible();+ // The list shows the chat under "Today" with a generated title.+ await expect(page.getByText('Today', { exact: true })).toBeVisible();+ });+});diff --git a/apps/start/package.json b/apps/start/package.jsonindex d9df49dd9..7e19a0f24 100644--- a/apps/start/package.json+++ b/apps/start/package.json@@ -18,8 +18,8 @@"with-env": "dotenv -e ../../.env -c --"},"dependencies": {+ "@ai-sdk/react": "4.0.148","@base-ui/react": "1.9.0",- "@better-agent/client": "0.1.0-beta.3","@codemirror/commands": "6.10.1","@codemirror/lang-javascript": "6.2.4","@codemirror/lang-json": "6.0.2",@@ -97,6 +97,7 @@"@visx/scale": "4.0.1-alpha.0","@visx/shape": "4.0.1-alpha.0","@visx/zoom": "4.0.1-alpha.0",+ "ai": "7.0.144","bind-event-listener": "3.0.0","class-variance-authority": "0.7.1","clsx": "2.1.1",diff --git a/apps/start/src/agents/client.ts b/apps/start/src/agents/client.tsdeleted file mode 100644index 7435e4dac..000000000--- a/apps/start/src/agents/client.ts+++ /dev/null@@ -1,38 +0,0 @@-import { createClient } from '@better-agent/client';-import type { ChatApp } from '@openpanel/core';--/**- * Typed Better Agent client. The `ChatApp` import surfaces every agent name,- * every context schema, and every typed tool input — so `useAgent(client, {- * agent: 'gpt-4-1' })` is autocompleted and validated end-to-end.- *- * `ChatApp = typeof chatApp` is the full Better Agent-inferred application- * type, bound to the server-side agent definition (models, tools, context).- * It can't move into `@openpanel/core`'s assistant.constants without- * dragging the entire agent definition (DB services, providers, etc.) along- * with it. It is type-only, erased at build time, so it stays within R12's- * rule that only `*.constants.ts` may be value-imported here — a second- * type-only exception, alongside `AppRouter`.- */-export type AppClient = ReturnType<typeof createClient<ChatApp>>;--let cachedClient: AppClient | null = null;-let cachedBaseURL: string | null = null;--/**- * Get-or-create the typed Better Agent client. Memoized per `apiUrl` so- * we don't rebuild on every render. We wrap `fetch` to force- * `credentials: 'include'` on every request — the auth plugin guard on- * the server reads the session cookie from the request.- */-export function getChatClient(apiUrl: string): AppClient {- if (cachedClient && cachedBaseURL === apiUrl) {- return cachedClient;- }- cachedBaseURL = apiUrl;- cachedClient = createClient<ChatApp>({- baseURL: `${apiUrl}/ai/agents`,- fetch: (input, init) => fetch(input, { ...init, credentials: 'include' }),- });- return cachedClient;-}diff --git a/apps/start/src/agents/models.ts b/apps/start/src/agents/models.tsdeleted file mode 100644index 4c57abb9b..000000000--- a/apps/start/src/agents/models.ts+++ /dev/null@@ -1,10 +0,0 @@-// Shared with the server so drift is a compile error, not a runtime "agent not-// found". The available models come from `trpc.chat.models`, filtered by the-// API's configured provider keys.--export type { ChatModelEntry as ChatModelOption } from '@openpanel/core/modules/assistant/assistant.constants';-export {- getModelLabel,- isValidModelId,- MODEL_STORAGE_KEY,-} from '@openpanel/core/modules/assistant/assistant.constants';diff --git a/apps/start/src/components/chat/chat-composer.tsx b/apps/start/src/components/chat/chat-composer.tsxnew file mode 100644index 000000000..160ae4336--- /dev/null+++ b/apps/start/src/components/chat/chat-composer.tsx@@ -0,0 +1,124 @@+import type { ChatModelEntry } from '@openpanel/core/modules/assistant/assistant.constants';+import { ArrowUpIcon, SquareIcon } from 'lucide-react';+import { useEffect, useRef, useState } from 'react';+import { ChatModelPicker } from './chat-model-picker';+import { Button } from '@/components/ui/button';+import { cn } from '@/utils/cn';++const MAX_ROWS_HEIGHT_PX = 200;++export function ChatComposer({+ onSend,+ onStop,+ busy,+ models,+ modelId,+ onModelChange,+ autoFocus,+}: {+ onSend: (text: string) => void;+ onStop: () => void;+ busy: boolean;+ models: readonly ChatModelEntry[];+ modelId: string | null;+ onModelChange: (id: string) => void;+ autoFocus?: boolean;+}) {+ const [text, setText] = useState('');+ const textareaRef = useRef<HTMLTextAreaElement | null>(null);++ useEffect(() => {+ if (autoFocus) {+ textareaRef.current?.focus();+ }+ }, [autoFocus]);++ // Grow with the draft up to a cap, then scroll.+ useEffect(() => {+ const element = textareaRef.current;+ if (!element) {+ return;+ }+ element.style.height = 'auto';+ element.style.height = `${Math.min(element.scrollHeight, MAX_ROWS_HEIGHT_PX)}px`;+ }, [text]);++ const submit = () => {+ const value = text.trim();+ if (!value || busy) {+ return;+ }+ onSend(value);+ setText('');+ };++ return (+ <form+ className="mx-auto w-full max-w-3xl px-3 pt-2 pb-[max(0.75rem,env(safe-area-inset-bottom))]"+ onSubmit={(event) => {+ event.preventDefault();+ submit();+ }}+ >+ <div+ className={cn(+ 'rounded-2xl border bg-card shadow-sm transition-shadow',+ 'focus-within:border-ring focus-within:ring-1 focus-within:ring-ring'+ )}+ >+ <textarea+ aria-label="Message"+ className={cn(+ 'block w-full resize-none bg-transparent px-4 pt-3 pb-1 text-base text-foreground leading-6 sm:text-sm',+ 'placeholder:text-muted-foreground/70',+ 'border-0 outline-none ring-0 focus:outline-none focus:ring-0'+ )}+ onChange={(event) => setText(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter' && !event.shiftKey) {+ event.preventDefault();+ submit();+ }+ }}+ placeholder="Ask about your data, build a chart, or ask how something works…"+ ref={textareaRef}+ rows={1}+ value={text}+ />+ <div className="flex items-center justify-between gap-2 px-2 pb-2">+ {models.length > 0 ? (+ <ChatModelPicker+ models={models}+ onChange={onModelChange}+ value={modelId}+ />+ ) : (+ <span />+ )}+ {busy ? (+ <Button+ aria-label="Stop generating"+ className="size-8 rounded-full"+ onClick={onStop}+ size="icon"+ type="button"+ variant="secondary"+ >+ <SquareIcon className="size-3.5 fill-current" />+ </Button>+ ) : (+ <Button+ aria-label="Send message"+ className="size-8 rounded-full"+ disabled={!text.trim()}+ size="icon"+ type="submit"+ >+ <ArrowUpIcon className="size-4" />+ </Button>+ )}+ </div>+ </div>+ </form>+ );+}diff --git a/apps/start/src/components/chat/chat-context-widget.tsx b/apps/start/src/components/chat/chat-context-widget.tsxdeleted file mode 100644index a703ff8b9..000000000--- a/apps/start/src/components/chat/chat-context-widget.tsx+++ /dev/null@@ -1,134 +0,0 @@-import { timeWindows } from '@openpanel/core/modules/report/report.constants';-import {- Building2Icon,- GanttChartIcon,- LayersIcon,- LayoutDashboardIcon,- LayoutPanelTopIcon,- type LucideIcon,- SearchIcon,- TrendingUpDownIcon,- UserCircleIcon,- UsersIcon,- WallpaperIcon,-} from 'lucide-react';-import { usePageContextValue } from '@/contexts/page-context';-import { cn } from '@/utils/cn';--/**- * Small banner shown at the top of the chat body explaining what- * page context the AI is working with. Helps the user understand- * "the assistant sees this page, this date range, these filters".- *- * Renders nothing when there's no useful context to surface.- */-export function ChatContextWidget() {- const ctx = usePageContextValue();- if (!ctx) {- return null;- }-- const meta = PAGE_META[ctx.page];- const Icon = meta?.icon ?? WallpaperIcon;- const pageLabel = meta?.label ?? ctx.page;-- const chips: string[] = [];-- // Date range- const range = ctx.filters?.range;- if (range === 'custom' && ctx.filters?.startDate && ctx.filters?.endDate) {- chips.push(`${ctx.filters.startDate} → ${ctx.filters.endDate}`);- } else if (range) {- chips.push(formatRange(range));- }-- // Event-name filter- if (ctx.filters?.eventNames && ctx.filters.eventNames.length > 0) {- chips.push(`Events: ${ctx.filters.eventNames.join(', ')}`);- }-- // Property filters — short form: "country=SE,US, device=mobile"- if (ctx.filters?.eventFilters && ctx.filters.eventFilters.length > 0) {- for (const f of ctx.filters.eventFilters) {- const filter = f as {- name?: string;- operator?: string;- value?: unknown[];- };- if (!filter.name) {- continue;- }- const op =- filter.operator && filter.operator !== 'is'- ? ` ${filter.operator}`- : '';- const value = Array.isArray(filter.value) ? filter.value.join(', ') : '';- chips.push(`${filter.name}${op}${value ? `: ${value}` : ''}`);- }- }-- // Entity ids on detail pages- if (ctx.ids?.profileId) {- chips.push('Profile');- }- if (ctx.ids?.sessionId) {- chips.push('Session');- }- if (ctx.ids?.groupId) {- chips.push('Group');- }- if (ctx.ids?.reportId) {- chips.push('Report');- }-- return (- <div className="mx-3 mt-3 mb-1 rounded-lg border bg-card/95 px-3 py-2">- <div className="flex items-start gap-2">- <Icon className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />- <div className="col min-w-0 flex-1 gap-1">- <div className="text-muted-foreground text-sm">Assistant context</div>- <div className="font-medium text-foreground/90 text-sm">- {pageLabel}- </div>- {chips.length > 0 && (- <div className="mt-1.5 flex flex-wrap gap-1">- {chips.map((chip) => (- <ContextChip key={chip}>{chip}</ContextChip>- ))}- </div>- )}- </div>- </div>- </div>- );-}--function ContextChip({ children }: { children: React.ReactNode }) {- return (- <span- className={cn(- 'inline-flex items-center rounded-md border bg-muted/40 px-1.5 py-0.5',- 'text-[11px] text-muted-foreground leading-none'- )}- >- {children}- </span>- );-}--const PAGE_META: Record<string, { label: string; icon: LucideIcon }> = {- overview: { label: 'Overview', icon: WallpaperIcon },- insights: { label: 'Insights', icon: TrendingUpDownIcon },- pages: { label: 'Pages', icon: LayersIcon },- seo: { label: 'SEO', icon: SearchIcon },- events: { label: 'Events', icon: GanttChartIcon },- sessionDetail: { label: 'Session detail', icon: UsersIcon },- 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 {- return timeWindows[range as keyof typeof timeWindows]?.label ?? range;-}diff --git a/apps/start/src/components/chat/chat-context.tsx b/apps/start/src/components/chat/chat-context.tsxdeleted file mode 100644index 42f914c41..000000000--- a/apps/start/src/components/chat/chat-context.tsx+++ /dev/null@@ -1,270 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import { useRouteContext } from '@tanstack/react-router';-import {- createContext,- type ReactNode,- useCallback,- useContext,- useEffect,- useMemo,- useState,-} from 'react';-import { newConversationId, useChatUrlState } from './use-chat-open';-import {- type ChatModelOption,- isValidModelId,- MODEL_STORAGE_KEY,-} from '@/agents/models';-import { useTRPC } from '@/integrations/trpc/react';--/**- * Thin global context for chat identifiers. The active conversation- * id and the drawer's open/closed state both live in the URL (`?chat`)- * so conversations are linkable and survive navigation. Everything- * else transient — the selected model, streaming title, pending- * message for the sidebar composer — stays in React state here.- *- * No `useChat` or `useAgent` runs in this provider. The actual chat- * runtime (`<ChatRuntimeProvider>`) lives inside the drawer and is- * scoped to it.- */--interface ChatStateValue {- /**- * Active conversation id. Mirrors `?chat` in the URL. When the- * drawer is closed this is still populated (the next open uses it),- * but `isOpen` will be false.- */- conversationId: string;- /** True when the `?chat` param is present in the URL. */- isOpen: boolean;-- /**- * Open the drawer with a fresh conversation (the default "Ask AI" / ⌘J- * behavior). The header's conversation dropdown resumes a prior one.- */- openChatForContext: () => void;- /**- * Start a brand-new conversation in the open drawer. Alias for- * openChatForContext — kept because several call sites use the- * name "newChat" for clarity.- */- openNewChat: () => void;- /** Open the drawer on a specific existing conversation id. */- openChat: (id: string) => void;- /** Close the drawer (clears `?chat`). */- closeChat: () => void;- /** Switch the active conversation (leaves the drawer open). */- switchConversation: (id: string) => void;- /**- * Start a fresh conversation inside the open drawer. Alias for- * openNewChat — kept for clarity at call sites.- */- newConversation: () => void;-- /** Active agent name = model id from the whitelist. */- agentName: string;- models: readonly ChatModelOption[];- setAgent: (agentName: string) => void;- /**- * Tri-state derived from the `chat.models` query:- * - `null` — query hasn't resolved yet (show the neutral loading state)- * - `true` — at least one provider is configured on the API- * - `false` — no providers configured → show setup instructions- */- isAiEnabled: boolean | null;-- /**- * Title being streamed for the active conversation, if any. Flips- * from null → accumulating deltas → null when either the stream- * finishes (persisted title takes over) or the conversation- * switches. The header renders this when non-null, falling back- * to the persisted title otherwise.- */- streamingTitle: string | null;- setStreamingTitle: (value: string | null) => void;- /**- * Message text the user wants to send the next time the chat- * runtime mounts. The sidebar composer sets this and opens the- * drawer; the runtime drains it once the agent is ready.- */- pendingMessage: string | null;- setPendingMessage: (text: string | null) => void;-}--const ChatContext = createContext<ChatStateValue | null>(null);--function readStoredAgent(): string | null {- if (typeof window === 'undefined') {- return null;- }- const raw = window.localStorage.getItem(MODEL_STORAGE_KEY);- return isValidModelId(raw) ? raw : null;-}--export function ChatStateProvider({ children }: { children: ReactNode }) {- const trpc = useTRPC();- const { session } = useRouteContext({- from: '__root__',- });-- // Single source of truth for "is AI configured on the API" — the- // `chat.models` query already filters by which provider keys are set, so- // an empty `models` array means no OpenAI/Anthropic key and we render the- // setup-instructions empty state. No need to leak env vars to the client.- const modelsQuery = useQuery(- trpc.chat.models.queryOptions(undefined, {- enabled: !!session?.session,- })- );- const models = modelsQuery.data?.models ?? [];- const defaultModelId = modelsQuery.data?.defaultModelId ?? null;- const isAiEnabled: boolean | null = modelsQuery.isPending- ? null- : models.length > 0;- // URL is the source of truth for the active conversation + drawer- // open state. `chatParam`:- // - null → drawer closed- // - non-empty id → drawer open, on that conversation- // - '' (empty) → drawer open, needs a new id (we auto-fill below)- const [chatParam, setChatParam] = useChatUrlState();-- // Fallback local id for first render / SSR when `chatParam` is- // null. Keeps `conversationId` stable as a non-empty string so- // `<ChatRuntimeProvider key={conversationId}>` never sees empty.- // Replaced the moment the user opens the drawer.- const [ghostId] = useState(() => newConversationId());- const conversationId =- chatParam && chatParam.length > 0 ? chatParam : ghostId;- const isOpen = chatParam !== null;-- // If the URL says "open with empty id" (e.g. ?chat= from a stale- // link or legacy boolean param), materialize a fresh conversation.- useEffect(() => {- if (chatParam === '') {- setChatParam(newConversationId());- }- }, [chatParam, setChatParam]);-- const openChatForContext = useCallback(() => {- setChatParam(newConversationId());- }, [setChatParam]);-- const openNewChat = openChatForContext;-- const openChat = useCallback(- (id: string) => {- setChatParam(id);- },- [setChatParam]- );-- const closeChat = useCallback(() => {- setChatParam(null);- }, [setChatParam]);-- const switchConversation = useCallback(- (id: string) => {- setChatParam(id);- },- [setChatParam]- );-- const newConversation = openNewChat;-- // Model selection — persisted to localStorage. Initial value is the- // stored preference (if any); resolves to the server-provided default- // once the models query loads.- const [agentName, setAgentNameState] = useState<string>(- () => readStoredAgent() ?? ''- );- const setAgent = useCallback(- (id: string) => {- if (!models.some((m) => m.id === id)) {- return;- }- setAgentNameState(id);- if (typeof window !== 'undefined') {- window.localStorage.setItem(MODEL_STORAGE_KEY, id);- }- },- [models]- );-- // Once the models query resolves, make sure `agentName` points at a- // model the server can actually serve. Covers:- // - first render (no stored preference) → pick `defaultModelId`- // - stored preference from a provider that's no longer configured- // (e.g. ANTHROPIC_API_KEY was removed) → fall back to default- useEffect(() => {- if (!defaultModelId) {- return;- }- if (agentName && models.some((m) => m.id === agentName)) {- return;- }- setAgentNameState(defaultModelId);- }, [agentName, defaultModelId, models]);-- const [streamingTitle, setStreamingTitle] = useState<string | null>(null);- const [pendingMessage, setPendingMessage] = useState<string | null>(null);-- // Clear `streamingTitle` when the conversation changes — the title- // belongs to the prior convo, not the new one.- //- // NB: we do NOT clear `pendingMessage` here. The sidebar composer- // deliberately sets it *before* calling `openNewChat()`, which- // changes `conversationId`. Clearing here would nuke the pending- // message between set-and-drain and the new chat would open empty.- // The runtime drains it as soon as the new `useAgent` is `ready`.- useEffect(() => {- setStreamingTitle(null);- }, [conversationId]);-- const value = useMemo<ChatStateValue>(- () => ({- conversationId,- isOpen,- openChatForContext,- openNewChat,- openChat,- closeChat,- switchConversation,- newConversation,- agentName,- models,- setAgent,- isAiEnabled,- streamingTitle,- setStreamingTitle,- pendingMessage,- setPendingMessage,- }),- [- conversationId,- isOpen,- openChatForContext,- openNewChat,- openChat,- closeChat,- switchConversation,- newConversation,- agentName,- models,- setAgent,- isAiEnabled,- streamingTitle,- pendingMessage,- ]- );-- return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;-}--export function useChatState(): ChatStateValue {- const value = useContext(ChatContext);- if (!value) {- throw new Error('useChatState must be used inside <ChatStateProvider>');- }- return value;-}diff --git a/apps/start/src/components/chat/chat-conversations.tsx b/apps/start/src/components/chat/chat-conversations.tsxnew file mode 100644index 000000000..2f0826af0--- /dev/null+++ b/apps/start/src/components/chat/chat-conversations.tsx@@ -0,0 +1,140 @@+import { CONVERSATION_LIST_LIMIT_DEFAULT } from '@openpanel/core/modules/conversation/conversation.constants';+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { MessageSquarePlusIcon, Trash2Icon } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { useAppParams } from '@/hooks/use-app-params';+import { useTRPC } from '@/integrations/trpc/react';+import { showConfirm } from '@/modals';+import { cn } from '@/utils/cn';++const MS_PER_DAY = 86_400_000;++function groupLabel(date: Date, now: Date): string {+ const days = Math.floor((now.getTime() - date.getTime()) / MS_PER_DAY);+ if (days <= 0) {+ return 'Today';+ }+ if (days === 1) {+ return 'Yesterday';+ }+ if (days < 7) {+ return 'This week';+ }+ if (days < 30) {+ return 'This month';+ }+ return 'Older';+}++export function ChatConversations({+ activeId,+ activeTitle,+ onSelect,+ onNew,+ className,+}: {+ activeId: string | null;+ activeTitle: string | null;+ onSelect: (id: string) => void;+ onNew: () => void;+ className?: string;+}) {+ const { projectId } = useAppParams();+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const { data: conversations = [] } = useQuery(+ trpc.conversation.list.queryOptions({+ projectId,+ limit: CONVERSATION_LIST_LIMIT_DEFAULT,+ })+ );+ const remove = useMutation(+ trpc.conversation.delete.mutationOptions({+ onSuccess: (_data, variables) => {+ queryClient.invalidateQueries(trpc.conversation.list.pathFilter());+ if (variables.id === activeId) {+ onNew();+ }+ },+ })+ );++ const now = new Date();+ const groups: { label: string; items: typeof conversations }[] = [];+ for (const conversation of conversations) {+ const label = groupLabel(new Date(conversation.updatedAt), now);+ const group = groups.find((entry) => entry.label === label);+ if (group) {+ group.items.push(conversation);+ } else {+ groups.push({ label, items: [conversation] });+ }+ }++ return (+ <div className={cn('flex h-full min-h-0 flex-col', className)}>+ <div className="p-3">+ <Button+ className="w-full justify-start gap-2"+ onClick={onNew}+ variant="outline"+ >+ <MessageSquarePlusIcon className="size-4" />+ New chat+ </Button>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-2 pb-3">+ {conversations.length === 0 && (+ <p className="px-2 py-6 text-center text-muted-foreground text-sm">+ Your chats will show up here.+ </p>+ )}+ {groups.map((group) => (+ <div className="mb-3" key={group.label}>+ <div className="px-2 py-1 font-medium text-[11px] text-muted-foreground uppercase tracking-wide">+ {group.label}+ </div>+ {group.items.map((conversation) => {+ const isActive = conversation.id === activeId;+ const title =+ (isActive ? activeTitle : null) ??+ conversation.title ??+ 'Untitled chat';+ return (+ <div+ className={cn(+ 'group flex items-center gap-1 rounded-md pr-1 text-sm',+ isActive ? 'bg-muted' : 'hover:bg-muted/60'+ )}+ key={conversation.id}+ >+ <button+ className="min-w-0 flex-1 truncate px-2 py-1.5 text-left"+ onClick={() => onSelect(conversation.id)}+ type="button"+ >+ {title}+ </button>+ <button+ aria-label="Delete chat"+ className="rounded p-1 text-muted-foreground opacity-0 hover:text-destructive focus:opacity-100 group-hover:opacity-100"+ onClick={() =>+ showConfirm({+ title: 'Delete chat',+ text: 'This removes the conversation for good.',+ onConfirm: () => remove.mutate({ id: conversation.id }),+ })+ }+ type="button"+ >+ <Trash2Icon className="size-3.5" />+ </button>+ </div>+ );+ })}+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/apps/start/src/components/chat/chat-drawer-body.tsx b/apps/start/src/components/chat/chat-drawer-body.tsxdeleted file mode 100644index 7a287c675..000000000--- a/apps/start/src/components/chat/chat-drawer-body.tsx+++ /dev/null@@ -1,99 +0,0 @@-import { AlertCircleIcon, ArrowDownIcon } from 'lucide-react';-import { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom';-import { ChatContextWidget } from './chat-context-widget';-import { ChatDrawerEmpty } from './chat-drawer-empty';-import { ChatMessage } from './chat-message';-import { useChatRuntime } from './chat-runtime';-import { Button } from '@/components/ui/button';-import { usePageContextValue } from '@/contexts/page-context';-import { cn } from '@/utils/cn';--/**- * Message list. Reads `messages`, `status`, `isLoading`, `isStreaming`- * from `useChatRuntime()` (the Better Agent `useAgent` hook- * indirected through the runtime provider so the footer can share it).- *- * Auto-scrolls to bottom on new content, but stops if the user scrolls- * up — courtesy of `use-stick-to-bottom`. Zero refs, zero effects.- */-export function ChatDrawerBody() {- const { messages, isLoading, isStreaming, status, error } = useChatRuntime();-- const hasContext = usePageContextValue();-- // `runStillActive` flags the currently-generating assistant message- // so its reasoning blocks can stay in the shimmer state until Better- // Agent emits a terminal signal. Everything in older messages is- // always done. `isLoading` covers submitted/waiting, `isStreaming`- // covers actively streaming — combining both catches the full run.- const isRunActive = isLoading || isStreaming;- const lastMessageIndex = messages.length - 1;-- if (messages.length === 0) {- return (- <div className="flex flex-1 flex-col">- <ChatContextWidget />- <ChatDrawerEmpty />- </div>- );- }-- return (- <div className="relative flex min-h-0 flex-1 flex-col">- <div className="absolute top-0 right-0 left-0 z-20 backdrop-blur-sm">- <ChatContextWidget />- </div>- <StickToBottom- className="relative flex-1 overflow-hidden"- initial="instant"- resize="smooth"- >- <StickToBottom.Content- className={cn('flex flex-col gap-4 px-3 py-4', hasContext && 'pt-24')}- >- {messages.map((message, idx) => (- <ChatMessage- key={message.localId}- message={message}- runStillActive={isRunActive && idx === lastMessageIndex}- />- ))}- {isLoading && !isStreaming && (- <div className="flex items-center gap-2 text-sm">- <span className="op-shimmer font-medium">Thinking…</span>- </div>- )}- {status === 'error' && (- <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm">- <AlertCircleIcon className="mt-0.5 size-4 shrink-0" />- <span className="leading-[1.5]">- {error?.message ?? 'Something went wrong. Try again.'}- </span>- </div>- )}- </StickToBottom.Content>- <ScrollToBottomButton />- </StickToBottom>- </div>- );-}--function ScrollToBottomButton() {- const { isAtBottom, scrollToBottom } = useStickToBottomContext();- if (isAtBottom) {- return null;- }- return (- <Button- aria-label="Scroll to bottom"- className="absolute bottom-3 left-1/2 h-7 -translate-x-1/2 gap-1 px-2 shadow-md"- onClick={() => scrollToBottom()}- size="sm"- type="button"- variant="secondary"- >- <ArrowDownIcon className="size-3" />- <span className="text-sm">Latest</span>- </Button>- );-}diff --git a/apps/start/src/components/chat/chat-drawer-empty.tsx b/apps/start/src/components/chat/chat-drawer-empty.tsxdeleted file mode 100644index a9e537e26..000000000--- a/apps/start/src/components/chat/chat-drawer-empty.tsx+++ /dev/null@@ -1,241 +0,0 @@-import { ExternalLinkIcon, KeyRoundIcon, SparklesIcon } from 'lucide-react';-import { useChatRuntime } from './chat-runtime';-import CopyInput from '@/components/forms/copy-input';-import { usePageContextValue } from '@/contexts/page-context';--/**- * Empty-state panel shown inside the drawer body when a chat has no- * messages yet — page-aware suggestion prompts. The "AI not configured"- * variant is a separate component (`ChatDrawerNotConfigured` below)- * rendered directly from `<ChatDrawer>` without the runtime, since- * it doesn't depend on an agent being available.- */-export function ChatDrawerEmpty() {- const ctx = usePageContextValue();- const { send } = useChatRuntime();- const suggestions = getSuggestionsForContext(ctx);-- return (- <div className="flex flex-1 flex-col items-center justify-center gap-5 px-6 py-8 text-center">- <div className="flex size-10 items-center justify-center rounded-full bg-primary/10 text-primary">- <SparklesIcon className="size-5" />- </div>- <div className="max-w-xs">- <h3 className="mb-2 font-semibold text-xl">{suggestions.headline}</h3>- <p className="mt-1.5 text-muted-foreground leading-[1.5]">- {suggestions.description}- </p>- </div>- <div className="flex w-full max-w-xs flex-col items-center gap-2">- {suggestions.prompts.map((prompt) => (- <button- className="rounded-md border bg-muted/30 px-3 py-2 text-left text-foreground/80 text-sm transition-colors hover:bg-muted/60 hover:text-foreground"- key={prompt}- onClick={() => send(prompt)}- type="button"- >- {prompt}- </button>- ))}- </div>- </div>- );-}--export function ChatDrawerNotConfigured() {- return (- <div className="flex flex-1 flex-col items-center justify-center gap-5 px-6 py-8 text-center">- <div className="flex size-10 items-center justify-center rounded-full bg-muted text-muted-foreground">- <KeyRoundIcon className="size-5" />- </div>- <div className="max-w-xs">- <h3 className="mb-2 font-semibold text-xl">AI chat isn't configured</h3>- <p className="mt-1.5 text-muted-foreground leading-[1.5]">- Set <code className="font-mono text-sm">OPENAI_API_KEY</code> and/or{' '}- <code className="font-mono text-sm">ANTHROPIC_API_KEY</code> on the- API service to enable AI chat, then restart it. The model picker shows- only providers with a configured key.- </p>- </div>- <div className="flex w-full max-w-xs flex-col gap-2">- <CopyInput label="OpenAI" value="OPENAI_API_KEY=sk-..." />- <CopyInput label="Anthropic" value="ANTHROPIC_API_KEY=sk-ant-..." />- </div>- <a- className="inline-flex items-center gap-1.5 text-muted-foreground text-sm hover:text-foreground"- href="https://openpanel.dev/docs/self-hosting/environment-variables#ai-features"- rel="noopener"- target="_blank"- >- View setup docs- <ExternalLinkIcon className="size-3.5" />- </a>- </div>- );-}--type Suggestions = {- headline: string;- description: string;- prompts: string[];-};--function getSuggestionsForContext(- ctx: ReturnType<typeof usePageContextValue>-): Suggestions {- if (!ctx) {- return {- headline: 'Ask about your data',- description:- 'I can answer questions about your analytics, generate reports, and dig into users, sessions, or pages.',- prompts: [- 'What happened yesterday?',- 'Show me last 7 days of traffic',- 'Which pages have the highest bounce rate?',- ],- };- }-- switch (ctx.page) {- case 'overview':- return {- headline: 'Ask about this overview',- description:- 'I can explain trends, compare periods, or filter the page. Try a question or pick a starter.',- prompts: [- 'What changed compared to the previous period?',- 'Filter to mobile only',- 'Show me last 7 days of traffic',- 'Which referrers drove the most sessions?',- ],- };-- case 'insights':- return {- headline: 'Explore your insights',- description:- 'I can explain why an insight fired, find related ones, or walk you through the most important.',- prompts: [- 'What are the most important insights right now?',- 'Explain the biggest anomaly this week',- 'Any insights related to device trends?',- ],- };-- case 'pages':- return {- headline: 'Ask about your pages',- description:- 'I can rank pages by performance, find declining ones, or identify entry/exit patterns.',- prompts: [- 'Which pages are declining vs last month?',- 'Show pages with the highest bounce rate',- 'Top entry pages in the last 7 days',- 'Find pages with underperforming SEO',- ],- };-- case 'seo':- return {- headline: 'Dig into your SEO',- description:- 'I can surface high-opportunity queries, check for cannibalization, and correlate SEO with on-site engagement.',- prompts: [- 'Queries on page 2 with high impressions (easy wins)',- 'Any query cannibalization I should fix?',- 'Which pages bring GSC clicks but bounce hard?',- 'Top SEO queries last 30 days',- ],- };-- case 'events':- return {- headline: 'Analyze your events',- description:- 'I can analyze distribution, correlate events, and drill into properties.',- prompts: [- 'Which events often happen together?',- 'Analyze event distribution by country',- 'Filter to signup events only',- 'What are the most common event properties?',- ],- };-- case 'profileDetail':- return {- headline: 'Ask about this user',- description:- 'I can summarize this profile, build a journey, or compare them to the average user.',- prompts: [- "Tell me about this user's journey",- 'How does this user compare to average?',- 'What was their last session?',- 'Do they have unusual behavior?',- ],- };-- case 'sessionDetail':- return {- headline: 'Ask about this session',- description:- 'I can walk through the path, compare to typical sessions, or explain the referrer context.',- prompts: [- 'Walk me through this session',- 'How does this compare to typical sessions?',- 'Where did this traffic come from?',- 'Are there similar sessions today?',- ],- };-- case 'groupDetail':- return {- headline: 'Ask about this group',- description:- 'I can show metrics, list members, and compare to peer groups.',- prompts: [- "Summarize this group's activity",- 'Compare to other groups',- 'Who are the most active members?',- "What's this group's engagement trend?",- ],- };-- case 'reportEditor':- return {- headline: 'Edit this report with me',- description:- 'I can preview changes, suggest breakdowns, or compare to the previous period.',- prompts: [- 'Suggest useful breakdowns for this report',- 'Compare to the previous period',- 'Find anomalies in the current data',- 'Add a country breakdown',- ],- };-- 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',- description:- "I can answer questions about the page you're viewing, generate reports, and dig into specific users, sessions, or pages.",- prompts: [- "What's our visitor count this week?",- 'Top traffic sources right now',- 'Show me top pages by bounce rate',- ],- };- }-}diff --git a/apps/start/src/components/chat/chat-drawer-footer.tsx b/apps/start/src/components/chat/chat-drawer-footer.tsxdeleted file mode 100644index ea73a065a..000000000--- a/apps/start/src/components/chat/chat-drawer-footer.tsx+++ /dev/null@@ -1,111 +0,0 @@-import { ArrowUpIcon, StopCircleIcon } from 'lucide-react';-import { useEffect, useRef, useState } from 'react';-import { useChatRuntime } from './chat-runtime';-import { ModelPicker } from './model-picker';-import { Button } from '@/components/ui/button';-import { cn } from '@/utils/cn';--/**- * Composer card.- *- * Layout mirrors the modern "single-card" pattern: textarea on top,- * model picker bottom-left, send button bottom-right. Owns its own- * input state — `useChat` v5+ doesn't manage input.- */-export function ChatDrawerFooter() {- const { send, stop, status } = useChatRuntime();- const [text, setText] = useState('');- const isStreaming = status === 'streaming' || status === 'submitted';-- // Auto-focus the textarea on mount. Because the footer sits inside- // `<ChatRuntimeProvider key={conversationId}>`, the provider (and- // therefore this footer) remounts whenever the drawer opens or the- // active conversation changes — so this runs on every "open"- // without us needing to track the event explicitly.- const textareaRef = useRef<HTMLTextAreaElement | null>(null);- useEffect(() => {- textareaRef.current?.focus();- }, []);-- const submit = (e?: React.FormEvent) => {- e?.preventDefault();- const value = text.trim();- if (!value || isStreaming) {- return;- }- send(value);- setText('');- };-- return (- <form className="px-3 pt-2 pb-3" onSubmit={submit}>- <div- className={cn(- 'rounded-xl border bg-card transition-shadow',- 'focus-within:border-ring focus-within:ring-1 focus-within:ring-ring'- )}- >- {/*- Plain `<textarea>` here — the shadcn `<Textarea>` ships with- its own `border-input` + `focus-visible:ring-2 + ring-offset-2`,- which stack on top of the parent card's focus-within ring and- produce a double-outline (see prior screenshot). Keep things- unstyled at the element level so the parent card owns the- focus boundary.- */}- {/*- Input stays editable while a reply streams — the user can- draft the next message in parallel. Enter is a no-op during- streaming (blocked inside `submit`); once the run ends the- drafted text sends on the next Enter press.- */}- <textarea- className={cn(- 'block w-full bg-transparent text-foreground text-sm leading-[1.5]',- 'placeholder:text-muted-foreground/70',- 'resize-none border-0 shadow-none outline-none ring-0',- 'focus:outline-none focus:ring-0 focus-visible:outline-none focus-visible:ring-0',- 'max-h-[200px] min-h-[48px] px-3 pt-3 pb-1'- )}- onChange={(e) => setText(e.target.value)}- onKeyDown={(e) => {- if (e.key === 'Enter' && !e.shiftKey) {- e.preventDefault();- submit();- }- }}- placeholder="Ask anything about your data…"- ref={textareaRef}- rows={2}- value={text}- />- <div className="flex items-center justify-between gap-2 px-2 pb-2">- <ModelPicker />- {isStreaming ? (- <Button- aria-label="Stop generating"- className="size-7 shrink-0 rounded-md"- onClick={stop}- size="icon"- type="button"- variant="secondary"- >- <StopCircleIcon className="size-3.5" />- </Button>- ) : (- <Button- aria-label="Send message"- className="size-7 shrink-0 rounded-md"- disabled={!text.trim()}- size="icon"- type="submit"- variant="default"- >- <ArrowUpIcon className="size-3.5" />- </Button>- )}- </div>- </div>- </form>- );-}diff --git a/apps/start/src/components/chat/chat-drawer-header.tsx b/apps/start/src/components/chat/chat-drawer-header.tsxdeleted file mode 100644index d6b105c5a..000000000--- a/apps/start/src/components/chat/chat-drawer-header.tsx+++ /dev/null@@ -1,183 +0,0 @@-import { CONVERSATION_LIST_LIMIT_DEFAULT } from '@openpanel/core/modules/conversation/conversation.constants';-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';-import { MessageSquarePlusIcon, Trash2Icon, XIcon } from 'lucide-react';-import { useEffect, useRef, useState } from 'react';-import { useChatState } from './chat-context';-import { Button } from '@/components/ui/button';-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';-import { useTRPC } from '@/integrations/trpc/react';--/**- * Header — conversation picker, model picker, new chat, close.- *- * Reads the global `useChatState()` for the current conversation and- * agent. Conversation list still uses TRPC; switching a conversation- * just sets the id — Better Agent's `hydrateFromServer` loads the- * messages on the next render of the body.- */-export function ChatDrawerHeader({- projectId,- onClose,-}: {- projectId: string;- onClose: () => void;-}) {- const trpc = useTRPC();- const queryClient = useQueryClient();- const {- conversationId,- switchConversation,- newConversation,- streamingTitle,- } = useChatState();-- const { data: conversations } = useQuery(- trpc.conversation.list.queryOptions({- projectId,- limit: CONVERSATION_LIST_LIMIT_DEFAULT,- })- );-- const deleteMutation = useMutation(- trpc.conversation.delete.mutationOptions({- onSuccess: (_data, variables) => {- queryClient.invalidateQueries(trpc.conversation.list.pathFilter());- if (variables.id === conversationId) {- newConversation();- }- },- })- );-- // Header title priority:- // 1. In-session streaming title (either mid-stream or finalized- // after the title finished generating)- // 2. Persisted title from the conversation list query- // 3. "New chat" fallback when nothing is known yet- const persistedTitle =- conversations?.find((c) => c.id === conversationId)?.title ?? null;- const activeTitle = streamingTitle ?? persistedTitle ?? 'New chat';-- return (- <header className="flex items-center justify-between gap-2 border-b px-3 py-2">- <div className="flex min-w-0 flex-1 items-center gap-2">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- className="max-w-[200px] truncate font-medium text-sm"- size="sm"- variant="ghost"- >- {activeTitle}- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent- align="start"- className="max-h-96 w-72 overflow-y-auto"- >- <DropdownMenuLabel>Conversations</DropdownMenuLabel>- <DropdownMenuSeparator />- {(!conversations || conversations.length === 0) && (- <div className="px-2 py-3 text-muted-foreground text-sm">- No conversations yet. Start typing to create one.- </div>- )}- {conversations?.map((c) => (- <DropdownMenuItem- className="flex items-center justify-between gap-2"- key={c.id}- onSelect={() => switchConversation(c.id)}- >- <span className="truncate">{c.title ?? 'Untitled chat'}</span>- <InlineDeleteButton- onConfirm={() => deleteMutation.mutate({ id: c.id })}- />- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- </div>- <div className="flex shrink-0 items-center gap-1">- <Button- aria-label="New conversation"- onClick={() => newConversation()}- size="sm"- title="New conversation"- variant="ghost"- >- <MessageSquarePlusIcon className="size-4" />- </Button>- <Button- aria-label="Close chat"- onClick={onClose}- size="sm"- variant="ghost"- >- <XIcon className="size-4" />- </Button>- </div>- </header>- );-}--/**- * Two-step inline delete. First click swaps the X icon for a red- * check; second click within the arm window fires `onConfirm`.- * Auto-reverts after 4s of inactivity. Moving the mouse away doesn't- * disarm — that was too aggressive (the dropdown re-layouts between- * hovers and the button briefly loses hover state). Only the- * time-based auto-revert applies.- */-function InlineDeleteButton({ onConfirm }: { onConfirm: () => void }) {- const [armed, setArmed] = useState(false);- const timerRef = useRef<number | null>(null);-- const clearTimer = () => {- if (timerRef.current !== null) {- window.clearTimeout(timerRef.current);- timerRef.current = null;- }- };-- useEffect(() => clearTimer, []);-- const handleClick = (e: React.MouseEvent) => {- e.preventDefault();- e.stopPropagation();- if (armed) {- clearTimer();- setArmed(false);- onConfirm();- return;- }- setArmed(true);- clearTimer();- timerRef.current = window.setTimeout(() => {- setArmed(false);- timerRef.current = null;- }, 4000);- };-- return (- <button- aria-label={armed ? 'Confirm delete' : 'Delete conversation'}- className={- armed- ? 'shrink-0 rounded bg-destructive p-1 text-white transition-colors hover:bg-destructive/90'- : 'shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-destructive'- }- onClick={handleClick}- title={armed ? 'Click again to confirm' : 'Delete'}- type="button"- >- {armed ? <Trash2Icon className="size-3" /> : <XIcon className="size-3" />}- </button>- );-}diff --git a/apps/start/src/components/chat/chat-drawer-slot.tsx b/apps/start/src/components/chat/chat-drawer-slot.tsxdeleted file mode 100644index 20df95b63..000000000--- a/apps/start/src/components/chat/chat-drawer-slot.tsx+++ /dev/null@@ -1,40 +0,0 @@-import { lazy, Suspense, useEffect, useState } from 'react';--/**- * Client-only mount wrapper for the chat drawer.- *- * `@better-agent/client` uses Ajv for JSON schema validation which- * compiles validators via `new Function()`. The Cloudflare Workers- * SSR environment (workerd) disallows runtime code generation, so the- * client module can't be evaluated during SSR.- *- * This slot:- * - Returns null on the server and during initial hydration (no- * mismatch: the server HTML has no drawer, the client's first- * render matches)- * - After `useEffect` fires on the client, triggers the lazy import- * which loads `@better-agent/client` for the first time- * - Suspense keeps the tree stable while the chunk loads- *- * The drawer is gated by `?chat=<id>` anyway, so it's never visible- * on the first paint — there's no UX cost to this wrapping.- */-const ChatDrawer = lazy(() =>- import('./chat-drawer').then((m) => ({ default: m.ChatDrawer }))-);--export function ChatDrawerSlot() {- const [mounted, setMounted] = useState(false);- useEffect(() => {- setMounted(true);- }, []);-- if (!mounted) {- return null;- }- return (- <Suspense fallback={null}>- <ChatDrawer />- </Suspense>- );-}diff --git a/apps/start/src/components/chat/chat-drawer.tsx b/apps/start/src/components/chat/chat-drawer.tsxdeleted file mode 100644index 7584887e3..000000000--- a/apps/start/src/components/chat/chat-drawer.tsx+++ /dev/null@@ -1,98 +0,0 @@-import { useEffect } from 'react';-import { useChatState } from './chat-context';-import { ChatDrawerBody } from './chat-drawer-body';-import { ChatDrawerNotConfigured } from './chat-drawer-empty';-import { ChatDrawerFooter } from './chat-drawer-footer';-import { ChatDrawerHeader } from './chat-drawer-header';-import { ChatRuntimeProvider } from './chat-runtime';-import { useAppParams } from '@/hooks/use-app-params';-import { useResizableDrawer } from '@/hooks/use-resizable-drawer';--const WIDTH_STORAGE_KEY = 'op-chat-drawer-width';-const DEFAULT_WIDTH = 440;-const MIN_WIDTH = 360;-const MAX_WIDTH = 720;--/**- * Persistent right-side drawer for the context-aware AI chat. Mounts- * once inside `_app.tsx` (so it can flex-shrink the main content on- * `lg+`). Renders nothing when `?chat` is absent from the URL or- * there's no project in scope.- *- * The drawer wraps body + footer in `<ChatRuntimeProvider>`, which- * owns the single `useAgent()` instance for the active agent +- * conversation. Header sits outside the runtime and only reads the- * thin `useChatState()` context (conversation list, new chat button).- */-export function ChatDrawer() {- const { projectId } = useAppParams();- const {- agentName,- conversationId,- isOpen,- isAiEnabled,- closeChat,- openChatForContext,- } = useChatState();- const { width, dragHandleProps } = useResizableDrawer({- defaultWidth: DEFAULT_WIDTH,- minWidth: MIN_WIDTH,- maxWidth: MAX_WIDTH,- storageKey: WIDTH_STORAGE_KEY,- });-- // Cmd+J / Ctrl+J shortcut — toggles the drawer. Opening resumes- // the last conversation for the current context (same page +- // same entity); closing just clears `?chat`.- useEffect(() => {- if (!projectId) {- return;- }- const handler = (e: KeyboardEvent) => {- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'j') {- e.preventDefault();- if (isOpen) {- closeChat();- } else {- openChatForContext();- }- }- };- window.addEventListener('keydown', handler);- return () => window.removeEventListener('keydown', handler);- }, [projectId, isOpen, closeChat, openChatForContext]);-- if (!(projectId && isOpen)) {- return null;- }-- return (- <>- {/* The aside is `fixed`; this spacer makes the page shrink on `lg+`. */}- <div aria-hidden className="hidden shrink-0 lg:block" style={{ width }} />- <aside- className="fixed top-0 right-0 z-40 flex h-screen flex-col border-l bg-background shadow-2xl"- style={{ width }}- >- <div- aria-label="Resize chat drawer"- className="absolute top-0 left-0 z-10 h-full w-1 cursor-ew-resize transition-colors hover:bg-border"- {...dragHandleProps}- />- <ChatDrawerHeader onClose={closeChat} projectId={projectId} />- {/* `key={conversationId}` remounts the runtime so a switch re-hydrates. The- placeholder avoids `useAgent({ agent: '' })` while models load. */}- {isAiEnabled === false ? (- <ChatDrawerNotConfigured />- ) : agentName ? (- <ChatRuntimeProvider key={conversationId}>- <ChatDrawerBody />- <ChatDrawerFooter />- </ChatRuntimeProvider>- ) : (- <div className="flex-1" />- )}- </aside>- </>- );-}diff --git a/apps/start/src/components/chat/chat-empty.tsx b/apps/start/src/components/chat/chat-empty.tsxnew file mode 100644index 000000000..3419e2240--- /dev/null+++ b/apps/start/src/components/chat/chat-empty.tsx@@ -0,0 +1,125 @@+import type { ChatLaunchHint } from '@openpanel/core/modules/assistant/assistant.constants';+import { ExternalLinkIcon, KeyRoundIcon, SparklesIcon } from 'lucide-react';+import CopyInput from '@/components/forms/copy-input';++const DEFAULT_PROMPTS = [+ 'What changed this week compared to last week?',+ 'Show me unique visitors per day for the last 30 days',+ 'Build a dashboard for signups and where they come from',+ 'How do I connect the MCP server to Claude?',+];++function promptsFor(hint?: ChatLaunchHint): string[] {+ switch (hint?.page) {+ case 'profile':+ return [+ 'Tell me about this user',+ 'What did they do in their last session?',+ 'How does this user compare to a typical one?',+ 'Which pages did they visit most?',+ ];+ case 'session':+ return [+ 'Walk me through this session',+ 'Where did this visitor come from?',+ 'Did they convert?',+ 'Show similar sessions from the same referrer',+ ];+ case 'dashboard':+ return [+ 'Summarize this dashboard',+ 'Which report changed the most this week?',+ 'Add a chart of signups by referrer to this dashboard',+ 'Which of these charts should I worry about?',+ ];+ case 'seo':+ return [+ 'Which queries are the easiest wins?',+ 'Is my organic traffic trending up?',+ 'Any pages competing for the same query?',+ 'Top pages in Google last 30 days',+ ];+ case 'pages':+ return [+ 'Which pages have the highest bounce rate?',+ 'Top entry pages last 7 days',+ 'Which pages are losing traffic?',+ 'Chart pageviews for /pricing over time',+ ];+ case 'events':+ return [+ 'Which events fire most often?',+ 'Show me the last 20 purchase events',+ 'Build a funnel from signup to purchase',+ 'Chart the daily count of each conversion event',+ ];+ default:+ return DEFAULT_PROMPTS;+ }+}++export function ChatEmpty({+ hint,+ onPick,+}: {+ hint?: ChatLaunchHint;+ onPick: (prompt: string) => void;+}) {+ return (+ <div className="mx-auto flex w-full max-w-2xl flex-1 flex-col items-center justify-center gap-6 px-4 py-10 text-center">+ <div className="flex size-11 items-center justify-center rounded-full bg-primary/10 text-primary">+ <SparklesIcon className="size-5" />+ </div>+ <div>+ <h1 className="font-semibold text-2xl">What do you want to know?</h1>+ <p className="mt-2 text-muted-foreground">+ Ask about your numbers, get charts inline, build dashboards, or ask+ how OpenPanel works.+ </p>+ </div>+ <div className="grid w-full gap-2 sm:grid-cols-2">+ {promptsFor(hint).map((prompt) => (+ <button+ className="rounded-xl border bg-card px-4 py-3 text-left text-sm transition-colors hover:bg-muted/60"+ key={prompt}+ onClick={() => onPick(prompt)}+ type="button"+ >+ {prompt}+ </button>+ ))}+ </div>+ </div>+ );+}++export function ChatNotConfigured() {+ return (+ <div className="mx-auto flex w-full max-w-md flex-1 flex-col items-center justify-center gap-5 px-6 py-10 text-center">+ <div className="flex size-11 items-center justify-center rounded-full bg-muted text-muted-foreground">+ <KeyRoundIcon className="size-5" />+ </div>+ <div>+ <h1 className="font-semibold text-2xl">AI chat is not configured</h1>+ <p className="mt-2 text-muted-foreground">+ Set <code className="font-mono text-sm">OPENAI_API_KEY</code> or{' '}+ <code className="font-mono text-sm">ANTHROPIC_API_KEY</code> on the+ API service and restart it.+ </p>+ </div>+ <div className="flex w-full flex-col gap-2">+ <CopyInput label="OpenAI" value="OPENAI_API_KEY=sk-..." />+ <CopyInput label="Anthropic" value="ANTHROPIC_API_KEY=sk-ant-..." />+ </div>+ <a+ className="inline-flex items-center gap-1.5 text-muted-foreground text-sm hover:text-foreground"+ href="https://openpanel.dev/docs/self-hosting/environment-variables#ai-features"+ rel="noopener"+ target="_blank"+ >+ View setup docs+ <ExternalLinkIcon className="size-3.5" />+ </a>+ </div>+ );+}diff --git a/apps/start/src/components/chat/chat-launch.ts b/apps/start/src/components/chat/chat-launch.tsnew file mode 100644index 000000000..c8861ba3d--- /dev/null+++ b/apps/start/src/components/chat/chat-launch.ts@@ -0,0 +1,29 @@+import { useNavigate } from '@tanstack/react-router';+import { useCallback } from 'react';+import { usePageContextRef } from '@/contexts/page-context';+import { useAppParams } from '@/hooks/use-app-params';++/**+ * Opens the chat page. A question travels in `q` and is sent on arrival; the+ * page the user came from travels in `hint`.+ */+export function useChatLaunch() {+ const navigate = useNavigate();+ const { organizationId, projectId } = useAppParams();+ const hintRef = usePageContextRef();++ return useCallback(+ (question?: string) => {+ const text = question?.trim();+ navigate({+ to: '/$organizationId/$projectId/chat',+ params: { organizationId, projectId },+ search: {+ q: text || undefined,+ hint: hintRef.current ?? undefined,+ },+ });+ },+ [navigate, organizationId, projectId, hintRef]+ );+}diff --git a/apps/start/src/components/chat/chat-layout.tsx b/apps/start/src/components/chat/chat-layout.tsxnew file mode 100644index 000000000..8f15de087--- /dev/null+++ b/apps/start/src/components/chat/chat-layout.tsx@@ -0,0 +1,86 @@+import { HistoryIcon } from 'lucide-react';+import { type ReactNode, useState } from 'react';+import { ChatConversations } from './chat-conversations';+import { Button } from '@/components/ui/button';+import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet';++/**+ * The parts of the chat page that stay put while a conversation loads: the+ * list on the left (a sheet on phones) and the header. The pane is the child.+ */+export function ChatLayout({+ activeId,+ activeTitle,+ onSelect,+ onNew,+ children,+}: {+ activeId: string | null;+ activeTitle: string | null;+ onSelect: (id: string) => void;+ onNew: () => void;+ children: ReactNode;+}) {+ const [listOpen, setListOpen] = useState(false);+ const select = (id: string) => {+ setListOpen(false);+ onSelect(id);+ };+ const startNew = () => {+ setListOpen(false);+ onNew();+ };++ return (+ <div className="flex h-full min-h-0 w-full">+ <ChatConversations+ activeId={activeId}+ activeTitle={activeTitle}+ className="hidden w-64 shrink-0 border-r bg-card/50 lg:flex"+ onNew={startNew}+ onSelect={select}+ />+ <Sheet onOpenChange={setListOpen} open={listOpen}>+ <SheetContent className="w-80 p-0" side="left">+ <SheetTitle className="sr-only">Conversations</SheetTitle>+ <ChatConversations+ activeId={activeId}+ activeTitle={activeTitle}+ onNew={startNew}+ onSelect={select}+ />+ </SheetContent>+ </Sheet>++ <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ <header className="flex h-12 shrink-0 items-center gap-2 border-b px-3">+ <Button+ aria-label="Conversations"+ className="lg:hidden"+ onClick={() => setListOpen(true)}+ size="icon"+ variant="ghost"+ >+ <HistoryIcon className="size-4" />+ </Button>+ <div className="min-w-0 flex-1 truncate font-medium text-sm">+ {activeTitle ?? 'New chat'}+ </div>+ </header>+ {children}+ </div>+ </div>+ );+}++export function ChatPaneLoading() {+ return (+ <div className="flex min-h-0 flex-1 flex-col gap-4 px-4 py-6">+ <div className="ml-auto h-10 w-2/5 animate-pulse rounded-2xl bg-muted" />+ <div className="h-4 w-1/3 animate-pulse rounded bg-muted" />+ <div className="h-48 w-full animate-pulse rounded-xl bg-muted" />+ <div className="h-4 w-3/4 animate-pulse rounded bg-muted" />+ <div className="h-4 w-1/2 animate-pulse rounded bg-muted" />+ </div>+ );+}diff --git a/apps/start/src/components/chat/chat-limit-notice.tsx b/apps/start/src/components/chat/chat-limit-notice.tsxnew file mode 100644index 000000000..6263baef3--- /dev/null+++ b/apps/start/src/components/chat/chat-limit-notice.tsx@@ -0,0 +1,59 @@+import {+ type ChatLimitError,+ zChatLimitError,+} from '@openpanel/core/modules/assistant/assistant.constants';+import { Link } from '@tanstack/react-router';+import { GaugeIcon } from 'lucide-react';+import { useAppParams } from '@/hooks/use-app-params';++const UPGRADABLE_TIERS: ReadonlySet<ChatLimitError['tier']> = new Set([+ 'trial',+ 'starter',+ 'growth',+]);++/** The chat route answers a refused turn with a JSON body; the transport surfaces it as the error text. */+export function parseChatLimit(+ error: Error | undefined+): ChatLimitError | null {+ if (!error) {+ return null;+ }+ const body =+ 'responseBody' in error && typeof error.responseBody === 'string'+ ? error.responseBody+ : error.message;+ try {+ const parsed = zChatLimitError.safeParse(JSON.parse(body));+ return parsed.success ? parsed.data : null;+ } catch {+ return null;+ }+}++export function ChatLimitNotice({ limit }: { limit: ChatLimitError }) {+ const { organizationId } = useAppParams();+ const canUpgrade =+ limit.reason !== 'burst' && UPGRADABLE_TIERS.has(limit.tier);++ return (+ <div className="flex items-start gap-2 rounded-lg border bg-muted/40 px-3 py-2 text-sm">+ <GaugeIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <div className="flex-1">+ <span>{limit.message}</span>+ {canUpgrade && (+ <>+ {' '}+ <Link+ className="text-primary underline underline-offset-2"+ params={{ organizationId }}+ to="/$organizationId/billing"+ >+ Upgrade for a higher limit+ </Link>+ </>+ )}+ </div>+ </div>+ );+}diff --git a/apps/start/src/components/chat/chat-markdown.tsx b/apps/start/src/components/chat/chat-markdown.tsxindex e1cb28643..69bba72f7 100644--- a/apps/start/src/components/chat/chat-markdown.tsx+++ b/apps/start/src/components/chat/chat-markdown.tsx@@ -1,4 +1,4 @@-import { memo } from 'react';+import { isValidElement, memo, type ReactNode } from 'react';import ReactMarkdown from 'react-markdown';import remarkGfm from 'remark-gfm';import { cn } from '@/utils/cn';@@ -10,6 +10,22 @@ import { cn } from '@/utils/cn';* Memoized so repeated streaming re-renders of the same chunk skip* the markdown parse when the content hasn't changed.*/+/** Numbers, money and percentages, so they line up on the right like in the tool tables. */+const NUMERIC_CELL = /^[\s$€£+\-−]*[\d.,]+\s*(%|[A-Z]{3})?\s*$/;++function cellText(children: ReactNode): string {+ if (typeof children === 'string' || typeof children === 'number') {+ return String(children);+ }+ if (Array.isArray(children)) {+ return children.map(cellText).join('');+ }+ if (isValidElement<{ children?: ReactNode }>(children)) {+ return cellText(children.props.children);+ }+ return '';+}+function ChatMarkdownInner({text,className,@@ -42,15 +58,48 @@ function ChatMarkdownInner({'[&_pre]:overflow-x-auto [&_pre]:rounded-md [&_pre]:bg-muted [&_pre]:p-3 [&_pre]:text-[12.5px]','[&_pre>code]:bg-transparent [&_pre>code]:p-0','[&_blockquote]:border-muted-foreground/30 [&_blockquote]:border-l-2 [&_blockquote]:pl-3 [&_blockquote]:text-muted-foreground',- '[&_table]:my-2 [&_table]:w-full [&_table]:text-sm',- '[&_th]:border-b [&_th]:px-2 [&_th]:py-1 [&_th]:text-left [&_th]:font-medium',- '[&_td]:border-border/40 [&_td]:border-b [&_td]:px-2 [&_td]:py-1','[&_hr]:my-3 [&_hr]:border-border',className)}><ReactMarkdowncomponents={{+ // Tables get the same card the tool tables use.+ table: ({ children }) => (+ <div className="my-2 overflow-hidden rounded-xl border bg-card">+ <div className="overflow-x-auto">+ <table className="w-full text-sm">{children}</table>+ </div>+ </div>+ ),+ thead: ({ children }) => (+ <thead className="text-left text-muted-foreground text-xs">+ {children}+ </thead>+ ),+ tbody: ({ children }) => <tbody>{children}</tbody>,+ tr: ({ children }) => (+ <tr className="border-t first:border-t-0">{children}</tr>+ ),+ th: ({ children }) => (+ <th className="whitespace-nowrap px-3 py-1.5 font-medium">+ {children}+ </th>+ ),+ td: ({ children }) => {+ const text = cellText(children);+ return (+ <td+ className={cn(+ 'max-w-[320px] truncate px-3 py-1.5',+ NUMERIC_CELL.test(text) && 'text-right font-mono tabular-nums'+ )}+ title={text}+ >+ {children}+ </td>+ );+ },// Open external links in a new tab; safe defaults.a: ({ href, children, ...rest }) => (<adiff --git a/apps/start/src/components/chat/chat-message.tsx b/apps/start/src/components/chat/chat-message.tsxindex 8eef28ecc..b723acb49 100644--- a/apps/start/src/components/chat/chat-message.tsx+++ b/apps/start/src/components/chat/chat-message.tsx@@ -1,182 +1,348 @@-import type { UIMessage } from '@better-agent/client';+import { useNavigate } from '@tanstack/react-router';+import { getToolName, isToolUIPart } from 'ai';import { ChevronRightIcon } from 'lucide-react';import { useState } from 'react';import { ChatMarkdown } from './chat-markdown';-import { chatToolRenderers, DefaultToolResult } from './tool-results/registry';-import type { ToolResultPart } from './tool-results/types';+import { ApprovalCard, ApprovalDecided } from './parts/approval-card';+import { BillingCard, type BillingOutput } from './parts/billing-card';+import { ChartCard } from './parts/chart-card';+import { DiagnosisCard, type DiagnosisOutput } from './parts/diagnosis-card';+import {+ DialogCard,+ DocsCard,+ NavigateCard,+ PlanChangeCard,+ SearchCard,+} from './parts/result-cards';+import { TableCard } from './parts/table-card';+import {+ isRichToolPart,+ ToolActivityGroup,+ type ToolPart,+} from './parts/tool-activity-group';+import { ToolActivity, ToolDone, ToolError } from './parts/tool-card';+import { toolPhrase } from './tool-labels';+import {+ type AssistantUIMessage,+ type AssistantUIMessagePart,+ isChartOutput,+ isErrorOutput,+ isRowsOutput,+} from './types';+import { useAppParams } from '@/hooks/use-app-params';+import { pushModal } from '@/modals';import { cn } from '@/utils/cn';-/**- * Renders a single message by switching over `message.parts[i].type`.- *- * Better Agent's part model splits tool calls and results into TWO- * separate parts (`tool-call` and `tool-result`) keyed by `callId`.- * We pair them up before rendering so the UI sees one logical "tool- * invocation" per call.- *- * Assistant text supports markdown via `<ChatMarkdown>`. User text- * stays plain (no markdown injection from user input).- */export function ChatMessage({message,- runStillActive = false,+ streaming,+ onApproval,}: {- message: UIMessage;- /**- * True only for the message currently being generated by the agent.- * Used to decide whether a reasoning block without an explicit- * "complete" state signal should keep its streaming UI. Anything in- * a prior message is always considered done.- */- runStillActive?: boolean;+ message: AssistantUIMessage;+ /** True only for the assistant message being generated right now. */+ streaming: boolean;+ onApproval: (approvalId: string, approved: boolean) => void;}) {- const isUser = message.role === 'user';-- const resultByCallId = new Map<- string,- { result?: unknown; status: string }- >();- for (const part of message.parts) {- if (part.type === 'tool-result') {- resultByCallId.set(part.callId, {- result: part.result,- status: part.status,- });- }+ if (message.role === 'user') {+ const text = message.parts+ .map((part) => (part.type === 'text' ? part.text : ''))+ .join('');+ return (+ <div className="flex justify-end">+ <div className="max-w-[85%] whitespace-pre-wrap break-words rounded-2xl rounded-br-md bg-primary px-4 py-2.5 text-primary-foreground">+ {text}+ </div>+ </div>+ );}- const lastIdx = message.parts.length - 1;-+ const lastIndex = message.parts.length - 1;return (- <div- className={cn(- 'flex flex-col gap-2',- isUser ? 'items-end' : 'items-start'+ <div className="flex flex-col gap-3">+ {groupParts(message.parts).map((group, index) =>+ Array.isArray(group) ? (+ <ToolActivityGroup+ key={group[0]?.toolCallId ?? index}+ parts={group}+ />+ ) : (+ <MessagePart+ key={partKey(group.part, group.index)}+ onApproval={onApproval}+ part={group.part}+ streaming={streaming && group.index === lastIndex}+ />+ ))}- >- {message.parts.map((part, idx) => {- switch (part.type) {- case 'text':- if (isUser) {- return (- <div- className="text max-w-[90%] whitespace-pre-wrap break-words rounded-lg bg-primary px-3 py-2 text-primary-foreground leading-[1.5]"- key={`${message.localId}-text-${idx}`}- >- {part.text}- </div>- );- }- return (- <div- className="w-full max-w-full"- key={`${message.localId}-text-${idx}`}- >- <ChatMarkdown text={part.text} />- </div>- );+ </div>+ );+}- case 'reasoning': {- // A reasoning block is done when any of:- // - the part's own `state` says so (the ideal signal)- // - another part follows it in this message (the model- // moved on to tool-calls, text, or fresh reasoning)- // - the run as a whole is no longer active (this message- // is either a prior turn or the current run has- // ended, so nothing else is coming)- // Without the latter two fallbacks the shimmer sticks- // indefinitely when Better Agent doesn't emit a terminal- // state on reasoning parts.- const stateComplete =- (part as { state?: string }).state === 'complete';- const hasFollowingPart = idx < lastIdx;- return (- <ReasoningBlock- complete={stateComplete || hasFollowingPart || !runStillActive}- key={`${message.localId}-reasoning-${idx}`}- text={part.text}- />- );- }+type PartGroup = ToolPart[] | { part: AssistantUIMessagePart; index: number };- case 'tool-call': {- const matched = resultByCallId.get(part.callId);- const toolName = part.name;- // If the tool's name hasn't streamed in yet (intermediate- // state between TOOL_CALL_START and the args event), show- // a neutral "Thinking…" shimmer instead of "Running- // unknown…". Once the name arrives, the part re-renders- // with the real tool + its renderer.- if (!toolName) {- return (- <div- className="flex items-center gap-2 py-1.5 text-sm"- key={part.callId}- >- <span className="op-shimmer font-medium">Thinking…</span>- </div>- );- }- const Renderer =- chatToolRenderers[- `tool-${toolName}` as keyof typeof chatToolRenderers- ] ?? DefaultToolResult;- const toolPart: ToolResultPart = {- type: `tool-${toolName}`,- toolCallId: part.callId,- state: derivePartState(part.state, matched?.status),- input: part.args ? safeParse(part.args) : undefined,- output: matched?.result,- errorText:- matched?.status === 'error' ? 'Tool failed' : undefined,- };- return (- <div className="w-full max-w-full" key={part.callId}>- <Renderer part={toolPart} />- </div>- );- }+/** Plain tool calls that follow each other become one activity line. */+function groupParts(parts: AssistantUIMessagePart[]): PartGroup[] {+ const groups: PartGroup[] = [];+ for (const [index, part] of parts.entries()) {+ const isPlainTool = isToolUIPart(part) && !isRichToolPart(part);+ const last = groups.at(-1);+ if (isPlainTool && Array.isArray(last)) {+ last.push(part as ToolPart);+ } else if (isPlainTool) {+ groups.push([part as ToolPart]);+ } else if (part.type === 'step-start') {+ // Step boundaries carry nothing to show and must not split a group.+ } else {+ groups.push({ part, index });+ }+ }+ return groups;+}- case 'tool-result':- // Already rendered above as part of the matching tool-call.- return null;+function partKey(part: AssistantUIMessagePart, index: number): string {+ if (isToolUIPart(part)) {+ return part.toolCallId;+ }+ return `${part.type}-${index}`;+}- default:- return null;- }- })}- </div>- );+function MessagePart({+ part,+ streaming,+ onApproval,+}: {+ part: AssistantUIMessagePart;+ streaming: boolean;+ onApproval: (approvalId: string, approved: boolean) => void;+}) {+ if (part.type === 'text') {+ return <ChatMarkdown text={part.text} />;+ }+ if (part.type === 'reasoning') {+ return <Reasoning streaming={streaming} text={part.text} />;+ }+ if (isToolUIPart(part)) {+ return <ToolPartView onApproval={onApproval} part={part} />;+ }+ return null;+}++function ToolPartView({+ part,+ onApproval,+}: {+ part: ToolPart;+ onApproval: (approvalId: string, approved: boolean) => void;+}) {+ const toolName = getToolName(part);+ const input = part.input as Record<string, unknown> | undefined;++ switch (part.state) {+ case 'input-streaming':+ case 'input-available':+ return <ToolActivity toolName={toolName} />;+ case 'approval-requested': {+ if (part.approval.isAutomatic) {+ return <ToolActivity toolName={toolName} />;+ }+ return (+ <ApprovalCard+ input={input}+ onRespond={(approved) => onApproval(part.approval.id, approved)}+ toolName={toolName}+ />+ );+ }+ case 'approval-responded':+ return part.approval.approved ? (+ <ToolActivity toolName={toolName} />+ ) : (+ <ApprovalDecided approved={false} input={input} toolName={toolName} />+ );+ case 'output-denied':+ return (+ <ApprovalDecided approved={false} input={input} toolName={toolName} />+ );+ case 'output-error':+ return <ToolError message={part.errorText} toolName={toolName} />;+ case 'output-available':+ return (+ <ToolResult input={input} output={part.output} toolName={toolName} />+ );+ default:+ return null;+ }}-/**- * Reasoning trace from the model. While streaming, shows a shimmer- * "Thinking…" header with the latest line as a one-line preview.- * When complete, becomes a click-to-expand "Thought" disclosure.- */-function ReasoningBlock({- text,- complete,+function ToolResult({+ toolName,+ input,+ output,}: {- text: string;- complete: boolean;+ toolName: string;+ input: Record<string, unknown> | undefined;+ output: unknown;}) {+ if (isErrorOutput(output)) {+ return <ToolError message={output.error} toolName={toolName} />;+ }+ if (isChartOutput(output)) {+ return <ChartCard output={output} />;+ }+ if (toolName === 'navigate' && input) {+ return (+ <NavigateCard+ input={input as Parameters<typeof NavigateCard>[0]['input']}+ output={output as { opened?: string }}+ />+ );+ }+ if (toolName === 'open_dialog' && input) {+ return (+ <DialogCard input={input as Parameters<typeof DialogCard>[0]['input']} />+ );+ }+ if (toolName === 'search_docs') {+ const results = (output as { results?: { title: string; url: string }[] })+ .results;+ return results ? <DocsCard results={results} /> : null;+ }+ if (toolName === 'search') {+ const hit = output as Parameters<typeof SearchCard>[0];+ return (+ <SearchCard+ eventNames={hit.eventNames ?? []}+ profiles={hit.profiles ?? []}+ session={hit.session ?? null}+ />+ );+ }+ if (toolName === 'change_plan') {+ return <PlanChangeCard output={output as { checkoutUrl?: string }} />;+ }+ if (toolName === 'get_billing') {+ return <BillingCard output={output as BillingOutput} />;+ }+ if (toolName === 'diagnose_tracking') {+ return <DiagnosisCard output={output as DiagnosisOutput} />;+ }+ if (isRowsOutput(output) && output.rows.length === 0) {+ return <ToolDone output={output} toolName={toolName} />;+ }+ if (isRowsOutput(output)) {+ const dimensions = Array.isArray(input?.dimensions)+ ? (input.dimensions as string[]).join(' and ')+ : typeof input?.dimension === 'string'+ ? String(input.dimension)+ : null;+ const title = dimensions+ ? `Top ${dimensions.replace(/_/g, ' ')}`+ : toolPhrase(toolName, 'done');+ return (+ <RowsTable+ rows={output.rows}+ title={title}+ toolName={toolName}+ total={output.total}+ />+ );+ }+ if (+ Array.isArray(output) &&+ output.every((row) => typeof row === 'object' && row)+ ) {+ return (+ <TableCard+ rows={output as Record<string, unknown>[]}+ title={toolPhrase(toolName, 'done')}+ />+ );+ }+ return <ToolDone output={output} toolName={toolName} />;+}++/** Columns worth seeing first for raw rows, and what a click on a row opens. */+const PREFERRED_COLUMNS: Record<string, string[]> = {+ query_events: [+ 'created_at',+ 'name',+ 'path',+ 'country',+ 'device',+ 'profile_id',+ ],+ query_sessions: [+ 'created_at',+ 'entry_path',+ 'referrer_name',+ 'country',+ 'device',+ 'duration',+ 'screen_view_count',+ ],+};++function RowsTable({+ rows,+ title,+ toolName,+ total,+}: {+ rows: Record<string, unknown>[];+ title: string;+ toolName: string;+ total?: number;+}) {+ const navigate = useNavigate();+ const { organizationId, projectId } = useAppParams();+ let onRowClick: ((row: Record<string, unknown>) => void) | undefined;+ if (toolName === 'query_events') {+ onRowClick = (row) => {+ if (typeof row.id === 'string' && typeof row.created_at === 'string') {+ pushModal('EventDetails', {+ id: row.id,+ createdAt: new Date(row.created_at),+ projectId,+ });+ }+ };+ }+ if (toolName === 'query_sessions') {+ onRowClick = (row) => {+ if (typeof row.id === 'string') {+ navigate({+ to: '/$organizationId/$projectId/sessions/$sessionId',+ params: { organizationId, projectId, sessionId: row.id },+ });+ }+ };+ }+ return (+ <TableCard+ onRowClick={onRowClick}+ preferredColumns={PREFERRED_COLUMNS[toolName]}+ rows={rows}+ title={title}+ total={total}+ />+ );+}++/** The model's reasoning: a shimmer while it streams, a disclosure afterwards. */+function Reasoning({ text, streaming }: { text: string; streaming: boolean }) {const [open, setOpen] = useState(false);const trimmed = text.trim();- // Latest non-empty line for the live preview.const latestLine =trimmed.split('\n')- .map((l) => l.trim())+ .map((line) => line.trim()).filter(Boolean).pop() ?? '';- if (!complete) {+ if (streaming) {return (- <div className="w-full max-w-full">- <div className="flex items-center gap-2 text-sm">- <span className="op-shimmer font-medium">Thinking…</span>- </div>+ <div>+ <div className="op-shimmer font-medium text-sm">Thinking…</div>{latestLine && (<div className="mt-1 line-clamp-1 text-muted-foreground/80 text-sm italic">{latestLine}@@ -185,57 +351,27 @@ function ReasoningBlock({</div>);}-+ if (!trimmed) {+ return null;+ }return (- <div className="mb-2 w-full max-w-full">+ <div><buttonclassName="flex items-center gap-1 text-muted-foreground text-sm transition-colors hover:text-foreground"- onClick={() => setOpen((v) => !v)}+ onClick={() => setOpen((value) => !value)}type="button"><ChevronRightIconclassName={cn('size-3 transition-transform', open && 'rotate-90')}/>- <span>Thought</span>+ Thought</button>{open && (- <div className="mt-2">- <ChatMarkdown- className="text-muted-foreground text-sm leading-normal"- text={trimmed}- />- </div>+ <ChatMarkdown+ className="mt-2 text-muted-foreground text-sm"+ text={trimmed}+ />)}</div>);}--function derivePartState(- callState: string | undefined,- resultStatus: string | undefined-): string {- if (resultStatus === 'success') {- return 'output-available';- }- if (resultStatus === 'error') {- return 'output-error';- }- if (resultStatus === 'pending') {- return 'input-available';- }- if (callState === 'input-streaming') {- return 'input-streaming';- }- if (callState === 'input-complete') {- return 'input-available';- }- return 'input-streaming';-}--function safeParse(json: string): unknown {- try {- return JSON.parse(json);- } catch {- return undefined;- }-}diff --git a/apps/start/src/components/chat/chat-messages.tsx b/apps/start/src/components/chat/chat-messages.tsxnew file mode 100644index 000000000..2ff0ac508--- /dev/null+++ b/apps/start/src/components/chat/chat-messages.tsx@@ -0,0 +1,79 @@+import { AlertCircleIcon, ArrowDownIcon } from 'lucide-react';+import { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom';+import { ChatLimitNotice, parseChatLimit } from './chat-limit-notice';+import { ChatMessage } from './chat-message';+import type { AssistantUIMessage } from './types';+import { Button } from '@/components/ui/button';++export function ChatMessages({+ messages,+ status,+ error,+ onApproval,+ onRetry,+}: {+ messages: AssistantUIMessage[];+ status: 'submitted' | 'streaming' | 'ready' | 'error';+ error?: Error;+ onApproval: (approvalId: string, approved: boolean) => void;+ onRetry: () => void;+}) {+ const active = status === 'submitted' || status === 'streaming';+ const lastIndex = messages.length - 1;+ const limit = status === 'error' ? parseChatLimit(error) : null;++ return (+ <StickToBottom+ className="relative min-h-0 flex-1 overflow-hidden"+ initial="instant"+ resize="smooth"+ >+ <StickToBottom.Content className="mx-auto flex w-full max-w-3xl flex-col gap-6 px-4 py-6">+ {messages.map((message, index) => (+ <ChatMessage+ key={message.id}+ message={message}+ onApproval={onApproval}+ streaming={active && index === lastIndex}+ />+ ))}+ {status === 'submitted' && (+ <div className="op-shimmer font-medium text-sm">Thinking…</div>+ )}+ {limit && <ChatLimitNotice limit={limit} />}+ {status === 'error' && !limit && (+ <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm">+ <AlertCircleIcon className="mt-0.5 size-4 shrink-0" />+ <span className="flex-1">+ {error?.message ?? 'Something went wrong.'}+ </span>+ <button className="underline" onClick={onRetry} type="button">+ Retry+ </button>+ </div>+ )}+ </StickToBottom.Content>+ <ScrollToBottom />+ </StickToBottom>+ );+}++function ScrollToBottom() {+ const { isAtBottom, scrollToBottom } = useStickToBottomContext();+ if (isAtBottom) {+ return null;+ }+ return (+ <Button+ aria-label="Scroll to latest"+ className="absolute bottom-3 left-1/2 h-7 -translate-x-1/2 gap-1 rounded-full px-3 shadow-md"+ onClick={() => scrollToBottom()}+ size="sm"+ type="button"+ variant="secondary"+ >+ <ArrowDownIcon className="size-3" />+ Latest+ </Button>+ );+}diff --git a/apps/start/src/components/chat/chat-model-picker.tsx b/apps/start/src/components/chat/chat-model-picker.tsxnew file mode 100644index 000000000..6c380ce40--- /dev/null+++ b/apps/start/src/components/chat/chat-model-picker.tsx@@ -0,0 +1,90 @@+import type { ChatModelEntry } from '@openpanel/core/modules/assistant/assistant.constants';+import { CheckIcon, ChevronDownIcon } from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';++const PROVIDER_LABELS: Record<ChatModelEntry['provider'], string> = {+ openai: 'OpenAI',+ anthropic: 'Anthropic',+};++const TIER_LABELS: Record<ChatModelEntry['tier'], string> = {+ fast: 'Fast',+ balanced: 'Balanced',+ deep: 'Deep',+};++export function ChatModelPicker({+ models,+ value,+ onChange,+}: {+ models: readonly ChatModelEntry[];+ value: string | null;+ onChange: (id: string) => void;+}) {+ const current = models.find((model) => model.id === value);+ const grouped: Record<string, ChatModelEntry[]> = {};+ for (const model of models) {+ const group = grouped[model.provider] ?? [];+ group.push(model);+ grouped[model.provider] = group;+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ aria-label="Select model"+ className="h-8 gap-1 px-2 text-muted-foreground text-xs"+ size="sm"+ variant="ghost"+ >+ <span className="max-w-[140px] truncate">+ {current?.label ?? 'Model'}+ </span>+ <ChevronDownIcon className="size-3" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-64">+ {Object.entries(grouped).map(([provider, entries], index) => (+ <div key={provider}>+ {index > 0 && <DropdownMenuSeparator />}+ <DropdownMenuLabel className="text-[11px] text-muted-foreground uppercase tracking-wide">+ {PROVIDER_LABELS[provider as ChatModelEntry['provider']]}+ </DropdownMenuLabel>+ {entries.map((model) => (+ <DropdownMenuItem+ className="flex items-start justify-between gap-3"+ key={model.id}+ onSelect={() => onChange(model.id)}+ >+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span className="truncate">{model.label}</span>+ <span className="rounded border px-1 text-[10px] text-muted-foreground uppercase">+ {TIER_LABELS[model.tier]}+ </span>+ </div>+ <div className="text-muted-foreground text-xs">+ {model.description}+ </div>+ </div>+ {value === model.id && (+ <CheckIcon className="mt-0.5 size-3.5 shrink-0" />+ )}+ </DropdownMenuItem>+ ))}+ </div>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/apps/start/src/components/chat/chat-runtime.tsx b/apps/start/src/components/chat/chat-runtime.tsxdeleted file mode 100644index 4281c78f8..000000000--- a/apps/start/src/components/chat/chat-runtime.tsx+++ /dev/null@@ -1,241 +0,0 @@-import { useAgent } from '@better-agent/client/react';-import { useMutation, useQueryClient } from '@tanstack/react-query';-import {- createContext,- type ReactNode,- useContext,- useEffect,- useMemo,- useRef,- useState,-} from 'react';-import { useChatState } from './chat-context';-import { streamTitle } from './title-stream';-import { chatToolHandlers } from './tool-handlers';-import { getChatClient } from '@/agents/client';-import { usePageContextValue } from '@/contexts/page-context';-import { useAppContext } from '@/hooks/use-app-context';-import { useAppParams } from '@/hooks/use-app-params';-import { useTRPC } from '@/integrations/trpc/react';--/**- * Drawer-scoped runtime that owns the `useAgent()` instance, so the chat- * client is only active while the drawer is open. Page context is read per- * send, so every message carries the user's current view.- */--type ChatRuntimeValue = ReturnType<typeof useAgent> & {- /** Send a plain-text message with the current page context attached. */- send: (text: string) => void;-};--const ChatRuntimeContext = createContext<ChatRuntimeValue | null>(null);--export function ChatRuntimeProvider({ children }: { children: ReactNode }) {- const { apiUrl } = useAppContext();- const { projectId, organizationId } = useAppParams();- const {- agentName,- conversationId,- setStreamingTitle,- pendingMessage,- setPendingMessage,- } = useChatState();- const pageContext = usePageContextValue();- const trpc = useTRPC();- const queryClient = useQueryClient();-- const client = useMemo(() => getChatClient(apiUrl), [apiUrl]);-- const renameConversation = useMutation(- trpc.conversation.rename.mutationOptions()- );-- // Title streams run fire-and-forget. If the user switches or closes- // the conversation before the stream finishes, we abort so:- // - the stream stops pulling from the network- // - stale `setStreamingTitle(partial)` calls don't flash the old- // title into the header of the new conversation (global state)- // The ref is cleared on unmount; the provider remounts on- // conversation switch (via `key={conversationId}`) which triggers- // the cleanup.- const titleAbortRef = useRef<AbortController | null>(null);- useEffect(- () => () => {- titleAbortRef.current?.abort();- titleAbortRef.current = null;- },- []- );-- const agent = useAgent(client, {- agent: agentName,- conversationId,- hydrateFromServer: true,- optimisticUserMessage: true,- // Better Agent forwards tool calls for any tool declared via- // `.client()` on the server (see `@openpanel/core`'s- // `modules/assistant/src/tools/ui.ts`)- // to the matching entry here. Typed via `ToolHandlers<ChatApp>`- // on the map itself, so this line stays cast-free.- toolHandlers: chatToolHandlers,- onFinish: () => {- // Refresh the conversation list so the new row appears in the- // header dropdown.- queryClient.invalidateQueries(trpc.conversation.list.pathFilter());- },- });-- const value = useMemo<ChatRuntimeValue>(- () => ({- ...agent,- send: (text: string) => {- const trimmed = text.trim();- if (!trimmed) {- return;- }- if (agent.status === 'submitted' || agent.status === 'streaming') {- return;- }- const isFirstTurn = agent.messages.length === 0;-- void agent.sendMessage({- input: text,- // The `agentName` is a runtime-resolved string so TypeScript- // can't narrow `useAgent`'s context type — we know the shape- // from `chatContextSchema` on the server.- // biome-ignore lint/suspicious/noExplicitAny: see comment above- context: {- projectId,- organizationId,- pageContext: pageContext ?? undefined,- } as any,- });-- // On the first turn, kick off a parallel title stream. Deltas- // flow into `streamingTitle` so the header renders the title- // word-by-word. When the stream finishes we persist via TRPC- // so the title survives a reload, but we leave `streamingTitle`- // set — it's the in-memory source of truth for this session.- // It gets cleared on `newConversation()` / `switchConversation()`.- if (isFirstTurn) {- // Defensive: a first turn should have no title request in flight.- titleAbortRef.current?.abort();- const controller = new AbortController();- titleAbortRef.current = controller;- const idAtSend = conversationId;- setStreamingTitle('');- void (async () => {- const finalTitle = await streamTitle(- client,- trimmed,- (partial) => {- if (controller.signal.aborted) {- return;- }- setStreamingTitle(partial);- },- controller.signal- );- if (controller.signal.aborted || !finalTitle) {- return;- }- try {- await renameConversation.mutateAsync({- id: idAtSend,- title: finalTitle,- projectId,- });- queryClient.invalidateQueries(- trpc.conversation.list.pathFilter()- );- } catch (err) {- console.error('[chat] conversation rename failed', err);- }- })();- }- },- }),- [- agent,- client,- conversationId,- projectId,- organizationId,- pageContext,- renameConversation,- setStreamingTitle,- ]- );-- // Drain the pending message left by the sidebar composer.- //- // Timing is tricky because of `hydrateFromServer: true`:- // useAgent's initial snapshot reports status="ready", then its- // init() effect flips it to "hydrating", and finally back to- // "ready" once hydration completes. If we send on the very first- // "ready", init() aborts the run moments later.- //- // We model this as an explicit state machine:- // 'init' — mount frame before init() has run- // 'hydrating' — saw a non-ready status at least once- // 'settled' — hydration finished, safe to send- //- // For brand-new conversations Better Agent may never leave 'ready'- // (nothing to load). A single setTimeout(0) on mount flips 'init'- // to 'settled' after the current task queue drains, which lets the- // drain effect fire for that case too.- type HydrationPhase = 'init' | 'hydrating' | 'settled';- const [hydrationPhase, setHydrationPhase] = useState<HydrationPhase>('init');-- useEffect(() => {- setHydrationPhase((prev) => {- if (agent.status !== 'ready') {- return 'hydrating';- }- if (prev === 'hydrating') {- return 'settled';- }- return prev;- });- }, [agent.status]);-- useEffect(() => {- const id = window.setTimeout(() => {- setHydrationPhase((prev) => (prev === 'init' ? 'settled' : prev));- }, 0);- return () => window.clearTimeout(id);- }, []);-- useEffect(() => {- if (hydrationPhase !== 'settled') {- return;- }- if (agent.status !== 'ready') {- return;- }- if (!pendingMessage) {- return;- }- const text = pendingMessage;- // Clear first to prevent re-entry: the effect re-runs when `value`- // rebuilds (it depends on agent state), and without the early null- // guard we'd send twice.- setPendingMessage(null);- value.send(text);- }, [hydrationPhase, agent.status, pendingMessage, setPendingMessage, value]);-- return (- <ChatRuntimeContext.Provider value={value}>- {children}- </ChatRuntimeContext.Provider>- );-}--export function useChatRuntime(): ChatRuntimeValue {- const value = useContext(ChatRuntimeContext);- if (!value) {- throw new Error('useChatRuntime must be used inside <ChatRuntimeProvider>');- }- return value;-}diff --git a/apps/start/src/components/chat/chat-view.tsx b/apps/start/src/components/chat/chat-view.tsxnew file mode 100644index 000000000..848327471--- /dev/null+++ b/apps/start/src/components/chat/chat-view.tsx@@ -0,0 +1,124 @@+import type { ChatLaunchHint } from '@openpanel/core/modules/assistant/assistant.constants';+import {+ type ChatModelEntry,+ isValidModelId,+ MODEL_STORAGE_KEY,+} from '@openpanel/core/modules/assistant/assistant.constants';+import { useCallback, useEffect, useRef, useState } from 'react';+import { ChatComposer } from './chat-composer';+import { ChatEmpty } from './chat-empty';+import { ChatMessages } from './chat-messages';+import type { AssistantUIMessage } from './types';+import { useChatSession } from './use-chat-session';++function readStoredModel(): string | null {+ if (typeof window === 'undefined') {+ return null;+ }+ const stored = window.localStorage.getItem(MODEL_STORAGE_KEY);+ return isValidModelId(stored) ? stored : null;+}++/** The conversation itself: messages and composer. The list and header live in `ChatLayout`. */+export function ChatView({+ conversationId,+ initialMessages,+ initialTitle,+ models,+ defaultModelId,+ hint,+ initialQuestion,+ onFirstMessage,+ onTitleChange,+}: {+ conversationId: string;+ initialMessages: AssistantUIMessage[];+ initialTitle: string | null;+ models: readonly ChatModelEntry[];+ defaultModelId: string | null;+ hint?: ChatLaunchHint;+ /** Sent once on mount; the launcher puts it in the URL. */+ initialQuestion?: string;+ onFirstMessage: () => void;+ onTitleChange: (title: string | null) => void;+}) {+ const [storedModel, setStoredModel] = useState<string | null>(+ readStoredModel+ );+ const modelId =+ storedModel && models.some((model) => model.id === storedModel)+ ? storedModel+ : defaultModelId;+ const selectModel = useCallback((id: string) => {+ setStoredModel(id);+ window.localStorage.setItem(MODEL_STORAGE_KEY, id);+ }, []);++ const session = useChatSession({+ conversationId,+ initialMessages,+ initialTitle,+ modelId,+ hint,+ });+ const { messages, status, sendMessage, stop, regenerate, error, title } =+ session;+ const busy = status === 'submitted' || status === 'streaming';++ const hasMessages = messages.length > 0;++ useEffect(() => {+ onTitleChange(hasMessages ? title : null);+ }, [title, hasMessages, onTitleChange]);++ const send = useCallback(+ (text: string) => {+ if (messages.length === 0) {+ onFirstMessage();+ }+ sendMessage({ text });+ },+ [messages.length, onFirstMessage, sendMessage]+ );++ // The launcher's question is sent exactly once, however the page re-renders.+ const sentInitial = useRef(false);+ useEffect(() => {+ if (initialQuestion && !sentInitial.current && messages.length === 0) {+ sentInitial.current = true;+ send(initialQuestion);+ }+ }, [initialQuestion, messages.length, send]);++ return (+ <>+ {hasMessages ? (+ <ChatMessages+ error={error}+ messages={messages}+ onApproval={(id, approved) =>+ session.addToolApprovalResponse({ id, approved })+ }+ onRetry={() => regenerate()}+ status={status}+ />+ ) : (+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">+ <ChatEmpty hint={hint} onPick={send} />+ </div>+ )}++ <div className="shrink-0 border-t bg-background">+ <ChatComposer+ autoFocus+ busy={busy}+ modelId={modelId}+ models={models}+ onModelChange={selectModel}+ onSend={send}+ onStop={() => stop()}+ />+ </div>+ </>+ );+}diff --git a/apps/start/src/components/chat/model-picker.tsx b/apps/start/src/components/chat/model-picker.tsxdeleted file mode 100644index 68e6ba85d..000000000--- a/apps/start/src/components/chat/model-picker.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { CheckIcon, ChevronDownIcon } from 'lucide-react';-import { useChatState } from './chat-context';-import { type ChatModelOption, getModelLabel } from '@/agents/models';-import { Button } from '@/components/ui/button';-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';--/**- * Model (= agent) picker for the chat header. Each entry corresponds- * to one Better Agent definition; selecting a model swaps to a- * different agent name on the next render.- */-export function ModelPicker() {- const { agentName, setAgent, models } = useChatState();-- const grouped = models.reduce<Record<string, ChatModelOption[]>>((acc, m) => {- (acc[m.group] ??= []).push(m);- return acc;- }, {});-- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- aria-label="Select model"- className="h-7 gap-1 px-2 text-muted-foreground text-xs"- size="sm"- title="Select model"- variant="ghost"- >- <span className="max-w-[140px] truncate">- {getModelLabel(agentName)}- </span>- <ChevronDownIcon className="size-3" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-56">- {Object.entries(grouped).map(([group, items], idx) => (- <div key={group}>- {idx > 0 && <DropdownMenuSeparator />}- <DropdownMenuLabel className="text-[11px] text-muted-foreground uppercase tracking-wide">- {group}- </DropdownMenuLabel>- {items.map((m) => (- <DropdownMenuItem- className="flex items-center justify-between gap-2"- key={m.id}- onSelect={() => setAgent(m.id)}- >- <span className="truncate">{m.label}</span>- {agentName === m.id && (- <CheckIcon className="size-3 shrink-0 text-foreground" />- )}- </DropdownMenuItem>- ))}- </div>- ))}- </DropdownMenuContent>- </DropdownMenu>- );-}diff --git a/apps/start/src/components/chat/parts/approval-card.tsx b/apps/start/src/components/chat/parts/approval-card.tsxnew file mode 100644index 000000000..c8600e3af--- /dev/null+++ b/apps/start/src/components/chat/parts/approval-card.tsx@@ -0,0 +1,56 @@+import { ShieldCheckIcon } from 'lucide-react';+import { approvalPrompt } from '../tool-labels';+import { Button } from '@/components/ui/button';++export function ApprovalCard({+ toolName,+ input,+ onRespond,+}: {+ toolName: string;+ input: unknown;+ onRespond: (approved: boolean) => void;+}) {+ return (+ <div className="rounded-xl border bg-card px-4 py-3">+ <div className="flex items-start gap-2">+ <ShieldCheckIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <div className="font-medium text-sm">+ {approvalPrompt(toolName, input)}+ </div>+ <pre className="mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-all font-mono text-[11px] text-muted-foreground">+ {JSON.stringify(input, null, 2)}+ </pre>+ </div>+ </div>+ <div className="mt-3 flex justify-end gap-2">+ <Button onClick={() => onRespond(false)} size="sm" variant="ghost">+ Cancel+ </Button>+ <Button onClick={() => onRespond(true)} size="sm">+ Confirm+ </Button>+ </div>+ </div>+ );+}++export function ApprovalDecided({+ toolName,+ input,+ approved,+}: {+ toolName: string;+ input: unknown;+ approved: boolean;+}) {+ return (+ <div className="text-muted-foreground text-sm">+ {approvalPrompt(toolName, input)}{' '}+ <span className="font-medium">+ {approved ? 'Confirmed.' : 'Cancelled.'}+ </span>+ </div>+ );+}diff --git a/apps/start/src/components/chat/parts/billing-card.tsx b/apps/start/src/components/chat/parts/billing-card.tsxnew file mode 100644index 000000000..82806b58b--- /dev/null+++ b/apps/start/src/components/chat/parts/billing-card.tsx@@ -0,0 +1,118 @@+import { Link } from '@tanstack/react-router';+import { CreditCardIcon } from 'lucide-react';++export interface BillingOutput {+ selfHosted: boolean;+ organization?: string;+ state?: string;+ statusLine?: string | null;+ plan?: {+ name: string | null;+ free: boolean;+ price: number | null;+ currency: string | null;+ interval: string | null;+ eventsLimit: number | null;+ };+ usage?: {+ eventsThisPeriod: number;+ eventsLimit: number | null;+ percentUsed: number | null;+ periodEnd: string | null;+ };+ assistant?: {+ messagesPerDay: number | null;+ messagesToday: number;+ };+ billingUrl?: string;+}++const number = new Intl.NumberFormat('en-US');+const PERCENT_CAP = 100;++function priceLabel(plan: NonNullable<BillingOutput['plan']>): string {+ if (plan.free) {+ return 'Free';+ }+ if (plan.price === null) {+ return '';+ }+ const amount = new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: plan.currency?.toUpperCase() || 'USD',+ maximumFractionDigits: 2,+ }).format(plan.price);+ return plan.interval ? `${amount} / ${plan.interval}` : amount;+}++export function BillingCard({ output }: { output: BillingOutput }) {+ if (output.selfHosted || !(output.plan && output.usage)) {+ return null;+ }+ const { plan, usage } = output;+ const percent = Math.min(usage.percentUsed ?? 0, PERCENT_CAP);+ const path = output.billingUrl ? new URL(output.billingUrl).pathname : null;++ return (+ <div className="overflow-hidden rounded-xl border bg-card">+ <div className="flex items-center justify-between gap-3 px-4 py-3">+ <div className="flex min-w-0 items-center gap-2">+ <CreditCardIcon className="size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0">+ <div className="truncate font-medium">+ {plan.name ?? 'No plan'}+ {plan.eventsLimit && (+ <span className="ml-2 font-normal text-muted-foreground">+ {number.format(plan.eventsLimit)} events+ </span>+ )}+ </div>+ {output.statusLine && (+ <div className="truncate text-muted-foreground text-xs">+ {output.statusLine}+ </div>+ )}+ </div>+ </div>+ <div className="shrink-0 text-right text-sm">{priceLabel(plan)}</div>+ </div>+ <div className="border-t px-4 py-3">+ <div className="mb-1 flex justify-between text-xs">+ <span className="text-muted-foreground">Used this period</span>+ <span className="font-mono tabular-nums">+ {number.format(usage.eventsThisPeriod)}+ {usage.eventsLimit ? ` / ${number.format(usage.eventsLimit)}` : ''}+ </span>+ </div>+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">+ <div+ className={+ percent >= PERCENT_CAP+ ? 'h-full bg-destructive'+ : 'h-full bg-primary'+ }+ style={{ width: `${percent}%` }}+ />+ </div>+ </div>+ {output.assistant && (+ <div className="flex justify-between border-t px-4 py-2 text-xs">+ <span className="text-muted-foreground">AI messages today</span>+ <span className="font-mono tabular-nums">+ {number.format(output.assistant.messagesToday)}+ {output.assistant.messagesPerDay === null+ ? ''+ : ` / ${number.format(output.assistant.messagesPerDay)}`}+ </span>+ </div>+ )}+ {path && (+ <div className="border-t px-4 py-2 text-xs">+ <Link className="text-primary underline underline-offset-2" to={path}>+ Manage billing+ </Link>+ </div>+ )}+ </div>+ );+}diff --git a/apps/start/src/components/chat/parts/chart-card.tsx b/apps/start/src/components/chat/parts/chart-card.tsxnew file mode 100644index 000000000..87a2c692c--- /dev/null+++ b/apps/start/src/components/chat/parts/chart-card.tsx@@ -0,0 +1,109 @@+import type { IReport } from '@openpanel/core/modules/report/report.constants';+import {+ ExternalLinkIcon,+ MaximizeIcon,+ MinimizeIcon,+ SaveIcon,+} from 'lucide-react';+import { useState } from 'react';+import type { ChartOutput } from '../types';+import { ReportChart } from '@/components/report-chart';+import { Button } from '@/components/ui/button';+import { pushModal } from '@/modals';+import { cn } from '@/utils/cn';++const DATE_LENGTH = 10;++function rangeCaption(report: ChartOutput['report']): string {+ const start = report.startDate?.slice(0, DATE_LENGTH);+ const end = report.endDate?.slice(0, DATE_LENGTH);+ if (start && end) {+ return `${start} to ${end}, by ${report.interval}`;+ }+ return `${report.range}, by ${report.interval}`;+}++/** A chart inline in the conversation: compact by default, expandable, saveable. */+export function ChartCard({ output }: { output: ChartOutput }) {+ const [expanded, setExpanded] = useState(false);+ const { report } = output;+ const isMetric = report.chartType === 'metric';++ return (+ <div className="overflow-hidden rounded-xl border bg-card">+ <div className="flex items-start justify-between gap-2 px-4 pt-3 pb-1">+ <div className="min-w-0">+ <div className="truncate font-medium">{output.title}</div>+ <div className="text-muted-foreground text-xs">+ {rangeCaption(report)}+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {output.dashboardUrl && (+ <Button+ aria-label="Open report"+ asChild+ className="size-7"+ size="icon"+ variant="ghost"+ >+ <a+ href={output.dashboardUrl}+ rel="noopener noreferrer"+ target="_blank"+ >+ <ExternalLinkIcon className="size-3.5" />+ </a>+ </Button>+ )}+ {!report.id && (+ <Button+ aria-label="Save to dashboard"+ className="size-7"+ onClick={() =>+ pushModal('SaveReport', {+ report: {+ ...report,+ name: output.title,+ } as unknown as IReport,+ disableRedirect: true,+ })+ }+ size="icon"+ variant="ghost"+ >+ <SaveIcon className="size-3.5" />+ </Button>+ )}+ {!isMetric && (+ <Button+ aria-label={expanded ? 'Shrink chart' : 'Expand chart'}+ className="size-7"+ onClick={() => setExpanded((value) => !value)}+ size="icon"+ variant="ghost"+ >+ {expanded ? (+ <MinimizeIcon className="size-3.5" />+ ) : (+ <MaximizeIcon className="size-3.5" />+ )}+ </Button>+ )}+ </div>+ </div>+ <div className={cn('px-2 pb-2', isMetric && 'px-4 pb-4')}>+ <ReportChart+ lazy={false}+ options={{+ hideTable: !expanded,+ hideLegend: false,+ minHeight: expanded ? 360 : 220,+ maxHeight: expanded ? 520 : 300,+ }}+ report={report}+ />+ </div>+ </div>+ );+}diff --git a/apps/start/src/components/chat/parts/diagnosis-card.tsx b/apps/start/src/components/chat/parts/diagnosis-card.tsxnew file mode 100644index 000000000..321d2ba6c--- /dev/null+++ b/apps/start/src/components/chat/parts/diagnosis-card.tsx@@ -0,0 +1,99 @@+import { Link } from '@tanstack/react-router';+import {+ AlertTriangleIcon,+ CheckIcon,+ InfoIcon,+ XCircleIcon,+} from 'lucide-react';++interface Finding {+ level: 'ok' | 'warn' | 'error' | 'info';+ check: string;+ message: string;+}++export interface DiagnosisOutput {+ url: string;+ status: 'healthy' | 'warnings' | 'issues';+ findings: Finding[];+ settingsUrl?: string;+}++const STATUS_LABELS: Record<DiagnosisOutput['status'], string> = {+ healthy: 'Looks good',+ warnings: 'Worth a look',+ issues: 'Needs attention',+};++const STATUS_STYLES: Record<DiagnosisOutput['status'], string> = {+ healthy:+ 'rounded-full bg-emerald-500/10 px-2 py-0.5 text-emerald-600 text-xs',+ warnings: 'rounded-full bg-amber-500/10 px-2 py-0.5 text-amber-600 text-xs',+ issues: 'rounded-full bg-destructive/10 px-2 py-0.5 text-destructive text-xs',+};++function LevelIcon({ level }: { level: Finding['level'] }) {+ switch (level) {+ case 'ok':+ return <CheckIcon className="size-4 shrink-0 text-emerald-500" />;+ case 'warn':+ return <AlertTriangleIcon className="size-4 shrink-0 text-amber-500" />;+ case 'error':+ return <XCircleIcon className="size-4 shrink-0 text-destructive" />;+ default:+ return <InfoIcon className="size-4 shrink-0 text-muted-foreground" />;+ }+}++/** The tracking checklist: one line per check, problems first. */+export function DiagnosisCard({ output }: { output: DiagnosisOutput }) {+ const order: Record<Finding['level'], number> = {+ error: 0,+ warn: 1,+ info: 2,+ ok: 3,+ };+ const findings = [...output.findings].sort(+ (a, b) => order[a.level] - order[b.level]+ );+ const settingsPath = output.settingsUrl+ ? new URL(output.settingsUrl).pathname+ : null;++ return (+ <div className="overflow-hidden rounded-xl border bg-card">+ <div className="flex items-center justify-between gap-2 border-b px-4 py-2">+ <div className="min-w-0">+ <div className="font-medium text-sm">Tracking check</div>+ <div className="truncate text-muted-foreground text-xs">+ {output.url}+ </div>+ </div>+ <span className={STATUS_STYLES[output.status]}>+ {STATUS_LABELS[output.status]}+ </span>+ </div>+ <ul className="divide-y">+ {findings.map((finding) => (+ <li+ className="flex items-start gap-2 px-4 py-2 text-sm"+ key={`${finding.check}-${finding.message}`}+ >+ <LevelIcon level={finding.level} />+ <span className="min-w-0">{finding.message}</span>+ </li>+ ))}+ </ul>+ {settingsPath && output.status !== 'healthy' && (+ <div className="border-t px-4 py-2 text-xs">+ <Link+ className="text-primary underline underline-offset-2"+ to={settingsPath}+ >+ Open project settings+ </Link>+ </div>+ )}+ </div>+ );+}diff --git a/apps/start/src/components/chat/parts/result-cards.tsx b/apps/start/src/components/chat/parts/result-cards.tsxnew file mode 100644index 000000000..4a703342b--- /dev/null+++ b/apps/start/src/components/chat/parts/result-cards.tsx@@ -0,0 +1,167 @@+import type {+ NavigateInput,+ OpenDialogInput,+} from '@openpanel/core/modules/assistant/assistant.constants';+import {+ CHAT_DIALOGS,+ CHAT_ROUTES,+} from '@openpanel/core/modules/assistant/assistant.constants';+import { Link } from '@tanstack/react-router';+import { ArrowRightIcon, BookOpenIcon, PlusIcon, UserIcon } from 'lucide-react';+import { openDialog } from '../use-chat-session';++export function NavigateCard({+ input,+ output,+}: {+ input: NavigateInput;+ output?: { opened?: string };+}) {+ const route = CHAT_ROUTES[input.route];+ const href = output?.opened;+ const label = input.reason ?? `Open ${route?.label ?? input.route}`;+ if (!href) {+ return null;+ }+ return (+ <Link+ className="inline-flex items-center gap-2 rounded-lg border bg-card px-3 py-2 font-medium text-sm transition-colors hover:bg-muted/60"+ to={href}+ >+ {label}+ <ArrowRightIcon className="size-3.5 text-muted-foreground" />+ </Link>+ );+}++export function DialogCard({ input }: { input: OpenDialogInput }) {+ const label = CHAT_DIALOGS[input.dialog]?.label ?? input.dialog;+ return (+ <button+ className="inline-flex items-center gap-2 rounded-lg border bg-card px-3 py-2 font-medium text-sm transition-colors hover:bg-muted/60"+ onClick={() => openDialog(input)}+ type="button"+ >+ <PlusIcon className="size-3.5 text-muted-foreground" />+ {label}+ </button>+ );+}++interface DocResult {+ title: string;+ url: string;+}++export function DocsCard({ results }: { results: DocResult[] }) {+ if (results.length === 0) {+ return null;+ }+ return (+ <div className="rounded-xl border bg-card px-4 py-2 text-sm">+ <div className="mb-1 text-muted-foreground text-xs">From the docs</div>+ <ul className="space-y-1">+ {results.map((result) => (+ <li key={result.url}>+ <a+ className="inline-flex items-center gap-1.5 hover:underline"+ href={result.url}+ rel="noopener noreferrer"+ target="_blank"+ >+ <BookOpenIcon className="size-3.5 text-muted-foreground" />+ {result.title}+ </a>+ </li>+ ))}+ </ul>+ </div>+ );+}++interface ProfileHit {+ id: string;+ email?: string;+ name?: string;+ url: string;+}++export function SearchCard({+ profiles,+ session,+ eventNames,+}: {+ profiles: ProfileHit[];+ session: { url: string } | null;+ eventNames: string[];+}) {+ const empty = profiles.length === 0 && !session && eventNames.length === 0;+ if (empty) {+ return (+ <div className="rounded-xl border bg-card px-4 py-2 text-muted-foreground text-sm">+ Nothing matched.+ </div>+ );+ }+ return (+ <div className="rounded-xl border bg-card px-4 py-2 text-sm">+ {profiles.length > 0 && (+ <ul className="space-y-1">+ {profiles.map((profile) => (+ <li key={profile.id}>+ <a+ className="inline-flex items-center gap-1.5 hover:underline"+ href={profile.url}+ >+ <UserIcon className="size-3.5 text-muted-foreground" />+ {profile.name || profile.email || profile.id}+ {profile.email && profile.name && (+ <span className="text-muted-foreground">{profile.email}</span>+ )}+ </a>+ </li>+ ))}+ </ul>+ )}+ {session && (+ <a+ className="mt-1 inline-flex items-center gap-1.5 hover:underline"+ href={session.url}+ >+ <ArrowRightIcon className="size-3.5 text-muted-foreground" />+ Open session+ </a>+ )}+ {eventNames.length > 0 && (+ <div className="mt-1 text-muted-foreground">+ Events: {eventNames.join(', ')}+ </div>+ )}+ </div>+ );+}++export function PlanChangeCard({+ output,+}: {+ output: { checkoutUrl?: string; changed?: boolean };+}) {+ if (output.checkoutUrl) {+ return (+ <a+ className="inline-flex items-center gap-2 rounded-lg border bg-card px-3 py-2 font-medium text-sm transition-colors hover:bg-muted/60"+ href={output.checkoutUrl}+ rel="noopener noreferrer"+ target="_blank"+ >+ Continue to checkout+ <ArrowRightIcon className="size-3.5 text-muted-foreground" />+ </a>+ );+ }+ return (+ <div className="rounded-lg border bg-card px-3 py-2 text-sm">+ Plan changed. Billing is prorated from today.+ </div>+ );+}diff --git a/apps/start/src/components/chat/parts/table-card.tsx b/apps/start/src/components/chat/parts/table-card.tsxnew file mode 100644index 000000000..3b3614b32--- /dev/null+++ b/apps/start/src/components/chat/parts/table-card.tsx@@ -0,0 +1,138 @@+import { useState } from 'react';+import { cn } from '@/utils/cn';++const COLLAPSED_ROWS = 8;+const MAX_COLUMNS = 6;+const numberFormat = new Intl.NumberFormat('en-US', {+ maximumFractionDigits: 2,+});++function cell(value: unknown): string {+ // An empty dimension (no UTM, no referrer) reads better named than blank.+ if (value === null || value === undefined || value === '') {+ return '(none)';+ }+ if (typeof value === 'number') {+ return numberFormat.format(value);+ }+ if (typeof value === 'object') {+ return JSON.stringify(value);+ }+ return String(value);+}++function humanize(key: string): string {+ return key.replace(/_/g, ' ');+}++/** Rows from a tool, as a compact table with a "show all" toggle. */+export function TableCard({+ title,+ rows,+ total,+ preferredColumns,+ onRowClick,+}: {+ title: string;+ rows: Record<string, unknown>[];+ total?: number;+ /** Shown first when present in the rows; the rest fill up to the column cap. */+ preferredColumns?: string[];+ onRowClick?: (row: Record<string, unknown>) => void;+}) {+ const [showAll, setShowAll] = useState(false);+ const available = Object.keys(rows[0] ?? {}).filter(+ (key) => !key.startsWith('__') && key !== 'url'+ );+ const preferred = (preferredColumns ?? []).filter((key) =>+ available.includes(key)+ );+ const columns = [+ ...preferred,+ ...available.filter((key) => !preferred.includes(key)),+ ].slice(0, Math.max(MAX_COLUMNS, preferred.length));+ const visible = showAll ? rows : rows.slice(0, COLLAPSED_ROWS);+ const hidden = rows.length - visible.length;++ if (rows.length === 0) {+ return (+ <div className="rounded-xl border bg-card px-4 py-3 text-muted-foreground text-sm">+ {title}: no rows.+ </div>+ );+ }++ return (+ <div className="overflow-hidden rounded-xl border bg-card">+ <div className="flex items-center justify-between px-4 py-2 text-sm">+ <span className="font-medium">{title}</span>+ <span className="text-muted-foreground text-xs">+ {total && total > rows.length+ ? `${rows.length} of ${total}`+ : `${rows.length} rows`}+ </span>+ </div>+ <div className="overflow-x-auto border-t">+ <table className="w-full text-sm">+ <thead>+ <tr className="text-left text-muted-foreground text-xs">+ {columns.map((column) => (+ <th+ className="whitespace-nowrap px-3 py-1.5 font-medium"+ key={column}+ >+ {humanize(column)}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {visible.map((row, index) => (+ <tr+ className={cn(+ 'border-t',+ onRowClick && 'cursor-pointer hover:bg-muted/50'+ )}+ key={`${index}-${cell(row[columns[0] ?? ''])}`}+ onClick={onRowClick ? () => onRowClick(row) : undefined}+ onKeyDown={+ onRowClick+ ? (event) => {+ if (event.key === 'Enter') {+ onRowClick(row);+ }+ }+ : undefined+ }+ tabIndex={onRowClick ? 0 : undefined}+ >+ {columns.map((column) => (+ <td+ className={cn(+ 'max-w-[260px] truncate px-3 py-1.5',+ typeof row[column] === 'number' &&+ 'text-right font-mono tabular-nums'+ )}+ key={column}+ title={cell(row[column])}+ >+ {cell(row[column])}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ {hidden > 0 && (+ <button+ className="w-full border-t px-4 py-1.5 text-muted-foreground text-xs hover:bg-muted/50"+ onClick={() => setShowAll(true)}+ type="button"+ >+ Show {hidden} more+ </button>+ )}+ </div>+ );+}diff --git a/apps/start/src/components/chat/parts/tool-activity-group.tsx b/apps/start/src/components/chat/parts/tool-activity-group.tsxnew file mode 100644index 000000000..9dc454b73--- /dev/null+++ b/apps/start/src/components/chat/parts/tool-activity-group.tsx@@ -0,0 +1,192 @@+import { getToolName, isToolUIPart } from 'ai';+import {+ AlertCircleIcon,+ CheckIcon,+ ChevronRightIcon,+ Loader2Icon,+} from 'lucide-react';+import { useState } from 'react';+import { toolPhrase } from '../tool-labels';+import type { AssistantUIMessagePart } from '../types';+import { cn } from '@/utils/cn';++export type ToolPart = Extract<AssistantUIMessagePart, { toolCallId: string }>;++const MAX_DETAIL_CHARS = 8000;++type ItemStatus = 'running' | 'done' | 'error';++function statusOf(part: ToolPart): ItemStatus {+ switch (part.state) {+ case 'output-available':+ return 'done';+ case 'output-error':+ return 'error';+ default:+ return 'running';+ }+}++function labelOf(part: ToolPart, status: ItemStatus): string {+ const name = getToolName(part);+ if (status === 'running') {+ return toolPhrase(name, 'active');+ }+ if (status === 'error') {+ return `${toolPhrase(name, 'active')} failed`;+ }+ if (name === 'list_references') {+ const rows = (part.output as { rows?: unknown[] } | undefined)?.rows;+ if (Array.isArray(rows) && rows.length === 0) {+ return 'No references in this window';+ }+ }+ if (name === 'search') {+ return 'Nothing matched the search';+ }+ return toolPhrase(name, 'done');+}++function detailsOf(part: ToolPart): string {+ const payload =+ part.state === 'output-error'+ ? { input: part.input, error: part.errorText }+ : { input: part.input, output: part.output };+ const serialized = JSON.stringify(payload, null, 2) ?? '';+ return serialized.length > MAX_DETAIL_CHARS+ ? `${serialized.slice(0, MAX_DETAIL_CHARS)}…`+ : serialized;+}++function StatusIcon({ status }: { status: ItemStatus }) {+ if (status === 'running') {+ return <Loader2Icon className="size-3 animate-spin" />;+ }+ if (status === 'error') {+ return <AlertCircleIcon className="size-3 text-destructive" />;+ }+ return <CheckIcon className="size-3 text-emerald-500" />;+}++/**+ * A run of plain tool calls as one quiet line: what the assistant did, in+ * order, expanding to the raw inputs and outputs when asked.+ */+export function ToolActivityGroup({ parts }: { parts: ToolPart[] }) {+ const [open, setOpen] = useState(false);+ const items = parts.map((part) => {+ const status = statusOf(part);+ return { part, status, label: labelOf(part, status) };+ });+ const anyRunning = items.some((item) => item.status === 'running');++ return (+ <div className="text-xs">+ <button+ aria-expanded={open}+ className="group inline-flex max-w-full flex-wrap items-center gap-x-1.5 gap-y-1 text-left text-muted-foreground transition-colors hover:text-foreground"+ onClick={() => setOpen((value) => !value)}+ type="button"+ >+ {items.map((item, index) => (+ <span+ className="inline-flex items-center gap-1"+ key={item.part.toolCallId}+ >+ {index > 0 && <span className="text-muted-foreground/50">·</span>}+ <StatusIcon status={item.status} />+ <span+ className={cn(+ item.status === 'running' && 'op-shimmer font-medium'+ )}+ >+ {item.label}+ </span>+ </span>+ ))}+ {!anyRunning && (+ <ChevronRightIcon+ className={cn('size-3 transition-transform', open && 'rotate-90')}+ />+ )}+ </button>+ {open && (+ <div className="mt-2 space-y-2">+ {items.map((item) => (+ <details+ className="rounded-lg border bg-muted/20"+ key={item.part.toolCallId}+ >+ <summary className="cursor-pointer px-2.5 py-1.5 font-medium text-foreground/80">+ {getToolName(item.part)}+ {item.status === 'error' &&+ item.part.state === 'output-error' && (+ <span className="ml-2 font-normal text-destructive">+ {item.part.errorText}+ </span>+ )}+ </summary>+ <pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all border-t px-2.5 py-2 font-mono text-[11px]">+ {detailsOf(item.part)}+ </pre>+ </details>+ ))}+ </div>+ )}+ </div>+ );+}++/** Tool parts that get their own card instead of a line in the activity group. */+export function isRichToolPart(part: AssistantUIMessagePart): boolean {+ if (!isToolUIPart(part)) {+ return false;+ }+ if (+ part.state === 'approval-requested' ||+ part.state === 'approval-responded' ||+ part.state === 'output-denied'+ ) {+ return true;+ }+ if (part.state !== 'output-available') {+ return false;+ }+ const name = getToolName(part);+ const output = part.output as Record<string, unknown> | unknown[] | undefined;+ if (name === 'search') {+ const hit = output as+ | { profiles?: unknown[]; session?: unknown; eventNames?: unknown[] }+ | undefined;+ return Boolean(+ hit?.session || hit?.profiles?.length || hit?.eventNames?.length+ );+ }+ if (+ [+ 'navigate',+ 'open_dialog',+ 'search_docs',+ 'search',+ 'diagnose_tracking',+ 'get_billing',+ 'change_plan',+ ].includes(name)+ ) {+ return true;+ }+ if (Array.isArray(output)) {+ return output.length > 0;+ }+ if (typeof output !== 'object' || output === null) {+ return false;+ }+ if ('error' in output) {+ return true;+ }+ if ('report' in output) {+ return true;+ }+ const rows = (output as { rows?: unknown }).rows;+ return Array.isArray(rows) && rows.length > 0;+}diff --git a/apps/start/src/components/chat/parts/tool-card.tsx b/apps/start/src/components/chat/parts/tool-card.tsxnew file mode 100644index 000000000..d9afe262e--- /dev/null+++ b/apps/start/src/components/chat/parts/tool-card.tsx@@ -0,0 +1,77 @@+import {+ AlertCircleIcon,+ CheckIcon,+ ChevronRightIcon,+ SparklesIcon,+} from 'lucide-react';+import { useState } from 'react';+import { toolPhrase } from '../tool-labels';++export function ToolActivity({ toolName }: { toolName: string }) {+ return (+ <div className="flex items-center gap-2 py-1 text-sm">+ <SparklesIcon className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="op-shimmer font-medium">+ {toolPhrase(toolName, 'active')}…+ </span>+ </div>+ );+}++export function ToolError({+ toolName,+ message,+}: {+ toolName: string;+ message?: string;+}) {+ return (+ <div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm">+ <AlertCircleIcon className="mt-0.5 size-3.5 shrink-0" />+ <span>+ {toolPhrase(toolName, 'active')} failed{message ? `: ${message}` : '.'}+ </span>+ </div>+ );+}++const MAX_PREVIEW_CHARS = 12_000;++/** A finished tool without a dedicated card: a chip that opens to the raw result. */+export function ToolDone({+ toolName,+ output,+}: {+ toolName: string;+ output: unknown;+}) {+ const [open, setOpen] = useState(false);+ const serialized = JSON.stringify(output, null, 2) ?? '';+ const preview =+ serialized.length > MAX_PREVIEW_CHARS+ ? `${serialized.slice(0, MAX_PREVIEW_CHARS)}…`+ : serialized;++ return (+ <div className="inline-flex max-w-full flex-col rounded-lg border bg-card text-sm">+ <button+ className="flex items-center gap-2 px-2.5 py-1.5 text-left"+ onClick={() => setOpen((value) => !value)}+ type="button"+ >+ <CheckIcon className="size-3.5 shrink-0 text-emerald-500" />+ <span className="font-medium text-foreground/80">+ {toolPhrase(toolName, 'done')}+ </span>+ <ChevronRightIcon+ className={`size-3 text-muted-foreground transition-transform ${open ? 'rotate-90' : ''}`}+ />+ </button>+ {open && (+ <pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all border-t bg-muted/20 px-2.5 py-2 font-mono text-[11px]">+ {preview}+ </pre>+ )}+ </div>+ );+}diff --git a/apps/start/src/components/chat/sidebar-chat-composer.tsx b/apps/start/src/components/chat/sidebar-chat-composer.tsxindex 814d4b662..1beaaafc3 100644--- a/apps/start/src/components/chat/sidebar-chat-composer.tsx+++ b/apps/start/src/components/chat/sidebar-chat-composer.tsx@@ -1,34 +1,18 @@import { ArrowUpIcon, SparklesIcon } from 'lucide-react';import { useState } from 'react';-import { useChatState } from './chat-context';+import { useChatLaunch } from './chat-launch';import { Button } from '@/components/ui/button';import { cn } from '@/utils/cn';-/**- * Compact "Ask AI" composer for the sidebar.- *- * Single-row layout:- * [✨] Ask AI anything… [⌘J] | [↑ send]- *- * The trailing slot shows the keyboard-shortcut hint while the input- * is empty and swaps to a send button the moment the user starts- * typing. Submitting stashes the draft on `chatState.pendingMessage`- * and opens a fresh conversation — the drawer's runtime drains the- * pending message once `useAgent` is ready.- */+/** The sidebar's one-line "Ask AI" box; submitting opens the chat page with the question. */export function SidebarChatComposer() {- const { setPendingMessage, openNewChat } = useChatState();+ const launch = useChatLaunch();const [text, setText] = useState('');const hasText = text.trim().length > 0;- const submit = (e?: React.FormEvent) => {- e?.preventDefault();- const value = text.trim();- if (!value) {- return;- }- setPendingMessage(value);- openNewChat();+ const submit = (event?: React.FormEvent) => {+ event?.preventDefault();+ launch(text);setText('');};@@ -48,10 +32,10 @@ export function SidebarChatComposer() {'border-0 shadow-none outline-none ring-0','focus:outline-none focus:ring-0 focus-visible:outline-none focus-visible:ring-0')}- onChange={(e) => setText(e.target.value)}- onKeyDown={(e) => {- if (e.key === 'Enter') {- e.preventDefault();+ onChange={(event) => setText(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ event.preventDefault();submit();}}}@@ -70,16 +54,17 @@ export function SidebarChatComposer() {<ArrowUpIcon className="size-3.5" /></Button>) : (- <kbd- aria-label="Keyboard shortcut: Cmd+J"+ <button+ aria-label="Open the chat (Cmd+J)"className={cn('shrink-0 rounded border border-border bg-def-200 px-1.5 py-0.5 font-mono text-[11px]','cursor-pointer text-muted-foreground')}- onClick={() => openNewChat()}+ onClick={() => launch()}+ type="button">⌘J- </kbd>+ </button>)}</form>);diff --git a/apps/start/src/components/chat/title-stream.tsx b/apps/start/src/components/chat/title-stream.tsxdeleted file mode 100644index 4fd3df46a..000000000--- a/apps/start/src/components/chat/title-stream.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { CONVERSATION_TITLE_MAX_LENGTH } from '@openpanel/core/modules/conversation/conversation.constants';-import type { AppClient } from '@/agents/client';--/**- * Stream a conversation title from the backend `__titler` agent.- *- * Calls `onDelta(fullText)` after every text event so the caller can- * render the title as it's generated. Returns the final accumulated- * title string (trimmed), or null if nothing useful was produced.- *- * Pass an `AbortSignal` to cancel an in-flight stream (e.g. when the- * user switches or closes the conversation before the title finishes).- * Once aborted the function returns null and stops calling `onDelta`.- *- * Fails silently — titles are non-critical; the header just falls- * back to "Untitled chat" or the persisted DB value.- */-export async function streamTitle(- client: AppClient,- firstUserText: string,- onDelta: (text: string) => void,- signal?: AbortSignal-): Promise<string | null> {- const trimmed = firstUserText.trim().slice(0, 400);- if (!trimmed) {- return null;- }- if (signal?.aborted) {- return null;- }-- let accumulated = '';- try {- const iterable = client.stream('__titler', {- input: `Generate a 3-5 word title for a chat that started with: "${trimmed}"`,- // biome-ignore lint/suspicious/noExplicitAny: titler agent has no typed context; its run-input shape is generic- } as any);- for await (const event of iterable) {- if (signal?.aborted) {- return null;- }- // Better Agent emits `TEXT_MESSAGE_CONTENT` with a `delta` field- // for each streamed chunk of assistant text.- const maybe = event as { type?: string; delta?: string };- if (- maybe.type === 'TEXT_MESSAGE_CONTENT' &&- typeof maybe.delta === 'string'- ) {- accumulated += maybe.delta;- onDelta(accumulated.trim().slice(0, CONVERSATION_TITLE_MAX_LENGTH));- }- }- if (signal?.aborted) {- return null;- }- return accumulated.trim().slice(0, CONVERSATION_TITLE_MAX_LENGTH) || null;- } catch (err) {- console.error('[chat] title stream failed', err);- return null;- }-}diff --git a/apps/start/src/components/chat/tool-handlers.ts b/apps/start/src/components/chat/tool-handlers.tsdeleted file mode 100644index 191471c6d..000000000--- a/apps/start/src/components/chat/tool-handlers.ts+++ /dev/null@@ -1,189 +0,0 @@-import type {- ApplyFiltersInput,- ChatClientToolHandlers,- SetEventNamesFilterInput,- SetPropertyFiltersInput,-} from '@openpanel/core/modules/assistant/assistant.constants';--/**- * Client-side handlers for tools the LLM can invoke to mutate page- * state. Better Agent emits these as `tool-call` parts with no server- * execution; the controller forwards each call to the matching entry- * here, and the return value is sent back as the tool's `output`.- *- * Keep handlers tiny and side-effect-only — they shouldn't render UI- * or maintain state of their own.- *- * URL params we mutate map 1:1 to what the dashboard hooks read:- * - `range`, `start`, `end`, `overrideInterval` ← `useOverviewOptions`- * - `events` ← `useEventQueryNamesFilter`- * - `f` ← `useEventQueryFilters`- *- * After mutating the URL we dispatch a `popstate` event so nuqs picks- * up the change without a hook subscription on our side.- *- * Handler types come from `@openpanel/core`'s assistant.constants (shared- * with the server's tool schemas) so the map stays in sync with the Zod inputs- * without crossing the app boundary for its type.- */--type PropertyFilter = SetPropertyFiltersInput['filters'][number];--function pushUrl(url: URL): void {- window.history.pushState(null, '', url.toString());- window.dispatchEvent(new PopStateEvent('popstate'));-}--// Each of these mutates a URL rather than navigating, so one command that-// changes a range AND a filter results in one history entry and one round of-// queries instead of two or three.-function applyFiltersToUrl(- url: URL,- input: Omit<ApplyFiltersInput, 'range'> & { range?: string }-): void {- if (input.startDate && input.endDate) {- url.searchParams.set('range', 'custom');- url.searchParams.set('start', input.startDate);- url.searchParams.set('end', input.endDate);- } else if (input.range) {- url.searchParams.set('range', input.range);- url.searchParams.delete('start');- url.searchParams.delete('end');- }-- if (input.interval) {- url.searchParams.set('overrideInterval', input.interval);- }-}--function setPropertyFiltersOnUrl(- url: URL,- input: {- filters: (Omit<PropertyFilter, 'operator'> & { operator?: string })[];- }-): void {- if (input.filters.length === 0) {- url.searchParams.delete('f');- } else {- url.searchParams.set('f', serializePropertyFilters(input.filters));- }-}--function setEventNamesFilterOnUrl(- url: URL,- input: SetEventNamesFilterInput-): void {- if (input.eventNames.length === 0) {- url.searchParams.delete('events');- } else {- // nuqs `parseAsArrayOf(parseAsString)` defaults to comma-separated.- url.searchParams.set('events', input.eventNames.join(','));- }-}--function applyFilters(input: ApplyFiltersInput): {- applied: boolean;- applied_filters: ApplyFiltersInput;-} {- if (typeof window === 'undefined') {- return { applied: false, applied_filters: input };- }- const url = new URL(window.location.href);- applyFiltersToUrl(url, input);- pushUrl(url);- return { applied: true, applied_filters: input };-}--/**- * Mirrors the serializer in `useEventQueryFilters` — each filter is- * `name,operator,value1|value2`, joined by `;`. We URL-encode the- * values to match the parser.- */-function serializePropertyFilters(- filters: (Omit<PropertyFilter, 'operator'> & { operator?: string })[]-): string {- return filters- .map((f) => {- const op = f.operator ?? 'is';- const values = f.value.map((v) => encodeURIComponent(v.trim())).join('|');- return `${f.name},${op},${values}`;- })- .join(';');-}--function setPropertyFilters(input: SetPropertyFiltersInput): {- applied: boolean;- count: number;-} {- if (typeof window === 'undefined') {- return { applied: false, count: 0 };- }- const url = new URL(window.location.href);- setPropertyFiltersOnUrl(url, input);- pushUrl(url);- return { applied: true, count: input.filters.length };-}--function setEventNamesFilter(input: SetEventNamesFilterInput): {- applied: boolean;- count: number;-} {- if (typeof window === 'undefined') {- return { applied: false, count: 0 };- }- const url = new URL(window.location.href);- setEventNamesFilterOnUrl(url, input);- pushUrl(url);- return { applied: true, count: input.eventNames.length };-}--export const chatToolHandlers: ChatClientToolHandlers = {- apply_filters: async (input) => applyFilters(input as ApplyFiltersInput),- set_property_filters: async (input) =>- setPropertyFilters(input as SetPropertyFiltersInput),- set_event_names_filter: async (input) =>- setEventNamesFilter(input as SetEventNamesFilterInput),-};--/**- * Applies every part of one filter command in a single navigation.- *- * One navigation, so a command like "last 30 days, mobile only" pushes one- * history entry and runs the overview queries once.- */-export function applyFilterCommandToUrl(command: {- // `range` and `operator` are widened to `string` on purpose.- // `overview.runFilterCommand` validates against the canonical `zRange` and- // operator list, while the chat tool's own schemas in assistant.constants.ts- // hand-list subsets: they are missing `last24h` and `3m` for range, and- // `inCohort`/`notInCohort` for operator. Both values are written verbatim- // into search params that the overview's own parsers then validate, so the- // wider types are correct here and keep the drift visible.- applyFilters?: (Omit<ApplyFiltersInput, 'range'> & { range?: string }) | null;- setPropertyFilters?: {- filters: (Omit<PropertyFilter, 'operator'> & { operator?: string })[];- } | null;- setEventNamesFilter?: SetEventNamesFilterInput | null;-}): number {- if (typeof window === 'undefined') {- return 0;- }- const url = new URL(window.location.href);- let applied = 0;- if (command.applyFilters) {- applyFiltersToUrl(url, command.applyFilters);- applied += 1;- }- if (command.setPropertyFilters) {- setPropertyFiltersOnUrl(url, command.setPropertyFilters);- applied += 1;- }- if (command.setEventNamesFilter) {- setEventNamesFilterOnUrl(url, command.setEventNamesFilter);- applied += 1;- }- if (applied > 0) {- pushUrl(url);- }- return applied;-}diff --git a/apps/start/src/components/chat/tool-labels.ts b/apps/start/src/components/chat/tool-labels.tsnew file mode 100644index 000000000..4110dd8aa--- /dev/null+++ b/apps/start/src/components/chat/tool-labels.ts@@ -0,0 +1,110 @@+/** What the chat says while a tool runs and once it is done. */+const TOOL_PHRASES: Record<string, { active: string; done: string }> = {+ describe_data: {+ active: 'Looking at what is tracked',+ done: 'Checked the tracked events',+ },+ get_property_values: {+ active: 'Listing property values',+ done: 'Listed property values',+ },+ get_overview: {+ active: 'Fetching the overview',+ done: 'Fetched the overview',+ },+ get_traffic_attribution: {+ active: 'Attributing traffic',+ done: 'Attribution ready',+ },+ get_breakdown: {+ active: 'Breaking down the traffic',+ done: 'Breakdown fetched',+ },+ query_events: { active: 'Querying events', done: 'Events queried' },+ query_sessions: { active: 'Querying sessions', done: 'Sessions queried' },+ get_active_users: {+ active: 'Counting active users',+ done: 'Active users counted',+ },+ get_funnel: { active: 'Running the funnel', done: 'Funnel ready' },+ get_retention: { active: 'Computing retention', done: 'Retention ready' },+ get_user_flow: { active: 'Tracing user flows', done: 'User flow ready' },+ create_chart: { active: 'Building a chart', done: 'Chart ready' },+ get_report: { active: 'Running the report', done: 'Report ready' },+ search: { active: 'Searching', done: 'Search done' },+ get_profile: { active: 'Loading the profile', done: 'Profile loaded' },+ get_session: { active: 'Loading the session', done: 'Session loaded' },+ list_references: {+ active: 'Checking references',+ done: 'References checked',+ },+ gsc_overview: {+ active: 'Fetching Search Console',+ done: 'Search Console fetched',+ },+ gsc_top_queries: {+ active: 'Fetching top queries',+ done: 'Top queries fetched',+ },+ gsc_top_pages: { active: 'Fetching top pages', done: 'Top pages fetched' },+ gsc_opportunities: {+ active: 'Finding SEO opportunities',+ done: 'SEO opportunities found',+ },+ gsc_cannibalization: {+ active: 'Checking cannibalization',+ done: 'Cannibalization checked',+ },+ list_dashboards: { active: 'Listing dashboards', done: 'Dashboards listed' },+ list_reports: { active: 'Listing reports', done: 'Reports listed' },+ create_dashboard: {+ active: 'Creating the dashboard',+ done: 'Dashboard created',+ },+ save_chart: { active: 'Saving the chart', done: 'Chart saved' },+ create_reference: { active: 'Adding the reference', done: 'Reference added' },+ invite_member: { active: 'Sending the invite', done: 'Invite sent' },+ update_project: { active: 'Updating the project', done: 'Project updated' },+ search_docs: { active: 'Reading the docs', done: 'Docs checked' },+ get_billing: { active: 'Looking up the plan', done: 'Plan looked up' },+ list_plans: { active: 'Listing plans', done: 'Plans listed' },+ change_plan: { active: 'Changing the plan', done: 'Plan changed' },+ diagnose_tracking: {+ active: 'Checking the tracking setup',+ done: 'Tracking checked',+ },+ navigate: { active: 'Opening the page', done: 'Opened' },+ open_dialog: { active: 'Opening the dialog', done: 'Dialog opened' },+};++export function toolPhrase(toolName: string, phase: 'active' | 'done'): string {+ const known = TOOL_PHRASES[toolName];+ if (known) {+ return known[phase];+ }+ const readable = toolName.replace(/_/g, ' ');+ return phase === 'active' ? `Running ${readable}` : `Ran ${readable}`;+}++/** Tools the user needs to approve before they run. */+export function approvalPrompt(toolName: string, input: unknown): string {+ const fields = (input ?? {}) as Record<string, unknown>;+ switch (toolName) {+ case 'create_dashboard':+ return `Create the dashboard "${String(fields.name ?? '')}"?`;+ case 'save_chart': {+ const chart = fields.chart as { title?: string } | undefined;+ return `Save "${chart?.title ?? 'this chart'}" to the dashboard?`;+ }+ case 'create_reference':+ return `Add the reference "${String(fields.title ?? '')}" on ${String(fields.date ?? '')}?`;+ case 'invite_member':+ return `Invite ${String(fields.email ?? '')} as ${String(fields.role ?? 'member')}?`;+ case 'update_project':+ return 'Update the project settings?';+ case 'change_plan':+ return 'Change the workspace plan?';+ default:+ return `Run ${toolName.replace(/_/g, ' ')}?`;+ }+}diff --git a/apps/start/src/components/chat/tool-results/chat-metrics-result.tsx b/apps/start/src/components/chat/tool-results/chat-metrics-result.tsxdeleted file mode 100644index 7d2717882..000000000--- a/apps/start/src/components/chat/tool-results/chat-metrics-result.tsx+++ /dev/null@@ -1,68 +0,0 @@-import { isMetricsLike } from './output-types';-import { ResultCard, ToolStateGuard } from './shared';-import type { ToolResultProps } from './types';--/**- * Renders simple metric grids for tools like `get_analytics_overview`- * and `get_profile_metrics`. Tools return a flat object of named values;- * we render up to 6 of them as labelled tiles.- */-export function ChatMetricsResult({ part }: ToolResultProps) {- return (- <ToolStateGuard- errorText={part.errorText}- state={part.state}- toolName={part.type.replace(/^tool-/, '')}- >- <ChatMetricsInner output={part.output} />- </ToolStateGuard>- );-}--function ChatMetricsInner({ output }: { output: unknown }) {- if (!isMetricsLike(output)) {- return null;- }-- const entries = Object.entries(output).filter(- (entry): entry is [string, number | string] =>- typeof entry[1] === 'number' || typeof entry[1] === 'string'- );- if (entries.length === 0) {- return null;- }-- return (- <ResultCard>- <div className="grid grid-cols-2 divide-x divide-y sm:grid-cols-3">- {entries.slice(0, 6).map(([key, value]) => (- <div className="p-3" key={key}>- <div className="text-[11px] text-muted-foreground uppercase tracking-wide">- {humanize(key)}- </div>- <div className="mt-0.5 font-mono font-semibold text-sm tabular-nums">- {formatValue(value)}- </div>- </div>- ))}- </div>- </ResultCard>- );-}--function humanize(key: string): string {- return key- .replace(/_/g, ' ')- .replace(/([a-z])([A-Z])/g, '$1 $2')- .replace(/^\w/, (c) => c.toUpperCase());-}--function formatValue(v: number | string): string {- if (typeof v === 'number') {- if (Number.isInteger(v)) {- return v.toLocaleString();- }- return v.toFixed(2);- }- return v;-}diff --git a/apps/start/src/components/chat/tool-results/chat-profile-result.tsx b/apps/start/src/components/chat/tool-results/chat-profile-result.tsxdeleted file mode 100644index e1b22546d..000000000--- a/apps/start/src/components/chat/tool-results/chat-profile-result.tsx+++ /dev/null@@ -1,120 +0,0 @@-import {- asProfileFullOutput,- isProfileFullError,- type ProfileFullSuccess,-} from './output-types';-import {- ResultCard,- ResultLabel,- ResultRow,- ResultValue,- ToolStateGuard,-} from './shared';-import type { ToolResultProps } from './types';-import { useNumber } from '@/hooks/use-numer-formatter';--/**- * Renders the result of `get_profile_full` — profile + metrics + recent- * sessions. Card-with-rows layout so it stays narrow-friendly.- */-export function ChatProfileFullResult({ part }: ToolResultProps) {- return (- <ToolStateGuard- errorText={part.errorText}- state={part.state}- toolName={part.type.replace(/^tool-/, '')}- >- <Inner output={part.output} />- </ToolStateGuard>- );-}--function Inner({ output }: { output: unknown }) {- const value = asProfileFullOutput(output);- if (!value) {- return (- <ResultCard>- <div className="px-3 py-2 text-muted-foreground text-sm">- No profile- </div>- </ResultCard>- );- }-- if (isProfileFullError(value)) {- return (- <ResultCard>- <div className="px-3 py-2 text-muted-foreground text-sm">- {value.error}- </div>- </ResultCard>- );- }-- return <SuccessCard value={value} />;-}--function SuccessCard({ value }: { value: ProfileFullSuccess }) {- const number = useNumber();- const { profile, metrics, dashboard_url } = value;- const title =- profile &&- (`${profile.firstName ?? ''} ${profile.lastName ?? ''}`.trim() ||- profile.email ||- profile.id);-- return (- <ResultCard title={title || 'Profile'}>- {metrics && (- <div className="border-b">- {typeof metrics.sessions === 'number' && (- <ResultRow>- <ResultLabel>Sessions</ResultLabel>- <ResultValue>{metrics.sessions}</ResultValue>- </ResultRow>- )}- {typeof metrics.totalEvents === 'number' && (- <ResultRow>- <ResultLabel>Total events</ResultLabel>- <ResultValue>{metrics.totalEvents}</ResultValue>- </ResultRow>- )}- {typeof metrics.avgSessionDurationMin === 'number' && (- <ResultRow>- <ResultLabel>Avg session</ResultLabel>- <ResultValue>- {metrics.avgSessionDurationMin.toFixed(1)} min- </ResultValue>- </ResultRow>- )}- {typeof metrics.bounceRate === 'number' && (- <ResultRow>- <ResultLabel>Bounce rate</ResultLabel>- <ResultValue>- {(metrics.bounceRate * 100).toFixed(0)}%- </ResultValue>- </ResultRow>- )}- {typeof metrics.revenue === 'number' && metrics.revenue > 0 && (- <ResultRow>- <ResultLabel>Revenue</ResultLabel>- <ResultValue>- {number.currency(metrics.revenue / 100)}- </ResultValue>- </ResultRow>- )}- </div>- )}- {dashboard_url && (- <a- className="block px-3 py-1.5 text-muted-foreground text-sm hover:underline"- href={dashboard_url}- rel="noopener noreferrer"- target="_blank"- >- Open profile →- </a>- )}- </ResultCard>- );-}diff --git a/apps/start/src/components/chat/tool-results/chat-report-result.tsx b/apps/start/src/components/chat/tool-results/chat-report-result.tsxdeleted file mode 100644index 131fa92b1..000000000--- a/apps/start/src/components/chat/tool-results/chat-report-result.tsx+++ /dev/null@@ -1,215 +0,0 @@-import type {- IReport,- IReportInput,-} from '@openpanel/core/modules/report/report.constants';-import { SaveIcon } from 'lucide-react';-import { asReportOutput } from './output-types';-import { ResultCard, ToolStateGuard } from './shared';-import type { ToolResultProps } from './types';-import { ReportChart } from '@/components/report-chart';-import { Button } from '@/components/ui/button';-import { pushModal } from '@/modals';--/**- * Renders the result of `get_report_data` / `generate_report` /- * `preview_report_with_changes` / `get_funnel` / `get_rolling_active_users` —- * all return `{ report, data }` we can plug into `<ReportChart>`.- *- * Title priority (first match wins):- * 1. `output.name` if the tool returned one (e.g. a saved report's name)- * 2. A nice derived title from the tool's INPUT args (funnel → "Funnel: A → B", etc.)- * 3. `"<CHART_TYPE> chart"` fallback- */-export function ChatReportResult({ part }: ToolResultProps) {- return (- <ToolStateGuard- errorText={part.errorText}- state={part.state}- toolName={part.type.replace(/^tool-/, '')}- >- <ChatReportInner- input={part.input}- output={part.output}- toolType={part.type}- />- </ToolStateGuard>- );-}--function ChatReportInner({- output,- input,- toolType,-}: {- output: unknown;- input: unknown;- toolType: string;-}) {- const value = asReportOutput(output);- if (!value || value.error) {- return (- <ResultCard>- <div className="px-3 py-2 text-muted-foreground text-sm">- {value?.error ?? 'No data'}- </div>- </ResultCard>- );- }-- const report = value.report;- if (!(report && report.chartType)) {- return (- <ResultCard title={value.name ?? 'Report'}>- <div className="px-3 py-2 text-muted-foreground text-sm">- Report data returned but no renderable config.- </div>- </ResultCard>- );- }-- const title =- value.name ??- deriveTitleFromInput(toolType, input) ??- `${humanizeChartType(String(report.chartType))} report`;-- return (- <ResultCard title={title}>- <div className="p-2">- <ReportChart- lazy={false}- options={{- hideLegend: false,- hideXAxis: false,- minHeight: 180,- maxHeight: 260,- }}- report={report as unknown as IReportInput}- />- </div>- {(value.dashboard_url || !report.id) && (- <div className="flex items-center justify-between gap-2 border-t px-3 py-1.5">- {value.dashboard_url && (- <a- className="text-muted-foreground text-sm hover:underline"- href={value.dashboard_url}- rel="noopener noreferrer"- target="_blank"- >- Open in dashboard →- </a>- )}- {!report.id && (- <Button- className="ml-auto h-6 text-sm"- onClick={() =>- pushModal('SaveReport', {- report: {- ...report,- name: value.name ?? report.name,- } as unknown as IReport,- disableRedirect: true,- })- }- size="sm"- variant="ghost"- >- <SaveIcon className="mr-1 size-3" />- Save- </Button>- )}- </div>- )}- </ResultCard>- );-}--/**- * Build a human title from the tool call's input args. The model- * often calls chart tools without setting `output.name` explicitly- * — we can do better than `"LINEAR chart"` by reading what the- * user actually asked for.- */-function deriveTitleFromInput(toolType: string, input: unknown): string | null {- if (!input || typeof input !== 'object') {- return null;- }- const args = input as {- steps?: unknown;- series?: Array<{ name?: string; displayName?: string }>;- chartType?: string;- windowDays?: number;- days?: number;- };-- switch (toolType) {- case 'tool-get_funnel': {- if (Array.isArray(args.steps) && args.steps.length > 0) {- const names = args.steps.filter(- (s): s is string => typeof s === 'string'- );- if (names.length > 0) {- return `Funnel: ${names.join(' → ')}`;- }- }- return 'Funnel';- }-- case 'tool-get_rolling_active_users': {- // The chart this tool returns is daily uniques whatever `windowDays`- // asked for — only the numeric summary honours the rolling window — so- // the title must not say DAU/WAU/MAU.- const days = args.days ?? 30;- return `Daily active users — last ${days} days`;- }-- case 'tool-generate_report': {- const events = Array.isArray(args.series)- ? args.series- .map((s) => s?.displayName || s?.name)- .filter((n): n is string => typeof n === 'string' && n.length > 0)- : [];- const kind = args.chartType- ? humanizeChartType(args.chartType)- : 'Report';- if (events.length === 0) {- return kind;- }- if (events.length === 1) {- return `${kind}: ${events[0]}`;- }- return `${kind}: ${events.join(', ')}`;- }-- default:- return null;- }-}--function humanizeChartType(type: string): string {- switch (type) {- case 'linear':- return 'Line chart';- case 'bar':- return 'Bar chart';- case 'area':- return 'Area chart';- case 'pie':- return 'Pie chart';- case 'funnel':- return 'Funnel';- case 'metric':- return 'Metric';- case 'retention':- return 'Retention';- case 'histogram':- return 'Histogram';- case 'sankey':- return 'Sankey';- case 'map':- return 'Map';- case 'conversion':- return 'Conversion';- default:- return type.charAt(0).toUpperCase() + type.slice(1);- }-}diff --git a/apps/start/src/components/chat/tool-results/chat-table-result.tsx b/apps/start/src/components/chat/tool-results/chat-table-result.tsxdeleted file mode 100644index 7e057227f..000000000--- a/apps/start/src/components/chat/tool-results/chat-table-result.tsx+++ /dev/null@@ -1,183 +0,0 @@-import { DefaultToolResult } from './default-tool-result';-import { normalizeTableOutput, type TableRow } from './output-types';-import { ResultCard, ToolStateGuard } from './shared';-import type { ToolResultProps } from './types';--/**- * Generic compact table for top-pages / top-referrers / breakdowns / etc.- * The shape varies across tools (some return arrays, some `{ rows }`,- * some `{ data }`); `normalizeTableOutput` is the single shape boundary.- */-export function ChatTableResult(props: ToolResultProps) {- const { part } = props;- // When we can't shape this as a table (output isn't array-like OR the- // array has 0 rows), fall through to the default "done chip" renderer- // instead of showing a bare "No rows" card — which looks like an- // error but usually just means the tool's output shape isn't what- // we expected (or the user genuinely has no data yet). The chip is- // tidy, has the real tool label, and lets the user expand to see- // the raw output if they're curious.- if (part.state === 'output-available') {- const { rows } = normalizeTableOutput(part.output);- if (rows.length === 0) {- return <DefaultToolResult part={part} />;- }- }-- return (- <ToolStateGuard- errorText={part.errorText}- state={part.state}- toolName={part.type.replace(/^tool-/, '')}- >- <ChatTableInner output={part.output} />- </ToolStateGuard>- );-}--function ChatTableInner({ output }: { output: unknown }) {- const { rows, total, truncated } = normalizeTableOutput(output);- // Empty case is handled at the wrapper level (falls through to- // DefaultToolResult) — this function only runs with rows present.- if (rows.length === 0) {- return null;- }- const { labelKey, valueKeys } = inferColumns(rows[0]!);-- return (- <ResultCard>- <table className="w-full text-sm">- <thead className="bg-muted/30">- <tr>- <th className="px-3 py-1.5 text-left font-medium text-muted-foreground">- {humanize(labelKey)}- </th>- {valueKeys.map((k) => (- <th- className="px-3 py-1.5 text-right font-medium text-muted-foreground"- key={k}- >- {humanize(k)}- </th>- ))}- </tr>- </thead>- <tbody>- {rows.slice(0, 15).map((row, idx) => (- <tr- className="border-t"- key={typeof row.id === 'string' ? row.id : idx}- >- <td- className="max-w-[200px] truncate px-3 py-1.5"- title={String(row[labelKey] ?? '')}- >- {String(row[labelKey] ?? '')}- </td>- {valueKeys.map((k) => (- <td- className="px-3 py-1.5 text-right font-mono tabular-nums"- key={k}- >- {formatValue(row[k])}- </td>- ))}- </tr>- ))}- </tbody>- </table>- {rows.length > 15 && (- <div className="border-t px-3 py-1 text-[11px] text-muted-foreground">- Showing 15 of {total ?? rows.length}- {truncated && ' (truncated)'}- </div>- )}- </ResultCard>- );-}--// Preferred label columns, in order. The table renderer picks the-// first one present on the row over the file-order default — so a row-// with both `id` and `title` shows the title as the label, not the-// UUID. Add anything else that's a common "this is the human-readable-// name" field below.-const PREFERRED_LABEL_KEYS = [- 'title',- 'name',- 'label',- 'displayName',- 'display_name',- 'event_name',- 'eventName',- 'page',- 'path',- 'query',- 'referrer',- 'referrer_name',- 'country',- 'city',- 'device',- 'browser',- 'os',- 'summary',-] as const;--// Keys we never want as the label column even if they happen to be the-// first string field. UUIDs / opaque ids are unhelpful in the table —-// the model can still reference them in prose.-const UNINTERESTING_LABEL_KEYS = new Set([- 'id',- 'projectId',- 'organizationId',- 'userId',- 'profileId',- 'sessionId',- 'reportId',- 'groupId',- 'dashboardId',- 'insightId',- 'threadId',-]);--function inferColumns(first: TableRow): {- labelKey: string;- valueKeys: string[];-} {- const numericKeys: string[] = [];- const stringKeys: string[] = [];- for (const [key, value] of Object.entries(first)) {- if (typeof value === 'number') {- numericKeys.push(key);- } else if (typeof value === 'string') {- stringKeys.push(key);- }- }-- // 1. Prefer one of our known descriptive keys.- const preferred = PREFERRED_LABEL_KEYS.find((k) => k in first);- // 2. Otherwise the first string key that isn't an opaque id.- const firstNonId = stringKeys.find((k) => !UNINTERESTING_LABEL_KEYS.has(k));- // 3. Last resort: the first string (or any) key.- const labelKey =- preferred ?? firstNonId ?? stringKeys[0] ?? Object.keys(first)[0]!;-- const valueKeys = numericKeys.slice(0, 3);- return { labelKey, valueKeys };-}--function humanize(key: string): string {- return key- .replace(/_/g, ' ')- .replace(/([a-z])([A-Z])/g, '$1 $2')- .replace(/^\w/, (c) => c.toUpperCase());-}--function formatValue(v: unknown): string {- if (typeof v === 'number') {- if (Number.isInteger(v)) {- return v.toLocaleString();- }- return v.toFixed(2);- }- return v != null ? String(v) : '—';-}diff --git a/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsx b/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsxdeleted file mode 100644index c8e03e544..000000000--- a/apps/start/src/components/chat/tool-results/chat-ui-apply-result.tsx+++ /dev/null@@ -1,85 +0,0 @@-import { timeWindows } from '@openpanel/core/modules/report/report.constants';-import { CheckIcon } from 'lucide-react';-import type { ReactNode } from 'react';-import type { ToolResultProps } from './types';--/**- * Renderers for the client-side UI-mutator tools:- * - apply_filters (date range / interval)- * - set_property_filters (country, device, referrer_name, …)- * - set_event_names_filter (event-name whitelist)- *- * These tools run instantly on the client (they just push URL params),- * so there's nothing to shimmer for. We bypass `ToolStateGuard` and- * always render a tidy confirmation chip with a summary parsed from- * the tool's INPUT args — even on the `input-complete` intermediate- * state the chip looks "done" because the action has already landed.- */--export function ApplyFiltersResult({ part }: ToolResultProps) {- const input = (part.input ?? {}) as {- range?: string;- startDate?: string;- endDate?: string;- interval?: string;- };- const parts: string[] = [];- if (input.startDate && input.endDate) {- parts.push(`date range: ${input.startDate} → ${input.endDate}`);- } else if (input.range) {- parts.push(`date range: ${formatRange(input.range)}`);- }- if (input.interval) {- parts.push(`interval: ${input.interval}`);- }- const summary = parts.length > 0 ? parts.join(' · ') : 'filters';- return <AppliedChip>Applied {summary}</AppliedChip>;-}--export function SetPropertyFiltersResult({ part }: ToolResultProps) {- const input = (part.input ?? {}) as {- filters?: Array<{- name?: string;- operator?: string;- value?: string[];- }>;- };- const filters = Array.isArray(input.filters) ? input.filters : [];- if (filters.length === 0) {- return <AppliedChip>Cleared property filters</AppliedChip>;- }- const summary = filters- .map((f) => {- const op = f.operator && f.operator !== 'is' ? ` ${f.operator}` : '';- const value = Array.isArray(f.value) ? f.value.join(', ') : '';- return `${f.name}${op}${value ? ` = ${value}` : ''}`;- })- .join(' · ');- return <AppliedChip>Applied filters: {summary}</AppliedChip>;-}--export function SetEventNamesFilterResult({ part }: ToolResultProps) {- const input = (part.input ?? {}) as { eventNames?: string[] };- const names = Array.isArray(input.eventNames) ? input.eventNames : [];- if (names.length === 0) {- return <AppliedChip>Cleared event-name filter</AppliedChip>;- }- return (- <AppliedChip>- Filtered to {names.length === 1 ? 'event' : 'events'}: {names.join(', ')}- </AppliedChip>- );-}--function AppliedChip({ children }: { children: ReactNode }) {- return (- <div className="inline-flex items-center gap-1.5 rounded-md border bg-card px-2.5 py-1 text-foreground/80 text-sm">- <CheckIcon className="size-3.5 shrink-0 text-emerald-500" />- <span className="truncate">{children}</span>- </div>- );-}--function formatRange(range: string): string {- return timeWindows[range as keyof typeof timeWindows]?.label ?? range;-}diff --git a/apps/start/src/components/chat/tool-results/default-tool-result.tsx b/apps/start/src/components/chat/tool-results/default-tool-result.tsxdeleted file mode 100644index 12b065015..000000000--- a/apps/start/src/components/chat/tool-results/default-tool-result.tsx+++ /dev/null@@ -1,78 +0,0 @@-import { ChevronRightIcon } from 'lucide-react';-import { useState } from 'react';-import { ResultCard, ToolDoneBadge, ToolStateGuard } from './shared';-import { getToolPhrase } from './tool-labels';-import type { ToolResultProps } from './types';--/**- * Auto-fallback for tools that don't have a custom UI in the registry.- * Shows a friendly "Done — <Tool>" chip with click-to-expand JSON.- */-export function DefaultToolResult({ part }: ToolResultProps) {- const toolName = part.type.replace(/^tool-/, '');-- return (- <ToolStateGuard- errorText={part.errorText}- state={part.state}- toolName={toolName}- >- <DefaultInner output={part.output} toolName={toolName} />- </ToolStateGuard>- );-}--function DefaultInner({- toolName,- output,-}: {- toolName: string;- output: unknown;-}) {- const [expanded, setExpanded] = useState(false);-- if (output == null) {- return (- <ResultCard title={getToolPhrase(toolName, 'done')}>- <div className="px-3 py-2 text-muted-foreground text-sm">- No result.- </div>- </ResultCard>- );- }-- if (typeof output === 'string') {- return (- <ResultCard title={getToolPhrase(toolName, 'done')}>- <div className="whitespace-pre-wrap px-3 py-2 text-sm">{output}</div>- </ResultCard>- );- }-- // Most "data" tools: render the friendly Done chip with optional- // JSON drill-down. Tools we want as full cards have their own- // entry in the registry.- return (- <ToolDoneBadge toolName={toolName}>- <button- className="-mx-2.5 -my-2 flex w-[calc(100%+1.25rem)] items-center gap-1 px-2.5 py-1.5 text-left text-muted-foreground text-sm hover:bg-muted/40"- onClick={() => setExpanded((e) => !e)}- type="button"- >- <ChevronRightIcon- className={`size-3 transition-transform ${expanded ? 'rotate-90' : ''}`}- />- <span className="truncate">- {Array.isArray(output)- ? `${output.length} item${output.length === 1 ? '' : 's'}`- : 'View raw output'}- </span>- </button>- {expanded && (- <pre className="-mx-2.5 mt-2 -mb-2 max-h-64 overflow-y-auto whitespace-pre-wrap break-all border-t bg-muted/20 px-2.5 py-2 font-mono text-[11px]">- {JSON.stringify(output, null, 2)}- </pre>- )}- </ToolDoneBadge>- );-}diff --git a/apps/start/src/components/chat/tool-results/output-types.ts b/apps/start/src/components/chat/tool-results/output-types.tsdeleted file mode 100644index 26c023549..000000000--- a/apps/start/src/components/chat/tool-results/output-types.ts+++ /dev/null@@ -1,127 +0,0 @@-/**- * Frontend-side TypeScript types for the chat tool outputs we render- * with custom UIs. These mirror what the matching backend tool returns.- * The renderers narrow `unknown` via the type guards below before- * reading any field.- *- * If the backend changes a tool's return shape, the matching renderer- * will fall back to a "no data" card rather than crashing — that's why- * we narrow with predicates rather than `as any`.- */--export type MetricsLike = Record<string, unknown>;--export function isMetricsLike(value: unknown): value is MetricsLike {- return value !== null && typeof value === 'object' && !Array.isArray(value);-}--export type ProfileMetrics = {- sessions?: number;- totalEvents?: number;- screenViews?: number;- avgSessionDurationMin?: number;- bounceRate?: number;- revenue?: number;-};--export type ProfileFullSuccess = {- profile?: {- id: string;- firstName?: string | null;- lastName?: string | null;- email?: string | null;- };- metrics?: ProfileMetrics | null;- recent_sessions?: unknown[];- recent_events?: unknown[];- dashboard_url?: string;-};--export type ProfileFullError = {- error: string;- profileId?: string;-};--export type ProfileFullOutput = ProfileFullSuccess | ProfileFullError;--export function isProfileFullError(- value: ProfileFullOutput-): value is ProfileFullError {- return 'error' in value && typeof value.error === 'string';-}--export function asProfileFullOutput(value: unknown): ProfileFullOutput | null {- if (!value || typeof value !== 'object') {- return null;- }- return value as ProfileFullOutput;-}--export type ReportOutput = {- data?: unknown;- report?: {- id?: string;- chartType?: string;- [key: string]: unknown;- };- name?: string;- dashboard_url?: string;- error?: string;-};--export function asReportOutput(value: unknown): ReportOutput | null {- if (!value || typeof value !== 'object') {- return null;- }- return value as ReportOutput;-}--export type TableRow = Record<string, unknown>;--export type TableNormalized = {- rows: TableRow[];- total: number | undefined;- truncated: boolean;-};--/**- * Several tools return either an array directly or wrap it in `{ rows }`,- * `{ data }`, `{ opportunities }`, or `{ properties }`. This is the one- * place where we resolve that — every renderer downstream gets a clean- * `TableRow[]`.- *- * `properties` covers `list_event_properties` / `list_properties_for_event`,- * which return a flat `string[]` of property keys after the server rolled- * up dotted sub-keys. We lift each into `{ property_key }` so the generic- * table renderer can pick it up as the label column.- */-export function normalizeTableOutput(value: unknown): TableNormalized {- if (Array.isArray(value)) {- return {- rows: value as TableRow[],- total: undefined,- truncated: false,- };- }- if (value && typeof value === 'object') {- const o = value as Record<string, unknown>;- const total = typeof o.total === 'number' ? o.total : undefined;- const truncated = o._truncated === true;- if (Array.isArray(o.rows)) {- return { rows: o.rows as TableRow[], total, truncated };- }- if (Array.isArray(o.data)) {- return { rows: o.data as TableRow[], total, truncated };- }- if (Array.isArray(o.opportunities)) {- return { rows: o.opportunities as TableRow[], total, truncated };- }- if (Array.isArray(o.properties)) {- const rows: TableRow[] = (o.properties as unknown[]).map((p) =>- typeof p === 'string' ? { property_key: p } : (p as TableRow)- );- return { rows, total, truncated };- }- }- return { rows: [], total: undefined, truncated: false };-}diff --git a/apps/start/src/components/chat/tool-results/registry.tsx b/apps/start/src/components/chat/tool-results/registry.tsxdeleted file mode 100644index c5a8da07e..000000000--- a/apps/start/src/components/chat/tool-results/registry.tsx+++ /dev/null@@ -1,64 +0,0 @@-import type { FC } from 'react';-import { ChatMetricsResult } from './chat-metrics-result';-import { ChatProfileFullResult } from './chat-profile-result';-import { ChatReportResult } from './chat-report-result';-import { ChatTableResult } from './chat-table-result';-import {- ApplyFiltersResult,- SetEventNamesFilterResult,- SetPropertyFiltersResult,-} from './chat-ui-apply-result';-import type { ToolResultProps } from './types';--/**- * Map of tool-${toolName} → renderer. Anything not in this map falls- * through to `DefaultToolResult` which renders an auto-inferred summary.- *- * Adding a new backend tool does NOT require touching this map — it'll- * still render usefully via the default. Only add an entry here if you- * want a custom UI.- */-export const chatToolRenderers: Record<string, FC<ToolResultProps>> = {- // Reports — these all return { chartType, report, data, ... }- 'tool-get_report_data': ChatReportResult,- 'tool-generate_report': ChatReportResult,- 'tool-preview_report_with_changes': ChatReportResult,- 'tool-get_rolling_active_users': ChatReportResult,- 'tool-get_funnel': ChatReportResult,-- // Metric cards- 'tool-get_analytics_overview': ChatMetricsResult,- 'tool-get_profile_metrics': ChatMetricsResult,-- // Compact tables for breakdowns / lists- 'tool-get_top_pages': ChatTableResult,- 'tool-get_top_referrers': ChatTableResult,- 'tool-get_country_breakdown': ChatTableResult,- 'tool-get_device_breakdown': ChatTableResult,- 'tool-get_entry_exit_pages': ChatTableResult,- 'tool-find_declining_pages': ChatTableResult,- 'tool-find_profiles': ChatTableResult,- 'tool-query_events': ChatTableResult,- 'tool-query_sessions': ChatTableResult,- 'tool-list_event_names': ChatTableResult,- 'tool-list_event_properties': ChatTableResult,- 'tool-list_dashboards': ChatTableResult,- 'tool-list_reports': ChatTableResult,- 'tool-list_insights': ChatTableResult,- 'tool-gsc_get_top_queries': ChatTableResult,- 'tool-gsc_get_top_pages': ChatTableResult,- 'tool-gsc_get_query_opportunities': ChatTableResult,- 'tool-correlate_seo_with_traffic': ChatTableResult,- 'tool-list_references': ChatTableResult,-- // Profile detail- 'tool-get_profile_full': ChatProfileFullResult,-- // Client-side UI mutators — render a "done" chip regardless of- // state (no async work to shimmer for).- 'tool-apply_filters': ApplyFiltersResult,- 'tool-set_property_filters': SetPropertyFiltersResult,- 'tool-set_event_names_filter': SetEventNamesFilterResult,-};--export { DefaultToolResult } from './default-tool-result';diff --git a/apps/start/src/components/chat/tool-results/shared.tsx b/apps/start/src/components/chat/tool-results/shared.tsxdeleted file mode 100644index 8a67baac2..000000000--- a/apps/start/src/components/chat/tool-results/shared.tsx+++ /dev/null@@ -1,142 +0,0 @@-import { AlertCircleIcon, CheckIcon, SparklesIcon } from 'lucide-react';-import type { ReactNode } from 'react';-import { getToolPhrase } from './tool-labels';-import { Skeleton } from '@/components/skeleton';-import { cn } from '@/utils/cn';--/**- * Wrapper that handles the tool-part state machine. Shows a shimmer- * activity row while the tool is running, an error card on failure,- * and the renderer's children on success.- */-export function ToolStateGuard({- state,- errorText,- toolName,- pending,- children,-}: {- state: string;- errorText?: string;- /** Used for the friendly action label on in-progress / completed badges. */- toolName?: string;- pending?: ReactNode;- children: ReactNode;-}) {- if (state === 'input-streaming' || state === 'input-available') {- return pending ?? <ToolActivityBadge toolName={toolName} />;- }- if (state === 'output-error') {- return (- <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm">- <AlertCircleIcon className="mt-0.5 size-3.5 shrink-0" />- <span>{errorText ?? 'Tool failed'}</span>- </div>- );- }- if (state === 'output-available') {- return <>{children}</>;- }- return null;-}--/**- * Compact "the AI is working on this" badge with shimmer text. Shown- * while a tool's input is streaming or it's executing on the server.- */-export function ToolActivityBadge({ toolName }: { toolName?: string }) {- const label = toolName ? getToolPhrase(toolName, 'active') : 'Working';- return (- <div className="flex items-center gap-2 py-1.5 text-sm">- <SparklesIcon className="size-3.5 shrink-0 text-muted-foreground" />- <span className="op-shimmer font-medium">{label}…</span>- </div>- );-}--/**- * Compact "done" badge for tools whose output we don't surface as a- * full card (the model already wrote prose with the result). Renders- * a small chip you can click to expand into details.- */-export function ToolDoneBadge({- toolName,- children,-}: {- toolName: string;- children?: ReactNode;-}) {- return (- <details className="group rounded-md border bg-card text-sm">- <summary className="flex cursor-pointer list-none items-center gap-2 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden">- <CheckIcon className="size-3 shrink-0 text-emerald-500" />- <span className="font-medium text-foreground/80">- {getToolPhrase(toolName, 'done')}- </span>- </summary>- {children && <div className="border-t px-2.5 py-2">{children}</div>}- </details>- );-}--export function ResultCard({- title,- children,- className,-}: {- title?: string;- children: ReactNode;- className?: string;-}) {- return (- <div className={cn('overflow-hidden rounded-md border bg-card', className)}>- {title && (- <div className="border-b px-3 py-1.5 font-medium text-muted-foreground text-sm">- {title}- </div>- )}- {children}- </div>- );-}--export function ResultRow({- children,- className,-}: {- children: ReactNode;- className?: string;-}) {- return (- <div- className={cn(- 'flex items-center justify-between gap-2 px-3 py-1.5 text-sm',- className- )}- >- {children}- </div>- );-}--export function ResultLabel({ children }: { children: ReactNode }) {- return <span className="truncate text-muted-foreground">{children}</span>;-}--export function ResultValue({- children,- mono = true,-}: {- children: ReactNode;- mono?: boolean;-}) {- return (- <span- className={cn('shrink-0 font-medium tabular-nums', mono && 'font-mono')}- >- {children}- </span>- );-}--export { Skeleton };diff --git a/apps/start/src/components/chat/tool-results/tool-labels.ts b/apps/start/src/components/chat/tool-results/tool-labels.tsdeleted file mode 100644index 0f6868a64..000000000--- a/apps/start/src/components/chat/tool-results/tool-labels.ts+++ /dev/null@@ -1,283 +0,0 @@-/**- * Humanizes raw tool names into action-phrase labels for the UI.- *- * Each tool gets a tuple: (verb-form for in-progress, noun-form for- * completed). E.g.- * list_event_names → ["Looking up event names", "Event names"]- *- * Falls back to a generic transformation when a tool isn't in the- * map: snake_case → "Snake case", with verb-prefix heuristics- * ("get_" → "Loading", "list_" → "Looking up", "find_" → "Finding").- */--const VERB_PREFIXES: Array<[string, string]> = [- ['list_', 'Looking up'],- ['get_', 'Loading'],- ['find_', 'Finding'],- ['query_', 'Querying'],- ['analyze_', 'Analyzing'],- ['compare_', 'Comparing'],- ['correlate_', 'Correlating'],- ['explain_', 'Explaining'],- ['suggest_', 'Suggesting'],- ['preview_', 'Previewing'],- ['generate_', 'Generating'],- ['apply_', 'Applying'],- ['set_', 'Updating'],- ['gsc_', 'Loading SEO'],-];--const PHRASES: Record<string, { active: string; done: string }> = {- // Discovery- list_event_names: { active: 'Looking up event names', done: 'Event names' },- list_event_properties: {- active: 'Looking up properties',- done: 'Event properties',- },- get_event_property_values: {- active: 'Loading property values',- done: 'Property values',- },-- // Saved reports & dashboards- list_dashboards: { active: 'Loading dashboards', done: 'Dashboards' },- list_reports: { active: 'Loading reports', done: 'Reports' },- get_report_data: { active: 'Running report', done: 'Report' },- generate_report: { active: 'Building report', done: 'Report' },-- // Aggregate analytics- get_analytics_overview: { active: 'Loading overview', done: 'Overview' },- get_top_pages: { active: 'Loading top pages', done: 'Top pages' },- get_top_referrers: {- active: 'Loading top referrers',- done: 'Top referrers',- },- get_country_breakdown: {- active: 'Loading geo breakdown',- done: 'Geo breakdown',- },- get_device_breakdown: {- active: 'Loading device breakdown',- done: 'Device breakdown',- },- get_rolling_active_users: {- active: 'Loading active users',- done: 'Active users',- },- get_funnel: { active: 'Building funnel', done: 'Funnel' },- get_retention_cohort: {- active: 'Building retention cohort',- done: 'Retention',- },- get_user_flow: { active: 'Building user flow', done: 'User flow' },-- // Free-form- query_events: { active: 'Querying events', done: 'Events' },- query_sessions: { active: 'Querying sessions', done: 'Sessions' },- find_profiles: { active: 'Finding profiles', done: 'Profiles' },-- // Profile- get_profile_full: { active: 'Loading profile', done: 'Profile' },- get_profile_events: {- active: 'Loading profile events',- done: 'Profile events',- },- get_profile_sessions: {- active: 'Loading profile sessions',- done: 'Profile sessions',- },- get_profile_metrics: {- active: 'Loading profile metrics',- done: 'Profile metrics',- },- get_profile_journey: {- active: 'Loading user journey',- done: 'User journey',- },- get_profile_groups: {- active: 'Loading profile groups',- done: 'Profile groups',- },- compare_profile_to_average: {- active: 'Comparing to average',- done: 'Profile comparison',- },-- // Session- get_session_full: { active: 'Loading session', done: 'Session' },- get_session_path: { active: 'Loading session path', done: 'Session path' },- get_session_events: {- active: 'Loading session events',- done: 'Session events',- },- get_similar_sessions: {- active: 'Finding similar sessions',- done: 'Similar sessions',- },- compare_session_to_typical: {- active: 'Comparing to typical',- done: 'Session comparison',- },- get_session_referrer_context: {- active: 'Loading referrer context',- done: 'Referrer context',- },- get_session_replay_summary: {- active: 'Loading session replay',- done: 'Session replay',- },-- // Pages- get_page_performance: {- active: 'Loading page performance',- done: 'Page performance',- },- get_page_conversions: {- active: 'Loading page conversions',- done: 'Page conversions',- },- get_entry_exit_pages: {- active: 'Loading entry/exit pages',- done: 'Entry/exit pages',- },- find_declining_pages: {- active: 'Finding declining pages',- done: 'Declining pages',- },-- // SEO / GSC- gsc_get_overview: { active: 'Loading SEO overview', done: 'SEO overview' },- gsc_get_top_queries: { active: 'Loading top queries', done: 'Top queries' },- gsc_get_top_pages: {- active: 'Loading top SEO pages',- done: 'Top SEO pages',- },- gsc_get_query_details: {- active: 'Loading query details',- done: 'Query details',- },- gsc_get_page_details: {- active: 'Loading page details',- done: 'Page details',- },- gsc_get_query_opportunities: {- active: 'Finding query opportunities',- done: 'Query opportunities',- },- gsc_get_cannibalization: {- active: 'Checking cannibalization',- done: 'Cannibalization',- },- correlate_seo_with_traffic: {- active: 'Correlating SEO with traffic',- done: 'SEO/traffic correlation',- },-- // Events- analyze_event_distribution: {- active: 'Analyzing event distribution',- done: 'Event distribution',- },- correlate_events: { active: 'Correlating events', done: 'Event correlation' },- get_event_property_distribution: {- active: 'Loading property distribution',- done: 'Property distribution',- },- // Retired server-side — it was a second wire name over- // `list_event_properties`' handler — but conversations saved before that- // still replay tool calls under this name, so the label stays.- list_properties_for_event: {- active: 'Loading properties',- done: 'Event properties',- },-- // Insights- list_insights: { active: 'Loading insights', done: 'Insights' },- explain_insight: { active: 'Loading insight', done: 'Insight' },- find_related_insights: {- active: 'Finding related insights',- done: 'Related insights',- },-- // Group- get_group_full: { active: 'Loading group', done: 'Group' },- get_group_members: { active: 'Loading group members', done: 'Group members' },- get_group_events: { active: 'Loading group events', done: 'Group events' },- get_group_metrics: {- active: 'Loading group metrics',- done: 'Group metrics',- },- compare_groups: { active: 'Comparing groups', done: 'Group comparison' },-- // Report editor- preview_report_with_changes: {- active: 'Previewing changes',- done: 'Report preview',- },- suggest_breakdowns: {- active: 'Suggesting breakdowns',- done: 'Breakdown suggestions',- },- compare_to_previous_period: {- active: 'Comparing to previous period',- done: 'Period comparison',- },- find_anomalies_in_current_report: {- active: 'Finding anomalies',- done: 'Anomalies',- },- explain_filter_impact: {- active: 'Analyzing filter impact',- done: 'Filter impact',- },-- // UI mutators (client-side)- apply_filters: {- active: 'Applying date range',- done: 'Date range updated',- },- set_property_filters: {- active: 'Applying filters',- done: 'Filters updated',- },- set_event_names_filter: {- active: 'Applying event filter',- done: 'Event filter updated',- },-- // References- list_references: {- active: 'Loading references',- done: 'References',- },- get_references_around: {- active: 'Checking references around this date',- done: 'Nearby references',- },-};--export type ToolPhrasePhase = 'active' | 'done';--export function getToolPhrase(- toolName: string,- phase: ToolPhrasePhase-): string {- const explicit = PHRASES[toolName];- if (explicit) {- return explicit[phase];- }-- const matchedPrefix = VERB_PREFIXES.find(([p]) => toolName.startsWith(p));- const verb = matchedPrefix?.[0] ?? '';- const verbLabel = matchedPrefix?.[1] ?? 'Running';-- const noun = humanizeNoun(toolName.slice(verb.length) || toolName);- return phase === 'active' ? `${verbLabel} ${noun.toLowerCase()}` : noun;-}--function humanizeNoun(s: string): string {- return s- .replace(/_/g, ' ')- .replace(/^\w/, (c) => c.toUpperCase())- .trim();-}diff --git a/apps/start/src/components/chat/tool-results/types.ts b/apps/start/src/components/chat/tool-results/types.tsdeleted file mode 100644index 89c0e6b4d..000000000--- a/apps/start/src/components/chat/tool-results/types.ts+++ /dev/null@@ -1,21 +0,0 @@-/**- * Minimal shape for a tool UI part that all renderers consume. We keep- * this looser than `ToolUIPart` from the AI SDK so the registry can- * dispatch generically without `any` casts.- *- * `output` is `unknown` on purpose: the registry hands the part to a- * renderer that knows the shape, and the renderer narrows it via the- * type guards in `output-types.ts`.- */-export type ToolResultPart = {- type: string;- toolCallId: string;- state: string;- input?: unknown;- output?: unknown;- errorText?: string;-};--export type ToolResultProps = {- part: ToolResultPart;-};diff --git a/apps/start/src/components/chat/types.ts b/apps/start/src/components/chat/types.tsnew file mode 100644index 000000000..14d64d80f--- /dev/null+++ b/apps/start/src/components/chat/types.ts@@ -0,0 +1,44 @@+import type { IReportInput } from '@openpanel/core/modules/report/report.constants';++export type {+ AssistantUIMessage,+ AssistantUIMessagePart,+} from '@openpanel/core';++/** What every chart-producing tool returns; the chart fetches its own data from `report`. */+export interface ChartOutput {+ title: string;+ report: IReportInput & { name: string; id?: string };+ dashboardUrl?: string;+}++export function isChartOutput(value: unknown): value is ChartOutput {+ if (typeof value !== 'object' || value === null) {+ return false;+ }+ const candidate = value as { report?: { chartType?: unknown } };+ return typeof candidate.report?.chartType === 'string';+}++export function isRowsOutput(value: unknown): value is {+ rows: Record<string, unknown>[];+ total?: number;+ truncated?: boolean;+} {+ if (typeof value !== 'object' || value === null) {+ return false;+ }+ const rows = (value as { rows?: unknown }).rows;+ return (+ Array.isArray(rows) &&+ rows.every((row) => typeof row === 'object' && row !== null)+ );+}++export function isErrorOutput(value: unknown): value is { error: string } {+ return (+ typeof value === 'object' &&+ value !== null &&+ typeof (value as { error?: unknown }).error === 'string'+ );+}diff --git a/apps/start/src/components/chat/use-chat-open.ts b/apps/start/src/components/chat/use-chat-open.tsdeleted file mode 100644index afdaf0cd2..000000000--- a/apps/start/src/components/chat/use-chat-open.ts+++ /dev/null@@ -1,30 +0,0 @@-import { parseAsString, useQueryState } from 'nuqs';--/**- * The `?chat` URL param is the single source of truth for the chat- * drawer. Possible states:- * - param absent (null) → drawer closed- * - param is a string → drawer open, the value is the active- * conversation id- *- * Opening a brand-new conversation = push a freshly generated UUID.- * Switching to an existing conversation = push its id. Closing =- * clear the param.- *- * This makes conversations linkable (paste a URL, land on that chat)- * and keeps chat state in the browser history.- */-export function useChatUrlState() {- return useQueryState('chat', parseAsString.withOptions({ history: 'push' }));-}--/**- * Generate a new conversation id. Browser-native UUID when available,- * fallback to a timestamp+random combo for very old browsers.- */-export function newConversationId(): string {- if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {- return crypto.randomUUID();- }- return `conv_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;-}diff --git a/apps/start/src/components/chat/use-chat-session.ts b/apps/start/src/components/chat/use-chat-session.tsnew file mode 100644index 000000000..28fecc08a--- /dev/null+++ b/apps/start/src/components/chat/use-chat-session.ts@@ -0,0 +1,241 @@+import { Chat, useChat } from '@ai-sdk/react';+import type {+ ChatLaunchHint,+ NavigateInput,+ OpenDialogInput,+} from '@openpanel/core/modules/assistant/assistant.constants';+import { CHAT_ROUTES } from '@openpanel/core/modules/assistant/assistant.constants';+import type { IIntegrationConfig } from '@openpanel/core/modules/integration/integration.constants';+import { useQueryClient } from '@tanstack/react-query';+import {+ DefaultChatTransport,+ lastAssistantMessageIsCompleteWithApprovalResponses,+ lastAssistantMessageIsCompleteWithToolCalls,+} from 'ai';+import { useCallback, useEffect, useMemo, useState } from 'react';+import type { AssistantUIMessage } from './types';+import { useAppContext } from '@/hooks/use-app-context';+import { useAppParams } from '@/hooks/use-app-params';+import { useTRPC } from '@/integrations/trpc/react';+import { pushModal } from '@/modals';++const CLIENT_TYPES = ['read', 'write', 'root'] as const;+const DEFAULT_INTEGRATION_TYPE = 'webhook';++function clientType(value: string | undefined) {+ return CLIENT_TYPES.find((type) => type === value);+}++/** Each dialog takes only the fields it has; anything else in the prefill is dropped. */+export function openDialog(input: OpenDialogInput): void {+ const prefill = input.prefill ?? {};+ switch (input.dialog) {+ case 'addClient':+ pushModal('AddClient', {+ name: prefill.name,+ type: clientType(prefill.type),+ });+ return;+ case 'addDashboard':+ pushModal('AddDashboard', { name: prefill.name });+ return;+ case 'addReference':+ pushModal('AddReference', {+ title: prefill.title,+ description: prefill.description,+ datetime: prefill.datetime ?? prefill.date,+ });+ return;+ case 'addNotificationRule':+ pushModal('AddNotificationRule', { rule: undefined });+ return;+ case 'addIntegration':+ pushModal('AddIntegration', {+ type: (prefill.type ??+ DEFAULT_INTEGRATION_TYPE) as IIntegrationConfig['type'],+ });+ return;+ case 'addProject':+ pushModal('AddProject');+ return;+ case 'inviteMember':+ pushModal('CreateInvite');+ return;+ case 'addCohort':+ pushModal('AddCohort');+ return;+ default:+ return;+ }+}++function fillRoute(+ input: NavigateInput,+ ids: { organizationId: string; projectId: string }+): string {+ const route = CHAT_ROUTES[input.route];+ const base =+ 'scope' in route && route.scope === 'organization'+ ? `/${ids.organizationId}`+ : `/${ids.organizationId}/${ids.projectId}`;+ const path = route.path.replace(/:([a-zA-Z]+)/g, (_match, key: string) =>+ encodeURIComponent(input.params?.[key] ?? '')+ );+ return `${base}${path}`;+}++interface ChatHandlers {+ onToolCall: (toolCall: {+ toolName: string;+ toolCallId: string;+ input: unknown;+ }) => void;+ onTitle: (title: string) => void;+ onFinish: () => void;+}++interface ChatEntry {+ chat: Chat<AssistantUIMessage>;+ handlers: ChatHandlers | null;+ /** Read at request time, so a model switch or a new hint applies to the next turn. */+ request: { modelId: string | null; hint?: ChatLaunchHint };+}++/** Newest chats stay; the page rarely touches more than a handful per visit. */+const MAX_CACHED_CHATS = 20;++/**+ * One Chat per conversation id, outside React. The chat page remounts on the+ * first send (the URL gains the conversation id), and a remount must pick up+ * the stream in flight instead of starting a new, empty chat.+ */+const chats = new Map<string, ChatEntry>();++function getChatEntry(+ id: string,+ initialMessages: AssistantUIMessage[],+ transport: DefaultChatTransport<AssistantUIMessage>+): ChatEntry {+ const existing = chats.get(id);+ if (existing) {+ return existing;+ }+ const entry: ChatEntry = {+ chat: null as unknown as Chat<AssistantUIMessage>,+ handlers: null,+ request: { modelId: null },+ };+ entry.chat = new Chat<AssistantUIMessage>({+ id,+ messages: initialMessages,+ transport,+ sendAutomaticallyWhen: (state) =>+ lastAssistantMessageIsCompleteWithToolCalls(state) ||+ lastAssistantMessageIsCompleteWithApprovalResponses(state),+ onToolCall: ({ toolCall }) => {+ if (!toolCall.dynamic) {+ entry.handlers?.onToolCall(toolCall);+ }+ },+ onData: (part) => {+ if (part.type === 'data-title') {+ entry.handlers?.onTitle(part.data.title);+ }+ },+ onFinish: () => entry.handlers?.onFinish(),+ });+ chats.set(id, entry);+ if (chats.size > MAX_CACHED_CHATS) {+ const oldest = chats.keys().next().value;+ if (oldest !== undefined && oldest !== id) {+ chats.delete(oldest);+ }+ }+ return entry;+}++export interface ChatSessionOptions {+ conversationId: string;+ initialMessages: AssistantUIMessage[];+ initialTitle: string | null;+ modelId: string | null;+ hint?: ChatLaunchHint;+}++/** One `useChat` wired to the API, the router, the modals and the conversation list. */+export function useChatSession(options: ChatSessionOptions) {+ const { apiUrl } = useAppContext();+ const { organizationId, projectId } = useAppParams();+ const trpc = useTRPC();+ const queryClient = useQueryClient();+ const [title, setTitle] = useState<string | null>(options.initialTitle);++ const transport = useMemo(+ () =>+ new DefaultChatTransport<AssistantUIMessage>({+ api: `${apiUrl}/ai/chat`,+ credentials: 'include',+ prepareSendMessagesRequest: ({ id, messages, trigger, messageId }) => ({+ body: {+ id,+ projectId,+ organizationId,+ modelId: chats.get(id)?.request.modelId ?? undefined,+ trigger,+ messageId,+ message: messages.at(-1),+ hint: chats.get(id)?.request.hint,+ },+ }),+ }),+ [apiUrl, projectId, organizationId]+ );++ const invalidateList = useCallback(() => {+ queryClient.invalidateQueries(trpc.conversation.list.pathFilter());+ }, [queryClient, trpc]);++ // The handlers close over router and modal state, so the cached Chat reads+ // the latest ones through the registry instead of the ones it was built with.+ const handlers: ChatHandlers = {+ onToolCall: (toolCall) => {+ if (toolCall.toolName === 'navigate') {+ const input = toolCall.input as NavigateInput;+ // Offered as a link, not followed: moving away mid-answer loses the answer.+ chat.addToolOutput({+ tool: 'navigate',+ toolCallId: toolCall.toolCallId,+ output: { opened: fillRoute(input, { organizationId, projectId }) },+ });+ return;+ }+ if (toolCall.toolName === 'open_dialog') {+ const input = toolCall.input as OpenDialogInput;+ // Offered as a button, not opened: a dialog appearing mid-answer is confusing.+ chat.addToolOutput({+ tool: 'open_dialog',+ toolCallId: toolCall.toolCallId,+ output: { opened: input.dialog },+ });+ }+ },+ onTitle: setTitle,+ onFinish: invalidateList,+ };+ const entry = getChatEntry(+ options.conversationId,+ options.initialMessages,+ transport+ );+ entry.handlers = handlers;+ entry.request = { modelId: options.modelId, hint: options.hint };+ const chat = useChat<AssistantUIMessage>({ chat: entry.chat });++ useEffect(() => {+ setTitle(options.initialTitle);+ }, [options.initialTitle]);++ return { ...chat, title, invalidateList };+}++export type ChatSession = ReturnType<typeof useChatSession>;diff --git a/apps/start/src/components/organization/feedback-prompt.tsx b/apps/start/src/components/organization/feedback-prompt.tsxindex c32592bdb..d8e0e1569 100644--- a/apps/start/src/components/organization/feedback-prompt.tsx+++ b/apps/start/src/components/organization/feedback-prompt.tsx@@ -1,3 +1,4 @@+import { useLocation } from '@tanstack/react-router';import { useEffect, useMemo } from 'react';import { PromptCard } from '@/components/organization/prompt-card';import { Button } from '@/components/ui/button';@@ -9,6 +10,8 @@ const THIRTY_DAYS_IN_SECONDS = 60 * 60 * 24 * 30;export default function FeedbackPrompt() {const { isSelfHosted, isDemo } = useAppContext();+ // The chat page owns the bottom of the screen; the card would cover the composer.+ const onChatPage = useLocation().pathname.endsWith('/chat');const [feedbackPromptSeen, setFeedbackPromptSeen] = useCookieStore('feedback-prompt-seen','',@@ -16,7 +19,7 @@ export default function FeedbackPrompt() {);const shouldShow = useMemo(() => {- if (isSelfHosted) {+ if (isSelfHosted || onChatPage) {return false;}@@ -39,7 +42,7 @@ export default function FeedbackPrompt() {// If date parsing fails, show the promptreturn true;}- }, [isDemo, isSelfHosted, feedbackPromptSeen]);+ }, [isDemo, isSelfHosted, onChatPage, feedbackPromptSeen]);const handleGiveFeedback = () => {// Open userjot widgetdiff --git a/apps/start/src/components/overview/filter-command-url.ts b/apps/start/src/components/overview/filter-command-url.tsnew file mode 100644index 000000000..7ebf1439d--- /dev/null+++ b/apps/start/src/components/overview/filter-command-url.ts@@ -0,0 +1,98 @@+/**+ * Applies a filter command to the overview URL in one navigation, so one+ * command that changes the range and a filter is one history entry and one+ * round of queries. The params match what the overview hooks read:+ * `range`/`start`/`end`/`overrideInterval`, `events`, and `f`.+ */++interface PropertyFilter {+ name: string;+ operator?: string;+ value: string[];+}++export interface FilterCommand {+ applyFilters?: {+ range?: string;+ startDate?: string;+ endDate?: string;+ interval?: string;+ } | null;+ setPropertyFilters?: { filters: PropertyFilter[] } | null;+ setEventNamesFilter?: { eventNames: string[] } | null;+}++function pushUrl(url: URL): void {+ window.history.pushState(null, '', url.toString());+ // nuqs listens for popstate; a pushState alone does not re-render.+ window.dispatchEvent(new PopStateEvent('popstate'));+}++function applyRange(+ url: URL,+ input: NonNullable<FilterCommand['applyFilters']>+): void {+ if (input.startDate && input.endDate) {+ url.searchParams.set('range', 'custom');+ url.searchParams.set('start', input.startDate);+ url.searchParams.set('end', input.endDate);+ } else if (input.range) {+ url.searchParams.set('range', input.range);+ url.searchParams.delete('start');+ url.searchParams.delete('end');+ }+ if (input.interval) {+ url.searchParams.set('overrideInterval', input.interval);+ }+}++/** Mirrors `useEventQueryFilters`: `name,operator,value1|value2` joined by `;`. */+function serializePropertyFilters(filters: PropertyFilter[]): string {+ return filters+ .map((filter) => {+ const operator = filter.operator ?? 'is';+ const values = filter.value+ .map((value) => encodeURIComponent(value.trim()))+ .join('|');+ return `${filter.name},${operator},${values}`;+ })+ .join(';');+}++export function applyFilterCommandToUrl(command: FilterCommand): number {+ if (typeof window === 'undefined') {+ return 0;+ }+ const url = new URL(window.location.href);+ let applied = 0;+ if (command.applyFilters) {+ applyRange(url, command.applyFilters);+ applied += 1;+ }+ if (command.setPropertyFilters) {+ if (command.setPropertyFilters.filters.length === 0) {+ url.searchParams.delete('f');+ } else {+ url.searchParams.set(+ 'f',+ serializePropertyFilters(command.setPropertyFilters.filters)+ );+ }+ applied += 1;+ }+ if (command.setEventNamesFilter) {+ if (command.setEventNamesFilter.eventNames.length === 0) {+ url.searchParams.delete('events');+ } else {+ url.searchParams.set(+ 'events',+ command.setEventNamesFilter.eventNames.join(',')+ );+ }+ applied += 1;+ }+ if (applied > 0) {+ pushUrl(url);+ }+ return applied;+}diff --git a/apps/start/src/components/overview/overview-ai-command.tsx b/apps/start/src/components/overview/overview-ai-command.tsxindex 1222c2bb8..db85673f8 100644--- a/apps/start/src/components/overview/overview-ai-command.tsx+++ b/apps/start/src/components/overview/overview-ai-command.tsx@@ -2,8 +2,8 @@ import { useMutation } from '@tanstack/react-query';import { Loader2Icon, SparklesIcon } from 'lucide-react';import { useState } from 'react';import { toast } from 'sonner';-import { applyFilterCommandToUrl } from '../chat/tool-handlers';import { Input } from '../ui/input';+import { applyFilterCommandToUrl } from './filter-command-url';import { useOverviewOptions } from './useOverviewOptions';import { useAppParams } from '@/hooks/use-app-params';import {@@ -23,7 +23,7 @@ import { cn } from '@/utils/cn';* page header, `w-full` inside a filter sheet).*/export function OverviewAICommand({ className }: { className?: string }) {- const { projectId, organizationId } = useAppParams();+ const { projectId } = useAppParams();const { range, startDate, endDate, interval } = useOverviewOptions();const [eventNames] = useEventQueryNamesFilter();const [eventFilters] = useEventQueryFilters();@@ -77,8 +77,6 @@ export function OverviewAICommand({ className }: { className?: string }) {projectId,query,pageContext: {- page: 'overview',- route: { projectId, organizationId },filters: {range,startDate: startDate ?? undefined,diff --git a/apps/start/src/components/providers.tsx b/apps/start/src/components/providers.tsxindex 3c61440bd..3082f5773 100644--- a/apps/start/src/components/providers.tsx+++ b/apps/start/src/components/providers.tsx@@ -7,7 +7,6 @@ import {ChartConfigProvider,type ChartConfigValue,} from '@/components/charts/chart-config-context';-import { ChatStateProvider } from '@/components/chat/chat-context';import { NotificationProvider } from '@/components/notifications/notification-provider';import { TooltipProvider } from '@/components/ui/tooltip';import { PageContextProvider } from '@/contexts/page-context';@@ -37,12 +36,10 @@ export function Providers({ children }: { children: React.ReactNode }) {<TooltipProvider delayDuration={200}><ChartConfigProvider value={CHART_CONFIG}><PageContextProvider>- <ChatStateProvider>- {children}- <NotificationProvider />- <Toaster />- <ModalProvider />- </ChatStateProvider>+ {children}+ <NotificationProvider />+ <Toaster />+ <ModalProvider /></PageContextProvider></ChartConfigProvider></TooltipProvider>diff --git a/apps/start/src/components/sidebar-project-menu.tsx b/apps/start/src/components/sidebar-project-menu.tsxindex 2e66633f4..1330a05a2 100644--- a/apps/start/src/components/sidebar-project-menu.tsx+++ b/apps/start/src/components/sidebar-project-menu.tsx@@ -33,7 +33,7 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from './ui/dropdown-menu';-import { useChatState } from '@/components/chat/chat-context';+import { useChatLaunch } from '@/components/chat/chat-launch';import { SidebarChatComposer } from '@/components/chat/sidebar-chat-composer';import { pushModal } from '@/modals';import { cn } from '@/utils/cn';@@ -99,7 +99,7 @@ export default function SidebarProjectMenu({export function ActionCTAButton() {const navigate = useNavigate();- const { openChatForContext } = useChatState();+ const launchChat = useChatLaunch();const ACTIONS = [{@@ -119,7 +119,7 @@ export function ActionCTAButton() {{label: 'Ask AI',icon: SparklesIcon,- onClick: () => openChatForContext(),+ onClick: () => launchChat(),},{label: 'Create dashboard',diff --git a/apps/start/src/components/sidebar.tsx b/apps/start/src/components/sidebar.tsxindex d461e3399..141f49535 100644--- a/apps/start/src/components/sidebar.tsx+++ b/apps/start/src/components/sidebar.tsx@@ -3,7 +3,7 @@ import { useQuery } from '@tanstack/react-query';import { Link, useLocation, useParams } from '@tanstack/react-router';import { MenuIcon, SparklesIcon, XIcon } from 'lucide-react';import { useEffect, useState } from 'react';-import { useChatState } from './chat/chat-context';+import { useChatLaunch } from './chat/chat-launch';import { FeedbackButton } from './feedback-button';import { LogoSquare } from './logo';import { ProfileToggle } from './profile-toggle';@@ -80,7 +80,7 @@ export function SidebarContainer({const location = useLocation();const { isSelfHosted } = useAppContext();const { projectId } = useParams({ strict: false });- const { isOpen: chatOpen, openChatForContext, closeChat } = useChatState();+ const launchChat = useChatLaunch();useEffect(() => {setActive(false);@@ -149,9 +149,7 @@ export function SidebarContainer({<buttonaria-label="Open AI chat"className="flex h-12 w-12 items-center justify-center border-border border-r font-medium text-muted-foreground text-sm transition-colors hover:bg-accent hover:text-accent-foreground"- onClick={() =>- chatOpen ? closeChat() : openChatForContext()- }+ onClick={() => launchChat()}title="Open AI chat (⌘J)"type="button">diff --git a/apps/start/src/contexts/page-context.tsx b/apps/start/src/contexts/page-context.tsxindex c1698e08f..11b856a60 100644--- a/apps/start/src/contexts/page-context.tsx+++ b/apps/start/src/contexts/page-context.tsx@@ -1,13 +1,7 @@-import type {- PageContextPage,- PageContext as ValidatedPageContext,-} from '@openpanel/core/modules/assistant/assistant.constants';-import type {- IChartEventFilter,- IChartRange,- IInterval,- IReportInput,-} from '@openpanel/core/modules/report/report.constants';+import type { ChatLaunchHint } from '@openpanel/core/modules/assistant/assistant.constants';++export type { ChatLaunchHint } from '@openpanel/core/modules/assistant/assistant.constants';+import {createContext,type MutableRefObject,@@ -20,56 +14,25 @@ import {useState,} from 'react';-export type { PageContextPage };-/**- * What the chat backend needs to know about "what the user is currently- * looking at".- *- * Same wire shape as `ValidatedPageContext` from- * `@openpanel/core`'s assistant.constants, but with stricter typing for- * `filters` / `reportDraft`. The validation- * schema keeps those loose (`z.record(unknown)`) because Zod can't narrow- * `IChartEventFilter` / `IReportInput` at the boundary; the server- * re-narrows in `@openpanel/core`'s- * `modules/assistant/src/tools/helpers.ts` (`pageContextFilters`).- *- * Each target page calls `usePageContext({...})` in an effect; the- * provider stores the latest value. The chat drawer reads it via a ref so- * it always sends the *current* page's context with each request, even on- * an old conversation.+ * What the chat is told about the page it was launched from: the page, an+ * entity id, the visible date window. Pages register it; the launcher reads it.*/-export type PageContext = Omit<- ValidatedPageContext,- 'filters' | 'reportDraft'-> & {- filters?: {- range?: IChartRange;- startDate?: string;- endDate?: string;- interval?: IInterval;- eventNames?: string[];- eventFilters?: IChartEventFilter[];- search?: string;- };- reportDraft?: IReportInput;-};--type PageContextValue = {- context: PageContext | null;- setContext: (ctx: PageContext | null) => void;- ref: MutableRefObject<PageContext | null>;-};+interface PageContextValue {+ context: ChatLaunchHint | null;+ setContext: (hint: ChatLaunchHint | null) => void;+ ref: MutableRefObject<ChatLaunchHint | null>;+}const PageContextContext = createContext<PageContextValue | null>(null);export function PageContextProvider({ children }: { children: ReactNode }) {- const [context, setContextState] = useState<PageContext | null>(null);- const ref = useRef<PageContext | null>(null);+ const [context, setContextState] = useState<ChatLaunchHint | null>(null);+ const ref = useRef<ChatLaunchHint | null>(null);- const setContext = useCallback((ctx: PageContext | null) => {- ref.current = ctx;- setContextState(ctx);+ const setContext = useCallback((hint: ChatLaunchHint | null) => {+ ref.current = hint;+ setContextState(hint);}, []);const value = useMemo(@@ -92,36 +55,22 @@ function useInternalPageContext(): PageContextValue {return value;}-/** Read the current page context from React state (causes re-renders). */-export function usePageContextValue(): PageContext | null {+export function usePageContextValue(): ChatLaunchHint | null {return useInternalPageContext().context;}-/**- * Read the current page context via ref. Use inside `useChat`'s- * `prepareSendMessagesRequest` so the chat always sends the *latest*- * page's context without forcing a hook re-run on every keystroke.- */-export function usePageContextRef(): MutableRefObject<PageContext | null> {+/** The latest hint without re-rendering on every change; read it at launch time. */+export function usePageContextRef(): MutableRefObject<ChatLaunchHint | null> {return useInternalPageContext().ref;}-/**- * Register a page context. The current page calls this in an effect; the- * provider keeps the latest value. Cleanup clears it when the page- * unmounts so a stale context doesn't leak between routes.- *- * The context is JSON-serialized for the dependency list to avoid- * referential-equality re-renders on identical-but-new objects.- */-export function usePageContext(context: PageContext): void {+/** Register the current page's hint; cleared when the page unmounts. */+export function usePageContext(hint: ChatLaunchHint): void {const { setContext } = useInternalPageContext();- const serialized = JSON.stringify(context);+ const serialized = JSON.stringify(hint);- // biome-ignore lint/correctness/useExhaustiveDependencies: serialized is the stable depuseEffect(() => {- setContext(context);+ setContext(JSON.parse(serialized) as ChatLaunchHint);return () => setContext(null);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [serialized]);+ }, [serialized, setContext]);}diff --git a/apps/start/src/hooks/use-page-context-helpers.ts b/apps/start/src/hooks/use-page-context-helpers.tsindex d8a2c21c6..c21c46377 100644--- a/apps/start/src/hooks/use-page-context-helpers.ts+++ b/apps/start/src/hooks/use-page-context-helpers.ts@@ -1,109 +1,44 @@-import type { IReportInput } from '@openpanel/core/modules/report/report.constants';-import { useAppParams } from './use-app-params';-import {- useEventQueryFilters,- useEventQueryNamesFilter,-} from './use-event-query-filters';+import type { ChatLaunchHint } from '@openpanel/core/modules/assistant/assistant.constants';import { useOverviewOptions } from '@/components/overview/useOverviewOptions';-import {- type PageContext,- type PageContextPage,- usePageContext,-} from '@/contexts/page-context';+import { usePageContext } from '@/contexts/page-context';-/**- * For pages that share the standard date-range / interval filters- * (Overview, Insights, Pages, SEO, Events, etc.). Reads the current- * range + interval from `useOverviewOptions` and registers the page- * context.- */-export function useRangePageContext(page: PageContextPage) {- const { projectId, organizationId } = useAppParams();- const { range, startDate, endDate, interval } = useOverviewOptions();- const [eventNames] = useEventQueryNamesFilter();- const [eventFilters] = useEventQueryFilters();+type RangePage = Extract<+ ChatLaunchHint['page'],+ 'overview' | 'insights' | 'pages' | 'seo' | 'events' | 'realtime'+>;+/** Pages with the shared date-range picker. */+export function useRangePageContext(page: RangePage) {+ const { range, startDate, endDate, interval } = useOverviewOptions();usePageContext({page,- route: { projectId, organizationId },- filters: {- range,- startDate: startDate ?? undefined,- endDate: endDate ?? undefined,- interval: interval ?? undefined,- // Send the active event-name + property filters so the chat- // assistant can reason about the current view (e.g. "you're- // already filtering to mobile") and produce diff-style- // updates via the apply_filters tool.- ...(eventNames.length > 0 ? { eventNames } : {}),- ...(eventFilters.length > 0 ? { eventFilters } : {}),- },+ range,+ startDate: startDate ?? undefined,+ endDate: endDate ?? undefined,+ interval: interval ?? undefined,});}-/**- * For entity-detail pages (session detail, profile detail, group detail).- * Takes the primary IDs + an optional primer object (small structured- * snapshot of what's visible — country, device, duration, etc.) so the- * model can answer trivial follow-ups without a tool call.- */+/** Detail pages: the entity the user is looking at. */export function useEntityPageContext(- page: 'sessionDetail' | 'profileDetail' | 'groupDetail',- ids: PageContext['ids'],- primer?: Record<string, unknown>+ page: 'profile' | 'session' | 'group',+ ids: Pick<ChatLaunchHint, 'profileId' | 'sessionId' | 'groupId'>) {- const { projectId, organizationId } = useAppParams();-- usePageContext({- page,- route: { projectId, organizationId },- ids,- primer,- });+ usePageContext({ page, ...ids });}-/**- * 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();+export function useDashboardPageContext(dashboardId: string) {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 } : {}),+ dashboardId,+ range,+ startDate: startDate ?? undefined,+ endDate: endDate ?? undefined,+ interval: interval ?? undefined,});}-/**- * For the Report Editor page. Sends the full live report draft so the- * model can propose concrete edits via `preview_report_with_changes`.- */-export function useReportEditorContext(reportDraft: IReportInput | null) {- const { projectId, organizationId } = useAppParams();-- // The draft can be null while the report loads — the cleanup handler- // in usePageContext clears it on unmount, so passing null on every- // render before the data arrives is safe (we just register a context- // without a draft until the first render with a real draft).- usePageContext({- page: 'reportEditor',- route: { projectId, organizationId },- ...(reportDraft ? { reportDraft } : {}),- });+export function useReportEditorContext(reportId: string | null | undefined) {+ usePageContext({ page: 'report', reportId: reportId ?? undefined });}diff --git a/apps/start/src/modals/add-client.tsx b/apps/start/src/modals/add-client.tsxindex 22f8c0dfb..acec2be5c 100644--- a/apps/start/src/modals/add-client.tsx+++ b/apps/start/src/modals/add-client.tsx@@ -24,13 +24,18 @@ const validation = z.object({type IForm = z.infer<typeof validation>;-export default function AddClient() {+export interface AddClientProps {+ name?: string;+ type?: IForm['type'];+}++export default function AddClient({ name, type }: AddClientProps = {}) {const { organizationId, projectId } = useAppParams();const form = useForm<IForm>({resolver: zodResolver(validation),defaultValues: {- name: '',- type: 'write',+ name: name ?? '',+ type: type ?? 'write',},});const queryClient = useQueryClient();diff --git a/apps/start/src/modals/add-dashboard.tsx b/apps/start/src/modals/add-dashboard.tsxindex 7c4e857fe..c3410ed68 100644--- a/apps/start/src/modals/add-dashboard.tsx+++ b/apps/start/src/modals/add-dashboard.tsx@@ -18,7 +18,11 @@ const validator = z.object({type IForm = z.infer<typeof validator>;-export default function AddDashboard() {+export interface AddDashboardProps {+ name?: string;+}++export default function AddDashboard({ name }: AddDashboardProps = {}) {const { projectId, organizationId } = useAppParams();const router = useRouter();const trpc = useTRPC();@@ -27,7 +31,7 @@ export default function AddDashboard() {const { register, handleSubmit, formState } = useForm<IForm>({resolver: zodResolver(validator),defaultValues: {- name: '',+ name: name ?? '',},});diff --git a/apps/start/src/modals/add-reference.tsx b/apps/start/src/modals/add-reference.tsxindex 4c84a09c2..21e45bc68 100644--- a/apps/start/src/modals/add-reference.tsx+++ b/apps/start/src/modals/add-reference.tsx@@ -16,17 +16,23 @@ import { handleError, useTRPC } from '@/integrations/trpc/react';type IForm = z.infer<typeof zCreateReference>;interface AddReferenceProps {+ title?: string;+ description?: string;datetime?: string;}-export default function AddReference({ datetime }: AddReferenceProps = {}) {+export default function AddReference({+ title,+ description,+ datetime,+}: AddReferenceProps = {}) {const { projectId } = useAppParams();const queryClient = useQueryClient();const { register, handleSubmit, formState, control } = useForm<IForm>({resolver: zodResolver(zCreateReference),defaultValues: {- title: '',- description: '',+ title: title ?? '',+ description: description ?? '',projectId,datetime: datetime || new Date().toISOString(),},diff --git a/apps/start/src/routeTree.gen.ts b/apps/start/src/routeTree.gen.tsindex 987eec64a..9fe298ed6 100644--- a/apps/start/src/routeTree.gen.ts+++ b/apps/start/src/routeTree.gen.ts@@ -51,6 +51,7 @@ import { Route as AppOrganizationIdProjectIdInsightsRouteImport } from './routesimport { Route as AppOrganizationIdProjectIdGroupsRouteImport } from './routes/_app.$organizationId.$projectId.groups'import { Route as AppOrganizationIdProjectIdDashboardsRouteImport } from './routes/_app.$organizationId.$projectId.dashboards'import { Route as AppOrganizationIdProjectIdCohortsRouteImport } from './routes/_app.$organizationId.$projectId.cohorts'+import { Route as AppOrganizationIdProjectIdChatRouteImport } from './routes/_app.$organizationId.$projectId.chat'import { Route as AppOrganizationIdMembersTabsIndexRouteImport } from './routes/_app.$organizationId.members._tabs.index'import { Route as AppOrganizationIdAccountTabsIndexRouteImport } from './routes/_app.$organizationId.account._tabs.index'import { Route as AppOrganizationIdMembersTabsMembersRouteImport } from './routes/_app.$organizationId.members._tabs.members'@@ -386,6 +387,12 @@ const AppOrganizationIdProjectIdCohortsRoute =path: '/cohorts',getParentRoute: () => AppOrganizationIdProjectIdRoute,} as any)+const AppOrganizationIdProjectIdChatRoute =+ AppOrganizationIdProjectIdChatRouteImport.update({+ id: '/chat',+ path: '/chat',+ getParentRoute: () => AppOrganizationIdProjectIdRoute,+ } as any)const AppOrganizationIdProjectIdProfilesProfileIdRoute =AppOrganizationIdProjectIdProfilesProfileIdRouteImport.update({id: '/$profileId',@@ -713,6 +720,7 @@ export interface FileRoutesByFullPath {'/share/overview/$shareId': typeof ShareOverviewShareIdRoute'/share/report/$shareId': typeof ShareReportShareIdRoute'/$organizationId/': typeof AppOrganizationIdIndexRoute+ '/$organizationId/$projectId/chat': typeof AppOrganizationIdProjectIdChatRoute'/$organizationId/$projectId/cohorts': typeof AppOrganizationIdProjectIdCohortsRoute'/$organizationId/$projectId/dashboards': typeof AppOrganizationIdProjectIdDashboardsRoute'/$organizationId/$projectId/groups': typeof AppOrganizationIdProjectIdGroupsRoute@@ -798,6 +806,7 @@ export interface FileRoutesByTo {'/share/overview/$shareId': typeof ShareOverviewShareIdRoute'/share/report/$shareId': typeof ShareReportShareIdRoute'/$organizationId': typeof AppOrganizationIdIndexRoute+ '/$organizationId/$projectId/chat': typeof AppOrganizationIdProjectIdChatRoute'/$organizationId/$projectId/cohorts': typeof AppOrganizationIdProjectIdCohortsRoute'/$organizationId/$projectId/dashboards': typeof AppOrganizationIdProjectIdDashboardsRoute'/$organizationId/$projectId/groups': typeof AppOrganizationIdProjectIdGroupsRoute@@ -880,6 +889,7 @@ export interface FileRoutesById {'/share/overview/$shareId': typeof ShareOverviewShareIdRoute'/share/report/$shareId': typeof ShareReportShareIdRoute'/_app/$organizationId/': typeof AppOrganizationIdIndexRoute+ '/_app/$organizationId/$projectId/chat': typeof AppOrganizationIdProjectIdChatRoute'/_app/$organizationId/$projectId/cohorts': typeof AppOrganizationIdProjectIdCohortsRoute'/_app/$organizationId/$projectId/dashboards': typeof AppOrganizationIdProjectIdDashboardsRoute'/_app/$organizationId/$projectId/groups': typeof AppOrganizationIdProjectIdGroupsRoute@@ -979,6 +989,7 @@ export interface FileRouteTypes {| '/share/overview/$shareId'| '/share/report/$shareId'| '/$organizationId/'+ | '/$organizationId/$projectId/chat'| '/$organizationId/$projectId/cohorts'| '/$organizationId/$projectId/dashboards'| '/$organizationId/$projectId/groups'@@ -1064,6 +1075,7 @@ export interface FileRouteTypes {| '/share/overview/$shareId'| '/share/report/$shareId'| '/$organizationId'+ | '/$organizationId/$projectId/chat'| '/$organizationId/$projectId/cohorts'| '/$organizationId/$projectId/dashboards'| '/$organizationId/$projectId/groups'@@ -1145,6 +1157,7 @@ export interface FileRouteTypes {| '/share/overview/$shareId'| '/share/report/$shareId'| '/_app/$organizationId/'+ | '/_app/$organizationId/$projectId/chat'| '/_app/$organizationId/$projectId/cohorts'| '/_app/$organizationId/$projectId/dashboards'| '/_app/$organizationId/$projectId/groups'@@ -1569,6 +1582,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AppOrganizationIdProjectIdCohortsRouteImportparentRoute: typeof AppOrganizationIdProjectIdRoute}+ '/_app/$organizationId/$projectId/chat': {+ id: '/_app/$organizationId/$projectId/chat'+ path: '/chat'+ fullPath: '/$organizationId/$projectId/chat'+ preLoaderRoute: typeof AppOrganizationIdProjectIdChatRouteImport+ parentRoute: typeof AppOrganizationIdProjectIdRoute+ }'/_app/$organizationId/$projectId/profiles/$profileId': {id: '/_app/$organizationId/$projectId/profiles/$profileId'path: '/$profileId'@@ -2252,6 +2272,7 @@ const AppOrganizationIdProjectIdGroupsGroupIdRouteWithChildren =)interface AppOrganizationIdProjectIdRouteChildren {+ AppOrganizationIdProjectIdChatRoute: typeof AppOrganizationIdProjectIdChatRouteAppOrganizationIdProjectIdCohortsRoute: typeof AppOrganizationIdProjectIdCohortsRouteAppOrganizationIdProjectIdDashboardsRoute: typeof AppOrganizationIdProjectIdDashboardsRouteAppOrganizationIdProjectIdGroupsRoute: typeof AppOrganizationIdProjectIdGroupsRoute@@ -2277,6 +2298,7 @@ interface AppOrganizationIdProjectIdRouteChildren {const AppOrganizationIdProjectIdRouteChildren: AppOrganizationIdProjectIdRouteChildren ={+ AppOrganizationIdProjectIdChatRoute: AppOrganizationIdProjectIdChatRoute,AppOrganizationIdProjectIdCohortsRoute:AppOrganizationIdProjectIdCohortsRoute,AppOrganizationIdProjectIdDashboardsRoute:diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.chat.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.chat.tsxnew file mode 100644index 000000000..f7db1138b--- /dev/null+++ b/apps/start/src/routes/_app.$organizationId.$projectId.chat.tsx@@ -0,0 +1,138 @@+import { zChatLaunchHint } from '@openpanel/core/modules/assistant/assistant.constants';+import { useQuery } from '@tanstack/react-query';+import { createFileRoute, useNavigate } from '@tanstack/react-router';+import { useCallback, useMemo, useState } from 'react';+import { z } from 'zod';+import { ChatNotConfigured } from '@/components/chat/chat-empty';+import { ChatLayout, ChatPaneLoading } from '@/components/chat/chat-layout';+import { ChatView } from '@/components/chat/chat-view';+import type { AssistantUIMessage } from '@/components/chat/types';+import FullPageLoadingState from '@/components/full-page-loading-state';+import { useTRPC } from '@/integrations/trpc/react';+import { createProjectTitle } from '@/utils/title';++const searchSchema = z.object({+ /** Conversation id. Absent means a new chat. */+ c: z.string().optional(),+ /** A question to send on arrival. */+ q: z.string().optional(),+ hint: zChatLaunchHint.optional(),+});++export const Route = createFileRoute('/_app/$organizationId/$projectId/chat')({+ component: Component,+ validateSearch: searchSchema,+ head: () => ({ meta: [{ title: createProjectTitle('Chat') }] }),+});++function newConversationId(): string {+ return crypto.randomUUID();+}++function Component() {+ const { organizationId, projectId } = Route.useParams();+ const { c, q, hint } = Route.useSearch();+ const navigate = useNavigate();+ const trpc = useTRPC();++ const modelsQuery = useQuery(trpc.chat.models.queryOptions());+ // A fresh id per new chat; it becomes the URL once the first message is sent.+ const [draftId, setDraftId] = useState(newConversationId);+ // The title streams in while the first answer is generated.+ const [liveTitle, setLiveTitle] = useState<string | null>(null);+ const conversationId = c ?? draftId;++ // A chat started here lives in memory until its first turn is saved; only+ // conversations opened from the list or a link are loaded.+ const shouldLoad = !!c && c !== draftId;+ const conversationQuery = useQuery(+ trpc.conversation.get.queryOptions(+ { id: conversationId },+ { enabled: shouldLoad, retry: false }+ )+ );++ const initialMessages = useMemo<AssistantUIMessage[]>(() => {+ const rows = conversationQuery.data?.messages ?? [];+ return rows.map((row) => ({+ id: row.id,+ role: row.role as AssistantUIMessage['role'],+ parts: row.parts as AssistantUIMessage['parts'],+ metadata: (row.metadata ?? undefined) as AssistantUIMessage['metadata'],+ }));+ }, [conversationQuery.data]);++ const setSearch = useCallback(+ (next: { c?: string; q?: string }) =>+ navigate({+ to: '/$organizationId/$projectId/chat',+ params: { organizationId, projectId },+ search: { c: next.c, q: next.q, hint },+ replace: next.c === conversationId,+ }),+ [navigate, organizationId, projectId, hint, conversationId]+ );++ if (modelsQuery.isPending) {+ return <FullPageLoadingState />;+ }+ if (!modelsQuery.data || modelsQuery.data.models.length === 0) {+ return (+ <ChatFrame>+ <ChatNotConfigured />+ </ChatFrame>+ );+ }++ const loading = shouldLoad && conversationQuery.isPending;+ const activeTitle = liveTitle ?? conversationQuery.data?.title ?? null;++ return (+ <ChatFrame>+ <ChatLayout+ activeId={c ?? null}+ activeTitle={c ? activeTitle : null}+ onNew={() => {+ setDraftId(newConversationId());+ setLiveTitle(null);+ setSearch({});+ }}+ onSelect={(id) => {+ setLiveTitle(null);+ setSearch({ c: id });+ }}+ >+ {loading ? (+ <ChatPaneLoading />+ ) : (+ <ChatView+ conversationId={conversationId}+ defaultModelId={modelsQuery.data.defaultModelId}+ hint={hint}+ initialMessages={initialMessages}+ initialQuestion={q}+ initialTitle={conversationQuery.data?.title ?? null}+ key={conversationId}+ models={+ modelsQuery.data.canChooseModel ? modelsQuery.data.models : []+ }+ onFirstMessage={() => setSearch({ c: conversationId })}+ onTitleChange={setLiveTitle}+ />+ )}+ </ChatLayout>+ </ChatFrame>+ );+}++/**+ * Pinned to the viewport instead of the page's `h-screen` column, so Chrome's+ * mobile toolbar cannot push the composer off screen.+ */+function ChatFrame({ children }: { children: React.ReactNode }) {+ return (+ <div className="fixed inset-x-0 top-16 bottom-0 flex lg:top-0 lg:left-72">+ {children}+ </div>+ );+}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsxindex 8cc00c594..8cf36cadc 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx@@ -192,20 +192,7 @@ function Component() {const [layout, setLayout] = useDashboardLayout(filteredReports);- 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);+ useDashboardPageContext(dashboardId);const saveLayout = useCallback((newLayout: Layout) => {diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.tsxindex 9d626754c..81e5fbf4c 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.groups_.$groupId._tabs.tsx@@ -58,16 +58,7 @@ function Component() {trpc.group.byId.queryOptions({ id: groupId, projectId }));- useEntityPageContext(- 'groupDetail',- { groupId },- group.data- ? {- name: group.data.name,- type: group.data.type,- }- : undefined- );+ useEntityPageContext('group', { groupId });const deleteMutation = useMutation(trpc.group.delete.mutationOptions({diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.tsxindex cfc0feeb0..9a92ee7de 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.profiles.$profileId._tabs.tsx@@ -38,17 +38,7 @@ function Component() {}));- useEntityPageContext(- 'profileDetail',- { profileId },- {- country: profile.data?.properties.country,- device: profile.data?.properties.device,- browser: profile.data?.properties.browser,- os: profile.data?.properties.os,- email: profile.data?.email,- }- );+ useEntityPageContext('profile', { profileId });const { activeTab, tabs } = usePageTabs([{diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.reports_.$reportId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.reports_.$reportId.tsxindex fd89fe6ad..70ac0d455 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.reports_.$reportId.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.reports_.$reportId.tsx@@ -37,6 +37,6 @@ function Component() {const { reportId } = Route.useParams();const trpc = useTRPC();const query = useSuspenseQuery(trpc.report.get.queryOptions({ reportId }));- useReportEditorContext(query.data ?? null);+ useReportEditorContext(query.data?.id ?? null);return <ReportEditor report={query.data} />;}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsxindex 6ae21c264..c32918efb 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.sessions_.$sessionId.tsx@@ -145,20 +145,7 @@ function Component() {trpc.session.byId.queryOptions({ sessionId, projectId }));- useEntityPageContext(- 'sessionDetail',- { sessionId },- {- duration: session.duration,- eventCount: session.eventCount,- screenViewCount: session.screenViewCount,- country: session.country,- device: session.device,- isBounce: session.isBounce,- entryPath: session.entryPath,- exitPath: session.exitPath,- }- );+ useEntityPageContext('session', { sessionId });const { data: eventsData } = useSuspenseQuery(trpc.event.events.queryOptions({diff --git a/apps/start/src/routes/_app.tsx b/apps/start/src/routes/_app.tsxindex 325364893..ffcc628eb 100644--- a/apps/start/src/routes/_app.tsx+++ b/apps/start/src/routes/_app.tsx@@ -1,6 +1,12 @@-import { createFileRoute, Outlet, redirect } from '@tanstack/react-router';+import {+ createFileRoute,+ Outlet,+ redirect,+ useParams,+} from '@tanstack/react-router';import { ConstructionIcon } from 'lucide-react';-import { ChatDrawerSlot } from '@/components/chat/chat-drawer-slot';+import { useEffect } from 'react';+import { useChatLaunch } from '@/components/chat/chat-launch';import { FullPageEmptyState } from '@/components/full-page-empty-state';import { Sidebar } from '@/components/sidebar';import { buttonVariants } from '@/components/ui/button';@@ -19,6 +25,7 @@ export const Route = createFileRoute('/_app')({function AppLayout() {const { isMaintenance } = useAppContext();+ useChatShortcut();if (isMaintenance) {return (@@ -48,7 +55,25 @@ function AppLayout() {<div className="block h-16 lg:hidden" /><Outlet /></div>- <ChatDrawerSlot /></div>);}++/** ⌘J / Ctrl+J opens the chat for the current project. */+function useChatShortcut() {+ const launchChat = useChatLaunch();+ const { organizationId, projectId } = useParams({ strict: false });+ useEffect(() => {+ if (!(organizationId && projectId)) {+ return;+ }+ const handler = (event: KeyboardEvent) => {+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'j') {+ event.preventDefault();+ launchChat();+ }+ };+ window.addEventListener('keydown', handler);+ return () => window.removeEventListener('keydown', handler);+ }, [launchChat, organizationId, projectId]);+}diff --git a/bun.lock b/bun.lockindex ad407a288..aabf22adc 100644--- a/bun.lock+++ b/bun.lock@@ -94,8 +94,8 @@"apps/start": {"name": "start","dependencies": {+ "@ai-sdk/react": "4.0.148","@base-ui/react": "1.9.0",- "@better-agent/client": "0.1.0-beta.3","@codemirror/commands": "6.10.1","@codemirror/lang-javascript": "6.2.4","@codemirror/lang-json": "6.0.2",@@ -173,6 +173,7 @@"@visx/scale": "4.0.1-alpha.0","@visx/shape": "4.0.1-alpha.0","@visx/zoom": "4.0.1-alpha.0",+ "ai": "7.0.144","bind-event-listener": "3.0.0","class-variance-authority": "0.7.1","clsx": "2.1.1",@@ -293,11 +294,11 @@"name": "@openpanel/core","version": "0.0.1","dependencies": {+ "@ai-sdk/anthropic": "4.0.83",+ "@ai-sdk/openai": "4.0.97","@aws-sdk/client-s3": "3.984.0","@aws-sdk/client-sts": "3.1117.0","@babel/parser": "7.29.7",- "@better-agent/core": "0.1.0-beta.3",- "@better-agent/providers": "0.1.0-beta.3","@bull-board/api": "9.6.0","@bull-board/elysia": "9.6.0","@elysiajs/cors": "1.4.2",@@ -318,6 +319,7 @@"@slack/bolt": "3.21.4","@slack/oauth": "3.0.1","@trpc/server": "11.6.0",+ "ai": "7.0.144","arctic": "2.3.0","bullmq": "6.3.3","cheerio": "1.1.2",@@ -678,6 +680,20 @@"zod": "4.3.6",},"packages": {+ "@ai-sdk/anthropic": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "4.0.30", "@ai-sdk/provider-utils": "5.0.63" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-DoTa4lu9KMpTFeqDmu/0+yMCnF6+Hkt0d//PT7Y+UdU4yMI26Bq4FWM6Q4j9Q2MP7rJjY/JlqP0vHP8LU5hvOg=="],++ "@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "4.0.30", "@ai-sdk/provider-utils": "5.0.63", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-ha4Hm3j+8kRblmNKA7akWpTlobH2uSk0Wvbzun72LQ83o+vJzXNd3UvQ3MF2iTnB3uoGRrnNw7aDQHlK6EmPlw=="],++ "@ai-sdk/mcp": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "4.0.30", "@ai-sdk/provider-utils": "5.0.63", "cross-spawn": "^7.0.6", "pkce-challenge": "^5.0.1" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-O9zog3guttyOnJMAmVv+rfs1GvWvz5whCe5ENXwULflKRIFXKCMlqsAY9mAY683OUjPRSzV0baB6MbYYqlXAEw=="],++ "@ai-sdk/openai": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "4.0.30", "@ai-sdk/provider-utils": "5.0.63" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-lqdexxNAkkJ9WkJuJE/IG9iW6qgbUmaUn8sZujXs/FFN81b6hOkBYVgFZ1Hx1zgEGvgRFo0qYkri5OirzUgoEA=="],++ "@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-SWrYVA0pJBNIee3eHnjr9gop0n/JELHJlYksLC4/O1QIuoAxWJbI2z3pA3Q5f0fKNAfk1sS8dtAr5ppsOdcLgA=="],++ "@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "4.0.30", "@standard-schema/spec": "^1.1.0", "@workflow/serde": "4.1.0", "eventsource-parser": "^3.0.8", "undici": "^7.29.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-98Wg18IAdEIwlyon2dCvrDfLNitjwshP+EVFmwnA6+APFf7rj5nGci/B7P5qfX0ea0x9gq6ZMRQJ6Qw22mVHqg=="],++ "@ai-sdk/react": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/mcp": "2.0.79", "@ai-sdk/provider": "4.0.30", "@ai-sdk/provider-utils": "5.0.63", "ai": "7.0.144", "swr": "^2.4.1", "throttleit": "2.1.0" }, "peerDependencies": { "react": "^18 || ~19.0.1 || ~19.1.2 || ^19.2.1" } }, "sha512-uXtA7z4X3Fw0T8wf2zRGHEqrEDDwqNzcttymvlvs29tGERN5PES6U3OH9hU/1y5FkMG05fMwGhwqbToirsRhow=="],+"@alloc/quick-lru": ["@alloc/[email protected]", "", {}, "sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA=="],"@ampproject/remapping": ["@ampproject/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw=="],@@ -1062,14 +1078,6 @@"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.29.7 || ^8.0.0", "@floating-ui/utils": "^0.2.12", "reselect": "^5.3.0", "use-sync-external-store": "^1.7.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A=="],- "@better-agent/client": ["@better-agent/[email protected]", "", { "dependencies": { "@better-agent/core": "0.1.0-beta.3", "@better-agent/shared": "0.1.0-beta.3" }, "peerDependencies": { "preact": "^10.0.0", "react": "^18.0.0 || ^19.0.0", "solid-js": "^1.9.0", "svelte": "^4.0.0 || ^5.0.0", "vue": "^3.3.0" }, "optionalPeers": ["preact", "react", "solid-js", "svelte", "vue"] }, "sha512-+fqFcmxHQRBE5D69Cq8EZJpU0xjNi4UfQSSSgxwz2CWmdaGAep6Xhh5CRFaJBvqXv6+WHdM3d8g2sXQKCyZqHw=="],-- "@better-agent/core": ["@better-agent/[email protected]", "", { "dependencies": { "@better-agent/shared": "0.1.0-beta.3", "@standard-schema/spec": "1.1.0", "ajv": "^8.17.1", "json-schema-to-ts": "^3.1.1" } }, "sha512-Mic8iDyHz/2ESTgZvgslPD+zf3iYFiSBda2l0f2T3UD/wMXux9rkSVXCpD8jSgMYWUxx1gt8Fns+7IVQfbnDJw=="],-- "@better-agent/providers": ["@better-agent/[email protected]", "", { "dependencies": { "@better-agent/shared": "0.1.0-beta.3", "zod": "^4.1.13" }, "peerDependencies": { "@better-agent/core": "0.1.0-beta.3" } }, "sha512-6YEYeQSyr9a0gzdP08dcyklZ/qjyglmzeUYPg5VotQS19KmV4+ErKHyUm/clGRDdM7+qxz7cC6QbM+6uJ/USUA=="],-- "@better-agent/shared": ["@better-agent/[email protected]", "", { "dependencies": { "neverthrow": "^8.2.0" } }, "sha512-Rj39OFkWSHEl6uPf3b9zXsFMh3DjbTI9ivghh6+JToVwQM31y6PhaXpWc8xXAIZiParDetJgpNEeWip8UF2vkA=="],-"@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.3.15", "@biomejs/cli-darwin-x64": "2.3.15", "@biomejs/cli-linux-arm64": "2.3.15", "@biomejs/cli-linux-arm64-musl": "2.3.15", "@biomejs/cli-linux-x64": "2.3.15", "@biomejs/cli-linux-x64-musl": "2.3.15", "@biomejs/cli-win32-arm64": "2.3.15", "@biomejs/cli-win32-x64": "2.3.15" }, "bin": { "biome": "bin/biome" } }, "sha512-u+jlPBAU2B45LDkjjNNYpc1PvqrM/co4loNommS9/sl9oSxsAQKsNZejYuUztvToB5oXi1tN/e62iNd6ESiY3g=="],"@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-SDCdrJ4COim1r8SNHg19oqT50JfkI/xGZHSyC6mGzMfKrpNe/217Eq6y98XhNTc0vGWDjznSDNXdUc6Kg24jbw=="],@@ -2880,6 +2888,8 @@"@vercel/nft": ["@vercel/[email protected]", "", { "dependencies": { "@mapbox/node-pre-gyp": "^2.0.0", "@rollup/pluginutils": "^5.1.3", "acorn": "^8.6.0", "acorn-import-attributes": "^1.9.5", "async-sema": "^3.1.1", "bindings": "^1.4.0", "estree-walker": "2.0.2", "glob": "^13.0.0", "graceful-fs": "^4.2.9", "node-gyp-build": "^4.2.2", "picomatch": "^4.0.4", "resolve-from": "^5.0.0" }, "bin": { "nft": "out/cli.js" } }, "sha512-m1QFg+U+3yPOnP1xSYJ73UIRxLOXdts1JOhiOiyPYqEsALgrXFFINvgUaD6R6iNvaBFAjHllBCbkfx4FuOdpaA=="],+ "@vercel/oidc": ["@vercel/[email protected]", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="],+"@visx/curve": ["@visx/[email protected]", "", { "dependencies": { "@visx/vendor": "4.0.0-alpha.0" } }, "sha512-jRu61Uz274pV1zyioXmboyrLutYbnKsgjj4njSGCnhdXj5GkZvZbg+ThDb6oOzoAnJOBRLz4rzPlWvNJOzuVMg=="],"@visx/event": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@visx/point": "4.0.1-alpha.0" } }, "sha512-EQqCMSv/s8NbFjo+hz3FKsvvYfP+2QslsFJ/24/O5l/W+7UC6J6aAvO0ujVwrTwdYbuQ+vhxKi1xdPdKR/qj1g=="],@@ -2970,6 +2980,8 @@"@vue/shared": ["@vue/[email protected]", "", {}, "sha512-AbOPdQQnAnzs58H2FrrDxYj/TJfmeS2jdfEEhgiKINy+bnOANmVizIEgq1r+C5zsbs6l1CCQxtcj71rwNQ4jWg=="],+ "@workflow/serde": ["@workflow/[email protected]", "", {}, "sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ=="],+"@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA=="],"@xstate/fsm": ["@xstate/[email protected]", "", {}, "sha512-b5o1I6aLNeYlU/3CPlj/Z91ybk1gUsKT+5NAJI+2W4UjvS5KLG28K9v5UvNoFVjHV8PajVZ00RH3vnjyQO7ZAw=="],@@ -2998,6 +3010,8 @@"agentkeepalive": ["[email protected]", "", { "dependencies": { "humanize-ms": "^1.2.1" } }, "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ=="],+ "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "4.0.117", "@ai-sdk/provider": "4.0.30", "@ai-sdk/provider-utils": "5.0.63" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-gs2SI1d2Ts8/8hDXVFFFJJ0dvcfDNmbpPb6oelBmr0vTOYsoqIgDgE0otXnedD4HeAGHtrO81+/8pHPxMwekNQ=="],+"ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],"ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],@@ -4294,7 +4308,7 @@"json-pointer": ["[email protected]", "", { "dependencies": { "foreach": "^2.0.4" } }, "sha512-vLWcKbOaXlO+jvRy4qNd+TI1QUPZzfJj1tpJ3vAXDych5XJf93ftpUKe5pKCrzyIIwgBJcOcCVRUfqQP25afBw=="],- "json-schema-to-ts": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" } }, "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g=="],+ "json-schema": ["[email protected]", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="],"json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],@@ -4696,8 +4710,6 @@"neotraverse": ["[email protected]", "", {}, "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA=="],- "neverthrow": ["[email protected]", "", { "optionalDependencies": { "@rollup/rollup-linux-x64-gnu": "^4.24.0" } }, "sha512-kOCT/1MCPAxY5iUV3wytNFUMUolzuwd/VF/1KCx7kf6CutrOsTie+84zTGTpgQycjvfLdBBdvBvFLqFD2c0wkQ=="],-"next": ["[email protected]", "", { "dependencies": { "@next/env": "15.0.3", "@swc/counter": "0.1.3", "@swc/helpers": "0.5.13", "busboy": "1.6.0", "caniuse-lite": "^1.0.30001579", "postcss": "8.4.31", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "15.0.3", "@next/swc-darwin-x64": "15.0.3", "@next/swc-linux-arm64-gnu": "15.0.3", "@next/swc-linux-arm64-musl": "15.0.3", "@next/swc-linux-x64-gnu": "15.0.3", "@next/swc-linux-x64-musl": "15.0.3", "@next/swc-win32-arm64-msvc": "15.0.3", "@next/swc-win32-x64-msvc": "15.0.3", "sharp": "^0.33.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.41.2", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-66855b96-20241106", "react-dom": "^18.2.0 || 19.0.0-rc-66855b96-20241106", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-ontCbCRKJUIoivAdGB34yCaOcPgYXr9AAkV/IwqFfWWTXEPUgLYkSkqBhIk9KK7gGmgjc64B+RdoeIDM13Irnw=="],"next-themes": ["[email protected]", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],@@ -5562,6 +5574,8 @@"svgo": ["[email protected]", "", { "dependencies": { "commander": "^11.1.0", "css-select": "^6.0.0", "css-tree": "^3.0.1", "css-what": "^7.0.0", "csso": "^5.0.5", "picocolors": "^1.1.1", "sax": "1.6.1" }, "bin": { "svgo": "bin/svgo.js" } }, "sha512-bkxnTg1kSU0guhIBmibA6UUhrQmPVA1XsQLN+ylCd+UWzbnLkySOcXpyk1mrl05f+pcaCx2eHb+sp6BgMZWX+Q=="],+ "swr": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-BRw55e8r0B7SpDN20CAzoQAHl7y1yP7/Zt7oqUjMv0vSt2u2Xnkm88Ws+VypbV9BXHQVuSuyVq7zMjO16wSExw=="],+"symbol-tree": ["[email protected]", "", {}, "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw=="],"tagged-tag": ["[email protected]", "", {}, "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng=="],@@ -5602,6 +5616,8 @@"throat": ["[email protected]", "", {}, "sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA=="],+ "throttleit": ["[email protected]", "", {}, "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw=="],+"through2": ["[email protected]", "", { "dependencies": { "readable-stream": "~2.3.6", "xtend": "~4.0.1" } }, "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ=="],"tiny-emitter": ["[email protected]", "", {}, "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q=="],@@ -5660,8 +5676,6 @@"trough": ["[email protected]", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="],- "ts-algebra": ["[email protected]", "", {}, "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw=="],-"ts-interface-checker": ["[email protected]", "", {}, "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA=="],"ts-toolbelt": ["[email protected]", "", {}, "sha512-nsZd8ZeNUzukXPlJmTBwUAuABDe/9qtVDelJeT/qW0ow3ZS3BsQJtNkan1802aM9Uf68/Y8ljw86Hu0h5IUW3w=="],@@ -5976,6 +5990,8 @@"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],+ "@ai-sdk/provider-utils/undici": ["[email protected]", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="],+"@asamuzakjp/css-color/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],"@astrojs/internal-helpers/picomatch": ["[email protected]", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],@@ -7134,8 +7150,6 @@"negotiator/content-type": ["[email protected]", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],- "neverthrow/@rollup/rollup-linux-x64-gnu": ["@rollup/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-gfI5T24WLLuFfSKw7Go/zDXjAAV0fny0swTaDv+WjK7vqcw4cRhFfdsyKL1n+ukI+ooBxn3bVQnyrn06WpI50w=="],-"next/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" } }, "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ=="],"nitropack/@rollup/plugin-alias": ["@rollup/[email protected]", "", { "peerDependencies": { "rollup": ">=4.0.0" }, "optionalPeers": ["rollup"] }, "sha512-tPCzJOtS7uuVZd+xPhoy5W4vThe6KWXNmsFCNktaAh5RTqcLiSfT4huPQIXkgJ6YCOjJHvecOAzQxLFhPxKr+g=="],diff --git a/packages/core/package.json b/packages/core/package.jsonindex 42d92579f..36e14618e 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -18,11 +18,11 @@"with-env": "dotenv -e ../../.env -c --"},"dependencies": {+ "@ai-sdk/anthropic": "4.0.83",+ "@ai-sdk/openai": "4.0.97","@aws-sdk/client-s3": "3.984.0","@aws-sdk/client-sts": "3.1117.0","@babel/parser": "7.29.7",- "@better-agent/core": "0.1.0-beta.3",- "@better-agent/providers": "0.1.0-beta.3","@bull-board/api": "9.6.0","@bull-board/elysia": "9.6.0","@elysiajs/cors": "1.4.2",@@ -43,6 +43,7 @@"@slack/bolt": "3.21.4","@slack/oauth": "3.0.1","@trpc/server": "11.6.0",+ "ai": "7.0.144","arctic": "2.3.0","bullmq": "6.3.3","cheerio": "1.1.2",diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 02afd7b39..45330e99b 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -96,8 +96,11 @@ export {// `registry` itself is not exported: a caller that can reach it could start a// second collector graph outside a module.export { registerDefaultMetrics } from './metrics';-// `ChatApp` stays a type so no value of the assistant module reaches a browser bundle.-export type { ChatApp } from './modules/assistant/assistant.service';+// Type-only: no value of the assistant module reaches a browser bundle.+export type {+ AssistantUIMessage,+ AssistantUIMessagePart,+} from './modules/assistant/assistant.service';export { createAssistantService } from './modules/assistant/assistant.service';export {Arctic,diff --git a/packages/core/src/modules/assistant/assistant.constants.ts b/packages/core/src/modules/assistant/assistant.constants.tsindex cb96dde82..1b320b568 100644--- a/packages/core/src/modules/assistant/assistant.constants.ts+++ b/packages/core/src/modules/assistant/assistant.constants.ts@@ -1,259 +1,509 @@import { z } from 'zod';-export const pageContextPageSchema = z.enum([- 'overview',- 'insights',- 'pages',- 'seo',- 'sessionDetail',- 'profileDetail',- 'reportEditor',- 'events',- 'groupDetail',- 'dashboard',-]);--export const pageContextSchema = z.object({- page: pageContextPageSchema,- route: z.object({- projectId: z.string(),- organizationId: z.string(),- }),- ids: z- .object({- sessionId: z.string().optional(),- profileId: z.string().optional(),- reportId: z.string().optional(),- groupId: z.string().optional(),- dashboardId: z.string().optional(),- })- .optional(),- filters: z- .object({- range: z.string().optional(),- startDate: z.string().optional(),- endDate: z.string().optional(),- interval: z.string().optional(),- eventNames: z.array(z.string()).optional(),- eventFilters: z.array(z.record(z.string(), z.unknown())).optional(),- search: z.string().optional(),- })- .optional(),- reportDraft: z.record(z.string(), z.unknown()).optional(),- primer: z.record(z.string(), z.unknown()).optional(),-});--export type PageContext = z.infer<typeof pageContextSchema>;-export type PageContextPage = z.infer<typeof pageContextPageSchema>;+export type ChatProvider = 'openai' | 'anthropic';+export type ChatModelTier = 'fast' | 'balanced' | 'deep';+export type ChatReasoningEffort =+ | 'none'+ | 'minimal'+ | 'low'+ | 'medium'+ | 'high';-/**- * Agent context shared by every agent. `assistant.routes.ts` checks the session- * user's access to (projectId, organizationId) before a run; that is the- * module's only tenancy gate, so tools trust `context.projectId`.- */-export const chatContextSchema = z.object({- projectId: z.string(),- organizationId: z.string(),- pageContext: pageContextSchema.optional(),-});--export type ChatAgentContext = z.infer<typeof chatContextSchema>;--export type ChatProvider = 'OpenAI' | 'Anthropic';--export type ChatModelEntry = {- /** URL-safe agent name (no colons, slashes, or percent-encoding needed). */+export interface ChatModelEntry {+ /** URL- and storage-safe id. */id: string;- /** Native model id passed to the provider client. */+ /** Native model id passed to the provider. */modelId: string;label: string;- group: ChatProvider;- /** Only for reasoning-capable models; others reject the `reasoning` option. */- reasoning?: boolean;-};+ provider: ChatProvider;+ tier: ChatModelTier;+ reasoning: ChatReasoningEffort;+ description: string;+}export const CHAT_MODELS = [- { id: 'gpt-4-1', modelId: 'gpt-4.1', label: 'GPT-4.1', group: 'OpenAI' },{- id: 'gpt-4-1-mini',- modelId: 'gpt-4.1-mini',- label: 'GPT-4.1 mini',- group: 'OpenAI',+ id: 'gpt-6-1-sol',+ modelId: 'gpt-6.1-sol',+ label: 'GPT-6.1 Sol',+ provider: 'openai',+ tier: 'balanced',+ reasoning: 'low',+ description: 'Quick and capable. The default.',},{- id: 'gpt-5.4-mini',+ id: 'gpt-5-4-mini',modelId: 'gpt-5.4-mini',label: 'GPT-5.4 mini',- group: 'OpenAI',- reasoning: true,+ provider: 'openai',+ tier: 'fast',+ reasoning: 'low',+ description: 'Fastest and cheapest.',+ },+ {+ id: 'gpt-5-5',+ modelId: 'gpt-5.5',+ label: 'GPT-5.5',+ provider: 'openai',+ tier: 'deep',+ reasoning: 'medium',+ description: 'Slower. Thinks harder on tricky analysis.',},{- id: 'claude-haiku-4-5',- modelId: 'claude-haiku-4-5',- label: 'Claude Haiku 4.5',- group: 'Anthropic',+ id: 'claude-sonnet-5-5',+ modelId: 'claude-sonnet-5-5',+ label: 'Claude Sonnet 5.5',+ provider: 'anthropic',+ tier: 'balanced',+ reasoning: 'low',+ description: 'Quick and capable.',},{- id: 'claude-sonnet-4-6',- modelId: 'claude-sonnet-4-6',- label: 'Claude Sonnet 4.6',- group: 'Anthropic',+ id: 'claude-haiku-5-5',+ modelId: 'claude-haiku-5-5',+ label: 'Claude Haiku 5.5',+ provider: 'anthropic',+ tier: 'fast',+ reasoning: 'low',+ description: 'Fastest and cheapest.',},{- id: 'claude-opus-4-6',- modelId: 'claude-opus-4-6',- label: 'Claude Opus 4.6',- group: 'Anthropic',+ id: 'claude-opus-5-5',+ modelId: 'claude-opus-5-5',+ label: 'Claude Opus 5.5',+ provider: 'anthropic',+ tier: 'deep',+ reasoning: 'medium',+ description: 'Slower. Thinks harder on tricky analysis.',},] as const satisfies readonly ChatModelEntry[];export type ChatModelId = (typeof CHAT_MODELS)[number]['id'];-/**- * localStorage key for the preferred chat model id. Bump the suffix when the- * default changes: it invalidates models users had pinned (gpt-4-1 hit Tier 1- * rate limits almost immediately).- */-export const MODEL_STORAGE_KEY = 'op-chat-model-v2';+/** Bumped when the default changes so a stale pinned model does not stick. */+export const MODEL_STORAGE_KEY = 'op-chat-model-v3';-/**- * Preferred default model id when its provider is configured. gpt-4.1-mini has- * a far higher per-minute token budget than gpt-4.1 on OpenAI Tier 1 (200k vs 30k TPM).- */-export const PREFERRED_DEFAULT_MODEL_ID = 'gpt-4-1-mini';+/** OpenAI first: Cloud already runs with that key. */+export const DEFAULT_MODEL_BY_PROVIDER = {+ openai: 'gpt-6-1-sol',+ anthropic: 'claude-sonnet-5-5',+} as const satisfies Record<ChatProvider, ChatModelId>;++export type ConfiguredProviders = Record<ChatProvider, boolean>;export function isValidModelId(id: string | null | undefined): id is ChatModelId {- return !!id && CHAT_MODELS.some((m) => m.id === id);+ return !!id && CHAT_MODELS.some((model) => model.id === id);}export function getModelLabel(id: string): string {- return CHAT_MODELS.find((m) => m.id === id)?.label ?? id;+ return CHAT_MODELS.find((model) => model.id === id)?.label ?? id;}-/** Models whose provider has an API key configured, in `CHAT_MODELS` order so the first entry is a stable default. */-export function getAvailableChatModels(providers: {- openai: boolean;- anthropic: boolean;-}): ChatModelEntry[] {- return CHAT_MODELS.filter((m) => {- if (m.group === 'OpenAI') {- return providers.openai;- }- if (m.group === 'Anthropic') {- return providers.anthropic;- }- return false;- });+export function getAvailableChatModels(+ providers: ConfiguredProviders+): ChatModelEntry[] {+ return CHAT_MODELS.filter((model) => providers[model.provider]);}-export const applyFiltersSchema = z.object({- range: z- .enum([- '30min',- 'lastHour',- 'today',- 'yesterday',- '7d',- '30d',- '6m',- '12m',- 'monthToDate',- 'lastMonth',- 'yearToDate',- 'lastYear',- 'custom',- ])- .optional()- .describe(- 'Preset date range. Use ONE of these exact values; anything else (e.g. "last week", "14d", "Q1 2026") MUST go through startDate + endDate as a custom range.'- ),- startDate: z- .string()- .optional()- .describe(- 'ISO date YYYY-MM-DD. Pair with endDate for custom ranges. Switches range to custom automatically.'- ),- endDate: z- .string()- .optional()- .describe('ISO date YYYY-MM-DD. Pair with startDate.'),- interval: z- .enum(['minute', 'hour', 'day', 'week', 'month'])- .optional()- .describe(- 'Override the chart interval (otherwise auto-picked from the range).'- ),+export function getDefaultChatModelId(+ providers: ConfiguredProviders+): ChatModelId | null {+ if (providers.openai) {+ return DEFAULT_MODEL_BY_PROVIDER.openai;+ }+ if (providers.anthropic) {+ return DEFAULT_MODEL_BY_PROVIDER.anthropic;+ }+ return null;+}++/**+ * What the dashboard tells the chat about where it was opened from. Only the+ * cheap, stable facts: the page, an entity id and the visible date window.+ */+export const CHAT_HINT_PAGES = [+ 'overview',+ 'dashboard',+ 'report',+ 'profile',+ 'session',+ 'group',+ 'pages',+ 'seo',+ 'events',+ 'insights',+ 'realtime',+] as const;++const MAX_ID_LENGTH = 128;+const MAX_RANGE_LENGTH = 32;++export const zChatLaunchHint = z.object({+ page: z.enum(CHAT_HINT_PAGES).optional(),+ dashboardId: z.string().max(MAX_ID_LENGTH).optional(),+ reportId: z.string().max(MAX_ID_LENGTH).optional(),+ profileId: z.string().max(MAX_ID_LENGTH).optional(),+ sessionId: z.string().max(MAX_ID_LENGTH).optional(),+ groupId: z.string().max(MAX_ID_LENGTH).optional(),+ range: z.string().max(MAX_RANGE_LENGTH).optional(),+ startDate: z.string().max(MAX_RANGE_LENGTH).optional(),+ endDate: z.string().max(MAX_RANGE_LENGTH).optional(),+ interval: z.string().max(MAX_RANGE_LENGTH).optional(),});-export type ApplyFiltersInput = z.infer<typeof applyFiltersSchema>;--export const setPropertyFiltersSchema = z.object({- filters: z- .array(- z.object({- name: z- .string()- .describe(- [- 'Property key. Common values:',- '- Geo: country, region, city',- '- Device: device, browser, os',- '- Referrer: PREFER `referrer_name` for filtering by source name (e.g. "GitHub", "Hacker News", "Direct"). Use `referrer_type` only for traffic class (search, social, direct, etc.) and the raw `referrer` URL only when the user asks for an exact URL match.',- '- Page: path, origin',- '- UTM: utm_source, utm_medium, utm_campaign, utm_term, utm_content',- 'Verify with list_event_properties when unsure.',- ].join('\n')- ),- operator: z- .enum([- 'is',- 'isNot',- 'contains',- 'doesNotContain',- 'startsWith',- 'endsWith',- 'regex',- 'isNull',- 'isNotNull',- 'gt',- 'lt',- 'gte',- 'lte',- ])- .default('is'),- value: z- .array(z.string())- .describe(- 'Values to match. Multiple values are OR\'d together within the same filter (e.g. ["SE", "US"] = country is SE or US). Use [] when operator is isNull / isNotNull.'- ),- })- )- .describe(- 'The full new filter set. REPLACES the current filters — to add to the existing set, include the current ones too.'- ),+export type ChatLaunchHint = z.infer<typeof zChatLaunchHint>;++export const CHAT_MESSAGE_ROLES = ['user', 'assistant'] as const;+export const CHAT_TRIGGERS = ['submit-message', 'regenerate-message'] as const;++const MAX_MESSAGE_ID_LENGTH = 64;++/** The one message the client sends per turn: the new user message, or the assistant message it responded to (tool approvals, client tool results). */+export const zChatRequestMessage = z.object({+ id: z.string().min(1).max(MAX_MESSAGE_ID_LENGTH),+ role: z.enum(CHAT_MESSAGE_ROLES),+ parts: z.array(z.record(z.string(), z.unknown())),+ metadata: z.record(z.string(), z.unknown()).optional(),});-export type SetPropertyFiltersInput = z.infer<typeof setPropertyFiltersSchema>;+export const zChatRequest = z.object({+ id: z.string().min(1).max(MAX_MESSAGE_ID_LENGTH),+ projectId: z.string().min(1),+ organizationId: z.string().min(1),+ modelId: z.string().optional(),+ trigger: z.enum(CHAT_TRIGGERS).default('submit-message'),+ messageId: z.string().max(MAX_MESSAGE_ID_LENGTH).optional(),+ message: zChatRequestMessage.optional(),+ hint: zChatLaunchHint.optional(),+});++export type ChatRequest = z.infer<typeof zChatRequest>;-export const setEventNamesFilterSchema = z.object({- eventNames: z- .array(z.string())- .describe('Full list of event names to restrict to. Empty = show all.'),+export const zChatMessageMetadata = z.object({+ modelId: z.string().optional(),+ createdAt: z.number().optional(),+ totalTokens: z.number().optional(),+ durationMs: z.number().optional(),});-export type SetEventNamesFilterInput = z.infer<- typeof setEventNamesFilterSchema->;+export type ChatMessageMetadata = z.infer<typeof zChatMessageMetadata>;/**- * Handler map for the client-side UI tools. Inputs are `unknown` to match Better- * Agent's `toolHandlers`; the key set makes a new `.client()` tool fail to- * compile until a handler is registered.+ * Spend tiers for the chat. Cloud bands follow the plan's event limit;+ * `unlimited` is a self-hosted install (its own API key), `blocked` is a+ * workspace whose dashboard is already locked by billing.*/-export type ChatClientToolHandlers = {- apply_filters: (input: unknown) => unknown | Promise<unknown>;- set_property_filters: (input: unknown) => unknown | Promise<unknown>;- set_event_names_filter: (input: unknown) => unknown | Promise<unknown>;+export const CHAT_TIERS = [+ 'trial',+ 'starter',+ 'growth',+ 'scale',+ 'unlimited',+ 'blocked',+] as const;+export type ChatTier = (typeof CHAT_TIERS)[number];++/** Messages one workspace may send per UTC day. `null` is no cap. */+export const CHAT_MESSAGES_PER_DAY: Record<ChatTier, number | null> = {+ trial: 15,+ starter: 20,+ growth: 60,+ scale: 200,+ unlimited: null,+ blocked: 0,};++/** Plans up to this many events per month fall in the band. Above the last band is `scale`. */+export const CHAT_TIER_EVENT_BANDS = {+ starter: 100_000,+ growth: 2_500_000,+} as const;++/** Per-user burst guard on every tier, so a stuck client or script cannot loop. */+export const CHAT_BURST_LIMIT = { max: 6, windowMs: 60_000 } as const;++export const CHAT_LIMIT_REASONS = ['daily', 'burst', 'blocked'] as const;++/** Body of the 429 the chat route answers with. */+export const zChatLimitError = z.object({+ code: z.literal('chat_limit'),+ reason: z.enum(CHAT_LIMIT_REASONS),+ tier: z.enum(CHAT_TIERS),+ limit: z.number(),+ resetsAt: z.string(),+ message: z.string(),+});+export type ChatLimitError = z.infer<typeof zChatLimitError>;++/** Data parts the server streams besides the model output. */+export type ChatDataParts = Record<'title', { title: string }>;++/**+ * Where the assistant can send the user. Paths are relative to+ * `/:organizationId/:projectId` unless `scope` is `organization`.+ */+export const CHAT_ROUTES = {+ overview: {+ path: '',+ label: 'Overview',+ description:+ 'Traffic overview: visitors, sessions, pageviews, referrers, devices, countries, live visitors.',+ },+ dashboards: {+ path: '/dashboards',+ label: 'Dashboards',+ description: 'All saved dashboards.',+ },+ dashboard: {+ path: '/dashboards/:dashboardId',+ label: 'Dashboard',+ description: 'One saved dashboard and its reports.',+ params: ['dashboardId'],+ },+ reportEditor: {+ path: '/reports',+ label: 'Report editor',+ description:+ 'Build a new chart by hand: pick events, breakdowns, chart type.',+ },+ report: {+ path: '/reports/:reportId',+ label: 'Report',+ description: 'Edit one saved report.',+ params: ['reportId'],+ },+ insights: {+ path: '/insights',+ label: 'Insights',+ description: 'Automatic anomaly and trend insights.',+ },+ pages: {+ path: '/pages',+ label: 'Pages',+ description:+ 'Page performance, entry and exit pages, conversions per page.',+ },+ seo: {+ path: '/seo',+ label: 'SEO',+ description:+ 'Google Search Console queries and pages (needs the GSC integration).',+ },+ realtime: {+ path: '/realtime',+ label: 'Realtime',+ description: 'Who is on the site right now.',+ },+ events: {+ path: '/events',+ label: 'Events',+ description: 'Raw event stream with filters, conversions and event stats.',+ },+ sessions: {+ path: '/sessions',+ label: 'Sessions',+ description: 'Session list with session replays.',+ },+ session: {+ path: '/sessions/:sessionId',+ label: 'Session',+ description: 'One session: its events, path and replay.',+ params: ['sessionId'],+ },+ profiles: {+ path: '/profiles',+ label: 'Profiles',+ description: 'Identified and anonymous user profiles, power users.',+ },+ profile: {+ path: '/profiles/:profileId',+ label: 'Profile',+ description: 'One user profile with their sessions and events.',+ params: ['profileId'],+ },+ groups: {+ path: '/groups',+ label: 'Groups',+ description: 'Groups (accounts, companies) and their members.',+ },+ cohorts: {+ path: '/cohorts',+ label: 'Cohorts',+ description: 'Saved user cohorts.',+ },+ references: {+ path: '/references',+ label: 'References',+ description:+ 'Annotations like launches, campaigns and deploys that show up on charts.',+ },+ notifications: {+ path: '/notifications',+ label: 'Notifications',+ description: 'Notification history.',+ },+ notificationRules: {+ path: '/notifications/rules',+ label: 'Notification rules',+ description: 'Alert rules: notify on events or funnel completions.',+ },+ integrations: {+ path: '/integrations',+ label: 'Integrations',+ description: 'Installed integrations (Slack, Discord, webhooks, exports).',+ },+ integrationsAvailable: {+ path: '/integrations/available',+ label: 'Available integrations',+ description: 'Integrations that can be installed.',+ },+ settings: {+ path: '/settings',+ label: 'Project settings',+ description: 'Project details: name, domain, timezone, CORS, filters.',+ },+ settingsClients: {+ path: '/settings/clients',+ label: 'API clients',+ description:+ 'Client id and secret pairs used by SDKs and the API to send events.',+ },+ settingsTracking: {+ path: '/settings/tracking',+ label: 'Tracking setup',+ description: 'Install snippets and SDK setup for this project.',+ },+ settingsEvents: {+ path: '/settings/events',+ label: 'Event settings',+ description: 'Conversions, custom events and event metadata.',+ },+ settingsMcp: {+ path: '/settings/mcp',+ label: 'MCP server',+ description:+ 'Connect Claude, Cursor or another AI client to this project with MCP.',+ },+ settingsGsc: {+ path: '/settings/gsc',+ label: 'Google Search Console',+ description: 'Connect Google Search Console for SEO data.',+ },+ settingsImports: {+ path: '/settings/imports',+ label: 'Imports',+ description: 'Import historical data from other tools.',+ },+ settingsWidgets: {+ path: '/settings/widgets',+ label: 'Widgets',+ description: 'Embeddable counters and live widgets.',+ },+ workspace: {+ path: '',+ label: 'Workspace',+ description: 'The organization: its projects.',+ scope: 'organization',+ },+ workspaceSettings: {+ path: '/settings',+ label: 'Workspace settings',+ description: 'Organization name, members, invites, billing.',+ scope: 'organization',+ },+} as const satisfies Record<+ string,+ {+ path: string;+ label: string;+ description: string;+ params?: readonly string[];+ scope?: 'organization';+ }+>;++export type ChatRouteKey = keyof typeof CHAT_ROUTES;++const CHAT_ROUTE_KEYS = Object.keys(CHAT_ROUTES) as [+ ChatRouteKey,+ ...ChatRouteKey[],+];++const MAX_REASON_LENGTH = 200;++export const zNavigateInput = z.object({+ route: z.enum(CHAT_ROUTE_KEYS),+ params: z+ .record(z.string(), z.string())+ .optional()+ .describe('Route params, e.g. { "profileId": "..." }.'),+ reason: z+ .string()+ .max(MAX_REASON_LENGTH)+ .optional()+ .describe('Short label shown on the navigation card.'),+});++export type NavigateInput = z.infer<typeof zNavigateInput>;++/** Dialogs the assistant can open with prefilled fields. Keys match the modal registry in the dashboard. */+export const CHAT_DIALOGS = {+ addClient: {+ label: 'Create API client',+ description:+ 'Mint a client id and secret. Prefill: name, type (`write` for SDKs and websites, `read` for MCP and exports, `root` for the management API). The MCP token is only shown for read and root clients, so use `read` when the user wants MCP.',+ },+ addDashboard: {+ label: 'Create dashboard',+ description: 'A new empty dashboard. Prefill: name.',+ },+ addReference: {+ label: 'Add reference',+ description:+ 'Annotate a date on every chart (launch, campaign, deploy). Prefill: title, description, datetime (ISO).',+ },+ addNotificationRule: {+ label: 'Create notification rule',+ description: 'Alert on an event or a funnel. No prefill.',+ },+ addIntegration: {+ label: 'Add integration',+ description:+ 'Install an integration. Prefill: type (`slack`, `discord`, `webhook`, or another integration type).',+ },+ addProject: {+ label: 'Create project',+ description: 'A new project in the workspace. No prefill.',+ },+ inviteMember: {+ label: 'Invite member',+ description: 'Invite a teammate by email. No prefill.',+ },+ addCohort: {+ label: 'Create cohort',+ description: 'Save a user segment. No prefill.',+ },+} as const satisfies Record<string, { label: string; description: string }>;++export type ChatDialogKey = keyof typeof CHAT_DIALOGS;++const CHAT_DIALOG_KEYS = Object.keys(CHAT_DIALOGS) as [+ ChatDialogKey,+ ...ChatDialogKey[],+];++export const zOpenDialogInput = z.object({+ dialog: z.enum(CHAT_DIALOG_KEYS),+ prefill: z+ .record(z.string(), z.string())+ .optional()+ .describe('Field values to prefill where the dialog supports them.'),+});++export type OpenDialogInput = z.infer<typeof zOpenDialogInput>;++/** Tool names handled in the browser; the server declares them without `execute`. */+export const CHAT_CLIENT_TOOLS = ['navigate', 'open_dialog'] as const;+export type ChatClientToolName = (typeof CHAT_CLIENT_TOOLS)[number];diff --git a/packages/core/src/modules/assistant/assistant.routes.test.ts b/packages/core/src/modules/assistant/assistant.routes.test.tsdeleted file mode 100644index 10f9069fb..000000000--- a/packages/core/src/modules/assistant/assistant.routes.test.ts+++ /dev/null@@ -1,142 +0,0 @@-// The /ai/agents/* mount end to end through `app.handle()`, with the global-// request-logging hook mounted the way apps/api does. That hook references-// `body`, which makes Elysia parse every POST body up front; the route must-// opt out (`parse: 'none'`) or better-agent's own `request.text()` throws-// "Body is disturbed or locked" and every chat run is a 500.--import { beforeEach, expect, mock, test } from 'bun:test';-import { Elysia } from 'elysia';-import { stubAppDeps } from '../../../test/http-fixtures';-import { requestLogging } from '../../http/context';--let session: { userId: string } | null = null;-const resolveSession = mock(() => Promise.resolve(session));-mock.module('../../http/session', () => ({- SESSION_COOKIE_NAME: 'session',- resolveSession,-}));--const seenBodies: string[] = [];-mock.module('./assistant.service', () => ({- createAssistantService: () => ({- getChatApp: () => ({- handler: async (request: Request) => {- seenBodies.push(await request.text());- return new Response('ok', { status: 200 });- },- }),- getChatRunContext: () => ({- run: (_context: unknown, fn: () => Promise<Response>) => fn(),- }),- }),-}));--const { assistantRoutes } = await import('./assistant.routes');--const OWN_CONVERSATION_ID = 'conv_own';-const OTHER_USER_CONVERSATION_ID = 'conv_other';-const conversationsById: Record<string, { userId: string }> = {- [OWN_CONVERSATION_ID]: { userId: 'user_1' },- [OTHER_USER_CONVERSATION_ID]: { userId: 'user_2' },-};-const findConversation = mock(({ where }: { where: { id: string } }) =>- Promise.resolve(conversationsById[where.id] ?? null)-);--function buildApp() {- const { deps } = stubAppDeps();- deps.db = {- conversation: { findUnique: findConversation },- } as unknown as typeof deps.db;- return new Elysia().use(requestLogging(deps)).use(assistantRoutes(deps));-}--let app: ReturnType<typeof buildApp>;--beforeEach(() => {- app = buildApp();- session = { userId: 'user_1' };- seenBodies.length = 0;- findConversation.mockClear();-});--function get(path: string) {- return app.handle(- new Request(`http://localhost${path}`, {- headers: { cookie: 'session=s' },- })- );-}--function post(path: string, body: unknown) {- return app.handle(- new Request(`http://localhost${path}`, {- method: 'POST',- headers: { 'content-type': 'application/json', cookie: 'session=s' },- body: JSON.stringify(body),- })- );-}--test('hands the chat app an unread body even with the global logging hook mounted', async () => {- const body = { agent: '__titler', input: 'hi' };- const response = await post('/ai/agents/__titler/run', body);- expect(response.status).toBe(200);- expect(seenBodies).toEqual([JSON.stringify(body)]);-});--test('a run without project context is a 400, not a body error', async () => {- const response = await post('/ai/agents/gpt/run', { input: 'hi' });- expect(response.status).toBe(400);- await expect(response.json()).resolves.toEqual({- message: 'Missing projectId or organizationId in context',- });-});--test('no session -> 401', async () => {- session = null;- const response = await post('/ai/agents/__titler/run', { input: 'hi' });- expect(response.status).toBe(401);-});--test("the titler cannot load another user's conversation", async () => {- const response = await get(- `/ai/agents/__titler/conversations/${OTHER_USER_CONVERSATION_ID}`- );- expect(response.status).toBe(404);- expect(seenBodies).toEqual([]);-});--test('the titler serves nothing but a stateless run', async () => {- const resume = await get(- `/ai/agents/__titler/conversations/${OWN_CONVERSATION_ID}/resume`- );- const abort = await post('/ai/agents/__titler/runs/run_1/abort', {});- const withConversation = await post('/ai/agents/__titler/run', {- input: 'hi',- conversationId: OWN_CONVERSATION_ID,- });- expect([resume.status, abort.status, withConversation.status]).toEqual([- 404, 404, 404,- ]);- expect(seenBodies).toEqual([]);-});--test("loading another user's conversation is a 404", async () => {- const response = await get(- `/ai/agents/gpt/conversations/${OTHER_USER_CONVERSATION_ID}`- );- expect(response.status).toBe(404);- expect(findConversation).toHaveBeenCalledTimes(1);-});--test("a run cannot continue another user's conversation", async () => {- const response = await post('/ai/agents/gpt/run', {- input: 'hi',- conversationId: OTHER_USER_CONVERSATION_ID,- context: { projectId: 'p', organizationId: 'o' },- });- expect(response.status).toBe(404);- expect(findConversation).toHaveBeenCalledTimes(1);- expect(seenBodies).toEqual([]);-});diff --git a/packages/core/src/modules/assistant/assistant.routes.ts b/packages/core/src/modules/assistant/assistant.routes.tsindex 4179e95b5..9dbc62ec2 100644--- a/packages/core/src/modules/assistant/assistant.routes.ts+++ b/packages/core/src/modules/assistant/assistant.routes.ts@@ -1,125 +1,77 @@-// `parse: 'none'` is load-bearing: the global request-logging hook references-// `body`, so Elysia would consume the stream before the handler runs and-// `request.clone` would throw "Body is disturbed or locked". With parsing off,-// the body is read via `request.clone` for the access check and-// `chatApp.handler` gets the original request to re-read itself.-import { defineRoutes } from '../../http/define';import { getProjectAccess } from '../../shared/access-lookups';import {getOrganizationByProjectIdCached,getSettingsForProject,} from '../organization/organization.service';+import { getProjectById } from '../project/project.service';+import { zChatRequest } from './assistant.constants';+import { checkChatLimits, resolveChatTier } from './src/limits';-const TITLER_AGENT_NAME = '__titler';--interface RunBody {- conversationId?: string;- context?: { projectId?: string; organizationId?: string };-}--function readRunBody(request: Request): Promise<RunBody | null> {- return request- .clone()- .json()- .catch(() => null) as Promise<RunBody | null>;-}+const TOO_MANY_REQUESTS = 429;export const assistantRoutes = defineRoutes((app) =>- app.all(- '/ai/agents/*',- async ({ params, session, status, request, ctx }) => {+ app.post(+ '/ai/chat',+ async ({ body, session, status, request, ctx }) => {const userId = session.userId;if (!userId) {return status(401, { message: 'Sign in required' });}- const chatApp = ctx.services.assistant.getChatApp();- const chatRunContext = ctx.services.assistant.getChatRunContext();-- // Parse the URL tail that comes after `/ai/agents/`. Examples:- // "claude-sonnet-4-5/run" → run- // "claude-sonnet-4-5/conversations/abc" → load conversation- // "__titler/run" → title stream (no project context)- const wildcard = params['*'] ?? '';- const segments = wildcard.split('/').filter(Boolean);- const agentName = segments[0] ?? '';- const route = segments[1] ?? '';- const routeId = segments[2] ?? '';-- // The store loads conversations by id alone, whatever the agent name.- const isOwnConversation = async (conversationId: string) => {- const conv =- await ctx.services.conversation.getConversationById(conversationId);- return !conv || conv.userId === userId;- };-- // The titler has no project context, so it may only run statelessly:- // any other route or a `conversationId` would load a conversation- // without the ownership check below.- if (agentName === TITLER_AGENT_NAME) {- const isStatelessRun =- request.method === 'POST' &&- route === 'run' &&- segments.length === 2 &&- !(await readRunBody(request))?.conversationId;- if (!isStatelessRun) {- return status(404, { message: 'Not found' });- }- return chatApp.handler(request);+ const parsed = zChatRequest.safeParse(body);+ if (!parsed.success) {+ return status(400, {+ message: 'Invalid chat request',+ issues: parsed.error.issues,+ });}+ const chat = parsed.data;- // A brand-new chat (no row yet) falls through to the agent handler,- // whose `ConversationStore.load()` returns null.- if (route === 'conversations' && routeId) {- if (!(await isOwnConversation(routeId))) {- return status(404, { message: 'Conversation not found' });- }- return chatApp.handler(request);+ const [access, organization, settings, project, conversation] =+ await Promise.all([+ getProjectAccess({ projectId: chat.projectId, userId }),+ getOrganizationByProjectIdCached(ctx, chat.projectId),+ getSettingsForProject(ctx, chat.projectId).catch(() => ({+ timezone: 'UTC',+ })),+ getProjectById(ctx, chat.projectId),+ ctx.services.conversation.getConversationById(chat.id),+ ]);+ if (+ !(access && organization && project) ||+ organization.id !== chat.organizationId+ ) {+ return status(403, { message: 'No access to this project' });}-- // Everything else (primarily `POST /:name/run`) is an active run and- // must carry `context.projectId` + `context.organizationId`.- const body = await readRunBody(request);if (- body?.conversationId &&- !(await isOwnConversation(body.conversationId))+ conversation &&+ (conversation.userId !== userId ||+ conversation.projectId !== chat.projectId)) {return status(404, { message: 'Conversation not found' });}- const projectId = body?.context?.projectId;- const organizationIdFromBody = body?.context?.organizationId;- if (!(projectId && organizationIdFromBody)) {- return status(400, {- message: 'Missing projectId or organizationId in context',- });- }-- const [access, organization, settings] = await Promise.all([- getProjectAccess({ projectId, userId }),- getOrganizationByProjectIdCached(ctx, projectId),- getSettingsForProject(ctx, projectId).catch(() => ({- timezone: 'UTC',- })),- ]);- if (- !(access && organization) ||- organization.id !== organizationIdFromBody- ) {- return status(403, { message: 'No access to this project' });+ // Every request runs the model, including approval and client-tool+ // continuations; exempting any shape of body would let a crafted one through.+ const limited = await checkChatLimits(ctx, {+ organizationId: organization.id,+ userId,+ tier: resolveChatTier(organization, ctx.config.selfHosted),+ });+ if (limited) {+ return status(TOO_MANY_REQUESTS, limited);}- return chatRunContext.run(- {- userId,- projectId,- organizationId: organization.id,- timezone: settings.timezone || 'UTC',- },- () => chatApp.handler(request)- );+ return ctx.services.assistant.runChat({+ httpCtx: ctx,+ request: chat,+ userId,+ timezone: settings.timezone || 'UTC',+ projectName: project.name,+ abortSignal: request.signal,+ });},- { session: true, detail: { hide: true }, parse: 'none' }+ { session: true, detail: { hide: true } }));diff --git a/packages/core/src/modules/assistant/assistant.rpc.test.ts b/packages/core/src/modules/assistant/assistant.rpc.test.tsindex 8456c6790..4160a14c3 100644--- a/packages/core/src/modules/assistant/assistant.rpc.test.ts+++ b/packages/core/src/modules/assistant/assistant.rpc.test.ts@@ -54,6 +54,7 @@ test('models returns no models and a null default with no provider keys set', asproviders: { openai: false, anthropic: false },models: [],defaultModelId: null,+ canChooseModel: false,});});@@ -61,6 +62,6 @@ test('models filters to the configured provider and prefers the recorded defaultconst caller = await callerWith(TEST_SESSION, { openai: 'sk-test' });const result = await caller.models();expect(result.providers).toEqual({ openai: true, anthropic: false });- expect(result.models.every((m) => m.group === 'OpenAI')).toBe(true);- expect(result.defaultModelId).toBe('gpt-4-1-mini');+ expect(result.models.every((m) => m.provider === 'openai')).toBe(true);+ expect(result.defaultModelId).toBe('gpt-6-1-sol');});diff --git a/packages/core/src/modules/assistant/assistant.rpc.ts b/packages/core/src/modules/assistant/assistant.rpc.tsindex b195ee254..c533772ad 100644--- a/packages/core/src/modules/assistant/assistant.rpc.ts+++ b/packages/core/src/modules/assistant/assistant.rpc.ts@@ -5,7 +5,7 @@import { createTRPCRouter, protectedProcedure } from '../../rpc/base';import {getAvailableChatModels,- PREFERRED_DEFAULT_MODEL_ID,+ getDefaultChatModelId,} from './assistant.constants';export const chatRouter = createTRPCRouter({@@ -14,13 +14,12 @@ export const chatRouter = createTRPCRouter({openai: Boolean(ctx.config.ai.openai.apiKey),anthropic: Boolean(ctx.config.ai.anthropic.apiKey),};- const models = getAvailableChatModels(providers);- const preferred = models.find((m) => m.id === PREFERRED_DEFAULT_MODEL_ID);- const defaultModelId = preferred?.id ?? models[0]?.id ?? null;return {providers,- models,- defaultModelId,+ models: getAvailableChatModels(providers),+ defaultModelId: getDefaultChatModelId(providers),+ // Cloud runs one vetted model; a self-hoster pays for their own keys and picks.+ canChooseModel: ctx.config.selfHosted,};}),});diff --git a/packages/core/src/modules/assistant/assistant.service.ts b/packages/core/src/modules/assistant/assistant.service.tsindex 422144437..f9f8dc36c 100644--- a/packages/core/src/modules/assistant/assistant.service.ts+++ b/packages/core/src/modules/assistant/assistant.service.ts@@ -1,45 +1,21 @@-// The chat app is memoized per `deps` object, not per process: a Ctx builds one-// `ServiceDeps` per unit of work, so calls inside one chat request share an app-// and separate requests do not.-import type { ServiceDeps, Services } from '../../services';-import type { PageContext } from './assistant.constants';-import { type ChatApp, createChatApp } from './src/app';-import { runFilterCommand } from './src/filter-command';-import { chatRunContext } from './src/run-context';+import { type RunChatInput, runChat } from './src/chat';+import {+ type FilterCommandInput,+ runFilterCommand,+} from './src/filter-command';-export type { ChatApp } from './src/app';export type { FilterCommandResult } from './src/filter-command';-export type { ChatRunContext } from './src/run-context';--const appsByDeps = new WeakMap<ServiceDeps, ChatApp>();--function chatAppFor(deps: ServiceDeps): ChatApp {- const existing = appsByDeps.get(deps);- if (existing) {- return existing;- }- const built = createChatApp(deps);- appsByDeps.set(deps, built);- return built;-}--export interface RunFilterCommandInput {- query: string;- projectId: string;- pageContext?: PageContext;- timezone: string;-}+export type { AssistantUIMessage, AssistantUIMessagePart } from './src/message';export function createAssistantService(deps: ServiceDeps,_services: () => Services) {return {- getChatApp: (): ChatApp => chatAppFor(deps),- getChatRunContext: (): typeof chatRunContext => chatRunContext,+ runChat: (input: RunChatInput): Promise<Response> => runChat(deps, input),runFilterCommand: (- input: RunFilterCommandInput+ input: FilterCommandInput): ReturnType<typeof runFilterCommand> => runFilterCommand(deps, input),};}diff --git a/packages/core/src/modules/assistant/src/actions.ts b/packages/core/src/modules/assistant/src/actions.tsnew file mode 100644index 000000000..d9ef16fcc--- /dev/null+++ b/packages/core/src/modules/assistant/src/actions.ts@@ -0,0 +1,31 @@+// The assistant's write path is the same tRPC procedures the dashboard calls,+// so access rules and side effects live in one place.+import type { HttpCtx } from '../../../context';+import { createTRPCRouter, makeTrpcContext } from '../../../rpc/base';+import { dashboardRouter } from '../../dashboard/dashboard.rpc';+import { organizationRouter } from '../../organization/organization.rpc';+import { projectRouter } from '../../project/project.rpc';+import { referenceRouter } from '../../reference/reference.rpc';+import { reportRouter } from '../../report/report.rpc';+import { subscriptionRouter } from '../../subscription/subscription.rpc';++const chatActionsRouter = createTRPCRouter({+ dashboard: dashboardRouter,+ organization: organizationRouter,+ project: projectRouter,+ reference: referenceRouter,+ report: reportRouter,+ subscription: subscriptionRouter,+});++export type ChatActions = ReturnType<typeof chatActionsRouter.createCaller>;++export async function createChatActions(+ httpCtx: HttpCtx+): Promise<ChatActions> {+ const trpcCtx = await makeTrpcContext(httpCtx, new Headers(), {+ cookieOptions: {},+ demoMode: Boolean(httpCtx.config.demoUserId),+ });+ return chatActionsRouter.createCaller(trpcCtx);+}diff --git a/packages/core/src/modules/assistant/src/app.ts b/packages/core/src/modules/assistant/src/app.tsdeleted file mode 100644index 64b155121..000000000--- a/packages/core/src/modules/assistant/src/app.ts+++ /dev/null@@ -1,78 +0,0 @@-// Tool handlers close over `deps` because @better-agent/core's tool handler-// signature has no context parameter.-import { betterAgent, defineAgent } from '@better-agent/core';-import type { ServiceDeps } from '../../../services';-import { type ChatAgentContext, chatContextSchema } from './context';-import { createConversationStore } from './persistence';-import { buildSystemPrompt } from './prompt';-import {- ALLOWED_MODELS,- type ChatModelEntry,- openaiProvider,- resolveModel,-} from './providers';-import { composeChatTools } from './tools';--/**- * One agent per whitelisted model; they differ only in the provider model. The- * config is `any`-cast because `resolveModel` returns a union and- * `defineAgent`'s conditional generics fall back to `object`, which strips- * `instruction` and `tools` from the inferred type. `defineAgent` still- * validates the definition at runtime.- */-function createChatAgent(deps: ServiceDeps, entry: ChatModelEntry) {- return defineAgent({- name: entry.id,- description: `OpenPanel chat assistant (${entry.label})`,- model: resolveModel(deps.config, entry),- contextSchema: chatContextSchema,- instruction: (context: ChatAgentContext) => buildSystemPrompt(context),- tools: (context: ChatAgentContext) => composeChatTools(deps, context),- maxSteps: 20,- // Reasoning-capable models need `reasoning.summary` to stream reasoning text.- ...(entry.reasoning- ? {- defaultModelOptions: {- reasoning: {- effort: 'medium',- summary: 'auto',- },- },- }- : {}),- // biome-ignore lint/suspicious/noExplicitAny: see block comment above- } as any);-}--/** Cheap agent that titles a new conversation (3-5 words) after its first turn. */-function createTitlerAgent(deps: ServiceDeps) {- return defineAgent({- name: '__titler',- description: 'Generates concise 3-5 word titles for chat conversations.',- // biome-ignore lint/suspicious/noExplicitAny: OpenAI model id union is open- model: openaiProvider(deps.config).model('gpt-4.1-mini' as any),- instruction:- 'You generate concise 3-5 word titles for chat conversations. Respond with ONLY the title. No quotes, no punctuation, no trailing period.',- maxSteps: 1,- // biome-ignore lint/suspicious/noExplicitAny: see block comment on createChatAgent- } as any);-}--/**- * The Better Agent app for one unit of work; `.handler` is mounted by- * `assistant.routes.ts`, which checks auth and project access first.- */-export function createChatApp(deps: ServiceDeps) {- return betterAgent({- agents: [- ...ALLOWED_MODELS.map((entry) => createChatAgent(deps, entry)),- createTitlerAgent(deps),- ],- persistence: {- conversations: createConversationStore(deps),- },- baseURL: '/ai/agents',- });-}--export type ChatApp = ReturnType<typeof createChatApp>;diff --git a/packages/core/src/modules/assistant/src/chat.ts b/packages/core/src/modules/assistant/src/chat.tsnew file mode 100644index 000000000..f41b7ba41--- /dev/null+++ b/packages/core/src/modules/assistant/src/chat.ts@@ -0,0 +1,233 @@+import {+ convertToModelMessages,+ createIdGenerator,+ createUIMessageStream,+ createUIMessageStreamResponse,+ isStepCount,+ streamText,+ toUIMessageStream,+} from 'ai';+import type { HttpCtx } from '../../../context';+import type { ServiceDeps } from '../../../services';+import {+ CHAT_MODELS,+ type ChatRequest,+ getAvailableChatModels,+ getDefaultChatModelId,+} from '../assistant.constants';+import { createChatActions } from './actions';+import type { ChatToolContext } from './context';+import type { AssistantUIMessage } from './message';+import { deleteMessagesFrom, loadMessages, saveMessages } from './persistence';+import { buildSystemPrompt } from './prompt';+import {+ configuredProviders,+ reasoningProviderOptions,+ resolveChatModel,+} from './providers';+import { generateConversationTitle } from './title';+import { CHAT_TOOL_APPROVAL, createChatTools } from './tools';++/** Dashboard-building turns chain many tool calls; the ceiling stops runaway loops. */+const MAX_STEPS = 30;+const MESSAGE_ID_PREFIX = 'msg';+const MESSAGE_ID_SIZE = 16;++export interface RunChatInput {+ httpCtx: HttpCtx;+ request: ChatRequest;+ userId: string;+ timezone: string;+ projectName: string;+ abortSignal?: AbortSignal;+}++function firstUserText(message: AssistantUIMessage | undefined): string {+ if (!message || message.role !== 'user') {+ return '';+ }+ return message.parts+ .map((part) => (part.type === 'text' ? part.text : ''))+ .join(' ')+ .trim();+}++function describeError(error: unknown): string {+ if (error instanceof Error) {+ return error.message;+ }+ if (typeof error === 'string') {+ return error;+ }+ return 'Something went wrong.';+}++/** One chat turn: load history, run the model with tools, stream UI parts, persist on finish. */+export async function runChat(+ deps: ServiceDeps,+ input: RunChatInput+): Promise<Response> {+ const { request, httpCtx } = input;+ const config = deps.config;+ const providers = configuredProviders(config);+ const available = getAvailableChatModels(providers);+ // Cloud runs the one vetted model; only a self-hosted install may pick another.+ const requested = config.selfHosted+ ? CHAT_MODELS.find((model) => model.id === request.modelId)+ : undefined;+ const entry =+ requested && available.some((model) => model.id === requested.id)+ ? requested+ : available.find(+ (model) => model.id === getDefaultChatModelId(providers)+ );+ if (!entry) {+ return Response.json(+ { message: 'No AI provider is configured on the API.' },+ { status: 503 }+ );+ }++ const incoming = request.message as AssistantUIMessage | undefined;+ let history = await loadMessages(deps, request.id);+ if (request.trigger === 'regenerate-message' && request.messageId) {+ const index = history.findIndex(+ (message) => message.id === request.messageId+ );+ if (index >= 0) {+ history = history.slice(0, index);+ await deleteMessagesFrom(deps, request.id, request.messageId);+ }+ }+ if (incoming) {+ const existing = history.findIndex((message) => message.id === incoming.id);+ history =+ existing >= 0+ ? history.map((message) =>+ message.id === incoming.id ? incoming : message+ )+ : [...history, incoming];+ }++ const isFirstTurn =+ incoming?.role === 'user' &&+ history.filter((message) => message.role === 'user').length === 1;++ const toolContext: ChatToolContext = {+ deps,+ config,+ projectId: request.projectId,+ organizationId: request.organizationId,+ userId: input.userId,+ projectName: input.projectName,+ timezone: input.timezone,+ hint: request.hint,+ actions: await createChatActions(httpCtx),+ };+ const tools = createChatTools(toolContext);+ const modelMessages = await convertToModelMessages(history, { tools });+ const startedAt = Date.now();+ let title: string | null = null;++ const stream = createUIMessageStream<AssistantUIMessage>({+ originalMessages: history,+ generateId: createIdGenerator({+ prefix: MESSAGE_ID_PREFIX,+ size: MESSAGE_ID_SIZE,+ }),+ execute: async ({ writer }) => {+ const titlePromise = isFirstTurn+ ? generateConversationTitle(config, firstUserText(incoming)).then(+ (generated) => {+ if (generated) {+ title = generated;+ writer.write({+ type: 'data-title',+ data: { title: generated },+ transient: true,+ });+ }+ }+ )+ : Promise.resolve();++ const result = streamText({+ model: resolveChatModel(config, entry),+ instructions: buildSystemPrompt({+ projectName: input.projectName,+ timezone: input.timezone,+ selfHosted: config.selfHosted,+ hint: request.hint,+ }),+ messages: modelMessages,+ tools,+ toolApproval: CHAT_TOOL_APPROVAL,+ stopWhen: isStepCount(MAX_STEPS),+ reasoning: entry.reasoning,+ providerOptions: reasoningProviderOptions(entry),+ abortSignal: input.abortSignal,+ });++ writer.merge(+ toUIMessageStream({+ stream: result.stream,+ sendReasoning: true,+ onError: describeError,+ messageMetadata: ({ part }) => {+ if (part.type === 'start') {+ return { modelId: entry.id, createdAt: startedAt };+ }+ if (part.type === 'finish') {+ const durationMs = Date.now() - startedAt;+ deps.logger.info(+ {+ conversationId: request.id,+ organizationId: request.organizationId,+ projectId: request.projectId,+ userId: input.userId,+ modelId: entry.id,+ // Keys avoid "token": the log redaction masks any key containing it.+ usage: {+ input: part.totalUsage.inputTokens,+ output: part.totalUsage.outputTokens,+ total: part.totalUsage.totalTokens,+ },+ durationMs,+ },+ 'chat turn finished'+ );+ return {+ totalTokens: part.totalUsage.totalTokens,+ durationMs,+ };+ }+ return undefined;+ },+ })+ );++ await titlePromise;+ },+ onError: describeError,+ onEnd: async ({ responseMessage }) => {+ const toSave: AssistantUIMessage[] = [];+ if (incoming?.role === 'user') {+ toSave.push({+ ...incoming,+ metadata: { ...incoming.metadata, createdAt: startedAt },+ });+ }+ toSave.push(responseMessage);+ await saveMessages(deps, {+ conversationId: request.id,+ projectId: request.projectId,+ organizationId: request.organizationId,+ userId: input.userId,+ messages: toSave,+ title,+ });+ },+ });++ return createUIMessageStreamResponse({ stream });+}diff --git a/packages/core/src/modules/assistant/src/context.ts b/packages/core/src/modules/assistant/src/context.tsindex a1b4e8e91..248720e6c 100644--- a/packages/core/src/modules/assistant/src/context.ts+++ b/packages/core/src/modules/assistant/src/context.ts@@ -1,10 +1,18 @@-export type {- ChatAgentContext,- PageContext,- PageContextPage,-} from '../assistant.constants';-export {- chatContextSchema,- pageContextPageSchema,- pageContextSchema,-} from '../assistant.constants';+import type { CoreConfig } from '../../../config';+import type { ServiceDeps } from '../../../services';+import type { ChatLaunchHint } from '../assistant.constants';+import type { ChatActions } from './actions';++/** Everything a tool needs for one turn; the route checks access before building it. */+export interface ChatToolContext {+ deps: ServiceDeps;+ config: CoreConfig;+ projectId: string;+ organizationId: string;+ userId: string;+ projectName: string;+ /** IANA timezone of the project. */+ timezone: string;+ hint?: ChatLaunchHint;+ actions: ChatActions;+}diff --git a/packages/core/src/modules/assistant/src/filter-command.ts b/packages/core/src/modules/assistant/src/filter-command.tsindex 8f83cc508..1b58bf631 100644--- a/packages/core/src/modules/assistant/src/filter-command.ts+++ b/packages/core/src/modules/assistant/src/filter-command.ts@@ -1,15 +1,9 @@-// Tool handlers close over `deps` because @better-agent/core's tool handler-// signature has no context parameter.-import {- type AgentToolDefinition,- betterAgent,- defineAgent,- defineTool,- type ToolRunContext,-} from '@better-agent/core';+// The overview command bar: one natural-language request becomes one+// structured filter change, checked against real referrer, country, device+// and page values before it is applied.import { resolveDateRange as resolveDateRangeCore } from '@openpanel/shared';+import { generateText, isStepCount, Output, tool } from 'ai';import { z } from 'zod';-import type { CoreConfig } from '../../../config';import type { ServiceDeps } from '../../../services';import { listEventNamesCore } from '../../event/event.service';import { getTrafficBreakdownCore } from '../../overview/overview.service';@@ -23,35 +17,31 @@ import {zRange,} from '../../report/report.constants';import { getDatesFromRange } from '../../report/src/chart-dates';-import {- CHAT_MODELS,- type ChatModelEntry,- type PageContext,-} from '../assistant.constants';-import { resolveModel } from './providers';+import { resolveUtilityModel } from './providers';-function objectToZodEnums<K extends string>(- obj: Record<K, unknown>-): [K, ...K[]] {- const [firstKey, ...otherKeys] = Object.keys(obj) as K[];- return [firstKey!, ...otherKeys];+function enumKeys<K extends string>(record: Record<K, unknown>): [K, ...K[]] {+ const [first, ...rest] = Object.keys(record) as K[];+ return [first as K, ...rest];}-const operatorEnum = z.enum(objectToZodEnums(operators));-const rangeEnum = zRange;-const intervalEnum = z.enum(objectToZodEnums(intervals));+const MAX_STEPS = 4;+const REFERRER_LIMIT = 30;+const COUNTRY_LIMIT = 50;+const DEVICE_LIMIT = 20;+const PAGE_LIMIT = 50;+const DATE_LENGTH = 10;const filterCommandOutputSchema = z.object({applyFilters: z.object({- range: rangeEnum.nullable(),+ range: zRange.nullable(),startDate: z.string().nullable().describe('YYYY-MM-DD or null'),endDate: z.string().nullable().describe('YYYY-MM-DD or null'),- interval: intervalEnum.nullable(),+ interval: z.enum(enumKeys(intervals)).nullable(),}).nullable().describe(- 'Date range / interval. Null = no change. Either set `range` to a preset (and null both dates) OR set `startDate`+`endDate` for a custom window (and null `range`) — never both.'+ 'Date range and interval. Null = no change. Either set `range` to a preset (and null both dates) or set `startDate`+`endDate` (and null `range`), never both.'),setPropertyFilters: z.object({@@ -62,347 +52,208 @@ const filterCommandOutputSchema = z.object({.describe('Property key. Common: country, region, city, device, browser, os, referrer_name, referrer_type, path, origin, utm_source, utm_medium, utm_campaign.'),- operator: operatorEnum,+ operator: z.enum(enumKeys(operators)),value: z.array(z.string())- .describe("Values to match (OR'd). Use [] for isNull / isNotNull."),+ .describe("Values to match (OR'd). [] for isNull / isNotNull."),})),}).nullable().describe(- 'REPLACES the active property-filter set. Null = no change. To ADD to existing filters, include the current ones (see "Current view"). Empty filters array clears all property filters.'+ 'REPLACES the active property filters. Null = no change. To add to the existing set, include the current filters. An empty array clears them.'),setEventNamesFilter: z.object({ eventNames: z.array(z.string()) }).nullable().describe(- 'REPLACES the event-name filter. Null = no change. Empty array shows all events. Verify names with list_event_names if unsure.'+ 'REPLACES the event-name filter. Null = no change. [] shows all events.'),summary: z.string().describe(- 'One-line confirmation in 8-15 words. No preamble, no markdown. If ambiguous and you applied no changes, explain what you need.'+ 'One-line confirmation in 8 to 15 words. No preamble, no markdown. If nothing was applied, say what is missing.'),});export type FilterCommandResult = z.infer<typeof filterCommandOutputSchema>;-const filterCommandContextSchema = z.object({- projectId: z.string(),- timezone: z.string(),- pageContext: z- .object({- filters: z- .object({- range: z.string().optional(),- startDate: z.string().optional(),- endDate: z.string().optional(),- interval: z.string().optional(),- eventNames: z.array(z.string()).optional(),- eventFilters: z.array(z.record(z.string(), z.unknown())).optional(),- })- .optional(),- })- .optional(),-});--type FilterCommandContext = z.infer<typeof filterCommandContextSchema>;--const PREFERRED_MODEL_IDS = ['claude-haiku-4-5', 'gpt-4-1-mini'] as const;--function pickModel(config: CoreConfig): ChatModelEntry {- const haveOpenai = Boolean(config.ai.openai.apiKey);- const haveAnthropic = Boolean(config.ai.anthropic.apiKey);- const available = (entry: ChatModelEntry) =>- (entry.group === 'OpenAI' && haveOpenai) ||- (entry.group === 'Anthropic' && haveAnthropic);-- for (const id of PREFERRED_MODEL_IDS) {- const entry = CHAT_MODELS.find((m) => m.id === id);- if (entry && available(entry)) {- return entry;- }- }- const fallback = CHAT_MODELS.find(available);- if (!fallback) {- throw new Error(- 'filter-command: no model available — set OPENAI_API_KEY or ANTHROPIC_API_KEY.'- );- }- return fallback;+export interface FilterCommandInput {+ query: string;+ projectId: string;+ timezone: string;+ pageContext?: {+ filters?: {+ range?: string;+ startDate?: string;+ endDate?: string;+ interval?: string;+ eventNames?: string[];+ eventFilters?: Record<string, unknown>[];+ };+ };}-const PRESET_RANGES: ReadonlySet<IChartRange> = new Set(- (Object.keys(timeWindows) as IChartRange[]).filter((k) => k !== 'custom')+const PRESET_RANGES: ReadonlySet<string> = new Set(+ Object.keys(timeWindows).filter((key) => key !== 'custom'));-function resolveRange(- filters: FilterCommandContext['pageContext'] extends infer T- ? T extends { filters?: infer F }- ? F- : undefined- : undefined,- timezone: string-): { startDate: string; endDate: string } {+function resolveRange(input: FilterCommandInput): {+ startDate: string;+ endDate: string;+} {+ const filters = input.pageContext?.filters;if (filters?.startDate || filters?.endDate) {return resolveDateRangeCore(filters.startDate, filters.endDate);}- const range = filters?.range as IChartRange | undefined;- if (range && PRESET_RANGES.has(range)) {- return getDatesFromRange(range, timezone);+ if (filters?.range && PRESET_RANGES.has(filters.range)) {+ return getDatesFromRange(filters.range as IChartRange, input.timezone);}return resolveDateRangeCore(undefined, undefined);}-function activeFilters(ctx: FilterCommandContext): IChartEventFilter[] {- const raw = ctx.pageContext?.filters?.eventFilters;+function activeFilters(input: FilterCommandInput): IChartEventFilter[] {+ const raw = input.pageContext?.filters?.eventFilters;if (!Array.isArray(raw)) {return [];}return raw.filter(- (f): f is IChartEventFilter =>- typeof (f as { name?: unknown })?.name === 'string'+ (filter): filter is IChartEventFilter => typeof filter.name === 'string');}-function defineServerTool<TSchema extends z.ZodTypeAny>(config: {- name: string;- description: string;- schema: TSchema;- handler: (- input: z.infer<TSchema>,- ctx: FilterCommandContext- ) => Promise<unknown>;-}): AgentToolDefinition {- // biome-ignore lint/suspicious/noExplicitAny: Zod schema instantiation depth — same dodge as `chatTool` in src/tools/helpers.ts- const contract: any = defineTool({- name: config.name,- description: config.description,- schema: config.schema,- });- return contract.server(async (input: unknown, runCtx: ToolRunContext) =>- config.handler(- input as z.infer<TSchema>,- runCtx.context as FilterCommandContext- )- ) as AgentToolDefinition;-}+function lookupTools(deps: ServiceDeps, input: FilterCommandInput) {+ const range = resolveRange(input);+ const filters = activeFilters(input);+ const breakdown = (+ column: 'referrer_name' | 'country' | 'device',+ limit: number+ ) =>+ getTrafficBreakdownCore(deps, {+ projectId: input.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column,+ filters,+ }).then((rows) => ({ rows: rows.slice(0, limit) }));-const listEventNamesTool = (deps: ServiceDeps) =>- defineServerTool({- name: 'list_event_names',- description:- 'Top 50 event names tracked in this project. Use BEFORE setting `setEventNamesFilter`.',- schema: z.object({}),- handler: async (_input, ctx) => ({- event_names: await listEventNamesCore(deps, ctx.projectId),+ return {+ list_event_names: tool({+ description:+ 'Event names tracked in this project. Use before setting an event-name filter.',+ inputSchema: z.object({}),+ execute: async () => ({+ events: await listEventNamesCore(deps, input.projectId),+ }),}),- });--const getTopReferrersTool = (deps: ServiceDeps) =>- defineServerTool({- name: 'get_top_referrers',- description:- "Top traffic sources by `referrer_name` ('Google', 'GitHub', 'Direct') in the user's current date range. Use to translate vague names into exact filter values.",- schema: z.object({}),- handler: async (_input, ctx) => {- const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);- const rows = await getTrafficBreakdownCore(deps, {- projectId: ctx.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: 'referrer_name',- filters: activeFilters(ctx),- });- return { rows: rows.slice(0, 30) };- },- });--const getTopCountriesTool = (deps: ServiceDeps) =>- defineServerTool({- name: 'get_top_countries',- description:- "Top countries (ISO-2 codes) in the user's current date range.",- schema: z.object({}),- handler: async (_input, ctx) => {- const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);- const rows = await getTrafficBreakdownCore(deps, {- projectId: ctx.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: 'country',- filters: activeFilters(ctx),- });- return { rows: rows.slice(0, 50) };- },- });--const getTopDevicesTool = (deps: ServiceDeps) =>- defineServerTool({- name: 'get_top_devices',- description:- "Device classes seen in the user's current date range (mobile, desktop, tablet, …).",- schema: z.object({}),- handler: async (_input, ctx) => {- const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);- const rows = await getTrafficBreakdownCore(deps, {- projectId: ctx.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: 'device',- filters: activeFilters(ctx),- });- return { rows: rows.slice(0, 20) };- },- });--const getTopPagesTool = (deps: ServiceDeps) =>- defineServerTool({- name: 'get_top_pages',- description:- "Top pages (paths like '/blog/foo', '/pricing', '/') in the user's current date range. Use to discover the path shape so you can pick the right operator (`startsWith` for sections like /blog, `is` for an exact page, `contains` for fuzzy matching).",- schema: z.object({}),- handler: async (_input, ctx) => {- const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);- const rows = await getTopPagesCore(deps, {- projectId: ctx.projectId,- startDate: range.startDate,- endDate: range.endDate,- filters: activeFilters(ctx),- limit: 50,- });- return { rows };- },- });+ get_top_referrers: tool({+ description:+ "Referrer names seen in the current range ('Google', 'GitHub', 'Direct'). Use to turn a vague source into exact `referrer_name` values.",+ inputSchema: z.object({}),+ execute: () => breakdown('referrer_name', REFERRER_LIMIT),+ }),+ get_top_countries: tool({+ description: 'Country codes (ISO-2) seen in the current range.',+ inputSchema: z.object({}),+ execute: () => breakdown('country', COUNTRY_LIMIT),+ }),+ get_top_devices: tool({+ description:+ 'Device classes seen in the current range (mobile, desktop, tablet).',+ inputSchema: z.object({}),+ execute: () => breakdown('device', DEVICE_LIMIT),+ }),+ get_top_pages: tool({+ description:+ 'Paths seen in the current range. Use to pick the right operator: startsWith for a section, is for one page, contains for fuzzy.',+ inputSchema: z.object({}),+ execute: async () => ({+ rows: await getTopPagesCore(deps, {+ projectId: input.projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ filters,+ limit: PAGE_LIMIT,+ }),+ }),+ }),+ };+}-const FILTER_COMMAND_TOOLS: ((deps: ServiceDeps) => AgentToolDefinition)[] = [- listEventNamesTool,- getTopReferrersTool,- getTopCountriesTool,- getTopDevicesTool,- getTopPagesTool,-];+function currentView(input: FilterCommandInput): string {+ const filters = input.pageContext?.filters;+ const lines = ['# Current view'];+ if (filters?.range) {+ const range = resolveRange(input);+ lines.push(+ `Date range: ${filters.range} (${range.startDate} to ${range.endDate}), interval: ${filters.interval ?? 'day'}.`+ );+ } else {+ lines.push('Date range: default.');+ }+ lines.push(+ filters?.eventNames?.length+ ? `Active event-name filter: ${JSON.stringify(filters.eventNames)}`+ : 'No event-name filter active.'+ );+ lines.push(+ filters?.eventFilters?.length+ ? `Active property filters: ${JSON.stringify(filters.eventFilters)}`+ : 'No property filters active.'+ );+ return lines.join('\n');+}-function buildInstruction(ctx: FilterCommandContext): string {- const today = new Date();- const todayIso = today.toISOString().slice(0, 10);- const dayName = today.toLocaleDateString('en-US', {+function instructions(input: FilterCommandInput): string {+ const now = new Date();+ const today = now.toISOString().slice(0, DATE_LENGTH);+ const weekday = now.toLocaleDateString('en-US', {weekday: 'long',timeZone: 'UTC',});-return [- "You are the OpenPanel filter command bar. Convert the user's short request into a structured filter update, then output a single short confirmation sentence in `summary`.",+ "You are the OpenPanel filter command bar. Convert the user's short request into a structured filter update and one short confirmation sentence.",'',- `Today is **${dayName}, ${todayIso}** (UTC). Use it for relative date math.`,+ `Today is ${weekday}, ${today} (UTC).`,'','# Rules',- '- For date ranges, prefer presets when they match exactly. Anything that does not map to a preset MUST go through `startDate`+`endDate` (YYYY-MM-DD).',- '- "last week", explicit calendar windows ("Q1 2026", "august last year", "May 24-28") → ALWAYS compute `startDate`+`endDate` manually relative to today.',- '- For property filters: REPLACE semantics. To ADD to the existing set, include the current filters (listed under "Current view") in your output.',- '- When the user names a source ("google", "twitter", "hackernews") that may not be an exact known referrer, call `get_top_referrers` first and pick the matching `referrer_name` value(s). Same for countries (`get_top_countries`) and devices (`get_top_devices`).',- '- Prefer `referrer_name` for source filtering (e.g. "Google", "GitHub"), not the raw URL.',+ '- Prefer a preset range when it matches exactly. Anything else ("last week", "Q1 2026", "august last year", "May 24-28") goes through startDate and endDate.',+ '- Property filters replace the active set: to add, include the current filters from "Current view".',+ '- When the user names a source, country or device, call the matching lookup tool and use the exact values it returns. Filter sources on `referrer_name`.',+ '- Page requests filter on `path`: startsWith for a section (/blog), is for one page (/pricing), contains for fuzzy, endsWith for a suffix. Call get_top_pages when unsure what paths exist.',+ '- Never invent event names; call list_event_names if unsure.',+ '- Leave a group null when the user did not ask to change it. If the request is ambiguous, leave all three null and ask in `summary`.','',- '# Page / path filtering',- '- When the user asks about a page or section ("blog posts", "the pricing page", "anything under /docs", "homepage only"), filter on the `path` property.',- '- Pick the operator that matches intent:',- ' - "blog posts" / "anything under /blog" / "the docs section" → `startsWith` with value like `["/blog"]` or `["/docs"]`',- ' - "pages with `pricing` in the URL" / fuzzy match → `contains`',- ' - exact page ("the homepage", "the pricing page") → `is` with the exact path (`["/"]` or `["/pricing"]`)',- ' - "anything ending in .pdf" → `endsWith`',- '- If you are not sure what paths exist (e.g. user says "blog" but the project might use `/posts/*` instead), call `get_top_pages` FIRST to see real paths, then pick the right prefix.',- '- Never invent event names — call `list_event_names` if unsure.',- '- Set `applyFilters` / `setPropertyFilters` / `setEventNamesFilter` to `null` when the user did not ask to change them. Do not over-apply.',- '- If the request is ambiguous, leave all three groups null and put a clarification in `summary`.',- '',- buildPageContextSection(ctx),+ currentView(input),].join('\n');}-function buildPageContextSection(ctx: FilterCommandContext): string {- const pc = ctx.pageContext;- const lines: string[] = ['# Current view'];-- if (!pc?.filters) {- lines.push('No filters currently active.');- return lines.join('\n');- }-- if (pc.filters.range) {- const resolved = resolveRange(pc.filters, ctx.timezone);- const interval = pc.filters.interval ?? 'day';- lines.push(- `Date range: ${pc.filters.range} (${resolved.startDate} to ${resolved.endDate}), interval: ${interval}.`- );- } else {- lines.push('Date range: default (no `range` set).');- }-- if (pc.filters.eventNames && pc.filters.eventNames.length > 0) {- lines.push(- `Active event-name filter: ${JSON.stringify(pc.filters.eventNames)}`- );- } else {- lines.push('No event-name filter active.');- }-- if (pc.filters.eventFilters && pc.filters.eventFilters.length > 0) {- lines.push(- `Active property filters: ${JSON.stringify(pc.filters.eventFilters)}`- );- } else {- lines.push('No property filters active.');- }-- return lines.join('\n');-}--const filterCommandOutputJsonSchema = z.toJSONSchema(- filterCommandOutputSchema,- { target: 'draft-07' }-);--function createFilterCommandApp(deps: ServiceDeps) {- const agent = defineAgent({- name: 'filter-command',- description: 'OpenPanel filter command bar (one-shot, no persistence).',- model: resolveModel(deps.config, pickModel(deps.config)),- contextSchema: filterCommandContextSchema,- outputSchema: {- schema: filterCommandOutputJsonSchema,- name: 'filter_command_output',- strict: true,- },- instruction: (ctx: FilterCommandContext) => buildInstruction(ctx),- tools: () => FILTER_COMMAND_TOOLS.map((tool) => tool(deps)),- maxSteps: 6,- // biome-ignore lint/suspicious/noExplicitAny: same dodge as `createChatAgent` in src/app.ts- } as any);- return betterAgent({ agents: [agent] });-}-export async function runFilterCommand(deps: ServiceDeps,- input: {- query: string;- projectId: string;- pageContext?: PageContext;- timezone: string;- }+ input: FilterCommandInput): Promise<FilterCommandResult> {- const result = (await createFilterCommandApp(deps).run('filter-command', {- input: input.query,- context: {- projectId: input.projectId,- timezone: input.timezone,- pageContext: input.pageContext as FilterCommandContext['pageContext'],- },- // biome-ignore lint/suspicious/noExplicitAny: same dodge as `createChatAgent` in src/app.ts- } as any)) as { structured?: FilterCommandResult };-- if (!result.structured) {- throw new Error('filter-command agent returned no structured output');+ const model = resolveUtilityModel(deps.config);+ if (!model) {+ throw new Error(+ 'No AI provider is configured: set OPENAI_API_KEY or ANTHROPIC_API_KEY.'+ );+ }+ const result = await generateText({+ model,+ instructions: instructions(input),+ prompt: input.query,+ tools: lookupTools(deps, input),+ stopWhen: isStepCount(MAX_STEPS),+ reasoning: 'low',+ output: Output.object({ schema: filterCommandOutputSchema }),+ });+ if (!result.output) {+ return {+ applyFilters: null,+ setPropertyFilters: null,+ setEventNamesFilter: null,+ summary: "Couldn't turn that into a filter. Try rephrasing.",+ };}- return result.structured;+ return result.output;}diff --git a/packages/core/src/modules/assistant/src/limits.test.ts b/packages/core/src/modules/assistant/src/limits.test.tsnew file mode 100644index 000000000..f66e226fe--- /dev/null+++ b/packages/core/src/modules/assistant/src/limits.test.ts@@ -0,0 +1,215 @@+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { Logger } from '../../../logger';+import {+ CHAT_BURST_LIMIT,+ CHAT_MESSAGES_PER_DAY,+} from '../assistant.constants';+import {+ type ChatLimitStore,+ checkChatLimits,+ readChatUsageToday,+ resolveChatTier,+} from './limits';++const NOW = new Date('2026-10-20T10:00:00Z');+const FUTURE = new Date('2036-01-01T00:00:00Z');+const PAST = new Date('2020-01-01T00:00:00Z');++function organization(+ overrides: Partial<Parameters<typeof resolveChatTier>[0]> = {}+) {+ return {+ subscriptionStatus: 'active',+ subscriptionCanceledAt: null,+ subscriptionEndsAt: FUTURE,+ subscriptionPauseAtPeriodEnd: false,+ subscriptionPeriodEventsLimit: 10_000,+ ...overrides,+ };+}++describe('resolveChatTier', () => {+ // The test preload pins SELF_HOSTED=true; the Cloud bands need it off.+ let selfHostedEnv: string | undefined;+ beforeAll(() => {+ selfHostedEnv = process.env.SELF_HOSTED;+ process.env.SELF_HOSTED = 'false';+ });+ afterAll(() => {+ process.env.SELF_HOSTED = selfHostedEnv;+ });++ test('self-hosted installs are unlimited whatever the billing rows say', () => {+ expect(+ resolveChatTier(organization({ subscriptionStatus: null }), true)+ ).toBe('unlimited');+ });++ test('trials and blocked billing states', () => {+ expect(+ resolveChatTier(organization({ subscriptionStatus: 'trialing' }), false)+ ).toBe('trial');+ expect(+ resolveChatTier(+ organization({ subscriptionStatus: null, subscriptionEndsAt: PAST }),+ false+ )+ ).toBe('blocked');+ expect(+ resolveChatTier(organization({ subscriptionStatus: 'canceled' }), false)+ ).toBe('blocked');+ expect(+ resolveChatTier(organization({ subscriptionStatus: 'past_due' }), false)+ ).toBe('starter');+ });++ test('paid plans band by their event limit', () => {+ expect(resolveChatTier(organization(), false)).toBe('starter');+ expect(+ resolveChatTier(+ organization({ subscriptionPeriodEventsLimit: 100_000 }),+ false+ )+ ).toBe('starter');+ expect(+ resolveChatTier(+ organization({ subscriptionPeriodEventsLimit: 250_000 }),+ false+ )+ ).toBe('growth');+ expect(+ resolveChatTier(+ organization({ subscriptionPeriodEventsLimit: 5_000_000 }),+ false+ )+ ).toBe('scale');+ });+});++class MemoryStore implements ChatLimitStore {+ values = new Map<string, number>();+ expiries = new Map<string, number>();+ failing = false;++ get(key: string) {+ const value = this.values.get(key);+ return Promise.resolve(value === undefined ? null : String(value));+ }+ incr(key: string) {+ if (this.failing) {+ return Promise.reject(new Error('redis down'));+ }+ const next = (this.values.get(key) ?? 0) + 1;+ this.values.set(key, next);+ return Promise.resolve(next);+ }+ pttl(key: string) {+ return Promise.resolve(this.expiries.get(key) ?? -2);+ }+ pexpire(key: string, ms: number) {+ this.expiries.set(key, ms);+ return Promise.resolve(1);+ }+}++const silentLogger: Logger = {+ fatal: () => undefined,+ error: () => undefined,+ warn: () => undefined,+ info: () => undefined,+ debug: () => undefined,+ trace: () => undefined,+ child: () => silentLogger,+};++function deps(store: MemoryStore) {+ return { redis: store, logger: silentLogger };+}++describe('checkChatLimits', () => {+ test('a blocked workspace is refused without touching the store', async () => {+ const store = new MemoryStore();+ const refusal = await checkChatLimits(deps(store), {+ organizationId: 'org',+ userId: 'user',+ tier: 'blocked',+ now: NOW,+ });+ expect(refusal?.reason).toBe('blocked');+ expect(store.values.size).toBe(0);+ });++ test('the daily cap counts per workspace and resets at midnight UTC', async () => {+ const store = new MemoryStore();+ const cap = CHAT_MESSAGES_PER_DAY.trial ?? 0;+ for (let turn = 0; turn < cap; turn += 1) {+ const refusal = await checkChatLimits(deps(store), {+ organizationId: 'org',+ userId: `user-${turn}`,+ tier: 'trial',+ now: NOW,+ });+ expect(refusal).toBeNull();+ }+ const refusal = await checkChatLimits(deps(store), {+ organizationId: 'org',+ userId: 'late',+ tier: 'trial',+ now: NOW,+ });+ expect(refusal?.reason).toBe('daily');+ expect(refusal?.limit).toBe(cap);+ expect(refusal?.resetsAt).toBe('2026-10-21T00:00:00.000Z');+ expect(await readChatUsageToday(store, 'org', NOW)).toBe(cap + 1);+ // The day key expires at midnight, not a fixed 24h after the first hit.+ expect(store.expiries.get('chat:day:org:2026-10-20')).toBe(+ 14 * 60 * 60 * 1000+ );+ });++ test('the burst window refuses before a daily slot is consumed', async () => {+ const store = new MemoryStore();+ for (let turn = 0; turn < CHAT_BURST_LIMIT.max; turn += 1) {+ await checkChatLimits(deps(store), {+ organizationId: 'org',+ userId: 'user',+ tier: 'scale',+ now: NOW,+ });+ }+ const refusal = await checkChatLimits(deps(store), {+ organizationId: 'org',+ userId: 'user',+ tier: 'scale',+ now: NOW,+ });+ expect(refusal?.reason).toBe('burst');+ expect(await readChatUsageToday(store, 'org', NOW)).toBe(+ CHAT_BURST_LIMIT.max+ );+ });++ test('unlimited tiers only pay the burst guard', async () => {+ const store = new MemoryStore();+ const refusal = await checkChatLimits(deps(store), {+ organizationId: 'org',+ userId: 'user',+ tier: 'unlimited',+ now: NOW,+ });+ expect(refusal).toBeNull();+ expect(await readChatUsageToday(store, 'org', NOW)).toBe(0);+ });++ test('a store outage lets the turn through', async () => {+ const store = new MemoryStore();+ store.failing = true;+ const refusal = await checkChatLimits(deps(store), {+ organizationId: 'org',+ userId: 'user',+ tier: 'starter',+ now: NOW,+ });+ expect(refusal).toBeNull();+ });+});diff --git a/packages/core/src/modules/assistant/src/limits.ts b/packages/core/src/modules/assistant/src/limits.tsnew file mode 100644index 000000000..91bb62c0c--- /dev/null+++ b/packages/core/src/modules/assistant/src/limits.ts@@ -0,0 +1,194 @@+import {+ getSubscriptionState,+ type SubscriptionStateInput,+ subscriptionBlocksDashboard,+} from '@openpanel/payments/subscription-state';+import type { Logger } from '../../../logger';+import {+ CHAT_BURST_LIMIT,+ CHAT_MESSAGES_PER_DAY,+ CHAT_TIER_EVENT_BANDS,+ type ChatLimitError,+ type ChatTier,+} from '../assistant.constants';++const SECOND = 1000;+const DAY_MS = 24 * 60 * 60 * SECOND;+const KEY_MISSING = -2;+const KEY_WITHOUT_EXPIRY = -1;+const DATE_LENGTH = 'YYYY-MM-DD'.length;++const TIER_LABELS: Record<ChatTier, string> = {+ trial: 'free trial',+ starter: 'Starter',+ growth: 'Growth',+ scale: 'Scale',+ unlimited: 'self-hosted',+ blocked: 'inactive',+};++export type ChatTierInput = SubscriptionStateInput & {+ subscriptionPeriodEventsLimit: number;+};++export function resolveChatTier(+ organization: ChatTierInput,+ selfHosted: boolean+): ChatTier {+ if (selfHosted) {+ return 'unlimited';+ }+ const state = getSubscriptionState(organization);+ if (state === 'self_hosted') {+ return 'unlimited';+ }+ if (state === 'trialing') {+ return 'trial';+ }+ if (subscriptionBlocksDashboard(state)) {+ return 'blocked';+ }+ const events = organization.subscriptionPeriodEventsLimit;+ if (events <= CHAT_TIER_EVENT_BANDS.starter) {+ return 'starter';+ }+ if (events <= CHAT_TIER_EVENT_BANDS.growth) {+ return 'growth';+ }+ return 'scale';+}++/** The subset of the Redis client the counters need; narrow so tests can stub it. */+export interface ChatLimitStore {+ get(key: string): Promise<string | null>;+ incr(key: string): Promise<number>;+ pttl(key: string): Promise<number>;+ pexpire(key: string, ms: number): Promise<unknown>;+}++export interface ChatLimitDeps {+ redis: ChatLimitStore;+ logger: Logger;+}++export interface ChatLimitInput {+ organizationId: string;+ userId: string;+ tier: ChatTier;+ now?: Date;+}++const dayKey = (organizationId: string, now: Date) =>+ `chat:day:${organizationId}:${now.toISOString().slice(0, DATE_LENGTH)}`;+const burstKey = (userId: string) => `chat:burst:${userId}`;++function nextUtcMidnight(now: Date): Date {+ return new Date(Math.floor(now.getTime() / DAY_MS) * DAY_MS + DAY_MS);+}++/** Fixed window: the first hit opens it; a counter that lost its expiry is re-armed so it cannot lock a caller out for good. */+async function countHit(+ store: ChatLimitStore,+ key: string,+ windowMs: number+): Promise<{ hits: number; ttlMs: number }> {+ const hits = await store.incr(key);+ let ttlMs = await store.pttl(key);+ if (hits === 1 || ttlMs === KEY_WITHOUT_EXPIRY || ttlMs === KEY_MISSING) {+ await store.pexpire(key, windowMs);+ ttlMs = windowMs;+ }+ return { hits, ttlMs };+}++function blockedError(tier: ChatTier, resetsAt: Date): ChatLimitError {+ return {+ code: 'chat_limit',+ reason: 'blocked',+ tier,+ limit: 0,+ resetsAt: resetsAt.toISOString(),+ message:+ 'The AI assistant is paused until the workspace has an active plan.',+ };+}++function burstError(tier: ChatTier, ttlMs: number, now: Date): ChatLimitError {+ const seconds = Math.max(1, Math.ceil(ttlMs / SECOND));+ return {+ code: 'chat_limit',+ reason: 'burst',+ tier,+ limit: CHAT_BURST_LIMIT.max,+ resetsAt: new Date(now.getTime() + ttlMs).toISOString(),+ message: `That is a lot of messages at once. You can send the next one in ${seconds} seconds.`,+ };+}++function dailyError(tier: ChatTier, limit: number, now: Date): ChatLimitError {+ return {+ code: 'chat_limit',+ reason: 'daily',+ tier,+ limit,+ resetsAt: nextUtcMidnight(now).toISOString(),+ message: `Today's ${limit} AI messages on the ${TIER_LABELS[tier]} plan are used up. The limit resets at midnight UTC.`,+ };+}++/**+ * Counts one user turn and answers with the refusal to send, or `null` when+ * the turn may run. The burst window is checked first so a refused burst does+ * not consume a daily slot. A Redis failure lets the turn through: this guards+ * spend, not access.+ */+export async function checkChatLimits(+ deps: ChatLimitDeps,+ input: ChatLimitInput+): Promise<ChatLimitError | null> {+ const now = input.now ?? new Date();+ const { tier } = input;+ if (tier === 'blocked') {+ return blockedError(tier, now);+ }+ try {+ const burst = await countHit(+ deps.redis,+ burstKey(input.userId),+ CHAT_BURST_LIMIT.windowMs+ );+ if (burst.hits > CHAT_BURST_LIMIT.max) {+ return burstError(tier, burst.ttlMs, now);+ }+ const cap = CHAT_MESSAGES_PER_DAY[tier];+ if (cap === null) {+ return null;+ }+ const day = await countHit(+ deps.redis,+ dayKey(input.organizationId, now),+ nextUtcMidnight(now).getTime() - now.getTime()+ );+ if (day.hits > cap) {+ deps.logger.warn(+ { organizationId: input.organizationId, tier, cap, hits: day.hits },+ 'chat daily limit reached'+ );+ return dailyError(tier, cap, now);+ }+ return null;+ } catch (error) {+ deps.logger.error({ err: error }, 'chat limit store unavailable');+ return null;+ }+}++/** Messages the workspace has sent today, for the billing tool. */+export async function readChatUsageToday(+ store: ChatLimitStore,+ organizationId: string,+ now = new Date()+): Promise<number> {+ const value = await store.get(dayKey(organizationId, now));+ return Number(value) || 0;+}diff --git a/packages/core/src/modules/assistant/src/message.ts b/packages/core/src/modules/assistant/src/message.tsnew file mode 100644index 000000000..394f2d8aa--- /dev/null+++ b/packages/core/src/modules/assistant/src/message.ts@@ -0,0 +1,15 @@+import type { InferUITools, UIMessage } from 'ai';+import type {+ ChatDataParts,+ ChatMessageMetadata,+} from '../assistant.constants';+import type { ChatTools } from './tools';++/** The wire and storage shape of one chat message. */+export type AssistantUIMessage = UIMessage<+ ChatMessageMetadata,+ ChatDataParts,+ InferUITools<ChatTools>+>;++export type AssistantUIMessagePart = AssistantUIMessage['parts'][number];diff --git a/packages/core/src/modules/assistant/src/persistence.ts b/packages/core/src/modules/assistant/src/persistence.tsindex 6693c4a1e..cc08dea6c 100644--- a/packages/core/src/modules/assistant/src/persistence.ts+++ b/packages/core/src/modules/assistant/src/persistence.ts@@ -1,103 +1,95 @@-import type { ConversationStore } from '@better-agent/core';-import type { ConversationItem } from '@better-agent/core/providers';import type { ServiceDeps } from '../../../services';-import { chatRunContext } from './run-context';+import type { AssistantUIMessage } from './message';-// Built from the route's deps and closing over them: `ConversationStore`'s-// load/save signatures leave no room for a `Ctx`.--/**- * Prisma-backed `ConversationStore`: one `ConversationItem` per `ChatMessage`- * row, the whole item in `parts`.- *- * Better Agent hands over the full item list on every save and prior items are- * immutable, so when the list is not shorter than the stored count only the- * tail is inserted; otherwise (edit, retry) the rows are rewritten. The cursor- * is `updatedAt`; a single writer per conversation is assumed, not checked.- */-function roleOf(item: ConversationItem): string {- if (item.type === 'message') {- return item.role;- }- return item.type;-}--function itemToRow(conversationId: string, item: ConversationItem) {- return {- conversationId,- role: roleOf(item),- // Prisma types the column as `unknown[]` but it stores one `ConversationItem`.- // biome-ignore lint/suspicious/noExplicitAny: see comment above- parts: item as any,- };+/** Rows are one UI message each; `parts` is the message's parts array. */+export async function loadMessages(+ deps: ServiceDeps,+ conversationId: string+): Promise<AssistantUIMessage[]> {+ const rows = await deps.db.chatMessage.findMany({+ where: { conversationId },+ orderBy: { createdAt: 'asc' },+ });+ return rows.map((row) => ({+ id: row.id,+ role: row.role as AssistantUIMessage['role'],+ parts: row.parts as AssistantUIMessage['parts'],+ metadata: (row.metadata ?? undefined) as AssistantUIMessage['metadata'],+ }));}-export function createConversationStore(deps: ServiceDeps): ConversationStore {- const db = deps.db;- return {- async load({ conversationId }) {- const conv = await db.conversation.findUnique({- where: { id: conversationId },- include: {- messages: { orderBy: { createdAt: 'asc' } },+export async function saveMessages(+ deps: ServiceDeps,+ input: {+ conversationId: string;+ projectId: string;+ organizationId: string;+ userId: string;+ messages: AssistantUIMessage[];+ title?: string | null;+ }+): Promise<void> {+ await deps.db.$transaction(async (tx) => {+ // Message ids come from the client; one must not overwrite a row in another conversation.+ const foreign = await tx.chatMessage.findFirst({+ where: {+ id: { in: input.messages.map((message) => message.id) },+ conversationId: { not: input.conversationId },+ },+ select: { id: true },+ });+ if (foreign) {+ throw new Error(`Message ${foreign.id} belongs to another conversation`);+ }+ await tx.conversation.upsert({+ where: { id: input.conversationId },+ create: {+ id: input.conversationId,+ projectId: input.projectId,+ organizationId: input.organizationId,+ userId: input.userId,+ title: input.title ?? undefined,+ },+ update: {+ updatedAt: new Date(),+ ...(input.title ? { title: input.title } : {}),+ },+ });+ // Rows saved together must load in this order; the default timestamp can tie.+ const baseTime = Date.now();+ for (const [index, message] of input.messages.entries()) {+ const parts = message.parts as unknown[];+ const metadata = (message.metadata ?? {}) as Record<string, unknown>;+ await tx.chatMessage.upsert({+ where: { id: message.id },+ create: {+ id: message.id,+ conversationId: input.conversationId,+ role: message.role,+ parts,+ metadata,+ createdAt: new Date(baseTime + index),},+ update: { parts, metadata },});- if (!conv) {- return null;- }-- return {- items: conv.messages.map((m) => m.parts as unknown as ConversationItem),- cursor: conv.updatedAt.getTime(),- };- },-- async save({ conversationId, items }) {- const owner = chatRunContext.getStore();- if (!owner) {- throw new Error(- 'chatRunContext missing during save — assistant.routes.ts must run the handler inside chatRunContext.run()'- );- }-- await db.$transaction(async (tx) => {- await tx.conversation.upsert({- where: { id: conversationId },- create: {- id: conversationId,- projectId: owner.projectId,- organizationId: owner.organizationId,- userId: owner.userId,- },- update: { updatedAt: new Date() },- });-- const existingCount = await tx.chatMessage.count({- where: { conversationId },- });-- if (items.length >= existingCount) {- const newItems = items.slice(existingCount);- if (newItems.length > 0) {- await tx.chatMessage.createMany({- data: newItems.map((item) => itemToRow(conversationId, item)),- });- }- } else {- await tx.chatMessage.deleteMany({ where: { conversationId } });- if (items.length > 0) {- await tx.chatMessage.createMany({- data: items.map((item) => itemToRow(conversationId, item)),- });- }- }- });+ }+ });+}- const updated = await db.conversation.findUnique({- where: { id: conversationId },- select: { updatedAt: true },- });- return { cursor: updated?.updatedAt.getTime() ?? Date.now() };- },- };+/** Regeneration: drop the message and everything after it. */+export async function deleteMessagesFrom(+ deps: ServiceDeps,+ conversationId: string,+ messageId: string+): Promise<void> {+ const target = await deps.db.chatMessage.findFirst({+ where: { id: messageId, conversationId },+ select: { createdAt: true },+ });+ if (!target) {+ return;+ }+ await deps.db.chatMessage.deleteMany({+ where: { conversationId, createdAt: { gte: target.createdAt } },+ });}diff --git a/packages/core/src/modules/assistant/src/prompt.test.ts b/packages/core/src/modules/assistant/src/prompt.test.tsnew file mode 100644index 000000000..e382ac218--- /dev/null+++ b/packages/core/src/modules/assistant/src/prompt.test.ts@@ -0,0 +1,37 @@+import { describe, expect, test } from 'bun:test';+import { buildSystemPrompt } from './prompt';++const base = {+ projectName: 'Acme',+ timezone: 'UTC',+ now: new Date('2026-10-19T12:00:00Z'),+};++describe('buildSystemPrompt', () => {+ test('Cloud users are never sent to environment variables', () => {+ const prompt = buildSystemPrompt({ ...base, selfHosted: false });+ expect(prompt).toContain('OpenPanel Cloud');+ expect(prompt).toContain('never suggest');+ expect(prompt).toContain('mailto:[email protected]');+ expect(prompt).not.toContain('self-hosted OpenPanel install');+ });++ test('self-hosters are told they own the stack', () => {+ const prompt = buildSystemPrompt({ ...base, selfHosted: true });+ expect(prompt).toContain('self-hosted OpenPanel install');+ expect(prompt).toContain('There is no billing');+ });++ test('the launch hint lands at the end', () => {+ const prompt = buildSystemPrompt({+ ...base,+ selfHosted: false,+ hint: { page: 'profile', profileId: 'p1' },+ });+ expect(+ prompt.endsWith(+ 'They were viewing profile p1; get_profile defaults to it.'+ )+ ).toBe(true);+ });+});diff --git a/packages/core/src/modules/assistant/src/prompt.ts b/packages/core/src/modules/assistant/src/prompt.tsindex 5e2618afa..e0cc0568c 100644--- a/packages/core/src/modules/assistant/src/prompt.ts+++ b/packages/core/src/modules/assistant/src/prompt.ts@@ -1,220 +1,133 @@-import type { ChatAgentContext, PageContext } from './context';-import { resolveDateRange } from './tools/helpers';--function buildBasePrompt(): string {- return `You are the OpenPanel AI assistant. OpenPanel is an open-source product/web analytics platform similar to Mixpanel and Plausible. You help users explore and understand their analytics data.--The current date is supplied at the bottom of this prompt under "Current view". Use it for relative date math ("last week", "yesterday", "this month").--# Behavioral rules-- Every factual claim must come from a tool result. Never fabricate numbers, names, or dates.-- Prefer SAVED reports over ad-hoc generation: try list_dashboards → list_reports → get_report_data first when the user asks about something that might already be saved.-- Before calling generate_report, verify event names with list_event_names and breakdown property keys with list_event_properties.-- Use the user's current date range and filters from "Current view" below unless they explicitly ask for a different range.-- Cite data through rendered tool results, not by repeating numbers in prose. Keep prose short — let the UI do the work.-- If a tool result has _truncated: true, briefly mention there's more data available.--# Filtering the page (apply_filters / set_property_filters / set_event_names_filter)-The user can ask you to "filter to X" or "show me Y" — when they do, **call the matching client-side tool** to actually move the page, don't just describe the data.--For \`apply_filters\` (date range / interval):-- The ONLY valid preset values for \`range\` are: \`30min\`, \`lastHour\`, \`today\`, \`yesterday\`, \`7d\`, \`30d\`, \`6m\`, \`12m\`, \`monthToDate\`, \`lastMonth\`, \`yearToDate\`, \`lastYear\`, \`custom\`. Anything else is invalid and the page will reject it.-- Map common phrasing to presets when possible:- - "last 7 days" / "past week" / "this week" → \`7d\`- - "last 30 days" / "past month" → \`30d\`- - "last 6 months" → \`6m\`- - "last year" → \`lastYear\`- - "this month" → \`monthToDate\`- - "last month" → \`lastMonth\`- - "this year" → \`yearToDate\`-- For ANYTHING that doesn't match a preset above, you MUST use \`startDate\` + \`endDate\` (YYYY-MM-DD) computed relative to today (see the date at the bottom of this prompt) — do NOT invent new preset names. Examples:- - "last week" (Mon-Sun of previous calendar week) → compute the dates manually as a custom range- - "the past 14 days" → startDate = today − 14 days, endDate = today- - "May 24-28" → startDate = current-year-05-24, endDate = current-year-05-28- - "Q1 2026" → startDate = 2026-01-01, endDate = 2026-03-31-- When you set \`startDate\` + \`endDate\`, omit \`range\` (it's set to \`custom\` automatically by the handler).--For \`set_property_filters\` and \`set_event_names_filter\`:-- These REPLACE the current filter set — to ADD to existing filters, include the current ones too (read them from \`Current view\` below).-- For referrers: default to the \`referrer_name\` property (matches values like "GitHub", "Hacker News", "Bing", "Direct"). Use \`referrer_type\` only for traffic class (search/social/direct/etc.) and the raw \`referrer\` URL only when the user asks for an exact URL.-- After applying, briefly confirm what changed: "Done — filtered to mobile only." Then optionally answer the underlying question.--# Reasoning approach-- For deep questions, plan a chain of 2-5 tool calls. You have up to 20 steps.-- For comparative questions ("why is X higher than Y?"), gather both sides before answering.-- For "explain this spike/drop" questions, drill into the time interval AND a relevant breakdown (country, device, referrer).-- **Always check references when explaining traffic changes.** The user may have logged a real-world event (campaign launch, deploy, press mention). Use \`get_references_around\` with the spike/drop date before concluding "we don't know why" — a reference often explains it in one sentence.--# Charts and visualizations — IMPORTANT-Users frequently want to SEE data, not just read numbers. Whenever the user says "show me…", "chart of…", "trend of…", "graph / line / visualization", "plot…", "over time", or asks a follow-up like "can I get a trend line for that?" — you MUST call \`generate_report\` (or a specialized chart tool) so the UI renders an actual chart. If the user asks for a chart and you respond with prose only, you failed.--## Chart type decision table-Pick the \`chartType\` that matches the question:--- \`linear\` — trends over time (default for time series). "signups over time", "pageviews per day"-- \`area\` — stacked time series, usually with a breakdown-- \`bar\` — categorical comparisons / top-N. "top pages", "traffic by country"-- \`pie\` — part-of-whole, ≤6 slices only. If >6, use \`bar\` with \`limit\`-- \`metric\` — single KPI number. "total signups this month"-- \`funnel\` — ordered step completion (2+ events). Returns step drop-off-- \`retention\` — cohort retention of a single event. Use \`interval: "week"\`-- \`conversion\` — A→B rate chart (2 events). Shows conversion % series-- \`sankey\` — multi-step user flow (3+ events)-- \`map\` — geographic breakdown. Use \`breakdowns: [{ name: "country" }]\`-- \`histogram\` — distribution of a numeric property (e.g. session duration buckets)--Specialized tools (prefer these when they fit — they're cheaper and already typed):-- DAU / WAU / MAU over time → \`get_rolling_active_users\` with \`windowDays: 1\` / \`7\` / \`30\`-- Funnel → \`get_funnel\` (or \`generate_report\` with \`chartType: "funnel"\`)--## Filter operators — use these EXACT keys-\`generate_report\` filters use an enum; inventing an operator will fail validation:--- \`is\` — equals (DEFAULT for equality — NOT \`equals\` / \`eq\` / \`==\`)-- \`isNot\` — not equal-- \`contains\` / \`doesNotContain\`-- \`startsWith\` / \`endsWith\`-- \`regex\`-- \`isNull\` / \`isNotNull\` (use empty \`value: []\`)-- \`gt\` / \`lt\` / \`gte\` / \`lte\` — numeric comparisons--## Defaults to always emit-- \`metric\` → \`"sum"\` unless user explicitly asks for average/min/max.-- \`interval\` by range: \`hour\` for ≤48h, \`day\` for ≤90d, \`week\` for ≤1y, \`month\` beyond.-- \`lineType\` → \`"monotone"\` on \`linear\`/\`area\` unless the user wants a stepped/straight look.-- "Top X by Y" → \`chartType: "bar"\`, \`breakdowns: [{ name: Y }]\`, \`limit: X\`.-- Always include \`title\` (3-8 words describing what the chart shows).--## Advanced patterns-- **Unique users / sessions**: \`segment: "user"\` or \`"session"\` on the event (NOT default \`"event"\` which counts firings).-- **Sum/avg a numeric property**: \`segment: "property_sum"\` (or \`_average\`/\`_max\`/\`_min\`) + \`property: "revenue"\` (or duration, etc.). Example: \`{ type: "event", name: "purchase", segment: "property_sum", property: "revenue" }\`.-- **Ratios / conversion rate over time**: add a \`formula\` series. Series are lettered A, B, C, … by array index:- \`\`\`- series: [- { type: "event", name: "signup" }, // A- { type: "event", name: "subscription_started" }, // B- { type: "formula", formula: "B / A * 100", displayName: "Conversion %", hideSeries: ["A", "B"] }- ]- \`\`\`-- **Vs previous period**: top-level \`previous: true\`. Great for "vs last week" / "vs last month".-- **Funnel by session vs profile**: \`chartType: "funnel"\` + \`funnelGroup: "session"\` when the user says "funnel by session".--## Anti-patterns — DO NOT-- DO NOT invent event names. Always call \`list_event_names\` first.-- DO NOT put an unverified property key in filters/breakdowns — call \`list_event_properties\` first.-- DO NOT use \`operator: "equals"\` / \`"eq"\` / \`"=="\` — the only valid equality operator is \`is\`.-- DO NOT combine \`segment: "user"\` with \`property\` — \`property\` only applies to \`property_*\` segments.-- DO NOT use \`chartType: "pie"\` with >10 values — switch to \`bar\` + \`limit: 10\`.-- DO NOT omit \`title\`.--When you call a chart tool, keep prose SHORT — a one-line caption like "Here's the MAU trend over the last 30 days." The chart does the talking.--## Examples--1. **Pageviews per day, last 30 days**-\`{ "chartType": "linear", "interval": "day", "startDate": "...", "endDate": "...", "lineType": "monotone", "series": [{ "type": "event", "name": "screen_view" }], "title": "Pageviews per day" }\`--2. **Top 10 pages**-\`{ "chartType": "bar", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "screen_view" }], "breakdowns": [{ "name": "path" }], "limit": 10, "title": "Top 10 pages" }\`--3. **Unique visitors by country (map)**-\`{ "chartType": "map", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "screen_view", "segment": "user" }], "breakdowns": [{ "name": "country" }], "title": "Unique visitors by country" }\`--4. **Signup → subscription conversion rate over time**-\`{ "chartType": "linear", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "signup" }, { "type": "event", "name": "subscription_started" }, { "type": "formula", "formula": "B / A * 100", "displayName": "Conversion %", "hideSeries": ["A","B"] }], "unit": "%", "title": "Signup → subscription rate" }\`--5. **Revenue per day**-\`{ "chartType": "linear", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "purchase", "segment": "property_sum", "property": "revenue" }], "unit": "$", "title": "Revenue per day" }\`--6. **Signup → activation → purchase funnel**-\`{ "chartType": "funnel", "interval": "day", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "signup" }, { "type": "event", "name": "activated" }, { "type": "event", "name": "purchase" }], "title": "Signup to purchase funnel" }\`--7. **Weekly retention for signup**-\`{ "chartType": "retention", "interval": "week", "startDate": "...", "endDate": "...", "series": [{ "type": "event", "name": "signup" }], "title": "Weekly signup retention" }\`--8. **MRR vs last month**-\`{ "chartType": "linear", "interval": "day", "startDate": "...", "endDate": "...", "previous": true, "series": [{ "type": "event", "name": "subscription_charge", "segment": "property_sum", "property": "amount" }], "unit": "$", "title": "MRR vs last month" }\``;+import {+ CHAT_DIALOGS,+ CHAT_ROUTES,+ type ChatLaunchHint,+} from '../assistant.constants';++const DATE_LENGTH = 10;++function routeCatalog(): string {+ return Object.entries(CHAT_ROUTES)+ .map(([key, route]) => `- ${key}: ${route.label}. ${route.description}`)+ .join('\n');}-export function buildSystemPrompt(context: ChatAgentContext): string {- return [buildBasePrompt(), buildPageContextSection(context.pageContext)].join(- '\n\n'- );+function dialogCatalog(): string {+ return Object.entries(CHAT_DIALOGS)+ .map(([key, dialog]) => `- ${key}: ${dialog.label}. ${dialog.description}`)+ .join('\n');}-function buildPageContextSection(pc?: PageContext): string {- // The date changes daily, so it goes at the bottom, out of the cached prefix.- // UTC: queries bucket by day, not by user timezone.- const today = new Date();- const todayIso = today.toISOString().slice(0, 10);- const dayName = today.toLocaleDateString('en-US', {+const PRODUCT_KNOWLEDGE = `# What OpenPanel is+OpenPanel is an open-source product and web analytics platform (an alternative to Mixpanel, Plausible and Google Analytics), available as a cloud service and self-hosted.++Core concepts:+- Events are tracked with the SDKs or the track API. \`screen_view\` is a page view with a \`path\`; \`session_start\` and \`session_end\` are automatic; everything else is a custom event with custom properties.+- A session is a visit; it carries device, browser, OS, country, referrer and UTM parameters.+- A profile is a visitor. Anonymous profiles are per device; \`identify\` turns one into an identified profile with an id, email and name. Groups (accounts, companies) hold profiles.+- Reports are charts: linear, bar, area, pie, metric, funnel, retention, conversion, sankey, map, histogram. Dashboards hold reports.+- References are dated annotations drawn on charts. Cohorts are saved user segments. Notification rules alert on events or funnels through Slack, Discord, email or webhooks.+- Session replay records sessions when enabled in the SDK. Insights are automatic anomaly detections.+- API clients are id and secret pairs: \`write\` for SDKs, \`read\` for exports, \`root\` for the management API. Websites and apps use the client id only. Clients are created through the addClient dialog (open_dialog), never by you: the dialog shows the secret once, and you never see or ask for it.+- The MCP server lets Claude, Cursor and other AI clients query a project; it is set up from the MCP settings page with the token of a read or root client (write clients cannot use MCP).+- SDKs: Web script, JavaScript, React, Next.js, Vue, Nuxt, Remix, Astro, React Native, Expo, Swift, Kotlin, Node, Express, Python, Ruby, Java, Rust. Imports exist for Mixpanel and Umami.`;++export interface SystemPromptInput {+ projectName: string;+ timezone: string;+ /** True on a self-hosted install, false on OpenPanel Cloud. */+ selfHosted: boolean;+ hint?: ChatLaunchHint;+ now?: Date;+}++const CLOUD_DEPLOYMENT = `# Deployment+This is OpenPanel Cloud, hosted at openpanel.dev. The user is a customer, not an operator: they cannot set environment variables, run Docker, edit compose files or touch the database, so never suggest any of that. Infrastructure, upgrades and backups are handled for them. Billing, plans and usage live under the workspace settings; get_billing reads them and change_plan changes the plan. The MCP endpoint is https://api.openpanel.dev/mcp; the MCP settings page shows it with the per-client token. Support is [email protected]: whenever you point the user to support, a custom plan, or anything the dashboard cannot do, write it as the link [[email protected]](mailto:[email protected]).`;++const SELF_HOSTED_DEPLOYMENT = `# Deployment+This is a self-hosted OpenPanel install run by the user's own team. They control environment variables, the Docker Compose stack (ClickHouse, Postgres, Redis, the API and the dashboard), upgrades and backups, so pointing to the self-hosting docs and environment variables is appropriate. Some features need keys they provide themselves (AI chat, Google Search Console, email). The MCP endpoint is their own API URL followed by /mcp; the MCP settings page shows the exact value. There is no billing in a self-hosted install. For help beyond the docs, point to the GitHub issues at https://github.com/Openpanel-dev/openpanel/issues, or [[email protected]](mailto:[email protected]) for commercial questions.`;++export function buildSystemPrompt(input: SystemPromptInput): string {+ const now = input.now ?? new Date();+ const today = now.toISOString().slice(0, DATE_LENGTH);+ const weekday = now.toLocaleDateString('en-US', {weekday: 'long',timeZone: 'UTC',});- const lines: string[] = [- '# Current view',- `Today is **${dayName}, ${todayIso}** (UTC).`,- ];+ return `You are the OpenPanel assistant for the project "${input.projectName}". You answer questions about its analytics data, build charts and dashboards, explain how OpenPanel works, and take the user to the right place in the dashboard.- if (!pc) {- return lines.join('\n');- }+${PRODUCT_KNOWLEDGE}- lines.push(`The user is on the **${pc.page}** page.`);+# How to work+- Every number comes from a tool. Never estimate or invent data, event names or property names. Call describe_data before naming an event or property you have not seen in this conversation.+- Keep answers short. Lead with the answer, then one or two sentences of context. Use a short markdown table for several numbers. No headings in chat replies.+- Data is shown as charts. get_overview, get_breakdown, get_funnel, get_active_users, get_retention, get_user_flow and create_chart all render a report card in the chat; add a one-line caption and name only the one or two numbers that matter. Never restate the chart's rows as a list or table in prose: the card already shows them. Do not call the same tool twice with the same range.+- For "why did X change" questions, look at the breakdowns (referrer, country, device, page) and check list_references for the period before concluding.+- When the user pastes an id, email, name or URL path, call search first.+- For questions about the plan, billing, usage or event limits, call get_billing and answer from it. To upgrade or downgrade: call list_plans, name the plan and its price back to the user, then change_plan; an active paid subscription changes immediately, otherwise the user gets a checkout button. Only workspace admins can change the plan.+- When events are missing, a site "is not tracking", or the user asks whether the install is right, call diagnose_tracking with the site URL. If they did not name a site and the project has a domain, confirm that domain in one line before or after running it. The checklist card lists every finding; do not repeat it. Explain the one or two findings that explain the problem, say what to change, and link the settings page.+- For product questions ("how do I", "can I", "where is", "is it possible", "what does X mean"), call search_docs, answer from the result, and link the page. If the answer is a setting or a page in the dashboard, call navigate to offer the link. If the next step is creating something, call open_dialog with the fields prefilled (it renders a button the user presses), or use a create_* tool.+- Tools that change data ask the user to confirm; propose them freely and say what will happen. If a tool fails because of missing permissions, say so and point to who can do it.+- When the user asks for a dashboard, plan it: confirm the events with describe_data, create the dashboard, then save 3 to 6 charts that answer the question, and finish with the link.+- If something is impossible in OpenPanel, say so plainly and suggest the closest thing.- if (pc.filters?.range) {- const range = pc.filters.range;- // Resolve presets ("6m", "7d") in the project's timezone so the model sees- // the window the dashboard shows.- const resolved = resolveDateRange(pc.filters);- const dates = ` (${resolved.startDate} to ${resolved.endDate})`;- const interval = pc.filters.interval ?? 'day';- lines.push(`Date range: ${range}${dates}, interval: ${interval}.`);- }+# Charts+- Use create_chart for ad-hoc charts. Verify names first. Pick: linear for trends, bar for top-N, pie for a few shares, metric for a single number, funnel for ordered steps, retention for cohorts (interval week), conversion for an A-to-B rate over time, map for countries, histogram for distributions.+- Interval: hour for up to 2 days, day for up to 90 days, week for up to a year, month beyond.+- Unique visitors or users: segment \`user\`. Revenue or any sum: segment \`property_sum\` with the property. Rates: two event series plus a formula series such as \`B / A * 100\` with the inputs hidden.+- Dates are YYYY-MM-DD. Resolve relative ranges from today's date below.+- Revenue in rows from the query and breakdown tools is already in currency units; a revenue sum in a chart summary is in cents, as the summary says. The dashboard shows currency units.- if (pc.filters?.eventNames && pc.filters.eventNames.length > 0) {- lines.push(- `Active event-name filter: ${JSON.stringify(pc.filters.eventNames)}`- );- }+# Dashboard routes (for navigate; it offers a link, it does not move the user)+${routeCatalog()}++# Dialogs (for open_dialog; it offers a button, the user opens it)+${dialogCatalog()}++${input.selfHosted ? SELF_HOSTED_DEPLOYMENT : CLOUD_DEPLOYMENT}++# Today+${weekday}, ${today} (UTC). The project reports in the ${input.timezone} timezone.${hintSection(input.hint)}`;+}- if (pc.filters?.eventFilters && pc.filters.eventFilters.length > 0) {+function hintSection(hint?: ChatLaunchHint): string {+ if (!hint) {+ return '';+ }+ const lines: string[] = [];+ if (hint.page) {+ lines.push(`The user opened the chat from the ${hint.page} page.`);+ }+ if (hint.startDate && hint.endDate) {lines.push(- `Active property filters: ${JSON.stringify(pc.filters.eventFilters)}`+ `They were looking at ${hint.startDate} to ${hint.endDate}${hint.interval ? ` by ${hint.interval}` : ''}. Use that range unless they ask for another.`);- }-- if (pc.ids?.profileId) {+ } else if (hint.range) {lines.push(- `They are viewing profile \`${pc.ids.profileId}\`. Profile-specific tools below are pre-bound to this profile by default.`+ `They were looking at the "${hint.range}" range${hint.interval ? ` by ${hint.interval}` : ''}. Use that range unless they ask for another.`);}- if (pc.ids?.sessionId) {+ if (hint.profileId) {lines.push(- `They are viewing session \`${pc.ids.sessionId}\`. Session-specific tools are pre-bound to this session.`+ `They were viewing profile ${hint.profileId}; get_profile defaults to it.`);}- if (pc.ids?.groupId) {+ if (hint.sessionId) {lines.push(- `They are viewing group \`${pc.ids.groupId}\`. Group-specific tools are pre-bound to this group.`+ `They were viewing session ${hint.sessionId}; get_session defaults to it.`);}- if (pc.ids?.reportId) {- lines.push(`They are viewing report \`${pc.ids.reportId}\`.`);+ if (hint.dashboardId) {+ lines.push(`They were viewing dashboard ${hint.dashboardId}.`);}-- if (pc.reportDraft) {- lines.push(- `They are editing this report draft:\n\`\`\`json\n${JSON.stringify(pc.reportDraft, null, 2)}\n\`\`\`\nUse preview_report_with_changes to propose edits to it.`- );+ if (hint.reportId) {+ lines.push(`They were viewing report ${hint.reportId}.`);}-- if (pc.primer) {- lines.push(- `Quick context (no tool call needed): ${JSON.stringify(pc.primer)}`- );+ if (hint.groupId) {+ lines.push(`They were viewing group ${hint.groupId}.`);}-- return lines.join('\n');+ return lines.length > 0+ ? `\n\n# Where the user came from\n${lines.join('\n')}`+ : '';}diff --git a/packages/core/src/modules/assistant/src/providers.ts b/packages/core/src/modules/assistant/src/providers.tsindex ac8f46391..b19242e8f 100644--- a/packages/core/src/modules/assistant/src/providers.ts+++ b/packages/core/src/modules/assistant/src/providers.ts@@ -1,34 +1,37 @@-// Server-only: browser code imports the model catalog from `assistant.constants`.-import { createAnthropic } from '@better-agent/providers/anthropic';-import { createOpenAI } from '@better-agent/providers/openai';+// Server-only: the browser reads the catalog from `assistant.constants`.+import { createAnthropic } from '@ai-sdk/anthropic';+import { createOpenAI } from '@ai-sdk/openai';+import type { LanguageModel, streamText } from 'ai';import type { CoreConfig } from '../../../config';-import type { ChatModelEntry } from '../assistant.constants';+import type {+ ChatModelEntry,+ ChatProvider,+ ConfiguredProviders,+} from '../assistant.constants';-export type { ChatModelEntry } from '../assistant.constants';-export { CHAT_MODELS as ALLOWED_MODELS } from '../assistant.constants';+/** Cheap models for titles and the one-shot filter command. */+const UTILITY_MODEL_BY_PROVIDER = {+ openai: 'gpt-5.4-nano',+ anthropic: 'claude-haiku-5-5',+} as const satisfies Record<ChatProvider, string>;// Memoized per `CoreConfig`, so a second config in one process (a test, a-// reboot) gets clients with its own credentials. Nothing to close: the clients-// are closures over `fetch` and hold no socket.+// reboot) gets clients with its own credentials.const openaiClients = new WeakMap<CoreConfig,ReturnType<typeof createOpenAI>>();+const anthropicClients = new WeakMap<+ CoreConfig,+ ReturnType<typeof createAnthropic>+>();function openai(config: CoreConfig) {const memoized = openaiClients.get(config);if (memoized) {return memoized;}-const { apiKey, baseUrl, project, organization } = config.ai.openai;-- if (!apiKey) {- console.warn(- `[chat] OPENAI_API_KEY is not set. Models routed through OpenAI will fail with "x-api-key required" until you add it to the API's env.`- );- }-const client = createOpenAI({apiKey,baseURL: baseUrl,@@ -39,45 +42,85 @@ function openai(config: CoreConfig) {return client;}-const anthropicClients = new WeakMap<- CoreConfig,- ReturnType<typeof createAnthropic>->();-function anthropic(config: CoreConfig) {const memoized = anthropicClients.get(config);if (memoized) {return memoized;}+ const { apiKey, baseUrl, authToken } = config.ai.anthropic;+ const client = createAnthropic({ apiKey, baseURL: baseUrl, authToken });+ anthropicClients.set(config, client);+ return client;+}++export function configuredProviders(config: CoreConfig): ConfiguredProviders {+ return {+ openai: Boolean(config.ai.openai.apiKey),+ anthropic: Boolean(config.ai.anthropic.apiKey),+ };+}++function modelFor(+ config: CoreConfig,+ provider: ChatProvider,+ modelId: string+): LanguageModel {+ return provider === 'openai'+ ? openai(config)(modelId)+ : anthropic(config)(modelId);+}- const { apiKey, baseUrl, authToken, version } = config.ai.anthropic;+export function resolveChatModel(+ config: CoreConfig,+ entry: ChatModelEntry+): LanguageModel {+ return modelFor(config, entry.provider, entry.modelId);+}- if (!apiKey) {- console.warn(- `[chat] ANTHROPIC_API_KEY is not set. Models routed through Anthropic will fail with "x-api-key required" until you add it to the API's env.`- );+/** The cheapest configured model, for titles and the filter command. */+export function resolveUtilityModel(config: CoreConfig): LanguageModel | null {+ const providers = configuredProviders(config);+ if (providers.openai) {+ return modelFor(config, 'openai', UTILITY_MODEL_BY_PROVIDER.openai);}+ if (providers.anthropic) {+ return modelFor(config, 'anthropic', UTILITY_MODEL_BY_PROVIDER.anthropic);+ }+ return null;+}- const client = createAnthropic({- apiKey,- baseURL: baseUrl,- authToken,- anthropicVersion: version,- });- anthropicClients.set(config, client);- return client;+type ProviderOptions = NonNullable<+ Parameters<typeof streamText>[0]['providerOptions']+>;++/** Reasoning summaries are off by default on both providers; the chat shows them. */+export function reasoningProviderOptions(+ entry: ChatModelEntry+): ProviderOptions {+ if (entry.provider === 'openai') {+ return { openai: { reasoningSummary: 'auto' as const } };+ }+ return {+ anthropic: {+ thinking: { type: 'adaptive' as const, display: 'summarized' as const },+ },+ };}-export const openaiProvider = openai;-export const anthropicProvider = anthropic;+/** OpenAI model ids the one-shot generators (digests, insights, win-back) pin to. */+export const OPENAI_TASK_MODELS = {+ /** Cheap batch scoring and short copy. */+ small: 'gpt-5.4-mini',+ /** Synthesis over a supplied breakdown. */+ standard: 'gpt-6.1-sol',+} as const;-export function resolveModel(config: CoreConfig, entry: ChatModelEntry) {- switch (entry.group) {- case 'OpenAI':- // biome-ignore lint/suspicious/noExplicitAny: OpenAI model id union is open- return openai(config).model(entry.modelId as any);- case 'Anthropic':- // biome-ignore lint/suspicious/noExplicitAny: Anthropic model id union is open- return anthropic(config).model(entry.modelId as any);+export function resolveOpenAITaskModel(+ config: CoreConfig,+ size: keyof typeof OPENAI_TASK_MODELS+): LanguageModel {+ if (!config.ai.openai.apiKey) {+ throw new Error('OPENAI_API_KEY is not set');}+ return modelFor(config, 'openai', OPENAI_TASK_MODELS[size]);}diff --git a/packages/core/src/modules/assistant/src/report-runner.ts b/packages/core/src/modules/assistant/src/report-runner.tsdeleted file mode 100644index 902fe815b..000000000--- a/packages/core/src/modules/assistant/src/report-runner.ts+++ /dev/null@@ -1,156 +0,0 @@-// Intentionally separate from `modules/mcp/src/tools/analytics/reports.ts`: both-// call the same @openpanel/db primitives and must be kept in sync by hand.--import type { CoreConfig } from '../../../config';-import type { ServiceDeps } from '../../../services';-import { executeAggregateChart, executeChart } from '../../chart/chart.service';-import { getFunnel } from '../../chart/funnel.service';-import { getSettingsForProject } from '../../organization/organization.service';-import {- getReportById,- type IServiceReport,-} from '../../report/report.service';-import { getChartStartEndDate } from '../../report/src/chart-dates';--const DEFAULT_DASHBOARD_URL = 'https://dashboard.openpanel.dev';-const TRAILING_SLASH = /\/$/;--function reportUrl(- config: CoreConfig,- organizationId: string,- projectId: string,- reportId: string-): string {- const base = (config.dashboardUrl || DEFAULT_DASHBOARD_URL).replace(- TRAILING_SLASH,- ''- );- return `${base}/${organizationId}/${projectId}/reports/${reportId}`;-}--/**- * Execute a saved report by ID, dispatching on chart type. Returns the raw- * engine output: the chat renderer needs the full chart, unlike MCP's copy,- * which reshapes it for an LLM.- */-export async function runReport(- deps: ServiceDeps,- input: {- organizationId: string;- projectId: string;- reportId: string;- }-): Promise<- | { error: string; reportId: string }- | {- id: string;- name: string;- chartType: string;- range: string;- interval: string;- startDate: string;- endDate: string;- dashboard_url: string;- /** The saved config as `zReportInput`, so the renderer can draw the chart. */- report: Omit<NonNullable<IServiceReport>, 'layout'>;- data: unknown;- }-> {- const report = await getReportById(deps, input.reportId);-- if (!report) {- return { error: 'Report not found', reportId: input.reportId };- }-- if (report.projectId !== input.projectId) {- return {- error: 'Report does not belong to this project',- reportId: input.reportId,- };- }-- const { timezone } = await getSettingsForProject(deps, input.projectId);- const { startDate, endDate } = getChartStartEndDate(report, timezone);- const chartInput = { ...report, startDate, endDate, timezone };-- // `layout` is the dashboard grid position, not chart config. `id` stays so the- // renderer can tell a saved report from an ad-hoc one.- const { layout: _layout, ...config } = report;-- const meta = {- id: report.id,- name: report.name,- chartType: report.chartType,- range: report.range,- interval: report.interval,- startDate,- endDate,- dashboard_url: reportUrl(- deps.config,- input.organizationId,- input.projectId,- input.reportId- ),- report: config,- };-- if (report.chartType === 'funnel') {- return { ...meta, data: await getFunnel(deps, chartInput) };- }- if (report.chartType === 'metric') {- return { ...meta, data: await executeAggregateChart(deps, chartInput) };- }- return { ...meta, data: await executeChart(deps, chartInput) };-}--/** Execute an ad-hoc report config (no DB lookup). */-export async function runReportFromConfig(- deps: ServiceDeps,- input: {- organizationId: string;- projectId: string;- config: {- chartType: string;- interval: string;- startDate: string;- endDate: string;- [key: string]: unknown;- };- }-): Promise<{- chartType: string;- interval: string;- startDate: string;- endDate: string;- report: typeof input.config & { projectId: string };- data: unknown;-}> {- const { timezone } = await getSettingsForProject(deps, input.projectId);- const chartInput = {- ...input.config,- projectId: input.projectId,- timezone,- } as unknown as Parameters<typeof executeChart>[1];-- const meta = {- chartType: input.config.chartType,- interval: input.config.interval,- startDate: input.config.startDate,- endDate: input.config.endDate,- report: { ...input.config, projectId: input.projectId },- };-- if (input.config.chartType === 'funnel') {- return {- ...meta,- data: await getFunnel(- deps,- chartInput as Parameters<typeof getFunnel>[1]- ),- };- }- if (input.config.chartType === 'metric') {- return { ...meta, data: await executeAggregateChart(deps, chartInput) };- }- return { ...meta, data: await executeChart(deps, chartInput) };-}diff --git a/packages/core/src/modules/assistant/src/run-context.ts b/packages/core/src/modules/assistant/src/run-context.tsdeleted file mode 100644index f009a0d90..000000000--- a/packages/core/src/modules/assistant/src/run-context.ts+++ /dev/null@@ -1,16 +0,0 @@-import { AsyncLocalStorage } from 'node:async_hooks';--/**- * Per-request context set by `assistant.routes.ts` after its access checks, read- * by the persistence store and the date-range/prompt code. AsyncLocalStorage- * because Better Agent's `onBeforeSave` hook does not expose the agent `context`.- */-export type ChatRunContext = {- userId: string;- projectId: string;- organizationId: string;- /** Project's configured timezone (IANA). Defaults to `UTC`. */- timezone: string;-};--export const chatRunContext = new AsyncLocalStorage<ChatRunContext>();diff --git a/packages/core/src/modules/assistant/src/title.ts b/packages/core/src/modules/assistant/src/title.tsnew file mode 100644index 000000000..2a6090d96--- /dev/null+++ b/packages/core/src/modules/assistant/src/title.ts@@ -0,0 +1,37 @@+import { generateText } from 'ai';+import type { CoreConfig } from '../../../config';+import { resolveUtilityModel } from './providers';++const MAX_INPUT_CHARS = 400;+const MAX_TITLE_CHARS = 80;+const MAX_OUTPUT_TOKENS = 40;+const QUOTES = /^["'“”]+|["'“”.]+$/g;++/** A 3 to 6 word title from the first message; null when nothing usable comes back. */+export async function generateConversationTitle(+ config: CoreConfig,+ firstMessage: string+): Promise<string | null> {+ const model = resolveUtilityModel(config);+ const text = firstMessage.trim().slice(0, MAX_INPUT_CHARS);+ if (!(model && text)) {+ return null;+ }+ try {+ const result = await generateText({+ model,+ instructions:+ 'Write a 3 to 6 word title for a chat that starts with the user message below. Reply with the title only: no quotes, no trailing period.',+ prompt: text,+ reasoning: 'low',+ maxOutputTokens: MAX_OUTPUT_TOKENS,+ });+ const title = result.text+ .trim()+ .replace(QUOTES, '')+ .slice(0, MAX_TITLE_CHARS);+ return title || null;+ } catch {+ return null;+ }+}diff --git a/packages/core/src/modules/assistant/src/tools/analytics.ts b/packages/core/src/modules/assistant/src/tools/analytics.tsnew file mode 100644index 000000000..2ae9863a8--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/analytics.ts@@ -0,0 +1,585 @@+import { sql } from '@openpanel/db/src/clickhouse/sql';+import { tool } from 'ai';+import { z } from 'zod';+import { chQuery } from '../../../../ch-query';+import { getFunnelCore } from '../../../chart/funnel.service';+import {+ getRetentionCohortCore,+ getRollingActiveUsersCore,+} from '../../../chart/retention.service';+import { getUserFlowCore } from '../../../chart/sankey.service';+import { queryEventsCore } from '../../../event/event.service';+import {+ getAnalyticsOverviewCore,+ getTrafficBreakdownCore,+ type TrafficColumn,+} from '../../../overview/overview.service';+import { getTopPagesCore } from '../../../overview/pages.service';+import type { IReportInput } from '../../../report/report.constants';+import { querySessionsCore } from '../../../session/session.service';+import type { ChatToolContext } from '../context';+import {+ type ChartToolOutput,+ chartModelSummary,+ chartToModelOutput,+ runReportConfig,+ summarizeChartData,+} from './charts';+import {+ resolveRange,+ revenueToUnits,+ toDateOnly,+ truncateRows,+} from './shared';++const TRAFFIC_COLUMNS = [+ 'referrer_name',+ 'referrer_type',+ 'referrer',+ 'utm_source',+ 'utm_medium',+ 'utm_campaign',+ 'country',+ 'region',+ 'city',+ 'device',+ 'browser',+ 'os',+] as const satisfies readonly TrafficColumn[];++const DEFAULT_BREAKDOWN_LIMIT = 25;+const MAX_BREAKDOWN_LIMIT = 200;+const DEFAULT_QUERY_LIMIT = 20;+const MAX_QUERY_LIMIT = 100;+const DEFAULT_ACTIVE_USER_DAYS = 30;+const MAX_ACTIVE_USER_DAYS = 365;+const DEFAULT_FUNNEL_WINDOW_HOURS = 24;+const MAX_FUNNEL_WINDOW_HOURS = 720;+const MAX_FUNNEL_STEPS = 10;+const MS_PER_DAY = 86_400_000;+const DATE_LENGTH = 10;+const RETENTION_WEEKS = 12;+const DAYS_PER_WEEK = 7;++const zOptionalRange = {+ startDate: z+ .string()+ .optional()+ .describe('YYYY-MM-DD, defaults to the current view.'),+ endDate: z+ .string()+ .optional()+ .describe('YYYY-MM-DD, defaults to the current view.'),+};++function daysAgo(days: number): string {+ return new Date(Date.now() - days * MS_PER_DAY)+ .toISOString()+ .slice(0, DATE_LENGTH);+}++type Segment = NonNullable<+ IReportInput['series'][number] extends infer S+ ? S extends { type: 'event'; segment?: infer Seg }+ ? Seg+ : never+ : never+>;++const HOURLY_MAX_DAYS = 2;+const DAILY_MAX_DAYS = 90;+const WEEKLY_MAX_DAYS = 366;++/** The interval the dashboard itself would pick for a window. */+function autoInterval(+ startDate: string,+ endDate: string+): 'hour' | 'day' | 'week' | 'month' {+ const days =+ (new Date(endDate).getTime() - new Date(startDate).getTime()) / MS_PER_DAY;+ if (days <= HOURLY_MAX_DAYS) {+ return 'hour';+ }+ if (days <= DAILY_MAX_DAYS) {+ return 'day';+ }+ if (days <= WEEKLY_MAX_DAYS) {+ return 'week';+ }+ return 'month';+}++/** Series ids are letters so two series on the same event stay distinct. */+const SERIES_IDS = 'ABCDEFGHIJ'.split('');++function eventSeries(+ id: string,+ name: string,+ segment: Segment,+ displayName = name+) {+ return {+ id,+ type: 'event' as const,+ name,+ displayName,+ segment,+ filters: [],+ };+}++export function analyticsTools(ctx: ChatToolContext) {+ const { deps, projectId } = ctx;++ return {+ get_overview: tool({+ description:+ 'Headline metrics for a period with the previous period for comparison: unique visitors, sessions, pageviews, bounce rate, session duration. Renders a visitors-and-sessions chart with the previous period overlaid. Start here for "how are we doing" questions; one call covers both periods.',+ inputSchema: z.object({+ ...zOptionalRange,+ interval: z+ .enum(['hour', 'day', 'week', 'month'])+ .optional()+ .describe('Defaults to what fits the range.'),+ }),+ execute: async ({ startDate, endDate, interval }) => {+ const range = resolveRange(ctx, { startDate, endDate });+ const bucket = interval ?? autoInterval(range.startDate, range.endDate);+ const overview = await getAnalyticsOverviewCore(deps, {+ projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ interval: bucket,+ filters: [],+ });+ const report: IReportInput & { name: string } = {+ projectId,+ name: 'Visitors and sessions',+ chartType: 'linear',+ interval: bucket,+ range: 'custom',+ startDate: range.startDate,+ endDate: range.endDate,+ metric: 'sum',+ previous: true,+ breakdowns: [],+ lineType: 'monotone',+ series: [+ eventSeries('A', 'screen_view', 'user', 'Unique visitors'),+ eventSeries('B', 'screen_view', 'session', 'Sessions'),+ ],+ };+ const output: ChartToolOutput = {+ title: report.name,+ report,+ summary: overview.summary as unknown as Record<string, unknown>,+ };+ return output;+ },+ toModelOutput: ({ output }) => chartToModelOutput(output),+ }),++ get_breakdown: tool({+ description:+ 'Top values of one dimension for a period: pages (`path`), referrers, UTM parameters, geography or device. Renders a bar chart; you get sessions, pageviews and revenue per value.',+ inputSchema: z.object({+ dimension: z.enum(['path', ...TRAFFIC_COLUMNS]),+ ...zOptionalRange,+ limit: z+ .number()+ .int()+ .min(1)+ .max(MAX_BREAKDOWN_LIMIT)+ .default(DEFAULT_BREAKDOWN_LIMIT),+ }),+ execute: async ({ dimension, startDate, endDate, limit }) => {+ const range = resolveRange(ctx, { startDate, endDate });+ const rows =+ dimension === 'path'+ ? await getTopPagesCore(deps, {+ projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ limit,+ })+ : await getTrafficBreakdownCore(deps, {+ projectId,+ startDate: range.startDate,+ endDate: range.endDate,+ column: dimension,+ });+ const label =+ dimension === 'path' ? 'pages' : dimension.replace(/_/g, ' ');+ const report: IReportInput & { name: string } = {+ projectId,+ name: `Top ${label}`,+ chartType: 'bar',+ interval: autoInterval(range.startDate, range.endDate),+ range: 'custom',+ startDate: range.startDate,+ endDate: range.endDate,+ metric: 'sum',+ previous: false,+ limit,+ breakdowns: [{ id: '1', name: dimension }],+ series: [+ dimension === 'path'+ ? eventSeries('A', 'screen_view', 'event', 'Pageviews')+ : eventSeries('A', 'screen_view', 'session', 'Sessions'),+ ],+ };+ const output: ChartToolOutput = {+ title: report.name,+ report,+ summary: {+ dimension,+ ...truncateRows(+ revenueToUnits(rows as { revenue?: number }[]),+ limit+ ),+ },+ };+ return output;+ },+ toModelOutput: ({ output }) => chartToModelOutput(output),+ }),++ get_traffic_attribution: tool({+ description:+ 'Sessions, pageviews and revenue grouped by one or two traffic dimensions at once (utm_source and utm_campaign, referrer_name and country, ...). Reads the sessions table, which carries UTM parameters, referrer and revenue together, so this is the tool for "which campaign brings the most revenue". Returns a table; charts cannot express this combination.',+ inputSchema: z.object({+ dimensions: z+ .array(z.enum(TRAFFIC_COLUMNS))+ .min(1)+ .max(2)+ .describe('One or two session columns to group by.'),+ ...zOptionalRange,+ sortBy: z+ .enum(['revenue', 'sessions', 'pageviews'])+ .default('sessions'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(MAX_BREAKDOWN_LIMIT)+ .default(DEFAULT_BREAKDOWN_LIMIT),+ }),+ execute: async ({ dimensions, startDate, endDate, sortBy, limit }) => {+ const range = resolveRange(ctx, { startDate, endDate });+ const groupBy = sql.join(+ dimensions.map((dimension) => sql.id(dimension, TRAFFIC_COLUMNS)),+ ', '+ );+ const rows = await chQuery<Record<string, string | number>>(+ deps,+ sql`SELECT ${groupBy},+ sum(sign) AS sessions,+ sum(screen_view_count * sign) AS pageviews,+ sum(revenue * sign) / 100 AS revenue+ FROM sessions+ WHERE project_id = ${sql.string(projectId)}+ AND created_at >= toDateTime(${sql.string(toDateOnly(range.startDate))})+ AND created_at < toDateTime(${sql.string(toDateOnly(range.endDate))}) + INTERVAL 1 DAY+ GROUP BY ${groupBy}+ HAVING sessions > 0+ ORDER BY ${sql.id(sortBy, ['revenue', 'sessions', 'pageviews'])} DESC+ LIMIT ${sql.uint64(limit)}`+ );+ return {+ dimensions,+ ...range,+ ...truncateRows(+ rows.map((row) => ({+ ...row,+ sessions: Number(row.sessions),+ pageviews: Number(row.pageviews),+ revenue: Number(row.revenue),+ })),+ limit+ ),+ };+ },+ }),++ query_events: tool({+ description:+ 'Raw events matching filters, newest first. For "show me the last X events", "did we get any Y events", or inspecting the properties of real events. Aggregates belong in create_chart.',+ inputSchema: z.object({+ ...zOptionalRange,+ eventNames: z.array(z.string()).optional(),+ path: z.string().optional(),+ country: z.string().optional(),+ city: z.string().optional(),+ device: z.string().optional(),+ browser: z.string().optional(),+ os: z.string().optional(),+ referrer: z.string().optional(),+ referrerName: z.string().optional(),+ referrerType: z.string().optional(),+ profileId: z.string().optional(),+ sessionId: z.string().optional(),+ properties: z+ .record(z.string(), z.string())+ .optional()+ .describe('Exact matches on custom properties, keyed by bare key.'),+ limit: z+ .number()+ .int()+ .min(1)+ .max(MAX_QUERY_LIMIT)+ .default(DEFAULT_QUERY_LIMIT),+ }),+ execute: async (input) => {+ const range = resolveRange(ctx, input);+ const rows = await queryEventsCore(deps, {+ projectId,+ ...input,+ startDate: range.startDate,+ endDate: range.endDate,+ });+ return truncateRows(revenueToUnits(rows), input.limit);+ },+ }),++ query_sessions: tool({+ description:+ 'Raw sessions matching filters, newest first: duration, pages, entry and exit, referrer, device, country.',+ inputSchema: z.object({+ ...zOptionalRange,+ country: z.string().optional(),+ city: z.string().optional(),+ device: z.string().optional(),+ browser: z.string().optional(),+ os: z.string().optional(),+ referrer: z.string().optional(),+ referrerName: z.string().optional(),+ referrerType: z.string().optional(),+ profileId: z.string().optional(),+ limit: z+ .number()+ .int()+ .min(1)+ .max(MAX_QUERY_LIMIT)+ .default(DEFAULT_QUERY_LIMIT),+ }),+ execute: async (input) => {+ const range = resolveRange(ctx, input);+ const rows = await querySessionsCore(deps, {+ projectId,+ ...input,+ startDate: range.startDate,+ endDate: range.endDate,+ });+ return truncateRows(revenueToUnits(rows), input.limit);+ },+ }),++ get_active_users: tool({+ description:+ 'Daily, weekly or monthly active users: the current rolling count (`windowDays` 1, 7 or 30) plus a chart of daily unique users over the last `days`.',+ inputSchema: z.object({+ windowDays: z.number().int().min(1).max(90).default(1),+ days: z+ .number()+ .int()+ .min(1)+ .max(MAX_ACTIVE_USER_DAYS)+ .default(DEFAULT_ACTIVE_USER_DAYS),+ }),+ execute: async ({ windowDays, days }) => {+ const label =+ windowDays === 1+ ? 'Daily'+ : windowDays === DAYS_PER_WEEK+ ? 'Weekly'+ : windowDays === DEFAULT_ACTIVE_USER_DAYS+ ? 'Monthly'+ : `${windowDays}-day`;+ const report: IReportInput & { name: string } = {+ projectId,+ name: `Daily active users, last ${days} days`,+ chartType: 'linear',+ interval: 'day',+ range: 'custom',+ startDate: daysAgo(days - 1),+ endDate: daysAgo(0),+ metric: 'sum',+ previous: false,+ breakdowns: [],+ lineType: 'monotone',+ series: [eventSeries('A', 'screen_view', 'user', 'Active users')],+ };+ const [data, current] = await Promise.all([+ runReportConfig(ctx, report),+ getRollingActiveUsersCore(deps, { projectId, days: windowDays }),+ ]);+ const output: ChartToolOutput & { current: unknown; label: string } = {+ title: report.name,+ report,+ summary: summarizeChartData(data),+ current,+ label: `${label} active users`,+ };+ return output;+ },+ toModelOutput: ({ output }) => ({+ type: 'text' as const,+ value: JSON.stringify({+ ...chartModelSummary(output),+ current: output.current,+ label: output.label,+ }),+ }),+ }),++ get_funnel: tool({+ description:+ 'Conversion through ordered steps: users per step, conversion and drop-off, drawn as a funnel chart. Verify step event names with describe_data first.',+ inputSchema: z.object({+ title: z.string().min(1).describe('3 to 8 words.'),+ steps: z.array(z.string()).min(2).max(MAX_FUNNEL_STEPS),+ ...zOptionalRange,+ windowHours: z+ .number()+ .int()+ .min(1)+ .max(MAX_FUNNEL_WINDOW_HOURS)+ .default(DEFAULT_FUNNEL_WINDOW_HOURS),+ groupBy: z.enum(['session_id', 'profile_id']).default('session_id'),+ }),+ execute: async ({+ title,+ steps,+ startDate,+ endDate,+ windowHours,+ groupBy,+ }) => {+ const range = resolveRange(ctx, { startDate, endDate });+ const report: IReportInput & { name: string } = {+ projectId,+ name: title,+ chartType: 'funnel',+ interval: 'day',+ range: 'custom',+ startDate: range.startDate,+ endDate: range.endDate,+ metric: 'sum',+ previous: false,+ breakdowns: [],+ options: {+ type: 'funnel',+ funnelGroup: groupBy,+ funnelWindow: windowHours * 3600,+ },+ series: steps.map((name, index) =>+ eventSeries(SERIES_IDS[index] ?? String(index), name, 'event')+ ),+ };+ const numbers = await getFunnelCore(deps, {+ projectId,+ steps,+ startDate: range.startDate,+ endDate: range.endDate,+ windowHours,+ groupBy,+ });+ const output: ChartToolOutput = {+ title,+ report,+ summary: numbers as unknown as Record<string, unknown>,+ };+ return output;+ },+ toModelOutput: ({ output }) => chartToModelOutput(output),+ }),++ get_retention: tool({+ description:+ 'Weekly retention cohorts for the last 12 weeks: how many users who were first seen in a week came back in later weeks. Drawn as a retention chart.',+ inputSchema: z.object({}),+ execute: async () => {+ const cohorts = await getRetentionCohortCore(deps, projectId);+ const report: IReportInput & { name: string } = {+ projectId,+ name: 'Weekly retention',+ chartType: 'retention',+ interval: 'week',+ range: 'custom',+ startDate: daysAgo(RETENTION_WEEKS * DAYS_PER_WEEK),+ endDate: daysAgo(0),+ metric: 'sum',+ previous: false,+ breakdowns: [],+ series: [eventSeries('A', 'screen_view', 'user', 'Active users')],+ };+ const output: ChartToolOutput = {+ title: report.name,+ report,+ summary: { cohorts } as Record<string, unknown>,+ };+ return output;+ },+ toModelOutput: ({ output }) => chartToModelOutput(output),+ }),++ get_user_flow: tool({+ description:+ 'Where users go after (or before) an event: the most common next steps, as nodes and links, drawn as a sankey chart.',+ inputSchema: z.object({+ startEvent: z.string(),+ endEvent: z+ .string()+ .optional()+ .describe('Required for mode `between`.'),+ mode: z.enum(['after', 'before', 'between']).default('after'),+ steps: z.number().int().min(2).max(10).default(5),+ ...zOptionalRange,+ }),+ execute: async ({+ startEvent,+ endEvent,+ mode,+ steps,+ startDate,+ endDate,+ }) => {+ const range = resolveRange(ctx, { startDate, endDate });+ const flow = await getUserFlowCore(deps, {+ projectId,+ startEvent,+ endEvent,+ mode,+ steps,+ startDate: range.startDate,+ endDate: range.endDate,+ });+ const series = [eventSeries('A', startEvent, 'event')];+ if (endEvent) {+ series.push(eventSeries('B', endEvent, 'event'));+ }+ const report: IReportInput & { name: string } = {+ projectId,+ name: `User flow ${mode} ${startEvent}`,+ chartType: 'sankey',+ interval: 'day',+ range: 'custom',+ startDate: range.startDate,+ endDate: range.endDate,+ metric: 'sum',+ previous: false,+ breakdowns: [],+ options: { type: 'sankey', mode, steps, exclude: [] },+ series,+ };+ const output: ChartToolOutput = {+ title: report.name,+ report,+ summary: flow as unknown as Record<string, unknown>,+ };+ return output;+ },+ toModelOutput: ({ output }) => chartToModelOutput(output),+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/base.ts b/packages/core/src/modules/assistant/src/tools/base.tsdeleted file mode 100644index d0dc46aee..000000000--- a/packages/core/src/modules/assistant/src/tools/base.ts+++ /dev/null@@ -1,966 +0,0 @@-import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import { getFunnelCore } from '../../../chart/funnel.service';-import {- getRetentionCohortCore,- getRollingActiveUsersCore,-} from '../../../chart/retention.service';-import { getUserFlowCore } from '../../../chart/sankey.service';-import { listDashboardsCore } from '../../../dashboard/dashboard.service';-import {- getEventPropertyValuesCore,- listEventNamesCore,- listEventPropertiesCore,- queryEventsCore,-} from '../../../event/event.service';-import {- getAnalyticsOverviewCore,- getTrafficBreakdownCore,-} from '../../../overview/overview.service';-import { getTopPagesCore } from '../../../overview/pages.service';-import { findProfilesCore } from '../../../profile/profile.service';-import {- chartTypes,- lineTypes,- operators,- zReportInput,-} from '../../../report/report.constants';-import { listReportsCore } from '../../../report/report.service';-import { querySessionsCore } from '../../../session/session.service';-import { runReport, runReportFromConfig } from '../report-runner';-import {- chatTool,- compactEventProperties,- dashboardUrl,- pageContextFilters,- resolveDateRange,- truncateRows,-} from './helpers';--/** Series label for `get_rolling_active_users`' chart — always daily uniques. */-const DAILY_ACTIVE_USERS_SERIES_LABEL = 'Daily active users';--function objectToZodEnums<K extends string>(- obj: Record<K, unknown>-): [K, ...K[]] {- const [firstKey, ...otherKeys] = Object.keys(obj) as K[];- return [firstKey!, ...otherKeys];-}--export const listEventNames = (deps: ServiceDeps) =>- chatTool(- {- name: 'list_event_names',- description:- 'Get the top 50 event names tracked in this project. Call this BEFORE referencing event names in generate_report or other tools — never guess at event names.',- schema: z.object({}),- },- async (_input, context) => {- const names = await listEventNamesCore(deps, context.projectId);- return { event_names: names };- }- );--export const listEventProperties = (deps: ServiceDeps) =>- chatTool(- {- name: 'list_event_properties',- description:- 'List fields available for filtering or breaking down events. Returns TWO buckets:\n\n- `columns`: top-level event columns (path, referrer, country, device, browser, os, etc.). Apply to every event. Use the bare name in filters/breakdowns (e.g. `{ name: "path", operator: "endsWith", value: ["/cohorts"] }`).\n- `properties`: custom keys from the event\'s JSON `properties` map. Use prefixed as `properties.<key>` in filters/breakdowns (e.g. `properties.plan`).\n\nCall this before using any field as a filter or breakdown in generate_report. NOTE: dotted sub-keys inside `properties` are rolled up to their root — e.g. all `__query.foo`, `__query.bar`, … are represented by a single `__query` entry, ordered by how many sub-keys roll up under them (most prominent first). To filter on a specific sub-key like `properties.__query.utm_source`, use that exact full key — the rollup is purely a discovery optimization.',- schema: z.object({- eventName: z- .string()- .optional()- .describe(- 'Optional — filter to one event. Omit to list properties across all events.'- ),- }),- },- async ({ eventName }, context) => {- const raw = await listEventPropertiesCore(deps, {- projectId: context.projectId,- eventName,- });- return compactEventProperties(raw, { eventName });- }- );--export const getEventPropertyValues = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_event_property_values',- description:- 'List distinct values for a specific event property. Useful when the user wants to filter on something concrete like "country = SE".',- schema: z.object({- eventName: z.string().describe('The event name (e.g. screen_view)'),- propertyKey: z- .string()- .describe('The property key (e.g. path, country)'),- }),- },- async ({ eventName, propertyKey }, context) =>- getEventPropertyValuesCore(deps, {- projectId: context.projectId,- eventName,- propertyKey,- })- );--export const listDashboards = (deps: ServiceDeps) =>- chatTool(- {- name: 'list_dashboards',- description:- 'List all dashboards in this project. Each dashboard groups a set of reports the user has built. Use this to discover what already exists before building anything new.',- schema: z.object({}),- },- async (_input, context) => {- const dashboards = await listDashboardsCore(deps, {- projectId: context.projectId,- organizationId: context.organizationId,- });- return dashboards.map((d) => ({- ...d,- dashboard_url: dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- `/dashboards/${d.id}`- ),- }));- }- );--export const listReports = (deps: ServiceDeps) =>- chatTool(- {- name: 'list_reports',- description:- 'List the reports inside a dashboard. Returns chart type, range, interval, and event series for each. Use this with get_report_data to fetch real numbers.',- schema: z.object({- dashboardId: z- .string()- .describe('The dashboard ID (from list_dashboards)'),- }),- },- async ({ dashboardId }, context) =>- listReportsCore(deps, {- projectId: context.projectId,- dashboardId,- organizationId: context.organizationId,- })- );--export const getReportData = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_report_data',- description:- 'Execute a saved report by ID and return its data. Works for every chart type (linear, bar, area, pie, metric, funnel, retention, etc.). PREFER this over generate_report when the user asks about something a saved report likely already covers.',- schema: z.object({- reportId: z.string().describe('The report ID (from list_reports)'),- }),- },- async ({ reportId }, context) =>- runReport(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- reportId,- })- );--export const generateReport = (deps: ServiceDeps) =>- chatTool(- {- name: 'generate_report',- description: [- 'Generate an ad-hoc chart from a report config. Use only when no saved report fits. Always call list_event_names first to verify event names exist; call list_event_properties if you need a breakdown property. ALWAYS supply a concise `title` (3-8 words) describing what the chart shows.',- '',- 'Series are ordered A, B, C, … (based on array index). Use the letter id from a `formula` series like "A / B * 100" for ratios or conversions.',- '',- 'Examples:',- '- **Unique users per day**: one event series with `segment: "user"` + `chartType: "linear"`.',- '- **Revenue per day**: one event series with `segment: "property_sum"` + `property: "revenue"`.',- '- **Conversion rate over time**: two event series (A = completed, B = started) + a `formula` series `"A / B * 100"` with all three visible, or set `hideSeries: ["A","B"]` to show only the rate.',- '- **Period-over-period**: set `previous: true` to overlay the prior period of equal length.',- ].join('\n'),- schema: z.object({- chartType: z- .enum(objectToZodEnums(chartTypes))- .describe(- 'Chart type. See the decision table in the system prompt — pick `linear`/`area` for trends, `bar`/`pie`/`map` for breakdowns, `metric` for a single number, `funnel`/`conversion`/`sankey` for flows, `retention` for cohorts, `histogram` for numeric distributions.'- ),- interval: z- .enum(['minute', 'hour', 'day', 'week', 'month'])- .default('day'),- startDate: z.string().describe('ISO date YYYY-MM-DD'),- endDate: z.string().describe('ISO date YYYY-MM-DD'),- series: z- .array(- z.union([- z.object({- type: z.literal('event'),- name: z- .string()- .describe('Event name — verify with list_event_names'),- displayName: z.string().optional(),- segment: z- .enum([- 'event',- 'user',- 'session',- 'group',- 'user_average',- 'one_event_per_user',- 'property_sum',- 'property_average',- 'property_max',- 'property_min',- ])- .default('event')- .optional()- .describe(- [- 'How to segment/aggregate the event:',- '- `event` — every event firing (default, "all events")',- '- `user` — unique users (e.g. for DAU/MAU)',- '- `session` — unique sessions',- '- `group` — unique groups/accounts',- '- `user_average` — average events per user',- '- `one_event_per_user` — count users who did it at least once',- '- `property_sum` / `property_average` / `property_max` / `property_min` — aggregate a numeric property from the event (requires `property`)',- ].join('\n')- ),- property: z- .string()- .optional()- .describe(- 'Numeric property on the event to aggregate. Required when segment is `property_sum`/`average`/`max`/`min`. Example: `revenue`, `duration`, `score`.'- ),- filters: z- .array(- z.object({- name: z- .string()- .describe(- 'Field to filter on — verify with list_event_properties. Use the bare column name for top-level columns (e.g. `path`, `country`, `device`) or `properties.<key>` for custom JSON properties (e.g. `properties.plan`).'- ),- operator: z- .enum(objectToZodEnums(operators))- .describe(- 'One of: is, isNot, contains, doesNotContain, startsWith, endsWith, regex, isNull, isNotNull, gt, lt, gte, lte. `is` is the default for equality (NOT `equals` / `eq` / `==`).'- ),- value: z- .array(- z.union([- z.string(),- z.number(),- z.boolean(),- z.null(),- ])- )- .describe(- 'Values to match. Use [] with isNull/isNotNull.'- ),- })- )- .default([])- .optional(),- }),- z.object({- type: z.literal('formula'),- formula: z- .string()- .describe(- 'Expression referencing other series by letter id. Examples: `A / B * 100` (conversion rate), `A + B` (union total), `A - B` (difference). Earlier series are A, B, C, …'- ),- displayName: z.string().optional(),- hideSeries: z- .array(z.string())- .optional()- .describe(- 'Letter ids (e.g. ["A", "B"]) of series used by the formula that should be hidden from the chart — useful when you only want to display the computed ratio.'- ),- }),- ])- )- .min(1)- .describe(- 'At least one series. Mix event series and formula series to compute ratios.'- ),- breakdowns: z- .array(- z.object({- name: z.string().describe('Property key to group by'),- })- )- .default([])- .optional(),- // No `.default()` here on purpose: it would make an omitted metric- // indistinguishable from an explicit `sum`, and the fallback depends on- // the chart type (see below).- metric: z- .enum(['sum', 'count', 'average', 'min', 'max'])- .optional()- .describe(- 'How a series is aggregated for display. Only the metric and map chart types read this; `count` is unique profiles. Omit it unless the user asked for a specific aggregation — metric cards then default to unique profiles.'- ),- previous: z- .boolean()- .optional()- .describe(- 'Overlay the same-length previous period for comparison. Great for "vs last week" / "vs last month" questions.'- ),- lineType: z- .enum(objectToZodEnums(lineTypes))- .optional()- .describe(- 'Line style for linear/area charts. Default to `monotone` unless you have a reason not to.'- ),- limit: z- .number()- .min(1)- .max(500)- .optional()- .describe(- 'Top-N limit for bar/pie/sankey. Example: "top 10 pages" → limit: 10.'- ),- unit: z- .string()- .optional()- .describe('Y-axis unit suffix, e.g. `%`, `$`, `ms`, `users`.'),- funnelGroup: z- .enum(['session', 'profile'])- .optional()- .describe(- 'Only for `chartType: "funnel"`. Whether each funnel step counts by unique session or unique profile. Default is profile.'- ),- title: z- .string()- .optional()- .describe(- 'Short, descriptive card title (3-8 words) — e.g. "Signups per day, last 7 days". Always provide one.'- ),- }),- },- async (input, context) => {- // biome-ignore lint/suspicious/noExplicitAny: union discrimination between event/formula series is easier to do explicitly- const series = (input.series as any[]).map((s: any, i: number) => {- const id = ALPHABET_IDS[i] ?? String(i + 1);- if (s?.type === 'formula') {- return {- id,- type: 'formula' as const,- formula: s.formula,- displayName: s.displayName,- ...(Array.isArray(s.hideSeries)- ? { hideSeries: s.hideSeries }- : {}),- };- }- return {- id,- type: 'event' as const,- name: s.name,- displayName: s.displayName ?? s.name,- segment: s.segment ?? 'event',- ...(s.property ? { property: s.property } : {}),- filters: s.filters ?? [],- };- });-- const options =- input.chartType === 'funnel' && input.funnelGroup- ? { type: 'funnel' as const, funnelGroup: input.funnelGroup }- : undefined;-- const config = {- projectId: context.projectId,- chartType: input.chartType,- interval: input.interval,- startDate: input.startDate,- endDate: input.endDate,- series,- breakdowns: (input.breakdowns ?? []).map(- (b: { name: string }, i: number) => ({- id: String(i + 1),- name: b.name,- })- ),- range: 'custom' as const,- // A metric card has always shown the total unique count, so an- // unspecified metric must stay `count` there — `sum` would silently turn- // "1.2k users" into "45k events".- metric:- input.metric ?? (input.chartType === 'metric' ? 'count' : 'sum'),- previous: input.previous ?? false,- ...(input.lineType ? { lineType: input.lineType } : {}),- ...(input.limit ? { limit: input.limit } : {}),- ...(input.unit ? { unit: input.unit } : {}),- ...(options ? { options } : {}),- };-- // Pre-validate so an invalid shape is returned to the model as a structured- // error it can self-correct from, instead of producing a broken chart.- const parsed = zReportInput.safeParse(config);- if (!parsed.success) {- return {- error:- 'Invalid report config — fix the issues and call generate_report again.',- issues: parsed.error.issues.map((i) => ({- path: i.path.join('.'),- message: i.message,- })),- };- }-- const chart = await runReportFromConfig(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- config: parsed.data as Parameters<- typeof runReportFromConfig- >[1]['config'],- });- return {- // The frontend derives a title when this is empty.- ...(input.title?.trim() ? { name: input.title.trim() } : {}),- ...chart,- };- }- );--// Letter ids for series. Must match the chart engine's expectation-// that series are referenced by A, B, C, … in formula expressions.-const ALPHABET_IDS = [- 'A',- 'B',- 'C',- 'D',- 'E',- 'F',- 'G',- 'H',- 'I',- 'J',- 'K',- 'L',- 'M',- 'N',- 'O',- 'P',- 'Q',- 'R',- 'S',- 'T',- 'U',- 'V',- 'W',- 'X',- 'Y',- 'Z',-] as const;--export const getAnalyticsOverview = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_analytics_overview',- description:- "Top-level metrics: unique visitors, total pageviews, sessions, bounce rate, avg session duration, plus an optional time series. Defaults to the user's current date range.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- interval: z- .enum(['hour', 'day', 'week', 'month'])- .default('day')- .optional(),- }),- },- async ({ startDate, endDate, interval }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- return getAnalyticsOverviewCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- interval: interval ?? 'day',- filters: pageContextFilters(pageContext),- });- }- );--export const getTopPages = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_top_pages',- description:- "Top pages ranked by visitors / pageviews. Returns path, sessions, pageviews, bounce rate, avg duration. Respects the page's active property filters.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async ({ startDate, endDate, limit }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- const pages = await getTopPagesCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- limit: limit ?? 20,- filters: pageContextFilters(pageContext),- });- return truncateRows(pages, 50);- }- );--export const getTopReferrers = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_top_referrers',- description:- "Traffic source breakdown — by referrer name, type, or UTM source/medium/campaign. Respects the page's active property filters.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- breakdown: z- .enum(['referrer_name', 'referrer_type', 'referrer'])- .default('referrer_name')- .optional(),- }),- },- async ({ startDate, endDate, breakdown }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- const rows = await getTrafficBreakdownCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: (breakdown ?? 'referrer_name') as- | 'referrer_name'- | 'referrer_type'- | 'referrer',- filters: pageContextFilters(pageContext),- });- return truncateRows(rows, 50);- }- );--export const getCountryBreakdown = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_country_breakdown',- description:- "Visitor breakdown by country / region / city. Returns sessions and percentage of total. Respects the page's active property filters.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- breakdown: z- .enum(['country', 'region', 'city'])- .default('country')- .optional(),- }),- },- async ({ startDate, endDate, breakdown }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- const rows = await getTrafficBreakdownCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: (breakdown ?? 'country') as 'country' | 'region' | 'city',- filters: pageContextFilters(pageContext),- });- return truncateRows(rows, 100);- }- );--export const getDeviceBreakdown = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_device_breakdown',- description:- "Visitor breakdown by device / browser / OS. Respects the page's active property filters.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- breakdown: z- .enum(['device', 'browser', 'os'])- .default('device')- .optional(),- }),- },- async ({ startDate, endDate, breakdown }, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- const rows = await getTrafficBreakdownCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- column: (breakdown ?? 'device') as 'device' | 'browser' | 'os',- filters: pageContextFilters(pageContext),- });- return truncateRows(rows, 50);- }- );--export const getRollingActiveUsers = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_rolling_active_users',- description:- 'Rolling active users (DAU/WAU/MAU). Returns TWO things that answer different questions: `summary` is the rolling active-user count over `windowDays` (1 = DAU, 7 = WAU, 30 = MAU — quote this for "how many MAU do we have?"), and the chart is a DAILY unique-users trend over the last `days` — it is NOT a rolling-window series, so do not describe the line as WAU/MAU. ALWAYS supply a concise `title` (3-8 words) that describes what the chart shows.',- schema: z.object({- /**- * The rolling window. 1 = DAU (default), 7 = WAU, 30 = MAU.- */- windowDays: z.number().min(1).max(90).default(1).optional(),- /** Number of days to chart. Defaults to 30. */- days: z.number().min(1).max(365).default(30).optional(),- title: z- .string()- .optional()- .describe(- 'Short, descriptive card title (3-8 words) — e.g. "Monthly active users trend". Always provide one.'- ),- }),- },- async ({ windowDays, days, title }, context) => {- const window = windowDays ?? 1;- const range = days ?? 30;-- // Unique users per day: a user-segment on `screen_view` with a linear chart.- // The chart is daily uniques whatever `windowDays` is, since the engine has- // no rolling-window series type; `windowDays` only shapes the `summary`- // below, so the series is labelled for what it is.- const endDate = new Date().toISOString().slice(0, 10);- const startDate = new Date(Date.now() - (range - 1) * 86_400_000)- .toISOString()- .slice(0, 10);- const summaryLabel =- window === 1- ? 'DAU'- : window === 7- ? 'WAU'- : window === 30- ? 'MAU'- : `${window}-day active users`;-- const config = {- chartType: 'linear' as const,- interval: 'day' as const,- startDate,- endDate,- range: 'custom' as const,- metric: 'sum' as const,- previous: false,- breakdowns: [],- series: [- {- id: '1',- type: 'event' as const,- name: 'screen_view',- displayName: DAILY_ACTIVE_USERS_SERIES_LABEL,- segment: 'user' as const,- filters: [],- },- ],- };-- const chart = await runReportFromConfig(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- config: config as Parameters<typeof runReportFromConfig>[1]['config'],- });-- const summary = await getRollingActiveUsersCore(deps, {- projectId: context.projectId,- days: window,- });-- return {- // Names the CHART, not the summary: the two measure different windows.- name:- title?.trim() ||- `${DAILY_ACTIVE_USERS_SERIES_LABEL} — last ${range} days`,- label: summaryLabel,- window,- summary,- ...chart,- };- }- );--export const getFunnel = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_funnel',- description:- 'Multi-step conversion funnel. Returns BOTH a renderable funnel chart AND the numeric breakdown (users per step, conversion rates, drop-off). The UI draws an actual funnel chart. Provide an ordered list of event names — verify with list_event_names first. ALWAYS supply a concise `title` (3-8 words) describing what the funnel measures.',- schema: z.object({- steps: z- .array(z.string())- .min(2)- .max(10)- .describe('Ordered event names. Verify with list_event_names first.'),- startDate: z.string().optional(),- endDate: z.string().optional(),- windowHours: z.number().min(1).max(720).default(24).optional(),- groupBy: z- .enum(['session_id', 'profile_id'])- .default('session_id')- .optional(),- title: z- .string()- .optional()- .describe(- 'Short, descriptive card title (3-8 words) — e.g. "Cart to checkout conversion" or "Signup to paid funnel". Always provide one.'- ),- }),- },- async (- { steps, startDate, endDate, windowHours, groupBy, title },- context- ) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });-- const numbers = await getFunnelCore(deps, {- projectId: context.projectId,- steps,- startDate: range.startDate,- endDate: range.endDate,- windowHours,- groupBy,- });-- // Same shape `generate_report` returns, so `ChatReportResult` draws a funnel.- const chartConfig = {- chartType: 'funnel' as const,- interval: 'day' as const,- startDate: range.startDate,- endDate: range.endDate,- range: 'custom' as const,- metric: 'sum' as const,- previous: false,- breakdowns: [],- funnelGroup: groupBy ?? 'session_id',- funnelWindowSeconds: (windowHours ?? 24) * 3600,- series: (steps as string[]).map((name: string, i: number) => ({- id: String(i + 1),- type: 'event' as const,- name,- displayName: name,- segment: 'event' as const,- filters: [],- })),- };-- const chart = await runReportFromConfig(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- config: chartConfig as Parameters<- typeof runReportFromConfig- >[1]['config'],- });-- return {- name: title?.trim() || `Funnel: ${steps.join(' → ')}`,- numbers,- ...chart,- };- }- );--export const getRetentionCohort = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_retention_cohort',- description:- 'Weekly active-user retention cohort for the last 12 weeks. Each row is a cohort (the week users were first seen) with cohort size (sum), retained user counts (values) and retained share (percentages) for subsequent weeks; a leading weighted-average row summarises all cohorts.',- schema: z.object({}),- },- async (_input, context) => getRetentionCohortCore(deps, context.projectId)- );--export const getUserFlow = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_user_flow',- description:- 'Sankey-style user navigation flow from a starting event. Returns nodes + links suitable for visualizing common paths.',- schema: z.object({- startEvent: z.string().describe('Event name where the flow starts'),- endEvent: z.string().optional().describe('Required when mode=between'),- mode: z.enum(['after', 'before', 'between']).default('after'),- steps: z.number().min(2).max(10).default(5).optional(),- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async (- { startEvent, endEvent, mode, steps, startDate, endDate },- context- ) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: startDate ?? pageContext?.filters?.startDate,- endDate: endDate ?? pageContext?.filters?.endDate,- });- return getUserFlowCore(deps, {- projectId: context.projectId,- startEvent,- endEvent,- mode,- steps,- startDate: range.startDate,- endDate: range.endDate,- });- }- );--export const queryEvents = (deps: ServiceDeps) =>- chatTool(- {- name: 'query_events',- description:- "Free-form query over raw events with filters (path, country, device, browser, OS, referrer, custom properties, profileId, eventNames). Use this when aggregate tools don't cover the question.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- eventNames: z.array(z.string()).optional(),- path: z.string().optional(),- country: z.string().optional(),- city: z.string().optional(),- device: z.string().optional(),- browser: z.string().optional(),- os: z.string().optional(),- referrer: z.string().optional(),- referrerName: z.string().optional(),- referrerType: z.string().optional(),- profileId: z.string().optional(),- properties: z.record(z.string(), z.string()).optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async (input, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: input.startDate ?? pageContext?.filters?.startDate,- endDate: input.endDate ?? pageContext?.filters?.endDate,- });- const rows = await queryEventsCore(deps, {- projectId: context.projectId,- ...input,- startDate: range.startDate,- endDate: range.endDate,- limit: input.limit ?? 20,- });- return truncateRows(rows, 100);- }- );--export const querySessions = (deps: ServiceDeps) =>- chatTool(- {- name: 'query_sessions',- description:- 'Free-form query over raw sessions with filters (country, device, browser, OS, referrer, profileId).',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- country: z.string().optional(),- city: z.string().optional(),- device: z.string().optional(),- browser: z.string().optional(),- os: z.string().optional(),- referrer: z.string().optional(),- referrerName: z.string().optional(),- referrerType: z.string().optional(),- profileId: z.string().optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async (input, context) => {- const pageContext = context.pageContext;- const range = resolveDateRange({- ...pageContext?.filters,- startDate: input.startDate ?? pageContext?.filters?.startDate,- endDate: input.endDate ?? pageContext?.filters?.endDate,- });- const rows = await querySessionsCore(deps, {- projectId: context.projectId,- ...input,- startDate: range.startDate,- endDate: range.endDate,- limit: input.limit ?? 20,- });- return truncateRows(rows, 100);- }- );--export const findProfiles = (deps: ServiceDeps) =>- chatTool(- {- name: 'find_profiles',- description:- 'Search for user profiles by name, email, country, device, inactivity, minimum sessions, or having performed a specific event.',- schema: z.object({- name: z.string().optional(),- email: z.string().optional(),- country: z.string().optional(),- city: z.string().optional(),- device: z.string().optional(),- browser: z.string().optional(),- inactiveDays: z.number().min(1).optional(),- minSessions: z.number().min(1).optional(),- performedEvent: z.string().optional(),- sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async (input, context) => {- const profiles = await findProfilesCore(deps, {- projectId: context.projectId,- ...input,- });- return truncateRows(- profiles.map((p) => ({- ...p,- dashboard_url: dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- `/profiles/${p.id}`- ),- })),- 100- );- }- );diff --git a/packages/core/src/modules/assistant/src/tools/billing.ts b/packages/core/src/modules/assistant/src/tools/billing.tsnew file mode 100644index 000000000..8eff48df6--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/billing.ts@@ -0,0 +1,244 @@+import { FREE_PRODUCT_IDS } from '@openpanel/payments';+import { getSubscriptionState } from '@openpanel/payments/subscription-state';+import { getSubscriptionStateMeta } from '@openpanel/payments/subscription-state-meta';+import { tool } from 'ai';+import { z } from 'zod';+import { getCurrentSubscriptionProduct } from '../../../subscription/subscription.service';+import {+ CHAT_MESSAGES_PER_DAY,+ type ChatTier,+} from '../../assistant.constants';+import type { ChatToolContext } from '../context';+import { readChatUsageToday, resolveChatTier } from '../limits';++const CENTS_PER_UNIT = 100;+const PERCENT = 100;++interface PriceLike {+ priceAmount?: number;+ priceCurrency?: string;+}++export interface BillingOutput {+ selfHosted: boolean;+ organization: string;+ state: string;+ statusLine: string | null;+ plan: {+ name: string | null;+ free: boolean;+ price: number | null;+ currency: string | null;+ interval: string | null;+ eventsLimit: number | null;+ };+ usage: {+ eventsThisPeriod: number;+ eventsLimit: number | null;+ percentUsed: number | null;+ periodStart: string | null;+ periodEnd: string | null;+ limitExceededAt: string | null;+ };+ schedule: {+ canceledAt: string | null;+ pauseAtPeriodEnd: boolean;+ resumesAt: string | null;+ };+ assistant: {+ tier: ChatTier;+ messagesPerDay: number | null;+ messagesToday: number;+ };+ billingUrl: string;+}++const iso = (date: Date | null | undefined) => date?.toISOString() ?? null;++interface PlanOption {+ productId: string;+ productPriceId: string | null;+ name: string;+ eventsLimit: number | null;+ price: number | null;+ currency: string | null;+ interval: string | null;+ current: boolean;+ unavailable: string | null;+}++export function billingTools(ctx: ChatToolContext) {+ const { deps, organizationId, actions } = ctx;+ const billingUrl = `${ctx.config.dashboardUrl.replace(/\/$/, '')}/${organizationId}/settings`;++ return {+ get_billing: tool({+ description:+ "The workspace's plan and usage: which plan, its price and event limit, events used this billing period, renewal or trial end date, whether it is canceling or paused, and the daily AI message allowance with today's use. Use for any question about the plan, billing, limits or usage. Self-hosted installs have no billing.",+ inputSchema: z.object({}),+ execute: async (): Promise<+ BillingOutput | { selfHosted: true; message: string }+ > => {+ if (ctx.config.selfHosted) {+ return {+ selfHosted: true,+ message:+ 'This is a self-hosted install; there is no plan or billing.',+ };+ }+ const organization = await deps.db.organization.findUniqueOrThrow({+ where: { id: organizationId },+ select: {+ name: true,+ subscriptionProductId: true,+ subscriptionStatus: true,+ subscriptionStartsAt: true,+ subscriptionEndsAt: true,+ subscriptionCanceledAt: true,+ subscriptionPauseAtPeriodEnd: true,+ subscriptionResumesAt: true,+ subscriptionInterval: true,+ subscriptionPeriodEventsCount: true,+ subscriptionPeriodEventsLimit: true,+ subscriptionPeriodEventsCountExceededAt: true,+ },+ });+ const state = getSubscriptionState(organization);+ const meta = getSubscriptionStateMeta(state, {+ endsAt: organization.subscriptionEndsAt,+ canceledAt: organization.subscriptionCanceledAt,+ resumesAt: organization.subscriptionResumesAt,+ });+ const product = organization.subscriptionProductId+ ? await getCurrentSubscriptionProduct(deps, organizationId).catch(+ () => null+ )+ : null;+ const price = (product?.prices?.[0] ?? null) as PriceLike | null;+ const productLimit = Number(product?.metadata?.eventsLimit);+ const eventsLimit =+ Number.isFinite(productLimit) && productLimit > 0+ ? productLimit+ : organization.subscriptionPeriodEventsLimit || null;+ const used = organization.subscriptionPeriodEventsCount;+ const tier = resolveChatTier(organization, ctx.config.selfHosted);+ const messagesToday = await readChatUsageToday(+ deps.redis,+ organizationId+ );++ return {+ selfHosted: false,+ organization: organization.name,+ state,+ statusLine: meta.statusLine?.text ?? meta.banner?.description ?? null,+ plan: {+ name: product?.name ?? null,+ free: organization.subscriptionProductId+ ? FREE_PRODUCT_IDS.includes(organization.subscriptionProductId)+ : false,+ price:+ typeof price?.priceAmount === 'number'+ ? price.priceAmount / CENTS_PER_UNIT+ : null,+ currency: price?.priceCurrency ?? null,+ interval:+ product?.recurringInterval ?? organization.subscriptionInterval,+ eventsLimit,+ },+ usage: {+ eventsThisPeriod: used,+ eventsLimit,+ percentUsed: eventsLimit+ ? Math.round((used / eventsLimit) * PERCENT)+ : null,+ periodStart: iso(organization.subscriptionStartsAt),+ periodEnd: iso(organization.subscriptionEndsAt),+ limitExceededAt: iso(+ organization.subscriptionPeriodEventsCountExceededAt+ ),+ },+ schedule: {+ canceledAt: iso(organization.subscriptionCanceledAt),+ pauseAtPeriodEnd: organization.subscriptionPauseAtPeriodEnd,+ resumesAt: iso(organization.subscriptionResumesAt),+ },+ assistant: {+ tier,+ messagesPerDay: CHAT_MESSAGES_PER_DAY[tier],+ messagesToday,+ },+ billingUrl,+ };+ },+ }),++ list_plans: tool({+ description:+ 'The plans the workspace can move to, with price, interval and event limit, and which one is current. Call before change_plan so the user can pick.',+ inputSchema: z.object({}),+ execute: async (): Promise<+ { plans: PlanOption[] } | { selfHosted: true; message: string }+ > => {+ if (ctx.config.selfHosted) {+ return {+ selfHosted: true,+ message: 'Self-hosted installs have no plans.',+ };+ }+ const [organization, products] = await Promise.all([+ deps.db.organization.findUniqueOrThrow({+ where: { id: organizationId },+ select: { subscriptionProductId: true },+ }),+ actions.subscription.products({ organizationId }),+ ]);+ return {+ plans: products.map((product) => {+ const price = (product.prices?.[0] ?? null) as+ | (PriceLike & { id?: string })+ | null;+ const limit = Number(product.metadata?.eventsLimit);+ return {+ productId: product.id,+ productPriceId: price?.id ?? null,+ name: product.name,+ eventsLimit: Number.isFinite(limit) && limit > 0 ? limit : null,+ price:+ typeof price?.priceAmount === 'number'+ ? price.priceAmount / CENTS_PER_UNIT+ : null,+ currency: price?.priceCurrency ?? null,+ interval: product.recurringInterval ?? null,+ current: product.id === organization.subscriptionProductId,+ unavailable: product.disabled ?? null,+ };+ }),+ };+ },+ }),++ change_plan: tool({+ description:+ 'Move the workspace to another plan. Asks the user to confirm. With an active paid subscription the change applies right away (Polar prorates it); otherwise the result is a checkout link the user completes on Polar. Only workspace admins can do this. Use productId and productPriceId from list_plans.',+ inputSchema: z.object({+ productId: z.string(),+ productPriceId: z.string(),+ }),+ execute: async ({ productId, productPriceId }) => {+ if (ctx.config.selfHosted) {+ return { error: 'Self-hosted installs have no plans to change.' };+ }+ const result = await actions.subscription.checkout({+ organizationId,+ productId,+ productPriceId,+ });+ if (result?.url) {+ return { checkoutUrl: result.url, billingUrl };+ }+ return { changed: true, billingUrl };+ },+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/charts.test.ts b/packages/core/src/modules/assistant/src/tools/charts.test.tsnew file mode 100644index 000000000..868662d41--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/charts.test.ts@@ -0,0 +1,153 @@+import { describe, expect, test } from 'bun:test';+import type { ChatToolContext } from '../context';+import { buildReportConfig, summarizeChartData } from './charts';++const ctx = { projectId: 'p1', timezone: 'UTC' } as ChatToolContext;++describe('buildReportConfig', () => {+ test('letters the series so formulas can reference them', () => {+ const built = buildReportConfig(ctx, {+ title: 'Signup rate',+ chartType: 'linear',+ interval: 'day',+ startDate: '2026-10-01',+ endDate: '2026-10-19',+ series: [+ { type: 'event', name: 'screen_view', segment: 'user', filters: [] },+ { type: 'event', name: 'signup', segment: 'user', filters: [] },+ { type: 'formula', formula: 'B / A * 100', hideSeries: ['A', 'B'] },+ ],+ breakdowns: [],+ });+ expect('config' in built).toBe(true);+ if (!('config' in built)) {+ return;+ }+ expect(built.config.series.map((serie) => serie.id)).toEqual([+ 'A',+ 'B',+ 'C',+ ]);+ expect(built.config.projectId).toBe('p1');+ expect(built.config.range).toBe('custom');+ expect(built.config.name).toBe('Signup rate');+ });++ test('metric cards default to unique profiles, other charts to sum', () => {+ const base = {+ title: 't',+ interval: 'day' as const,+ startDate: '2026-10-01',+ endDate: '2026-10-19',+ series: [+ {+ type: 'event' as const,+ name: 'signup',+ segment: 'event' as const,+ filters: [],+ },+ ],+ breakdowns: [],+ };+ const metric = buildReportConfig(ctx, { ...base, chartType: 'metric' });+ const line = buildReportConfig(ctx, { ...base, chartType: 'linear' });+ expect('config' in metric && metric.config.metric).toBe('count');+ expect('config' in line && line.config.metric).toBe('sum');+ });++ test('a funnel carries its group and window as options', () => {+ const built = buildReportConfig(ctx, {+ title: 'Checkout',+ chartType: 'funnel',+ interval: 'day',+ startDate: '2026-10-01',+ endDate: '2026-10-19',+ series: [+ { type: 'event', name: 'cart', segment: 'event', filters: [] },+ { type: 'event', name: 'purchase', segment: 'event', filters: [] },+ ],+ breakdowns: [],+ funnelGroup: 'profile_id',+ funnelWindowHours: 2,+ });+ expect('config' in built && built.config.options).toEqual({+ type: 'funnel',+ funnelGroup: 'profile_id',+ funnelWindow: 7200,+ });+ });++ test('an invalid config is returned as issues the model can fix', () => {+ const built = buildReportConfig(ctx, {+ title: 'Bad',+ chartType: 'linear',+ interval: 'day',+ startDate: '2026-10-01',+ endDate: '2026-10-19',+ series: [{ type: 'formula', formula: 'A ; drop' }],+ breakdowns: [],+ });+ expect('error' in built).toBe(true);+ });+});++describe('summarizeChartData', () => {+ test('series charts collapse to totals, peaks and compact points', () => {+ const summary = summarizeChartData({+ metrics: { sum: 30, count: 3, average: 10, min: 5, max: 15 },+ series: [+ {+ id: 'a',+ names: ['screen_view'],+ event: { name: 'screen_view' },+ metrics: { sum: 30, count: 3, average: 10, min: 5, max: 15 },+ data: [+ { date: '2026-10-01', count: 5 },+ { date: '2026-10-02', count: 15 },+ { date: '2026-10-03', count: 10 },+ ],+ },+ ],+ });+ expect(summary.seriesCount).toBe(1);+ const [serie] = summary.series as Record<string, unknown>[];+ expect(serie?.peak).toEqual({ date: '2026-10-02', value: 15 });+ expect(serie?.low).toEqual({ date: '2026-10-01', value: 5 });+ expect(serie?.data).toEqual([+ ['2026-10-01', 5],+ ['2026-10-02', 15],+ ['2026-10-03', 10],+ ]);+ });++ test('funnels collapse to steps', () => {+ const summary = summarizeChartData({+ totalSessions: 100,+ steps: [+ {+ event: { name: 'cart', displayName: 'Cart' },+ count: 100,+ percent: 100,+ dropoffCount: null,+ dropoffPercent: null,+ },+ {+ event: { name: 'purchase' },+ count: 25,+ percent: 25,+ dropoffCount: 75,+ dropoffPercent: 75,+ },+ ],+ });+ expect(summary.totalSessions).toBe(100);+ expect(+ (summary.steps as Array<{ event: string }>).map((step) => step.event)+ ).toEqual(['Cart', 'purchase']);+ });++ test('anything else is passed through as capped JSON', () => {+ const summary = summarizeChartData({ nodes: [], links: [] });+ expect(typeof summary.raw).toBe('string');+ });+});diff --git a/packages/core/src/modules/assistant/src/tools/charts.ts b/packages/core/src/modules/assistant/src/tools/charts.tsnew file mode 100644index 000000000..9763848a8--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/charts.ts@@ -0,0 +1,430 @@+import { tool } from 'ai';+import { z } from 'zod';+import {+ executeAggregateChart,+ executeChart,+} from '../../../chart/chart.service';+import { getFunnel } from '../../../chart/funnel.service';+import {+ chartTypes,+ type FinalChart,+ type IReportInput,+ intervals,+ lineTypes,+ operators,+ zReportInput,+} from '../../../report/report.constants';+import { getReportById } from '../../../report/report.service';+import { getChartStartEndDate } from '../../../report/src/chart-dates';+import type { ChatToolContext } from '../context';+import { dashboardUrl, errorResult } from './shared';++function enumKeys<K extends string>(record: Record<K, unknown>): [K, ...K[]] {+ const [first, ...rest] = Object.keys(record) as K[];+ return [first as K, ...rest];+}++/** Series are lettered so formulas can reference them. */+const SERIES_IDS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');+const MAX_SUMMARY_SERIES = 12;+const MAX_INLINE_POINTS = 62;+const MAX_LIMIT = 500;++const zEventSeriesInput = z.object({+ type: z.literal('event'),+ name: z.string().describe('Event name from describe_data.'),+ displayName: z.string().optional(),+ segment: z+ .enum([+ 'event',+ 'user',+ 'session',+ 'group',+ 'user_average',+ 'one_event_per_user',+ 'property_sum',+ 'property_average',+ 'property_max',+ 'property_min',+ ])+ .default('event')+ .describe(+ '`event` counts firings, `user` unique users, `session` unique sessions, `one_event_per_user` users who did it at least once, `property_*` aggregates a numeric `property`.'+ ),+ property: z+ .string()+ .optional()+ .describe('Numeric property for the property_* segments, e.g. `revenue`.'),+ filters: z+ .array(+ z.object({+ name: z+ .string()+ .describe('Bare column (`path`, `country`) or `properties.<key>`.'),+ operator: z.enum(enumKeys(operators)),+ value: z.array(+ z.union([z.string(), z.number(), z.boolean(), z.null()])+ ),+ })+ )+ .default([]),+});++const zFormulaSeriesInput = z.object({+ type: z.literal('formula'),+ formula: z+ .string()+ .describe('Arithmetic over series letters, e.g. `B / A * 100`.'),+ displayName: z.string().optional(),+ hideSeries: z+ .array(z.string())+ .optional()+ .describe('Letters of input series to hide from the chart.'),+});++export const zChartInput = z.object({+ title: z.string().min(1).describe('3 to 8 words. Shown as the card title.'),+ chartType: z.enum(enumKeys(chartTypes)),+ interval: z.enum(enumKeys(intervals)).default('day'),+ startDate: z.string().describe('YYYY-MM-DD'),+ endDate: z.string().describe('YYYY-MM-DD'),+ series: z.array(z.union([zEventSeriesInput, zFormulaSeriesInput])).min(1),+ breakdowns: z+ .array(z.object({ name: z.string() }))+ .default([])+ .describe('Group by a column or `properties.<key>`.'),+ metric: z+ .enum(['sum', 'count', 'average', 'min', 'max'])+ .optional()+ .describe(+ 'Metric and map charts only. Omit unless the user asked for an aggregation; metric cards then show unique profiles.'+ ),+ previous: z+ .boolean()+ .optional()+ .describe('Overlay the previous period of equal length.'),+ lineType: z.enum(enumKeys(lineTypes)).optional(),+ limit: z+ .number()+ .int()+ .min(1)+ .max(MAX_LIMIT)+ .optional()+ .describe('Top N for bar, pie and sankey.'),+ unit: z.string().optional().describe('Y-axis unit: `%`, `$`, `ms`.'),+ funnelGroup: z+ .enum(['session_id', 'profile_id'])+ .optional()+ .describe('Funnel only: count unique sessions or unique profiles.'),+ funnelWindowHours: z+ .number()+ .int()+ .min(1)+ .optional()+ .describe('Funnel only: hours a user has to complete all steps.'),+});++export type ChartInput = z.infer<typeof zChartInput>;++export type ChartSummary = Record<string, unknown>;++export interface ChartToolOutput {+ title: string;+ report: IReportInput & { name: string; id?: string };+ summary: ChartSummary;+ dashboardUrl?: string;+}++/** Builds the engine config from the model's flattened input, or a structured error the model can fix. */+export function buildReportConfig(+ ctx: ChatToolContext,+ input: ChartInput+):+ | { config: IReportInput & { name: string } }+ | { error: string; issues: unknown } {+ const series = input.series.map((entry, index) => {+ const id = SERIES_IDS[index] ?? String(index + 1);+ if (entry.type === 'formula') {+ return {+ id,+ type: 'formula' as const,+ formula: entry.formula,+ displayName: entry.displayName,+ hideSeries: entry.hideSeries,+ };+ }+ return {+ id,+ type: 'event' as const,+ name: entry.name,+ displayName: entry.displayName ?? entry.name,+ segment: entry.segment,+ property: entry.property,+ filters: entry.filters,+ };+ });++ const options =+ input.chartType === 'funnel'+ ? {+ type: 'funnel' as const,+ funnelGroup: input.funnelGroup ?? 'session_id',+ funnelWindow: input.funnelWindowHours+ ? input.funnelWindowHours * 3600+ : undefined,+ }+ : undefined;++ const parsed = zReportInput.safeParse({+ projectId: ctx.projectId,+ chartType: input.chartType,+ interval: input.interval,+ startDate: input.startDate,+ endDate: input.endDate,+ range: 'custom',+ series,+ breakdowns: input.breakdowns.map((breakdown, index) => ({+ id: String(index + 1),+ name: breakdown.name,+ })),+ // A metric card has always shown unique profiles; `sum` would turn+ // "1.2k users" into "45k events".+ metric: input.metric ?? (input.chartType === 'metric' ? 'count' : 'sum'),+ previous: input.previous ?? false,+ lineType: input.lineType ?? 'monotone',+ limit: input.limit,+ unit: input.unit,+ options,+ name: input.title,+ });+ if (!parsed.success) {+ return {+ error: 'Invalid chart config. Fix the issues and call again.',+ issues: parsed.error.issues.map((issue) => ({+ path: issue.path.join('.'),+ message: issue.message,+ })),+ };+ }+ return { config: { ...parsed.data, name: input.title } };+}++type EngineInput = Parameters<typeof executeChart>[1];++export async function runReportConfig(+ ctx: ChatToolContext,+ config: IReportInput+): Promise<unknown> {+ const engineInput = {+ ...config,+ projectId: ctx.projectId,+ timezone: ctx.timezone,+ } as unknown as EngineInput;+ if (config.chartType === 'funnel') {+ return getFunnel(ctx.deps, engineInput as Parameters<typeof getFunnel>[1]);+ }+ if (config.chartType === 'metric') {+ return executeAggregateChart(ctx.deps, engineInput);+ }+ return executeChart(ctx.deps, engineInput);+}++function isFinalChart(value: unknown): value is FinalChart {+ return (+ typeof value === 'object' &&+ value !== null &&+ Array.isArray((value as { series?: unknown }).series)+ );+}++interface FunnelLike {+ totalSessions: number;+ steps: Array<{+ event: { name: string; displayName?: string };+ count: number;+ percent: number;+ dropoffCount: number | null;+ dropoffPercent: number | null;+ }>;+}++function isFunnelLike(value: unknown): value is FunnelLike {+ return (+ typeof value === 'object' &&+ value !== null &&+ Array.isArray((value as { steps?: unknown }).steps)+ );+}++function summarizeSeries(chart: FinalChart): ChartSummary {+ const ordered = [...chart.series].sort(+ (a, b) => (b.metrics.sum ?? 0) - (a.metrics.sum ?? 0)+ );+ const series = ordered.slice(0, MAX_SUMMARY_SERIES).map((serie) => {+ const points = serie.data;+ let peak = points[0];+ let low = points[0];+ for (const point of points) {+ if (!peak || point.count > peak.count) {+ peak = point;+ }+ if (!low || point.count < low.count) {+ low = point;+ }+ }+ return {+ name: serie.names.join(' › '),+ ...serie.metrics,+ points: points.length,+ peak: peak ? { date: peak.date, value: peak.count } : undefined,+ low: low ? { date: low.date, value: low.count } : undefined,+ data:+ points.length <= MAX_INLINE_POINTS+ ? points.map((point) => [point.date, point.count])+ : undefined,+ };+ });+ return {+ total: chart.metrics,+ seriesCount: chart.series.length,+ omittedSeries: Math.max(0, chart.series.length - series.length),+ series,+ };+}++function summarizeFunnel(funnel: FunnelLike): ChartSummary {+ return {+ totalSessions: funnel.totalSessions,+ steps: funnel.steps.map((step) => ({+ event: step.event.displayName ?? step.event.name,+ count: step.count,+ percent: step.percent,+ dropoffCount: step.dropoffCount,+ dropoffPercent: step.dropoffPercent,+ })),+ };+}++const MAX_RAW_SUMMARY_CHARS = 4000;++/** The compact view of a chart's data the model reasons over; the UI renders the chart itself. */+export function summarizeChartData(data: unknown): ChartSummary {+ if (isFinalChart(data)) {+ return summarizeSeries(data);+ }+ if (isFunnelLike(data)) {+ return summarizeFunnel(data);+ }+ const raw = JSON.stringify(data) ?? '';+ return {+ raw:+ raw.length > MAX_RAW_SUMMARY_CHARS+ ? `${raw.slice(0, MAX_RAW_SUMMARY_CHARS)}…`+ : raw,+ };+}++/** Everything but the chart config: the UI needs the config, the model needs the numbers. */+export function chartModelSummary(+ output: ChartToolOutput | { error: string }+): Record<string, unknown> {+ if ('error' in output) {+ return output;+ }+ return {+ title: output.title,+ chartType: output.report.chartType,+ startDate: output.report.startDate,+ endDate: output.report.endDate,+ interval: output.report.interval,+ summary: output.summary,+ dashboardUrl: output.dashboardUrl,+ ...(usesRevenue(output.report)+ ? {+ note: 'Revenue sums here are in cents; divide by 100 for the amount.',+ }+ : {}),+ };+}++function usesRevenue(report: IReportInput): boolean {+ return report.series.some(+ (serie) => serie.type === 'event' && serie.property === 'revenue'+ );+}++export function chartToModelOutput(+ output: ChartToolOutput | { error: string }+) {+ return {+ type: 'text' as const,+ value: JSON.stringify(chartModelSummary(output)),+ };+}++export async function createChartOutput(+ ctx: ChatToolContext,+ input: ChartInput+): Promise<ChartToolOutput | { error: string; issues?: unknown }> {+ const built = buildReportConfig(ctx, input);+ if ('error' in built) {+ return built;+ }+ const data = await runReportConfig(ctx, built.config);+ const summary = summarizeChartData(data);+ if (+ built.config.breakdowns.length > 0 &&+ isFinalChart(data) &&+ data.series.length <= 1+ ) {+ summary.note =+ 'The breakdown produced a single group, so the event does not carry that property. UTM parameters and referrers live on screen_view and session_start events, not on purchase or revenue events; for revenue by source or campaign use get_traffic_attribution.';+ }+ return {+ title: input.title,+ report: built.config,+ summary,+ };+}++export function chartTools(ctx: ChatToolContext) {+ return {+ create_chart: tool({+ description:+ 'Render a chart in the chat from events in this project. Pick the chart type for the question: `linear` for trends over time, `bar` for top-N comparisons, `pie` for shares (max 6 slices), `metric` for one number, `funnel` for ordered steps, `retention` for cohorts (use interval week), `conversion` for an A-to-B rate over time, `sankey` for user flows, `map` for countries, `histogram` for distributions. Verify event and property names with describe_data first. You get the numbers back as a summary; the user sees the chart.',+ inputSchema: zChartInput,+ execute: (input) => createChartOutput(ctx, input),+ toModelOutput: ({ output }) => chartToModelOutput(output),+ }),++ get_report: tool({+ description:+ 'Run a saved report by id and show it as a chart. Use list_dashboards and list_reports to find ids. Prefer a saved report when one already answers the question.',+ inputSchema: z.object({ reportId: z.string() }),+ execute: async ({ reportId }) => {+ const report = await getReportById(ctx.deps, reportId);+ if (!report || report.projectId !== ctx.projectId) {+ return errorResult('Report not found', { reportId });+ }+ const { startDate, endDate } = getChartStartEndDate(+ report,+ ctx.timezone+ );+ const { layout: _layout, ...config } = report;+ const data = await runReportConfig(ctx, {+ ...config,+ startDate,+ endDate,+ });+ const output: ChartToolOutput = {+ title: report.name,+ report: { ...config, name: report.name, id: report.id },+ summary: summarizeChartData(data),+ dashboardUrl: dashboardUrl(ctx, `/reports/${report.id}`),+ };+ return output;+ },+ toModelOutput: ({ output }) => chartToModelOutput(output),+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/client-tools.ts b/packages/core/src/modules/assistant/src/tools/client-tools.tsnew file mode 100644index 000000000..18c6f85a7--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/client-tools.ts@@ -0,0 +1,32 @@+import { tool } from 'ai';+import { z } from 'zod';+import {+ CHAT_DIALOGS,+ CHAT_ROUTES,+ zNavigateInput,+ zOpenDialogInput,+} from '../../assistant.constants';++function catalog(+ entries: Record<string, { label: string; description: string }>+) {+ return Object.entries(entries)+ .map(([key, entry]) => `\`${key}\`: ${entry.label}. ${entry.description}`)+ .join('\n');+}++/** Run in the browser: no `execute`, the dashboard reports back. */+export function clientTools() {+ return {+ navigate: tool({+ description: `Offer the user a link to a page in the dashboard; it renders as a button they can press. Use it when they ask where something is or how to change a setting. Routes:\n${catalog(CHAT_ROUTES)}`,+ inputSchema: zNavigateInput,+ outputSchema: z.object({ opened: z.string() }),+ }),+ open_dialog: tool({+ description: `Offer the user a button that opens a creation dialog, prefilled where possible, so they only have to press save. Say what the dialog is for before offering it. Dialogs:\n${catalog(CHAT_DIALOGS)}`,+ inputSchema: zOpenDialogInput,+ outputSchema: z.object({ opened: z.string() }),+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/dashboard.ts b/packages/core/src/modules/assistant/src/tools/dashboard.tsdeleted file mode 100644index 1fdcaf931..000000000--- a/packages/core/src/modules/assistant/src/tools/dashboard.ts+++ /dev/null@@ -1,150 +0,0 @@-import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import {- executeAggregateChart,- executeChart,-} from '../../../chart/chart.service';-import { getFunnel } from '../../../chart/funnel.service';-import { getDashboardById } from '../../../dashboard/dashboard.service';-import { getSettingsForProject } from '../../../organization/organization.service';-import type { IChartRange, IInterval } from '../../../report/report.constants';-import { getReportsByDashboardId } from '../../../report/report.service';-import { getChartStartEndDate } from '../../../report/src/chart-dates';-import { chatTool, dashboardUrl } from './helpers';--// Caps parallel report execution so a huge dashboard cannot blow the 30s tool-// timeout or hammer ClickHouse.-const MAX_REPORTS_PER_SUMMARY = 30;--export const summarizeDashboard = (deps: ServiceDeps) =>- 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(- deps,- dashboardId,- context.projectId- );- if (!dashboard) {- return { error: 'Dashboard not found', dashboardId };- }-- const allReports = await getReportsByDashboardId(deps, dashboardId);- const meta = {- id: dashboard.id,- name: dashboard.name,- dashboard_url: dashboardUrl(- deps.config,- 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(deps, 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 {- // The dashboard's global range applies to each report; explicit- // start+end dates win over the preset.- 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 getFunnel(- deps,- chartInput as Parameters<typeof getFunnel>[1]- );- } else if (report.chartType === 'metric') {- data = await executeAggregateChart(deps, chartInput);- } else {- data = await executeChart(deps, 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/packages/core/src/modules/assistant/src/tools/dashboards.ts b/packages/core/src/modules/assistant/src/tools/dashboards.tsnew file mode 100644index 000000000..b73c56294--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/dashboards.ts@@ -0,0 +1,140 @@+import { tool } from 'ai';+import { z } from 'zod';+import { listDashboardsCore } from '../../../dashboard/dashboard.service';+import { listReportsCore } from '../../../report/report.service';+import type { ChatToolContext } from '../context';+import { buildReportConfig, zChartInput } from './charts';+import { dashboardUrl } from './shared';++export function dashboardTools(ctx: ChatToolContext) {+ const { deps, projectId, organizationId, actions } = ctx;++ return {+ list_dashboards: tool({+ description:+ 'The saved dashboards in this project with their ids and links.',+ inputSchema: z.object({}),+ execute: async () => {+ const dashboards = await listDashboardsCore(deps, {+ projectId,+ organizationId,+ });+ return dashboards.map((dashboard) => ({+ id: dashboard.id,+ name: dashboard.name,+ url: dashboardUrl(ctx, `/dashboards/${dashboard.id}`),+ }));+ },+ }),++ list_reports: tool({+ description:+ 'The reports on one dashboard: id, name, chart type, events and range. Use get_report to run one.',+ inputSchema: z.object({ dashboardId: z.string() }),+ execute: ({ dashboardId }) =>+ listReportsCore(deps, { projectId, dashboardId, organizationId }),+ }),++ create_dashboard: tool({+ description:+ 'Create an empty dashboard. Asks the user to confirm. Follow up with save_chart to fill it.',+ inputSchema: z.object({ name: z.string().min(1) }),+ execute: async ({ name }) => {+ const dashboard = await actions.dashboard.create({ name, projectId });+ return {+ id: dashboard.id,+ name: dashboard.name,+ url: dashboardUrl(ctx, `/dashboards/${dashboard.id}`),+ };+ },+ }),++ save_chart: tool({+ description:+ 'Save a chart as a report on a dashboard. Asks the user to confirm. Pass the same chart definition you used (or would use) with create_chart, plus the dashboard id from list_dashboards or create_dashboard.',+ inputSchema: z.object({+ dashboardId: z.string(),+ chart: zChartInput,+ }),+ execute: async ({ dashboardId, chart }) => {+ const built = buildReportConfig(ctx, chart);+ if ('error' in built) {+ return built;+ }+ const { projectId: _projectId, ...report } = built.config;+ const saved = await actions.report.create({ dashboardId, report });+ return {+ id: saved.id,+ name: saved.name,+ dashboardId,+ url: dashboardUrl(ctx, `/reports/${saved.id}`),+ };+ },+ }),++ create_reference: tool({+ description:+ 'Add a reference: an annotation on a date that shows on every chart (launch, campaign, deploy, outage). Asks the user to confirm.',+ inputSchema: z.object({+ title: z.string().min(1),+ description: z.string().optional(),+ date: z.string().describe('ISO date or datetime.'),+ }),+ execute: async ({ title, description, date }) => {+ const reference = await actions.reference.create({+ projectId,+ title,+ description: description ?? null,+ datetime: new Date(date).toISOString(),+ });+ return {+ id: reference.id,+ title: reference.title,+ url: dashboardUrl(ctx, '/references'),+ };+ },+ }),++ invite_member: tool({+ description:+ 'Invite a teammate to the workspace by email with access to all projects. Asks the user to confirm.',+ inputSchema: z.object({+ email: z.string().email(),+ role: z.enum(['admin', 'member']).default('member'),+ }),+ execute: async ({ email, role }) => {+ const invite = await actions.organization.inviteUser({+ email,+ organizationId,+ role,+ projectScope: 'all',+ access: [],+ });+ return {+ ...invite,+ url: dashboardUrl(ctx, '/settings').replace(`/${projectId}`, ''),+ };+ },+ }),++ update_project: tool({+ description:+ 'Rename the project or change its domain. Asks the user to confirm. Other settings live on the settings page; use navigate for those.',+ inputSchema: z.object({+ name: z.string().min(1).optional(),+ domain: z.string().url().optional(),+ }),+ execute: async ({ name, domain }) => {+ const project = await actions.project.update({+ id: projectId,+ name,+ domain,+ });+ if (!project) {+ return { error: 'Project not found' };+ }+ return { id: project.id, name: project.name, domain: project.domain };+ },+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/discovery.ts b/packages/core/src/modules/assistant/src/tools/discovery.tsnew file mode 100644index 000000000..de03e8643--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/discovery.ts@@ -0,0 +1,91 @@+import { tool } from 'ai';+import { z } from 'zod';+import {+ getEventPropertyValuesCore,+ listEventNamesCore,+ listEventPropertiesCore,+} from '../../../event/event.service';+import type { ChatToolContext } from '../context';+import { compactPropertyKeys } from './shared';++/** Properties sampled when describing one event. */+const SAMPLED_PROPERTY_COUNT = 6;+const SAMPLE_VALUES_PER_PROPERTY = 12;+/** Tracking internals the model never needs sample values for. */+const INTERNAL_PROPERTY_PREFIX = '__';++export function discoveryTools(ctx: ChatToolContext) {+ const { deps, projectId } = ctx;++ return {+ describe_data: tool({+ description:+ "What is tracked in this project. Without `eventName`: the event names (most frequent first), the built-in event columns and the custom property keys. With `eventName`: that event's property keys plus sample values. Call this before naming an event or property in any other tool; never guess names.",+ inputSchema: z.object({+ eventName: z+ .string()+ .optional()+ .describe(+ 'Describe one event in depth instead of the whole project.'+ ),+ }),+ execute: async ({ eventName }) => {+ if (!eventName) {+ const [names, properties] = await Promise.all([+ listEventNamesCore(deps, projectId),+ listEventPropertiesCore(deps, { projectId }),+ ]);+ const compact = compactPropertyKeys(properties.properties);+ return {+ events: names,+ columns: properties.columns,+ properties: compact.properties,+ propertiesTruncated: compact.truncated,+ usage:+ 'Columns are used bare (`path`, `country`). Custom keys are used as `properties.<key>`.',+ };+ }++ const properties = await listEventPropertiesCore(deps, {+ projectId,+ eventName,+ });+ const compact = compactPropertyKeys(properties.properties);+ const sampled = compact.properties+ .filter((key) => !key.startsWith(INTERNAL_PROPERTY_PREFIX))+ .slice(0, SAMPLED_PROPERTY_COUNT);+ const samples = await Promise.all(+ sampled.map(async (key) => {+ const result = await getEventPropertyValuesCore(deps, {+ projectId,+ eventName,+ propertyKey: `properties.${key}`,+ }).catch(() => null);+ return {+ key,+ values: result?.values.slice(0, SAMPLE_VALUES_PER_PROPERTY) ?? [],+ };+ })+ );+ return {+ event: eventName,+ columns: properties.columns,+ properties: compact.properties,+ propertiesTruncated: compact.truncated,+ samples,+ };+ },+ }),++ get_property_values: tool({+ description:+ 'Distinct values of one property for one event, for exact filter values ("country = SE", "plan = pro"). Use the key form the data tool returned: a bare column name or `properties.<key>`.',+ inputSchema: z.object({+ eventName: z.string(),+ propertyKey: z.string(),+ }),+ execute: ({ eventName, propertyKey }) =>+ getEventPropertyValuesCore(deps, { projectId, eventName, propertyKey }),+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/docs.test.ts b/packages/core/src/modules/assistant/src/tools/docs.test.tsnew file mode 100644index 000000000..1cf20db91--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/docs.test.ts@@ -0,0 +1,62 @@+import { describe, expect, test } from 'bun:test';+import { rankSections } from './docs';++const SELF_HOSTING_SECTION = {+ title: 'Environment variables',+ url: 'https://openpanel.dev/docs/self-hosting/environment-variables',+ body: 'OPENAI_API_KEY enables the MCP and chat features on your own install.',+ lowerTitle: 'environment variables',+ lowerBody:+ 'openai_api_key enables the mcp and chat features on your own install.',+};++const sections = [+ SELF_HOSTING_SECTION,+ {+ title: 'MCP Server',+ url: 'https://openpanel.dev/docs/mcp',+ body: 'Connect Claude, Cursor and other AI clients to your analytics with the Model Context Protocol. Create a read client to get a token.',+ lowerTitle: 'mcp server',+ lowerBody:+ 'connect claude, cursor and other ai clients to your analytics with the model context protocol. create a read client to get a token.',+ },+ {+ title: 'Track events',+ url: 'https://openpanel.dev/docs/get-started/track-events',+ body: 'Call op.track with a name and properties. Events show up in the events page.',+ lowerTitle: 'track events',+ lowerBody:+ 'call op.track with a name and properties. events show up in the events page.',+ },+];++describe('rankSections', () => {+ test('title matches outrank body matches', () => {+ const results = rankSections(+ sections,+ 'how do I connect the MCP server to Claude',+ { selfHosted: false }+ );+ expect(results[0]?.title).toBe('MCP Server');+ });++ test('short words and unknown terms match nothing', () => {+ expect(rankSections(sections, 'an it', { selfHosted: true })).toEqual([]);+ expect(rankSections(sections, 'kubernetes', { selfHosted: true })).toEqual(+ []+ );+ });++ test('self-hosting pages are hidden on Cloud and shown on a self-hosted install', () => {+ const cloud = rankSections(sections, 'environment variables mcp', {+ selfHosted: false,+ });+ expect(cloud.some((result) => result.url.includes('/self-hosting/'))).toBe(+ false+ );+ const own = rankSections(sections, 'environment variables mcp', {+ selfHosted: true,+ });+ expect(own[0]?.title).toBe('Environment variables');+ });+});diff --git a/packages/core/src/modules/assistant/src/tools/docs.ts b/packages/core/src/modules/assistant/src/tools/docs.tsnew file mode 100644index 000000000..c694fe37c--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/docs.ts@@ -0,0 +1,138 @@+import { tool } from 'ai';+import { z } from 'zod';+import type { ChatToolContext } from '../context';++/** The public docs rendered for LLMs, one section per page. */+const DOCS_URL = 'https://openpanel.dev/llms-full.txt';+const DOCS_CACHE_TTL_MS = 6 * 60 * 60 * 1000;+const DOCS_FETCH_TIMEOUT_MS = 10_000;+const MAX_RESULTS = 3;+const MAX_SECTION_CHARS = 3500;+const MIN_TERM_LENGTH = 3;+const TITLE_WEIGHT = 6;+const MAX_BODY_HITS = 12;+const SECTION_SEPARATOR = /\n---\n/;+const TITLE_LINE = /^## (.+)$/m;+const URL_LINE = /^URL: (\S+)$/m;+const NON_WORD = /[^a-z0-9]+/;+/** Pages that only make sense when you run OpenPanel yourself. */+const SELF_HOSTING_DOCS = '/docs/self-hosting';++interface DocSection {+ title: string;+ url: string;+ body: string;+ lowerTitle: string;+ lowerBody: string;+}++let cached: { fetchedAt: number; sections: DocSection[] } | null = null;++function parseSections(text: string): DocSection[] {+ const sections: DocSection[] = [];+ for (const chunk of text.split(SECTION_SEPARATOR)) {+ const title = TITLE_LINE.exec(chunk)?.[1]?.trim();+ const url = URL_LINE.exec(chunk)?.[1]?.trim();+ if (!(title && url)) {+ continue;+ }+ const body = chunk.replace(TITLE_LINE, '').replace(URL_LINE, '').trim();+ sections.push({+ title,+ url,+ body,+ lowerTitle: title.toLowerCase(),+ lowerBody: body.toLowerCase(),+ });+ }+ return sections;+}++async function loadSections(): Promise<DocSection[]> {+ if (cached && Date.now() - cached.fetchedAt < DOCS_CACHE_TTL_MS) {+ return cached.sections;+ }+ const response = await fetch(DOCS_URL, {+ signal: AbortSignal.timeout(DOCS_FETCH_TIMEOUT_MS),+ });+ if (!response.ok) {+ throw new Error(`Docs fetch failed with ${response.status}`);+ }+ const sections = parseSections(await response.text());+ cached = { fetchedAt: Date.now(), sections };+ return sections;+}++function countOccurrences(haystack: string, needle: string): number {+ let count = 0;+ let index = haystack.indexOf(needle);+ while (index !== -1 && count < MAX_BODY_HITS) {+ count += 1;+ index = haystack.indexOf(needle, index + needle.length);+ }+ return count;+}++export function rankSections(+ sections: DocSection[],+ query: string,+ options: { selfHosted: boolean }+) {+ const terms = query+ .toLowerCase()+ .split(NON_WORD)+ .filter((term) => term.length >= MIN_TERM_LENGTH);+ if (terms.length === 0) {+ return [];+ }+ return sections+ .filter(+ (section) =>+ options.selfHosted || !section.url.includes(SELF_HOSTING_DOCS)+ )+ .map((section) => {+ let score = 0;+ for (const term of terms) {+ if (section.lowerTitle.includes(term)) {+ score += TITLE_WEIGHT;+ }+ score += countOccurrences(section.lowerBody, term);+ }+ return { section, score };+ })+ .filter((entry) => entry.score > 0)+ .sort((a, b) => b.score - a.score)+ .slice(0, MAX_RESULTS)+ .map(({ section }) => ({+ title: section.title,+ url: section.url,+ content:+ section.body.length > MAX_SECTION_CHARS+ ? `${section.body.slice(0, MAX_SECTION_CHARS)}…`+ : section.body,+ }));+}++export function docsTools(ctx: Pick<ChatToolContext, 'config'>) {+ return {+ search_docs: tool({+ description:+ 'Search the OpenPanel documentation: SDK setup, tracking, identify users, groups, session replay, MCP, API, self-hosting, integrations, pricing concepts. Use it for any "how do I" or "is it possible" question about the product before answering from memory, and link the page you used.',+ inputSchema: z.object({ query: z.string().min(1) }),+ execute: async ({ query }) => {+ try {+ const sections = await loadSections();+ return {+ results: rankSections(sections, query, {+ selfHosted: ctx.config.selfHosted,+ }),+ };+ } catch (error) {+ return {+ error: `Documentation is not reachable right now (${error instanceof Error ? error.message : 'unknown error'}). Answer from what you know and point to https://openpanel.dev/docs.`,+ };+ }+ },+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/entities.ts b/packages/core/src/modules/assistant/src/tools/entities.tsnew file mode 100644index 000000000..489050f62--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/entities.ts@@ -0,0 +1,86 @@+import { tool } from 'ai';+import { z } from 'zod';+import { queryEventsCore } from '../../../event/event.service';+import {+ getProfileById,+ getProfileMetricsCore,+ getProfileSessionsCore,+ getProfileWithEvents,+} from '../../../profile/profile.service';+import { getSessionById } from '../../../session/session.service';+import type { ChatToolContext } from '../context';+import { dashboardUrl, errorResult } from './shared';++const RECENT_EVENTS = 15;+const RECENT_SESSIONS = 5;+const SESSION_EVENT_LIMIT = 100;+const SESSION_EVENTS_RETURNED = 50;++export function entityTools(ctx: ChatToolContext) {+ const { deps, projectId } = ctx;++ return {+ get_profile: tool({+ description:+ 'One user in depth: profile fields, lifetime metrics, recent sessions and recent events. Defaults to the profile the chat was opened from.',+ inputSchema: z.object({ profileId: z.string().optional() }),+ execute: async ({ profileId }) => {+ const id = profileId || ctx.hint?.profileId || '';+ if (!id) {+ return errorResult('No profile id given.');+ }+ const [profile, withEvents, sessions, metrics] = await Promise.all([+ getProfileById(deps, id, projectId),+ getProfileWithEvents(deps, projectId, id, RECENT_EVENTS),+ getProfileSessionsCore(deps, projectId, id, RECENT_SESSIONS),+ getProfileMetricsCore(deps, { projectId, profileId: id }).catch(+ () => null+ ),+ ]);+ if (!profile) {+ return errorResult('Profile not found', { profileId: id });+ }+ return {+ profile,+ metrics,+ recentSessions: sessions,+ recentEvents: withEvents.recent_events,+ url: dashboardUrl(ctx, `/profiles/${id}`),+ };+ },+ }),++ get_session: tool({+ description:+ 'One session in depth: device, referrer, duration, the pages visited in order and its events. Defaults to the session the chat was opened from.',+ inputSchema: z.object({ sessionId: z.string().optional() }),+ execute: async ({ sessionId }) => {+ const id = sessionId || ctx.hint?.sessionId || '';+ if (!id) {+ return errorResult('No session id given.');+ }+ const [session, events] = await Promise.all([+ getSessionById(deps, id, projectId),+ queryEventsCore(deps, {+ projectId,+ sessionId: id,+ limit: SESSION_EVENT_LIMIT,+ }),+ ]);+ if (!session) {+ return errorResult('Session not found', { sessionId: id });+ }+ const path = events+ .filter((event) => event.name === 'screen_view' && event.path)+ .map((event) => ({ path: event.path, at: event.created_at }));+ return {+ session,+ eventCount: events.length,+ path,+ events: events.slice(0, SESSION_EVENTS_RETURNED),+ url: dashboardUrl(ctx, `/sessions/${id}`),+ };+ },+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/events.ts b/packages/core/src/modules/assistant/src/tools/events.tsdeleted file mode 100644index d0d0a9b98..000000000--- a/packages/core/src/modules/assistant/src/tools/events.ts+++ /dev/null@@ -1,145 +0,0 @@-import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import {- getEventPropertyValuesCore,- queryEventsCore,-} from '../../../event/event.service';-import { chatTool, resolveDateRange, truncateRows } from './helpers';--/** How many recent events `analyze_event_distribution` tallies. */-const DISTRIBUTION_SAMPLE_LIMIT = 100;-/** How many recent events `correlate_events` pairs up by session. */-const CORRELATION_SAMPLE_LIMIT = 100;--export const analyzeEventDistribution = (deps: ServiceDeps) =>- chatTool(- {- name: 'analyze_event_distribution',- description: `For a set of events (or all events in the current view), break down their frequency, top countries and top devices. Computed from the ${DISTRIBUTION_SAMPLE_LIMIT} most recent matching events, NOT the whole period — \`sample_size\` is that sample, so describe the shape and never quote the counts as totals.`,- schema: z.object({- eventNames: z.array(z.string()).optional(),- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async ({ eventNames, startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });-- const events = await queryEventsCore(deps, {- projectId: context.projectId,- eventNames,- startDate: range.startDate,- endDate: range.endDate,- limit: DISTRIBUTION_SAMPLE_LIMIT,- });-- const frequency = new Map<string, number>();- const byCountry = new Map<string, number>();- const byDevice = new Map<string, number>();- for (const e of events) {- frequency.set(e.name, (frequency.get(e.name) ?? 0) + 1);- if (e.country) {- byCountry.set(e.country, (byCountry.get(e.country) ?? 0) + 1);- }- if (e.device) {- byDevice.set(e.device, (byDevice.get(e.device) ?? 0) + 1);- }- }-- const top = (m: Map<string, number>, n: number) =>- Array.from(m.entries())- .sort((a, b) => b[1] - a[1])- .slice(0, n)- .map(([name, count]) => ({ name, count }));-- return {- sample_size: events.length,- event_frequency: top(frequency, 20),- top_countries: top(byCountry, 10),- top_devices: top(byDevice, 10),- };- }- );--export const correlateEvents = (deps: ServiceDeps) =>- chatTool(- {- name: 'correlate_events',- description: `Find pairs of events that frequently occur in the same session. Ranked by co-occurrence within the ${CORRELATION_SAMPLE_LIMIT} most recent events, NOT the whole period — treat the counts as a sample, never as totals.`,- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async ({ startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });-- const events = await queryEventsCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- limit: CORRELATION_SAMPLE_LIMIT,- });-- const bySession = new Map<string, Set<string>>();- for (const e of events) {- if (!e.session_id) {- continue;- }- if (!bySession.has(e.session_id)) {- bySession.set(e.session_id, new Set());- }- bySession.get(e.session_id)?.add(e.name);- }-- const pairCounts = new Map<string, number>();- for (const eventNames of bySession.values()) {- const list = Array.from(eventNames).sort();- for (let i = 0; i < list.length; i++) {- for (let j = i + 1; j < list.length; j++) {- const key = `${list[i]} + ${list[j]}`;- pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);- }- }- }-- const pairs = Array.from(pairCounts.entries())- .sort((a, b) => b[1] - a[1])- .slice(0, 30)- .map(([pair, count]) => ({ pair, count }));-- return {- sample_sessions: bySession.size,- top_pairs: pairs,- };- }- );--export const getEventPropertyDistribution = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_event_property_distribution',- description:- 'Distribution of distinct values for a specific property on a specific event. Use to answer "what countries fire screen_view most?" type questions.',- schema: z.object({- eventName: z.string(),- propertyKey: z.string(),- }),- },- async ({ eventName, propertyKey }, context) => {- const result = await getEventPropertyValuesCore(deps, {- projectId: context.projectId,- eventName,- propertyKey,- });- return truncateRows(result.values, 100);- }- );diff --git a/packages/core/src/modules/assistant/src/tools/groups.ts b/packages/core/src/modules/assistant/src/tools/groups.tsdeleted file mode 100644index c57d9a503..000000000--- a/packages/core/src/modules/assistant/src/tools/groups.ts+++ /dev/null@@ -1,238 +0,0 @@-import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import { queryEventsCore } from '../../../event/event.service';-import {- findGroupsCore,- getGroupCore,- getGroupMemberProfiles,-} from '../../../group/group.service';-import { chatTool, dashboardUrl, truncateRows } from './helpers';--/** How many members `get_group_metrics` pulls before bucketing activity. */-const GROUP_METRICS_MEMBER_LIMIT = 1000;-/** How many of those members' recent events back the 7d/30d activity counts. */-const GROUP_METRICS_EVENT_LIMIT = 1000;-/** How many same-type peers `compare_groups` looks at. */-const PEER_GROUP_LIMIT = 100;--export const getGroupFull = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_group_full',- description:- 'One-shot deep dive: group info + member count + first 10 members + recent events from members. CALL THIS FIRST for "tell me about this group".',- schema: z.object({- groupId: z.string().optional(),- }),- },- async ({ groupId }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;- const orgPath = (path = '') =>- dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- path- );-- const group = await getGroupCore(deps, {- projectId: context.projectId,- groupId: id,- memberLimit: 10,- });-- // `profileIds IN (...)` lets the DB narrow instead of post-filtering a feed.- const memberIds = group.members.map((m) => m.id);- const recentEvents = memberIds.length- ? await queryEventsCore(deps, {- projectId: context.projectId,- profileIds: memberIds,- limit: 10,- })- : [];-- return {- ...group,- recent_events: recentEvents,- dashboard_url: orgPath(`/groups/${id}`),- };- }- );--export const getGroupMembers = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_group_members',- description: 'Paginated list of profiles in this group.',- schema: z.object({- groupId: z.string().optional(),- limit: z.number().min(1).max(100).default(20).optional(),- search: z.string().optional(),- }),- },- async ({ groupId, limit, search }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;- const orgPath = (path = '') =>- dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- path- );-- const result = await getGroupMemberProfiles(deps, {- projectId: context.projectId,- groupId: id,- take: limit ?? 20,- search,- });- return {- group_id: id,- total_count: result.count,- members: result.data.map((p) => ({- ...p,- dashboard_url: orgPath(`/profiles/${p.id}`),- })),- };- }- );--export const getGroupEvents = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_group_events',- description: 'Recent events from members of this group.',- schema: z.object({- groupId: z.string().optional(),- eventNames: z.array(z.string()).optional(),- limit: z.number().min(1).max(100).default(50).optional(),- }),- },- async ({ groupId, eventNames, limit }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;-- const members = await getGroupMemberProfiles(deps, {- projectId: context.projectId,- groupId: id,- take: 100,- });- if (members.data.length === 0) {- return { group_id: id, events: [], note: 'Group has no members' };- }-- const events = await queryEventsCore(deps, {- projectId: context.projectId,- profileIds: members.data.map((m) => m.id),- eventNames,- limit: limit ?? 50,- });-- return truncateRows(events, 100);- }- );--export const getGroupMetrics = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_group_metrics',- description: `Aggregate metrics for this group: total members, and how many of them were active in the last 7 days / 30 days. Activity is derived from the group members' most recent ${GROUP_METRICS_EVENT_LIMIT} events, so very large groups are undercounted.`,- schema: z.object({- groupId: z.string().optional(),- }),- },- async ({ groupId }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;-- const members = await getGroupMemberProfiles(deps, {- projectId: context.projectId,- groupId: id,- take: GROUP_METRICS_MEMBER_LIMIT,- });-- if (members.data.length === 0) {- return { group_id: id, total_members: 0, note: 'Group has no members' };- }-- // `profileIds IN (...)` lets ClickHouse narrow: a project-wide feed would- // miss members whose activity falls outside the last N raw events.- const memberIds = members.data.map((m) => m.id);- const recentEvents = await queryEventsCore(deps, {- projectId: context.projectId,- profileIds: memberIds,- startDate: new Date(Date.now() - 30 * 86_400_000)- .toISOString()- .slice(0, 10),- limit: GROUP_METRICS_EVENT_LIMIT,- });- const activeIds7d = new Set<string>();- const activeIds30d = new Set<string>();- const sevenDaysAgo = Date.now() - 7 * 86_400_000;- for (const e of recentEvents) {- if (!e.profile_id) {- continue;- }- activeIds30d.add(e.profile_id);- if (new Date(e.created_at).getTime() >= sevenDaysAgo) {- activeIds7d.add(e.profile_id);- }- }-- return {- group_id: id,- total_members: members.count,- active_last_7_days: activeIds7d.size,- active_last_30_days: activeIds30d.size,- };- }- );--export const compareGroups = (deps: ServiceDeps) =>- chatTool(- {- name: 'compare_groups',- description:- "Compare this group's member count against how many other groups of the same type exist, and list a few of those peers by name. Peer member counts and peer activity are NOT fetched — do not claim a ranking.",- schema: z.object({- groupId: z.string().optional(),- }),- },- async ({ groupId }, context) => {- const defaultGroupId = context.pageContext?.ids?.groupId ?? '';- const id = groupId || defaultGroupId;-- const thisGroup = await getGroupCore(deps, {- projectId: context.projectId,- groupId: id,- memberLimit: 0,- });-- const peers = await findGroupsCore(deps, {- projectId: context.projectId,- type: thisGroup.group.type,- limit: PEER_GROUP_LIMIT,- });-- if (peers.length === 0) {- return { this_group: thisGroup, peers: [], note: 'No peer groups' };- }-- // `findGroupsCore` returns no memberCount (that is `IServiceGroupStats`, a- // separate query), so peers are listed without rankings.- return {- this_group: {- id: thisGroup.group.id,- name: thisGroup.group.name,- member_count: thisGroup.member_count,- },- peer_count: peers.length,- top_peers: peers.slice(0, 5).map((g) => ({- id: g.id,- name: g.name,- })),- };- }- );diff --git a/packages/core/src/modules/assistant/src/tools/helpers.ts b/packages/core/src/modules/assistant/src/tools/helpers.tsdeleted file mode 100644index 4e5cbe1d6..000000000--- a/packages/core/src/modules/assistant/src/tools/helpers.ts+++ /dev/null@@ -1,209 +0,0 @@-import {- type AgentToolDefinition,- defineTool,- type ToolRunContext,-} from '@better-agent/core';-import { resolveDateRange as resolveDateRangeCore } from '@openpanel/shared';-import type { z } from 'zod';-import type { CoreConfig } from '../../../../config';-import type {- IChartEventFilter,- IChartRange,-} from '../../../report/report.constants';-import { getDatesFromRange } from '../../../report/src/chart-dates';-import type { ChatAgentContext, PageContext } from '../context';-import { chatRunContext } from '../run-context';--/** Max time a single tool handler is allowed to run. */-const TOOL_TIMEOUT_MS = 30_000;--/**- * Wrapper around `defineTool().server()` that types the agent context and- * enforces a time ceiling.- *- * - `defineTool` does not know which agent it is bound to, so `runCtx.context`- * is `unknown`; it is cast to `ChatAgentContext` here.- * - The handler input is `any` (validated at runtime by Zod): inferring it from- * the schema generic hits TypeScript's "type instantiation is excessively- * deep" limit. Tools that need typed input annotate it inline or use- * `z.infer`.- * - A 30-second timeout wraps every handler so a slow query or stalled fetch- * cannot hold the turn; the agent gets a clear "tool took too long" error.- * It bounds the TURN, not the work: the race abandons the handler, so the- * query behind a timed-out tool keeps running on the server.- */-export function chatTool(- config: {- name: string;- description: string;- schema: z.ZodTypeAny;- },- handler: (- // biome-ignore lint/suspicious/noExplicitAny: deliberate, see comment above- input: any,- ctx: ChatAgentContext,- runCtx: ToolRunContext- ) => Promise<unknown>-): AgentToolDefinition {- // biome-ignore lint/suspicious/noExplicitAny: see block comment above- const contract: any = defineTool({- name: config.name,- description: config.description,- schema: config.schema,- });- return contract.server(async (input: unknown, runCtx: ToolRunContext) => {- const work = handler(input, runCtx.context as ChatAgentContext, runCtx);- let timer: NodeJS.Timeout | undefined;- const timeout = new Promise<never>((_, reject) => {- timer = setTimeout(() => {- reject(- new Error(- `Tool "${config.name}" timed out after ${TOOL_TIMEOUT_MS / 1000}s`- )- );- }, TOOL_TIMEOUT_MS);- });- try {- return await Promise.race([work, timeout]);- } finally {- if (timer) {- clearTimeout(timer);- }- }- }) as AgentToolDefinition;-}--/** Cap an array result to `max` items and append a truncation marker so the renderer and the LLM know there is more. */-export function truncateRows<T>(- rows: T[],- max = 500-): { rows: T[]; total: number; _truncated: boolean } {- if (rows.length <= max) {- return { rows, total: rows.length, _truncated: false };- }- return { rows: rows.slice(0, max), total: rows.length, _truncated: true };-}--/**- * Compact `listEventPropertiesCore` output for the LLM. `columns` are top-level- * event columns, used bare in filters; `properties` are keys of the JSON- * `properties` map, used as `properties.<key>`.- *- * The raw rows are alphabetical and capped at 500, so a property with dynamic- * sub-paths (`__query.<uuid>`, ...) can flood the list before `country`- * appears. This collapses dotted keys to their root, dedupes, orders by- * frequency and keeps the ~50 roots the model needs.- */-export function compactEventProperties(- raw: {- columns: readonly string[];- properties: Array<{ property_key: string; event_name: string }>;- },- options: { eventName?: string; max?: number } = {}-): {- event_name?: string;- columns: readonly string[];- properties: string[];- total: number;- _truncated: boolean;-} {- const { eventName, max = 50 } = options;- const counts = new Map<string, number>();- for (const row of raw.properties) {- const dot = row.property_key.indexOf('.');- const root = dot >= 0 ? row.property_key.slice(0, dot) : row.property_key;- counts.set(root, (counts.get(root) ?? 0) + 1);- }- const sorted = Array.from(counts.entries())- .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))- .map(([key]) => key);- const truncated = sorted.length > max;- return {- ...(eventName ? { event_name: eventName } : {}),- columns: raw.columns,- properties: truncated ? sorted.slice(0, max) : sorted,- total: sorted.length,- _truncated: truncated,- };-}--/** Range presets `getDatesFromRange` understands; anything else (including `"custom"`) falls through to explicit dates or the 30-day default. */-const PRESET_RANGES: ReadonlySet<IChartRange> = new Set([- '30min',- 'lastHour',- 'today',- 'yesterday',- '7d',- '30d',- '6m',- '12m',- 'monthToDate',- 'lastMonth',- 'yearToDate',- 'lastYear',-]);--/**- * Resolve a date range from `PageContext.filters`: explicit start/end dates- * first, then a known preset expanded in the project timezone (so a- * preset-only URL gives the window the dashboard shows), else the last 30- * days. The timezone comes from `chatRunContext`, UTC outside it (tests).- */-export function resolveDateRange(filters?: PageContext['filters']): {- startDate: string;- endDate: string;-} {- if (filters?.startDate || filters?.endDate) {- return resolveDateRangeCore(filters.startDate, filters.endDate);- }-- const range = filters?.range as IChartRange | undefined;- if (range && PRESET_RANGES.has(range)) {- const timezone = chatRunContext.getStore()?.timezone ?? 'UTC';- return getDatesFromRange(range, timezone);- }-- return resolveDateRangeCore(undefined, undefined);-}--/**- * Extract `IChartEventFilter[]` from the page context so the assistant sees the- * user's active filters instead of returning project-wide numbers that- * contradict the dashboard. The context schema keeps filters loose, so this- * casts and drops entries without a `name`.- */-export function pageContextFilters(- pageContext: ChatAgentContext['pageContext']-): IChartEventFilter[] {- const raw = pageContext?.filters?.eventFilters;- if (!Array.isArray(raw)) {- return [];- }- return raw.filter(- (f): f is IChartEventFilter =>- typeof (f as { name?: unknown })?.name === 'string'- );-}--export function previousPeriod(startDate: string, endDate: string) {- const start = new Date(startDate).getTime();- const end = new Date(endDate).getTime();- const span = end - start;- return {- startDate: new Date(start - span - 86_400_000).toISOString().slice(0, 10),- endDate: new Date(start - 86_400_000).toISOString().slice(0, 10),- };-}--/** Where a dev box's dashboard runs when DASHBOARD_URL is not set. */-const DEFAULT_DASHBOARD_URL = 'http://localhost:3000';--export function dashboardUrl(- config: CoreConfig,- organizationId: string,- projectId: string,- path = ''-): string {- const base = config.dashboardUrl || DEFAULT_DASHBOARD_URL;- return `${base}/${organizationId}/${projectId}${path}`;-}diff --git a/packages/core/src/modules/assistant/src/tools/index.ts b/packages/core/src/modules/assistant/src/tools/index.tsindex e37e64df6..8b9a88b74 100644--- a/packages/core/src/modules/assistant/src/tools/index.ts+++ b/packages/core/src/modules/assistant/src/tools/index.ts@@ -1,171 +1,43 @@-import type { AgentToolDefinition } from '@better-agent/core';-import type { ServiceDeps } from '../../../../services';-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';-import * as pages from './pages';-import * as profile from './profile';-import * as references from './references';-import * as report from './report';-import * as seo from './seo';-import * as session from './session';-import * as ui from './ui';--// `@better-agent/core`'s tool handler signature has no context parameter, so-// handlers close over `deps`. Lists are typed loosely: without the cast,-// TypeScript hits its instantiation depth limit computing the union of every-// tool's schema and result type.-type ToolFactory = (deps: ServiceDeps) => AgentToolDefinition;-type ToolList = ToolFactory[];--const BASE_TOOLS: ToolList = [- base.listEventNames,- base.listEventProperties,- base.getEventPropertyValues,- base.listDashboards,- base.listReports,- base.getReportData,- base.generateReport,- base.getAnalyticsOverview,- base.getTopPages,- base.getTopReferrers,- base.getCountryBreakdown,- base.getDeviceBreakdown,- base.getRollingActiveUsers,- base.getFunnel,- base.getRetentionCohort,- base.getUserFlow,- base.queryEvents,- base.querySessions,- base.findProfiles,- // Available on every page: "what happened around X?" is not overview-specific.- references.listReferences,- references.getReferencesAround,-] as ToolList;--const PROFILE_TOOLS: ToolList = [- profile.getProfileFull,- profile.getProfileEvents,- profile.getProfileSessions,- profile.getProfileMetrics,- profile.getProfileJourney,- profile.getProfileGroups,- profile.compareProfileToAverage,-] as ToolList;--const SESSION_TOOLS: ToolList = [- session.getSessionFull,- session.getSessionPath,- session.getSessionEvents,- session.getSimilarSessions,- session.compareSessionToTypical,- session.getSessionReferrerContext,- session.getSessionReplaySummary,-] as ToolList;--const REPORT_EDITOR_TOOLS: ToolList = [- report.previewReportWithChanges,- report.suggestBreakdowns,- report.compareToPreviousPeriod,- report.findAnomaliesInCurrentReport,- report.explainFilterImpact,-] as ToolList;--const PAGES_TOOLS: ToolList = [- pages.getPagePerformance,- pages.getPageConversions,- pages.getEntryExitPages,- pages.findDecliningPages,-] as ToolList;--const SEO_TOOLS: ToolList = [- seo.gscGetOverview,- seo.gscGetTopQueries,- seo.gscGetTopPages,- seo.gscGetQueryDetails,- seo.gscGetPageDetails,- seo.gscGetQueryOpportunities,- seo.gscGetCannibalization,- seo.correlateSeoWithTraffic,-] as ToolList;--// No property-listing tool here: `base.listEventProperties` is already in BASE_TOOLS.-const EVENTS_TOOLS: ToolList = [- events.analyzeEventDistribution,- events.correlateEvents,- events.getEventPropertyDistribution,-] as ToolList;--const INSIGHTS_TOOLS: ToolList = [- insights.listInsights,- insights.explainInsight,- insights.findRelatedInsights,-] as ToolList;--const GROUP_TOOLS: ToolList = [- groups.getGroupFull,- groups.getGroupMembers,- groups.getGroupEvents,- groups.getGroupMetrics,- groups.compareGroups,-] as ToolList;--const DASHBOARD_TOOLS: ToolList = [dashboard.summarizeDashboard] as ToolList;--// Client-side UI mutators, for pages with user-settable filters.-const UI_TOOLS: ToolList = [- ui.applyFilters,- ui.setEventNamesFilter,- ui.setPropertyFilters,-] as ToolList;--/**- * Compose the chat tool set for a request: base tools always, page-specific- * tools only when their entity id is in pageContext, so the model is not- * offered tools it cannot usefully call.- */-export function composeChatTools(- deps: ServiceDeps,- context: ChatAgentContext-): AgentToolDefinition[] {- const page = context.pageContext?.page;- const ids = context.pageContext?.ids;- const build = (...groups: ToolList[]): AgentToolDefinition[] =>- groups.flat().map((tool) => tool(deps));-- switch (page) {- case 'profileDetail':- return ids?.profileId- ? build(BASE_TOOLS, PROFILE_TOOLS, UI_TOOLS)- : build(BASE_TOOLS, UI_TOOLS);- case 'sessionDetail':- return ids?.sessionId- ? build(BASE_TOOLS, SESSION_TOOLS)- : build(BASE_TOOLS);- case 'reportEditor':- return context.pageContext?.reportDraft- ? build(BASE_TOOLS, REPORT_EDITOR_TOOLS)- : build(BASE_TOOLS);- case 'pages':- return build(BASE_TOOLS, PAGES_TOOLS, UI_TOOLS);- case 'seo':- return build(BASE_TOOLS, SEO_TOOLS, UI_TOOLS);- case 'events':- return build(BASE_TOOLS, EVENTS_TOOLS, UI_TOOLS);- case 'insights':- return build(BASE_TOOLS, INSIGHTS_TOOLS, UI_TOOLS);- case 'groupDetail':- return ids?.groupId ? build(BASE_TOOLS, GROUP_TOOLS) : build(BASE_TOOLS);- case 'dashboard':- return ids?.dashboardId- ? build(BASE_TOOLS, DASHBOARD_TOOLS, UI_TOOLS)- : build(BASE_TOOLS, UI_TOOLS);- case 'overview':- return build(BASE_TOOLS, UI_TOOLS);- default:- return build(BASE_TOOLS);- }+import type { ChatToolContext } from '../context';+import { analyticsTools } from './analytics';+import { billingTools } from './billing';+import { chartTools } from './charts';+import { clientTools } from './client-tools';+import { dashboardTools } from './dashboards';+import { discoveryTools } from './discovery';+import { docsTools } from './docs';+import { entityTools } from './entities';+import { referenceTools } from './references';+import { searchTools } from './search';+import { seoTools } from './seo';+import { trackingTools } from './tracking';++/** One tool set per turn; every tool closes over the checked context. */+export function createChatTools(ctx: ChatToolContext) {+ return {+ ...discoveryTools(ctx),+ ...analyticsTools(ctx),+ ...chartTools(ctx),+ ...searchTools(ctx),+ ...entityTools(ctx),+ ...referenceTools(ctx),+ ...seoTools(ctx),+ ...trackingTools(ctx),+ ...billingTools(ctx),+ ...dashboardTools(ctx),+ ...docsTools(ctx),+ ...clientTools(),+ };}++export type ChatTools = ReturnType<typeof createChatTools>;++/** Writes wait for the user to confirm in the chat. */+export const CHAT_TOOL_APPROVAL = {+ create_dashboard: 'user-approval',+ save_chart: 'user-approval',+ create_reference: 'user-approval',+ invite_member: 'user-approval',+ update_project: 'user-approval',+ change_plan: 'user-approval',+} as const satisfies Partial<Record<keyof ChatTools, 'user-approval'>>;diff --git a/packages/core/src/modules/assistant/src/tools/insights.ts b/packages/core/src/modules/assistant/src/tools/insights.tsdeleted file mode 100644index e7e8c8360..000000000--- a/packages/core/src/modules/assistant/src/tools/insights.ts+++ /dev/null@@ -1,127 +0,0 @@-import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import { chatTool, truncateRows } from './helpers';--export const listInsights = (deps: ServiceDeps) =>- chatTool(- {- name: 'list_insights',- description:- 'List active auto-detected insights for this project, sorted by impact. Each has module (geo/devices/referrers/etc.), direction (up/down/flat), severity, and impact score.',- schema: z.object({- limit: z.number().min(1).max(500).default(50).optional(),- moduleKey: z- .string()- .optional()- .describe(- 'Filter by module: geo, devices, referrers, entry-pages, page-trends, exit-pages, traffic-anomalies'- ),- severity: z.enum(['severe', 'moderate', 'low']).optional(),- direction: z.enum(['up', 'down', 'flat']).optional(),- }),- },- async ({ limit, moduleKey, severity, direction }, context) => {- const db = deps.db;- const insights = await db.projectInsight.findMany({- where: {- projectId: context.projectId,- state: 'active',- ...(moduleKey ? { moduleKey } : {}),- ...(severity ? { severityBand: severity } : {}),- ...(direction ? { direction } : {}),- },- orderBy: { impactScore: 'desc' },- take: limit ?? 50,- });- // Project to a UI/LLM-friendly shape. Order matters: the table- // renderer uses the first string column as the label, and we want- // the human title there — not the UUID.- return truncateRows(- insights.map((i) => ({- title: i.title,- summary: i.summary ?? '',- module: i.moduleKey,- dimension: i.dimensionKey,- direction: i.direction ?? '',- severity: i.severityBand ?? '',- impact: Math.round(i.impactScore),- window: i.windowKind,- // Keep the id LAST so the model can call explain_insight with it,- // but the table won't pick it as the label column.- id: i.id,- })),- 100- );- }- );--export const explainInsight = (deps: ServiceDeps) =>- chatTool(- {- name: 'explain_insight',- description:- 'Get a single insight by ID with its full payload (the structured data the dashboard renders) plus its event history (when first detected, version updates).',- schema: z.object({- insightId: z.string(),- }),- },- async ({ insightId }, context) => {- const db = deps.db;- const insight = await db.projectInsight.findFirst({- where: { id: insightId, projectId: context.projectId },- });- if (!insight) {- return { error: 'Insight not found', insightId };- }- const events = await db.insightEvent.findMany({- where: { insightId },- orderBy: { createdAt: 'desc' },- take: 20,- });- return { insight, events };- }- );--export const findRelatedInsights = (deps: ServiceDeps) =>- chatTool(- {- name: 'find_related_insights',- description:- 'Given one insight, find others that share the same module or dimension. Useful when one insight prompts a "what else is going on with this country/page/device?" follow-up.',- schema: z.object({- insightId: z.string(),- limit: z.number().min(1).max(50).default(10).optional(),- }),- },- async ({ insightId, limit }, context) => {- const db = deps.db;- const insight = await db.projectInsight.findFirst({- where: { id: insightId, projectId: context.projectId },- });- if (!insight) {- return { error: 'Insight not found', insightId };- }- const related = await db.projectInsight.findMany({- where: {- projectId: context.projectId,- id: { not: insightId },- state: 'active',- OR: [- { moduleKey: insight.moduleKey },- { dimensionKey: insight.dimensionKey },- ],- },- orderBy: { impactScore: 'desc' },- take: limit ?? 10,- });- return {- source_insight: {- id: insight.id,- moduleKey: insight.moduleKey,- dimensionKey: insight.dimensionKey,- },- related_count: related.length,- related,- };- }- );diff --git a/packages/core/src/modules/assistant/src/tools/pages.ts b/packages/core/src/modules/assistant/src/tools/pages.tsdeleted file mode 100644index 53d76e328..000000000--- a/packages/core/src/modules/assistant/src/tools/pages.ts+++ /dev/null@@ -1,193 +0,0 @@-import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import {- getEntryExitPagesCore,- getPageConversionsCore,- getPagePerformanceCore,- getTopPagesCore,-} from '../../../overview/pages.service';-import {- chatTool,- previousPeriod,- resolveDateRange,- truncateRows,-} from './helpers';--export const getPagePerformance = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_page_performance',- description:- "Per-page performance metrics with SEO signal flags (high bounce, low engagement, good landing page). Sortable by sessions, pageviews, bounce_rate, or avg_duration. Inherits the current view's date range but NOT its property filters, so the numbers are project-wide and can differ from the filter-respecting `get_top_pages`.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- search: z.string().optional(),- sortBy: z- .enum(['sessions', 'pageviews', 'bounce_rate', 'avg_duration'])- .default('sessions')- .optional(),- sortOrder: z.enum(['asc', 'desc']).default('desc').optional(),- limit: z.number().min(1).max(500).default(50).optional(),- }),- },- async (input, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: input.startDate ?? context.pageContext?.filters?.startDate,- endDate: input.endDate ?? context.pageContext?.filters?.endDate,- });- return getPagePerformanceCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- search: input.search,- sortBy: input.sortBy,- sortOrder: input.sortOrder,- limit: input.limit ?? 50,- });- }- );--export const getPageConversions = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_page_conversions',- description:- "For a given conversion event, find which pages drive the most conversions. Includes conversion rate per page. Inherits the current view's date range but NOT its property filters, so the numbers are project-wide and can differ from the filter-respecting `get_top_pages`.",- schema: z.object({- conversionEvent: z- .string()- .describe('The conversion event name (e.g. "signup", "purchase")'),- startDate: z.string().optional(),- endDate: z.string().optional(),- windowHours: z.number().min(1).max(720).default(24).optional(),- limit: z.number().min(1).max(500).default(50).optional(),- }),- },- async (input, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: input.startDate ?? context.pageContext?.filters?.startDate,- endDate: input.endDate ?? context.pageContext?.filters?.endDate,- });- const rows = await getPageConversionsCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- conversionEvent: input.conversionEvent,- windowHours: input.windowHours,- limit: input.limit ?? 50,- });- return truncateRows(rows, 100);- }- );--export const getEntryExitPages = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_entry_exit_pages',- description:- "Top entry pages or top exit pages — useful for understanding where users start and where they bounce. Inherits the current view's date range but NOT its property filters, so the numbers are project-wide and can differ from the filter-respecting `get_top_pages`.",- schema: z.object({- mode: z.enum(['entry', 'exit']),- startDate: z.string().optional(),- endDate: z.string().optional(),- }),- },- async ({ mode, startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- const rows = await getEntryExitPagesCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- mode,- });- return truncateRows(rows, 50);- }- );--export const findDecliningPages = (deps: ServiceDeps) =>- chatTool(- {- name: 'find_declining_pages',- description:- "Find pages where pageview volume dropped vs the immediately preceding period of the same length. Returns each declining page with absolute and percent change. Inherits the current view's date range but NOT its property filters, so the numbers are project-wide and can differ from the filter-respecting `get_top_pages`.",- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- minPageviews: z- .number()- .min(1)- .default(50)- .optional()- .describe(- 'Filter out pages with fewer than N pageviews in the previous period'- ),- }),- },- async (input, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: input.startDate ?? context.pageContext?.filters?.startDate,- endDate: input.endDate ?? context.pageContext?.filters?.endDate,- });- const prev = previousPeriod(range.startDate, range.endDate);-- const [current, previous] = await Promise.all([- getTopPagesCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- limit: 500,- }),- getTopPagesCore(deps, {- projectId: context.projectId,- startDate: prev.startDate,- endDate: prev.endDate,- limit: 500,- }),- ]);-- // biome-ignore lint/suspicious/noExplicitAny: pages shape varies between engines- const currMap = new Map<string, any>(- (current as Array<{ name?: string; path?: string }>).map((p) => [- String(p.name ?? p.path),- p,- ])- );- const min = input.minPageviews ?? 50;- const declines = (- previous as Array<{- name?: string;- path?: string;- count?: number;- sessions?: number;- }>- )- .filter((p) => (p.count ?? p.sessions ?? 0) >= min)- .map((p) => {- const key = String(p.name ?? p.path);- const curr = currMap.get(key);- const prevCount = Number(p.count ?? p.sessions ?? 0);- const currCount = Number(curr?.count ?? curr?.sessions ?? 0);- const delta = currCount - prevCount;- const pct = prevCount > 0 ? (delta / prevCount) * 100 : 0;- return {- path: key,- previous: prevCount,- current: currCount,- delta,- percent_change: Number(pct.toFixed(1)),- };- })- .filter((row) => row.delta < 0)- .sort((a, b) => a.percent_change - b.percent_change);-- return truncateRows(declines, 50);- }- );diff --git a/packages/core/src/modules/assistant/src/tools/profile.ts b/packages/core/src/modules/assistant/src/tools/profile.tsdeleted file mode 100644index 0cd8d2145..000000000--- a/packages/core/src/modules/assistant/src/tools/profile.ts+++ /dev/null@@ -1,334 +0,0 @@-import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import { queryEventsCore } from '../../../event/event.service';-import {- findProfilesCore,- getProfileById,- getProfileMetricsCore,- getProfileSessionsCore,- getProfileWithEvents,-} from '../../../profile/profile.service';-import { chatTool, dashboardUrl, truncateRows } from './helpers';--/** How many other profiles `compare_profile_to_average` fetches to sample from. */-const AVERAGE_CANDIDATE_LIMIT = 100;-/** How many of those candidates actually get a metrics query. */-const AVERAGE_SAMPLE_SIZE = 30;--export const getProfileFull = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_profile_full',- description:- 'One-shot deep dive: profile data + lifetime metrics + last 5 sessions + last 10 events. CALL THIS FIRST when the user asks "tell me about this user" — it covers ~80% of follow-up questions in one round trip.',- schema: z.object({- profileId: z- .string()- .optional()- .describe('Defaults to the currently-viewed profile.'),- }),- },- async ({ profileId }, context) => {- const id = profileId || context.pageContext?.ids?.profileId || '';- const [profile, withEvents, sessions, metrics] = await Promise.all([- getProfileById(deps, id, context.projectId),- getProfileWithEvents(deps, context.projectId, id, 10),- getProfileSessionsCore(deps, context.projectId, id, 5),- getProfileMetricsCore(deps, {- projectId: context.projectId,- profileId: id,- }).catch(() => null),- ]);- if (!profile) {- return { error: 'Profile not found', profileId: id };- }- return {- profile,- metrics,- recent_sessions: sessions,- recent_events: withEvents.recent_events,- dashboard_url: dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- `/profiles/${id}`- ),- };- }- );--export const getProfileEvents = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_profile_events',- description:- "Recent events for this profile, optionally filtered by event name or property. Use when get_profile_full doesn't cover the question.",- schema: z.object({- profileId: z.string().optional(),- eventNames: z- .array(z.string())- .optional()- .describe('Filter to specific event names'),- properties: z.record(z.string(), z.string()).optional(),- limit: z.number().min(1).max(100).default(50).optional(),- }),- },- async ({ profileId, eventNames, properties, limit }, context) => {- const events = await queryEventsCore(deps, {- projectId: context.projectId,- profileId: profileId || context.pageContext?.ids?.profileId || '',- eventNames,- properties,- limit: limit ?? 50,- });- return truncateRows(events, 100);- }- );--export const getProfileSessions = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_profile_sessions',- description: 'All sessions for this profile, ordered most-recent-first.',- schema: z.object({- profileId: z.string().optional(),- limit: z.number().min(1).max(100).default(20).optional(),- }),- },- async ({ profileId, limit }, context) => {- const sessions = await getProfileSessionsCore(- deps,- context.projectId,- profileId || context.pageContext?.ids?.profileId || '',- limit ?? 20- );- return truncateRows(- sessions.map((s) => ({- ...s,- dashboard_url: dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- `/sessions/${s.id}`- ),- })),- 100- );- }- );--export const getProfileMetrics = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_profile_metrics',- description:- 'Lifetime metrics for this profile: sessions, screen views, total events, avg/p90 session duration, bounce rate, conversion events, time between sessions, revenue.',- schema: z.object({- profileId: z.string().optional(),- }),- },- async ({ profileId }, context) =>- getProfileMetricsCore(deps, {- projectId: context.projectId,- profileId: profileId || context.pageContext?.ids?.profileId || '',- })- );--export const getProfileJourney = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_profile_journey',- description:- 'Chronological narrative of this user\'s journey: first session, key conversion events, last 30 days summary. Designed for "tell me their story" questions — gives the LLM a structured timeline rather than a flat event list.',- schema: z.object({- profileId: z.string().optional(),- sinceDays: z.number().min(1).max(365).default(90).optional(),- maxEvents: z.number().min(5).max(100).default(50).optional(),- }),- },- async ({ profileId, sinceDays, maxEvents }, context) => {- const id = profileId || context.pageContext?.ids?.profileId || '';- const [profile, events, sessions, metrics] = await Promise.all([- getProfileById(deps, id, context.projectId),- queryEventsCore(deps, {- projectId: context.projectId,- profileId: id,- limit: maxEvents ?? 50,- }),- getProfileSessionsCore(deps, context.projectId, id, 20),- getProfileMetricsCore(deps, {- projectId: context.projectId,- profileId: id,- }).catch(() => null),- ]);-- if (!profile) {- return { error: 'Profile not found', profileId: id };- }-- // Heuristic: events that look like conversions (purchase, signup,- // checkout, subscribe, upgrade, complete, etc.)- const conversionPattern =- /^(purchase|sign_?up|signup|register|subscribe|checkout|upgrade|complete|paid|conversion)/i;- const keyMoments = events.filter((e) => conversionPattern.test(e.name));-- return {- profile_id: id,- first_seen:- metrics?.firstSeen ??- sessions[sessions.length - 1]?.created_at ??- null,- last_seen: metrics?.lastSeen ?? sessions[0]?.created_at ?? null,- total_sessions: metrics?.sessions ?? sessions.length,- total_events: metrics?.totalEvents ?? events.length,- key_moments: keyMoments.slice(0, 10),- recent_sessions: sessions.slice(0, 5).map((s) => ({- id: s.id,- created_at: s.created_at,- duration: s.duration,- entry_path: s.entry_path,- exit_path: s.exit_path,- is_bounce: s.is_bounce,- country: s.country,- referrer: s.referrer,- })),- recent_events: events.slice(0, 20).map((e) => ({- id: e.id,- name: e.name,- path: e.path,- created_at: e.created_at,- })),- dashboard_url: dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- `/profiles/${id}`- ),- };- }- );--export const getProfileGroups = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_profile_groups',- description:- 'Groups (B2B accounts) this profile belongs to. Returns the list of group IDs from the profile record.',- schema: z.object({- profileId: z.string().optional(),- }),- },- async ({ profileId }, context) => {- const id = profileId || context.pageContext?.ids?.profileId || '';- const profile = await getProfileById(deps, id, context.projectId);- if (!profile) {- return { error: 'Profile not found', profileId: id };- }- return {- profileId: profile.id,- group_count: (profile.groups ?? []).length,- groups: profile.groups ?? [],- };- }- );--export const compareProfileToAverage = (deps: ServiceDeps) =>- chatTool(- {- name: 'compare_profile_to_average',- description:- 'How this profile\'s key metrics compare to the project average — sessions, total events, bounce rate, etc. Returns ratios and "above/below" labels for each metric. Useful for spotting power users vs lurkers.',- schema: z.object({- profileId: z.string().optional(),- }),- },- async ({ profileId }, context) => {- const id = profileId || context.pageContext?.ids?.profileId || '';-- const [thisMetrics, allProfiles] = await Promise.all([- getProfileMetricsCore(deps, {- projectId: context.projectId,- profileId: id,- }).catch(() => null),- findProfilesCore(deps, {- projectId: context.projectId,- limit: AVERAGE_CANDIDATE_LIMIT,- }),- ]);-- if (!thisMetrics) {- return { error: 'Profile not found or has no events', profileId: id };- }-- // Average over a sample: metrics for the first AVERAGE_SAMPLE_SIZE of the- // AVERAGE_CANDIDATE_LIMIT profiles fetched, in parallel. Not a precise- // project-wide average.- const sampleIds = allProfiles- .filter((p) => p.id !== id)- .slice(0, AVERAGE_SAMPLE_SIZE)- .map((p) => p.id);-- const sampleMetrics = await Promise.all(- sampleIds.map((sid) =>- getProfileMetricsCore(deps, {- projectId: context.projectId,- profileId: sid,- }).catch(() => null)- )- );- const valid = sampleMetrics.filter(- (m): m is NonNullable<typeof m> => m != null- );-- if (valid.length === 0) {- return {- profile: thisMetrics,- comparison: null,- note: 'No other profiles available for comparison',- };- }-- const avg = (sel: (m: (typeof valid)[number]) => number) =>- valid.reduce((s, m) => s + sel(m), 0) / valid.length;-- const project_avg = {- sessions: avg((m) => m.sessions),- totalEvents: avg((m) => m.totalEvents),- screenViews: avg((m) => m.screenViews),- avgSessionDurationMin: avg((m) => m.avgSessionDurationMin),- bounceRate: avg((m) => m.bounceRate),- revenue: avg((m) => m.revenue),- };-- const ratio = (- a: number,- b: number- ): { ratio: number; label: 'above' | 'below' | 'equal' } => {- if (b === 0) {- return { ratio: 0, label: a > 0 ? 'above' : 'equal' };- }- const r = a / b;- return {- ratio: Number(r.toFixed(2)),- label: r > 1.05 ? 'above' : r < 0.95 ? 'below' : 'equal',- };- };-- return {- profile: thisMetrics,- project_avg,- comparison: {- sessions: ratio(thisMetrics.sessions, project_avg.sessions),- totalEvents: ratio(thisMetrics.totalEvents, project_avg.totalEvents),- screenViews: ratio(thisMetrics.screenViews, project_avg.screenViews),- avgSessionDurationMin: ratio(- thisMetrics.avgSessionDurationMin,- project_avg.avgSessionDurationMin- ),- bounceRate: ratio(thisMetrics.bounceRate, project_avg.bounceRate),- revenue: ratio(thisMetrics.revenue, project_avg.revenue),- },- sample_size: valid.length,- };- }- );diff --git a/packages/core/src/modules/assistant/src/tools/references.test.ts b/packages/core/src/modules/assistant/src/tools/references.test.tsdeleted file mode 100644index 2263563db..000000000--- a/packages/core/src/modules/assistant/src/tools/references.test.ts+++ /dev/null@@ -1,47 +0,0 @@-import { expect, test } from 'bun:test';-import { getChartStartEndDate } from '../../../report/src/chart-dates';-import { chatRunContext } from '../run-context';-import { getReferenceDateWindow } from './references';--const RUN_CONTEXT = {- userId: 'user_1',- projectId: 'proj_1',- organizationId: 'org_1',- timezone: 'Europe/Stockholm',-};--test('a preset range yields valid bounds matching the chart window', () => {- const window = chatRunContext.run(RUN_CONTEXT, () =>- getReferenceDateWindow({ range: '7d' })- );- const chartWindow = getChartStartEndDate(- { range: '7d', startDate: null, endDate: null },- RUN_CONTEXT.timezone- );-- expect(Number.isNaN(window.gte.getTime())).toBe(false);- expect(Number.isNaN(window.lte.getTime())).toBe(false);- expect(window.gte).toEqual(new Date(chartWindow.startDate));- expect(window.lte).toEqual(new Date(chartWindow.endDate));-});--test('explicit dates cover the whole of both days like the chart window', () => {- const window = getReferenceDateWindow({- startDate: '2026-09-01',- endDate: '2026-09-10',- });- const chartWindow = getChartStartEndDate(- { range: '30d', startDate: '2026-09-01', endDate: '2026-09-10' },- 'UTC'- );-- expect(window.gte).toEqual(new Date(chartWindow.startDate));- expect(window.lte).toEqual(new Date(chartWindow.endDate));-});--test('a start date alone runs to today', () => {- const window = getReferenceDateWindow({ startDate: '2026-09-01' });-- expect(window.gte).toEqual(new Date('2026-09-01 00:00:00'));- expect(window.lte.getTime()).toBeGreaterThan(Date.now() - 86_400_000);-});diff --git a/packages/core/src/modules/assistant/src/tools/references.ts b/packages/core/src/modules/assistant/src/tools/references.tsindex 6e8a04d04..5420e043f 100644--- a/packages/core/src/modules/assistant/src/tools/references.ts+++ b/packages/core/src/modules/assistant/src/tools/references.ts@@ -1,139 +1,104 @@+import { tool } from 'ai';import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import { getChartStartEndDate } from '../../../report/src/chart-dates';-import type { PageContext } from '../context';-import { chatRunContext } from '../run-context';-import { chatTool, resolveDateRange, truncateRows } from './helpers';+import type { ChatToolContext } from '../context';+import { resolveRange, toDateOnly, truncateRows } from './shared';-/**- * References are manual annotations the user adds (e.g. "Launched new marketing- * campaign" on 2026-03-15) so the AI can correlate traffic changes with- * off-platform events.- */+const DEFAULT_AROUND_DAYS = 7;+const MAX_AROUND_DAYS = 90;+const DEFAULT_LIMIT = 50;+const MAX_LIMIT = 100;+const MS_PER_DAY = 86_400_000;+const DATE_LENGTH = 10;-// Never read: `resolveDateRange` always returns both bounds, which is the case-// where `getChartStartEndDate` only normalizes them.-const UNUSED_FALLBACK_RANGE = '30d';+export function referenceTools(ctx: ChatToolContext) {+ const { deps, projectId } = ctx;-/** The same window the chart's reference annotations use for these filters. */-export function getReferenceDateWindow(filters: PageContext['filters']): {- gte: Date;- lte: Date;-} {- const timezone = chatRunContext.getStore()?.timezone ?? 'UTC';- const { startDate, endDate } = getChartStartEndDate(- { ...resolveDateRange(filters), range: UNUSED_FALLBACK_RANGE },- timezone- );- return { gte: new Date(startDate), lte: new Date(endDate) };-}--export const listReferences = (deps: ServiceDeps) =>- chatTool(- {- name: 'list_references',+ return {+ list_references: tool({description:- "List the user's manual references (campaign launches, deploys, announcements, etc.). Use when the user asks about causes of traffic changes or wants to understand what was happening at a specific time. Defaults to the user's current page date range; pass explicit dates to override.",- schema: z.object({- startDate: z- .string()- .optional()- .describe('ISO date YYYY-MM-DD. Defaults to the current view range.'),- endDate: z+ "The team's own annotations: launches, campaigns, deploys, press. Check these before explaining a spike or drop; pass `aroundDate` to look a week either side of a date.",+ inputSchema: z.object({+ startDate: z.string().optional().describe('YYYY-MM-DD'),+ endDate: z.string().optional().describe('YYYY-MM-DD'),+ aroundDate: z.string().optional()- .describe('ISO date YYYY-MM-DD. Defaults to the current view range.'),- search: z- .string()- .optional()- .describe('Optional free-text filter on title/description.'),- limit: z.number().min(1).max(100).default(50).optional(),+ .describe(+ 'YYYY-MM-DD. Overrides start and end with a window around this date.'+ ),+ days: z+ .number()+ .int()+ .min(0)+ .max(MAX_AROUND_DAYS)+ .default(DEFAULT_AROUND_DAYS),+ search: z.string().optional(),+ limit: z.number().int().min(1).max(MAX_LIMIT).default(DEFAULT_LIMIT),}),- },- async ({ startDate, endDate, search, limit }, context) => {- const dateWindow = getReferenceDateWindow({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- const db = deps.db;- const rows = await db.reference.findMany({- where: {- projectId: context.projectId,- date: dateWindow,- ...(search- ? {- OR: [- { title: { contains: search, mode: 'insensitive' as const } },- {- description: {- contains: search,- mode: 'insensitive' as const,+ execute: async ({+ startDate,+ endDate,+ aroundDate,+ days,+ search,+ limit,+ }) => {+ let window: { gte: Date; lte: Date };+ if (aroundDate) {+ const target = new Date(aroundDate);+ if (Number.isNaN(target.getTime())) {+ return { error: 'Invalid aroundDate', aroundDate };+ }+ window = {+ gte: new Date(target.getTime() - days * MS_PER_DAY),+ lte: new Date(target.getTime() + days * MS_PER_DAY),+ };+ } else {+ const range = resolveRange(ctx, { startDate, endDate });+ window = {+ gte: new Date(`${toDateOnly(range.startDate)}T00:00:00.000Z`),+ lte: new Date(`${toDateOnly(range.endDate)}T23:59:59.999Z`),+ };+ }+ const rows = await deps.db.reference.findMany({+ where: {+ projectId,+ date: window,+ ...(search+ ? {+ OR: [+ {+ title: { contains: search, mode: 'insensitive' as const },},- },- ],- }- : {}),- },- orderBy: { date: 'desc' },- take: limit ?? 50,- });-- return truncateRows(- rows.map((r) => ({- title: r.title,- date: r.date.toISOString().slice(0, 10),- description: r.description ?? '',- id: r.id,- })),- 100- );- }- );--export const getReferencesAround = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_references_around',- description:- 'Find references within ±N days of a target date. Perfect for "what was happening around 2026-03-15?" — returns references that might explain a spike or drop.',- schema: z.object({- date: z.string().describe('Target date (YYYY-MM-DD) to search around.'),- daysBefore: z.number().min(0).max(90).default(7).optional(),- daysAfter: z.number().min(0).max(90).default(7).optional(),- }),- },- async ({ date, daysBefore, daysAfter }, context) => {- const target = new Date(date);- if (Number.isNaN(target.getTime())) {- return { error: 'Invalid date', date };- }- const before = daysBefore ?? 7;- const after = daysAfter ?? 7;- const start = new Date(target.getTime() - before * 86_400_000);- const end = new Date(target.getTime() + after * 86_400_000);-- const db = deps.db;- const rows = await db.reference.findMany({- where: {- projectId: context.projectId,- date: { gte: start, lte: end },- },- orderBy: { date: 'asc' },- });-- return {- target_date: date,- window: {- start: start.toISOString().slice(0, 10),- end: end.toISOString().slice(0, 10),- },- references: rows.map((r) => ({- title: r.title,- date: r.date.toISOString().slice(0, 10),- description: r.description ?? '',- id: r.id,- })),- };- }- );+ {+ description: {+ contains: search,+ mode: 'insensitive' as const,+ },+ },+ ],+ }+ : {}),+ },+ orderBy: { date: 'desc' },+ take: limit,+ });+ return {+ window: {+ start: window.gte.toISOString().slice(0, DATE_LENGTH),+ end: window.lte.toISOString().slice(0, DATE_LENGTH),+ },+ ...truncateRows(+ rows.map((row) => ({+ id: row.id,+ title: row.title,+ date: row.date.toISOString().slice(0, DATE_LENGTH),+ description: row.description ?? '',+ })),+ limit+ ),+ };+ },+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/report.ts b/packages/core/src/modules/assistant/src/tools/report.tsdeleted file mode 100644index c770e81d4..000000000--- a/packages/core/src/modules/assistant/src/tools/report.ts+++ /dev/null@@ -1,351 +0,0 @@-import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import { listEventPropertiesCore } from '../../../event/event.service';-import type { IReportInput } from '../../../report/report.constants';-import { runReportFromConfig } from '../report-runner';-import { chatTool, previousPeriod, resolveDateRange } from './helpers';--export const previewReportWithChanges = (deps: ServiceDeps) =>- chatTool(- {- name: 'preview_report_with_changes',- description:- 'Apply a partial diff to the current report draft, execute it, and return the resulting data + the modified config. Use this to PROPOSE edits — the user can then accept or reject. Pass only the fields you want to change (e.g. { breakdowns: [{ name: "country" }] }).',- schema: z.object({- chartType: z- .enum([- 'linear',- 'bar',- 'area',- 'histogram',- 'pie',- 'metric',- 'funnel',- ])- .optional(),- interval: z.enum(['minute', 'hour', 'day', 'week', 'month']).optional(),- startDate: z.string().optional(),- endDate: z.string().optional(),- addBreakdown: z- .string()- .optional()- .describe('Property key to add as a breakdown (e.g. "country")'),- removeBreakdown: z- .string()- .optional()- .describe('Property key to remove from breakdowns'),- addEventFilter: z- .object({- seriesIndex: z.number().min(0),- name: z.string(),- operator: z.string(),- value: z.array(z.string()),- })- .optional(),- }),- },- async (input, context) => {- const draft = context.pageContext?.reportDraft as- | IReportInput- | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };- }-- const range = resolveDateRange({- startDate: input.startDate ?? draft.startDate ?? undefined,- endDate: input.endDate ?? draft.endDate ?? undefined,- });-- const next: IReportInput = {- ...draft,- chartType: input.chartType ?? draft.chartType,- interval: input.interval ?? draft.interval,- startDate: range.startDate,- endDate: range.endDate,- range: 'custom',- breakdowns: [...(draft.breakdowns ?? [])],- series: draft.series.map((s) => ({ ...s })),- };-- if (- input.addBreakdown &&- !next.breakdowns.some((b) => b.name === input.addBreakdown)- ) {- next.breakdowns.push({- id: String(next.breakdowns.length + 1),- name: input.addBreakdown,- });- }- if (input.removeBreakdown) {- next.breakdowns = next.breakdowns.filter(- (b) => b.name !== input.removeBreakdown- );- }- if (input.addEventFilter) {- const idx = input.addEventFilter.seriesIndex;- const target = next.series[idx];- if (target && idx >= 0 && target.type === 'event') {- // biome-ignore lint/suspicious/noExplicitAny: series type is heavily discriminated; filter ops vary- const series = target as any;- series.filters = [- ...(series.filters ?? []),- {- id: String((series.filters?.length ?? 0) + 1),- name: input.addEventFilter.name,- operator: input.addEventFilter.operator,- value: input.addEventFilter.value,- },- ];- }- }-- return runReportFromConfig(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- config: next as unknown as Parameters<- typeof runReportFromConfig- >[1]['config'],- });- }- );--export const suggestBreakdowns = (deps: ServiceDeps) =>- chatTool(- {- name: 'suggest_breakdowns',- description:- 'Look at the events selected in the current draft and suggest 3-5 useful properties to break down by. Returns property keys + how often they appear.',- schema: z.object({}),- },- async (_input, context) => {- const draft = context.pageContext?.reportDraft as- | IReportInput- | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };- }-- const eventNames = draft.series- .filter((s) => s.type === 'event')- .map((s) => (s as { name: string }).name);-- if (eventNames.length === 0) {- return { suggestions: [], note: 'Draft has no event series' };- }-- const propsPerEvent = await Promise.all(- eventNames.map((name) =>- listEventPropertiesCore(deps, {- projectId: context.projectId,- eventName: name,- })- )- );-- const keyCount = new Map<string, number>();- for (const r of propsPerEvent) {- for (const p of r.properties) {- keyCount.set(p.property_key, (keyCount.get(p.property_key) ?? 0) + 1);- }- }-- const used = new Set((draft.breakdowns ?? []).map((b) => b.name));- const suggestions = Array.from(keyCount.entries())- .filter(([k]) => !used.has(k))- .sort((a, b) => b[1] - a[1])- .slice(0, 5)- .map(([key, count]) => ({- property_key: key,- present_in_events: count,- }));-- return {- events_in_draft: eventNames,- existing_breakdowns: Array.from(used),- suggestions,- };- }- );--export const compareToPreviousPeriod = (deps: ServiceDeps) =>- chatTool(- {- name: 'compare_to_previous_period',- description:- 'Run the current draft against the immediately preceding period of the same length, and return both as { current, previous } so the user can see week-over-week / month-over-month change.',- schema: z.object({}),- },- async (_input, context) => {- const draft = context.pageContext?.reportDraft as- | IReportInput- | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };- }-- const range = resolveDateRange({- startDate: draft.startDate ?? undefined,- endDate: draft.endDate ?? undefined,- });- const prev = previousPeriod(range.startDate, range.endDate);-- const [current, previous] = await Promise.all([- runReportFromConfig(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- config: {- ...(draft as unknown as Record<string, unknown>),- startDate: range.startDate,- endDate: range.endDate,- range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],- }),- runReportFromConfig(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- config: {- ...(draft as unknown as Record<string, unknown>),- startDate: prev.startDate,- endDate: prev.endDate,- range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],- }),- ]);-- return { current, previous };- }- );--export const findAnomaliesInCurrentReport = (deps: ServiceDeps) =>- chatTool(- {- name: 'find_anomalies_in_current_report',- description:- 'Run the current draft and find data points that are unusually high or low (z-score > 2 from rolling mean). Returns the anomalies with their dates and magnitudes.',- schema: z.object({}),- },- async (_input, context) => {- const draft = context.pageContext?.reportDraft as- | IReportInput- | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };- }-- const range = resolveDateRange({- startDate: draft.startDate ?? undefined,- endDate: draft.endDate ?? undefined,- });-- const result = await runReportFromConfig(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- config: {- ...(draft as unknown as Record<string, unknown>),- startDate: range.startDate,- endDate: range.endDate,- range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],- });-- // Best-effort anomaly detection on the first series, if it is an array of- // { date, count } points.- // biome-ignore lint/suspicious/noExplicitAny: chart engine output shape is varied- const data = result.data as any;- const series = Array.isArray(data) ? data[0] : data?.series?.[0];- const points = series?.data ?? [];-- if (!Array.isArray(points) || points.length < 5) {- return {- note: 'Not enough data points to detect anomalies',- point_count: points.length ?? 0,- };- }-- const values = points.map((p: { count?: number }) =>- Number(p.count ?? 0)- );- const mean =- values.reduce((s: number, v: number) => s + v, 0) / values.length;- const variance =- values.reduce((s: number, v: number) => s + (v - mean) ** 2, 0) /- values.length;- const std = Math.sqrt(variance);-- const anomalies = points- .map((p: { date?: string; count?: number }, i: number) => {- const z = std === 0 ? 0 : (Number(p.count ?? 0) - mean) / std;- return {- date: p.date,- value: p.count,- z_score: Number(z.toFixed(2)),- index: i,- };- })- .filter((a: { z_score: number }) => Math.abs(a.z_score) > 2);-- return {- mean: Number(mean.toFixed(2)),- std: Number(std.toFixed(2)),- point_count: points.length,- anomalies,- };- }- );--export const explainFilterImpact = (deps: ServiceDeps) =>- chatTool(- {- name: 'explain_filter_impact',- description:- 'Run the current draft both with and without its filters, and return both totals so the user can see how much the filters cut down the data.',- schema: z.object({}),- },- async (_input, context) => {- const draft = context.pageContext?.reportDraft as- | IReportInput- | undefined;- if (!draft) {- return { error: 'No report draft available in the current context' };- }-- const range = resolveDateRange({- startDate: draft.startDate ?? undefined,- endDate: draft.endDate ?? undefined,- });-- const filtered = await runReportFromConfig(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- config: {- ...(draft as unknown as Record<string, unknown>),- startDate: range.startDate,- endDate: range.endDate,- range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],- });-- const cleanedSeries = draft.series.map((s) => ({- ...s,- filters: [],- }));-- const unfiltered = await runReportFromConfig(deps, {- organizationId: context.organizationId,- projectId: context.projectId,- config: {- ...(draft as unknown as Record<string, unknown>),- series: cleanedSeries,- startDate: range.startDate,- endDate: range.endDate,- range: 'custom',- } as unknown as Parameters<typeof runReportFromConfig>[1]['config'],- });-- return {- with_filters: filtered,- without_filters: unfiltered,- };- }- );diff --git a/packages/core/src/modules/assistant/src/tools/search.ts b/packages/core/src/modules/assistant/src/tools/search.tsnew file mode 100644index 000000000..82988b335--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/search.ts@@ -0,0 +1,105 @@+import { tool } from 'ai';+import { z } from 'zod';+import {+ listEventNamesCore,+ queryEventsCore,+} from '../../../event/event.service';+import {+ findProfilesCore,+ getProfileById,+} from '../../../profile/profile.service';+import { getSessionById } from '../../../session/session.service';+import type { ChatToolContext } from '../context';+import { dashboardUrl } from './shared';++const PROFILE_LIMIT = 10;+const EVENT_LIMIT = 10;+const MAX_EVENT_NAME_MATCHES = 15;++interface ProfileHit {+ id: string;+ email: string;+ name: string;+ lastSeen: string;+ url: string;+}++export function searchTools(ctx: ChatToolContext) {+ const { deps, projectId } = ctx;++ return {+ search: tool({+ description:+ 'Find what a pasted id, email, name, path or word refers to. Looks across profile ids, emails and names, session ids, event names and recent events on a path, and links each hit to the dashboard. Use it whenever the user pastes something that looks like an identifier.',+ inputSchema: z.object({ query: z.string().min(1) }),+ execute: async ({ query }) => {+ const trimmed = query.trim();+ const looksLikePath = trimmed.startsWith('/');+ const [byId, byEmail, byName, session, names, pathEvents] =+ await Promise.all([+ getProfileById(deps, trimmed, projectId).catch(() => null),+ findProfilesCore(deps, {+ projectId,+ email: trimmed,+ limit: PROFILE_LIMIT,+ }).catch(() => []),+ findProfilesCore(deps, {+ projectId,+ name: trimmed,+ limit: PROFILE_LIMIT,+ }).catch(() => []),+ getSessionById(deps, trimmed, projectId).catch(() => null),+ listEventNamesCore(deps, projectId).catch(() => []),+ looksLikePath+ ? queryEventsCore(deps, {+ projectId,+ path: trimmed,+ limit: EVENT_LIMIT,+ }).catch(() => [])+ : Promise.resolve([]),+ ]);++ const seen = new Set<string>();+ const profiles: ProfileHit[] = [];+ const addProfile = (hit: ProfileHit) => {+ if (!seen.has(hit.id)) {+ seen.add(hit.id);+ profiles.push(hit);+ }+ };+ if (byId) {+ addProfile({+ id: byId.id,+ email: byId.email,+ name: `${byId.firstName} ${byId.lastName}`.trim(),+ lastSeen: byId.lastSeenAt.toISOString(),+ url: dashboardUrl(ctx, `/profiles/${byId.id}`),+ });+ }+ for (const profile of [...byEmail, ...byName]) {+ addProfile({+ id: profile.id,+ email: profile.email,+ name: `${profile.first_name} ${profile.last_name}`.trim(),+ lastSeen: profile.last_seen_at,+ url: dashboardUrl(ctx, `/profiles/${profile.id}`),+ });+ }+ const lowered = trimmed.toLowerCase();+ const eventNames = names+ .filter((name) => name.toLowerCase().includes(lowered))+ .slice(0, MAX_EVENT_NAME_MATCHES);++ return {+ query: trimmed,+ profiles,+ session: session+ ? { ...session, url: dashboardUrl(ctx, `/sessions/${trimmed}`) }+ : null,+ eventNames,+ pathEvents,+ };+ },+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/seo.ts b/packages/core/src/modules/assistant/src/tools/seo.tsindex ba2d7be51..656890990 100644--- a/packages/core/src/modules/assistant/src/tools/seo.ts+++ b/packages/core/src/modules/assistant/src/tools/seo.ts@@ -1,291 +1,110 @@+import { tool } from 'ai';import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';import {gscGetCannibalizationCore,gscGetOverviewCore,- gscGetPageDetailsCore,- gscGetQueryDetailsCore,gscGetQueryOpportunitiesCore,gscGetTopPagesCore,gscGetTopQueriesCore,} from '../../../gsc/gsc.service';-import { getTopPagesCore } from '../../../overview/pages.service';-import { chatTool, resolveDateRange, truncateRows } from './helpers';+import type { ChatToolContext } from '../context';+import { resolveRange, toDateOnly, truncateRows } from './shared';-/** `YYYY-MM-DD`. */-const DATE_ONLY_LENGTH = 10;+const DEFAULT_LIMIT = 50;+const MAX_LIMIT = 200;-/**- * The GSC tables store `date` as a ClickHouse `Date`, so the datetime bounds- * `resolveDateRange` returns for the event and session tables are refused here- * ("Cannot convert string ... to type Date").- */-function toGscRange(range: { startDate: string; endDate: string }) {- return {- startDate: range.startDate.slice(0, DATE_ONLY_LENGTH),- endDate: range.endDate.slice(0, DATE_ONLY_LENGTH),- };-}--export const gscGetOverview = (deps: ServiceDeps) =>- chatTool(- {- name: 'gsc_get_overview',- description:- 'GSC performance over time — clicks, impressions, CTR, average position. Returns a daily/weekly/monthly time series plus totals.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- interval: z.enum(['day', 'week', 'month']).default('day').optional(),- }),- },- async ({ startDate, endDate, interval }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetOverviewCore(deps, {- projectId: context.projectId,- ...toGscRange(range),- interval,- });- }- );+const zOptionalRange = {+ startDate: z.string().optional().describe('YYYY-MM-DD'),+ endDate: z.string().optional().describe('YYYY-MM-DD'),+};-export const gscGetTopQueries = (deps: ServiceDeps) =>- chatTool(- {- name: 'gsc_get_top_queries',- description:- 'Top search queries by clicks. Returns query, clicks, impressions, CTR, position.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- limit: z.number().min(1).max(500).default(50).optional(),- }),- },- async ({ startDate, endDate, limit }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- const rows = await gscGetTopQueriesCore(deps, {- projectId: context.projectId,- ...toGscRange(range),- limit: limit ?? 50,- });- return truncateRows(rows, 100);- }- );--export const gscGetTopPages = (deps: ServiceDeps) =>- chatTool(- {- name: 'gsc_get_top_pages',- description:- 'Top pages by GSC clicks. Returns page URL, clicks, impressions, CTR, position.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- limit: z.number().min(1).max(500).default(50).optional(),- }),- },- async ({ startDate, endDate, limit }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- const rows = await gscGetTopPagesCore(deps, {- projectId: context.projectId,- ...toGscRange(range),- limit: limit ?? 50,- });- return truncateRows(rows, 100);- }- );+export function seoTools(ctx: ChatToolContext) {+ const { deps, projectId } = ctx;+ // GSC stores plain dates; datetime bounds are refused.+ const gscRange = (input: { startDate?: string; endDate?: string }) => {+ const range = resolveRange(ctx, input);+ return {+ startDate: toDateOnly(range.startDate),+ endDate: toDateOnly(range.endDate),+ };+ };-export const gscGetQueryDetails = (deps: ServiceDeps) =>- chatTool(- {- name: 'gsc_get_query_details',+ return {+ gsc_overview: tool({description:- 'Time-series + page list for a single query. Use after gsc_get_top_queries to drill into one query.',- schema: z.object({- query: z.string(),- startDate: z.string().optional(),- endDate: z.string().optional(),+ 'Google Search Console totals and trend: clicks, impressions, CTR and average position. Needs the GSC integration; an error means it is not connected.',+ inputSchema: z.object({+ ...zOptionalRange,+ interval: z.enum(['day', 'week', 'month']).default('day'),}),- },- async ({ query, startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetQueryDetailsCore(deps, {- projectId: context.projectId,- ...toGscRange(range),- query,- });- }- );+ execute: ({ startDate, endDate, interval }) =>+ gscGetOverviewCore(deps, {+ projectId,+ ...gscRange({ startDate, endDate }),+ interval,+ }),+ }),-export const gscGetPageDetails = (deps: ServiceDeps) =>- chatTool(- {- name: 'gsc_get_page_details',+ gsc_top_queries: tool({description:- 'Time-series + ranking queries for a single page URL. Use after gsc_get_top_pages.',- schema: z.object({- page: z.string().describe('Full page URL'),- startDate: z.string().optional(),- endDate: z.string().optional(),+ 'Top Google search queries by clicks with impressions, CTR and position.',+ inputSchema: z.object({+ ...zOptionalRange,+ limit: z.number().int().min(1).max(MAX_LIMIT).default(DEFAULT_LIMIT),}),- },- async ({ page, startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetPageDetailsCore(deps, {- projectId: context.projectId,- ...toGscRange(range),- page,- });- }- );+ execute: async ({ startDate, endDate, limit }) =>+ truncateRows(+ await gscGetTopQueriesCore(deps, {+ projectId,+ ...gscRange({ startDate, endDate }),+ limit,+ }),+ limit+ ),+ }),-export const gscGetQueryOpportunities = (deps: ServiceDeps) =>- chatTool(- {- name: 'gsc_get_query_opportunities',+ gsc_top_pages: tool({description:- 'Find low-hanging SEO fruit — queries ranking position 4-20 with high impressions but low clicks. Returns each opportunity with a score and reason.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- minImpressions: z.number().min(1).default(50).optional(),+ 'Top pages in Google search by clicks with impressions, CTR and position.',+ inputSchema: z.object({+ ...zOptionalRange,+ limit: z.number().int().min(1).max(MAX_LIMIT).default(DEFAULT_LIMIT),}),- },- async ({ startDate, endDate, minImpressions }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetQueryOpportunitiesCore(deps, {- projectId: context.projectId,- ...toGscRange(range),- minImpressions,- });- }- );+ execute: async ({ startDate, endDate, limit }) =>+ truncateRows(+ await gscGetTopPagesCore(deps, {+ projectId,+ ...gscRange({ startDate, endDate }),+ limit,+ }),+ limit+ ),+ }),-export const gscGetCannibalization = (deps: ServiceDeps) =>- chatTool(- {- name: 'gsc_get_cannibalization',+ gsc_opportunities: tool({description:- 'Find queries where multiple pages from the same site compete for the same ranking. Each result shows the query and the competing pages.',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),+ 'Queries with many impressions but a weak position or CTR: the quickest SEO wins.',+ inputSchema: z.object({+ ...zOptionalRange,+ minImpressions: z.number().int().min(1).optional(),}),- },- async ({ startDate, endDate }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });- return gscGetCannibalizationCore(deps, {- projectId: context.projectId,- ...toGscRange(range),- });- }- );+ execute: ({ startDate, endDate, minImpressions }) =>+ gscGetQueryOpportunitiesCore(deps, {+ projectId,+ ...gscRange({ startDate, endDate }),+ minImpressions,+ }),+ }),-export const correlateSeoWithTraffic = (deps: ServiceDeps) =>- chatTool(- {- name: 'correlate_seo_with_traffic',+ gsc_cannibalization: tool({description:- 'Combine GSC clicks with OpenPanel session data per page. Identifies pages with high SEO traffic but poor conversion (high bounce or low engagement). Run this when the user wants to know "which SEO pages aren\'t converting".',- schema: z.object({- startDate: z.string().optional(),- endDate: z.string().optional(),- limit: z.number().min(1).max(100).default(30).optional(),- }),- },- async ({ startDate, endDate, limit }, context) => {- const range = resolveDateRange({- ...context.pageContext?.filters,- startDate: startDate ?? context.pageContext?.filters?.startDate,- endDate: endDate ?? context.pageContext?.filters?.endDate,- });-- const [gscPages, opPages] = await Promise.all([- gscGetTopPagesCore(deps, {- projectId: context.projectId,- ...toGscRange(range),- limit: 200,- }),- getTopPagesCore(deps, {- projectId: context.projectId,- startDate: range.startDate,- endDate: range.endDate,- limit: 200,+ 'Queries where several of your pages compete against each other in Google.',+ inputSchema: z.object(zOptionalRange),+ execute: ({ startDate, endDate }) =>+ gscGetCannibalizationCore(deps, {+ projectId,+ ...gscRange({ startDate, endDate }),}),- ]);-- // The two functions return different row shapes; these types cover the- // fields read.- type OpPage = {- name?: string;- path?: string;- sessions?: number;- bounce_rate?: number;- avg_duration?: number;- };- type GscPage = {- page: string;- clicks: number;- impressions: number;- ctr: number;- position: number;- };-- const opByPath = new Map<string, OpPage>();- for (const p of opPages as OpPage[]) {- const key = String(p.name ?? p.path ?? '');- opByPath.set(key, p);- opByPath.set(key.replace(/\/$/, ''), p);- }-- const correlated = (gscPages as GscPage[])- .map((g) => {- const pathOnly = g.page.replace(/^https?:\/\/[^/]+/, '');- const op =- opByPath.get(pathOnly) ?? opByPath.get(pathOnly.replace(/\/$/, ''));- return {- page: g.page,- gsc_clicks: g.clicks,- gsc_impressions: g.impressions,- gsc_ctr: g.ctr,- gsc_position: g.position,- op_sessions: op?.sessions ?? null,- op_bounce_rate: op?.bounce_rate ?? null,- op_avg_duration: op?.avg_duration ?? null,- underperforming:- (op?.bounce_rate ?? 0) > 70 || (op?.avg_duration ?? 99) < 1,- };- })- .sort((a, b) => b.gsc_clicks - a.gsc_clicks);-- return truncateRows(correlated, limit ?? 30);- }- );+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/session.ts b/packages/core/src/modules/assistant/src/tools/session.tsdeleted file mode 100644index 824cbcd5e..000000000--- a/packages/core/src/modules/assistant/src/tools/session.ts+++ /dev/null@@ -1,292 +0,0 @@-import { z } from 'zod';-import type { ServiceDeps } from '../../../../services';-import { queryEventsCore } from '../../../event/event.service';-import {- getSessionById,- querySessionsCore,-} from '../../../session/session.service';-import { chatTool, dashboardUrl, truncateRows } from './helpers';--/** How many same-referrer sessions `get_session_referrer_context` samples. */-const REFERRER_SAMPLE_LIMIT = 20;-/** How many of that sample are returned in full. */-const REFERRER_SAMPLE_DETAIL_COUNT = 5;--export const getSessionFull = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_session_full',- description:- 'One-shot session deep dive: session data + ordered events + path. CALL THIS FIRST for "what happened in this session".',- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const [session, events] = await Promise.all([- getSessionById(deps, id, context.projectId),- queryEventsCore(deps, {- projectId: context.projectId,- sessionId: id,- limit: 100,- }),- ]);-- const screenViews = events- .filter((e) => e.name === 'screen_view' && e.path)- .map((e) => ({ path: e.path, created_at: e.created_at }));-- return {- session,- event_count: events.length,- path_length: screenViews.length,- path: screenViews,- events: events.slice(0, 50),- dashboard_url: dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- `/sessions/${id}`- ),- };- }- );--export const getSessionPath = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_session_path',- description: 'The chronological list of pages visited in this session.',- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const events = await queryEventsCore(deps, {- projectId: context.projectId,- sessionId: id,- eventNames: ['screen_view'],- limit: 100,- });- const path = events- .filter((e) => e.path)- .map((e) => ({- path: e.path,- origin: e.origin,- created_at: e.created_at,- }));- return { sessionId: id, page_count: path.length, path };- }- );--export const getSessionEvents = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_session_events',- description:- 'All events in this session, optionally filtered by event name.',- schema: z.object({- sessionId: z.string().optional(),- eventNames: z.array(z.string()).optional(),- }),- },- async ({ sessionId, eventNames }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const events = await queryEventsCore(deps, {- projectId: context.projectId,- sessionId: id,- eventNames,- limit: 100,- });- return truncateRows(events, 100);- }- );--export const getSimilarSessions = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_similar_sessions',- description:- 'Find sessions with the same device + country as this one. Returns up to 10. The reference session\'s entry path is reported back for context but is NOT used as a match criterion. Useful for "is this typical?" questions.',- schema: z.object({- sessionId: z.string().optional(),- limit: z.number().min(1).max(20).default(10).optional(),- }),- },- async ({ sessionId, limit }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const session = await getSessionById(deps, id, context.projectId);-- const similar = await querySessionsCore(deps, {- projectId: context.projectId,- country: session.country ?? undefined,- device: session.device ?? undefined,- limit: (limit ?? 10) + 1,- });- const filtered = similar.filter((s) => s.id !== id).slice(0, limit ?? 10);-- return {- reference: {- id: session.id,- country: session.country,- device: session.device,- entryPath: session.entryPath,- },- similar_sessions: filtered.map((s) => ({- ...s,- dashboard_url: dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- `/sessions/${s.id}`- ),- })),- };- }- );--export const compareSessionToTypical = (deps: ServiceDeps) =>- chatTool(- {- name: 'compare_session_to_typical',- description:- "Compare this session's duration / event count / screen views against the project averages. Helps spot outliers.",- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const session = await getSessionById(deps, id, context.projectId);-- const sample = await querySessionsCore(deps, {- projectId: context.projectId,- limit: 100,- });- if (sample.length === 0) {- return { session, comparison: null };- }-- const avg = (sel: (s: (typeof sample)[number]) => number) =>- sample.reduce((s, sess) => s + sel(sess), 0) / sample.length;-- const project_avg = {- duration: avg((s) => s.duration),- event_count: avg((s) => s.event_count),- screen_view_count: avg((s) => s.screen_view_count),- };-- const ratio = (a: number, b: number) => {- if (b === 0) {- return { ratio: 0, label: 'equal' as const };- }- const r = a / b;- return {- ratio: Number(r.toFixed(2)),- label:- r > 1.05- ? ('above' as const)- : r < 0.95- ? ('below' as const)- : ('equal' as const),- };- };-- return {- session: {- id: session.id,- duration: session.duration,- event_count: session.eventCount,- screen_view_count: session.screenViewCount,- is_bounce: session.isBounce,- },- project_avg,- comparison: {- duration: ratio(session.duration, project_avg.duration),- event_count: ratio(session.eventCount, project_avg.event_count),- screen_view_count: ratio(- session.screenViewCount,- project_avg.screen_view_count- ),- },- sample_size: sample.length,- };- }- );--export const getSessionReferrerContext = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_session_referrer_context',- description: `Context about how the user arrived: a sample of up to ${REFERRER_SAMPLE_LIMIT} recent sessions from the same referrer, across all time (not the current date range), plus a few of them in full. \`sampled_from_referrer\` is that sample size, NOT a project total — never quote it as one.`,- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const session = await getSessionById(deps, id, context.projectId);-- if (!(session.referrer || session.referrerName)) {- return {- session_id: id,- referrer: null,- note: 'This session has no referrer (direct traffic).',- };- }-- const fromSameReferrer = await querySessionsCore(deps, {- projectId: context.projectId,- referrerName: session.referrerName ?? undefined,- limit: REFERRER_SAMPLE_LIMIT,- });-- return {- session_id: id,- referrer: session.referrer,- referrer_name: session.referrerName,- referrer_type: session.referrerType,- sampled_from_referrer: fromSameReferrer.length,- sample_limit: REFERRER_SAMPLE_LIMIT,- sample_sessions: fromSameReferrer- .slice(0, REFERRER_SAMPLE_DETAIL_COUNT)- .map((s) => ({- id: s.id,- created_at: s.created_at,- country: s.country,- is_bounce: s.is_bounce,- entry_path: s.entry_path,- })),- };- }- );--export const getSessionReplaySummary = (deps: ServiceDeps) =>- chatTool(- {- name: 'get_session_replay_summary',- description:- 'Whether this session has a recorded replay available. Returns metadata if so. If no replay, returns { available: false }.',- schema: z.object({- sessionId: z.string().optional(),- }),- },- async ({ sessionId }, context) => {- const id = sessionId || context.pageContext?.ids?.sessionId || '';- const session = await getSessionById(deps, id, context.projectId);- return {- session_id: id,- available: session.hasReplay,- replay_url: session.hasReplay- ? dashboardUrl(- deps.config,- context.organizationId,- context.projectId,- `/sessions/${id}`- )- : null,- };- }- );diff --git a/packages/core/src/modules/assistant/src/tools/shared.ts b/packages/core/src/modules/assistant/src/tools/shared.tsnew file mode 100644index 000000000..85449b467--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/shared.ts@@ -0,0 +1,105 @@+import { resolveDateRange as resolveDateRangeCore } from '@openpanel/shared';+import type { IChartRange } from '../../../report/report.constants';+import { timeWindows } from '../../../report/report.constants';+import { getDatesFromRange } from '../../../report/src/chart-dates';+import type { ChatToolContext } from '../context';++/** `YYYY-MM-DD`. */+export const DATE_ONLY_LENGTH = 10;+const DEFAULT_ROW_LIMIT = 50;++const PRESET_RANGES: ReadonlySet<string> = new Set(+ Object.keys(timeWindows).filter((key) => key !== 'custom')+);++/**+ * Explicit dates win, then the window the user was looking at when the chat+ * was opened, then the last 30 days.+ */+export function resolveRange(+ ctx: ChatToolContext,+ input: { startDate?: string; endDate?: string } = {}+): { startDate: string; endDate: string } {+ if (input.startDate || input.endDate) {+ return resolveDateRangeCore(input.startDate, input.endDate);+ }+ const hint = ctx.hint;+ if (hint?.startDate || hint?.endDate) {+ return resolveDateRangeCore(hint.startDate, hint.endDate);+ }+ if (hint?.range && PRESET_RANGES.has(hint.range)) {+ return getDatesFromRange(hint.range as IChartRange, ctx.timezone);+ }+ return resolveDateRangeCore(undefined, undefined);+}++export function toDateOnly(value: string): string {+ return value.slice(0, DATE_ONLY_LENGTH);+}++/** Cap rows and say so, so the model knows there is more. */+export function truncateRows<T>(+ rows: T[],+ max = DEFAULT_ROW_LIMIT+): { rows: T[]; total: number; truncated: boolean } {+ if (rows.length <= max) {+ return { rows, total: rows.length, truncated: false };+ }+ return { rows: rows.slice(0, max), total: rows.length, truncated: true };+}++const DEFAULT_DASHBOARD_URL = 'http://localhost:3000';+const TRAILING_SLASH = /\/$/;++export function dashboardUrl(ctx: ChatToolContext, path = ''): string {+ const base = (ctx.config.dashboardUrl || DEFAULT_DASHBOARD_URL).replace(+ TRAILING_SLASH,+ ''+ );+ return `${base}/${ctx.organizationId}/${ctx.projectId}${path}`;+}++/**+ * Property keys for the model: dotted keys collapse to their root, ordered by+ * how many keys roll up under them, so dynamic `__query.<uuid>` noise cannot+ * push `country` out of the list.+ */+export function compactPropertyKeys(+ rows: Array<{ property_key: string }>,+ max = DEFAULT_ROW_LIMIT+): { properties: string[]; total: number; truncated: boolean } {+ const counts = new Map<string, number>();+ for (const row of rows) {+ const dot = row.property_key.indexOf('.');+ const root = dot >= 0 ? row.property_key.slice(0, dot) : row.property_key;+ counts.set(root, (counts.get(root) ?? 0) + 1);+ }+ const sorted = Array.from(counts.entries())+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))+ .map(([key]) => key);+ return {+ properties: sorted.slice(0, max),+ total: sorted.length,+ truncated: sorted.length > max,+ };+}++export function errorResult(+ message: string,+ extra: Record<string, unknown> = {}+) {+ return { error: message, ...extra };+}++const CENTS_PER_UNIT = 100;++/** Revenue is stored in minor units (cents); the chat talks in currency units like the dashboard. */+export function revenueToUnits<T extends { revenue?: number | null }>(+ rows: T[]+): T[] {+ return rows.map((row) =>+ typeof row.revenue === 'number'+ ? { ...row, revenue: row.revenue / CENTS_PER_UNIT }+ : row+ );+}diff --git a/packages/core/src/modules/assistant/src/tools/tracking.test.ts b/packages/core/src/modules/assistant/src/tools/tracking.test.tsnew file mode 100644index 000000000..d7798a892--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/tracking.test.ts@@ -0,0 +1,113 @@+import { describe, expect, test } from 'bun:test';+import { assessTracking, type TrackingFacts } from './tracking';++const CLIENT = 'a6d8af68-dfdb-4794-baac-809f503fb7bf';++function facts(overrides: Partial<TrackingFacts> = {}): TrackingFacts {+ return {+ requestedUrl: 'https://acme.test',+ storedDomain: 'https://acme.test',+ pageOrigin: 'https://acme.test',+ fetch: { ok: true, status: 200, finalUrl: 'https://acme.test/' },+ snippet: {+ scriptTag: true,+ initCall: true,+ sdkPackage: false,+ clientIds: [CLIENT],+ },+ projectClients: [+ { id: CLIENT, name: 'Web', type: 'write', ignoreCorsAndSecret: false },+ ],+ foreignClients: [],+ cors: ['https://acme.test'],+ crossDomain: false,+ filters: { event: [], ip: 0, profile: 0 },+ firstEventAt: '2026-10-01T00:00:00.000Z',+ lastEventAt: '2026-10-19 12:00:00',+ recentByOrigin: [+ {+ origin: 'https://acme.test',+ count: 120,+ lastSeen: '2026-10-19 12:00:00',+ },+ ],+ ...overrides,+ };+}++const levels = (findings: ReturnType<typeof assessTracking>, check: string) =>+ findings+ .filter((finding) => finding.check === check)+ .map((finding) => finding.level);++describe('assessTracking', () => {+ test('a correct install is all green', () => {+ const findings = assessTracking(facts());+ expect(findings.every((finding) => finding.level === 'ok')).toBe(true);+ });++ test('a client id from another project is an error', () => {+ const findings = assessTracking(+ facts({+ snippet: {+ scriptTag: true,+ initCall: true,+ sdkPackage: false,+ clientIds: ['11111111-1111-4111-8111-111111111111'],+ },+ foreignClients: [+ { id: '11111111-1111-4111-8111-111111111111', projectId: 'other' },+ ],+ })+ );+ expect(levels(findings, 'clientId')).toEqual(['error']);+ expect(+ findings.find((finding) => finding.check === 'clientId')?.message+ ).toContain('another project');+ });++ test('an origin outside the allowed list is an error, a wildcard is fine', () => {+ expect(+ levels(assessTracking(facts({ cors: ['https://other.test'] })), 'cors')+ ).toEqual(['error']);+ expect(levels(assessTracking(facts({ cors: ['*'] })), 'cors')).toEqual([+ 'ok',+ ]);+ expect(levels(assessTracking(facts({ cors: [] })), 'cors')).toEqual([+ 'error',+ ]);+ });++ test('a missing snippet is a warning, not an error', () => {+ const findings = assessTracking(+ facts({+ snippet: {+ scriptTag: false,+ initCall: false,+ sdkPackage: false,+ clientIds: [],+ },+ })+ );+ expect(levels(findings, 'snippet')).toEqual(['warn']);+ });++ test('traffic from other origins but not this one is called out', () => {+ const findings = assessTracking(+ facts({+ recentByOrigin: [+ { origin: 'https://staging.acme.test', count: 5, lastSeen: 'x' },+ ],+ })+ );+ const data = findings.find((finding) => finding.check === 'data');+ expect(data?.level).toBe('warn');+ expect(data?.message).toContain('staging.acme.test');+ });++ test('a project without any event ever is an error', () => {+ expect(+ levels(assessTracking(facts({ firstEventAt: null })), 'data')+ ).toEqual(['error']);+ });+});diff --git a/packages/core/src/modules/assistant/src/tools/tracking.ts b/packages/core/src/modules/assistant/src/tools/tracking.tsnew file mode 100644index 000000000..dd6743a8a--- /dev/null+++ b/packages/core/src/modules/assistant/src/tools/tracking.ts@@ -0,0 +1,462 @@+import { sql } from '@openpanel/db/src/clickhouse/sql';+import { safeFetch } from '@openpanel/shared/server';+import { tool } from 'ai';+import { z } from 'zod';+import { chQuery } from '../../../../ch-query';+import { getMemberProjectGrants } from '../../../../shared/access-lookups';+import { isOriginAllowed } from '../../../../shared/origin-allowed';+import type { ChatToolContext } from '../context';+import { dashboardUrl } from './shared';++const FETCH_TIMEOUT_MS = 10_000;+const MAX_HTML_BYTES = 2_000_000;+// Mirrored literally in the ClickHouse query below.+const RECENT_WINDOW_DAYS = 1;+const HTTP_ERROR = 400;++const SCRIPT_URL = /openpanel\.dev\/op1\.js|\/op1\.js\b/i;+const INIT_CALL = /\bop\(\s*['"]init['"]/;+const SDK_PACKAGE = /@openpanel\/(web|nextjs|react|vue|nuxt|remix|astro|sdk)/;+const CLIENT_ID =+ /client[_-]?id['"]?\s*[:=]\s*['"]([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})['"]/gi;++export type FindingLevel = 'ok' | 'warn' | 'error' | 'info';++export interface Finding {+ level: FindingLevel;+ /** Stable key so the UI and tests can refer to a check. */+ check: string;+ message: string;+}++export interface TrackingFacts {+ requestedUrl: string;+ storedDomain: string | null;+ pageOrigin: string | null;+ fetch: { ok: boolean; status?: number; finalUrl?: string; error?: string };+ snippet: {+ scriptTag: boolean;+ initCall: boolean;+ sdkPackage: boolean;+ clientIds: string[];+ };+ projectClients: {+ id: string;+ name: string;+ type: string;+ ignoreCorsAndSecret: boolean;+ }[];+ /** Where a found client id actually belongs, when not to this project. */+ foreignClients: { id: string; projectId: string | null }[];+ cors: string[];+ crossDomain: boolean;+ filters: { event: string[]; ip: number; profile: number };+ firstEventAt: string | null;+ lastEventAt: string | null;+ recentByOrigin: { origin: string; count: number; lastSeen: string }[];+}++function originOf(url: string): string | null {+ try {+ return new URL(url).origin;+ } catch {+ return null;+ }+}++function normalizeUrl(input: string): string {+ const trimmed = input.trim();+ return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;+}++/** Turns the gathered facts into the checklist the user sees and the model explains. */+export function assessTracking(facts: TrackingFacts): Finding[] {+ const findings: Finding[] = [];+ const pageHost = facts.pageOrigin ? new URL(facts.pageOrigin).host : null;+ const storedHost = facts.storedDomain ? originOf(facts.storedDomain) : null;++ if (+ facts.storedDomain &&+ pageHost &&+ storedHost &&+ new URL(storedHost).host !== pageHost+ ) {+ findings.push({+ level: 'warn',+ check: 'domain',+ message: `The project's domain is ${facts.storedDomain}, but this check ran against ${facts.pageOrigin}.`,+ });+ } else if (facts.storedDomain) {+ findings.push({+ level: 'ok',+ check: 'domain',+ message: `Project domain ${facts.storedDomain} matches the page.`,+ });+ } else {+ findings.push({+ level: 'info',+ check: 'domain',+ message:+ 'The project has no domain set; that is fine, it only drives defaults.',+ });+ }++ if (!facts.fetch.ok) {+ findings.push({+ level: 'error',+ check: 'fetch',+ message: `Could not load the page${facts.fetch.status ? ` (HTTP ${facts.fetch.status})` : ''}${facts.fetch.error ? `: ${facts.fetch.error}` : '.'}`,+ });+ }++ const { snippet } = facts;+ if (facts.fetch.ok) {+ if (snippet.scriptTag || snippet.initCall) {+ findings.push({+ level: 'ok',+ check: 'snippet',+ message: 'The OpenPanel snippet is on the page.',+ });+ } else if (snippet.sdkPackage) {+ findings.push({+ level: 'ok',+ check: 'snippet',+ message: 'An OpenPanel SDK package is referenced by the page.',+ });+ } else {+ findings.push({+ level: 'warn',+ check: 'snippet',+ message:+ 'No OpenPanel snippet was found in the HTML. A framework SDK loaded from a JavaScript bundle is not visible here, so this is only a problem if the site uses the script tag.',+ });+ }+ }++ if (snippet.clientIds.length === 0) {+ if (facts.fetch.ok) {+ findings.push({+ level: 'info',+ check: 'clientId',+ message: 'No client id is visible in the HTML.',+ });+ }+ } else {+ for (const id of snippet.clientIds) {+ const own = facts.projectClients.find((client) => client.id === id);+ if (own) {+ findings.push({+ level: 'ok',+ check: 'clientId',+ message: `Client id ${id} is "${own.name}" (${own.type}) in this project.`,+ });+ continue;+ }+ const foreign = facts.foreignClients.find((client) => client.id === id);+ findings.push({+ level: 'error',+ check: 'clientId',+ message: foreign+ ? `Client id ${id} belongs to another project${foreign.projectId ? ` (${foreign.projectId})` : ''}, so its events land there, not here.`+ : `Client id ${id} does not exist. Events sent with it are rejected.`,+ });+ }+ }++ const pageClient = snippet.clientIds+ .map((id) => facts.projectClients.find((client) => client.id === id))+ .find(Boolean);+ if (pageClient?.ignoreCorsAndSecret) {+ findings.push({+ level: 'ok',+ check: 'cors',+ message: `Client "${pageClient.name}" skips the origin check.`,+ });+ } else if (facts.cors.length === 0) {+ findings.push({+ level: 'error',+ check: 'cors',+ message:+ 'No allowed origins are set. Browser events without a client secret are rejected; add the site origin (or * for any) under project settings.',+ });+ } else if (+ facts.pageOrigin &&+ isOriginAllowed(facts.cors, facts.pageOrigin)+ ) {+ findings.push({+ level: 'ok',+ check: 'cors',+ message: `${facts.pageOrigin} is an allowed origin.`,+ });+ } else if (facts.pageOrigin) {+ findings.push({+ level: 'error',+ check: 'cors',+ message: `${facts.pageOrigin} is not in the allowed origins (${facts.cors.join(', ')}). Browser events from it are rejected.`,+ });+ }++ if (facts.filters.event.length > 0) {+ findings.push({+ level: 'info',+ check: 'filters',+ message: `Events matching these filters are dropped on arrival: ${facts.filters.event.join(', ')}.`,+ });+ }+ if (facts.filters.ip > 0 || facts.filters.profile > 0) {+ findings.push({+ level: 'info',+ check: 'filters',+ message: `${facts.filters.ip} IP filter(s) and ${facts.filters.profile} profile filter(s) also drop events.`,+ });+ }++ if (!facts.firstEventAt) {+ findings.push({+ level: 'error',+ check: 'data',+ message: 'This project has never received an event.',+ });+ } else if (facts.recentByOrigin.length === 0) {+ findings.push({+ level: 'warn',+ check: 'data',+ message: `No page views in the last ${RECENT_WINDOW_DAYS * 24} hours. The last event arrived ${facts.lastEventAt ?? 'at an unknown time'}.`,+ });+ } else {+ const fromPage = facts.pageOrigin+ ? facts.recentByOrigin.find((row) => row.origin === facts.pageOrigin)+ : undefined;+ if (fromPage) {+ findings.push({+ level: 'ok',+ check: 'data',+ message: `${fromPage.count} page views arrived from ${fromPage.origin} in the last 24 hours, the latest at ${fromPage.lastSeen}.`,+ });+ } else {+ const others = facts.recentByOrigin+ .slice(0, 3)+ .map((row) => `${row.origin || '(no origin)'}: ${row.count}`)+ .join(', ');+ findings.push({+ level: facts.pageOrigin ? 'warn' : 'info',+ check: 'data',+ message: facts.pageOrigin+ ? `No page views from ${facts.pageOrigin} in the last 24 hours, while other origins sent some (${others}).`+ : `Page views in the last 24 hours by origin: ${others}.`,+ });+ }+ }++ return findings;+}++async function fetchPage(+ url: string+): Promise<{ fetch: TrackingFacts['fetch']; html: string }> {+ try {+ const result = await safeFetch(url, {+ timeoutMs: FETCH_TIMEOUT_MS,+ maxBytes: MAX_HTML_BYTES,+ headers: { 'user-agent': 'OpenPanel tracking check' },+ });+ const html = result.body.toString('utf8');+ return {+ fetch: {+ ok: result.status < HTTP_ERROR,+ status: result.status,+ finalUrl: result.finalUrl,+ },+ html,+ };+ } catch (error) {+ return {+ fetch: {+ ok: false,+ error: error instanceof Error ? error.message : 'unknown error',+ },+ html: '',+ };+ }+}++function inspectHtml(html: string): TrackingFacts['snippet'] {+ const clientIds = new Set<string>();+ for (const match of html.matchAll(CLIENT_ID)) {+ const id = match[1];+ if (id) {+ clientIds.add(id.toLowerCase());+ }+ }+ return {+ scriptTag: SCRIPT_URL.test(html),+ initCall: INIT_CALL.test(html),+ sdkPackage: SDK_PACKAGE.test(html),+ clientIds: [...clientIds],+ };+}++async function recentPageViews(ctx: ChatToolContext) {+ const rows = await chQuery<{+ origin: string;+ count: string;+ last_seen: string;+ }>(+ ctx.deps,+ sql`SELECT origin, count() AS count, max(created_at) AS last_seen+ FROM events+ WHERE project_id = ${sql.string(ctx.projectId)}+ AND name = 'screen_view'+ AND created_at >= now() - INTERVAL 1 DAY+ GROUP BY origin+ ORDER BY count DESC+ LIMIT 20`+ );+ return rows.map((row) => ({+ origin: row.origin,+ count: Number(row.count),+ lastSeen: row.last_seen,+ }));+}++async function lastEventAt(ctx: ChatToolContext): Promise<string | null> {+ const rows = await chQuery<{ last_event: string | null }>(+ ctx.deps,+ sql`SELECT max(created_at) AS last_event FROM events WHERE project_id = ${sql.string(ctx.projectId)}`+ );+ const value = rows[0]?.last_event;+ return value && !value.startsWith('1970') ? value : null;+}++/**+ * Client ids found on the page that are not this project's. The owning+ * project is named only when the user may open it: a `selected`-scope+ * member must not learn sibling projects from a client id on a web page.+ */+async function findForeignClients(+ ctx: ChatToolContext,+ clientIds: string[]+): Promise<TrackingFacts['foreignClients']> {+ if (clientIds.length === 0) {+ return [];+ }+ const [clients, grants] = await Promise.all([+ ctx.deps.db.client.findMany({+ where: { id: { in: clientIds }, organizationId: ctx.organizationId },+ select: { id: true, projectId: true },+ }),+ getMemberProjectGrants(ctx.deps.db, {+ userId: ctx.userId,+ organizationId: ctx.organizationId,+ }),+ ]);+ const canOpen = (projectId: string | null) =>+ grants?.projectScope === 'all' ||+ (grants?.projects.some((grant) => grant.projectId === projectId) ?? false);+ return clients.map((client) => ({+ id: client.id,+ projectId: canOpen(client.projectId) ? client.projectId : null,+ }));+}++export async function gatherTrackingFacts(+ ctx: ChatToolContext,+ requestedUrl: string+): Promise<TrackingFacts> {+ const project = await ctx.deps.db.project.findUniqueOrThrow({+ where: { id: ctx.projectId },+ select: {+ domain: true,+ cors: true,+ crossDomain: true,+ filters: true,+ firstEventAt: true,+ },+ });+ const [{ fetch, html }, projectClients, recentByOrigin, lastEvent] =+ await Promise.all([+ fetchPage(requestedUrl),+ ctx.deps.db.client.findMany({+ where: { projectId: ctx.projectId },+ select: { id: true, name: true, type: true, ignoreCorsAndSecret: true },+ }),+ recentPageViews(ctx).catch(() => []),+ lastEventAt(ctx).catch(() => null),+ ]);+ const snippet = inspectHtml(html);+ const unknownIds = snippet.clientIds.filter(+ (id) => !projectClients.some((client) => client.id === id)+ );+ const foreignClients = await findForeignClients(ctx, unknownIds);+ const filters = project.filters ?? [];+ return {+ requestedUrl,+ storedDomain: project.domain || null,+ pageOrigin: originOf(fetch.finalUrl ?? requestedUrl),+ fetch,+ snippet,+ projectClients,+ foreignClients,+ cors: project.cors,+ crossDomain: project.crossDomain,+ filters: {+ event: filters+ .filter((filter) => filter.type === 'event')+ .map((filter) => (filter as { name: string }).name),+ ip: filters.filter((filter) => filter.type === 'ip').length,+ profile: filters.filter((filter) => filter.type === 'profile_id').length,+ },+ firstEventAt: project.firstEventAt?.toISOString() ?? null,+ lastEventAt: lastEvent,+ recentByOrigin,+ };+}++export function trackingTools(ctx: ChatToolContext) {+ return {+ diagnose_tracking: tool({+ description:+ "Check why events from a website are not showing up. Loads the page, looks for the OpenPanel snippet and client id, and checks them against this project's clients, allowed origins (CORS), event filters and the page views that actually arrived. Pass the URL the user mentions; without one it uses the project's configured domain, so confirm that domain with the user first when it is unclear.",+ inputSchema: z.object({+ url: z+ .string()+ .optional()+ .describe(+ 'Page to check, e.g. https://example.com. Defaults to the project domain.'+ ),+ }),+ execute: async ({ url }) => {+ const project = await ctx.deps.db.project.findUniqueOrThrow({+ where: { id: ctx.projectId },+ select: { domain: true },+ });+ const target = url?.trim() || project.domain;+ if (!target) {+ return {+ error:+ 'The project has no domain configured and no URL was given. Ask the user which website to check.',+ };+ }+ const facts = await gatherTrackingFacts(ctx, normalizeUrl(target));+ const findings = assessTracking(facts);+ return {+ url: facts.fetch.finalUrl ?? facts.requestedUrl,+ status: findings.some((finding) => finding.level === 'error')+ ? 'issues'+ : findings.some((finding) => finding.level === 'warn')+ ? 'warnings'+ : 'healthy',+ findings,+ clients: facts.projectClients.map((client) => ({+ id: client.id,+ name: client.name,+ type: client.type,+ })),+ allowedOrigins: facts.cors,+ settingsUrl: dashboardUrl(ctx, '/settings'),+ trackingUrl: dashboardUrl(ctx, '/settings/tracking'),+ };+ },+ }),+ };+}diff --git a/packages/core/src/modules/assistant/src/tools/ui.ts b/packages/core/src/modules/assistant/src/tools/ui.tsdeleted file mode 100644index cbe16727e..000000000--- a/packages/core/src/modules/assistant/src/tools/ui.ts+++ /dev/null@@ -1,50 +0,0 @@-import { type AgentToolDefinition, defineTool } from '@better-agent/core';-import type { ServiceDeps } from '../../../../services';-import {- applyFiltersSchema,- setEventNamesFilterSchema,- setPropertyFiltersSchema,-} from '../../assistant.constants';--/**- * Client-side UI-mutator tools: Better Agent emits each call as a `tool-call`- * part with no server execution, and the frontend handles it by updating the- * URL params the dashboard reads. Factories take an unused `_deps` to match the- * other tool buckets.- */--// Cast to `any` before `.client()`: TS otherwise fully instantiates-// `ClientToolDefinition` for the deeply nested Zod schema and trips its-// instantiation depth limit.-// biome-ignore lint/suspicious/noExplicitAny: see comment above-const applyFiltersContract: any = defineTool({- name: 'apply_filters',- description:- "Apply filters to the user's current dashboard page. Use this whenever the user asks to change the date range, interval, or otherwise filter the view (e.g. 'filter to 24-28 May', 'show last 7 days', 'switch to weekly intervals'). Pair with prose like 'Done — showing 24-28 May.' Only one of `range` (a preset) OR `startDate`+`endDate` (a custom range) should be set, not both.",- schema: applyFiltersSchema,-});--export const applyFilters = (_deps: ServiceDeps): AgentToolDefinition =>- applyFiltersContract.client() as AgentToolDefinition;--// biome-ignore lint/suspicious/noExplicitAny: see comment on applyFiltersContract-const setPropertyFiltersContract: any = defineTool({- name: 'set_property_filters',- description:- "Replace the active event-property filter set on the user's current dashboard page (overview, pages, seo, events, insights, profile detail). Use for requests like 'show me referrers from GitHub', 'mobile only', 'filter to Sweden + Germany', or 'add Bing as a referrer' — for the add case, pass the new full list including what's already active (the current filters are in pageContext.filters.eventFilters). Pass an empty array to clear all property filters.",- schema: setPropertyFiltersSchema,-});--export const setPropertyFilters = (_deps: ServiceDeps): AgentToolDefinition =>- setPropertyFiltersContract.client() as AgentToolDefinition;--// biome-ignore lint/suspicious/noExplicitAny: see comment on applyFiltersContract-const setEventNamesFilterContract: any = defineTool({- name: 'set_event_names_filter',- description:- "Restrict the page to specific event names (e.g. 'show me only signups', 'just screen_view + click events'). Pass the FULL list of event names — replaces the current set. Pass an empty array to clear (show all events). Verify event names with list_event_names when unsure.",- schema: setEventNamesFilterSchema,-});--export const setEventNamesFilter = (_deps: ServiceDeps): AgentToolDefinition =>- setEventNamesFilterContract.client() as AgentToolDefinition;diff --git a/packages/core/src/modules/ingest/src/client-auth.ts b/packages/core/src/modules/ingest/src/client-auth.tsindex c741979f2..a18617607 100644--- a/packages/core/src/modules/ingest/src/client-auth.ts+++ b/packages/core/src/modules/ingest/src/client-auth.ts@@ -10,6 +10,7 @@ import { path } from 'ramda';import type { DbScope } from '../../../cacheable-per-deps';import { verifyClientSecret as verifyClientSecretHash } from '../../../shared/client-secret';import { headerValue, type IngestHeaders } from '../../../shared/headers';+import { isOriginAllowed } from '../../../shared/origin-allowed';import {getClientByIdCached,type IServiceClientWithProject,@@ -33,10 +34,6 @@ const verifiedInProcess = new LRUCache<string, true>({ttl: VERIFY_LOCAL_CACHE_TTL_MS,});const REDACTED_SECRET_EDGE_LENGTH = 5;-const DOMAIN_PROTOCOL = /https?:\/\//;-const DOMAIN_TRAILING_SLASH = /\/$/;-const DOMAIN_DOT = /\./g;-const DOMAIN_WILDCARD = /\*/g;export interface IngestAuthErrorPayload {clientId?: string;@@ -73,34 +70,6 @@ export type IngestAuthOutcome =secretVerified: boolean;};-const cleanDomain = (domain: string) =>- domain- .replace('www.', '')- .replace(DOMAIN_PROTOCOL, '')- .replace(DOMAIN_TRAILING_SLASH, '');--function isOriginAllowed(cors: string[], origin: string | undefined): boolean {- const domainAllowed = cors.find((domain) => {- const cleanedDomain = cleanDomain(domain);- // support wildcard domains `*.foo.com`- if (cleanedDomain.includes('*')) {- const regex = new RegExp(- `${cleanedDomain.replace(DOMAIN_DOT, '\\.').replace(DOMAIN_WILDCARD, '.+?')}`- );-- return regex.test(origin || '');- }-- return cleanedDomain === cleanDomain(origin || '');- });-- if (domainAllowed) {- return true;- }-- return cors.includes('*') && !!origin;-}-/*** Only successful verifications are cached: the key embeds the caller-supplied* secret, so caching a negative would let anyone create entries with keys ofdiff --git a/packages/core/src/modules/insight/src/enrich.ts b/packages/core/src/modules/insight/src/enrich.tsindex d4b87dd5f..4310f7a26 100644--- a/packages/core/src/modules/insight/src/enrich.ts+++ b/packages/core/src/modules/insight/src/enrich.ts@@ -1,33 +1,20 @@// Tier-1 insight enrichment: a one-shot OpenAI call that scores and summarizes// insights so the product can filter noise, pick email-worthy items and flag// chart-reference candidates. No persistence: the caller writes results back.-import { betterAgent, defineAgent } from '@better-agent/core';+import { generateText, Output } from 'ai';import { z } from 'zod';import { callProvider } from '../../../clients/provider-error';import type { CoreConfig } from '../../../config';-import { ALLOWED_MODELS, resolveModel } from '../../assistant/src/providers';+import { resolveOpenAITaskModel } from '../../assistant/src/providers';// Bump when the prompt or output shape changes — the worker re-enriches any// insight whose stored enrichVersion is below this.export const ENRICH_VERSION = 1;-// Tier-1 is cheap, fast, non-reasoning work — gpt-4.1-mini is the right tier.-const ENRICH_MODEL_ID = 'gpt-4-1-mini';-// Both the preferred model and the fallback are OpenAI, so every failure this// call classifies is an OpenAI one.const ENRICH_PROVIDER = 'openai';-function enrichModel(config: CoreConfig) {- const entry =- ALLOWED_MODELS.find((m) => m.id === ENRICH_MODEL_ID) ??- ALLOWED_MODELS.find((m) => m.group === 'OpenAI');- if (!entry) {- throw new Error('No OpenAI model available for insight enrichment');- }- return resolveModel(config, entry);-}-export interface InsightToEnrich {id: string;moduleKey: string;@@ -68,10 +55,6 @@ const enrichmentOutputSchema = z.object({),});-const enrichmentOutputJsonSchema = z.toJSONSchema(enrichmentOutputSchema, {- target: 'draft-07',-});-const INSTRUCTION = `You are an analytics insight editor for OpenPanel, a web/product analytics platform.You receive a JSON array of automatically-detected insights about ONE project's traffic. Each has a moduleKey (referrers, entry-pages, page-trends, geo, devices), a dimension, a time window, a statistically-derived title/summary, a direction, an impactScore, and a payload of metrics.@@ -85,31 +68,6 @@ For EACH input insight, produce:Return exactly one result per input insight, preserving each "id" verbatim. Be calibrated and consistent across the batch.`;-let _app: ReturnType<typeof betterAgent> | null = null;-function getApp(config: CoreConfig) {- if (_app) {- return _app;- }- const agent = defineAgent({- name: 'insight-enrich',- description:- 'Scores and summarizes analytics insights (one-shot, no persistence).',- model: enrichModel(config),- contextSchema: z.object({}),- outputSchema: {- schema: enrichmentOutputJsonSchema,- name: 'insight_enrichment',- strict: true,- },- instruction: () => INSTRUCTION,- tools: () => [],- maxSteps: 1,- // biome-ignore lint/suspicious/noExplicitAny: same dodge as filter-command.ts- } as any);- _app = betterAgent({ agents: [agent] });- return _app;-}-/*** Enrich a batch of insights in one model call. Returns one entry per insight* the model scored; the caller maps back by id and missing ids are skipped.@@ -124,13 +82,15 @@ export async function enrichInsights(}const input = JSON.stringify(insights);- const result = (await callProvider(ENRICH_PROVIDER, () =>- getApp(config).run('insight-enrich', {- input,- context: {},- // biome-ignore lint/suspicious/noExplicitAny: same dodge as filter-command.ts- } as any)- )) as { structured?: { results: InsightEnrichment[] } };+ const result = await callProvider(ENRICH_PROVIDER, () =>+ generateText({+ model: resolveOpenAITaskModel(config, 'small'),+ instructions: INSTRUCTION,+ prompt: input,+ reasoning: 'low',+ output: Output.object({ schema: enrichmentOutputSchema }),+ })+ );- return result.structured?.results ?? [];+ return result.output?.results ?? [];}diff --git a/packages/core/src/modules/insight/src/explain.ts b/packages/core/src/modules/insight/src/explain.tsindex 2a0038aea..7169b6a0f 100644--- a/packages/core/src/modules/insight/src/explain.ts+++ b/packages/core/src/modules/insight/src/explain.ts@@ -3,29 +3,15 @@// sub-segment drove the delta and which off-platform event might correlate. It// narrates the internal decomposition, not invented external causes; the caller// gathers the data.-import { betterAgent, defineAgent } from '@better-agent/core';+import { generateText, Output } from 'ai';import { z } from 'zod';import { callProvider } from '../../../clients/provider-error';import type { CoreConfig } from '../../../config';-import { ALLOWED_MODELS, resolveModel } from '../../assistant/src/providers';--// gpt-4.1 (larger, non-reasoning) synthesizes the supplied breakdown well-// without reasoning-option plumbing.-const EXPLAIN_MODEL_ID = 'gpt-4-1';+import { resolveOpenAITaskModel } from '../../assistant/src/providers';// Preferred model and fallback are both OpenAI — see enrich.ts.const EXPLAIN_PROVIDER = 'openai';-function explainModel(config: CoreConfig) {- const entry =- ALLOWED_MODELS.find((m) => m.id === EXPLAIN_MODEL_ID) ??- ALLOWED_MODELS.find((m) => m.group === 'OpenAI');- if (!entry) {- throw new Error('No OpenAI model available for insight explanation');- }- return resolveModel(config, entry);-}-export interface BreakdownComparison {column: string;current: { name: string | null; sessions: number }[];@@ -77,10 +63,6 @@ const explanationSchema = z.object({confidence: z.enum(['low', 'medium', 'high']),});-const explanationJsonSchema = z.toJSONSchema(explanationSchema, {- target: 'draft-07',-});-const INSTRUCTION = `You explain WHY an analytics metric changed for a website/product owner.You receive: the insight (what changed); a dailySeries — the segment's own per-day values for the current window vs the baseline window; a decomposition of the change across dimensions (referrer, country, device, utm_source) as current-vs-baseline session breakdowns; and any manual references (off-platform events the owner logged) near the window.@@ -99,41 +81,19 @@ Produce:Be honest and precise. You can only see what's in the data: explain the shape and the internal decomposition (which segment moved, when), not external causes you can't observe. If the data doesn't clearly explain it, say so and set confidence low. Never invent numbers or dates.`;-let _app: ReturnType<typeof betterAgent> | null = null;-function getApp(config: CoreConfig) {- if (_app) {- return _app;- }- const agent = defineAgent({- name: 'insight-explain',- description: 'Explains why an insight changed (one-shot).',- model: explainModel(config),- contextSchema: z.object({}),- outputSchema: {- schema: explanationJsonSchema,- name: 'insight_explanation',- strict: true,- },- instruction: () => INSTRUCTION,- tools: () => [],- maxSteps: 1,- // biome-ignore lint/suspicious/noExplicitAny: same dodge as enrich.ts- } as any);- _app = betterAgent({ agents: [agent] });- return _app;-}-export async function generateInsightExplanation(config: CoreConfig,input: ExplainInsightInput): Promise<InsightExplanation | null> {- const result = (await callProvider(EXPLAIN_PROVIDER, () =>- getApp(config).run('insight-explain', {- input: JSON.stringify(input),- context: {},- // biome-ignore lint/suspicious/noExplicitAny: same dodge as enrich.ts- } as any)- )) as { structured?: InsightExplanation };+ const result = await callProvider(EXPLAIN_PROVIDER, () =>+ generateText({+ model: resolveOpenAITaskModel(config, 'standard'),+ instructions: INSTRUCTION,+ prompt: JSON.stringify(input),+ reasoning: 'low',+ output: Output.object({ schema: explanationSchema }),+ })+ );- return result.structured ?? null;+ return result.output ?? null;}diff --git a/packages/core/src/modules/insight/src/narrative.ts b/packages/core/src/modules/insight/src/narrative.tsindex d8fc85bf6..27c765b41 100644--- a/packages/core/src/modules/insight/src/narrative.ts+++ b/packages/core/src/modules/insight/src/narrative.ts@@ -1,26 +1,13 @@// Weekly-digest narrative: one short OpenAI call that turns a project's// week-over-week stats and notable insights into an intro paragraph.-import { betterAgent, defineAgent } from '@better-agent/core';+import { generateText, Output } from 'ai';import { z } from 'zod';import { callProvider } from '../../../clients/provider-error';import type { CoreConfig } from '../../../config';-import { ALLOWED_MODELS, resolveModel } from '../../assistant/src/providers';+import { resolveOpenAITaskModel } from '../../assistant/src/providers';-const NARRATIVE_MODEL_ID = 'gpt-4-1-mini';--// Preferred model and fallback are both OpenAI — see enrich.ts.const NARRATIVE_PROVIDER = 'openai';-function narrativeModel(config: CoreConfig) {- const entry =- ALLOWED_MODELS.find((m) => m.id === NARRATIVE_MODEL_ID) ??- ALLOWED_MODELS.find((m) => m.group === 'OpenAI');- if (!entry) {- throw new Error('No OpenAI model available for weekly narrative');- }- return resolveModel(config, entry);-}-export interface WeeklyNarrativeInput {projectName: string;dateRange: string;@@ -34,10 +21,6 @@ export interface WeeklyNarrativeInput {}const narrativeOutputSchema = z.object({ narrative: z.string() });-const narrativeOutputJsonSchema = z.toJSONSchema(narrativeOutputSchema, {- target: 'draft-07',-});-const INSTRUCTION = `You write the intro paragraph for a weekly analytics email digest sent to a website/product owner.You receive the project's week-over-week stats and a few notable insights (already filtered as email-worthy). Write 2-4 short, friendly, plain-language sentences summarizing how the week went and what stood out.@@ -49,41 +32,19 @@ Rules:- If a notable insight explains a change, connect them.- If the week was quiet, say so plainly and briefly. Never invent data.`;-let _app: ReturnType<typeof betterAgent> | null = null;-function getApp(config: CoreConfig) {- if (_app) {- return _app;- }- const agent = defineAgent({- name: 'weekly-narrative',- description: 'Writes a weekly digest intro paragraph (one-shot).',- model: narrativeModel(config),- contextSchema: z.object({}),- outputSchema: {- schema: narrativeOutputJsonSchema,- name: 'weekly_narrative',- strict: true,- },- instruction: () => INSTRUCTION,- tools: () => [],- maxSteps: 1,- // biome-ignore lint/suspicious/noExplicitAny: same dodge as enrich.ts- } as any);- _app = betterAgent({ agents: [agent] });- return _app;-}-export async function generateWeeklyNarrative(config: CoreConfig,input: WeeklyNarrativeInput): Promise<string> {- const result = (await callProvider(NARRATIVE_PROVIDER, () =>- getApp(config).run('weekly-narrative', {- input: JSON.stringify(input),- context: {},- // biome-ignore lint/suspicious/noExplicitAny: same dodge as enrich.ts- } as any)- )) as { structured?: { narrative: string } };-- return result.structured?.narrative ?? '';+ const result = await callProvider(NARRATIVE_PROVIDER, () =>+ generateText({+ model: resolveOpenAITaskModel(config, 'small'),+ instructions: INSTRUCTION,+ prompt: JSON.stringify(input),+ reasoning: 'low',+ output: Output.object({ schema: narrativeOutputSchema }),+ })+ );++ return result.output?.narrative ?? '';}diff --git a/packages/core/src/modules/organization/src/win-back-pitch.ts b/packages/core/src/modules/organization/src/win-back-pitch.tsindex 296003ced..f656bb642 100644--- a/packages/core/src/modules/organization/src/win-back-pitch.ts+++ b/packages/core/src/modules/organization/src/win-back-pitch.ts@@ -1,27 +1,14 @@// One short OpenAI call that turns a lapsed trial's recent stats into a// two-sentence pitch. A throw means "no pitch", never a failed email: the job// falls back to a deterministic sentence built from the same facts.-import { betterAgent, defineAgent } from '@better-agent/core';+import { generateText, Output } from 'ai';import { z } from 'zod';import { callProvider } from '../../../clients/provider-error';import type { CoreConfig } from '../../../config';-import { ALLOWED_MODELS, resolveModel } from '../../assistant/src/providers';+import { resolveOpenAITaskModel } from '../../assistant/src/providers';-const WIN_BACK_MODEL_ID = 'gpt-4-1-mini';--// Preferred model and fallback are both OpenAI.const WIN_BACK_PROVIDER = 'openai';-function winBackModel(config: CoreConfig) {- const entry =- ALLOWED_MODELS.find((m) => m.id === WIN_BACK_MODEL_ID) ??- ALLOWED_MODELS.find((m) => m.group === 'OpenAI');- if (!entry) {- throw new Error('No OpenAI model available for win-back pitch');- }- return resolveModel(config, entry);-}-export interface WinBackPitchInput {projectName: string;/** e.g. "the last 30 days" */@@ -33,10 +20,6 @@ export interface WinBackPitchInput {}const winBackOutputSchema = z.object({ pitch: z.string() });-const winBackOutputJsonSchema = z.toJSONSchema(winBackOutputSchema, {- target: 'draft-07',-});-const INSTRUCTION = `You write one short paragraph for an email to someone whose analytics trial expired months ago but whose website is still sending us tracking data. They have not looked at their dashboard in a long time. The email's goal is to get them to subscribe before we stop recording their events.You receive their real stats from the recent window. Write 1-2 plain sentences with the most interesting concrete facts. The reader should think "huh, I didn't know that", not "I am being marketed to". The paragraph sits inside an email written in the founder's own casual voice, so it must read like a person, not a report.@@ -54,44 +37,22 @@ Rules:- No em dashes.- Contractions are fine.`;-let _app: ReturnType<typeof betterAgent> | null = null;-function getApp(config: CoreConfig) {- if (_app) {- return _app;- }- const agent = defineAgent({- name: 'win-back-pitch',- description: 'Writes a wind-down win-back paragraph (one-shot).',- model: winBackModel(config),- contextSchema: z.object({}),- outputSchema: {- schema: winBackOutputJsonSchema,- name: 'win_back_pitch',- strict: true,- },- instruction: () => INSTRUCTION,- tools: () => [],- maxSteps: 1,- // biome-ignore lint/suspicious/noExplicitAny: same dodge as enrich.ts- } as any);- _app = betterAgent({ agents: [agent] });- return _app;-}-export async function generateWinBackPitch(config: CoreConfig,input: WinBackPitchInput): Promise<string> {- const result = (await callProvider(WIN_BACK_PROVIDER, () =>- getApp(config).run('win-back-pitch', {- input: JSON.stringify(input),- context: {},- // biome-ignore lint/suspicious/noExplicitAny: same dodge as enrich.ts- } as any)- )) as { structured?: { pitch: string } };+ const result = await callProvider(WIN_BACK_PROVIDER, () =>+ generateText({+ model: resolveOpenAITaskModel(config, 'small'),+ instructions: INSTRUCTION,+ prompt: JSON.stringify(input),+ reasoning: 'low',+ output: Output.object({ schema: winBackOutputSchema }),+ })+ );// The instruction bans em dashes, but the model slips one in often enough// that a prompt rule alone won't hold across hundreds of sends. Commas read// fine in every construction it produces them in.- return (result.structured?.pitch ?? '').replace(/\s*[—–]\s*/g, ', ').trim();+ return (result.output?.pitch ?? '').replace(/\s*[—–]\s*/g, ', ').trim();}diff --git a/packages/core/src/modules/overview/overview.rpc.ts b/packages/core/src/modules/overview/overview.rpc.tsindex 3e066e75f..cc6f10be8 100644--- a/packages/core/src/modules/overview/overview.rpc.ts+++ b/packages/core/src/modules/overview/overview.rpc.ts@@ -13,7 +13,6 @@ import {} from '../../rpc/base';import { TRPCForbiddenError } from '../../rpc/errors';import type { ServiceDeps } from '../../services';-import { pageContextSchema } from '../assistant/assistant.constants';import { getConversionEventNames } from '../event/event.service';import { getReferrerSpikes } from '../insight/insight.service';import {@@ -130,6 +129,20 @@ function getCurrentAndPrevious<};}+/** What the command bar tells the model about the current view. */+const zFilterCommandPageContext = z.object({+ filters: z+ .object({+ range: z.string().optional(),+ startDate: z.string().optional(),+ endDate: z.string().optional(),+ interval: z.string().optional(),+ eventNames: z.array(z.string()).optional(),+ eventFilters: z.array(z.record(z.string(), z.unknown())).optional(),+ })+ .optional(),+});+export const overviewRouter = createTRPCRouter({liveVisitors: overviewProcedure.input(z.object({ projectId: z.string(), shareId: z.string().optional() }))@@ -394,7 +407,7 @@ export const overviewRouter = createTRPCRouter({z.object({projectId: z.string(),query: z.string().min(1).max(500),- pageContext: pageContextSchema.optional(),+ pageContext: zFilterCommandPageContext.optional(),})).mutation(async ({ ctx, input }) => {diff --git a/packages/core/src/shared/origin-allowed.ts b/packages/core/src/shared/origin-allowed.tsnew file mode 100644index 000000000..c0b1b2941--- /dev/null+++ b/packages/core/src/shared/origin-allowed.ts@@ -0,0 +1,36 @@+// The browser-origin rule ingestion applies, shared with the tracking+// diagnosis so what the chat reports is what the API enforces.++const DOMAIN_PROTOCOL = /https?:\/\//;+const DOMAIN_TRAILING_SLASH = /\/$/;+const DOMAIN_DOT = /\./g;+const DOMAIN_WILDCARD = /\*/g;++export const cleanDomain = (domain: string) =>+ domain+ .replace('www.', '')+ .replace(DOMAIN_PROTOCOL, '')+ .replace(DOMAIN_TRAILING_SLASH, '');++/** Whether `origin` matches the project's allowed origins (`*.foo.com` wildcards and `*` included). */+export function isOriginAllowed(+ cors: string[],+ origin: string | undefined+): boolean {+ const domainAllowed = cors.find((domain) => {+ const cleanedDomain = cleanDomain(domain);+ if (cleanedDomain.includes('*')) {+ const regex = new RegExp(+ `${cleanedDomain.replace(DOMAIN_DOT, '\\.').replace(DOMAIN_WILDCARD, '.+?')}`+ );+ return regex.test(origin || '');+ }+ return cleanedDomain === cleanDomain(origin || '');+ });++ if (domainAllowed) {+ return true;+ }++ return cors.includes('*') && !!origin;+}diff --git a/packages/db/prisma/migrations/20261019200000_chat_message_metadata/migration.sql b/packages/db/prisma/migrations/20261019200000_chat_message_metadata/migration.sqlnew file mode 100644index 000000000..e15d36dfc--- /dev/null+++ b/packages/db/prisma/migrations/20261019200000_chat_message_metadata/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "chat_messages" ADD COLUMN "metadata" JSONB;diff --git a/packages/db/prisma/prisma-json-types.ts b/packages/db/prisma/prisma-json-types.tsindex 90663ce2f..6c1b7276a 100644--- a/packages/db/prisma/prisma-json-types.ts+++ b/packages/db/prisma/prisma-json-types.ts@@ -144,23 +144,30 @@ function replaceJsonValueInFileForModel(modified = true;}- // Pattern 4: Union types with JsonNullValueInput | runtime.InputJsonValue- const unionJsonValueRegex =- /(Prisma\.JsonNullValueInput\s*\|\s*)runtime\.InputJsonValue/g;+ // Pattern 4: `field: Prisma.(Nullable)JsonNullValueInput | runtime.InputJsonValue`+ // (create/update inputs). Scoped to the field so a model with two Json+ // columns does not get the first column's type stamped on the second.+ const unionJsonValueRegex = new RegExp(+ `\\b${mapping.field}(\\??):\\s*(Prisma\\.(?:Nullable)?JsonNullValueInput\\s*\\|\\s*)runtime\\.InputJsonValue\\b`,+ 'g'+ );if (unionJsonValueRegex.test(content)) {content = content.replace(unionJsonValueRegex,- `$1PrismaJson.${mapping.type}`+ `${mapping.field}$1: $2PrismaJson.${mapping.type}`);modified = true;}- // Pattern 5: Just runtime.InputJsonValue in unions- const simpleInputJsonValueRegex = /\|\s*runtime\.InputJsonValue/g;+ // Pattern 5: `field: X | runtime.InputJsonValue` for any other union shape.+ const simpleInputJsonValueRegex = new RegExp(+ `(\\b${mapping.field}\\??:[^\\n]*?)\\|\\s*runtime\\.InputJsonValue\\b`,+ 'g'+ );if (simpleInputJsonValueRegex.test(content)) {content = content.replace(simpleInputJsonValueRegex,- `| PrismaJson.${mapping.type}`+ `$1| PrismaJson.${mapping.type}`);modified = true;}@@ -193,7 +200,9 @@ function main() {const mappings = parseSchemaForJsonTypes(schemaPath);console.log('Found Json type mappings:');- mappings.forEach((m) => console.log(` ${m.model}.${m.field} -> ${m.type}`));+ for (const mapping of mappings) {+ console.log(` ${mapping.model}.${mapping.field} -> ${mapping.type}`);+ }if (mappings.length === 0) {console.log('No mappings found!');diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prismaindex a4455cbbb..1c9ee0b64 100644--- a/packages/db/prisma/schema.prisma+++ b/packages/db/prisma/schema.prisma@@ -59,6 +59,8 @@ model ChatMessage {role String/// [IPrismaUIMessageParts]parts Json+ /// [IPrismaChatMessageMetadata]+ metadata Json?createdAt DateTime @default(now())@@index([conversationId, createdAt])diff --git a/packages/db/src/code-migrations/27-chat-ui-messages.test.ts b/packages/db/src/code-migrations/27-chat-ui-messages.test.tsnew file mode 100644index 000000000..8caee56d2--- /dev/null+++ b/packages/db/src/code-migrations/27-chat-ui-messages.test.ts@@ -0,0 +1,97 @@+import { describe, expect, test } from 'bun:test';+import { convertLegacyRows } from './27-chat-ui-messages';++const at = (second: number) => new Date(2026, 9, 19, 12, 0, second);++describe('convertLegacyRows', () => {+ test('folds a user item, its tool calls and the assistant text into two messages', () => {+ const messages = convertLegacyRows([+ {+ id: 'u1',+ createdAt: at(0),+ parts: { type: 'message', role: 'user', content: 'show signups' },+ },+ {+ id: 't1',+ createdAt: at(1),+ parts: {+ type: 'tool-call',+ name: 'generate_report',+ callId: 'c1',+ arguments: '{"chartType":"linear"}',+ },+ },+ {+ id: 't2',+ createdAt: at(2),+ parts: {+ type: 'tool-call',+ name: 'generate_report',+ callId: 'c1',+ result: { report: { chartType: 'linear' } },+ arguments: '{}',+ },+ },+ {+ id: 'a1',+ createdAt: at(3),+ parts: {+ type: 'message',+ role: 'assistant',+ content: [{ type: 'text', text: 'Here you go.' }],+ },+ },+ ]);++ expect(messages).toHaveLength(2);+ expect(messages[0]).toMatchObject({+ id: 'u1',+ role: 'user',+ parts: [{ type: 'text', text: 'show signups' }],+ });+ expect(messages[1]?.id).toBe('t1');+ expect(messages[1]?.role).toBe('assistant');+ expect(messages[1]?.parts).toEqual([+ {+ type: 'tool-generate_report',+ toolCallId: 'c1',+ state: 'output-available',+ input: { chartType: 'linear' },+ output: { report: { chartType: 'linear' } },+ },+ { type: 'text', text: 'Here you go.', state: 'done' },+ ]);+ });++ test('a call without a result becomes an error part', () => {+ const messages = convertLegacyRows([+ {+ id: 'u1',+ createdAt: at(0),+ parts: { type: 'message', role: 'user', content: 'hi' },+ },+ {+ id: 't1',+ createdAt: at(1),+ parts: {+ type: 'tool-call',+ name: 'list_event_names',+ callId: 'c1',+ arguments: '{}',+ },+ },+ ]);+ expect(messages[1]?.parts[0]).toMatchObject({+ state: 'output-error',+ errorText: 'No result recorded',+ });+ });++ test('rows already in the new format are ignored', () => {+ expect(+ convertLegacyRows([+ { id: 'x', createdAt: at(0), parts: [{ type: 'text', text: 'new' }] },+ ])+ ).toEqual([]);+ });+});diff --git a/packages/db/src/code-migrations/27-chat-ui-messages.ts b/packages/db/src/code-migrations/27-chat-ui-messages.tsnew file mode 100644index 000000000..b71e47b07--- /dev/null+++ b/packages/db/src/code-migrations/27-chat-ui-messages.ts@@ -0,0 +1,238 @@+// Chat messages used to be stored one Better Agent item per row (a user+// message, a tool call, a tool result, an assistant message). The chat now+// stores one AI SDK UIMessage per row, so each conversation is rewritten:+// user items become user messages, and every run of tool calls and assistant+// text in between becomes one assistant message with tool and text parts.+import { db } from '../prisma-client';+import { getIsDry, printBoxMessage } from './helpers';++const MAX_TOOL_OUTPUT_CHARS = 200_000;+const PAGE_SIZE = 100;++interface LegacyMessageItem {+ type: 'message';+ role: 'user' | 'assistant' | 'system';+ content: string | Array<{ type: string; text?: string }>;+}++interface LegacyToolCallItem {+ type: 'tool-call';+ name: string;+ callId: string;+ arguments?: string;+ result?: unknown;+ status?: string;+}++type LegacyItem = LegacyMessageItem | LegacyToolCallItem | { type: string };++interface UIPart {+ type: string;+ [key: string]: unknown;+}++interface UIMessageRow {+ id: string;+ role: 'user' | 'assistant';+ parts: UIPart[];+ createdAt: Date;+}++function isLegacyRow(parts: unknown): parts is LegacyItem {+ return (+ typeof parts === 'object' &&+ parts !== null &&+ !Array.isArray(parts) &&+ typeof (parts as { type?: unknown }).type === 'string'+ );+}++function textOf(content: LegacyMessageItem['content']): string {+ if (typeof content === 'string') {+ return content;+ }+ return content+ .filter((block) => block.type === 'text' && typeof block.text === 'string')+ .map((block) => block.text)+ .join('\n');+}++function parseArguments(raw: string | undefined): unknown {+ if (!raw) {+ return {};+ }+ try {+ return JSON.parse(raw);+ } catch {+ return { raw };+ }+}++/** Keeps what the chart card needs when a result is too large to store twice. */+function compactOutput(output: unknown): unknown {+ const serialized = JSON.stringify(output) ?? '';+ if (serialized.length <= MAX_TOOL_OUTPUT_CHARS) {+ return output;+ }+ if (typeof output === 'object' && output !== null) {+ const {+ data: _data,+ rows: _rows,+ ...rest+ } = output as Record<string, unknown>;+ return { ...rest, truncated: true };+ }+ return { truncated: true };+}++export function convertLegacyRows(+ rows: Array<{ id: string; parts: unknown; createdAt: Date }>+): UIMessageRow[] {+ const messages: UIMessageRow[] = [];+ let assistant: UIMessageRow | null = null;+ const toolParts = new Map<string, UIPart>();++ const flush = () => {+ if (assistant && assistant.parts.length > 0) {+ messages.push(assistant);+ }+ assistant = null;+ toolParts.clear();+ };++ for (const row of rows) {+ if (!isLegacyRow(row.parts)) {+ continue;+ }+ const item = row.parts;++ if (item.type === 'message') {+ const message = item as LegacyMessageItem;+ if (message.role === 'user') {+ flush();+ messages.push({+ id: row.id,+ role: 'user',+ parts: [{ type: 'text', text: textOf(message.content) }],+ createdAt: row.createdAt,+ });+ continue;+ }+ if (message.role === 'assistant') {+ assistant ??= {+ id: row.id,+ role: 'assistant',+ parts: [],+ createdAt: row.createdAt,+ };+ const text = textOf(message.content);+ if (text) {+ assistant.parts.push({ type: 'text', text, state: 'done' });+ }+ }+ continue;+ }++ if (item.type === 'tool-call') {+ const call = item as LegacyToolCallItem;+ assistant ??= {+ id: row.id,+ role: 'assistant',+ parts: [],+ createdAt: row.createdAt,+ };+ const existing = toolParts.get(call.callId);+ if (existing) {+ if ('result' in call) {+ if (call.status === 'error') {+ existing.state = 'output-error';+ existing.errorText = 'Tool failed';+ } else {+ existing.state = 'output-available';+ existing.output = compactOutput(call.result);+ existing.errorText = undefined;+ }+ }+ continue;+ }+ const part: UIPart = {+ type: `tool-${call.name}`,+ toolCallId: call.callId,+ state: 'result' in call ? 'output-available' : 'output-error',+ input: parseArguments(call.arguments),+ };+ if ('result' in call) {+ part.output = compactOutput(call.result);+ } else {+ part.errorText = 'No result recorded';+ }+ toolParts.set(call.callId, part);+ assistant.parts.push(part);+ }+ }+ flush();+ return messages;+}++export async function up() {+ printBoxMessage('🔄 Converting chat messages to UI messages', []);+ const dry = getIsDry();+ let converted = 0;+ let skipped = 0;+ let cursor: string | undefined;++ for (;;) {+ const conversations = await db.conversation.findMany({+ select: { id: true },+ orderBy: { id: 'asc' },+ take: PAGE_SIZE,+ ...(cursor ? { skip: 1, cursor: { id: cursor } } : {}),+ });+ if (conversations.length === 0) {+ break;+ }+ cursor = conversations.at(-1)?.id;++ for (const conversation of conversations) {+ const rows = await db.chatMessage.findMany({+ where: { conversationId: conversation.id },+ orderBy: { createdAt: 'asc' },+ select: { id: true, parts: true, createdAt: true },+ });+ if (rows.length === 0 || !rows.some((row) => isLegacyRow(row.parts))) {+ skipped += 1;+ continue;+ }+ const messages = convertLegacyRows(rows);+ if (dry) {+ console.log(+ `Would rewrite ${conversation.id}: ${rows.length} items → ${messages.length} messages`+ );+ converted += 1;+ continue;+ }+ await db.$transaction(async (tx) => {+ await tx.chatMessage.deleteMany({+ where: { conversationId: conversation.id },+ });+ if (messages.length > 0) {+ await tx.chatMessage.createMany({+ data: messages.map((message) => ({+ id: message.id,+ conversationId: conversation.id,+ role: message.role,+ parts: message.parts as unknown[],+ createdAt: message.createdAt,+ })),+ });+ }+ });+ converted += 1;+ }+ }++ printBoxMessage('✅ Chat messages converted', [+ `Converted: ${converted} conversations${dry ? ' (dry run)' : ''}`,+ `Skipped: ${skipped} conversations (already in the new format or empty)`,+ ]);+}diff --git a/packages/db/src/code-migrations/7-migrate-events-to-series.ts b/packages/db/src/code-migrations/7-migrate-events-to-series.tsindex 2256e8bef..31440db0d 100644--- a/packages/db/src/code-migrations/7-migrate-events-to-series.ts+++ b/packages/db/src/code-migrations/7-migrate-events-to-series.ts@@ -1,3 +1,4 @@+import type { Prisma } from '../generated/prisma/client';import { db } from '../prisma-client';import type { IChartEvent, IChartEventItem, IChartFormula } from './constants';import { printBoxMessage, shortId } from './helpers';@@ -77,7 +78,9 @@ export async function up() {await db.report.update({where: { id: report.id },data: {- events: migratedSeries,+ // `events` has no PrismaJson annotation; the engine's series type is+ // plain JSON, so the cast only tells Prisma so.+ events: migratedSeries as unknown as Prisma.InputJsonValue,},});diff --git a/packages/db/src/code-migrations/migrate.ts b/packages/db/src/code-migrations/migrate.tsindex 8fc76d0ba..e793f49b9 100644--- a/packages/db/src/code-migrations/migrate.ts+++ b/packages/db/src/code-migrations/migrate.ts@@ -22,9 +22,11 @@ export async function runCodeMigrations(env: CodeMigrationEnv) {.readdirSync(MIGRATIONS_DIR).filter((file) => {const version = file.split('-')[0];+ // A migration's test sits beside it and must not run as a migration.return (!Number.isNaN(Number.parseInt(version ?? '', 10)) &&- file.endsWith('.ts')+ file.endsWith('.ts') &&+ !file.endsWith('.test.ts'));}).sort((a, b) => {diff --git a/packages/db/src/types.ts b/packages/db/src/types.tsindex ca9a78dca..34fd414b6 100644--- a/packages/db/src/types.ts+++ b/packages/db/src/types.ts@@ -32,12 +32,11 @@ declare global {type IPrismaClickhouseBotEvent = IClickhouseBotEvent;type IPrismaCohortDefinition = CohortDefinition;type IPrismaCustomEventItems = ICustomEventItem[];- // Each ChatMessage row stores one Better Agent `ConversationItem`- // (message, tool call, or tool result) as JSON. Typed as `unknown[]`- // here to avoid pulling `@better-agent/core` into @openpanel/db's- // dependency graph; the real shape is narrowed at the API boundary- // in packages/core/src/modules/assistant/src/persistence.ts.+ // One ChatMessage row is one AI SDK `UIMessage`: `parts` is its parts+ // array. Typed loosely so `ai` stays out of @openpanel/db; the assistant+ // module narrows it.type IPrismaUIMessageParts = unknown[];+ type IPrismaChatMessageMetadata = Record<string, unknown>;type IPrismaSubscriptionStatus =| 'incomplete'| 'incomplete_expired'