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.

fix(tracking): say how the first run is going: answers saved, time left, no stale copy (#1774)

Cihan02251579cf30
diff --git a/server/src/lib/run-settlement.js b/server/src/lib/run-settlement.js
index 7482798d0..3642c565b 100644
--- a/server/src/lib/run-settlement.js
+++ b/server/src/lib/run-settlement.js
@@ -153,9 +153,11 @@ async function awaitLateResults(run, { pollMs, waitMs, rollups }) {
* days; and a run that has to wait for late answers refreshes once now, then
* as they land.
*
- * @returns {Promise<{ stamped: boolean, lateStamp: Promise<boolean> | null }>}
+ * @returns {Promise<{ stamped: boolean, lateStamp: Promise<boolean> | null, resultCount: number | null }>}
* `stamped` when the row stamped now; otherwise `lateStamp` resolves true
- * if and when it stamps later, false if it never does.
+ * if and when it stamps later, false if it never does. `resultCount` is
+ * the run's answers stored so far, however they came (a webhook's
+ * included); null when they couldn't be counted.
*/
export async function settleTrackingRun(
{ brandId, runId, startedAt, plannedTasks },
@@ -167,14 +169,14 @@ export async function settleTrackingRun(
// Leave the row uncompleted: the dashboard keeps the previous completed
// run and the next run clears the dangling row.
logger.error({ brandId, runId }, 'failed to count run results');
- return { stamped: false, lateStamp: null };
+ return { stamped: false, lateStamp: null, resultCount: null };
}
const pending = await countRunPending(brandId, startedAt);
const decision = settleDecision({ resultCount, plannedTasks, final: pending === 0 });
if (decision !== 'wait') {
await rollups?.idle();
- return { stamped: await act(decision, run, resultCount), lateStamp: null };
+ return { stamped: await act(decision, run, resultCount), lateStamp: null, resultCount };
}
logger.info(
@@ -188,5 +190,5 @@ export async function settleTrackingRun(
logger.error({ err, brandId, runId }, 'waiting for late results failed');
return false;
});
- return { stamped: false, lateStamp };
+ return { stamped: false, lateStamp, resultCount };
}
diff --git a/server/src/lib/run-settlement.test.js b/server/src/lib/run-settlement.test.js
index 9ae825d2e..56c4b8514 100644
--- a/server/src/lib/run-settlement.test.js
+++ b/server/src/lib/run-settlement.test.js
@@ -87,7 +87,7 @@ describe('settleTrackingRun', () => {
db.results = 98;
db.pending = 2;
const out = await settleTrackingRun(run, fast);
- expect(out).toEqual({ stamped: true, lateStamp: null });
+ expect(out).toEqual({ stamped: true, lateStamp: null, resultCount: 98 });
expect(db.stamped.result_count).toBe(98);
});
@@ -96,6 +96,8 @@ describe('settleTrackingRun', () => {
db.pending = 46;
const out = await settleTrackingRun(run, { pollMs: 5, waitMs: 1000 });
expect(out.stamped).toBe(false);
+ // What is in so far, for the person waiting on it.
+ expect(out.resultCount).toBe(54);
expect(db.stamped).toBeNull();
db.results = 97;
@@ -178,7 +180,7 @@ describe('settleTrackingRun with a first run refresher', () => {
expect(db.stamped).toBeNull();
rollups.release();
- expect(await settling).toEqual({ stamped: true, lateStamp: null });
+ expect(await settling).toEqual({ stamped: true, lateStamp: null, resultCount: 98 });
expect(db.stamped.result_count).toBe(98);
// A run that stamps at once needs no refresh of its own: the stamp's covers it.
expect(rollups.flush).not.toHaveBeenCalled();
diff --git a/server/src/workers/tracking-worker.js b/server/src/workers/tracking-worker.js
index 7233dd69a..14b85c7f4 100644
--- a/server/src/workers/tracking-worker.js
+++ b/server/src/workers/tracking-worker.js
@@ -960,11 +960,15 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,
// for it, and late answers keep the rollups moving.
firstRun ? { pollMs: FIRST_RUN_LATE_POLL_MS, rollups: firstRunRollups } : undefined,
)
- : { stamped: false, lateStamp: null };
+ : { stamped: false, lateStamp: null, resultCount: null };
return {
- resultCount: insertedCount,
+ // A webhook's answers are stored by /cloro/callback, never through
+ // insertResult: the settlement's count, read from the table, has them.
+ resultCount: settlement.resultCount ?? insertedCount,
stamped: settlement.stamped,
+ // Still arriving: the run waits for its late answers before it stamps.
+ stillArriving: Boolean(settlement.lateStamp),
lateStamp: settlement.lateStamp,
};
}
diff --git a/web/messages/en.json b/web/messages/en.json
index b03217a98..4a7bae9d1 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -375,7 +375,9 @@
"firstRun": {
"running": "First analysis running",
"queued": "First analysis queued",
- "progress": "{current} of {total} answers",
+ "progress": "{current} of {total} checks",
+ "minutesLeft": "about {minutes} min left",
+ "hoursLeft": "{hours, plural, one {about # hour left} other {about # hours left}}",
"runningBody": "AI assistants are answering your prompts for the first time. Actions, signals and KPIs fill in once it finishes: a few minutes, or an hour or two at busy times. You can leave this page.",
"queuedBody": "Another analysis is running right now. Yours starts the moment a slot opens, and keeps going in the background.",
"link": "Follow it on Brand Visibility"
@@ -3633,6 +3635,25 @@
"viewAll": "View all"
},
"insights": {
+ "tracking": {
+ "queued": "Queued — starting automatically",
+ "analyzing": "Analyzing prompts...",
+ "stop": "Stop",
+ "queuedBody": "Another analysis is running right now. Yours will begin the moment a slot opens up — no need to wait here, it'll keep going in the background.",
+ "activeBody": "This can take anywhere from a few minutes to 1–2 hours at busy times. You can leave this page — it keeps running in the background.",
+ "activeBodyMinutes": "About {minutes} min left at the current pace. You can leave this page — it keeps running in the background.",
+ "activeBodyHours": "{hours, plural, one {About # hour left} other {About # hours left}} at the current pace. You can leave this page — it keeps running in the background.",
+ "dailyRun": "Daily tracking in progress",
+ "run": "Tracking in progress",
+ "runBody": "— showing the latest completed results; the numbers will refresh when this run finishes.",
+ "firstRun": "First tracking in progress",
+ "firstRunBody": "— your results appear here as soon as it finishes. You can leave this page.",
+ "done": "Analysis complete.",
+ "doneCount": "{count, plural, one {Analysis complete — # answer saved.} other {Analysis complete — # answers saved.}}",
+ "doneSoFar": "{count, plural, one {Almost done — # answer saved so far, the rest still arriving.} other {Almost done — # answers saved so far, the rest still arriving.}}",
+ "failed": "Job failed: {reason}",
+ "unknownError": "Unknown error"
+ },
"title": "Answer Engine Insights",
"description": "Monitor how your brand is represented in AI-generated answers.",
"runPrompts": "Run Prompts",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index b6d8c1bca..b4d9aded9 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -489,18 +489,28 @@ function NoDataForPeriod({ datePreset, onReset }: { datePreset: DatePreset; onRe
// ─── Tracking Progress ────────────────────────────────────────────────────────
-import { saveTrackingJob, loadTrackingJob, clearTrackingJob } from '@/lib/tracking-job-store';
+import {
+ saveTrackingJob,
+ loadTrackingJob,
+ clearTrackingJob,
+ doneMessage,
+} from '@/lib/tracking-job-store';
+import { etaParts, minutesLeft, withSample, type ProgressSample } from '@/lib/tracking-eta';
import { toCsv } from '@/lib/csv';
import { RunLine } from './_run-line';
import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';
function TrackingProgressBanner({
jobStatus,
+ pace,
onStop,
}: {
jobStatus: TrackingJobStatus | null;
+ /** The run's progress readings while this page polls it, for the time left. */
+ pace: ProgressSample[];
onStop: () => void;
}) {
+ const t = useTranslations('insights.tracking');
if (!jobStatus) return null;
const isActive = jobStatus.status === 'active' || jobStatus.status === 'waiting';
@@ -508,6 +518,8 @@ function TrackingProgressBanner({
const progress = jobStatus.progress;
const pct = progress ? Math.round((progress.current / progress.total) * 100) : 0;
+ const eta = progress ? minutesLeft(pace, progress.total) : null;
+ const left = eta === null ? null : etaParts(eta);
return (
<div className="rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 space-y-2">
@@ -515,9 +527,7 @@ function TrackingProgressBanner({
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
<span className="text-sm font-medium">
- {jobStatus.status === 'waiting'
- ? 'Queued — starting automatically'
- : 'Analyzing prompts...'}
+ {jobStatus.status === 'waiting' ? t('queued') : t('analyzing')}
</span>
</div>
<Button
@@ -527,21 +537,22 @@ function TrackingProgressBanner({
onClick={onStop}
>
<StopCircle className="h-3.5 w-3.5" />
- Stop
+ {t('stop')}
</Button>
</div>
{jobStatus.status === 'waiting' && (
- <p className="text-xs text-muted-foreground">
- Another analysis is running right now. Yours will begin the moment a slot opens up — no
- need to wait here, it&apos;ll keep going in the background.
- </p>
+ <p className="text-xs text-muted-foreground">{t('queuedBody')}</p>
)}
{jobStatus.status === 'active' && (
<p className="text-xs text-muted-foreground">
- This can take anywhere from a few minutes to 1–2 hours at busy times. You can leave this
- page — it keeps running in the background.
+ {/* The pace so far, once there is enough of it; the general range before. */}
+ {left === null
+ ? t('activeBody')
+ : 'hours' in left
+ ? t('activeBodyHours', left)
+ : t('activeBodyMinutes', left)}
</p>
)}
@@ -573,21 +584,30 @@ function TrackingProgressBanner({
/**
* Banner for runs this browser did NOT start (the daily cron, or a teammate's
- * Run All) — detected from the tracking_runs ledger, not localStorage. The
- * dashboard keeps showing the last completed run's numbers until the active
- * run finishes, then swaps in one step.
+ * Run All), or whose saved job this browser no longer restores: detected
+ * from the tracking_runs ledger, not localStorage. The dashboard keeps
+ * showing the last completed run's numbers until the active run finishes,
+ * then swaps in one step. A brand's first run has none to show, and says so.
*/
-function ServerRunBanner({ run }: { run: TrackingWindow['activeRun'] }) {
+function ServerRunBanner({
+ run,
+ firstRun,
+}: {
+ run: TrackingWindow['activeRun'];
+ /** No completed run yet: nothing older is on the page. */
+ firstRun: boolean;
+}) {
+ const t = useTranslations('insights.tracking');
if (!run) return null;
return (
<div className="rounded-lg border border-primary/20 bg-primary/5 px-4 py-3">
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
<span className="text-sm font-medium">
- {run.source === 'cron' ? 'Daily tracking in progress' : 'Tracking in progress'}
+ {firstRun ? t('firstRun') : run.source === 'cron' ? t('dailyRun') : t('run')}
</span>
<span className="text-xs text-muted-foreground">
- — showing the latest completed results; the numbers will refresh when this run finishes.
+ {firstRun ? t('firstRunBody') : t('runBody')}
</span>
</div>
</div>
@@ -627,6 +647,11 @@ function NoCompetitorsTeaser() {
export default function InsightsPage() {
const t = useTranslations('insights');
+ // The job poll's toasts read it: the loop outlives a render.
+ const tRef = useRef(t);
+ tRef.current = t;
+ // The tracking job's pace while this page polls it ("about N min left").
+ const [pace, setPace] = useState<ProgressSample[]>([]);
const tCommon = useTranslations('common');
const router = useRouter();
const { isCloud } = usePlanContext();
@@ -919,6 +944,10 @@ export default function InsightsPage() {
const status = await getJobStatus(activeJobId);
if (cancelled) break;
setJobStatus(status);
+ const current = status.progress?.current;
+ if (current !== undefined) {
+ setPace((prev) => withSample(prev, { at: Date.now(), current }));
+ }
// Refresh data every ~10s while active so new results appear progressively
const now = Date.now();
@@ -932,7 +961,8 @@ export default function InsightsPage() {
setActiveJobId(null);
setIsRunning(false);
setJobStatus(null);
- toast.success(`Analysis complete — ${status.result?.resultCount ?? 0} results saved.`);
+ const done = doneMessage(status.result);
+ toast.success(tRef.current(`tracking.${done.key}`, 'count' in done ? done : undefined));
loadData(undefined, { silent: true });
break;
}
@@ -943,7 +973,11 @@ export default function InsightsPage() {
setIsRunning(false);
setJobStatus(null);
if (status.status === 'failed') {
- toast.error(`Job failed: ${status.failedReason ?? 'Unknown error'}`);
+ toast.error(
+ tRef.current('tracking.failed', {
+ reason: status.failedReason ?? tRef.current('tracking.unknownError'),
+ }),
+ );
}
break;
}
@@ -1112,8 +1146,8 @@ export default function InsightsPage() {
<p className="text-muted-foreground text-sm">{brand.name}</p>
</div>
</HeaderWithAiUsage>
- <TrackingProgressBanner jobStatus={jobStatus} onStop={handleStopTracking} />
- {!localJobActive && <ServerRunBanner run={cronRun} />}
+ <TrackingProgressBanner jobStatus={jobStatus} pace={pace} onStop={handleStopTracking} />
+ {!localJobActive && <ServerRunBanner run={cronRun} firstRun={!runTimes.lastRunAt} />}
<EmptyState onRunPrompts={runAll} isRunning={isRunning} isCloud={isCloud} />
{!isCloud && (
<div className="flex justify-center">
@@ -1221,8 +1255,8 @@ export default function InsightsPage() {
/>
{/* Tracking Progress */}
- <TrackingProgressBanner jobStatus={jobStatus} onStop={handleStopTracking} />
- {!localJobActive && <ServerRunBanner run={cronRun} />}
+ <TrackingProgressBanner jobStatus={jobStatus} pace={pace} onStop={handleStopTracking} />
+ {!localJobActive && <ServerRunBanner run={cronRun} firstRun={!runTimes.lastRunAt} />}
{/* Refetch overlay: on a filter/date change the previous window's data
stays mounted (no skeleton — that's first-load only), so without a
diff --git a/web/src/components/action-center/first-run-note.test.tsx b/web/src/components/action-center/first-run-note.test.tsx
index ee63bf873..ad58bebbd 100644
--- a/web/src/components/action-center/first-run-note.test.tsx
+++ b/web/src/components/action-center/first-run-note.test.tsx
@@ -106,7 +106,33 @@ describe('FirstRunNote', () => {
loadTrackingJob.mockReturnValue({ jobId: 'j1', brandId: 'b1', startedAt: 1 });
getJobStatus.mockResolvedValue(job({ progress: { current: 12, total: 40 } }));
await render();
- expect(text()).toContain('First analysis running12 of 40 answers');
+ // Checks, not answers: a task can end without one.
+ expect(text()).toContain('First analysis running12 of 40 checks');
+ });
+
+ it('reads again every 12 seconds, and says about how long is left once the pace shows', async () => {
+ getTrackingWindow.mockResolvedValue(
+ win({ activeRun: { startedAt: '2026-10-20T09:00:00Z', source: 'manual' } }),
+ );
+ loadTrackingJob.mockReturnValue({ jobId: 'j1', brandId: 'b1', startedAt: 1 });
+ let reads = 0;
+ getJobStatus.mockImplementation(async () =>
+ job({ progress: { current: 12 + 4 * reads++, total: 400 } }),
+ );
+ await render();
+ expect(text()).toContain('12 of 400 checks');
+ expect(text()).not.toContain('left');
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(12_000);
+ });
+ expect(getTrackingWindow).toHaveBeenCalledTimes(2);
+
+ // A minute in: 20 checks done, 368 to go at that pace, about 18 min.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(48_000);
+ });
+ expect(text()).toContain('32 of 400 checks · about 20 min left');
});
it('shows nothing once the brand has a completed run, and stops reading', async () => {
@@ -146,15 +172,16 @@ describe('FirstRunNote', () => {
await render();
expect(text()).toContain('First analysis running');
+ // One read each: the note reads again every 12 seconds.
getTrackingWindow.mockRejectedValueOnce(new Error('timeout'));
await act(async () => {
- await vi.advanceTimersByTimeAsync(30_000);
+ await vi.advanceTimersByTimeAsync(12_000);
});
expect(text()).toContain('First analysis running');
getTrackingWindow.mockResolvedValueOnce(win({ lastRunAt: '2026-10-20T09:40:00Z' }));
await act(async () => {
- await vi.advanceTimersByTimeAsync(30_000);
+ await vi.advanceTimersByTimeAsync(12_000);
});
expect(text()).toBe('');
});
diff --git a/web/src/components/action-center/first-run-note.tsx b/web/src/components/action-center/first-run-note.tsx
index 07ecc2304..a3a848ed7 100644
--- a/web/src/components/action-center/first-run-note.tsx
+++ b/web/src/components/action-center/first-run-note.tsx
@@ -7,9 +7,13 @@ import { Link } from '@/i18n/navigation';
import { useBrandStore } from '@/stores/use-brand-store';
import { getJobStatus, getTrackingWindow, type TrackingJobStatus } from '@/lib/actions/tracking';
import { loadTrackingJob } from '@/lib/tracking-job-store';
+import { etaParts, minutesLeft, withSample, type ProgressSample } from '@/lib/tracking-eta';
-/** How often the note reads again while the first run goes on. */
-const POLL_MS = 30_000;
+/**
+ * How often the note reads again while the first run goes on: often, since
+ * it is someone's first look and the count is what tells them it's working.
+ */
+const POLL_MS = 12_000;
/** A saved job the worker hasn't finished: queued, delayed or running. */
const LIVE_JOB = new Set<TrackingJobStatus['status']>(['waiting', 'delayed', 'active']);
@@ -34,6 +38,8 @@ export function FirstRunNote() {
const t = useTranslations('actionCenter.firstRun');
const brandId = useBrandStore((s) => s.activeBrandId);
const [run, setRun] = useState<FirstRun | null>(null);
+ // The run's pace while this page watches it, for "about N min left".
+ const [pace, setPace] = useState<ProgressSample[]>([]);
useEffect(() => {
if (!brandId) return;
@@ -55,6 +61,8 @@ export function FirstRunNote() {
saved?.brandId === brandId ? await getJobStatus(saved.jobId).catch(() => null) : null;
if (cancelled) return;
const live = job !== null && LIVE_JOB.has(job.status);
+ const current = live ? job.progress?.current : undefined;
+ if (current !== undefined) setPace((prev) => withSample(prev, { at: Date.now(), current }));
setRun(
win.activeRun || live
? {
@@ -78,6 +86,8 @@ export function FirstRunNote() {
// Another brand's run never shows under this one.
if (!run || run.brandId !== brandId) return null;
const { progress } = run;
+ const eta = progress ? minutesLeft(pace, progress.total) : null;
+ const left = eta === null ? null : etaParts(eta);
return (
<div role="status" className="rounded-lg border border-primary/20 bg-primary/5 px-4 py-3">
@@ -87,6 +97,7 @@ export function FirstRunNote() {
{progress && progress.total > 0 && (
<span className="text-xs text-muted-foreground tabular-nums">
{t('progress', { current: progress.current, total: progress.total })}
+ {left && ` · ${'hours' in left ? t('hoursLeft', left) : t('minutesLeft', left)}`}
</span>
)}
<Link
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index c8777b166..b69bf8f1c 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -2222,7 +2222,11 @@ export interface TrackingJobStatus {
region?: string;
platform?: string;
} | null;
- result: { resultCount: number } | null;
+ /**
+ * A finished job's answers stored, webhook deliveries included; `stillArriving`
+ * when the run waits on late answers before it closes.
+ */
+ result: { resultCount: number; stamped?: boolean; stillArriving?: boolean } | null;
failedReason: string | null;
}
diff --git a/web/src/lib/tracking-eta.test.ts b/web/src/lib/tracking-eta.test.ts
new file mode 100644
index 000000000..66527f403
--- /dev/null
+++ b/web/src/lib/tracking-eta.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+import { PACE_WINDOW_MS, etaParts, minutesLeft, withSample } from './tracking-eta';
+
+/** "About N min left" for a tracking run, from the pace its checks finish at. */
+
+const MIN = 60_000;
+
+describe('withSample', () => {
+ it('keeps a reading only when the count moved, within the pace window', () => {
+ let samples = withSample([], { at: 0, current: 0 });
+ samples = withSample(samples, { at: MIN, current: 0 });
+ expect(samples).toEqual([{ at: 0, current: 0 }]);
+ samples = withSample(samples, { at: 2 * MIN, current: 10 });
+ // The first reading falls out of the window; the one at 2 min stays.
+ samples = withSample(samples, { at: PACE_WINDOW_MS + MIN, current: 20 });
+ expect(samples).toEqual([
+ { at: 2 * MIN, current: 10 },
+ { at: PACE_WINDOW_MS + MIN, current: 20 },
+ ]);
+ });
+
+ it('starts over when the count goes back (a new run)', () => {
+ expect(withSample([{ at: 0, current: 40 }], { at: MIN, current: 2 })).toEqual([
+ { at: MIN, current: 2 },
+ ]);
+ });
+});
+
+describe('minutesLeft', () => {
+ const samples = [
+ { at: 0, current: 100 },
+ { at: 2 * MIN, current: 120 },
+ ];
+
+ it('reads the pace of the last minutes: 20 checks in 2 min, 180 left, about 18 min', () => {
+ expect(minutesLeft(samples, 300, 2 * MIN)).toBe(18);
+ });
+
+ it('says nothing without enough to go on', () => {
+ expect(minutesLeft([{ at: 0, current: 100 }], 300, 0)).toBeNull();
+ // Under a minute apart, or fewer than 5 checks done.
+ expect(minutesLeft([samples[0], { at: 30_000, current: 140 }], 300, 30_000)).toBeNull();
+ expect(minutesLeft([samples[0], { at: 2 * MIN, current: 103 }], 300, 2 * MIN)).toBeNull();
+ // Done, or no total.
+ expect(minutesLeft([samples[0], { at: 2 * MIN, current: 300 }], 300, 2 * MIN)).toBeNull();
+ expect(minutesLeft(samples, 0, 2 * MIN)).toBeNull();
+ });
+
+ it('says nothing once the count has been still for the pace window', () => {
+ expect(minutesLeft(samples, 300, 2 * MIN + PACE_WINDOW_MS + 1)).toBeNull();
+ });
+
+ it('never says less than a minute', () => {
+ expect(minutesLeft([samples[0], { at: 2 * MIN, current: 299 }], 300, 2 * MIN)).toBe(1);
+ });
+});
+
+describe('etaParts', () => {
+ it('reads minutes up to 90, to the nearest 5 past 10, and hours past it', () => {
+ expect(etaParts(4)).toEqual({ minutes: 4 });
+ expect(etaParts(18)).toEqual({ minutes: 20 });
+ expect(etaParts(90)).toEqual({ minutes: 90 });
+ expect(etaParts(125)).toEqual({ hours: 2 });
+ });
+});
diff --git a/web/src/lib/tracking-eta.ts b/web/src/lib/tracking-eta.ts
new file mode 100644
index 000000000..e97849ca3
--- /dev/null
+++ b/web/src/lib/tracking-eta.ts
@@ -0,0 +1,61 @@
+/**
+ * A rough "about N min left" for a tracking run, from the pace its checks
+ * have been finishing at in this tab. Answers come in bursts with quiet
+ * gaps, so only the last few minutes count, and nothing is said until there
+ * is enough to go on: a minute or more, and a few checks done in it. Before
+ * that, the banner keeps its general "a few minutes to 1–2 hours".
+ */
+
+/** One reading of a run's progress: when, and how many of its checks were done. */
+export interface ProgressSample {
+ at: number;
+ current: number;
+}
+
+/** Readings older than this (from the newest) no longer set the pace. */
+export const PACE_WINDOW_MS = 10 * 60_000;
+/** The pace needs readings this far apart… */
+const MIN_SPAN_MS = 60_000;
+/** …and this many checks done between them. */
+const MIN_DONE = 5;
+
+/**
+ * The readings with a new one added: kept only when the count moved (or it is
+ * the first), and only the ones within PACE_WINDOW_MS of it. A count that
+ * went back (a new run) starts over.
+ */
+export function withSample(samples: ProgressSample[], sample: ProgressSample): ProgressSample[] {
+ const last = samples[samples.length - 1];
+ if (last && sample.current < last.current) return [sample];
+ if (last && sample.current === last.current) return samples;
+ return [...samples, sample].filter((s) => sample.at - s.at <= PACE_WINDOW_MS);
+}
+
+/**
+ * Whole minutes left at the pace of the readings; null without enough to go
+ * on, or when nothing has moved for PACE_WINDOW_MS (a quiet gap: the old
+ * pace would promise too much).
+ */
+export function minutesLeft(
+ samples: ProgressSample[],
+ total: number,
+ now: number = Date.now(),
+): number | null {
+ if (samples.length < 2 || total <= 0) return null;
+ const first = samples[0];
+ const last = samples[samples.length - 1];
+ if (now - last.at > PACE_WINDOW_MS) return null;
+ const span = last.at - first.at;
+ const done = last.current - first.current;
+ if (span < MIN_SPAN_MS || done < MIN_DONE || last.current >= total) return null;
+ return Math.max(1, Math.ceil((total - last.current) / (done / span) / 60_000));
+}
+
+/**
+ * How the time left reads: minutes up to 90 (to the nearest 5 past 10), whole
+ * hours past it.
+ */
+export function etaParts(minutes: number): { minutes: number } | { hours: number } {
+ if (minutes > 90) return { hours: Math.round(minutes / 60) };
+ return { minutes: minutes > 10 ? Math.round(minutes / 5) * 5 : minutes };
+}
diff --git a/web/src/lib/tracking-job-store.test.ts b/web/src/lib/tracking-job-store.test.ts
new file mode 100644
index 000000000..519454721
--- /dev/null
+++ b/web/src/lib/tracking-job-store.test.ts
@@ -0,0 +1,57 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ TRACKING_JOB_KEEP_MS,
+ doneMessage,
+ loadTrackingJob,
+ saveTrackingJob,
+} from './tracking-job-store';
+
+/** The tracking job this browser started, kept across refreshes. */
+
+// An in-memory localStorage: the test environment has none.
+const kept = new Map<string, string>();
+Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ value: {
+ getItem: (key: string) => kept.get(key) ?? null,
+ setItem: (key: string, value: string) => void kept.set(key, value),
+ removeItem: (key: string) => void kept.delete(key),
+ clear: () => kept.clear(),
+ },
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-29T12:00:00Z'));
+ localStorage.clear();
+});
+afterEach(() => vi.useRealTimers());
+
+describe('loadTrackingJob', () => {
+ it('keeps the job as long as the worker may wait on its answers, then drops it', () => {
+ const startedAt = Date.now();
+ saveTrackingJob({ jobId: 'j1', brandId: 'b1', startedAt });
+
+ // A long first run: past the old 60 minutes, the banner is still restored.
+ vi.setSystemTime(startedAt + 149 * 60_000);
+ expect(loadTrackingJob()).toEqual({ jobId: 'j1', brandId: 'b1', startedAt });
+
+ vi.setSystemTime(startedAt + TRACKING_JOB_KEEP_MS + 1);
+ expect(loadTrackingJob()).toBeNull();
+ expect(localStorage.getItem('aeo:tracking-job')).toBeNull();
+ });
+});
+
+describe('doneMessage', () => {
+ it('gives the answers saved, the ones so far while late ones arrive, or no number', () => {
+ expect(doneMessage({ resultCount: 640 })).toEqual({ key: 'doneCount', count: 640 });
+ expect(doneMessage({ resultCount: 350, stillArriving: true })).toEqual({
+ key: 'doneSoFar',
+ count: 350,
+ });
+ // Nothing counted, or an older server's answer: no "0 results saved".
+ expect(doneMessage({ resultCount: 0 })).toEqual({ key: 'done' });
+ expect(doneMessage(null)).toEqual({ key: 'done' });
+ expect(doneMessage(undefined)).toEqual({ key: 'done' });
+ });
+});
diff --git a/web/src/lib/tracking-job-store.ts b/web/src/lib/tracking-job-store.ts
index 1baba307b..ae9349a93 100644
--- a/web/src/lib/tracking-job-store.ts
+++ b/web/src/lib/tracking-job-store.ts
@@ -1,5 +1,15 @@
const TRACKING_STORAGE_KEY = 'aeo:tracking-job';
+/**
+ * How long a saved job is restored across refreshes: as long as the worker
+ * may wait on a run's answers. Up to 90 minutes for the first answer
+ * (CLORO_FIRST_RESULT_WAIT_MIN), then up to 60 for the rest
+ * (CLORO_DRAIN_TAIL_MIN); a brand's first run, with nothing to compare its
+ * pace with, can take all of it. Dropping the job sooner hid the progress
+ * banner in the middle of a long first run.
+ */
+export const TRACKING_JOB_KEEP_MS = 150 * 60 * 1000;
+
export interface TrackingJob {
jobId: string;
brandId: string;
@@ -17,9 +27,7 @@ export function loadTrackingJob(): TrackingJob | null {
const raw = localStorage.getItem(TRACKING_STORAGE_KEY);
if (!raw) return null;
const job = JSON.parse(raw) as TrackingJob;
- // Large brands legitimately take ~45 min to finish; keep restoring the
- // progress banner across refreshes until the worker's 60-min drain deadline.
- if (Date.now() - job.startedAt > 60 * 60 * 1000) {
+ if (Date.now() - job.startedAt > TRACKING_JOB_KEEP_MS) {
localStorage.removeItem(TRACKING_STORAGE_KEY);
return null;
}
@@ -29,6 +37,19 @@ export function loadTrackingJob(): TrackingJob | null {
}
}
+/**
+ * What a finished job says (insights.tracking): its answers saved, or the
+ * ones in so far while late answers still arrive; no number when it has
+ * none to give (an older server, or a run that stored nothing).
+ */
+export function doneMessage(
+ result: { resultCount?: number; stillArriving?: boolean } | null | undefined,
+): { key: 'done' } | { key: 'doneCount' | 'doneSoFar'; count: number } {
+ const count = Number(result?.resultCount) || 0;
+ if (count <= 0) return { key: 'done' };
+ return { key: result?.stillArriving ? 'doneSoFar' : 'doneCount', count };
+}
+
export function clearTrackingJob() {
try {
localStorage.removeItem(TRACKING_STORAGE_KEY);