πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Clean up the site page redesign, and fix what Codex found in it (#1296)
Goldflagaea238af8055
diff --git a/client/src/api/analytics/endpoints/userProfile.ts b/client/src/api/analytics/endpoints/userProfile.tsindex b1ef8a0c9..acfc7f44e 100644--- a/client/src/api/analytics/endpoints/userProfile.ts+++ b/client/src/api/analytics/endpoints/userProfile.ts@@ -44,15 +44,3 @@ export interface UserSegments {/** The site has more segments than one request evaluates. */truncated: boolean;}--/** The latest session in the window in which one error message was thrown twice or more. */-export interface UserRepeatedError {- message: string;- session_id: string;- occurrences: number;- /** Page the first of them was thrown on. */- pathname: string;- first_seen: string;- last_seen: string;- has_replay: boolean;-}diff --git a/client/src/api/analytics/hooks/goals/invalidateGoalDependents.ts b/client/src/api/analytics/hooks/goals/invalidateGoalDependents.tsnew file mode 100644index 000000000..fa3b0ae92--- /dev/null+++ b/client/src/api/analytics/hooks/goals/invalidateGoalDependents.ts@@ -0,0 +1,18 @@+import { QueryClient } from "@tanstack/react-query";++// Reads that carry the goals each session completed. Several are cached until+// the period changes, so a goal created, edited or deleted must drop them.+const GOAL_DEPENDENT_KEYS = [+ "sessions",+ "sessions-infinite",+ "sessions-summary",+ "session-details-infinite",+ "user-goals",+ "user-session-goals",+];++export function invalidateGoalDependents(queryClient: QueryClient) {+ for (const key of GOAL_DEPENDENT_KEYS) {+ queryClient.invalidateQueries({ queryKey: [key] });+ }+}diff --git a/client/src/api/analytics/hooks/goals/useCreateGoal.ts b/client/src/api/analytics/hooks/goals/useCreateGoal.tsindex dac2719e4..2b81f03ed 100644--- a/client/src/api/analytics/hooks/goals/useCreateGoal.ts+++ b/client/src/api/analytics/hooks/goals/useCreateGoal.ts@@ -1,5 +1,6 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { createGoal, GoalConfig, GoalType } from "../../endpoints";+import { invalidateGoalDependents } from "./invalidateGoalDependents";export interface CreateGoalRequest {siteId: number;@@ -35,6 +36,7 @@ export function useCreateGoal() {queryClient.invalidateQueries({queryKey: ["goal-time-series", variables.siteId.toString()],});+ invalidateGoalDependents(queryClient);},});}diff --git a/client/src/api/analytics/hooks/goals/useDeleteGoal.ts b/client/src/api/analytics/hooks/goals/useDeleteGoal.tsindex 8c269e7fb..813281af7 100644--- a/client/src/api/analytics/hooks/goals/useDeleteGoal.ts+++ b/client/src/api/analytics/hooks/goals/useDeleteGoal.ts@@ -1,6 +1,7 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { useStore } from "../../../../lib/store";import { deleteGoal } from "../../endpoints";+import { invalidateGoalDependents } from "./invalidateGoalDependents";export function useDeleteGoal() {const queryClient = useQueryClient();@@ -21,6 +22,7 @@ export function useDeleteGoal() {queryClient.invalidateQueries({queryKey: ["goal-time-series", site],});+ invalidateGoalDependents(queryClient);},});}diff --git a/client/src/api/analytics/hooks/goals/useUpdateGoal.ts b/client/src/api/analytics/hooks/goals/useUpdateGoal.tsindex c05c24ea4..b2868a2af 100644--- a/client/src/api/analytics/hooks/goals/useUpdateGoal.ts+++ b/client/src/api/analytics/hooks/goals/useUpdateGoal.ts@@ -1,6 +1,7 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { useStore } from "../../../../lib/store";import { GoalConfig, GoalType, updateGoal } from "../../endpoints";+import { invalidateGoalDependents } from "./invalidateGoalDependents";export interface UpdateGoalRequest {goalId: number;@@ -43,6 +44,7 @@ export function useUpdateGoal() {queryClient.invalidateQueries({queryKey: ["goal-sessions", goalData.goalId],});+ invalidateGoalDependents(queryClient);},});}diff --git a/client/src/api/analytics/hooks/useGetJourneys.ts b/client/src/api/analytics/hooks/useGetJourneys.tsindex 5325b698c..f281791c5 100644--- a/client/src/api/analytics/hooks/useGetJourneys.ts+++ b/client/src/api/analytics/hooks/useGetJourneys.ts@@ -104,14 +104,15 @@ export const useJourneySummary = ({export const useJourneySessions = ({path,replaysOnly = false,- page = 1,+ offset = 0,limit = 25,enabled = true,...shape}: JourneyShape & {path: string[];replaysOnly?: boolean;- page?: number;+ /** Rows to skip. */+ offset?: number;limit?: number;enabled?: boolean;}) => {@@ -125,7 +126,7 @@ export const useJourneySessions = ({...journeyShapeParams(shape),path: JSON.stringify(path),replays_only: replaysOnly ? "true" : undefined,- page,+ offset,limit,},enabled: enabled && path.length > 0,diff --git a/client/src/api/analytics/hooks/useUserProfile.ts b/client/src/api/analytics/hooks/useUserProfile.tsindex 97747af29..ac33b66bb 100644--- a/client/src/api/analytics/hooks/useUserProfile.ts+++ b/client/src/api/analytics/hooks/useUserProfile.ts@@ -2,7 +2,7 @@ import { Query } from "@tanstack/react-query";import { Time } from "../../../components/DateSelector/types";import { USER_DETAIL_PAGE_FILTERS } from "../../../lib/filterGroups";import { getFilteredFilters } from "../../../lib/store";-import { UserGoal, UserRepeatedError, UserSegments, UserSessionGoals, UserSummary } from "../endpoints/userProfile";+import { UserGoal, UserSegments, UserSessionGoals, UserSummary } from "../endpoints/userProfile";import { useAnalyticsQuery } from "../useAnalyticsQuery";// Every profile panel applies the page's own filter set, the way useUserInfo@@ -78,14 +78,3 @@ export function useUserSegments(userId: string) {props: { placeholderData: sameUserPlaceholder<UserSegments>(userId) },});}--export function useUserRepeatedError(userId: string) {- return useAnalyticsQuery<UserRepeatedError | null>({- key: ["user-repeated-error", userId],- path: userPath(userId, "repeated-error"),- ...profileFilters(),- // An insight about one period must not linger over the next.- placeholder: false,- enabled: !!userId,- });-}diff --git a/client/src/app/[site]/events/components/EventNames/AutocaptureTable.tsx b/client/src/app/[site]/events/components/EventNames/AutocaptureTable.tsxindex 66a48267e..7767b3e0d 100644--- a/client/src/app/[site]/events/components/EventNames/AutocaptureTable.tsx+++ b/client/src/app/[site]/events/components/EventNames/AutocaptureTable.tsx@@ -72,13 +72,16 @@ export function AutocaptureTable({ rows, maxCount, total, valueLabel, links = fatarget="_blank"rel="noopener noreferrer"title={row.value}- className="truncate font-medium text-neutral-900 hover:underline dark:text-neutral-100"+ className="truncate text-xs font-medium text-neutral-900 hover:underline dark:text-neutral-100">{truncateUrl(row.value)}</a></div>) : (- <div className="truncate font-medium text-neutral-900 dark:text-neutral-100" title={row.value}>+ <div+ className="truncate text-xs font-medium text-neutral-900 dark:text-neutral-100"+ title={row.value}+ >{truncateString(row.value, 120)}</div>)}diff --git a/client/src/app/[site]/events/components/EventNames/EventNamesCard.tsx b/client/src/app/[site]/events/components/EventNames/EventNamesCard.tsxindex 35efb665b..da45ec4b1 100644--- a/client/src/app/[site]/events/components/EventNames/EventNamesCard.tsx+++ b/client/src/app/[site]/events/components/EventNames/EventNamesCard.tsx@@ -1,6 +1,6 @@"use client";-import { BookOpen, ChevronDown, ChevronUp } from "lucide-react";+import { BookOpen } from "lucide-react";import { useExtracted } from "next-intl";import { ReactNode, useState } from "react";@@ -12,20 +12,19 @@ import { useGetGoals } from "@/api/analytics/hooks/goals/useGetGoals";import { ErrorState } from "@/components/ErrorState";import { ExternalLink } from "@/components/ExternalLink";import { SegmentedControl } from "@/components/interior/segmented-control";-import { Button } from "@/components/ui/button";+import { Pagination } from "@/components/pagination";import { Card } from "@/components/ui/card";import { Input } from "@/components/ui/input";import { useCanOnSite } from "@/hooks/usePermissions";import { useComparisonEnabled, useStore } from "@/lib/store";import { EventNameRow, EventNameSortKey, filterEventNameRows, sortEventNameRows } from "../../utils/eventNameRows";-import { formatShare } from "../../utils/properties";import { AutocaptureRow, AutocaptureTable } from "./AutocaptureTable";import { EventNamesSort, EventNamesTable, EventNamesTableSkeleton } from "./EventNamesTable";type Kind = "events" | "outbound" | "button_click" | "form_submit" | "copy";-// Rows on show before "Show all".-const ROW_LIMIT = 8;+// Rows on one page of the table.+const PAGE_SIZE = 10;// The goals endpoint's largest page.const GOALS_PAGE_SIZE = 100;@@ -48,43 +47,39 @@ function Message({ title, children }: { title: string; children?: ReactNode }) {);}-/** "8 of 24. The other 16 account for β¦" and the switch between the short list and all of it. */-function ListFooter({- shown,+/** The page of rows on show, and the page control under them once there is more than one. */+function pageOf<T>(rows: T[], page: number) {+ const pageCount = Math.max(1, Math.ceil(rows.length / PAGE_SIZE));+ // The rows can shrink under the page (a new period, a narrower search).+ const current = Math.min(page, pageCount);+ return { pageCount, current, shown: rows.slice((current - 1) * PAGE_SIZE, current * PAGE_SIZE) };+}++function PageFooter({+ page,+ pageCount,total,- restEvents,- restShare,- expanded,- onToggle,+ itemName,+ onPageChange,}: {- shown: number;+ page: number;+ pageCount: number;total: number;- /** Events in the rows that are not on show. */- restEvents: number;- restShare: number;- expanded: boolean;- onToggle: () => void;+ itemName: string;+ onPageChange: (page: number) => void;}) {- const t = useExtracted();- if (total <= ROW_LIMIT) return null;+ if (pageCount <= 1) return null;return (- <div className="flex flex-wrap items-center justify-between gap-2 border-t border-neutral-100 px-4 py-2 text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400">- <span>- {expanded- ? t("All {total} shown.", { total: total.toLocaleString() })- : t("{shown} of {total}. The other {rest} account for {events} events ({share}).", {- shown: shown.toLocaleString(),- total: total.toLocaleString(),- rest: (total - shown).toLocaleString(),- events: restEvents.toLocaleString(),- share: formatShare(restShare),- })}- </span>- <Button type="button" variant="ghost" size="xs" className="gap-1" onClick={onToggle}>- {expanded ? t("Show fewer") : t("Show all {total}", { total: total.toLocaleString() })}- {expanded ? <ChevronUp /> : <ChevronDown />}- </Button>+ <div className="border-t border-neutral-100 px-3 py-2 dark:border-neutral-800">+ <Pagination+ page={page}+ pageCount={pageCount}+ totalItems={total}+ pageSize={PAGE_SIZE}+ onPageChange={onPageChange}+ itemName={itemName}+ /></div>);}@@ -113,7 +108,7 @@ export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEvconst [kind, setKind] = useState<Kind>("events");const [search, setSearch] = useState("");- const [expanded, setExpanded] = useState(false);+ const [page, setPage] = useState(1);const [sort, setSort] = useState<EventNamesSort>({ key: "count", direction: "desc" });const goals = useGetGoals({ pageSize: GOALS_PAGE_SIZE });@@ -125,31 +120,35 @@ export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEvconst autocapture: Record<Exclude<Kind, "events">,- { rows: AutocaptureRow[] | undefined; isLoading: boolean; isError: boolean; valueLabel: string }+ { rows: AutocaptureRow[] | undefined; isLoading: boolean; isError: boolean; valueLabel: string; itemName: string }> = {outbound: {rows: outbound.data?.map(link => ({ value: String(link.url), count: link.count, lastSeen: link.lastClicked })),isLoading: outbound.isPending,isError: outbound.isError,valueLabel: t("Link"),+ itemName: t("links"),},button_click: {rows: buttons.data?.map(row => ({ value: row.value, count: row.count, lastSeen: row.lastOccurred })),isLoading: buttons.isPending,isError: buttons.isError,valueLabel: t("Button text"),+ itemName: t("buttons"),},form_submit: {rows: forms.data?.map(row => ({ value: row.value, count: row.count, lastSeen: row.lastOccurred })),isLoading: forms.isPending,isError: forms.isError,valueLabel: t("Form"),+ itemName: t("forms"),},copy: {rows: copies.data?.map(row => ({ value: row.value, count: row.count, lastSeen: row.lastOccurred })),isLoading: copies.isPending,isError: copies.isError,valueLabel: t("Copied text"),+ itemName: t("copies"),},};@@ -167,12 +166,14 @@ export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEv{ value: "copy", label: tab(t("Copies"), autocapture.copy.rows?.length) },];- const changeSort = (key: EventNameSortKey) =>+ const changeSort = (key: EventNameSortKey) => {setSort(current =>current.key === key? { key, direction: current.direction === "asc" ? "desc" : "asc" }: { key, direction: FIRST_DIRECTION[key] });+ setPage(1);+ };const errorState = (<ErrorState@@ -185,9 +186,7 @@ export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEvlet body: ReactNode;if (kind === "events") {const matching = sortEventNameRows(filterEventNameRows(rows, search), sort.key, sort.direction);- const shown = expanded ? matching : matching.slice(0, ROW_LIMIT);- const total = rows.reduce((sum, row) => sum + row.count, 0);- const restEvents = matching.slice(shown.length).reduce((sum, row) => sum + row.count, 0);+ const { pageCount, current, shown } = pageOf(matching, page);body = isLoading ? (<EventNamesTableSkeleton />@@ -219,13 +218,12 @@ export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEvsilentEvents={silentEvents}showChange={comparisonEnabled}/>- <ListFooter- shown={shown.length}+ <PageFooter+ page={current}+ pageCount={pageCount}total={matching.length}- restEvents={restEvents}- restShare={total > 0 ? restEvents / total : 0}- expanded={expanded}- onToggle={() => setExpanded(current => !current)}+ itemName={t("event names")}+ onPageChange={setPage}/></>);@@ -234,9 +232,8 @@ export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEvconst all = list.rows ?? [];const query = search.trim().toLowerCase();const matching = query ? all.filter(row => row.value.toLowerCase().includes(query)) : all;- const shown = expanded ? matching : matching.slice(0, ROW_LIMIT);+ const { pageCount, current, shown } = pageOf(matching, page);const total = all.reduce((sum, row) => sum + row.count, 0);- const restEvents = matching.slice(shown.length).reduce((sum, row) => sum + row.count, 0);body = list.isLoading ? (<EventNamesTableSkeleton />@@ -257,13 +254,12 @@ export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEvvalueLabel={list.valueLabel}links={kind === "outbound"}/>- <ListFooter- shown={shown.length}+ <PageFooter+ page={current}+ pageCount={pageCount}total={matching.length}- restEvents={restEvents}- restShare={total > 0 ? restEvents / total : 0}- expanded={expanded}- onToggle={() => setExpanded(current => !current)}+ itemName={list.itemName}+ onPageChange={setPage}/></>);@@ -282,7 +278,7 @@ export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEvvalue={kind}onValueChange={next => {setKind(next);- setExpanded(false);+ setPage(1);setSearch("");}}/>@@ -294,7 +290,10 @@ export function EventNamesCard({ rows, isLoading, isError, trendBucket, silentEvinputSize="sm"className="h-8"value={search}- onChange={event => setSearch(event.target.value)}+ onChange={event => {+ setSearch(event.target.value);+ setPage(1);+ }}placeholder={kind === "events" ? t("Search event names") : t("Search")}aria-label={kind === "events" ? t("Search event names") : t("Search")}/>diff --git a/client/src/app/[site]/events/components/EventNames/EventNamesTable.tsx b/client/src/app/[site]/events/components/EventNames/EventNamesTable.tsxindex d950cdf20..164fde32e 100644--- a/client/src/app/[site]/events/components/EventNames/EventNamesTable.tsx+++ b/client/src/app/[site]/events/components/EventNames/EventNamesTable.tsx@@ -194,7 +194,7 @@ export function EventNamesTable({type="button"title={t("Filter by {name}", { name: row.eventName })}onClick={() => addFilter(eventFilter(row.eventName)[0])}- className="min-w-0 cursor-pointer truncate text-left font-medium text-neutral-900 hover:underline dark:text-neutral-100"+ className="min-w-0 cursor-pointer truncate text-left text-xs font-medium text-neutral-900 hover:underline dark:text-neutral-100">{row.eventName}</button>diff --git a/client/src/app/[site]/events/components/EventNames/UsedIn.test.tsx b/client/src/app/[site]/events/components/EventNames/UsedIn.test.tsxindex 151d90dd7..9f955912f 100644--- a/client/src/app/[site]/events/components/EventNames/UsedIn.test.tsx+++ b/client/src/app/[site]/events/components/EventNames/UsedIn.test.tsx@@ -52,8 +52,6 @@ const funnel = (id: number, name: string): SavedFunnel => ({steps: [{ type: "event", value: "signup" }],createdAt: "2026-01-01",updatedAt: "2026-01-01",- conversionRate: null,- totalVisitors: null,});const renderUsedIn = (props: Partial<Parameters<typeof UsedIn>[0]> = {}) =>diff --git a/client/src/app/[site]/events/components/SilentEventNotice.tsx b/client/src/app/[site]/events/components/SilentEventNotice.tsxdeleted file mode 100644index e4c284d5a..000000000--- a/client/src/app/[site]/events/components/SilentEventNotice.tsx+++ /dev/null@@ -1,57 +0,0 @@-"use client";--import { DateTime } from "luxon";-import { useExtracted } from "next-intl";--import { SilentEvent } from "@/api/analytics/endpoints";-import { InsightRow } from "@/components/site/InsightRow";-import { Button } from "@/components/ui/button";-import { addFilter, getTimezone } from "@/lib/store";-import { silentEventDailyAverage } from "../utils/usedIn";--interface SilentEventNoticeProps {- /** Ranked by how often they used to fire; the first one is named. */- events: SilentEvent[] | undefined;-}--/**- * Says when a custom event that fired on most days has stopped. Nothing else- * on the page can: an event with no occurrences drops out of every list.- */-export function SilentEventNotice({ events }: SilentEventNoticeProps) {- const t = useExtracted();- const event = events?.[0];- if (!event) return null;-- const lastSeen = DateTime.fromSQL(event.lastSeen, { zone: "utc" }).setZone(getTimezone());- const average = silentEventDailyAverage(event);- const others = (events?.length ?? 1) - 1;-- return (- <InsightRow- action={- <Button- variant="ghost"- size="xs"- onClick={() => addFilter({ parameter: "event_name", type: "equals", value: [event.eventName] })}- >- {t("View event")}- </Button>- }- >- {t.rich("<name></name> has not fired since {date}. It averaged {average} a day before that.", {- name: () => <span className="font-medium text-neutral-900 dark:text-neutral-50">{event.eventName}</span>,- date: lastSeen.toFormat("MMM d"),- average: average >= 10 ? Math.round(average).toLocaleString() : average.toFixed(1),- })}- {others > 0 && (- <span className="text-neutral-500 dark:text-neutral-400">- {" "}- {t("{count, plural, one {# other event has gone quiet too.} other {# other events have gone quiet too.}}", {- count: others,- })}- </span>- )}- </InsightRow>- );-}diff --git a/client/src/app/[site]/events/page.tsx b/client/src/app/[site]/events/page.tsxindex 06df39545..ebbc1cbe9 100644--- a/client/src/app/[site]/events/page.tsx+++ b/client/src/app/[site]/events/page.tsx@@ -18,7 +18,6 @@ import { EventLog } from "./components/EventLog";import { EventNamesCard } from "./components/EventNames/EventNamesCard";import { EVENT_LIMIT_OPTIONS, EventsBreakdown, EventsChart } from "./components/EventsChart";import { EventsStatBand } from "./components/EventsStatBand";-import { SilentEventNotice } from "./components/SilentEventNotice";import { buildEventNameRows, countNewEventNames } from "./utils/eventNameRows";import { trendBucketFor } from "./utils/trendBucket";@@ -76,7 +75,6 @@ export default function EventsPage() {)}</AnalysisBar><EventsChart breakdown={breakdown} eventLimit={eventLimit} />- <SilentEventNotice events={silentEvents} /><EventNamesCardrows={rows}isLoading={stats.isPending}diff --git a/client/src/app/[site]/events/utils/eventsPageUtils.test.ts b/client/src/app/[site]/events/utils/eventsPageUtils.test.tsindex 9ca515a5d..c05f385a5 100644--- a/client/src/app/[site]/events/utils/eventsPageUtils.test.ts+++ b/client/src/app/[site]/events/utils/eventsPageUtils.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import { Goal, SavedFunnel, SiteEventCountPoint } from "../../../../api/analytics/endpoints";import { DEFAULT_HIDDEN_TYPES, EVENT_TYPE_SERIES, SERIES_COLORS, seriesColor, totalsByType } from "./eventTypes";import { formatShare, groupProperties } from "./properties";-import { funnelsForEvent, goalsForEvent, silentEventDailyAverage } from "./usedIn";+import { funnelsForEvent, goalsForEvent } from "./usedIn";const goal = (goalId: number, goalType: Goal["goalType"], config: Goal["config"]): Goal => ({goalId,@@ -21,8 +21,6 @@ const funnel = (id: number, steps: SavedFunnel["steps"]): SavedFunnel => ({steps,createdAt: "2026-01-01",updatedAt: "2026-01-01",- conversionRate: null,- totalVisitors: null,});describe("goalsForEvent", () => {@@ -67,16 +65,6 @@ describe("funnelsForEvent", () => {});});-describe("silentEventDailyAverage", () => {- it("averages over the days between the first and last occurrence", () => {- expect(silentEventDailyAverage({ total: 66, spanDays: 22 })).toBe(3);- });-- it("does not divide by zero", () => {- expect(silentEventDailyAverage({ total: 5, spanDays: 0 })).toBe(0);- });-});-describe("event type series", () => {const point = (overrides: Partial<SiteEventCountPoint>): SiteEventCountPoint => ({time: "2026-09-01 00:00:00",diff --git a/client/src/app/[site]/events/utils/usedIn.ts b/client/src/app/[site]/events/utils/usedIn.tsindex 51f30198c..26d14506f 100644--- a/client/src/app/[site]/events/utils/usedIn.ts+++ b/client/src/app/[site]/events/utils/usedIn.ts@@ -1,4 +1,4 @@-import { Goal, SavedFunnel, SilentEvent } from "../../../../api/analytics/endpoints";+import { Goal, SavedFunnel } from "../../../../api/analytics/endpoints";/** The goals that complete on this custom event. Event goals match the name exactly. */export function goalsForEvent(goals: Goal[] | undefined, eventName: string): Goal[] {@@ -9,8 +9,3 @@ export function goalsForEvent(goals: Goal[] | undefined, eventName: string): Goaexport function funnelsForEvent(funnels: SavedFunnel[] | undefined, eventName: string): SavedFunnel[] {return (funnels ?? []).filter(funnel => funnel.steps.some(step => step.type === "event" && step.value === eventName));}--/** How often a silent event fired per day, over the days between its first and last occurrence in the lookback. */-export function silentEventDailyAverage(event: Pick<SilentEvent, "total" | "spanDays">): number {- return event.spanDays > 0 ? event.total / event.spanDays : 0;-}diff --git a/client/src/app/[site]/funnels/components/funnelMetrics.test.ts b/client/src/app/[site]/funnels/components/funnelMetrics.test.tsindex 616408977..a22994614 100644--- a/client/src/app/[site]/funnels/components/funnelMetrics.test.ts+++ b/client/src/app/[site]/funnels/components/funnelMetrics.test.ts@@ -1,7 +1,6 @@import { describe, expect, it } from "vitest";import type { FunnelSummariesResponse, Goal, SavedFunnel } from "@/api/analytics/endpoints";import {- biggestDecline,biggestDropOff,biggestGain,computeFunnelMetrics,@@ -214,22 +213,6 @@ describe("the stat band's picks", () => {expect(biggestGain([row(1, "No comparison", [10, 5])])).toBeNull();});- it("picks the funnel whose conversion fell the most and the step transition that lost the most ground", () => {- const decline = biggestDecline(rows);-- expect(decline?.row.funnel.name).toBe("Docs activation");- expect(decline?.delta).toMatchObject({ direction: "down", text: "10.0 pp" });- // Step 1 to 2 fell from 50% to 40%, step 2 to 3 from 60% to 50%: the first transition wins the tie.- expect(decline?.stepIndex).toBe(0);- // Entries rose from 400 to 500 while conversion fell.- expect(decline?.enteredDelta).toMatchObject({ direction: "up", text: "25.0%" });- });-- it("only mentions entries when they rose", () => {- expect(biggestDecline([rows[2]])?.enteredDelta).toBeNull();- expect(biggestDecline([rows[0]])).toBeNull();- });-it("picks the single leakiest step across all funnels", () => {const leak = biggestDropOff(rows);diff --git a/client/src/app/[site]/funnels/components/funnelMetrics.ts b/client/src/app/[site]/funnels/components/funnelMetrics.tsindex 84ac52a8a..1908473cf 100644--- a/client/src/app/[site]/funnels/components/funnelMetrics.ts+++ b/client/src/app/[site]/funnels/components/funnelMetrics.ts@@ -1,5 +1,5 @@import { FunnelResponse, FunnelStep, FunnelSummariesResponse, Goal, SavedFunnel } from "@/api/analytics/endpoints";-import { DeltaValue, percentDelta, pointDelta } from "@/lib/delta";+import { DeltaValue, pointDelta } from "@/lib/delta";import { resolvePropertyFilters } from "@/lib/events";/** One step of a funnel over one period. Rates are fractions (0 to 1). */@@ -188,43 +188,6 @@ function biggestMove(rows: FunnelRowData[], direction: "up" | "down") {export const biggestGain = (rows: FunnelRowData[]) => biggestMove(rows, "up");-export interface FunnelDecline {- row: FunnelRowData;- delta: DeltaValue;- /** Change in sessions entering the funnel, when they rose while conversion fell. */- enteredDelta: DeltaValue | null;- /** Index of the step whose continue rate fell the most. */- stepIndex: number;-}--/** The funnel whose conversion fell the most, and the step transition that lost the most ground. */-export function biggestDecline(rows: FunnelRowData[]): FunnelDecline | null {- const worst = biggestMove(rows, "down");- if (!worst) return null;-- const { current, previous } = worst.row;- let stepIndex: number | null = null;- let largestFall = 0;- current!.steps.forEach((step, index) => {- const before = previous!.steps[index]?.continueRate;- if (step.continueRate === null || before == null) return;- const fall = before - step.continueRate;- if (fall > largestFall) {- largestFall = fall;- stepIndex = index;- }- });- if (stepIndex === null) return null;-- const enteredDelta = percentDelta(current!.entered, previous!.entered);- return {- row: worst.row,- delta: worst.delta,- enteredDelta: enteredDelta?.direction === "up" ? enteredDelta : null,- stepIndex,- };-}-/** The funnel with the highest conversion this period: the stat band's third cell when there is no comparison. */export function highestConversion(rows: FunnelRowData[]): FunnelRowData | null {let best: FunnelRowData | null = null;diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsxindex 3eb7951f6..c09e244e4 100644--- a/client/src/app/[site]/funnels/page.tsx+++ b/client/src/app/[site]/funnels/page.tsx@@ -13,8 +13,6 @@ import { ErrorState } from "@/components/ErrorState";import { ExternalLink } from "@/components/ExternalLink";import { NothingFound } from "@/components/NothingFound";import { AnalysisBar } from "@/components/site/AnalysisBar";-import { InsightRow } from "@/components/site/InsightRow";-import { Button } from "@/components/ui/button";import { Card } from "@/components/ui/card";import { Input } from "@/components/ui/input";import { Skeleton } from "@/components/ui/skeleton";@@ -25,19 +23,10 @@ import { useComparisonEnabled, useStore, useTimezone } from "@/lib/store";import { cn } from "@/lib/utils";import { SubHeader } from "../components/SubHeader/SubHeader";import { CreateFunnelDialog } from "./components/CreateFunnel";-import {- biggestDecline,- FunnelRowData,- FunnelSort,- metricsFromSummary,- searchFunnels,- sortFunnels,- stepLabel,-} from "./components/funnelMetrics";+import { FunnelRowData, FunnelSort, metricsFromSummary, searchFunnels, sortFunnels } from "./components/funnelMetrics";import { FUNNEL_ROW_GRID, FunnelRow } from "./components/FunnelRow";import { FunnelSortControl } from "./components/FunnelSortControl";import { FunnelStatBand } from "./components/FunnelStatBand";-import { useStepTypeLabels } from "./components/useStepTypeLabels";const FunnelRowSkeleton = () => (<Card className="@container">@@ -69,7 +58,6 @@ export default function FunnelsPage() {const comparisonEnabled = useComparisonEnabled();const canWrite = useCanOnSite("funnels:write");const search = useSearchParams().toString();- const typeLabels = useStepTypeLabels();const { data: funnels, isLoading, error } = useGetFunnels(site);const current = useGetFunnelSummaries();@@ -122,15 +110,6 @@ export default function FunnelsPage() {setSearchQuery(next);};- const openFunnel = (id: number) => {- setSearchQuery("");- setOpenIds(effectiveOpenIds.includes(id) ? effectiveOpenIds : [...effectiveOpenIds, id]);- // After the row has rendered open.- requestAnimationFrame(() =>- document.getElementById(`funnel-${id}`)?.scrollIntoView({ block: "nearest", behavior: "smooth" })- );- };-// Goals are only read to link an open funnel's last step.const { data: goals } = useGetFunnelGoals({ enabled: effectiveOpenIds.length > 0 });@@ -140,12 +119,6 @@ export default function FunnelsPage() {const comparisonLabel = comparisonEnabled ? describeComparisonWindow(previousTime, time, zone) : null;- const decline = previousData ? biggestDecline(rows) : null;- const declineStep = (offset: number) => {- const step = decline!.row.funnel.steps[decline!.stepIndex + offset];- return stepLabel(step, typeLabels[step.type] ?? typeLabels.event);- };-const hasFunnels = !!funnels?.length;return (@@ -186,39 +159,6 @@ export default function FunnelsPage() {</>)}- {decline && (- <InsightRow- action={- <Button variant="ghost" size="xs" onClick={() => openFunnel(decline.row.funnel.id)}>- {t("Open funnel")}- </Button>- }- >- {decline.enteredDelta- ? t.rich(- "<name>{funnel}</name> converts {change} lower than the comparison period while sessions entering it are up {entered}. The largest fall is between {from} and {to}.",- {- funnel: decline.row.funnel.name,- change: decline.delta.text,- entered: decline.enteredDelta.text,- from: declineStep(0),- to: declineStep(1),- name: chunks => <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>,- }- )- : t.rich(- "<name>{funnel}</name> converts {change} lower than the comparison period. The largest fall is between {from} and {to}.",- {- funnel: decline.row.funnel.name,- change: decline.delta.text,- from: declineStep(0),- to: declineStep(1),- name: chunks => <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>,- }- )}- </InsightRow>- )}-{isLoading || !funnels ? (error ? (<ErrorStatediff --git a/client/src/app/[site]/goals/utils/goalLedger.test.ts b/client/src/app/[site]/goals/utils/goalLedger.test.tsindex ad202dfab..b5c3f109c 100644--- a/client/src/app/[site]/goals/utils/goalLedger.test.ts+++ b/client/src/app/[site]/goals/utils/goalLedger.test.ts@@ -310,8 +310,6 @@ describe("funnelRefs", () => {steps,createdAt: "",updatedAt: "",- conversionRate: null,- totalVisitors: null,});const funnels = [funnel(1, [diff --git a/client/src/app/[site]/journeys/components/PathSessionsSheet.tsx b/client/src/app/[site]/journeys/components/PathSessionsSheet.tsxindex a2db9e2d6..bf0b85030 100644--- a/client/src/app/[site]/journeys/components/PathSessionsSheet.tsx+++ b/client/src/app/[site]/journeys/components/PathSessionsSheet.tsx@@ -34,7 +34,7 @@ function PathSessions({ target, shape }: { target: PathSessionsTarget; shape: Jo...shape,path: target.path,replaysOnly,- page,+ offset: (page - 1) * PAGE_SIZE,limit: PAGE_SIZE + 1,});const sessions = data ?? [];diff --git a/client/src/app/[site]/journeys/components/journeyUtils.test.ts b/client/src/app/[site]/journeys/components/journeyUtils.test.tsindex d5d385b7b..a5372a1a0 100644--- a/client/src/app/[site]/journeys/components/journeyUtils.test.ts+++ b/client/src/app/[site]/journeys/components/journeyUtils.test.ts@@ -3,7 +3,6 @@ import {buildSankeyGraph,connectedLinkIds,JourneyRow,- largestExit,layoutSankey,linkId,nodeId,@@ -178,28 +177,6 @@ describe("pathContinuation", () => {});});-describe("largestExit", () => {- it("picks the path where the most sessions ended while others carried on", () => {- expect(largestExit(JOURNEYS, 4)).toEqual({ path: ["/", "/pricing"], exits: 300, sessions: 450 });- });-- it("skips a path nobody on the shown paths continues: nothing to compare the exits with", () => {- expect(largestExit([journey(["/blog", "/pricing"], 900), ...JOURNEYS], 4)).toEqual({- path: ["/", "/pricing"],- exits: 300,- sessions: 450,- });- });-- it("skips paths that fill every step, which may not have ended", () => {- expect(largestExit([journey(["/", "/a"], 10), journey(["/", "/b"], 5)], 2)).toBeNull();- });-- it("is null without journeys", () => {- expect(largestExit([], 4)).toBeNull();- });-});-describe("layoutSankey", () => {const graph = buildSankeyGraph(JOURNEYS, 4);const layout = layoutSankey(graph, 4, 1104);diff --git a/client/src/app/[site]/journeys/components/journeyUtils.ts b/client/src/app/[site]/journeys/components/journeyUtils.tsindex 0a891b3f3..a881e1e20 100644--- a/client/src/app/[site]/journeys/components/journeyUtils.ts+++ b/client/src/app/[site]/journeys/components/journeyUtils.ts@@ -195,33 +195,6 @@ export function pathContinuation(journeys: JourneyRow[], path: string[]): Contin});}-export interface PathExit {- path: string[];- /** Sessions that took exactly this path and ended there. */- exits: number;- /** Sessions on the shown paths that started with this path. */- sessions: number;-}--/**- * The shown path where the most sessions ended while others carried on: a- * journey shorter than `steps` (so the session ended on its last page) that at- * least one other shown journey continues.- */-export function largestExit(journeys: JourneyRow[], steps: number): PathExit | null {- let best: PathExit | null = null;- for (const journey of journeys) {- if (journey.path.length >= steps || journey.path.length < 2) continue;- if (best && journey.count <= best.exits) continue;- const sessions = journeys.reduce(- (total, other) => (startsWithPath(other.path, journey.path) ? total + other.count : total),- 0- );- if (sessions > journey.count) best = { path: journey.path, exits: journey.count, sessions };- }- return best;-}-// βββββββββ layout βββββββββexport interface LaidOutNode extends SankeyNode {diff --git a/client/src/app/[site]/journeys/page.tsx b/client/src/app/[site]/journeys/page.tsxindex 66f53f66f..128a0342a 100644--- a/client/src/app/[site]/journeys/page.tsx+++ b/client/src/app/[site]/journeys/page.tsx@@ -3,7 +3,7 @@import { FolderTree, LogIn, LogOut, Route, Target } from "lucide-react";import { useExtracted } from "next-intl";import Link from "next/link";-import { ReactNode, useMemo, useState } from "react";+import { useMemo, useState } from "react";import { useGetSite } from "@/api/admin/hooks/useSites";import { JourneyGrouping } from "@/api/analytics/endpoints";import { useGetGoals } from "@/api/analytics/hooks/goals/useGetGoals";@@ -13,7 +13,6 @@ import { DisabledOverlay } from "@/components/DisabledOverlay";import { ErrorState } from "@/components/ErrorState";import { AnalysisBar } from "@/components/site/AnalysisBar";import { ChartLegend } from "@/components/site/ChartLegend";-import { InsightRow } from "@/components/site/InsightRow";import { Button } from "@/components/ui/button";import { Card, CardLoader } from "@/components/ui/card";import { Skeleton } from "@/components/ui/skeleton";@@ -30,9 +29,8 @@ import {StepsStepper,} from "./components/JourneyControls";import { JourneyStats } from "./components/JourneyStats";-import { formatShare, largestExit, pathKey, sectionOfPage } from "./components/journeyUtils";+import { formatShare, pathKey, sectionOfPage } from "./components/journeyUtils";import { PathActionHandlers, PathActions } from "./components/PathActions";-import { PathChips } from "./components/PathChips";import { PathSessionsSheet, PathSessionsTarget } from "./components/PathSessionsSheet";import { PinnedPath } from "./components/PinnedPath";import { SankeyDiagram } from "./components/SankeyDiagram";@@ -162,7 +160,6 @@ export default function JourneysPage() {const isLoading = isLoadingGoals || journeysQuery.isLoading || !siteMetadata;const covered = journeys.reduce((total, journey) => total + journey.count, 0);const pinnedJourney = journeys.find(journey => pathKey(journey.path) === pinnedKey);- const exit = exitsKnown && !isLoading ? largestExit(journeys, steps) : null;const previousJourneys = previousJourneysQuery.data?.journeys;const previousCounts = useMemo(@@ -199,10 +196,6 @@ export default function JourneysPage() {saveAsFunnel: canWriteFunnels && !privateKey ? setFunnelPath : undefined,};- const strong = (chunks: ReactNode) => (- <span className="font-medium tabular-nums text-neutral-900 dark:text-neutral-50">{chunks}</span>- );-return (<DisabledOverlay message="User Journeys" featurePath="journeys"><div className="mx-auto max-w-[1300px] space-y-3 p-2 md:p-4">@@ -244,21 +237,6 @@ export default function JourneysPage() {/></AnalysisBar>- {exit && (- <InsightRow action={<PathActions path={exit.path} handlers={handlers} hideFunnel className="shrink-0" />}>- {t.rich(- "<b>{percent}</b> of sessions that start <path></path> end there ({exits} of {sessions}), the largest exit on the paths shown.",- {- percent: `${((exit.exits / exit.sessions) * 100).toFixed(1)}%`,- exits: exit.exits.toLocaleString(),- sessions: exit.sessions.toLocaleString(),- b: strong,- path: () => <PathChips path={exit.path} pageHref={pageHref} className="mx-0.5 align-middle" />,- }- )}- </InsightRow>- )}-<Card>{journeysQuery.isFetching && !isLoading && <CardLoader />}<div className="flex flex-col gap-3 border-b border-neutral-100 px-4 py-3 xl:flex-row xl:items-center xl:justify-between dark:border-neutral-850">diff --git a/client/src/app/[site]/pages/components/PagesInsight.tsx b/client/src/app/[site]/pages/components/PagesInsight.tsxdeleted file mode 100644index 35d8bcda7..000000000--- a/client/src/app/[site]/pages/components/PagesInsight.tsx+++ /dev/null@@ -1,54 +0,0 @@-"use client";--import { useExtracted } from "next-intl";-import { useGetPagesSummary } from "@/api/analytics/hooks/useGetPages";-import { InsightRow } from "@/components/site/InsightRow";-import { Button } from "@/components/ui/button";-import { percentDelta } from "@/lib/delta";-import { useComparisonEnabled } from "@/lib/store";-import { formatSection } from "./pageIdentity";-import { findOnlyLosingSection, LosingSection } from "./losingSection";--/**- * One sentence, shown only when it is exactly true: a single section has fewer- * views than in the comparison period while every other section held or grew.- */-export function PagesInsight({ onShowSection }: { onShowSection: (section: LosingSection) => void }) {- const t = useExtracted();- const comparing = useComparisonEnabled();- const current = useGetPagesSummary();- const previous = useGetPagesSummary({ periodTime: "previous" });-- // Both answers must be for the periods on screen, not the ones before a change.- if (!comparing || current.isPlaceholderData || previous.isPlaceholderData) return null;-- const losing = findOnlyLosingSection(current.data, previous.data);- const change = losing && percentDelta(losing.pageviews, losing.previousPageviews);- // A drop that rounds to 0.0% is not worth a sentence.- if (!losing || change?.direction !== "down") return null;-- const section = formatSection(losing.section);-- return (- <InsightRow- action={- losing.rank !== null && (- <Button type="button" variant="ghost" size="xs" onClick={() => onShowSection(losing)}>- {t("Show {section} pages", { section })}- </Button>- )- }- >- {t.rich(- "<name>{section}</name> is the only section losing traffic: {views} views, down {change} from {previous}.",- {- name: chunks => <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>,- section,- views: losing.pageviews.toLocaleString(),- change: change.text,- previous: losing.previousPageviews.toLocaleString(),- }- )}- </InsightRow>- );-}diff --git a/client/src/app/[site]/pages/components/PagesTable.tsx b/client/src/app/[site]/pages/components/PagesTable.tsxindex 148c67992..50c4d0a72 100644--- a/client/src/app/[site]/pages/components/PagesTable.tsx+++ b/client/src/app/[site]/pages/components/PagesTable.tsx@@ -104,8 +104,6 @@ interface TableContextValue {domain: string | undefined;expanded: ReadonlySet<string>;onToggleSection: (section: string) => void;- focusSection: string | null;- onFocusHandled: () => void;}const TableContext = createContext<TableContextValue | null>(null);@@ -260,25 +258,12 @@ function PageTableRow({ row, figures, child }: { row: PageRow; figures: RowFigurfunction SectionTableRow({ row, figures }: { row: PageRow; figures: RowFigures }) {const t = useExtracted();- const { expanded, onToggleSection, focusSection, onFocusHandled } = useTableContext();+ const { expanded, onToggleSection } = useTableContext();const isOpen = expanded.has(row.key);const label = formatSection(row.key);return (- <TableRow- // Scrolls to the section the insight row points at, once it is on screen.- ref={- focusSection === row.key- ? node => {- if (!node) return;- node.scrollIntoView({ block: "center", behavior: "smooth" });- onFocusHandled();- }- : undefined- }- onClick={() => onToggleSection(row.key)}- className="cursor-pointer bg-neutral-50 dark:bg-neutral-850/60"- >+ <TableRow onClick={() => onToggleSection(row.key)} className="cursor-pointer bg-neutral-50 dark:bg-neutral-850/60"><TableCell className="py-1.5 pl-2 pr-3"><div className="flex min-w-0 items-center gap-1"><Button@@ -530,9 +515,6 @@ export interface PagesTableProps {onPageChange: (page: number) => void;expanded: ReadonlySet<string>;onExpandedChange: (expanded: Set<string>) => void;- /** A section to scroll to when its row appears. */- focusSection: string | null;- onFocusHandled: () => void;}export function PagesTable({@@ -546,8 +528,6 @@ export function PagesTable({onPageChange,expanded,onExpandedChange,- focusSection,- onFocusHandled,}: PagesTableProps) {const t = useExtracted();const { data: siteMetadata } = useGetSite();@@ -585,8 +565,6 @@ export function PagesTable({if (!next.delete(section)) next.add(section);onExpandedChange(next);},- focusSection,- onFocusHandled,};if (isError) {diff --git a/client/src/app/[site]/pages/components/losingSection.test.ts b/client/src/app/[site]/pages/components/losingSection.test.tsdeleted file mode 100644index 91807c05d..000000000--- a/client/src/app/[site]/pages/components/losingSection.test.ts+++ /dev/null@@ -1,113 +0,0 @@-import { describe, expect, it } from "vitest";--import type { PagesSummary, SectionViews } from "@/api/analytics/hooks/useGetPages";-import { findOnlyLosingSection } from "./losingSection";--const summary = (sections: [string, number, number][], sectionCount = sections.length): PagesSummary => ({- pageviews: 0,- sessions: 0,- pages: 0,- bounced_sessions: 0,- bounce_rate: null,- time_on_page_seconds: null,- views_per_session: null,- sections: sections.map(([section, pageviews, pages]): SectionViews => ({ section, pageviews, pages })),- sectionCount,-});--describe("findOnlyLosingSection", () => {- it("names the section when it alone lost views", () => {- const current = summary([- ["/docs", 500, 12],- ["/", 300, 1],- ["/blog", 180, 8],- ]);- const previous = summary([- ["/docs", 450, 11],- ["/", 400, 1],- ["/blog", 200, 8],- ]);-- // "/" lost views too, but a single page is not a section.- expect(findOnlyLosingSection(current, previous)).toEqual({- section: "/blog",- pageviews: 180,- previousPageviews: 200,- rank: 2,- });- });-- it("says nothing when no section or several sections lost views", () => {- const previous = summary([- ["/docs", 450, 11],- ["/blog", 200, 8],- ]);-- expect(- findOnlyLosingSection(- summary([- ["/docs", 500, 12],- ["/blog", 200, 8],- ]),- previous- )- ).toBeNull();- expect(- findOnlyLosingSection(- summary([- ["/docs", 400, 12],- ["/blog", 180, 8],- ]),- previous- )- ).toBeNull();- });-- it("needs another section to compare with", () => {- expect(findOnlyLosingSection(summary([["/docs", 400, 12]]), summary([["/docs", 450, 11]]))).toBeNull();- });-- it("counts a section that lost all its traffic", () => {- const current = summary([["/docs", 500, 12]]);- const previous = summary([- ["/docs", 450, 11],- ["/blog", 200, 8],- ]);-- expect(findOnlyLosingSection(current, previous)).toEqual({- section: "/blog",- pageviews: 0,- previousPageviews: 200,- rank: null,- });- });-- it("does not point at a section that is down to one page", () => {- const current = summary([- ["/docs", 500, 12],- ["/blog", 50, 1],- ]);- const previous = summary([- ["/docs", 450, 11],- ["/blog", 200, 8],- ]);-- expect(findOnlyLosingSection(current, previous)?.rank).toBeNull();- });-- it("says nothing without a comparison or when either section list was capped", () => {- const current = summary([- ["/docs", 500, 12],- ["/blog", 180, 8],- ]);- const previous = summary([- ["/docs", 450, 11],- ["/blog", 200, 8],- ]);-- expect(findOnlyLosingSection(current, undefined)).toBeNull();- expect(findOnlyLosingSection(undefined, previous)).toBeNull();- expect(findOnlyLosingSection({ ...current, sectionCount: 900 }, previous)).toBeNull();- expect(findOnlyLosingSection(current, { ...previous, sectionCount: 900 })).toBeNull();- });-});diff --git a/client/src/app/[site]/pages/components/losingSection.ts b/client/src/app/[site]/pages/components/losingSection.tsdeleted file mode 100644index 5a3f0121b..000000000--- a/client/src/app/[site]/pages/components/losingSection.ts+++ /dev/null@@ -1,51 +0,0 @@-import type { PagesSummary } from "@/api/analytics/hooks/useGetPages";--export interface LosingSection {- section: string;- pageviews: number;- previousPageviews: number;- /**- * Where the section sits among the top-level rows sorted by views, or null- * when it is not a row of its own in this period (fewer than two pages left).- */- rank: number | null;-}--// A list the server capped cannot prove that no other section lost traffic.-const isComplete = (summary: PagesSummary) => summary.sections.length >= summary.sectionCount;--/**- * The one section with fewer views than in the comparison period, when every- * other section held or grew. Null in every other case: no comparison, a- * capped section list, fewer than two sections, or none or several losing.- *- * A section is a first path segment with two or more pages in either period,- * so one that lost all its traffic still counts as losing.- */-export function findOnlyLosingSection(- current: PagesSummary | undefined,- previous: PagesSummary | undefined-): LosingSection | null {- if (!current || !previous || !isComplete(current) || !isComplete(previous)) return null;-- const now = new Map(current.sections.map(section => [section.section, section]));- const before = new Map(previous.sections.map(section => [section.section, section]));-- const sections = [...new Set([...now.keys(), ...before.keys()])].filter(- key => (now.get(key)?.pages ?? 0) >= 2 || (before.get(key)?.pages ?? 0) >= 2- );- if (sections.length < 2) return null;-- const losing = sections.filter(key => (now.get(key)?.pageviews ?? 0) < (before.get(key)?.pageviews ?? 0));- if (losing.length !== 1) return null;-- const [section] = losing;- const rank = current.sections.findIndex(candidate => candidate.section === section);-- return {- section,- pageviews: now.get(section)?.pageviews ?? 0,- previousPageviews: before.get(section)?.pageviews ?? 0,- rank: rank !== -1 && (now.get(section)?.pages ?? 0) >= 2 ? rank : null,- };-}diff --git a/client/src/app/[site]/pages/page.tsx b/client/src/app/[site]/pages/page.tsxindex c65cf4fda..33cf0593b 100644--- a/client/src/app/[site]/pages/page.tsx+++ b/client/src/app/[site]/pages/page.tsx@@ -12,9 +12,8 @@ import { useSetPageTitle } from "@/hooks/useSetPageTitle";import { useStore } from "@/lib/store";import { DisabledOverlay } from "../../../components/DisabledOverlay";import { SubHeader } from "../components/SubHeader/SubHeader";-import { PagesInsight } from "./components/PagesInsight";import { PagesStatBand } from "./components/PagesStatBand";-import { PAGE_SIZE, PagesTable } from "./components/PagesTable";+import { PagesTable } from "./components/PagesTable";type Breakdown = "section" | "none";@@ -42,7 +41,6 @@ export default function Pages() {const page = paging.scope === scope ? paging.page : 1;const setPage = (next: number) => setPaging({ page: next, scope });const [expanded, setExpanded] = useState<Set<string>>(() => new Set());- const [focusSection, setFocusSection] = useState<string | null>(null);const debouncedSearch = useDebounce(search.trim(), 300);// Typing waits for a pause; clearing the box applies at once.@@ -54,11 +52,8 @@ export default function Pages() {return null;}- // Any change to what is listed starts again from the first page, and drops a pending scroll.- const restart = () => {- setPage(1);- setFocusSection(null);- };+ // Any change to what is listed starts again from the first page.+ const restart = () => setPage(1);return (<DisabledOverlay message={t("pages")} featurePath="pages">@@ -114,19 +109,6 @@ export default function Pages() {]}/></AnalysisBar>- <PagesInsight- onShowSection={({ section, rank }) => {- if (rank === null) return;- // The section's place among the rows sorted by views is its place in the default table.- setBreakdown("section");- setMode("all");- setSorting({ sort: "pageviews", order: "desc" });- setSearch("");- setPage(Math.floor(rank / PAGE_SIZE) + 1);- setExpanded(current => new Set(current).add(section));- setFocusSection(section);- }}- /><PagesTable// A search lists the matching pages themselves: a rollup of a few matches would read as the section's total.group={breakdown === "section" && !activeSearch ? "section" : "page"}@@ -145,8 +127,6 @@ export default function Pages() {onPageChange={setPage}expanded={expanded}onExpandedChange={setExpanded}- focusSection={focusSection}- onFocusHandled={() => setFocusSection(null)}/></div></DisabledOverlay>diff --git a/client/src/app/[site]/performance/components/PerformanceChart.tsx b/client/src/app/[site]/performance/components/PerformanceChart.tsxindex 8e2cd8480..7b86098b7 100644--- a/client/src/app/[site]/performance/components/PerformanceChart.tsx+++ b/client/src/app/[site]/performance/components/PerformanceChart.tsx@@ -1,26 +1,27 @@"use client";-import type { Annotation, TimeBucket } from "@rybbit/shared";-import * as d3 from "d3";+import type { Annotation } from "@rybbit/shared";import { DateTime } from "luxon";import { useExtracted } from "next-intl";+import { useTheme } from "next-themes";import { useEffect, useMemo, useState } from "react";import { createPortal } from "react-dom";-import { ChartLegend, ChartLegendItem } from "@/components/site/ChartLegend";import { Card, CardLoader } from "@/components/ui/card";import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";import { Skeleton } from "@/components/ui/skeleton";-import { cn, formatter } from "@/lib/utils";-import { GetPerformanceTimeSeriesResponse } from "../../../../api/analytics/endpoints";import { useGetPerformanceTimeSeries } from "../../../../api/analytics/hooks/performance/useGetPerformanceTimeSeries";import { ChartTooltip } from "../../../../components/charts/ChartTooltip";import { TimeSeriesChart } from "../../../../components/charts/TimeSeriesChart";-import type { TimeSeriesChartPoint, TimeSeriesOverlayContext } from "../../../../components/charts/TimeSeriesChart";-import { bucketsBetween, getChartTimeBounds, shiftBuckets } from "../../../../components/charts/timeSeriesChartUtils";-import { describeComparisonWindow } from "../../../../components/DateSelector/rangeFields";+import type {+ TimeSeriesChartMarker,+ TimeSeriesChartPoint,+ TimeSeriesChartSeries,+} from "../../../../components/charts/TimeSeriesChart";+import { getChartTimeBounds } from "../../../../components/charts/timeSeriesChartUtils";+import { ToggleChip } from "../../../../components/ToggleChip";import { formatChartDateTime } from "../../../../lib/dateTimeUtils";-import { useComparisonEnabled, useStore, useTimezone } from "../../../../lib/store";+import { useStore, useTimezone } from "../../../../lib/store";import {AnnotationHoverCard,AnnotationPopoverContent,@@ -28,234 +29,69 @@ import {import { AnnotationPins } from "../../main/components/MainSection/annotations/AnnotationPins";import type { AnnotationCluster } from "../../main/components/MainSection/annotations/annotationUtils";import { PercentileLevel, PerformanceMetric, usePerformanceStore } from "../performanceStore";-import {- formatMetric,- getMetricRating,- getPerformanceThresholds,- MetricRating,- RATING_COLOR,- RATING_TEXT_CLASS,-} from "../utils/performanceUtils";+import { formatMetric, getMetricRating, getPerformanceThresholds, RATING_COLOR } from "../utils/performanceUtils";import { useVisibleAnnotations } from "../utils/useVisibleAnnotations";import { RatingMark, useMetricNames, useRatingLabels } from "./shared/RatingMark";-const DATA_COLOR = "hsl(var(--dataviz))";-const RANGE_COLOR = "hsl(var(--dataviz) / 0.35)";-const PREVIOUS_COLOR = "hsl(var(--neutral-500))";-const TOOLTIP_PERCENTILES: PercentileLevel[] = ["p99", "p90", "p75", "p50"];+const PERCENTILES: PercentileLevel[] = ["p50", "p75", "p90", "p99"];++// One hue, deeper for the slower percentiles, so the lines read in order. The+// light ramp starts a step darker to keep p50 visible on white.+const PERCENTILE_COLORS: Record<"light" | "dark", Record<PercentileLevel, string>> = {+ dark: {+ p50: "hsl(var(--indigo-200))",+ p75: "hsl(var(--indigo-300))",+ p90: "hsl(var(--indigo-400))",+ p99: "hsl(var(--indigo-500))",+ },+ light: {+ p50: "hsl(var(--indigo-300))",+ p75: "hsl(var(--indigo-400))",+ p90: "hsl(var(--indigo-500))",+ p99: "hsl(var(--indigo-700))",+ },+};// TimeSeriesChart never lets its y axis end below 1, which flattens a metric// measured in hundredths. CLS is plotted in thousandths and printed back in// its own unit.const plotScaleOf = (metric: PerformanceMetric) => (metric === "cls" ? 1000 : 1);-type TimeSeriesRow = GetPerformanceTimeSeriesResponse[number];-const isMeasured = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value);type VitalPoint = TimeSeriesChartPoint & {time: DateTime;loads: number;- /** The metric at every percentile, in its own unit. */- percentiles: Record<PercentileLevel, number | null>;+ /** The value in the metric's own unit. */+ value: number;};-type RangePoint = { x: Date; low: number; high: number };-type PreviousPoint = TimeSeriesChartPoint & { value: number; originalTime: DateTime };-type LoadsBar = { x: Date; loads: number };--const percentilesOf = (row: TimeSeriesRow, metric: PerformanceMetric): Record<PercentileLevel, number | null> => ({- p50: row[`${metric}_p50`],- p75: row[`${metric}_p75`],- p90: row[`${metric}_p90`],- p99: row[`${metric}_p99`],-});-type PinTarget = { cluster: AnnotationCluster; rect: DOMRect };-/**- * Everything the chart adds to a plain line: the rating bands, the p50 to p90- * range, the previous period, and the loads each bucket rests on. It is drawn- * through TimeSeriesChart's overlay, so it shares the chart's scales exactly;- * the zone labels and the loads strip sit just outside the plot, in padding- * the wrapper reserves for them.- */-function VitalsOverlay({- context,- metric,- line,- range,- previous,- bars,- bucket,- ratingLabels,- loadsLabel,-}: {- context: TimeSeriesOverlayContext;- metric: PerformanceMetric;- line: VitalPoint[];- range: RangePoint[];- previous: PreviousPoint[];- bars: LoadsBar[];- bucket: TimeBucket;- ratingLabels: Record<MetricRating, string>;- loadsLabel: string;-}) {- const { xScale, yScale, plotLeft, plotRight, plotTop, plotBottom, isDark } = context;- const thresholds = getPerformanceThresholds(metric);- const scale = plotScaleOf(metric);- const clampY = (value: number) => Math.max(plotTop, Math.min(plotBottom, yScale(value * scale)));- const goodY = clampY(thresholds.good);- const poorY = clampY(thresholds.needs_improvement);-- const linePath = d3- .line<TimeSeriesChartPoint>()- .x(d => xScale(d.x))- .y(d => yScale(d.y));- const rangePath = d3- .area<RangePoint>()- .x(d => xScale(d.x))- .y0(d => yScale(d.low))- .y1(d => yScale(d.high));-- const zones: { rating: MetricRating; y: number }[] = [- { rating: "good", y: (plotBottom + goodY) / 2 },- { rating: "needs_improvement", y: (goodY + poorY) / 2 },- { rating: "poor", y: (poorY + plotTop) / 2 },- ];-- const axisColor = isDark ? "hsl(var(--neutral-400))" : "hsl(var(--neutral-500))";- const gridColor = isDark ? "hsl(var(--neutral-800))" : "hsl(var(--neutral-100))";- // Below the x axis labels.- const stripTop = plotBottom + 34;- const stripBottom = stripTop + 32;- const maxLoads = bars.reduce((largest, bar) => Math.max(largest, bar.loads), 0);- const bucketWidth = bars.length- ? xScale(shiftBuckets(DateTime.fromJSDate(bars[0].x), bucket, 1).toJSDate()) - xScale(bars[0].x)- : 0;- const barWidth = Math.max(1, Math.min(24, bucketWidth * 0.62));- // The first bar is centred on the plot's left edge, so its labels start left of it.- const labelX = plotLeft - barWidth / 2 - 6;-- return (- <g pointerEvents="none">- <rect- x={plotLeft}- y={poorY}- width={plotRight - plotLeft}- height={goodY - poorY}- fill={RATING_COLOR.needs_improvement}- opacity={0.05}- />- <rect- x={plotLeft}- y={plotTop}- width={plotRight - plotLeft}- height={poorY - plotTop}- fill={RATING_COLOR.poor}- opacity={0.07}- />- {zones.map(zone => (- <text- key={zone.rating}- x={plotRight + 10}- y={zone.y}- dy="0.35em"- fontSize={11}- className={cn("hidden fill-current md:block", RATING_TEXT_CLASS[zone.rating])}- >- {ratingLabels[zone.rating]}- </text>- ))}-- {range.length > 1 && <path d={rangePath(range) ?? ""} fill={DATA_COLOR} opacity={0.13} />}- {/* The two limits, above the range so it does not wash them out. */}- <line- x1={plotLeft}- x2={plotRight}- y1={goodY}- y2={goodY}- stroke={RATING_COLOR.good}- strokeDasharray="6 5"- opacity={0.75}- />- <line- x1={plotLeft}- x2={plotRight}- y1={poorY}- y2={poorY}- stroke={RATING_COLOR.poor}- strokeDasharray="6 5"- opacity={0.75}- />- {previous.length > 0 && (- <path- d={linePath(previous) ?? ""}- fill="none"- stroke={PREVIOUS_COLOR}- strokeWidth={1.5}- strokeDasharray="4 4"- strokeLinejoin="round"- />- )}- {/* Again, so the measured line stays above the range and the previous period. */}- <path d={linePath(line) ?? ""} fill="none" stroke={DATA_COLOR} strokeWidth={2} strokeLinejoin="round" />-- {maxLoads > 0 && (- <g>- <line x1={plotLeft} x2={plotRight} y1={stripBottom} y2={stripBottom} stroke={gridColor} strokeWidth={1} />- <text x={labelX} y={stripTop} dy="0.7em" textAnchor="end" fontSize={11} fill={axisColor}>- {formatter(maxLoads)}- </text>- <text x={labelX} y={stripBottom} textAnchor="end" fontSize={11} fill={axisColor}>- 0- </text>- {bars.map(bar => {- const height = Math.max(1, (bar.loads / maxLoads) * (stripBottom - stripTop));- return (- <rect- key={bar.x.getTime()}- x={xScale(bar.x) - barWidth / 2}- y={stripBottom - height}- width={barWidth}- height={height}- rx={Math.min(1.5, barWidth / 2)}- fill={DATA_COLOR}- opacity={0.4}- />- );- })}- <text- x={plotRight + 10}- y={(stripTop + stripBottom) / 2}- dy="0.35em"- fontSize={11}- fill={axisColor}- className="hidden md:block"- >- {loadsLabel}- </text>- </g>- )}- </g>- );-}-export function PerformanceChart() {const t = useExtracted();- const { site, bucket, time, previousTime } = useStore();+ const { site, bucket, time } = useStore();const timezone = useTimezone();- const comparisonEnabled = useComparisonEnabled();- const { selectedPerformanceMetric: metric, selectedPercentile: percentile, showAnnotations } = usePerformanceStore();+ const { resolvedTheme } = useTheme();+ const { selectedPerformanceMetric: metric, showAnnotations } = usePerformanceStore();const metricNames = useMetricNames();const ratingLabels = useRatingLabels();const visibleAnnotations = useVisibleAnnotations();const annotations: Annotation[] = showAnnotations ? visibleAnnotations : [];+ const colors = PERCENTILE_COLORS[resolvedTheme === "light" ? "light" : "dark"];++ const [visiblePercentiles, setVisiblePercentiles] = useState<ReadonlySet<PercentileLevel>>(+ () => new Set<PercentileLevel>(["p50", "p75", "p90"])+ );+ const togglePercentile = (percentile: PercentileLevel) =>+ setVisiblePercentiles(current => {+ const next = new Set(current);+ if (next.has(percentile)) next.delete(percentile);+ else next.add(percentile);+ return next;+ });const { data, isLoading, isFetching } = useGetPerformanceTimeSeries({ site });- const { data: previousSeries } = useGetPerformanceTimeSeries({ site, periodTime: "previous" });- // A query that is switched off keeps its last result as a placeholder.- const previousData = comparisonEnabled ? previousSeries : undefined;const [hoveredPin, setHoveredPin] = useState<PinTarget | null>(null);const [selectedPin, setSelectedPin] = useState<PinTarget | null>(null);@@ -264,114 +100,64 @@ export function PerformanceChart() {useEffect(() => {setSelectedPin(null);setHoveredPin(null);- }, [time, bucket, site, metric, percentile, showAnnotations]);+ }, [time, bucket, site, metric, showAnnotations]);const thresholds = getPerformanceThresholds(metric);const scale = plotScaleOf(metric);- const { line, range, bars, previous, previousByTime, chartMin, chartMax, max } = useMemo(() => {+ const { series, chartMin, chartMax, max } = useMemo(() => {const { min: boundsMin, max: boundsMax } = getChartTimeBounds(time, bucket, timezone);const now = DateTime.now();const lowerBoundMs = boundsMin?.getTime();const upperBoundMs = (boundsMax ?? now.toJSDate()).getTime();- // Stale rows from the period just left must not land on the new x axis.- const inWindow = (ms: number) => (lowerBoundMs === undefined || ms >= lowerBoundMs) && ms <= upperBoundMs;- const line: VitalPoint[] = [];- const range: RangePoint[] = [];- const bars: LoadsBar[] = [];+ const points = new Map<PercentileLevel, VitalPoint[]>(PERCENTILES.map(level => [level, []]));data?.forEach(row => {const timestamp = DateTime.fromSQL(row.time, { zone: timezone }).toUTC();+ const ms = timestamp.toMillis();const loads = Number(row.event_count) || 0;- // A bucket nobody loaded a page in is a gap, not a zero.- if (timestamp > now || !inWindow(timestamp.toMillis()) || loads <= 0) return;-- const x = timestamp.toJSDate();- const percentiles = percentilesOf(row, metric);- bars.push({ x, loads });- const value = percentiles[percentile];- if (isMeasured(value)) line.push({ x, y: value * scale, time: timestamp, loads, percentiles });- if (isMeasured(percentiles.p50) && isMeasured(percentiles.p90)) {- range.push({ x, low: percentiles.p50 * scale, high: percentiles.p90 * scale });- }+ // Stale rows from the period just left must not land on the new x axis,+ // and a bucket nobody loaded a page in is a gap, not a zero.+ if (timestamp > now || (lowerBoundMs !== undefined && ms < lowerBoundMs) || ms > upperBoundMs) return;+ if (loads <= 0) return;++ PERCENTILES.forEach(level => {+ if (!visiblePercentiles.has(level)) return;+ const value = row[`${metric}_${level}`];+ if (!isMeasured(value)) return;+ points.get(level)?.push({ x: timestamp.toJSDate(), y: value * scale, value, time: timestamp, loads });+ });});- // The previous period is moved onto this period's x axis by a whole number- // of buckets, first bucket onto first bucket, as the Main chart does.- const previousMin = previousTime ? getChartTimeBounds(previousTime, bucket, timezone).min : undefined;- const bucketShift =- boundsMin && previousMin- ? bucketsBetween(- DateTime.fromJSDate(previousMin, { zone: timezone }),- DateTime.fromJSDate(boundsMin, { zone: timezone }),- bucket- )- : 0;- const previous: PreviousPoint[] = [];- previousData?.forEach(row => {- const originalTime = DateTime.fromSQL(row.time, { zone: timezone }).toUTC();- const value = row[`${metric}_${percentile}`];- if (!isMeasured(value) || !(Number(row.event_count) > 0)) return;- const mappedMs = shiftBuckets(originalTime.setZone(timezone), bucket, bucketShift).toMillis();- if (!inWindow(mappedMs)) return;- previous.push({ x: new Date(mappedMs), y: value * scale, value, originalTime });- });+ const series: TimeSeriesChartSeries<VitalPoint>[] = PERCENTILES.filter(level => visiblePercentiles.has(level))+ .map(level => ({ id: level, data: points.get(level) ?? [], color: colors[level], strokeWidth: 2 }))+ .filter(item => item.data.length > 0);- const highest = [...line.map(p => p.y), ...range.map(p => p.high), ...previous.map(p => p.y)].reduce(- (largest, y) => Math.max(largest, y),- 0- );+ const all = series.flatMap(item => item.data);+ const highest = all.reduce((largest, point) => Math.max(largest, point.y), 0);return {- line,- range,- bars,- previous,- previousByTime: new Map(previous.map(point => [point.x.getTime(), point])),- chartMin: boundsMin ?? bars[0]?.x,- chartMax: boundsMax ?? bars[bars.length - 1]?.x ?? now.toJSDate(),- // Tall enough to show all three rating bands, with room above the data.- max: Math.max(highest * 1.05, thresholds.needs_improvement * scale * 1.25),+ series,+ chartMin: boundsMin ?? all[0]?.x,+ chartMax: boundsMax ?? all[all.length - 1]?.x ?? now.toJSDate(),+ max: highest * 1.1,};- }, [data, previousData, metric, percentile, scale, thresholds, time, previousTime, bucket, timezone]);-- const interval = (() => {- switch (bucket) {- case "minute":- return t("per minute");- case "five_minutes":- return t("per 5 minutes");- case "ten_minutes":- return t("per 10 minutes");- case "fifteen_minutes":- return t("per 15 minutes");- case "hour":- return t("per hour");- case "day":- return t("per day");- case "week":- return t("per week");- case "month":- return t("per month");- case "year":- return t("per year");- }- })();-- const currentWindow = describeComparisonWindow(time, time, timezone);- const previousWindow = describeComparisonWindow(previousTime, time, timezone);- const legend: ChartLegendItem[] = [- { id: "current", label: currentWindow ? `${percentile}, ${currentWindow}` : percentile, color: DATA_COLOR },- { id: "range", label: t("p50 to p90"), color: RANGE_COLOR },+ }, [data, metric, scale, time, bucket, timezone, visiblePercentiles, colors]);++ const markers: TimeSeriesChartMarker[] = [+ {+ value: thresholds.good * scale,+ color: RATING_COLOR.good,+ strokeDasharray: "6 5",+ label: t("Good β€ {value}", { value: formatMetric(metric, thresholds.good) }),+ },+ {+ value: thresholds.needs_improvement * scale,+ color: RATING_COLOR.poor,+ strokeDasharray: "6 5",+ label: t("Poor > {value}", { value: formatMetric(metric, thresholds.needs_improvement) }),+ },];- if (previous.length > 0) {- legend.push({- id: "previous",- label: previousWindow ? `${percentile}, ${previousWindow}` : t("{percentile}, previous period", { percentile }),- color: PREVIOUS_COLOR,- dashed: true,- });- }const hoverLeft =hoveredPin && typeof window !== "undefined" ? Math.min(hoveredPin.rect.right + 8, window.innerWidth - 272) : 0;@@ -379,58 +165,49 @@ export function PerformanceChart() {return (<Card className="overflow-visible">{isFetching && <CardLoader />}- <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2 p-4 pb-2">- <div className="min-w-0">- <div className="font-semibold leading-none tracking-tight">{metricNames[metric]}</div>- <p className="mt-1.5 text-sm text-neutral-500 dark:text-neutral-400">- {t("{percentile} {interval}. Good up to {good}, poor over {poor}.", {- percentile,- interval,- good: formatMetric(metric, thresholds.good),- poor: formatMetric(metric, thresholds.needs_improvement),- })}{" "}- {t("Select a metric in the band above.")}- </p>+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 p-4 pb-2">+ <div className="font-semibold leading-none tracking-tight">{metricNames[metric]}</div>+ <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={t("Percentiles on the chart")}>+ {PERCENTILES.map(level => (+ <ToggleChip+ key={level}+ isSelected={visiblePercentiles.has(level)}+ onClick={() => togglePercentile(level)}+ swatchColor={colors[level]}+ label={level}+ />+ ))}</div>- {line.length > 0 && <ChartLegend items={legend} className="pt-0.5" />}</div><div className="px-2 pb-3 md:px-4">{isLoading ? (<Skeleton className="h-[300px] w-full rounded-md" />- ) : line.length === 0 ? (+ ) : series.length === 0 ? (<div className="flex h-[300px] w-full items-center justify-center"><div className="text-center text-neutral-500 dark:text-neutral-400">- <p className="text-base font-medium">{t("No performance data available")}</p>- <p className="text-sm">{t("Try adjusting your date range or filters")}</p>+ <p className="text-base font-medium">+ {visiblePercentiles.size === 0 ? t("Pick a percentile to plot") : t("No performance data available")}+ </p>+ {visiblePercentiles.size > 0 && (+ <p className="text-sm">{t("Try adjusting your date range or filters")}</p>+ )}</div></div>) : (- // The padding holds what the overlay draws outside the plot: the loads- // strip below it and, from `md`, the zone labels beside it.- <div className="pb-11 md:pr-28 [&_svg]:overflow-visible">- <div className="h-[260px] w-full">- <TimeSeriesChart- current={[]}- series={[{ id: percentile, data: line, color: DATA_COLOR, strokeWidth: 2 }]}- max={max}- chartMin={chartMin}- chartMax={chartMax}- yTickFormat={value => (value === 0 ? "0" : formatMetric(metric, value / scale))}- renderOverlay={context => (- <>- <VitalsOverlay- context={context}- metric={metric}- line={line}- range={range}- previous={previous}- bars={bars}- bucket={bucket}- ratingLabels={ratingLabels}- loadsLabel={t("Loads measured")}- />- {annotations.length > 0 && (+ // Lets the widest y tick ("500ms") spill left of the chart's own margin.+ <div className="h-[300px] w-full [&_svg]:overflow-visible">+ <TimeSeriesChart+ current={[]}+ series={series}+ markers={markers}+ max={max}+ chartMin={chartMin}+ chartMax={chartMax}+ yTickFormat={value => (value === 0 ? "0" : formatMetric(metric, value / scale))}+ renderOverlay={+ annotations.length > 0+ ? context => (<AnnotationPinscontext={context}annotations={annotations}@@ -442,89 +219,42 @@ export function PerformanceChart() {}}onHover={(cluster, rect) => setHoveredPin(cluster && rect ? { cluster, rect } : null)}/>- )}- </>- )}- renderTooltip={({ point, bucket }) => {- const previousPoint = previousByTime.get(point.x.getTime());- return (- <ChartTooltip>- <div className="p-3 text-xs">- <div className="flex items-center justify-between gap-3">- <span className="font-medium">{formatChartDateTime(point.time, bucket)}</span>- <span className="tabular-nums text-neutral-500 dark:text-neutral-400">- {t("{count} loads", { count: point.loads.toLocaleString() })}- </span>- </div>- <div className="mt-2 space-y-1.5">- {TOOLTIP_PERCENTILES.map(level => {- const value = point.percentiles[level];- const selected = level === percentile;- const inRange = level === "p50" || level === "p90";- return (- <div key={level} className="flex items-center justify-between gap-4">- <span className="flex items-center gap-2 text-neutral-600 dark:text-neutral-300">- <span- className="h-2 w-2 shrink-0 rounded-full"- style={{- background: selected ? DATA_COLOR : inRange ? RANGE_COLOR : "transparent",- }}- />- {level}- </span>- <span- className={cn(- "inline-flex items-center gap-1.5 tabular-nums",- selected- ? "font-medium text-neutral-900 dark:text-neutral-50"- : "text-neutral-700 dark:text-neutral-200"- )}- >- {selected && isMeasured(value) && (- <RatingMark- rating={getMetricRating(metric, value)}- label={ratingLabels[getMetricRating(metric, value)]}- />- )}- {isMeasured(value) ? formatMetric(metric, value) : "β"}- </span>- </div>- );- })}- </div>- {previousPoint && (- <div className="mt-2 flex items-center justify-between gap-4 border-t border-neutral-100 pt-2 dark:border-neutral-750">- <span className="flex min-w-0 items-center gap-2 text-neutral-600 dark:text-neutral-300">- <span- className="w-2.5 shrink-0 border-t border-dashed"- style={{ borderColor: PREVIOUS_COLOR }}- />- <span className="truncate">- {percentile}, {formatChartDateTime(previousPoint.originalTime, bucket)}- </span>+ )+ : undefined+ }+ renderTooltip={({ point, points, bucket }) => (+ <ChartTooltip>+ <div className="min-w-[160px] p-3 text-xs">+ <div className="flex items-center justify-between gap-3">+ <span className="font-medium">{formatChartDateTime(point.time, bucket)}</span>+ <span className="tabular-nums text-neutral-500 dark:text-neutral-400">+ {t("{count} loads", { count: point.loads.toLocaleString() })}+ </span>+ </div>+ <div className="mt-2 space-y-1.5">+ {/* Slowest first, the order the lines stack in. */}+ {[...points].reverse().map(({ id, color, point }) => {+ const rating = getMetricRating(metric, point.value);+ return (+ <div key={id} className="flex items-center justify-between gap-4">+ <span className="flex items-center gap-2 text-neutral-600 dark:text-neutral-300">+ <span className="h-3 w-1 shrink-0 rounded-[3px]" style={{ backgroundColor: color }} />+ {id}</span>- <span className="inline-flex shrink-0 items-center gap-1.5 tabular-nums text-neutral-700 dark:text-neutral-200">- <RatingMark- rating={getMetricRating(metric, previousPoint.value)}- label={ratingLabels[getMetricRating(metric, previousPoint.value)]}- />- {formatMetric(metric, previousPoint.value)}+ <span className="inline-flex items-center gap-1.5 font-medium tabular-nums text-neutral-900 dark:text-neutral-50">+ <RatingMark rating={rating} label={ratingLabels[rating]} />+ {formatMetric(metric, point.value)}</span></div>- )}- </div>- </ChartTooltip>- );- }}- />- </div>+ );+ })}+ </div>+ </div>+ </ChartTooltip>+ )}+ /></div>)}- {!isLoading && line.length > 0 && (- <p className="px-2 text-xs text-neutral-500 dark:text-neutral-400 md:hidden">- {t("The bars under the chart are the loads measured {interval}.", { interval })}- </p>- )}</div>{hoveredPin &&diff --git a/client/src/app/[site]/performance/components/PerformanceInsight.tsx b/client/src/app/[site]/performance/components/PerformanceInsight.tsxdeleted file mode 100644index 89b8b24ad..000000000--- a/client/src/app/[site]/performance/components/PerformanceInsight.tsx+++ /dev/null@@ -1,62 +0,0 @@-"use client";--import { ArrowRight } from "lucide-react";-import { useExtracted } from "next-intl";-import Link from "next/link";-import { InsightRow } from "@/components/site/InsightRow";-import { Button } from "@/components/ui/button";-import { usePivotHref } from "@/hooks/usePivotHref";-import { usePerformanceStore } from "../performanceStore";-import { findOnlyPoorRow, formatMetric, getRatingSplit, METRIC_LABELS_SHORT } from "../utils/performanceUtils";-import { usePerformanceRows } from "../utils/usePerformanceRows";--// A p75 over a handful of loads says little about a page.-const MIN_LOADS = 20;--/**- * One sentence, only when it is plainly true of the numbers on the page:- * among the pages with the most loads, exactly one is rated poor on the- * selected metric at p75, the percentile Core Web Vitals are assessed at.- * Nothing is inferred; with no such page, or several, the row is not drawn.- *- * It reads the same request as the Pages tab in its default state, so it adds- * no query of its own.- */-export function PerformanceInsight() {- const t = useExtracted();- const pivotHref = usePivotHref();- const metric = usePerformanceStore(state => state.selectedPerformanceMetric);- const { rows, previousByValue } = usePerformanceRows({ dimension: "pathname" });-- const busiest = rows.filter(row => (getRatingSplit(row, metric)?.count ?? 0) >= MIN_LOADS);- const poor = findOnlyPoorRow(busiest, metric, row => row[`${metric}_p75`]);- const current = poor?.[`${metric}_p75`];- if (!poor || typeof current !== "number") return null;-- const page = String(poor.pathname);- const previous = previousByValue.get(page)?.[`${metric}_p75`];- const values = { metric: METRIC_LABELS_SHORT[metric], page, current: formatMetric(metric, current) };-- return (- <InsightRow- action={- <Button asChild variant="ghost" size="xs" className="shrink-0 gap-1">- <Link href={pivotHref("sessions", [{ parameter: "pathname", type: "equals", value: [page] }])}>- {t("View sessions")}- <ArrowRight />- </Link>- </Button>- }- >- {typeof previous === "number" && formatMetric(metric, previous) !== values.current- ? t("{metric} on {page} went from {previous} to {current} at p75.", {- ...values,- previous: formatMetric(metric, previous),- })- : t("{metric} on {page} is {current} at p75.", values)}{" "}- {t("It is the only one of the {count} pages with the most loads rated poor.", {- count: String(busiest.length),- })}- </InsightRow>- );-}diff --git a/client/src/app/[site]/performance/page.tsx b/client/src/app/[site]/performance/page.tsxindex 2ee364788..4d0a16ce1 100644--- a/client/src/app/[site]/performance/page.tsx+++ b/client/src/app/[site]/performance/page.tsx@@ -13,7 +13,6 @@ import { EnableWebVitals } from "./components/EnableWebVitals";import { PercentileSelector } from "./components/PercentileSelector";import { PerformanceByDimensions } from "./components/PerformanceByDimensions";import { PerformanceChart } from "./components/PerformanceChart";-import { PerformanceInsight } from "./components/PerformanceInsight";import { PerformanceOverview } from "./components/PerformanceOverview";import { usePerformanceStore } from "./performanceStore";import { useVisibleAnnotations } from "./utils/useVisibleAnnotations";@@ -55,7 +54,6 @@ export default function PerformancePage() {<PercentileSelector /><BucketSelection /></AnalysisBar>- <PerformanceInsight /><PerformanceChart /><PerformanceByDimensions /></div>diff --git a/client/src/app/[site]/performance/utils/performanceUtils.test.ts b/client/src/app/[site]/performance/utils/performanceUtils.test.tsindex cd4c5b91f..3e6278c0c 100644--- a/client/src/app/[site]/performance/utils/performanceUtils.test.ts+++ b/client/src/app/[site]/performance/utils/performanceUtils.test.ts@@ -1,14 +1,7 @@import type { Annotation } from "@rybbit/shared";import { describe, expect, it } from "vitest";import { annotationsInWindow } from "./annotationWindow";-import {- findOnlyPoorRow,- formatMetric,- formatShare,- getMetricRating,- getRatingSplit,- PERFORMANCE_METRICS,-} from "./performanceUtils";+import { formatMetric, formatShare, getMetricRating, getRatingSplit, PERFORMANCE_METRICS } from "./performanceUtils";describe("getMetricRating", () => {it("rates a value on the limit as the better of the two", () => {@@ -77,35 +70,6 @@ describe("formatShare", () => {});});-describe("findOnlyPoorRow", () => {- const rows = (values: (number | null)[]) => values.map((lcp_p75, index) => ({ pathname: `/page-${index}`, lcp_p75 }));- const value = (row: { lcp_p75: number | null }) => row.lcp_p75;-- it("finds the single poor row", () => {- expect(findOnlyPoorRow(rows([2100, 4100, 1800, 3900]), "lcp", value)).toEqual({- pathname: "/page-1",- lcp_p75: 4100,- });- });-- it("says nothing when no row or several rows are poor", () => {- expect(findOnlyPoorRow(rows([2100, 3900, 1800]), "lcp", value)).toBeNull();- expect(findOnlyPoorRow(rows([4100, 4700, 1800]), "lcp", value)).toBeNull();- });-- it("needs three rated rows to single one out", () => {- expect(findOnlyPoorRow(rows([4100, 1800]), "lcp", value)).toBeNull();- expect(findOnlyPoorRow(rows([4100, 1800, null]), "lcp", value)).toBeNull();- expect(findOnlyPoorRow(rows([4100, 1800, null, 2000]), "lcp", value)?.pathname).toBe("/page-0");- });-- it("rates against the metric it is asked about", () => {- // 600 is a poor INP but a good LCP.- expect(findOnlyPoorRow(rows([600, 100, 150]), "inp", value)?.pathname).toBe("/page-0");- expect(findOnlyPoorRow(rows([600, 100, 150]), "lcp", value)).toBeNull();- });-});-describe("PERFORMANCE_METRICS", () => {it("lists the Core Web Vitals first", () => {expect(PERFORMANCE_METRICS).toEqual(["lcp", "inp", "cls", "fcp", "ttfb"]);diff --git a/client/src/app/[site]/performance/utils/performanceUtils.ts b/client/src/app/[site]/performance/utils/performanceUtils.tsindex eec06a701..b0f36abd1 100644--- a/client/src/app/[site]/performance/utils/performanceUtils.ts+++ b/client/src/app/[site]/performance/utils/performanceUtils.ts@@ -154,21 +154,3 @@ export const getRatingSplit = (/** A percentage of loads to one decimal: 77.34 β "77.3%". */export const formatShare = (share: number): string => `${share.toFixed(1)}%`;--/**- * The one row rated poor in a list, or null when none or several are. Fewer- * than three rated rows is not a list worth singling one out of.- */-export const findOnlyPoorRow = <T>(- rows: T[],- metric: PerformanceMetric,- getValue: (row: T) => number | null | undefined-): T | null => {- const rated = rows.filter(row => {- const value = getValue(row);- return typeof value === "number" && Number.isFinite(value);- });- if (rated.length < 3) return null;- const poor = rated.filter(row => getMetricRating(metric, getValue(row) as number) === "poor");- return poor.length === 1 ? poor[0] : null;-};diff --git a/client/src/app/[site]/retention/page.test.tsx b/client/src/app/[site]/retention/page.test.tsxindex 48d383190..b57f1e8c2 100644--- a/client/src/app/[site]/retention/page.test.tsx+++ b/client/src/app/[site]/retention/page.test.tsx@@ -184,17 +184,13 @@ describe("RetentionPage", () => {expect(within(popover).getByText("Average for Week 2").nextElementSibling?.textContent).toBe("8.0%");});- it("calls out the largest cohort when it retains differently, and highlights it on request", () => {+ it("highlights a cohort when its row is picked, with no insight sentence above the grid", () => {render(<RetentionPage />);- expect(- screen.getByText(- "The Sep 14 β Sep 20 cohort is your largest at 2,000 new users, but only 10.0% came back in week 1, 2.5 pp under average."- )- ).toBeTruthy();+ expect(screen.queryByText(/cohort is your largest/)).toBeNull();const row = screen.getByRole("button", { name: "Sep 14 β Sep 20" });expect(row.getAttribute("aria-pressed")).toBe("false");- fireEvent.click(screen.getByRole("button", { name: "View cohort" }));+ fireEvent.click(row);expect(row.getAttribute("aria-pressed")).toBe("true");});diff --git a/client/src/app/[site]/retention/page.tsx b/client/src/app/[site]/retention/page.tsxindex 4bbb806b1..a59be1538 100644--- a/client/src/app/[site]/retention/page.tsx+++ b/client/src/app/[site]/retention/page.tsx@@ -1,15 +1,6 @@"use client";-import {- ArrowRight,- CalendarClock,- CalendarRange,- ChartColumnDecreasing,- Download,- Repeat,- Trophy,- Users,-} from "lucide-react";+import { CalendarClock, CalendarRange, ChartColumnDecreasing, Download, Repeat, Trophy, Users } from "lucide-react";import { DateTime } from "luxon";import { useExtracted } from "next-intl";import { ReactNode, useCallback, useMemo, useState } from "react";@@ -22,7 +13,6 @@ import { ErrorState } from "../../../components/ErrorState";import { SegmentedControl } from "../../../components/interior/segmented-control";import { NothingFound } from "../../../components/NothingFound";import { AnalysisBar } from "../../../components/site/AnalysisBar";-import { InsightRow } from "../../../components/site/InsightRow";import { StatBand, StatBandCell } from "../../../components/site/StatBand";import { Button } from "../../../components/ui/button";import { Card } from "../../../components/ui/card";@@ -39,7 +29,6 @@ import { RetentionCard } from "./RetentionCard";import {buildRetentionModel,defaultRetentionMode,- findCohortOutlier,formatPercent,periodDays,retentionCsv,@@ -121,7 +110,6 @@ export default function RetentionPage() {dataMode === "week" ? t("week {index}", { index: String(offset) }) : t("day {index}", { index: String(offset) });const hasGrid = !!model && model.cohorts.length >= 2 && model.totalNew > 0;- const outlier = hasGrid ? findCohortOutlier(model) : null;const comparisonWindow = previousModel ? describeComparisonWindow(previousTime, time, timezone) : null;const periodStat = (offset: number, icon: ReactNode): StatBandCell => {@@ -196,17 +184,6 @@ export default function RetentionPage() {downloadCSV(`retention-${model.mode === "week" ? "weekly" : "daily"}-${first}-to-${last}.csv`, rows, columns);};- const outlierName = (chunks: ReactNode) => (- <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>- );- const outlierValues = outlier && {- cohort: cohortLabel(outlier.cohort.key),- size: outlier.cohort.size.toLocaleString(),- value: formatPercent(outlier.pct),- difference: `${Math.abs(outlier.difference).toFixed(1)} pp`,- name: outlierName,- };-return (<DisabledOverlay message="Retention" featurePath="retention"><div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3">@@ -242,37 +219,6 @@ export default function RetentionPage() {/></AnalysisBar>- {outlier && outlierValues && (- <InsightRow- action={- <Button variant="ghost" size="xs" className="gap-1" onClick={() => setPinnedCohort(outlier.cohort.key)}>- {t("View cohort")}- <ArrowRight />- </Button>- }- >- {isWeekly- ? outlier.difference < 0- ? t.rich(- "The <name>{cohort}</name> cohort is your largest at {size} new users, but only {value} came back in week 1, {difference} under average.",- outlierValues- )- : t.rich(- "The <name>{cohort}</name> cohort is your largest at {size} new users, and {value} came back in week 1, {difference} above average.",- outlierValues- )- : outlier.difference < 0- ? t.rich(- "The <name>{cohort}</name> cohort is your largest at {size} new users, but only {value} came back on day 1, {difference} under average.",- outlierValues- )- : t.rich(- "The <name>{cohort}</name> cohort is your largest at {size} new users, and {value} came back on day 1, {difference} above average.",- outlierValues- )}- </InsightRow>- )}-{isError ? (<Card><ErrorStatediff --git a/client/src/app/[site]/retention/retentionModel.test.ts b/client/src/app/[site]/retention/retentionModel.test.tsindex df85434ec..0a6fc378f 100644--- a/client/src/app/[site]/retention/retentionModel.test.ts+++ b/client/src/app/[site]/retention/retentionModel.test.ts@@ -3,7 +3,6 @@ import { ProcessedRetentionData } from "../../../api/analytics/endpoints";import {buildRetentionModel,defaultRetentionMode,- findCohortOutlier,HEAT_STEPS,heatStep,lastPeriodProgress,@@ -161,52 +160,6 @@ describe("statOffsets", () => {});});-describe("findCohortOutlier", () => {- it("reports the largest cohort when it is clearly larger and retains differently", () => {- const outlier = findCohortOutlier(buildRetentionModel(sample()));-- expect(outlier?.cohort.key).toBe("2026-09-14");- expect(outlier?.pct).toBe(10);- expect(outlier?.difference).toBe(-2.5);- });-- it("stays quiet when no cohort stands out in size", () => {- const model = buildRetentionModel(- response({- "2026-08-31": [1000, 200, 100, 80, 20],- "2026-09-07": [1050, 100, 60, 10],- "2026-09-14": [1000, 150, 30],- "2026-09-21": [1000, 40],- "2026-09-28": [400],- })- );- expect(findCohortOutlier(model)).toBeNull();- });-- it("stays quiet when the largest cohort retains like the rest", () => {- const model = buildRetentionModel(- response({- "2026-08-31": [1000, 125, 100, 80, 20],- "2026-09-07": [1000, 125, 60, 10],- "2026-09-14": [2000, 250, 30],- "2026-09-21": [1000, 40],- "2026-09-28": [400],- })- );- expect(findCohortOutlier(model)).toBeNull();- });-- it("needs at least three cohorts with a finished period 1", () => {- const model = buildRetentionModel(- response(- { "2026-09-14": [2000, 200, 30], "2026-09-21": [1000, 40], "2026-09-28": [400] },- { periods: ["2026-09-14", "2026-09-21", "2026-09-28"] }- )- );- expect(findCohortOutlier(model)).toBeNull();- });-});-describe("lastPeriodProgress", () => {it("counts the days of the last period the window has reached", () => {// Monday Sep 28 to Wednesday Sep 30, 15:00: three days in.diff --git a/client/src/app/[site]/retention/retentionModel.ts b/client/src/app/[site]/retention/retentionModel.tsindex 8dd7eb952..c086b4205 100644--- a/client/src/app/[site]/retention/retentionModel.ts+++ b/client/src/app/[site]/retention/retentionModel.ts@@ -164,41 +164,6 @@ export function buildRetentionModel(data: ProcessedRetentionData): RetentionMode};}-export interface CohortOutlier {- cohort: RetentionCohortRow;- /** The cohort's period-1 retention, in percent. */- pct: number;- /** Percentage points above (positive) or below the all-cohort average. */- difference: number;-}--const OUTLIER_SIZE_RATIO = 1.15;-const OUTLIER_MIN_DIFFERENCE = 1;-const OUTLIER_MIN_COHORTS = 3;--/**- * The largest cohort, when it is clearly larger than usual and its period-1- * retention sits at least a point away from the average: the case where a- * spike in new users (a launch, a campaign) retained differently. Fixed- * thresholds, no judgement: null whenever the data does not meet them.- */-export function findCohortOutlier(model: RetentionModel): CohortOutlier | null {- const average = model.average[1];- if (!average || model.averageSize === null) return null;-- const measured = model.cohorts.filter(cohort => cohort.size > 0 && cohort.cells[1] && !cohort.cells[1].partial);- if (measured.length < OUTLIER_MIN_COHORTS) return null;-- const largest = measured.reduce((winner, cohort) => (cohort.size > winner.size ? cohort : winner));- if (largest.size < model.averageSize * OUTLIER_SIZE_RATIO) return null;-- const pct = largest.cells[1].pct;- const difference = pct - average.pct;- if (Math.abs(difference) < OUTLIER_MIN_DIFFERENCE) return null;-- return { cohort: largest, pct, difference };-}-/*** Stepped opacity ramp of the data hue. The jump from 0.44 to 0.64 skips the* band where neither light nor dark text reaches 4.5:1 on the dark panel, sodiff --git a/client/src/app/[site]/user/[userId]/components/UserErrorInsight.tsx b/client/src/app/[site]/user/[userId]/components/UserErrorInsight.tsxdeleted file mode 100644index 53583e1a6..000000000--- a/client/src/app/[site]/user/[userId]/components/UserErrorInsight.tsx+++ /dev/null@@ -1,77 +0,0 @@-"use client";--import { Video } from "lucide-react";-import { DateTime } from "luxon";-import { useExtracted } from "next-intl";-import { ReactNode, useState } from "react";-import { useUserRepeatedError } from "../../../../../api/analytics/hooks/useUserProfile";-import { ReplayDrawer } from "../../../../../components/Sessions/ReplayDrawer";-import { InsightRow } from "../../../../../components/site/InsightRow";-import { Button } from "../../../../../components/ui/button";-import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";-import { useReplayAvailable } from "../../../../../hooks/useReplayAvailable";-import { useTimezone } from "../../../../../lib/store";--/**- * One sentence, shown only when it is true: in the selected period this user- * hit the same error more than once in a single session. The rule is fixed- * (one message, one session, two or more times; the latest such session wins)- * and the server evaluates it, so the row never guesses.- */-export function UserErrorInsight({ userId }: { userId: string }) {- const t = useExtracted();- const zone = useTimezone();- const replayAvailable = useReplayAvailable();- const { formatDateTime, formatRelative } = useDateTimeFormat();- const [replayOpen, setReplayOpen] = useState(false);- const { data: repeated } = useUserRepeatedError(userId);-- if (!repeated) return null;-- const firstSeen = DateTime.fromSQL(repeated.first_seen, { zone: "utc" }).setZone(zone);- const when = firstSeen.isValid ? formatRelative(firstSeen) : "";- const exact = firstSeen.isValid- ? formatDateTime(firstSeen, {- year: "numeric",- month: "short",- day: "numeric",- hour: "numeric",- minute: "2-digit",- timeZone: zone,- })- : undefined;-- const strong = (chunks: ReactNode) => (- <span className="font-medium text-neutral-900 dark:text-neutral-50">{chunks}</span>- );- const values = { count: repeated.occurrences.toLocaleString(), path: repeated.pathname, when, strong };- const canWatch = repeated.has_replay && replayAvailable;-- return (- <>- <InsightRow- action={- canWatch ? (- <Button- variant="ghost"- size="xs"- className="hidden shrink-0 gap-1 md:inline-flex"- onClick={() => setReplayOpen(true)}- >- <Video />- {t("Watch replay")}- </Button>- ) : undefined- }- >- <span title={exact}>- {repeated.pathname- ? t.rich("Hit the same error {count} times in one session {when}, on <strong>{path}</strong>:", values)- : t.rich("Hit the same error {count} times in one session {when}:", values)}- </span>{" "}- <span className="break-words font-mono text-xs text-neutral-600 dark:text-neutral-300">{repeated.message}</span>- </InsightRow>- {canWatch && <ReplayDrawer sessionId={repeated.session_id} open={replayOpen} onOpenChange={setReplayOpen} />}- </>- );-}diff --git a/client/src/app/[site]/user/[userId]/components/UserHeader.tsx b/client/src/app/[site]/user/[userId]/components/UserHeader.tsxindex 3588a19f9..98edfe661 100644--- a/client/src/app/[site]/user/[userId]/components/UserHeader.tsx+++ b/client/src/app/[site]/user/[userId]/components/UserHeader.tsx@@ -1,9 +1,8 @@"use client";-import { Clock, Rewind, Video } from "lucide-react";+import { Clock, Video } from "lucide-react";import { DateTime } from "luxon";import { useExtracted, useLocale } from "next-intl";-import Link from "next/link";import { useState } from "react";import { UserInfo } from "../../../../../api/analytics/endpoints";import { Avatar } from "../../../../../components/Avatar";@@ -18,7 +17,6 @@ import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";import { useReplayAvailable } from "../../../../../hooks/useReplayAvailable";import { getTimezone } from "../../../../../lib/store";import { userStore } from "../../../../../lib/userStore";-import { useProfileHref, userFilter } from "./profileLinks";import { UserActions } from "./UserActions";import { headlineTraits, traitLabel } from "./userTraits";@@ -84,8 +82,6 @@ function LatestReplayButton({ sessionId }: { sessionId: string }) {interface UserHeaderProps {/** The id in the URL: what the avatar, the copy button and the delete action refer to. */userId: string;- /** The identity the profile's panels query: the identified id when there is one. */- queryUserId: string;displayName: string;data: UserInfo | undefined;isLoading: boolean;@@ -93,19 +89,11 @@ interface UserHeaderProps {latestReplaySessionId?: string;}-export function UserHeader({- userId,- queryUserId,- displayName,- data,- isLoading,- latestReplaySessionId,-}: UserHeaderProps) {+export function UserHeader({ userId, displayName, data, isLoading, latestReplaySessionId }: UserHeaderProps) {const t = useExtracted();const locale = useLocale();const { user } = userStore();const { formatRelative, formatDateTime, hour12 } = useDateTimeFormat();- const profileHref = useProfileHref();const isIdentified = !!data?.identified_user_id;const traitsEmail = data?.traits?.email as string | undefined;@@ -211,14 +199,6 @@ export function UserHeader({</div><div className="flex shrink-0 flex-wrap items-center gap-1.5">{latestReplaySessionId && <LatestReplayButton sessionId={latestReplaySessionId} />}- {data && (- <Button asChild variant="outline" size="sm">- <Link href={profileHref("sessions", [userFilter(queryUserId)])} prefetch={false}>- <Rewind />- {t("Open in Sessions")}- </Link>- </Button>- )}{user && data && <UserActions userId={userId} data={data} />}</div></header>diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.test.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.test.tsxindex 134d1d6a0..472078219 100644--- a/client/src/app/[site]/user/[userId]/components/UserSidebar.test.tsx+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.test.tsx@@ -97,7 +97,7 @@ describe("UserSidebar", () => {it("is one ledger with traits first and web vitals last", () => {showSidebar();- expect(sectionTitles()).toEqual(["Traits", "Acquisition", "Location & device", "Linked devices", "Web vitals"]);+ expect(sectionTitles()).toEqual(["Traits", "Acquisition", "Location & device", "Web vitals"]);});it("lists custom traits and leaves out the ones the header shows as identity", () => {@@ -109,14 +109,13 @@ describe("UserSidebar", () => {expect(traits.queryByText("[email protected]")).toBeNull();});- it("draws the linked devices the API returns, with the day each was linked", () => {+ it("does not list the anonymous IDs merged into the identity", () => {showSidebar();- const linked = within(section("Linked devices"));- expect(linked.getByText("5be2c07f41d9")).toBeTruthy();- expect(linked.getByText("linked Aug 14")).toBeTruthy();- expect(linked.getByText("c84a19e6d370")).toBeTruthy();- expect(linked.getByText("linked Aug 19")).toBeTruthy();+ // Each IP and browser pair an identified user is seen on becomes an alias,+ // so a regular user collects hundreds; they are not devices.+ expect(screen.queryByText("Linked devices")).toBeNull();+ expect(screen.queryByText("5be2c07f41d9")).toBeNull();});it("takes first-touch facts from the user's first day, not from the selected period", () => {@@ -185,7 +184,7 @@ describe("UserSidebar", () => {expect(segments.queryByRole("link")).toBeNull();});- it("shows no traits or linked devices for an anonymous visitor", () => {+ it("shows no traits for an anonymous visitor", () => {showSidebar({ data: { ...base, identified_user_id: "", traits: null } as UserInfo });expect(sectionTitles()).toEqual(["Acquisition", "Location & device", "Web vitals"]);diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsxindex 64f1d659a..e1aeea1d7 100644--- a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx@@ -1,6 +1,6 @@"use client";-import { Bookmark, Fingerprint, Pencil, Plus } from "lucide-react";+import { Bookmark, Pencil, Plus } from "lucide-react";import { DateTime } from "luxon";import { useExtracted } from "next-intl";import Link from "next/link";@@ -99,7 +99,6 @@ export function UserSidebar({const vitals = data?.vitals ?? null;const vitalsToShow = vitals ? VITALS_ORDER.filter(metric => vitals[`${metric}_p75`] != null) : [];const showMap = !!configs?.mapboxToken && !!data?.country;- const linkedDevices = isIdentified ? (data?.linked_devices ?? []) : [];const truncated = (value: string) => (<span className="inline-block max-w-[170px] truncate align-bottom" title={value}>@@ -301,64 +300,6 @@ export function UserSidebar({<LocationDevices data={data} isLoading={isLoading} getRegionName={getRegionName} /></SidebarSection>- {/* Devices that were merged into this identity. The API has always- returned them; the page never drew them. */}- {linkedDevices.length > 0 && (- <SidebarSection>- <SidebarHeader- title={t("Linked devices")}- right={<SidebarHint>{linkedDevices.length.toLocaleString()}</SidebarHint>}- />- <div>- {linkedDevices.map(device => {- const linkedAt = parseUtc(device.created_at)?.setZone(zone) ?? null;- return (- <InfoRow- key={device.anonymous_id}- label={- <span className="inline-flex items-center gap-1.5">- <Fingerprint className="h-3.5 w-3.5 shrink-0 text-neutral-400 dark:text-neutral-500" />- <span- className="inline-block max-w-[110px] truncate font-mono text-neutral-700 dark:text-neutral-200"- title={device.anonymous_id}- >- {device.anonymous_id}- </span>- </span>- }- value={- linkedAt ? (- <span- className="whitespace-nowrap text-neutral-500 dark:text-neutral-400"- title={formatDateTime(linkedAt, {- year: "numeric",- month: "short",- day: "numeric",- hour: "numeric",- minute: "2-digit",- timeZone: zone,- })}- >- {t("linked {date}", {- date: formatDateTime(linkedAt, {- month: "short",- day: "numeric",- year: linkedAt.year === DateTime.now().year ? undefined : "numeric",- timeZone: zone,- }),- })}- </span>- ) : (- "β"- )- }- />- );- })}- </div>- </SidebarSection>- )}-{/* Web vitals (p75 across this user's performance events) */}{vitals && vitalsToShow.length > 0 && (<SidebarSection>diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsxindex d1660591a..fd3330b36 100644--- a/client/src/app/[site]/user/[userId]/page.tsx+++ b/client/src/app/[site]/user/[userId]/page.tsx@@ -30,7 +30,6 @@ import { MobileSidebar } from "../../components/Sidebar/MobileSidebar";import { ActivityCalendar } from "./components/ActivityCalendar";import { firstActiveDay } from "./components/calendarLayout";import { SessionBreakdown } from "./components/sessionGroups";-import { UserErrorInsight } from "./components/UserErrorInsight";import { UserGoals } from "./components/UserGoals";import { UserHeader } from "./components/UserHeader";import { SESSIONS_PAGE_SIZE, UserSessions } from "./components/UserSessions";@@ -174,7 +173,6 @@ export default function UserPage() {<UserHeaderuserId={userId}- queryUserId={queryUserId}displayName={displayName}data={data}isLoading={isLoading}@@ -197,8 +195,6 @@ export default function UserPage() {}/>- <UserErrorInsight userId={queryUserId} />-{/* Main content leads in the DOM so activity comes first on mobile;row-reverse puts the profile rail back on the left on desktop */}<div className="flex flex-col gap-3 lg:flex-row-reverse">diff --git a/client/src/components/site/InsightRow.tsx b/client/src/components/site/InsightRow.tsxdeleted file mode 100644index c5f86320c..000000000--- a/client/src/components/site/InsightRow.tsx+++ /dev/null@@ -1,30 +0,0 @@-import { Sparkles } from "lucide-react";-import { ReactNode } from "react";-import { cn } from "@/lib/utils";--export interface InsightRowProps {- /** One plain sentence about what changed and why it matters. */- children: ReactNode;- /** One follow-up, usually a `<Button variant="ghost" size="sm">`. */- action?: ReactNode;- className?: string;-}--/**- * A single observation above a page's content. Neutral on purpose: no accent- * tint, no border stripe. A page shows one or two at most.- */-export function InsightRow({ children, action, className }: InsightRowProps) {- return (- <div- className={cn(- "flex items-center gap-2.5 rounded-lg border border-neutral-100 bg-white px-3 py-2 text-sm dark:border-neutral-850 dark:bg-neutral-900",- className- )}- >- <Sparkles className="h-4 w-4 shrink-0 text-neutral-500 dark:text-neutral-400" aria-hidden="true" />- <div className="min-w-0 flex-1 text-neutral-700 dark:text-neutral-200">{children}</div>- {action}- </div>- );-}diff --git a/server/src/api/__snapshots__/routes.test.ts.snap b/server/src/api/__snapshots__/routes.test.ts.snapindex 81b36e679..a96ad90ec 100644--- a/server/src/api/__snapshots__/routes.test.ts.snap+++ b/server/src/api/__snapshots__/routes.test.ts.snap@@ -121,7 +121,6 @@ exports[`API route table > pins the access each route requires 1`] = `"GET /api/sites/:siteId/users β site users:read [viewer+] (or public)","GET /api/sites/:siteId/users/:userId β site users:read [viewer+] (or public)","GET /api/sites/:siteId/users/:userId/goals β site users:read [viewer+] (or public)",- "GET /api/sites/:siteId/users/:userId/repeated-error β site users:read [viewer+] (or public)","GET /api/sites/:siteId/users/:userId/segments β site users:read [viewer+] (or public)","GET /api/sites/:siteId/users/:userId/session-goals β site users:read [viewer+] (or public)","GET /api/sites/:siteId/users/:userId/summary β site users:read [viewer+] (or public)",diff --git a/server/src/api/analytics/funnels/funnelSteps.test.ts b/server/src/api/analytics/funnels/funnelSteps.test.tsindex 20d1cb608..103b8d71e 100644--- a/server/src/api/analytics/funnels/funnelSteps.test.ts+++ b/server/src/api/analytics/funnels/funnelSteps.test.ts@@ -60,7 +60,7 @@ describe("buildFunnelStepCondition β event steps", () => {propertyFilters: [{ key: "amount", value: 10 }],})).toBe(- "type = 'custom_event' AND event_name = 'purchase' AND toFloat64(JSONExtractString(toString(props), 'amount')) = 10"+ "type = 'custom_event' AND event_name = 'purchase' AND toFloat64OrNull(JSONExtractString(toString(props), 'amount')) = 10");});diff --git a/server/src/api/analytics/getJourneySessions.ts b/server/src/api/analytics/getJourneySessions.tsindex b5627e89b..9e3fed146 100644--- a/server/src/api/analytics/getJourneySessions.ts+++ b/server/src/api/analytics/getJourneySessions.ts@@ -37,6 +37,8 @@ interface GetJourneySessionsRequest {replays_only?: string;limit?: string;page?: string;+ /** Rows to skip, in place of `(page - 1) * limit`: lets a caller read one row past its page. */+ offset?: string;}>;}@@ -45,7 +47,7 @@ interface JourneySessionsOptions {path: string[];replaysOnly: boolean;limit: number;- page: number;+ offset: number;}/**@@ -57,7 +59,7 @@ export const buildJourneySessionsQuery = (query: GetJourneySessionsRequest["Querystring"],siteId: number,options: JourneyOptions,- { path, replaysOnly, limit, page }: JourneySessionsOptions+ { path, replaysOnly, limit, offset }: JourneySessionsOptions): JourneyQuerySpec => {const { ctes, params } = buildJourneyFragments(query, siteId, options);const timeStatement = getTimeStatement(query);@@ -135,7 +137,7 @@ export const buildJourneySessionsQuery = (ORDER BY a.session_end DESCLIMIT {limit:Int32} OFFSET {offset:Int32}`,- params: { ...params, journeyPath: path, limit, offset: (page - 1) * limit },+ params: { ...params, journeyPath: path, limit, offset },};};@@ -165,13 +167,17 @@ export const getJourneySessions = analyticsRoute<GetJourneySessionsRequest>(if (isNaN(page) || page < 1) {return reply.status(400).send({ error: "Invalid page number" });}+ const offset = request.query.offset === undefined ? (page - 1) * limit : Number(request.query.offset);+ if (!Number.isInteger(offset) || offset < 0) {+ return reply.status(400).send({ error: "Invalid offset" });+ }const data = await runAnalyticsQuery<Omit<GetSessionsResponse[number], "traits">>(buildJourneySessionsQuery(request.query, siteId, parsed.options, {path,replaysOnly: request.query.replays_only === "true",limit,- page,+ offset,}));diff --git a/server/src/api/analytics/getJourneys.test.ts b/server/src/api/analytics/getJourneys.test.tsindex 4b20f824b..c1371ebbe 100644--- a/server/src/api/analytics/getJourneys.test.ts+++ b/server/src/api/analytics/getJourneys.test.ts@@ -187,7 +187,7 @@ describe("buildJourneySessionsQuery", () => {path: ["/", "/pricing"],replaysOnly,limit: 25,- page: 3,+ offset: 50,});it("selects the sessions whose journey is exactly the path", () => {diff --git a/server/src/api/analytics/goals/goalConditions.test.ts b/server/src/api/analytics/goals/goalConditions.test.tsindex 887792cbf..09f5f86d9 100644--- a/server/src/api/analytics/goals/goalConditions.test.ts+++ b/server/src/api/analytics/goals/goalConditions.test.ts@@ -91,7 +91,7 @@ describe("buildGoalCondition β event goals", () => {config: { eventName: "purchase", propertyFilters: [{ key: "amount", value: 99.5 }] },})).toBe(- "type = 'custom_event' AND event_name = 'purchase' AND toFloat64(JSONExtractString(toString(props), 'amount')) = 99.5"+ "type = 'custom_event' AND event_name = 'purchase' AND toFloat64OrNull(JSONExtractString(toString(props), 'amount')) = 99.5");});diff --git a/server/src/api/analytics/index.ts b/server/src/api/analytics/index.tsindex 9944efcab..1504a795f 100644--- a/server/src/api/analytics/index.ts+++ b/server/src/api/analytics/index.ts@@ -87,7 +87,6 @@ export { getSessionsSummary } from "./sessions/getSessionsSummary.js";export { deleteUser } from "./users/deleteUser.js";export { getUserGoals, getUserSessionGoals } from "./users/getUserGoals.js";export { getUserInfo } from "./users/getUserInfo.js";-export { getUserRepeatedError } from "./users/getUserRepeatedError.js";export { getUserSegments } from "./users/getUserSegments.js";export { getUserSessionCount } from "./users/getUserSessionCount.js";export { getUserSummary } from "./users/getUserSummary.js";diff --git a/server/src/api/analytics/sessions/getSession.ts b/server/src/api/analytics/sessions/getSession.tsindex aa9957006..6ae745fcc 100644--- a/server/src/api/analytics/sessions/getSession.ts+++ b/server/src/api/analytics/sessions/getSession.ts@@ -161,7 +161,7 @@ export const getSession = analyticsRoute<GetSessionRequest>(// The same conditions the Goals page counts with, so an event marked here// is one that page counted as a conversion.- const matcher = await getSessionGoalMatcher(Number(siteId));+ const matcher = await getSessionGoalMatcher(Number(siteId), req);const { sessionQuery, countQuery, eventsQuery } = buildSessionQueries(req.query, matcher.expression);// Execute queries in paralleldiff --git a/server/src/api/analytics/sessions/getSessions.ts b/server/src/api/analytics/sessions/getSessions.tsindex b92b7d349..87f387ae2 100644--- a/server/src/api/analytics/sessions/getSessions.ts+++ b/server/src/api/analytics/sessions/getSessions.ts@@ -189,7 +189,7 @@ export const getSessions = analyticsRoute<GetSessionsRequest>(// Goals are matched only for a request that shows or filters on them.const wantsGoals = parsed.params.include_goals === "true" || parsed.params.view === "converted";- const matcher = wantsGoals ? await getSessionGoalMatcher(siteId) : NO_GOALS;+ const matcher = wantsGoals ? await getSessionGoalMatcher(siteId, req) : NO_GOALS;const rows = await runAnalyticsQuery<SessionRow>(buildSessionsQuery(req.query, siteId, matcher));const withReplay = await findSessionsWithReplay(diff --git a/server/src/api/analytics/sessions/getSessionsSummary.ts b/server/src/api/analytics/sessions/getSessionsSummary.tsindex 580d996bc..8a11c694c 100644--- a/server/src/api/analytics/sessions/getSessionsSummary.ts+++ b/server/src/api/analytics/sessions/getSessionsSummary.ts@@ -163,7 +163,7 @@ export const getSessionsSummary = analyticsRoute<GetSessionsSummaryRequest>(return res.status(400).send({ error: parsed.error });}- const matcher = await getSessionGoalMatcher(siteId);+ const matcher = await getSessionGoalMatcher(siteId, req);const rows = await runAnalyticsQuery<SummaryRow>(buildSessionsSummaryQuery(req.query, siteId, matcher));return res.send({ data: toSessionsSummary(rows, matcher.goals.length > 0) });diff --git a/server/src/api/analytics/sessions/sessionGoals.scope.test.ts b/server/src/api/analytics/sessions/sessionGoals.scope.test.tsnew file mode 100644index 000000000..4ef4e1abf--- /dev/null+++ b/server/src/api/analytics/sessions/sessionGoals.scope.test.ts@@ -0,0 +1,68 @@+import { FastifyRequest } from "fastify";+import { beforeEach, describe, expect, it, vi } from "vitest";++const state = vi.hoisted(() => ({ goals: [] as Record<string, unknown>[], reads: 0 }));++vi.mock("../../../db/postgres/postgres.js", () => ({+ db: {+ select: () => ({+ from: () => ({+ where: () => ({+ orderBy: () => ({+ limit: async () => {+ state.reads += 1;+ return state.goals;+ },+ }),+ }),+ }),+ }),+ },+}));++vi.mock("../../../db/postgres/schema.js", () => ({+ goals: { siteId: "site_id", goalId: "goal_id" },+}));++vi.mock("drizzle-orm", () => ({+ asc: (column: unknown) => column,+ eq: (_column: unknown, value: unknown) => value,+}));++import { getSessionGoalMatcher } from "./sessionGoals.js";++const signup = { goalId: 7, name: "Signup", goalType: "event", config: { eventName: "signup" } };+const request = (extra: Record<string, unknown> = {}) => extra as unknown as FastifyRequest;++describe("getSessionGoalMatcher", () => {+ beforeEach(() => {+ state.goals = [signup];+ state.reads = 0;+ });++ it("matches the site's goals for a dashboard session", async () => {+ const matcher = await getSessionGoalMatcher(1, request());++ expect(matcher.goals).toEqual([{ id: 7, name: "Signup" }]);+ });++ it("matches the site's goals for a credential that may read goals", async () => {+ const matcher = await getSessionGoalMatcher(+ 1,+ request({ bearerAuth: true, bearerStatements: { sessions: ["read"], goals: ["read"] } })+ );++ expect(matcher.goals).toHaveLength(1);+ });++ it("gives a credential without goals:read no goals, and does not read them", async () => {+ const matcher = await getSessionGoalMatcher(+ 1,+ request({ bearerAuth: true, bearerStatements: { sessions: ["read"] } })+ );++ expect(matcher.goals).toEqual([]);+ expect(matcher.expression).toBe("emptyArrayUInt32()");+ expect(state.reads).toBe(0);+ });+});diff --git a/server/src/api/analytics/sessions/sessionGoals.ts b/server/src/api/analytics/sessions/sessionGoals.tsindex 1e8c80635..6e5ca533a 100644--- a/server/src/api/analytics/sessions/sessionGoals.ts+++ b/server/src/api/analytics/sessions/sessionGoals.ts@@ -1,6 +1,8 @@import { asc, eq } from "drizzle-orm";+import { FastifyRequest } from "fastify";import { db } from "../../../db/postgres/postgres.js";import { goals } from "../../../db/postgres/schema.js";+import { hasScope } from "../../../lib/scopes.js";import { buildGoalCondition } from "../goals/goalConditions.js";/** A goal as the session endpoints report it: enough to name it and link to it. */@@ -58,7 +60,19 @@ export function buildSessionGoalMatcher(siteGoals: GoalRow[]): SessionGoalMatche};}-export async function getSessionGoalMatcher(siteId: number): Promise<SessionGoalMatcher> {+const GOALS_READ = { resource: "goals", action: "read" } as const;++/**+ * The site's goal matcher for a session request. The session routes are+ * guarded by sessions:read alone, so a scoped bearer credential without+ * goals:read gets no goals: it would otherwise read goal names and+ * conversions it cannot list directly.+ */+export async function getSessionGoalMatcher(siteId: number, req: FastifyRequest): Promise<SessionGoalMatcher> {+ if (req.bearerAuth && !hasScope(req.bearerStatements ?? null, GOALS_READ)) {+ return buildSessionGoalMatcher([]);+ }+const siteGoals = await db.select({ goalId: goals.goalId, name: goals.name, goalType: goals.goalType, config: goals.config }).from(goals)diff --git a/server/src/api/analytics/users/getUserRepeatedError.ts b/server/src/api/analytics/users/getUserRepeatedError.tsdeleted file mode 100644index 1d3512bea..000000000--- a/server/src/api/analytics/users/getUserRepeatedError.ts+++ /dev/null@@ -1,112 +0,0 @@-import { FilterParams } from "@rybbit/shared";-import { FastifyReply, FastifyRequest } from "fastify";-import { analyticsRoute, runAnalyticsQuery } from "../utils/analyticsQuery.js";-import { buildUserEventScope } from "./userEventScope.js";--export interface GetUserRepeatedErrorRequest {- Params: {- siteId: string;- userId: string;- };- Querystring: FilterParams;-}--export interface UserRepeatedError {- message: string;- session_id: string;- /** Times the same message was thrown in that one session. Always 2 or more. */- occurrences: number;- /** Page the first of them was thrown on. */- pathname: string;- first_seen: string;- last_seen: string;- has_replay: boolean;-}--interface RepeatedErrorRow {- error_message: string | number;- session_id: string;- occurrences: number;- pathname: string | number | null;- first_seen: string;- last_seen: string;-}--/**- * The profile's one insight: the most recent session in the window in which- * this user hit the same error message more than once. A rule, not a- * judgement: one message, one session, a count of at least two.- */-export const buildUserRepeatedErrorQuery = (query: GetUserRepeatedErrorRequest["Querystring"], siteId: number) => {- const { withFilteredSessions, scopedEvents } = buildUserEventScope(query, siteId);-- return `- ${withFilteredSessions}- SELECT- JSONExtractString(toString(props), 'message') AS error_message,- session_id,- count() AS occurrences,- argMin(pathname, timestamp) AS pathname,- MIN(timestamp) AS first_seen,- MAX(timestamp) AS last_seen- FROM ${scopedEvents}- WHERE- type = 'error'- AND JSONExtractString(toString(props), 'message') <> ''- GROUP BY- error_message,- session_id- HAVING- occurrences >= 2- ORDER BY- last_seen DESC- LIMIT 1- `;-};--// Same definition of "has a replay" as the session list: a recording with at-// least two events. The table is keyed by (site_id, session_id).-export const SESSION_HAS_REPLAY_QUERY = `- SELECT count() AS replays- FROM session_replay_metadata_v2- FINAL- WHERE site_id = {site:Int32}- AND session_id = {sessionId:String}- AND event_count >= 2- `;--export const getUserRepeatedError = analyticsRoute<GetUserRepeatedErrorRequest>(- "user repeated error",- async (req: FastifyRequest<GetUserRepeatedErrorRequest>, res: FastifyReply) => {- const { siteId, userId } = req.params;- const site = Number(siteId);-- const rows = await runAnalyticsQuery<RepeatedErrorRow>({- query: buildUserRepeatedErrorQuery(req.query, site),- params: { userId, site },- });-- const repeated = rows[0];- if (!repeated) {- return res.send({ data: null });- }-- const replayRows = await runAnalyticsQuery<{ replays: number }>({- query: SESSION_HAS_REPLAY_QUERY,- params: { site, sessionId: repeated.session_id },- });-- const data: UserRepeatedError = {- // processResults turns a numeric-looking message ("404") into a number.- message: String(repeated.error_message),- session_id: repeated.session_id,- occurrences: Number(repeated.occurrences),- pathname: String(repeated.pathname ?? ""),- first_seen: repeated.first_seen,- last_seen: repeated.last_seen,- has_replay: Number(replayRows[0]?.replays ?? 0) > 0,- };-- return res.send({ data });- }-);diff --git a/server/src/api/analytics/users/userProfileQueries.test.ts b/server/src/api/analytics/users/userProfileQueries.test.tsindex 11b1e8a8e..f604bc500 100644--- a/server/src/api/analytics/users/userProfileQueries.test.ts+++ b/server/src/api/analytics/users/userProfileQueries.test.ts@@ -17,7 +17,6 @@ import {parseSessionIds,toGoalConditions,} from "./getUserGoals.js";-import { buildUserRepeatedErrorQuery } from "./getUserRepeatedError.js";import { buildUserSegmentsQuery } from "./getUserSegments.js";import { buildUserSummaryQuery } from "./getUserSummary.js";@@ -109,20 +108,6 @@ describe("user goals queries", () => {});});-describe("user repeated error query", () => {- it("returns the latest session in which one message was thrown at least twice", () => {- const sql = buildUserRepeatedErrorQuery(range(), 1);-- expect(sql).toContain("type = 'error'");- expect(sql).toContain("error_message,\n session_id");- expect(sql).toContain("occurrences >= 2");- expect(sql).toContain("last_seen DESC");- expect(sql).toContain("LIMIT 1");- expect(sql).toContain(USER_PREDICATE);- expect(sql).toContain("toDateTime('2026-09-01', 'Europe/Stockholm')");- });-});-describe("user segments query", () => {const segments = [{ segmentId: 4, filters: [campaignFilter] as never },diff --git a/server/src/api/analytics/utils/eventConditions.test.ts b/server/src/api/analytics/utils/eventConditions.test.tsindex f0228000b..5c5f2d5eb 100644--- a/server/src/api/analytics/utils/eventConditions.test.ts+++ b/server/src/api/analytics/utils/eventConditions.test.ts@@ -172,10 +172,10 @@ describe("buildEventCondition", () => {it("compares numeric property filters as floats with an unquoted literal", () => {expect(buildEventCondition("purchase", [{ key: "amount", value: 42 }])).toBe(- "type = 'custom_event' AND event_name = 'purchase' AND toFloat64(JSONExtractString(toString(props), 'amount')) = 42"+ "type = 'custom_event' AND event_name = 'purchase' AND toFloat64OrNull(JSONExtractString(toString(props), 'amount')) = 42");expect(buildEventCondition("purchase", [{ key: "amount", value: 9.5 }])).toBe(- "type = 'custom_event' AND event_name = 'purchase' AND toFloat64(JSONExtractString(toString(props), 'amount')) = 9.5"+ "type = 'custom_event' AND event_name = 'purchase' AND toFloat64OrNull(JSONExtractString(toString(props), 'amount')) = 9.5");});@@ -195,7 +195,7 @@ describe("buildEventCondition", () => {{ key: "seats", value: 3 },])).toBe(- "type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'plan') = 'pro' AND toFloat64(JSONExtractString(toString(props), 'seats')) = 3"+ "type = 'custom_event' AND event_name = 'purchase' AND JSONExtractString(toString(props), 'plan') = 'pro' AND toFloat64OrNull(JSONExtractString(toString(props), 'seats')) = 3");});@@ -301,7 +301,7 @@ describe("buildAutocaptureCondition", () => {])).toBe("type = 'button_click' AND JSONExtractString(toString(props), 'id') = 'cta'" +- " AND toFloat64(JSONExtractString(toString(props), 'count')) = 2"+ " AND toFloat64OrNull(JSONExtractString(toString(props), 'count')) = 2");});diff --git a/server/src/api/analytics/utils/eventConditions.ts b/server/src/api/analytics/utils/eventConditions.tsindex 80b1d54a8..59e1e6dab 100644--- a/server/src/api/analytics/utils/eventConditions.ts+++ b/server/src/api/analytics/utils/eventConditions.ts@@ -42,7 +42,7 @@ export function resolvePropertyFilters(config: LegacyPropertyConfig): PropertyFifunction propsFilterCondition(filter: PropertyFilter): string {const key = SqlString.escape(filter.key);if (typeof filter.value === "number") {- return `toFloat64(JSONExtractString(toString(props), ${key})) = ${SqlString.escape(filter.value)}`;+ return `toFloat64OrNull(JSONExtractString(toString(props), ${key})) = ${SqlString.escape(filter.value)}`;}const value = typeof filter.value === "boolean" ? (filter.value ? "true" : "false") : filter.value;return `JSONExtractString(toString(props), ${key}) = ${SqlString.escape(value)}`;diff --git a/server/src/api/routes.ts b/server/src/api/routes.tsindex 08e790353..243ab198e 100644--- a/server/src/api/routes.ts+++ b/server/src/api/routes.ts@@ -89,7 +89,6 @@ import {getSiteEventCount,getUserGoals,getUserInfo,- getUserRepeatedError,getUserSegments,getUserSessionCount,getUserSessionGoals,@@ -345,7 +344,6 @@ async function analyticsRoutes(fastify: FastifyInstance) {fastify.get("/sites/:siteId/users/:userId/goals", publicUsersRead, getUserGoals);fastify.get("/sites/:siteId/users/:userId/session-goals", publicUsersRead, getUserSessionGoals);fastify.get("/sites/:siteId/users/:userId/segments", publicUsersRead, getUserSegments);- fastify.get("/sites/:siteId/users/:userId/repeated-error", publicUsersRead, getUserRepeatedError);fastify.post("/sites/:siteId/users/identify", site("users:write"), identifyUser);fastify.put("/sites/:siteId/users/:userId/traits", site("users:write"), updateUserTraits);fastify.delete("/sites/:siteId/users/:userId", site("users:delete"), deleteUser);