Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

Add docs funnel analytics (#1643)

John Phamousd3728bd6bcd4
diff --git a/apps/docs/app/[lang]/(home)/components/cta.tsx b/apps/docs/app/[lang]/(home)/components/cta.tsx
index 449fa294a..ff4abfa73 100644
--- a/apps/docs/app/[lang]/(home)/components/cta.tsx
+++ b/apps/docs/app/[lang]/(home)/components/cta.tsx
@@ -1,5 +1,9 @@
+"use client";
+
+import { track } from "@vercel/analytics";
import { Button } from "@vercel/geistdocs/components/button";
import Link from "next/link";
+import { analyticsEvents } from "@/lib/analytics/events";
export function CTA() {
return (
@@ -9,7 +13,12 @@ export function CTA() {
Build your first agent today.
</h2>
<Button asChild size="lg" className="w-fit text-base h-12 rounded-full">
- <Link href="/docs/getting-started">Get started</Link>
+ <Link
+ href="/docs/getting-started"
+ onClick={() => track(analyticsEvents.gettingStartedOpened, { source: "home_footer" })}
+ >
+ Get started
+ </Link>
</Button>
</div>
</section>
diff --git a/apps/docs/app/[lang]/(home)/components/install-switcher.tsx b/apps/docs/app/[lang]/(home)/components/install-switcher.tsx
index 412ba7aae..5ad7b0d89 100644
--- a/apps/docs/app/[lang]/(home)/components/install-switcher.tsx
+++ b/apps/docs/app/[lang]/(home)/components/install-switcher.tsx
@@ -13,6 +13,7 @@ import {
CommandPromptViewport,
} from "@vercel/geistdocs/components/command-prompt";
import type { JSX } from "react";
+import { analyticsEvents } from "@/lib/analytics/events";
import { cn } from "@/lib/utils";
const HUMAN_COMMAND = "npx eve@latest init my-agent";
@@ -39,7 +40,7 @@ export const InstallSwitcher = ({
defaultValue="humans"
onValueChange={(nextValue) => {
const audience = nextValue === "agents" ? "agents" : "humans";
- track("Selected installer command", { target: audience });
+ track(analyticsEvents.installerCommandSelected, { target: audience });
onValueChange?.(audience);
}}
>
@@ -63,7 +64,14 @@ export const InstallSwitcher = ({
{AGENT_COMMAND}
</CommandPromptContent>
</CommandPromptViewport>
- <CommandPromptCopy />
+ <CommandPromptCopy
+ onClick={() =>
+ track(analyticsEvents.installerCommandCopyClicked, {
+ source: "home_hero",
+ target: value ?? "humans",
+ })
+ }
+ />
</CommandPromptSurface>
</CommandPromptRoot>
);
diff --git a/apps/docs/app/[lang]/integrations/[slug]/integration-docs-link.tsx b/apps/docs/app/[lang]/integrations/[slug]/integration-docs-link.tsx
new file mode 100644
index 000000000..850f797c4
--- /dev/null
+++ b/apps/docs/app/[lang]/integrations/[slug]/integration-docs-link.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { track } from "@vercel/analytics";
+import { ArrowUpRightIcon } from "lucide-react";
+import Link from "next/link";
+import { analyticsEvents } from "@/lib/analytics/events";
+
+export const IntegrationDocsLink = ({
+ href,
+ integration,
+ type,
+}: {
+ href: string;
+ integration: string;
+ type: string;
+}) => (
+ <Link
+ className="inline-flex w-fit items-center gap-1 text-gray-900 text-sm transition-colors hover:text-gray-1000"
+ href={href}
+ onClick={() => track(analyticsEvents.integrationDocsOpened, { integration, type })}
+ >
+ Read the full {type.toLowerCase()} docs
+ <ArrowUpRightIcon className="size-3.5" />
+ </Link>
+);
diff --git a/apps/docs/app/[lang]/integrations/[slug]/page.tsx b/apps/docs/app/[lang]/integrations/[slug]/page.tsx
index 10b788da5..45472f819 100644
--- a/apps/docs/app/[lang]/integrations/[slug]/page.tsx
+++ b/apps/docs/app/[lang]/integrations/[slug]/page.tsx
@@ -1,4 +1,4 @@
-import { ArrowLeftIcon, ArrowUpRightIcon } from "lucide-react";
+import { ArrowLeftIcon } from "lucide-react";
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
@@ -17,6 +17,7 @@ import { logos } from "@/lib/integrations/logos";
import { translations } from "@/geistdocs";
import { Markdown } from "../components/markdown";
import { SetupTabs } from "../components/setup-tabs";
+import { IntegrationDocsLink } from "./integration-docs-link";
const typeLabel = {
channel: "Channel",
@@ -113,18 +114,18 @@ const IntegrationDetailPage = async ({ params }: PageProps<"/[lang]/integrations
</div>
<p className="text-gray-900 text-lg">{integration.tagline}</p>
</div>
- <Link
- className="inline-flex w-fit items-center gap-1 text-gray-900 text-sm transition-colors hover:text-gray-1000"
+ <IntegrationDocsLink
href={integration.docsHref}
- >
- Read the full {typeLabel[integration.type].toLowerCase()} docs
- <ArrowUpRightIcon className="size-3.5" />
- </Link>
+ integration={integration.slug}
+ type={typeLabel[integration.type]}
+ />
</header>
<div className="mt-10 flex flex-col">
<Section title="Install">
- <Markdown>{install}</Markdown>
+ <Markdown analytics={{ integration: integration.slug, section: "install" }}>
+ {install}
+ </Markdown>
</Section>
<Section title="Quick start">
{setup ? (
@@ -136,13 +137,16 @@ const IntegrationDetailPage = async ({ params }: PageProps<"/[lang]/integrations
}
>
<SetupTabs
+ analytics={{ integration: integration.slug, section: "quick_start" }}
authModes={setup.authModes}
protocols={setup.protocols}
variants={setup.variants}
/>
</Suspense>
) : (
- <Markdown>{integration.quickStart ?? ""}</Markdown>
+ <Markdown analytics={{ integration: integration.slug, section: "quick_start" }}>
+ {integration.quickStart ?? ""}
+ </Markdown>
)}
</Section>
<Section title="Configure">
@@ -155,13 +159,16 @@ const IntegrationDetailPage = async ({ params }: PageProps<"/[lang]/integrations
}
>
<SetupTabs
+ analytics={{ integration: integration.slug, section: "configure" }}
authModes={setup.authModes}
protocols={setup.protocols}
variants={setup.configureVariants}
/>
</Suspense>
) : (
- <Markdown>{configure}</Markdown>
+ <Markdown analytics={{ integration: integration.slug, section: "configure" }}>
+ {configure}
+ </Markdown>
)}
</Section>
</div>
diff --git a/apps/docs/app/[lang]/integrations/components/gallery.tsx b/apps/docs/app/[lang]/integrations/components/gallery.tsx
index fb6c89456..59729359c 100644
--- a/apps/docs/app/[lang]/integrations/components/gallery.tsx
+++ b/apps/docs/app/[lang]/integrations/components/gallery.tsx
@@ -1,10 +1,17 @@
"use client";
+import { track } from "@vercel/analytics";
import { Input } from "@vercel/geistdocs/components/input";
import { InputGroup, InputGroupAddon } from "@vercel/geistdocs/components/input-group";
import { SearchIcon } from "lucide-react";
import Link from "next/link";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ analyticsEvents,
+ getCountBucket,
+ getQueryLengthBucket,
+ normalizeSearchQuery,
+} from "@/lib/analytics/events";
import type { Integration, IntegrationType } from "@/lib/integrations/data";
import { cn } from "@/lib/utils";
import { IntegrationCard } from "./integration-card";
@@ -38,6 +45,7 @@ interface GalleryProps {
export const Gallery = ({ filter, integrations }: GalleryProps) => {
const [query, setQuery] = useState("");
+ const lastTrackedSearch = useRef("");
const results = useMemo(() => {
const normalized = query.trim().toLowerCase();
@@ -58,6 +66,29 @@ export const Gallery = ({ filter, integrations }: GalleryProps) => {
});
}, [integrations, filter, query]);
+ useEffect(() => {
+ const normalizedQuery = normalizeSearchQuery(query);
+ if (!normalizedQuery) {
+ lastTrackedSearch.current = "";
+ return;
+ }
+
+ const searchKey = `${filter}:${normalizedQuery}`;
+ if (searchKey === lastTrackedSearch.current) return;
+
+ const timer = setTimeout(() => {
+ track(analyticsEvents.integrationsSearched, {
+ filter,
+ query: normalizedQuery,
+ query_length: getQueryLengthBucket(normalizedQuery),
+ results: getCountBucket(results.length),
+ });
+ lastTrackedSearch.current = searchKey;
+ }, 500);
+
+ return () => clearTimeout(timer);
+ }, [filter, query, results.length]);
+
return (
<div className="flex min-w-0 flex-col gap-6">
<div className="flex min-w-0 flex-col gap-3 min-[1024px]:flex-row min-[1024px]:items-center min-[1024px]:justify-between">
@@ -77,6 +108,7 @@ export const Gallery = ({ filter, integrations }: GalleryProps) => {
)}
href={value === "all" ? "/integrations" : `/integrations?filter=${value}`}
key={value}
+ onClick={() => track(analyticsEvents.integrationFilterSelected, { filter: value })}
scroll={false}
>
{label}
@@ -102,7 +134,17 @@ export const Gallery = ({ filter, integrations }: GalleryProps) => {
{results.length > 0 ? (
<div className="grid min-w-0 grid-cols-1 gap-4 min-[1024px]:grid-cols-2 min-[1200px]:grid-cols-3">
{results.map((integration) => (
- <IntegrationCard integration={integration} key={integration.slug} />
+ <IntegrationCard
+ integration={integration}
+ key={integration.slug}
+ onSelect={() =>
+ track(analyticsEvents.integrationOpened, {
+ filter,
+ integration: integration.slug,
+ search: query.trim().length > 0,
+ })
+ }
+ />
))}
</div>
) : (
diff --git a/apps/docs/app/[lang]/integrations/components/integration-card.tsx b/apps/docs/app/[lang]/integrations/components/integration-card.tsx
index 4078112f6..1dd5b536e 100644
--- a/apps/docs/app/[lang]/integrations/components/integration-card.tsx
+++ b/apps/docs/app/[lang]/integrations/components/integration-card.tsx
@@ -12,15 +12,17 @@ const typeLabel: Record<Integration["type"], string> = {
interface IntegrationCardProps {
integration: Integration;
+ onSelect?: () => void;
}
-export const IntegrationCard = ({ integration }: IntegrationCardProps) => {
+export const IntegrationCard = ({ integration, onSelect }: IntegrationCardProps) => {
const Logo = logos[integration.logo];
return (
<Link
className="group flex flex-col gap-4 rounded-lg border bg-background-100 p-5 transition-colors hover:border-gray-400 hover:bg-gray-100"
href={integrationPath(integration.slug)}
+ onClick={onSelect}
>
<div className="flex flex-wrap items-start justify-between gap-3">
<span className="flex size-10 shrink-0 items-center justify-center rounded-md border bg-background text-gray-1000">
diff --git a/apps/docs/app/[lang]/integrations/components/markdown.tsx b/apps/docs/app/[lang]/integrations/components/markdown.tsx
index b9ba87654..b3555d8a7 100644
--- a/apps/docs/app/[lang]/integrations/components/markdown.tsx
+++ b/apps/docs/app/[lang]/integrations/components/markdown.tsx
@@ -1,12 +1,20 @@
"use client";
import { createCodePlugin } from "@streamdown/code";
+import { track } from "@vercel/analytics";
import Link from "next/link";
import { useMemo } from "react";
import { type Components, Streamdown } from "streamdown";
import { geistShikiTheme } from "@vercel/geistdocs/shiki-theme";
+import { analyticsEvents } from "@/lib/analytics/events";
+
+export type IntegrationSection = "configure" | "install" | "quick_start";
interface MarkdownProps {
+ analytics?: {
+ integration: string;
+ section: IntegrationSection;
+ };
children: string;
}
@@ -31,21 +39,33 @@ const components: Partial<Components> = {
* directive in `app/styles/geistdocs.css`, and `@streamdown/code` provides
* Shiki syntax highlighting with the Geist theme.
*/
-export const Markdown = ({ children }: MarkdownProps) => {
+export const Markdown = ({ analytics, children }: MarkdownProps) => {
const codePlugin = useMemo(
() => createCodePlugin({ themes: [geistShikiTheme, geistShikiTheme] }),
[],
);
return (
- <Streamdown
- className="text-gray-900 [&_a]:font-medium [&_a]:text-gray-1000 [&_a]:underline [&_a]:underline-offset-4 [&_code]:text-gray-1000 [&_li]:my-1 [&_p]:my-3 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:pl-5"
- components={components}
- mode="static"
- plugins={{ code: codePlugin }}
- shikiTheme={[geistShikiTheme, geistShikiTheme]}
+ <div
+ onClick={(event) => {
+ if (
+ analytics &&
+ event.target instanceof Element &&
+ event.target.closest('[data-streamdown="code-block-copy-button"]')
+ ) {
+ track(analyticsEvents.integrationCodeCopyClicked, analytics);
+ }
+ }}
>
- {children}
- </Streamdown>
+ <Streamdown
+ className="text-gray-900 [&_a]:font-medium [&_a]:text-gray-1000 [&_a]:underline [&_a]:underline-offset-4 [&_code]:text-gray-1000 [&_li]:my-1 [&_p]:my-3 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:pl-5"
+ components={components}
+ mode="static"
+ plugins={{ code: codePlugin }}
+ shikiTheme={[geistShikiTheme, geistShikiTheme]}
+ >
+ {children}
+ </Streamdown>
+ </div>
);
};
diff --git a/apps/docs/app/[lang]/integrations/components/setup-tabs.tsx b/apps/docs/app/[lang]/integrations/components/setup-tabs.tsx
index 6021a1bc8..9233eaf69 100644
--- a/apps/docs/app/[lang]/integrations/components/setup-tabs.tsx
+++ b/apps/docs/app/[lang]/integrations/components/setup-tabs.tsx
@@ -1,7 +1,9 @@
"use client";
+import { track } from "@vercel/analytics";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback } from "react";
+import { analyticsEvents } from "@/lib/analytics/events";
import {
type AuthMode,
type ConnectionProtocol,
@@ -10,12 +12,16 @@ import {
} from "@/lib/integrations/data";
import { setupKey } from "@/lib/integrations/connection-setup";
import { cn } from "@/lib/utils";
-import { Markdown } from "./markdown";
+import { Markdown, type IntegrationSection } from "./markdown";
const PROTOCOL_PARAM = "protocol";
const AUTH_PARAM = "auth";
interface SetupTabsProps {
+ analytics: {
+ integration: string;
+ section: IntegrationSection;
+ };
protocols: ConnectionProtocol[];
authModes: AuthMode[];
variants: Record<string, string>;
@@ -51,7 +57,7 @@ const SwitcherRow = <T extends string>({
</div>
);
-export const SetupTabs = ({ protocols, authModes, variants }: SetupTabsProps) => {
+export const SetupTabs = ({ analytics, protocols, authModes, variants }: SetupTabsProps) => {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
@@ -71,8 +77,13 @@ export const SetupTabs = ({ protocols, authModes, variants }: SetupTabsProps) =>
const params = new URLSearchParams(searchParams);
params.set(param, value);
router.replace(`${pathname}?${params.toString()}`, { scroll: false });
+ track(analyticsEvents.integrationSetupOptionSelected, {
+ ...analytics,
+ option: param === PROTOCOL_PARAM ? "protocol" : "auth",
+ value,
+ });
},
- [pathname, router, searchParams],
+ [analytics, pathname, router, searchParams],
);
return (
@@ -97,7 +108,11 @@ export const SetupTabs = ({ protocols, authModes, variants }: SetupTabsProps) =>
)}
</div>
)}
- {body ? <Markdown key={variantKey}>{body}</Markdown> : null}
+ {body ? (
+ <Markdown analytics={analytics} key={variantKey}>
+ {body}
+ </Markdown>
+ ) : null}
</div>
);
};
diff --git a/apps/docs/app/[lang]/llms.mdx/[[...slug]]/route.ts b/apps/docs/app/[lang]/llms.mdx/[[...slug]]/route.ts
index 494febfb3..60d3c7075 100644
--- a/apps/docs/app/[lang]/llms.mdx/[[...slug]]/route.ts
+++ b/apps/docs/app/[lang]/llms.mdx/[[...slug]]/route.ts
@@ -1,4 +1,12 @@
import { createDocsMarkdownRoute } from "@vercel/geistdocs/routes/llms";
+import {
+ analyticsEvents,
+ countMarkdownSuggestions,
+ getCountBucket,
+ getDocsSurface,
+ getMarkdownFormat,
+} from "@/lib/analytics/events";
+import { trackServerEvent } from "@/lib/analytics/server";
import { getMarkdownRequestedPath } from "@/lib/geistdocs/markdown-path";
import { geistdocsSource } from "@/lib/geistdocs/source";
import { integrationSource } from "@/lib/integrations/source";
@@ -10,5 +18,19 @@ const markdownRoute = createDocsMarkdownRoute({
sources: [geistdocsSource, integrationSource],
});
-export const GET = markdownRoute.GET;
+export const GET = async (request: Request, context: Parameters<typeof markdownRoute.GET>[1]) => {
+ const response = await markdownRoute.GET(request, context);
+
+ if (response.headers.get("x-geistdocs-not-found") === "1") {
+ const { pathname } = new URL(request.url);
+ const body = await response.clone().text();
+ trackServerEvent(request, analyticsEvents.smartMarkdownNotFound, {
+ format: getMarkdownFormat(pathname, request.headers.get("accept")),
+ suggestions: getCountBucket(countMarkdownSuggestions(body)),
+ surface: getDocsSurface(pathname),
+ });
+ }
+
+ return response;
+};
export const generateStaticParams = markdownRoute.generateStaticParams;
diff --git a/apps/docs/app/[lang]/templates/[slug]/page.tsx b/apps/docs/app/[lang]/templates/[slug]/page.tsx
index d34f89db4..5520b84fd 100644
--- a/apps/docs/app/[lang]/templates/[slug]/page.tsx
+++ b/apps/docs/app/[lang]/templates/[slug]/page.tsx
@@ -79,7 +79,11 @@ const TemplateDetailPage = async ({ params }: { params: Promise<PageParams> }) =
<div className="min-w-0">
<p className="max-w-[520px] text-copy-16 text-gray-900">{entry.description}</p>
<div className="mt-6">
- <TemplateActions setupPrompt={entry.setupPrompt} sourceHref={entry.sourceHref} />
+ <TemplateActions
+ setupPrompt={entry.setupPrompt}
+ sourceHref={entry.sourceHref}
+ template={entry.slug}
+ />
</div>
<div className="pt-3 lg:hidden">
<IntegrationList entry={entry} />
diff --git a/apps/docs/app/[lang]/templates/[slug]/template-actions.tsx b/apps/docs/app/[lang]/templates/[slug]/template-actions.tsx
index cd6569c65..385f735e5 100644
--- a/apps/docs/app/[lang]/templates/[slug]/template-actions.tsx
+++ b/apps/docs/app/[lang]/templates/[slug]/template-actions.tsx
@@ -1,16 +1,19 @@
"use client";
import { SiGithub } from "@icons-pack/react-simple-icons";
+import { track } from "@vercel/analytics";
import { Button } from "@vercel/geistdocs/components/button";
import { CheckIcon, CopyIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
+import { analyticsEvents } from "@/lib/analytics/events";
interface TemplateActionsProps {
setupPrompt: string;
sourceHref: string;
+ template: string;
}
-export const TemplateActions = ({ setupPrompt, sourceHref }: TemplateActionsProps) => {
+export const TemplateActions = ({ setupPrompt, sourceHref, template }: TemplateActionsProps) => {
const [copied, setCopied] = useState(false);
const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -25,6 +28,7 @@ export const TemplateActions = ({ setupPrompt, sourceHref }: TemplateActionsProp
const copyPrompt = async () => {
await navigator.clipboard.writeText(setupPrompt);
+ track(analyticsEvents.templateSetupCopied, { template });
setCopied(true);
if (resetTimer.current) {
clearTimeout(resetTimer.current);
@@ -63,7 +67,12 @@ export const TemplateActions = ({ setupPrompt, sourceHref }: TemplateActionsProp
</span>
</Button>
<Button asChild className="font-medium text-label-14" variant="outline">
- <a href={sourceHref} rel="noopener noreferrer" target="_blank">
+ <a
+ href={sourceHref}
+ onClick={() => track(analyticsEvents.templateSourceOpened, { template })}
+ rel="noopener noreferrer"
+ target="_blank"
+ >
<SiGithub aria-hidden="true" className="size-4" />
View GitHub
</a>
diff --git a/apps/docs/app/[lang]/templates/template-gallery.tsx b/apps/docs/app/[lang]/templates/template-gallery.tsx
index 343ebb12a..a01b3fcfc 100644
--- a/apps/docs/app/[lang]/templates/template-gallery.tsx
+++ b/apps/docs/app/[lang]/templates/template-gallery.tsx
@@ -1,5 +1,6 @@
"use client";
+import { track } from "@vercel/analytics";
import { Button } from "@vercel/geistdocs/components/button";
import {
DropdownMenu,
@@ -11,7 +12,13 @@ import {
import { Input } from "@vercel/geistdocs/components/input";
import { ChevronDownIcon, SearchIcon } from "lucide-react";
import Link from "next/link";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ analyticsEvents,
+ getCountBucket,
+ getQueryLengthBucket,
+ normalizeSearchQuery,
+} from "@/lib/analytics/events";
import { templatePath } from "@/lib/geistdocs/canonical";
import type { TemplateCategory, TemplateEntry, TemplateIntegration } from "@/lib/templates/data";
import { integrationIcons } from "./integration-icons";
@@ -70,11 +77,12 @@ const FilterOption = ({ label, value }: { label: string; value: string }) => (
</DropdownMenuRadioItem>
);
-const TemplateCard = ({ entry }: { entry: TemplateEntry }) => (
+const TemplateCard = ({ entry, onSelect }: { entry: TemplateEntry; onSelect: () => void }) => (
<li>
<Link
className="flex min-h-36 flex-col rounded-lg border border-gray-alpha-400 bg-background-100 p-4 no-underline outline-none transition-colors hover:border-gray-alpha-500 hover:bg-gray-alpha-100 focus-visible:border-gray-alpha-600 focus-visible:ring-2 focus-visible:ring-blue-700 focus-visible:ring-offset-2 focus-visible:ring-offset-background-100 motion-reduce:transition-none"
href={templatePath(entry.slug)}
+ onClick={onSelect}
>
<h2 className="text-gray-1000 text-heading-16">{entry.title}</h2>
<p className="mt-2 line-clamp-2 max-w-[90%] text-balance text-[14px] leading-[1.3] text-gray-800">
@@ -103,6 +111,7 @@ export const TemplateGallery = ({ entries }: TemplateGalleryProps) => {
const [query, setQuery] = useState("");
const [category, setCategory] = useState<FilterValue<TemplateCategory>>(ALL);
const [integration, setIntegration] = useState<FilterValue<TemplateIntegration>>(ALL);
+ const lastTrackedSearch = useRef("");
const filterOptions = useMemo(() => {
const categories = new Set<TemplateCategory>();
@@ -142,6 +151,30 @@ export const TemplateGallery = ({ entries }: TemplateGalleryProps) => {
});
}, [category, entries, integration, query]);
+ useEffect(() => {
+ const normalizedQuery = normalizeSearchQuery(query);
+ if (!normalizedQuery) {
+ lastTrackedSearch.current = "";
+ return;
+ }
+
+ const searchKey = `${category}:${integration}:${normalizedQuery}`;
+ if (searchKey === lastTrackedSearch.current) return;
+
+ const timer = setTimeout(() => {
+ track(analyticsEvents.templatesSearched, {
+ category,
+ integration,
+ query: normalizedQuery,
+ query_length: getQueryLengthBucket(normalizedQuery),
+ results: getCountBucket(results.length),
+ });
+ lastTrackedSearch.current = searchKey;
+ }, 500);
+
+ return () => clearTimeout(timer);
+ }, [category, integration, query, results.length]);
+
return (
<section aria-label="Templates" className="flex flex-col gap-6">
<div className="flex flex-col gap-2 md:flex-row">
@@ -163,14 +196,26 @@ export const TemplateGallery = ({ entries }: TemplateGalleryProps) => {
<FilterSelect
allLabel="All categories"
label="Filter by category"
- onChange={setCategory}
+ onChange={(value) => {
+ setCategory(value);
+ track(analyticsEvents.templateFilterSelected, {
+ filter: "category",
+ value,
+ });
+ }}
options={filterOptions.categories}
value={category}
/>
<FilterSelect
allLabel="All integrations"
label="Filter by integration"
- onChange={setIntegration}
+ onChange={(value) => {
+ setIntegration(value);
+ track(analyticsEvents.templateFilterSelected, {
+ filter: "integration",
+ value,
+ });
+ }}
options={filterOptions.integrations}
value={integration}
/>
@@ -181,7 +226,18 @@ export const TemplateGallery = ({ entries }: TemplateGalleryProps) => {
{results.length > 0 ? (
<ul className="grid list-none gap-4 p-0 sm:grid-cols-2 lg:grid-cols-3">
{results.map((entry) => (
- <TemplateCard entry={entry} key={entry.title} />
+ <TemplateCard
+ entry={entry}
+ key={entry.title}
+ onSelect={() =>
+ track(analyticsEvents.templateOpened, {
+ category,
+ integration,
+ search: query.trim().length > 0,
+ template: entry.slug,
+ })
+ }
+ />
))}
</ul>
) : (
diff --git a/apps/docs/app/api/chat/route.ts b/apps/docs/app/api/chat/route.ts
index edbcc635c..e4c9b4e51 100644
--- a/apps/docs/app/api/chat/route.ts
+++ b/apps/docs/app/api/chat/route.ts
@@ -1,4 +1,11 @@
import { createChatRoute } from "@vercel/geistdocs/routes/chat";
+import {
+ analyticsEvents,
+ getAskAiContext,
+ getDocsSurface,
+ getResponseOutcome,
+} from "@/lib/analytics/events";
+import { trackServerEvent } from "@/lib/analytics/server";
import { config } from "@/lib/geistdocs/config";
import { geistdocsSource } from "@/lib/geistdocs/source";
@@ -9,4 +16,30 @@ const chatRoute = createChatRoute({
sources: [geistdocsSource],
});
-export const POST = chatRoute.POST;
+export const POST = async (request: Request) => {
+ const analyticsRequest = request.clone();
+ const response = await chatRoute.POST(request);
+ const body: unknown = await analyticsRequest.json().catch(() => null);
+
+ if (typeof body === "object" && body !== null && "messages" in body) {
+ const messages = Array.isArray(body.messages) ? body.messages : [];
+ const userTurns = messages.filter(
+ (message) =>
+ typeof message === "object" &&
+ message !== null &&
+ "role" in message &&
+ message.role === "user",
+ ).length;
+ const currentRoute = "currentRoute" in body ? body.currentRoute : undefined;
+ const hasPageContext = "pageContext" in body && Boolean(body.pageContext);
+
+ trackServerEvent(request, analyticsEvents.askAiSubmitted, {
+ context: getAskAiContext(currentRoute, hasPageContext),
+ outcome: getResponseOutcome(response.status),
+ surface: getDocsSurface(currentRoute),
+ turn: userTurns > 1 ? "follow_up" : "first",
+ });
+ }
+
+ return response;
+};
diff --git a/apps/docs/lib/analytics/events.test.ts b/apps/docs/lib/analytics/events.test.ts
new file mode 100644
index 000000000..9d7a3cb1a
--- /dev/null
+++ b/apps/docs/lib/analytics/events.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from "vitest";
+import {
+ analyticsEvents,
+ countMarkdownSuggestions,
+ getAskAiContext,
+ getCountBucket,
+ getDocsSurface,
+ getMarkdownFormat,
+ getQueryLengthBucket,
+ getResponseOutcome,
+ isQueryFreeUrl,
+ normalizeSearchQuery,
+} from "./events";
+
+describe("docs analytics", () => {
+ it("keeps event names unique", () => {
+ const names = Object.values(analyticsEvents);
+ expect(new Set(names).size).toBe(names.length);
+ });
+
+ it("identifies requests safe for server analytics", () => {
+ expect(isQueryFreeUrl("https://eve.dev/api/chat")).toBe(true);
+ expect(isQueryFreeUrl("https://eve.dev/docs/missing?token=secret")).toBe(false);
+ expect(isQueryFreeUrl("not a URL")).toBe(false);
+ });
+
+ it.each([
+ ["/", "home"],
+ ["https://eve.dev/docs/agent-config?tab=files", "docs"],
+ ["/integrations/slack", "integrations"],
+ ["/templates/eve-chat-template", "templates"],
+ ["/api/search", "other"],
+ [undefined, "other"],
+ ])("classifies %s as %s without retaining the URL", (value, expected) => {
+ expect(getDocsSurface(value)).toBe(expected);
+ });
+
+ it.each([
+ ["/docs/agent-config", false, "page"],
+ ["/", false, "global"],
+ [undefined, false, "global"],
+ [undefined, true, "page"],
+ ])("classifies Ask AI context for %s", (currentRoute, hasPageContext, expected) => {
+ expect(getAskAiContext(currentRoute, hasPageContext)).toBe(expected);
+ });
+
+ it("uses bounded result-count buckets", () => {
+ expect([0, 1, 5, 6, 10, 11, 500].map(getCountBucket)).toEqual([
+ "0",
+ "1-5",
+ "1-5",
+ "6-10",
+ "6-10",
+ "11+",
+ "11+",
+ ]);
+ });
+
+ it("uses bounded query-length buckets", () => {
+ expect(getQueryLengthBucket("a")).toBe("1-2");
+ expect(getQueryLengthBucket("agent")).toBe("3-10");
+ expect(getQueryLengthBucket("how do sessions work")).toBe("11-30");
+ expect(getQueryLengthBucket("how do I deploy an agent to my own infrastructure")).toBe("31+");
+ });
+
+ it("normalizes and bounds recorded search terms", () => {
+ expect(normalizeSearchQuery(" Durable Agents ")).toBe("durable agents");
+ expect(normalizeSearchQuery("AGENT")).toBe("agent");
+ expect(normalizeSearchQuery("a".repeat(200))).toHaveLength(120);
+ });
+
+ it.each([
+ [200, "accepted"],
+ [399, "accepted"],
+ [400, "client_error"],
+ [499, "client_error"],
+ [500, "server_error"],
+ ])("classifies status %i as %s", (status, expected) => {
+ expect(getResponseOutcome(status)).toBe(expected);
+ });
+
+ it("classifies Markdown negotiation without retaining the requested path", () => {
+ expect(getMarkdownFormat("/docs/missing.md", null)).toBe("md");
+ expect(getMarkdownFormat("/docs/missing.mdx", null)).toBe("mdx");
+ expect(getMarkdownFormat("/docs/missing", "text/markdown")).toBe("accept");
+ expect(getMarkdownFormat("/docs/missing", "text/html")).toBe("unknown");
+ });
+
+ it("counts smart 404 suggestions without retaining their destinations", () => {
+ expect(
+ countMarkdownSuggestions(
+ "# Page Not Found\n\n- [Agent config](/docs/agent-config.md): Configure an agent.\n- [Tools](/docs/tools.md): Add tools.\n",
+ ),
+ ).toBe(2);
+ expect(
+ countMarkdownSuggestions("# Page Not Found\n\nAll pages: [/llms.txt](/llms.txt)\n"),
+ ).toBe(0);
+ });
+});
diff --git a/apps/docs/lib/analytics/events.ts b/apps/docs/lib/analytics/events.ts
new file mode 100644
index 000000000..9dabd8141
--- /dev/null
+++ b/apps/docs/lib/analytics/events.ts
@@ -0,0 +1,94 @@
+export const analyticsEvents = {
+ askAiSubmitted: "Submitted docs question",
+ gettingStartedOpened: "Opened getting started",
+ installerCommandCopyClicked: "Clicked installer command copy",
+ installerCommandSelected: "Selected installer command",
+ integrationCodeCopyClicked: "Clicked integration code copy",
+ integrationDocsOpened: "Opened integration docs",
+ integrationFilterSelected: "Selected integration filter",
+ integrationOpened: "Opened integration",
+ integrationSetupOptionSelected: "Selected integration setup option",
+ integrationsSearched: "Searched integrations",
+ smartMarkdownNotFound: "Served smart Markdown 404",
+ templateFilterSelected: "Selected template filter",
+ templateOpened: "Opened template",
+ templatesSearched: "Searched templates",
+ templateSetupCopied: "Copied template setup prompt",
+ templateSourceOpened: "Opened template source",
+} as const;
+
+export type AnalyticsEventName = (typeof analyticsEvents)[keyof typeof analyticsEvents];
+
+export type DocsSurface = "docs" | "home" | "integrations" | "other" | "templates";
+
+export const isQueryFreeUrl = (url: string): boolean => {
+ try {
+ return new URL(url).search === "";
+ } catch {
+ return false;
+ }
+};
+
+export const normalizeSearchQuery = (query: string): string =>
+ query.normalize("NFKC").trim().replace(/\s+/g, " ").toLowerCase().slice(0, 120);
+
+export const getDocsSurface = (value: unknown): DocsSurface => {
+ if (typeof value !== "string") return "other";
+
+ let pathname = value;
+ try {
+ pathname = new URL(value, "https://eve.dev").pathname;
+ } catch {
+ pathname = value.split("?")[0]?.split("#")[0] ?? value;
+ }
+
+ if (pathname === "/" || pathname === "/en") return "home";
+ if (pathname === "/docs" || pathname.startsWith("/docs/")) return "docs";
+ if (pathname === "/integrations" || pathname.startsWith("/integrations/")) {
+ return "integrations";
+ }
+ if (pathname === "/templates" || pathname.startsWith("/templates/")) return "templates";
+ return "other";
+};
+
+export const getAskAiContext = (
+ currentRoute: unknown,
+ hasPageContext: boolean,
+): "global" | "page" =>
+ hasPageContext || getDocsSurface(currentRoute) === "docs" ? "page" : "global";
+
+export const getCountBucket = (count: number): "0" | "1-5" | "6-10" | "11+" => {
+ if (count <= 0) return "0";
+ if (count <= 5) return "1-5";
+ if (count <= 10) return "6-10";
+ return "11+";
+};
+
+export const getQueryLengthBucket = (query: string): "1-2" | "3-10" | "11-30" | "31+" => {
+ const length = query.trim().length;
+ if (length <= 2) return "1-2";
+ if (length <= 10) return "3-10";
+ if (length <= 30) return "11-30";
+ return "31+";
+};
+
+export const getResponseOutcome = (
+ status: number,
+): "accepted" | "client_error" | "server_error" => {
+ if (status >= 500) return "server_error";
+ if (status >= 400) return "client_error";
+ return "accepted";
+};
+
+export const getMarkdownFormat = (
+ pathname: string,
+ accept: string | null,
+): "accept" | "md" | "mdx" | "unknown" => {
+ if (pathname.endsWith(".mdx")) return "mdx";
+ if (pathname.endsWith(".md")) return "md";
+ if (accept?.toLowerCase().includes("text/markdown")) return "accept";
+ return "unknown";
+};
+
+export const countMarkdownSuggestions = (body: string): number =>
+ body.match(/^- \[[^\]]+\]\([^\n]+\)/gm)?.length ?? 0;
diff --git a/apps/docs/lib/analytics/server.test.ts b/apps/docs/lib/analytics/server.test.ts
new file mode 100644
index 000000000..aaf9e79dc
--- /dev/null
+++ b/apps/docs/lib/analytics/server.test.ts
@@ -0,0 +1,32 @@
+import { track } from "@vercel/analytics/server";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { analyticsEvents } from "./events";
+import { trackServerEvent } from "./server";
+
+vi.mock("@vercel/analytics/server", () => ({ track: vi.fn() }));
+
+describe("server analytics", () => {
+ afterEach(() => {
+ vi.mocked(track).mockClear();
+ });
+
+ it("does not call the SDK in a query-bearing request context", () => {
+ const request = new Request("https://eve.dev/docs/missing?token=secret");
+
+ trackServerEvent(request, analyticsEvents.smartMarkdownNotFound, { surface: "docs" });
+
+ expect(track).not.toHaveBeenCalled();
+ });
+
+ it("tracks query-free requests with the original request context", () => {
+ const request = new Request("https://eve.dev/api/chat", { method: "POST" });
+
+ trackServerEvent(request, analyticsEvents.askAiSubmitted, { outcome: "accepted" });
+
+ expect(track).toHaveBeenCalledWith(
+ analyticsEvents.askAiSubmitted,
+ { outcome: "accepted" },
+ { request },
+ );
+ });
+});
diff --git a/apps/docs/lib/analytics/server.ts b/apps/docs/lib/analytics/server.ts
new file mode 100644
index 000000000..2b46ce1f3
--- /dev/null
+++ b/apps/docs/lib/analytics/server.ts
@@ -0,0 +1,13 @@
+import { track } from "@vercel/analytics/server";
+import { type AnalyticsEventName, isQueryFreeUrl } from "./events";
+
+export const trackServerEvent = (
+ request: Request,
+ event: AnalyticsEventName,
+ properties: Record<string, boolean | number | string>,
+) => {
+ // The SDK prefers Next's ambient request URL over the passed Request, so a
+ // query-bearing request must be skipped rather than reconstructed.
+ if (!isQueryFreeUrl(request.url)) return;
+ void track(event, properties, { request });
+};