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
fix(prompts): show positions and prompt detail dates in the viewer's time zone (#1030)
Cihan33962b55db4f
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/_workflow-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/_workflow-cards.tsxindex 67155cb17..3102e57b0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/_workflow-cards.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/_workflow-cards.tsx@@ -43,7 +43,7 @@ import {function formatShortDate(iso: string): string {const date = new Date(iso);if (Number.isNaN(date.getTime())) return '—';- return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });+ return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });}/**@@ -86,15 +86,18 @@ function CitedBadge({ target }: { target: PromptTargetUrl }) {);}+/** A note's time on the viewer's clock, written as the answer times above it. */function formatNoteDate(iso: string): string {const date = new Date(iso);if (Number.isNaN(date.getTime())) return '—';- return date.toLocaleString(undefined, {+ return date.toLocaleString('en-US', {year: 'numeric',month: 'short',day: 'numeric',- hour: 'numeric',+ hour: '2-digit',minute: '2-digit',+ hourCycle: 'h23',+ timeZoneName: 'short',});}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsxindex f9ff6b8b9..e0c74e564 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/[id]/page.tsx@@ -68,6 +68,7 @@ import {import { TablePager, usePagination } from '@/components/table-pager';import { MODEL_PROVIDER_LABELS, PLATFORM_LABELS } from '@/config/platform-labels';import { groupByPlatform, type PlatformGroup } from './grouping';+import { dayRangeBounds, viewerTimeZone } from '@/lib/time-zone';// ─── Date range (kept in sync with the insights page filter bar) ─────────────@@ -78,10 +79,9 @@ const DATE_PRESETS: DatePreset[] = ['24h', '7d', '30d', '90d', 'all', 'custom'];function getDateRange(preset: DatePreset, custom: { from: string; to: string }) {if (preset === 'all') return { dateFrom: undefined, dateTo: undefined };if (preset === 'custom') {- return {- dateFrom: custom.from || undefined,- dateTo: custom.to ? `${custom.to}T23:59:59.999Z` : undefined,- };+ // Whole days on the viewer's clock, as the answer times below read.+ const { from, to } = dayRangeBounds(custom.from, custom.to, viewerTimeZone());+ return { dateFrom: from, dateTo: to };}if (preset === '24h') {const from = new Date();@@ -163,14 +163,20 @@ function getModelDisplayName(model?: string, platform?: string): string {return model ?? platform ?? 'Unknown';}+/**+ * An answer's time on the viewer's clock, with the zone so it can't be read+ * as UTC, written as the Positions panel writes it ("Oct 12, 16:28 GMT+3").+ */function formatTimestamp(iso: string): string {const date = new Date(iso);if (Number.isNaN(date.getTime())) return '—';- return date.toLocaleString(undefined, {+ return date.toLocaleString('en-US', {month: 'short',day: 'numeric',- hour: 'numeric',+ hour: '2-digit',minute: '2-digit',+ hourCycle: 'h23',+ timeZoneName: 'short',});}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex 98b4f555c..6834f2f1c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -138,10 +138,12 @@ import { formatCompactNumber } from '@/lib/format';import { usePagination, TablePager } from '@/components/table-pager';import { PromptPositionsSheet } from '@/components/prompts/prompt-positions-sheet';import {+ panelRangeFromTable,parsePositionsRange,positionsUrlParams,type PositionsRange,} from '@/lib/positions-range';+import { viewerTimeZone } from '@/lib/time-zone';// ─── Info Tooltip ─────────────────────────────────────────────────────────────@@ -2724,11 +2726,7 @@ function AllPromptsTab({const openPositionsPanel = useCallback((promptId: string, tab: 'platforms' | 'improve' = 'platforms') => {setPositionsTab(tab);- setPositionsRange({- preset: positionsPreset,- from: positionsPreset === 'custom' ? positionsWindow.from.slice(0, 10) : '',- to: positionsPreset === 'custom' ? (positionsWindow.to?.slice(0, 10) ?? '') : '',- });+ setPositionsRange(panelRangeFromTable(positionsPreset, positionsWindow, viewerTimeZone()));setPositionsId(promptId);},[positionsPreset, positionsWindow],diff --git a/web/src/components/prompts/prompt-positions-sheet.tsx b/web/src/components/prompts/prompt-positions-sheet.tsxindex 38f0be27b..1d0a9f295 100644--- a/web/src/components/prompts/prompt-positions-sheet.tsx+++ b/web/src/components/prompts/prompt-positions-sheet.tsx@@ -45,6 +45,7 @@ import type { PositionsRange } from '@/lib/positions-range';import { DateRangeFilter } from '@/components/filters/date-range-filter';import { ImproveTab, useImprove, type ImproveController } from './prompt-improve-tab';import { getPromptPositions, type PromptPositionsData } from '@/lib/actions/prompt-positions';+import { viewerTimeZone } from '@/lib/time-zone';import type {AnswerView,PlatformDay,@@ -79,28 +80,36 @@ interface Props {const DAYS_PAGE = 10;const HISTORY_PAGE = 7;-const DATE_FMT = new Intl.DateTimeFormat('en-US', {+// Days arrive as YYYY-MM-DD already in the viewer's time zone, so they are+// printed as plain calendar dates (read at UTC midnight, never shifted).+const DAY_FMT = new Intl.DateTimeFormat('en-US', {timeZone: 'UTC',month: 'short',day: 'numeric',year: 'numeric',});-const SHORT_DATE_FMT = new Intl.DateTimeFormat('en-US', {+const SHORT_DAY_FMT = new Intl.DateTimeFormat('en-US', {timeZone: 'UTC',month: 'short',day: 'numeric',});+// Answer times are instants, shown on the viewer's clock with its zone.+const DATE_FMT = new Intl.DateTimeFormat('en-US', {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+});const TIME_FMT = new Intl.DateTimeFormat('en-US', {- timeZone: 'UTC',hour: '2-digit',minute: '2-digit',hourCycle: 'h23',+ timeZoneName: 'short',});-const formatDay = (day: string) => DATE_FMT.format(new Date(`${day}T00:00:00Z`));-const formatTime = (iso: string) => `${TIME_FMT.format(new Date(iso))} UTC`;+const formatDay = (day: string) => DAY_FMT.format(new Date(`${day}T00:00:00Z`));+const formatTime = (iso: string) => TIME_FMT.format(new Date(iso));const formatDateTime = (iso: string) =>- `${DATE_FMT.format(new Date(iso))}, ${TIME_FMT.format(new Date(iso))} UTC`;+ `${DATE_FMT.format(new Date(iso))}, ${TIME_FMT.format(new Date(iso))}`;const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;const pct = (n: number, of: number) => (of > 0 ? `${Math.round((n / of) * 100)}%` : '—');@@ -135,7 +144,12 @@ export function PromptPositionsSheet({useEffect(() => {if (!prompt) return;let cancelled = false;- getPromptPositions(prompt.id, { from: window.from, to: window.to, region: region || undefined })+ getPromptPositions(prompt.id, {+ from: window.from,+ to: window.to,+ region: region || undefined,+ timeZone: viewerTimeZone(),+ }).then((data) => {if (cancelled) return;setLoaded({ key, data, error: data ? null : 'This prompt is no longer available.' });@@ -209,8 +223,8 @@ export function PromptPositionsSheet({)}{data && !latestMode && data.summary.days.length > 0 && (<span>- {SHORT_DATE_FMT.format(new Date(`${data.summary.days[0]}T00:00:00Z`))} –{' '}- {formatDay(data.summary.days[data.summary.days.length - 1])} (UTC)+ {SHORT_DAY_FMT.format(new Date(`${data.summary.days[0]}T00:00:00Z`))} –{' '}+ {formatDay(data.summary.days[data.summary.days.length - 1])}</span>)}{region && <span>· {formatRegionDisplay(region)}</span>}@@ -390,11 +404,12 @@ function CitationStatus({ answer }: { answer: AnswerView }) {/** One answer: its mention and its citation side by side. */function AnswerLine({ answer, showTime }: { answer: AnswerView; showTime: boolean }) {return (- <div className="grid grid-cols-1 gap-1 text-xs sm:grid-cols-[5.5rem_1fr_1fr] sm:gap-3">+ <div className="grid grid-cols-1 gap-1 text-xs sm:grid-cols-[6rem_1fr_1fr] sm:gap-3">{showTime ? (<span className="tabular-nums text-muted-foreground">- {formatTime(answer.at)}- {answer.region ? ` · ${formatRegionDisplay(answer.region)}` : ''}+ {/* The time keeps its zone on one line ("16:28 GMT+5:30"). */}+ <span className="block whitespace-nowrap">{formatTime(answer.at)}</span>+ {answer.region && <span className="block">{formatRegionDisplay(answer.region)}</span>}</span>) : (<span className="hidden sm:block" />@@ -634,8 +649,8 @@ function PeriodView({)}</div><p className="text-xs text-muted-foreground">- Each block is one UTC day in the selected range. Hover a block for that day's- positions; open a platform for every run.+ Each block is one day in the selected range, in your time zone. Hover a block for that+ day's positions; open a platform for every run.</p></TabsContent><TabsContent value="history" className="mt-3">diff --git a/web/src/config/prompt-options.test.ts b/web/src/config/prompt-options.test.tsnew file mode 100644index 000000000..79a8c29ca--- /dev/null+++ b/web/src/config/prompt-options.test.ts@@ -0,0 +1,45 @@+/**+ * prompt-options.test.ts+ *+ * A custom date range covers whole days on the viewer's clock.+ */++import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { resolvePromptRange } from './prompt-options';++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-10-14T12:00:00.000Z'));+});++afterEach(() => {+ vi.useRealTimers();+});++describe('resolvePromptRange (custom)', () => {+ test('runs from the start of the first day to the end of the last, in the given zone', () => {+ expect(+ resolvePromptRange('custom', { from: '2026-10-01', to: '2026-10-03' }, 'Europe/Istanbul'),+ ).toEqual({+ from: '2026-09-30T21:00:00.000Z',+ to: '2026-10-03T20:59:59.999Z',+ days: 3,+ });+ expect(resolvePromptRange('custom', { from: '2026-10-01', to: '2026-10-03' }, 'UTC')).toEqual({+ from: '2026-10-01T00:00:00.000Z',+ to: '2026-10-03T23:59:59.999Z',+ days: 3,+ });+ });++ test('never reaches past now', () => {+ expect(+ resolvePromptRange('custom', { from: '2026-10-13', to: '2026-10-20' }, 'Europe/Istanbul').to,+ ).toBe('2026-10-14T12:00:00.000Z');+ });++ test('falls back to the furthest window when the start is missing or not a date', () => {+ const range = resolvePromptRange('custom', { from: 'nonsense', to: '2026-10-03' }, 'UTC');+ expect(range.days).toBe(90);+ });+});diff --git a/web/src/config/prompt-options.ts b/web/src/config/prompt-options.tsindex b3cd5d2c2..b455336c2 100644--- a/web/src/config/prompt-options.ts+++ b/web/src/config/prompt-options.ts@@ -1,3 +1,5 @@+import { dayRangeBounds, viewerTimeZone } from '@/lib/time-zone';+export const REGIONS = [{ code: 'US', label: 'United States' },{ code: 'GB', label: 'United Kingdom' },@@ -181,19 +183,23 @@ export interface PromptRange {/*** Resolve a preset (plus the custom inputs) into the bounds both data paths- * take. A custom range is clamped to PROMPT_RANGE_MAX_DAYS and never extends- * into the future, so the two tabs cannot disagree about what they read.+ * take. A custom range runs from the start of its first day to the end of its+ * last in the viewer's time zone, is clamped to PROMPT_RANGE_MAX_DAYS and+ * never extends into the future, so the two tabs cannot disagree about what+ * they read.*/export function resolvePromptRange(preset: PromptRangePreset,custom?: { from?: string; to?: string },+ timeZone: string = viewerTimeZone(),): PromptRange {const now = Date.now();const dayMs = 86_400_000;if (preset === 'custom') {- const parsedTo = custom?.to ? Date.parse(`${custom.to}T23:59:59.999Z`) : NaN;- const parsedFrom = custom?.from ? Date.parse(custom.from) : NaN;+ const bounds = dayRangeBounds(custom?.from, custom?.to, timeZone);+ const parsedTo = bounds.to ? Date.parse(bounds.to) : NaN;+ const parsedFrom = bounds.from ? Date.parse(bounds.from) : NaN;const to = Number.isFinite(parsedTo) ? Math.min(parsedTo, now) : now;const earliest = to - PROMPT_RANGE_MAX_DAYS * dayMs;const from = Number.isFinite(parsedFrom)diff --git a/web/src/lib/actions/prompt-positions.ts b/web/src/lib/actions/prompt-positions.tsindex cd299fb64..7399b9f22 100644--- a/web/src/lib/actions/prompt-positions.ts+++ b/web/src/lib/actions/prompt-positions.ts@@ -12,6 +12,7 @@ import {type PositionAnswer,type PositionsSummary,} from '@/lib/prompt-positions';+import { isTimeZone } from '@/lib/time-zone';import type { Sentiment } from '@/types';export interface PromptPositionsData {@@ -38,11 +39,12 @@ const SENTIMENTS: readonly string[] = ['positive', 'neutral', 'negative'];* caller's organisations comes back as null. Engines the org's plan doesn't* include are never queried: their rows carry only the upgrade state.* Answer text and source lists stay on the server; the panel gets the- * folded numbers.+ * folded numbers. Answers are filed under the viewer's days (`timeZone`, an+ * IANA zone from the browser; UTC when missing or unknown).*/export async function getPromptPositions(promptId: string,- opts: { from: string; to?: string; region?: string },+ opts: { from: string; to?: string; region?: string; timeZone?: string },): Promise<PromptPositionsData | null> {if (!Number.isFinite(Date.parse(opts.from))) throw new Error('Invalid date range');if (opts.to && !Number.isFinite(Date.parse(opts.to))) throw new Error('Invalid date range');@@ -138,7 +140,12 @@ export async function getPromptPositions(});const window = { from: opts.from, to };- const { summary, platforms: rowsByPlatform } = summarizePositions(answers, platforms, window);+ const { summary, platforms: rowsByPlatform } = summarizePositions(+ answers,+ platforms,+ window,+ isTimeZone(opts.timeZone) ? opts.timeZone : 'UTC',+ );return {prompt: {diff --git a/web/src/lib/positions-range.test.ts b/web/src/lib/positions-range.test.tsindex 6046f602f..038e5483b 100644--- a/web/src/lib/positions-range.test.ts+++ b/web/src/lib/positions-range.test.ts@@ -5,7 +5,7 @@*/import { describe, expect, test } from 'vitest';-import { parsePositionsRange, positionsUrlParams } from './positions-range';+import { panelRangeFromTable, parsePositionsRange, positionsUrlParams } from './positions-range';describe('positionsUrlParams', () => {test('a closed panel clears every param', () => {@@ -55,3 +55,23 @@ describe('parsePositionsRange', () => {expect(parsePositionsRange(new URLSearchParams('positionsRange=1y'), '7d').preset).toBe('7d');});});++describe('panelRangeFromTable', () => {+ // The table's custom Oct 1 – Oct 3, as resolved on an Istanbul and a New York clock.+ const istanbul = { from: '2026-09-30T21:00:00.000Z', to: '2026-10-03T20:59:59.999Z' };+ const newYork = { from: '2026-10-01T04:00:00.000Z', to: '2026-10-04T03:59:59.999Z' };++ test("opens the panel on the table's own days, whatever the viewer's zone", () => {+ const want = { preset: 'custom', from: '2026-10-01', to: '2026-10-03' };+ expect(panelRangeFromTable('custom', istanbul, 'Europe/Istanbul')).toEqual(want);+ expect(panelRangeFromTable('custom', newYork, 'America/New_York')).toEqual(want);+ });++ test('a preset carries no dates', () => {+ expect(panelRangeFromTable('7d', istanbul, 'Europe/Istanbul')).toEqual({+ preset: '7d',+ from: '',+ to: '',+ });+ });+});diff --git a/web/src/lib/positions-range.ts b/web/src/lib/positions-range.tsindex 8a5b29a28..ca9374f43 100644--- a/web/src/lib/positions-range.ts+++ b/web/src/lib/positions-range.ts@@ -5,6 +5,7 @@*/import { isPromptRangePreset, type PromptRangePreset } from '@/config/prompt-options';+import { dayIn } from '@/lib/time-zone';/** The panel's own window choice; `from` / `to` are YYYY-MM-DD and only used by custom. */export interface PositionsRange {@@ -39,3 +40,22 @@ export function parsePositionsRange(to: params.get('positionsTo') ?? '',};}++/**+ * The range the panel opens on from the table: the table's preset and, for a+ * custom range, the days its window covers. The window holds instants, which+ * read as those days only on the viewer's clock, so they are taken in+ * `timeZone` rather than cut from the ISO string (which is UTC).+ */+export function panelRangeFromTable(+ preset: PromptRangePreset,+ window: { from: string; to?: string },+ timeZone: string,+): PositionsRange {+ if (preset !== 'custom') return { preset, from: '', to: '' };+ return {+ preset,+ from: dayIn(window.from, timeZone),+ to: window.to ? dayIn(window.to, timeZone) : '',+ };+}diff --git a/web/src/lib/prompt-positions.test.ts b/web/src/lib/prompt-positions.test.tsindex 0630af303..cfb3e71ef 100644--- a/web/src/lib/prompt-positions.test.ts+++ b/web/src/lib/prompt-positions.test.ts@@ -131,6 +131,23 @@ describe('windowDays', () => {'2026-10-03',]);});++ it("counts the viewer's days: a whole-day range in Istanbul stays three days", () => {+ expect(+ windowDays(+ '2026-09-30T21:00:00.000Z',+ '2026-10-03T20:59:59.999Z',+ new Set(),+ 'Europe/Istanbul',+ ),+ ).toEqual(['2026-10-01', '2026-10-02', '2026-10-03']);+ });++ it('returns no days, rather than failing, for a window that ends before it starts', () => {+ expect(windowDays('2026-10-05T00:00:00.000Z', '2026-10-03T00:00:00.000Z', new Set())).toEqual(+ [],+ );+ });});describe('countRuns', () => {@@ -174,6 +191,16 @@ const PLATFORMS = [const WEEK = { from: '2026-10-04T00:00:00.000Z', to: '2026-10-10T23:59:59.999Z' };describe('summarizePositions', () => {+ it("files an answer under the viewer's day, not the UTC one", () => {+ const late = answer({ createdAt: '2026-10-08T22:30:00Z', mentioned: true, mentionPosition: 1 });+ const utc = summarizePositions([late], PLATFORMS, WEEK);+ const istanbul = summarizePositions([late], PLATFORMS, WEEK, 'Europe/Istanbul');+ expect(utc.platforms[0].days[0].day).toBe('2026-10-08');+ // 22:30 UTC is 01:30 the next morning in Istanbul (UTC+3).+ expect(istanbul.platforms[0].days[0].day).toBe('2026-10-09');+ expect(istanbul.summary.mentionedDays).toBe(1);+ });+it('counts a day once however many answers it has, and keeps every answer', () => {const { platforms } = summarizePositions([diff --git a/web/src/lib/prompt-positions.ts b/web/src/lib/prompt-positions.tsindex 7a98502c7..ebd806dcf 100644--- a/web/src/lib/prompt-positions.ts+++ b/web/src/lib/prompt-positions.ts@@ -9,6 +9,7 @@*/import { PLANS, PLAN_ORDER, type Plan } from '@/config/plans';import { extractHostname, normalizeDomain } from '@/lib/citations/classify';+import { dayIn, nextDay, startOfDayIn } from '@/lib/time-zone';import type { Sentiment } from '@/types';/** The engines the panel lists, in the order it lists them. */@@ -135,7 +136,7 @@ export interface AnswerView {}export interface PlatformDay {- /** UTC date, YYYY-MM-DD. */+ /** Date in the viewer's time zone, YYYY-MM-DD. */day: string;/** Newest first. */answers: AnswerView[];@@ -164,7 +165,7 @@ export interface PlatformPositions {}export interface PositionsSummary {- /** Every UTC date the window covers, oldest first. */+ /** Every date the window covers in the viewer's time zone, oldest first. */days: string[];/** Tracking runs that produced an answer for this prompt, across engines. */runs: number;@@ -177,8 +178,6 @@ export interface PositionsSummary {citationPosition: PositionStats | null;}-const DAY_MS = 86_400_000;-/*** Answers from one run of a prompt land within a couple of hours of each* other, and runs are a day apart. A gap longer than this between two@@ -186,23 +185,24 @@ const DAY_MS = 86_400_000;*/export const RUN_GAP_MS = 6 * 60 * 60 * 1000;-export function utcDay(iso: string): string {- return new Date(iso).toISOString().slice(0, 10);-}-/**- * The UTC dates a window covers, oldest first. A rolling window starts part- * way through its first date; that date is left out unless an answer landed- * in the part the window covers, so "last 7 days" reads as 7 days rather- * than 8 with an empty one in front.+ * The dates a window covers in `timeZone`, oldest first. A rolling window+ * starts part way through its first date; that date is left out unless an+ * answer landed in the part the window covers, so "last 7 days" reads as 7+ * days rather than 8 with an empty one in front.*/-export function windowDays(from: string, to: string, answeredDays: Set<string>): string[] {- const start = Date.parse(`${utcDay(from)}T00:00:00Z`);- const end = Date.parse(`${utcDay(to)}T00:00:00Z`);+export function windowDays(+ from: string,+ to: string,+ answeredDays: Set<string>,+ timeZone = 'UTC',+): string[] {+ const last = dayIn(to, timeZone);const days: string[] = [];- for (let t = start; t <= end; t += DAY_MS) days.push(new Date(t).toISOString().slice(0, 10));+ for (let day = dayIn(from, timeZone); day <= last; day = nextDay(day)) days.push(day);+ if (days.length === 0) return days;- const partialStart = Date.parse(from) > start;+ const partialStart = Date.parse(from) > Date.parse(startOfDayIn(days[0], timeZone));if (partialStart && days.length > 1 && !answeredDays.has(days[0])) days.shift();return days;}@@ -248,12 +248,13 @@ function toView(a: PositionAnswer): AnswerView {function summarizePlatform(platform: { id: PositionPlatformId; label: string; access: PlatformAccess },answers: PositionAnswer[],+ timeZone: string,): PlatformPositions {const views = answers.map(toView).sort((a, b) => Date.parse(b.at) - Date.parse(a.at));const byDay = new Map<string, AnswerView[]>();for (const v of views) {- const day = utcDay(v.at);+ const day = dayIn(v.at, timeZone);byDay.set(day, [...(byDay.get(day) ?? []), v]);}const days = [...byDay.entries()]@@ -290,25 +291,31 @@ function summarizePlatform(* Fold a window's answers into the panel's summary and per-engine rows.* `answers` must already be limited to the engines the plan includes; a* locked engine gets its row with empty numbers, which the panel replaces- * with the upgrade prompt.+ * with the upgrade prompt. Days are the viewer's (`timeZone`), so they match+ * the answer times the viewer reads.*/export function summarizePositions(answers: PositionAnswer[],platforms: { id: PositionPlatformId; label: string; access: PlatformAccess }[],window: { from: string; to: string },+ timeZone = 'UTC',): { summary: PositionsSummary; platforms: PlatformPositions[] } {const rows = platforms.map((p) =>summarizePlatform(p,p.access.state === 'included' ? answers.filter((a) => a.platform === p.id) : [],+ timeZone,),);- const counted = rows.flatMap((r) => r.days.flatMap((d) => d.answers));+ // Each answer's day, as its platform row already worked it out.+ const dayOf = new Map<AnswerView, string>();+ for (const r of rows) for (const d of r.days) for (const a of d.answers) dayOf.set(a, d.day);+ const counted = [...dayOf.keys()];- const tracked = new Set(counted.map((a) => utcDay(a.at)));- const mentioned = new Set(counted.filter((a) => a.mentioned).map((a) => utcDay(a.at)));- const cited = new Set(counted.filter((a) => a.cited).map((a) => utcDay(a.at)));- const days = windowDays(window.from, window.to, tracked);+ const tracked = new Set(dayOf.values());+ const mentioned = new Set(counted.filter((a) => a.mentioned).map((a) => dayOf.get(a)!));+ const cited = new Set(counted.filter((a) => a.cited).map((a) => dayOf.get(a)!));+ const days = windowDays(window.from, window.to, tracked, timeZone);const lastAnswerAt = counted.reduce<string | null>((latest, a) => (latest === null || Date.parse(a.at) > Date.parse(latest) ? a.at : latest),null,diff --git a/web/src/lib/time-zone.test.ts b/web/src/lib/time-zone.test.tsnew file mode 100644index 000000000..a2239dde4--- /dev/null+++ b/web/src/lib/time-zone.test.ts@@ -0,0 +1,92 @@+/**+ * time-zone.test.ts+ *+ * Calendar days in the viewer's time zone, checked in fixed zones so the+ * results don't depend on the machine running the tests.+ */++import { describe, expect, test } from 'vitest';+import {+ dayIn,+ dayRangeBounds,+ endOfDayIn,+ isCalendarDay,+ isTimeZone,+ nextDay,+ startOfDayIn,+} from './time-zone';++describe('dayIn', () => {+ test("puts a late-evening UTC answer on the next day in Istanbul's time", () => {+ expect(dayIn('2026-10-12T21:30:00.000Z', 'UTC')).toBe('2026-10-12');+ expect(dayIn('2026-10-12T21:30:00.000Z', 'Europe/Istanbul')).toBe('2026-10-13');+ });++ test('puts an early UTC answer on the previous day in New York', () => {+ expect(dayIn('2026-10-13T02:00:00.000Z', 'America/New_York')).toBe('2026-10-12');+ });+});++describe('startOfDayIn / endOfDayIn', () => {+ test('a day in Istanbul runs from 21:00 UTC the evening before', () => {+ expect(startOfDayIn('2026-10-12', 'Europe/Istanbul')).toBe('2026-10-11T21:00:00.000Z');+ expect(endOfDayIn('2026-10-12', 'Europe/Istanbul')).toBe('2026-10-12T20:59:59.999Z');+ });++ test('UTC days are unchanged', () => {+ expect(startOfDayIn('2026-10-12', 'UTC')).toBe('2026-10-12T00:00:00.000Z');+ expect(endOfDayIn('2026-10-12', 'UTC')).toBe('2026-10-12T23:59:59.999Z');+ });++ test('follows daylight saving: a 23-hour and a 25-hour day in New York', () => {+ // Clocks go forward on 2026-03-08 and back on 2026-11-01.+ expect(startOfDayIn('2026-03-08', 'America/New_York')).toBe('2026-03-08T05:00:00.000Z');+ expect(endOfDayIn('2026-03-08', 'America/New_York')).toBe('2026-03-09T03:59:59.999Z');+ expect(startOfDayIn('2026-11-01', 'America/New_York')).toBe('2026-11-01T04:00:00.000Z');+ expect(endOfDayIn('2026-11-01', 'America/New_York')).toBe('2026-11-02T04:59:59.999Z');+ });+ test('starts the day at the jump where the clocks skip midnight itself', () => {+ // Santiago goes from 23:59 on Sep 5 straight to 01:00 on Sep 6.+ expect(startOfDayIn('2026-09-06', 'America/Santiago')).toBe('2026-09-06T04:00:00.000Z');+ expect(endOfDayIn('2026-09-05', 'America/Santiago')).toBe('2026-09-06T03:59:59.999Z');+ // Beirut skips midnight on Mar 29.+ expect(startOfDayIn('2026-03-29', 'Asia/Beirut')).toBe('2026-03-28T22:00:00.000Z');+ });+});++describe('dayRangeBounds', () => {+ test('turns custom inputs into whole days, leaving an empty or invalid side open', () => {+ expect(dayRangeBounds('2026-10-01', '2026-10-03', 'Europe/Istanbul')).toEqual({+ from: '2026-09-30T21:00:00.000Z',+ to: '2026-10-03T20:59:59.999Z',+ });+ expect(dayRangeBounds('', 'nonsense', 'UTC')).toEqual({ from: undefined, to: undefined });+ });+});++describe('nextDay', () => {+ test('crosses month and year ends', () => {+ expect(nextDay('2026-10-31')).toBe('2026-11-01');+ expect(nextDay('2026-12-31')).toBe('2027-01-01');+ });+});++describe('isTimeZone', () => {+ test('accepts IANA zones and refuses anything else', () => {+ expect(isTimeZone('Europe/Istanbul')).toBe(true);+ expect(isTimeZone('UTC')).toBe(true);+ expect(isTimeZone('Mars/Olympus')).toBe(false);+ expect(isTimeZone('')).toBe(false);+ expect(isTimeZone(42)).toBe(false);+ });+});++describe('isCalendarDay', () => {+ test('takes real YYYY-MM-DD dates only', () => {+ expect(isCalendarDay('2026-10-12')).toBe(true);+ expect(isCalendarDay('2026-02-30')).toBe(false);+ expect(isCalendarDay('2026-10-12T00:00:00Z')).toBe(false);+ expect(isCalendarDay('')).toBe(false);+ expect(isCalendarDay(undefined)).toBe(false);+ });+});diff --git a/web/src/lib/time-zone.ts b/web/src/lib/time-zone.tsnew file mode 100644index 000000000..0d14eb790--- /dev/null+++ b/web/src/lib/time-zone.ts@@ -0,0 +1,126 @@+/**+ * Calendar days in the viewer's time zone, for the prompts pages: the+ * Positions panel's days and the custom date ranges follow the viewer's+ * clock, as the answer times on the prompt detail page already do. Every+ * function takes the IANA zone, so the rules are tested in fixed zones; the+ * browser passes its own (`viewerTimeZone`).+ */++/** The viewer's IANA time zone, or UTC when it can't be read. */+export function viewerTimeZone(): string {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';+ } catch {+ return 'UTC';+ }+}++/** Whether `timeZone` is an IANA zone this runtime knows. */+export function isTimeZone(timeZone: unknown): timeZone is string {+ if (typeof timeZone !== 'string' || timeZone.length === 0 || timeZone.length > 64) return false;+ try {+ new Intl.DateTimeFormat('en-US', { timeZone });+ return true;+ } catch {+ return false;+ }+}++const formats = new Map<string, Intl.DateTimeFormat>();++/** The wall clock an instant shows in `timeZone`, field by field. */+function wallClock(ms: number, timeZone: string) {+ let fmt = formats.get(timeZone);+ if (!fmt) {+ fmt = new Intl.DateTimeFormat('en-US', {+ timeZone,+ hourCycle: 'h23',+ year: 'numeric',+ month: 'numeric',+ day: 'numeric',+ hour: 'numeric',+ minute: 'numeric',+ second: 'numeric',+ });+ formats.set(timeZone, fmt);+ }+ const fields: Partial<Record<Intl.DateTimeFormatPartTypes, number>> = {};+ for (const part of fmt.formatToParts(new Date(ms))) {+ if (part.type !== 'literal') fields[part.type] = Number(part.value);+ }+ return {+ year: fields.year ?? NaN,+ month: fields.month ?? NaN,+ day: fields.day ?? NaN,+ hour: fields.hour ?? NaN,+ minute: fields.minute ?? NaN,+ second: fields.second ?? NaN,+ };+}++const pad = (n: number, width = 2) => String(n).padStart(width, '0');++/** The calendar date, YYYY-MM-DD, an instant falls on in `timeZone`. */+export function dayIn(instant: string | number, timeZone: string): string {+ const { year, month, day } = wallClock(new Date(instant).getTime(), timeZone);+ return `${pad(year, 4)}-${pad(month)}-${pad(day)}`;+}++/** How far `timeZone`'s clock is ahead of UTC at an instant, in ms. */+function offsetAt(ms: number, timeZone: string): number {+ const w = wallClock(ms, timeZone);+ const wall = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second);+ return wall - (ms - (((ms % 1000) + 1000) % 1000));+}++const HALF_DAY_MS = 43_200_000;++/**+ * When a calendar date starts in `timeZone`, as an ISO instant. Midnight is+ * tried with the offsets in force half a day either side, which covers a+ * daylight-saving change that night; the earliest that reads as `day` wins.+ * Where the clocks jump over midnight itself, that is the jump.+ */+export function startOfDayIn(day: string, timeZone: string): string {+ const midnight = Date.parse(`${day}T00:00:00.000Z`);+ const candidates = [midnight - HALF_DAY_MS, midnight, midnight + HALF_DAY_MS].map(+ (at) => midnight - offsetAt(at, timeZone),+ );+ const onDay = candidates.filter((t) => dayIn(t, timeZone) === day);+ return new Date(Math.min(...(onDay.length ? onDay : candidates))).toISOString();+}++/** The last millisecond of a calendar date in `timeZone`, as an ISO instant. */+export function endOfDayIn(day: string, timeZone: string): string {+ return new Date(Date.parse(startOfDayIn(nextDay(day), timeZone)) - 1).toISOString();+}++/**+ * A custom range's YYYY-MM-DD inputs as instants: from the start of the first+ * day to the end of the last, on `timeZone`'s clock. An empty or invalid+ * input leaves its side open (undefined).+ */+export function dayRangeBounds(+ from: string | undefined,+ to: string | undefined,+ timeZone: string,+): { from?: string; to?: string } {+ return {+ from: isCalendarDay(from) ? startOfDayIn(from, timeZone) : undefined,+ to: isCalendarDay(to) ? endOfDayIn(to, timeZone) : undefined,+ };+}++/** Whether `value` is a real calendar date written YYYY-MM-DD. */+export function isCalendarDay(value: unknown): value is string {+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;+ const t = Date.parse(`${value}T00:00:00Z`);+ // Rolled-over dates (Feb 30 → Mar 2) don't read back the same.+ return Number.isFinite(t) && new Date(t).toISOString().slice(0, 10) === value;+}++/** The calendar date after `day`. Pure date arithmetic, no zone involved. */+export function nextDay(day: string): string {+ const t = Date.parse(`${day}T00:00:00Z`) + 86_400_000;+ return new Date(t).toISOString().slice(0, 10);+}