Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(api): say how old cached analytics are and fetch fresh data on Refresh
spacesdrivefe1e34b5190e
diff --git a/backend/controllers/analyticsController.ts b/backend/controllers/analyticsController.tsindex 4a46569..f93f7ea 100644--- a/backend/controllers/analyticsController.ts+++ b/backend/controllers/analyticsController.ts@@ -1,6 +1,6 @@import { controller, pathParam, servicesFor } from './http.ts';import { queryParams } from '../middleware/validate.ts';-import { parseVideoLibraryQuery } from '../validators/analyticsValidators.ts';+import { parseFreshQuery, parseVideoLibraryQuery } from '../validators/analyticsValidators.ts';import type {YouTubeAnalyticsPayload, YouTubeComparisonResponse, YouTubeLibraryResponse, YouTubeVideosResponse,} from '../../shared/types/youtube.ts';@@ -11,8 +11,8 @@ export const getChannelAnalytics = controller.createHandlers(async c => {return c.json({ success: true, ...result } satisfies YouTubeAnalyticsPayload);});-export const getChannelVideos = controller.createHandlers(async c => {- const result = await servicesFor(c).youtubeAnalytics.channelVideos(c.get('userId'), pathParam(c, 'id'));+export const getChannelVideos = controller.createHandlers(queryParams(parseFreshQuery), async c => {+ const result = await servicesFor(c).youtubeAnalytics.channelVideos(c.get('userId'), pathParam(c, 'id'), c.req.valid('query'));return c.json({ success: true, ...result } satisfies YouTubeVideosResponse);});@@ -31,7 +31,7 @@ export const getInstagramAnalytics = controller.createHandlers(async c => {return c.json({ success: true, ...result } satisfies InstagramAnalyticsResponse);});-export const getInstagramMedia = controller.createHandlers(async c => {- const result = await servicesFor(c).instagramAnalytics.media(c.get('userId'), pathParam(c, 'id'));+export const getInstagramMedia = controller.createHandlers(queryParams(parseFreshQuery), async c => {+ const result = await servicesFor(c).instagramAnalytics.media(c.get('userId'), pathParam(c, 'id'), c.req.valid('query'));return c.json({ success: true, ...result } satisfies InstagramMediaResponse);});diff --git a/backend/controllers/redditController.ts b/backend/controllers/redditController.tsindex f7f030a..ede55e0 100644--- a/backend/controllers/redditController.ts+++ b/backend/controllers/redditController.ts@@ -1,8 +1,10 @@import { controller, pathParam, servicesFor } from './http.ts';+import { queryParams } from '../middleware/validate.ts';+import { parseFreshQuery } from '../validators/analyticsValidators.ts';import type { RedditCacheData, RedditPost } from '../../shared/types/reddit.ts';-export const getRedditAnalytics = controller.createHandlers(async c => {- const result = await servicesFor(c).redditAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));+export const getRedditAnalytics = controller.createHandlers(queryParams(parseFreshQuery), async c => {+ const result = await servicesFor(c).redditAnalytics.analytics(c.get('userId'), pathParam(c, 'id'), c.req.valid('query'));return c.json(result satisfies RedditCacheData);});diff --git a/backend/services/instagramAnalyticsService.ts b/backend/services/instagramAnalyticsService.tsindex 3a5302a..877aa8b 100644--- a/backend/services/instagramAnalyticsService.ts+++ b/backend/services/instagramAnalyticsService.ts@@ -29,7 +29,7 @@ export interface InstagramMediaList {export interface InstagramAnalyticsService {analytics(userId: string, accountId: string): Promise<InstagramAccountAnalytics>;- media(userId: string, accountId: string): Promise<InstagramMediaList>;+ media(userId: string, accountId: string, options?: { fresh?: boolean }): Promise<InstagramMediaList>;}type ConnectedInstagramAccount = Account & { igUserId: string; accessToken: string };@@ -67,9 +67,12 @@ export function createInstagramAnalyticsService({ accounts, cache, context }: Inreturn { profile, account: safeAccount(account), analytics: computeInstagramAnalytics(profile, media), mediaCount: media.length };},- async media(userId, accountId) {- const cached = await cache.getInstagramMedia(userId, accountId);- if (cached?.media) return { media: cached.media, fetchedAt: cached.fetchedAt };+ // cache first, unless a person asked for fresh data+ async media(userId, accountId, { fresh = false } = {}) {+ if (!fresh) {+ const cached = await cache.getInstagramMedia(userId, accountId);+ if (cached?.media) return { media: cached.media, fetchedAt: cached.fetchedAt };+ }const account = await findConnected(userId, accountId);const media = await fetchInstagramMedia(account.igUserId, account.accessToken, MEDIA_LIMIT, signal);const fetchedAt = new Date().toISOString();diff --git a/backend/services/overviewService.ts b/backend/services/overviewService.tsindex 3410b61..54bb7ff 100644--- a/backend/services/overviewService.ts+++ b/backend/services/overviewService.ts@@ -48,7 +48,9 @@ export function createOverviewService({ accounts, tracked, cache, config }: OverfetchRedditProfile(username, cookie, signal),fetchRedditPosts(username, cookie, 100, signal),]);- await cache.setReddit(userId, account.id, { profile, analytics: computeRedditAnalytics(profile, posts), posts });+ await cache.setReddit(userId, account.id, {+ profile, analytics: computeRedditAnalytics(profile, posts), posts, fetchedAt: new Date().toISOString(),+ });};}@@ -89,6 +91,7 @@ export function createOverviewService({ accounts, tracked, cache, config }: Overreturn {id: account.id,cacheWarmed: true,+ fetchedAt: cached.fetchedAt,fetchedPosts: cached.analytics.fetchedPosts ?? 0,totalScore: cached.analytics.totalScore ?? 0,totalComments: cached.analytics.totalComments ?? 0,@@ -107,6 +110,7 @@ export function createOverviewService({ accounts, tracked, cache, config }: OvertotalComments: sumBy(types, type => type.comments),totalViews: sumBy(types, type => type.views),contentTypes,+ fetchedAt: cached.fetchedAt,};};@@ -118,6 +122,7 @@ export function createOverviewService({ accounts, tracked, cache, config }: OvercacheWarmed: true,totalLikes: sumBy(cached.videos, video => video.likeCount ?? 0),totalComments: sumBy(cached.videos, video => video.commentCount ?? 0),+ fetchedAt: cached.fetchedAt,};};diff --git a/backend/services/redditAnalyticsService.ts b/backend/services/redditAnalyticsService.tsindex eb7df21..4a12ab7 100644--- a/backend/services/redditAnalyticsService.ts+++ b/backend/services/redditAnalyticsService.ts@@ -14,7 +14,7 @@ export interface RedditAnalyticsDeps {}export interface RedditAnalyticsService {- analytics(userId: string, accountId: string): Promise<RedditCacheData>;+ analytics(userId: string, accountId: string, options?: { fresh?: boolean }): Promise<RedditCacheData>;posts(userId: string, accountId: string): Promise<RedditPost[]>;}@@ -37,16 +37,24 @@ export function createRedditAnalyticsService({ accounts, cache, context }: Reddi}return {- async analytics(userId, accountId) {+ // a fresh load is what a person's Refresh asks for; without it the cache answers and its age is shown+ async analytics(userId, accountId, { fresh = false } = {}) {const { username, cookie } = await credentialsFor(userId, accountId);- const cached = await cache.getReddit(userId, accountId);- if (cached) return cached;+ if (!fresh) {+ const cached = await cache.getReddit(userId, accountId);+ if (cached) return cached;+ }const [profile, posts] = await Promise.all([fetchRedditProfile(username, cookie, signal),fetchRedditPosts(username, cookie, POST_LIMIT, signal),]);- const result: RedditCacheData = { profile, analytics: computeRedditAnalytics(profile, posts), posts };+ const result: RedditCacheData = {+ profile,+ analytics: computeRedditAnalytics(profile, posts),+ posts,+ fetchedAt: new Date().toISOString(),+ };await cache.setReddit(userId, accountId, result);return result;},diff --git a/backend/services/youtubeAnalyticsService.ts b/backend/services/youtubeAnalyticsService.tsindex f533783..aec1183 100644--- a/backend/services/youtubeAnalyticsService.ts+++ b/backend/services/youtubeAnalyticsService.ts@@ -45,7 +45,7 @@ export interface VideoLibrary {export interface YouTubeAnalyticsService {channelAnalytics(userId: string, accountId: string): Promise<ChannelAnalytics>;- channelVideos(userId: string, accountId: string): Promise<ChannelVideos>;+ channelVideos(userId: string, accountId: string, options?: { fresh?: boolean }): Promise<ChannelVideos>;comparison(userId: string): Promise<YouTubeAccountComparison<SafeAccount> | null>;videoLibrary(userId: string, query: VideoLibraryQuery): Promise<VideoLibrary>;}@@ -109,10 +109,12 @@ export function createYouTubeAnalyticsService({ accounts, cache, config, contextreturn { channel: { ...safeAccount(channel), ...channelMetrics(channel) }, analytics, videoCount: videos.length };},- // served from the cache when it has the channel, without spending quota- async channelVideos(userId, accountId) {- const cached = await cache.getVideos(userId, accountId);- if (cached?.videos) return { videos: cached.videos, fetchedAt: cached.fetchedAt };+ // served from the cache when it has the channel, without spending quota, unless a person asked for fresh data+ async channelVideos(userId, accountId, { fresh = false } = {}) {+ if (!fresh) {+ const cached = await cache.getVideos(userId, accountId);+ if (cached?.videos) return { videos: cached.videos, fetchedAt: cached.fetchedAt };+ }const apiKey = youtubeKey();const account = await findChannel(userId, accountId);return fetchAndCacheVideos(userId, accountId, account.uploadsPlaylistId, apiKey);diff --git a/backend/tests/fixtures/overviewRoutes.summary.golden.json b/backend/tests/fixtures/overviewRoutes.summary.golden.jsonindex 353c7ce..d0d36af 100644--- a/backend/tests/fixtures/overviewRoutes.summary.golden.json+++ b/backend/tests/fixtures/overviewRoutes.summary.golden.json@@ -4,7 +4,7 @@{"call": "GET /overview","status": 200,- "body": "{\"tracked\":[{\"id\":\"t1\",\"accountId\":null,\"url\":\"https://youtu.be/x\",\"label\":\"\",\"category\":\"\",\"contentType\":\"youtube\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-08-01T00:00:00Z\",\"title\":\"Tracked\"}],\"analyticsCache\":{\"yt1\":{\"id\":\"yt1\",\"cacheWarmed\":true,\"totalLikes\":12,\"totalComments\":5},\"yt2\":{\"id\":\"yt2\",\"cacheWarmed\":true,\"totalLikes\":1,\"totalComments\":1},\"yt3\":{\"id\":\"yt3\",\"cacheWarmed\":false,\"syncing\":false},\"ig1\":{\"id\":\"ig1\",\"cacheWarmed\":true,\"totalLikes\":6,\"totalComments\":2,\"totalViews\":90,\"contentTypes\":{\"reel\":{\"count\":1,\"likes\":5,\"comments\":2,\"views\":90,\"viewsReported\":1},\"post\":{\"count\":1,\"likes\":1,\"comments\":0,\"views\":0,\"viewsReported\":0},\"video\":{\"count\":0,\"likes\":0,\"comments\":0,\"views\":0,\"viewsReported\":0}}},\"rd1\":{\"id\":\"rd1\",\"cacheWarmed\":true,\"fetchedPosts\":4,\"totalScore\":40,\"totalComments\":0},\"rd2\":{\"id\":\"rd2\",\"cacheWarmed\":false,\"syncing\":false}}}"+ "body": "{\"tracked\":[{\"id\":\"t1\",\"accountId\":null,\"url\":\"https://youtu.be/x\",\"label\":\"\",\"category\":\"\",\"contentType\":\"youtube\",\"createdAt\":\"2026-08-01T00:00:00Z\",\"updatedAt\":\"2026-08-01T00:00:00Z\",\"title\":\"Tracked\"}],\"analyticsCache\":{\"yt1\":{\"id\":\"yt1\",\"cacheWarmed\":true,\"totalLikes\":12,\"totalComments\":5,\"fetchedAt\":\"then\"},\"yt2\":{\"id\":\"yt2\",\"cacheWarmed\":true,\"totalLikes\":1,\"totalComments\":1,\"fetchedAt\":\"then\"},\"yt3\":{\"id\":\"yt3\",\"cacheWarmed\":false,\"syncing\":false},\"ig1\":{\"id\":\"ig1\",\"cacheWarmed\":true,\"totalLikes\":6,\"totalComments\":2,\"totalViews\":90,\"contentTypes\":{\"reel\":{\"count\":1,\"likes\":5,\"comments\":2,\"views\":90,\"viewsReported\":1},\"post\":{\"count\":1,\"likes\":1,\"comments\":0,\"views\":0,\"viewsReported\":0},\"video\":{\"count\":0,\"likes\":0,\"comments\":0,\"views\":0,\"viewsReported\":0}}},\"rd1\":{\"id\":\"rd1\",\"cacheWarmed\":true,\"fetchedPosts\":4,\"totalScore\":40,\"totalComments\":0},\"rd2\":{\"id\":\"rd2\",\"cacheWarmed\":false,\"syncing\":false}}}"}],"queries": [diff --git a/backend/tests/routes/analyticsRoutes.test.ts b/backend/tests/routes/analyticsRoutes.test.tsindex 351e8d2..7d58244 100644--- a/backend/tests/routes/analyticsRoutes.test.ts+++ b/backend/tests/routes/analyticsRoutes.test.ts@@ -143,6 +143,20 @@ describe('analytics and overview routes golden output', () => {assert.deepEqual(fetchMock.requests, []);});+ test('a fresh video list skips the cache and refetches the channel, while a plain read stays on the cache', async () => {+ const redis = cachedRedis();+ const supabase = fakeSupabase(ROWS);+ const app = mountWithContext(server => server.route('/', analyticsRouter), { supabase, redis, userId: 'user-1' });+ fetchMock = installFetch(youtubeReply);+ const cached = JSON.parse((await callRoute(app, 'GET', '/accounts/yt1/videos', { env: ENV })).body) as { fetchedAt: string };+ assert.equal(cached.fetchedAt, 'then');+ assert.deepEqual(fetchMock.requests, []);+ const fresh = JSON.parse((await callRoute(app, 'GET', '/accounts/yt1/videos?fresh=1', { env: ENV })).body) as { fetchedAt: string; videos: { title: string }[] };+ assert.notEqual(fresh.fetchedAt, 'then');+ assert.deepEqual(fresh.videos.map(video => video.title), ['Fresh']);+ assert.deepEqual(redis.writes.map(write => write.key), ['videos:user-1:yt1']);+ });+test('backfilling an older channel adds only stored account fields to the response', async () => {const supabase = fakeSupabase([accountRow({ id: 'ytNew', platform: 'youtube', channelId: 'UC3', uploadsPlaylistId: 'UU3', title: 'Gamma' })]);const app = mountWithContext(server => server.route('/', analyticsRouter), { supabase, redis: null, userId: 'user-1' });diff --git a/backend/tests/routes/redditRoutes.test.ts b/backend/tests/routes/redditRoutes.test.tsindex b5b572f..1132326 100644--- a/backend/tests/routes/redditRoutes.test.ts+++ b/backend/tests/routes/redditRoutes.test.ts@@ -66,4 +66,25 @@ describe('Reddit analytics routes', () => {assert.deepEqual(redis.writes, ['reddit:user-1:rd1']);assert.deepEqual(fetchMock.requests.map(request => (request.headers as Record<string, string>).Cookie), ['reddit_session=COOKIE', 'reddit_session=COOKIE']);});++ test('a fresh load skips the cache, fetches from Reddit and records when it fetched', async () => {+ fetchMock = installFetch(request => (request.url.includes('/about.json')+ ? reply({ data: { name: 'ribbon', total_karma: 9 } })+ : reply({ data: { children: [], after: null } })));+ const redis = storeRedis({ 'reddit:user-1:rd1': CACHED });+ const { status, body } = await call('/accounts/rd1/reddit-analytics?fresh=1', redis);+ assert.equal(status, 200);+ const fresh = body as { profile: { totalKarma: number }; fetchedAt: string };+ assert.equal(fresh.profile.totalKarma, 9);+ assert.ok(!Number.isNaN(Date.parse(fresh.fetchedAt)));+ assert.deepEqual(redis.writes, ['reddit:user-1:rd1']);+ assert.equal(fetchMock.requests.length, 2);+ });++ test('a fresh value other than 1 is refused before any Reddit call', async () => {+ fetchMock = installFetch(() => reply({}));+ const { status } = await call('/accounts/rd1/reddit-analytics?fresh=yes', storeRedis({}));+ assert.equal(status, 400);+ assert.deepEqual(fetchMock.requests, []);+ });});diff --git a/backend/validators/analyticsValidators.ts b/backend/validators/analyticsValidators.tsindex 97c499a..1b7206a 100644--- a/backend/validators/analyticsValidators.ts+++ b/backend/validators/analyticsValidators.ts@@ -11,6 +11,17 @@ function optionalCount(query: Fields, name: string): string | undefined {return value || undefined;}+export interface FreshQuery {+ fresh: boolean;+}++// ?fresh=1 on a cached read (reddit-analytics, videos, ig-media) skips the cache, for a person's explicit refresh+export function parseFreshQuery(query: Fields): FreshQuery {+ const fresh = optionalString(query, 'fresh');+ if (fresh && fresh !== '1') throw new ValidationError('fresh must be 1 when given');+ return { fresh: fresh === '1' };+}+// GET /api/videos/all?channelId=&search=&minViews=&maxViews=&sort=&order=export function parseVideoLibraryQuery(query: Fields): VideoLibraryQuery {const order = optionalString(query, 'order');diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.mdindex 3ae2f97..a6e77fd 100644--- a/docs/architecture/backend/CACHING.md+++ b/docs/architecture/backend/CACHING.md@@ -53,7 +53,7 @@ The rate limiter uses its own client with a 1 second timeout and no retries; see|---|---|---|---|| `videos:{userId}:{accountId}` | `{ videos, fetchedAt, version }` - YouTube video objects with stats | `GET /api/accounts/:id/analytics` succeeds, `GET /api/accounts/:id/videos` fetches live on a miss, or the Overview warms it | `DELETE /api/accounts/:id`, or a `version` mismatch || `ig:{userId}:{accountId}` | `{ media, fetchedAt, version }` - normalized Instagram media (see `normalizeInstagramMedia()`) | `GET /api/accounts/:id/ig-analytics` or `ig-media` succeeds, or the Overview warms it | `DELETE /api/accounts/:id`, or a `version` mismatch |-| `reddit:{userId}:{accountId}` | Object `{ profile, analytics, posts }` for Reddit account | `GET /api/accounts/:id/reddit-analytics` succeeds, or the Overview warms it | `DELETE /api/accounts/:id` |+| `reddit:{userId}:{accountId}` | Object `{ profile, analytics, posts, fetchedAt }` for Reddit account (`fetchedAt` is missing on entries written before it was stored) | `GET /api/accounts/:id/reddit-analytics` succeeds (with or without `?fresh=1`), or the Overview warms it | `DELETE /api/accounts/:id` |Rate limit state also lives in Redis under `twiligent:ratelimit:{rule}:{identifier}` keys (hashes or sorted sets, each with its own expiry). They are written only by the Lua scripts in `lib/rateLimit/scripts.ts` through a separate fast-fail client; see `RATE_LIMITING.md`.@@ -115,3 +115,13 @@ State format: base64url(userId:timestamp).base64url(HMAC-SHA256-signature)Expiry: 10 minutes (checked by comparing embedded timestamp to Date.now())Secret: INSTAGRAM_APP_SECRET```++## Freshness and explicit refresh++Every cached analytics read returns when its data came from the platform (`fetchedAt`), and the Overview's+per-account summaries carry the same field, so each data view in the app says how old its numbers are (the+`DataFreshness` line under the page title, with the exact time on hover and for screen readers). The cache-first+reads `GET /api/accounts/:id/videos`, `ig-media` and `reddit-analytics` accept `?fresh=1`, which the app sends+only when a person presses Refresh: it skips the cache, fetches live and rewrites the entry. Plain page loads+stay on the cache, so opening a page never spends platform quota by itself.+diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex fea3ee2..787ac82 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -94,10 +94,10 @@ Controllers call `YouTubeAnalyticsService` and `InstagramAnalyticsService`. Chan| Method | Path | File | Purpose ||---|---|---|---|| GET | `/api/accounts/:id/analytics` | `analyticsRoutes.ts`, `analyticsController.getChannelAnalytics` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics; 404 for an account that is not a YouTube channel, 400 when no uploads playlist is stored |-| GET | `/api/accounts/:id/videos` | `analyticsRoutes.ts`, `analyticsController.getChannelVideos` | Returns cached video list (from Redis if available); the same 404 and 400 checks before a live fetch |+| GET | `/api/accounts/:id/videos` | `analyticsRoutes.ts`, `analyticsController.getChannelVideos` | Returns `{ videos, fetchedAt }` from the cache when it has the channel, live otherwise; `?fresh=1` skips the cache (a person's Refresh; spends YouTube quota); the same 404 and 400 checks before a live fetch || GET | `/api/videos/all` | `analyticsRoutes.ts`, `analyticsController.getVideoLibrary` | Every cached video across the user's channels, filtered and sorted by `channelId`, `search`, `minViews`, `maxViews`, `sort` and `order` query parameters || GET | `/api/accounts/:id/ig-analytics` | `analyticsRoutes.ts`, `analyticsController.getInstagramAnalytics` | Instagram analytics - fetches up to 500 media with views, classifies each as reel, post, or video, runs `computeInstagramAnalytics()` |-| GET | `/api/accounts/:id/ig-media` | `analyticsRoutes.ts`, `analyticsController.getInstagramMedia` | Returns the Instagram media list (with `contentType` and `viewCount`) from cache, fetching live on a miss |+| GET | `/api/accounts/:id/ig-media` | `analyticsRoutes.ts`, `analyticsController.getInstagramMedia` | Returns `{ media, fetchedAt }` (each item with `contentType` and `viewCount`) from cache, fetching live on a miss; `?fresh=1` skips the cache || GET | `/api/comparison` | `analyticsRoutes.ts`, `analyticsController.getComparison` | Cross-account comparison data for the Overview dashboard |### Instagram OAuth@@ -138,8 +138,8 @@ Controllers call `AccountService` (adding) and `RedditAnalyticsService`.| Method | Path | File | Purpose ||---|---|---|---|| POST | `/api/accounts/reddit` | `accountRoutes.ts`, `accountController.addRedditAccount` | Add Reddit account by username and session cookie (both required); 409 when already added |-| GET | `/api/accounts/:id/reddit-analytics` | `redditRoutes.ts`, `redditController.getRedditAnalytics` | Fetch profile + posts + computed analytics; cached in Redis; 400 when the cookie or username is missing |-| GET | `/api/accounts/:id/reddit-posts` | `redditRoutes.ts`, `redditController.getRedditPosts` | Returns cached post list or live-fetched posts |+| GET | `/api/accounts/:id/reddit-analytics` | `redditRoutes.ts`, `redditController.getRedditAnalytics` | Profile, posts, computed analytics and `fetchedAt`; cached in Redis; `?fresh=1` skips the cache (any other `fresh` value is a 400); 400 when the cookie or username is missing |+| GET | `/api/accounts/:id/reddit-posts` | `redditRoutes.ts`, `redditController.getRedditPosts` | Returns cached post list or live-fetched posts. The app no longer calls it: the posts pages read `reddit-analytics`, which carries `fetchedAt` |### Overview| Method | Path | File | Purpose |diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 5e3d18a..baf9422 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -301,3 +301,12 @@ For a new feature service:3. Throw typed errors from `lib/errors.ts`; never return error objects4. Add it to `Services` and `createServices()` in `backend/container.ts`5. Update `docs/architecture/backend/SERVICES.md` (this file)++## Fresh reads++`youtubeAnalytics.channelVideos`, `instagramAnalytics.media` and `redditAnalytics.analytics` take an optional+`{ fresh }`. Without it they answer from the cache when it has the account; with `fresh: true` they fetch live and+rewrite the cache. The controllers pass it from `?fresh=1`, parsed by `parseFreshQuery` in+`validators/analyticsValidators.ts`. `redditAnalytics.analytics` stores `fetchedAt` with the cache entry, and+`overviewService` copies each cache entry's `fetchedAt` into its account summary.+diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.mdindex d4bd72c..a7ca68f 100644--- a/docs/architecture/data-flows/ANALYTICS.md+++ b/docs/architecture/data-flows/ANALYTICS.md@@ -110,7 +110,8 @@ InstagramAnalytics.tsx mounts -> api.getIGAnalytics(id)5. Return JSONGET /api/accounts/:id/ig-media (IG Content Explorer) returns the cached media when the-cache entry is current, otherwise fetches with the same pipeline and caches it.+cache entry is current, otherwise fetches with the same pipeline and caches it. With ?fresh=1+(the page's Refresh) it skips the cache. The response carries fetchedAt, shown as the data's age.```### Instagram media item (cached shape)@@ -167,7 +168,8 @@ RedditAnalytics.tsx mounts -> api.getRedditAnalytics(id)1. accounts.findForUser(id, userId) - verify ownership-> 404 unless it is a Reddit account, 400 without a stored cookie or username2. cache.getReddit(userId, id): key reddit:{userId}:{accountId}- -> cache hit: return immediately+ -> skipped when ?fresh=1 (the page's Refresh button)+ -> cache hit: return immediately, with the fetchedAt it was stored with-> cache miss: continue3. Fetch from Reddit public JSON API (with the stored session cookie):a. GET /user/{username}/about.json@@ -298,3 +300,39 @@ tab, where they are compared against other view figures.Reddit's API returns a post's net upvotes as `score`. Every aggregate the frontend derives fromit is named and labelled **karma**. The word "score" is reserved for the computed Virality Scoreand Consistency Score indices, which are unrelated to karma.++## How the analytics pages present data++These rules come from the UI/UX guide (issue #132) and apply to every analytics page.++- **Freshness.** Every data view shows when its numbers were fetched (`DataFreshness`): live pages (channel,+ Instagram account) show the time of the last load; cached pages show the cache's `fetchedAt`, and pages built+ from several accounts show the oldest. Refresh asks the server for fresh data (`?fresh=1`) instead of re-reading+ the cache, and the Reddit page's Refresh refreshes the posts as well as the profile.+- **Loading.** Skeletons show only before the first answer. A refresh keeps the page, its tab and its scroll+ position, marks the content `aria-busy` and spins the Refresh button. Library hooks key their loads on the+ account ids, so an account's fields changing elsewhere does not reload every list.+- **Failures.** A failed load is an error with a retry (`ErrorState`), never an empty state. A reload that fails+ keeps the last numbers with an inline alert. On library pages an account whose list fails is named in a warning+ (`FailedSourcesAlert`) and left out of the totals; "No channels yet" is decided from the account list, not from+ which requests succeeded. Refresh all reports the accounts it could not refresh.+- **Metric tiles.** Each tile states its time frame (`period`: "All time", "Last 50 posts", "Matching videos"). A+ trend is coloured by meaning (`upIsGood`) and read as "Up 12%" to screen readers. Rounded figures (`Num`) keep+ the exact value on hover and for screen readers; `fmtNum` drops a trailing `.0` and moves to the next unit when+ rounding would show 1000 of the smaller one. Pages lead with four to six headline tiles; supporting figures go in+ one `MetricDetails` list, each derived score explained in a line, and no figure repeats across tabs.+- **Charts.** Every chart has a one-sentence summary of what it shows and a Show table toggle with the same+ numbers (`ChartFigure`, used by `ChartPanel`, `MetricAreaChart` and `RankingBarChart`). Rankings of separate+ things (accounts, categories, videos, tags) are horizontal bars, not lines. One chart has one unit; a second+ measure goes in the tooltip and table. Platform hues (`PLATFORM_META.series`) mean the platform on every page;+ Instagram content types and categories use other series.+- **Libraries.** Search (debounced), filters, sort, layout and page live in the address (`useLibraryParams`), so+ Back, refresh and shared links keep the view. Every library uses the same controls: `SearchField`, an account+ select, `FilterChips` for ranges and types, `SortSelect` (also in grid layout), `ActiveFilters` with the result+ count and removable filters, `NoResults` that echoes the search, and `Pager` with the range announced. Engagement+ rates sort as numbers.+- **Tables.** Each table is named by its box title, has column headers with `scope`, sorts with `aria-sort` on the+ header cell, hides secondary columns on narrow screens and keeps the identifying column sticky. Long titles+ clamp with the full text on hover. Relative dates (`RelativeTime`) carry the exact date and time; past 30 days+ the date is shown instead of an age.+diff --git a/shared/types/domain.ts b/shared/types/domain.tsindex 0af1bad..bb5d7d4 100644--- a/shared/types/domain.ts+++ b/shared/types/domain.ts@@ -164,9 +164,11 @@ export interface PendingAccountSummary {syncing: boolean;}+// fetchedAt is when the cached numbers came from the platform, so the Overview can say how old they areexport interface RedditAccountSummary {id: string;cacheWarmed: true;+ fetchedAt?: string;fetchedPosts: number;totalScore: number;totalComments: number;@@ -175,6 +177,7 @@ export interface RedditAccountSummary {export interface InstagramAccountSummary {id: string;cacheWarmed: true;+ fetchedAt?: string;totalLikes: number;totalComments: number;totalViews: number;@@ -184,6 +187,7 @@ export interface InstagramAccountSummary {export interface YouTubeAccountSummary {id: string;cacheWarmed: true;+ fetchedAt?: string;totalLikes: number;totalComments: number;}diff --git a/shared/types/reddit.ts b/shared/types/reddit.tsindex a8a04f6..8fa25fe 100644--- a/shared/types/reddit.ts+++ b/shared/types/reddit.ts@@ -104,6 +104,8 @@ export interface RedditCacheData {profile: RedditProfile;analytics: RedditAnalytics;posts: RedditPost[];+ // when the posts were fetched from Reddit; missing on entries cached before it was recorded+ fetchedAt?: string;}// fetchTrackedPostData() output, patched into a reddit tracked post's data on add and refresh