Skip to content

AI-native design editor. Open-source Figma alternative.

feat: add the team's metrics dashboard at feedback.openpencil.dev/admin (#1330)

Danila Poyarkovcd0ac03ed02d
diff --git a/.github/workflows/feedback.yml b/.github/workflows/feedback.yml
index 17731d44a..b5d31c001 100644
--- a/.github/workflows/feedback.yml
+++ b/.github/workflows/feedback.yml
@@ -5,6 +5,15 @@ on:
branches: [master]
paths:
- packages/feedback/**
+ # The metrics dashboard page the Worker serves under /admin. Its bundle is built from the
+ # app's src/ (views, components, theme, styles, and the build target in
+ # src/app/shell/support) and this package, so any change there redeploys it.
+ - src/**
+ - metrics.html
+ - package.json
+ - bun.lock
+ - vite.config.ts
+ - vite/**
workflow_dispatch:
concurrency:
@@ -25,6 +34,10 @@ jobs:
- name: Typecheck and test against a local D1
run: bun run test:feedback
+ # Wrangler uploads dist-metrics/ as the Worker's static assets.
+ - name: Build the metrics dashboard page
+ run: bun run build:packages && bun run build:metrics
+
# Migrations run before the new code, so it never queries a table that is not there yet.
- uses: cloudflare/wrangler-action@v4
with:
diff --git a/.gitignore b/.gitignore
index e0db665be..9316a0bba 100644
--- a/.gitignore
+++ b/.gitignore
@@ -98,3 +98,4 @@ packages/feedback/.dev.vars
packages/cloud/deploy/generated/
packages/cloud/dist-standalone/
dist-cloud-portal/
+dist-metrics/
diff --git a/AGENTS.md b/AGENTS.md
index 9df3c1913..442eb490c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -59,7 +59,7 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun
- Non-component folders and files use lowercase or kebab-case except standard entrypoints (`README.md`, `AGENTS.md`, `index.ts`). Component domains use kebab-case folders; Vue files stay PascalCase and component composables camelCase. Do not add new PascalCase app folders or root-level base controls; migrate old ones when touched.
- No `any`, non-null assertions, or `Math.random()`; use precise types, guards, and `crypto.getRandomValues()` — through `randomHex`, `randomInt`, and `randomIndex` from `@open-pencil/scene-graph/random` rather than new copies. New component property IDs come from `createComponentPropertyId()`, and graph entity IDs from the `SceneGraph`'s generator (`createNode`, `createCollection`, `createMode`).
- Valibot for first-party runtime validation. Keep Zod only where an upstream dependency requires it; never maintain parallel first-party schemas in both.
-- Use existing dependencies before writing utilities: `culori` for color conversion, VueUse for browser, event, focus, clipboard, storage, and timer behavior (one-shot rAF or service-owned timers are fine when clearer), `dedent` for multiline prompt composition and embedded examples. Keep substantial prompt prose in the owning Markdown source and compose it.
+- Use existing dependencies before writing utilities: `culori` for color conversion, `@internationalized/date` for calendar days (`CalendarDate`, never millisecond arithmetic or sliced ISO strings; `Temporal` once Workers and the browser baseline ship it), VueUse for browser, event, focus, clipboard, storage, and timer behavior (one-shot rAF or service-owned timers are fine when clearer), `dedent` for multiline prompt composition and embedded examples. Keep substantial prompt prose in the owning Markdown source and compose it.
- Reach for `es-toolkit` before hand-writing a collection or object helper: `uniq`/`uniqBy` over `Set` round trips, `compact` over `filter(Boolean)`, `groupBy`/`keyBy`/`partition`/`countBy` over accumulator loops, `pick`/`omit`/`mapValues`/`mapKeys` over rewriting `Object.entries`, `isEmptyObject`/`isEqual` over manual checks. Keep native code where it is a single clear call (`map`, `some`, `Object.fromEntries` of a direct mapping) or on a measured hot path such as per-frame rendering and layout. `open-pencil/prefer-es-toolkit` enforces the `uniq` and `compact` cases.
- Use `js-base64` directly for Base64: `fromUint8Array`/`toUint8Array` for bytes, `encode`/`decode` for text, and `isValid` before decoding input from outside (clipboard, imported files, tool arguments). Do not wrap it or use `atob`, `btoa`, or `Buffer` Base64 conversions; `open-pencil/no-hand-rolled-base64` enforces this.
- Parse JSON from outside the process (clipboard, files, network, storage, tool arguments) with `v.safeParse(v.pipe(v.string(), v.parseJson(), Schema), text)`, so malformed JSON and a wrong shape fail the same way. Never assert a type on a `JSON.parse` or `.json()` result other than `unknown`; `open-pencil/no-unvalidated-json-parse` enforces this in source, tests, and tooling.
diff --git a/bun.lock b/bun.lock
index 04b0f0029..38d87713e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -28,6 +28,7 @@
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.9",
"@floating-ui/vue": "^1.1.11",
+ "@internationalized/date": "^3.12.3",
"@lezer/highlight": "^1.2.3",
"@nanostores/i18n": "^1.3.3",
"@nanostores/vue": "^1.1.0",
@@ -89,6 +90,7 @@
"tinykeys": "^3.1.0",
"ufo": "^1.6.4",
"valibot": "^1.5.0",
+ "vccs": "1.0.0-beta.2",
"vee-validate": "5.0.0-beta.0",
"vue": "^3.5.43",
"vue-router": "^5.3.1",
@@ -2314,6 +2316,12 @@
"@types/culori": ["@types/[email protected]", "", {}, "sha512-43M51r/22CjhbOXyGT361GZ9vncSVQ39u62x5eJdBQFviI8zWp2X5jzqg7k4M6PVgDQAClpy2bUe2dtwEgEDVQ=="],
+ "@types/d3-path": ["@types/[email protected]", "", {}, "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg=="],
+
+ "@types/d3-sankey": ["@types/[email protected]", "", { "dependencies": { "@types/d3-shape": "^1" } }, "sha512-/3RZSew0cLAtzGQ+C89hq/Rp3H20QJuVRSqFy6RKLe7E0B8kd2iOS1oBsodrgds4PcNVpqWhdUEng/SHvBcJ6Q=="],
+
+ "@types/d3-shape": ["@types/[email protected]", "", { "dependencies": { "@types/d3-path": "*" } }, "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw=="],
+
"@types/debug": ["@types/[email protected]", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="],
"@types/deep-eql": ["@types/[email protected]", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],
@@ -2970,6 +2978,28 @@
"culori": ["[email protected]", "", {}, "sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw=="],
+ "d3-array": ["[email protected]", "", { "dependencies": { "internmap": "^1.0.0" } }, "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ=="],
+
+ "d3-color": ["[email protected]", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
+
+ "d3-format": ["[email protected]", "", {}, "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg=="],
+
+ "d3-hierarchy": ["[email protected]", "", {}, "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA=="],
+
+ "d3-interpolate": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g=="],
+
+ "d3-path": ["[email protected]", "", {}, "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ=="],
+
+ "d3-sankey": ["[email protected]", "", { "dependencies": { "d3-array": "1 - 2", "d3-shape": "^1.2.0" } }, "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ=="],
+
+ "d3-scale": ["[email protected]", "", { "dependencies": { "d3-array": "2.10.0 - 3", "d3-format": "1 - 3", "d3-interpolate": "1.2.0 - 3", "d3-time": "2.1.1 - 3", "d3-time-format": "2 - 4" } }, "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ=="],
+
+ "d3-shape": ["[email protected]", "", { "dependencies": { "d3-path": "^3.1.0" } }, "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA=="],
+
+ "d3-time": ["[email protected]", "", { "dependencies": { "d3-array": "2 - 3" } }, "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q=="],
+
+ "d3-time-format": ["[email protected]", "", { "dependencies": { "d3-time": "1 - 3" } }, "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg=="],
+
"data-uri-to-buffer": ["[email protected]", "", {}, "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw=="],
"data-view-buffer": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-data-view": "^1.0.2" } }, "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ=="],
@@ -2982,6 +3012,8 @@
"decamelize": ["[email protected]", "", {}, "sha512-G7Cqgaelq68XHJNGlZ7lrNQyhZGsFqpwtGFexqUv4IQdjKoSYF7ipZ9UuTJZUSQXFj/XaoBLuEVIVqr8EJngEQ=="],
+ "decimal.js-light": ["[email protected]", "", {}, "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg=="],
+
"decode-named-character-reference": ["[email protected]", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="],
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
@@ -3468,6 +3500,8 @@
"internal-slot": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "hasown": "^2.0.2", "side-channel": "^1.1.0" } }, "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw=="],
+ "internmap": ["[email protected]", "", {}, "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="],
+
"iobuffer": ["[email protected]", "", {}, "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA=="],
"ip-address": ["[email protected]", "", {}, "sha512-4OUAqU9Z1i3vCnS05hzGiFnEMDpQ+62pAD/MVQOp83fYyNC8GleCqaS0QikQBmcWCrKFiUs/B8ztRRiYOAXuCA=="],
@@ -4810,6 +4844,8 @@
"vary": ["[email protected]", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
+ "vccs": ["[email protected]", "", { "dependencies": { "@types/d3-sankey": "^0.12.5", "@types/d3-shape": "^3.1.7", "@vueuse/core": "^13.1.0", "d3-color": "^3.1.0", "d3-hierarchy": "^3.1.2", "d3-sankey": "^0.12.3", "d3-scale": "^4.0.2", "d3-shape": "^3.2.0", "decimal.js-light": "^2.5.1", "es-toolkit": "^1.39.3" }, "peerDependencies": { "@nuxt/kit": "^4.0.0", "motion-v": "^2.4.0", "vue": "^3.5.0" }, "optionalPeers": ["@nuxt/kit"] }, "sha512-XiLG2RpOI/M2/9ecRsRTgkn7GPaKIaX4X8u3G3qSbIJN/mcea0gmxAlg86uZRlZX8FISDfzsXbM0H4MTC7xKHA=="],
+
"vee-validate": ["[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "@vue/devtools-api": "^7.5.2", "type-fest": "^4.8.3" }, "peerDependencies": { "vue": "^3.4.26" } }, "sha512-uGIRnODDMM0A8Weu8AJcZFFJceUpgbSX6G4UYZgWhBc90VcXDK+v7yO16G+sj+6vU1eML11M2BH4HxwoPE62rw=="],
"verkit": ["[email protected]", "", {}, "sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg=="],
@@ -5112,7 +5148,6 @@
"@modelcontextprotocol/sdk/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
-
"@oxc-parser/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="],
"@oxc-resolver/binding-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q=="],
@@ -5173,6 +5208,8 @@
"@trickfilm400/rollup-plugin-off-main-thread/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
+ "@types/d3-sankey/@types/d3-shape": ["@types/[email protected]", "", { "dependencies": { "@types/d3-path": "^1" } }, "sha512-8oMzcd4+poSLGgV0R1Q1rOlx/xdmozS4Xab7np0eamFFUYq71AU9pOCJEFnkXW2aI/oXdVYJzw6pssbSut7Z9Q=="],
+
"@typescript-eslint/visitor-keys/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="],
"@vitest/expect/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "3.2.4", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA=="],
@@ -5301,6 +5338,12 @@
"create-wdio/yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g=="],
+ "d3-sankey/d3-shape": ["[email protected]", "", { "dependencies": { "d3-path": "1" } }, "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw=="],
+
+ "d3-scale/d3-array": ["[email protected]", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="],
+
+ "d3-time/d3-array": ["[email protected]", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="],
+
"defaults/clone": ["[email protected]", "", {}, "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg=="],
"degenerator/ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w=="],
@@ -5533,6 +5576,8 @@
"unplugin-vue-components/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
+ "vccs/@vueuse/core": ["@vueuse/[email protected]", "", { "dependencies": { "@types/web-bluetooth": "^0.0.21", "@vueuse/metadata": "13.9.0", "@vueuse/shared": "13.9.0" }, "peerDependencies": { "vue": "^3.5.0" } }, "sha512-ts3regBQyURfCE2BcytLqzm8+MmLlo5Ln/KLoxDVcsZ2gzIwVNnQpQOL/UKV8alUqjSZOlpFZcRNsLRqj+OzyA=="],
+
"vee-validate/@vue/devtools-api": ["@vue/[email protected]", "", { "dependencies": { "@vue/devtools-kit": "^7.7.10" } }, "sha512-KxtEpUOOpFz/qOGRrAwA36QF7DqIA+FXgCYit9mk9wjbaZt0sXOFz81ElOZtKA4HbWHUdwNjZHBFsFFyp5BZiA=="],
"vite/rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.139.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.5", "@rolldown/binding-darwin-arm64": "1.1.5", "@rolldown/binding-darwin-x64": "1.1.5", "@rolldown/binding-freebsd-x64": "1.1.5", "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", "@rolldown/binding-linux-arm64-gnu": "1.1.5", "@rolldown/binding-linux-arm64-musl": "1.1.5", "@rolldown/binding-linux-ppc64-gnu": "1.1.5", "@rolldown/binding-linux-s390x-gnu": "1.1.5", "@rolldown/binding-linux-x64-gnu": "1.1.5", "@rolldown/binding-linux-x64-musl": "1.1.5", "@rolldown/binding-openharmony-arm64": "1.1.5", "@rolldown/binding-wasm32-wasi": "1.1.5", "@rolldown/binding-win32-arm64-msvc": "1.1.5", "@rolldown/binding-win32-x64-msvc": "1.1.5" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA=="],
@@ -5749,6 +5794,8 @@
"@testing-library/dom/pretty-format/ansi-styles": ["[email protected]", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
+ "@types/d3-sankey/@types/d3-shape/@types/d3-path": ["@types/[email protected]", "", {}, "sha512-4pQMp8ldf7UaB/gR8Fvvy69psNHkTpD/pVw3vmEi8iZAB9EPMBruB1JvHO4BIq9QkUUd2lV1F5YXpMNj7JPBpw=="],
+
"@vitest/expect/@vitest/utils/@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA=="],
"@vue-email/code-block/shiki/@shikijs/core": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/engine-javascript": "1.29.2", "@shikijs/engine-oniguruma": "1.29.2", "@shikijs/types": "1.29.2", "@shikijs/vscode-textmate": "^10.0.1", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.4" } }, "sha512-vju0lY9r27jJfOY4Z7+Rt/nIOjzJpZ3y+nYpqtUZInVoXQ/TJZcfGnNOGnKjFdVZb8qexiCuSlZRKcGfhhTTZQ=="],
@@ -5897,6 +5944,12 @@
"create-wdio/yargs/yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
+ "d3-sankey/d3-shape/d3-path": ["[email protected]", "", {}, "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg=="],
+
+ "d3-scale/d3-array/internmap": ["[email protected]", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
+
+ "d3-time/d3-array/internmap": ["[email protected]", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
+
"detective-typescript/@typescript-eslint/typescript-estree/@typescript-eslint/project-service": ["@typescript-eslint/[email protected]", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.67.0", "@typescript-eslint/types": "^8.67.0", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-cvE8c7ulYeXN9fYuszhCeCsbzyVEXuhrRCybnBre7TUmqb5nRmBfQAwCj0O3WJFDeyAZt4VYv51vMCC9LHSdYw=="],
"detective-typescript/@typescript-eslint/typescript-estree/@typescript-eslint/tsconfig-utils": ["@typescript-eslint/[email protected]", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-vV+LUSv5njUWsknE71fqKTlXUva+R76SaeORd6Zojcunk/6DvKFXONU3BrAs2H49mbygUXt6gbYunzwqNwlhdg=="],
@@ -6217,6 +6270,10 @@
"unplugin-vue-components/chokidar/readdirp": ["[email protected]", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="],
+ "vccs/@vueuse/core/@vueuse/metadata": ["@vueuse/[email protected]", "", {}, "sha512-1AFRvuiGphfF7yWixZa0KwjYH8ulyjDCC0aFgrGRz8+P4kvDFSdXLVfTk5xAN9wEuD1J6z4/myMoYbnHoX07zg=="],
+
+ "vccs/@vueuse/core/@vueuse/shared": ["@vueuse/[email protected]", "", { "peerDependencies": { "vue": "^3.5.0" } }, "sha512-e89uuTLMh0U5cZ9iDpEI2senqPGfbPRTHM/0AaQkcxnpqjkZqDYP8rpfm7edOz8s+pOCOROEy1PIveSW8+fL5g=="],
+
"vee-validate/@vue/devtools-api/@vue/devtools-kit": ["@vue/[email protected]", "", { "dependencies": { "@vue/devtools-shared": "^7.7.10", "birpc": "^2.3.0", "hookable": "^5.5.3", "mitt": "^3.0.1", "perfect-debounce": "^1.0.0", "speakingurl": "^14.0.1", "superjson": "^2.2.2" } }, "sha512-3WNi2Kq4tbpVbmhml7RiphmAt0279oh3fKNeWMQIrltfX8Q91b4i5PL8DtyNKdwmcsGrV4fg+erwWOmD05CLIw=="],
"vite/rolldown/@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw=="],
diff --git a/metrics.html b/metrics.html
new file mode 100644
index 000000000..a5e1f61f4
--- /dev/null
+++ b/metrics.html
@@ -0,0 +1,67 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="referrer" content="no-referrer" />
+ <meta name="robots" content="noindex" />
+ <title>OpenPencil metrics</title>
+ <link rel="icon" type="image/svg+xml" href="/brand/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="96x96" href="/brand/favicon-96x96.png" />
+ <style>
+ :root { --loader-bg: #1e1e1e; --loader-fg: 255, 255, 255; }
+ @media (prefers-color-scheme: light) {
+ :root { --loader-bg: #f3f4f6; --loader-fg: 32, 33, 36; }
+ }
+ html, body, #app { height: 100%; margin: 0; }
+ body { background: var(--loader-bg); }
+ /* The editor's splash, covering the first request until the page mounts with its numbers. */
+ #boot-splash {
+ position: fixed;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--loader-bg);
+ }
+ #boot-splash img { width: 40px; height: 40px; }
+ #boot-splash .bar {
+ position: absolute;
+ bottom: 50%;
+ left: 50%;
+ transform: translate(-50%, 40px);
+ width: 100px;
+ height: 2px;
+ background: rgba(var(--loader-fg), 0.08);
+ border-radius: 1px;
+ overflow: hidden;
+ }
+ #boot-splash .bar::after {
+ content: '';
+ display: block;
+ height: 100%;
+ width: 40%;
+ background: rgba(var(--loader-fg), 0.25);
+ border-radius: 1px;
+ animation: slide 1s ease-in-out infinite;
+ }
+ @keyframes slide {
+ 0% { transform: translateX(-100%); }
+ 100% { transform: translateX(350%); }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ #boot-splash .bar::after { animation: none; }
+ }
+ </style>
+ </head>
+
+ <body>
+ <div id="app">
+ <div id="boot-splash" role="status" aria-label="Loading metrics">
+ <img src="/brand/app-icon.svg" width="40" height="40" alt="" />
+ <div class="bar"></div>
+ </div>
+ </div>
+ <script type="module" src="/src/metrics/main.ts"></script>
+ </body>
+</html>
diff --git a/package.json b/package.json
index 9bc749fd2..9a2e2ed57 100644
--- a/package.json
+++ b/package.json
@@ -55,6 +55,7 @@
"cloud:dev:down": "bun tools/dev/cloud/src/index.ts down",
"build": "bun run build:packages && bun run lint && vite build",
"build:cloud-portal": "vite build --mode cloud-portal",
+ "build:metrics": "vite build --mode metrics",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build",
@@ -141,6 +142,7 @@
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.9",
"@floating-ui/vue": "^1.1.11",
+ "@internationalized/date": "^3.12.3",
"@lezer/highlight": "^1.2.3",
"@nanostores/i18n": "^1.3.3",
"@nanostores/vue": "^1.1.0",
@@ -202,6 +204,7 @@
"tinykeys": "^3.1.0",
"ufo": "^1.6.4",
"valibot": "^1.5.0",
+ "vccs": "1.0.0-beta.2",
"vee-validate": "5.0.0-beta.0",
"vue": "^3.5.43",
"vue-router": "^5.3.1",
diff --git a/packages/feedback/README.md b/packages/feedback/README.md
index 005105ac5..324310a5d 100644
--- a/packages/feedback/README.md
+++ b/packages/feedback/README.md
@@ -6,6 +6,7 @@ The Cloudflare Worker behind `feedback.openpencil.dev`. It is operated by the Op
| --- | --- | --- |
| `POST /ping` | The daily anonymous ping. | One counter per day and build (version, OS, architecture, desktop or web, browser family). Nothing per install, no addresses. |
| `POST /ingest` | Opt-in usage stats, forwarded to PostHog EU. Refuses any event or property not in `src/contract`. | Nothing. PostHog gets no client address, person profile, or GeoIP. |
+| `GET /admin/` | The team's metrics dashboard, built from the app's `metrics.html` (`bun run build:metrics` writes `dist-metrics/`, which Wrangler uploads as the Worker's assets), behind Cloudflare Access. | Nothing. |
| `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. |
@@ -20,8 +21,11 @@ cp packages/feedback/.dev.vars.example packages/feedback/.dev.vars
bun --filter @open-pencil/feedback dev # wrangler dev with a local D1
bun run test:feedback # typecheck and tests against a local D1
bun --filter @open-pencil/feedback types # after changing wrangler.jsonc
+bun run build:metrics # the dashboard page in dist-metrics/, for deploys
```
+The dashboard's components have Storybook stories under `App/Metrics/Dashboard`.
+
Apply migrations to the local database with `bunx wrangler d1 migrations apply feedback --local` from this folder.
## Production setup
diff --git a/packages/feedback/src/admin/route.ts b/packages/feedback/src/admin/route.ts
index 0125e589e..97bfe0635 100644
--- a/packages/feedback/src/admin/route.ts
+++ b/packages/feedback/src/admin/route.ts
@@ -7,14 +7,34 @@ import { requireAccess } from './access'
import { buildSnapshot } from './snapshot'
/**
- * The metrics dashboard's API, behind Cloudflare Access. Answers are for one signed-in person,
- * so nothing between here and the browser may keep a copy.
+ * The metrics dashboard's page and API, behind Cloudflare Access. Answers are for one signed-in
+ * person, so nothing between here and the browser may keep a copy.
*/
export function adminRoutes(services: FeedbackServices) {
- return new Hono<FeedbackEnv>()
- .use('/admin/*', requireAccess(services))
- .get('/admin/api/snapshot', validatedQuery(MetricsQuerySchema), async (c) => {
- c.header('Cache-Control', 'private, no-store')
- return c.json(await buildSnapshot(c.env, services, c.req.valid('query')), 200)
- })
+ const access = requireAccess(services)
+ return (
+ new Hono<FeedbackEnv>()
+ .use('/admin', access)
+ .use('/admin/*', access)
+ .get('/admin/api/snapshot', validatedQuery(MetricsQuerySchema), async (c) => {
+ c.header('Cache-Control', 'private, no-store')
+ return c.json(await buildSnapshot(c.env, services, c.req.valid('query')), 200)
+ })
+ .get('/admin', (c) => c.redirect('/admin/'))
+ // The page and its files, from the Worker's static assets once Access has let the request in.
+ .get('/admin/*', async (c) => {
+ const url = new URL(c.req.url)
+ // Vite names the page after its source, `metrics.html`.
+ if (url.pathname === '/admin/') url.pathname = '/admin/metrics.html'
+ // By URL alone: the page must never come back as a 304 for a cached copy.
+ const asset = await c.env.ASSETS.fetch(url.toString())
+ if (!asset.ok) return c.notFound()
+ // The binding answers with the Workers runtime's own Response type, so its bytes and
+ // type are copied into Hono's.
+ return c.body(await asset.arrayBuffer(), 200, {
+ 'Content-Type': asset.headers.get('content-type') ?? 'application/octet-stream',
+ 'Cache-Control': 'private, no-store'
+ })
+ })
+ )
}
diff --git a/packages/feedback/src/admin/snapshot.ts b/packages/feedback/src/admin/snapshot.ts
index 8f8ed88bd..78c285ba1 100644
--- a/packages/feedback/src/admin/snapshot.ts
+++ b/packages/feedback/src/admin/snapshot.ts
@@ -276,6 +276,22 @@ async function waitlist(db: Kysely<FeedbackDatabase>, range: MetricsQuery) {
}
}
+/** The first day anything was recorded: visits are backfilled, so they can predate the first ping. */
+async function firstDay(db: Kysely<FeedbackDatabase>): Promise<string | null> {
+ const [pinged, visited] = await Promise.all([
+ db
+ .selectFrom('usagePings')
+ .select((eb) => eb.fn.min<string>('day').as('day'))
+ .executeTakeFirst(),
+ db
+ .selectFrom('siteVisits')
+ .select((eb) => eb.fn.min<string>('day').as('day'))
+ .executeTakeFirst()
+ ])
+ const days = [pinged?.day, visited?.day].filter((day) => typeof day === 'string')
+ return days.toSorted().at(0) ?? null
+}
+
/**
* The dashboard's data for a range of UTC days: pings, snapshots, and the waitlist from D1, and
* usage from PostHog. PostHog failing leaves `usage` empty rather than failing the whole page.
@@ -291,9 +307,16 @@ export async function buildSnapshot(
const range = { start: query.start, end: end.toString() }
const days = eachDay(parseDate(range.start), end).map(String)
const db = createFeedbackDatabase(env.DB)
- const [pinged, visited, repository, signups, usage] = await Promise.all([
+ const [earliest, pinged, visited, repository, signups, usage] = await Promise.all([
+ firstDay(db),
pings(db, range, days),
- site(db, env, 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),
waitlist(db, range),
fetchUsage(env, services, range).catch((error: unknown) => {
@@ -304,6 +327,7 @@ export async function buildSnapshot(
return {
asOf: now.toISOString(),
today: today.toString(),
+ earliest,
...range,
...pinged,
...visited,
diff --git a/packages/feedback/src/contract/metrics.ts b/packages/feedback/src/contract/metrics.ts
index 354013ea3..7b7bdeeee 100644
--- a/packages/feedback/src/contract/metrics.ts
+++ b/packages/feedback/src/contract/metrics.ts
@@ -69,6 +69,8 @@ export type MetricsUsage = v.InferOutput<typeof MetricsUsageSchema>
export const MetricsSnapshotSchema = v.object({
asOf: v.pipe(v.string(), v.isoTimestamp()),
today: IsoDay,
+ /** The first day anything was recorded (pings or visits), or `null` before the first one. */
+ earliest: v.nullable(IsoDay),
start: IsoDay,
end: IsoDay,
/** Installs that pinged each day, by desktop and web. */
@@ -82,7 +84,7 @@ export const MetricsSnapshotSchema = v.object({
}),
/** The first day each stable version sent a ping, within the range. */
releases: v.array(v.object({ day: IsoDay, version: v.string() })),
- /** Cloudflare visits each day to the website and to the web app. */
+ /** Cloudflare visits each finished day to the website and to the web app; today is not recorded yet. */
visits: v.array(v.object({ day: IsoDay, site: Count, app: Count })),
website: v.object({ pages: v.array(RankedCountSchema), countries: v.array(RankedCountSchema) }),
github: v.object({
diff --git a/packages/feedback/src/env.ts b/packages/feedback/src/env.ts
index 3d46000d5..b8a154a86 100644
--- a/packages/feedback/src/env.ts
+++ b/packages/feedback/src/env.ts
@@ -1,4 +1,4 @@
-import type { D1Database, RateLimit, SendEmail } from '@cloudflare/workers-types/index'
+import type { D1Database, Fetcher, RateLimit, SendEmail } from '@cloudflare/workers-types/index'
/**
* The Worker's bindings, from `wrangler.jsonc` and its secrets. They are declared here with
@@ -8,6 +8,8 @@ import type { D1Database, RateLimit, SendEmail } from '@cloudflare/workers-types
*/
export interface FeedbackBindings {
DB: D1Database
+ /** The metrics dashboard's built page, served only through the admin routes. */
+ ASSETS: Fetcher
EMAIL: SendEmail
PING_LIMITER: RateLimit
INGEST_LIMITER: RateLimit
diff --git a/packages/feedback/tests/admin.test.ts b/packages/feedback/tests/admin.test.ts
index 0a4c65787..9f22eb3d5 100644
--- a/packages/feedback/tests/admin.test.ts
+++ b/packages/feedback/tests/admin.test.ts
@@ -173,6 +173,21 @@ describe('admin access', () => {
expect(response.headers.get('Cache-Control')).toBe('private, no-store')
})
+ test('serves the dashboard page only through Access, without caching', async () => {
+ expect((await service.request('/admin/')).status).toBe(403)
+ expect((await service.request('/admin')).status).toBe(403)
+ const headers = { 'cf-access-jwt-assertion': await accessToken(signingKey) }
+ const page = await service.request('/admin/', { headers })
+ expect(page.status).toBe(200)
+ expect(page.headers.get('Content-Type')).toBe('text/html')
+ expect(page.headers.get('Cache-Control')).toBe('private, no-store')
+ expect(await page.text()).toContain('<title>Metrics</title>')
+ const folder = await service.request('/admin', { headers })
+ expect(folder.status).toBe(302)
+ expect(folder.headers.get('Location')).toBe('/admin/')
+ expect((await service.request('/admin/missing.js', { headers })).status).toBe(404)
+ })
+
test('rejects a missing, malformed, or reversed range', async () => {
const token = await accessToken(signingKey)
for (const query of [
@@ -201,10 +216,23 @@ describe('metrics snapshot API', () => {
])
})
+ test('earliest is the first day with pings or backfilled visits', async () => {
+ expect((await snapshot()).earliest).toBeNull()
+ await ping('2026-10-12', { version: '0.16.0-beta.2', platform: 'macos', app: 'desktop' }, 6)
+ expect((await snapshot()).earliest).toBe('2026-10-12')
+ await database()
+ .insertInto('siteVisits')
+ .values({ day: '2026-09-22', host: 'openpencil.dev', visits: 2000 })
+ .execute()
+ expect((await snapshot()).earliest).toBe('2026-09-22')
+ })
+
test('an end after today stops at today', async () => {
const result = await snapshot('2026-10-19', '2026-12-31')
expect(result.end).toBe('2026-10-20')
expect(result.dailyActive.map((day) => day.day)).toEqual(['2026-10-19', '2026-10-20'])
+ // Visits are recorded after a day ends, so today has none to show.
+ expect(result.visits.map((day) => day.day)).toEqual(['2026-10-19'])
})
test('versions split the newest stable release from the rest and mark its first day', async () => {
diff --git a/packages/feedback/tests/harness.ts b/packages/feedback/tests/harness.ts
index 15ab55685..d0af54f54 100644
--- a/packages/feedback/tests/harness.ts
+++ b/packages/feedback/tests/harness.ts
@@ -67,6 +67,20 @@ export async function createTestService() {
ACCESS_TEAM_DOMAIN: 'https://openpencil.cloudflareaccess.com',
ACCESS_AUD: 'admin-audience',
POSTHOG_PERSONAL_KEY: 'phx_test',
+ // The built dashboard page as the asset binding serves it, at its file path only.
+ ASSETS: {
+ async fetch(input: RequestInfo | URL) {
+ const { pathname } = new URL(input instanceof Request ? input.url : String(input))
+ if (pathname === '/admin/metrics.html')
+ return new Response('<!doctype html><title>Metrics</title>', {
+ headers: { 'Content-Type': 'text/html' }
+ })
+ return new Response(null, { status: 404 })
+ },
+ connect() {
+ throw new Error('The test asset binding has no sockets')
+ }
+ },
PING_LIMITER: limiters.ping,
INGEST_LIMITER: limiters.ingest,
WAITLIST_LIMITER: limiters.waitlist,
diff --git a/packages/feedback/worker-configuration.d.ts b/packages/feedback/worker-configuration.d.ts
index 0c2b20b68..dfe33e107 100644
--- a/packages/feedback/worker-configuration.d.ts
+++ b/packages/feedback/worker-configuration.d.ts
@@ -1,11 +1,12 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: e85d17de9348939f8b2316b62003069d)
+// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: 3a4cf01ae118ee1043bbb3047f489806)
interface __BaseEnv_Env {
DB: D1Database;
EMAIL: SendEmail;
PING_LIMITER: RateLimit;
INGEST_LIMITER: RateLimit;
WAITLIST_LIMITER: RateLimit;
+ ASSETS: Fetcher;
POSTHOG_HOST: "https://eu.i.posthog.com";
EMAIL_FROM: "[email protected]";
TURNSTILE_HOSTNAMES: "openpencil.dev,app.openpencil.dev";
diff --git a/packages/feedback/wrangler.jsonc b/packages/feedback/wrangler.jsonc
index ff2d623d8..5cdf189fa 100644
--- a/packages/feedback/wrangler.jsonc
+++ b/packages/feedback/wrangler.jsonc
@@ -36,6 +36,15 @@
{ "name": "WAITLIST_LIMITER", "namespace_id": "1003", "simple": { "limit": 5, "period": 60 } }
],
"send_email": [{ "name": "EMAIL" }],
+ // The metrics dashboard, built by `vite build --mode metrics` at the repository root. Its page
+ // lives under admin/, which always runs the Worker first so Access is checked; only the
+ // public brand artwork is served directly.
+ "assets": {
+ "directory": "../../dist-metrics",
+ "binding": "ASSETS",
+ "html_handling": "none",
+ "run_worker_first": ["/admin", "/admin/*"]
+ },
// Just after midnight UTC the metrics snapshot records the day that ended; later, retention runs.
"triggers": { "crons": ["5 0 * * *", "17 3 * * *"] },
// Set with `wrangler secret put`; locally from `.dev.vars` (see `.dev.vars.example`).
diff --git a/src/AGENTS.md b/src/AGENTS.md
index 2ca41323c..a6e1ea07f 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -30,6 +30,7 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr
- Cloud servers are profiles of the `openpencil-cloud` storage provider (server = profile, workspace = container) and their sessions its credential; app code reaches a server through `src/app/cloud/sessions/connection.ts`, never with its own fetch (`tests/app/cloud/sessions/connection.test.ts`).
- An open Cloud document is live in its relay room, and only the elected saver (`electCloudSaver` in `src/app/cloud/rooms/live.ts`) uploads its revisions; guests from a link never save (`tests/integration/collab/cloud-relay.test.ts`).
- The Cloud portal is its own entry (`cloud.html`, `src/cloud/`, `src/views/cloud/`) served by the Cloud server, not the editor; it must not import editor sessions, CanvasKit, or `src/app/shell/**`, so `bun run build:cloud-portal` stays small (`open-pencil/no-editor-imports-in-cloud-portal`, `check:arch`).
+- The team's metrics dashboard is its own entry too (`metrics.html`, `src/metrics/`, `src/views/metrics/`), built by `bun run build:metrics` into `dist-metrics/` with base `/admin/` and served only by the feedback Worker behind Cloudflare Access; it follows the Cloud portal's isolation rule and reads its numbers through `@open-pencil/feedback/client` (`packages/feedback/tests/admin.test.ts`).
- Which portal pages a visitor may open, by sign-in and account standing, is decided in `portalDestination` alone (`tests/app/cloud-portal/navigation.test.ts`).
- A room is a document: every room tab owns its session (`src/app/collab/rooms.ts`, `session.ts`), joining always opens a new tab, and only Share binds an existing document; the collaboration UI reads the active tab's room through `useCollab()` and publishes cursors through the canvas's own tab (`tests/app/collab/session.test.ts`, `tests/e2e/collab/rooms.spec.ts`).
- A shared document records each layer's parent history, order key and page, never `parentId` or `childIds`, and only Share or a room's conversion sets its root in `meta`; local edits are written by `writeLocalPlacement` and remote changes applied by `applySharedTree` in `src/app/collab/shared-tree/sync.ts`, which resolve the tree with `LayerTree` from `src/app/collab/tree/` (`tests/app/collab/random-edits.test.ts`).
diff --git a/src/app/metrics/days.ts b/src/app/metrics/days.ts
new file mode 100644
index 000000000..424ea17dc
--- /dev/null
+++ b/src/app/metrics/days.ts
@@ -0,0 +1,10 @@
+import { type CalendarDate, parseAbsolute, today, toCalendarDate } from '@internationalized/date'
+
+/** The dashboard counts in UTC days, as the feedback Worker records them. */
+export const METRICS_TIME_ZONE = 'UTC'
+
+export const utcToday = (): CalendarDate => today(METRICS_TIME_ZONE)
+
+/** The UTC day of an ISO timestamp such as a sign-up's `2026-10-19T11:02:58.000Z`. */
+export const utcDayOfTimestamp = (timestamp: string): CalendarDate =>
+ toCalendarDate(parseAbsolute(timestamp, METRICS_TIME_ZONE))
diff --git a/src/app/metrics/format.ts b/src/app/metrics/format.ts
new file mode 100644
index 000000000..136054b80
--- /dev/null
+++ b/src/app/metrics/format.ts
@@ -0,0 +1,67 @@
+import { parseDate } from '@internationalized/date'
+
+import { METRICS_TIME_ZONE } from './days'
+
+/** Metrics are counted in UTC days, so every label is formatted in UTC too. */
+const DAY = new Intl.DateTimeFormat('en-US', {
+ month: 'short',
+ day: 'numeric',
+ timeZone: 'UTC'
+})
+const TIME = new Intl.DateTimeFormat('en-US', {
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ hourCycle: 'h23',
+ timeZone: 'UTC'
+})
+const COUNT = new Intl.NumberFormat('en-US')
+const PERCENT = new Intl.NumberFormat('en-US', {
+ style: 'percent',
+ maximumFractionDigits: 0
+})
+const CHANGE = new Intl.NumberFormat('en-US', { signDisplay: 'exceptZero' })
+
+export const formatDay = (day: string) => DAY.format(parseDate(day).toDate(METRICS_TIME_ZONE))
+export const formatTime = (iso: string) => `${TIME.format(new Date(iso))} UTC`
+export const formatCount = (value: number) => COUNT.format(value)
+export const formatPercent = (value: number) => PERCENT.format(value)
+export const formatChange = (value: number) => CHANGE.format(value)
+
+const REGION = new Intl.DisplayNames('en-US', { type: 'region' })
+
+// Cloudflare's codes for traffic it cannot place in a country; neither is a region subtag, and
+// `Intl.DisplayNames` throws on `T1` rather than returning nothing.
+const CLOUDFLARE_PSEUDO_COUNTRIES: Record<string, string> = { T1: 'Tor', XX: 'Unknown' }
+
+/** A country's name from Cloudflare's two-letter code, or the code when it has none. */
+export function formatCountry(code: string): string {
+ const pseudo = CLOUDFLARE_PSEUDO_COUNTRIES[code]
+ if (pseudo) return pseudo
+ try {
+ return REGION.of(code) ?? code
+ } catch {
+ return code
+ }
+}
+
+const SHARE = new Intl.NumberFormat('en-US', {
+ style: 'percent',
+ maximumFractionDigits: 1,
+ roundingMode: 'trunc'
+})
+
+/** A share that must never round up to 100% while anything is left: 697 of 699 is 99.7%. */
+export const formatShare = (value: number) => SHARE.format(value)
+
+const OS_NAMES: Record<string, string> = {
+ macos: 'macOS',
+ windows: 'Windows',
+ linux: 'Linux',
+ android: 'Android',
+ ios: 'iOS'
+}
+
+/** The OS as people write it, from the lowercase name pings carry. */
+export const formatOS = (os: string) => OS_NAMES[os] ?? os.charAt(0).toUpperCase() + os.slice(1)
diff --git a/src/app/metrics/load.ts b/src/app/metrics/load.ts
new file mode 100644
index 000000000..0f2c36e45
--- /dev/null
+++ b/src/app/metrics/load.ts
@@ -0,0 +1,59 @@
+import * as v from 'valibot'
+import { ref, shallowRef, watch, type Ref } from 'vue'
+
+import { createFeedbackClient } from '@open-pencil/feedback/client'
+import { MetricsSnapshotSchema, type MetricsSnapshot } from '@open-pencil/feedback/contract'
+
+import type { MetricsRange } from './range'
+
+/**
+ * The numbers for one range, from the feedback Worker that serves the page. It throws when the
+ * request fails, which is also what happens once Access's session has run out: the API then
+ * redirects to the login page, and reloading signs in again.
+ */
+export async function fetchMetricsSnapshot(range: MetricsRange): Promise<MetricsSnapshot> {
+ const client = createFeedbackClient({ origin: globalThis.location.origin })
+ const response = await client.admin.api.snapshot.$get({
+ query: { start: range.start, end: range.end }
+ })
+ if (response.status !== 200) throw new Error(`The metrics API answered ${response.status}`)
+ // Checked against the contract before use, as Cloud's client does with its answers.
+ const parsed = v.safeParse(
+ v.pipe(v.string(), v.parseJson(), MetricsSnapshotSchema),
+ await response.text()
+ )
+ if (!parsed.success) throw new Error('The metrics API sent an unexpected answer')
+ return parsed.output
+}
+
+/**
+ * The dashboard's numbers as the range changes, starting from the first snapshot the page was
+ * mounted with. A newer request wins over one still in flight, and the last numbers stay on
+ * screen while the next ones load or after a request fails.
+ */
+export function useMetricsSnapshot(range: Ref<MetricsRange>, first: MetricsSnapshot | undefined) {
+ const snapshot = shallowRef(first)
+ const loading = ref(false)
+ const failed = ref(first === undefined)
+ let latest = 0
+
+ async function load() {
+ const request = ++latest
+ loading.value = true
+ try {
+ const next = await fetchMetricsSnapshot(range.value)
+ if (request !== latest) return
+ snapshot.value = next
+ failed.value = false
+ } catch (error) {
+ if (request !== latest) return
+ console.warn('Metrics could not load', error)
+ failed.value = true
+ } finally {
+ if (request === latest) loading.value = false
+ }
+ }
+
+ watch(range, load)
+ return { snapshot, loading, failed, refresh: load }
+}
diff --git a/src/app/metrics/range.ts b/src/app/metrics/range.ts
new file mode 100644
index 000000000..92f6010f9
--- /dev/null
+++ b/src/app/metrics/range.ts
@@ -0,0 +1,73 @@
+import { parseDate } from '@internationalized/date'
+
+import { MAX_METRICS_RANGE_DAYS } from '@open-pencil/feedback/contract'
+
+import { formatDay } from './format'
+
+export type MetricsRangePreset = 'today' | '7d' | '30d' | '90d' | 'all' | 'custom'
+
+/** A span of whole UTC days, both ends included, as ISO dates. */
+export interface MetricsRange {
+ preset: MetricsRangePreset
+ start: string
+ end: string
+}
+
+export const METRICS_RANGE_PRESETS: {
+ value: Exclude<MetricsRangePreset, 'custom'>
+ label: string
+}[] = [
+ { value: 'today', label: 'Today' },
+ { value: '7d', label: 'Last 7 days' },
+ { value: '30d', label: 'Last 30 days' },
+ { value: '90d', label: 'Last 90 days' },
+ { value: 'all', label: 'All time' }
+]
+
+// "All time" is as long as the API answers; the history is far shorter for now.
+const PRESET_DAYS = {
+ today: 1,
+ '7d': 7,
+ '30d': 30,
+ '90d': 90,
+ all: MAX_METRICS_RANGE_DAYS
+} as const
+
+/**
+ * The days a preset covers, ending today. Ranges never start before `earliest`, the first day
+ * anything was recorded, so "Last 90 days" in the first week shows the same days as "All time";
+ * before the first answer that day is not known yet and the preset's full length is asked for.
+ */
+export function presetRange(
+ preset: Exclude<MetricsRangePreset, 'custom'>,
+ today: string,
+ earliest?: string | null
+): MetricsRange {
+ const start = parseDate(today)
+ .subtract({ days: PRESET_DAYS[preset] - 1 })
+ .toString()
+ return { preset, start: earliest && start < earliest ? earliest : start, end: today }
+}
+
+export function rangeLabel(range: MetricsRange): string {
+ const preset = METRICS_RANGE_PRESETS.find((option) => option.value === range.preset)
+ if (preset) return preset.label
+ if (range.start === range.end) return formatDay(range.start)
+ return `${formatDay(range.start)} – ${formatDay(range.end)}`
+}
+
+const RANGE_PHRASES: Record<Exclude<MetricsRangePreset, 'custom'>, string> = {
+ today: 'today',
+ '7d': 'in the last 7 days',
+ '30d': 'in the last 30 days',
+ '90d': 'in the last 90 days',
+ all: 'in total'
+}
+
+/** The range as the end of a sentence: "+374 in the last 7 days". */
+export function rangePhrase(range: MetricsRange): string {
+ if (range.preset !== 'custom') return RANGE_PHRASES[range.preset]
+ return range.start === range.end
+ ? `on ${formatDay(range.start)}`
+ : `${formatDay(range.start)} – ${formatDay(range.end)}`
+}
diff --git a/src/app/metrics/retention.ts b/src/app/metrics/retention.ts
new file mode 100644
index 000000000..99bf361dd
--- /dev/null
+++ b/src/app/metrics/retention.ts
@@ -0,0 +1,34 @@
+import { sumBy } from 'es-toolkit'
+
+import type { MetricsUsage } from '@open-pencil/feedback/contract'
+
+/** Installs first seen on `cohort`, then how many opened the app again each day after. */
+export type RetentionCohort = MetricsUsage['retention'][number]
+
+export interface RetentionPoint {
+ /** Days since an install was first seen; 0 is that first day. */
+ day: number
+ share: number
+ /** How many installs the share is taken from. */
+ installs: number
+}
+
+/**
+ * Every first day pooled into one curve: on day N, the share of installs that came back, counted
+ * only over first days at least N days old, so young cohorts don't pull the curve down.
+ */
+export function pooledRetention(cohorts: RetentionCohort[]): RetentionPoint[] {
+ const longest = Math.max(0, ...cohorts.map((cohort) => cohort.values.length))
+ const points: RetentionPoint[] = []
+ for (let day = 0; day < longest; day++) {
+ const reached = cohorts.filter((cohort) => cohort.values.length > day)
+ const installs = sumBy(reached, (cohort) => cohort.values[0] ?? 0)
+ if (!installs) continue
+ points.push({
+ day,
+ share: sumBy(reached, (cohort) => cohort.values[day] ?? 0) / installs,
+ installs
+ })
+ }
+ return points
+}
diff --git a/src/components/metrics/DailyChart.vue b/src/components/metrics/DailyChart.vue
new file mode 100644
index 000000000..0e3e9054b
--- /dev/null
+++ b/src/components/metrics/DailyChart.vue
@@ -0,0 +1,118 @@
+<script setup lang="ts" generic="Row extends { day: string }">
+import {
+ Bar,
+ BarChart,
+ CartesianGrid,
+ Cell,
+ Legend,
+ ReferenceLine,
+ Tooltip,
+ XAxis,
+ YAxis
+} from 'vccs'
+import { computed } from 'vue'
+
+import { formatCount, formatDay } from '@/app/metrics/format'
+
+import type { Release } from './types'
+
+/** One bar per series per UTC day, in a fixed chart color. */
+export interface DailySeries<Key extends string> {
+ key: Key
+ name: string
+ color: string
+}
+
+/**
+ * A count per UTC day, with series stacked when they add up to a whole and side by side when
+ * they don't. Today is still being counted, so its bars are drawn faint. Releases in the range
+ * get a marker, so a jump has its cause beside it.
+ */
+const {
+ label,
+ days,
+ series,
+ today,
+ releases = [],
+ stacked = false,
+ height = 240
+} = defineProps<{
+ /** The chart's accessible name. */
+ label: string
+ days: Row[]
+ series: DailySeries<Extract<keyof Row, string>>[]
+ today: string
+ releases?: Release[]
+ stacked?: boolean
+ height?: number
+}>()
+
+const dayLabel = (day: string) => (day === today ? 'Today' : formatDay(day))
+const rows = computed(() =>
+ days.map((day) => ({ ...day, label: dayLabel(day.day), partial: day.day === today }))
+)
+const markers = computed(() =>
+ releases
+ .filter((release) => days.some((day) => day.day === release.day))
+ .map((release) => ({ ...release, label: dayLabel(release.day) }))
+)
+const PARTIAL_OPACITY = 0.45
+const STACK = 'day'
+const formatTick = (value: unknown) =>
+ typeof value === 'number' ? formatCount(value) : String(value)
+// Stacked bars round only the top segment; side-by-side bars round each one.
+const radius = (index: number): [number, number, number, number] =>
+ !stacked || index === series.length - 1 ? [4, 4, 0, 0] : [0, 0, 0, 0]
+</script>
+
+<template>
+ <BarChart
+ :data="rows"
+ :height="height"
+ :margin="{ top: 8, right: 0, bottom: 0, left: 0 }"
+ :bar-gap="2"
+ :bar-category-gap="stacked ? '10%' : '30%'"
+ :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"
+ />
+ <ReferenceLine
+ v-for="marker in markers"
+ :key="marker.version"
+ :x="marker.label"
+ stroke="var(--color-muted)"
+ :stroke-width="1"
+ :label="{
+ value: `v${marker.version}`,
+ position: 'insideTopLeft',
+ fill: 'var(--color-muted)',
+ fontSize: 10
+ }"
+ />
+ <Tooltip :cursor="{ fill: 'var(--color-hover)' }" />
+ <Legend :height="28" vertical-align="top" align="right" icon-type="circle" :icon-size="8" />
+ <Bar
+ v-for="(item, index) in series"
+ :key="item.key"
+ :data-key="item.key"
+ :name="item.name"
+ :fill="item.color"
+ :stack-id="stacked ? STACK : undefined"
+ stroke="var(--color-panel)"
+ :stroke-width="stacked ? 2 : 0"
+ :radius="radius(index)"
+ :max-bar-size="48"
+ >
+ <Cell v-for="row in rows" :key="row.day" :fill-opacity="row.partial ? PARTIAL_OPACITY : 1" />
+ </Bar>
+ </BarChart>
+</template>
diff --git a/src/components/metrics/MetricsCard.vue b/src/components/metrics/MetricsCard.vue
new file mode 100644
index 000000000..8c9a0a8a2
--- /dev/null
+++ b/src/components/metrics/MetricsCard.vue
@@ -0,0 +1,19 @@
+<script setup lang="ts">
+import { metricsCard } from '@/theme/metrics/dashboard'
+
+const { heading, note } = defineProps<{ heading: string; note?: string }>()
+const ui = metricsCard()
+</script>
+
+<template>
+ <section :class="ui.root()" :aria-label="heading">
+ <header :class="ui.header()">
+ <div :class="ui.titleGroup()">
+ <h3 :class="ui.title()">{{ heading }}</h3>
+ <p v-if="note" :class="ui.note()">{{ note }}</p>
+ </div>
+ <div v-if="$slots.aside" :class="ui.aside()"><slot name="aside" /></div>
+ </header>
+ <slot />
+ </section>
+</template>
diff --git a/src/components/metrics/MetricsDashboard.stories.ts b/src/components/metrics/MetricsDashboard.stories.ts
new file mode 100644
index 000000000..eb5ac8bf5
--- /dev/null
+++ b/src/components/metrics/MetricsDashboard.stories.ts
@@ -0,0 +1,209 @@
+import { parseDate } from '@internationalized/date'
+import type { Meta, StoryObj } from '@storybook/vue3-vite'
+import { sumBy } from 'es-toolkit'
+import { computed, ref } from 'vue'
+
+import type { MetricsSnapshot } from '@open-pencil/feedback/contract'
+
+import { utcDayOfTimestamp } from '@/app/metrics/days'
+import { presetRange } from '@/app/metrics/range'
+import type { MetricsRange } from '@/app/metrics/range'
+
+import MetricsDashboard from './MetricsDashboard.vue'
+
+// The week after v0.16.0 shipped, as the feedback Worker answers for it. Pings, versions, visits,
+// website pages and countries, GitHub traffic and referrers, usage, retention, and waitlist
+// sign-ups are real; daily star and download growth before the snapshot job are illustrative.
+const TODAY = '2026-10-19'
+const EARLIEST = '2026-09-22'
+
+const dailyActive = [
+ { day: '2026-10-13', desktop: 19, web: 0 },
+ { day: '2026-10-14', desktop: 193, web: 183 },
+ { day: '2026-10-15', desktop: 432, web: 481 },
+ { day: '2026-10-16', desktop: 443, web: 397 },
+ { day: '2026-10-17', desktop: 390, web: 249 },
+ { day: '2026-10-18', desktop: 401, web: 298 },
+ { day: '2026-10-19', desktop: 330, web: 257 }
+]
+const visits = [
+ { day: '2026-10-13', site: 2342, app: 1107 },
+ { day: '2026-10-14', site: 3884, app: 729 },
+ { day: '2026-10-15', site: 4810, app: 970 },
+ { day: '2026-10-16', site: 3356, app: 1030 },
+ { day: '2026-10-17', site: 2283, app: 1093 },
+ { day: '2026-10-18', site: 2829, app: 1282 },
+ { day: '2026-10-19', site: 1765, app: 830 }
+]
+const versions = [
+ { day: '2026-10-13', latest: 0, other: 19 },
+ { day: '2026-10-14', latest: 354, other: 22 },
+ { day: '2026-10-15', latest: 905, other: 8 },
+ { day: '2026-10-16', latest: 838, other: 2 },
+ { day: '2026-10-17', latest: 637, other: 2 },
+ { day: '2026-10-18', latest: 697, other: 2 },
+ { day: '2026-10-19', latest: 586, other: 1 }
+]
+const growth = (added: number[]) =>
+ added.map((value, index) => ({ day: dailyActive[index]?.day ?? TODAY, added: value }))
+const traffic = [
+ { day: '2026-10-13', views: 420, uniqueViews: 230, clones: 2900 },
+ { day: '2026-10-14', views: 980, uniqueViews: 610, clones: 7400 },
+ { day: '2026-10-15', views: 760, uniqueViews: 402, clones: 6800 },
+ { day: '2026-10-16', views: 515, uniqueViews: 277, clones: 6170 },
+ { day: '2026-10-17', views: 601, uniqueViews: 299, clones: 3884 },
+ { day: '2026-10-18', views: 477, uniqueViews: 283, clones: 3807 }
+]
+const signups = [
+ { domain: 'crugroup.com', signedUpAt: '2026-10-14T16:12:31Z', confirmed: true },
+ { domain: 'gmail.com', signedUpAt: '2026-10-14T22:11:38Z', confirmed: true },
+ { domain: 'cpiprint.com', signedUpAt: '2026-10-15T03:06:45Z', confirmed: true },
+ { domain: 'allganize.io', signedUpAt: '2026-10-15T08:50:54Z', confirmed: true },
+ { domain: 'protonmail.com', signedUpAt: '2026-10-15T19:13:20Z', confirmed: false },
+ { domain: 'gmail.com', signedUpAt: '2026-10-16T15:56:03Z', confirmed: true },
+ { domain: 'creatonium.agency', signedUpAt: '2026-10-17T08:35:45Z', confirmed: true },
+ { domain: 'veltrum.cl', signedUpAt: '2026-10-18T15:39:22Z', confirmed: false },
+ { domain: 'gmail.com', signedUpAt: '2026-10-18T20:33:57Z', confirmed: true },
+ { domain: 'szscc.cn', signedUpAt: '2026-10-19T04:07:57Z', confirmed: true },
+ { domain: 'gmail.com', signedUpAt: '2026-10-19T07:46:12Z', confirmed: false },
+ { domain: 'exient.com', signedUpAt: '2026-10-19T11:02:58Z', confirmed: true }
+]
+const usageDaily = [
+ { day: '2026-10-13', installs: 2 },
+ { day: '2026-10-14', installs: 30 },
+ { day: '2026-10-15', installs: 68 },
+ { day: '2026-10-16', installs: 56 },
+ { day: '2026-10-17', installs: 43 },
+ { day: '2026-10-18', installs: 45 },
+ { day: '2026-10-19', installs: 53 }
+]
+const retention = [
+ { cohort: '2026-10-14', values: [28, 9, 7, 3, 2, 3] },
+ { cohort: '2026-10-15', values: [59, 14, 4, 0, 7] },
+ { cohort: '2026-10-16', values: [35, 6, 6, 4] },
+ { cohort: '2026-10-17', values: [30, 7] },
+ { cohort: '2026-10-18', values: [30, 8] },
+ { cohort: '2026-10-19', values: [31] }
+]
+
+/** Whether a day falls within the range, both ends included. */
+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 {
+ const inRange = <T extends { day: string }>(rows: T[]) =>
+ rows.filter((row) => isInRange(row.day, range))
+ const recent = signups.filter((signup) =>
+ isInRange(utcDayOfTimestamp(signup.signedUpAt).toString(), range)
+ )
+ return {
+ asOf: '2026-10-19T11:36:00Z',
+ today: TODAY,
+ earliest: EARLIEST,
+ start: range.start,
+ end: range.end,
+ dailyActive: inRange(dailyActive),
+ platforms: [
+ { os: 'macos', desktop: 428, web: 356 },
+ { os: 'windows', desktop: 386, web: 327 },
+ { os: 'linux', desktop: 83, web: 105 },
+ { os: 'android', desktop: 0, web: 43 },
+ { os: 'ios', desktop: 0, web: 28 }
+ ],
+ versions: { latest: '0.16.0', daily: inRange(versions) },
+ releases: inRange([{ day: '2026-10-14', version: '0.16.0' }]),
+ visits: inRange(visits),
+ website: {
+ pages: [
+ { name: '/', value: 9181 },
+ { name: '/programmable/mcp-server', value: 786 },
+ { name: '/getting-started', value: 564 },
+ { name: '/download', value: 488 },
+ { name: '/development/roadmap', value: 422 },
+ { name: '/es/', value: 358 }
+ ],
+ countries: [
+ { name: 'US', value: 8212 },
+ { name: 'CN', value: 1831 },
+ { name: 'SG', value: 1672 },
+ { name: 'FR', value: 1330 },
+ { name: 'DE', value: 955 },
+ { name: 'IN', value: 779 }
+ ]
+ },
+ github: {
+ stars: { total: 9120, daily: inRange(growth([18, 30, 33, 31, 25, 27, 9])) },
+ downloads: {
+ total: 36662,
+ latestTag: 'v0.16.0',
+ latestTotal: 2028,
+ daily: inRange(growth([0, 620, 419, 308, 307, 374, 0])),
+ updateChecks: inRange(growth([0, 1110, 931, 1100, 980, 1050, 0]))
+ },
+ traffic: inRange(traffic),
+ referrers: [
+ { name: 'Google', value: 1722 },
+ { name: 'github.com', value: 847 },
+ { name: 'openpencil.dev', value: 467 },
+ { name: 'Bing', value: 124 },
+ { name: 'youtube.com', value: 80 }
+ ]
+ },
+ waitlist: { total: 22, confirmed: 16, added: recent.length, recent: recent.toReversed() },
+ usage: withUsage
+ ? {
+ installs: sumBy(inRange(usageDaily), (day) => day.installs),
+ daily: inRange(usageDaily),
+ retention: retention.filter((cohort) => isInRange(cohort.cohort, range)),
+ documents: [
+ { name: 'fig', value: 496 },
+ { name: 'pen', value: 19 },
+ { name: 'html', value: 5 }
+ ],
+ exports: [
+ { name: 'png', value: 14 },
+ { name: 'pptx', value: 1 }
+ ],
+ aiProviders: [
+ { name: 'openai-compatible', value: 85 },
+ { name: 'openrouter', value: 22 },
+ { name: 'deepseek', value: 6 },
+ { name: 'openai', value: 5 },
+ { name: 'anthropic-compatible', value: 3 },
+ { name: 'google', value: 1 },
+ { name: 'anthropic', value: 1 }
+ ]
+ }
+ : null
+ }
+}
+
+const meta = {
+ title: 'App/Metrics/Dashboard',
+ parameters: { layout: 'fullscreen' }
+} satisfies Meta
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+const story = (frame: string, withUsage = true): Story => ({
+ render: () => ({
+ components: { MetricsDashboard },
+ setup: () => {
+ const range = ref(presetRange('7d', TODAY, EARLIEST))
+ const snapshot = computed(() => scope(range.value, withUsage))
+ 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]')
+
+/** PostHog did not answer: retention and usage give way to a notice, the rest stays. */
+export const WithoutUsage = story('h-[2600px]', false)
+
+/** The dashboard in a phone-width window. */
+export const Narrow = story('h-[4400px] w-[390px]')
diff --git a/src/components/metrics/MetricsDashboard.vue b/src/components/metrics/MetricsDashboard.vue
new file mode 100644
index 000000000..f0fa99933
--- /dev/null
+++ b/src/components/metrics/MetricsDashboard.vue
@@ -0,0 +1,360 @@
+<script setup lang="ts">
+import { countBy, maxBy, meanBy, sumBy } from 'es-toolkit'
+import { BarList } from 'vccs'
+import { computed } from 'vue'
+
+import type { MetricsSnapshot } from '@open-pencil/feedback/contract'
+
+import { utcDayOfTimestamp } from '@/app/metrics/days'
+import {
+ formatCount,
+ formatCountry,
+ formatDay,
+ formatPercent,
+ formatShare,
+ formatTime
+} from '@/app/metrics/format'
+import { rangePhrase } from '@/app/metrics/range'
+import type { MetricsRange } from '@/app/metrics/range'
+import BrandMark from '@/components/brand/BrandMark.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'
+import { metricsDashboard } from '@/theme/metrics/dashboard'
+
+import DailyChart from './DailyChart.vue'
+import type { DailySeries } from './DailyChart.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 WaitlistList from './WaitlistList.vue'
+
+/**
+ * Day-to-day numbers in one place: anonymous daily pings and Cloudflare visits for reach,
+ * PostHog for what the installs that share stats do, and GitHub and the Cloud waitlist for
+ * growth. The range scopes everything below it; `snapshot` already holds only those days.
+ */
+const {
+ host,
+ snapshot,
+ loading = false
+} = defineProps<{
+ host: string
+ snapshot: MetricsSnapshot
+ /** Newer numbers are on their way; the current ones stay, dimmed. */
+ loading?: boolean
+}>()
+const range = defineModel<MetricsRange>('range', { required: true })
+const emit = defineEmits<{ refresh: [] }>()
+defineSlots<{ /** A notice above the numbers, such as a failed refresh. */ alert?(): unknown }>()
+
+const ui = metricsDashboard()
+const phrase = computed(() => rangePhrase(range.value))
+const usage = computed(() => snapshot.usage)
+
+// Today is still being counted, so headline numbers and tile trends use full days only.
+const isFull = (row: { day: string }) => row.day !== snapshot.today
+const totals = computed(() =>
+ snapshot.dailyActive.map((day) => ({ day: day.day, installs: day.desktop + day.web }))
+)
+const fullDays = computed(() => totals.value.filter(isFull))
+const peak = computed(() => maxBy(fullDays.value, (day) => day.installs))
+const active = computed(() =>
+ fullDays.value.length
+ ? {
+ value: Math.round(meanBy(fullDays.value, (day) => day.installs)),
+ label: 'Daily active installs, average',
+ detail: peak.value
+ ? `peak ${formatCount(peak.value.installs)} on ${formatDay(peak.value.day)}`
+ : undefined,
+ trend: fullDays.value.map((day) => day.installs)
+ }
+ : {
+ value: totals.value.at(-1)?.installs ?? 0,
+ label: 'Daily active installs',
+ detail: 'so far today',
+ trend: undefined
+ }
+)
+type Growth = MetricsSnapshot['github']['stars']['daily']
+// Growth needs two recorded days; until then the tile says so rather than showing a zero.
+const added = (daily: Growth) => (daily.length ? sumBy(daily, (day) => day.added) : undefined)
+const growthDetail = (daily: Growth) => (daily.length ? phrase.value : 'no daily history yet')
+const fullTrend = (daily: Growth) => daily.filter(isFull).map((day) => day.added)
+const signupTrend = computed(() => {
+ const perDay = countBy(snapshot.waitlist.recent, (signup) =>
+ utcDayOfTimestamp(signup.signedUpAt).toString()
+ )
+ return fullDays.value.map((day) => perDay[day.day] ?? 0)
+})
+
+const INSTALL_SERIES: DailySeries<keyof DailyActiveDay & string>[] = [
+ { key: 'desktop', name: 'Desktop', color: 'var(--color-chart-1)' },
+ { key: 'web', name: 'Web', color: 'var(--color-chart-2)' }
+]
+// The web app keeps the web installs' color; the site takes the next one.
+const VISIT_SERIES: DailySeries<keyof DailyVisits & string>[] = [
+ { key: 'site', name: 'openpencil.dev', color: 'var(--color-chart-3)' },
+ { key: 'app', name: 'app.openpencil.dev', color: 'var(--color-chart-2)' }
+]
+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)' }
+]
+// 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)' },
+ { key: 'other', name: 'Other versions', color: 'var(--color-muted)' }
+])
+const latestShare = computed(() => {
+ const day = snapshot.versions.daily.findLast(isFull)
+ return day && day.latest + day.other ? day.latest / (day.latest + day.other) : undefined
+})
+
+// Pings and visits count different things, so this is a rough share, over full days only.
+const fullDaySet = computed(() => new Set(fullDays.value.map((day) => day.day)))
+const reachedEditor = computed(() => {
+ const visits = sumBy(
+ snapshot.visits.filter((day) => fullDaySet.value.has(day.day)),
+ (day) => day.app
+ )
+ const web = sumBy(
+ snapshot.dailyActive.filter((day) => fullDaySet.value.has(day.day)),
+ (day) => day.web
+ )
+ return visits ? web / visits : undefined
+})
+const countries = computed(() =>
+ snapshot.website.countries.map((country) => ({ ...country, name: formatCountry(country.name) }))
+)
+// How much of the daily pings PostHog sees, so its numbers are read as the share they are.
+const sharingNote = computed(() => {
+ if (!usage.value) return undefined
+ const shared = sumBy(
+ usage.value.daily.filter((day) => fullDaySet.value.has(day.day)),
+ (day) => day.installs
+ )
+ const pinged = sumBy(fullDays.value, (day) => day.installs)
+ const share = pinged ? `, about ${formatPercent(shared / pinged)} of daily active installs` : ''
+ return `${formatCount(usage.value.installs)} installs sharing stats${share}`
+})
+</script>
+
+<template>
+ <div :class="ui.page()">
+ <header :class="ui.bar()">
+ <BrandMark variant="micro" decorative />
+ <span :class="ui.barTitle()">Metrics</span>
+ <span :class="ui.barHost()">{{ host }}</span>
+ <div :class="ui.barEnd()">
+ <span :class="ui.barMeta()">Updated {{ formatTime(snapshot.asOf) }}</span>
+ <MetricsRangePicker
+ v-model="range"
+ :today="snapshot.today"
+ :earliest="snapshot.earliest ?? snapshot.start"
+ />
+ <IconButton label="Refresh" :disabled="loading" @click="emit('refresh')">
+ <icon-lucide-refresh-cw class="size-3.5" />
+ </IconButton>
+ </div>
+ </header>
+ <main :class="ui.main()">
+ <div :class="ui.inner()" :data-loading="loading" :aria-busy="loading">
+ <slot name="alert" />
+ <div :class="ui.tiles()">
+ <MetricsTile
+ :label="active.label"
+ :value="active.value"
+ :detail="active.detail"
+ :trend="active.trend"
+ />
+ <MetricsTile
+ label="Installer downloads"
+ :value="snapshot.github.downloads.total"
+ :change="added(snapshot.github.downloads.daily)"
+ :detail="growthDetail(snapshot.github.downloads.daily)"
+ :trend="fullTrend(snapshot.github.downloads.daily)"
+ />
+ <MetricsTile
+ label="GitHub stars"
+ :value="snapshot.github.stars.total"
+ :change="added(snapshot.github.stars.daily)"
+ :detail="growthDetail(snapshot.github.stars.daily)"
+ :trend="fullTrend(snapshot.github.stars.daily)"
+ />
+ <MetricsTile
+ label="Cloud waitlist"
+ :value="snapshot.waitlist.total"
+ :change="snapshot.waitlist.added"
+ :detail="`${phrase} · ${formatCount(snapshot.waitlist.confirmed)} confirmed`"
+ :trend="signupTrend"
+ />
+ </div>
+
+ <section :class="ui.section()" aria-labelledby="metrics-reach">
+ <h2 id="metrics-reach" :class="ui.sectionHeading()">Reach</h2>
+ <MetricsCard
+ heading="Daily active installs"
+ note="Anonymous pings, one per install per UTC day. Days can't be added up: a returning install counts on each day."
+ >
+ <DailyChart
+ label="Daily active installs, desktop and web"
+ :days="snapshot.dailyActive"
+ :series="INSTALL_SERIES"
+ :today="snapshot.today"
+ :releases="snapshot.releases"
+ stacked
+ />
+ </MetricsCard>
+ <MetricsCard
+ heading="Visits"
+ note="Cloudflare's count of page views that arrived from another site or a link. Not unique people: a returning visitor counts again."
+ >
+ <template v-if="reachedEditor !== undefined" #aside>
+ About {{ formatPercent(reachedEditor) }} of app visits reach the editor
+ </template>
+ <DailyChart
+ label="Visits to the website and the web app"
+ :days="snapshot.visits"
+ :series="VISIT_SERIES"
+ :today="snapshot.today"
+ :releases="snapshot.releases"
+ />
+ </MetricsCard>
+ <div :class="ui.row()">
+ <MetricsCard heading="Platforms" note="Daily pings added up across the range">
+ <PlatformsChart :platforms="snapshot.platforms" />
+ </MetricsCard>
+ <MetricsCard
+ heading="Versions"
+ note="Daily pings by version. Versions before 0.16.0 send no pings, so older installs show up from the next release on."
+ >
+ <template v-if="latestShare !== undefined && snapshot.versions.latest" #aside>
+ {{ formatShare(latestShare) }} on {{ snapshot.versions.latest }}
+ </template>
+ <DailyChart
+ label="Daily pings on the latest version and on others"
+ :days="snapshot.versions.daily"
+ :series="versionSeries"
+ :today="snapshot.today"
+ :height="200"
+ stacked
+ />
+ </MetricsCard>
+ </div>
+ <MetricsCard heading="Website" note="Visits to openpencil.dev by page and country">
+ <div :class="ui.breakdown()">
+ <div>
+ <h4 :class="ui.sectionLabel()">Top pages</h4>
+ <BarList
+ class="text-xs"
+ :data="snapshot.website.pages"
+ :value-formatter="formatCount"
+ :row-height="28"
+ :is-animation-active="false"
+ />
+ </div>
+ <div>
+ <h4 :class="ui.sectionLabel()">Countries</h4>
+ <BarList
+ class="text-xs"
+ :data="countries"
+ :value-formatter="formatCount"
+ :row-height="28"
+ :is-animation-active="false"
+ />
+ </div>
+ </div>
+ </MetricsCard>
+ </section>
+
+ <section :class="ui.section()" aria-labelledby="metrics-engagement">
+ <h2 id="metrics-engagement" :class="ui.sectionHeading()">Engagement</h2>
+ <div v-if="usage" :class="ui.row()">
+ <MetricsCard
+ heading="Retention"
+ note="Share of installs that came back N days after their first day; only installs sharing stats"
+ >
+ <RetentionChart :cohorts="usage.retention" />
+ </MetricsCard>
+ <MetricsCard heading="What people do" :note="sharingNote">
+ <div :class="ui.usage()">
+ <div>
+ <h4 :class="ui.sectionLabel()">Documents opened</h4>
+ <BarList
+ class="text-xs"
+ :data="usage.documents"
+ :row-height="28"
+ :is-animation-active="false"
+ />
+ </div>
+ <div>
+ <h4 :class="ui.sectionLabel()">Exports</h4>
+ <BarList
+ class="text-xs"
+ :data="usage.exports"
+ :row-height="28"
+ :is-animation-active="false"
+ />
+ </div>
+ <div>
+ <h4 :class="ui.sectionLabel()">AI replies by provider</h4>
+ <BarList
+ class="text-xs"
+ :data="usage.aiProviders"
+ :row-height="28"
+ :is-animation-active="false"
+ />
+ </div>
+ </div>
+ </MetricsCard>
+ </div>
+ <MetricsCard v-else heading="Usage">
+ <AppPlaceholder
+ size="compact"
+ :fill="false"
+ label="PostHog did not answer"
+ description="Retention and usage come from PostHog; the rest of the page is current. Refresh to ask again."
+ >
+ <template #icon><icon-lucide-cloud-off class="size-4" /></template>
+ </AppPlaceholder>
+ </MetricsCard>
+ </section>
+
+ <section :class="ui.section()" aria-labelledby="metrics-growth">
+ <h2 id="metrics-growth" :class="ui.sectionHeading()">Growth</h2>
+ <div :class="ui.row()">
+ <MetricsCard
+ heading="GitHub"
+ note="Repository views per day, and the sites that sent visitors over the last 14 days"
+ >
+ <DailyChart
+ label="Repository views and unique visitors"
+ :days="snapshot.github.traffic"
+ :series="TRAFFIC_SERIES"
+ :today="snapshot.today"
+ :height="200"
+ />
+ <BarList
+ class="text-xs"
+ :data="snapshot.github.referrers"
+ :value-formatter="formatCount"
+ :row-height="28"
+ :is-animation-active="false"
+ />
+ </MetricsCard>
+ <MetricsCard heading="Cloud waitlist" note="Sign-ups in the range by email domain">
+ <template #aside>
+ {{ formatCount(snapshot.waitlist.confirmed) }} of
+ {{ formatCount(snapshot.waitlist.total) }} confirmed
+ </template>
+ <WaitlistList :signups="snapshot.waitlist.recent" />
+ </MetricsCard>
+ </div>
+ </section>
+ </div>
+ </main>
+ </div>
+</template>
diff --git a/src/components/metrics/MetricsRangePicker.vue b/src/components/metrics/MetricsRangePicker.vue
new file mode 100644
index 000000000..4d5eb0508
--- /dev/null
+++ b/src/components/metrics/MetricsRangePicker.vue
@@ -0,0 +1,79 @@
+<script setup lang="ts">
+import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'
+import { computed, ref } from 'vue'
+
+import { formatDay } from '@/app/metrics/format'
+import { METRICS_RANGE_PRESETS, presetRange, rangeLabel } from '@/app/metrics/range'
+import type { MetricsRange, MetricsRangePreset } from '@/app/metrics/range'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import AppRangeCalendar from '@/components/ui/date/AppRangeCalendar.vue'
+import type { DayRange } from '@/components/ui/date/range'
+import { usePopoverUI } from '@/components/ui/overlay/popover'
+import { metricsRangePicker } from '@/theme/metrics/dashboard'
+
+/**
+ * Which days the whole dashboard shows: presets as rows, a calendar for any other span. Days
+ * before anything was recorded can't be picked.
+ */
+const { today, earliest } = defineProps<{ today: string; earliest: string }>()
+const range = defineModel<MetricsRange>({ required: true })
+
+const open = ref(false)
+const ui = metricsRangePicker()
+const popover = usePopoverUI({ content: 'p-0' })
+
+const label = computed(() => rangeLabel(range.value))
+const span = computed(() =>
+ range.value.start === range.value.end
+ ? formatDay(range.value.start)
+ : `${formatDay(range.value.start)} – ${formatDay(range.value.end)}`
+)
+const days = computed<DayRange | null>({
+ get: () => ({ start: range.value.start, end: range.value.end }),
+ set: (picked) => {
+ if (!picked) return
+ range.value = { preset: 'custom', ...picked }
+ open.value = false
+ }
+})
+
+function choose(preset: Exclude<MetricsRangePreset, 'custom'>) {
+ range.value = presetRange(preset, today, earliest)
+ open.value = false
+}
+</script>
+
+<template>
+ <PopoverRoot v-model:open="open">
+ <PopoverTrigger as-child>
+ <AppButton variant="outline" size="sm">
+ <icon-lucide-calendar class="size-3.5" />
+ <span>{{ label }}</span>
+ <span v-if="range.preset !== 'custom'" :class="ui.triggerSpan()">{{ span }}</span>
+ <icon-lucide-chevron-down class="size-3 text-muted" />
+ </AppButton>
+ </PopoverTrigger>
+ <PopoverPortal>
+ <PopoverContent :class="popover.content" align="end" :side-offset="6">
+ <div :class="ui.body()">
+ <ul :class="ui.presets()" aria-label="Date range">
+ <li v-for="preset in METRICS_RANGE_PRESETS" :key="preset.value">
+ <button
+ type="button"
+ :class="ui.preset()"
+ :data-selected="range.preset === preset.value"
+ @click="choose(preset.value)"
+ >
+ <span>{{ preset.label }}</span>
+ <icon-lucide-check v-if="range.preset === preset.value" class="size-3.5" />
+ </button>
+ </li>
+ </ul>
+ <div :class="ui.calendar()">
+ <AppRangeCalendar v-model="days" label="Custom range" :min="earliest" :max="today" />
+ </div>
+ </div>
+ </PopoverContent>
+ </PopoverPortal>
+ </PopoverRoot>
+</template>
diff --git a/src/components/metrics/MetricsTile.vue b/src/components/metrics/MetricsTile.vue
new file mode 100644
index 000000000..52c212128
--- /dev/null
+++ b/src/components/metrics/MetricsTile.vue
@@ -0,0 +1,48 @@
+<script setup lang="ts">
+import { Sparkline } from 'vccs'
+import { computed } from 'vue'
+
+import { formatChange, formatCount } from '@/app/metrics/format'
+import { metricsTile } from '@/theme/metrics/dashboard'
+
+/**
+ * A headline number, how it changed over the chosen days, and a bar for each of those days. A
+ * number nothing has recorded yet shows as a dash.
+ */
+const { label, value, change, detail, trend } = defineProps<{
+ label: string
+ value: number | null
+ change?: number
+ detail?: string
+ trend?: number[]
+}>()
+
+const ui = metricsTile()
+const direction = computed(() => {
+ if (!change) return 'flat'
+ return change > 0 ? 'up' : 'down'
+})
+</script>
+
+<template>
+ <div :class="ui.root()">
+ <span :class="ui.label()">{{ label }}</span>
+ <span :class="ui.value()">{{ value === null ? '—' : formatCount(value) }}</span>
+ <span :class="ui.detail()">
+ <span v-if="change !== undefined" :class="ui.change()" :data-direction="direction">
+ {{ formatChange(change) }}
+ </span>
+ <span v-if="detail">{{ detail }}</span>
+ </span>
+ <Sparkline
+ v-if="trend?.length"
+ :class="ui.trend()"
+ :data="trend"
+ type="bar"
+ :height="32"
+ :is-animation-active="false"
+ :value-formatter="formatCount"
+ :title="`${label}, ${trend.length} days`"
+ />
+ </div>
+</template>
diff --git a/src/components/metrics/PlatformsChart.vue b/src/components/metrics/PlatformsChart.vue
new file mode 100644
index 000000000..e466d8db3
--- /dev/null
+++ b/src/components/metrics/PlatformsChart.vue
@@ -0,0 +1,64 @@
+<script setup lang="ts">
+import { Bar, BarChart, Legend, Tooltip, XAxis, YAxis } from 'vccs'
+import { computed } from 'vue'
+
+import { formatOS } from '@/app/metrics/format'
+
+import type { PlatformCount } from './types'
+
+/**
+ * One row per OS, desktop and web stacked in the installs chart's colors, so each OS reads as a
+ * whole and as its two parts.
+ */
+const { platforms } = defineProps<{ platforms: PlatformCount[] }>()
+
+const rows = computed(() =>
+ platforms
+ .map((platform) => ({ ...platform, os: formatOS(platform.os) }))
+ .toSorted((a, b) => b.desktop + b.web - (a.desktop + a.web))
+)
+const ROW_HEIGHT = 32
+const LEGEND_HEIGHT = 28
+const height = computed(() => rows.value.length * ROW_HEIGHT + LEGEND_HEIGHT)
+</script>
+
+<template>
+ <BarChart
+ :data="rows"
+ layout="vertical"
+ :height="height"
+ :margin="{ top: 0, right: 0, bottom: 0, left: 0 }"
+ :bar-category-gap="6"
+ :is-animation-active="false"
+ class="text-[11px]"
+ title="Daily pings by OS, desktop and web"
+ >
+ <XAxis type="number" hide />
+ <YAxis type="category" data-key="os" :width="64" :tick-line="false" :axis-line="false" />
+ <Tooltip :cursor="{ fill: 'var(--color-hover)' }" />
+ <Legend
+ :height="LEGEND_HEIGHT"
+ vertical-align="top"
+ align="right"
+ icon-type="circle"
+ :icon-size="8"
+ />
+ <Bar
+ data-key="desktop"
+ name="Desktop"
+ stack-id="os"
+ fill="var(--color-chart-1)"
+ stroke="var(--color-panel)"
+ :stroke-width="2"
+ />
+ <Bar
+ data-key="web"
+ name="Web"
+ stack-id="os"
+ fill="var(--color-chart-2)"
+ stroke="var(--color-panel)"
+ :stroke-width="2"
+ :radius="[0, 4, 4, 0]"
+ />
+ </BarChart>
+</template>
diff --git a/src/components/metrics/RetentionChart.vue b/src/components/metrics/RetentionChart.vue
new file mode 100644
index 000000000..97eae1d99
--- /dev/null
+++ b/src/components/metrics/RetentionChart.vue
@@ -0,0 +1,79 @@
+<script setup lang="ts">
+import { CartesianGrid, Line, LineChart, Tooltip, XAxis, YAxis } from 'vccs'
+import { computed } from 'vue'
+
+import { formatCount, formatPercent } from '@/app/metrics/format'
+import { pooledRetention } from '@/app/metrics/retention'
+import type { RetentionCohort } from '@/app/metrics/retention'
+import { metricsRetention } from '@/theme/metrics/dashboard'
+
+/**
+ * How many installs come back: Day 1, 7, and 30 as numbers, then the whole curve. A day says
+ * how long it still needs until some installs are that old.
+ */
+const { cohorts } = defineProps<{ cohorts: RetentionCohort[] }>()
+
+const ui = metricsRetention()
+const points = computed(() =>
+ pooledRetention(cohorts).map((point) => ({
+ ...point,
+ label: point.day === 0 ? 'First day' : `Day ${point.day}`
+ }))
+)
+const HEADLINE_DAYS = [1, 7, 30]
+const headline = computed(() =>
+ HEADLINE_DAYS.map((day) => {
+ const point = points.value.find((candidate) => candidate.day === day)
+ return point
+ ? { day, value: formatPercent(point.share), empty: false }
+ : { day, value: day === 1 ? 'needs 1 day' : `needs ${day} days`, empty: true }
+ })
+)
+const formatShare = (value: unknown) => (typeof value === 'number' ? formatPercent(value) : '')
+// The tooltip hands each row back untyped, so the install count is read through a guard.
+const installsOf = (row: unknown) =>
+ typeof row === 'object' && row !== null && 'installs' in row && typeof row.installs === 'number'
+ ? row.installs
+ : 0
+const tooltipValue = (value: unknown, _name: unknown, item: { payload?: unknown }) =>
+ `${formatShare(value)} of ${formatCount(installsOf(item.payload))} installs`
+</script>
+
+<template>
+ <div :class="ui.root()">
+ <dl :class="ui.stats()">
+ <div v-for="stat in headline" :key="stat.day" :class="ui.stat()">
+ <dt :class="ui.statLabel()">Day {{ stat.day }}</dt>
+ <dd :class="ui.statValue()" :data-empty="stat.empty">{{ stat.value }}</dd>
+ </div>
+ </dl>
+ <LineChart
+ :data="points"
+ :height="180"
+ :margin="{ top: 8, right: 8, bottom: 0, left: 0 }"
+ :is-animation-active="false"
+ class="text-[11px]"
+ title="Share of installs that came back, by days since first seen"
+ >
+ <CartesianGrid :vertical="false" />
+ <XAxis data-key="label" :tick-line="false" :axis-line="false" :tick-margin="8" />
+ <YAxis
+ :width="40"
+ :domain="[0, 1]"
+ :ticks="[0, 0.25, 0.5, 0.75, 1]"
+ :tick-line="false"
+ :axis-line="false"
+ :tick-formatter="formatShare"
+ />
+ <Tooltip :formatter="tooltipValue" />
+ <Line
+ data-key="share"
+ name="Came back"
+ type="monotone"
+ stroke="var(--color-chart-1)"
+ :stroke-width="2"
+ :dot="{ r: 4, fill: 'var(--color-chart-1)', stroke: 'var(--color-panel)', strokeWidth: 2 }"
+ />
+ </LineChart>
+ </div>
+</template>
diff --git a/src/components/metrics/WaitlistList.vue b/src/components/metrics/WaitlistList.vue
new file mode 100644
index 000000000..58019e7e9
--- /dev/null
+++ b/src/components/metrics/WaitlistList.vue
@@ -0,0 +1,38 @@
+<script setup lang="ts">
+import { computed, ref } from 'vue'
+
+import { formatTime } from '@/app/metrics/format'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import { metricsWaitlist } from '@/theme/metrics/dashboard'
+
+import type { WaitlistSignup } from './types'
+
+/**
+ * Latest Cloud waitlist sign-ups by email domain; addresses never reach the dashboard. A long
+ * range shows the newest few until asked for the rest.
+ */
+const { signups } = defineProps<{ signups: WaitlistSignup[] }>()
+const ui = metricsWaitlist()
+
+const COLLAPSED_ROWS = 6
+const expanded = ref(false)
+const shown = computed(() => (expanded.value ? signups : signups.slice(0, COLLAPSED_ROWS)))
+const hidden = computed(() => signups.length - shown.value.length)
+</script>
+
+<template>
+ <div>
+ <ul :class="ui.list()">
+ <li v-for="signup in shown" :key="signup.signedUpAt" :class="ui.row()">
+ <span :class="ui.domain()">{{ signup.domain }}</span>
+ <span :class="ui.time()">{{ formatTime(signup.signedUpAt) }}</span>
+ <span :class="ui.status()" :data-confirmed="signup.confirmed">
+ {{ signup.confirmed ? 'Confirmed' : 'Waiting' }}
+ </span>
+ </li>
+ </ul>
+ <AppButton v-if="hidden > 0" size="sm" :class="ui.more()" @click="expanded = true">
+ Show {{ hidden }} more
+ </AppButton>
+ </div>
+</template>
diff --git a/src/components/metrics/types.ts b/src/components/metrics/types.ts
new file mode 100644
index 000000000..9f430a165
--- /dev/null
+++ b/src/components/metrics/types.ts
@@ -0,0 +1,10 @@
+import type { MetricsSnapshot } from '@open-pencil/feedback/contract'
+
+/** The rows the dashboard's charts and lists take, named after the API's own shape. */
+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 PlatformCount = MetricsSnapshot['platforms'][number]
+export type Release = MetricsSnapshot['releases'][number]
+export type WaitlistSignup = MetricsSnapshot['waitlist']['recent'][number]
diff --git a/src/components/ui/date/AppRangeCalendar.stories.ts b/src/components/ui/date/AppRangeCalendar.stories.ts
new file mode 100644
index 000000000..ce37ff9c6
--- /dev/null
+++ b/src/components/ui/date/AppRangeCalendar.stories.ts
@@ -0,0 +1,35 @@
+import type { Meta, StoryObj } from '@storybook/vue3-vite'
+import { expect, userEvent, within } from 'storybook/test'
+import { ref } from 'vue'
+
+import AppRangeCalendar from './AppRangeCalendar.vue'
+import type { DayRange } from './range'
+
+const meta = {
+ title: 'Design System/Inputs/Range Calendar',
+ render: () => ({
+ components: { AppRangeCalendar },
+ setup: () => ({ range: ref<DayRange | null>({ start: '2026-10-13', end: '2026-10-19' }) }),
+ template: `
+ <div class="w-72 bg-panel p-3 text-surface">
+ <AppRangeCalendar v-model="range" label="Days" min="2026-09-22" max="2026-10-20" />
+ <p class="mt-2 text-xs text-muted" data-testid="range">{{ range?.start }} – {{ range?.end }}</p>
+ </div>`
+ })
+} satisfies Meta
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const Selected: Story = {}
+
+/** A span is picked with two clicks; the model changes only once both ends are chosen. */
+export const PickASpan: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.click(canvas.getByRole('button', { name: /October 15, 2026/u }))
+ await expect(canvas.getByTestId('range')).toHaveTextContent('2026-10-13 – 2026-10-19')
+ await userEvent.click(canvas.getByRole('button', { name: /October 17, 2026/u }))
+ await expect(canvas.getByTestId('range')).toHaveTextContent('2026-10-15 – 2026-10-17')
+ }
+}
diff --git a/src/components/ui/date/AppRangeCalendar.vue b/src/components/ui/date/AppRangeCalendar.vue
new file mode 100644
index 000000000..76aa09316
--- /dev/null
+++ b/src/components/ui/date/AppRangeCalendar.vue
@@ -0,0 +1,100 @@
+<script setup lang="ts">
+import { parseDate } from '@internationalized/date'
+import type { DateRange } from 'reka-ui'
+import {
+ RangeCalendarCell,
+ RangeCalendarCellTrigger,
+ RangeCalendarGrid,
+ RangeCalendarGridBody,
+ RangeCalendarGridHead,
+ RangeCalendarGridRow,
+ RangeCalendarHeadCell,
+ RangeCalendarHeader,
+ RangeCalendarHeading,
+ RangeCalendarNext,
+ RangeCalendarPrev,
+ RangeCalendarRoot
+} from 'reka-ui'
+import { computed, shallowRef, watch } from 'vue'
+
+import IconButton from '@/components/ui/button/IconButton.vue'
+import { rangeCalendar } from '@/theme/date/range-calendar'
+
+import type { DayRange } from './range'
+
+/**
+ * One month for picking a span of days. The model changes only once both ends are chosen, so a
+ * half-picked span never reaches the caller.
+ */
+const { label, min, max } = defineProps<{ label: string; min?: string; max?: string }>()
+const model = defineModel<DayRange | null>({ required: true })
+
+const ui = rangeCalendar()
+const toCalendar = (range: DayRange | null): DateRange =>
+ range
+ ? { start: parseDate(range.start), end: parseDate(range.end) }
+ : { start: undefined, end: undefined }
+
+// Reka holds the span while it is being picked; the model only takes finished ones.
+const picking = shallowRef<DateRange>(toCalendar(model.value))
+watch(model, (range) => (picking.value = toCalendar(range)))
+
+const minValue = computed(() => (min ? parseDate(min) : undefined))
+const maxValue = computed(() => (max ? parseDate(max) : undefined))
+
+function pick(range: DateRange) {
+ picking.value = range
+ if (range.start && range.end)
+ model.value = { start: range.start.toString(), end: range.end.toString() }
+}
+</script>
+
+<template>
+ <RangeCalendarRoot
+ v-slot="{ weekDays, grid }"
+ :model-value="picking"
+ :min-value="minValue"
+ :max-value="maxValue"
+ :calendar-label="label"
+ :week-starts-on="1"
+ weekday-format="short"
+ fixed-weeks
+ :class="ui.root()"
+ @update:model-value="pick"
+ >
+ <RangeCalendarHeader :class="ui.header()">
+ <RangeCalendarPrev as-child>
+ <IconButton label="Previous month">
+ <icon-lucide-chevron-left class="size-3.5" />
+ </IconButton>
+ </RangeCalendarPrev>
+ <RangeCalendarHeading :class="ui.heading()" />
+ <RangeCalendarNext as-child>
+ <IconButton label="Next month">
+ <icon-lucide-chevron-right class="size-3.5" />
+ </IconButton>
+ </RangeCalendarNext>
+ </RangeCalendarHeader>
+ <RangeCalendarGrid v-for="month in grid" :key="month.value.toString()" :class="ui.grid()">
+ <RangeCalendarGridHead>
+ <RangeCalendarGridRow>
+ <RangeCalendarHeadCell v-for="day in weekDays" :key="day" :class="ui.headCell()">
+ {{ day }}
+ </RangeCalendarHeadCell>
+ </RangeCalendarGridRow>
+ </RangeCalendarGridHead>
+ <RangeCalendarGridBody>
+ <RangeCalendarGridRow v-for="(week, index) in month.rows" :key="index">
+ <RangeCalendarCell
+ v-for="day in week"
+ :key="day.toString()"
+ :date="day"
+ :class="ui.cell()"
+ >
+ <RangeCalendarCellTrigger :day="day" :month="month.value" :class="ui.day()" />
+ </RangeCalendarCell>
+ </RangeCalendarGridRow>
+ </RangeCalendarGridBody>
+ </RangeCalendarGrid>
+ </RangeCalendarRoot>
+</template>
diff --git a/src/components/ui/date/range.ts b/src/components/ui/date/range.ts
new file mode 100644
index 000000000..548d4bafb
--- /dev/null
+++ b/src/components/ui/date/range.ts
@@ -0,0 +1,5 @@
+/** A span of whole days, both ends included, as ISO dates (`2026-10-19`). */
+export interface DayRange {
+ start: string
+ end: string
+}
diff --git a/src/metrics/main.ts b/src/metrics/main.ts
new file mode 100644
index 000000000..28a3459ea
--- /dev/null
+++ b/src/metrics/main.ts
@@ -0,0 +1,25 @@
+import { createApp } from 'vue'
+
+import '@/app.css'
+import { utcToday } from '@/app/metrics/days'
+import { fetchMetricsSnapshot } from '@/app/metrics/load'
+import { presetRange } from '@/app/metrics/range'
+import MetricsView from '@/views/metrics/MetricsView.vue'
+
+// Entry for the team's metrics dashboard (`metrics.html`). Only the feedback Worker serves it,
+// under /admin behind Cloudflare Access; the editor never loads it.
+async function start(): Promise<void> {
+ const initialRange = presetRange('7d', utcToday().toString())
+ // The splash in metrics.html covers the first request; the page mounts with its answer.
+ const initialSnapshot = await fetchMetricsSnapshot(initialRange).catch((error: unknown) => {
+ console.warn('Metrics could not load', error)
+ return undefined
+ })
+ const app = createApp(MetricsView, { initialRange, initialSnapshot })
+ app.config.errorHandler = (error) => {
+ console.error(error)
+ }
+ app.mount('#app')
+}
+
+void start()
diff --git a/src/theme/date/range-calendar.ts b/src/theme/date/range-calendar.ts
new file mode 100644
index 000000000..62b33faa5
--- /dev/null
+++ b/src/theme/date/range-calendar.ts
@@ -0,0 +1,29 @@
+import { tv } from 'tailwind-variants'
+
+/**
+ * A month of days for picking a span: the ends are solid, the days between a tint, and the
+ * span under the pointer previews in the same tint before the second click.
+ */
+export const rangeCalendar = tv({
+ slots: {
+ root: 'flex flex-col gap-2 text-xs',
+ header: 'flex items-center justify-between gap-2',
+ heading: 'text-xs font-semibold',
+ grid: 'w-full border-collapse select-none',
+ headCell: 'h-7 w-8 text-center text-[10px] font-medium text-muted',
+ cell: 'p-0 text-center',
+ day: [
+ 'mx-auto flex size-8 cursor-pointer items-center justify-center rounded-md tabular-nums outline-none',
+ 'hover:bg-hover focus-visible:ring-1 focus-visible:ring-panel-focus',
+ 'data-[today]:font-semibold data-[today]:text-primary',
+ 'data-[highlighted]:rounded-none data-[highlighted]:bg-accent/15',
+ 'data-[selected]:rounded-none data-[selected]:bg-accent/15',
+ 'data-[selection-start]:rounded-l-md data-[selection-start]:bg-accent data-[selection-start]:text-on-accent',
+ 'data-[selection-end]:rounded-r-md data-[selection-end]:bg-accent data-[selection-end]:text-on-accent',
+ 'data-[highlighted-start]:rounded-l-md data-[highlighted-end]:rounded-r-md',
+ 'data-[outside-view]:text-muted/50',
+ 'data-[unavailable]:cursor-default data-[unavailable]:text-muted/40 data-[unavailable]:hover:bg-transparent',
+ 'data-[disabled]:cursor-default data-[disabled]:text-muted/40 data-[disabled]:hover:bg-transparent'
+ ]
+ }
+})
diff --git a/src/theme/metrics/dashboard.ts b/src/theme/metrics/dashboard.ts
new file mode 100644
index 000000000..83a35c232
--- /dev/null
+++ b/src/theme/metrics/dashboard.ts
@@ -0,0 +1,85 @@
+import { tv } from 'tailwind-variants'
+
+/** The metrics dashboard: a bar like Cloud's console, then cards on a grid. */
+export const metricsDashboard = tv({
+ slots: {
+ page: 'chart-theme flex h-full min-h-0 flex-col overflow-hidden bg-canvas text-surface',
+ bar: 'flex h-11 shrink-0 items-center gap-2 border-b border-border bg-panel px-4',
+ barTitle: 'text-xs font-semibold whitespace-nowrap',
+ barHost: 'truncate text-[11px] text-muted max-sm:hidden',
+ barMeta: 'truncate text-[11px] text-muted max-sm:hidden',
+ barEnd: 'ml-auto flex items-center gap-2',
+ main: 'min-w-0 flex-1 overflow-y-auto',
+ inner:
+ 'mx-auto flex w-full max-w-6xl flex-col gap-4 px-4 py-6 transition-opacity md:px-6 data-[loading=true]:opacity-60',
+ tiles: 'grid grid-cols-2 gap-4 lg:grid-cols-4',
+ row: 'grid gap-4 lg:grid-cols-2',
+ usage: 'flex flex-col gap-4',
+ breakdown: 'grid gap-6 md:grid-cols-2',
+ sectionLabel: 'mb-2 text-[11px] font-medium text-muted',
+ section: 'flex flex-col gap-4',
+ sectionHeading: 'mt-2 text-[11px] font-semibold tracking-wide text-muted uppercase'
+ }
+})
+
+/** A bordered panel with a title, an optional note, and its chart or list. */
+export const metricsCard = tv({
+ slots: {
+ root: 'flex min-w-0 flex-col gap-3 rounded-lg border border-border bg-panel p-4',
+ header: 'flex flex-wrap items-start justify-between gap-x-3 gap-y-1',
+ titleGroup: 'flex min-w-64 flex-1 flex-col gap-0.5',
+ title: 'text-xs font-semibold',
+ note: 'text-[11px] text-muted',
+ aside: 'shrink-0 text-[11px] text-muted tabular-nums'
+ }
+})
+
+/** A headline number above a word-sized trend. */
+export const metricsTile = tv({
+ slots: {
+ root: 'flex min-w-0 flex-col gap-1 rounded-lg border border-border bg-panel p-4',
+ label: 'text-[11px] text-muted',
+ value: 'text-2xl font-semibold tabular-nums',
+ detail: 'flex flex-wrap items-center gap-x-1 text-[11px] text-muted tabular-nums',
+ change: 'font-medium data-[direction=up]:text-success data-[direction=down]:text-error',
+ trend: 'mt-2 h-8'
+ }
+})
+
+/** Recent sign-ups, drawn like the Cloud console's lists. */
+export const metricsWaitlist = tv({
+ slots: {
+ list: 'flex flex-col',
+ row: 'flex min-h-9 items-center gap-3 border-b border-border py-1.5 text-xs last:border-b-0',
+ domain: 'min-w-0 flex-1 truncate font-medium',
+ time: 'shrink-0 text-[11px] text-muted tabular-nums',
+ more: 'mt-2',
+ status:
+ 'shrink-0 rounded px-1.5 py-px text-[10px] font-medium data-[confirmed=false]:bg-panel-field data-[confirmed=false]:text-muted data-[confirmed=true]:bg-success/10 data-[confirmed=true]:text-success'
+ }
+})
+
+/** Presets as rows beside a month calendar; the trigger shows the preset and its days. */
+export const metricsRangePicker = tv({
+ slots: {
+ triggerSpan: 'text-muted tabular-nums max-sm:hidden',
+ body: 'flex max-sm:flex-col',
+ presets:
+ 'flex w-40 flex-col gap-0.5 border-r border-border p-1.5 max-sm:w-auto max-sm:border-r-0 max-sm:border-b',
+ preset:
+ 'flex h-7 w-full cursor-pointer items-center justify-between gap-2 rounded-md px-2 text-xs outline-none hover:bg-hover focus-visible:ring-1 focus-visible:ring-panel-focus data-[selected=true]:font-semibold',
+ calendar: 'p-3'
+ }
+})
+
+/** Day 1, 7, and 30 above the retention curve; a day without data yet is a quiet dash. */
+export const metricsRetention = tv({
+ slots: {
+ root: 'flex flex-col gap-3',
+ stats: 'grid grid-cols-3 gap-4',
+ stat: 'flex flex-col gap-0.5',
+ statLabel: 'text-[11px] text-muted',
+ statValue:
+ 'flex h-7 items-center text-lg font-semibold tabular-nums data-[empty=true]:text-xs data-[empty=true]:font-normal data-[empty=true]:text-muted'
+ }
+})
diff --git a/src/theme/tokens.css b/src/theme/tokens.css
index eb581866a..574e44bfc 100644
--- a/src/theme/tokens.css
+++ b/src/theme/tokens.css
@@ -99,6 +99,11 @@
--color-code-string: #a3d9a5;
--color-code-number: #e5bc8b;
--color-code-comment: #969eaa;
+
+ /* Chart series in fixed order, checked as a set for color-vision deficiency on the panel. */
+ --color-chart-1: #3987e5;
+ --color-chart-2: #d95926;
+ --color-chart-3: #199e70;
}
html[data-theme='light'] {
@@ -139,4 +144,26 @@ html[data-theme='light'] {
--color-code-string: #276b3b;
--color-code-number: #965212;
--color-code-comment: #69727f;
+ --color-chart-1: #2a78d6;
+ --color-chart-2: #eb6834;
+ --color-chart-3: #1baf7a;
+}
+
+/* Points vccs charts at the theme: series colors, quiet grid and axes, panel tooltips. */
+@utility chart-theme {
+ --v-charts-series-1: var(--color-chart-1);
+ --v-charts-series-2: var(--color-chart-2);
+ --v-charts-series-3: var(--color-chart-3);
+ --v-charts-grid: var(--color-border);
+ --v-charts-axis: var(--color-border);
+ --v-charts-text: var(--color-muted);
+ --v-charts-cursor: var(--color-hover);
+ --v-charts-muted: var(--color-panel-field);
+ --v-charts-background: var(--color-panel);
+ --v-charts-inactive: var(--color-muted);
+ --v-charts-focus: var(--color-panel-focus);
+ --v-charts-tooltip-background: var(--color-panel);
+ --v-charts-tooltip-border: var(--color-border);
+ --v-charts-tooltip-foreground: var(--color-surface);
+ --v-charts-label-foreground: var(--color-surface);
}
diff --git a/src/views/metrics/MetricsView.vue b/src/views/metrics/MetricsView.vue
new file mode 100644
index 000000000..6a3b17ce5
--- /dev/null
+++ b/src/views/metrics/MetricsView.vue
@@ -0,0 +1,65 @@
+<script setup lang="ts">
+import { ref } from 'vue'
+
+import type { MetricsSnapshot } from '@open-pencil/feedback/contract'
+
+import { usePortalTheme } from '@/app/cloud-portal/theme'
+import { useMetricsSnapshot } from '@/app/metrics/load'
+import type { MetricsRange } from '@/app/metrics/range'
+import MetricsDashboard from '@/components/metrics/MetricsDashboard.vue'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import AppAlert from '@/components/ui/feedback/AppAlert.vue'
+import AppPlaceholder from '@/components/ui/feedback/AppPlaceholder.vue'
+
+// Served from the feedback Worker's own address, so it follows the system theme as Cloud's
+// pages do; the editor's stored theme is not visible here.
+usePortalTheme()
+
+/** The page mounts once its first numbers have loaded, or failed to, so it never shows half. */
+const { initialRange, initialSnapshot } = defineProps<{
+ initialRange: MetricsRange
+ initialSnapshot?: MetricsSnapshot
+}>()
+
+const range = ref(initialRange)
+const { snapshot, loading, failed, refresh } = useMetricsSnapshot(range, initialSnapshot)
+const host = globalThis.location.host
+// Access's session may have run out; reloading the page signs in again.
+const reload = () => globalThis.location.reload()
+</script>
+
+<template>
+ <MetricsDashboard
+ v-if="snapshot"
+ v-model:range="range"
+ :host="host"
+ :snapshot="snapshot"
+ :loading="loading"
+ @refresh="refresh"
+ >
+ <template v-if="failed" #alert>
+ <AppAlert
+ tone="warning"
+ heading="These numbers could not be updated"
+ description="Your sign-in may have expired. Reload the page to sign in again."
+ >
+ <template #actions>
+ <AppButton size="sm" variant="outline" @click="reload">Reload</AppButton>
+ </template>
+ </AppAlert>
+ </template>
+ </MetricsDashboard>
+ <main v-else-if="failed" class="flex h-full bg-canvas text-surface">
+ <AppPlaceholder
+ size="page"
+ label-as="h1"
+ label="The metrics could not load"
+ description="Your sign-in may have expired, or the service did not answer. Reload the page to try again."
+ >
+ <template #icon><icon-lucide-cloud-off class="size-5" /></template>
+ <template #action>
+ <AppButton variant="outline" @click="reload">Reload</AppButton>
+ </template>
+ </AppPlaceholder>
+ </main>
+</template>
diff --git a/tests/app/metrics/format.test.ts b/tests/app/metrics/format.test.ts
new file mode 100644
index 000000000..ff212e519
--- /dev/null
+++ b/tests/app/metrics/format.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test } from 'bun:test'
+
+import { formatCountry, formatDay } from '@/app/metrics/format'
+import { presetRange } from '@/app/metrics/range'
+
+describe('metrics labels', () => {
+ test('names countries, and Cloudflare codes that are not countries', () => {
+ expect(formatCountry('US')).toBe('United States')
+ // Tor traffic: `Intl.DisplayNames` throws on this code.
+ expect(formatCountry('T1')).toBe('Tor')
+ expect(formatCountry('XX')).toBe('Unknown')
+ expect(formatCountry('1')).toBe('1')
+ })
+
+ test('formats a day as the UTC day it names', () => {
+ expect(formatDay('2026-10-19')).toBe('Oct 19')
+ })
+})
+
+describe('metrics ranges', () => {
+ test('a preset ends today and never starts before the first recorded day', () => {
+ expect(presetRange('7d', '2026-10-19')).toEqual({
+ preset: '7d',
+ start: '2026-10-13',
+ end: '2026-10-19'
+ })
+ expect(presetRange('30d', '2026-10-19', '2026-09-22')).toMatchObject({ start: '2026-09-22' })
+ })
+})
diff --git a/tools/checks/architecture/src/steiger-rules/index.ts b/tools/checks/architecture/src/steiger-rules/index.ts
index eb3acd6c7..e62912cb6 100644
--- a/tools/checks/architecture/src/steiger-rules/index.ts
+++ b/tools/checks/architecture/src/steiger-rules/index.ts
@@ -1,14 +1,13 @@
import { readFileSync } from 'node:fs'
import path from 'node:path'
-import { parse as parseVueSfc } from 'vue/compiler-sfc'
-
import { noCrossPackageReexportShims } from './cross-package-reexport-shims.ts'
import {
noDynamicTailwindStateClasses,
noVueTemplateUIHooksOrSVG
} from './dynamic-tailwind-classes.ts'
import { noGraphBuildersInFrontEnds } from './graph-builders.ts'
+import { noNativeTitleAttributesInVue } from './native-titles.ts'
import {
collectFiles,
collectFolders,
@@ -337,15 +336,16 @@ const noNonUIImportsInSharedUI = createImportRule(
}
)
-// The editor's root and router, the desktop Software Update window's page entry, and the Cloud
-// portal's entry and router.
+// The editor's root and router, the desktop Software Update window's page entry, the Cloud
+// portal's entry and router, and the metrics dashboard's entry.
const VIEW_ENTRYPOINTS = new Set([
'src/App.vue',
'src/main.ts',
'src/router.ts',
'src/updater.ts',
'src/cloud/main.ts',
- 'src/cloud/router.ts'
+ 'src/cloud/router.ts',
+ 'src/metrics/main.ts'
])
const noViewsImportedOutsideEntry = createImportRule(
@@ -357,14 +357,19 @@ const noViewsImportedOutsideEntry = createImportRule(
}
)
-// The Cloud portal is served by the Cloud server on its own; it reuses the app's UI, never the
-// editor, so its build stays small.
+// The Cloud portal is served by the Cloud server on its own, and the metrics dashboard by the
+// feedback Worker; both reuse the app's UI, never the editor, so their builds stay small.
const CLOUD_PORTAL_SOURCES = [
'src/cloud/',
'src/views/cloud/',
'src/app/cloud-portal/',
'src/components/cloud-portal/',
- 'src/theme/cloud-portal/'
+ 'src/theme/cloud-portal/',
+ 'src/metrics/',
+ 'src/views/metrics/',
+ 'src/app/metrics/',
+ 'src/components/metrics/',
+ 'src/theme/metrics/'
]
const EDITOR_ONLY_MODULES = ['src/app/editor/', 'src/app/shell/']
@@ -376,7 +381,7 @@ const noEditorImportsInCloudPortal = createImportRule(
specifier.startsWith('canvaskit-wasm') ||
EDITOR_ONLY_MODULES.some((prefix) => resolved?.startsWith(prefix))
if (!editorOnly) return null
- return 'The Cloud portal must not import editor sessions, CanvasKit, or the app shell, so `bun run build:cloud-portal` stays small.'
+ return 'The Cloud portal and the metrics dashboard must not import editor sessions, CanvasKit, or the app shell, so their standalone builds stay small.'
}
)
@@ -421,30 +426,6 @@ const noHardcodedMacOSShortcutGlyphs = createTextRule(
}
)
-const VUE_ATTRIBUTE_NODE = 6
-const VUE_DIRECTIVE_NODE = 7
-
-type VueTemplateNode = {
- type?: number
- name?: string
- arg?: { content?: string }
- props?: VueTemplateNode[]
- children?: VueTemplateNode[]
- loc?: { start?: { line?: number; column?: number } }
-}
-
-function walkVueTemplateAst(node: VueTemplateNode, visitor: (node: VueTemplateNode) => void) {
- visitor(node)
- for (const prop of node.props ?? []) walkVueTemplateAst(prop, visitor)
- for (const child of node.children ?? []) walkVueTemplateAst(child, visitor)
-}
-
-function vuePropName(prop: VueTemplateNode) {
- if (prop.type === VUE_ATTRIBUTE_NODE) return prop.name ?? null
- if (prop.type === VUE_DIRECTIVE_NODE && prop.name === 'bind') return prop.arg?.content ?? null
- return null
-}
-
const SHARED_TEST_ID_ALLOWLIST = new Set([
'packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue'
])
@@ -473,33 +454,6 @@ const noProductionTestIdsInSharedLayers = createTextRule(
}
)
-const noNativeTitleAttributesInVue = createTextRule(
- 'open-pencil/no-native-title-attributes-in-vue',
- (sourceRel, content) => {
- if (
- !sourceRel.endsWith('.vue') ||
- (!sourceRel.startsWith('src/') && !sourceRel.startsWith('packages/vue/src/'))
- ) {
- return []
- }
-
- const template = parseVueSfc(content, { filename: sourceRel }).descriptor.template?.ast
- if (!template) return []
-
- const diagnostics: Array<{ message: string; line?: number; column?: number }> = []
- walkVueTemplateAst(template as VueTemplateNode, (node) => {
- if (vuePropName(node) !== 'title') return
- const loc = node.loc?.start
- diagnostics.push({
- message: 'Use Tip/Reka tooltip patterns instead of native title attributes.',
- line: loc?.line,
- column: loc?.column
- })
- })
- return diagnostics
- }
-)
-
const SHORTCUT_LABEL_PATTERN = /(?:Shift|Ctrl|Alt|Option|Cmd|Command|⌘|⇧|⌥|⌃)\s*[+)\w]/u
const noShortcutTextInLabels = createTextRule(
diff --git a/tools/checks/architecture/src/steiger-rules/native-titles.ts b/tools/checks/architecture/src/steiger-rules/native-titles.ts
new file mode 100644
index 000000000..02db4d2ad
--- /dev/null
+++ b/tools/checks/architecture/src/steiger-rules/native-titles.ts
@@ -0,0 +1,87 @@
+import ts from 'typescript'
+import { parse as parseVueSfc } from 'vue/compiler-sfc'
+
+import { createTextRule, type Rule } from './support.ts'
+
+const VUE_ATTRIBUTE_NODE = 6
+const VUE_DIRECTIVE_NODE = 7
+
+type VueTemplateNode = {
+ type?: number
+ name?: string
+ tag?: string
+ arg?: { content?: string }
+ props?: VueTemplateNode[]
+ children?: VueTemplateNode[]
+ loc?: { start?: { line?: number; column?: number } }
+}
+
+function propName(prop: VueTemplateNode) {
+ if (prop.type === VUE_ATTRIBUTE_NODE) return prop.name ?? null
+ if (prop.type === VUE_DIRECTIVE_NODE && prop.name === 'bind') return prop.arg?.content ?? null
+ return null
+}
+
+/**
+ * Components the file imports from vccs. A vccs chart takes `title` as its accessible name,
+ * which it renders as the chart's `aria-label`, not as a native tooltip.
+ */
+function chartComponents(sourceRel: string, scripts: string[]): Set<string> {
+ const names = new Set<string>()
+ for (const script of scripts) {
+ const source = ts.createSourceFile(sourceRel, script, ts.ScriptTarget.Latest, true)
+ for (const statement of source.statements) {
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
+ continue
+ if (statement.moduleSpecifier.text !== 'vccs') continue
+ const bindings = statement.importClause?.namedBindings
+ if (!bindings || !ts.isNamedImports(bindings)) continue
+ for (const element of bindings.elements) names.add(element.name.text)
+ }
+ }
+ return names
+}
+
+export interface NativeTitle {
+ line?: number
+ column?: number
+}
+
+/** `title` attributes and bindings in an app or SDK Vue template, except on vccs charts. */
+export function nativeTitles(sourceRel: string, content: string): NativeTitle[] {
+ if (
+ !sourceRel.endsWith('.vue') ||
+ (!sourceRel.startsWith('src/') && !sourceRel.startsWith('packages/vue/src/'))
+ ) {
+ return []
+ }
+ const { descriptor } = parseVueSfc(content, { filename: sourceRel })
+ const template = descriptor.template?.ast
+ if (!template) return []
+ const charts = chartComponents(sourceRel, [
+ descriptor.script?.content ?? '',
+ descriptor.scriptSetup?.content ?? ''
+ ])
+
+ const found: NativeTitle[] = []
+ const visit = (node: VueTemplateNode) => {
+ if (!node.tag || !charts.has(node.tag)) {
+ for (const prop of node.props ?? []) {
+ if (propName(prop) !== 'title') continue
+ found.push({ line: prop.loc?.start?.line, column: prop.loc?.start?.column })
+ }
+ }
+ for (const child of node.children ?? []) visit(child)
+ }
+ visit(template as VueTemplateNode)
+ return found
+}
+
+export const noNativeTitleAttributesInVue: Rule = createTextRule(
+ 'open-pencil/no-native-title-attributes-in-vue',
+ (sourceRel, content) =>
+ nativeTitles(sourceRel, content).map((position) => ({
+ message: 'Use Tip/Reka tooltip patterns instead of native title attributes.',
+ ...position
+ }))
+)
diff --git a/tools/checks/architecture/tests/native-titles.test.ts b/tools/checks/architecture/tests/native-titles.test.ts
new file mode 100644
index 000000000..c22330764
--- /dev/null
+++ b/tools/checks/architecture/tests/native-titles.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, test } from 'bun:test'
+
+import { nativeTitles } from '../src/steiger-rules/native-titles'
+
+const sfc = (template: string, script = '') =>
+ `<script setup lang="ts">\n${script}\n</script>\n<template>\n${template}\n</template>\n`
+
+describe('native titles in Vue templates', () => {
+ test('finds title attributes and bindings on elements and app components', () => {
+ const content = sfc(
+ `<div title="Hint"><span :title="hint" /><MetricsCard title="Visits" /></div>`,
+ "import MetricsCard from './MetricsCard.vue'"
+ )
+ expect(nativeTitles('src/components/Example.vue', content)).toHaveLength(3)
+ })
+
+ test("allows a vccs chart's title, which is its accessible name", () => {
+ const content = sfc(
+ `<BarChart title="Daily installs"><Bar /></BarChart><Sparkline :title="label" />`,
+ "import { Bar, BarChart, Sparkline } from 'vccs'"
+ )
+ expect(nativeTitles('src/components/metrics/Chart.vue', content)).toEqual([])
+ })
+
+ test('a component with a chart name from elsewhere is still checked', () => {
+ const content = sfc(
+ `<BarChart title="Daily installs" />`,
+ "import BarChart from './BarChart.vue'"
+ )
+ expect(nativeTitles('src/components/metrics/Chart.vue', content)).toHaveLength(1)
+ })
+
+ test('only checks app and SDK Vue files', () => {
+ expect(nativeTitles('packages/docs/Example.vue', sfc(`<div title="Hint" />`))).toEqual([])
+ expect(nativeTitles('src/app/example.ts', 'const title = 1')).toEqual([])
+ })
+})
diff --git a/vite.config.ts b/vite.config.ts
index 47e30709f..4d87cae65 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -32,9 +32,13 @@ export default defineConfig(async ({ command, mode }) => {
// `--mode cloud-portal` builds only the Cloud server's own pages (`cloud.html`), without the
// editor, its demo document, CanvasKit, or the PWA.
const cloudPortal = mode === 'cloud-portal'
+ // `--mode metrics` builds only the metrics dashboard (`metrics.html`) for the feedback Worker,
+ // which serves it under /admin behind Cloudflare Access.
+ const metrics = mode === 'metrics'
+ const standalone = cloudPortal || metrics
// `VITE_OPENPENCIL_CLOUD=off` builds the editor without OpenPencil Cloud.
const cloud = loadEnv(mode, __dirname, 'VITE_').VITE_OPENPENCIL_CLOUD !== 'off'
- await Promise.all([ensureBrandAssets(['web']), cloudPortal ? undefined : ensureDemoDocument()])
+ await Promise.all([ensureBrandAssets(['web']), standalone ? undefined : ensureDemoDocument()])
return {
resolve: {
alias: createOpenPencilAliases(__dirname, { cloud })
@@ -54,25 +58,33 @@ export default defineConfig(async ({ command, mode }) => {
tailwindcss(),
Icons({ compiler: 'vue3', customCollections: { ai: aiIconCollection() } }),
Components({ resolvers: [IconsResolver({ prefix: 'icon', customCollections: ['ai'] })] }),
- cloudPortal ? undefined : openPencilAutomationPlugin(command, host),
+ standalone ? undefined : openPencilAutomationPlugin(command, host),
vue(),
- cloudPortal ? cloudPortalBrandPlugin() : openPencilPwaPlugin()
+ metrics
+ ? cloudPortalBrandPlugin((outDir) => resolve(outDir, '..'))
+ : cloudPortal
+ ? cloudPortalBrandPlugin()
+ : openPencilPwaPlugin()
],
clearScreen: false,
- publicDir: cloudPortal ? false : 'public',
+ publicDir: standalone ? false : 'public',
+ base: metrics ? '/admin/' : '/',
build: {
// Syntax is lowered to the supported browser baseline; APIs are not polyfilled.
target: viteBuildTarget(),
chunkSizeWarningLimit: 2500,
- outDir: cloudPortal ? 'dist-cloud-portal' : 'dist',
+ outDir: metrics ? 'dist-metrics/admin' : cloudPortal ? 'dist-cloud-portal' : 'dist',
rolldownOptions: {
- // The desktop Software Update window is its own page; the Cloud portal builds alone.
- input: cloudPortal
- ? { cloud: resolve(__dirname, 'cloud.html') }
- : {
- main: resolve(__dirname, 'index.html'),
- updater: resolve(__dirname, 'updater.html')
- }
+ // The desktop Software Update window is its own page; the Cloud portal and the metrics
+ // dashboard build alone.
+ input: metrics
+ ? { metrics: resolve(__dirname, 'metrics.html') }
+ : cloudPortal
+ ? { cloud: resolve(__dirname, 'cloud.html') }
+ : {
+ main: resolve(__dirname, 'index.html'),
+ updater: resolve(__dirname, 'updater.html')
+ }
}
},
server: createDevServerOptions(host, __dirname)
diff --git a/vite/cloud-portal.ts b/vite/cloud-portal.ts
index 38f0551b8..4a995ef36 100644
--- a/vite/cloud-portal.ts
+++ b/vite/cloud-portal.ts
@@ -4,10 +4,11 @@ import { resolve } from 'node:path'
import type { Plugin, ResolvedConfig } from 'vite'
/**
- * The Cloud portal builds without the editor's public directory (fonts, CanvasKit, demo files)
- * and copies only the brand artwork, which components load from `/brand/`.
+ * The Cloud portal and the metrics dashboard build without the editor's public directory
+ * (fonts, CanvasKit, demo files) and copy only the brand artwork, which components load from
+ * `/brand/`. `site` is the folder served at the site's root, when the page itself lives below it.
*/
-export function cloudPortalBrandPlugin(): Plugin {
+export function cloudPortalBrandPlugin(site?: (outDir: string) => string): Plugin {
let config: ResolvedConfig | undefined
return {
name: 'open-pencil-cloud-portal-brand',
@@ -17,7 +18,8 @@ export function cloudPortalBrandPlugin(): Plugin {
},
writeBundle() {
if (!config) return
- cpSync(resolve(config.root, 'public/brand'), resolve(config.build.outDir, 'brand'), {
+ const outDir = resolve(config.root, config.build.outDir)
+ cpSync(resolve(config.root, 'public/brand'), resolve(site?.(outDir) ?? outDir, 'brand'), {
recursive: true
})
}