Skip to content

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.

feat(insights): show the last and next run in the header

Cihanc25933fd57fe
diff --git a/web/messages/en.json b/web/messages/en.json
index b6552b832..68e037150 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1838,6 +1838,14 @@
"openAction": "Open",
"gapChanged": "The gap changed since the page loaded. Refresh to see the latest."
},
+ "header": {
+ "lastRun": "Last run {when}",
+ "noRuns": "No runs yet",
+ "nextRun": "next run in {when}",
+ "minutes": "{n}m",
+ "hours": "{n}h",
+ "days": "{n}d"
+ },
"opportunities": {
"title": "Opportunities",
"seeAll": "See all",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_run-line.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_run-line.tsx
new file mode 100644
index 000000000..eb6620b1c
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_run-line.tsx
@@ -0,0 +1,59 @@
+'use client';
+
+import { Fragment, useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { formatRelative } from '@/lib/format-relative';
+import { timeUntil } from '@/lib/tracking-schedule';
+
+/**
+ * The header's "Acme Coffee · Last run 11h ago · next run in 13h" (VIS-012).
+ * Its own component with its own minute tick, so keeping "11h ago" current
+ * re-renders this line, not the whole page.
+ */
+export function RunLine({
+ brandName,
+ lastRunAt,
+ nextRunAt,
+ hasData,
+}: {
+ brandName: string;
+ /** The brand's last full run; null when it has none. */
+ lastRunAt: string | null;
+ /** When the next scheduled run is due; null when not known. */
+ nextRunAt: string | null;
+ /** Whether the brand has any answers, for a last run the ledger doesn't know. */
+ hasData: boolean;
+}) {
+ const t = useTranslations('insights.header');
+ const tCommon = useTranslations('common');
+ const [, setTick] = useState(0);
+ useEffect(() => {
+ const id = setInterval(() => setTick((n) => n + 1), 60_000);
+ return () => clearInterval(id);
+ }, []);
+
+ const nextIn = nextRunAt ? timeUntil(nextRunAt) : null;
+ const parts = [
+ // Answers without a known run (older than the ledger, outside the range):
+ // say nothing rather than "No runs yet".
+ lastRunAt
+ ? t('lastRun', { when: formatRelative(lastRunAt, tCommon) })
+ : hasData
+ ? null
+ : t('noRuns'),
+ nextIn ? t('nextRun', { when: t(nextIn.unit, { n: nextIn.value }) }) : null,
+ ].filter((part): part is string => part !== null);
+
+ return (
+ <p className="text-muted-foreground text-sm">
+ {brandName}
+ {/* Wraps between the parts, never inside one ("next / run in 13h"). */}
+ {parts.map((part) => (
+ <Fragment key={part}>
+ {' · '}
+ <span className="whitespace-nowrap">{part}</span>
+ </Fragment>
+ ))}
+ </p>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index a7cad0e1e..563765549 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -560,7 +560,7 @@ function NoDataForPeriod({ datePreset, onReset }: { datePreset: DatePreset; onRe
import { saveTrackingJob, loadTrackingJob, clearTrackingJob } from '@/lib/tracking-job-store';
import { toCsv } from '@/lib/csv';
-import { formatRelative } from '@/lib/format-relative';
+import { RunLine } from './_run-line';
function TrackingProgressBanner({
jobStatus,
@@ -732,6 +732,21 @@ export default function InsightsPage() {
const [isExporting, setIsExporting] = useState(false);
const [cronRun, setCronRun] = useState<TrackingWindow['activeRun']>(null);
const cronRunRef = useRef<TrackingWindow['activeRun']>(null);
+ // The header's last and next run (VIS-012), from the ledger read every minute.
+ const [runTimes, setRunTimes] = useState<Pick<TrackingWindow, 'lastRunAt' | 'nextRunAt'>>({
+ lastRunAt: null,
+ nextRunAt: null,
+ });
+ // Kept as is when unchanged, so the minute's read doesn't re-render the page.
+ const updateRunTimes = useCallback(
+ ({ lastRunAt, nextRunAt }: Pick<TrackingWindow, 'lastRunAt' | 'nextRunAt'>) =>
+ setRunTimes((prev) =>
+ prev.lastRunAt === lastRunAt && prev.nextRunAt === nextRunAt
+ ? prev
+ : { lastRunAt, nextRunAt },
+ ),
+ [],
+ );
const filtersRef = useRef(filters);
filtersRef.current = filters;
@@ -795,6 +810,7 @@ export default function InsightsPage() {
if (insights.trackingWindow) {
cronRunRef.current = insights.trackingWindow.activeRun;
setCronRun(insights.trackingWindow.activeRun);
+ updateRunTimes(insights.trackingWindow);
}
const anchored = insights.trackingWindow?.anchored;
setLoadedFilters({
@@ -871,7 +887,7 @@ export default function InsightsPage() {
setIsLoading(false);
}
},
- [brandId],
+ [brandId, updateRunTimes],
);
// A brand switch clears the brand-specific filters. Not on the first brand,
@@ -902,6 +918,11 @@ export default function InsightsPage() {
// localStorage, which is why users never saw anything during the daily
// morning run. When the active run disappears (= completed), silently
// reload so the anchored 24h window swaps to the fresh run in one step.
+ // Another brand's run times never show under this one's name, even when
+ // its first read fails.
+ useEffect(() => {
+ updateRunTimes({ lastRunAt: null, nextRunAt: null });
+ }, [brand?.id, updateRunTimes]);
useEffect(() => {
if (!brand?.id) return;
let cancelled = false;
@@ -912,6 +933,7 @@ export default function InsightsPage() {
const wasRunning = cronRunRef.current !== null;
cronRunRef.current = win.activeRun;
setCronRun(win.activeRun);
+ updateRunTimes(win);
if (wasRunning && !win.activeRun) {
loadData(undefined, { silent: true });
}
@@ -923,7 +945,7 @@ export default function InsightsPage() {
cancelled = true;
clearInterval(id);
};
- }, [brand?.id, loadData]);
+ }, [brand?.id, loadData, updateRunTimes]);
// Restore active job from localStorage or URL query param (post-payment redirect)
const searchParams = useSearchParams();
@@ -1165,10 +1187,6 @@ export default function InsightsPage() {
);
}
- const lastCheckedLabel = summary?.lastCheckedAt
- ? formatRelative(summary.lastCheckedAt, tCommon)
- : 'Never';
-
// The trend's subtitle (VIS-007): "Visibility · last 30 days".
const trendRangeLabel =
filters.datePreset === 'custom'
@@ -1191,9 +1209,14 @@ export default function InsightsPage() {
<div>
<h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
- <p className="text-muted-foreground text-sm">
- {brand.name} · Last run: {lastCheckedLabel}
- </p>
+ {/* The brand's last full run from the ledger; before the ledger has
+ one, the newest answer in view. */}
+ <RunLine
+ brandName={brand.name}
+ lastRunAt={runTimes.lastRunAt ?? summary?.lastCheckedAt ?? null}
+ nextRunAt={runTimes.nextRunAt}
+ hasData={hasAnyData === true}
+ />
</div>
<div className="flex items-center gap-2 shrink-0">
diff --git a/web/src/lib/actions/tracking-window.test.ts b/web/src/lib/actions/tracking-window.test.ts
new file mode 100644
index 000000000..2f8d5d83e
--- /dev/null
+++ b/web/src/lib/actions/tracking-window.test.ts
@@ -0,0 +1,110 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * getTrackingWindow's run times for the Insights header (VIS-012): the last
+ * run is the newest completed run of any kind, and the next one is worked
+ * out from the scheduled (cron) runs only, so a Run All never moves it.
+ */
+
+interface Run {
+ source: string;
+ started_at: string;
+ completed_at: string | null;
+}
+
+let runs: Run[] = [];
+
+function trackingRuns() {
+ const filters: { eq: Record<string, unknown>; notNull?: string; isNull?: string } = { eq: {} };
+ let order: string | null = null;
+ let limit = Infinity;
+ const result = () => {
+ const rows = runs
+ .filter((r) =>
+ Object.entries(filters.eq).every(([k, v]) => k === 'brand_id' || r[k as keyof Run] === v),
+ )
+ .filter((r) => !filters.notNull || r[filters.notNull as keyof Run] !== null)
+ .filter((r) => !filters.isNull || r[filters.isNull as keyof Run] === null)
+ .sort((a, b) =>
+ order ? String(b[order as keyof Run]).localeCompare(String(a[order as keyof Run])) : 0,
+ )
+ .slice(0, limit);
+ return { data: rows, error: null };
+ };
+ const b = {
+ select: () => b,
+ eq: (col: string, val: unknown) => {
+ filters.eq[col] = val;
+ return b;
+ },
+ not: (col: string) => {
+ filters.notNull = col;
+ return b;
+ },
+ is: (col: string) => {
+ filters.isNull = col;
+ return b;
+ },
+ gte: () => b,
+ order: (col: string) => {
+ order = col;
+ return b;
+ },
+ limit: (n: number) => {
+ limit = n;
+ return b;
+ },
+ then: (resolve: (r: unknown) => void) => resolve(result()),
+ };
+ return b;
+}
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({ from: () => trackingRuns() }),
+}));
+vi.mock('@/lib/actions/topic', () => ({ getTopicById: vi.fn() }));
+
+const { getTrackingWindow } = await import('./tracking');
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-15T13:00:00.000Z'));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('getTrackingWindow run times', () => {
+ it('takes the last run from any completed run and the next from the scheduled ones', async () => {
+ runs = [
+ {
+ source: 'cron',
+ started_at: '2026-10-14T02:00:00.000Z',
+ completed_at: '2026-10-14T02:50:00.000Z',
+ },
+ {
+ source: 'cron',
+ started_at: '2026-10-15T02:00:00.000Z',
+ completed_at: '2026-10-15T02:50:00.000Z',
+ },
+ // A Run All at lunchtime: the latest run, but not the schedule.
+ {
+ source: 'manual',
+ started_at: '2026-10-15T11:30:00.000Z',
+ completed_at: '2026-10-15T12:10:00.000Z',
+ },
+ ];
+
+ expect(await getTrackingWindow('b1')).toMatchObject({
+ lastRunAt: '2026-10-15T12:10:00.000Z',
+ nextRunAt: '2026-10-16T02:00:00.000Z',
+ });
+ });
+
+ it('knows no next run without scheduled runs, and no last run without completed ones', async () => {
+ runs = [{ source: 'manual', started_at: '2026-10-15T12:55:00.000Z', completed_at: null }];
+
+ expect(await getTrackingWindow('b1')).toMatchObject({ lastRunAt: null, nextRunAt: null });
+ });
+});
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 9a4873f00..2a7aa484a 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -42,6 +42,7 @@ import { getTopicById } from '@/lib/actions/topic';
import { getOrgPlan } from '@/lib/guards/plan-guard';
import { getOrgLocationUsage } from '@/lib/prompt-locations';
import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';
+import { nextScheduledRun } from '@/lib/tracking-schedule';
import { getContentUsage } from '@/lib/actions/content';
import type { ContentUsage } from '@/lib/content-usage';
import { percentageChange } from '@/lib/metrics';
@@ -774,6 +775,10 @@ export interface TrackingWindow {
anchored: { dateFrom: string; dateTo: string } | null;
/** A full run currently in flight (cron or manual), for the progress banner. */
activeRun: { startedAt: string; source: string } | null;
+ /** The brand's last completed full run, scheduled or Run All (VIS-012); null before its first. */
+ lastRunAt: string | null;
+ /** When the next scheduled run is due, from the last ones (VIS-012); null when not known. */
+ nextRunAt: string | null;
}
/**
@@ -792,7 +797,7 @@ export interface TrackingWindow {
export async function getTrackingWindow(brandId: string): Promise<TrackingWindow> {
const supabase = await dbClient();
- const [completedResp, activeResp] = await Promise.all([
+ const [completedResp, activeResp, scheduledResp] = await Promise.all([
supabase
.from('tracking_runs')
.select('completed_at')
@@ -810,6 +815,14 @@ export async function getTrackingWindow(brandId: string): Promise<TrackingWindow
.gte('started_at', new Date(Date.now() - 2 * 3600_000).toISOString())
.order('started_at', { ascending: false })
.limit(1),
+ // The daily runs, for when the next one is due (the header's "next run in 13h").
+ supabase
+ .from('tracking_runs')
+ .select('started_at')
+ .eq('brand_id', brandId)
+ .eq('source', 'cron')
+ .order('started_at', { ascending: false })
+ .limit(2),
]);
const completed = completedResp.data ?? [];
@@ -829,6 +842,8 @@ export async function getTrackingWindow(brandId: string): Promise<TrackingWindow
activeRun: active
? { startedAt: active.started_at as string, source: (active.source as string) ?? 'manual' }
: null,
+ lastRunAt: latest ?? null,
+ nextRunAt: nextScheduledRun((scheduledResp.data ?? []).map((r) => r.started_at as string)),
};
}
diff --git a/web/src/lib/tracking-schedule.test.ts b/web/src/lib/tracking-schedule.test.ts
new file mode 100644
index 000000000..ee9cb4dd6
--- /dev/null
+++ b/web/src/lib/tracking-schedule.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+import { nextScheduledRun, timeUntil } from './tracking-schedule';
+
+const at = (iso: string) => Date.parse(iso);
+
+describe('nextScheduledRun', () => {
+ it('is a day after the last scheduled run', () => {
+ expect(
+ nextScheduledRun(
+ ['2026-10-15T02:04:00.000Z', '2026-10-14T02:01:00.000Z'],
+ at('2026-10-15T13:00:00.000Z'),
+ ),
+ ).toBe('2026-10-16T02:04:00.000Z');
+ });
+
+ it('assumes once a day with a single run on record', () => {
+ expect(nextScheduledRun(['2026-10-15T02:04:00.000Z'], at('2026-10-15T13:00:00.000Z'))).toBe(
+ '2026-10-16T02:04:00.000Z',
+ );
+ });
+
+ it('follows a self-hosted schedule that runs more often', () => {
+ expect(
+ nextScheduledRun(
+ ['2026-10-15T12:00:00.000Z', '2026-10-15T00:00:00.000Z'],
+ at('2026-10-15T13:00:00.000Z'),
+ ),
+ ).toBe('2026-10-16T00:00:00.000Z');
+ });
+
+ it('reads a missed day as the daily schedule, not a two-day one', () => {
+ expect(
+ nextScheduledRun(
+ ['2026-10-15T02:00:00.000Z', '2026-10-13T02:00:00.000Z'],
+ at('2026-10-15T13:00:00.000Z'),
+ ),
+ ).toBe('2026-10-16T02:00:00.000Z');
+ });
+
+ it('keeps a daily run that started a little early or late daily', () => {
+ expect(
+ nextScheduledRun(
+ ['2026-10-15T01:20:00.000Z', '2026-10-14T03:00:00.000Z'],
+ at('2026-10-15T13:00:00.000Z'),
+ ),
+ ).toBe('2026-10-16T01:20:00.000Z');
+ });
+
+ it('is null once due, or without a scheduled run', () => {
+ expect(
+ nextScheduledRun(['2026-10-13T02:00:00.000Z'], at('2026-10-15T13:00:00.000Z')),
+ ).toBeNull();
+ expect(nextScheduledRun([], at('2026-10-15T13:00:00.000Z'))).toBeNull();
+ expect(nextScheduledRun(['not a date'], at('2026-10-15T13:00:00.000Z'))).toBeNull();
+ });
+});
+
+describe('timeUntil', () => {
+ const now = at('2026-10-15T13:00:00.000Z');
+
+ it('counts minutes, then hours, then days, each to the nearest', () => {
+ expect(timeUntil('2026-10-15T13:40:20.000Z', now)).toEqual({ unit: 'minutes', value: 40 });
+ // 12h59m: a day after a run 11h ago reads "13h", not "12h".
+ expect(timeUntil('2026-10-16T01:59:00.000Z', now)).toEqual({ unit: 'hours', value: 13 });
+ expect(timeUntil('2026-10-17T15:00:00.000Z', now)).toEqual({ unit: 'days', value: 2 });
+ });
+
+ it('moves up a unit at the edges rather than writing 60m or 24h', () => {
+ expect(timeUntil('2026-10-15T13:59:40.000Z', now)).toEqual({ unit: 'hours', value: 1 });
+ expect(timeUntil('2026-10-16T12:45:00.000Z', now)).toEqual({ unit: 'days', value: 1 });
+ });
+
+ it('never says less than a minute', () => {
+ expect(timeUntil('2026-10-15T13:00:10.000Z', now)).toEqual({ unit: 'minutes', value: 1 });
+ });
+});
diff --git a/web/src/lib/tracking-schedule.ts b/web/src/lib/tracking-schedule.ts
new file mode 100644
index 000000000..045fbd672
--- /dev/null
+++ b/web/src/lib/tracking-schedule.ts
@@ -0,0 +1,48 @@
+/**
+ * When a brand's tracking runs (VIS-012): the Insights header's "Last run
+ * 11h ago · next run in 13h". Read from the tracking-run ledger (00044), so
+ * the cloud and self-hosted installs work the same without knowing the cron.
+ */
+
+const MINUTE = 60_000;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+
+/** A gap up to this long between scheduled runs is a schedule of its own; longer is daily. */
+const SUB_DAILY_MAX = 20 * HOUR;
+
+/**
+ * When the next scheduled run is due: the last scheduled (cron) run's start
+ * plus the schedule's period. Tracking runs once a day; a shorter gap between
+ * the last two runs means a self-hosted install runs more often, and a longer
+ * one is a missed day, not a slower schedule. Null without a scheduled run,
+ * or once it's due (running now, or not coming on its own: a plan without
+ * daily monitoring, a brand with no active prompts).
+ *
+ * @param cronStarts `started_at` of the latest scheduled runs, newest first
+ */
+export function nextScheduledRun(cronStarts: string[], now = Date.now()): string | null {
+ const [last, prev] = cronStarts.map((s) => Date.parse(s)).filter(Number.isFinite);
+ if (last === undefined) return null;
+ const gap = prev === undefined ? DAY : Math.round((last - prev) / HOUR) * HOUR;
+ const period = gap >= HOUR && gap <= SUB_DAILY_MAX ? gap : DAY;
+ const next = last + period;
+ return next > now ? new Date(next).toISOString() : null;
+}
+
+/**
+ * The time until `iso`, as the header writes it: minutes under an hour,
+ * hours under a day, days after that, each to the nearest, so 12h59m reads
+ * "13h" and 59m30s reads "1h". Never less than a minute.
+ */
+export function timeUntil(
+ iso: string,
+ now = Date.now(),
+): { unit: 'minutes' | 'hours' | 'days'; value: number } {
+ const diff = Math.max(0, Date.parse(iso) - now);
+ const minutes = Math.round(diff / MINUTE);
+ if (minutes < 60) return { unit: 'minutes', value: Math.max(1, minutes) };
+ const hours = Math.round(diff / HOUR);
+ if (hours < 24) return { unit: 'hours', value: hours };
+ return { unit: 'days', value: Math.round(diff / DAY) };
+}