@zhangferry-dev/tokendash 1.6.0 → 1.6.2

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.
Files changed (60) hide show
  1. package/README.md +146 -83
  2. package/dist/client/assets/index-Bw503sNp.css +1 -0
  3. package/dist/client/index.html +2 -2
  4. package/dist/client/popover.html +4 -3
  5. package/dist/daemon.cjs +3306 -0
  6. package/dist/daemon.cjs.map +7 -0
  7. package/dist/electron-server.cjs +1043 -27
  8. package/dist/electron-server.cjs.map +4 -4
  9. package/dist/server/daemon.d.ts +12 -0
  10. package/dist/server/daemon.js +176 -0
  11. package/dist/server/index.js +39 -13
  12. package/dist/server/insightsCalculator.d.ts +15 -0
  13. package/dist/server/insightsCalculator.js +276 -0
  14. package/dist/server/quota/adapter.d.ts +47 -0
  15. package/dist/server/quota/adapter.js +41 -0
  16. package/dist/server/quota/adapters/claude.d.ts +2 -0
  17. package/dist/server/quota/adapters/claude.js +124 -0
  18. package/dist/server/quota/adapters/codex.d.ts +2 -0
  19. package/dist/server/quota/adapters/codex.js +188 -0
  20. package/dist/server/quota/adapters/glm.d.ts +2 -0
  21. package/dist/server/quota/adapters/glm.js +133 -0
  22. package/dist/server/quota/adapters/kimi.d.ts +2 -0
  23. package/dist/server/quota/adapters/kimi.js +184 -0
  24. package/dist/server/quota/adapters/minimax.d.ts +2 -0
  25. package/dist/server/quota/adapters/minimax.js +77 -0
  26. package/dist/server/quota/cache.d.ts +20 -0
  27. package/dist/server/quota/cache.js +44 -0
  28. package/dist/server/quota/credentialsFile.d.ts +13 -0
  29. package/dist/server/quota/credentialsFile.js +23 -0
  30. package/dist/server/quota/helpers.d.ts +39 -0
  31. package/dist/server/quota/helpers.js +93 -0
  32. package/dist/server/quota/index.d.ts +5 -0
  33. package/dist/server/quota/index.js +23 -0
  34. package/dist/server/quota/quotaService.d.ts +37 -0
  35. package/dist/server/quota/quotaService.js +141 -0
  36. package/dist/server/quota/schemas.d.ts +358 -0
  37. package/dist/server/quota/schemas.js +53 -0
  38. package/dist/server/quota/types.d.ts +65 -0
  39. package/dist/server/quota/types.js +10 -0
  40. package/dist/server/routes/api.d.ts +6 -1
  41. package/dist/server/routes/api.js +26 -1
  42. package/dist/server/routes/insights.d.ts +2 -0
  43. package/dist/server/routes/insights.js +155 -0
  44. package/package.json +6 -10
  45. package/resources/icon-1024.png +0 -0
  46. package/resources/icon.icns +0 -0
  47. package/resources/icon.png +0 -0
  48. package/resources/product_menu.png +0 -0
  49. package/resources/readme-hero.png +0 -0
  50. package/dist/client/assets/index-_yA9tOzZ.css +0 -1
  51. package/electron/main.cjs +0 -490
  52. package/electron/main.js +0 -291
  53. package/electron/preload.cjs +0 -36
  54. package/electron/trayBadge.cjs +0 -27
  55. package/electron/trayBadge.js +0 -30
  56. package/electron/trayHelper +0 -0
  57. package/electron/trayHelper.swift +0 -152
  58. package/electron/updateService.cjs +0 -148
  59. package/electron-builder.yml +0 -20
  60. /package/dist/client/assets/{index-CY4G_b0x.js → index-C913wKtU.js} +0 -0
