Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(prompts): make Prompts an expandable sidebar menu with a route per view (#1016)
Cihanbb4216ea0be6
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 65c6a2f2f..be1e0acbd 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -64,7 +64,12 @@"toggleMenu": "Toggle navigation menu","keepSidebarOpen": "Keep sidebar open","collapseSidebar": "Collapse sidebar",- "feedback": "Send feedback"+ "feedback": "Send feedback",+ "trackedPrompts": "Tracked Prompts",+ "promptSuggestions": "Prompt Suggestions",+ "queryFanouts": "Query Fan-outs",+ "promptsInsights": "Insights",+ "toggleSubmenu": "Show or hide {label}"},"actionCenter": {"tabs": {diff --git a/web/next.config.ts b/web/next.config.tsindex 904064222..92151e571 100644--- a/web/next.config.ts+++ b/web/next.config.ts@@ -4,7 +4,33 @@ import createNextIntlPlugin from 'next-intl/plugin';const withNextIntl = createNextIntlPlugin('./src/i18n/request.ts');const nextConfig: NextConfig = {- /* config options here */+ // The Prompts area has a route per view (PROMPT-001). Older links and+ // bookmarks — /dashboard/prompts and its ?tab= / ?view= shapes — land on+ // the matching route; their other query params come along.+ async redirects() {+ const base = '/dashboard/prompts';+ return [+ {+ source: base,+ has: [{ type: 'query', key: 'tab', value: 'fanout' }],+ destination: `${base}/fan-outs`,+ permanent: false,+ },+ {+ source: base,+ has: [{ type: 'query', key: 'tab', value: 'insights' }],+ destination: `${base}/insights`,+ permanent: false,+ },+ {+ source: base,+ has: [{ type: 'query', key: 'view', value: 'suggestions' }],+ destination: `${base}/suggestions`,+ permanent: false,+ },+ { source: base, destination: `${base}/tracked`, permanent: false },+ ];+ },};export default withNextIntl(nextConfig);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/fan-outs/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/fan-outs/page.tsxnew file mode 100644index 000000000..3b647993c--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/fan-outs/page.tsx@@ -0,0 +1,3 @@+// The Prompts page, opened on its fan-outs view (PROMPT-001). It reads the view from+// the route, so the sidebar submenu and the in-page tabs stay in sync.+export { default } from '../page';diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/insights/page.tsxnew file mode 100644index 000000000..b3a02226d--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/insights/page.tsx@@ -0,0 +1,3 @@+// The Prompts page, opened on its insights view (PROMPT-001). It reads the view from+// the route, so the sidebar submenu and the in-page tabs stay in sync.+export { default } from '../page';diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex ef30bf4f8..fdbe1efa4 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -4,7 +4,8 @@ import { useState, useRef, useEffect, useCallback, useMemo } from 'react';import { createPortal } from 'react-dom';import { useTranslations } from 'next-intl';import { useSearchParams } from 'next/navigation';-import { Link } from '@/i18n/navigation';+import { Link, usePathname } from '@/i18n/navigation';+import { PROMPTS_BASE, sectionFor, sectionFromPath } from '@/lib/prompts-routes';import dynamic from 'next/dynamic';import { Skeleton } from '@/components/ui/skeleton';@@ -1115,8 +1116,12 @@ export default function PromptsPage() {(s) => s.brands.find((brand) => brand.id === s.activeBrandId) ?? null,);const searchParams = useSearchParams();+ // On /dashboard/prompts/{tracked,suggestions,fan-outs,insights} the route+ // names the view (PROMPT-001); ?tab= / ?view= are the older links' shape.+ const section = sectionFromPath(usePathname());const initialTab: TabId = (() => {+ if (section) return section.tab;const raw = searchParams.get('tab');if ((VALID_TABS as readonly string[]).includes(raw ?? '')) return raw as TabId;return 'all';@@ -1127,6 +1132,7 @@ export default function PromptsPage() {// what could be. A sub-tab rather than a fourth top-level tab, because the// date range, the Add prompt action and the export all belong to both.const initialView: PromptsView = (() => {+ if (section) return section.view;const raw = searchParams.get('view');if ((PROMPT_VIEWS as readonly string[]).includes(raw ?? '')) return raw as PromptsView;// Links written before the split point at the suggestions card's anchor.@@ -1148,7 +1154,9 @@ export default function PromptsPage() {const [rangePreset, setRangePreset] = useState<PromptRangePreset>(initialRange);// Which tracked location the health columns describe. Empty = every// location blended, which is what the table has always shown (#691).- const [regionFilter, setRegionFilter] = useState('');+ // In the URL like the range, so it survives moving between the Prompts+ // routes from the sidebar (PROMPT-001).+ const [regionFilter, setRegionFilter] = useState(() => searchParams.get('region') ?? '');const [availableRegions, setAvailableRegions] = useState<string[]>([]);const [customFrom, setCustomFrom] = useState(() => searchParams.get('from') ?? '');const [customTo, setCustomTo] = useState(() => searchParams.get('to') ?? '');@@ -1176,38 +1184,37 @@ export default function PromptsPage() {// blocked Next's server-action queue, so the page's data fetch never even// dispatched (the "prompts table spins forever" bug). replaceState updates// the URL with no server request; Next's router syncs with the History API.+ //+ // The tab and view live in the path (PROMPT-001): /dashboard/prompts/tracked,+ // /suggestions, /fan-outs, /insights — the routes the sidebar's Prompts+ // submenu links to, so the sidebar and these tabs always agree. The path is+ // rewritten in place under any locale prefix.useEffect(() => {- const currentTab = searchParams.get('tab');- const currentRange = searchParams.get('range');// The default range stays out of the URL so shared links keep their// existing shape unless the user actually picked a different window.- const wantRange = rangePreset === DEFAULT_PROMPT_RANGE_PRESET ? null : rangePreset;- const wantView = view === 'tracked' ? null : view;- const wantFrom = rangePreset === 'custom' && customFrom ? customFrom : null;- const wantTo = rangePreset === 'custom' && customTo ? customTo : null;- if (- currentTab === tab &&- searchParams.get('view') === wantView &&- currentRange === wantRange &&- searchParams.get('from') === wantFrom &&- searchParams.get('to') === wantTo- ) {+ const want: Record<string, string | null> = {+ range: rangePreset === DEFAULT_PROMPT_RANGE_PRESET ? null : rangePreset,+ from: rangePreset === 'custom' && customFrom ? customFrom : null,+ to: rangePreset === 'custom' && customTo ? customTo : null,+ region: regionFilter || null,+ tab: null,+ view: null,+ };+ const { pathname, search, hash } = window.location;+ const at = pathname.indexOf(PROMPTS_BASE);+ const wantPath = `${at > 0 ? pathname.slice(0, at) : ''}${sectionFor(tab, view).href}`;+ const params = new URLSearchParams(search);+ if (pathname === wantPath && Object.entries(want).every(([k, v]) => params.get(k) === v)) {return;}- const params = new URLSearchParams(Array.from(searchParams.entries()));- params.set('tab', tab);- if (wantView) params.set('view', wantView);- else params.delete('view');- if (wantRange) params.set('range', wantRange);- else params.delete('range');- if (wantFrom) params.set('from', wantFrom);- else params.delete('from');- if (wantTo) params.set('to', wantTo);- else params.delete('to');- // Keep the hash: deep links like #prompt-opportunities arrive without a- // tab param, and this sync must not strip their anchor from the URL.- window.history.replaceState(null, '', `?${params.toString()}${window.location.hash}`);- }, [tab, view, rangePreset, customFrom, customTo, searchParams]);+ for (const [k, v] of Object.entries(want)) {+ if (v) params.set(k, v);+ else params.delete(k);+ }+ const query = params.toString();+ // Keep the hash: deep links like #prompt-opportunities must keep their anchor.+ window.history.replaceState(null, '', `${wantPath}${query ? `?${query}` : ''}${hash}`);+ }, [tab, view, rangePreset, customFrom, customTo, regionFilter, searchParams]);// Deep link from the Insights Recommendations row (#459): the target card// only exists once the Insights tab's volume data has rendered, so a barediff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/suggestions/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/suggestions/page.tsxnew file mode 100644index 000000000..7f3e2629f--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/suggestions/page.tsx@@ -0,0 +1,3 @@+// The Prompts page, opened on its suggestions view (PROMPT-001). It reads the view from+// the route, so the sidebar submenu and the in-page tabs stay in sync.+export { default } from '../page';diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/tracked/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/tracked/page.tsxnew file mode 100644index 000000000..e9fecc2b2--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/tracked/page.tsx@@ -0,0 +1,3 @@+// The Prompts page, opened on its tracked view (PROMPT-001). It reads the view from+// the route, so the sidebar submenu and the in-page tabs stay in sync.+export { default } from '../page';diff --git a/web/src/components/layout/mobile-nav.tsx b/web/src/components/layout/mobile-nav.tsxindex 026ee1482..3a5bfec5d 100644--- a/web/src/components/layout/mobile-nav.tsx+++ b/web/src/components/layout/mobile-nav.tsx@@ -124,7 +124,7 @@ export function MobileNav() {);}- return (+ const link = (<Link key={item.href} href={item.href} onClick={() => setOpen(false)}><spanclassName={cn(@@ -147,6 +147,29 @@ export function MobileNav() {</span></Link>);+ if (!item.children?.length) return link;+ // The Prompts submenu (PROMPT-001), always shown on mobile.+ return (+ <div key={item.href}>+ {link}+ <div className="ml-7 border-l pl-2">+ {item.children.map((child) => (+ <Link key={child.href} href={child.href} onClick={() => setOpen(false)}>+ <span+ className={cn(+ 'block rounded-md px-3 py-1.5 text-sm transition-colors',+ pathname === child.href+ ? 'font-medium text-primary'+ : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',+ )}+ >+ {getDashboardNavLabel(child.title, t, tBrands)}+ </span>+ </Link>+ ))}+ </div>+ </div>+ );}),)}</nav>diff --git a/web/src/components/layout/sidebar.tsx b/web/src/components/layout/sidebar.tsxindex 27f6da21f..57d44cdb6 100644--- a/web/src/components/layout/sidebar.tsx+++ b/web/src/components/layout/sidebar.tsx@@ -4,7 +4,10 @@ import Image from 'next/image';import { useTheme } from 'next-themes';import { useEffect, useRef, useState } from 'react';import { useTranslations } from 'next-intl';+import { useSearchParams } from 'next/navigation';import { usePathname, Link } from '@/i18n/navigation';+import { getTrackedPromptCount } from '@/lib/actions/prompt';+import { carriedParams, PROMPTS_BASE } from '@/lib/prompts-routes';import { dashboardNav } from '@/config/dashboard';import {getDashboardNavLabel,@@ -24,6 +27,7 @@ import { Separator } from '@/components/ui/separator';import { BrandSwitcher } from '@/components/layout/brand-switcher';import { UserProfileNavItem } from '@/components/layout/user-profile-nav-item';import {+ ChevronDown,ChevronsLeft,ChevronsRight,Crown,@@ -35,6 +39,48 @@ import {/** How long the pointer rests on the collapsed sidebar before it opens. */const PEEK_DELAY_MS = 150;+/** Where the Prompts submenu's open/closed state is remembered (PROMPT-001). */+const SUBMENU_KEY = 'ansvisor.sidebar.promptsOpen';++/**+ * Arrow keys in the sidebar's links (PROMPT-001): up and down move between+ * them; right opens a submenu (or enters it), left leaves or closes it.+ * Enter follows the focused link, as links do.+ */+function handleNavKeys(+ e: React.KeyboardEvent<HTMLElement>,+ setSubmenuOpen: (open: boolean) => void,+) {+ const items = [...e.currentTarget.querySelectorAll<HTMLElement>('[data-nav-item]')];+ const current = document.activeElement as HTMLElement | null;+ const i = current ? items.indexOf(current) : -1;+ if (i < 0) return;+ const focus = (el: HTMLElement | undefined) => {+ if (!el) return;+ e.preventDefault();+ el.focus();+ };+ const isParent = current?.dataset.navItem === 'parent';+ const isChild = current?.dataset.navItem === 'child';+ if (e.key === 'ArrowDown') focus(items[i + 1]);+ else if (e.key === 'ArrowUp') focus(items[i - 1]);+ else if (e.key === 'ArrowRight' && isParent) {+ e.preventDefault();+ if (current?.getAttribute('aria-expanded') === 'true') focus(items[i + 1]);+ else setSubmenuOpen(true);+ } else if (e.key === 'ArrowLeft' && isParent) {+ e.preventDefault();+ setSubmenuOpen(false);+ } else if (e.key === 'ArrowLeft' && isChild) {+ focus(+ items+ .slice(0, i)+ .reverse()+ .find((el) => el.dataset.navItem === 'parent'),+ );+ }+}+export function Sidebar() {const pathname = usePathname();const { isCollapsed, toggleCollapse } = useSidebarStore();@@ -45,6 +91,13 @@ export function Sidebar() {const peekTimer = useRef<ReturnType<typeof setTimeout>>(undefined);const asideRef = useRef<HTMLElement>(null);const compact = isCollapsed && !peeking && !menuOpen;+ const searchParams = useSearchParams();+ const underPrompts = pathname.startsWith(PROMPTS_BASE);+ // The Prompts submenu: remembered per browser, and open whenever a Prompts+ // route is showing so the current view is always visible in it.+ const [submenuOpen, setSubmenuOpenState] = useState(true);+ const [trackedCount, setTrackedCount] = useState<number | null>(null);+ const activeBrandId = useBrandStore((s) => s.activeBrandId);const t = useTranslations('nav');const tBrands = useTranslations('brands');const { canUse, requiredPlanFor, isCloud } = useFeatureGate();@@ -73,6 +126,44 @@ export function Sidebar() {useEffect(() => () => clearTimeout(peekTimer.current), []);+ useEffect(() => {+ let stored: string | null = null;+ try {+ stored = localStorage.getItem(SUBMENU_KEY);+ } catch {+ // Storage can be unavailable (private mode); the default stands.+ }+ // eslint-disable-next-line react-hooks/set-state-in-effect+ if (stored !== null) setSubmenuOpenState(stored === '1');+ }, []);++ useEffect(() => {+ // eslint-disable-next-line react-hooks/set-state-in-effect+ if (underPrompts) setSubmenuOpenState(true);+ }, [underPrompts]);++ // The count beside Tracked Prompts, refreshed on brand switch and on every+ // page change so adding or deleting prompts shows up.+ useEffect(() => {+ if (!activeBrandId) return;+ let cancelled = false;+ getTrackedPromptCount(activeBrandId)+ .then((n) => !cancelled && setTrackedCount(n))+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, [activeBrandId, pathname]);++ const setSubmenuOpen = (open: boolean) => {+ setSubmenuOpenState(open);+ try {+ localStorage.setItem(SUBMENU_KEY, open ? '1' : '0');+ } catch {+ // Not remembered this time; nothing else depends on it.+ }+ };+const logoSrc = mounted && resolvedTheme === 'dark' ? '/logo_dark.svg' : '/logo_light.svg';function handleMouseEnter() {@@ -126,6 +217,13 @@ export function Sidebar() {ref={asideRef}onMouseEnter={handleMouseEnter}onMouseLeave={handleMouseLeave}+ // Keyboard users open a collapsed sidebar by tabbing into it, as+ // pointer users do by hovering.+ onFocus={() => isCollapsed && setPeeking(true)}+ onBlur={(e) => {+ if (!asideRef.current?.contains(e.relatedTarget as Node | null)) setPeeking(false);+ }}+ onKeyDown={(e) => handleNavKeys(e, setSubmenuOpen)}className={cn('absolute inset-y-0 left-0 z-40 flex flex-col border-r bg-sidebar transition-[width] duration-200',compact ? 'w-16' : 'w-60',@@ -223,8 +321,72 @@ export function Sidebar() {);}+ if (item.children?.length && !compact) {+ // Expandable item (PROMPT-001): the row toggles the+ // submenu, whose links are the item's views.+ const carry = underPrompts ? carriedParams(searchParams.toString()) : '';+ const submenuId = `submenu-${item.href.replace(/\W+/g, '-')}`;+ return (+ <div key={item.href}>+ <button+ type="button"+ data-nav-item="parent"+ aria-expanded={submenuOpen}+ aria-controls={submenuId}+ onClick={() => setSubmenuOpen(!submenuOpen)}+ className={cn(+ 'flex w-full items-center gap-3 rounded-md px-2 py-1.5 text-left text-[13px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',+ isActive+ ? 'text-primary'+ : 'text-muted-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',+ )}+ >+ <item.icon className="h-4 w-4 shrink-0" />+ <span className="flex-1 truncate">{label}</span>+ <ChevronDown+ className={cn(+ 'h-3.5 w-3.5 shrink-0 transition-transform',+ !submenuOpen && '-rotate-90',+ )}+ />+ </button>+ {submenuOpen && (+ <ul id={submenuId} className="mt-0.5 ml-[18px] space-y-0.5 border-l pl-2">+ {item.children.map((child) => {+ const childActive = pathname === child.href;+ return (+ <li key={child.href}>+ <Link+ href={`${child.href}${carry}`}+ data-nav-item="child"+ aria-current={childActive ? 'page' : undefined}+ className={cn(+ 'flex items-center gap-2 rounded-md px-2 py-1 text-[13px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',+ childActive+ ? 'bg-primary/10 font-medium text-primary'+ : 'text-muted-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',+ )}+ >+ <span className="flex-1 truncate">+ {getDashboardNavLabel(child.title, t, tBrands)}+ </span>+ {child.href.endsWith('/tracked') && trackedCount !== null && (+ <span className="text-[11px] tabular-nums text-muted-foreground">+ {trackedCount.toLocaleString()}+ </span>+ )}+ </Link>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ );+ }+return (- <Link key={item.href} href={item.href}>+ <Link key={item.href} href={item.href} data-nav-item="link"><spanclassName={cn('flex items-center gap-3 rounded-md px-2 py-1.5 text-[13px] font-medium transition-colors',diff --git a/web/src/config/dashboard.ts b/web/src/config/dashboard.tsindex 5956d3534..bc24f1643 100644--- a/web/src/config/dashboard.ts+++ b/web/src/config/dashboard.ts@@ -24,9 +24,17 @@ import type { Feature } from '@/config/plans';*/export type BrandPrefKey = 'shoppingModeEnabled';+/** A submenu entry under a NavItem (PROMPT-001). */+export interface NavChild {+ title: string;+ href: string;+}+export interface NavItem {title: string;href: string;+ /** Opens as a submenu under the item; the item itself then toggles it. */+ children?: NavChild[];icon: React.ComponentType<{ className?: string }>;badge?: string;disabled?: boolean;@@ -68,6 +76,12 @@ export const dashboardNav: NavGroup[] = [title: 'Prompts',href: '/dashboard/prompts',icon: Globe,+ children: [+ { title: 'Tracked Prompts', href: '/dashboard/prompts/tracked' },+ { title: 'Prompt Suggestions', href: '/dashboard/prompts/suggestions' },+ { title: 'Query Fan-outs', href: '/dashboard/prompts/fan-outs' },+ { title: 'Prompts Insights', href: '/dashboard/prompts/insights' },+ ],},{title: 'Topics',diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.tsindex ec0f01992..8769b3277 100644--- a/web/src/lib/actions/prompt.ts+++ b/web/src/lib/actions/prompt.ts@@ -796,3 +796,14 @@ export async function getPromptsPageData(locationQuota,};}++/** How many prompts the brand tracks — the count beside Tracked Prompts in the sidebar (PROMPT-001). */+export async function getTrackedPromptCount(brandId: string): Promise<number> {+ const supabase = await createClient();+ const { count, error } = await supabase+ .from('prompts')+ .select('id, prompt_sets!inner(brand_id)', { count: 'exact', head: true })+ .eq('prompt_sets.brand_id', brandId);+ if (error) throw new Error(error.message);+ return count ?? 0;+}diff --git a/web/src/lib/dashboard-navigation.test.ts b/web/src/lib/dashboard-navigation.test.tsindex daaae5e31..ef8ca8d70 100644--- a/web/src/lib/dashboard-navigation.test.ts+++ b/web/src/lib/dashboard-navigation.test.ts@@ -11,7 +11,9 @@ const translateBrands = (key: string) => `brands.${key}`;describe('getDashboardNavLabel', () => {it('maps every dashboard item through an i18n key', () => {- const titles = dashboardNav.flatMap((group) => group.items.map((item) => item.title));+ const titles = dashboardNav.flatMap((group) =>+ group.items.flatMap((item) => [item.title, ...(item.children ?? []).map((c) => c.title)]),+ );expect(Object.keys(dashboardNavLabelKeys).sort()).toEqual([...titles].sort());diff --git a/web/src/lib/dashboard-navigation.ts b/web/src/lib/dashboard-navigation.tsindex abb3c9415..4c4af90df 100644--- a/web/src/lib/dashboard-navigation.ts+++ b/web/src/lib/dashboard-navigation.ts@@ -14,6 +14,10 @@ export const dashboardNavLabelKeys: Record<string, NavLabelKey> = {'Answer Engine Insights': { namespace: 'nav', key: 'insights' },'AI Traffic Analytics': { namespace: 'nav', key: 'traffic' },Prompts: { namespace: 'nav', key: 'prompts' },+ 'Tracked Prompts': { namespace: 'nav', key: 'trackedPrompts' },+ 'Prompt Suggestions': { namespace: 'nav', key: 'promptSuggestions' },+ 'Query Fan-outs': { namespace: 'nav', key: 'queryFanouts' },+ 'Prompts Insights': { namespace: 'nav', key: 'promptsInsights' },Topics: { namespace: 'nav', key: 'topics' },'Content Optimization': { namespace: 'nav', key: 'content' },'Site Audit': { namespace: 'nav', key: 'audit' },diff --git a/web/src/lib/prompts-routes.test.ts b/web/src/lib/prompts-routes.test.tsnew file mode 100644index 000000000..aaca992e6--- /dev/null+++ b/web/src/lib/prompts-routes.test.ts@@ -0,0 +1,49 @@+/**+ * prompts-routes.test.ts (PROMPT-001)+ *+ * Tests the Prompts routes the sidebar submenu and the page's tabs share.+ */++import { describe, expect, test } from 'vitest';+import { carriedParams, sectionFor, sectionFromPath } from './prompts-routes';++describe('sectionFromPath', () => {+ test('reads the view from each route, with or without a trailing slash', () => {+ expect(sectionFromPath('/dashboard/prompts/tracked')).toMatchObject({+ tab: 'all',+ view: 'tracked',+ });+ expect(sectionFromPath('/dashboard/prompts/suggestions/')).toMatchObject({+ tab: 'all',+ view: 'suggestions',+ });+ expect(sectionFromPath('/dashboard/prompts/fan-outs')?.tab).toBe('fanout');+ expect(sectionFromPath('/dashboard/prompts/insights')?.tab).toBe('insights');+ });++ test('is null off the four routes (the base path, a prompt detail page)', () => {+ expect(sectionFromPath('/dashboard/prompts')).toBeNull();+ expect(sectionFromPath('/dashboard/prompts/8a1c-uuid')).toBeNull();+ });+});++describe('sectionFor', () => {+ test('maps the in-page tabs to the routes', () => {+ expect(sectionFor('all', 'tracked').href).toBe('/dashboard/prompts/tracked');+ expect(sectionFor('all', 'suggestions').href).toBe('/dashboard/prompts/suggestions');+ expect(sectionFor('fanout', 'suggestions').href).toBe('/dashboard/prompts/fan-outs');+ expect(sectionFor('insights', 'tracked').href).toBe('/dashboard/prompts/insights');+ });+});++describe('carriedParams', () => {+ test('keeps the date range and location, drops the rest', () => {+ expect(carriedParams('?tab=all&range=7d®ion=TR&sort=runs&positions=x')).toBe(+ '?range=7d®ion=TR',+ );+ expect(carriedParams('?range=custom&from=2026-10-01&to=2026-10-05')).toBe(+ '?range=custom&from=2026-10-01&to=2026-10-05',+ );+ expect(carriedParams('')).toBe('');+ });+});diff --git a/web/src/lib/prompts-routes.ts b/web/src/lib/prompts-routes.tsnew file mode 100644index 000000000..02247d3df--- /dev/null+++ b/web/src/lib/prompts-routes.ts@@ -0,0 +1,55 @@+/**+ * The Prompts area's four views and their routes (PROMPT-001). The sidebar's+ * Prompts submenu links to them, and the page's own tabs keep the URL on the+ * matching route, so the two always show the same view.+ */++export type PromptsTab = 'all' | 'fanout' | 'insights';+export type PromptsListView = 'tracked' | 'suggestions';++export interface PromptsSection {+ /** The route's last segment. */+ slug: 'tracked' | 'suggestions' | 'fan-outs' | 'insights';+ href: string;+ tab: PromptsTab;+ /** The Tracked / Suggestions switch; only meaningful on the Prompts tab. */+ view: PromptsListView;+}++export const PROMPTS_BASE = '/dashboard/prompts';++export const PROMPTS_SECTIONS: readonly PromptsSection[] = [+ { slug: 'tracked', href: `${PROMPTS_BASE}/tracked`, tab: 'all', view: 'tracked' },+ { slug: 'suggestions', href: `${PROMPTS_BASE}/suggestions`, tab: 'all', view: 'suggestions' },+ { slug: 'fan-outs', href: `${PROMPTS_BASE}/fan-outs`, tab: 'fanout', view: 'tracked' },+ { slug: 'insights', href: `${PROMPTS_BASE}/insights`, tab: 'insights', view: 'tracked' },+];++/** The section a pathname (without locale prefix) is on; null off the four routes. */+export function sectionFromPath(pathname: string): PromptsSection | null {+ const path = pathname.replace(/\/+$/, '');+ return PROMPTS_SECTIONS.find((s) => s.href === path) ?? null;+}++/** The route for a tab and list view, as the page's tabs set them. */+export function sectionFor(tab: PromptsTab, view: PromptsListView): PromptsSection {+ if (tab === 'fanout') return PROMPTS_SECTIONS[2];+ if (tab === 'insights') return PROMPTS_SECTIONS[3];+ return view === 'suggestions' ? PROMPTS_SECTIONS[1] : PROMPTS_SECTIONS[0];+}++/**+ * Query params that carry over when moving between the four sections — the+ * date range and location stay; the tab and view are in the path now, and a+ * prompt-specific panel or sort belongs to the table it was opened from.+ */+export function carriedParams(search: string): string {+ const params = new URLSearchParams(search);+ const keep = new URLSearchParams();+ for (const key of ['range', 'from', 'to', 'region']) {+ const value = params.get(key);+ if (value) keep.set(key, value);+ }+ const s = keep.toString();+ return s ? `?${s}` : '';+}