tally-menubar 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # tally-menubar
2
2
 
3
+ ## Your AI coding Wrapped
4
+
5
+ ```sh
6
+ npx tally-menubar wrapped
7
+ ```
8
+
9
+ Reads the session logs Claude Code, Codex, Pi and OpenCode already keep on your computer, prices them at API rates, and opens a Wrapped-style deck in your browser: six 1080×1920 story slides and a 1200×630 card for X. Pick 24 hours, 7 days or 30 days, set which plans you pay for, then copy, download or post. Works on macOS, Linux and Windows.
10
+
11
+ Nothing is uploaded and no project names are shown. The only network request is LiteLLM's public model price table, cached for a week. Your plan is read from `~/.claude.json` and `~/.codex/auth.json` (never the Keychain), and you can change it on the page.
12
+
13
+ Options: `--period=24h|7d|30d` picks the range it opens on (default 30d); `--no-open` prints the file path instead of opening a browser.
14
+
15
+ ## The menu bar app (macOS)
16
+
3
17
  Installs [Tally](https://github.com/PratikRai0101/tally), a macOS menu bar app that shows how much of each AI coding plan (Claude, Codex, OpenCode Go) you have left, when it resets, and what your usage would cost at API prices.
4
18
 
5
19
  ```sh
@@ -10,6 +24,7 @@ That downloads the Tally release from GitHub, checks it against the SHA-256 ship
10
24
 
11
25
  | Command | What it does |
12
26
  |---|---|
27
+ | `npx tally-menubar wrapped` | Your AI coding Wrapped (any OS) |
13
28
  | `npx tally-menubar` | Install Tally and open it |
14
29
  | `npx tally-menubar@latest update` | Update to the newest version |
15
30
  | `npx tally-menubar usage` | Print spend, tokens and limits in the terminal |
@@ -18,6 +33,8 @@ That downloads the Tally release from GitHub, checks it against the SHA-256 ship
18
33
 
19
34
  Options: `--no-open` skips launching after install, `--force` reinstalls.
20
35
 
36
+ The deck's font is Newsreader by Production Type, under the SIL Open Font License (`wrapped/OFL-Newsreader.txt`).
37
+
21
38
  If Tally is already in `/Applications`, it is updated there. Set `TALLY_INSTALL_DIR` to install somewhere else.
22
39
 
23
40
  ## Why use this instead of the .zip
package/bin/tally.js CHANGED
@@ -156,16 +156,25 @@ function uninstall() {
156
156
  }
157
157
  }
158
158
 
159
+ async function wrapped() {
160
+ const opts = { "no-open": flags.has("--no-open") };
161
+ const p = args.find((a) => a.startsWith("--period="));
162
+ if (p) opts.period = p.split("=")[1];
163
+ await require("../lib/wrapped.js").wrapped({ say, flags: opts, version: PKG.version });
164
+ }
165
+
159
166
  function help() {
160
167
  say(`tally-menubar ${PKG.version}: installs Tally ${RELEASE.version}, AI plan limits in your macOS menu bar
161
168
 
169
+ npx tally-menubar wrapped your AI coding Wrapped: share cards from your logs (any OS)
162
170
  npx tally-menubar install Tally and open it
163
171
  npx tally-menubar@latest update update to the newest version
164
172
  npx tally-menubar usage print spend, tokens and limits in the terminal
165
173
  npx tally-menubar uninstall remove Tally (--purge also removes its settings)
166
174
  npx tally-menubar version show versions
167
175
 
168
- Options: --no-open (don't launch after installing), --force (reinstall)
176
+ Options: --no-open (don't launch or open the browser), --force (reinstall),
177
+ --period=24h|7d|30d (which range the Wrapped opens on; default 30d)
169
178
  Installs to ~/Applications, or /Applications if Tally is already there.
170
179
  https://github.com/PratikRai0101/tally`);
171
180
  }
@@ -176,7 +185,7 @@ function version() {
176
185
  say(fs.existsSync(app) ? `installed: Tally ${appVersion(app)} at ${app}` : "installed: none");
177
186
  }
178
187
 
179
- const commands = { install, update: install, usage, uninstall, version, help };
188
+ const commands = { install, update: install, usage, uninstall, version, help, wrapped };
180
189
  if (flags.has("--help") || flags.has("-h")) help();
181
190
  else if (flags.has("--version") || flags.has("-v")) version();
182
191
  else if (!commands[cmd]) { help(); process.exit(1); }
package/lib/wrapped.js ADDED
@@ -0,0 +1,345 @@
1
+ // `npx tally-menubar wrapped`: reads the session logs your coding agents already keep, prices them,
2
+ // and opens a Wrapped-style deck in the browser. Runs on macOS, Linux and Windows. Nothing is uploaded;
3
+ // the only network call is LiteLLM's public price table (cached for a week).
4
+ "use strict";
5
+
6
+ const fs = require("fs");
7
+ const os = require("os");
8
+ const path = require("path");
9
+ const { spawn } = require("child_process");
10
+
11
+ const HOME = os.homedir();
12
+ const DAY = 86400000;
13
+ const PERIODS = { "24h": 86400, "7d": 7 * 86400, "30d": 30 * 86400 };
14
+
15
+ // ---------- prices (LiteLLM's table, same resolution rules as the app) ----------
16
+
17
+ const LITELLM = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
18
+
19
+ function cacheDir() {
20
+ const d = process.platform === "darwin" ? path.join(HOME, "Library", "Caches", "tally-menubar")
21
+ : process.platform === "win32" ? path.join(process.env.LOCALAPPDATA || path.join(HOME, "AppData", "Local"), "tally-menubar")
22
+ : path.join(process.env.XDG_CACHE_HOME || path.join(HOME, ".cache"), "tally-menubar");
23
+ try { fs.mkdirSync(d, { recursive: true }); } catch {}
24
+ return d;
25
+ }
26
+
27
+ function ingest(text) {
28
+ let obj;
29
+ try { obj = JSON.parse(text); } catch { return null; }
30
+ const doc = obj && (obj.document || obj);
31
+ const t = new Map();
32
+ for (const [k, v] of Object.entries(doc || {})) {
33
+ if (!v || typeof v.input_cost_per_token !== "number" || typeof v.output_cost_per_token !== "number") continue;
34
+ const inp = v.input_cost_per_token, write = v.cache_creation_input_token_cost ?? inp * 1.25;
35
+ t.set(k.toLowerCase(), {
36
+ input: inp, output: v.output_cost_per_token,
37
+ cacheRead: v.cache_read_input_token_cost ?? inp * 0.1,
38
+ cacheWrite: write, cacheWrite1h: v.cache_creation_input_token_cost_above_1hr ?? write * 1.6,
39
+ });
40
+ }
41
+ return t.size ? t : null;
42
+ }
43
+
44
+ const readText = (p) => { try { return fs.readFileSync(p, "utf8"); } catch { return null; } };
45
+
46
+ async function loadPrices() {
47
+ const own = path.join(cacheDir(), "model-prices.json");
48
+ const app = path.join(HOME, "Library", "Application Support", "Tally", "model-prices.json");
49
+ const fresh = (p) => { try { return Date.now() - fs.statSync(p).mtimeMs < 7 * DAY; } catch { return false; } };
50
+ for (const p of [own, app]) if (fresh(p)) { const t = ingest(readText(p)); if (t) return t; }
51
+ try {
52
+ const r = await fetch(LITELLM, { signal: AbortSignal.timeout(20000) });
53
+ if (r.ok) { const text = await r.text(); const t = ingest(text); if (t) { try { fs.writeFileSync(own, text); } catch {} return t; } }
54
+ } catch {}
55
+ for (const p of [own, app]) { const t = ingest(readText(p)); if (t) return t; } // stale beats nothing
56
+ return new Map();
57
+ }
58
+
59
+ function rater(table) {
60
+ const memo = new Map();
61
+ const resolve = (model) => {
62
+ const names = [model];
63
+ const slash = model.lastIndexOf("/");
64
+ if (slash >= 0) names.push(model.slice(slash + 1));
65
+ for (const n of [...names]) {
66
+ const c = n.replace(/\[.*\]$/, "").replace(/-\d{8}$/, "");
67
+ if (c !== n) names.push(c);
68
+ }
69
+ for (const n of names) {
70
+ if (table.has(n)) return table.get(n);
71
+ for (const p of ["anthropic/", "openai/", "anthropic.", "openai.", "xai/", "deepseek/"]) if (table.has(p + n)) return table.get(p + n);
72
+ }
73
+ const base = names[names.length - 1];
74
+ let best = null;
75
+ for (const k of table.keys()) if (!k.includes("/") && k.length >= 6 && base.startsWith(k) && (!best || k.length > best.length)) best = k;
76
+ return best ? table.get(best) : null;
77
+ };
78
+ return (raw) => {
79
+ const m = String(raw).toLowerCase();
80
+ if (!memo.has(m)) memo.set(m, resolve(m));
81
+ return memo.get(m);
82
+ };
83
+ }
84
+
85
+ // ---------- log files ----------
86
+
87
+ function jsonlFiles(dir, since, out = []) {
88
+ let ents;
89
+ try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
90
+ for (const e of ents) {
91
+ if (e.name.startsWith(".")) continue;
92
+ const p = path.join(dir, e.name);
93
+ if (e.isDirectory()) jsonlFiles(p, since, out);
94
+ else if (e.isFile() && e.name.endsWith(".jsonl")) { try { if (fs.statSync(p).mtimeMs >= since) out.push(p); } catch {} }
95
+ }
96
+ return out;
97
+ }
98
+
99
+ /** Calls fn(obj, i) for each line containing needles[i]; other lines are never JSON-parsed. */
100
+ function eachLine(file, needles, fn) {
101
+ let buf;
102
+ try { buf = fs.readFileSync(file); } catch { return; }
103
+ const nb = needles.map((n) => Buffer.from(n));
104
+ let s = 0;
105
+ while (s < buf.length) {
106
+ let e = buf.indexOf(10, s);
107
+ if (e < 0) e = buf.length;
108
+ if (e - s > 2) {
109
+ const line = buf.subarray(s, e);
110
+ for (let i = 0; i < nb.length; i++) {
111
+ if (line.includes(nb[i])) {
112
+ let o = null;
113
+ try { o = JSON.parse(line.toString("utf8")); } catch {}
114
+ if (o) fn(o, i);
115
+ break;
116
+ }
117
+ }
118
+ }
119
+ s = e + 1;
120
+ }
121
+ }
122
+
123
+ const int = (v) => (typeof v === "number" && isFinite(v) ? Math.trunc(v) : 0);
124
+ const stem = (f) => path.basename(f, ".jsonl");
125
+
126
+ function serviceFrom(provider) {
127
+ switch (String(provider || "").toLowerCase()) {
128
+ case "anthropic": case "claude": return "claude";
129
+ case "openai-codex": case "codex": case "chatgpt": return "codex";
130
+ case "opencode-go": return "opencodeGo";
131
+ case "opencode": case "opencode-zen": return "opencodeZen";
132
+ case "openai": return "openai";
133
+ default: return "other";
134
+ }
135
+ }
136
+
137
+ function parseClaude(file, rate, out) {
138
+ eachLine(file, ['"usage"'], (o) => {
139
+ const m = o.message, u = m && m.usage;
140
+ if (!u || !m.model || m.model === "<synthetic>") return;
141
+ const t = Date.parse(o.timestamp);
142
+ if (!t) return;
143
+ const input = int(u.input_tokens), read = int(u.cache_read_input_tokens), write = int(u.cache_creation_input_tokens), output = int(u.output_tokens);
144
+ const w1h = int(u.cache_creation && u.cache_creation.ephemeral_1h_input_tokens), w5m = Math.max(0, write - w1h);
145
+ const r = rate(m.model);
146
+ const cost = r ? input * r.input + output * r.output + read * r.cacheRead + w5m * r.cacheWrite + w1h * r.cacheWrite1h : 0;
147
+ out.push({ t, tool: "claude-code", svc: "claude", model: m.model, tokens: input + read + write + output, cost,
148
+ session: o.sessionId || stem(file), key: m.id ? `c:${m.id}:${o.requestId || ""}` : null });
149
+ });
150
+ }
151
+
152
+ function parseCodex(file, rate, out) {
153
+ let model = "gpt-5-codex", lastTotal = -1;
154
+ eachLine(file, ['"token_count"', '"turn_context"'], (o, kind) => {
155
+ const p = o.payload;
156
+ if (!p) return;
157
+ if (kind === 1) { if (p.model) model = p.model; return; }
158
+ if (p.type !== "token_count" || !p.info || !p.info.last_token_usage) return;
159
+ const t = Date.parse(o.timestamp);
160
+ if (!t) return;
161
+ const total = int(p.info.total_token_usage && p.info.total_token_usage.total_tokens);
162
+ if (total === lastTotal) return;
163
+ lastTotal = total;
164
+ const l = p.info.last_token_usage;
165
+ const cached = int(l.cached_input_tokens), write = int(l.cache_write_input_tokens), output = int(l.output_tokens);
166
+ const input = Math.max(0, int(l.input_tokens) - cached - write);
167
+ const r = rate(model);
168
+ const cost = r ? input * r.input + cached * r.cacheRead + write * r.cacheWrite + output * r.output : 0;
169
+ out.push({ t, tool: "codex", svc: "codex", model, tokens: input + cached + write + output, cost, session: stem(file) });
170
+ });
171
+ }
172
+
173
+ function parsePi(file, rate, out) {
174
+ eachLine(file, ['"usage"'], (o) => {
175
+ const m = o.message, u = m && m.usage;
176
+ if (!u) return;
177
+ const t = Date.parse(o.timestamp) || (typeof m.timestamp === "number" ? m.timestamp : 0);
178
+ if (!t) return;
179
+ const model = m.model || "unknown", provider = m.provider;
180
+ const input = int(u.input), output = int(u.output), read = int(u.cacheRead), write = int(u.cacheWrite);
181
+ let cost = (u.cost && typeof u.cost.total === "number") ? u.cost.total : 0;
182
+ if (!cost) { const r = rate(model); if (r) cost = input * r.input + output * r.output + read * r.cacheRead + write * r.cacheWrite; }
183
+ out.push({ t, tool: "pi", svc: serviceFrom(provider), model: provider ? `${provider}/${model}` : model,
184
+ tokens: input + output + read + write, cost, session: stem(file) });
185
+ });
186
+ }
187
+
188
+ function scanOpenCode(since, out) {
189
+ const db = path.join(HOME, ".local", "share", "opencode", "opencode.db");
190
+ if (!fs.existsSync(db)) return;
191
+ let sqlite;
192
+ const warn = process.emitWarning;
193
+ process.emitWarning = () => {}; // node:sqlite prints an "experimental" warning on some versions
194
+ try { sqlite = require("node:sqlite"); } catch { return; } finally { process.emitWarning = warn; }
195
+ try {
196
+ const d = new sqlite.DatabaseSync(db, { readOnly: true });
197
+ const rows = d.prepare("SELECT session_id, time_created, data FROM session_message WHERE type = 'assistant' AND time_created >= ?").all(since);
198
+ d.close();
199
+ for (const row of rows) {
200
+ let o;
201
+ try { o = JSON.parse(row.data); } catch { continue; }
202
+ const tk = o && o.tokens;
203
+ if (!tk) continue;
204
+ const cache = tk.cache || {};
205
+ const input = int(tk.input), output = int(tk.output) + int(tk.reasoning), read = int(cache.read), write = int(cache.write);
206
+ if (input + output + read + write === 0) continue;
207
+ const mo = o.model || {};
208
+ out.push({ t: Number(row.time_created), tool: "opencode", svc: serviceFrom(mo.providerID || o.providerID),
209
+ model: mo.id || o.modelID || "unknown", tokens: input + output + read + write, cost: typeof o.cost === "number" ? o.cost : 0,
210
+ session: String(row.session_id) });
211
+ }
212
+ } catch {}
213
+ }
214
+
215
+ async function scan() {
216
+ const since = Date.now() - PERIODS["30d"] * 1000;
217
+ const rate = rater(await loadPrices());
218
+ const recs = [];
219
+ const roots = (dirs) => dirs.flatMap((d) => jsonlFiles(path.join(HOME, ...d.split("/")), since));
220
+ for (const f of roots([".claude/projects", ".config/claude/projects"])) parseClaude(f, rate, recs);
221
+ for (const f of roots([".codex/sessions", ".codex/archived_sessions"])) parseCodex(f, rate, recs);
222
+ for (const f of roots([".pi/agent/sessions"])) parsePi(f, rate, recs);
223
+ scanOpenCode(since, recs);
224
+ const seen = new Set();
225
+ return recs.filter((r) => r.t >= since && (!r.key || (!seen.has(r.key) && seen.add(r.key))));
226
+ }
227
+
228
+ // ---------- plans, read from files the CLIs keep (never the Keychain, never a network call) ----------
229
+
230
+ function jsonFile(p) { try { return JSON.parse(fs.readFileSync(p, "utf8")); } catch { return null; } }
231
+
232
+ function detectPlans() {
233
+ const plans = {};
234
+ // Claude: ~/.claude.json records the subscription type of the signed-in account.
235
+ const acct = (jsonFile(path.join(HOME, ".claude.json")) || {}).oauthAccount;
236
+ const creds = ((jsonFile(path.join(HOME, ".claude", ".credentials.json")) || {}).claudeAiOauth) || {};
237
+ const kind = String((acct && acct.organizationType) || creds.subscriptionType || "").toLowerCase();
238
+ const tier = String((acct && acct.organizationRateLimitTier) || creds.rateLimitTier || "").toLowerCase();
239
+ if (kind.includes("max")) plans.claude = tier.includes("20x") ? "Claude Max 20x" : "Claude Max 5x";
240
+ else if (kind.includes("team") || kind.includes("enterprise")) plans.claude = "Claude Team";
241
+ else if (kind.includes("pro")) plans.claude = "Claude Pro";
242
+ else if (acct) plans.claude = "Claude Pro";
243
+ // Codex: the ChatGPT plan is a claim inside the stored id token.
244
+ try {
245
+ const a = jsonFile(path.join(HOME, ".codex", "auth.json"));
246
+ const tok = a && a.tokens && a.tokens.id_token;
247
+ if (tok) {
248
+ const claims = JSON.parse(Buffer.from(tok.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
249
+ const p = String((claims["https://api.openai.com/auth"] || {}).chatgpt_plan_type || "").toLowerCase();
250
+ plans.codex = p.includes("pro") ? "ChatGPT Pro" : (p.includes("team") || p.includes("business")) ? "ChatGPT Business" : p ? "ChatGPT Plus" : undefined;
251
+ }
252
+ } catch {}
253
+ return plans;
254
+ }
255
+
256
+ // ---------- numbers per period (no project names, no paths) ----------
257
+
258
+ function periodData(recs, key, now) {
259
+ const secs = PERIODS[key], since = now - secs * 1000;
260
+ const rs = recs.filter((r) => r.t >= since);
261
+ const services = {}, models = {}, sessions = new Set();
262
+ const hours = Array(24).fill(0), weekdays = Array(7).fill(0);
263
+ const w = (r) => (r.cost > 0 ? r.cost : r.tokens * 1e-7);
264
+ for (const r of rs) {
265
+ const s = services[r.svc] || (services[r.svc] = { cost: 0, tokens: 0 });
266
+ s.cost += r.cost; s.tokens += r.tokens;
267
+ const name = r.model.split("/").pop();
268
+ models[name] = (models[name] || 0) + r.cost;
269
+ sessions.add(r.tool + "|" + r.session);
270
+ const d = new Date(r.t);
271
+ hours[d.getHours()] += w(r);
272
+ weekdays[d.getDay()] += w(r);
273
+ }
274
+ // Bars: hourly for 24 h, daily otherwise, ending now.
275
+ const n = key === "24h" ? 24 : key === "7d" ? 7 : 30;
276
+ const nowD = new Date(now);
277
+ const starts = Array.from({ length: n }, (_, i) => key === "24h"
278
+ ? new Date(nowD.getFullYear(), nowD.getMonth(), nowD.getDate(), nowD.getHours() - (n - 1 - i)).getTime()
279
+ : new Date(nowD.getFullYear(), nowD.getMonth(), nowD.getDate() - (n - 1 - i)).getTime());
280
+ const bars = Array(n).fill(0);
281
+ for (const r of rs) { for (let i = n - 1; i >= 0; i--) if (starts[i] <= r.t) { bars[i] += w(r); break; } }
282
+ const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
283
+ const labels = starts.map((t, i) => {
284
+ const d = new Date(t);
285
+ if (key === "24h") return d.getHours() % 6 === 0 ? String(d.getHours()).padStart(2, "0") : "";
286
+ if (key === "7d") return days[d.getDay()];
287
+ return (n - 1 - i) % 7 === 0 ? String(d.getDate()) : "";
288
+ });
289
+ let peak = -1;
290
+ bars.forEach((v, i) => { if (v > 0 && (peak < 0 || v > bars[peak])) peak = i; });
291
+ return {
292
+ seconds: secs, services, sessions: sessions.size,
293
+ models: Object.entries(models).sort((a, b) => b[1] - a[1]).slice(0, 4).map(([name, cost]) => ({ name, cost })),
294
+ hours, weekdays, bars, barLabels: labels, peakBar: peak >= 0 ? starts[peak] : null,
295
+ };
296
+ }
297
+
298
+ // ---------- the command ----------
299
+
300
+ const money = (v) => (v >= 100 ? "$" + Math.round(v) : "$" + v.toFixed(2));
301
+
302
+ function opener(file) {
303
+ if (process.platform === "darwin") return ["open", [file]];
304
+ if (process.platform === "win32") return ["cmd", ["/c", "start", "", file]];
305
+ return ["xdg-open", [file]];
306
+ }
307
+
308
+ async function wrapped({ say, flags, version }) {
309
+ say("Reading your Claude Code, Codex, Pi and OpenCode logs (last 30 days)…");
310
+ const recs = await scan();
311
+ if (!recs.length) {
312
+ say("No usage found. Tally reads ~/.claude/projects, ~/.codex/sessions, ~/.pi/agent/sessions and OpenCode's database.");
313
+ return;
314
+ }
315
+ const now = Date.now();
316
+ const data = {
317
+ generated: now, version, plans: detectPlans(),
318
+ periods: Object.fromEntries(Object.keys(PERIODS).map((k) => [k, periodData(recs, k, now)])),
319
+ defaultPeriod: ["24h", "7d", "30d"].includes(flags.period) ? flags.period : "30d",
320
+ };
321
+ const dir = path.join(__dirname, "..", "wrapped");
322
+ const font = fs.readFileSync(path.join(dir, "newsreader.woff2")).toString("base64");
323
+ const html = fs.readFileSync(path.join(dir, "page.html"), "utf8")
324
+ .replace("__FONT__", font)
325
+ .replace("/*__DATA__*/null", JSON.stringify(data).replace(/</g, "\\u003c"));
326
+ const outDir = path.join(os.tmpdir(), "tally-wrapped");
327
+ fs.mkdirSync(outDir, { recursive: true });
328
+ const out = path.join(outDir, `tally-wrapped-${new Date(now - new Date(now).getTimezoneOffset() * 60000).toISOString().slice(0, 10)}.html`);
329
+ fs.writeFileSync(out, html);
330
+
331
+ const m = data.periods["30d"], api = Object.values(m.services).reduce((s, v) => s + v.cost, 0);
332
+ const tokens = Object.values(m.services).reduce((s, v) => s + v.tokens, 0);
333
+ const tk = tokens >= 1e9 ? (tokens / 1e9).toFixed(2) + "B" : (tokens / 1e6).toFixed(1) + "M";
334
+ say(`\n Last 30 days: ${money(api)} at API prices · ${tk} tokens · ${m.sessions} sessions`);
335
+ say(` Your Wrapped: ${out}`);
336
+ if (!flags["no-open"]) {
337
+ const [bin, argv] = opener(out);
338
+ try { spawn(bin, argv, { stdio: "ignore", detached: true }).unref(); say(" Opened it in your browser."); }
339
+ catch { say(" Open that file in your browser."); }
340
+ }
341
+ say("\n Nothing was uploaded: the page is a local file built from your logs.");
342
+ if (process.platform === "darwin") say(" Want this live in your menu bar? npx tally-menubar");
343
+ }
344
+
345
+ module.exports = { wrapped, scan, periodData, detectPlans };
package/package.json CHANGED
@@ -1,15 +1,14 @@
1
1
  {
2
2
  "name": "tally-menubar",
3
- "version": "1.5.0",
4
- "description": "Install Tally, the macOS menu bar app that shows your AI coding plan limits, resets and spend (Claude, Codex, OpenCode).",
5
- "keywords": ["macos", "menubar", "claude", "codex", "opencode", "usage", "limits", "ai"],
3
+ "version": "1.6.0",
4
+ "description": "Your AI coding Wrapped (npx tally-menubar wrapped, any OS), and the installer for Tally, the macOS menu bar app for Claude, Codex and OpenCode limits, resets and spend.",
5
+ "keywords": ["wrapped", "claude-code", "codex", "opencode", "ai-usage", "macos", "menubar", "claude", "usage", "limits", "ai"],
6
6
  "homepage": "https://github.com/PratikRai0101/tally",
7
7
  "repository": { "type": "git", "url": "git+https://github.com/PratikRai0101/tally.git", "directory": "npm" },
8
8
  "bugs": "https://github.com/PratikRai0101/tally/issues",
9
9
  "license": "MIT",
10
10
  "bin": { "tally-menubar": "bin/tally.js" },
11
- "files": ["bin", "release.json", "LICENSE"],
12
- "os": ["darwin"],
11
+ "files": ["bin", "lib", "wrapped", "release.json", "LICENSE"],
13
12
  "engines": { "node": ">=18" },
14
13
  "scripts": {
15
14
  "pin": "node scripts/pin-release.mjs"
package/release.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.5",
3
- "url": "https://github.com/PratikRai0101/tally/releases/download/v1.5/Tally.zip",
4
- "sha256": "21129f5063116242b99a5f6e64225183cfc412505e539776a28b01a72f48a599"
2
+ "version": "1.6",
3
+ "url": "https://github.com/PratikRai0101/tally/releases/download/v1.6/Tally.zip",
4
+ "sha256": "439b8b0bd2f37c6c3ec473baedf17d55583629e329833db1db7caa7e7505744b"
5
5
  }
@@ -0,0 +1,93 @@
1
+ Copyright 2020 The Newsreader Project Authors (http://github.com/productiontype/Newsreader)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file
@@ -0,0 +1,499 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>Your Tally Wrapped</title>
7
+ <style>
8
+ @font-face{font-family:"Newsreader";src:url(data:font/woff2;base64,__FONT__) format("woff2");font-display:block}
9
+ :root{--bg:#0e0e0d;--panel:#161615;--fg:#f1f1ee;--dim:#8a8a86;--line:#2a2a28;--orange:#e5874c;--green:#3fb987}
10
+ *{box-sizing:border-box;margin:0}
11
+ html,body{background:var(--bg)}
12
+ body{color:var(--fg);font:15px/1.45 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;-webkit-font-smoothing:antialiased;min-height:100vh;display:flex;flex-direction:column}
13
+ button,select{font:inherit;color:inherit}
14
+ header{display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:18px 28px;border-bottom:1px solid var(--line)}
15
+ header h1{font-size:17px;font-weight:600;letter-spacing:-.01em;margin-right:auto;display:flex;align-items:center;gap:10px}
16
+ header h1 canvas{width:28px;height:28px}
17
+ .seg{display:flex;border:1px solid var(--line);border-radius:9px;padding:2px;background:var(--panel)}
18
+ .seg button{border:0;background:none;padding:6px 14px;border-radius:7px;cursor:pointer;color:var(--dim)}
19
+ .seg button[aria-pressed=true]{background:#2c2c2a;color:var(--fg)}
20
+ .plans{display:flex;gap:10px;align-items:center;flex-wrap:wrap;color:var(--dim);font-size:13px}
21
+ .plans label{display:flex;gap:6px;align-items:center}
22
+ .plans select{background:var(--panel);border:1px solid var(--line);border-radius:7px;padding:5px 8px}
23
+ main{flex:1;display:flex;gap:22px;overflow-x:auto;padding:26px 28px 18px;scroll-snap-type:x mandatory;scroll-padding-inline:28px;align-items:flex-start}
24
+ figure{flex:none;scroll-snap-align:start;display:flex;flex-direction:column;gap:10px}
25
+ figure canvas{display:block;height:min(66vh,620px);width:auto;border-radius:12px;box-shadow:0 10px 30px rgba(0,0,0,.45)}
26
+ figure.post canvas{height:auto;width:min(80vw,640px)}
27
+ figcaption{display:flex;gap:8px;align-items:center;color:var(--dim);font-size:12.5px}
28
+ figcaption span{margin-right:auto}
29
+ .btn{border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:6px 12px;cursor:pointer}
30
+ .btn:hover{border-color:#44443f}
31
+ .btn.primary{background:var(--fg);color:var(--bg);border-color:var(--fg);font-weight:600}
32
+ footer{display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:16px 28px 22px;border-top:1px solid var(--line);color:var(--dim);font-size:13px}
33
+ footer .note{margin-right:auto}
34
+ footer code{color:var(--fg);background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:2px 7px;font:12.5px ui-monospace,"SF Mono",Menlo,Consolas,monospace}
35
+ #toast{position:fixed;left:50%;bottom:84px;transform:translateX(-50%);background:var(--fg);color:var(--bg);padding:9px 16px;border-radius:9px;font-weight:600;opacity:0;transition:opacity .2s;pointer-events:none}
36
+ #toast.on{opacity:1}
37
+ @media (max-width:640px){header,main,footer{padding-left:16px;padding-right:16px}main{scroll-padding-inline:16px}}
38
+ </style>
39
+ </head>
40
+ <body>
41
+ <header>
42
+ <h1><canvas id="logo" width="56" height="56"></canvas>Your Tally Wrapped</h1>
43
+ <div class="plans" id="plans"></div>
44
+ <div class="seg" id="periods"></div>
45
+ </header>
46
+ <main id="strip"></main>
47
+ <footer>
48
+ <div class="note">Built on your computer from your agents’ logs. Nothing was uploaded. No project names are shown.</div>
49
+ <button class="btn" id="all">Download all</button>
50
+ <button class="btn primary" id="x">Copy card &amp; post on X</button>
51
+ </footer>
52
+ <div id="toast"></div>
53
+ <script>
54
+ "use strict";
55
+ const DATA = /*__DATA__*/null;
56
+
57
+ // ---------- look ----------
58
+ const SANS = '-apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
59
+ const SERIF = '"Newsreader", Georgia, serif';
60
+ const MONO = 'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace';
61
+ const C = { paper: "#fbfbfa", ink: "#0e0e0d", orange: "#e5874c", green: "#3fb987", grey: "#a9a9a5", soft: "#d9d9d5", dim: "#3a3a37", muted: "#6b6b68" };
62
+ const TILE = { claude: C.orange, codex: C.paper, opencodeGo: C.green, opencodeZen: "#4e95f5", openai: "#9b7bea", other: "#d9b44a" };
63
+ const NAMES = { claude: "Claude", codex: "Codex", opencodeGo: "OpenCode Go", opencodeZen: "OpenCode Zen", openai: "OpenAI", other: "Other" };
64
+ const PLANS = {
65
+ claude: [["none", "None", 0], ["Claude Pro", "Pro", 20], ["Claude Max 5x", "Max 5×", 100], ["Claude Max 20x", "Max 20×", 200], ["Claude Team", "Team", 30]],
66
+ codex: [["none", "None", 0], ["ChatGPT Plus", "Plus", 20], ["ChatGPT Pro", "Pro", 200], ["ChatGPT Business", "Business", 30]],
67
+ opencodeGo: [["none", "None", 0], ["Go", "Go", 10]],
68
+ };
69
+ const state = { period: DATA.defaultPeriod, plans: { claude: DATA.plans.claude || "none", codex: DATA.plans.codex || "none", opencodeGo: "Go" } };
70
+ try { const saved = JSON.parse(localStorage.getItem("tally-wrapped-plans") || "null"); if (saved) Object.assign(state.plans, saved); } catch {}
71
+
72
+ // ---------- numbers ----------
73
+ const money = (v) => v === 0 ? "$0.00" : v < 0.01 ? "<$0.01" : v >= 1000 ? "$" + Math.round(v) : "$" + v.toFixed(2);
74
+ const times = (m) => (m >= 10 ? m.toFixed(0) : m.toFixed(1)) + "×";
75
+ function tok(n) {
76
+ const t = (v) => v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2);
77
+ return n >= 1e9 ? t(n / 1e9) + "B" : n >= 1e6 ? t(n / 1e6) + "M" : n >= 1e3 ? t(n / 1e3) + "K" : String(n);
78
+ }
79
+ const priceOf = (s) => { const p = (PLANS[s] || []).find((x) => x[0] === state.plans[s]); return p ? p[2] : 0; };
80
+ const hourName = (h) => h === 0 ? "midnight" : h === 12 ? "noon" : `${h % 12} ${h < 12 ? "am" : "pm"}`;
81
+
82
+ function stats() {
83
+ const P = DATA.periods[state.period], share = P.seconds / (30 * 86400);
84
+ let planCost = 0, covered = 0;
85
+ const rows = [];
86
+ for (const [s, v] of Object.entries(P.services)) {
87
+ if (v.cost <= 0.005) continue;
88
+ const price = priceOf(s);
89
+ let x = null;
90
+ if (price > 0) { planCost += price * share; covered += v.cost; x = v.cost / (price * share); }
91
+ const plan = state.plans[s] && state.plans[s] !== "none" ? state.plans[s] : null;
92
+ const name = s === "claude" ? (plan || "Claude") : s === "openai" ? "OpenAI API" : NAMES[s];
93
+ let meta = money(v.cost);
94
+ if (s === "codex" && plan) meta += " · " + plan;
95
+ if (x != null) meta += " · " + times(x) + (s === "codex" ? "" : " value");
96
+ else if (s === "openai") meta += " · pay as you go";
97
+ rows.push({ s, cost: v.cost, x, name, meta });
98
+ }
99
+ rows.sort((a, b) => b.cost - a.cost);
100
+ const api = Object.values(P.services).reduce((a, v) => a + v.cost, 0);
101
+ const tokens = Object.values(P.services).reduce((a, v) => a + v.tokens, 0);
102
+ const multiple = planCost > 0 ? covered / planCost : null;
103
+ const end = new Date(DATA.generated), days = state.period === "24h" ? 1 : state.period === "7d" ? 7 : 30;
104
+ const start = new Date(end.getFullYear(), end.getMonth(), end.getDate() - (days - 1));
105
+ const md = (d) => d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
106
+ const range = days === 1 ? md(end) : start.getMonth() === end.getMonth() ? `${md(start)} – ${end.getDate()}` : `${md(start)} – ${md(end)}`;
107
+ return {
108
+ P, rows, api, tokens, planCost, multiple, range,
109
+ money: api >= 100 ? "$" + Math.round(api) : money(api),
110
+ unit: { "24h": "day", "7d": "week", "30d": "month" }[state.period],
111
+ span: { "24h": "24 hours", "7d": "seven days", "30d": "30 days" }[state.period],
112
+ persona: persona(P),
113
+ };
114
+ }
115
+
116
+ function persona(P) {
117
+ const hrs = P.hours, total = Math.max(hrs.reduce((a, b) => a + b, 0), 1e-12);
118
+ const share = (a, b) => hrs.slice(a, b).reduce((x, y) => x + y, 0) / total;
119
+ const night = share(0, 5), morning = share(5, 12), evening = share(18, 24);
120
+ const wd = P.weekdays, weekend = (wd[0] + wd[6]) / Math.max(wd.reduce((a, b) => a + b, 0), 1e-12);
121
+ let peak = 12; hrs.forEach((v, i) => { if (v > hrs[peak]) peak = i; });
122
+ let name;
123
+ if (state.period !== "24h" && weekend >= 0.45) name = "Weekender";
124
+ else if (night >= 0.3) name = "Night Owl";
125
+ else if ((morning < 0.05 || peak >= 22 || peak < 5) && evening + night >= 0.3) name = "Late Shift";
126
+ else if (morning >= 0.4) name = "Early Bird";
127
+ else name = "Day Shift";
128
+ let s = morning < 0.005 ? "Not one prompt before noon. " : `${Math.round(morning * 100)}% of it before noon. `;
129
+ s += "Peak at " + hourName(peak);
130
+ s += night > 0.02 && peak !== 0 ? ", still going past midnight. " : ". ";
131
+ if (state.period !== "24h" && P.peakBar) s += new Date(P.peakBar).toLocaleDateString("en-US", { weekday: "long" }) + " was your biggest day.";
132
+ return { name, line: s.trim() };
133
+ }
134
+
135
+ function tokenWords(n) {
136
+ if (n >= 1e9) return (n >= 1e10 ? (n / 1e9).toFixed(1) : (n / 1e9).toFixed(2)) + " billion";
137
+ if (n >= 1e6) return (n >= 1e8 ? (n / 1e6).toFixed(0) : (n / 1e6).toFixed(1)) + " million";
138
+ return tok(n);
139
+ }
140
+
141
+ function postText(st) {
142
+ let t = `My ${st.unit} in AI coding: ${st.money} at API prices`;
143
+ if (st.multiple) t += ` on ${money(st.planCost)} of plans (${times(st.multiple)})`;
144
+ t += `. ${tok(st.tokens)} tokens, and apparently I'm ${st.persona.name === "Weekender" ? "a Weekender" : "on the " + st.persona.name}.`;
145
+ return t + " Get yours: npx tally-menubar wrapped · https://github.com/PratikRai0101/tally";
146
+ }
147
+
148
+ // ---------- dithering ----------
149
+ const B4 = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];
150
+ const ch = (i, v) => { const q = Math.round(Math.max(0, Math.min(1, v)) * 255); return i === 0 ? `rgb(${q},0,0)` : i === 1 ? `rgb(0,${q},0)` : `rgb(0,0,${q})`; };
151
+
152
+ /** Paints intensities into a low-res mask (one channel per colour), then draws a square dot wherever a cell beats the Bayer threshold. */
153
+ function dots(ctx, x0, y0, w, h, cell, colors, paint, dot = 0.78) {
154
+ const sw = Math.ceil(w / cell), sh = Math.ceil(h / cell), m = document.createElement("canvas");
155
+ m.width = sw; m.height = sh;
156
+ const mx = m.getContext("2d", { willReadFrequently: true });
157
+ mx.fillStyle = "#000"; mx.fillRect(0, 0, sw, sh);
158
+ mx.globalCompositeOperation = "lighten";
159
+ mx.save(); mx.scale(1 / cell, 1 / cell); paint(mx); mx.restore();
160
+ const d = mx.getImageData(0, 0, sw, sh).data, paths = [new Path2D(), new Path2D(), new Path2D()], z = cell * dot;
161
+ for (let y = 0; y < sh; y++) for (let x = 0; x < sw; x++) {
162
+ const i = (y * sw + x) * 4, r = d[i], g = d[i + 1], b = d[i + 2], v = Math.max(r, g, b) / 255;
163
+ if (v < 0.04 || v <= (B4[y & 3][x & 3] + 0.5) / 16) continue;
164
+ paths[r >= g && r >= b ? 0 : g >= b ? 1 : 2].rect(x0 + x * cell, y0 + y * cell, z, z);
165
+ }
166
+ paths.forEach((p, c) => { if (colors[c]) { ctx.fillStyle = colors[c]; ctx.fill(p); } });
167
+ }
168
+
169
+ function sphere(mx, i, x, y, r, lvl = 1) {
170
+ const g = mx.createRadialGradient(x - r * 0.35, y - r * 0.4, 0, x, y, r);
171
+ g.addColorStop(0, ch(i, 0.34 * lvl)); g.addColorStop(0.5, ch(i, 0.7 * lvl)); g.addColorStop(0.86, ch(i, lvl)); g.addColorStop(1, ch(i, 0));
172
+ mx.fillStyle = g; mx.beginPath(); mx.arc(x, y, r, 0, 6.2832); mx.fill();
173
+ }
174
+
175
+ /** The Tally mascot: an 11×11 squircle of balls with two tall eyes cut out. */
176
+ function mascot(mx, cx, cy, S, colOf = () => 1, look = [0, 0]) {
177
+ const c = S / 11;
178
+ for (let y = 0; y < 11; y++) for (let x = 0; x < 11; x++) {
179
+ const u = (x - 5) / 5.4, v = (y - 5) / 5.4;
180
+ if (u ** 4 + v ** 4 <= 1) sphere(mx, colOf(x), cx + (x - 5) * c, cy + (y - 5) * c, c * 0.47);
181
+ }
182
+ const k = S / 320;
183
+ mx.save(); mx.globalCompositeOperation = "source-over"; mx.fillStyle = "#000";
184
+ for (const ex of [116, 204]) {
185
+ const w = 40 * k, h = 98 * k;
186
+ mx.beginPath(); mx.roundRect(cx + (ex - 160) * k + look[0] * k * 16 - w / 2, cy - 4 * k + look[1] * k * 12 - h / 2, w, h, w / 2); mx.fill();
187
+ }
188
+ mx.restore();
189
+ }
190
+
191
+ // ---------- type ----------
192
+ function setFont(ctx, weight, size, fam, track = 0) {
193
+ ctx.font = `${weight} ${size}px ${fam}`;
194
+ if ("letterSpacing" in ctx) ctx.letterSpacing = track + "px";
195
+ }
196
+ const heavy = (ctx, size) => setFont(ctx, 800, size, SANS, -size * 0.045);
197
+ function put(ctx, s, x, y, color, align = "left", base = "alphabetic") {
198
+ ctx.textAlign = align; ctx.textBaseline = base; if (color) ctx.fillStyle = color; ctx.fillText(s, x, y);
199
+ }
200
+ function fitHeavy(ctx, lines, size, maxW) {
201
+ heavy(ctx, size);
202
+ const w = Math.max(...lines.map((l) => ctx.measureText(l).width));
203
+ return w > maxW ? size * maxW / w : size;
204
+ }
205
+ function wrap(ctx, s, maxW) {
206
+ const out = []; let cur = "";
207
+ for (const w of s.split(" ")) { const t = cur ? cur + " " + w : w; if (cur && ctx.measureText(t).width > maxW) { out.push(cur); cur = w; } else cur = t; }
208
+ if (cur) out.push(cur);
209
+ return out;
210
+ }
211
+ /** Serif paragraph whose last line sits on `bottom`. Returns the top of its first line. */
212
+ function serif(ctx, s, x, bottom, size, maxW, color) {
213
+ setFont(ctx, 400, size, SERIF, -size * 0.01);
214
+ const lines = wrap(ctx, s, maxW), lh = size * 1.2;
215
+ lines.forEach((l, i) => put(ctx, l, x, bottom - (lines.length - 1 - i) * lh, color));
216
+ return bottom - (lines.length - 1) * lh - size * 0.75;
217
+ }
218
+ function mono(ctx, s, x, y, size, color, align = "left", alpha = 1) {
219
+ setFont(ctx, 400, size, MONO, size * 0.08);
220
+ ctx.globalAlpha = alpha; put(ctx, s.toUpperCase(), x, y, color, align); ctx.globalAlpha = 1;
221
+ }
222
+ /** Lines of the display face; `top` is the top of the first line's capitals. */
223
+ function display(ctx, lines, size, x, top, color, maxW = 920) {
224
+ const sz = fitHeavy(ctx, lines, size, maxW);
225
+ heavy(ctx, sz);
226
+ lines.forEach((l, i) => put(ctx, l, x, top + sz * 0.73 + i * sz * 0.98, color));
227
+ return sz;
228
+ }
229
+ function boxed(ctx, s, x, baseline, size, bg, fg) {
230
+ heavy(ctx, size);
231
+ const pad = size * 0.12, w = ctx.measureText(s).width;
232
+ ctx.fillStyle = bg; ctx.fillRect(x, baseline - size * 0.86, w + pad * 2, size * 1.1);
233
+ put(ctx, s, x + pad, baseline, fg);
234
+ return w + pad * 2;
235
+ }
236
+ function sticker(ctx, s, x, y, bg, deg) {
237
+ heavy(ctx, 76);
238
+ const W = ctx.measureText(s).width + 60, H = 114;
239
+ ctx.save(); ctx.translate(x + W / 2, y + H / 2); ctx.rotate(deg * Math.PI / 180);
240
+ ctx.fillStyle = bg; ctx.fillRect(-W / 2, -H / 2, W, H);
241
+ put(ctx, s, -W / 2 + 30, -H / 2 + 16 + 60, C.ink);
242
+ ctx.restore();
243
+ }
244
+ function icon(ctx, x, y, s) {
245
+ ctx.save();
246
+ const g = ctx.createLinearGradient(0, y, 0, y + s); g.addColorStop(0, "#26262a"); g.addColorStop(1, "#141416");
247
+ ctx.fillStyle = g; ctx.beginPath(); ctx.roundRect(x, y, s, s, s * 0.225); ctx.fill();
248
+ const cols = [["#e2774f", 0.78], ["#e8e8ea", 0.52], ["#42c08d", 0.3]], cw = s * 0.17, gap = s * 0.085;
249
+ const x0 = x + (s - 3 * cw - 2 * gap) / 2, h = s * 0.66, yb = y + s * 0.83, p = Math.max(1.6, s * 0.05);
250
+ cols.forEach(([c, f], i) => {
251
+ for (let yy = 0; yy + p <= h; yy += p) for (let xx = 0; xx + p * 0.7 <= cw; xx += p) {
252
+ ctx.fillStyle = yy < h * f ? c : "rgba(255,255,255,.13)";
253
+ ctx.fillRect(x0 + i * (cw + gap) + xx, yb - yy - p, p * 0.72, p * 0.72);
254
+ }
255
+ });
256
+ ctx.restore();
257
+ }
258
+ function brand(ctx, x, y, size, color) {
259
+ icon(ctx, x, y, size);
260
+ setFont(ctx, 600, size * 0.6, SANS, -size * 0.012);
261
+ put(ctx, "Tally", x + size * 1.32, y + size / 2, color, "left", "middle");
262
+ }
263
+ /** The install line, as a dark pill whose bottom-right corner is (xr, yb). */
264
+ function pill(ctx, s, xr, yb, size, bg, fg) {
265
+ setFont(ctx, 500, size, MONO, 0);
266
+ const w = ctx.measureText(s).width, ph = size * 0.6, pv = size * 0.5;
267
+ ctx.fillStyle = bg; ctx.beginPath(); ctx.roundRect(xr - w - ph * 2, yb - size - pv * 2, w + ph * 2, size + pv * 2, size * 0.3); ctx.fill();
268
+ put(ctx, s, xr - ph, yb - pv - size * 0.5, fg, "right", "middle");
269
+ }
270
+ function rankList(ctx, title, items, x, y, size, maxW, color) {
271
+ mono(ctx, title, x, y + size * 0.6, size * 0.6, color, "left", 0.7);
272
+ items.forEach((s, i) => {
273
+ const base = y + size * 0.6 + size * 0.5 + size * 0.8 + i * size * 1.38;
274
+ setFont(ctx, 700, size, SANS, -size * 0.025);
275
+ ctx.globalAlpha = 0.55; put(ctx, String(i + 1), x, base, color); ctx.globalAlpha = 1;
276
+ let sz = size; const w = ctx.measureText(s).width, room = maxW - size * 1.15;
277
+ if (w > room) { sz = size * room / w; setFont(ctx, 700, sz, SANS, -sz * 0.025); }
278
+ put(ctx, s, x + size * 1.15, base, color);
279
+ });
280
+ }
281
+ function stat(ctx, k, v, x, y, size, maxW, color) {
282
+ mono(ctx, k, x, y + size * 0.27, size * 0.27, color, "left", 0.7);
283
+ const sz = fitHeavy(ctx, [v], size, maxW); heavy(ctx, sz);
284
+ put(ctx, v, x, y + size * 0.27 + size * 0.18 + size * 0.8, color);
285
+ }
286
+ function art(ctx, x, y, w, h, cell) {
287
+ ctx.fillStyle = C.ink; ctx.fillRect(x, y, w, h);
288
+ dots(ctx, x, y, w, h, cell, [C.orange, C.paper, C.green], (m) => mascot(m, w / 2, h * 0.52, Math.min(w, h) * 0.8, (cx) => cx <= 3 ? 0 : cx <= 6 ? 1 : 2, [0.3, 0.1]));
289
+ }
290
+
291
+ // ---------- slides (1080 × 1920; the post card is 1200 × 630 drawn at 2×) ----------
292
+ const W = 1080, H = 1920;
293
+ const bg = (ctx, c, w = W, h = H) => { ctx.fillStyle = c; ctx.fillRect(0, 0, w, h); };
294
+
295
+ function intro(ctx, st) {
296
+ bg(ctx, C.orange);
297
+ dots(ctx, 0, 0, W, H, 6, [null, C.ink, null], (m) => mascot(m, 540, 760, 820, () => 1, [0, 0.5]));
298
+ brand(ctx, 80, 80, 56, C.ink);
299
+ mono(ctx, st.range, 1000, 117, 26, C.ink, "right");
300
+ const top = serif(ctx, "Let’s see where it all went.", 80, 1800, 52, 920, C.ink);
301
+ const lines = [`Your ${st.unit} in`, "AI coding."], sz = fitHeavy(ctx, lines, 176, 940);
302
+ display(ctx, lines, sz, 80, top - 96 - sz * 0.73 - sz * 0.98, C.ink, 940);
303
+ }
304
+
305
+ function total(ctx, st) {
306
+ bg(ctx, C.ink);
307
+ const r = st.P, n = Math.max(1, r.bars.length), gap = n > 10 ? 6 : 26, bw = (920 - gap * (n - 1)) / n, mx = Math.max(...r.bars, 1e-12);
308
+ dots(ctx, 0, 0, W, H, 5, [C.orange, C.dim, null], (m) => {
309
+ setFont(m, 800, 360, SANS, -360 * 0.03);
310
+ let size = 360; const w = m.measureText(st.money).width;
311
+ if (w > 950) { size = 360 * 950 / w; setFont(m, 800, size, SANS, -size * 0.03); }
312
+ const g = m.createLinearGradient(0, 690 - size * 0.72, 0, 690); g.addColorStop(0, ch(0, 0.55)); g.addColorStop(1, ch(0, 1));
313
+ m.fillStyle = g; m.textBaseline = "alphabetic"; m.textAlign = "left"; m.fillText(st.money, 64, 690);
314
+ r.bars.forEach((v, i) => {
315
+ const h = v > 0 ? 24 + 300 * Math.sqrt(v / mx) : 6, x = 80 + i * (bw + gap);
316
+ const gb = m.createLinearGradient(0, 1770 - h, 0, 1770); gb.addColorStop(0, ch(0, 0.5)); gb.addColorStop(1, ch(0, 1));
317
+ m.fillStyle = gb; m.fillRect(x, 1770 - h, bw, h);
318
+ });
319
+ });
320
+ mono(ctx, "Your agents ran up", 80, 222, 26, C.grey);
321
+ display(ctx, ["of AI coding at", "API prices."], 104, 80, 770, C.paper);
322
+ if (st.multiple) {
323
+ sticker(ctx, `You paid ${money(st.planCost)}.`, 70, 1070, C.green, -4);
324
+ sticker(ctx, `That’s ${times(st.multiple)} your money.`, 170, 1200, C.paper, 3);
325
+ } else {
326
+ sticker(ctx, `${tok(st.tokens)} tokens.`, 70, 1070, C.green, -4);
327
+ sticker(ctx, `${r.sessions} sessions.`, 170, 1200, C.paper, 3);
328
+ }
329
+ r.barLabels.forEach((l, i) => { if (l) mono(ctx, l, 80 + i * (bw + gap) + bw / 2, 1812, 22, C.grey, "center"); });
330
+ }
331
+
332
+ function plans(ctx, st) {
333
+ bg(ctx, C.green);
334
+ display(ctx, ["Your top plans"], 150, 80, 225, C.ink);
335
+ st.rows.slice(0, 4).forEach((r, i) => {
336
+ const y = 560 + i * 246;
337
+ heavy(ctx, 96); put(ctx, String(i + 1), 80, y + 130, C.ink);
338
+ ctx.fillStyle = C.ink; ctx.fillRect(206, y, 190, 190);
339
+ const n = [5, 4, 3, 2][i], p = 190 / n;
340
+ dots(ctx, 206, y, 190, 190, 4, [TILE[r.s], null, null], (m) => { for (let a = 0; a < n; a++) for (let b = 0; b < n; b++) sphere(m, 0, p * (b + 0.5), p * (a + 0.5), p * 0.47); });
341
+ const nsz = fitHeavy(ctx, [r.name], 62, 568); heavy(ctx, nsz); put(ctx, r.name, 432, y + 95, C.ink);
342
+ setFont(ctx, 400, 28, MONO, 0);
343
+ let msz = 28; const mw = ctx.measureText(r.meta).width; if (mw > 568) { msz = 28 * 568 / mw; setFont(ctx, 400, msz, MONO, 0); }
344
+ ctx.globalAlpha = 0.75; put(ctx, r.meta, 432, y + 140, C.ink); ctx.globalAlpha = 1;
345
+ });
346
+ let note = "Nothing to see yet.";
347
+ const top = st.rows[0];
348
+ if (top && st.api > 0) {
349
+ note = `${NAMES[top.s]} did ${Math.round(top.cost / st.api * 100)}% of the work.`;
350
+ if (st.P.models[0]) note += ` Your top model was ${st.P.models[0].name}.`;
351
+ }
352
+ serif(ctx, note, 80, 1810, 62, 920, C.ink);
353
+ }
354
+
355
+ function tokens(ctx, st) {
356
+ bg(ctx, C.paper);
357
+ const copies = st.tokens / 780000, per = Math.max(1, Math.ceil(copies / 1600)), n = Math.max(1, Math.round(copies / per));
358
+ const cols = n > 200 ? 44 : Math.max(6, Math.ceil(Math.sqrt(n * 1.3))), p = Math.min(120, 920 / cols);
359
+ dots(ctx, 0, 0, W, H, 3, [C.orange, C.ink, null], (m) => {
360
+ for (let i = 0; i < n; i++) sphere(m, i === 0 ? 0 : 1, 80 + (i % cols) * p + p / 2, 680 + Math.floor(i / cols) * p + p / 2, p * 0.42, 0.95);
361
+ });
362
+ const words = tokenWords(st.tokens), sz = fitHeavy(ctx, [words + " "], 150, 900);
363
+ boxed(ctx, words, 80, 180 + sz * 0.86, sz, C.orange, C.ink);
364
+ heavy(ctx, sz); put(ctx, "tokens.", 80, 180 + sz * 0.86 + sz * 0.98, C.ink);
365
+ mono(ctx, per === 1 ? "= one War and Peace" : `= ${per} copies of War and Peace`, 1000, 646, 22, C.muted, "right");
366
+ setFont(ctx, 400, 22, MONO, 22 * 0.08);
367
+ const kw = ctx.measureText((per === 1 ? "= one War and Peace" : `= ${per} copies of War and Peace`).toUpperCase()).width;
368
+ ctx.fillStyle = C.orange; ctx.fillRect(1000 - kw - 28, 630, 16, 16);
369
+ const round = copies >= 1000 ? Math.round(copies / 100) * 100 : copies >= 100 ? Math.round(copies / 10) * 10 : Math.round(copies);
370
+ const amount = copies < 1.5 ? "about one copy" : `about ${round.toLocaleString("en-US")} copies`;
371
+ serif(ctx, `That’s ${amount} of War and Peace, read and written in ${st.span}.`, 80, 1790, 56, 920, C.ink);
372
+ }
373
+
374
+ function hours(ctx, st) {
375
+ bg(ctx, C.ink);
376
+ const hrs = st.P.hours, mx = Math.max(...hrs, 1e-12), cx = 540, cy = 780;
377
+ dots(ctx, 0, 0, W, H, 5, [C.orange, C.dim, null], (m) => {
378
+ for (let h = 0; h < 24; h++) {
379
+ const v = hrs[h], a = h / 24 * 2 * Math.PI - Math.PI / 2, len = v > 0 ? 50 + 270 * Math.sqrt(v / mx) : 14;
380
+ for (let s = 0; s < len; s += 26) { const rr = 100 + s + 13; sphere(m, v > 0 ? 0 : 1, cx + Math.cos(a) * rr, cy + Math.sin(a) * rr, 11.5, v > 0 ? 0.55 + 0.45 * s / len : 0.8); }
381
+ }
382
+ mascot(m, cx, cy, 170, () => 1, [0.6, -0.3]);
383
+ });
384
+ mono(ctx, "Your coding hours", 80, 172, 26, C.grey);
385
+ for (const [t, h] of [["Midnight", 0], ["6 am", 6], ["Noon", 12], ["6 pm", 18]]) {
386
+ const a = h / 24 * 2 * Math.PI - Math.PI / 2, r = h % 12 === 0 ? 450 : 420;
387
+ setFont(ctx, 400, 22, MONO, 22 * 0.08); put(ctx, t.toUpperCase(), cx + Math.cos(a) * r, cy + Math.sin(a) * r, C.grey, "center", "middle");
388
+ }
389
+ const p = st.persona, words = p.name.split(" ");
390
+ const top = serif(ctx, p.line, 80, 1810, 52, 910, C.soft);
391
+ const l1 = words.length > 1 ? ["The", words[0]] : ["The"], l2 = words.length > 1 ? words.slice(1).join(" ") : p.name;
392
+ heavy(ctx, 168);
393
+ const wl1 = ctx.measureText(l1.join(" ")).width + 30 + 168 * 0.24, wl2 = ctx.measureText(l2).width + 168 * 0.24;
394
+ const sz = Math.min(168, 168 * 920 / Math.max(wl1, wl2));
395
+ const b2 = top - 52, b1 = b2 - sz * 0.98;
396
+ heavy(ctx, sz); put(ctx, "The", 80, b1, C.paper);
397
+ if (l1.length > 1) boxed(ctx, l1[1], 80 + ctx.measureText("The").width + 30, b1, sz, C.orange, C.ink);
398
+ boxed(ctx, l2, 80, b2, sz, C.orange, C.ink);
399
+ }
400
+
401
+ function summary(ctx, st) {
402
+ bg(ctx, C.orange);
403
+ art(ctx, 80, 180, 920, 740, 5);
404
+ rankList(ctx, "Top plans", st.rows.slice(0, 4).map((r) => r.name), 80, 990, 40, 440, C.ink);
405
+ rankList(ctx, "Top models", st.P.models.map((m) => m.name), 560, 990, 40, 440, C.ink);
406
+ stat(ctx, "At API prices", st.money, 80, 1360, 88, 440, C.ink);
407
+ stat(ctx, "Value", st.multiple ? times(st.multiple) : "—", 560, 1360, 88, 440, C.ink);
408
+ stat(ctx, "Tokens", tok(st.tokens), 80, 1528, 88, 440, C.ink);
409
+ stat(ctx, "Shift", st.persona.name.split(" ")[0], 560, 1528, 88, 440, C.ink);
410
+ brand(ctx, 80, H - 80 - 56, 56, C.ink);
411
+ pill(ctx, "npx tally-menubar wrapped", 1000, H - 80, 26, C.ink, C.paper);
412
+ mono(ctx, st.range, 1000, H - 80 - 26 - 26 - 22, 22, C.ink, "right", 0.75);
413
+ }
414
+
415
+ function post(ctx, st) {
416
+ ctx.save(); ctx.scale(2, 2);
417
+ bg(ctx, C.orange, 1200, 630);
418
+ art(ctx, 40, 40, 550, 550, 4);
419
+ stat(ctx, "At API prices", st.money, 640, 52, 70, 242, C.ink);
420
+ stat(ctx, "Value", st.multiple ? times(st.multiple) : tok(st.tokens), 906, 52, 70, 242, C.ink);
421
+ rankList(ctx, "Top plans", st.rows.slice(0, 4).map((r) => r.name), 640, 196, 22, 242, C.ink);
422
+ rankList(ctx, "Top models", st.P.models.map((m) => m.name), 906, 196, 22, 242, C.ink);
423
+ brand(ctx, 640, 630 - 44 - 34, 34, C.ink);
424
+ pill(ctx, "npx tally-menubar wrapped", 1148, 630 - 44, 15, C.ink, C.paper);
425
+ mono(ctx, `${st.range} · The ${st.persona.name}`, 1148, 630 - 44 - 15 - 15 - 14, 13, C.ink, "right", 0.75);
426
+ ctx.restore();
427
+ }
428
+
429
+ const SLIDES = [["intro", intro], ["total", total], ["plans", plans], ["tokens", tokens], ["hours", hours], ["summary", summary], ["post", post]];
430
+
431
+ // ---------- page ----------
432
+ const strip = document.getElementById("strip"), toast = document.getElementById("toast");
433
+ let canvases = [];
434
+ function say(s) { toast.textContent = s; toast.classList.add("on"); clearTimeout(say.t); say.t = setTimeout(() => toast.classList.remove("on"), 2200); }
435
+ const blob = (cv) => new Promise((res) => cv.toBlob(res, "image/png"));
436
+ const fileName = (i) => `tally-${state.period}-${i === SLIDES.length - 1 ? "post" : (i + 1) + "-" + SLIDES[i][0]}.png`;
437
+
438
+ async function download(i) {
439
+ const a = document.createElement("a");
440
+ a.href = URL.createObjectURL(await blob(canvases[i])); a.download = fileName(i); a.click();
441
+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);
442
+ }
443
+ async function copy(i) {
444
+ try { await navigator.clipboard.write([new ClipboardItem({ "image/png": blob(canvases[i]) })]); say("Copied"); return true; }
445
+ catch { await download(i); say("This browser blocks copying here, so it was downloaded instead"); return false; }
446
+ }
447
+
448
+ function render() {
449
+ const st = stats();
450
+ strip.innerHTML = ""; canvases = [];
451
+ SLIDES.forEach(([name, draw], i) => {
452
+ const isPost = name === "post", cv = document.createElement("canvas");
453
+ cv.width = isPost ? 2400 : W; cv.height = isPost ? 1260 : H;
454
+ draw(cv.getContext("2d"), st);
455
+ const fig = document.createElement("figure"); if (isPost) fig.className = "post";
456
+ const cap = document.createElement("figcaption");
457
+ cap.innerHTML = `<span>${isPost ? "Card for X · 1200×630" : `Story ${i + 1} of 6`}</span>`;
458
+ const b1 = Object.assign(document.createElement("button"), { className: "btn", textContent: "Copy" }); b1.onclick = () => copy(i);
459
+ const b2 = Object.assign(document.createElement("button"), { className: "btn", textContent: "Download" }); b2.onclick = () => download(i);
460
+ cap.append(b1, b2); fig.append(cv, cap); strip.append(fig); canvases.push(cv);
461
+ });
462
+ render.st = st;
463
+ }
464
+
465
+ function controls() {
466
+ const per = document.getElementById("periods");
467
+ for (const [k, label] of [["24h", "24 hours"], ["7d", "7 days"], ["30d", "30 days"]]) {
468
+ const b = Object.assign(document.createElement("button"), { textContent: label });
469
+ b.setAttribute("aria-pressed", String(state.period === k));
470
+ b.onclick = () => { state.period = k; per.querySelectorAll("button").forEach((x) => x.setAttribute("aria-pressed", String(x === b))); render(); };
471
+ per.append(b);
472
+ }
473
+ const used = new Set(Object.values(DATA.periods).flatMap((p) => Object.keys(p.services)));
474
+ const box = document.getElementById("plans");
475
+ for (const s of ["claude", "codex", "opencodeGo"]) {
476
+ if (!used.has(s)) continue;
477
+ const lab = document.createElement("label"); lab.textContent = (s === "codex" ? "ChatGPT" : NAMES[s]) + " plan";
478
+ const sel = document.createElement("select");
479
+ for (const [id, label, price] of PLANS[s]) sel.append(new Option(price ? `${label} · $${price}` : label, id));
480
+ sel.value = state.plans[s];
481
+ sel.onchange = () => { state.plans[s] = sel.value; try { localStorage.setItem("tally-wrapped-plans", JSON.stringify(state.plans)); } catch {} render(); };
482
+ lab.append(sel); box.append(lab);
483
+ }
484
+ document.getElementById("all").onclick = async () => {
485
+ for (let i = 0; i < canvases.length; i++) { await download(i); await new Promise((r) => setTimeout(r, 350)); }
486
+ say(`Downloaded ${canvases.length} images`);
487
+ };
488
+ document.getElementById("x").onclick = async () => {
489
+ const copied = await copy(SLIDES.length - 1);
490
+ window.open("https://x.com/intent/post?text=" + encodeURIComponent(postText(render.st)), "_blank");
491
+ if (copied) say("Card copied: paste it into the post");
492
+ };
493
+ icon(document.getElementById("logo").getContext("2d"), 0, 0, 56);
494
+ }
495
+
496
+ document.fonts.load('400 52px "Newsreader"').then(() => { controls(); render(); });
497
+ </script>
498
+ </body>
499
+ </html>