AI-native design editor. Open-source Figma alternative.
feat: show issues and pull requests on the metrics dashboard (#1358)
Danila Poyarkov854f8fddf2ab
diff --git a/packages/feedback/AGENTS.md b/packages/feedback/AGENTS.mdindex 28f82c3ec..a4e7aa832 100644--- a/packages/feedback/AGENTS.md+++ b/packages/feedback/AGENTS.md@@ -9,5 +9,5 @@ Cloudflare Worker for pings, opt-in usage stats, and the Cloud waitlist; overvie- Routes are chained Hono routers that validate bodies with `validatedJSON(schema)` and export `FeedbackAPI`; clients use `createFeedbackClient` (`hc<FeedbackAPI>`), as Cloud's do, never hand-written paths (`tests/harness.ts` uses `testClient`).- Bindings are declared in `src/env.ts` with importable Workers types, so the app can typecheck `FeedbackAPI`; never use the generated global `Env` in code the router reaches. Run `bun --filter @open-pencil/feedback types` after changing `wrangler.jsonc`; `src/index.ts` checks `Env` against `FeedbackBindings` and `bun run test:feedback` checks the generated file.- Outside services (`fetch`, the clock) come through `FeedbackServices`, and bindings through `Env`, so tests run the real app against a local D1 under `bun test` (`tests/harness.ts`).-- The metrics snapshot (`src/snapshot/`) keys every table on the UTC day it describes and replaces whole days in one D1 batch (`replaceDays`), so a rerun corrects a day and a failed write keeps the old rows; it writes the table it resumes from (`site_visits`) last, runs each source on its own, and parses every answer with Valibot before writing (`tests/snapshot.test.ts`).+- The metrics snapshot (`src/snapshot/`) keys every table on the UTC day it describes and replaces whole days in one D1 batch (`replaceDays`), so a rerun corrects a day and a failed write keeps the old rows; it writes the table it resumes from (`site_visits`) last, runs each source on its own, and parses every answer with Valibot before writing (`tests/snapshot.test.ts`). Issues and pull requests are the exception: `repo_items` mirrors each one by number and resumes from its newest update, and the admin API derives daily counts from it.- Everything under `/admin` passes `requireAccess` (`src/admin/access.ts`), which verifies Cloudflare Access's signed token against the team's keys and the application's audience even though Access already blocks others at the edge; admin answers are `private, no-store` and carry waitlist domains, never addresses (`tests/admin.test.ts`).diff --git a/packages/feedback/README.md b/packages/feedback/README.mdindex 324310a5d..412435529 100644--- a/packages/feedback/README.md+++ b/packages/feedback/README.md@@ -10,7 +10,7 @@ The Cloudflare Worker behind `feedback.openpencil.dev`. It is operated by the Op| `GET /admin/api/snapshot?start&end` | The metrics dashboard's data for a range of UTC days, behind Cloudflare Access. | Nothing; it reads pings, snapshots, and the waitlist from D1 (email domains only) and asks PostHog for usage. || `POST /waitlist` | OpenPencil Cloud waitlist sign-ups from the website and the web app's Settings, checked by Turnstile and confirmed by email. | The address and optional note; unconfirmed sign-ups are removed after seven days. |-Two daily cron jobs run besides the routes. Just after midnight UTC the metrics snapshot records the day that ended for the team's metrics dashboard: GitHub stars and forks, running download totals per release and kind of file (installers, macOS updates, and `latest.json` update checks), repository views, clones, and referrers, and Cloudflare's visits to `openpencil.dev` and `app.openpencil.dev` with the website's top pages and countries. GitHub keeps traffic for 14 days and Cloudflare's Free plan keeps visits for 31, so these tables are the only lasting history; each run also fetches again the last few days Cloudflare may still have been counting, and fills any missing days it still can. At 03:17 UTC, retention deletes unconfirmed waitlist sign-ups.+Two daily cron jobs run besides the routes. Just after midnight UTC the metrics snapshot records the day that ended for the team's metrics dashboard: GitHub stars and forks, running download totals per release and kind of file (installers, macOS updates, and `latest.json` update checks), repository views, clones, and referrers, and Cloudflare's visits to `openpencil.dev` and `app.openpencil.dev` with the website's top pages and countries. It also mirrors the repository's issues and pull requests (author association, opening, closing, and merge times), syncing only what changed since the last run, so open counts per day go back to the repository's start. GitHub keeps traffic for 14 days and Cloudflare's Free plan keeps visits for 31, so these tables are the only lasting history; each run also fetches again the last few days Cloudflare may still have been counting, and fills any missing days it still can. At 03:17 UTC, retention deletes unconfirmed waitlist sign-ups.`@open-pencil/feedback/contract` holds the request schemas and the event list, and `@open-pencil/feedback/client` is a client typed by the Worker's routes (`hc<FeedbackAPI>`). The app sends through that client and the privacy page renders its tables from the contract, so the documented, sent, and accepted data cannot drift apart.@@ -36,6 +36,6 @@ Done once on the Cloudflare account; `.github/workflows/feedback.yml` deploys ev2. Onboard `openpencil.dev` to Email Service so `[email protected]` can send. Sending to addresses outside the account needs the Workers Paid plan; send one confirmation to an outside address before announcing the waitlist.3. Create a Turnstile widget for `openpencil.dev` and `app.openpencil.dev`, the hostnames in `TURNSTILE_HOSTNAMES` (its public site key is `TURNSTILE_SITE_KEY` in the contract; the form gives it the `waitlist` action), then `bunx wrangler secret put TURNSTILE_SECRET`.4. Create a PostHog EU project with "Discard client IP data" on and data retention at 12 months, as the privacy page promises, then `bunx wrangler secret put POSTHOG_KEY` with its project key.-5. For the metrics snapshot, `bunx wrangler secret put GITHUB_TOKEN` with a fine-grained token for the repository in `GITHUB_REPOSITORY` that has read-only **Administration** access, which the traffic API requires (every token can already read the public repository's releases), and `bunx wrangler secret put CLOUDFLARE_ANALYTICS_TOKEN` with an account API token that has **Zone → Analytics → Read** on the zone in `SITE_ZONE_ID`.+5. For the metrics snapshot, `bunx wrangler secret put GITHUB_TOKEN` with a fine-grained token for the repository in `GITHUB_REPOSITORY` that has read-only **Administration** access, which the traffic API requires (every token can already read the public repository's releases, issues, and pull requests), and `bunx wrangler secret put CLOUDFLARE_ANALYTICS_TOKEN` with an account API token that has **Zone → Analytics → Read** on the zone in `SITE_ZONE_ID`.6. For the dashboard's API, create a Cloudflare Access self-hosted application for `feedback.openpencil.dev/admin/*` that allows the team's addresses (add the One-time PIN login method for people without a Cloudflare account), then `bunx wrangler secret put ACCESS_TEAM_DOMAIN` with `https://<team>.cloudflareaccess.com` and `bunx wrangler secret put ACCESS_AUD` with the application's audience tag. Until both are set, `/admin` refuses every request.7. Create a PostHog personal API key scoped to the project in `POSTHOG_PROJECT_ID` with only **Query: Read**, then `bunx wrangler secret put POSTHOG_PERSONAL_KEY`.diff --git a/packages/feedback/migrations/0004_repo_items.sql b/packages/feedback/migrations/0004_repo_items.sqlnew file mode 100644index 000000000..d7f510bef--- /dev/null+++ b/packages/feedback/migrations/0004_repo_items.sql@@ -0,0 +1,16 @@+-- The repository's issues and pull requests, mirrored by the daily snapshot. Each one's opening,+-- closing, and merge times give the open counts on any past day, so the whole history comes from+-- this table rather than from daily totals. Times are UTC ISO timestamps.+CREATE TABLE repo_items (+ number INTEGER PRIMARY KEY,+ -- 'issue' or 'pull'.+ kind TEXT NOT NULL,+ -- GitHub's author_association as of the last sync: OWNER, MEMBER, COLLABORATOR, CONTRIBUTOR...+ author_association TEXT NOT NULL,+ created_at TEXT NOT NULL,+ closed_at TEXT,+ -- Pull requests only; a closed pull request without it was closed unmerged.+ merged_at TEXT,+ -- GitHub's last update, where the next sync resumes.+ updated_at TEXT NOT NULL+) WITHOUT ROWID;diff --git a/packages/feedback/src/admin/snapshot.ts b/packages/feedback/src/admin/snapshot.tsindex 78c285ba1..04b3ac6cc 100644--- a/packages/feedback/src/admin/snapshot.ts+++ b/packages/feedback/src/admin/snapshot.ts@@ -1,9 +1,9 @@import type { DailyGrowth, MetricsQuery, MetricsSnapshot, RankedCount } from '#feedback/contract'-import { eachDay, utcDayOf } from '#feedback/days'+import { eachDay, utcDayOf, utcDayOfTimestamp } from '#feedback/days'import { createFeedbackDatabase, type FeedbackDatabase } from '#feedback/db'import type { FeedbackBindings, FeedbackServices } from '#feedback/env'import { minDate, parseDate, toZoned } from '@internationalized/date'-import { groupBy, maxBy, sumBy } from 'es-toolkit'+import { countBy, groupBy, maxBy, omit, partition, sumBy } from 'es-toolkit'import type { Kysely } from 'kysely'import { fetchUsage } from './posthog'@@ -149,10 +149,15 @@ async function site(}}-async function github(db: Kysely<FeedbackDatabase>, range: MetricsQuery, days: string[]) {+async function github(+ db: Kysely<FeedbackDatabase>,+ range: MetricsQuery,+ days: string[],+ finished: string[]+) {// One day earlier than the range, so its first day has something to grow from.const from = parseDate(range.start).subtract({ days: 1 }).toString()- const [stars, downloads, traffic, lastReferrerDay] = await Promise.all([+ const [stars, downloads, traffic, lastReferrerDay, daily] = await Promise.all([db.selectFrom('githubStars').selectAll()@@ -176,7 +181,9 @@ async function github(db: Kysely<FeedbackDatabase>, range: MetricsQuery, days: s.selectFrom('repoReferrers').select((eb) => eb.fn.max('day').as('day')).where('day', '<=', range.end)- .executeTakeFirst()+ .executeTakeFirst(),+ // The mirror is synced once a day, so today's counts would still be yesterday's.+ activity(db, range, finished)])const referrers = lastReferrerDay?.day? await db@@ -226,7 +233,8 @@ async function github(db: Kysely<FeedbackDatabase>, range: MetricsQuery, days: suniqueViews: row.uniqueViews,clones: row.clones})),- referrers: ranking(referrers)+ referrers: ranking(referrers),+ activity: daily}}@@ -239,6 +247,79 @@ function timestampRange(range: MetricsQuery) {}}+/** The authors GitHub counts as the repository's own; everyone else is the community. */+const TEAM_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR'])++type RepoItemRow = Pick<+ FeedbackDatabase['repoItems'],+ 'kind' | 'authorAssociation' | 'createdAt' | 'closedAt' | 'mergedAt'+>++/**+ * Each finished day's open issues or pull requests, counted from the mirror: open before the+ * range, plus what was opened, minus what was closed, day by day. Times are compared as the+ * ISO strings they are stored as.+ */+function tally(items: RepoItemRow[], days: string[], from: string, until: string) {+ const inRange = (moment: string | null): moment is string =>+ moment !== null && moment >= from && moment < until+ const perDay = (moments: (string | null)[]) =>+ countBy(moments.filter(inRange), (moment) => utcDayOfTimestamp(moment).toString())+ const count = (group: RepoItemRow[]) => {+ const opened = perDay(group.map((item) => item.createdAt))+ const closed = perDay(group.map((item) => item.closedAt))+ const merged = perDay(group.map((item) => item.mergedAt))+ let open = group.filter((item) => item.createdAt < from).length+ return days.map((day) => {+ open += (opened[day] ?? 0) - (closed[day] ?? 0)+ return { open, opened: opened[day] ?? 0, closed: closed[day] ?? 0, merged: merged[day] ?? 0 }+ })+ }+ const [team, community] = partition(items, (item) =>+ TEAM_ASSOCIATIONS.has(item.authorAssociation)+ )+ const byTeam = count(team)+ const byCommunity = count(community)+ // Both tallies have one entry per day, in the same order.+ return days.map((day, index) => {+ const ours = byTeam[index]+ const theirs = byCommunity[index]+ return {+ day,+ openTeam: ours.open,+ openCommunity: theirs.open,+ openedTeam: ours.opened,+ openedCommunity: theirs.opened,+ closedTeam: ours.closed,+ closedCommunity: theirs.closed,+ mergedTeam: ours.merged,+ mergedCommunity: theirs.merged+ }+ })+}++async function activity(db: Kysely<FeedbackDatabase>, range: MetricsQuery, days: string[]) {+ const { from, until } = timestampRange(range)+ const [items, synced] = await Promise.all([+ db+ .selectFrom('repoItems')+ .select(['kind', 'authorAssociation', 'createdAt', 'closedAt', 'mergedAt'])+ .where('createdAt', '<', until)+ .where((eb) => eb.or([eb('closedAt', 'is', null), eb('closedAt', '>=', from)]))+ .execute(),+ db.selectFrom('repoItems').select('number').limit(1).executeTakeFirst()+ ])+ if (!synced) return { issues: [], pulls: [] }+ const [pulls, issues] = partition(items, (item) => item.kind === 'pull')+ return {+ // Issues are never merged.+ issues: tally(issues, days, from, until).map((day) =>+ omit(day, ['mergedTeam', 'mergedCommunity'])+ ),+ pulls: tally(pulls, days, from, until)+ }+}+async function waitlist(db: Kysely<FeedbackDatabase>, range: MetricsQuery) {const { from, until } = timestampRange(range)const [totals, recent] = await Promise.all([@@ -306,18 +387,14 @@ export async function buildSnapshot(const end = minDate(parseDate(query.end), today) ?? todayconst range = { start: query.start, end: end.toString() }const days = eachDay(parseDate(range.start), end).map(String)+ // Visits and the issue mirror are recorded once a day has ended, so today never has any.+ const finished = days.filter((day) => parseDate(day).compare(today) < 0)const db = createFeedbackDatabase(env.DB)const [earliest, pinged, visited, repository, signups, usage] = await Promise.all([firstDay(db),pings(db, range, days),- // Visits are recorded once a day has ended, so today never has any.- site(- db,- env,- range,- days.filter((day) => parseDate(day).compare(today) < 0)- ),- github(db, range, days),+ site(db, env, range, finished),+ github(db, range, days, finished),waitlist(db, range),fetchUsage(env, services, range).catch((error: unknown) => {console.warn('PostHog usage unavailable', { error: String(error) })diff --git a/packages/feedback/src/contract/metrics.ts b/packages/feedback/src/contract/metrics.tsindex 7b7bdeeee..4b4b1afbe 100644--- a/packages/feedback/src/contract/metrics.ts+++ b/packages/feedback/src/contract/metrics.ts@@ -49,6 +49,21 @@ export type RankedCount = v.InferOutput<typeof RankedCountSchema>const DailyGrowthSchema = v.object({ day: IsoDay, added: v.number() })export type DailyGrowth = v.InferOutput<typeof DailyGrowthSchema>+/**+ * A day of issues or pull requests, split between the team (the repository's owners, members,+ * and collaborators) and the community: how many were open at the end of the day, and how many+ * were opened and closed that day.+ */+const IssueDaySchema = v.object({+ day: IsoDay,+ openTeam: Count,+ openCommunity: Count,+ openedTeam: Count,+ openedCommunity: Count,+ closedTeam: Count,+ closedCommunity: Count+})+/** What PostHog knows about the installs that share usage stats; `null` when it could not be asked. */const MetricsUsageSchema = v.object({/** Different installs that opened the app in the range. */@@ -98,7 +113,14 @@ export const MetricsSnapshotSchema = v.object({updateChecks: v.array(DailyGrowthSchema)}),traffic: v.array(v.object({ day: IsoDay, views: Count, uniqueViews: Count, clones: Count })),- referrers: v.array(RankedCountSchema)+ referrers: v.array(RankedCountSchema),+ /** Issues and pull requests per finished day, by the team and by everyone else; empty until the first sync. */+ activity: v.object({+ issues: v.array(IssueDaySchema),+ pulls: v.array(+ v.object({ ...IssueDaySchema.entries, mergedTeam: Count, mergedCommunity: Count })+ )+ })}),waitlist: v.object({total: Count,diff --git a/packages/feedback/src/db/schema.ts b/packages/feedback/src/db/schema.tsindex 57e2c8b36..64fb97556 100644--- a/packages/feedback/src/db/schema.ts+++ b/packages/feedback/src/db/schema.ts@@ -68,6 +68,16 @@ export interface SiteCountriesTable {visits: number}+export interface RepoItemTable {+ number: number+ kind: 'issue' | 'pull'+ authorAssociation: string+ createdAt: string+ closedAt: string | null+ mergedAt: string | null+ updatedAt: string+}+/** The D1 tables `migrations/` creates, in Kysely's camelCase. */export interface FeedbackDatabase {usagePings: UsagePingTable@@ -79,4 +89,5 @@ export interface FeedbackDatabase {siteVisits: SiteVisitsTablesitePages: SitePagesTablesiteCountries: SiteCountriesTable+ repoItems: RepoItemTable}diff --git a/packages/feedback/src/snapshot/github.ts b/packages/feedback/src/snapshot/github.tsindex 4ef792cc9..c7311492d 100644--- a/packages/feedback/src/snapshot/github.ts+++ b/packages/feedback/src/snapshot/github.ts@@ -8,8 +8,8 @@ import { releaseFileKind } from './assets'const API = 'https://api.github.com'const REQUEST_TIMEOUT_MS = 15_000-// GitHub's maximum page size; a repository with more releases takes several pages.-const RELEASES_PER_PAGE = 100+// GitHub's maximum page size; a repository with more releases or issues takes several pages.+const PER_PAGE = 100const RepositorySchema = v.object({ stargazers_count: v.number(), forks_count: v.number() })const ReleasesSchema = v.array(@@ -21,6 +21,17 @@ const ReleasesSchema = v.array(const TrafficDaySchema = v.object({ timestamp: v.string(), count: v.number(), uniques: v.number() })const ViewsSchema = v.object({ views: v.array(TrafficDaySchema) })const ClonesSchema = v.object({ clones: v.array(TrafficDaySchema) })+const IssuesSchema = v.array(+ v.object({+ number: v.number(),+ author_association: v.string(),+ created_at: v.string(),+ updated_at: v.string(),+ closed_at: v.nullable(v.string()),+ // Present on pull requests only; `/issues` lists both.+ pull_request: v.optional(v.object({ merged_at: v.nullable(v.string()) }))+ })+)const ReferrersSchema = v.array(v.object({ referrer: v.string(), count: v.number(), uniques: v.number() }))@@ -43,6 +54,20 @@ export interface GithubTraffic {referrers: { referrer: string; views: number; uniqueViews: number }[]}+export interface RepoItem {+ number: number+ kind: 'issue' | 'pull'+ /** How the author relates to the repository, as GitHub names it: `MEMBER`, `CONTRIBUTOR`... */+ authorAssociation: string+ createdAt: string+ closedAt: string | null+ mergedAt: string | null+ updatedAt: string+}++/** GitHub's timestamps in the `toISOString()` form the other tables use, so they compare as strings. */+const timestamp = (value: string) => new Date(value).toISOString()+/** Reads the repository's GitHub API with the snapshot's token; a failed or unexpected answer throws. */export function githubClient(fetcher: FeedbackServices['fetch'],@@ -73,12 +98,9 @@ export function githubClient(async function releases() {const all: v.InferOutput<typeof ReleasesSchema> = []for (let page = 1; ; page++) {- const batch = await get(- `/releases?per_page=${RELEASES_PER_PAGE}&page=${page}`,- ReleasesSchema- )+ const batch = await get(`/releases?per_page=${PER_PAGE}&page=${page}`, ReleasesSchema)all.push(...batch)- if (batch.length < RELEASES_PER_PAGE) return all+ if (batch.length < PER_PAGE) return all}}@@ -107,6 +129,33 @@ export function githubClient(return { stars: repository.stargazers_count, forks: repository.forks_count, downloads }},+ /**+ * One page of issues and pull requests, least recently updated first, from those updated+ * at `since` or later; without it, from the oldest. `full` says another page may follow.+ */+ async itemsUpdatedSince(+ since: string | undefined+ ): Promise<{ items: RepoItem[]; full: boolean }> {+ const query = new URLSearchParams({+ state: 'all',+ sort: 'updated',+ direction: 'asc',+ per_page: String(PER_PAGE)+ })+ if (since) query.set('since', since)+ const page = await get(`/issues?${query.toString()}`, IssuesSchema)+ const items = page.map((item): RepoItem => ({+ number: item.number,+ kind: item.pull_request ? 'pull' : 'issue',+ authorAssociation: item.author_association,+ createdAt: timestamp(item.created_at),+ closedAt: item.closed_at ? timestamp(item.closed_at) : null,+ mergedAt: item.pull_request?.merged_at ? timestamp(item.pull_request.merged_at) : null,+ updatedAt: timestamp(item.updated_at)+ }))+ return { items, full: page.length === PER_PAGE }+ },+/** The last 14 days of views and clones, and the referrers over that window. */async traffic(): Promise<GithubTraffic> {const [views, clones, referrers] = await Promise.all([diff --git a/packages/feedback/src/snapshot/index.ts b/packages/feedback/src/snapshot/index.tsindex 2baff4efb..cde1c5667 100644--- a/packages/feedback/src/snapshot/index.ts+++ b/packages/feedback/src/snapshot/index.ts@@ -6,7 +6,7 @@ import { compact } from 'es-toolkit'import { cloudflareClient } from './cloudflare'import { githubClient } from './github'-import { lastDay, replaceDays, type SnapshotStore } from './store'+import { lastDay, lastItemUpdate, replaceDays, saveRepoItems, type SnapshotStore } from './store'/*** How far back the visit history is filled: Cloudflare's Free plan keeps 31 days and answers at@@ -15,8 +15,13 @@ import { lastDay, replaceDays, type SnapshotStore } from './store'const BACKFILL_DAYS = 28/** Days Cloudflare may still be counting; they are fetched again on the next runs. */const SETTLING_DAYS = 3+/**+ * Pages of 100 issues and pull requests one run reads at most, which keeps a run inside the+ * Worker's subrequest limit; a bigger first sync finishes on the next runs.+ */+const MAX_ITEM_PAGES = 20-export type SnapshotSource = 'github' | 'traffic' | 'site'+export type SnapshotSource = 'github' | 'traffic' | 'site' | 'activity'interface Run {store: SnapshotStore@@ -111,16 +116,36 @@ async function recordSite({ store, env, services, yesterday }: Run) {await replaceDays(store, 'siteVisits', days, visits)}+/**+ * Issues and pull requests updated since the last sync, the first time the whole history. Each+ * page resumes from the newest update on the page before, so an item updated mid-sync moves to+ * a later page instead of shifting another one past the window. Items deleted or transferred+ * away keep their last mirrored state.+ */+async function recordActivity({ store, env, services }: Run) {+ const github = githubClient(services.fetch, env.GITHUB_REPOSITORY, env.GITHUB_TOKEN)+ let since = await lastItemUpdate(store.db)+ for (let page = 0; page < MAX_ITEM_PAGES; page++) {+ const { items, full } = await github.itemsUpdatedSince(since)+ await saveRepoItems(store, items)+ const newest = items.at(-1)?.updatedAt+ // A full page that ends where it started would be read again forever.+ if (!full || !newest || newest === since) return+ since = newest+ }+}+const SOURCES: [SnapshotSource, (run: Run) => Promise<void>][] = [['github', recordGithub],['traffic', recordTraffic],- ['site', recordSite]+ ['site', recordSite],+ ['activity', recordActivity]]/*** The daily metrics snapshot, run just after midnight UTC. GitHub reports only running totals* and keeps traffic for 14 days, and Cloudflare keeps visits for 31, so these tables are the- * only lasting history. Each source runs on its own: one failing still records the others, and+ * only lasting history; issues and pull requests are mirrored whole. Each source runs on its own: one failing still records the others, and* its gap is filled by the next run where the API still has the days.*/export async function runSnapshot(diff --git a/packages/feedback/src/snapshot/store.ts b/packages/feedback/src/snapshot/store.tsindex 5faa731b4..95de62cb5 100644--- a/packages/feedback/src/snapshot/store.ts+++ b/packages/feedback/src/snapshot/store.ts@@ -58,10 +58,51 @@ export async function replaceDays<T extends SnapshotTable>(for (const batch of chunk(rows, perStatement))statements.push(db.insertInto(table).values(batch).compile())}+ await runBatch(d1, statements)+}++async function runBatch(d1: D1Database, statements: CompiledQuery[]): Promise<void> {if (!statements.length) returnawait d1.batch(statements.map((query) => d1.prepare(query.sql).bind(...query.parameters)))}+/** Adds issues and pull requests, or updates the ones already mirrored, in one batch. */+export async function saveRepoItems(+ { db, d1 }: SnapshotStore,+ items: Insertable<FeedbackDatabase['repoItems']>[]+): Promise<void> {+ if (!items.length) return+ const perStatement = Math.floor(MAX_BOUND_VALUES / Object.keys(items[0]).length)+ await runBatch(+ d1,+ chunk(items, perStatement).map((batch) =>+ db+ .insertInto('repoItems')+ .values(batch)+ .onConflict((conflict) =>+ conflict.column('number').doUpdateSet((eb) => ({+ kind: eb.ref('excluded.kind'),+ authorAssociation: eb.ref('excluded.authorAssociation'),+ createdAt: eb.ref('excluded.createdAt'),+ closedAt: eb.ref('excluded.closedAt'),+ mergedAt: eb.ref('excluded.mergedAt'),+ updatedAt: eb.ref('excluded.updatedAt')+ }))+ )+ .compile()+ )+ )+}++/** GitHub's newest update among the mirrored issues and pull requests, if any are. */+export async function lastItemUpdate(db: Kysely<FeedbackDatabase>): Promise<string | undefined> {+ const row = await db+ .selectFrom('repoItems')+ .select((eb) => eb.fn.max('updatedAt').as('updatedAt'))+ .executeTakeFirst()+ return row?.updatedAt ?? undefined+}+/** The newest day recorded in a table, if any. */export async function lastDay(db: Kysely<FeedbackDatabase>,diff --git a/packages/feedback/tests/admin.test.ts b/packages/feedback/tests/admin.test.tsindex 9f22eb3d5..bca623fd5 100644--- a/packages/feedback/tests/admin.test.ts+++ b/packages/feedback/tests/admin.test.ts@@ -23,7 +23,8 @@ const TABLES = ['repoReferrers','siteVisits','sitePages',- 'siteCountries'+ 'siteCountries',+ 'repoItems'] as const/** An Access token as Cloudflare would issue it, signed with `key`; `expiresIn` null leaves `exp` out. */@@ -343,6 +344,101 @@ describe('metrics snapshot API', () => {})})+ test('issues and pull requests count open ones per finished day, team apart from community', async () => {+ expect((await snapshot()).github.activity).toEqual({ issues: [], pulls: [] })+ const opened = (createdAt: string) => ({ createdAt, updatedAt: createdAt })+ await database()+ .insertInto('repoItems')+ .values([+ // Open before the range, closed inside it.+ {+ number: 1,+ kind: 'issue',+ authorAssociation: 'NONE',+ ...opened('2026-10-10T09:00:00.000Z'),+ closedAt: '2026-10-15T05:00:00.000Z',+ mergedAt: null+ },+ {+ number: 2,+ kind: 'issue',+ authorAssociation: 'MEMBER',+ ...opened('2026-10-15T23:59:59.000Z'),+ closedAt: null,+ mergedAt: null+ },+ // Closed before the range: counts nowhere.+ {+ number: 3,+ kind: 'issue',+ authorAssociation: 'CONTRIBUTOR',+ ...opened('2026-10-01T09:00:00.000Z'),+ closedAt: '2026-10-05T09:00:00.000Z',+ mergedAt: null+ },+ // Opened today, which is not counted yet.+ {+ number: 4,+ kind: 'issue',+ authorAssociation: 'CONTRIBUTOR',+ ...opened('2026-10-20T09:00:00.000Z'),+ closedAt: null,+ mergedAt: null+ },+ {+ number: 5,+ kind: 'pull',+ authorAssociation: 'OWNER',+ ...opened('2026-10-14T09:00:00.000Z'),+ closedAt: '2026-10-16T09:00:00.000Z',+ mergedAt: '2026-10-16T09:00:00.000Z'+ },+ // Closed without merging.+ {+ number: 6,+ kind: 'pull',+ authorAssociation: 'FIRST_TIME_CONTRIBUTOR',+ ...opened('2026-10-16T09:00:00.000Z'),+ closedAt: '2026-10-17T09:00:00.000Z',+ mergedAt: null+ }+ ])+ .execute()+ const { activity } = (await snapshot('2026-10-14', '2026-10-20')).github+ const zero = { openedTeam: 0, openedCommunity: 0, closedTeam: 0, closedCommunity: 0 }+ expect(activity.issues).toEqual([+ { day: '2026-10-14', openTeam: 0, openCommunity: 1, ...zero },+ {+ day: '2026-10-15',+ openTeam: 1,+ openCommunity: 0,+ ...zero,+ openedTeam: 1,+ closedCommunity: 1+ },+ { day: '2026-10-16', openTeam: 1, openCommunity: 0, ...zero },+ { day: '2026-10-17', openTeam: 1, openCommunity: 0, ...zero },+ { day: '2026-10-18', openTeam: 1, openCommunity: 0, ...zero },+ { day: '2026-10-19', openTeam: 1, openCommunity: 0, ...zero }+ ])+ const unmerged = { mergedTeam: 0, mergedCommunity: 0 }+ expect(activity.pulls.slice(0, 4)).toEqual([+ { day: '2026-10-14', openTeam: 1, openCommunity: 0, ...zero, ...unmerged, openedTeam: 1 },+ { day: '2026-10-15', openTeam: 1, openCommunity: 0, ...zero, ...unmerged },+ {+ day: '2026-10-16',+ openTeam: 0,+ openCommunity: 1,+ ...zero,+ openedCommunity: 1,+ closedTeam: 1,+ mergedTeam: 1,+ mergedCommunity: 0+ },+ { day: '2026-10-17', openTeam: 0, openCommunity: 0, ...zero, ...unmerged, closedCommunity: 1 }+ ])+ })+test('the waitlist shows email domains only', async () => {await database().insertInto('waitlist')diff --git a/packages/feedback/tests/snapshot.test.ts b/packages/feedback/tests/snapshot.test.tsindex a850142ab..235c5fcf1 100644--- a/packages/feedback/tests/snapshot.test.ts+++ b/packages/feedback/tests/snapshot.test.ts@@ -22,9 +22,22 @@ const TABLES = ['repoReferrers','siteVisits','sitePages',- 'siteCountries'+ 'siteCountries',+ 'repoItems'] as const+/** An issue or pull request as `/issues` lists it, last updated `updated`. */+function item(number: number, updated: string, fields: Record<string, unknown> = {}) {+ return {+ number,+ author_association: 'CONTRIBUTOR',+ created_at: '2026-10-01T09:00:00Z',+ updated_at: updated,+ closed_at: null,+ ...fields+ }+}+const RELEASES = [{tag_name: 'v0.16.0',@@ -77,6 +90,16 @@ function answerGithub() {service.respond(`${REPO}/traffic/popular/referrers`, () =>Response.json([{ referrer: 'news.ycombinator.com', count: 700, uniques: 300 }]))+ service.respond(`${REPO}/issues`, () =>+ Response.json([+ item(1, '2026-10-02T10:00:00Z', {+ author_association: 'MEMBER',+ closed_at: '2026-10-02T10:00:00Z',+ pull_request: { merged_at: '2026-10-02T10:00:00Z' }+ }),+ item(2, '2026-10-03T08:00:00Z')+ ])+ )}/** Answers every day with the same visits, and each breakdown with `pages` for the website. */@@ -128,7 +151,8 @@ const rows = {repoReferrers: () => database().selectFrom('repoReferrers').selectAll().orderBy('day').execute(),siteVisits: () =>database().selectFrom('siteVisits').selectAll().orderBy(['day', 'host']).execute(),- siteCountries: () => database().selectFrom('siteCountries').selectAll().execute()+ siteCountries: () => database().selectFrom('siteCountries').selectAll().execute(),+ repoItems: () => database().selectFrom('repoItems').selectAll().orderBy('number').execute()}beforeAll(async () => {@@ -351,4 +375,52 @@ describe('metrics snapshot', () => {expect(await runSnapshot(service.env, service.services)).toEqual({ failed: ['site'] })expect(await rows.siteVisits()).toEqual([])})++ test('mirrors issues and pull requests with their author and merge time', async () => {+ expect(await runSnapshot(service.env, service.services)).toEqual({ failed: [] })+ expect(await rows.repoItems()).toEqual([+ {+ number: 1,+ kind: 'pull',+ authorAssociation: 'MEMBER',+ createdAt: '2026-10-01T09:00:00.000Z',+ closedAt: '2026-10-02T10:00:00.000Z',+ mergedAt: '2026-10-02T10:00:00.000Z',+ updatedAt: '2026-10-02T10:00:00.000Z'+ },+ {+ number: 2,+ kind: 'issue',+ authorAssociation: 'CONTRIBUTOR',+ createdAt: '2026-10-01T09:00:00.000Z',+ closedAt: null,+ mergedAt: null,+ updatedAt: '2026-10-03T08:00:00.000Z'+ }+ ])+ })++ test('pages on from the newest update, and the next run resumes there', async () => {+ const first = Array.from({ length: 100 }, (_, index) =>+ item(index + 1, `2026-10-05T10:${String(Math.floor(index / 2)).padStart(2, '0')}:00Z`)+ )+ const since = (call: FetchCall) => new URL(call.url).searchParams.get('since')+ service.respond(`${REPO}/issues`, (call) => {+ if (since(call) === null) return Response.json(first)+ // The page boundary comes back again, now closed.+ if (since(call) === '2026-10-05T10:49:00.000Z')+ return Response.json([+ item(100, '2026-10-05T11:00:00Z', { closed_at: '2026-10-05T11:00:00Z' })+ ])+ return Response.json([])+ })+ await runSnapshot(service.env, service.services)+ const items = await rows.repoItems()+ expect(items).toHaveLength(100)+ expect(items.at(-1)?.closedAt).toBe('2026-10-05T11:00:00.000Z')+ service.fetchCalls.length = 0+ await runSnapshot(service.env, service.services)+ const issueCalls = service.fetchCalls.filter((call) => call.url.startsWith(`${REPO}/issues`))+ expect(issueCalls.map(since)).toEqual(['2026-10-05T11:00:00.000Z'])+ })})diff --git a/src/components/metrics/DailyLevelChart.vue b/src/components/metrics/DailyLevelChart.vuenew file mode 100644index 000000000..f2296d94d--- /dev/null+++ b/src/components/metrics/DailyLevelChart.vue@@ -0,0 +1,68 @@+<script setup lang="ts" generic="Row extends { day: string }">+import { Area, AreaChart, CartesianGrid, Legend, Tooltip, XAxis, YAxis } from 'vccs'+import { computed } from 'vue'++import { formatCount, formatDay } from '@/app/metrics/format'++import type { DailySeries } from './DailyChart.vue'++/**+ * A level at the end of each UTC day, such as how many issues were open, with series stacked+ * so the top edge is the total. Levels are read as change over time, so they are areas rather+ * than the bars `DailyChart` draws for per-day counts.+ */+const {+ label,+ days,+ series,+ height = 200+} = defineProps<{+ /** The chart's accessible name. */+ label: string+ days: Row[]+ series: DailySeries<Extract<keyof Row, string>>[]+ height?: number+}>()++const rows = computed(() => days.map((day) => ({ ...day, label: formatDay(day.day) })))+const STACK = 'level'+const FILL_OPACITY = 0.25+const formatTick = (value: unknown) =>+ typeof value === 'number' ? formatCount(value) : String(value)+</script>++<template>+ <AreaChart+ :data="rows"+ :height="height"+ :margin="{ top: 8, right: 0, bottom: 0, left: 0 }"+ :is-animation-active="false"+ class="text-[11px]"+ :title="label"+ >+ <CartesianGrid :vertical="false" />+ <XAxis data-key="label" :tick-line="false" :axis-line="false" :tick-margin="8" />+ <YAxis+ :width="40"+ :tick-line="false"+ :axis-line="false"+ :tick-formatter="formatTick"+ :allow-decimals="false"+ />+ <Tooltip :cursor="{ stroke: 'var(--color-border)' }" />+ <Legend :height="28" vertical-align="top" align="right" icon-type="circle" :icon-size="8" />+ <Area+ v-for="item in series"+ :key="item.key"+ :data-key="item.key"+ :name="item.name"+ type="linear"+ :stack-id="STACK"+ :stroke="item.color"+ :stroke-width="2"+ :fill="item.color"+ :fill-opacity="FILL_OPACITY"+ :is-animation-active="false"+ />+ </AreaChart>+</template>diff --git a/src/components/metrics/MetricsDashboard.stories.ts b/src/components/metrics/MetricsDashboard.stories.tsindex eb5ac8bf5..08e5660f0 100644--- a/src/components/metrics/MetricsDashboard.stories.ts+++ b/src/components/metrics/MetricsDashboard.stories.ts@@ -54,6 +54,130 @@ const traffic = [{ day: '2026-10-17', views: 601, uniqueViews: 299, clones: 3884 },{ day: '2026-10-18', views: 477, uniqueViews: 283, clones: 3807 }]+const issues = [+ {+ day: '2026-10-13',+ openTeam: 23,+ openCommunity: 42,+ openedTeam: 7,+ openedCommunity: 7,+ closedTeam: 0,+ closedCommunity: 1+ },+ {+ day: '2026-10-14',+ openTeam: 23,+ openCommunity: 44,+ openedTeam: 0,+ openedCommunity: 2,+ closedTeam: 0,+ closedCommunity: 0+ },+ {+ day: '2026-10-15',+ openTeam: 23,+ openCommunity: 44,+ openedTeam: 0,+ openedCommunity: 2,+ closedTeam: 0,+ closedCommunity: 2+ },+ {+ day: '2026-10-16',+ openTeam: 23,+ openCommunity: 46,+ openedTeam: 0,+ openedCommunity: 2,+ closedTeam: 0,+ closedCommunity: 0+ },+ {+ day: '2026-10-17',+ openTeam: 24,+ openCommunity: 49,+ openedTeam: 1,+ openedCommunity: 3,+ closedTeam: 0,+ closedCommunity: 0+ },+ {+ day: '2026-10-18',+ openTeam: 25,+ openCommunity: 50,+ openedTeam: 1,+ openedCommunity: 2,+ closedTeam: 0,+ closedCommunity: 1+ }+]+const pulls = [+ {+ day: '2026-10-13',+ openTeam: 15,+ openCommunity: 37,+ openedTeam: 20,+ openedCommunity: 42,+ closedTeam: 21,+ closedCommunity: 6,+ mergedTeam: 21,+ mergedCommunity: 6+ },+ {+ day: '2026-10-14',+ openTeam: 17,+ openCommunity: 43,+ openedTeam: 8,+ openedCommunity: 6,+ closedTeam: 6,+ closedCommunity: 0,+ mergedTeam: 6,+ mergedCommunity: 0+ },+ {+ day: '2026-10-15',+ openTeam: 17,+ openCommunity: 53,+ openedTeam: 14,+ openedCommunity: 13,+ closedTeam: 14,+ closedCommunity: 3,+ mergedTeam: 13,+ mergedCommunity: 2+ },+ {+ day: '2026-10-16',+ openTeam: 17,+ openCommunity: 56,+ openedTeam: 5,+ openedCommunity: 4,+ closedTeam: 5,+ closedCommunity: 1,+ mergedTeam: 4,+ mergedCommunity: 1+ },+ {+ day: '2026-10-17',+ openTeam: 15,+ openCommunity: 60,+ openedTeam: 1,+ openedCommunity: 12,+ closedTeam: 3,+ closedCommunity: 8,+ mergedTeam: 2,+ mergedCommunity: 0+ },+ {+ day: '2026-10-18',+ openTeam: 17,+ openCommunity: 59,+ openedTeam: 6,+ openedCommunity: 1,+ closedTeam: 4,+ closedCommunity: 2,+ mergedTeam: 4,+ mergedCommunity: 1+ }+]const signups = [{ domain: 'crugroup.com', signedUpAt: '2026-10-14T16:12:31Z', confirmed: true },{ domain: 'gmail.com', signedUpAt: '2026-10-14T22:11:38Z', confirmed: true },@@ -91,8 +215,11 @@ const isInRange = (day: string, range: MetricsRange) =>parseDate(day).compare(parseDate(range.start)) >= 0 &&parseDate(day).compare(parseDate(range.end)) <= 0-/** What the feedback Worker answers for a range; `withUsage` false is PostHog not answering. */-function scope(range: MetricsRange, withUsage: boolean): MetricsSnapshot {+/**+ * What the feedback Worker answers for a range; `withUsage` false is PostHog not answering,+ * `withActivity` false is the issue mirror before its first sync.+ */+function scope(range: MetricsRange, withUsage: boolean, withActivity: boolean): MetricsSnapshot {const inRange = <T extends { day: string }>(rows: T[]) =>rows.filter((row) => isInRange(row.day, range))const recent = signups.filter((signup) =>@@ -149,7 +276,10 @@ function scope(range: MetricsRange, withUsage: boolean): MetricsSnapshot {{ name: 'openpencil.dev', value: 467 },{ name: 'Bing', value: 124 },{ name: 'youtube.com', value: 80 }- ]+ ],+ activity: withActivity+ ? { issues: inRange(issues), pulls: inRange(pulls) }+ : { issues: [], pulls: [] }},waitlist: { total: 22, confirmed: 16, added: recent.length, recent: recent.toReversed() },usage: withUsage@@ -188,22 +318,25 @@ const meta = {export default metatype Story = StoryObj<typeof meta>-const story = (frame: string, withUsage = true): Story => ({+const story = (frame: string, withUsage = true, withActivity = true): Story => ({render: () => ({components: { MetricsDashboard },setup: () => {const range = ref(presetRange('7d', TODAY, EARLIEST))- const snapshot = computed(() => scope(range.value, withUsage))+ const snapshot = computed(() => scope(range.value, withUsage, withActivity))return { range, snapshot }},template: `<div class="${frame}"><MetricsDashboard host="feedback.openpencil.dev" :snapshot="snapshot" v-model:range="range" /></div>`})})-export const Overview = story('h-[3000px]')+export const Overview = story('h-[3700px]')/** PostHog did not answer: retention and usage give way to a notice, the rest stays. */-export const WithoutUsage = story('h-[2600px]', false)+export const WithoutUsage = story('h-[3300px]', false)++/** Before the first nightly sync, issues and pull requests give way to a notice. */+export const BeforeIssueSync = story('h-[3000px]', true, false)/** The dashboard in a phone-width window. */-export const Narrow = story('h-[4400px] w-[390px]')+export const Narrow = story('h-[5600px] w-[390px]')diff --git a/src/components/metrics/MetricsDashboard.vue b/src/components/metrics/MetricsDashboard.vueindex f0fa99933..c9e334c8a 100644--- a/src/components/metrics/MetricsDashboard.vue+++ b/src/components/metrics/MetricsDashboard.vue@@ -23,12 +23,20 @@ import { metricsDashboard } from '@/theme/metrics/dashboard'import DailyChart from './DailyChart.vue'import type { DailySeries } from './DailyChart.vue'+import DailyLevelChart from './DailyLevelChart.vue'import MetricsCard from './MetricsCard.vue'import MetricsRangePicker from './MetricsRangePicker.vue'import MetricsTile from './MetricsTile.vue'import PlatformsChart from './PlatformsChart.vue'import RetentionChart from './RetentionChart.vue'-import type { DailyActiveDay, DailyTraffic, DailyVersions, DailyVisits } from './types'+import type {+ DailyActiveDay,+ DailyIssues,+ DailyPulls,+ DailyTraffic,+ DailyVersions,+ DailyVisits+} from './types'import WaitlistList from './WaitlistList.vue'/**@@ -103,6 +111,28 @@ const TRAFFIC_SERIES: DailySeries<keyof DailyTraffic & string>[] = [{ key: 'views', name: 'Views', color: 'var(--color-chart-1)' },{ key: 'uniqueViews', name: 'Unique visitors', color: 'var(--color-chart-3)' }]+// The community leads: outside work is what the team answers to.+const OPEN_SERIES: DailySeries<'openCommunity' | 'openTeam'>[] = [+ { key: 'openCommunity', name: 'Community', color: 'var(--color-chart-1)' },+ { key: 'openTeam', name: 'Team', color: 'var(--color-chart-3)' }+]+const OPENED_SERIES: DailySeries<keyof DailyIssues & string>[] = [+ { key: 'openedCommunity', name: 'Community', color: 'var(--color-chart-1)' },+ { key: 'openedTeam', name: 'Team', color: 'var(--color-chart-3)' }+]+const MERGED_SERIES: DailySeries<keyof DailyPulls & string>[] = [+ { key: 'mergedCommunity', name: 'Community', color: 'var(--color-chart-1)' },+ { key: 'mergedTeam', name: 'Team', color: 'var(--color-chart-3)' }+]+const activity = computed(() => snapshot.github.activity)+/** How many are open at the end of the last finished day, and how many of them are the community's. */+function openNow(days: { openTeam: number; openCommunity: number }[]) {+ const last = days.at(-1)+ return last+ ? `${formatCount(last.openTeam + last.openCommunity)} open · ${formatCount(last.openCommunity)} from the community`+ : undefined+}+// Older versions recede: the question is how much of the day is already on the latest.const versionSeries = computed<DailySeries<keyof DailyVersions & string>[]>(() => [{ key: 'latest', name: snapshot.versions.latest ?? 'Latest', color: 'var(--color-chart-1)' },@@ -354,6 +384,68 @@ const sharingNote = computed(() => {</MetricsCard></div></section>++ <section :class="ui.section()" aria-labelledby="metrics-development">+ <h2 id="metrics-development" :class="ui.sectionHeading()">Development</h2>+ <div v-if="activity.issues.length" :class="ui.row()">+ <MetricsCard+ heading="Issues"+ note="Open at the end of each day, and opened per day. Team: the repository's members and collaborators."+ >+ <template v-if="openNow(activity.issues)" #aside>{{+ openNow(activity.issues)+ }}</template>+ <h4 :class="ui.sectionLabel()">Open</h4>+ <DailyLevelChart+ label="Open issues by the community and the team"+ :days="activity.issues"+ :series="OPEN_SERIES"+ />+ <h4 :class="ui.sectionLabel()">Opened per day</h4>+ <DailyChart+ label="Issues opened per day by the community and the team"+ :days="activity.issues"+ :series="OPENED_SERIES"+ :today="snapshot.today"+ :height="160"+ stacked+ />+ </MetricsCard>+ <MetricsCard+ heading="Pull requests"+ note="Open at the end of each day, and merged per day"+ >+ <template v-if="openNow(activity.pulls)" #aside>{{+ openNow(activity.pulls)+ }}</template>+ <h4 :class="ui.sectionLabel()">Open</h4>+ <DailyLevelChart+ label="Open pull requests by the community and the team"+ :days="activity.pulls"+ :series="OPEN_SERIES"+ />+ <h4 :class="ui.sectionLabel()">Merged per day</h4>+ <DailyChart+ label="Pull requests merged per day from the community and the team"+ :days="activity.pulls"+ :series="MERGED_SERIES"+ :today="snapshot.today"+ :height="160"+ stacked+ />+ </MetricsCard>+ </div>+ <MetricsCard v-else heading="Issues and pull requests">+ <AppPlaceholder+ size="compact"+ :fill="false"+ label="Not synced yet"+ description="The nightly snapshot at 00:05 UTC mirrors the repository's issues and pull requests; their whole history shows from then on."+ >+ <template #icon><icon-lucide-git-pull-request class="size-4" /></template>+ </AppPlaceholder>+ </MetricsCard>+ </section></div></main></div>diff --git a/src/components/metrics/types.ts b/src/components/metrics/types.tsindex 9f430a165..7e4a8a8b2 100644--- a/src/components/metrics/types.ts+++ b/src/components/metrics/types.ts@@ -5,6 +5,8 @@ export type DailyActiveDay = MetricsSnapshot['dailyActive'][number]export type DailyVisits = MetricsSnapshot['visits'][number]export type DailyVersions = MetricsSnapshot['versions']['daily'][number]export type DailyTraffic = MetricsSnapshot['github']['traffic'][number]+export type DailyIssues = MetricsSnapshot['github']['activity']['issues'][number]+export type DailyPulls = MetricsSnapshot['github']['activity']['pulls'][number]export type PlatformCount = MetricsSnapshot['platforms'][number]export type Release = MetricsSnapshot['releases'][number]export type WaitlistSignup = MetricsSnapshot['waitlist']['recent'][number]