package/electron/main.cjs DELETED
@@ -1,490 +0,0 @@
1
- const { app, BrowserWindow, ipcMain, screen, shell } = require('electron');
2
- const path = require('node:path');
3
- const fs = require('node:fs');
4
- const http = require('node:http');
5
- const { spawn } = require('node:child_process');
6
-
7
- // Global debug logger (writes to file since stdout is lost in packaged apps)
8
- const DEBUG_LOG = '/tmp/tokendash-debug.log';
9
- try { fs.writeFileSync(DEBUG_LOG, 'main.js loaded\n'); } catch(_){}
10
-
11
- // Import from bundled server (created by esbuild)
12
- let createApp;
13
- try {
14
- createApp = require('../dist/electron-server.cjs').createApp;
15
- } catch (e) {
16
- console.error('Failed to load bundled server. Did you run the build?', e.message);
17
- app.quit();
18
- }
19
-
20
- const { formatTokens } = require('./trayBadge.cjs');
21
- const { checkForUpdates, downloadUpdateAsset } = require('./updateService.cjs');
22
-
23
- // Resolve trayHelper binary: extract from asar if needed
24
- function resolveTrayHelperPath() {
25
- const srcPath = path.join(__dirname, 'trayHelper');
26
- const isAsar = srcPath.includes('.asar');
27
- const debugLog = (msg) => {
28
- const logPath = '/tmp/tokendash-debug.log';
29
- fs.appendFileSync(logPath, msg + '\n');
30
- };
31
- debugLog('[trayHelper] __dirname: ' + __dirname);
32
- debugLog('[trayHelper] srcPath: ' + srcPath + ' isAsar: ' + isAsar);
33
- if (isAsar) {
34
- const destDir = path.join(app.getPath('userData'), 'helpers');
35
- const destPath = path.join(destDir, 'trayHelper');
36
- debugLog('[trayHelper] extracting to: ' + destPath);
37
- if (!fs.existsSync(destDir)) fs.mkdirSync(destDir, { recursive: true });
38
- fs.copyFileSync(srcPath, destPath);
39
- fs.chmodSync(destPath, 0o755);
40
- debugLog('[trayHelper] extracted OK');
41
- return destPath;
42
- }
43
- return srcPath;
44
- }
45
-
46
- // ---------------------------------------------------------------------------
47
- // State
48
- // ---------------------------------------------------------------------------
49
-
50
- let popover = null;
51
- let server = null;
52
- let trayProcess = null;
53
- let selectedAgents = null; // null = use all available agents
54
- let serverPort = parseInt(process.env.TOKENDASH_PORT || '3456', 10);
55
- let lastUpdateInfo = null;
56
- let isDownloadingUpdate = false;
57
- const POPOVER_WIDTH = 380;
58
- const POPOVER_HEIGHT = 540;
59
- const PACKAGE_NAME = '@zhangferry-dev/tokendash';
60
- const GITHUB_REPO = 'zhangferry/tokendash';
61
-
62
- // ---------------------------------------------------------------------------
63
- // Helpers
64
- // ---------------------------------------------------------------------------
65
-
66
- function listenWithFallback(expressApp, port) {
67
- return new Promise((resolve, reject) => {
68
- let currentPort = port;
69
- let attempts = 0;
70
-
71
- function tryListen() {
72
- const s = expressApp.listen(currentPort);
73
- s.once('listening', () => resolve({ server: s, port: currentPort }));
74
- s.once('error', (err) => {
75
- if (err.code === 'EADDRINUSE' && attempts < 20) {
76
- attempts++;
77
- currentPort++;
78
- tryListen();
79
- } else {
80
- reject(err);
81
- }
82
- });
83
- }
84
-
85
- tryListen();
86
- });
87
- }
88
-
89
- function fetchJson(url) {
90
- return new Promise((resolve, reject) => {
91
- http.get(url, (res) => {
92
- let data = '';
93
- res.on('data', (chunk) => { data += chunk; });
94
- res.on('end', () => {
95
- try { resolve(JSON.parse(data)); }
96
- catch (e) { reject(e); }
97
- });
98
- }).on('error', reject);
99
- });
100
- }
101
-
102
- function getAppInfo() {
103
- // app.getVersion() returns Electron's version in dev mode (e.g. 41.5).
104
- // Always read from package.json to get the app's own version.
105
- let version = app.getVersion();
106
- try {
107
- const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
108
- if (pkg.version) version = pkg.version;
109
- } catch (_) {}
110
- return {
111
- version,
112
- launchAtLogin: app.getLoginItemSettings().openAtLogin,
113
- platform: process.platform,
114
- packageName: PACKAGE_NAME,
115
- };
116
- }
117
-
118
- function positionPopoverAtClick(clickScreenX) {
119
- if (!popover) return;
120
-
121
- // Find which display the click is on
122
- const allDisplays = screen.getAllDisplays();
123
- const clickDisplay = allDisplays.find(d => {
124
- const bounds = d.bounds;
125
- return clickScreenX >= bounds.x && clickScreenX < bounds.x + bounds.width;
126
- }) || screen.getPrimaryDisplay();
127
-
128
- const { x: screenX, y: screenY, width: screenW, height: screenH } = clickDisplay.workArea;
129
- const popoverWidth = POPOVER_WIDTH;
130
- const popoverHeight = POPOVER_HEIGHT;
131
-
132
- // Center horizontally on click position
133
- let x = clickScreenX - popoverWidth / 2;
134
- // Below menu bar, close to the icon
135
- let y = screenY + 6;
136
-
137
- // Clamp to screen bounds
138
- if (x < screenX + 8) x = screenX + 8;
139
- if (x + popoverWidth > screenX + screenW - 8) x = screenX + screenW - popoverWidth - 8;
140
- if (y + popoverHeight > screenY + screenH - 8) y = screenY + screenH - popoverHeight - 8;
141
-
142
- popover.setPosition(Math.round(x), Math.round(y), false);
143
- }
144
-
145
- function togglePopover(clickScreenX) {
146
- if (!popover) return;
147
-
148
- if (popover.isVisible()) {
149
- popover.hide();
150
- } else {
151
- positionPopoverAtClick(clickScreenX || 0);
152
- popover.show();
153
- popover.focus();
154
- }
155
- }
156
-
157
- // ---------------------------------------------------------------------------
158
- // Native tray helper (Swift binary for macOS 26+ compatibility)
159
- // ---------------------------------------------------------------------------
160
-
161
- function startTrayHelper() {
162
- const helperPath = resolveTrayHelperPath();
163
- trayProcess = spawn(helperPath, [], {
164
- stdio: ['pipe', 'pipe', 'inherit'],
165
- });
166
-
167
- let buffer = '';
168
-
169
- trayProcess.stdout.on('data', (data) => {
170
- buffer += data.toString();
171
- const lines = buffer.split('\n');
172
- buffer = lines.pop(); // keep incomplete line in buffer
173
-
174
- for (const line of lines) {
175
- const event = line.trim();
176
- if (event.startsWith('click:')) {
177
- // Format: click:x,y (screen coordinates in macOS points)
178
- const parts = event.split(':')[1];
179
- const clickX = parseInt(parts.split(',')[0], 10) || 0;
180
- // Convert macOS screen coords (origin bottom-left) to top-left for Electron
181
- const primaryDisplay = screen.getPrimaryDisplay();
182
- const screenH = primaryDisplay.size.height;
183
- togglePopover(clickX);
184
- } else if (event === 'ready') {
185
- // Helper is ready, start badge updates
186
- startBadgeUpdates();
187
- }
188
- }
189
- });
190
-
191
- trayProcess.on('close', (code) => {
192
- console.log('Tray helper exited with code', code);
193
- trayProcess = null;
194
- });
195
-
196
- trayProcess.on('error', (err) => {
197
- console.error('Failed to start tray helper:', err.message);
198
- trayProcess = null;
199
- });
200
- }
201
-
202
- function sendTrayCommand(command) {
203
- if (trayProcess && trayProcess.stdin && !trayProcess.stdin.destroyed) {
204
- trayProcess.stdin.write(command + '\n');
205
- }
206
- }
207
-
208
- function stopTrayHelper() {
209
- if (trayProcess) {
210
- sendTrayCommand('quit');
211
- trayProcess = null;
212
- }
213
- }
214
-
215
- // ---------------------------------------------------------------------------
216
- // Tray badge updater
217
- // ---------------------------------------------------------------------------
218
-
219
- let updateTimer = null;
220
- let lastTraySnapshot = null;
221
-
222
- function getTrayAgentKey(agents) {
223
- return agents.slice().sort().join(',');
224
- }
225
-
226
- function applyTraySnapshot(snapshot) {
227
- const totalTokens = Number(snapshot && snapshot.totalTokens) || 0;
228
- const totalInput = Number(snapshot && snapshot.totalInput) || 0;
229
- const totalCost = Number(snapshot && snapshot.totalCost) || 0;
230
- const totalCacheRead = Number(snapshot && snapshot.totalCacheRead) || 0;
231
- const today = snapshot && snapshot.today;
232
- const agentKey = snapshot && snapshot.agentKey;
233
-
234
- lastTraySnapshot = { today, agentKey, totalTokens, totalInput, totalCost, totalCacheRead };
235
-
236
- const tokenStr = formatTokens(totalTokens);
237
- sendTrayCommand('title:' + tokenStr);
238
-
239
- const cacheInput = totalInput + totalCacheRead;
240
- const cacheRate = cacheInput > 0 ? ((totalCacheRead / cacheInput) * 100).toFixed(1) : '0.0';
241
- sendTrayCommand('tooltip:TokenDash - ' + tokenStr + ' tokens today ($' + totalCost.toFixed(2) + ') | cache: ' + cacheRate + '%');
242
- }
243
-
244
- function updateTrayBadge() {
245
- const d = new Date(); const today = d.getFullYear() + "-" + String(d.getMonth()+1).padStart(2,"0") + "-" + String(d.getDate()).padStart(2,"0");
246
-
247
- // Fetch agents list, then fetch daily data for each agent in parallel
248
- fetchJson(`http://localhost:${serverPort}/api/agents`)
249
- .then((agentData) => {
250
- let agents = (agentData && Array.isArray(agentData.available)) ? agentData.available : ['claude'];
251
- if (agents.length === 0) {
252
- // Transient agent detection failures should not clear a previously valid tray badge.
253
- return null;
254
- }
255
-
256
- // Apply agent filter from popover settings
257
- if (selectedAgents && selectedAgents.length > 0) {
258
- const filtered = agents.filter(a => selectedAgents.includes(a));
259
- if (filtered.length > 0) agents = filtered;
260
- }
261
-
262
- const agentKey = getTrayAgentKey(agents);
263
- return Promise.all(
264
- agents.map(agent =>
265
- fetchJson(`http://localhost:${serverPort}/api/daily?agent=${agent}`)
266
- .catch(() => null)
267
- )
268
- ).then(results => ({ agentKey, results }));
269
- })
270
- .then((payload) => {
271
- if (!payload) return;
272
- const { agentKey, results } = payload;
273
- const successfulResults = results.filter(data => data && data.daily);
274
- if (successfulResults.length === 0) {
275
- // Keep the last good value when every daily request failed.
276
- return;
277
- }
278
-
279
- let totalTokens = 0;
280
- let totalCost = 0;
281
- let totalInput = 0;
282
- let totalOutput = 0;
283
- let totalCacheRead = 0;
284
-
285
- for (const data of results) {
286
- if (!data || !data.daily) continue;
287
- const entry = data.daily.find(d => d.date === today);
288
- if (!entry) continue;
289
- totalTokens += entry.totalTokens || 0;
290
- totalCost += entry.totalCost || 0;
291
- totalInput += entry.inputTokens || 0;
292
- totalOutput += entry.outputTokens || 0;
293
- totalCacheRead += entry.cacheReadTokens || 0;
294
- }
295
-
296
- const shouldPreserveLastPositive =
297
- totalTokens === 0 &&
298
- lastTraySnapshot &&
299
- lastTraySnapshot.today === today &&
300
- lastTraySnapshot.agentKey === agentKey &&
301
- lastTraySnapshot.totalTokens > 0;
302
-
303
- if (shouldPreserveLastPositive) {
304
- // Daily usage should not drop to zero during the same day for the same agent filter.
305
- // Treat a zero refresh after a positive value as transient empty data and keep the badge stable.
306
- return;
307
- }
308
-
309
- applyTraySnapshot({ today, agentKey, totalTokens, totalInput, totalCost, totalCacheRead });
310
- })
311
- .catch((err) => {
312
- if (err.code !== 'ECONNREFUSED') {
313
- console.error('Tray badge update error:', err.message);
314
- }
315
- });
316
- }
317
-
318
- function startBadgeUpdates() {
319
- updateTrayBadge();
320
- updateTimer = setInterval(updateTrayBadge, 5000);
321
- }
322
-
323
- function stopBadgeUpdates() {
324
- if (updateTimer) {
325
- clearInterval(updateTimer);
326
- updateTimer = null;
327
- }
328
- }
329
-
330
- // ---------------------------------------------------------------------------
331
- // Create popover window
332
- // ---------------------------------------------------------------------------
333
-
334
- function createPopoverWindow() {
335
- popover = new BrowserWindow({
336
- width: POPOVER_WIDTH,
337
- height: POPOVER_HEIGHT,
338
- frame: false,
339
- resizable: false,
340
- hasShadow: true,
341
- alwaysOnTop: true,
342
- skipTaskbar: true,
343
- show: false,
344
- fullscreenable: false,
345
- transparent: false,
346
- webPreferences: {
347
- nodeIntegration: false,
348
- contextIsolation: true,
349
- preload: path.join(__dirname, 'preload.cjs'),
350
- },
351
- });
352
-
353
- popover.loadURL(`http://localhost:${serverPort}/popover.html`);
354
-
355
- popover.on('blur', () => {
356
- popover.hide();
357
- });
358
-
359
- popover.on('close', (e) => {
360
- if (!app.isQuitting) {
361
- e.preventDefault();
362
- popover.hide();
363
- }
364
- });
365
- }
366
-
367
- function registerIpcHandlers() {
368
- ipcMain.handle('tokendash:open-dashboard', (_event, url) => {
369
- const target = typeof url === 'string' && url.length > 0 ? url : `http://localhost:${serverPort}`;
370
- return shell.openExternal(target);
371
- });
372
-
373
- ipcMain.handle('tokendash:get-app-info', () => {
374
- return getAppInfo();
375
- });
376
-
377
- ipcMain.handle('tokendash:set-launch-at-login', (_event, enabled) => {
378
- const openAtLogin = Boolean(enabled);
379
- app.setLoginItemSettings({ openAtLogin });
380
- return { launchAtLogin: app.getLoginItemSettings().openAtLogin };
381
- });
382
-
383
- ipcMain.handle('tokendash:check-for-updates', async () => {
384
- const currentVersion = getAppInfo().version;
385
-
386
- try {
387
- lastUpdateInfo = await checkForUpdates({ repo: GITHUB_REPO, currentVersion });
388
- return lastUpdateInfo;
389
- } catch (error) {
390
- return {
391
- currentVersion,
392
- latestVersion: currentVersion,
393
- upToDate: true,
394
- error: error instanceof Error ? error.message : String(error),
395
- };
396
- }
397
- });
398
-
399
- ipcMain.handle('tokendash:download-update', async (event) => {
400
- if (isDownloadingUpdate) {
401
- return { ok: false, error: 'An update download is already in progress.' };
402
- }
403
-
404
- const info = lastUpdateInfo;
405
- if (!info || info.upToDate || !info.asset || !info.asset.url) {
406
- return { ok: false, error: 'No downloadable update is available.' };
407
- }
408
-
409
- isDownloadingUpdate = true;
410
- try {
411
- const downloadsDir = path.join(app.getPath('downloads'), 'TokenDash Updates');
412
- const filePath = await downloadUpdateAsset(info.asset, downloadsDir, (progress) => {
413
- event.sender.send('tokendash:update-download-progress', progress);
414
- });
415
- await shell.openPath(filePath);
416
- return { ok: true, filePath };
417
- } catch (error) {
418
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
419
- } finally {
420
- isDownloadingUpdate = false;
421
- }
422
- });
423
-
424
- ipcMain.handle('tokendash:quit', () => {
425
- app.isQuitting = true;
426
- stopBadgeUpdates();
427
- stopTrayHelper();
428
- if (server) server.close();
429
- app.quit();
430
- });
431
-
432
- ipcMain.handle('tokendash:set-selected-agents', (_event, agents) => {
433
- selectedAgents = Array.isArray(agents) ? agents : null;
434
- lastTraySnapshot = null;
435
- // Immediately refresh badge with new filter
436
- updateTrayBadge();
437
- return { ok: true };
438
- });
439
-
440
- ipcMain.handle('tokendash:update-tray-snapshot', (_event, snapshot) => {
441
- if (!snapshot || typeof snapshot !== 'object') return { ok: false };
442
- applyTraySnapshot(snapshot);
443
- return { ok: true };
444
- });
445
- }
446
-
447
- // ---------------------------------------------------------------------------
448
- // App lifecycle
449
- // ---------------------------------------------------------------------------
450
-
451
- app.whenReady().then(async () => {
452
- if (process.platform === 'darwin' && app.dock) {
453
- app.dock.hide();
454
- }
455
-
456
- registerIpcHandlers();
457
-
458
- app.on('before-quit', () => {
459
- app.isQuitting = true;
460
- stopBadgeUpdates();
461
- stopTrayHelper();
462
- if (server) server.close();
463
- });
464
-
465
- // Create and bind Express server
466
- // Pass dist/ directory so createApp resolves client assets correctly
467
- const distDir = path.join(__dirname, '..', 'dist');
468
- const expressApp = createApp(serverPort, distDir);
469
- try {
470
- const result = await listenWithFallback(expressApp, serverPort);
471
- server = result.server;
472
- serverPort = result.port;
473
- console.log(`tokendash running on http://localhost:${result.port}`);
474
- } catch (err) {
475
- console.error('Failed to start server:', err);
476
- app.quit();
477
- return;
478
- }
479
-
480
- // Start native tray helper
481
- startTrayHelper();
482
-
483
- // Create popover
484
- createPopoverWindow();
485
- });
486
-
487
- process.on('uncaughtException', (err) => {
488
- console.error('Fatal error in Electron main:', err);
489
- app.quit();
490
- });