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(#767): consolidate relative-time formatting into a single shared helper (#772)

Maqbool Ahmed6ef219cbd74e
diff --git a/web/messages/en.json b/web/messages/en.json
index 2b48897c1..c0eacbbc3 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -13,7 +13,13 @@
"search": "Search",
"filter": "Filter",
"export": "Export",
- "noData": "No data available"
+ "noData": "No data available",
+ "relative": {
+ "justNow": "just now",
+ "minutesAgo": "{m}m ago",
+ "hoursAgo": "{h}h ago",
+ "daysAgo": "{d}d ago"
+ }
},
"nav": {
"overview": "Overview",
@@ -233,13 +239,7 @@
"lastRun": "Last run"
},
"appearedIn": "Appeared in {visible} of {active, plural, one {# prompt} other {# prompts}}",
- "openDetails": "Open topic details",
- "relative": {
- "justNow": "just now",
- "minutesAgo": "{m}m ago",
- "hoursAgo": "{h}h ago",
- "daysAgo": "{d}d ago"
- }
+ "openDetails": "Open topic details"
},
"content": {
"title": "Content Opportunities",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index e7af41f1e..a6dbb8052 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -819,6 +819,7 @@ function RecommendationsSection({ data }: { data: InsightsRecommendations }) {
import { saveTrackingJob, loadTrackingJob, clearTrackingJob } from '@/lib/tracking-job-store';
import { toCsv } from '@/lib/csv';
+import { formatRelative } from '@/lib/format-relative';
function TrackingProgressBanner({
jobStatus,
@@ -951,6 +952,7 @@ function NoCompetitorsTeaser() {
export default function InsightsPage() {
const t = useTranslations('insights');
+ const tCommon = useTranslations('common');
const router = useRouter();
const { isCloud } = usePlanContext();
const brand = useBrandStore((s) => s.getActiveBrand());
@@ -1395,7 +1397,7 @@ export default function InsightsPage() {
}
const lastCheckedLabel = summary?.lastCheckedAt
- ? formatTimeAgo(new Date(summary.lastCheckedAt))
+ ? formatRelative(summary.lastCheckedAt, tCommon)
: 'Never';
const handleResetFilters = () => {
@@ -1756,16 +1758,3 @@ export default function InsightsPage() {
</div>
);
}
-
-// ─── Helpers ──────────────────────────────────────────────────────────────────
-
-function formatTimeAgo(date: Date): string {
- const diff = Date.now() - date.getTime();
- const minutes = Math.floor(diff / 60_000);
- if (minutes < 1) return 'just now';
- if (minutes < 60) return `${minutes}m ago`;
- const hours = Math.floor(minutes / 60);
- if (hours < 24) return `${hours}h ago`;
- const days = Math.floor(hours / 24);
- return `${days}d ago`;
-}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 56608d09e..c0fad1d31 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -2,6 +2,7 @@
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 dynamic from 'next/dynamic';
@@ -105,6 +106,7 @@ import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';
import type { PromptVolume, Prompt, Topic } from '@/types';
import { toast } from 'sonner';
import { toCsv } from '@/lib/csv';
+import { formatRelative } from '@/lib/format-relative';
import { compareNullsLast, type SortDir } from './prompt-sort';
import { formatCompactNumber } from '@/lib/format';
import { usePagination, TablePager } from '@/components/table-pager';
@@ -271,19 +273,6 @@ type TabId = (typeof VALID_TABS)[number];
const PROMPT_VIEWS = ['tracked', 'suggestions'] as const;
type PromptsView = (typeof PROMPT_VIEWS)[number];
-function formatRelative(iso?: string): string {
- if (!iso) return '—';
- const diffMs = Date.now() - new Date(iso).getTime();
- const diffMin = Math.round(diffMs / 60000);
- if (diffMin < 1) return 'Just now';
- if (diffMin < 60) return `${diffMin}m ago`;
- const diffHr = Math.round(diffMin / 60);
- if (diffHr < 24) return `${diffHr}h ago`;
- const diffDay = Math.round(diffHr / 24);
- if (diffDay < 30) return `${diffDay}d ago`;
- return new Date(iso).toLocaleDateString();
-}
-
function visibilityColorClass(score: number): string {
if (score >= 70) return 'text-emerald-600 dark:text-emerald-400';
if (score >= 40) return 'text-amber-600 dark:text-amber-400';
@@ -1984,6 +1973,7 @@ function AllPromptsTab({
/** Opens the Edit Prompt dialog for a row; undefined hides the pencil (member role). */
onEditPrompt?: (prompt: Prompt) => void;
}) {
+ const tCommon = useTranslations('common');
const [search, setSearch] = useState('');
const [workFilter, setWorkFilter] = useState<'all' | 'none' | PromptWorkStatus>('all');
// Optimistic per-row status overrides — the prompts prop belongs to the
@@ -2363,7 +2353,7 @@ function AllPromptsTab({
)}
</TableCell>
<TableCell className="text-right text-xs text-muted-foreground">
- {formatRelative(vis?.lastRunAt)}
+ {formatRelative(vis?.lastRunAt, tCommon)}
</TableCell>
{onEditPrompt && (
<TableCell className="text-right pr-6">
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
index 1136d3b50..7a011e891 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx
@@ -50,23 +50,11 @@ import {
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toCsv } from '@/lib/csv';
+import { formatRelative } from '@/lib/format-relative';
import { compareNullsLast, type SortDir } from '../prompts/prompt-sort';
// ─── Helpers ─────────────────────────────────────────────────────────────
-function formatRelative(iso: string | null, t: ReturnType<typeof useTranslations>): string {
- if (!iso) return '—';
- const diff = Date.now() - new Date(iso).getTime();
- const m = Math.floor(diff / 60000);
- if (m < 1) return t('relative.justNow');
- if (m < 60) return t('relative.minutesAgo', { m });
- const h = Math.floor(m / 60);
- if (h < 24) return t('relative.hoursAgo', { h });
- const d = Math.floor(h / 24);
- if (d < 30) return t('relative.daysAgo', { d });
- return new Date(iso).toLocaleDateString();
-}
-
function visibilityBarColor(score: number) {
if (score >= 75) return 'bg-emerald-500';
if (score >= 50) return 'bg-amber-500';
@@ -723,7 +711,7 @@ export default function TopicsPage() {
)}
</TableCell>
<TableCell className="text-right text-xs text-muted-foreground">
- {formatRelative(topic.lastRunAt, t)}
+ {formatRelative(topic.lastRunAt, common)}
</TableCell>
<TableCell className="pr-6 text-right">
<Link
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index 7ecd714a5..296898974 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
@@ -17,6 +17,7 @@ const PlatformBreakdownChart = dynamic(
loading: () => <Skeleton className="h-64 w-full" />,
},
);
+import { useTranslations } from 'next-intl';
import { useBrandStore } from '@/stores/use-brand-store';
import type { Brand } from '@/types';
import {
@@ -62,6 +63,7 @@ import {
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { toCsv } from '@/lib/csv';
+import { formatRelative } from '@/lib/format-relative';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
@@ -200,17 +202,6 @@ function SnippetBanner({ trackingCode }: { trackingCode?: string }) {
);
}
-function timeAgo(dateStr: string): string {
- const diff = Date.now() - new Date(dateStr).getTime();
- const mins = Math.floor(diff / 60000);
- if (mins < 1) return 'just now';
- if (mins < 60) return `${mins}m ago`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h ago`;
- const days = Math.floor(hrs / 24);
- return `${days}d ago`;
-}
-
// ─── Filter Bar ───────────────────────────────────────────────────────────────
interface TrafficFilters {
@@ -459,6 +450,7 @@ export default function TrafficPage() {
}
function TrafficPageContent({ brand }: { brand: Brand }) {
+ const tCommon = useTranslations('common');
const [datePreset, setDatePreset] = useState<DatePreset>('7d');
const [customFrom, setCustomFrom] = useState('');
const [customTo, setCustomTo] = useState('');
@@ -881,7 +873,7 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
{logs.map((row) => (
<TableRow key={row.id} className="hover:bg-muted/50">
<TableCell className="pl-6 text-xs text-muted-foreground whitespace-nowrap">
- {timeAgo(row.createdAt)}
+ {formatRelative(row.createdAt, tCommon)}
</TableCell>
<TableCell>
<span className="text-sm">
diff --git a/web/src/lib/format-relative.test.ts b/web/src/lib/format-relative.test.ts
new file mode 100644
index 000000000..41d448293
--- /dev/null
+++ b/web/src/lib/format-relative.test.ts
@@ -0,0 +1,146 @@
+/**
+ * format-relative.test.ts (issue #767)
+ *
+ * Pattern follows web/src/lib/csv.test.ts.
+ *
+ * The translator is stubbed with a minimal implementation that mirrors
+ * what next-intl produces for the common.relative.* keys so the tests
+ * never touch the i18n runtime.
+ */
+
+import { expect, test } from 'vitest';
+import { formatRelative } from './format-relative.js';
+
+// ---------------------------------------------------------------------------
+// Stub translator
+// ---------------------------------------------------------------------------
+
+type Params = Record<string, unknown>;
+
+function makeT() {
+ return (key: string, params?: Params): string => {
+ switch (key) {
+ case 'relative.justNow':
+ return 'just now';
+ case 'relative.minutesAgo':
+ return `${params?.m}m ago`;
+ case 'relative.hoursAgo':
+ return `${params?.h}h ago`;
+ case 'relative.daysAgo':
+ return `${params?.d}d ago`;
+ default:
+ return key;
+ }
+ };
+}
+
+const t = makeT() as ReturnType<typeof import('next-intl').useTranslations<'common'>>;
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function isoMinutesAgo(minutes: number): string {
+ return new Date(Date.now() - minutes * 60_000).toISOString();
+}
+
+function isoHoursAgo(hours: number): string {
+ return isoMinutesAgo(hours * 60);
+}
+
+function isoDaysAgo(days: number): string {
+ return isoHoursAgo(days * 24);
+}
+
+// ---------------------------------------------------------------------------
+// Null / undefined guard
+// ---------------------------------------------------------------------------
+
+test('null returns em-dash', () => {
+ expect(formatRelative(null, t)).toBe('—');
+});
+
+test('undefined returns em-dash', () => {
+ expect(formatRelative(undefined, t)).toBe('—');
+});
+
+// ---------------------------------------------------------------------------
+// Sub-minute boundary
+// ---------------------------------------------------------------------------
+
+test('0 seconds ago → just now', () => {
+ expect(formatRelative(new Date().toISOString(), t)).toBe('just now');
+});
+
+test('59 seconds ago → just now', () => {
+ const iso = new Date(Date.now() - 59_000).toISOString();
+ expect(formatRelative(iso, t)).toBe('just now');
+});
+
+// ---------------------------------------------------------------------------
+// Math.floor vs Math.round at 90 seconds (the rounding bug)
+// ---------------------------------------------------------------------------
+
+test('90 seconds ago → 1m ago (floor, not 2m from round)', () => {
+ const iso = new Date(Date.now() - 90_000).toISOString();
+ expect(formatRelative(iso, t)).toBe('1m ago');
+});
+
+// ---------------------------------------------------------------------------
+// Minute / hour boundary
+// ---------------------------------------------------------------------------
+
+test('1 minute ago → 1m ago', () => {
+ expect(formatRelative(isoMinutesAgo(1), t)).toBe('1m ago');
+});
+
+test('59 minutes ago → 59m ago', () => {
+ expect(formatRelative(isoMinutesAgo(59), t)).toBe('59m ago');
+});
+
+test('45 minutes ago → 45m ago (not 1h ago from round)', () => {
+ // Prompts used Math.round: 45 min → Math.round(45/60)=1 → "1h ago".
+ // Floor keeps it at "45m ago".
+ expect(formatRelative(isoMinutesAgo(45), t)).toBe('45m ago');
+});
+
+test('60 minutes ago → 1h ago', () => {
+ expect(formatRelative(isoMinutesAgo(60), t)).toBe('1h ago');
+});
+
+// ---------------------------------------------------------------------------
+// Hour / day boundary
+// ---------------------------------------------------------------------------
+
+test('23 hours ago → 23h ago', () => {
+ expect(formatRelative(isoHoursAgo(23), t)).toBe('23h ago');
+});
+
+test('24 hours ago → 1d ago', () => {
+ expect(formatRelative(isoHoursAgo(24), t)).toBe('1d ago');
+});
+
+// ---------------------------------------------------------------------------
+// 30-day cliff (Insights/Traffic bug: counted indefinitely as Xd ago)
+// ---------------------------------------------------------------------------
+
+test('29 days ago → 29d ago', () => {
+ expect(formatRelative(isoDaysAgo(29), t)).toBe('29d ago');
+});
+
+test('30 days ago → locale date string, not "30d ago"', () => {
+ const iso = isoDaysAgo(30);
+ const result = formatRelative(iso, t);
+ // Must NOT look like "Xd ago"
+ expect(result).not.toMatch(/^\d+d ago$/);
+ // Must be a non-empty date string (locale-formatted)
+ expect(result.length).toBeGreaterThan(0);
+ expect(result).toBe(new Date(iso).toLocaleDateString());
+});
+
+test('412 days ago → locale date string, not "412d ago"', () => {
+ const iso = isoDaysAgo(412);
+ const result = formatRelative(iso, t);
+ expect(result).not.toMatch(/^\d+d ago$/);
+ expect(result).toBe(new Date(iso).toLocaleDateString());
+});
diff --git a/web/src/lib/format-relative.ts b/web/src/lib/format-relative.ts
new file mode 100644
index 000000000..8372afa5c
--- /dev/null
+++ b/web/src/lib/format-relative.ts
@@ -0,0 +1,39 @@
+/**
+ * format-relative.ts
+ *
+ * Single canonical implementation of the relative-time helper (issue #767).
+ *
+ * Rules (Topics copy is the source of truth):
+ * - null / undefined → '—'
+ * - < 1 min → t('common.relative.justNow')
+ * - < 60 min → t('common.relative.minutesAgo', { m }) (Math.floor)
+ * - < 24 h → t('common.relative.hoursAgo', { h }) (Math.floor)
+ * - < 30 d → t('common.relative.daysAgo', { d }) (Math.floor)
+ * - ≥ 30 d → toLocaleDateString()
+ *
+ * Signature: accepts an ISO string (or null/undefined) plus the next-intl
+ * translator scoped to 'common'. Call sites that previously received a Date
+ * (insights/page.tsx) should call .toISOString() before passing in.
+ */
+
+import type { useTranslations } from 'next-intl';
+
+type Translator = ReturnType<typeof useTranslations<'common'>>;
+
+export function formatRelative(iso: string | null | undefined, t: Translator): string {
+ if (!iso) return '—';
+
+ const diff = Date.now() - new Date(iso).getTime();
+ const m = Math.floor(diff / 60_000);
+
+ if (m < 1) return t('relative.justNow');
+ if (m < 60) return t('relative.minutesAgo', { m });
+
+ const h = Math.floor(m / 60);
+ if (h < 24) return t('relative.hoursAgo', { h });
+
+ const d = Math.floor(h / 24);
+ if (d < 30) return t('relative.daysAgo', { d });
+
+ return new Date(iso).toLocaleDateString();
+}