OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix: ai things
Carl-Gerhard Lindesvärdc3019607c4f2
diff --git a/apps/api/src/agents/prompt.ts b/apps/api/src/agents/prompt.tsindex 659869c44..6f3b15f02 100644--- a/apps/api/src/agents/prompt.ts+++ b/apps/api/src/agents/prompt.ts@@ -1,4 +1,5 @@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.@@ -169,10 +170,11 @@ function buildPageContextSection(pc?: PageContext): string {if (pc.filters?.range) {const range = pc.filters.range;- const dates =- pc.filters.startDate && pc.filters.endDate- ? ` (${pc.filters.startDate} to ${pc.filters.endDate})`- : '';+ // Resolve presets ("6m", "7d", …) to actual dates in the project's+ // timezone so the model sees the same window the dashboard shows.+ // Falls through gracefully if the range isn't a preset.+ 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}.`);}diff --git a/apps/api/src/agents/run-context.ts b/apps/api/src/agents/run-context.tsindex 1f8cb4687..8dd321602 100644--- a/apps/api/src/agents/run-context.ts+++ b/apps/api/src/agents/run-context.ts@@ -3,8 +3,12 @@ import { AsyncLocalStorage } from 'node:async_hooks';/*** Per-request context for chat runs. Populated by the Fastify route* wrapper (which validates the session + project access) before the- * Better Agent handler runs, and read by the persistence store to- * upsert the `Conversation` row with the right owner on first save.+ * Better Agent handler runs, and read by:+ * - the persistence store, to upsert the `Conversation` row with+ * the right owner on first save+ * - `resolveDateRange` / the prompt builder, to turn page-context+ * range presets (`"6m"`, `"7d"`, …) into actual dates in the+ * user's project timezone** Using AsyncLocalStorage means we don't have to thread these values* through Better Agent's plugin hooks — which don't expose the agent@@ -14,6 +18,8 @@ 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/apps/api/src/agents/tools/helpers.ts b/apps/api/src/agents/tools/helpers.tsindex f3cf3f3df..4286211e2 100644--- a/apps/api/src/agents/tools/helpers.ts+++ b/apps/api/src/agents/tools/helpers.ts@@ -3,10 +3,14 @@ import {defineTool,type ToolRunContext,} from '@better-agent/core';-import { resolveDateRange as resolveDateRangeCore } from '@openpanel/db';-import type { IChartEventFilter } from '@openpanel/validation';+import {+ getDatesFromRange,+ resolveDateRange as resolveDateRangeCore,+} from '@openpanel/db';+import type { IChartEventFilter, IChartRange } from '@openpanel/validation';import type { z } from 'zod';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;@@ -92,16 +96,57 @@ export function truncateRows<T>(}/**- * Resolve a date range from PageContext.filters, defaulting to the- * last 30 days. Delegates to the canonical `resolveDateRange` in- * `@openpanel/db` so server-side tools and db services agree on the- * default window.+ * Known range presets that map to date windows via `getDatesFromRange`.+ * Anything outside this set (including `"custom"`) is treated as "no+ * preset" and we fall through to explicit dates / 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`.+ *+ * Precedence:+ * 1. Explicit `startDate` + `endDate` → use as-is (either one alone+ * falls back to the other via `resolveDateRangeCore`).+ * 2. `range` is a known preset (`"7d"`, `"6m"`, …) → expand via+ * `getDatesFromRange(range, projectTimezone)` so a preset-only+ * URL (as set by the dashboard's `useOverviewOptions`) produces+ * the same window the dashboard is displaying.+ * 3. Nothing → default to the last 30 days (via+ * `resolveDateRangeCore`).+ *+ * Timezone comes from `chatRunContext` (populated by the Fastify+ * wrapper once per request). Outside that context we fall back to UTC+ * — only relevant in tests / direct calls.*/export function resolveDateRange(filters?: PageContext['filters']): {startDate: string;endDate: string;} {- return resolveDateRangeCore(filters?.startDate, filters?.endDate);+ 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);}/**diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex d772c3f64..23f0ca057 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -42,6 +42,7 @@ import {getConversationById,getOrganizationByProjectIdCached,getProjectAccess,+ getSettingsForProject,} from '@openpanel/db';import eventRouter from './routes/event.router';import exportRouter from './routes/export.router';@@ -276,9 +277,15 @@ export async function buildApp(});}- const [access, organization] = await Promise.all([+ const [access, organization, settings] = await Promise.all([getProjectAccess({ projectId, userId }),getOrganizationByProjectIdCached(projectId),+ // Fetch the project's timezone up front so the tools ++ // prompt builder can resolve range presets ("6m", "7d", …)+ // into concrete dates without an async lookup per call.+ // Falls back to UTC on any error — preset resolution then+ // still works, just in UTC instead of the user's zone.+ getSettingsForProject(projectId).catch(() => ({ timezone: 'UTC' })),]);if (!access ||@@ -297,7 +304,12 @@ export async function buildApp(// — no eager upsert needed here.return chatRunContext.run(- { userId, projectId, organizationId: organization.id },+ {+ userId,+ projectId,+ organizationId: organization.id,+ timezone: settings.timezone || 'UTC',+ },() => agentHandler(request, reply),);});diff --git a/apps/start/src/components/chat/chat-drawer-body.tsx b/apps/start/src/components/chat/chat-drawer-body.tsxindex 2debadf76..d16d0e6ea 100644--- a/apps/start/src/components/chat/chat-drawer-body.tsx+++ b/apps/start/src/components/chat/chat-drawer-body.tsx@@ -24,6 +24,14 @@ export function ChatDrawerBody() {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-1 flex flex-col">@@ -49,8 +57,12 @@ export function ChatDrawerBody() {hasContext && 'pt-24',)}>- {messages.map((message) => (- <ChatMessage key={message.localId} message={message} />+ {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">diff --git a/apps/start/src/components/chat/chat-message.tsx b/apps/start/src/components/chat/chat-message.tsxindex de811de84..37258be67 100644--- a/apps/start/src/components/chat/chat-message.tsx+++ b/apps/start/src/components/chat/chat-message.tsx@@ -17,7 +17,19 @@ import type { ToolResultPart } from './tool-results/types';* Assistant text supports markdown via `<ChatMarkdown>`. User text* stays plain (no markdown injection from user input).*/-export function ChatMessage({ message }: { message: UIMessage }) {+export function ChatMessage({+ message,+ runStillActive = false,+}: {+ 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;+}) {const isUser = message.role === 'user';// Index tool results by callId so we can attach them to their call.@@ -31,6 +43,8 @@ export function ChatMessage({ message }: { message: UIMessage }) {}}+ const lastIdx = message.parts.length - 1;+return (<divclassName={cn(@@ -60,14 +74,30 @@ export function ChatMessage({ message }: { message: UIMessage }) {</div>);- case 'reasoning':+ 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 (<ReasoningBlockkey={`${message.localId}-reasoning-${idx}`}text={part.text}- complete={(part as { state?: string }).state === 'complete'}+ complete={+ stateComplete || hasFollowingPart || !runStillActive+ }/>);+ }case 'tool-call': {const matched = resultByCallId.get(part.callId);@@ -156,7 +186,7 @@ function ReasoningBlock({}return (- <div className="w-full max-w-full">+ <div className="w-full max-w-full mb-2"><buttontype="button"onClick={() => setOpen((v) => !v)}@@ -168,10 +198,10 @@ function ReasoningBlock({<span>Thought</span></button>{open && (- <div className="mt-1 ml-4 border-l-2 border-muted-foreground/20 pl-3">+ <div className="mt-2"><ChatMarkdowntext={trimmed}- className="text-sm text-muted-foreground"+ className="text-sm text-muted-foreground leading-normal"/></div>)}