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