Files
magpie/site/pluginstats.js
T
yetone 13a9f1263a plugins: Discover counts who uses and likes each plugin
Discover showed npm's weekly downloads, which CI, mirrors and magpie's
own keepMovedCurrent updates inflate. Now each card and the hero say
how many people use a plugin, counted by magpie itself, and a plugin's
page has a like.

- The daily stats send (stats.Send) also POSTs usemagpie.ai
  /api/plugins/report with the install id and the installed, switched-on
  plugins Discover lists, by their Discover key: the npm name, or
  github:owner/repo for a repository tagged magpie-plugin
  (plugin.Public). A folder, a private repository or an unlisted
  package is never named. It goes only while "Share the agents,
  providers, models and plugins I use" is on (noUsageStats), and only
  where the day's event goes at all (Count me as a user, DO_NOT_TRACK,
  MAGPIE_NO_STATS, release builds).
- site/pluginstats.js on D1 magpie-plugins: users are the ids that
  reported a plugin in the last 7 days, reports drop after 30 days, a
  caller's address is kept only as a hash for an hour (60 asks an
  hour). /api/plugins/stats carries no id and is cached for an hour.
- A like (POST /api/plugins/like through the GUI's /api/plugins/like)
  is taken only for a plugin installed and on here, can be taken back,
  and is kept in plugin-likes.json.
- "Most liked" sorts by likes once a plugin has 20, below that by
  GitHub's stars.
- plugincounts.js is loaded with the Plugins page, not the core, and
  redraws the cards only when the counts changed.
- The privacy text follows: README.md, README.zh-CN.md, docs/reference.md,
  the site's privacy and start pages in en, zh and ja, llms-full.txt,
  and the Privacy switch's label and description in every language.

Run at this tree (on origin/main 51da6f1f5):
- Windows box (win-run): gofmt -l clean; go vet of internal/stats,
  internal/plugin, internal/gui ok for windows and linux (-tags nogui);
  node --test site/pluginstats.test.mjs site/worker.test.mjs 44 of 44;
  TestCoreScriptBudget, TestPluginCountsAndLikes ok; GUI old-webkit,
  i18n-keys, privacy-usage-stats, plugin-git, plugin-local,
  plugin-github in both engines: 45 of 46, the one red is #5919
  (.side-foot:has, d374168d0).
- mote, one commit before the rebase onto 51da6f1f5 (Go unchanged
  since): go vet darwin ok; TestSendPlugins, TestPublicPlugins,
  TestPluginCountsAndLikes, TestCoreScriptBudget ok.
- Windows, at 7bc7af1d0 (one rebase earlier): go test internal/stats
  ok; internal/plugin and internal/gui red only in TestPiPackage and
  eight gui tests that fail the same at origin/main 72f2deebe on that
  box (#4115, #5928; TestCherryStudioImportRow added to #4115 with its
  cause). Every plugin*, market*, privacy*, i18n*, old-webkit* and
  discover* GUI file (83 files, both engines, concurrency 4): the reds
  left after the fix below match origin/main 6d7862769 on the same box,
  or are flakes red there too under concurrency: plugin-update-button
  (#4500), plugin-proxy-page (#6017, new), privacy-agent-telemetry
  (#6018, new).
- Broken by hand, caught: the first run had `const like = !local && …`,
  so a local plugin's page called false?.sync() every 600ms; 136
  "like?.sync is not a function" errors across plugin-git, plugin-local,
  plugin-github and the sign-in files. Fixed before this commit.
- Live: D1 magpie-plugins created and the worker deployed;
  /api/plugins/stats answers {"plugins":{}}, a bad report or like 400,
  /api/latest and / 200. No test data was written to production.

Not tried: the full Go suite and the full GUI suite. mote had 28 suites
waiting for its lock, and WSL on the Windows box failed with
E_UNEXPECTED while another session uninstalled a distro. Not tried
either: a real like or report from a release build (source builds
never send), so the first real counts come with this release.
2026-11-11 04:28:18 +08:00

152 lines
6.5 KiB
JavaScript

// Discover's counts (the app's internal/stats/plugins.go): how many
// computers use each plugin Discover lists, and how many like it.
//
// Each app that lets its usage stats go reports once a day which of
// Discover's plugins are installed, under its random install id, never an
// account or address. A plugin's users are the ids that reported it in
// the last seven days. A like is one per id, can be taken back, and comes
// only from an app that has the plugin (the app checks; here a like also
// counts as that id having it). The caller's address is kept only hashed,
// for an hour, to hold each one to RATE asks an hour.
//
// D1 (wrangler.jsonc's PLUGINS) holds three tables; the quarter-hour
// cron prunes what is old.
const ID = /^[0-9a-f]{32}$/;
const NPM = /^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
const GIT = /^github:[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
export const MOST = 50; // plugins in one report, as the app's most
export const RATE = 60; // asks an address makes in an hour
const WEEK = 7 * 864e5;
const KEEP = 30 * 864e5;
const SCHEMA = [
"CREATE TABLE IF NOT EXISTS installs (device TEXT NOT NULL, plugin TEXT NOT NULL, day TEXT NOT NULL, PRIMARY KEY (device, plugin))",
"CREATE INDEX IF NOT EXISTS installs_day ON installs (day)",
"CREATE TABLE IF NOT EXISTS likes (device TEXT NOT NULL, plugin TEXT NOT NULL, PRIMARY KEY (device, plugin))",
"CREATE TABLE IF NOT EXISTS asks (who TEXT NOT NULL, hour INTEGER NOT NULL, n INTEGER NOT NULL, PRIMARY KEY (who, hour))",
];
// the tables are made once an isolate, for each database it is given
const made = new WeakMap();
function schema(db) {
if (!made.has(db))
made.set(
db,
db.batch(SCHEMA.map((s) => db.prepare(s))).catch((e) => {
made.delete(db);
throw e;
}),
);
return made.get(db);
}
export function validName(n) {
return typeof n === "string" && n.length <= 214 && (NPM.test(n) || GIT.test(n));
}
const day = (t) => new Date(t).toISOString().slice(0, 10);
function answer(body, status = 200, headers = {}) {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", ...headers },
});
}
async function who(req) {
const ip = req.headers.get("CF-Connecting-IP") || "";
const h = await crypto.subtle.digest("SHA-256", new TextEncoder().encode("magpie-plugins:" + ip));
return [...new Uint8Array(h).slice(0, 12)].map((b) => b.toString(16).padStart(2, "0")).join("");
}
// held reports whether the caller has made RATE asks this hour already
async function held(db, req, now) {
const row = await db
.prepare("INSERT INTO asks (who, hour, n) VALUES (?1, ?2, 1) ON CONFLICT (who, hour) DO UPDATE SET n = n + 1 RETURNING n")
.bind(await who(req), Math.floor(now / 36e5))
.first();
return (row?.n ?? 0) > RATE;
}
async function body(req) {
if (req.method !== "POST") return null;
try {
const text = await req.text();
if (text.length > 64 << 10) return null;
return JSON.parse(text);
} catch {
return null;
}
}
// handle answers /api/plugins/*, or null for any other path.
export async function handle(req, env, ctx, now = Date.now()) {
const path = new URL(req.url).pathname;
if (!["/api/plugins/report", "/api/plugins/like", "/api/plugins/stats"].includes(path)) return null;
const db = env.PLUGINS;
if (!db) return answer({ error: "counts aren't kept here" }, 503);
await schema(db);
if (path === "/api/plugins/stats") {
if (req.method !== "GET" && req.method !== "HEAD") return answer({ error: "GET" }, 405);
return stats(req, db, ctx, now);
}
const b = await body(req);
if (!b || !ID.test(b.id ?? "")) return answer({ error: "a report needs the app's id" }, 400);
if (await held(db, req, now)) return answer({ error: "too many asks; try again in an hour" }, 429);
if (path === "/api/plugins/report") {
const names = Array.isArray(b.plugins) ? [...new Set(b.plugins)] : null;
if (!names || names.length > MOST || !names.every(validName)) return answer({ error: "plugins: names Discover lists" }, 400);
const today = day(now);
const marks = names.map((_, i) => `?${i + 2}`).join(",");
const gone = db.prepare(`DELETE FROM installs WHERE device = ?1${names.length ? ` AND plugin NOT IN (${marks})` : ""}`).bind(b.id, ...names);
const put = names.map((n) =>
db
.prepare("INSERT INTO installs (device, plugin, day) VALUES (?1, ?2, ?3) ON CONFLICT (device, plugin) DO UPDATE SET day = ?3")
.bind(b.id, n, today),
);
await db.batch([gone, ...put]);
return answer({ ok: true });
}
// a like, or one taken back
if (!validName(b.plugin) || typeof b.on !== "boolean") return answer({ error: "which plugin, and on or off?" }, 400);
const steps = b.on
? [
db.prepare("INSERT INTO likes (device, plugin) VALUES (?1, ?2) ON CONFLICT DO NOTHING").bind(b.id, b.plugin),
db
.prepare("INSERT INTO installs (device, plugin, day) VALUES (?1, ?2, ?3) ON CONFLICT (device, plugin) DO UPDATE SET day = ?3")
.bind(b.id, b.plugin, day(now)),
]
: [db.prepare("DELETE FROM likes WHERE device = ?1 AND plugin = ?2").bind(b.id, b.plugin)];
await db.batch(steps);
const row = await db.prepare("SELECT COUNT(*) AS n FROM likes WHERE plugin = ?1").bind(b.plugin).first();
return answer({ likes: row?.n ?? 0 });
}
// stats is every plugin's users and likes, held at the edge for an hour
async function stats(req, db, ctx, now) {
const key = new Request(new URL("/api/plugins/stats", req.url).toString());
const hit = await caches.default.match(key);
if (hit) return hit;
const [users, likes] = await db.batch([
db.prepare("SELECT plugin, COUNT(*) AS n FROM installs WHERE day >= ?1 GROUP BY plugin").bind(day(now - WEEK)),
db.prepare("SELECT plugin, COUNT(*) AS n FROM likes GROUP BY plugin"),
]);
const plugins = {};
for (const r of users.results) (plugins[r.plugin] ??= {}).users = r.n;
for (const r of likes.results) (plugins[r.plugin] ??= {}).likes = r.n;
const res = answer({ plugins }, 200, { "Cache-Control": "public, max-age=3600" });
ctx.waitUntil(caches.default.put(key, res.clone()));
return res;
}
// prune drops installs not reported in a month and addresses' old counts
export async function prune(env, now = Date.now()) {
const db = env.PLUGINS;
if (!db) return;
await schema(db);
await db.batch([
db.prepare("DELETE FROM installs WHERE day < ?1").bind(day(now - KEEP)),
db.prepare("DELETE FROM asks WHERE hour < ?1").bind(Math.floor(now / 36e5) - 1),
]);
}