ai-wrapped 1.8.2 → 1.10.1

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/src/bun/index.ts CHANGED
@@ -9,19 +9,13 @@ import Electrobun, {
9
9
  PATHS,
10
10
  Tray,
11
11
  Utils,
12
+ type ApplicationMenuItemConfig,
12
13
  } from "electrobun/bun";
13
- import {
14
- EMPTY_TOKEN_USAGE,
15
- SESSION_SOURCES,
16
- type DailyAggregate,
17
- type DashboardSummary,
18
- type HourlyBreakdownEntry,
19
- type SessionSource,
20
- type TokenUsage,
21
- type TrayStats,
22
- } from "../shared/schema";
14
+ import type { TrayStats } from "../shared/schema";
23
15
  import type { AppSettings, AIStatsRPC } from "../shared/types";
24
16
  import { runScan } from "./scan";
17
+ import { getDailyTimelineFromStore, getDashboardSummaryFromStore } from "./queries";
18
+ import { createShareLink, saveShareImage } from "./share";
25
19
  import { resolveAggregationTimeZone } from "./aggregator";
26
20
  import {
27
21
  createEmptyDayStats,
@@ -30,9 +24,7 @@ import {
30
24
  getSettings,
31
25
  readDailyStore,
32
26
  setSettings,
33
- type DayStats,
34
27
  } from "./store";
35
- import { buildTopRepos } from "./dashboardSummary";
36
28
  import { getOpenExternalCommand, tryResolveAllowedExternalUrl } from "./external";
37
29
 
38
30
  const isMac = process.platform === "darwin";
@@ -54,223 +46,6 @@ Electrobun.events.on("before-quit", () => {
54
46
  isQuitting = true;
55
47
  });
56
48
 
57
- const addDayStats = (target: DayStats, source: DayStats): void => {
58
- target.sessions += source.sessions;
59
- target.messages += source.messages;
60
- target.toolCalls += source.toolCalls;
61
- target.inputTokens += source.inputTokens;
62
- target.outputTokens += source.outputTokens;
63
- target.cacheReadTokens += source.cacheReadTokens;
64
- target.cacheWriteTokens += source.cacheWriteTokens;
65
- target.reasoningTokens += source.reasoningTokens;
66
- target.costUsd += source.costUsd;
67
- target.durationMs += source.durationMs;
68
- };
69
-
70
- const toTokenUsage = (stats: DayStats): TokenUsage => ({
71
- inputTokens: stats.inputTokens,
72
- outputTokens: stats.outputTokens,
73
- cacheReadTokens: stats.cacheReadTokens,
74
- cacheWriteTokens: stats.cacheWriteTokens,
75
- reasoningTokens: stats.reasoningTokens,
76
- });
77
-
78
- const createEmptyByAgent = (): DashboardSummary["byAgent"] => ({
79
- claude: { sessions: 0, events: 0, tokens: { ...EMPTY_TOKEN_USAGE }, costUsd: 0 },
80
- codex: { sessions: 0, events: 0, tokens: { ...EMPTY_TOKEN_USAGE }, costUsd: 0 },
81
- gemini: { sessions: 0, events: 0, tokens: { ...EMPTY_TOKEN_USAGE }, costUsd: 0 },
82
- opencode: { sessions: 0, events: 0, tokens: { ...EMPTY_TOKEN_USAGE }, costUsd: 0 },
83
- droid: { sessions: 0, events: 0, tokens: { ...EMPTY_TOKEN_USAGE }, costUsd: 0 },
84
- copilot: { sessions: 0, events: 0, tokens: { ...EMPTY_TOKEN_USAGE }, costUsd: 0 },
85
- });
86
-
87
- const isInDateRange = (date: string, dateFrom?: string, dateTo?: string): boolean => {
88
- if (dateFrom && date < dateFrom) return false;
89
- if (dateTo && date > dateTo) return false;
90
- return true;
91
- };
92
-
93
- const getDailyTimelineFromStore = async (
94
- dateFrom: string,
95
- dateTo: string,
96
- source?: SessionSource,
97
- model?: string,
98
- ): Promise<DailyAggregate[]> => {
99
- const daily = await readDailyStore();
100
- const dates = Object.keys(daily).sort((a, b) => a.localeCompare(b));
101
-
102
- const rows = dates
103
- .filter((date) => isInDateRange(date, dateFrom, dateTo))
104
- .map((date) => {
105
- const entry = daily[date];
106
- if (!entry) return null;
107
-
108
- const stats =
109
- source
110
- ? entry.bySource[source]
111
- : model
112
- ? entry.byModel[model]
113
- : entry.totals;
114
- if (!stats) return null;
115
-
116
- return {
117
- date,
118
- source: source ?? "all",
119
- model: model ?? "all",
120
- sessionCount: stats.sessions,
121
- messageCount: stats.messages,
122
- toolCallCount: stats.toolCalls,
123
- tokens: toTokenUsage(stats),
124
- costUsd: stats.costUsd,
125
- totalDurationMs: stats.durationMs,
126
- } satisfies DailyAggregate;
127
- })
128
- .filter((row): row is DailyAggregate => row !== null);
129
-
130
- return rows;
131
- };
132
-
133
- const getDashboardSummaryFromStore = async (
134
- dateFrom?: string,
135
- dateTo?: string,
136
- ): Promise<DashboardSummary> => {
137
- const daily = await readDailyStore();
138
- const byAgent = createEmptyByAgent();
139
- const byModelMap = new Map<string, DayStats>();
140
- const byRepoMap = new Map<string, DayStats>();
141
- const byHourMap = new Map<number, DayStats>();
142
- const byHourSourceMap = new Map<number, Map<string, DayStats>>();
143
- const totals = createEmptyDayStats();
144
-
145
- for (const date of Object.keys(daily)) {
146
- if (!isInDateRange(date, dateFrom, dateTo)) continue;
147
-
148
- const entry = daily[date];
149
- if (!entry) continue;
150
-
151
- addDayStats(totals, entry.totals);
152
-
153
- for (const source of SESSION_SOURCES) {
154
- const stats = entry.bySource[source];
155
- if (!stats) continue;
156
-
157
- const target = byAgent[source];
158
- target.sessions += stats.sessions;
159
- target.events += stats.messages + stats.toolCalls;
160
- target.tokens.inputTokens += stats.inputTokens;
161
- target.tokens.outputTokens += stats.outputTokens;
162
- target.tokens.cacheReadTokens += stats.cacheReadTokens;
163
- target.tokens.cacheWriteTokens += stats.cacheWriteTokens;
164
- target.tokens.reasoningTokens += stats.reasoningTokens;
165
- target.costUsd += stats.costUsd;
166
- }
167
-
168
- for (const [model, modelStats] of Object.entries(entry.byModel)) {
169
- if (!byModelMap.has(model)) {
170
- byModelMap.set(model, createEmptyDayStats());
171
- }
172
-
173
- addDayStats(byModelMap.get(model) as DayStats, modelStats);
174
- }
175
-
176
- for (const [repo, repoStats] of Object.entries(entry.byRepo)) {
177
- if (!byRepoMap.has(repo)) {
178
- byRepoMap.set(repo, createEmptyDayStats());
179
- }
180
-
181
- addDayStats(byRepoMap.get(repo) as DayStats, repoStats);
182
- }
183
-
184
- for (const [hour, hourStats] of Object.entries(entry.byHour)) {
185
- const hourNum = Number(hour);
186
- if (!byHourMap.has(hourNum)) {
187
- byHourMap.set(hourNum, createEmptyDayStats());
188
- }
189
-
190
- addDayStats(byHourMap.get(hourNum) as DayStats, hourStats);
191
- }
192
-
193
- for (const [hour, sources] of Object.entries(entry.byHourSource)) {
194
- const hourNum = Number(hour);
195
- if (!byHourSourceMap.has(hourNum)) {
196
- byHourSourceMap.set(hourNum, new Map());
197
- }
198
- const sourceMap = byHourSourceMap.get(hourNum) as Map<string, DayStats>;
199
- for (const [source, sourceStats] of Object.entries(sources)) {
200
- if (!sourceMap.has(source)) {
201
- sourceMap.set(source, createEmptyDayStats());
202
- }
203
- addDayStats(sourceMap.get(source) as DayStats, sourceStats);
204
- }
205
- }
206
- }
207
-
208
- const byModel = [...byModelMap.entries()]
209
- .map(([model, stats]) => ({
210
- model,
211
- sessions: stats.sessions,
212
- tokens: toTokenUsage(stats),
213
- costUsd: stats.costUsd,
214
- }))
215
- .sort((left, right) => {
216
- if (right.sessions !== left.sessions) return right.sessions - left.sessions;
217
- return right.costUsd - left.costUsd;
218
- })
219
- .slice(0, 100);
220
-
221
- const dailyTimeline =
222
- dateFrom && dateTo ? await getDailyTimelineFromStore(dateFrom, dateTo) : [];
223
- const topRepos = buildTopRepos(byRepoMap);
224
-
225
- const hourlyBreakdown: HourlyBreakdownEntry[] = Array.from({ length: 24 }, (_, hour) => {
226
- const stats = byHourMap.get(hour) ?? createEmptyDayStats();
227
- const sourceMap = byHourSourceMap.get(hour);
228
- const byAgent = sourceMap
229
- ? SESSION_SOURCES
230
- .filter((source) => sourceMap.has(source))
231
- .map((source) => {
232
- const s = sourceMap.get(source) as DayStats;
233
- return {
234
- source,
235
- sessions: s.sessions,
236
- tokens: toTokenUsage(s),
237
- costUsd: s.costUsd,
238
- };
239
- })
240
- .sort((a, b) => {
241
- const aTot = a.tokens.inputTokens + a.tokens.outputTokens;
242
- const bTot = b.tokens.inputTokens + b.tokens.outputTokens;
243
- return bTot - aTot;
244
- })
245
- : [];
246
- return {
247
- hour,
248
- sessions: stats.sessions,
249
- tokens: toTokenUsage(stats),
250
- costUsd: stats.costUsd,
251
- durationMs: stats.durationMs,
252
- byAgent,
253
- };
254
- });
255
-
256
- return {
257
- totals: {
258
- sessions: totals.sessions,
259
- events: totals.messages + totals.toolCalls,
260
- messages: totals.messages,
261
- toolCalls: totals.toolCalls,
262
- tokens: toTokenUsage(totals),
263
- costUsd: totals.costUsd,
264
- durationMs: totals.durationMs,
265
- },
266
- byAgent,
267
- byModel,
268
- dailyTimeline,
269
- topRepos,
270
- topTools: [],
271
- hourlyBreakdown,
272
- };
273
- };
274
49
 
275
50
  const dailyStoreNeedsRepoBackfill = async (): Promise<boolean> => {
276
51
  const daily = await readDailyStore();
@@ -541,7 +316,8 @@ const exportFullSharePdf = async (
541
316
  }
542
317
 
543
318
  const parsed = new URL(resolvedUrl);
544
- const isSharePath = parsed.pathname === "/share" || parsed.pathname === "/share/";
319
+ const isSharePath =
320
+ parsed.pathname === "/share" || parsed.pathname === "/share/" || /^\/s\/[A-Za-z0-9_-]+$/.test(parsed.pathname);
545
321
  if (!isSharePath) {
546
322
  throw new Error("PDF export only supports ai-wrapped.com/share URLs.");
547
323
  }
@@ -891,9 +667,7 @@ const refreshApplicationMenu = async () => {
891
667
  return;
892
668
  }
893
669
 
894
- const settings = await getSettings();
895
-
896
- ApplicationMenu.setApplicationMenu([
670
+ const menu: ApplicationMenuItemConfig[] = [
897
671
  ...(isMac
898
672
  ? [
899
673
  {
@@ -910,7 +684,7 @@ const refreshApplicationMenu = async () => {
910
684
  data: { source: "application-menu" },
911
685
  enabled: !isScanning,
912
686
  },
913
- { type: "separator" },
687
+ { type: "separator" as const },
914
688
  {
915
689
  role: "quit",
916
690
  },
@@ -927,36 +701,15 @@ const refreshApplicationMenu = async () => {
927
701
  data: { source: "application-menu" },
928
702
  enabled: !isScanning,
929
703
  },
930
- { type: "separator" },
704
+ { type: "separator" as const },
931
705
  {
932
706
  role: "quit",
933
707
  },
934
708
  ],
935
709
  },
936
- {
937
- label: "View",
938
- submenu: [
939
- {
940
- label: "Toggle Dark Mode",
941
- type: "checkbox",
942
- action: "toggle-dark-mode",
943
- data: { source: "application-menu" },
944
- checked: settings.theme === "dark",
945
- },
946
- ],
947
- },
948
- ]);
949
- };
950
-
951
- const toggleDarkMode = async () => {
952
- const current = await getSettings();
953
- const nextTheme: AppSettings["theme"] = current.theme === "dark" ? "light" : "dark";
954
- const next = await updateSettings({ theme: nextTheme });
710
+ ];
955
711
 
956
- dispatchToWebview(() => {
957
- rpc.send.themeChanged({ theme: next.theme });
958
- });
959
- void refreshApplicationMenu();
712
+ ApplicationMenu.setApplicationMenu(menu);
960
713
  };
961
714
 
962
715
  const createTray = () => {
@@ -1033,6 +786,12 @@ const rpc = BrowserView.defineRPC<AIStatsRPC>({
1033
786
  }),
1034
787
  getTrayStats: () => getTrayStatsFromStore(),
1035
788
  getSettings: () => getSettings(),
789
+ createShareLink: ({ payload, imageJpegBase64 }) => createShareLink(payload, imageJpegBase64),
790
+ saveShareImage: ({ pngBase64 }) => saveShareImage(pngBase64),
791
+ copyText: ({ text }) => {
792
+ Utils.clipboardWriteText(String(text).slice(0, 100_000));
793
+ return true;
794
+ },
1036
795
  exportFullSharePdf: async ({ url }) => {
1037
796
  const resolved = tryResolveAllowedExternalUrl(url);
1038
797
  if (!resolved) {
@@ -1097,9 +856,6 @@ ApplicationMenu.on("application-menu-clicked", (event: unknown) => {
1097
856
  case "quit-app":
1098
857
  quitApp();
1099
858
  break;
1100
- case "toggle-dark-mode":
1101
- void toggleDarkMode();
1102
- break;
1103
859
  default:
1104
860
  break;
1105
861
  }
@@ -0,0 +1,147 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { describe, expect, test } from "bun:test";
3
+ import { mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import type { SessionSource } from "../../shared/schema";
7
+ import { normalizeSession } from "../normalizer";
8
+ import { parseFile } from "./index";
9
+
10
+ const fixture = (name: string): string => mkdtempSync(join(tmpdir(), `ai-stats-${name}-`));
11
+
12
+ const parse = async (path: string, source: SessionSource) => {
13
+ const fileStat = statSync(path);
14
+ return parseFile({ path, source, mtime: fileStat.mtimeMs, size: fileStat.size });
15
+ };
16
+
17
+ const firstSession = async (path: string, source: SessionSource) => {
18
+ const sessions = await parse(path, source);
19
+ expect(sessions).toHaveLength(1);
20
+ const parsed = sessions[0];
21
+ expect(parsed).toBeDefined();
22
+ if (!parsed) throw new Error("Expected parsed session");
23
+ return normalizeSession(parsed).session;
24
+ };
25
+
26
+ describe("additional harness parsers", () => {
27
+ test("parses Amp thread usage", async () => {
28
+ const dir = fixture("amp");
29
+ try {
30
+ const path = join(dir, "T-thread.json");
31
+ writeFileSync(path, JSON.stringify({
32
+ id: "amp-thread",
33
+ usageLedger: { events: [{ id: "evt", timestamp: "2026-07-01T12:00:00Z", model: "gpt-5.6", tokens: { input: 10, output: 5 } }] },
34
+ }));
35
+ const session = await firstSession(path, "amp");
36
+ expect(session.modelUsage[0]?.model).toBe("gpt-5.6");
37
+ expect(session.totalTokens).toMatchObject({ inputTokens: 10, outputTokens: 5 });
38
+ } finally { rmSync(dir, { recursive: true, force: true }); }
39
+ });
40
+
41
+ test("parses Codebuff assistant usage", async () => {
42
+ const dir = fixture("codebuff");
43
+ try {
44
+ const path = join(dir, "chat-messages.json");
45
+ writeFileSync(path, JSON.stringify([{
46
+ id: "message", role: "assistant", timestamp: "2026-07-01T12:00:00Z",
47
+ metadata: { model: "claude-fable-5", usage: { inputTokens: 10, outputTokens: 5, cacheReadInputTokens: 3 } },
48
+ }]));
49
+ const session = await firstSession(path, "codebuff");
50
+ expect(session.modelUsage[0]?.model).toBe("claude-fable-5");
51
+ expect(session.totalTokens).toMatchObject({ inputTokens: 10, outputTokens: 5, cacheReadTokens: 3 });
52
+ } finally { rmSync(dir, { recursive: true, force: true }); }
53
+ });
54
+
55
+ test("parses Goose sessions from SQLite", async () => {
56
+ const dir = fixture("goose");
57
+ try {
58
+ const path = join(dir, "sessions.db");
59
+ const db = new Database(path);
60
+ db.exec("CREATE TABLE sessions (id TEXT, model_config_json TEXT, created_at TEXT, input_tokens INTEGER, output_tokens INTEGER, total_tokens INTEGER, accumulated_input_tokens INTEGER, accumulated_output_tokens INTEGER, accumulated_total_tokens INTEGER)");
61
+ db.query("INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run("goose-1", '{"model_name":"gpt-5.6-terra"}', "2026-07-01 12:00:00", 0, 0, 0, 10, 5, 18);
62
+ db.close();
63
+ const session = await firstSession(path, "goose");
64
+ expect(session.modelUsage[0]?.model).toBe("gpt-5.6-terra");
65
+ expect(session.totalTokens).toMatchObject({ inputTokens: 10, outputTokens: 5, reasoningTokens: 3 });
66
+ } finally { rmSync(dir, { recursive: true, force: true }); }
67
+ });
68
+
69
+ test("parses Hermes sessions from SQLite", async () => {
70
+ const dir = fixture("hermes");
71
+ try {
72
+ const path = join(dir, "state.db");
73
+ const db = new Database(path);
74
+ db.exec("CREATE TABLE sessions (id TEXT, model TEXT, started_at REAL, message_count INTEGER, input_tokens INTEGER, output_tokens INTEGER, cache_read_tokens INTEGER, cache_write_tokens INTEGER, reasoning_tokens INTEGER, estimated_cost_usd REAL, actual_cost_usd REAL)");
75
+ db.query("INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run("hermes-1", "gpt-5.6-sol", 1_783_000_000, 2, 10, 5, 3, 1, 2, 0.1, 0.2);
76
+ db.close();
77
+ const session = await firstSession(path, "hermes");
78
+ expect(session.modelUsage[0]?.model).toBe("gpt-5.6-sol");
79
+ expect(session.totalCostUsd).toBe(0.2);
80
+ expect(session.totalTokens).toMatchObject({ cacheReadTokens: 3, cacheWriteTokens: 1, reasoningTokens: 2 });
81
+ } finally { rmSync(dir, { recursive: true, force: true }); }
82
+ });
83
+
84
+ test("parses Kilo messages from SQLite", async () => {
85
+ const dir = fixture("kilo");
86
+ try {
87
+ const path = join(dir, "kilo.db");
88
+ const db = new Database(path);
89
+ db.exec("CREATE TABLE message (id TEXT, session_id TEXT, data TEXT)");
90
+ db.query("INSERT INTO message VALUES (?, ?, ?)").run("row-1", "kilo-1", JSON.stringify({
91
+ id: "message-1", role: "assistant", modelID: "claude-fable-5", time: { created: 1_783_000_000_000 },
92
+ tokens: { input: 10, output: 5, reasoning: 2, cache: { read: 3, write: 1 } }, cost: 0.2,
93
+ }));
94
+ db.close();
95
+ const session = await firstSession(path, "kilo");
96
+ expect(session.modelUsage[0]?.model).toBe("claude-fable-5");
97
+ expect(session.totalTokens).toMatchObject({ inputTokens: 10, outputTokens: 5, cacheReadTokens: 3, cacheWriteTokens: 1, reasoningTokens: 2 });
98
+ } finally { rmSync(dir, { recursive: true, force: true }); }
99
+ });
100
+
101
+ test("parses Kimi wire usage", async () => {
102
+ const dir = fixture("kimi");
103
+ try {
104
+ const path = join(dir, "wire.jsonl");
105
+ writeFileSync(path, JSON.stringify({ type: "usage.record", usage_scope: "turn", time: 1_783_000_000_000, model: "kimi-code/k2", usage: { input_other: 10, output: 5, input_cache_read: 3, input_cache_creation: 1 } }) + "\n");
106
+ const session = await firstSession(path, "kimi");
107
+ expect(session.modelUsage[0]?.model).toBe("k2");
108
+ expect(session.totalTokens).toMatchObject({ inputTokens: 10, outputTokens: 5, cacheReadTokens: 3, cacheWriteTokens: 1 });
109
+ } finally { rmSync(dir, { recursive: true, force: true }); }
110
+ });
111
+
112
+ test("parses OpenClaw model changes and assistant usage", async () => {
113
+ const dir = fixture("openclaw");
114
+ try {
115
+ const path = join(dir, "session.jsonl");
116
+ writeFileSync(path, [
117
+ JSON.stringify({ type: "model_change", data: { modelId: "gpt-5.6-terra" } }),
118
+ JSON.stringify({ type: "message", message: { role: "assistant", timestamp: 1_783_000_000_000, usage: { input: 10, output: 5, cacheRead: 3, cacheWrite: 1, cost: { total: 0.2 } } } }),
119
+ ].join("\n"));
120
+ const session = await firstSession(path, "openclaw");
121
+ expect(session.modelUsage[0]?.model).toBe("gpt-5.6-terra");
122
+ expect(session.totalCostUsd).toBe(0.2);
123
+ } finally { rmSync(dir, { recursive: true, force: true }); }
124
+ });
125
+
126
+ test("parses pi assistant usage", async () => {
127
+ const dir = fixture("pi");
128
+ try {
129
+ const path = join(dir, "session.jsonl");
130
+ writeFileSync(path, JSON.stringify({ timestamp: "2026-07-01T12:00:00Z", message: { role: "assistant", model: "gpt-5.6-sol", usage: { input: 10, output: 5, cacheRead: 3, cacheWrite: 1, cost: { total: 0.2 } } } }) + "\n");
131
+ const session = await firstSession(path, "pi");
132
+ expect(session.modelUsage[0]?.model).toBe("gpt-5.6-sol");
133
+ expect(session.totalCostUsd).toBe(0.2);
134
+ } finally { rmSync(dir, { recursive: true, force: true }); }
135
+ });
136
+
137
+ test("parses Qwen assistant usage metadata", async () => {
138
+ const dir = fixture("qwen");
139
+ try {
140
+ const path = join(dir, "chat.jsonl");
141
+ writeFileSync(path, JSON.stringify({ type: "assistant", timestamp: "2026-07-01T12:00:00Z", model: "qwen3-coder", usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 5, thoughtsTokenCount: 2, cachedContentTokenCount: 3 } }) + "\n");
142
+ const session = await firstSession(path, "qwen");
143
+ expect(session.modelUsage[0]?.model).toBe("qwen3-coder");
144
+ expect(session.totalTokens).toMatchObject({ inputTokens: 10, outputTokens: 5, reasoningTokens: 2, cacheReadTokens: 3 });
145
+ } finally { rmSync(dir, { recursive: true, force: true }); }
146
+ });
147
+ });