Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(analytics): bucket timeline charts in the viewer timezone (#762)

h_bin4bc20ef9b0c2
diff --git a/client/src/pages/AnalyticsPage.tsx b/client/src/pages/AnalyticsPage.tsx
index 2768d380..1444c936 100644
--- a/client/src/pages/AnalyticsPage.tsx
+++ b/client/src/pages/AnalyticsPage.tsx
@@ -405,13 +405,13 @@ const gridStyle = 'var(--border)'
const primaryFill = 'var(--foreground)'
const tooltipStyle = { backgroundColor: 'var(--popover)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 } as const
-// The timeline endpoint returns UTC timestamps without a zone suffix
-// ("2026-08-10T14:00:00" hourly, "2026-08-10" daily). Parse them as UTC and
-// render in the viewer's local timezone; without this the x-axis showed UTC
-// wall-clock times that disagreed with every other timestamp on the page.
+// The timeline endpoint buckets on the viewer's wall clock (the query sends
+// the browser's tzOffset), so its zone-less timestamps ("2026-08-10T14:00:00"
+// hourly, "2026-08-10" daily) are already local time. Parse them as local —
+// re-interpreting them as UTC here would shift every tick a second time.
function formatTimelineTick(value: string): string {
if (!value) return ''
- const iso = value.includes('T') ? `${value}Z` : `${value}T00:00:00Z`
+ const iso = value.includes('T') ? value : `${value}T00:00:00`
const date = new Date(iso)
if (isNaN(date.getTime())) return value
return date.toLocaleString([], {
@@ -460,9 +460,13 @@ export default function AnalyticsPage() {
queryFn: () => apiFetch<ByClientRow[]>(`/api/analytics/by-client?range=${range}`),
})
+ // Browser's offset from UTC in minutes (480 = UTC+8), so the server buckets
+ // timeline hours/days on the viewer's wall clock instead of UTC.
+ const tzOffset = -new Date().getTimezoneOffset()
+
const { data: timeline = [] } = useQuery({
- queryKey: ['analytics', 'timeline', range],
- queryFn: () => apiFetch<TimelineBucket[]>(`/api/analytics/timeline?range=${range}`),
+ queryKey: ['analytics', 'timeline', range, tzOffset],
+ queryFn: () => apiFetch<TimelineBucket[]>(`/api/analytics/timeline?range=${range}&tzOffset=${tzOffset}`),
})
const { data: byModel = [] } = useQuery({
diff --git a/server/src/__tests__/routes/analytics.test.ts b/server/src/__tests__/routes/analytics.test.ts
index b668b412..c924c44b 100644
--- a/server/src/__tests__/routes/analytics.test.ts
+++ b/server/src/__tests__/routes/analytics.test.ts
@@ -419,6 +419,40 @@ describe('Analytics API', () => {
});
});
+ describe('timeline tzOffset', () => {
+ it('buckets timeline days by the viewer timezone instead of UTC', async () => {
+ insertRequest('2026-05-28 15:30:00'); // UTC day 05-28; UTC+8 23:30, still day 05-28
+ insertRequest('2026-05-28 17:30:00'); // UTC day 05-28; UTC+8 01:30 on day 05-29
+
+ const utc = await request(app, '/api/analytics/timeline?range=7d');
+ expect(utc.status).toBe(200);
+ expect(utc.body.map((b: any) => b.timestamp)).toEqual(['2026-05-28']);
+
+ const local = await request(app, '/api/analytics/timeline?range=7d&tzOffset=480');
+ expect(local.status).toBe(200);
+ expect(local.body.map((b: any) => b.timestamp)).toEqual(['2026-05-28', '2026-05-29']);
+ expect(local.body.map((b: any) => b.requests)).toEqual([1, 1]);
+ });
+
+ it('shifts hour labels to the viewer timezone', async () => {
+ insertRequest('2026-05-28 17:30:00'); // UTC 17:00 → UTC+8 next-day 01:00
+
+ const { status, body } = await request(app, '/api/analytics/timeline?range=24h&tzOffset=480');
+ expect(status).toBe(200);
+ expect(body.map((b: any) => b.timestamp)).toEqual(['2026-05-29T01:00:00']);
+ });
+
+ it('falls back to UTC bucketing for an invalid tzOffset', async () => {
+ insertRequest('2026-05-28 17:30:00');
+
+ for (const bad of ['abc', '9999', '1.5', '480; DROP TABLE request_hourly']) {
+ const { status, body } = await request(app, `/api/analytics/timeline?range=7d&tzOffset=${encodeURIComponent(bad)}`);
+ expect(status).toBe(200);
+ expect(body.map((b: any) => b.timestamp)).toEqual(['2026-05-28']);
+ }
+ });
+ });
+
describe('90d range', () => {
it('accepts range=90d across the analytics endpoints', async () => {
insertRequest('2026-02-01 12:00:00'); // ~117 days ago — outside 90d
diff --git a/server/src/routes/analytics.ts b/server/src/routes/analytics.ts
index 85b36c7e..249a1c87 100644
--- a/server/src/routes/analytics.ts
+++ b/server/src/routes/analytics.ts
@@ -380,12 +380,22 @@ analyticsRouter.get('/timeline', (req: Request, res: Response) => {
// dateFormat is a hardcoded whitelist — never user-controlled.
const dateFormat = interval === 'hour' ? '%Y-%m-%dT%H:00:00' : '%Y-%m-%d';
+ // tzOffset: viewer's local offset from UTC in minutes (480 = UTC+8), sent by
+ // the browser so hour/day bucket boundaries follow the viewer's wall clock
+ // instead of UTC. Whitelisted to a sane integer range; bound as a parameter,
+ // never interpolated into SQL.
+ const rawOffset = Number(req.query.tzOffset);
+ const tzOffset = Number.isInteger(rawOffset) && rawOffset >= -720 && rawOffset <= 840 ? rawOffset : 0;
+ // The single current offset applies to the whole range (SQLite has no tz
+ // database), so buckets on the far side of a DST transition sit 1h off.
+ const tzModifier = `${tzOffset >= 0 ? '+' : '-'}${Math.abs(tzOffset)} minutes`;
+
// Read from request_hourly (hour-bucketed) for both 'hour' and 'day'
// intervals. Day buckets are rolled up via strftime on the hour column,
// which keeps the timeline accurate past the raw-row prune window.
const rows = db.prepare(`
SELECT
- strftime('${dateFormat}', hour) as timestamp,
+ strftime(?, hour, ?) as timestamp,
SUM(total_requests) as requests,
SUM(success_count) as success_count,
SUM(error_count) as failure_count,
@@ -393,9 +403,9 @@ analyticsRouter.get('/timeline', (req: Request, res: Response) => {
SUM(output_tokens) as output_tokens
FROM request_hourly
WHERE hour >= ?
- GROUP BY strftime('${dateFormat}', hour)
+ GROUP BY timestamp
ORDER BY timestamp ASC
- `).all(since) as any[];
+ `).all(dateFormat, tzModifier, since) as any[];
res.json(rows.map(r => ({
timestamp: r.timestamp,