Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

docs: describe Twiligent with YouTube and Instagram only

spacesdrive6fc9c533ae88
diff --git a/CLAUDE.md b/CLAUDE.md
index c7ed956..3630bdf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2,11 +2,11 @@
## Project Identity
-Twiligent is a self-hosted social media analytics and publishing dashboard for creators and teams managing multiple YouTube channels, Instagram accounts and Reddit profiles. It is a private deployment product - the owner runs their own instance with their own API credentials. There is no SaaS model, no multi-tenancy abstraction, and no billing system.
+Twiligent is a self-hosted social media analytics and publishing dashboard for creators and teams managing multiple YouTube channels and Instagram accounts. It is a private deployment product - the owner runs their own instance with their own API credentials. There is no SaaS model, no multi-tenancy abstraction, and no billing system.
- Primary users: Small creator teams, agencies, individual power users
- Primary value: Unified analytics, scheduled Instagram publishing, and automatic private replies to Instagram comments across multiple accounts
-- Current platforms: YouTube (analytics only), Instagram (analytics, publishing and comment-to-DM automation), Reddit (analytics only)
+- Current platforms: YouTube (analytics only) and Instagram (analytics, publishing and comment-to-DM automation)
- Public site: https://twiligent.ujjwal.fyi is the project's own marketing site and documentation (the `site/` workspace); the app runs at https://app.twiligent.ujjwal.fyi. Self-hosters run only the app and the Worker; the site is not needed to run Twiligent
- GitHub repository: https://github.com/spacesdrive/twiligent
- Goals and priorities: `ROADMAP.md`
@@ -161,11 +161,11 @@ docs/
ARCHITECTURE.md Architectural principles and constraints
SECURITY.md Security model, key handling, isolation
PERFORMANCE.md Caching strategy, edge optimization
- platform-v2/ The v2 work (#142): Reddit removed, MCP server, YouTube publishing, security auditing
+ platform-v2/ The v2 work (#142): platform removal (ADR-049), MCP server, YouTube publishing, security auditing
RESEARCH.md Findings and verified facts; full reports in research/
ARCHITECTURE.md Target design, decisions and trade-offs, bottlenecks
IMPLEMENTATION_PLAN.md Phases, dependency map, tools, testing strategy, failure scenarios, owner actions, status
- DATABASE_MIGRATION.md Reddit cleanup and the new tables, with the backup and review steps
+ DATABASE_MIGRATION.md Cleanup of the removed platform's data, and the new tables, with the backup and review steps
site/content/docs/ Public user and self-hosting docs (MDX) served at twiligent.ujjwal.fyi/docs
DECISIONS.md Architectural decision log
diff --git a/DECISIONS.md b/DECISIONS.md
index 9913839..f64c3a6 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -1061,3 +1061,21 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts
**Trade-offs:**
- `react-aria-components` is a second headless library beside Base UI; it is used only inside the chart legend.
- The charts lose the visible summary and data table added in #132; screen readers still get each chart's description.
+
+## ADR-049: Reddit is removed; Twiligent supports YouTube and Instagram
+
+**Date:** 2026-11-05
+**Status:** Accepted
+
+**Decision:** Twiligent 2.0.0 drops Reddit (#144, part of #142). The Reddit routes (`POST /api/accounts/reddit`, `GET /api/accounts/:id/reddit-analytics` and `/reddit-posts`), the Reddit API client and analytics, the Reddit pages, the Reddit account form and Reddit tracked posts are removed. `Platform` is `'youtube' | 'instagram'`, `safeAccount()` strips only the Instagram access token, and tracked content follows YouTube videos only: no typed-in views, uploaded images or linked account. The Worker reads only YouTube and Instagram accounts and YouTube tracked posts, always writes `content_type = 'youtube'` and never writes `account_id`, so existing Reddit rows stay in the database but are never read. Removing those rows, the `'reddit'` values in the checks and the identity index, the `content_type` default and `tracked_posts.account_id` is a separate data change (#145, `docs/platform-v2/DATABASE_MIGRATION.md`), made only after this release is deployed and the owner has reviewed the SQL and the row counts.
+
+**Context:** On 2026-11-05 the owner decided to focus Twiligent on YouTube and Instagram, where publishing is planned next. Reddit was analytics only, and it was the one platform that kept session cookies and, in older rows, encrypted passwords and TOTP secrets in the database; dropping it removes those secrets from what the app stores and handles.
+
+**Alternatives considered:**
+- Hiding Reddit behind a setting. The code, the stored cookies and the tests would stay to maintain for a platform nobody uses.
+- Removing the code and the data in one release. The data change cannot be undone without a backup, so it waits for the owner's review of the exact SQL, separately from the code.
+
+**Trade-offs:**
+- Removing public routes is a breaking change, so this ships as 2.0.0. Old links to the Reddit pages show Not found in the app; the public site redirects its old Reddit paths to the Overview.
+- Until #145 runs, Reddit rows and their secrets remain in the database, unread. Reddit cache keys in Redis expire on their own within 6 hours.
+- Instances that used Reddit lose its history in the app; the rows can be exported before the cleanup.
diff --git a/README.md b/README.md
index d78d0c8..dcf22e5 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
<h3>Every channel, folded into one clear picture.</h3>
-<p>A self-hosted dashboard for your YouTube, Instagram and Reddit numbers.<br/>
+<p>A self-hosted dashboard for your YouTube and Instagram numbers.<br/>
Publish to Instagram, schedule posts, and answer comments automatically.<br/>
It runs on accounts you own, mostly on free plans.</p>
@@ -35,7 +35,7 @@ It runs on accounts you own, mostly on free plans.</p>
## Why Twiligent
-If you post in more than one place, your numbers live in more than one place. YouTube Studio has some of them, Instagram has others, and Reddit keeps its own. Most tools that bring them together charge a monthly fee and ask for access to your accounts.
+If you post in more than one place, your numbers live in more than one place. YouTube Studio has some of them and Instagram keeps the rest. Most tools that bring them together charge a monthly fee and ask for access to your accounts.
Twiligent puts them in one dashboard that you host yourself. Your data stays in your own database, your keys stay on your own server, and it runs mostly on free plans.
@@ -75,7 +75,7 @@ Twiligent puts them in one dashboard that you host yourself. Your data stays in
<td width="50%" valign="top">
<img src="docs/media/accounts.webp" alt="The Accounts page with connected channels" width="100%" />
<h4>Bring every account together</h4>
- <p>Add YouTube channels by link or handle and Reddit profiles by username, connect Instagram with one sign-in, and refresh them all at once.</p>
+ <p>Add YouTube channels by link or handle, connect Instagram with one sign-in, and refresh them all at once.</p>
</td>
</tr>
</table>
@@ -91,7 +91,7 @@ flowchart LR
You([You, in the browser]) --> App[Dashboard<br/>Cloudflare Pages]
App --> API[API<br/>Cloudflare Worker]
API --> DB[(Your Supabase<br/>database)]
- API --> Platforms[YouTube, Instagram<br/>and Reddit APIs]
+ API --> Platforms[YouTube and<br/>Instagram APIs]
Clock([Every minute]) --> API
```
diff --git a/ROADMAP.md b/ROADMAP.md
index d2390bf..e18342a 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -10,7 +10,7 @@ Every item that is being worked on has a GitHub issue (see `docs/workflows/ISSUE
What Twiligent is for, and what every change should move forward.
-1. **One place for a creator's numbers.** YouTube, Instagram and Reddit analytics on one dashboard, with the same metrics, terms and layout across platforms.
+1. **One place for a creator's numbers.** YouTube and Instagram analytics on one dashboard, with the same metrics, terms and layout across platforms.
2. **Publishing that does not miss.** Scheduled Instagram posts go out on time, exactly once, even if one of the two schedulers fails.
3. **Cheap and simple to self-host.** Runs on the free tiers of Cloudflare, Supabase, Upstash and Cloudinary. Setup is documented step by step in the public docs at `https://twiligent.ujjwal.fyi/docs`, and members of an instance need no setup at all.
4. **Safe by default.** Secrets stay server-side, every query is scoped to the signed-in user, tokens never reach the browser, and no client can exhaust the shared API quotas.
@@ -47,7 +47,7 @@ Add Twitter/X for analytics (read-only via twitterapi.io or the official v2 API)
- Fetch tweets, impressions and engagement through the provider's REST API
- No OAuth popup needed for public accounts
-Follow `docs/features/NEW_INTEGRATION.md`; the Reddit integration is the closest template.
+Follow `docs/features/NEW_INTEGRATION.md`; the YouTube integration, which reads public data with a server key and no OAuth, is the closest template.
---
@@ -126,7 +126,6 @@ React Native app using the same Cloudflare Worker backend.
- Redis cache TTL was never set - analytics caches now expire after 6 hours.
- The legacy Express prototype in the root `public/` folder and its root dependencies were removed; the root `package.json` is now the npm workspaces root.
-- Reddit integration shipped (public JSON API, no cookies or OAuth).
- Secrets with PowerShell-injected BOM characters broke the GitHub Actions publisher - it now strips non-ASCII characters from them.
- The API had no rate limiting - every request is now limited per IP, per user and per quota-spending route (#8).
- The codebase was JavaScript with API shapes restated on both sides - it is now strict TypeScript with shared API types (#2).
diff --git a/docs/WRITING_STANDARDS.md b/docs/WRITING_STANDARDS.md
index 1fbc50d..2c71d55 100644
--- a/docs/WRITING_STANDARDS.md
+++ b/docs/WRITING_STANDARDS.md
@@ -19,7 +19,7 @@ These rules apply to all generated code, documentation, UI copy, commit messages
- Never use emoji as icons in UI.
- Use SVG icons only.
-- In the app (`frontend/`), prefer Lucide React icons (`lucide-react`) at a 1.75 stroke. Platform logos (YouTube, Instagram, Reddit) come from `components/brand/platform-icons.tsx`.
+- In the app (`frontend/`), prefer Lucide React icons (`lucide-react`) at a 1.75 stroke. Platform logos (YouTube, Instagram) come from `components/brand/platform-icons.tsx`.
- If Lucide does not have an appropriate icon, use another open-source SVG icon library (e.g. Heroicons, Radix Icons).
- On the public site (`site/`), use the Solar icons (480 Design, CC BY 4.0, credited in `THIRD_PARTY_NOTICES.md`) generated into `site/src/components/icons.tsx`: the bold style for things and places, the linear style for small controls. Add an icon to the list in `site/build/genIcons.ts` and run `npm run icons --workspace site`. Platform logos on the site come from `site/src/components/marks.tsx`. The owner chose Solar for the site on 2026-10-15; the app keeps Lucide.
- All icons in the same UI context must have consistent size, stroke width, spacing, and visual weight.
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index 2b75a2b..2cb2716 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -46,15 +46,15 @@
│ Supabase │ │ Upstash │ │ External APIs │
│ Postgres │ │ Redis │ │ ├── YouTube Data API v3 │
│ │ │ (cache, │ │ ├── Instagram Graph API v25 │
-│ tables: │ │ rate │ │ ├── Reddit Public JSON API │
-│ accounts │ │ limits,│ │ ├── Cloudinary Upload API │
-│ │ │ email │ │ └── Resend Email API (auth emails) │
+│ tables: │ │ rate │ │ ├── Cloudinary Upload API │
+│ accounts │ │ limits,│ │ └── Resend Email API (auth emails) │
+│ │ │ email │ │ │
│ │ │ counts)│ │ │
│ settings │ │ │ └──────────────────────────────────────┘
│ sched_ │ │ keys: │
│ posts │ │ videos: │
│ tracked_ │ │ ig: │
-│ posts │ │ reddit: │
+│ posts │ │ │
│ automa- │ │ │
│ tion_* │ │ │
│ audit_ │ │ │
@@ -181,7 +181,6 @@ The full flow, limits and failure handling are in `docs/architecture/data-flows/
| Video/media analytics | Upstash Redis (`videos:` / `ig:` keys) | Avoids repeated heavy API calls |
| Auth email counts | Upstash Redis (`email:day:` / `email:to:` keys, addresses hashed) | Caps verification emails at the provider's free daily quota |
| Media files (for publishing) | Cloudinary CDN | Instagram requires public URL |
-| Tracked Reddit post images | Cloudinary CDN | Reddit's public JSON API carries no usable thumbnail |
| API secrets | Cloudflare Worker secrets | Encrypted at rest, never in responses |
## Environment Configuration
diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.md
index a6e77fd..95933b4 100644
--- a/docs/architecture/backend/CACHING.md
+++ b/docs/architecture/backend/CACHING.md
@@ -6,12 +6,12 @@ Caching is implemented via Upstash Redis (REST API) using the `@upstash/redis` S
## Cache Layer: `backend/repositories/analyticsCacheRepository.ts`
-The cache is a repository like the database tables. `createAnalyticsCacheRepository(redis)` is built in `container.ts` and handed to the services that read or warm analytics (`accounts`, `youtubeAnalytics`, `instagramAnalytics`, `redditAnalytics`, `overview`). No other code touches Redis keys for analytics.
+The cache is a repository like the database tables. `createAnalyticsCacheRepository(redis)` is built in `container.ts` and handed to the services that read or warm analytics (`accounts`, `youtubeAnalytics`, `instagramAnalytics`, `overview`). No other code touches Redis keys for analytics.
The repository follows this contract:
- Every method is a no-op without Redis: reads return `null`, writes and deletes return
- Every Redis call is wrapped in `try/catch` - a Redis failure must never break the main request
-- Reads return the cached shape from `shared/types` (`VideosCacheData`, `IGCacheData`, `RedditCacheData`), or `null` on a miss
+- Reads return the cached shape from `shared/types` (`VideosCacheData`, `IGCacheData`), or `null` on a miss
- `enabled` is `false` without Redis, so the Overview knows not to start warming
The private helpers `readKey<T>()`, `writeKey()` and `deleteKey()` implement the availability check, the `try/catch` and the TTL once; every method goes through them:
@@ -33,8 +33,7 @@ async function readKey<T>(key: string): Promise<T | null> {
|---|---|
| `getVideos(userId, accountId)`, `setVideos(userId, accountId, data)` | `videos:{userId}:{accountId}` |
| `getInstagramMedia(userId, accountId)`, `setInstagramMedia(userId, accountId, data)` | `ig:{userId}:{accountId}` |
-| `getReddit(userId, accountId)`, `setReddit(userId, accountId, data)` | `reddit:{userId}:{accountId}` |
-| `deleteAllForAccount(userId, accountId)` | All three keys for the account |
+| `deleteAllForAccount(userId, accountId)` | Both keys for the account |
## When Redis Fails
@@ -53,7 +52,6 @@ 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, 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`.
@@ -74,13 +72,13 @@ One Lua script reads both counters and increments both only when neither cap is
## Cache TTL
-`videos:`, `ig:` and `reddit:` keys expire after 6 hours (`ANALYTICS_TTL_SECONDS` in `analyticsCacheRepository.ts`), so counts refetch rather than going stale. They are also removed when the account is deleted.
+`videos:` and `ig:` keys expire after 6 hours (`ANALYTICS_TTL_SECONDS` in `analyticsCacheRepository.ts`), so counts refetch rather than going stale. They are also removed when the account is deleted. The removed platform's keys (ADR-049 in `DECISIONS.md`) are no longer read or written and expire within 6 hours of the upgrade to v2.0.0.
`videos:` entries carry a `version` field like `ig:` entries (`VIDEOS_CACHE_VERSION`). Version 2 stores `likeCount` and `commentCount` as `null` when YouTube hides them (the owner hid likes, or comments are off), instead of `0`; the UI shows those as "Hidden".
## Overview warming
-`GET /api/overview` returns `{ cacheWarmed, syncing }` per account. When an account has no cache entry, `overviewService.summary()` starts a background fetch (YouTube, Instagram and Reddit) and the controller keeps it alive with `waitUntil`; the response says `syncing: true` only if that fetch actually started. Without Redis, an API key, a token or a cookie it returns `syncing: false`, so the client never waits on something that cannot load. While any account is syncing the client polls again up to three times. Each poll waits 4, 8 and then 16 seconds after the previous response (about 4, 12 and 28 seconds after the first load), then polling stops.
+`GET /api/overview` returns `{ cacheWarmed, syncing }` per account. When an account has no cache entry, `overviewService.summary()` starts a background fetch (YouTube or Instagram) and the controller keeps it alive with `waitUntil`; the response says `syncing: true` only if that fetch actually started. Without Redis, an API key or a token it returns `syncing: false`, so the client never waits on something that cannot load. While any account is syncing the client polls again up to three times. Each poll waits 4, 8 and then 16 seconds after the previous response (about 4, 12 and 28 seconds after the first load), then polling stops.
## Cache Usage in Services
@@ -121,7 +119,7 @@ Secret: INSTAGRAM_APP_SECRET
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
+reads `GET /api/accounts/:id/videos` and `ig-media` 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/CRON.md b/docs/architecture/backend/CRON.md
index 234bd96..d1da441 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -117,8 +117,6 @@ After the refresh, `retention.purge()` in `backend/services/retentionService.ts`
- The daily cron refreshes any token expiring within 15 days
- This gives a 15-day window for recovery if the cron fails for a few days
-Reddit sessions are not refreshed on a schedule. Reddit accounts are added with a `reddit_session` cookie copied from the browser (`POST /api/accounts/reddit` with `{ username, cookie }`); when the cookie expires, the user re-adds the account.
-
## The `ctx.waitUntil()` Pattern
The `scheduled` handler passes the job to `ctx.waitUntil()`:
diff --git a/docs/architecture/backend/HONO.md b/docs/architecture/backend/HONO.md
index 1d7d573..ce765c4 100644
--- a/docs/architecture/backend/HONO.md
+++ b/docs/architecture/backend/HONO.md
@@ -32,7 +32,7 @@ The backend is split into layers, each with one job. `REQUEST_PIPELINE.md` is th
| `routes/` | One route table per feature (`<feature>Routes.ts`) and `index.ts`, which groups them into `publicRoutes` and `protectedRoutes` |
| `controllers/` | One controller file per feature (`<feature>Controller.ts`) and `http.ts` with `controller`, `servicesFor(c)` and `pathParam(c, name)` |
| `validators/` | Request body and query parsers (`<feature>Validators.ts`) and the field helpers in `fields.ts` |
-| `services/` | Feature services (`<feature>Service.ts`, `scheduledPublisher.ts`) the platform modules in `youtube/`, `instagram/` and `reddit/`, and the auth email modules in `email/` (see `SERVICES.md`) |
+| `services/` | Feature services (`<feature>Service.ts`, `scheduledPublisher.ts`) the platform modules in `youtube/` and `instagram/`, and the auth email modules in `email/` (see `SERVICES.md`) |
| `repositories/` | Data access, one repository per table or cache (`<table>Repository.ts`), and the query helpers in `query.ts` |
| `database/` | `supabase.ts` (`getSupabase`, `getSupabaseAuth`) and `redis.ts` (`getRedis`, `getRateLimitRedis`) |
| `jobs/` | `scheduled.ts`: the cron entry point, `runScheduledJob(cron, env, scheduledTime)` |
diff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.md
index 4dff545..8af3f5c 100644
--- a/docs/architecture/backend/MIDDLEWARE.md
+++ b/docs/architecture/backend/MIDDLEWARE.md
@@ -142,8 +142,8 @@ export async function requireAuth(c: AppContext, next: Next): Promise<void> {
`jsonBody(parse)` and `queryParams(parse)` wrap Hono's `validator`. Each parser in `backend/validators/` reads fields with the helpers in `validators/fields.ts` and throws `ValidationError` (400). For a query, a repeated key keeps its first value. The controller reads the parsed result with `c.req.valid('json')` or `c.req.valid('query')`.
```ts
-export const addRedditAccount = controller.createHandlers(jsonBody(parseRedditAccount), async c => {
- const account = await servicesFor(c).accounts.addReddit(c.get('userId'), c.req.valid('json'));
+export const addInstagramAccount = controller.createHandlers(jsonBody(parseInstagramToken), async c => {
+ const account = await servicesFor(c).accounts.addInstagram(c.get('userId'), c.req.valid('json').accessToken);
return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
});
```
diff --git a/docs/architecture/backend/RATE_LIMITING.md b/docs/architecture/backend/RATE_LIMITING.md
index e7e7100..858b317 100644
--- a/docs/architecture/backend/RATE_LIMITING.md
+++ b/docs/architecture/backend/RATE_LIMITING.md
@@ -3,7 +3,7 @@
Every `/api` request is rate limited inside the Worker. Cloudflare does not limit requests to a `workers.dev` Worker on its own: WAF rate limiting rules need a zone the owner controls, and the Workers rate limiting binding is per location and only supports 10 or 60 second periods. So the Worker enforces its own limits, which protect three things:
- Supabase Auth, which `requireAuth` calls on every protected request
-- The shared YouTube Data API quota and the Instagram and Reddit API limits
+- The shared YouTube Data API quota and the Instagram API limits
- Instagram publishing, which Instagram caps at 100 posts a day per account
## Request Flow
@@ -33,7 +33,7 @@ Defined in `backend/lib/rateLimit/rules.ts`.
|---|---|---|---|---|
| `ip` | Every `/api` request | Client IP; IPv6 by /64 | Sliding window counter | 300 per minute |
| `user` | Every protected request | User id from the verified JWT | Token bucket | Bursts of 120, refills 2 per second |
-| `quota` | `POST /accounts`, `/accounts/reddit`, `/accounts/instagram`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/accounts/:id/refresh-ig-token`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `GET` or `POST /process-scheduled`, `POST /automations/accounts/:accountId/subscribe` | User id | Sliding window log | 30 per 10 minutes |
+| `quota` | `POST /accounts`, `/accounts/instagram`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/accounts/:id/refresh-ig-token`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `GET` or `POST /process-scheduled`, `POST /automations/accounts/:accountId/subscribe` | User id | Sliding window log | 30 per 10 minutes |
| `publish` | `POST /accounts/:id/ig-media-publish`, `/accounts/:id/ig-publish` | User id | Leaking bucket | 50 deep, drains 1 every 15 seconds |
| `oauth` | `GET /auth/instagram/callback` | Client IP | Fixed window counter | 10 per 10 minutes |
diff --git a/docs/architecture/backend/REQUEST_PIPELINE.md b/docs/architecture/backend/REQUEST_PIPELINE.md
index 519de4d..b065be0 100644
--- a/docs/architecture/backend/REQUEST_PIPELINE.md
+++ b/docs/architecture/backend/REQUEST_PIPELINE.md
@@ -76,7 +76,7 @@ Services and repositories throw typed errors from `lib/errors.ts`. An error carr
| `NotFoundError` | `NOT_FOUND` | 404 | The resource does not exist for this user, or the route does not exist |
| `ConflictError` | `CONFLICT` | 409 | The account is already added |
| `RateLimitedError`, or the rate limiter | `RATE_LIMITED` | 429 | A daily allowance is used up (the auth email caps), or a rate limit rule is exceeded; the rate limiter's body adds `retryAfter` |
-| `UpstreamError` | `UPSTREAM_ERROR` | 502 | YouTube, Instagram or Reddit answered with an error; its message is kept, URLs are removed |
+| `UpstreamError` | `UPSTREAM_ERROR` | 502 | YouTube or Instagram answered with an error; its message is kept, URLs are removed |
| `NotConfiguredError` | `NOT_CONFIGURED` | 503 | A Worker secret the request needs is not set; `injectClients` throws it for every request when `SUPABASE_URL`, `SUPABASE_SERVICE_KEY` or `SUPABASE_ANON_KEY` is missing |
| `UpstreamTimeoutError` | `UPSTREAM_TIMEOUT` | 504 | A platform call was cancelled or timed out |
| `DatabaseError` | `DATABASE_ERROR` | 500 | A Supabase query failed or did not answer within 15 seconds; the client gets a plain message, the log gets the driver's |
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 787ac82..38c2a61 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -24,10 +24,12 @@ These statuses apply to every route below and are not repeated in the tables:
| 409 | `CONFLICT` | The account is already added, or an automation item cannot be retried in its state |
| 429 | `RATE_LIMITED` | A rate limit rule is exceeded; the body adds `retryAfter` (seconds). The email hook also answers 429 when the day's emails are used up |
| 500 | `DATABASE_ERROR`, `INTERNAL_ERROR` | A Supabase query failed, or a bug |
-| 502 | `UPSTREAM_ERROR` | YouTube, Instagram or Reddit answered with an error; the platform's message is kept with URLs removed |
+| 502 | `UPSTREAM_ERROR` | YouTube or Instagram answered with an error; the platform's message is kept with URLs removed |
| 503 | `NOT_CONFIGURED` | A Worker secret the route needs (YouTube key, Instagram app, Cloudinary, the email hook secrets, the Instagram webhook secrets) is not set |
| 504 | `UPSTREAM_TIMEOUT` | A platform call was cancelled or timed out |
+The routes of the platform removed in v2.0.0 answer 404 like any other unknown route (ADR-049 in `DECISIONS.md`).
+
## Public Routes
Registered on `publicRoutes` in `routes/index.ts`.
@@ -131,16 +133,6 @@ Controllers call `ScheduledPostService` (`services/scheduledPostService.ts`).
| GET | `/api/process-scheduled` | `scheduledPostRoutes.ts`, `scheduledPostController.publishDuePosts` | Manual trigger - runs `scheduledPublisher.publishDue()` immediately for every user's due posts (dev/test) |
| POST | `/api/process-scheduled` | `scheduledPostRoutes.ts`, `scheduledPostController.publishDuePosts` | Same as above |
-### Reddit
-
-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` | 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 |
|---|---|---|---|
@@ -148,15 +140,15 @@ Controllers call `AccountService` (adding) and `RedditAnalyticsService`.
### Tracked Content
-Controllers call `TrackedContentService`; link detection and the manual views and image checks live in `services/trackedContentRules.ts`.
+Controllers call `TrackedContentService`; link detection lives in `services/trackedContentRules.ts`. Tracked content is YouTube videos only.
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/tracked-content` | `trackedContentRoutes.ts`, `trackedContentController.listTrackedContent` | List all tracked items for the current user (Reddit posts and YouTube videos) |
-| POST | `/api/tracked-content` | `trackedContentRoutes.ts`, `trackedContentController.addTrackedContent` | Add a URL to track; auto-detects Reddit or YouTube; fetches live data immediately; answers `201` |
-| PUT | `/api/tracked-content/:id` | `trackedContentRoutes.ts`, `trackedContentController.updateTrackedContent` | Update `label`, `category`, `accountId`, `manualViews`, or `imageUrl` for a tracked item. `manualViews` and `imageUrl` are Reddit-only (400 for YouTube) and `null` clears either. `manualViews` must be a whole number of 0 or more; `imageUrl` must parse as an `https:` URL. An `accountId` on a YouTube item is 400, and one that is not the user's Reddit account is 404 `Reddit account not found` |
+| GET | `/api/tracked-content` | `trackedContentRoutes.ts`, `trackedContentController.listTrackedContent` | List all tracked YouTube videos for the current user |
+| POST | `/api/tracked-content` | `trackedContentRoutes.ts`, `trackedContentController.addTrackedContent` | Add a YouTube video to track from `{ url, label?, category? }`; fetches live data immediately; answers `201`. Any other link is 400 `Only YouTube video links can be tracked. Paste a youtube.com or youtu.be link.` |
+| PUT | `/api/tracked-content/:id` | `trackedContentRoutes.ts`, `trackedContentController.updateTrackedContent` | Update `label` and `category` for a tracked item (`{ label?, category? }`) |
| DELETE | `/api/tracked-content/:id` | `trackedContentRoutes.ts`, `trackedContentController.deleteTrackedContent` | Remove a tracked item |
-| POST | `/api/tracked-content/:id/refresh` | `trackedContentRoutes.ts`, `trackedContentController.refreshTrackedContent` | Re-fetch live data from Reddit or YouTube API for one tracked item |
+| POST | `/api/tracked-content/:id/refresh` | `trackedContentRoutes.ts`, `trackedContentController.refreshTrackedContent` | Re-fetch live data from the YouTube API for one tracked item |
### Automations
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index baf9422..28f379a 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -3,7 +3,7 @@
`backend/services/` holds two kinds of module:
- **Feature services** at the top level (`accountService.ts`, `publishingService.ts`, ...). Each is a factory, `createXService(deps)`, that returns an object of methods. They hold the business rules: they find the user's records through repositories, call the platform modules, use the cache and throw typed errors from `lib/errors.ts`. Controllers call them; they never see the Hono context.
-- **Platform modules** in `services/youtube/`, `services/instagram/` and `services/reddit/`. Plain functions that talk to one platform's API or compute analytics from its data. They know nothing about users, the database or the cache.
+- **Platform modules** in `services/youtube/` and `services/instagram/`. Plain functions that talk to one platform's API or compute analytics from its data. They know nothing about users, the database or the cache.
Data access is not here: repositories in `backend/repositories/` own every Supabase query and Redis key (see `CACHING.md` and `docs/guidelines/SUPABASE.md`). Services never import from routes or controllers.
@@ -29,15 +29,14 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from
| Service (key in `Services`) | File | Repositories | Methods |
|---|---|---|---|
-| `accounts` | `accountService.ts` | accounts, cache | `list`, `resolveChannel`, `addYouTube`, `addReddit`, `addInstagram`, `refresh`, `refreshAll`, `refreshInstagramToken`, `remove` |
+| `accounts` | `accountService.ts` | accounts, cache | `list`, `resolveChannel`, `addYouTube`, `addInstagram`, `refresh`, `refreshAll`, `refreshInstagramToken`, `remove` |
| `youtubeAnalytics` | `youtubeAnalyticsService.ts` | accounts, cache | `channelAnalytics`, `channelVideos`, `comparison`, `videoLibrary` |
| `instagramAnalytics` | `instagramAnalyticsService.ts` | accounts, cache | `analytics`, `media` |
-| `redditAnalytics` | `redditAnalyticsService.ts` | accounts, cache | `analytics`, `posts` |
| `publishing` | `publishingService.ts` | accounts | `cloudinaryConfig`, `publishingLimit`, `createContainer`, `containerStatus`, `publishContainer` |
| `scheduledPosts` | `scheduledPostService.ts` | accounts, scheduled posts (and the publisher) | `list`, `create`, `update`, `remove`, `removeAll`, `publishDueNow` |
| `scheduledPublisher` | `scheduledPublisher.ts` | accounts, scheduled posts | `publishDue` (every user's due posts; cron and manual trigger) |
| `tokenRefresh` | `tokenRefreshService.ts` | accounts | `refreshExpiringInstagramTokens` (daily cron) |
-| `trackedContent` | `trackedContentService.ts` | accounts, tracked posts | `list`, `add`, `update`, `remove`, `refresh` |
+| `trackedContent` | `trackedContentService.ts` | tracked posts | `list`, `add`, `update`, `remove`, `refresh` |
| `overview` | `overviewService.ts` | accounts, tracked posts, cache | `summary` |
| `settings` | `settingsService.ts` | settings | `githubSettings`, `saveGithubSettings`, `serverKeyStatus` |
| `instagramConnect` | `instagramConnectService.ts` | accounts | `authorizationUrl`, `userIdFromState`, `connect`, plus `configured` and `accountsPageUrl` |
@@ -75,22 +74,22 @@ The flow is in `docs/architecture/data-flows/AUTOMATION.md`. The rules the servi
### Accounts (`accountService.ts`, `accountFactory.ts`)
-`accountFactory.ts` holds pure builders: `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount`. Each builder takes its id from `newRowId()`.
+`accountFactory.ts` holds pure builders: `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildInstagramAccount`. Each builder takes its id from `newRowId()`.
`AccountService`:
-- `addYouTube`, `addReddit` and `addInstagram` throw `ConflictError` (409) for an account the user already has. `addInstagram` tries the long-lived token exchange when `INSTAGRAM_APP_SECRET` is set and keeps the pasted token if it fails.
-- `refresh` and `refreshAll` check the fields the platform call needs first (an Instagram token, a Reddit username and cookie, a YouTube channel id) and throw `ValidationError` (400) when one is missing; a missing YouTube key is a `NotConfiguredError` (503). A single refresh updates more fields than refresh-all. `refreshAll` uses `Promise.allSettled`, so one failure does not stop the rest, and its `results` line up with the account list by index.
-- `remove` deletes the account row and its cache entries. The database removes the account's scheduled posts with it and clears the account from its tracked items (the foreign keys in `docs/architecture/database/SCHEMA.md`).
+- `addYouTube` and `addInstagram` throw `ConflictError` (409) for an account the user already has. `addInstagram` tries the long-lived token exchange when `INSTAGRAM_APP_SECRET` is set and keeps the pasted token if it fails.
+- `refresh` and `refreshAll` check the fields the platform call needs first (an Instagram token, a YouTube channel id) and throw `ValidationError` (400) when one is missing; a missing YouTube key is a `NotConfiguredError` (503). A single refresh updates more fields than refresh-all. `refreshAll` uses `Promise.allSettled`, so one failure does not stop the rest, and its `results` line up with the account list by index.
+- `remove` deletes the account row and its cache entries. The database removes the account's scheduled posts with it (the foreign keys in `docs/architecture/database/SCHEMA.md`).
- Account updates go through `merge_account_data`, one statement in the database, so a token refresh and an analytics refresh on the same account never undo each other. A field passed as `undefined` keeps its stored value.
`YouTubeAnalyticsService.channelAnalytics` fills channel fields for a YouTube account without `publishedAt` the first time its analytics load; a failure is logged and skipped.
### Tracked content (`trackedContentService.ts`, `trackedContentRules.ts`)
-`TrackedContentService.add` stores the fetched data in the same insert that creates the item. `update` checks a new `accountId` before storing it: a YouTube item answers 400 `YouTube videos are read without an account; remove the account from this item.`, and an account that is not one of the user's Reddit accounts answers 404 `Reddit account not found`. `refresh` and the manual fields merge into `data` with `merge_tracked_post_data`.
+Tracked content is YouTube videos only. `TrackedContentService.add` refuses any other link with 400 `Only YouTube video links can be tracked. Paste a youtube.com or youtu.be link.` and stores the fetched data in the same insert that creates the item, with `content_type` set to `youtube`. `update` changes only `label` and `category`. `refresh` merges the fetched data into `data` with `merge_tracked_post_data`.
-`trackedContentRules.ts` holds the pure rules: `detectContentType(url)` (`reddit`, `youtube` or `null`), `manualViewsPatch(value, isYouTube)` and `imageUrlPatch(value, isYouTube)`. The two patch helpers return `{ patch }` to merge into the item's `data`, or `{ error }`, which the service throws as a `ValidationError`. Empty values clear the field, YouTube items refuse both, views must be whole numbers of 0 or more, and images must be `https` URLs.
+`trackedContentRules.ts` holds the pure rule `detectContentType(url)`, which returns `youtube` for a YouTube video link and `null` for anything else.
### Overview summary (`overviewService.ts`)
@@ -134,7 +133,7 @@ A notice that hits a cap is skipped with a warning instead of failing, because t
## Shared analytics math (`backend/lib/analyticsMath.ts`)
-Pure helpers whose formulas are identical in the Instagram and Reddit analytics: `DAY_NAMES`, `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf`, `countWithinDays` (inclusive `<=`), `postFrequency` (posts per week and month over the dated span), `consistencyScore` (coefficient of variation, needs 3 values), `bestToAverageRatio` (virality), `pickHighest`, `monthKey` (local time), and `reportedCount` and `percentOfReportedViews` for counts a platform may hide. YouTube keeps its own recency (strict `<`) and weekly consistency formulas: `youtubeAnalytics.ts` imports `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf` and `reportedCount`, and `youtubeTrends.ts` imports `DAY_NAMES`, `DAY_MS`, `monthKey`, `reportedCount` and `percentOfReportedViews`.
+Pure helpers the Instagram analytics modules use: `DAY_NAMES`, `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf`, `countWithinDays` (inclusive `<=`), `postFrequency` (posts per week and month over the dated span), `consistencyScore` (coefficient of variation, needs 3 values), `bestToAverageRatio` (virality), `pickHighest`, `monthKey` (local time), and `reportedCount` and `percentOfReportedViews` for counts a platform may hide. YouTube keeps its own recency (strict `<`) and weekly consistency formulas: `youtubeAnalytics.ts` imports `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf` and `reportedCount`, and `youtubeTrends.ts` imports `DAY_NAMES`, `DAY_MS`, `monthKey`, `reportedCount` and `percentOfReportedViews`.
---
@@ -192,18 +191,14 @@ Views come from the media insights `views` metric (the replacement for `plays`,
### `safeAccount(account)`
-`safeAccount()` lives in `backend/lib/safeAccount.ts`. It removes every field listed in `SECRET_FIELDS` (`accessToken`, `cookie`, `encryptedPassword`, `encryptedTotpSecret`, `authToken`, `ct0`) and adds `hasCookie`, returning the `SafeAccount` type from `shared/types/domain.ts`:
+`safeAccount()` lives in `backend/lib/safeAccount.ts`. It removes every field listed in `SECRET_FIELDS` (today the Instagram `accessToken`) and returns the `SafeAccount` type from `shared/types/domain.ts`:
```ts
-const SECRET_FIELDS: (keyof Account)[] = ['accessToken', 'cookie', 'encryptedPassword', 'encryptedTotpSecret', 'authToken', 'ct0'];
-
-export function safeAccount(account: Account): SafeAccount {
- const copy: Partial<Account> & { hasCookie: boolean } = { ...account, hasCookie: !!account.cookie };
- for (const field of SECRET_FIELDS) delete copy[field];
- return copy as SafeAccount;
-}
+const SECRET_FIELDS: (keyof Account)[] = ['accessToken'];
```
+A new platform with its own secret field adds it to `SECRET_FIELDS` and to the `Omit` list of `SafeAccount` (`docs/features/NEW_INTEGRATION.md`, Step 3).
+
**This function must be applied to every account object before it leaves the backend.** Repositories return full `Account` objects; controllers call `safeAccount()` on every account they put in a response, and services that return accounts inside a larger result (the comparison, Instagram analytics) apply it themselves.
---
@@ -254,28 +249,9 @@ There is no barrel: services and tests import each module directly.
---
-## Reddit (`backend/services/reddit/`)
-
-### HTTP Client
-
-`redditApi.ts` holds the API code. All Reddit public JSON API calls go through `redditFetch(path, cookie, signal)`, which runs them through the Reddit circuit breaker (`lib/circuitBreaker.ts`), and `normalizeRedditPost()` maps each submitted post to the cached post shape. Requests include a descriptive `User-Agent` header (required by Reddit). When a cookie is passed, it is sent as `Cookie: reddit_session=<value>` for private account access and higher rate limits. A 404 becomes a `NotFoundError` (the user does not exist); a 403 (expired cookie), a 429 and other failures become an `UpstreamError` with a message that says what to do.
-
-### Key Functions
-
-| Function | Purpose |
-|---|---|
-| `fetchRedditProfile(username, cookie, signal)` | Fetches profile data from `/user/{username}/about.json` |
-| `fetchRedditPosts(username, cookie, limit, signal)` | Paginates submitted posts up to `limit` (default 100) via `/user/{username}/submitted.json` |
-| `computeRedditAnalytics(profile, posts)` | Lives in `redditAnalytics.ts` (re-exported by `redditApi.ts`); computes score stats, subreddit breakdown, media type distribution, posting time patterns, monthly breakdown, virality/consistency scores using the shared helpers in `lib/analyticsMath.ts` |
-| `fetchTrackedPostData(postUrl, cookie, signal)` | Fetches score, comments, and metadata for any public Reddit post URL using the `.json` trick; optionally uses a session cookie |
-
-### Credentials in responses
-
-Account responses for every platform pass through `safeAccount()` in `backend/lib/safeAccount.ts`, which strips the Reddit `cookie` along with the Instagram `accessToken` and sets `hasCookie` so the frontend can show session status.
-
-### No Worker secrets required
+## Credentials in responses
-Reddit integration requires no Worker secrets. The session cookie is a per-user credential stored in `accounts.data.cookie` (in the Supabase DB). It is read server-side by the Worker and never returned to the frontend.
+Account responses for every platform pass through `safeAccount()` in `backend/lib/safeAccount.ts`, which strips the Instagram `accessToken`. The token is read server-side by the Worker and never returned to the frontend.
---
@@ -304,9 +280,9 @@ For a new feature service:
## Fresh reads
-`youtubeAnalytics.channelVideos`, `instagramAnalytics.media` and `redditAnalytics.analytics` take an optional
+`youtubeAnalytics.channelVideos` and `instagramAnalytics.media` 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
+`validators/analyticsValidators.ts`. Both store `fetchedAt` with the cache entry, and
`overviewService` copies each cache entry's `fetchedAt` into its account summary.
diff --git a/docs/architecture/cloudflare/PAGES.md b/docs/architecture/cloudflare/PAGES.md
index fcad542..3e8c1f0 100644
--- a/docs/architecture/cloudflare/PAGES.md
+++ b/docs/architecture/cloudflare/PAGES.md
@@ -113,7 +113,7 @@ The marketing site and the docs are a second static SPA, built from the `site/`
`.github/workflows/deploy-site.yml` builds and uploads it with `wrangler pages deploy dist --project-name=twiligent-site` from `site/`; see `CI_CD.md`. Besides the Vite output, the build writes `sitemap.xml` and `llms.txt` into `site/dist`.
-**Redirects.** `site/public/_redirects` sends the app's old paths on this domain (`/login`, `/accounts`, `/settings`, `/videos`, `/shorts`, `/tracked-content`, `/reddit-posts`, `/reddit-tracked`, `/channel/*`, `/instagram/*`, `/reddit/*`) to the same path on `https://app.twiligent.ujjwal.fyi` with a 301, so bookmarks from before the move still work; `/upload` and `/publish` go to the app's `/publish`, and `/reels` and `/instagram` to its `/instagram` (#132). The build copies `index.html` to `dist/404.html` (`site/build/notFoundPage.ts`), so Pages answers an unknown path with a real 404 status while the site's router still draws its not found page. Because a top-level `404.html` turns off Pages' single-page fallback, `_redirects` rewrites `/docs` and `/docs/*` to `/` with a 200 (not to `/index.html`: Pages answers that path with its own 308 to `/`, so a rewrite to it never applies and docs pages answered 404, #138); a mistyped docs address therefore still answers 200, and a new top-level marketing page needs its own rewrite line.
+**Redirects.** `site/public/_redirects` sends the app's old paths on this domain (`/login`, `/accounts`, `/settings`, `/videos`, `/shorts`, `/tracked-content`, `/channel/*`, `/instagram/*`) to the same path on `https://app.twiligent.ujjwal.fyi` with a 301, so bookmarks from before the move still work; `/upload` and `/publish` go to the app's `/publish`, and `/reels` and `/instagram` to its `/instagram` (#132). The old pages of the platform removed in v2.0.0 (ADR-049) go to the app's Overview, and its old tracked posts path to Tracked content. The build copies `index.html` to `dist/404.html` (`site/build/notFoundPage.ts`), so Pages answers an unknown path with a real 404 status while the site's router still draws its not found page. Because a top-level `404.html` turns off Pages' single-page fallback, `_redirects` rewrites `/docs` and `/docs/*` to `/` with a 200 (not to `/index.html`: Pages answers that path with its own 308 to `/`, so a rewrite to it never applies and docs pages answered 404, #138); a mistyped docs address therefore still answers 200, and a new top-level marketing page needs its own rewrite line.
`site/public/robots.txt` allows every crawler and points at `https://twiligent.ujjwal.fyi/sitemap.xml`.
diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.md
index 8b49ed7..52cd325 100644
--- a/docs/architecture/data-flows/ANALYTICS.md
+++ b/docs/architecture/data-flows/ANALYTICS.md
@@ -153,93 +153,6 @@ Typed as `InstagramAnalytics` in `shared/types/instagram.ts`.
}
```
-## Reddit Analytics Flow
-
-```
-User navigates to /reddit/:id
- │
- ▼
-RedditAnalytics.tsx mounts -> api.getRedditAnalytics(id)
- -> GET /api/accounts/:id/reddit-analytics
- │
- ▼
- Worker: redditRoutes -> redditController.getRedditAnalytics
- -> redditAnalytics.analytics(userId, id) [services/redditAnalyticsService.ts]
- 1. accounts.findForUser(id, userId) - verify ownership
- -> 404 unless it is a Reddit account, 400 without a stored cookie or username
- 2. cache.getReddit(userId, id): key reddit:{userId}:{accountId}
- -> skipped when ?fresh=1 (the page's Refresh button)
- -> cache hit: return immediately, with the fetchedAt it was stored with
- -> cache miss: continue
- 3. Fetch from Reddit public JSON API (with the stored session cookie):
- a. GET /user/{username}/about.json
- -> profile: totalKarma, postKarma, commentKarma, awardeeKarma, iconUrl, createdAt
- b. GET /user/{username}/submitted.json?limit=100&sort=new
- -> up to 100 posts
- 4. computeRedditAnalytics(profile, posts)
- -> score stats, subreddit breakdown, timing analysis
- 5. cache.setReddit(userId, id, result)
- 6. Return { profile, analytics, posts } (RedditCacheData)
-```
-
-### computeRedditAnalytics() Output (partial)
-
-Typed as `RedditAnalytics` in `shared/types/reddit.ts`.
-
-```ts
-{
- fetchedPosts: 100,
- totalScore: 45000,
- avgScore: 450,
- medianScore: 120,
- totalComments: 3200,
- avgComments: 32,
- avgUpvoteRatio: 91.4, // percentage
- totalAwards: 18,
- avgAwards: 0.18,
- topPosts: [ /* top 10 by score */ ],
- worstPosts: [ /* bottom 5 by score */ ],
- subredditBreakdown: [
- { subreddit: 'programming', posts: 40, totalScore: 20000, avgScore: 500, avgComments: 45 },
- // ...
- ],
- mediaTypeDistribution: { text: 60, link: 25, image: 10, video: 5 },
- postsByDayOfWeek: [ /* 7 entries with avgScore and post count per day */ ],
- postsByHour: [ /* 24 entries with avgScore per hour */ ],
- bestPostingDay: 'Tuesday',
- bestPostingHour: '14:00',
- monthlyBreakdown: [
- { month: '2025-06', posts: 8, score: 3600, avgScore: 450 },
- // ...
- ],
- postsLast7Days: 2,
- postsLast30Days: 8,
- postsLast90Days: 24,
- postFrequency: { perWeek: 1.8, perMonth: 7.6 },
- viralityScore: 4.2, // peak / average score ratio
- consistencyScore: 68, // 0-100, higher = more uniform performance
-}
-```
-
-### Per-post fields (in posts array and topPosts)
-
-Typed as `RedditPost` in `shared/types/reddit.ts`.
-
-```ts
-{
- id, title, subreddit, subredditPrefixed,
- score, upvoteRatio, numComments,
- url, permalink, thumbnail,
- mediaType, // 'text' | 'image' | 'video' | 'link'
- isSelf, isVideo, isNsfw,
- createdAt, // ISO string
- flair,
- awardsCount, // total_awards_received from Reddit API
-}
-```
-
-Note: Reddit disabled `view_count` from their API in December 2018. The field always returns `null` regardless of authentication method. Views are not available for Reddit posts.
-
## Overview Dashboard (Cross-Account)
```
@@ -263,43 +176,27 @@ are chained: each waits 4, 8 and then 16 seconds after the previous response, so
| Metric | Formula |
|---|---|
-| Total Audience | YouTube subscribers + Instagram followers + Reddit account karma |
-| Total Views | YouTube channel views + Instagram views (cache, reels + posts + videos) + tracked YouTube video views + manually entered Reddit post views |
-| Total Content | YouTube videos + Instagram media count (profile) + Reddit account posts (cache) + tracked items |
-| Total Comments | cache comments (YouTube + Instagram + Reddit) + tracked item comments |
-| Total Likes | Reddit karma (account + tracked) + YouTube likes (cache + tracked) + Instagram likes |
-
-Tracked items are third-party URLs the user monitors, never their own connected-account
-content, so cache totals and tracked totals are disjoint and are summed rather than
-one taking precedence over the other.
+| Total Audience | YouTube subscribers + Instagram followers |
+| Total Views | YouTube channel views + Instagram views (cache, reels + posts + videos) + tracked YouTube video views |
+| Total Content | YouTube videos + Instagram media count (profile) + tracked items |
+| Total Comments | cache comments (YouTube + Instagram) + tracked item comments |
+| Total Likes | YouTube likes (cache + tracked) + Instagram likes |
-Tracked Reddit post karma counts toward Total Likes, not Total Audience - a monitored post is
-content, not an audience the user owns. Connected-account karma does count toward Total
-Audience as that account's reputation.
+Tracked items are YouTube videos the user monitors, not their connected accounts' own uploads, so
+cache totals and tracked totals are disjoint and are summed rather than one taking precedence over
+the other. The Likes tab shows the total, YouTube and Instagram likes, and a chart of likes by
+tracked video; the Comments tab shows YouTube and Instagram comments.
### Tracked content views
-Reddit removed `view_count` from its API in December 2018, so a tracked Reddit post's views are
-whatever the user typed into the edit dialog, stored as `data.manualViews`. `trackedViews()` in
-`frontend/src/utils/trackedContent.ts` is the single place that decides which field to read:
-`viewCount` for YouTube items, `manualViews` for Reddit items. Every view total in the UI goes
-through it, so a post with no manual figure contributes 0 rather than breaking the sum.
-
-`hasTrackedViews()` distinguishes "no figure recorded" from a real zero, so tables can render a
-dash and a "Set" action instead of a misleading `0`.
+Tracked items are YouTube videos only, so their views are the `viewCount` the YouTube API reports,
+fetched when the item is added and on each manual refresh.
### Audience Comparison chart
-Categories plot **karma only**, never karma plus views. Views are a reach metric an order of
-magnitude larger than karma; adding them would push a category far above the accounts it sits
-beside on the same axis and misrepresent its audience. Category view totals belong in the Views
-tab, where they are compared against other view figures.
-
-### Naming
-
-Reddit's API returns a post's net upvotes as `score`. Every aggregate the frontend derives from
-it is named and labelled **karma**. The word "score" is reserved for the computed Virality Score
-and Consistency Score indices, which are unrelated to karma.
+The audience chart compares subscribers and followers per connected account. Tracked categories do
+not appear on it: a category is content the user monitors, not an audience the user owns. Category
+view totals belong in the Views tab, where they are compared against other view figures.
## How the analytics pages present data
@@ -308,7 +205,7 @@ These rules come from the UI/UX guide (issue #132) and apply to every analytics
- **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.
+ the cache.
- **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.
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index 37c973a..244b6cf 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -58,23 +58,25 @@ To change the schema, follow `docs/features/NEW_DATABASE_TABLE.md` (Write the Mi
## Table: `accounts`
-Stores connected YouTube channels, Instagram accounts and Reddit profiles.
+Stores connected YouTube channels and Instagram accounts.
| Column | Type | Nullable | Description |
|---|---|---|---|
| `id` | text | NOT NULL | PK. A UUID from `newRowId()` (`crypto.randomUUID()`); older rows keep their earlier ids |
| `user_id` | uuid | NOT NULL | FK -> `auth.users.id` ON DELETE CASCADE. All user-scoped queries filter on this |
-| `platform` | text | NOT NULL | `'youtube'`, `'instagram'` or `'reddit'` |
+| `platform` | text | NOT NULL | `'youtube'` or `'instagram'` |
| `data` | jsonb | NOT NULL DEFAULT `'{}'` | All platform-specific fields (see below) |
| `created_at` | timestamptz | NOT NULL DEFAULT now() | When the account was connected. The list order |
| `updated_at` | timestamptz | NOT NULL DEFAULT now() | Set by the trigger on every update |
| Constraint | Rule |
|---|---|
-| `accounts_platform_check` | `platform in ('youtube', 'instagram', 'reddit')` |
+| `accounts_platform_check` | `platform` is `'youtube'` or `'instagram'`, or the value of the platform removed in v2.0.0 (below) |
| `accounts_data_check` | `data` is a JSON object |
| `accounts_id_user_id_key` | `unique (id, user_id)`, so posts can reference an account together with its owner |
-| `accounts_identity_key` | Unique index on `(user_id, platform, identity)`, where the identity is `data ->> 'channelId'` for YouTube, `data ->> 'username'` for Reddit and `data ->> 'igUserId'` for Instagram. Two adds of the same account at the same moment store one row; the other gets the usual 409 |
+| `accounts_identity_key` | Unique index on `(user_id, platform, identity)`, where the identity is `data ->> 'channelId'` for YouTube and `data ->> 'igUserId'` for Instagram. Two adds of the same account at the same moment store one row; the other gets the usual 409 |
+
+The app reads and writes only YouTube and Instagram accounts: `accountRepository` selects rows whose `platform` is `youtube` or `instagram`. The check and the identity index still allow a value from a platform removed in v2.0.0, and rows of that platform may remain in the table, unseen by the app. The cleanup in #145 removes those rows, narrows the check and rebuilds the index (see `docs/platform-v2/DATABASE_MIGRATION.md` and ADR-049 in `DECISIONS.md`).
### `data` jsonb shape for YouTube accounts
@@ -110,7 +112,7 @@ Stores connected YouTube channels, Instagram accounts and Reddit profiles.
}
```
-**Critical:** `accessToken` (and a Reddit account's `cookie`) is always stripped by `safeAccount()` before being returned in any API response. It is intentionally stored server-side for use by the publishing and token-refresh pipelines.
+**Critical:** `accessToken` is always stripped by `safeAccount()` before being returned in any API response. It is intentionally stored server-side for use by the publishing and token-refresh pipelines.
---
@@ -217,68 +219,31 @@ A claim is one UPDATE that sets `status = 'publishing'`, `claimed_at = now()` an
## Table: `tracked_posts`
-Stores Reddit posts and YouTube videos the user wants to monitor. Previously Reddit-only; extended to support YouTube via the `content_type` column.
+Stores the YouTube videos the user wants to monitor. The app tracks YouTube videos only: `trackedPostRepository` reads rows whose `content_type` is `youtube`, writes `content_type: 'youtube'` on every insert and never writes `account_id`.
| Column | Type | Nullable | Description |
|---|---|---|---|
| `id` | text | NOT NULL | PK. A UUID from `newRowId()`; older rows keep their earlier ids |
| `user_id` | uuid | NOT NULL | FK -> `auth.users.id` ON DELETE CASCADE |
-| `account_id` | text | NULL | With `user_id`, FK -> `accounts (id, user_id)` ON DELETE SET NULL (`account_id`). Reddit only: which account's cookie to use |
-| `url` | text | NOT NULL | Full URL of the Reddit post or YouTube video |
+| `account_id` | text | NULL | With `user_id`, FK -> `accounts (id, user_id)` ON DELETE SET NULL (`account_id`). No longer written; the cleanup in #145 drops it |
+| `url` | text | NOT NULL | Full URL of the YouTube video |
| `label` | text | NOT NULL DEFAULT '' | User-defined name for the item |
-| `category` | text | NOT NULL DEFAULT '' | User-defined grouping label; shared across Reddit and YouTube items |
-| `content_type` | text | NOT NULL DEFAULT 'reddit' | `'reddit'` or `'youtube'` |
+| `category` | text | NOT NULL DEFAULT '' | User-defined grouping label |
+| `content_type` | text | NOT NULL DEFAULT (see below) | `'youtube'`. The app always sets it, so the default, the removed platform's value, is never used |
| `created_at` | timestamptz | NOT NULL DEFAULT now() | When the user added the item |
| `updated_at` | timestamptz | NOT NULL DEFAULT now() | Set by the trigger on every update; the code no longer sets it |
| `data` | jsonb | NULL | Cached data fetched from the platform API, stored in the same insert that creates the row (see below) |
| Constraint | Rule |
|---|---|
-| `tracked_posts_content_type_check` | `content_type in ('reddit', 'youtube')` |
-| `tracked_posts_account_check` | Only Reddit items have an account: `content_type = 'reddit' or account_id is null` |
+| `tracked_posts_content_type_check` | `content_type` is `'youtube'`, or the value of the platform removed in v2.0.0 |
+| `tracked_posts_account_check` | Only items of the removed platform may have an account, so a YouTube item's `account_id` is null |
| `tracked_posts_data_check` | `data` is null or a JSON object |
| `tracked_posts_account_fkey` | `(account_id, user_id)` -> `accounts (id, user_id)` ON DELETE SET NULL (`account_id`) |
Removing an account keeps its tracked items and clears only their `account_id`. The column list on SET NULL needs Postgres 15 or later; a plain SET NULL would try to clear `user_id` too.
-### `data` jsonb shape for Reddit items
-
-Populated by `fetchTrackedPostData()` in `backend/services/reddit/redditApi.ts`:
-
-```json
-{
- "contentType": "reddit",
- "title": "Post title from Reddit",
- "subreddit": "programming",
- "subredditPrefixed": "r/programming",
- "score": 1234,
- "upvoteRatio": 0.97,
- "numComments": 56,
- "permalink": "https://reddit.com/r/programming/comments/abc123/...",
- "lastFetchedAt": "2026-08-04T10:00:00Z",
- "manualViews": 12500,
- "imageUrl": "https://res.cloudinary.com/mycloud/image/upload/v1/abc.jpg"
-}
-```
-
-`manualViews` and `imageUrl` are the two keys in `data` that are not fetched from Reddit.
-Both are set by the user through `PUT /api/tracked-content/:id` and are `null` or absent
-until then.
-
-- `manualViews` - Reddit removed `view_count` from its API in December 2018, so view counts
- can only be entered by hand.
-- `imageUrl` - Reddit's public JSON API carries no usable thumbnail, so the user uploads a
- screenshot. The browser posts it directly to Cloudinary and only the returned `secure_url`
- reaches the Worker, which stores it after checking the URL parses and uses `https:`. That
- check matters because the value is rendered straight into an `img src`.
-
-Because of this, the refresh route calls `patchDataForUser()` rather than
-`updateForUser({ data })` - the former merges freshly fetched keys into the existing
-blob in the database (`merge_tracked_post_data`), so a manually entered view count survives
-a refresh that lands at the same moment. Anything writing to `data` for a Reddit item must
-merge, never replace.
-
-Both keys are rejected for YouTube items, which already carry a real `viewCount` and `thumbnail`.
+The default, the two checks and `account_id` are left from the platform removed in v2.0.0, and its tracked items may remain in the table, unseen by the app. The cleanup in #145 deletes those rows, makes `'youtube'` the only allowed value and the default, and drops `tracked_posts_account_check`, `tracked_posts_account_fkey` and `account_id` (see `docs/platform-v2/DATABASE_MIGRATION.md` and ADR-049 in `DECISIONS.md`).
### `data` jsonb shape for YouTube items
@@ -301,7 +266,7 @@ Populated by `fetchTrackedYouTubeData()` in `backend/services/youtube/youtubeTra
}
```
-Data is fetched on create and on manual refresh only. Not re-fetched on every GET.
+Data is fetched on create and on manual refresh only. Not re-fetched on every GET. A refresh merges the fetched keys into `data` with `patchDataForUser()` (`merge_tracked_post_data`) rather than replacing the blob, so anything writing to `data` merges, never replaces.
---
diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.md
index 6e3c338..2535d84 100644
--- a/docs/architecture/database/SECURITY.md
+++ b/docs/architecture/database/SECURITY.md
@@ -14,10 +14,10 @@ The merge functions follow the same rule: the `...ForUser` repository methods pa
## Ownership of Referenced Accounts
-A scheduled post names the account it publishes to, and a tracked Reddit item names the account whose cookie reads it. Both are checked twice:
+A scheduled post names the account it publishes to. It is checked twice:
-1. **In the service.** `scheduledPostService.create` loads the account with `accounts.findForUser(accountId, userId)` and passes it to `publishableAccount()`: another user's account, a missing one or one that is not Instagram answers 404 `Instagram account not found`, and one with no token answers 400 `No Instagram access token stored - reconnect this account`. `trackedContentService.update` refuses an account on a YouTube item (400) and answers 404 `Reddit account not found` for an account that is not one of the user's Reddit accounts.
-2. **In the database.** `scheduled_posts`, `tracked_posts` and the six automation tables reference `accounts (id, user_id)` with a composite foreign key, so a row whose `account_id` belongs to another user cannot be written, whatever the code does. A follow-up is created only by `automation_followups_for_messages`, which takes its user and account from the waiting comment, never from the message, so a message cannot reach another account's rule. A public reply is created only by `store_automation_comments`, which takes its user, account and comment from the stored comment row.
+1. **In the service.** `scheduledPostService.create` loads the account with `accounts.findForUser(accountId, userId)` and passes it to `publishableAccount()`: another user's account, a missing one or one that is not Instagram answers 404 `Instagram account not found`, and one with no token answers 400 `No Instagram access token stored - reconnect this account`.
+2. **In the database.** `scheduled_posts`, `tracked_posts` and the six automation tables reference `accounts (id, user_id)` with a composite foreign key, so a row whose `account_id` belongs to another user cannot be written, whatever the code does. Tracked items name no account: the app tracks YouTube videos only and never writes `tracked_posts.account_id`, which the cleanup in #145 drops (`docs/platform-v2/DATABASE_MIGRATION.md`). A follow-up is created only by `automation_followups_for_messages`, which takes its user and account from the waiting comment, never from the message, so a message cannot reach another account's rule. A public reply is created only by `store_automation_comments`, which takes its user, account and comment from the stored comment row.
An automation rule is created only after `accounts.findForUser(accountId, userId)` returns one of the user's Instagram accounts (404 otherwise), and a rule never moves to another account. Pausing, subscribing and retrying load the account or the item with the user's id first.
@@ -28,7 +28,7 @@ Row ids are UUIDs from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.t
See `DECISIONS.md` ADR-011 and ADR-038 for the full reasoning. Summary:
- Cron handlers (scheduler, token refresh) need to query across all users - they cannot be scoped to a single JWT
- Using the service-role key with application-layer filtering achieves the same isolation with less complexity
-- A policy that lets a signed-in user reach their own rows would also let them read their raw Instagram tokens and Reddit cookies and write rows the API would refuse. The browser has no reason to touch the tables, so it gets no access at all
+- A policy that lets a signed-in user reach their own rows would also let them read their raw Instagram tokens and write rows the API would refuse. The browser has no reason to touch the tables, so it gets no access at all
## Key Hierarchy
@@ -57,7 +57,7 @@ To check a live instance, call the Data API with the anon key (`GET <SUPABASE_UR
### What was wrong before
-Before the migrations, production had drifted from this model. The tables had the policies `users_own_accounts`, `users_own_settings` and `users_own_posts` (`for all using (auth.uid() = user_id)`) and full table grants to `anon` and `authenticated`. A signed-in user could read their raw Instagram tokens and Reddit cookies through the Data API and write rows directly, for example a scheduled post naming another user's account, which the scheduler would then publish to. `scheduled_posts` also had no foreign key to `accounts`, and the API never checked scheduled post account ownership. The migrations removed the policies and grants and added the composite keys; the service checks above were added at the same time.
+Before the migrations, production had drifted from this model. The tables had the policies `users_own_accounts`, `users_own_settings` and `users_own_posts` (`for all using (auth.uid() = user_id)`) and full table grants to `anon` and `authenticated`. A signed-in user could read their raw Instagram tokens and other stored credentials through the Data API and write rows directly, for example a scheduled post naming another user's account, which the scheduler would then publish to. `scheduled_posts` also had no foreign key to `accounts`, and the API never checked scheduled post account ownership. The migrations removed the policies and grants and added the composite keys; the service checks above were added at the same time.
## Signups
@@ -110,5 +110,5 @@ When reviewing security, check these files:
- `backend/controllers/` and `backend/services/` - the `userId` passed to a repository always comes from `c.get('userId')`, never from the body or query
- `backend/lib/safeAccount.ts` - `safeAccount()` definition; it strips every stored credential for all platforms
- `supabase/migrations/` - no migration grants anything to `anon` or `authenticated`, and every function revokes execute from them
-- `backend/services/scheduledPostService.ts` and `trackedContentService.ts` - an account named in a request is loaded with `findForUser` before it is stored
+- `backend/services/scheduledPostService.ts` - an account named in a request is loaded with `findForUser` before it is stored
- All controllers in `backend/controllers/` - verify `safeAccount()` is called on every account response
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index a0bb9bc..490b166 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -71,10 +71,9 @@ The response types are imported with `import type` from `@shared/types/*.ts`, so
### Fresh reads
-`getVideos(id, fresh?)`, `getIGMedia(id, fresh?)` and `getRedditAnalytics(id, fresh?)` read the server's cache by
-default. Passing `fresh = true` adds `?fresh=1`, which skips the cache; pages send it only from their Refresh button,
-so opening a page never spends platform quota by itself. The Reddit posts pages read `getRedditAnalytics`, which
-carries the posts with their `fetchedAt`; the old `getRedditPosts` method was removed.
+`getVideos(id, fresh?)` and `getIGMedia(id, fresh?)` read the server's cache by default. Passing `fresh = true`
+adds `?fresh=1`, which skips the cache; pages send it only from their Refresh button, so opening a page never
+spends platform quota by itself.
## Adding a New API Method
@@ -149,36 +148,25 @@ The types are in `shared/types/automation.ts`. Activity and stats take their fil
## Tracked Content Methods
-Added to the `api` object in `api.ts`. Handles both Reddit posts and YouTube videos:
+Added to the `api` object in `api.ts`. Tracked content is YouTube videos only:
```ts
getTrackedContent: () => request<TrackedContentItem[]>('/tracked-content'),
-addTrackedContent: (url: string, accountId: string | null, label: string, category: string) => request<TrackedContentItem>('/tracked-content', { method: 'POST', body: JSON.stringify({ url, accountId, label, category }) }),
+addTrackedContent: (url: string, label: string, category: string) => request<TrackedContentItem>('/tracked-content', { method: 'POST', body: JSON.stringify({ url, label, category }) }),
updateTrackedContent: (id: string, updates: TrackedContentUpdateRequest) => request<TrackedContentItem>(`/tracked-content/${id}`, { method: 'PUT', body: JSON.stringify(updates) }),
deleteTrackedContent: (id: string) => request<SuccessResponse>(`/tracked-content/${id}`, { method: 'DELETE' }),
refreshTrackedContent: (id: string) => request<TrackedContentItem>(`/tracked-content/${id}/refresh`, { method: 'POST' }),
```
-`accountId` may be `null`. For YouTube items, `accountId` is always `null` (fetched via the server's `YOUTUBE_API_KEY`). For Reddit items, `accountId` is optional and refers to a Reddit account whose cookie improves datacenter IP access.
+The Worker reads each video with its own `YOUTUBE_API_KEY`, so an item names no account. A link that is not a YouTube
+video answers 400 `Only YouTube video links can be tracked. Paste a youtube.com or youtu.be link.`
`updateTrackedContent` takes a partial object, so only the keys present are changed. Accepted
-keys are `label`, `category`, `accountId`, `manualViews`, and `imageUrl`. `manualViews` and
-`imageUrl` are Reddit-only and sending either for a YouTube item returns a 400; pass `null` to
-clear a previously set value.
-
-`imageUrl` must already be a hosted `https:` URL. The Worker never accepts binary uploads, so
-the browser posts the file straight to Cloudinary with `api.uploadImage()` (below) and
-sends only the returned `secure_url`.
+keys are `label` and `category`.
## Cloudinary Uploads
-These are the only calls in `api.ts` that do not go to the Worker.
-
-```ts
-uploadImage(file: File, cloudConfig: CloudinaryUploadConfig): Promise<string>
-```
-
-Used for tracked item screenshots. It posts the image with `fetch` to `https://api.cloudinary.com/v1_1/<cloudName>/image/upload` and resolves with `secure_url`. It throws an `Error` with Cloudinary's own message, or `'Cloudinary did not return an image URL'`, and network or JSON failures reject with the browser's own error. The tracked content editor shows that `(err as Error).message` after `Image upload failed.` in an error toast.
+This is the only call in `api.ts` that does not go to the Worker.
```ts
uploadToCloudinary(file: File, cloudConfig: CloudinaryUploadConfig, { onProgress }: UploadOptions = {}): Promise<string>
@@ -200,8 +188,7 @@ Failures reject with an `UploadError` (an `Error` with a `reason` of type `Uploa
| `rejected` | Cloudinary answered with a non-2xx status | `Upload failed` | `cloudinaryMessage` (Cloudinary's `error.message`, if any) or `parseMessage` (the body was not JSON) |
The bulk upload shows the default messages. The single post flow maps the error to its own
-wording (`singleUploadMessage` in `features/publishing/publishHelpers.ts`). Tracked Content does
-not use this function: its screenshots go through `uploadImage()` above.
+wording (`singleUploadMessage` in `features/publishing/publishHelpers.ts`).
## Authentication
diff --git a/docs/architecture/frontend/CONTEXTS.md b/docs/architecture/frontend/CONTEXTS.md
index 5c8cbc7..9d1b657 100644
--- a/docs/architecture/frontend/CONTEXTS.md
+++ b/docs/architecture/frontend/CONTEXTS.md
@@ -71,7 +71,7 @@ The value is typed as `AppContextValue`, exported from `AppContext.tsx`. `useApp
| Value | Type | Description |
|---|---|---|
-| `accounts` | `AppAccount[]` | All connected accounts (YouTube, Instagram, Reddit), normalized via `normalizeAccount()` |
+| `accounts` | `AppAccount[]` | All connected accounts (YouTube, Instagram), normalized via `normalizeAccount()` |
| `setAccounts` | `Dispatch<SetStateAction<AppAccount[]>>` | Direct setter (used by AccountManager after add/delete) |
| `loading` | `boolean` | True during `refreshAll()` only |
| `showToast(message, severity?)` | `(message: string, severity?: ToastSeverity) => void` | Shows a Sonner toast. `ToastSeverity`: `'success'` (default), `'error'`, `'warning'`, `'info'` |
@@ -98,7 +98,7 @@ All feature pages and layout components use `useAppContext()`:
```ts
{
id: 'account-id',
- platform: 'youtube' | 'instagram' | 'reddit',
+ platform: 'youtube' | 'instagram',
// YouTube fields:
channelId: '...',
title: '...',
@@ -112,10 +112,7 @@ All feature pages and layout components use `useAppContext()`:
username: '...',
followersCount: 5000,
mediaCount: 200,
- // Reddit fields:
- totalKarma: 1234,
- hasCookie: true,
- // Note: accessToken and cookie are NEVER present - stripped by safeAccount() on the backend
+ // Note: accessToken is NEVER present - stripped by safeAccount() on the backend
}
```
@@ -131,11 +128,11 @@ Hooks used by more than one feature. Hooks used by a single feature live in that
| `useCommandPaletteShortcut(setOpen)` | `use-command-palette-shortcut.ts` | Ctrl+K / Cmd+K toggle for the command palette |
| `useSmoothTheme()` | `use-smooth-theme.ts` | Theme switch as one cross-fade |
| `useCloudinaryConfig(reloadKey)` | `use-cloudinary-config.ts` | Loads `api.getCloudinaryConfig()`; returns the config or `null` |
-| `useAccountAnalytics(account, fetchAnalytics, label)` | `use-account-analytics.ts` | Loads one account's analytics and refreshes it; used by Instagram and Reddit analytics |
+| `useAccountAnalytics(account, fetchAnalytics, label)` | `use-account-analytics.ts` | Loads one account's analytics and refreshes it; used by Instagram analytics |
-`useCloudinaryConfig` sets the config only when the response has `success: true`. A failed request keeps the previous value (initially `null`), and pages show a missing config as an alert or a disabled upload field. The request runs again whenever `reloadKey` changes: the Publish page passes `accounts`, Tracked Content passes nothing and loads once.
+`useCloudinaryConfig` sets the config only when the response has `success: true`. A failed request keeps the previous value (initially `null`), and pages show a missing config as an alert or a disabled upload field. The request runs again whenever `reloadKey` changes: the Publish page passes `accounts`.
-`useAccountAnalytics` returns `{ loading, profile, analytics, refreshing, handleRefresh }`. Pass a stable `api` method (`api.getIGAnalytics`, `api.getRedditAnalytics`), never an inline arrow: the load is keyed on the account id and that method, so a background account refresh does not refetch analytics. `label` names the platform in the toasts (`Couldn't load Instagram analytics.`, `Instagram account refreshed`). `handleRefresh` calls `api.refreshAccount()` and then loads the analytics again.
+`useAccountAnalytics` returns `{ loading, profile, analytics, refreshing, handleRefresh }`. Pass a stable `api` method (`api.getIGAnalytics`), never an inline arrow: the load is keyed on the account id and that method, so a background account refresh does not refetch analytics. `label` names the platform in the toasts (`Couldn't load Instagram analytics.`, `Instagram account refreshed`). `handleRefresh` calls `api.refreshAccount()` and then loads the analytics again.
---
diff --git a/docs/architecture/frontend/DESIGN_SYSTEM.md b/docs/architecture/frontend/DESIGN_SYSTEM.md
index a690770..99050fb 100644
--- a/docs/architecture/frontend/DESIGN_SYSTEM.md
+++ b/docs/architecture/frontend/DESIGN_SYSTEM.md
@@ -73,8 +73,8 @@ Shared components live in `frontend/src/components/`. Reach for these before wri
| Pattern | Pages | Shape |
|---|---|---|
| Home | Overview | Display greeting, quick-action tiles, selectable metric tiles, detail per metric |
-| Library | Videos, Shorts, Instagram content, Reddit posts, Tracked content | Search, filter chips, quiet table or card grid, pager |
-| Detail | YouTube channel, Instagram account, Reddit account, Category | Back link, avatar header, metric grids, underline tabs or sections |
+| Library | Videos, Shorts, Instagram content, Tracked content | Search, filter chips, quiet table or card grid, pager |
+| Detail | YouTube channel, Instagram account, Category | Back link, avatar header, metric grids, underline tabs or sections |
| Create | Accounts (add flow) | Choice cards, then a form step, then review before commit |
| Working surface | Publish | Main editor on the left, sticky `DetailPanel` with settings and the primary action on the right |
| Settings | Settings | Sections with a label column and content column |
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 9cfdc71..e7662f1 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -9,7 +9,6 @@ frontend/src/
│ ├── MetricAreaChart.tsx <- Shared Intent UI area chart for single-metric comparisons
│ ├── ChartPanel.tsx, ChartFigure.tsx <- Titled chart container with an empty state; the chart's screen-reader name and description
│ ├── ExactTooltip.tsx, DonutChart.tsx <- Intent's tooltip with exact values; a ring for parts of a whole
-│ ├── ImageLightbox.tsx <- Thumbnail that opens the full image in a Dialog
│ ├── AccountSelect.tsx <- Instagram account picker with avatars (Publish, Automations)
│ ├── RowAction.tsx <- Icon button with a tooltip for table and list rows (Tracked content, Automations)
│ └── DocsRedirect.tsx <- The /docs/* route: replaces the location with the same page on the public docs
@@ -38,30 +37,21 @@ frontend/src/
│ │ │ ├── useOverviewData.ts <- Loads api.getOverview() and re-polls while accounts are syncing
│ │ │ ├── useOverviewStats.ts <- Memoized totals, rankings and chart rows
│ │ │ └── overviewStats.ts, overviewTrackedStats.ts, overviewCharts.ts, overviewLabels.ts, greeting.ts <- Pure helpers with *.test.ts
-│ │ ├── reddit/
-│ │ │ ├── RedditAnalytics.tsx <- Page: Reddit account analytics (loads through useAccountAnalytics)
-│ │ │ ├── RedditHeader.tsx, RedditKarmaSummary.tsx, RedditKarmaCharts.tsx, RedditStatPanels.tsx
-│ │ │ ├── RedditTimingCharts.tsx, RedditSubredditTable.tsx, RedditTopPostsTable.tsx
-│ │ │ ├── redditAnalyticsData.ts <- Pure chart rows and stat lists (redditAnalyticsData.test.ts)
-│ │ │ ├── RedditPosts.tsx <- Per-account post explorer
-│ │ │ ├── RedditPostsAll.tsx <- Global post explorer (all Reddit accounts)
-│ │ │ ├── RedditPostFilters.tsx, RedditPostTable.tsx <- Filters and table shared by both post explorers
-│ │ │ └── redditPostUtils.ts <- Shared sort options, filtering and sorting
│ │ └── tracked/
-│ │ ├── TrackedContent.tsx <- Page: tracked Reddit posts and YouTube videos
+│ │ ├── TrackedContent.tsx <- Page: tracked YouTube videos
│ │ ├── TrackedMetrics.tsx, TrackedFilters.tsx, BulkCategoryBar.tsx, TrackedTable.tsx, TrackedRow.tsx, TrackedThumbnail.tsx
-│ │ ├── AddTrackedDialog.tsx, EditTrackedDialog.tsx, TrackedImageField.tsx, CategoryPicker.tsx
+│ │ ├── AddTrackedDialog.tsx, EditTrackedDialog.tsx, CategoryPicker.tsx
│ │ ├── useTrackedItems.ts, useTrackedFilters.ts, useTrackedSelection.ts, useBulkCategory.ts
-│ │ ├── useTrackedDelete.ts, useAddTracked.ts, useTrackedEditor.ts <- Delete, add form, edit and image upload
+│ │ ├── useTrackedDelete.ts, useAddTracked.ts, useTrackedEditor.ts <- Delete, add form and edit
│ │ ├── trackedList.ts <- Pure sort, filter, stats and form helpers (trackedList.test.ts)
│ │ ├── TrackedCategory.tsx <- Page: per-category analytics for tracked content
-│ │ ├── CategoryYouTubeSection.tsx, CategoryRedditSection.tsx, NumberCell.tsx, OpenLink.tsx
+│ │ ├── CategoryYouTubeSection.tsx, NumberCell.tsx, OpenLink.tsx
│ │ └── trackedCategoryStats.ts <- Pure per-category totals and labels (trackedCategoryStats.test.ts)
│ ├── accounts/
│ │ ├── AccountManager.tsx <- Page: connected accounts by platform, refresh and remove
│ │ ├── AccountSection.tsx, AccountCard.tsx, AccountsEmptyState.tsx
│ │ ├── AddAccountDialog.tsx <- Platform picker, per-platform fields and footer actions
-│ │ ├── YouTubeAccountFields.tsx, RedditAccountFields.tsx, AddAccountFooter.tsx
+│ │ ├── YouTubeAccountFields.tsx, AddAccountFooter.tsx
│ │ ├── useAddAccount.ts <- Add dialog state; Back keeps typed fields, Cancel clears them
│ │ ├── useAccountRefresh.ts, useAccountDelete.ts
│ │ ├── useInstagramOAuthReturn.ts <- Reads ?ig_connected, ?ig_error and ?add once, then clears them
@@ -127,13 +117,9 @@ The user and self-hosting documentation is not part of the app. It lives in the
## Metric Naming
-Reddit exposes a post's net upvotes as `score` in its JSON API. In the UI this is always
-labelled **karma**, never "score", so it matches the vocabulary Reddit shows its own users.
-The raw `score` field name is kept when reading API responses; every aggregate derived from
-it is named `karma` (`rdKarma`, `avgKarma`, `redditKarma`).
-
-"Virality Score" and "Consistency Score" are separate computed indices, not karma, and keep
-the word "score".
+The computed indices `viralityScore` and `consistencyScore` (YouTube and Instagram analytics) are labelled
+**Virality** and **Consistency** in the UI, with the value's unit (`2.4x`, `78 of 100`) in place of the word
+"score".
## Shared Chart Components
@@ -159,7 +145,7 @@ data; nothing extra is shown on screen.
## Shared Library Pieces
-The library pages (Videos, Shorts, Instagram content, Reddit posts, Tracked content) are built from the same parts:
+The library pages (Videos, Shorts, Instagram content, Tracked content) are built from the same parts:
| Piece | Job |
|---|---|
@@ -170,20 +156,6 @@ The library pages (Videos, Shorts, Instagram content, Reddit posts, Tracked cont
| `FailedSourcesAlert`, `DataFreshness`, `RefreshButton` | Accounts that failed to load, the data's age, and the one Refresh control |
| `lib/metricIcons.ts` | One icon per meaning (`METRIC_ICONS`, `IG_TYPE_ICONS`) |
-## Image Lightbox
-
-`components/ImageLightbox.tsx` renders a thumbnail that opens the full image in a shadcn
-`Dialog`. Used for tracked Reddit post images, which have no platform thumbnail:
-
-```tsx
-<ImageLightbox src={item.imageUrl} alt={item.title} thumbClassName="size-14" />
-```
-
-Base UI supports nested dialogs, so this works inside the Tracked Content edit dialog. Child
-dialogs skip the backdrop and only the topmost one responds to Escape and outside clicks.
-
-Note the Base UI composition rule: the trigger takes a `render` prop, not `asChild`.
-
## Feature Conventions
### One directory per feature domain
@@ -229,15 +201,12 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo
| Feature | Path | Description |
|---|---|---|
-| Overview | `/` | Aggregate KPIs across all connected accounts (YouTube, Instagram, Reddit); six metric tabs, each with area charts |
-| Accounts | `/accounts` | Connect/disconnect accounts (YouTube, Instagram, Reddit) |
+| Overview | `/` | Aggregate KPIs across all connected accounts (YouTube, Instagram); six metric tabs, each with area charts |
+| Accounts | `/accounts` | Connect/disconnect accounts (YouTube, Instagram) |
| Channel Analytics | `/channel/:id` | YouTube analytics for one channel |
| Instagram Analytics | `/instagram/:id` | Instagram analytics for one account |
-| Reddit Analytics | `/reddit/:id` | Reddit analytics for one account - karma breakdown, score timeline, post type distribution, day/hour analysis, subreddit breakdown, top posts |
-| Reddit Posts (global) | `/reddit-posts` | Combined post explorer across all Reddit accounts with account and subreddit filters |
-| Reddit Posts (per account) | `/reddit-posts/:id` | Searchable and sortable post list for a single Reddit account |
-| Tracked Content | `/tracked-content` | Monitor Reddit posts and YouTube videos; add by URL, assign categories, bulk edit, per-row refresh |
-| Tracked Category | `/tracked-content/category/:name` | Detailed per-category analytics; YouTube section (views, likes, comments, area chart, table) and Reddit section (karma, ratio, comments, area chart, table) rendered separately |
+| Tracked Content | `/tracked-content` | Monitor YouTube videos; add by link, assign categories, bulk edit, per-row refresh |
+| Tracked Category | `/tracked-content/category/:name` | Detailed per-category analytics for its YouTube videos: views, likes, comments, area chart, table |
| Video Explorer | `/videos/:id` | YouTube video library with search and sort |
| Publish | `/publish` (`/upload` redirects) | Publish or schedule to Instagram, bulk upload, and the scheduled post queue |
| Automations | `/automations` | Keyword rules that answer Instagram comments with a private reply, a public reply under the comment or both, account pause and comment events, counts and the activity of both replies with separate retries (`docs/architecture/data-flows/AUTOMATION.md`) |
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index 8633a2d..331c49a 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -104,8 +104,8 @@ frontend/src/
use-command-palette-shortcut.ts Ctrl+K / Cmd+K toggle
use-smooth-theme.ts useSmoothTheme(), theme cross-fade
use-document-title.ts useDocumentTitle(name): a detail page names the browser tab after what it shows
- use-cloudinary-config.ts useCloudinaryConfig(reloadKey), shared by Publish and Tracked content
- use-account-analytics.ts useAccountAnalytics(account, fetchAnalytics, label), shared by Instagram and Reddit analytics
+ use-cloudinary-config.ts useCloudinaryConfig(reloadKey), used by Publish
+ use-account-analytics.ts useAccountAnalytics(account, fetchAnalytics, label), used by Instagram analytics
layout/
index.tsx AppShell: SidebarProvider + AppSidebar + TopBar + Outlet + CommandPalette
navigation.ts NAV_GROUPS with icons, routeTitle() and currentNavPath() (single source for sidebar, top bar, palette)
@@ -143,7 +143,6 @@ frontend/src/
videos/ VideoExplorer.tsx - all videos table (page; filters, table, grid and helpers beside it)
shorts/ ShortsExplorer.tsx - shorts-filtered grid (page; filters and grid beside it)
reels/ ReelsExplorer.tsx - Instagram media grid (page; hook, filters and helpers beside it)
- reddit/ RedditAnalytics (page; sections and helpers beside it), RedditPosts, RedditPostsAll, shared post table
tracked/ TrackedContent.tsx, TrackedCategory.tsx (pages; components, hooks and helpers beside them)
publishing/
UploadContent.tsx Instagram publishing + schedule queue (page; components, hooks and helpers beside it)
diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.md
index b8fd174..f448d40 100644
--- a/docs/architecture/frontend/ROUTING.md
+++ b/docs/architecture/frontend/ROUTING.md
@@ -15,12 +15,8 @@ The app uses React Router 7 in `frontend/src/App.tsx`: a data router from `creat
| `/accounts` | `AccountManager.tsx` | Connect and remove accounts. `?add=1` opens the add flow; `?ig_connected` (`true`, or `reconnected` when the account was already there) and `?ig_error` report the Instagram OAuth result |
| `/channel/:id` | `ChannelAnalytics.tsx` | `:id` = account.id for YouTube accounts |
| `/instagram/:id` | `InstagramAnalytics.tsx` | `:id` = account.id for Instagram accounts |
-| `/reddit/:id` | `RedditAnalytics.tsx` | `:id` = account.id for Reddit accounts |
-| `/reddit-posts` | `RedditPostsAll.tsx` | Combined post explorer across all connected Reddit accounts |
-| `/reddit-posts/:id` | `RedditPosts.tsx` | `:id` = account.id; filterable/sortable post explorer for one account |
-| `/tracked-content` | `TrackedContent.tsx` | Tracked Reddit posts and YouTube videos - add, manage, categorize, refresh |
-| `/tracked-content/category/:name` | `TrackedCategory.tsx` | Per-category analytics page; `:name` is URL-encoded category label; shows YouTube and Reddit sections separately |
-| `/reddit-tracked` | redirect | Redirects to `/tracked-content` |
+| `/tracked-content` | `TrackedContent.tsx` | Tracked YouTube videos - add, manage, categorize, refresh |
+| `/tracked-content/category/:name` | `TrackedCategory.tsx` | Per-category analytics page; `:name` is URL-encoded category label; shows the category's YouTube videos |
| `/videos` | `VideoExplorer.tsx` | Every video from every YouTube channel |
| `/shorts` | `ShortsExplorer.tsx` | Videos of 60 seconds or less |
| `/instagram` | `ReelsExplorer.tsx` | Instagram reels, posts and videos (the Instagram content page) |
@@ -31,7 +27,7 @@ The app uses React Router 7 in `frontend/src/App.tsx`: a data router from `creat
| `/automations/rules/new` | `features/automations/RuleEditorPage.tsx` | Create a rule on its own page, with a warning before leaving unsaved changes |
| `/automations/rules/:id` | `features/automations/RuleEditorPage.tsx` | Edit the rule with that id |
| `/settings` | `Settings.tsx` | User/platform settings |
-| `*` | `pages/NotFound.tsx` | Any other path inside the app: "Page not found" with the requested path, a link to the overview and the search shortcut. Unknown paths no longer redirect silently to `/` |
+| `*` | `pages/NotFound.tsx` | Any other path inside the app: "Page not found" with the requested path, a link to the overview and the search shortcut. Unknown paths no longer redirect silently to `/`. The pages of the platform removed in v2.0.0 (ADR-049) land here too |
## Auth Guard
@@ -98,7 +94,7 @@ Only the most specific matching link is the current page (`currentNavPath()` in
### Top bar
-The top bar shows the page title. On a detail page it is a breadcrumb whose parent is a real link (a category links back to Tracked content, a Reddit account's posts to Reddit posts, an account page to Overview). On the right are Search (on narrow screens, where the sidebar is hidden) and Help, which opens the documentation in a new tab. Refreshing and the theme live on the pages, in the user menu and in Settings, not in the top bar.
+The top bar shows the page title. On a detail page it is a breadcrumb whose parent is a real link (a category links back to Tracked content, an account page to Overview). On the right are Search (on narrow screens, where the sidebar is hidden) and Help, which opens the documentation in a new tab. Refreshing and the theme live on the pages, in the user menu and in Settings, not in the top bar.
## Page titles and focus
diff --git a/docs/architecture/site/SITE.md b/docs/architecture/site/SITE.md
index 1a38a71..544b319 100644
--- a/docs/architecture/site/SITE.md
+++ b/docs/architecture/site/SITE.md
@@ -51,7 +51,7 @@ site/
MarketingLayout.tsx Skip link, Navbar, page, Footer
Navbar.tsx, Footer.tsx, navLinks.ts, Pill.tsx, ThemeToggle.tsx, MotionToggle.tsx, ScrollManager.tsx
brand.tsx Logo, Mark, RibbonCrop, FoldBand (the brand graphics)
- marks.tsx Hand-written SVG logos for YouTube, Instagram, Reddit and GitHub
+ marks.tsx Hand-written SVG logos for YouTube, Instagram and GitHub
icons.tsx Generated Solar icons; never edited by hand
sections/ Home page sections: Story, Platforms, Faq, and the shared blocks (SectionHeader, FeatureSection, BentoCard, CtaBand)
mockups/ Product previews drawn in React (see Mockups and Motion): OverviewWindow, AnalyticsCard,
@@ -198,7 +198,7 @@ The product previews are React components drawn with the site's tokens, never sc
| Secrets | None in the build; the workflow needs only `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` |
| Workflow | `.github/workflows/deploy-site.yml`, on pushes to `main` that touch `site/**`, `tsconfig.base.json`, the root `package.json` or `package-lock.json`, or the workflow itself |
-`site/public/_redirects` sends the app's old paths on this domain (`/login`, `/accounts`, `/settings`, `/videos`, `/shorts`, `/tracked-content`, `/reddit-posts`, `/channel/*`, `/instagram/*`, `/reddit/*` and others) to the same path on `https://app.twiligent.ujjwal.fyi` with a 301; `/upload` and `/publish` go to the app's `/publish`, and `/reels` and `/instagram` to its `/instagram`. It also rewrites `/docs` and `/docs/*` to `/` with a 200 (see Routing). In the other direction, the app's `/docs/*` route sends old docs links to the same page here. See `docs/architecture/cloudflare/PAGES.md`, `docs/architecture/cloudflare/CI_CD.md` and `docs/workflows/DEPLOYMENT.md`.
+`site/public/_redirects` sends the app's old paths on this domain (`/login`, `/accounts`, `/settings`, `/videos`, `/shorts`, `/tracked-content`, `/channel/*`, `/instagram/*` and others) to the same path on `https://app.twiligent.ujjwal.fyi` with a 301; `/upload` and `/publish` go to the app's `/publish`, and `/reels` and `/instagram` to its `/instagram`. The old pages of the platform removed in v2.0.0 (ADR-049) go to the app's Overview, and its old tracked posts path to Tracked content. It also rewrites `/docs` and `/docs/*` to `/` with a 200 (see Routing). In the other direction, the app's `/docs/*` route sends old docs links to the same page here. See `docs/architecture/cloudflare/PAGES.md`, `docs/architecture/cloudflare/CI_CD.md` and `docs/workflows/DEPLOYMENT.md`.
## TypeScript and Lint
diff --git a/docs/brand-notes.md b/docs/brand-notes.md
index 00f1ee7..aecde4c 100644
--- a/docs/brand-notes.md
+++ b/docs/brand-notes.md
@@ -99,7 +99,7 @@ Semantic tokens (light / dark), each with its contrast note from `tokens.json`:
- Sentence case; no exclamation marks, emoji or hype words ("revolutionary", "magic", "10x").
- At most one light metaphor per screen (dusk, glow, fold, edge).
- Errors say what happened and what to do.
-- **Tagline:** "Intelligence, folded into everything." for covers and social; never in product UI. Since 2026-11-04 the site's pages do not use it: the owner chose headlines and buttons that say plainly what the product does and what a button leads to ("YouTube, Instagram and Reddit analytics in one dashboard", "Create an account").
+- **Tagline:** "Intelligence, folded into everything." for covers and social; never in product UI. Since 2026-11-04 the site's pages do not use it: the owner chose headlines and buttons that say plainly what the product does and what a button leads to ("YouTube and Instagram analytics in one dashboard", "Create an account").
- **Promise:** clarity from many sources, folded into one picture.
- **Personality:** sharp, not cold; calm, not quiet; warm, not cute.
- The project rules also ban em dashes, en dashes and diagonal arrows.
diff --git a/docs/design-reference.md b/docs/design-reference.md
index c3dcdc0..ffe4719 100644
--- a/docs/design-reference.md
+++ b/docs/design-reference.md
@@ -215,7 +215,7 @@ Series order follows the brand rule: red, ink-muted, afterglow, info, oxblood.
| `--chart-4` | `#2C5A99` | `#8DB3EC` | Brand `info` | 6.3:1 / 8.9:1 |
| `--chart-5` | `#5E0B14` | `#B4626E` | Brand `oxblood`; dark derived lighter because oxblood is 1.4:1 on dusk | 12.4:1 / 4.5:1 |
-Platforms map to series: YouTube `chart-1`, Instagram `chart-3`, Reddit `chart-4`, categories `chart-2`. Platform is always also named in a label or legend, never shown by colour alone.
+Platforms map to series: YouTube `chart-1`, Instagram `chart-3`, categories `chart-2`. Platform is always also named in a label or legend, never shown by colour alone.
### Type, space, shape, elevation, motion
diff --git a/docs/features/NEW_ANALYTICS_PAGE.md b/docs/features/NEW_ANALYTICS_PAGE.md
index a97a704..7af0d56 100644
--- a/docs/features/NEW_ANALYTICS_PAGE.md
+++ b/docs/features/NEW_ANALYTICS_PAGE.md
@@ -1,6 +1,8 @@
# Guide: Adding an Analytics Page for a New Platform
-Use this when adding a full analytics view for a new connected platform (e.g., Reddit, Twitter/X, TikTok). This guide is specific to analytics pages that follow the pattern of `ChannelAnalytics.tsx` and `InstagramAnalytics.tsx`.
+Use this when adding a full analytics view for a new connected platform (e.g., Twitter/X, TikTok). This guide is specific to analytics pages that follow the pattern of `ChannelAnalytics.tsx` and `InstagramAnalytics.tsx`. The examples use a placeholder platform called Example (`example`); replace the name with the real one. The Instagram analytics (`services/instagram/`, `instagramAnalyticsService.ts`, `getInstagramAnalytics` and `getInstagramMedia` in `analyticsController.ts`, `features/analytics/instagram/`) is the closest complete example.
+
+Adding the platform itself (the `Platform` union, the database check, adding and refreshing accounts, secrets) is covered in `docs/features/NEW_INTEGRATION.md`. Do that first.
## Architecture Impact
@@ -8,15 +10,14 @@ Adding a platform analytics page touches all layers:
| Layer | What changes |
|---|---|
-| **Shared types** | New `shared/types/<platform>.ts` with the profile, post, analytics and cache shapes |
+| **Shared types** | New `shared/types/<platform>.ts` with the profile, post, analytics, cache and response shapes |
| **Backend platform modules** | New `services/<platform>/` folder with the API client and the analytics computation |
| **Backend feature service** | New `services/<platform>AnalyticsService.ts`, wired in `container.ts` |
| **Backend cache** | New cache methods in `repositories/analyticsCacheRepository.ts` |
-| **Backend db** | No schema change needed - `platform='reddit'` works with the existing `accounts` table and `accountRepository` |
-| **Backend controller and routes** | New `controllers/<platform>Controller.ts` and `routes/<platform>Routes.ts` (`/accounts/:id/platform-analytics`, `/accounts/:id/platform-media`) |
-| **Backend route index** | Add the route table to `protectedRoutes` in `routes/index.ts` |
+| **Backend db** | No new table: accounts of every platform live in `accounts`. The `accounts_platform_check` constraint lists the allowed platforms, so it is replaced by a migration that adds the new one (`docs/features/NEW_INTEGRATION.md`) |
+| **Backend controller and routes** | New handlers in `controllers/analyticsController.ts` and routes in `routes/analyticsRoutes.ts` (`/accounts/:id/<platform>-analytics`, `/accounts/:id/<platform>-posts`), beside the YouTube and Instagram reads |
| **Frontend api** | New methods in `api.ts` |
-| **Frontend page** | New analytics page in `features/analytics/platform/` |
+| **Frontend page** | New analytics page in `features/analytics/<platform>/` |
| **Frontend routing** | New route in `App.tsx` |
| **Frontend navigation** | Platform branch in `accountPath()` and `PLATFORM_META` in `lib/accounts.ts`; the sidebar lists accounts from them |
| **Frontend overview** | Add platform KPIs to Overview dashboard if appropriate |
@@ -25,178 +26,211 @@ Adding a platform analytics page touches all layers:
```
shared/types/
- reddit.ts <- RedditProfile, RedditPost, RedditAnalytics, RedditCacheData
+ example.ts <- ExampleProfile, ExamplePost, ExampleAnalytics, ExampleCacheData, responses
backend/
services/
- reddit/
- redditApi.ts <- API client
- redditAnalytics.ts <- pure analytics computation
- redditAnalyticsService.ts <- ownership checks, cache, platform calls
+ example/
+ exampleApi.ts <- API client
+ exampleAnalytics.ts <- pure analytics computation
+ exampleAnalyticsService.ts <- ownership checks, cache, platform calls
controllers/
- redditController.ts
+ analyticsController.ts <- add getExampleAnalytics, getExamplePosts
routes/
- redditRoutes.ts <- analytics routes
+ analyticsRoutes.ts <- add the two routes
frontend/src/
features/
analytics/
- reddit/
- RedditAnalytics.tsx
+ example/
+ ExampleAnalytics.tsx
```
+A platform that also publishes or takes other input gets its own `controllers/<platform>Controller.ts` and `routes/<platform>Routes.ts` instead (see `docs/features/NEW_INTEGRATION.md`, Step 6).
+
## Step 1: Shared Types
Define what the API returns before writing code that produces or reads it. `shared/types/<platform>.ts` holds types only; both the Worker and the frontend import it with `import type`.
```ts
-// shared/types/reddit.ts
-export interface RedditProfile { username: string; totalKarma: number; /* ... */ }
-export interface RedditPost { id: string; title: string; score: number; /* ... */ }
-export interface RedditAnalytics { /* totals, breakdowns */ }
-export interface RedditCacheData { profile: RedditProfile; analytics: RedditAnalytics; posts: RedditPost[] }
+// shared/types/example.ts
+import type { SafeAccount } from './domain.ts';
+
+export interface ExampleProfile { username: string; followersCount: number; /* ... */ }
+export interface ExamplePost { id: string; caption: string; likeCount: number | null; /* ... */ }
+export interface ExampleAnalytics { /* totals, breakdowns */ }
+export interface ExampleCacheData { posts: ExamplePost[]; fetchedAt: string }
+
+// GET /api/accounts/:id/example-analytics
+export interface ExampleAnalyticsResponse {
+ success: true;
+ profile: ExampleProfile;
+ account: SafeAccount;
+ analytics: ExampleAnalytics;
+}
+
+// GET /api/accounts/:id/example-posts
+export interface ExamplePostsResponse {
+ success: true;
+ posts: ExamplePost[];
+ fetchedAt: string;
+}
```
## Step 2: Backend Platform Modules
-Model them after `backend/services/reddit/`. Raw upstream payloads get their own interfaces in the module, covering only the fields the code reads. Every call accepts an `AbortSignal` and turns a failure into a typed error:
+Model them after `backend/services/instagram/` (`instagramApi.ts` for the requests, `instagramMedia.ts` for paging, `instagramAnalytics.ts` for the computation). Raw upstream payloads get their own interfaces in the module, covering only the fields the code reads. Every call accepts an `AbortSignal`, runs through a circuit breaker (`lib/circuitBreaker.ts`, one per platform) and turns a failure into a typed error:
```ts
-// backend/services/reddit/redditApi.ts
+// backend/services/example/exampleApi.ts
+import { createCircuitBreaker } from '../../lib/circuitBreaker.ts';
import { NotFoundError, UpstreamError, UpstreamTimeoutError, isAbortError } from '../../lib/errors.ts';
-import type { RedditPost, RedditProfile } from '../../../shared/types/reddit.ts';
+import type { ExamplePost, ExampleProfile } from '../../../shared/types/example.ts';
+
+const EXAMPLE_BASE = 'https://api.example.com';
+
+export const exampleCircuit = createCircuitBreaker('Example');
+
+function exampleFetch<T>(path: string, accessToken: string, signal?: AbortSignal): Promise<T> {
+ return exampleCircuit.run(() => requestExample<T>(path, accessToken, signal), signal);
+}
-async function redditFetch<T>(path: string, cookie: string | null | undefined, signal?: AbortSignal): Promise<T> {
- const headers: Record<string, string> = { 'User-Agent': USER_AGENT, 'Accept': 'application/json' };
- if (cookie) headers['Cookie'] = `reddit_session=${cookie}`;
+async function requestExample<T>(path: string, accessToken: string, signal?: AbortSignal): Promise<T> {
let res: Response;
try {
- res = await fetch(`${REDDIT_BASE}${path}`, { headers, signal });
+ res = await fetch(`${EXAMPLE_BASE}${path}`, { headers: { Authorization: `Bearer ${accessToken}` }, signal });
} catch (err) {
- if (isAbortError(err)) throw new UpstreamTimeoutError('Reddit', err);
- throw new UpstreamError(`Reddit could not be reached (${(err as Error).message})`, { cause: err });
+ if (isAbortError(err)) throw new UpstreamTimeoutError('Example', err);
+ throw new UpstreamError(`Example could not be reached (${(err as Error).message})`, { reason: 'unreachable', cause: err });
}
- if (res.status === 404) throw new NotFoundError('Reddit user not found - check the username');
- if (!res.ok) throw new UpstreamError(`Reddit API ${res.status}: ${res.statusText}`, { status: res.status });
+ if (res.status === 404) throw new NotFoundError('Example account not found - check the username');
+ if (!res.ok) throw new UpstreamError(`Example API ${res.status}: ${res.statusText}`, { status: res.status });
return await res.json() as T;
}
-export async function fetchRedditProfile(username: string, cookie: string | null | undefined, signal?: AbortSignal): Promise<RedditProfile> { ... }
-export async function fetchRedditPosts(username: string, cookie: string | null | undefined, limit = 100, signal?: AbortSignal): Promise<RedditPost[]> { ... }
+export async function fetchExampleProfile(accessToken: string, signal?: AbortSignal): Promise<ExampleProfile> { ... }
+export async function fetchExamplePosts(accessToken: string, limit = 100, signal?: AbortSignal): Promise<ExamplePost[]> { ... }
```
```ts
-// backend/services/reddit/redditAnalytics.ts - pure, so it is easy to test
-export function computeRedditAnalytics(profile: RedditProfile, posts: RedditPost[] | null | undefined): RedditAnalytics {
- // totals, best post, posting time distribution, subreddit and monthly breakdowns,
+// backend/services/example/exampleAnalytics.ts - pure, so it is easy to test
+export function computeExampleAnalytics(profile: ExampleProfile, posts: ExamplePost[] | null | undefined): ExampleAnalytics {
+ // totals, best post, posting time distribution, monthly breakdown,
// using the shared helpers in lib/analyticsMath.ts
}
```
## Step 3: Backend Cache
-Add the methods to `AnalyticsCacheRepository` in `backend/repositories/analyticsCacheRepository.ts`. Build them on the private `readKey` and `writeKey` helpers, which return early without Redis, swallow Redis errors and apply the analytics TTL:
+Add the methods to `AnalyticsCacheRepository` in `backend/repositories/analyticsCacheRepository.ts`. Build them on the private `readKey` and `writeKey` helpers, which return early without Redis, swallow Redis errors and apply the analytics TTL. Store a version with the entry, as `videos:` and `ig:` do, so a later change to the shape makes old entries miss:
```ts
+// beside VIDEOS_CACHE_VERSION and IG_CACHE_VERSION
+const EXAMPLE_CACHE_VERSION = 1;
+
// in createAnalyticsCacheRepository()
-async getReddit(userId, accountId) {
- return (await readKey<RedditCacheData>(`reddit:${userId}:${accountId}`)) || null;
+async getExamplePosts(userId, accountId) {
+ const cached = await readKey<Versioned<ExampleCacheData>>(`example:${userId}:${accountId}`);
+ return cached?.version === EXAMPLE_CACHE_VERSION ? cached : null;
},
-setReddit: (userId, accountId, data) => writeKey(`reddit:${userId}:${accountId}`, data),
+setExamplePosts: (userId, accountId, data) => writeKey(`example:${userId}:${accountId}`, { ...data, version: EXAMPLE_CACHE_VERSION }),
```
Add the key to `deleteAllForAccount()`, which `AccountService.remove()` calls when the account is deleted.
-## Step 4: Backend Service, Controller and Routes
+## Step 4: Backend Service and Controller
-The feature service checks ownership and the stored credentials, reads the cache, and fetches live on a miss:
+The feature service checks ownership and the stored credentials, reads the cache, and fetches live on a miss. Like `instagramAnalyticsService.ts`, the analytics read is always live and refreshes the cached posts, and the posts read is cache first unless the person asked for fresh data:
```ts
-// backend/services/redditAnalyticsService.ts
-export function createRedditAnalyticsService({ accounts, cache, context }: RedditAnalyticsDeps): RedditAnalyticsService {
+// backend/services/exampleAnalyticsService.ts
+export function createExampleAnalyticsService({ accounts, cache, context }: ExampleAnalyticsDeps): ExampleAnalyticsService {
const { signal } = context;
- async function credentialsFor(userId: string, accountId: string): Promise<RedditCredentials> {
+ async function findConnected(userId: string, accountId: string): Promise<ConnectedExampleAccount> {
const account = await accounts.findForUser(accountId, userId);
- if (!account || account.platform !== 'reddit') throw new NotFoundError('Reddit account not found');
- if (!account.cookie) throw new ValidationError(NO_COOKIE_MESSAGE);
- if (!account.username) throw new ValidationError('No Reddit username stored - delete this account and add it again');
- return { username: account.username, cookie: account.cookie };
+ if (!account || account.platform !== 'example') throw new NotFoundError('Example account not found');
+ if (!account.accessToken) throw new ValidationError('No access token stored - reconnect this Example account');
+ return { ...account, accessToken: account.accessToken };
}
return {
+ // always live: the posts are cached for the posts read and the Overview
async analytics(userId, accountId) {
- const { username, cookie } = await credentialsFor(userId, accountId);
- const cached = await cache.getReddit(userId, accountId);
- if (cached) return cached;
-
+ const account = await findConnected(userId, accountId);
const [profile, posts] = await Promise.all([
- fetchRedditProfile(username, cookie, signal),
- fetchRedditPosts(username, cookie, POST_LIMIT, signal),
+ fetchExampleProfile(account.accessToken, signal),
+ fetchExamplePosts(account.accessToken, POST_LIMIT, signal),
]);
- const result: RedditCacheData = { profile, analytics: computeRedditAnalytics(profile, posts), posts };
- await cache.setReddit(userId, accountId, result);
- return result;
+ await cache.setExamplePosts(userId, accountId, { posts, fetchedAt: new Date().toISOString() });
+ return { profile, account: safeAccount(account), analytics: computeExampleAnalytics(profile, posts) };
+ },
+
+ // cache first, unless a person asked for fresh data
+ async posts(userId, accountId, { fresh = false } = {}) {
+ if (!fresh) {
+ const cached = await cache.getExamplePosts(userId, accountId);
+ if (cached?.posts) return { posts: cached.posts, fetchedAt: cached.fetchedAt };
+ }
+ const account = await findConnected(userId, accountId);
+ const posts = await fetchExamplePosts(account.accessToken, POST_LIMIT, signal);
+ const fetchedAt = new Date().toISOString();
+ await cache.setExamplePosts(userId, accountId, { posts, fetchedAt });
+ return { posts, fetchedAt };
},
- // ...
};
}
```
-Wire it in `backend/container.ts` (`redditAnalytics: createRedditAnalyticsService({ accounts, cache, context })`). The controller and route table stay thin:
+`ConnectedExampleAccount` is `Account & { accessToken: string }`, the account once the check has passed, as `ConnectedInstagramAccount` is in `instagramAnalyticsService.ts`. Wire the service in `backend/container.ts` (`exampleAnalytics: createExampleAnalyticsService({ accounts, cache, context })`). The controller handlers and routes stay thin and sit beside the Instagram ones:
```ts
-// backend/controllers/redditController.ts
-export const getRedditAnalytics = controller.createHandlers(async c => {
- const result = await servicesFor(c).redditAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));
- return c.json(result satisfies RedditCacheData);
+// backend/controllers/analyticsController.ts
+export const getExampleAnalytics = controller.createHandlers(async c => {
+ const result = await servicesFor(c).exampleAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, ...result } satisfies ExampleAnalyticsResponse);
});
-// backend/routes/redditRoutes.ts
-const router = new Hono<AppEnv>();
-
-router.get('/accounts/:id/reddit-analytics', ...getRedditAnalytics);
-router.get('/accounts/:id/reddit-posts', ...getRedditPosts);
+export const getExamplePosts = controller.createHandlers(queryParams(parseFreshQuery), async c => {
+ const result = await servicesFor(c).exampleAnalytics.posts(c.get('userId'), pathParam(c, 'id'), c.req.valid('query'));
+ return c.json({ success: true, ...result } satisfies ExamplePostsResponse);
+});
-export default router;
+// backend/routes/analyticsRoutes.ts
+router.get('/accounts/:id/example-analytics', ...getExampleAnalytics);
+router.get('/accounts/:id/example-posts', ...getExamplePosts);
```
-## Step 5: Register the Route Table
+`parseFreshQuery` (`validators/analyticsValidators.ts`) accepts `?fresh=1` and answers 400 for any other `fresh` value, as it does for `/videos` and `/ig-media`.
-```ts
-// backend/routes/index.ts
-import redditRoutes from './redditRoutes.ts';
-// ...
-for (const routes of [accountRoutes, analyticsRoutes, redditRoutes, /* ... */]) {
- protectedRoutes.route('/', routes);
-}
-```
+## Step 5: Rate Limits
-Routes that call the platform on a cache miss count against the shared API limits; add them to `QUOTA_ROUTES` in `backend/lib/rateLimit/rules.ts` if they can be called often.
+`analyticsRoutes.ts` is already in `protectedRoutes` in `routes/index.ts`, so the new routes need no registration. Routes that call the platform on a cache miss count against the shared API limits; add them to `QUOTA_ROUTES` in `backend/lib/rateLimit/rules.ts` if they can be called often.
## Step 6: Frontend Page
-Model after `InstagramAnalytics.tsx`. Read the data as the shared type (`RedditCacheData`) that `api.ts` returns, and give each sub-component a `<Component>Props` interface. Key sections:
-- Profile header (username, follower count, karma)
-- KPI row: avg upvotes, avg comments, total posts, engagement rate
+Model after `InstagramAnalytics.tsx`. Load the data with `useAccountAnalytics(account, api.getExampleAnalytics, 'Example', { live: true })`, read it as the shared type (`ExampleAnalyticsResponse`) that `api.ts` returns, and give each sub-component a `<Component>Props` interface. Pure chart rows and stat lists go in a plain `exampleAnalyticsData.ts` beside the page, as `instagramAnalyticsData.ts` does. Design every state: account not found (`EmptyState`), first load (`PageSkeleton`), failed load (`ErrorState` with retry). Key sections:
+- Profile header (username, follower count, refresh, last fetched)
+- KPI row: avg likes, avg comments, total posts, engagement rate
- Best performing post card
- Monthly breakdown chart (Recharts AreaChart or BarChart)
-- Subreddit distribution (pie or bar)
+- Content type distribution (bar)
- Posting time heatmap (if available)
## Step 7: Add to App.tsx, lib/accounts.ts, and api.ts
```tsx
// App.tsx
-const RedditAnalytics = lazy(() => import('./features/analytics/reddit/RedditAnalytics'));
+const ExampleAnalytics = lazy(() => import('./features/analytics/example/ExampleAnalytics'));
// route:
-{ path: 'reddit/:id', element: <RedditAnalytics /> }
+{ path: 'example/:id', element: <ExampleAnalytics /> }
```
```ts
// api.ts
-getRedditAnalytics: (id: string) => request<RedditCacheData>(`/accounts/${id}/reddit-analytics`),
+getExampleAnalytics: (id: string) => request<ExampleAnalyticsResponse>(`/accounts/${id}/example-analytics`),
+getExamplePosts: (id: string, fresh = false) => request<ExamplePostsResponse>(`/accounts/${id}/example-posts${fresh ? '?fresh=1' : ''}`),
```
```ts
@@ -204,19 +238,19 @@ getRedditAnalytics: (id: string) => request<RedditCacheData>(`/accounts/${id}/re
export function accountPath(account: AccountFields): string {
const platform = platformOf(account);
if (platform === 'instagram') return `/instagram/${account.id}`;
- if (platform === 'reddit') return `/reddit/${account.id}`;
+ if (platform === 'example') return `/example/${account.id}`;
return `/channel/${account.id}`;
}
```
## Step 8: Type-check and Test
-Run `npm run typecheck`, `npm run lint` and `npm test` from the repository root. Pure analytics helpers (like `computeRedditAnalytics`) get a test in `backend/tests/services/` at the mirrored path (`backend/tests/services/reddit/redditAnalytics.test.ts`), and the route table gets one in `backend/tests/routes/redditRoutes.test.ts`.
+Run `npm run typecheck`, `npm run lint` and `npm test` from the repository root. Pure analytics helpers (like `computeExampleAnalytics`) get a test in `backend/tests/services/` at the mirrored path (`backend/tests/services/example/exampleAnalytics.test.ts`), the API client one against `fixtures/fakeFetch.ts` (`backend/tests/services/example/exampleApi.test.ts`), and the new routes get cases in `backend/tests/routes/analyticsRoutes.test.ts`. Chart row helpers get a test in `frontend/tests/features/analytics/example/`.
## Step 9: Update Documentation
- `docs/architecture/backend/ROUTES.md` - new routes
- `docs/architecture/backend/CACHING.md` - new cache keys
-- `docs/architecture/backend/SERVICES.md` - Reddit service
-- `docs/architecture/data-flows/` - create `REDDIT.md` for the analytics flow
+- `docs/architecture/backend/SERVICES.md` - the platform modules and the feature service
+- `docs/architecture/data-flows/ANALYTICS.md` - a section for the platform's analytics flow
- `CHANGELOG.md` - feature entry
diff --git a/docs/features/NEW_API_ENDPOINT.md b/docs/features/NEW_API_ENDPOINT.md
index dcf8cef..75e0d7f 100644
--- a/docs/features/NEW_API_ENDPOINT.md
+++ b/docs/features/NEW_API_ENDPOINT.md
@@ -21,7 +21,7 @@ Follow this guide when adding a route to the Hono backend. Read `docs/architectu
## Step 1: Define the Request and Response Types
-Add the shapes the endpoint sends and receives to `shared/types/` first. Use `domain.ts` for cross-platform data, or `youtube.ts`, `instagram.ts` or `reddit.ts` for platform data. These files hold types only and never import runtime code.
+Add the shapes the endpoint sends and receives to `shared/types/` first. Use `domain.ts` for cross-platform data, or `youtube.ts` or `instagram.ts` for platform data. These files hold types only and never import runtime code.
```ts
// shared/types/domain.ts
@@ -129,7 +129,7 @@ export function createMyFeatureService({ resources }: MyFeatureDeps): MyFeatureS
}
```
-If the endpoint calls a platform API, put the call in the platform module (`services/youtube/`, `services/instagram/`, `services/reddit/`) and pass it `context.signal`. A missing Worker secret is a `NotConfiguredError` (503); a record the user does not own is a `NotFoundError` (404).
+If the endpoint calls a platform API, put the call in the platform module (`services/youtube/`, `services/instagram/`) and pass it `context.signal`. A missing Worker secret is a `NotConfiguredError` (503); a record the user does not own is a `NotFoundError` (404).
Wire a new repository or service in `backend/container.ts`: build the repository from `clients.supabase`, add the service to the `Services` interface, and create it in `createServices()`.
diff --git a/docs/features/NEW_INTEGRATION.md b/docs/features/NEW_INTEGRATION.md
index 480a6b7..b008058 100644
--- a/docs/features/NEW_INTEGRATION.md
+++ b/docs/features/NEW_INTEGRATION.md
@@ -1,6 +1,6 @@
# Guide: Adding a New Platform Integration
-A "platform integration" is a new social or content platform (e.g., Reddit, Twitter/X, TikTok, LinkedIn). This guide walks through every layer that needs to change. Read `docs/architecture/backend/REQUEST_PIPELINE.md` for the backend layers and `docs/guidelines/TYPESCRIPT.md` for the typing rules: the types for the new platform are written before the code that uses them. The Reddit integration (`services/reddit/`, `redditAnalyticsService.ts`, `redditController.ts`, `redditRoutes.ts`) is the smallest complete example.
+A "platform integration" is a new social or content platform (e.g., Twitter/X, TikTok, LinkedIn). This guide walks through every layer that needs to change. Read `docs/architecture/backend/REQUEST_PIPELINE.md` for the backend layers and `docs/guidelines/TYPESCRIPT.md` for the typing rules: the types for the new platform are written before the code that uses them. The Instagram integration (`services/instagram/`, `instagramAnalyticsService.ts`, its handlers in `analyticsController.ts` and `analyticsRoutes.ts`, `instagramConnectService.ts` for the OAuth connect) is the closest complete example.
## Decision Checklist Before Starting
@@ -49,7 +49,7 @@ Add the platform to the shared `Platform` union and its stored fields to `Accoun
```ts
// shared/types/domain.ts
-export type Platform = 'youtube' | 'instagram' | 'reddit' | 'twitter';
+export type Platform = 'youtube' | 'instagram' | 'twitter';
export interface Account {
// ...existing fields
@@ -203,7 +203,7 @@ export function computeTwitterAnalytics(apiTweets: TwitterApiTweet[], profile: T
`safeAccount()` in `backend/lib/safeAccount.ts` removes every field listed in `SECRET_FIELDS` before an account reaches the frontend. Add the new platform's secret fields there instead of writing a per-platform function:
```ts
-const SECRET_FIELDS: (keyof Account)[] = ['accessToken', 'cookie', 'encryptedPassword', 'encryptedTotpSecret', 'authToken', 'ct0', 'refreshToken'];
+const SECRET_FIELDS: (keyof Account)[] = ['accessToken', 'refreshToken'];
```
Add the same field to the `Omit` list of `SafeAccount` in `shared/types/domain.ts`, so the frontend type does not claim the field exists.
@@ -283,7 +283,7 @@ export function createTwitterAnalyticsService({ accounts, cache, context }: Twit
}
```
-Wire it in `backend/container.ts`: add `twitterAnalytics: TwitterAnalyticsService` to `Services` and `twitterAnalytics: createTwitterAnalyticsService({ accounts, cache, context })` to `createServices()`. Adding and refreshing accounts of the new platform goes in `AccountService` (`accountService.ts`) and a builder in `accountFactory.ts`, following the Reddit and Instagram branches.
+Wire it in `backend/container.ts`: add `twitterAnalytics: TwitterAnalyticsService` to `Services` and `twitterAnalytics: createTwitterAnalyticsService({ accounts, cache, context })` to `createServices()`. Adding and refreshing accounts of the new platform goes in `AccountService` (`accountService.ts`) and a builder in `accountFactory.ts`, following the YouTube and Instagram branches.
## Step 6: Add the Validator, Controller and Route Table
diff --git a/docs/guidelines/API_CONVENTIONS.md b/docs/guidelines/API_CONVENTIONS.md
index 4fc2ce9..fbd1619 100644
--- a/docs/guidelines/API_CONVENTIONS.md
+++ b/docs/guidelines/API_CONVENTIONS.md
@@ -4,7 +4,7 @@
### Success responses
-Every response body has a TypeScript type in `shared/types/` (`domain.ts`, `youtube.ts`, `instagram.ts`, `reddit.ts`). The controller checks the object it returns with `satisfies`, and the matching `api.ts` method returns the same type, so a change to a response shape is caught by `npm run typecheck` on both sides.
+Every response body has a TypeScript type in `shared/types/` (`domain.ts`, `youtube.ts`, `instagram.ts`, `automation.ts`). The controller checks the object it returns with `satisfies`, and the matching `api.ts` method returns the same type, so a change to a response shape is caught by `npm run typecheck` on both sides.
Most endpoints return the data directly as a JSON object or array:
@@ -50,7 +50,7 @@ Controllers never build these bodies; services, repositories, validators and mid
| `409` | `CONFLICT` - the resource already exists (an account that is already added) |
| `429` | `RATE_LIMITED` - returned by the `rateLimit` middleware, with `Retry-After` and `retryAfter` in the body (see `docs/architecture/backend/RATE_LIMITING.md`), and by the Send Email hook when the day's emails are used up (`RateLimitedError`, no `retryAfter`) |
| `500` | `DATABASE_ERROR` or `INTERNAL_ERROR` - a failed query or an unexpected error |
-| `502` | `UPSTREAM_ERROR` - YouTube, Instagram, Reddit or Resend answered with an error |
+| `502` | `UPSTREAM_ERROR` - YouTube, Instagram or Resend answered with an error |
| `503` | `NOT_CONFIGURED` - a Worker secret the request needs is not set |
| `504` | `UPSTREAM_TIMEOUT` - a platform call was cancelled or timed out |
diff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.md
index 4e970af..42063a2 100644
--- a/docs/guidelines/ERROR_HANDLING.md
+++ b/docs/guidelines/ERROR_HANDLING.md
@@ -12,7 +12,7 @@ Every backend failure is a typed error thrown where the problem is found and for
| `NotFoundError` | `NOT_FOUND` | 404 | The record does not exist for this user, or is on the wrong platform |
| `ConflictError` | `CONFLICT` | 409 | The account is already added, found by the list check or, for an add at the same moment, by the unique index (`isUniqueViolation`) |
| `RateLimitedError` | `RATE_LIMITED` | 429 | A daily allowance is used up: the auth email caps in `authEmailService.ts`. Per-request limits are the rate limiter's job, not this error |
-| `UpstreamError` | `UPSTREAM_ERROR` | 502 | YouTube, Instagram, Reddit or Resend answered with an error |
+| `UpstreamError` | `UPSTREAM_ERROR` | 502 | YouTube, Instagram or Resend answered with an error |
| `NotConfiguredError` | `NOT_CONFIGURED` | 503 | A Worker secret the request needs is not set, or a core Supabase secret is missing (thrown by `injectClients` for every request) |
| `UpstreamTimeoutError` | `UPSTREAM_TIMEOUT` | 504 | A platform call was cancelled or timed out |
| `DatabaseError` | `DATABASE_ERROR` | 500 | A Supabase query failed or passed the 15 second database timeout (thrown by `repositories/query.ts`) |
@@ -21,7 +21,7 @@ An error carries a code, not a status; `middleware/errorHandler.ts` maps the cod
## Layer-by-Layer Rules
-### Platform API Calls (`services/youtube/`, `services/instagram/`, `services/reddit/`)
+### Platform API Calls (`services/youtube/`, `services/instagram/`)
Throw an `UpstreamError` as soon as the platform returns an error, keeping the platform's own wording (users can act on it) and its reason and status:
@@ -32,7 +32,7 @@ if (data.error) {
}
```
-Each platform's request helper (`ytFetch`, `igFetch` and `igPost`, `redditFetch`) runs its call through a circuit breaker (`lib/circuitBreaker.ts`, one per platform and Worker isolate). Five outages in a row, meaning a timeout the caller did not cause, an unreachable host or a 5xx, pause calls for 30 seconds: they fail at once with an `UpstreamError` (reason `unreachable`, so a scheduled post that meets it is retried) whose message says to try again in a minute. One trial call then decides whether the platform is back. A 4xx, such as an expired token, never opens it, and Instagram's Graph error codes are not read as HTTP statuses. Comment replies (`instagramMessaging.ts`) keep their own cooldowns and do not use it.
+Each platform's request helper (`ytFetch`, `igFetch` and `igPost`) runs its call through a circuit breaker (`lib/circuitBreaker.ts`, one per platform and Worker isolate). Five outages in a row, meaning a timeout the caller did not cause, an unreachable host or a 5xx, pause calls for 30 seconds: they fail at once with an `UpstreamError` (reason `unreachable`, so a scheduled post that meets it is retried) whose message says to try again in a minute. One trial call then decides whether the platform is back. A 4xx, such as an expired token, never opens it, and Instagram's Graph error codes are not read as HTTP statuses. Comment replies (`instagramMessaging.ts`) keep their own cooldowns and do not use it.
`UpstreamError` passes its message through `redactSecrets` (`lib/redact.ts`), which removes URLs, `Bearer` tokens and token-like `name=value` pairs and JSON fields, because a platform error can echo the request URL, a header or the form body with the API key or token in it. Cast the parsed JSON once to an interface that covers the fields the module reads (see `docs/guidelines/TYPESCRIPT.md`).
@@ -89,9 +89,9 @@ const settled = await Promise.allSettled(listed.map(account => refreshListed(use
Controllers do not catch errors. A thrown error goes straight to the error handler:
```ts
-export const getRedditAnalytics = controller.createHandlers(async c => {
- const result = await servicesFor(c).redditAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));
- return c.json(result satisfies RedditCacheData);
+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);
});
```
@@ -167,4 +167,4 @@ Backend errors should be descriptive but not expose implementation details:
- Good: `'Account not found'`, `'This channel is already added'`, `'scheduledAt must be a valid future date'`
- Bad: `'supabase error: duplicate key value violates unique constraint accounts_pkey'`
-Say what went wrong and what to do (`'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools'`). When the platform API returns a message that is end-user readable, `UpstreamError` passes it through. Database driver messages never reach the client.
+Say what went wrong and what to do (`'No access token stored - reconnect this Instagram account'`). When the platform API returns a message that is end-user readable, `UpstreamError` passes it through. Database driver messages never reach the client.
diff --git a/docs/guidelines/HONO.md b/docs/guidelines/HONO.md
index 1103748..4517f4d 100644
--- a/docs/guidelines/HONO.md
+++ b/docs/guidelines/HONO.md
@@ -55,11 +55,8 @@ const userId = c.get('userId');
Input enters through a validator, never through `c.req.json()` or `c.req.query()` in a controller. `jsonBody(parse)` and `queryParams(parse)` in `backend/middleware/validate.ts` wrap Hono's `validator`; each parser lives in `backend/validators/<feature>Validators.ts`, reads fields with the helpers in `validators/fields.ts` (`requiredString`, `optionalString`, `optionalNumber`, `optionalBoolean`, `optionalArray`, `presentField`) and throws `ValidationError` with a message the user can act on:
```ts
-export function parseRedditAccount(body: Fields): RedditAccountInput {
- return {
- username: requiredString(body, 'username', 'Username is required'),
- cookie: requiredString(body, 'cookie', 'Session cookie is required - ...'),
- };
+export function parseChannelInput(body: Fields): ChannelInput {
+ return { input: requiredString(body, 'input', 'Enter a channel URL, @handle or channel ID') };
}
```
diff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.md
index 9a3ba93..03ac55d 100644
--- a/docs/guidelines/NAMING.md
+++ b/docs/guidelines/NAMING.md
@@ -10,7 +10,7 @@ Start with `docs/guidelines/CODE_STYLE.md`, which shows how code reads across th
| Backend controllers | `<feature>Controller.ts` | `accountController.ts`, `scheduledPostController.ts` |
| Backend validators | `<feature>Validators.ts` | `accountValidators.ts`, `publishingValidators.ts` |
| Backend feature services | `<feature>Service.ts` | `accountService.ts`, `youtubeAnalyticsService.ts` |
-| Backend platform modules | `<platform><Topic>.ts` in `services/<platform>/` | `youtube/youtubeApi.ts`, `instagram/instagramPublishing.ts`, `reddit/redditApi.ts` |
+| Backend platform modules | `<platform><Topic>.ts` in `services/<platform>/` | `youtube/youtubeApi.ts`, `instagram/instagramPublishing.ts` |
| Backend repositories | `<table>Repository.ts` | `accountRepository.ts`, `scheduledPostRepository.ts`, `analyticsCacheRepository.ts` |
| Backend database clients | `camelCase.ts` in `database/` | `supabase.ts`, `redis.ts` |
| Backend lib | `camelCase.ts` | `errors.ts`, `logger.ts`, `config.ts`, `safeAccount.ts` |
@@ -93,7 +93,7 @@ Use `.tsx` only for files that contain JSX; everything else is `.ts`.
## Redis Cache Keys
-`{entity}:{userId}:{accountId}` - `videos:abc-123:def-456`, `ig:abc-123:def-456`, `reddit:abc-123:def-456` (defined only in `repositories/analyticsCacheRepository.ts`)
+`{entity}:{userId}:{accountId}` - `videos:abc-123:def-456`, `ig:abc-123:def-456` (defined only in `repositories/analyticsCacheRepository.ts`)
## Environment Variables
diff --git a/docs/guidelines/TYPESCRIPT.md b/docs/guidelines/TYPESCRIPT.md
index 52aa732..4a01743 100644
--- a/docs/guidelines/TYPESCRIPT.md
+++ b/docs/guidelines/TYPESCRIPT.md
@@ -36,12 +36,12 @@ Because Node runs `.ts` files by removing the types, only syntax that can be era
| Kind of type | Location |
|---|---|
-| Shapes the API sends or receives: accounts, posts, analytics, request bodies, responses | `shared/types/*.ts` (`domain.ts`, `youtube.ts`, `instagram.ts`, `reddit.ts`) |
+| Shapes the API sends or receives: accounts, posts, analytics, request bodies, responses | `shared/types/*.ts` (`domain.ts`, `youtube.ts`, `instagram.ts`, `automation.ts`) |
| Worker bindings and Hono context | `backend/types/env.ts` (`Env`), `backend/types/app.ts` (`AppEnv`, `AppContext`, `AppVariables`) |
| Request metadata for services | `backend/types/context.ts` (`RequestContext`) |
| Service and repository contracts | The module that implements them (`AccountService` and `AccountServiceDeps` in `services/accountService.ts`, `AccountRepository` in `repositories/accountRepository.ts`); `Services` in `backend/container.ts` |
| Error codes | `ApiErrorCode` and `ApiFailure` in `shared/types/domain.ts`; the error classes in `backend/lib/errors.ts` |
-| Raw payloads from YouTube, Instagram and Reddit | The platform module that parses them (`YouTubeApiVideo` in `services/youtube/youtubeApi.ts`) |
+| Raw payloads from YouTube and Instagram | The platform module that parses them (`YouTubeApiVideo` in `services/youtube/youtubeApi.ts`) |
| Props, hook results, local state | The component or hook file, exported when another file needs it |
`shared/types` holds types only. It never imports runtime code, so either app can import it with `import type` and nothing from it reaches a bundle. The backend imports it by relative path (`../../shared/types/domain.ts`), the frontend by alias (`@shared/types/domain.ts`), except files that Node tests import, which use the relative path.
@@ -65,8 +65,8 @@ When a route's response changes, change its type in `shared/types` first. The ty
```ts
// controllers: createHandlers keeps the validator's types, so c.req.valid() is typed
-export const addRedditAccount = controller.createHandlers(jsonBody(parseRedditAccount), async c => {
- const account = await servicesFor(c).accounts.addReddit(c.get('userId'), c.req.valid('json'));
+export const addInstagramAccount = controller.createHandlers(jsonBody(parseInstagramToken), async c => {
+ const account = await servicesFor(c).accounts.addInstagram(c.get('userId'), c.req.valid('json').accessToken);
return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
});
diff --git a/docs/mcp/SEQUENTIAL_THINKING.md b/docs/mcp/SEQUENTIAL_THINKING.md
index b8dc0de..6f572ab 100644
--- a/docs/mcp/SEQUENTIAL_THINKING.md
+++ b/docs/mcp/SEQUENTIAL_THINKING.md
@@ -59,14 +59,14 @@ Consider Sequential Thinking when any of these are true:
## Examples
-### Planning Reddit integration
+### Planning a Twitter/X integration
Sequential Thinking would work through:
-- Cookie-based auth vs OAuth (trade-offs, ToS risk)
-- Which endpoints to call (`/user/{username}/submitted.json`, etc.)
-- How to store credentials (in `accounts.data` jsonb alongside Instagram pattern)
-- Token refresh strategy (poll `Set-Cookie` header on each API call)
-- Which shapes go in `shared/types/reddit.ts` (profile, post, analytics, cache entry)
+- Third-party provider vs the official API vs OAuth (trade-offs, cost, ToS risk)
+- Which endpoints to call (`/users/{id}/tweets`, etc.)
+- How to store credentials (in `accounts.data` jsonb alongside the Instagram pattern)
+- Token refresh strategy (refresh before expiry from the daily cron, like Instagram tokens)
+- Which shapes go in `shared/types/twitter.ts` (profile, post, analytics, cache entry)
- New cache keys to add to `repositories/analyticsCacheRepository.ts`
- New routes to add to backend
- New analytics page structure
diff --git a/docs/philosophy/ARCHITECTURE.md b/docs/philosophy/ARCHITECTURE.md
index 3e4264d..236b26f 100644
--- a/docs/philosophy/ARCHITECTURE.md
+++ b/docs/philosophy/ARCHITECTURE.md
@@ -32,7 +32,7 @@ Redis is optional infrastructure. The cache repository (`analyticsCacheRepositor
Platform API credentials (Instagram app secret, YouTube API key) are Worker secrets - not in code, not in the database, not in the frontend. The only credential that goes near the frontend is the Supabase anon key, which is public by design.
-User-specific credentials (Instagram access tokens, Reddit session cookies) live in `accounts.data` in the database. They are read by the Worker and never returned to the frontend. See `ADR-004`.
+User-specific credentials (Instagram access tokens) live in `accounts.data` in the database. They are read by the Worker and never returned to the frontend. See `ADR-004`.
### 6. Schemas bend before tables multiply
diff --git a/docs/philosophy/PERFORMANCE.md b/docs/philosophy/PERFORMANCE.md
index 14f1fa0..f767828 100644
--- a/docs/philosophy/PERFORMANCE.md
+++ b/docs/philosophy/PERFORMANCE.md
@@ -20,12 +20,11 @@ Request
|---|---|---|---|
| YouTube analytics | `videos:{userId}:{accountId}` | 6 hours | Versioned; old versions read as a miss |
| Instagram analytics | `ig:{userId}:{accountId}` | 6 hours | Versioned; old versions read as a miss |
-| Reddit analytics | `reddit:{userId}:{accountId}` | 6 hours | |
| OAuth state | none (HMAC-signed token, see `lib/oauthState.ts`) | 10 minutes | Security-critical - do not extend |
Cache entries change on:
- Expiry: every analytics key is written with a 6 hour TTL (`ANALYTICS_TTL_SECONDS` in `repositories/analyticsCacheRepository.ts`)
-- Account deletion: `cache.deleteAllForAccount()` removes the account's three keys
+- Account deletion: `cache.deleteAllForAccount()` removes the account's two keys
- Opening YouTube or Instagram analytics: those load live and overwrite the entry
- A cache version bump: an entry with an old `version` reads as a miss
diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.md
index 02b2d63..93e3094 100644
--- a/docs/philosophy/SECURITY.md
+++ b/docs/philosophy/SECURITY.md
@@ -67,7 +67,7 @@ The query filter is the first guard. The schema adds a second one that holds eve
- **No browser access.** The migrations turn row level security on with no policies, revoke every grant on the tables from `anon` and `authenticated`, revoke the default privileges for new tables and functions, and let only `service_role` call the merge functions. The anon key gets 401 permission denied from the Data API.
- **Composite foreign keys.** `scheduled_posts` and `tracked_posts` reference `accounts (id, user_id)`, so a row can only name an account that belongs to the same user.
-- **Service checks first.** Creating a scheduled post loads the account with `findForUser` and refuses another user's account with 404; changing a tracked item's account does the same for Reddit accounts. The foreign key refuses the same write if a check is ever missed.
+- **Service checks first.** Creating a scheduled post loads the account with `findForUser` and refuses another user's account with 404. The foreign key refuses the same write if a check is ever missed.
- **Value checks.** CHECK constraints refuse an unknown platform, post status or tracked item type.
Before the migrations, three tables had policies that let a signed-in user reach their own rows through the Data API, every table had full grants to the browser roles, and the API never checked a scheduled post's account. A user could read their raw tokens and cookies and write a scheduled post that named another user's Instagram account. All of these are closed; see `docs/architecture/database/SECURITY.md`.
@@ -112,7 +112,7 @@ The replies themselves are limited in the database per instance, member, account
## Rate Limiting
-Every `/api` request is rate limited per client IP before authentication, so a flood of invalid tokens never reaches Supabase Auth. Protected requests are also limited per user, and routes that spend the shared YouTube quota or the Instagram and Reddit limits have a tighter per-user rule. Limits are counted atomically in Redis (one Lua script per check) and fall back to per-isolate memory when Redis is absent or failing, so they never fail open entirely and never fail a request. See `docs/architecture/backend/RATE_LIMITING.md`.
+Every `/api` request is rate limited per client IP before authentication, so a flood of invalid tokens never reaches Supabase Auth. Protected requests are also limited per user, and routes that spend the shared YouTube quota or the Instagram limits have a tighter per-user rule. Limits are counted atomically in Redis (one Lua script per check) and fall back to per-isolate memory when Redis is absent or failing, so they never fail open entirely and never fail a request. See `docs/architecture/backend/RATE_LIMITING.md`.
## Input Validation
@@ -123,7 +123,7 @@ The backend validates every body and query string before the controller runs: a
- File types: Cloudinary upload accepts only image and video MIME types
The backend does not validate:
-- URL formats in user-provided content (the platform API will reject invalid URLs), except tracked content links (Reddit or YouTube only) and tracked item images (`https` only)
+- URL formats in user-provided content (the platform API will reject invalid URLs), except tracked content links (YouTube only)
- Text length in scheduled posts (the platform API enforces limits)
Error responses never carry a stack trace or a database driver message: `DatabaseError` sends a plain message and logs the driver's, and `UpstreamError` removes URLs, which can carry an API key or token, from the platform's message.
diff --git a/docs/workflows/GIT.md b/docs/workflows/GIT.md
index 165a3d6..6311abe 100644
--- a/docs/workflows/GIT.md
+++ b/docs/workflows/GIT.md
@@ -35,7 +35,7 @@ Commit as soon as one small change works, however small: a fixed message, a new
Examples of commits that are each one change:
- `fix(publish): use the local day for the schedule date picker`
- `refactor(frontend): move fieldHintId and fieldErrorId to lib/fieldIds`
-- `feat(api): accept ?fresh=1 on the Reddit analytics read`
+- `feat(api): accept ?fresh=1 on the Instagram media read`
- `test(frontend): cover engagement sorting as a number`
- `docs(routing): describe the /publish and /instagram redirects`
@@ -98,7 +98,7 @@ Use scope to name the area affected:
### Examples
```
-feat(reddit): add cookie-based analytics integration
+feat(analytics): show uploads by month or week on the Videos page
fix(scheduler): strip non-ASCII characters from env vars to prevent ByteString error
@@ -108,7 +108,7 @@ refactor(instagram): extract token refresh into standalone service function
chore(deps): update @supabase/supabase-js to latest
-release: v1.1.0 - Reddit integration
+release: v1.4.0 - Intent UI charts and uploads card
```
---
@@ -180,14 +180,14 @@ Choose the number from the largest change in the pull request.
```bash
# Example: the last commit on the change's own branch
git add CHANGELOG.md package.json package-lock.json
-git commit -m "release: v1.1.0 - Reddit analytics integration"
+git commit -m "release: v1.4.0 - Intent UI charts and uploads card"
git push
gh pr create --fill
# after the pull request is merged
git fetch origin
-git tag -a v1.1.0 origin/main -m "v1.1.0 - Reddit analytics integration"
-git push origin v1.1.0
-gh release create v1.1.0 --verify-tag --title "v1.1.0 - Reddit analytics integration" --notes-file release-notes.md --latest
+git tag -a v1.4.0 origin/main -m "v1.4.0 - Intent UI charts and uploads card"
+git push origin v1.4.0
+gh release create v1.4.0 --verify-tag --title "v1.4.0 - Intent UI charts and uploads card" --notes-file release-notes.md --latest
```
Write the notes file outside the repository; it is not committed.
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 85faa3f..3368eb0 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -34,6 +34,7 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
| `backend/middleware/errorHandler.ts` | `backend/tests/middleware/errorHandler.test.ts` |
| `backend/middleware/clients.ts` | `backend/tests/middleware/clients.test.ts` |
| `backend/routes/index.ts` (health checks) | `backend/tests/routes/healthRoutes.test.ts` |
+| `backend/routes/index.ts` (the protected route table; the routes removed in v2.0.0 answer 404) | `backend/tests/routes/index.test.ts` |
| `backend/database/supabase.ts` | `backend/tests/database/supabase.test.ts` |
| `backend/lib/redact.ts` | `backend/tests/lib/redact.test.ts` |
| `backend/lib/circuitBreaker.ts` | `backend/tests/lib/circuitBreaker.test.ts` |
@@ -76,7 +77,7 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
| `site/src/lib/chart.ts` | `site/tests/lib/chart.test.ts` |
| `site/src/lib/format.ts` | `site/tests/lib/format.test.ts` |
-Backend tests are in `backend/tests/database`, `backend/tests/jobs`, `backend/tests/lib`, `backend/tests/middleware`, `backend/tests/repositories`, `backend/tests/routes`, `backend/tests/services` (with `youtube/`, `instagram/` and `reddit/` for the platform modules) and `backend/tests/validators`. A route test is named after its route table (`accountRoutes.test.ts`) and exercises the whole stack below it: controller, service and repository. Shared test helpers (`fakeSupabase.ts`, `fakeFetch.ts`, `golden.ts`, `routeHarness.ts`, `rowIds.ts`, the per-platform `*Fixtures.ts` data) and the `*.golden.json` snapshots are in `backend/tests/fixtures/`. `fakeSupabase.ts` also answers `rpc()` for the three merge functions, running the same shallow merge on its in-memory rows (with `p_only_status` and the null-user cron form), and sets `updated_at` on every update and upsert as the database trigger does. The fake also answers `in`, `gte`, `gt` and `limit` (rows come back in stored order, so a test seeds them in the order it expects), inserts and upserts of several rows, and `ignoreDuplicates` upserts that return only the new rows; `fakeSupabase(rows, rpcHandlers)` runs any other database function the test supplies. `fakeFetch.ts` replies can carry headers. `mockRowIds()` in `rowIds.ts` replaces `crypto.randomUUID()` with numbered UUIDs, so the ids in responses and golden snapshots stay the same between runs. Wrangler only bundles files reachable from `server.ts`, so nothing in `backend/tests/` ships in the Worker.
+Backend tests are in `backend/tests/database`, `backend/tests/jobs`, `backend/tests/lib`, `backend/tests/middleware`, `backend/tests/repositories`, `backend/tests/routes`, `backend/tests/services` (with `youtube/` and `instagram/` for the platform modules) and `backend/tests/validators`. A route test is named after its route table (`accountRoutes.test.ts`) and exercises the whole stack below it: controller, service and repository. Shared test helpers (`fakeSupabase.ts`, `fakeFetch.ts`, `golden.ts`, `routeHarness.ts`, `rowIds.ts`, the per-platform `*Fixtures.ts` data) and the `*.golden.json` snapshots are in `backend/tests/fixtures/`. `fakeSupabase.ts` also answers `rpc()` for the three merge functions, running the same shallow merge on its in-memory rows (with `p_only_status` and the null-user cron form), and sets `updated_at` on every update and upsert as the database trigger does. The fake also answers `in`, `gte`, `gt` and `limit` (rows come back in stored order, so a test seeds them in the order it expects), inserts and upserts of several rows, and `ignoreDuplicates` upserts that return only the new rows; `fakeSupabase(rows, rpcHandlers)` runs any other database function the test supplies. `fakeFetch.ts` replies can carry headers. `mockRowIds()` in `rowIds.ts` replaces `crypto.randomUUID()` with numbered UUIDs, so the ids in responses and golden snapshots stay the same between runs. Wrangler only bundles files reachable from `server.ts`, so nothing in `backend/tests/` ships in the Worker.
Frontend tests cover shared helpers in `src/lib/` and `src/utils/` (hold-to-confirm timing, command palette ranking, library filtering and paging, platform helpers, and a check that every Lucide icon imported in `src` exists) and page helpers in `src/features/**`, such as `features/analytics/overview/overviewStats.ts`. A testable helper is a plain `.ts` file with no JSX and no `@/` or `@shared/` imports, and its imports of project files (including `shared/types`) are relative paths that end in `.ts`, so Node can load it directly. It uses only erasable TypeScript (no `enum`, no parameter properties) and `import type` for types. This rule lives here, so helper files do not repeat it in a header comment.
@@ -339,7 +340,7 @@ If you have a test post scheduled in the near future, use `GET /api/process-sche
## Future Test Infrastructure
-Already in place: golden tests for `computeVideoAnalytics()`, `computeInstagramAnalytics()` and `computeRedditAnalytics()`, route tests that run each route table, controller, service and repository against a fake Supabase client (`backend/tests/fixtures/`), and repository tests against the same fake. Still to add, in priority order:
+Already in place: golden tests for `computeVideoAnalytics()` and `computeInstagramAnalytics()`, route tests that run each route table, controller, service and repository against a fake Supabase client (`backend/tests/fixtures/`), and repository tests against the same fake. Still to add, in priority order:
1. **Tests for the repositories against a real database** - using a Supabase test project
2. **End-to-end tests** - Playwright for the full login -> view analytics -> publish flow