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