@diogonzafe/tokenwatch 0.7.0 → 0.8.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/dist/cli.js CHANGED
@@ -29,6 +29,7 @@ function rowToEntry(r) {
29
29
  ...r["session_id"] != null && { sessionId: r["session_id"] },
30
30
  ...r["user_id"] != null && { userId: r["user_id"] },
31
31
  ...r["feature"] != null && { feature: r["feature"] },
32
+ ...r["app_id"] != null && { appId: r["app_id"] },
32
33
  timestamp: r["timestamp"] instanceof Date ? r["timestamp"].toISOString() : r["timestamp"]
33
34
  };
34
35
  }
@@ -57,6 +58,7 @@ var init_postgres = __esm({
57
58
  session_id TEXT,
58
59
  user_id TEXT,
59
60
  feature TEXT,
61
+ app_id TEXT,
60
62
  timestamp TIMESTAMPTZ NOT NULL
61
63
  )
62
64
  `);
@@ -64,7 +66,8 @@ var init_postgres = __esm({
64
66
  "ALTER TABLE tokenwatch_usage ADD COLUMN IF NOT EXISTS reasoning_tokens INTEGER NOT NULL DEFAULT 0",
65
67
  "ALTER TABLE tokenwatch_usage ADD COLUMN IF NOT EXISTS feature TEXT",
66
68
  "ALTER TABLE tokenwatch_usage ADD COLUMN IF NOT EXISTS cached_tokens INTEGER NOT NULL DEFAULT 0",
67
- "ALTER TABLE tokenwatch_usage ADD COLUMN IF NOT EXISTS cache_creation_tokens INTEGER NOT NULL DEFAULT 0"
69
+ "ALTER TABLE tokenwatch_usage ADD COLUMN IF NOT EXISTS cache_creation_tokens INTEGER NOT NULL DEFAULT 0",
70
+ "ALTER TABLE tokenwatch_usage ADD COLUMN IF NOT EXISTS app_id TEXT"
68
71
  ]) {
69
72
  await this.client.query(col).catch(() => {
70
73
  });
@@ -74,8 +77,8 @@ var init_postgres = __esm({
74
77
  this.client.query(
75
78
  `INSERT INTO tokenwatch_usage
76
79
  (model, input_tokens, output_tokens, reasoning_tokens, cached_tokens, cache_creation_tokens,
77
- cost_usd, session_id, user_id, feature, timestamp)
78
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
80
+ cost_usd, session_id, user_id, feature, app_id, timestamp)
81
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
79
82
  [
80
83
  entry.model,
81
84
  entry.inputTokens,
@@ -87,6 +90,7 @@ var init_postgres = __esm({
87
90
  entry.sessionId ?? null,
88
91
  entry.userId ?? null,
89
92
  entry.feature ?? null,
93
+ entry.appId ?? null,
90
94
  entry.timestamp
91
95
  ]
92
96
  ).catch((err) => {
@@ -132,6 +136,7 @@ function rowToEntry2(r) {
132
136
  ...r["session_id"] != null && { sessionId: r["session_id"] },
133
137
  ...r["user_id"] != null && { userId: r["user_id"] },
134
138
  ...r["feature"] != null && { feature: r["feature"] },
139
+ ...r["app_id"] != null && { appId: r["app_id"] },
135
140
  timestamp: r["timestamp"] instanceof Date ? r["timestamp"].toISOString() : r["timestamp"]
136
141
  };
137
142
  }
@@ -160,6 +165,7 @@ var init_mysql = __esm({
160
165
  session_id VARCHAR(255),
161
166
  user_id VARCHAR(255),
162
167
  feature VARCHAR(255),
168
+ app_id VARCHAR(255),
163
169
  timestamp DATETIME(3) NOT NULL
164
170
  )
165
171
  `);
@@ -168,7 +174,8 @@ var init_mysql = __esm({
168
174
  ADD COLUMN IF NOT EXISTS reasoning_tokens INT NOT NULL DEFAULT 0,
169
175
  ADD COLUMN IF NOT EXISTS feature VARCHAR(255),
170
176
  ADD COLUMN IF NOT EXISTS cached_tokens INT NOT NULL DEFAULT 0,
171
- ADD COLUMN IF NOT EXISTS cache_creation_tokens INT NOT NULL DEFAULT 0
177
+ ADD COLUMN IF NOT EXISTS cache_creation_tokens INT NOT NULL DEFAULT 0,
178
+ ADD COLUMN IF NOT EXISTS app_id VARCHAR(255)
172
179
  `).catch(() => {
173
180
  });
174
181
  }
@@ -176,8 +183,8 @@ var init_mysql = __esm({
176
183
  this.client.execute(
177
184
  `INSERT INTO tokenwatch_usage
178
185
  (model, input_tokens, output_tokens, reasoning_tokens, cached_tokens, cache_creation_tokens,
179
- cost_usd, session_id, user_id, feature, timestamp)
180
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
186
+ cost_usd, session_id, user_id, feature, app_id, timestamp)
187
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
181
188
  [
182
189
  entry.model,
183
190
  entry.inputTokens,
@@ -189,6 +196,7 @@ var init_mysql = __esm({
189
196
  entry.sessionId ?? null,
190
197
  entry.userId ?? null,
191
198
  entry.feature ?? null,
199
+ entry.appId ?? null,
192
200
  entry.timestamp
193
201
  ]
194
202
  ).catch((err) => {
@@ -231,6 +239,7 @@ function docToEntry(doc) {
231
239
  ...doc.sessionId != null && { sessionId: doc.sessionId },
232
240
  ...doc.userId != null && { userId: doc.userId },
233
241
  ...doc.feature != null && { feature: doc.feature },
242
+ ...doc.appId != null && { appId: doc.appId },
234
243
  timestamp: doc.timestamp
235
244
  };
236
245
  }
@@ -250,6 +259,7 @@ var init_mongodb = __esm({
250
259
  await this.col.createIndex({ sessionId: 1 });
251
260
  await this.col.createIndex({ userId: 1 });
252
261
  await this.col.createIndex({ model: 1 });
262
+ await this.col.createIndex({ appId: 1 });
253
263
  }
254
264
  record(entry) {
255
265
  this.col.insertOne({
@@ -263,6 +273,7 @@ var init_mongodb = __esm({
263
273
  sessionId: entry.sessionId ?? null,
264
274
  userId: entry.userId ?? null,
265
275
  ...entry.feature !== void 0 && { feature: entry.feature },
276
+ ...entry.appId !== void 0 && { appId: entry.appId },
266
277
  timestamp: entry.timestamp
267
278
  }).catch((err) => {
268
279
  console.warn("[tokenwatch] MongoStorage.record failed:", err);
@@ -392,6 +403,7 @@ var SqliteStorage = class {
392
403
  session_id TEXT,
393
404
  user_id TEXT,
394
405
  feature TEXT,
406
+ app_id TEXT,
395
407
  timestamp TEXT NOT NULL
396
408
  )
397
409
  `);
@@ -408,13 +420,16 @@ var SqliteStorage = class {
408
420
  if (!cols.includes("cache_creation_tokens")) {
409
421
  this.db.exec(`ALTER TABLE usage ADD COLUMN cache_creation_tokens INTEGER NOT NULL DEFAULT 0`);
410
422
  }
423
+ if (!cols.includes("app_id")) {
424
+ this.db.exec(`ALTER TABLE usage ADD COLUMN app_id TEXT`);
425
+ }
411
426
  }
412
427
  record(entry) {
413
428
  this.db.prepare(
414
429
  `INSERT INTO usage
415
430
  (model, input_tokens, output_tokens, reasoning_tokens, cached_tokens, cache_creation_tokens,
416
- cost_usd, session_id, user_id, feature, timestamp)
417
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
431
+ cost_usd, session_id, user_id, feature, app_id, timestamp)
432
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
418
433
  ).run(
419
434
  entry.model,
420
435
  entry.inputTokens,
@@ -426,6 +441,7 @@ var SqliteStorage = class {
426
441
  entry.sessionId ?? null,
427
442
  entry.userId ?? null,
428
443
  entry.feature ?? null,
444
+ entry.appId ?? null,
429
445
  entry.timestamp
430
446
  );
431
447
  }
@@ -442,6 +458,7 @@ var SqliteStorage = class {
442
458
  ...r.session_id != null && { sessionId: r.session_id },
443
459
  ...r.user_id != null && { userId: r.user_id },
444
460
  ...r.feature != null && { feature: r.feature },
461
+ ...r.app_id != null && { appId: r.app_id },
445
462
  timestamp: r.timestamp
446
463
  }));
447
464
  }
@@ -527,7 +544,7 @@ function maybeSuggestCheaperModel(model, costUSD, inputTokens, outputTokens, lay
527
544
 
528
545
  // prices.json
529
546
  var prices_default = {
530
- updated_at: "2026-04-24",
547
+ updated_at: "2026-06-09",
531
548
  source: "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json",
532
549
  models: {
533
550
  "gpt-4o": {
@@ -571,14 +588,12 @@ var prices_default = {
571
588
  input: 3,
572
589
  output: 15,
573
590
  cachedInput: 0.3,
574
- cacheCreationInput: 3.75,
575
- maxInputTokens: 1e6
591
+ maxInputTokens: 2e5
576
592
  },
577
593
  "claude-haiku-4-5": {
578
594
  input: 1,
579
595
  output: 5,
580
596
  cachedInput: 0.1,
581
- cacheCreationInput: 1.25,
582
597
  maxInputTokens: 2e5
583
598
  },
584
599
  "gemini-2.5-pro": {
@@ -630,7 +645,6 @@ var prices_default = {
630
645
  input: 3,
631
646
  output: 15,
632
647
  cachedInput: 0.3,
633
- cacheCreationInput: 3.75,
634
648
  maxInputTokens: 2e5
635
649
  },
636
650
  "gpt-oss-120b": {
@@ -1123,9 +1137,9 @@ var prices_default = {
1123
1137
  maxInputTokens: 163840
1124
1138
  },
1125
1139
  "deepseek-r1": {
1126
- input: 0.55,
1127
- output: 2.19,
1128
- maxInputTokens: 65536
1140
+ input: 1.35,
1141
+ output: 5.4,
1142
+ maxInputTokens: 128e3
1129
1143
  },
1130
1144
  "deepseek-v3": {
1131
1145
  input: 0.27,
@@ -1565,7 +1579,7 @@ var prices_default = {
1565
1579
  "deepseek-r1-distill-llama-70b": {
1566
1580
  input: 0.99,
1567
1581
  output: 0.99,
1568
- maxInputTokens: 8e3
1582
+ maxInputTokens: 32768
1569
1583
  },
1570
1584
  "deepseek-llama3.3-70b": {
1571
1585
  input: 0.2,
@@ -1849,7 +1863,97 @@ var prices_default = {
1849
1863
  input: 5,
1850
1864
  output: 30,
1851
1865
  cachedInput: 0.5,
1866
+ maxInputTokens: 105e4
1867
+ },
1868
+ "gpt-5.5-2026-04-23": {
1869
+ input: 5,
1870
+ output: 30,
1871
+ cachedInput: 0.5,
1872
+ maxInputTokens: 105e4
1873
+ },
1874
+ "gpt-5.5-pro": {
1875
+ input: 30,
1876
+ output: 180,
1877
+ cachedInput: 3,
1878
+ maxInputTokens: 105e4
1879
+ },
1880
+ "gpt-5.5-pro-2026-04-23": {
1881
+ input: 30,
1882
+ output: 180,
1883
+ cachedInput: 3,
1884
+ maxInputTokens: 105e4
1885
+ },
1886
+ "gpt-5.4-mini-2026-03-17": {
1887
+ input: 0.75,
1888
+ output: 4.5,
1889
+ cachedInput: 0.075,
1852
1890
  maxInputTokens: 272e3
1891
+ },
1892
+ "gpt-5.4-nano-2026-03-17": {
1893
+ input: 0.2,
1894
+ output: 1.25,
1895
+ cachedInput: 0.02,
1896
+ maxInputTokens: 272e3
1897
+ },
1898
+ "gpt-image-2": {
1899
+ input: 5,
1900
+ output: 10,
1901
+ cachedInput: 1.25
1902
+ },
1903
+ "gpt-image-2-2026-04-21": {
1904
+ input: 5,
1905
+ output: 10,
1906
+ cachedInput: 1.25
1907
+ },
1908
+ "gpt-realtime-2": {
1909
+ input: 4,
1910
+ output: 16,
1911
+ cachedInput: 0.4,
1912
+ maxInputTokens: 32e3
1913
+ },
1914
+ "gemini-3.5-flash": {
1915
+ input: 1.5,
1916
+ output: 9,
1917
+ cachedInput: 0.15,
1918
+ maxInputTokens: 1048576
1919
+ },
1920
+ "gemini-3.1-flash-lite": {
1921
+ input: 0.25,
1922
+ output: 1.5,
1923
+ cachedInput: 0.025,
1924
+ maxInputTokens: 1048576
1925
+ },
1926
+ "claude-opus-4-8": {
1927
+ input: 5,
1928
+ output: 25,
1929
+ cachedInput: 0.5,
1930
+ cacheCreationInput: 6.25,
1931
+ maxInputTokens: 1e6
1932
+ },
1933
+ "claude-opus-4-8@default": {
1934
+ input: 5,
1935
+ output: 25,
1936
+ cachedInput: 0.5,
1937
+ cacheCreationInput: 6.25,
1938
+ maxInputTokens: 1e6
1939
+ },
1940
+ "claude-4-sonnet": {
1941
+ input: 3,
1942
+ output: 15,
1943
+ cachedInput: 0.3,
1944
+ maxInputTokens: 2e5
1945
+ },
1946
+ "claude-4-opus": {
1947
+ input: 5,
1948
+ output: 25,
1949
+ cachedInput: 0.5,
1950
+ maxInputTokens: 2e5
1951
+ },
1952
+ "claude-3-7-sonnet": {
1953
+ input: 3,
1954
+ output: 15,
1955
+ cachedInput: 0.3,
1956
+ maxInputTokens: 2e5
1853
1957
  }
1854
1958
  }
1855
1959
  };
@@ -1889,7 +1993,8 @@ var TrackerConfigSchema = z.object({
1889
1993
  windowHours: z.number().positive().optional().default(24),
1890
1994
  mode: z.enum(["once", "always"]).optional().default("once")
1891
1995
  }).optional(),
1892
- exporter: z.custom((v) => v !== null && typeof v === "object" && typeof v.export === "function").optional()
1996
+ exporter: z.custom((v) => v !== null && typeof v === "object" && typeof v.export === "function").optional(),
1997
+ appId: z.string().optional()
1893
1998
  });
1894
1999
  function createTracker(config = {}) {
1895
2000
  const parsed = TrackerConfigSchema.safeParse(config);
@@ -1908,7 +2013,8 @@ ${issues}`);
1908
2013
  budgets,
1909
2014
  suggestions,
1910
2015
  anomalyDetection,
1911
- exporter
2016
+ exporter,
2017
+ appId
1912
2018
  } = parsed.data;
1913
2019
  const storage = typeof storageOption === "object" ? storageOption : createStorage(storageOption);
1914
2020
  let remotePrices;
@@ -1963,7 +2069,8 @@ ${issues}`);
1963
2069
  const full = {
1964
2070
  ...entry,
1965
2071
  costUSD,
1966
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
2072
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2073
+ ...appId !== void 0 && entry.appId === void 0 && { appId }
1967
2074
  };
1968
2075
  storage.record(full);
1969
2076
  if (exporter) {
@@ -2050,6 +2157,7 @@ ${issues}`);
2050
2157
  const bySession = {};
2051
2158
  const byUser = {};
2052
2159
  const byFeature = {};
2160
+ const byApp = {};
2053
2161
  let totalInput = 0;
2054
2162
  let totalOutput = 0;
2055
2163
  let totalCost = 0;
@@ -2086,6 +2194,11 @@ ${issues}`);
2086
2194
  f.costUSD += e.costUSD;
2087
2195
  f.calls += 1;
2088
2196
  }
2197
+ if (e.appId) {
2198
+ const a = byApp[e.appId] ??= { costUSD: 0, calls: 0 };
2199
+ a.costUSD += e.costUSD;
2200
+ a.calls += 1;
2201
+ }
2089
2202
  }
2090
2203
  if (options && entries.length > 0) {
2091
2204
  periodFrom = entries[0]?.timestamp ?? periodFrom;
@@ -2097,6 +2210,7 @@ ${issues}`);
2097
2210
  bySession,
2098
2211
  byUser,
2099
2212
  byFeature,
2213
+ byApp,
2100
2214
  period: { from: periodFrom, to: lastTimestamp },
2101
2215
  ...pricesUpdatedAt ? { pricesUpdatedAt } : {}
2102
2216
  };
@@ -2201,7 +2315,7 @@ ${issues}`);
2201
2315
  }
2202
2316
  async function exportCSV() {
2203
2317
  const entries = await Promise.resolve(storage.getAll());
2204
- const header = "timestamp,model,inputTokens,outputTokens,reasoningTokens,cachedTokens,cacheCreationTokens,costUSD,sessionId,userId,feature";
2318
+ const header = "timestamp,model,inputTokens,outputTokens,reasoningTokens,cachedTokens,cacheCreationTokens,costUSD,sessionId,userId,feature,appId";
2205
2319
  const rows = entries.map(
2206
2320
  (e) => [
2207
2321
  csvEscape(e.timestamp),
@@ -2214,7 +2328,8 @@ ${issues}`);
2214
2328
  e.costUSD.toFixed(8),
2215
2329
  csvEscape(e.sessionId ?? ""),
2216
2330
  csvEscape(e.userId ?? ""),
2217
- csvEscape(e.feature ?? "")
2331
+ csvEscape(e.feature ?? ""),
2332
+ csvEscape(e.appId ?? "")
2218
2333
  ].join(",")
2219
2334
  );
2220
2335
  return [header, ...rows].join("\n");
@@ -2332,6 +2447,7 @@ async function getDashboardData(storage, filter) {
2332
2447
  const bySession = {};
2333
2448
  const byUser = {};
2334
2449
  const byFeature = {};
2450
+ const byApp = {};
2335
2451
  let totalInput = 0;
2336
2452
  let totalOutput = 0;
2337
2453
  let totalCost = 0;
@@ -2365,6 +2481,11 @@ async function getDashboardData(storage, filter) {
2365
2481
  f.costUSD += e.costUSD;
2366
2482
  f.calls += 1;
2367
2483
  }
2484
+ if (e.appId) {
2485
+ const a = byApp[e.appId] ??= { costUSD: 0, calls: 0 };
2486
+ a.costUSD += e.costUSD;
2487
+ a.calls += 1;
2488
+ }
2368
2489
  }
2369
2490
  const now = (/* @__PURE__ */ new Date()).toISOString();
2370
2491
  const periodFrom = entries[0]?.timestamp ?? now;
@@ -2376,6 +2497,7 @@ async function getDashboardData(storage, filter) {
2376
2497
  bySession,
2377
2498
  byUser,
2378
2499
  byFeature,
2500
+ byApp,
2379
2501
  period: { from: periodFrom, to: periodTo }
2380
2502
  };
2381
2503
  const forecastWindowMs = 24 * 60 * 60 * 1e3;
@@ -2422,555 +2544,1495 @@ async function getDashboardData(storage, filter) {
2422
2544
  }
2423
2545
 
2424
2546
  // src/dashboard/html.ts
2425
- function getHtml(port) {
2426
- void port;
2547
+ function getHtml(_port) {
2427
2548
  return `<!DOCTYPE html>
2428
2549
  <html lang="en">
2429
2550
  <head>
2430
2551
  <meta charset="UTF-8" />
2431
2552
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
2432
- <title>tokenwatch dashboard</title>
2433
- <script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
2553
+ <title>tokenwatch \u2014 Overview</title>
2434
2554
  <style>
2435
- *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
2555
+ :root{
2556
+ --bg:#0d1117; --surface:#161b22; --surface2:#1c2128;
2557
+ --border:#30363d; --border-muted:#21262d;
2558
+ --text:#e6edf3; --muted:#7d8590; --dim:#484f58;
2559
+ --accent:#58a6ff; --green:#3fb950; --yellow:#d29922; --red:#f85149;
2560
+ --mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace;
2561
+ --sans:-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;
2562
+ }
2563
+ *{box-sizing:border-box}
2564
+ html,body{margin:0}
2565
+ body{background:var(--bg);color:var(--text);font-family:var(--sans);
2566
+ font-size:13px;line-height:1.45;-webkit-font-smoothing:antialiased;
2567
+ font-variant-numeric:tabular-nums}
2568
+ h1,h2,h3{margin:0;font-weight:600}
2569
+ a{color:inherit;text-decoration:none}
2570
+ kbd{font-family:var(--sans);font-size:10px;color:var(--muted);
2571
+ background:#22272e;border:1px solid var(--border);border-radius:4px;
2572
+ padding:1px 5px;line-height:1.4}
2573
+ .tw-root{max-width:1440px;margin:0 auto;min-height:100vh;
2574
+ border-left:1px solid var(--border-muted);border-right:1px solid var(--border-muted)}
2575
+ .num,.tw-kpi-value,.tw-cost,.tw-num-cell,.tw-fc-value{font-variant-numeric:tabular-nums}
2576
+ .tw-header{position:sticky;top:0;z-index:40;height:54px;display:flex;
2577
+ align-items:center;justify-content:space-between;gap:16px;padding:0 18px;
2578
+ background:rgba(13,17,23,.86);backdrop-filter:blur(10px);
2579
+ border-bottom:1px solid var(--border)}
2580
+ .tw-hgroup{display:flex;align-items:center;gap:14px}
2581
+ .tw-logo{font-size:15px;font-weight:700;letter-spacing:-.01em}
2582
+ .tw-logo span{color:var(--accent)}
2583
+ .tw-ws{position:relative;display:flex;align-items:center;gap:7px;height:30px;
2584
+ padding:0 9px;background:var(--surface);border:1px solid var(--border);
2585
+ border-radius:7px;color:var(--text);font-size:12.5px;font-weight:500;cursor:pointer}
2586
+ .tw-ws:hover{border-color:#444c56}
2587
+ .tw-ws-dot{width:7px;height:7px;border-radius:50%;background:var(--green);
2588
+ box-shadow:0 0 0 3px rgba(63,185,80,.15)}
2589
+ .tw-ws-env{font-size:10px;color:var(--muted);background:#22272e;
2590
+ border-radius:4px;padding:1px 5px;text-transform:uppercase;letter-spacing:.03em}
2591
+ .tw-ws-menu{position:absolute;top:36px;left:0;width:230px;background:var(--surface2);
2592
+ border:1px solid var(--border);border-radius:9px;padding:5px;z-index:50;
2593
+ box-shadow:0 12px 32px rgba(0,0,0,.5)}
2594
+ .tw-ws-item{padding:7px 9px;border-radius:6px;font-size:12.5px;cursor:pointer;color:var(--text)}
2595
+ .tw-ws-item:hover{background:#22272e}
2596
+ .tw-ws-item.on{color:var(--accent)}
2597
+ .tw-ws-item.muted{color:var(--muted)}
2598
+ .tw-ws-sep{height:1px;background:var(--border);margin:5px 0}
2599
+ .tw-nav{display:flex;gap:2px;margin-left:6px}
2600
+ .tw-nav a{padding:6px 10px;border-radius:6px;font-size:13px;color:var(--muted);font-weight:500}
2601
+ .tw-nav a:hover{color:var(--text);background:var(--surface)}
2602
+ .tw-nav a.on{color:var(--text);background:var(--surface);box-shadow:inset 0 -2px 0 var(--accent)}
2603
+ .tw-search{display:flex;align-items:center;gap:8px;height:30px;padding:0 9px;
2604
+ width:200px;background:var(--surface);border:1px solid var(--border);
2605
+ border-radius:7px;color:var(--muted);font-size:12.5px;cursor:text}
2606
+ .tw-search:hover{border-color:#444c56}
2607
+ .tw-search span{flex:1;text-align:left}
2608
+ .tw-btn-2{display:flex;align-items:center;gap:6px;height:30px;padding:0 11px;
2609
+ background:var(--surface);border:1px solid var(--border);border-radius:7px;
2610
+ color:var(--text);font-size:12.5px;font-weight:500;cursor:pointer}
2611
+ .tw-btn-2:hover{border-color:#444c56;background:#1b2128}
2612
+ .tw-user{display:flex;align-items:center;gap:8px;margin-left:2px}
2613
+ .tw-plan{font-size:10px;font-weight:600;color:var(--accent);
2614
+ border:1px solid rgba(88,166,255,.4);background:rgba(88,166,255,.1);
2615
+ border-radius:5px;padding:2px 6px;text-transform:uppercase;letter-spacing:.04em}
2616
+ .tw-avatar{width:30px;height:30px;border-radius:50%;display:grid;place-items:center;
2617
+ font-size:11px;font-weight:600;color:#fff;
2618
+ background:linear-gradient(135deg,#bc8cff,#58a6ff)}
2619
+ .tw-main{padding:16px 18px 64px;display:flex;flex-direction:column;gap:14px}
2620
+ .tw-budget{background:var(--surface);border:1px solid var(--border);
2621
+ border-radius:10px;padding:13px 16px}
2622
+ .tw-budget-top{display:flex;align-items:center;gap:16px;margin-bottom:10px}
2623
+ .tw-budget-label{display:flex;align-items:baseline;gap:10px}
2624
+ .tw-bud-strong{font-weight:600;font-size:13px}
2625
+ .tw-bud-nums{color:var(--muted);font-size:12.5px}
2626
+ .tw-bud-nums b{color:var(--text)}
2627
+ .tw-bud-alert{display:flex;align-items:center;gap:6px;font-size:12px;
2628
+ padding:3px 9px;border-radius:6px;color:var(--green);
2629
+ background:rgba(63,185,80,.1);border:1px solid rgba(63,185,80,.25)}
2630
+ .tw-bud-alert b{color:var(--text)}
2631
+ .tw-budget-days{margin-left:auto;color:var(--muted);font-size:12px}
2632
+ .tw-bar{position:relative;height:9px;background:var(--border-muted);
2633
+ border-radius:5px;overflow:visible}
2634
+ .tw-bar-fill{height:100%;border-radius:5px;transition:width .5s}
2635
+ .tw-bar-proj{position:absolute;top:0;height:100%;
2636
+ background:repeating-linear-gradient(45deg,rgba(125,133,144,.35),rgba(125,133,144,.35) 4px,transparent 4px,transparent 8px);
2637
+ border-radius:0 5px 5px 0}
2638
+ .tw-bar-marker{position:absolute;top:-3px;width:2px;height:15px;background:var(--text);border-radius:2px}
2639
+ .tw-bar-marker::after{content:attr(data-tip);position:absolute;top:-18px;left:50%;
2640
+ transform:translateX(-50%);font-size:9.5px;color:var(--muted);white-space:nowrap}
2641
+ .tw-kpis{display:grid;grid-template-columns:repeat(5,1fr);gap:10px}
2642
+ .tw-kpi{background:var(--surface);border:1px solid var(--border);border-radius:10px;
2643
+ padding:12px 14px;display:flex;flex-direction:column;gap:7px;min-width:0}
2644
+ .tw-kpi-label{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}
2645
+ .tw-kpi-main{display:flex;align-items:flex-end;justify-content:space-between;gap:8px}
2646
+ .tw-kpi-value{font-size:21px;font-weight:600;letter-spacing:-.01em;
2647
+ white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
2648
+ .tw-kpi-foot{display:flex;align-items:center;gap:8px;font-size:11.5px;min-height:15px}
2649
+ .tw-delta{font-weight:600}
2650
+ .tw-kpi-sub{color:var(--muted)}
2651
+ .tw-timefilter{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:0 2px}
2652
+ .tw-tabs{display:flex;gap:2px;background:var(--surface);border:1px solid var(--border);
2653
+ border-radius:8px;padding:3px}
2654
+ .tw-tab{height:26px;padding:0 13px;border:0;background:transparent;color:var(--muted);
2655
+ font-size:12.5px;font-weight:600;font-family:var(--sans);border-radius:6px;cursor:pointer}
2656
+ .tw-tab:hover{color:var(--text)}
2657
+ .tw-tab.on{background:var(--accent);color:#0d1117}
2658
+ .tw-compare{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:12.5px;cursor:pointer}
2659
+ .tw-toggle-sm{position:relative;width:30px;height:17px;border:0;border-radius:999px;
2660
+ background:#30363d;cursor:pointer;padding:0;transition:background .15s}
2661
+ .tw-toggle-sm[data-on="1"]{background:var(--accent)}
2662
+ .tw-toggle-sm i{position:absolute;top:2px;left:2px;width:13px;height:13px;border-radius:50%;
2663
+ background:#fff;transition:transform .15s}
2664
+ .tw-toggle-sm[data-on="1"] i{transform:translateX(13px)}
2665
+ .tw-card,.tw-section{background:var(--surface);border:1px solid var(--border);border-radius:10px}
2666
+ .tw-section{padding:0}
2667
+ .tw-card{padding:14px 16px}
2668
+ .tw-sec-head{display:flex;align-items:center;justify-content:space-between;gap:10px;
2669
+ padding:13px 16px 11px}
2670
+ .tw-card .tw-sec-head{padding:0 0 10px}
2671
+ .tw-sec-head h3{font-size:13.5px}
2672
+ .tw-sec-sub{color:var(--muted);font-size:11.5px;font-weight:400}
2673
+ .tw-charts{display:grid;grid-template-columns:2fr 1fr;gap:14px}
2674
+ .tw-chart-main,.tw-chart-side{min-width:0}
2675
+ .tw-chart-legend{display:flex;align-items:center;gap:12px;font-size:11.5px;color:var(--muted)}
2676
+ .tw-chart-legend span{display:flex;align-items:center;gap:5px}
2677
+ .tw-chart-legend i{width:14px;height:3px;border-radius:2px;background:var(--accent)}
2678
+ .tw-chart-legend i.dash{background:repeating-linear-gradient(90deg,#6e7681,#6e7681 3px,transparent 3px,transparent 6px)}
2679
+ .tw-chart-legend .muted i{background:#6e7681}
2680
+ .tw-draw-line{stroke-dasharray:2600;stroke-dashoffset:2600;animation:tw-draw 1.1s cubic-bezier(.4,0,.2,1) forwards}
2681
+ .tw-draw-area{opacity:0;animation:tw-fade .9s ease .25s forwards}
2682
+ @keyframes tw-draw{to{stroke-dashoffset:0}}
2683
+ @keyframes tw-fade{to{opacity:1}}
2684
+ .tw-doughnut-wrap{display:grid;place-items:center;padding:6px 0 10px}
2685
+ .tw-legend{display:flex;flex-direction:column;gap:1px}
2686
+ .tw-legend-row{display:flex;align-items:center;gap:8px;padding:5px 7px;border-radius:6px;cursor:pointer}
2687
+ .tw-legend-row:hover,.tw-legend-row.on{background:#1b2128}
2688
+ .tw-legend-name{flex:1;font-size:12px;font-family:var(--mono);color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
2689
+ .tw-legend-val{font-size:12px;color:var(--muted);font-variant-numeric:tabular-nums}
2690
+ .tw-legend-pct{font-size:11px;color:var(--dim);width:30px;text-align:right;font-variant-numeric:tabular-nums}
2691
+ .tw-model-dot{width:8px;height:8px;border-radius:2px;flex-shrink:0}
2692
+ .tw-model-dot.lg{width:11px;height:11px;border-radius:3px}
2693
+ .tw-table-wrap{overflow-x:auto}
2694
+ .tw-table{width:100%;border-collapse:collapse;font-size:12.5px}
2695
+ .tw-table thead th{position:sticky;top:0;text-align:left;padding:8px 16px;
2696
+ font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;
2697
+ letter-spacing:.04em;border-bottom:1px solid var(--border);user-select:none;
2698
+ background:var(--surface)}
2699
+ .tw-th-inner{display:flex;align-items:center;gap:4px}
2700
+ .tw-th-inner:hover{color:var(--text)}
2701
+ .tw-sort{color:var(--accent);font-size:10px}
2702
+ .tw-row{border-bottom:1px solid var(--border-muted);cursor:pointer;transition:background .1s}
2703
+ .tw-row:last-child{border-bottom:0}
2704
+ .tw-row td{padding:10px 16px;vertical-align:middle}
2705
+ .tw-table.compact .tw-row td{padding:6px 16px}
2706
+ .tw-table.compact thead th{padding:6px 16px}
2707
+ .tw-row:hover{background:#1b2128}
2708
+ .tw-row.example{background:rgba(88,166,255,.07);box-shadow:inset 2px 0 0 var(--accent)}
2709
+ .tw-row.example:hover{background:rgba(88,166,255,.11)}
2710
+ .tw-model-cell{display:flex;align-items:center;gap:9px}
2711
+ .tw-model-name{font-family:var(--mono);font-size:12.5px;color:var(--text)}
2712
+ .tw-model-prov{font-size:10px;color:var(--muted);background:#22272e;border-radius:4px;padding:1px 5px}
2713
+ .tw-num-cell{text-align:right;font-variant-numeric:tabular-nums;color:var(--text);white-space:nowrap}
2714
+ .tw-cost{font-weight:600}
2715
+ .tw-row-actions{display:flex;gap:6px;justify-content:flex-end}
2716
+ .tw-row-actions button{height:24px;padding:0 9px;border:1px solid var(--border);
2717
+ background:var(--surface2);color:var(--text);border-radius:6px;font-size:11px;
2718
+ font-weight:500;cursor:pointer;font-family:var(--sans)}
2719
+ .tw-row-actions button:hover{border-color:var(--accent);color:var(--accent)}
2720
+ .tw-forecast{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;padding:0 16px 16px}
2721
+ .tw-fc{background:var(--surface2);border:1px solid var(--border);border-radius:9px;
2722
+ padding:12px 14px;display:flex;flex-direction:column;gap:6px}
2723
+ .tw-fc.flag{border-color:rgba(248,81,73,.5);background:rgba(248,81,73,.07)}
2724
+ .tw-fc-label{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.03em}
2725
+ .tw-fc-value{font-size:20px;font-weight:600;letter-spacing:-.01em}
2726
+ .tw-fc-sub{font-size:11.5px;color:var(--muted)}
2727
+ .tw-act-title{display:flex;align-items:center;gap:9px}
2728
+ .tw-collapse{border:0;background:transparent;color:var(--muted);cursor:pointer;
2729
+ display:grid;place-items:center;padding:2px;transition:transform .15s}
2730
+ .tw-live-dot{width:8px;height:8px;border-radius:50%;background:var(--dim)}
2731
+ .tw-live-dot.on{background:var(--green);animation:tw-pulse 1.6s ease-in-out infinite}
2732
+ @keyframes tw-pulse{0%,100%{box-shadow:0 0 0 0 rgba(63,185,80,.5)}50%{box-shadow:0 0 0 5px rgba(63,185,80,0)}}
2733
+ .tw-act-controls{display:flex;align-items:center;gap:10px}
2734
+ .tw-seg-sm{display:flex;gap:1px;background:var(--surface2);border:1px solid var(--border);border-radius:7px;padding:2px}
2735
+ .tw-seg-sm button{height:22px;padding:0 9px;border:0;background:transparent;color:var(--muted);
2736
+ font-size:11px;font-weight:600;border-radius:5px;cursor:pointer;font-family:var(--sans)}
2737
+ .tw-seg-sm button.on{background:var(--border);color:var(--text)}
2738
+ .tw-act-pause{height:26px;padding:0 10px;border:1px solid var(--border);background:var(--surface2);
2739
+ color:var(--muted);border-radius:6px;font-size:11.5px;cursor:pointer;font-family:var(--sans)}
2740
+ .tw-act-pause:hover{color:var(--text);border-color:#444c56}
2741
+ .tw-feed{padding:0 6px 8px}
2742
+ .tw-feed-head,.tw-feed-row{display:grid;grid-template-columns:72px 1.4fr 1fr 1fr 96px;gap:12px;align-items:center}
2743
+ .tw-feed-head{padding:6px 10px;font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--dim);border-bottom:1px solid var(--border-muted)}
2744
+ .tw-feed-body{display:flex;flex-direction:column}
2745
+ .tw-feed-row{padding:7px 10px;font-size:12px;border-bottom:1px solid var(--border-muted)}
2746
+ .tw-feed-row:last-child{border-bottom:0}
2747
+ .tw-feed-row.fresh{animation:tw-flash 1.4s ease}
2748
+ .tw-feed-row.err{background:rgba(248,81,73,.05)}
2749
+ @keyframes tw-flash{0%{background:rgba(88,166,255,.16)}100%{background:transparent}}
2750
+ .tw-feed-time{color:var(--muted);font-variant-numeric:tabular-nums}
2751
+ .tw-feed-model{display:flex;align-items:center;gap:7px;font-family:var(--mono);font-size:11.5px;color:var(--text);overflow:hidden}
2752
+ .tw-feed-sess{font-family:var(--mono);font-size:11.5px;color:var(--muted)}
2753
+ .tw-feed-cost{text-align:right;font-variant-numeric:tabular-nums;color:var(--text);font-weight:500;display:flex;align-items:center;justify-content:flex-end;gap:6px}
2754
+ .tw-feed-flag{font-size:9px;color:var(--red);border:1px solid rgba(248,81,73,.4);border-radius:4px;padding:0 4px;text-transform:uppercase}
2755
+ .tw-feed-flag.slow{color:var(--yellow);border-color:rgba(210,153,34,.4)}
2756
+ .tw-feat{font-size:10.5px;font-family:var(--mono);border:1px solid;border-radius:5px;padding:1px 6px;white-space:nowrap}
2757
+ .tw-feat.sm{font-size:10px;padding:0 5px}
2758
+ .tw-scrim{position:fixed;inset:0;background:rgba(1,4,9,.6);opacity:0;pointer-events:none;
2759
+ transition:opacity .25s;z-index:60}
2760
+ .tw-scrim.open{opacity:1;pointer-events:auto}
2761
+ .tw-slideover{position:fixed;top:0;right:0;height:100vh;width:400px;background:var(--surface);
2762
+ border-left:1px solid var(--border);transform:translateX(100%);transition:transform .28s cubic-bezier(.4,0,.2,1);
2763
+ z-index:61;box-shadow:-16px 0 40px rgba(0,0,0,.4);overflow-y:auto}
2764
+ .tw-slideover.open{transform:translateX(0)}
2765
+ .tw-so-inner{padding:18px}
2766
+ .tw-so-head{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;margin-bottom:16px}
2767
+ .tw-so-title{display:flex;align-items:center;gap:10px}
2768
+ .tw-so-name{font-family:var(--mono);font-size:15px;font-weight:600}
2769
+ .tw-so-prov{font-size:11.5px;color:var(--muted);margin-top:2px}
2770
+ .tw-so-close{width:28px;height:28px;border:1px solid var(--border);background:var(--surface2);
2771
+ color:var(--muted);border-radius:7px;cursor:pointer;font-size:13px}
2772
+ .tw-so-close:hover{color:var(--text);border-color:#444c56}
2773
+ .tw-so-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:12px}
2774
+ .tw-so-stat{background:var(--surface2);border:1px solid var(--border);border-radius:8px;padding:10px}
2775
+ .tw-so-stat-l{font-size:10.5px;color:var(--muted);text-transform:uppercase;letter-spacing:.03em;margin-bottom:5px}
2776
+ .tw-so-stat-v{font-size:16px;font-weight:600;font-variant-numeric:tabular-nums}
2777
+ .tw-so-metarow{display:flex;justify-content:space-between;padding:11px 12px;background:var(--surface2);
2778
+ border:1px solid var(--border);border-radius:8px;margin-bottom:16px}
2779
+ .tw-so-metarow>div{display:flex;flex-direction:column;gap:3px}
2780
+ .tw-so-meta-l{font-size:10.5px;color:var(--muted)}
2781
+ .tw-so-meta-v{font-size:12.5px;font-weight:500;font-variant-numeric:tabular-nums}
2782
+ .tw-so-section-label{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em;margin-bottom:8px}
2783
+ .tw-so-calls{display:flex;flex-direction:column;gap:7px;margin-bottom:14px}
2784
+ .tw-so-call{background:var(--surface2);border:1px solid var(--border);border-radius:8px;padding:9px 11px}
2785
+ .tw-so-call-top{display:flex;align-items:center;gap:9px;margin-bottom:5px}
2786
+ .tw-so-call-time{font-size:11px;color:var(--muted);flex:1}
2787
+ .tw-so-call-cost{font-size:12px;font-weight:600;font-variant-numeric:tabular-nums}
2788
+ .tw-so-call-bot{display:flex;justify-content:space-between;font-size:11px;color:var(--muted);font-variant-numeric:tabular-nums}
2789
+ .tw-so-viewall{width:100%;height:36px;border:1px solid var(--border);background:var(--surface2);
2790
+ color:var(--accent);border-radius:8px;font-size:12.5px;font-weight:600;cursor:pointer;font-family:var(--sans);
2791
+ display:flex;align-items:center;justify-content:center;gap:6px}
2792
+ .tw-so-viewall:hover{border-color:var(--accent);background:rgba(88,166,255,.08)}
2793
+ .tw-cmdk-scrim{position:fixed;inset:0;background:rgba(1,4,9,.55);z-index:80;
2794
+ display:flex;justify-content:center;align-items:flex-start;padding-top:14vh;
2795
+ animation:tw-fade .15s ease}
2796
+ .tw-cmdk{width:560px;max-width:92vw;background:var(--surface2);border:1px solid var(--border);
2797
+ border-radius:12px;box-shadow:0 24px 70px rgba(0,0,0,.6);overflow:hidden}
2798
+ .tw-cmdk-input{display:flex;align-items:center;gap:10px;padding:13px 15px;border-bottom:1px solid var(--border)}
2799
+ .tw-cmdk-input input{flex:1;background:transparent;border:0;outline:none;color:var(--text);
2800
+ font-size:14px;font-family:var(--sans)}
2801
+ .tw-cmdk-list{max-height:360px;overflow-y:auto;padding:6px}
2802
+ .tw-cmdk-item{display:flex;align-items:center;gap:11px;padding:9px 11px;border-radius:7px;cursor:pointer}
2803
+ .tw-cmdk-item:hover{background:#22272e}
2804
+ .tw-cmdk-g{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--dim);width:62px}
2805
+ .tw-cmdk-l{flex:1;font-size:13px}
2806
+ .tw-cmdk-empty{padding:18px;text-align:center;color:var(--muted);font-size:12.5px}
2807
+ .tw-skel-wrap{display:flex;flex-direction:column;gap:14px}
2808
+ .tw-skel{background:linear-gradient(90deg,var(--surface) 25%,#1b2128 50%,var(--surface) 75%);
2809
+ background-size:200% 100%;border:1px solid var(--border);border-radius:10px;
2810
+ animation:tw-shim 1.4s linear infinite}
2811
+ @keyframes tw-shim{to{background-position:-200% 0}}
2812
+ .tw-empty{display:flex;flex-direction:column;align-items:center;gap:12px;
2813
+ padding:80px 20px;text-align:center}
2814
+ .tw-empty-art{width:96px;height:96px;display:grid;place-items:center;
2815
+ background:var(--surface);border:1px solid var(--border);border-radius:20px}
2816
+ .tw-empty h2{font-size:18px}
2817
+ .tw-empty p{max-width:420px;color:var(--muted);font-size:13px;margin:0}
2818
+ .tw-empty-actions{display:flex;gap:10px;margin-top:6px}
2819
+ .tw-btn-primary{display:flex;align-items:center;gap:6px;height:34px;padding:0 14px;
2820
+ background:var(--accent);color:#0d1117;border:0;border-radius:8px;font-size:13px;
2821
+ font-weight:600;cursor:pointer;font-family:var(--sans)}
2822
+ .tw-btn-primary:hover{filter:brightness(1.08)}
2823
+ .tw-empty-snippet{margin-top:12px;font-family:var(--mono);font-size:12px;color:var(--muted);
2824
+ background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:10px 14px}
2825
+ .tw-snip-c{color:#ff7b72}.tw-snip-s{color:var(--green)}
2826
+ .tw-so-call-lat{font-variant-numeric:tabular-nums}
2827
+ @media(prefers-reduced-motion:reduce){*{animation-duration:.001s!important}}
2436
2828
 
2437
- :root {
2438
- --bg: #0d1117;
2439
- --surface: #161b22;
2440
- --border: #30363d;
2441
- --text: #e6edf3;
2442
- --muted: #8b949e;
2443
- --accent: #58a6ff;
2444
- --green: #3fb950;
2445
- --yellow: #d29922;
2446
- --red: #f85149;
2447
- --r: 6px;
2448
- }
2829
+ /* tweaks panel */
2830
+ .twk-panel{position:fixed;right:16px;bottom:16px;z-index:2147483646;width:280px;
2831
+ max-height:calc(100vh - 32px);display:flex;flex-direction:column;
2832
+ transform:scale(var(--dc-inv-zoom,1));transform-origin:bottom right;
2833
+ background:rgba(250,249,247,.78);color:#29261b;
2834
+ -webkit-backdrop-filter:blur(24px) saturate(160%);backdrop-filter:blur(24px) saturate(160%);
2835
+ border:.5px solid rgba(255,255,255,.6);border-radius:14px;
2836
+ box-shadow:0 1px 0 rgba(255,255,255,.5) inset,0 12px 40px rgba(0,0,0,.18);
2837
+ font:11.5px/1.4 ui-sans-serif,system-ui,-apple-system,sans-serif;overflow:hidden}
2838
+ .twk-hd{display:flex;align-items:center;justify-content:space-between;
2839
+ padding:10px 8px 10px 14px;cursor:move;user-select:none}
2840
+ .twk-hd b{font-size:12px;font-weight:600;letter-spacing:.01em}
2841
+ .twk-x{appearance:none;border:0;background:transparent;color:rgba(41,38,27,.55);
2842
+ width:22px;height:22px;border-radius:6px;cursor:default;font-size:13px;line-height:1}
2843
+ .twk-x:hover{background:rgba(0,0,0,.06);color:#29261b}
2844
+ .twk-body{padding:2px 14px 14px;display:flex;flex-direction:column;gap:10px;
2845
+ overflow-y:auto;overflow-x:hidden;min-height:0;
2846
+ scrollbar-width:thin;scrollbar-color:rgba(0,0,0,.15) transparent}
2847
+ .twk-body::-webkit-scrollbar{width:8px}
2848
+ .twk-body::-webkit-scrollbar-track{background:transparent;margin:2px}
2849
+ .twk-body::-webkit-scrollbar-thumb{background:rgba(0,0,0,.15);border-radius:4px;
2850
+ border:2px solid transparent;background-clip:content-box}
2851
+ .twk-row{display:flex;flex-direction:column;gap:5px}
2852
+ .twk-row-h{flex-direction:row;align-items:center;justify-content:space-between;gap:10px}
2853
+ .twk-lbl{display:flex;justify-content:space-between;align-items:baseline;color:rgba(41,38,27,.72)}
2854
+ .twk-lbl>span:first-child{font-weight:500}
2855
+ .twk-val{color:rgba(41,38,27,.5);font-variant-numeric:tabular-nums}
2856
+ .twk-sect{font-size:10px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;
2857
+ color:rgba(41,38,27,.45);padding:10px 0 0}
2858
+ .twk-sect:first-child{padding-top:0}
2859
+ .twk-field{appearance:none;box-sizing:border-box;width:100%;min-width:0;height:26px;padding:0 8px;
2860
+ border:.5px solid rgba(0,0,0,.1);border-radius:7px;
2861
+ background:rgba(255,255,255,.6);color:inherit;font:inherit;outline:none}
2862
+ .twk-field:focus{border-color:rgba(0,0,0,.25);background:rgba(255,255,255,.85)}
2863
+ select.twk-field{padding-right:22px}
2864
+ .twk-slider{appearance:none;-webkit-appearance:none;width:100%;height:4px;margin:6px 0;
2865
+ border-radius:999px;background:rgba(0,0,0,.12);outline:none}
2866
+ .twk-slider::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;
2867
+ width:14px;height:14px;border-radius:50%;background:#fff;
2868
+ border:.5px solid rgba(0,0,0,.12);box-shadow:0 1px 3px rgba(0,0,0,.2);cursor:default}
2869
+ .twk-seg{position:relative;display:flex;padding:2px;border-radius:8px;
2870
+ background:rgba(0,0,0,.06);user-select:none}
2871
+ .twk-seg-thumb{position:absolute;top:2px;bottom:2px;border-radius:6px;
2872
+ background:rgba(255,255,255,.9);box-shadow:0 1px 2px rgba(0,0,0,.12);
2873
+ transition:left .15s cubic-bezier(.3,.7,.4,1),width .15s}
2874
+ .twk-seg button{appearance:none;position:relative;z-index:1;flex:1;border:0;
2875
+ background:transparent;color:inherit;font:inherit;font-weight:500;min-height:22px;
2876
+ border-radius:6px;cursor:default;padding:4px 6px;line-height:1.2}
2877
+ .twk-toggle{position:relative;width:32px;height:18px;border:0;border-radius:999px;
2878
+ background:rgba(0,0,0,.15);transition:background .15s;cursor:default;padding:0}
2879
+ .twk-toggle[data-on="1"]{background:#34c759}
2880
+ .twk-toggle i{position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;
2881
+ background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.25);transition:transform .15s}
2882
+ .twk-toggle[data-on="1"] i{transform:translateX(14px)}
2883
+ .twk-chips{display:flex;gap:6px}
2884
+ .twk-chip{position:relative;appearance:none;flex:1;min-width:0;height:46px;
2885
+ padding:0;border:0;border-radius:6px;overflow:hidden;cursor:default;
2886
+ box-shadow:0 0 0 .5px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.06);transition:transform .12s}
2887
+ .twk-chip[data-on="1"]{box-shadow:0 0 0 1.5px rgba(0,0,0,.85),0 2px 6px rgba(0,0,0,.15)}
2888
+ .twk-chip>span{position:absolute;top:0;bottom:0;right:0;width:34%;display:flex;flex-direction:column}
2889
+ .twk-chip>span>i{flex:1}
2890
+ .twk-chip svg{position:absolute;top:6px;left:6px;width:13px;height:13px}
2891
+ .twk-swatch{appearance:none;-webkit-appearance:none;width:56px;height:22px;
2892
+ border:.5px solid rgba(0,0,0,.1);border-radius:6px;padding:0;cursor:default;background:transparent}
2893
+ .twk-swatch::-webkit-color-swatch-wrapper{padding:0}
2894
+ .twk-swatch::-webkit-color-swatch{border:0;border-radius:5.5px}
2895
+ </style>
2896
+ </head>
2897
+ <body>
2898
+ <div id="root"></div>
2899
+ <script src="https://unpkg.com/react@18.3.1/umd/react.production.min.js" crossorigin="anonymous"></script>
2900
+ <script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js" crossorigin="anonymous"></script>
2901
+ <script src="https://unpkg.com/@babel/standalone@7.29.0/babel.min.js" crossorigin="anonymous"></script>
2449
2902
 
2450
- body {
2451
- background: var(--bg);
2452
- color: var(--text);
2453
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
2454
- font-size: 14px;
2455
- line-height: 1.5;
2456
- min-height: 100vh;
2903
+ <script type="text/babel">
2904
+ // tweaks-panel \u2014 without runtime style injection (CSS is in the main style block)
2905
+ function useTweaks(defaults) {
2906
+ const [values, setValues] = React.useState(defaults);
2907
+ const setTweak = React.useCallback((keyOrEdits, val) => {
2908
+ const edits = typeof keyOrEdits === 'object' && keyOrEdits !== null
2909
+ ? keyOrEdits : { [keyOrEdits]: val };
2910
+ setValues((prev) => ({ ...prev, ...edits }));
2911
+ window.parent.postMessage({ type: '__edit_mode_set_keys', edits }, '*');
2912
+ window.dispatchEvent(new CustomEvent('tweakchange', { detail: edits }));
2913
+ }, []);
2914
+ return [values, setTweak];
2457
2915
  }
2458
2916
 
2459
- .container { max-width: 1200px; margin: 0 auto; padding: 24px 16px; }
2460
-
2461
- /* \u2500\u2500 Header \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2462
- header {
2463
- display: flex;
2464
- align-items: center;
2465
- justify-content: space-between;
2466
- margin-bottom: 24px;
2467
- }
2468
- header h1 { font-size: 18px; font-weight: 600; letter-spacing: -0.3px; }
2469
- header h1 span { color: var(--accent); }
2470
-
2471
- .live-badge {
2472
- display: flex;
2473
- align-items: center;
2474
- gap: 6px;
2475
- font-size: 12px;
2476
- color: var(--muted);
2477
- }
2478
- .live-dot {
2479
- width: 8px; height: 8px;
2480
- border-radius: 50%;
2481
- background: var(--green);
2482
- animation: pulse 2s ease-in-out infinite;
2483
- }
2484
- @keyframes pulse {
2485
- 0%, 100% { opacity: 1; }
2486
- 50% { opacity: 0.3; }
2917
+ function TweaksPanel({ title = 'Tweaks', children }) {
2918
+ const [open, setOpen] = React.useState(false);
2919
+ const dragRef = React.useRef(null);
2920
+ const offsetRef = React.useRef({ x: 16, y: 16 });
2921
+ const PAD = 16;
2922
+ const clampToViewport = React.useCallback(() => {
2923
+ const panel = dragRef.current; if (!panel) return;
2924
+ const w = panel.offsetWidth, h = panel.offsetHeight;
2925
+ offsetRef.current = {
2926
+ x: Math.min(Math.max(PAD, window.innerWidth - w - PAD), Math.max(PAD, offsetRef.current.x)),
2927
+ y: Math.min(Math.max(PAD, window.innerHeight - h - PAD), Math.max(PAD, offsetRef.current.y)),
2928
+ };
2929
+ panel.style.right = offsetRef.current.x + 'px';
2930
+ panel.style.bottom = offsetRef.current.y + 'px';
2931
+ }, []);
2932
+ React.useEffect(() => {
2933
+ if (!open) return;
2934
+ clampToViewport();
2935
+ const ro = new ResizeObserver(clampToViewport);
2936
+ ro.observe(document.documentElement);
2937
+ return () => ro.disconnect();
2938
+ }, [open, clampToViewport]);
2939
+ React.useEffect(() => {
2940
+ const onMsg = (e) => {
2941
+ const t = e && e.data && e.data.type;
2942
+ if (t === '__activate_edit_mode') setOpen(true);
2943
+ else if (t === '__deactivate_edit_mode') setOpen(false);
2944
+ };
2945
+ window.addEventListener('message', onMsg);
2946
+ window.parent.postMessage({ type: '__edit_mode_available' }, '*');
2947
+ return () => window.removeEventListener('message', onMsg);
2948
+ }, []);
2949
+ const dismiss = () => { setOpen(false); window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*'); };
2950
+ const onDragStart = (e) => {
2951
+ const panel = dragRef.current; if (!panel) return;
2952
+ const r = panel.getBoundingClientRect();
2953
+ const sx = e.clientX, sy = e.clientY;
2954
+ const startRight = window.innerWidth - r.right, startBottom = window.innerHeight - r.bottom;
2955
+ const move = (ev) => { offsetRef.current = { x: startRight - (ev.clientX - sx), y: startBottom - (ev.clientY - sy) }; clampToViewport(); };
2956
+ const up = () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); };
2957
+ window.addEventListener('mousemove', move); window.addEventListener('mouseup', up);
2958
+ };
2959
+ if (!open) return null;
2960
+ return (
2961
+ <div ref={dragRef} className="twk-panel" style={{ right: offsetRef.current.x, bottom: offsetRef.current.y }}>
2962
+ <div className="twk-hd" onMouseDown={onDragStart}>
2963
+ <b>{title}</b>
2964
+ <button className="twk-x" onMouseDown={(e) => e.stopPropagation()} onClick={dismiss}>&#x2715;</button>
2965
+ </div>
2966
+ <div className="twk-body">{children}</div>
2967
+ </div>
2968
+ );
2487
2969
  }
2488
-
2489
- /* \u2500\u2500 Tabs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2490
- .tabs {
2491
- display: flex;
2492
- gap: 4px;
2493
- margin-bottom: 24px;
2494
- background: var(--surface);
2495
- border: 1px solid var(--border);
2496
- border-radius: var(--r);
2497
- padding: 4px;
2498
- width: fit-content;
2499
- }
2500
- .tab {
2501
- padding: 6px 14px;
2502
- border-radius: calc(var(--r) - 2px);
2503
- border: none;
2504
- background: transparent;
2505
- color: var(--muted);
2506
- font-size: 13px;
2507
- font-weight: 500;
2508
- cursor: pointer;
2509
- transition: background 0.15s, color 0.15s;
2510
- }
2511
- .tab:hover { color: var(--text); background: rgba(255,255,255,0.05); }
2512
- .tab.active { background: var(--accent); color: #fff; }
2513
-
2514
- /* \u2500\u2500 Overview cards \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2515
- .cards {
2516
- display: grid;
2517
- grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
2518
- gap: 12px;
2519
- margin-bottom: 24px;
2520
- }
2521
- .card {
2522
- background: var(--surface);
2523
- border: 1px solid var(--border);
2524
- border-radius: var(--r);
2525
- padding: 16px;
2526
- }
2527
- .card-label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--muted); margin-bottom: 6px; }
2528
- .card-value { font-size: 22px; font-weight: 700; color: var(--text); font-variant-numeric: tabular-nums; }
2529
- .card-sub { font-size: 11px; color: var(--muted); margin-top: 3px; }
2530
-
2531
- /* \u2500\u2500 Chart section \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2532
- .charts {
2533
- display: grid;
2534
- grid-template-columns: 2fr 1fr;
2535
- gap: 16px;
2536
- margin-bottom: 24px;
2537
- }
2538
- @media (max-width: 768px) { .charts { grid-template-columns: 1fr; } }
2539
-
2540
- .panel {
2541
- background: var(--surface);
2542
- border: 1px solid var(--border);
2543
- border-radius: var(--r);
2544
- padding: 16px;
2545
- }
2546
- .panel-title {
2547
- font-size: 12px;
2548
- font-weight: 600;
2549
- text-transform: uppercase;
2550
- letter-spacing: 0.5px;
2551
- color: var(--muted);
2552
- margin-bottom: 14px;
2553
- }
2554
- .chart-wrap { position: relative; height: 220px; }
2555
-
2556
- /* \u2500\u2500 Breakdown tables \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2557
- .section { margin-bottom: 24px; }
2558
- .section-title {
2559
- font-size: 12px;
2560
- font-weight: 600;
2561
- text-transform: uppercase;
2562
- letter-spacing: 0.5px;
2563
- color: var(--muted);
2564
- margin-bottom: 10px;
2970
+ function TweakSection({ label }) { return <div className="twk-sect">{label}</div>; }
2971
+ function TweakRow({ label, value, children, inline }) {
2972
+ return (
2973
+ <div className={inline ? 'twk-row twk-row-h' : 'twk-row'}>
2974
+ <div className="twk-lbl"><span>{label}</span>{value != null && <span className="twk-val">{value}</span>}</div>
2975
+ {children}
2976
+ </div>
2977
+ );
2565
2978
  }
2566
-
2567
- table {
2568
- width: 100%;
2569
- border-collapse: collapse;
2570
- background: var(--surface);
2571
- border: 1px solid var(--border);
2572
- border-radius: var(--r);
2573
- overflow: hidden;
2574
- font-size: 13px;
2575
- }
2576
- thead { background: rgba(255,255,255,0.03); }
2577
- th {
2578
- padding: 10px 14px;
2579
- text-align: left;
2580
- font-weight: 600;
2581
- color: var(--muted);
2582
- font-size: 11px;
2583
- text-transform: uppercase;
2584
- letter-spacing: 0.4px;
2585
- border-bottom: 1px solid var(--border);
2586
- }
2587
- th.num, td.num { text-align: right; }
2588
- td {
2589
- padding: 10px 14px;
2590
- border-bottom: 1px solid rgba(48,54,61,0.5);
2591
- font-variant-numeric: tabular-nums;
2592
- color: var(--text);
2593
- }
2594
- tbody tr:last-child td { border-bottom: none; }
2595
- tbody tr:hover td { background: rgba(255,255,255,0.02); }
2596
-
2597
- .bar-wrap { width: 80px; height: 6px; background: var(--border); border-radius: 3px; display: inline-block; vertical-align: middle; margin-left: 8px; }
2598
- .bar-fill { height: 100%; border-radius: 3px; background: var(--accent); }
2599
-
2600
- /* \u2500\u2500 Forecast \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2601
- .forecast-grid {
2602
- display: grid;
2603
- grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
2604
- gap: 12px;
2979
+ function TweakSlider({ label, value, min=0, max=100, step=1, unit='', onChange }) {
2980
+ return (
2981
+ <TweakRow label={label} value={value + unit}>
2982
+ <input type="range" className="twk-slider" min={min} max={max} step={step} value={value} onChange={(e) => onChange(Number(e.target.value))} />
2983
+ </TweakRow>
2984
+ );
2605
2985
  }
2606
-
2607
- /* \u2500\u2500 Empty state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2608
- .empty {
2609
- color: var(--muted);
2610
- font-size: 13px;
2611
- padding: 20px 0;
2612
- text-align: center;
2986
+ function TweakToggle({ label, value, onChange }) {
2987
+ return (
2988
+ <div className="twk-row twk-row-h">
2989
+ <div className="twk-lbl"><span>{label}</span></div>
2990
+ <button type="button" className="twk-toggle" data-on={value ? '1' : '0'} onClick={() => onChange(!value)}><i /></button>
2991
+ </div>
2992
+ );
2613
2993
  }
2614
-
2615
- /* \u2500\u2500 Collapsible \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2616
- details summary {
2617
- cursor: pointer;
2618
- list-style: none;
2619
- display: flex;
2620
- align-items: center;
2621
- gap: 6px;
2622
- font-size: 12px;
2623
- font-weight: 600;
2624
- text-transform: uppercase;
2625
- letter-spacing: 0.5px;
2626
- color: var(--muted);
2627
- margin-bottom: 10px;
2628
- user-select: none;
2629
- }
2630
- details summary::before { content: '\u25B6'; font-size: 10px; transition: transform 0.15s; }
2631
- details[open] summary::before { transform: rotate(90deg); }
2632
-
2633
- /* \u2500\u2500 Last updated \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
2634
- .footer {
2635
- font-size: 11px;
2636
- color: var(--muted);
2637
- text-align: center;
2638
- padding: 16px 0 0;
2994
+ function TweakSelect({ label, value, options, onChange }) {
2995
+ return (
2996
+ <TweakRow label={label}>
2997
+ <select className="twk-field" value={value} onChange={(e) => onChange(e.target.value)}>
2998
+ {options.map((o) => { const v = typeof o === 'object' ? o.value : o; const l = typeof o === 'object' ? o.label : o; return <option key={v} value={v}>{l}</option>; })}
2999
+ </select>
3000
+ </TweakRow>
3001
+ );
2639
3002
  }
2640
- </style>
2641
- </head>
2642
- <body>
2643
- <div class="container">
3003
+ function TweakRadio({ label, value, options, onChange }) {
3004
+ const trackRef = React.useRef(null);
3005
+ const [dragging, setDragging] = React.useState(false);
3006
+ const valueRef = React.useRef(value); valueRef.current = value;
3007
+ const labelLen = (o) => String(typeof o === 'object' ? o.label : o).length;
3008
+ const maxLen = options.reduce((m, o) => Math.max(m, labelLen(o)), 0);
3009
+ const fitsAsSegments = maxLen <= ({ 2: 16, 3: 10 }[options.length] || 0);
3010
+ if (!fitsAsSegments) {
3011
+ const resolve = (s) => { const m = options.find((o) => String(typeof o === 'object' ? o.value : o) === s); return m === undefined ? s : typeof m === 'object' ? m.value : m; };
3012
+ return <TweakSelect label={label} value={value} options={options} onChange={(s) => onChange(resolve(s))} />;
3013
+ }
3014
+ const opts = options.map((o) => (typeof o === 'object' ? o : { value: o, label: o }));
3015
+ const idx = Math.max(0, opts.findIndex((o) => o.value === value));
3016
+ const n = opts.length;
3017
+ const segAt = (clientX) => {
3018
+ const r = trackRef.current.getBoundingClientRect();
3019
+ const i = Math.floor(((clientX - r.left - 2) / (r.width - 4)) * n);
3020
+ return opts[Math.max(0, Math.min(n - 1, i))].value;
3021
+ };
3022
+ const onPointerDown = (e) => {
3023
+ setDragging(true);
3024
+ const v0 = segAt(e.clientX); if (v0 !== valueRef.current) onChange(v0);
3025
+ const move = (ev) => { if (!trackRef.current) return; const v = segAt(ev.clientX); if (v !== valueRef.current) onChange(v); };
3026
+ const up = () => { setDragging(false); window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
3027
+ window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
3028
+ };
3029
+ return (
3030
+ <TweakRow label={label}>
3031
+ <div ref={trackRef} role="radiogroup" onPointerDown={onPointerDown} className={dragging ? 'twk-seg dragging' : 'twk-seg'}>
3032
+ <div className="twk-seg-thumb" style={{ left: 'calc(2px + ' + idx + ' * (100% - 4px) / ' + n + ')', width: 'calc((100% - 4px) / ' + n + ')' }} />
3033
+ {opts.map((o) => <button key={o.value} type="button" role="radio" aria-checked={o.value === value}>{o.label}</button>)}
3034
+ </div>
3035
+ </TweakRow>
3036
+ );
3037
+ }
3038
+ function __twkIsLight(hex) {
3039
+ const h = String(hex).replace('#', '');
3040
+ const x = h.length === 3 ? h.replace(/./g, (c) => c + c) : h.padEnd(6, '0');
3041
+ const n = parseInt(x.slice(0, 6), 16);
3042
+ if (Number.isNaN(n)) return true;
3043
+ const r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
3044
+ return r * 299 + g * 587 + b * 114 > 148000;
3045
+ }
3046
+ const __TwkCheck = ({ light }) => (
3047
+ <svg viewBox="0 0 14 14" aria-hidden="true">
3048
+ <path d="M3 7.2 5.8 10 11 4.2" fill="none" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" stroke={light ? 'rgba(0,0,0,.78)' : '#fff'} />
3049
+ </svg>
3050
+ );
3051
+ function TweakColor({ label, value, options, onChange }) {
3052
+ if (!options || !options.length) {
3053
+ return (
3054
+ <div className="twk-row twk-row-h">
3055
+ <div className="twk-lbl"><span>{label}</span></div>
3056
+ <input type="color" className="twk-swatch" value={value} onChange={(e) => onChange(e.target.value)} />
3057
+ </div>
3058
+ );
3059
+ }
3060
+ const key = (o) => String(JSON.stringify(o)).toLowerCase();
3061
+ const cur = key(value);
3062
+ return (
3063
+ <TweakRow label={label}>
3064
+ <div className="twk-chips" role="radiogroup">
3065
+ {options.map((o, i) => {
3066
+ const colors = Array.isArray(o) ? o : [o];
3067
+ const [hero, ...rest] = colors;
3068
+ const sup = rest.slice(0, 4);
3069
+ const on = key(o) === cur;
3070
+ return (
3071
+ <button key={i} type="button" className="twk-chip" role="radio" data-on={on ? '1' : '0'} style={{ background: hero }} onClick={() => onChange(o)}>
3072
+ {sup.length > 0 && <span>{sup.map((c, j) => <i key={j} style={{ background: c }} />)}</span>}
3073
+ {on && <__TwkCheck light={__twkIsLight(hero)} />}
3074
+ </button>
3075
+ );
3076
+ })}
3077
+ </div>
3078
+ </TweakRow>
3079
+ );
3080
+ }
3081
+ Object.assign(window, { useTweaks, TweaksPanel, TweakSection, TweakRow, TweakSlider, TweakToggle, TweakRadio, TweakSelect, TweakColor });
3082
+ </script>
2644
3083
 
2645
- <header>
2646
- <h1>token<span>watch</span></h1>
2647
- <div class="live-badge">
2648
- <div class="live-dot"></div>
2649
- <span id="live-label">live</span>
3084
+ <script type="text/babel">
3085
+ // tw-charts.jsx
3086
+ const { useRef, useState, useEffect, useLayoutEffect } = React;
3087
+ function useMeasure() {
3088
+ const ref = useRef(null);
3089
+ const [w, setW] = useState(0);
3090
+ useLayoutEffect(() => {
3091
+ if (!ref.current) return;
3092
+ const ro = new ResizeObserver((es) => setW(es[0].contentRect.width));
3093
+ ro.observe(ref.current);
3094
+ setW(ref.current.clientWidth);
3095
+ return () => ro.disconnect();
3096
+ }, []);
3097
+ return [ref, w];
3098
+ }
3099
+ function useCountUp(target, { duration = 700, enabled = true, decimals = 0 } = {}) {
3100
+ const [val, setVal] = useState(enabled ? 0 : target);
3101
+ const fromRef = useRef(enabled ? 0 : target);
3102
+ useEffect(() => {
3103
+ if (!enabled) { setVal(target); return; }
3104
+ const from = fromRef.current, start = performance.now();
3105
+ let raf;
3106
+ const tick = (t) => {
3107
+ const p = Math.min(1, (t - start) / duration);
3108
+ const e = 1 - Math.pow(1 - p, 3);
3109
+ setVal(from + (target - from) * e);
3110
+ if (p < 1) raf = requestAnimationFrame(tick);
3111
+ else fromRef.current = target;
3112
+ };
3113
+ raf = requestAnimationFrame(tick);
3114
+ return () => cancelAnimationFrame(raf);
3115
+ }, [target, enabled, duration]);
3116
+ return val;
3117
+ }
3118
+ function LineChart({ current, previous, n, color = '#58a6ff', compare = false, animate = true, fmt }) {
3119
+ const [ref, w] = useMeasure();
3120
+ const [hover, setHover] = useState(null);
3121
+ const H = 248, padT = 16, padB = 26, padL = 8, padR = 8;
3122
+ const innerW = Math.max(1, w - padL - padR), innerH = H - padT - padB;
3123
+ const series = compare && previous ? [...current, ...previous] : current;
3124
+ const max = Math.max(...series, 0.0001) * 1.18;
3125
+ const X = (i) => padL + (i / Math.max(n - 1, 1)) * innerW;
3126
+ const Y = (v) => padT + innerH - (v / max) * innerH;
3127
+ const path = (arr) => arr.map((v, i) => (i ? 'L' : 'M') + X(i).toFixed(1) + ' ' + Y(v).toFixed(1)).join(' ');
3128
+ const area = (arr) => path(arr) + ' L' + X(n - 1).toFixed(1) + ' ' + (padT + innerH).toFixed(1) + ' L' + padL.toFixed(1) + ' ' + (padT + innerH).toFixed(1) + ' Z';
3129
+ const gid = 'lg' + color.replace('#', '');
3130
+ const onMove = (e) => {
3131
+ const r = e.currentTarget.getBoundingClientRect();
3132
+ const x = e.clientX - r.left - padL;
3133
+ const i = Math.max(0, Math.min(n - 1, Math.round((x / innerW) * (n - 1))));
3134
+ setHover(i);
3135
+ };
3136
+ return (
3137
+ <div ref={ref} style={{ position: 'relative', width: '100%' }}>
3138
+ {w > 0 && (
3139
+ <svg width={w} height={H} onMouseMove={onMove} onMouseLeave={() => setHover(null)} style={{ display: 'block', cursor: 'crosshair' }}>
3140
+ <defs>
3141
+ <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
3142
+ <stop offset="0%" stopColor={color} stopOpacity="0.22" />
3143
+ <stop offset="100%" stopColor={color} stopOpacity="0" />
3144
+ </linearGradient>
3145
+ </defs>
3146
+ {[0.25, 0.5, 0.75, 1].map((g, i) => (
3147
+ <line key={i} x1={padL} x2={w - padR} y1={padT + innerH * g} y2={padT + innerH * g} stroke="#21262d" strokeWidth="1" />
3148
+ ))}
3149
+ {current.length > 1 && <path d={area(current)} fill={'url(#' + gid + ')'} className={animate ? 'tw-draw-area' : ''} />}
3150
+ {compare && previous && previous.length > 1 && (
3151
+ <path d={path(previous)} fill="none" stroke="#6e7681" strokeWidth="1.6" strokeDasharray="5 4" opacity="0.85" />
3152
+ )}
3153
+ {current.length > 1 && <path d={path(current)} fill="none" stroke={color} strokeWidth="2.2" strokeLinejoin="round" strokeLinecap="round" className={animate ? 'tw-draw-line' : ''} />}
3154
+ {hover != null && (
3155
+ <g>
3156
+ <line x1={X(hover)} x2={X(hover)} y1={padT} y2={padT + innerH} stroke="#484f58" strokeWidth="1" strokeDasharray="3 3" />
3157
+ {compare && previous && previous[hover] != null && <circle cx={X(hover)} cy={Y(previous[hover])} r="3.5" fill="#21262d" stroke="#6e7681" strokeWidth="1.6" />}
3158
+ <circle cx={X(hover)} cy={Y(current[hover])} r="4.5" fill="#0d1117" stroke={color} strokeWidth="2.2" />
3159
+ </g>
3160
+ )}
3161
+ </svg>
3162
+ )}
3163
+ {hover != null && w > 0 && (
3164
+ <div style={{ position: 'absolute', top: 6, pointerEvents: 'none', left: Math.min(Math.max(X(hover) - 70, 4), w - 144), width: 140, background: '#1c2128', border: '1px solid #30363d', borderRadius: 6, padding: '6px 8px', fontSize: 11, boxShadow: '0 6px 20px rgba(0,0,0,.5)' }}>
3165
+ <div style={{ color: '#7d8590', marginBottom: 3 }}>point {hover + 1}/{n}</div>
3166
+ <div style={{ display: 'flex', justifyContent: 'space-between', color: '#e6edf3', fontVariantNumeric: 'tabular-nums' }}>
3167
+ <span style={{ color }}>&#9679; current</span><b>{fmt ? fmt(current[hover]) : current[hover].toFixed(4)}</b>
3168
+ </div>
3169
+ {compare && previous && previous[hover] != null && (
3170
+ <div style={{ display: 'flex', justifyContent: 'space-between', color: '#8b949e', fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>
3171
+ <span>&#9675; previous</span><span>{fmt ? fmt(previous[hover]) : previous[hover].toFixed(4)}</span>
3172
+ </div>
3173
+ )}
3174
+ </div>
3175
+ )}
2650
3176
  </div>
2651
- </header>
2652
-
2653
- <div class="tabs">
2654
- <button class="tab" data-filter="1h">1h</button>
2655
- <button class="tab active" data-filter="24h">24h</button>
2656
- <button class="tab" data-filter="7d">7d</button>
2657
- <button class="tab" data-filter="30d">30d</button>
2658
- <button class="tab" data-filter="all">All</button>
2659
- </div>
3177
+ );
3178
+ }
3179
+ function Doughnut({ data, total, fmt, active, onHover }) {
3180
+ const size = 188, stroke = 26, r = (size - stroke) / 2, c = 2 * Math.PI * r;
3181
+ let acc = 0;
3182
+ const safeTotal = total || 0.0001;
3183
+ return (
3184
+ <svg width={size} height={size} viewBox={'0 0 ' + size + ' ' + size}>
3185
+ <g transform={'rotate(-90 ' + (size / 2) + ' ' + (size / 2) + ')'}>
3186
+ {data.map((d) => {
3187
+ const frac = d.cost / safeTotal;
3188
+ const dash = frac * c;
3189
+ const seg = (
3190
+ <circle key={d.id} cx={size / 2} cy={size / 2} r={r} fill="none"
3191
+ stroke={d.color} strokeWidth={active === d.id ? stroke + 5 : stroke}
3192
+ strokeDasharray={dash + ' ' + (c - dash)} strokeDashoffset={-acc}
3193
+ opacity={active && active !== d.id ? 0.32 : 1}
3194
+ style={{ transition: 'opacity .15s, stroke-width .15s', cursor: 'pointer' }}
3195
+ onMouseEnter={() => onHover && onHover(d.id)} onMouseLeave={() => onHover && onHover(null)} />
3196
+ );
3197
+ acc += dash;
3198
+ return seg;
3199
+ })}
3200
+ </g>
3201
+ <text x="50%" y="46%" textAnchor="middle" fill="#7d8590" fontSize="11" style={{ textTransform: 'uppercase', letterSpacing: '.05em' }}>
3202
+ {active ? ((data.find((d) => d.id === active) || {}).id || 'total') : 'total'}
3203
+ </text>
3204
+ <text x="50%" y="58%" textAnchor="middle" fill="#e6edf3" fontSize="20" fontWeight="600" style={{ fontVariantNumeric: 'tabular-nums' }}>
3205
+ {active ? fmt(((data.find((d) => d.id === active) || {}).cost) || 0) : fmt(total)}
3206
+ </text>
3207
+ </svg>
3208
+ );
3209
+ }
3210
+ function Sparkline({ data, color = '#58a6ff', w = 92, h = 30 }) {
3211
+ if (!data || data.length < 2) return null;
3212
+ const max = Math.max(...data, 0.0001), min = Math.min(...data);
3213
+ const X = (i) => (i / (data.length - 1)) * w;
3214
+ const Y = (v) => h - 2 - ((v - min) / (max - min || 1)) * (h - 4);
3215
+ const d = data.map((v, i) => (i ? 'L' : 'M') + X(i).toFixed(1) + ' ' + Y(v).toFixed(1)).join(' ');
3216
+ return (
3217
+ <svg width={w} height={h} style={{ display: 'block' }}>
3218
+ <path d={d + ' L' + w + ' ' + h + ' L0 ' + h + ' Z'} fill={color} opacity="0.12" />
3219
+ <path d={d} fill="none" stroke={color} strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" />
3220
+ </svg>
3221
+ );
3222
+ }
3223
+ function ShareBar({ frac, color }) {
3224
+ return (
3225
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
3226
+ <div style={{ flex: 1, height: 6, background: '#21262d', borderRadius: 3, overflow: 'hidden', minWidth: 40 }}>
3227
+ <div style={{ width: (frac * 100).toFixed(1) + '%', height: '100%', background: color, borderRadius: 3, transition: 'width .4s' }} />
3228
+ </div>
3229
+ <span style={{ color: '#7d8590', fontSize: 11, width: 34, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{(frac * 100).toFixed(1)}%</span>
3230
+ </div>
3231
+ );
3232
+ }
3233
+ Object.assign(window, { useMeasure, useCountUp, LineChart, Doughnut, Sparkline, ShareBar });
3234
+ </script>
2660
3235
 
2661
- <div class="cards">
2662
- <div class="card">
2663
- <div class="card-label">Total Cost</div>
2664
- <div class="card-value" id="card-cost">\u2014</div>
2665
- <div class="card-sub" id="card-period"></div>
3236
+ <script type="text/babel">
3237
+ // tw-cards.jsx
3238
+ const { useState: useStateC } = React;
3239
+ const Ico = {
3240
+ chevron: (p) => <svg width="12" height="12" viewBox="0 0 12 12" {...p}><path d="M3 4.5 6 7.5 9 4.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>,
3241
+ search: (p) => <svg width="14" height="14" viewBox="0 0 14 14" {...p}><circle cx="6" cy="6" r="4.2" fill="none" stroke="currentColor" strokeWidth="1.5" /><path d="M9.2 9.2 12 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /></svg>,
3242
+ download: (p) => <svg width="13" height="13" viewBox="0 0 14 14" {...p}><path d="M7 1.5v7m0 0 2.6-2.6M7 8.5 4.4 5.9M2 11.5h10" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>,
3243
+ bolt: (p) => <svg width="12" height="12" viewBox="0 0 12 12" {...p}><path d="M7 1 2.5 7H5l-.5 4L9 5H6.5z" fill="currentColor" /></svg>,
3244
+ arrow: (p) => <svg width="12" height="12" viewBox="0 0 12 12" {...p}><path d="M2.5 6h7m0 0L7 3.5M9.5 6 7 8.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>,
3245
+ warn: (p) => <svg width="13" height="13" viewBox="0 0 14 14" {...p}><path d="M7 1.5 13 12H1z" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" /><path d="M7 5.5v3M7 10.2v.1" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" /></svg>,
3246
+ check: (p) => <svg width="13" height="13" viewBox="0 0 14 14" {...p}><path d="M2.5 7.5 5.5 10.5 11.5 3.5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg>,
3247
+ };
3248
+ function Header({ t, onOpenPalette }) {
3249
+ const [wsOpen, setWsOpen] = useStateC(false);
3250
+ const nav = ['Overview', 'Sessions', 'Users', 'Features', 'Settings'];
3251
+ return (
3252
+ <header className="tw-header">
3253
+ <div className="tw-hgroup">
3254
+ <div className="tw-logo">token<span>watch</span></div>
3255
+ <button className="tw-ws" onClick={() => setWsOpen((v) => !v)}>
3256
+ <span className="tw-ws-dot" />
3257
+ <span>tokenwatch</span>
3258
+ <span className="tw-ws-env">local</span>
3259
+ <Ico.chevron style={{ color: '#7d8590' }} />
3260
+ </button>
3261
+ <nav className="tw-nav">
3262
+ {nav.map((n, i) => <a key={n} className={i === 0 ? 'on' : ''} href="#" onClick={(e) => e.preventDefault()}>{n}</a>)}
3263
+ </nav>
3264
+ </div>
3265
+ <div className="tw-hgroup">
3266
+ {t.commandPalette && (
3267
+ <button className="tw-search" onClick={onOpenPalette}>
3268
+ <Ico.search style={{ color: '#7d8590' }} />
3269
+ <span>Search</span>
3270
+ <kbd>&#8984;K</kbd>
3271
+ </button>
3272
+ )}
3273
+ <button className="tw-btn-2"><Ico.download /> Export CSV</button>
3274
+ </div>
3275
+ </header>
3276
+ );
3277
+ }
3278
+ function BudgetBar({ t }) {
3279
+ const { BUDGET, fmtMoney } = window.TW;
3280
+ const { used, limit, daysLeft, cycleDays } = BUDGET;
3281
+ const pct = Math.min(used / Math.max(limit, 0.0001), 1);
3282
+ const elapsed = cycleDays - daysLeft;
3283
+ const barColor = pct < 0.5 ? '#3fb950' : pct < 0.8 ? '#d29922' : '#f85149';
3284
+ const projectedDaily = used / Math.max(elapsed, 1);
3285
+ const projected = used + projectedDaily * daysLeft;
3286
+ const projPct = Math.min(projected / Math.max(limit, 0.0001), 1);
3287
+ return (
3288
+ <div className="tw-budget">
3289
+ <div className="tw-budget-top">
3290
+ <div className="tw-budget-label">
3291
+ <span className="tw-bud-strong">Monthly budget</span>
3292
+ <span className="tw-bud-nums"><b>{fmtMoney(used)}</b> used of {fmtMoney(limit)}</span>
3293
+ </div>
3294
+ {t.budgetAlerts && (
3295
+ <div className="tw-bud-alert ok">
3296
+ <Ico.check style={{ color: '#3fb950' }} />
3297
+ Projected <b>{fmtMoney(projected)}</b> by cycle end
3298
+ </div>
3299
+ )}
3300
+ <div className="tw-budget-days">{daysLeft} days left &middot; day {elapsed}/{cycleDays}</div>
3301
+ </div>
3302
+ <div className="tw-bar">
3303
+ <div className="tw-bar-fill" style={{ width: (pct * 100) + '%', background: barColor }} />
3304
+ {t.budgetAlerts && <div className="tw-bar-proj" style={{ left: (pct * 100) + '%', width: ((projPct - pct) * 100) + '%' }} />}
3305
+ {t.budgetAlerts && <div className="tw-bar-marker" style={{ left: (projPct * 100) + '%' }} data-tip={'proj ' + fmtMoney(projected)} />}
3306
+ </div>
2666
3307
  </div>
2667
- <div class="card">
2668
- <div class="card-label">Input Tokens</div>
2669
- <div class="card-value" id="card-input">\u2014</div>
3308
+ );
3309
+ }
3310
+ function KpiCard({ label, value, sub, delta, deltaColor, spark, sparkColor, t }) {
3311
+ return (
3312
+ <div className="tw-kpi">
3313
+ <div className="tw-kpi-label">{label}</div>
3314
+ <div className="tw-kpi-main">
3315
+ <div className="tw-kpi-value">{value}</div>
3316
+ {t.kpiSparklines && spark && spark.length >= 2 && <Sparkline data={spark} color={sparkColor} w={84} h={28} />}
3317
+ </div>
3318
+ <div className="tw-kpi-foot">
3319
+ {delta && <span className="tw-delta" style={{ color: t.smartHighlight ? deltaColor : '#7d8590' }}>{delta}</span>}
3320
+ {sub && <span className="tw-kpi-sub">{sub}</span>}
3321
+ </div>
2670
3322
  </div>
2671
- <div class="card">
2672
- <div class="card-label">Output Tokens</div>
2673
- <div class="card-value" id="card-output">\u2014</div>
3323
+ );
3324
+ }
3325
+ function KpiRow({ kpis, range, t }) {
3326
+ const { fmtUSD, fmtInt, seriesForRange } = window.TW;
3327
+ const s = seriesForRange(range).current;
3328
+ const callsSeries = s.map((v, i) => 6 + Math.abs(Math.sin(i * 1.7)) * 14);
3329
+ return (
3330
+ <div className="tw-kpis">
3331
+ <KpiCard t={t} label="Total cost" value={fmtUSD(kpis.cost)} delta="&#x2191; 12% vs last week" deltaColor="#f85149" spark={s} sparkColor="#58a6ff" />
3332
+ <KpiCard t={t} label="Input tokens" value={fmtInt(kpis.inTok)} sub="tokens in" spark={s} sparkColor="#3fb950" />
3333
+ <KpiCard t={t} label="Output tokens" value={fmtInt(kpis.outTok)} sub="tokens out" spark={s.map((v) => v * 0.9)} sparkColor="#bc8cff" />
3334
+ <KpiCard t={t} label="Total calls" value={fmtInt(kpis.calls)} delta="&#x2193; 5% vs last week" deltaColor="#3fb950" spark={callsSeries} sparkColor="#56d4dd" />
3335
+ <KpiCard t={t} label="Burn rate" value={fmtUSD(kpis.burnHr, 4) + '/hr'} sub={'proj ' + fmtUSD(kpis.burnHr * 24, 2) + '/day'} spark={s.map((v) => v * 1.05)} sparkColor="#e3b341" />
2674
3336
  </div>
2675
- <div class="card">
2676
- <div class="card-label">Total Calls</div>
2677
- <div class="card-value" id="card-calls">\u2014</div>
3337
+ );
3338
+ }
3339
+ function TimeFilter({ range, setRange, t, setTweak }) {
3340
+ const ranges = ['1h', '24h', '7d', '30d', 'All'];
3341
+ return (
3342
+ <div className="tw-timefilter">
3343
+ <div className="tw-tabs">
3344
+ {ranges.map((r) => (
3345
+ <button key={r} className={'tw-tab' + (r === range ? ' on' : '')} onClick={() => setRange(r)}>{r}</button>
3346
+ ))}
3347
+ </div>
3348
+ <label className="tw-compare">
3349
+ <button className="tw-toggle-sm" data-on={t.compareMode ? '1' : '0'} onClick={() => setTweak('compareMode', !t.compareMode)}><i /></button>
3350
+ Compare to previous period
3351
+ </label>
2678
3352
  </div>
2679
- <div class="card">
2680
- <div class="card-label">Burn Rate</div>
2681
- <div class="card-value" id="card-burn">\u2014</div>
2682
- <div class="card-sub">per hour</div>
3353
+ );
3354
+ }
3355
+ function ForecastCard({ label, value, sub, accent, flag }) {
3356
+ return (
3357
+ <div className={'tw-fc' + (flag ? ' flag' : '')}>
3358
+ <div className="tw-fc-label">{label}</div>
3359
+ <div className="tw-fc-value" style={accent ? { color: accent } : null}>{value}</div>
3360
+ {sub && <div className="tw-fc-sub">{sub}</div>}
2683
3361
  </div>
2684
- </div>
3362
+ );
3363
+ }
3364
+ function ForecastSection({ t }) {
3365
+ const { fmtUSD, fmtMoney, BUDGET } = window.TW;
3366
+ const daily = BUDGET.daily != null ? BUDGET.daily : 0.8473;
3367
+ const burnHr = daily / 24;
3368
+ const remaining = daily * BUDGET.daysLeft;
3369
+ const projCycle = BUDGET.used + remaining;
3370
+ const g = t.forecastScenario / 100;
3371
+ const scenarioCycle = BUDGET.used + remaining * (1 + g);
3372
+ const over = scenarioCycle > BUDGET.limit;
3373
+ return (
3374
+ <section className="tw-section">
3375
+ <div className="tw-sec-head"><h3>Cost forecast</h3><span className="tw-sec-sub">based on current run-rate</span></div>
3376
+ <div className="tw-forecast">
3377
+ <ForecastCard label="Projected daily" value={fmtUSD(daily, 2)} sub="next 24h at this rate" />
3378
+ <ForecastCard label="Projected this cycle" value={fmtMoney(projCycle)} sub={'of ' + fmtMoney(BUDGET.limit) + ' budget'} />
3379
+ <ForecastCard label="Burn rate" value={fmtUSD(burnHr, 4)} sub="per hour" accent="#e3b341" />
3380
+ <ForecastCard label={'If usage grows ' + t.forecastScenario + '%'} value={fmtMoney(scenarioCycle)} sub={over ? 'over budget \u26A0' : fmtMoney(BUDGET.limit - scenarioCycle) + ' headroom'} accent={over ? '#f85149' : '#58a6ff'} flag={over} />
3381
+ </div>
3382
+ </section>
3383
+ );
3384
+ }
3385
+ Object.assign(window, { Ico, Header, BudgetBar, KpiCard, KpiRow, TimeFilter, ForecastCard, ForecastSection });
3386
+ </script>
2685
3387
 
2686
- <div class="charts">
2687
- <div class="panel">
2688
- <div class="panel-title">Cost over time</div>
2689
- <div class="chart-wrap">
2690
- <canvas id="chart-line"></canvas>
3388
+ <script type="text/babel">
3389
+ // tw-table.jsx
3390
+ const { useState: useStateT } = React;
3391
+ function ModelTable({ models, total, t, onRowClick, exampleHover }) {
3392
+ const { fmtInt, fmtUSD, fmtCompact } = window.TW;
3393
+ const [sort, setSort] = useStateT({ key: 'cost', dir: -1 });
3394
+ const [hoverRow, setHoverRow] = useStateT(null);
3395
+ const cols = [
3396
+ { key: 'id', label: 'Model', align: 'left' },
3397
+ { key: 'calls', label: 'Calls', align: 'right' },
3398
+ { key: 'inTok', label: 'In tokens', align: 'right' },
3399
+ { key: 'outTok', label: 'Out tokens', align: 'right' },
3400
+ { key: 'cost', label: 'Cost', align: 'right' },
3401
+ { key: 'share', label: 'Share', align: 'left' },
3402
+ { key: 'avg', label: 'Avg / call', align: 'right' },
3403
+ ];
3404
+ const safeTotal = total || 0.0001;
3405
+ const rows = [...models].map((m) => ({ ...m, avg: m.cost / Math.max(m.calls, 1), share: m.cost / safeTotal }));
3406
+ if (t.tableSort) {
3407
+ rows.sort((a, b) => {
3408
+ const A = a[sort.key], B = b[sort.key];
3409
+ if (typeof A === 'string') return A.localeCompare(B) * sort.dir;
3410
+ return (A - B) * sort.dir;
3411
+ });
3412
+ }
3413
+ const clickHeader = (key) => {
3414
+ if (!t.tableSort) return;
3415
+ setSort((s) => s.key === key ? { key, dir: -s.dir } : { key, dir: key === 'id' ? 1 : -1 });
3416
+ };
3417
+ return (
3418
+ <section className="tw-section">
3419
+ <div className="tw-sec-head">
3420
+ <h3>Model breakdown</h3>
3421
+ <span className="tw-sec-sub">{models.length} models &middot; click a row for detail</span>
2691
3422
  </div>
2692
- </div>
2693
- <div class="panel">
2694
- <div class="panel-title">By model</div>
2695
- <div class="chart-wrap">
2696
- <canvas id="chart-doughnut"></canvas>
3423
+ <div className="tw-table-wrap">
3424
+ <table className={'tw-table' + (t.density === 'compact' ? ' compact' : '')}>
3425
+ <thead>
3426
+ <tr>
3427
+ {cols.map((c) => (
3428
+ <th key={c.key} style={{ textAlign: c.align, cursor: t.tableSort && c.key !== 'share' ? 'pointer' : 'default' }}
3429
+ onClick={() => c.key !== 'share' && clickHeader(c.key)}>
3430
+ <span className="tw-th-inner" style={{ justifyContent: c.align === 'right' ? 'flex-end' : 'flex-start' }}>
3431
+ {c.label}
3432
+ {t.tableSort && sort.key === c.key && <span className="tw-sort">{sort.dir < 0 ? '\u25BE' : '\u25B4'}</span>}
3433
+ </span>
3434
+ </th>
3435
+ ))}
3436
+ </tr>
3437
+ </thead>
3438
+ <tbody>
3439
+ {rows.map((m) => {
3440
+ const isExample = exampleHover && m.id === 'claude-sonnet-4-6';
3441
+ return (
3442
+ <tr key={m.id} className={'tw-row' + (isExample ? ' example' : '')}
3443
+ onMouseEnter={() => setHoverRow(m.id)} onMouseLeave={() => setHoverRow(null)}
3444
+ onClick={() => onRowClick(m)}>
3445
+ <td>
3446
+ <div className="tw-model-cell">
3447
+ <span className="tw-model-dot" style={{ background: m.color }} />
3448
+ <span className="tw-model-name">{m.id}</span>
3449
+ <span className="tw-model-prov">{m.provider}</span>
3450
+ </div>
3451
+ </td>
3452
+ <td className="tw-num-cell">{fmtInt(m.calls)}</td>
3453
+ <td className="tw-num-cell">{fmtCompact(m.inTok)}</td>
3454
+ <td className="tw-num-cell">{fmtCompact(m.outTok)}</td>
3455
+ <td className="tw-num-cell tw-cost">{fmtUSD(m.cost, 4)}</td>
3456
+ <td style={{ minWidth: 140 }}><ShareBar frac={m.share} color={m.color} /></td>
3457
+ <td className="tw-num-cell">
3458
+ {hoverRow === m.id && t.tableSort ? (
3459
+ <div className="tw-row-actions" onClick={(e) => e.stopPropagation()}>
3460
+ <button onClick={() => onRowClick(m)}>Details</button>
3461
+ <button>Alert</button>
3462
+ </div>
3463
+ ) : (
3464
+ <span>{fmtUSD(m.avg, 4)}</span>
3465
+ )}
3466
+ </td>
3467
+ </tr>
3468
+ );
3469
+ })}
3470
+ </tbody>
3471
+ </table>
2697
3472
  </div>
2698
- </div>
2699
- </div>
2700
-
2701
- <div class="section">
2702
- <div class="section-title">Model breakdown</div>
2703
- <div id="model-table-wrap"></div>
2704
- </div>
2705
-
2706
- <details id="users-section" style="margin-bottom:24px;">
2707
- <summary>By user</summary>
2708
- <div id="user-table-wrap"></div>
2709
- </details>
3473
+ </section>
3474
+ );
3475
+ }
3476
+ Object.assign(window, { ModelTable });
3477
+ </script>
2710
3478
 
2711
- <details id="features-section" style="margin-bottom:24px;">
2712
- <summary>By feature</summary>
2713
- <div id="feature-table-wrap"></div>
2714
- </details>
3479
+ <script type="text/babel">
3480
+ // tw-panel.jsx
3481
+ const { useEffect: useEffectP } = React;
3482
+ function SlideOver({ model, onClose, t }) {
3483
+ const { fmtInt, fmtUSD, callsForModel, fmtAgo } = window.TW;
3484
+ useEffectP(() => {
3485
+ const onKey = (e) => { if (e.key === 'Escape') onClose(); };
3486
+ window.addEventListener('keydown', onKey);
3487
+ return () => window.removeEventListener('keydown', onKey);
3488
+ }, [onClose]);
3489
+ const open = !!model;
3490
+ const m = model;
3491
+ const calls = m ? callsForModel(m.id, 5) : [];
3492
+ const totalIn = m ? m.inTok : 0, totalOut = m ? m.outTok : 0;
3493
+ return (
3494
+ <>
3495
+ <div className={'tw-scrim' + (open ? ' open' : '')} onClick={onClose} />
3496
+ <aside className={'tw-slideover' + (open ? ' open' : '')}>
3497
+ {m && (
3498
+ <div className="tw-so-inner">
3499
+ <div className="tw-so-head">
3500
+ <div className="tw-so-title">
3501
+ <span className="tw-model-dot lg" style={{ background: m.color }} />
3502
+ <div>
3503
+ <div className="tw-so-name">{m.id}</div>
3504
+ <div className="tw-so-prov">{m.provider} &middot; {fmtInt(m.calls)} calls in window</div>
3505
+ </div>
3506
+ </div>
3507
+ <button className="tw-so-close" onClick={onClose}>&#x2715;</button>
3508
+ </div>
3509
+ <div className="tw-so-stats">
3510
+ <div className="tw-so-stat"><div className="tw-so-stat-l">Total cost</div><div className="tw-so-stat-v">{fmtUSD(m.cost, 4)}</div></div>
3511
+ <div className="tw-so-stat"><div className="tw-so-stat-l">Calls</div><div className="tw-so-stat-v">{fmtInt(m.calls)}</div></div>
3512
+ <div className="tw-so-stat"><div className="tw-so-stat-l">Avg / call</div><div className="tw-so-stat-v">{fmtUSD(m.cost / Math.max(m.calls, 1), 4)}</div></div>
3513
+ </div>
3514
+ <div className="tw-so-metarow">
3515
+ <div><span className="tw-so-meta-l">In tokens</span><span className="tw-so-meta-v">{fmtInt(totalIn)}</span></div>
3516
+ <div><span className="tw-so-meta-l">Out tokens</span><span className="tw-so-meta-v">{fmtInt(totalOut)}</span></div>
3517
+ <div><span className="tw-so-meta-l">Cost / call</span><span className="tw-so-meta-v">{fmtUSD(m.cost / Math.max(m.calls, 1), 4)}</span></div>
3518
+ </div>
3519
+ <div className="tw-so-section-label">Last 5 calls (estimated)</div>
3520
+ <div className="tw-so-calls">
3521
+ {calls.map((c) => (
3522
+ <div key={c.id} className="tw-so-call">
3523
+ <div className="tw-so-call-top">
3524
+ <span className="tw-so-call-time">{fmtAgo(c.secondsAgo)}</span>
3525
+ <span className="tw-feat" style={{ color: c.featureColor, borderColor: c.featureColor + '55' }}>{c.feature}</span>
3526
+ <span className="tw-so-call-cost">{fmtUSD(c.cost, 4)}</span>
3527
+ </div>
3528
+ <div className="tw-so-call-bot">
3529
+ <span>{fmtInt(c.inTok)} in &middot; {fmtInt(c.outTok)} out</span>
3530
+ <span className="tw-so-call-lat">{c.latency}ms{c.status === 'slow' ? ' \xB7 slow' : c.status === 'error' ? ' \xB7 error' : ''}</span>
3531
+ </div>
3532
+ </div>
3533
+ ))}
3534
+ </div>
3535
+ <button className="tw-so-viewall">View all {fmtInt(m.calls)} calls <Ico.arrow /></button>
3536
+ </div>
3537
+ )}
3538
+ </aside>
3539
+ </>
3540
+ );
3541
+ }
3542
+ Object.assign(window, { SlideOver });
3543
+ </script>
2715
3544
 
2716
- <div class="section">
2717
- <div class="section-title">Cost forecast</div>
2718
- <div class="forecast-grid">
2719
- <div class="card">
2720
- <div class="card-label">Projected daily</div>
2721
- <div class="card-value" id="fc-daily">\u2014</div>
2722
- <div class="card-sub" id="fc-window"></div>
2723
- </div>
2724
- <div class="card">
2725
- <div class="card-label">Projected monthly</div>
2726
- <div class="card-value" id="fc-monthly">\u2014</div>
3545
+ <script type="text/babel">
3546
+ // tw-activity.jsx
3547
+ const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;
3548
+ function LiveActivity({ t }) {
3549
+ const { seedFeed, makeCall, fmtUSD, fmtInt, fmtAgo } = window.TW;
3550
+ const [feed, setFeed] = useStateA(() => seedFeed(14));
3551
+ const [now, setNow] = useStateA(Date.now());
3552
+ const [paused, setPaused] = useStateA(false);
3553
+ const [collapsed, setCollapsed] = useStateA(false);
3554
+ const [filter, setFilter] = useStateA('all');
3555
+ const seedRef = useRefA(5000);
3556
+ const streaming = t.liveFeed && t.animLevel !== 'minimal' && !paused;
3557
+ useEffectA(() => {
3558
+ if (!streaming) return;
3559
+ const iv = setInterval(() => {
3560
+ const c = makeCall(0, seedRef.current++);
3561
+ c.ts = Date.now(); c.fresh = true;
3562
+ setFeed((f) => [c, ...f].slice(0, 40));
3563
+ }, t.animLevel === 'subtle' ? 3600 : 2100);
3564
+ return () => clearInterval(iv);
3565
+ }, [streaming, t.animLevel]);
3566
+ useEffectA(() => {
3567
+ const iv = setInterval(() => setNow(Date.now()), 1000);
3568
+ return () => clearInterval(iv);
3569
+ }, []);
3570
+ const shown = feed
3571
+ .map((c) => ({ ...c, secondsAgo: Math.max(0, Math.round((now - c.ts) / 1000)) }))
3572
+ .filter((c) => filter === 'all' ? true : filter === 'errors' ? c.status !== 'ok' : c.cost >= 0.001)
3573
+ .slice(0, 10);
3574
+ return (
3575
+ <section className="tw-section tw-activity">
3576
+ <div className="tw-sec-head">
3577
+ <div className="tw-act-title">
3578
+ <button className="tw-collapse" onClick={() => setCollapsed((v) => !v)} style={{ transform: collapsed ? 'rotate(-90deg)' : 'none' }}><Ico.chevron /></button>
3579
+ <span className={'tw-live-dot' + (streaming ? ' on' : '')} />
3580
+ <h3>Live activity</h3>
3581
+ <span className="tw-sec-sub">{streaming ? 'streaming' : t.liveFeed ? 'paused' : 'static'}</span>
3582
+ </div>
3583
+ <div className="tw-act-controls">
3584
+ <div className="tw-seg-sm">
3585
+ {[['all', 'All'], ['signal', 'Signal'], ['errors', 'Errors']].map(([k, l]) => (
3586
+ <button key={k} className={filter === k ? 'on' : ''} onClick={() => setFilter(k)}>{l}</button>
3587
+ ))}
3588
+ </div>
3589
+ {t.liveFeed && (
3590
+ <button className="tw-act-pause" onClick={() => setPaused((p) => !p)}>{paused ? '\u25B6 Resume' : '\u275A\u275A Pause'}</button>
3591
+ )}
3592
+ </div>
2727
3593
  </div>
2728
- <div class="card">
2729
- <div class="card-label">Burn rate / hr</div>
2730
- <div class="card-value" id="fc-burn">\u2014</div>
3594
+ {!collapsed && (
3595
+ <div className="tw-feed">
3596
+ <div className="tw-feed-head">
3597
+ <span>Time</span><span>Model</span><span>Session</span><span>Feature</span><span style={{ textAlign: 'right' }}>Cost</span>
3598
+ </div>
3599
+ <div className="tw-feed-body">
3600
+ {shown.map((c) => (
3601
+ <div key={c.id} className={'tw-feed-row' + (c.fresh ? ' fresh' : '') + (c.status === 'error' ? ' err' : '')}>
3602
+ <span className="tw-feed-time">{c.secondsAgo === 0 ? 'now' : fmtAgo(c.secondsAgo)}</span>
3603
+ <span className="tw-feed-model"><span className="tw-model-dot" style={{ background: c.modelColor }} />{c.model}</span>
3604
+ <span className="tw-feed-sess">{c.session}</span>
3605
+ <span><span className="tw-feat sm" style={{ color: c.featureColor, borderColor: c.featureColor + '55' }}>{c.feature}</span></span>
3606
+ <span className="tw-feed-cost">{fmtUSD(c.cost, 4)}{c.status === 'error' && <span className="tw-feed-flag">err</span>}{c.status === 'slow' && <span className="tw-feed-flag slow">slow</span>}</span>
3607
+ </div>
3608
+ ))}
3609
+ </div>
3610
+ </div>
3611
+ )}
3612
+ </section>
3613
+ );
3614
+ }
3615
+ function CommandPalette({ open, onClose, onAction }) {
3616
+ const [q, setQ] = useStateA('');
3617
+ const inputRef = useRefA(null);
3618
+ useEffectA(() => { if (open && inputRef.current) inputRef.current.focus(); if (open) setQ(''); }, [open]);
3619
+ useEffectA(() => {
3620
+ const onKey = (e) => { if (e.key === 'Escape') onClose(); };
3621
+ if (open) window.addEventListener('keydown', onKey);
3622
+ return () => window.removeEventListener('keydown', onKey);
3623
+ }, [open, onClose]);
3624
+ const items = [
3625
+ { g: 'Filter', label: 'Set range: Last 1h', act: { range: '1h' } },
3626
+ { g: 'Filter', label: 'Set range: Last 24h', act: { range: '24h' } },
3627
+ { g: 'Filter', label: 'Set range: Last 7 days', act: { range: '7d' } },
3628
+ { g: 'Filter', label: 'Set range: Last 30 days', act: { range: '30d' } },
3629
+ { g: 'Filter', label: 'Set range: All time', act: { range: 'All' } },
3630
+ { g: 'Action', label: 'Export CSV', hint: '\u2318E' },
3631
+ { g: 'Action', label: 'Create budget alert' },
3632
+ ];
3633
+ const filtered = items.filter((i) => i.label.toLowerCase().includes(q.toLowerCase()));
3634
+ if (!open) return null;
3635
+ return (
3636
+ <div className="tw-cmdk-scrim" onClick={onClose}>
3637
+ <div className="tw-cmdk" onClick={(e) => e.stopPropagation()}>
3638
+ <div className="tw-cmdk-input">
3639
+ <Ico.search style={{ color: '#7d8590' }} />
3640
+ <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search models, sessions, actions\u2026" />
3641
+ <kbd>esc</kbd>
3642
+ </div>
3643
+ <div className="tw-cmdk-list">
3644
+ {filtered.length === 0 && <div className="tw-cmdk-empty">No results for "{q}"</div>}
3645
+ {filtered.map((i, idx) => (
3646
+ <div key={idx} className="tw-cmdk-item" onClick={() => { onAction(i.act); onClose(); }}>
3647
+ <span className="tw-cmdk-g">{i.g}</span>
3648
+ <span className="tw-cmdk-l">{i.label}</span>
3649
+ {i.hint && <kbd>{i.hint}</kbd>}
3650
+ </div>
3651
+ ))}
3652
+ </div>
2731
3653
  </div>
2732
3654
  </div>
2733
- </div>
2734
-
2735
- <div class="footer" id="footer-updated"></div>
2736
-
2737
- </div><!-- /container -->
2738
-
2739
- <script>
2740
- (function () {
2741
- 'use strict';
2742
-
2743
- // \u2500\u2500 Palette \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2744
- const PALETTE = [
2745
- '#58a6ff','#3fb950','#f78166','#d29922','#bc8cff',
2746
- '#79c0ff','#56d364','#ffa657','#ff7b72','#a5d6ff',
2747
- ];
2748
-
2749
- // \u2500\u2500 State \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2750
- let evtSource = null;
2751
- let activeFilter = '24h';
2752
- let lineChart = null;
2753
- let doughnutChart = null;
3655
+ );
3656
+ }
3657
+ Object.assign(window, { LiveActivity, CommandPalette });
3658
+ </script>
2754
3659
 
2755
- // \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2756
- function escHtml(str) {
2757
- return String(str)
2758
- .replace(/&/g, '&amp;')
2759
- .replace(/</g, '&lt;')
2760
- .replace(/>/g, '&gt;')
2761
- .replace(/"/g, '&quot;');
3660
+ <script type="text/babel">
3661
+ // tw-data.jsx \u2014 mock data + formatters (always-populated baseline)
3662
+ const fmtUSD = (n, d = 4) =>
3663
+ '$' + Number(n).toLocaleString('en-US', { minimumFractionDigits: d, maximumFractionDigits: d });
3664
+ const fmtMoney = (n) =>
3665
+ '$' + Number(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
3666
+ const fmtInt = (n) => Math.round(n || 0).toLocaleString('en-US');
3667
+ const fmtCompact = (n) => {
3668
+ n = n || 0;
3669
+ if (n >= 1e6) return (n / 1e6).toFixed(2).replace(/.?0+$/, '') + 'M';
3670
+ if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/.?0+$/, '') + 'K';
3671
+ return String(Math.round(n));
3672
+ };
3673
+ const fmtAgo = (s) => {
3674
+ if (s < 60) return s + 's ago';
3675
+ if (s < 3600) return Math.floor(s / 60) + 'm ago';
3676
+ if (s < 86400) return Math.floor(s / 3600) + 'h ago';
3677
+ return Math.floor(s / 86400) + 'd ago';
3678
+ };
3679
+ const BASE_MODELS = [
3680
+ { id: 'gpt-5-mini', provider: 'OpenAI', color: '#3fb950', calls: 94, inTok: 1040000, outTok: 118000, cost: 0.2110, latency: 590 },
3681
+ { id: 'claude-sonnet-4-6', provider: 'Anthropic', color: '#bc8cff', calls: 58, inTok: 612000, outTok: 84000, cost: 0.3120, latency: 1840 },
3682
+ { id: 'gemini-2.5-flash', provider: 'Google', color: '#58a6ff', calls: 47, inTok: 430000, outTok: 56000, cost: 0.1190, latency: 510 },
3683
+ { id: 'claude-haiku-4-5', provider: 'Anthropic', color: '#f778ba', calls: 38, inTok: 268100, outTok: 38540, cost: 0.1240, latency: 680 },
3684
+ { id: 'gpt-5.1', provider: 'OpenAI', color: '#e3b341', calls: 18, inTok: 88000, outTok: 12000, cost: 0.0613, latency: 2210 },
3685
+ { id: 'gemini-2.5-pro', provider: 'Google', color: '#56d4dd', calls: 8, inTok: 42000, outTok: 4000, cost: 0.0200, latency: 1990 },
3686
+ ];
3687
+ const RANGES = {
3688
+ '1h': { factor: 0.052, points: 12, label: 'last hour', step: '5 min' },
3689
+ '24h': { factor: 1, points: 24, label: 'last 24h', step: 'hour' },
3690
+ '7d': { factor: 6.4, points: 28, label: 'last 7 days', step: '6h' },
3691
+ '30d': { factor: 53.1, points: 30, label: 'last 30 days',step: 'day' },
3692
+ 'All': { factor: 142, points: 26, label: 'all time', step: 'week' },
3693
+ };
3694
+ function modelsForRange(range) {
3695
+ const f = RANGES[range].factor;
3696
+ return BASE_MODELS.map((m) => ({
3697
+ ...m,
3698
+ calls: Math.max(1, Math.round(m.calls * f)),
3699
+ inTok: Math.round(m.inTok * f),
3700
+ outTok: Math.round(m.outTok * f),
3701
+ cost: m.cost * f,
3702
+ }));
3703
+ }
3704
+ function kpisForRange(range) {
3705
+ const ms = modelsForRange(range);
3706
+ const sum = (k) => ms.reduce((a, m) => a + m[k], 0);
3707
+ const cost = sum('cost'), calls = sum('calls');
3708
+ return {
3709
+ cost, calls,
3710
+ inTok: sum('inTok'), outTok: sum('outTok'),
3711
+ models: ms,
3712
+ burnHr: cost / ({ '1h': 1, '24h': 24, '7d': 168, '30d': 720, 'All': 3408 }[range]),
3713
+ };
3714
+ }
3715
+ const DAY_SHAPE = [0.2,0.15,0.12,0.1,0.1,0.15,0.3,0.6,1.0,1.4,1.7,1.8,1.6,1.5,1.9,2.0,1.7,1.3,1.0,0.8,0.6,0.45,0.35,0.25];
3716
+ function shapeFor(n) {
3717
+ const out = [];
3718
+ for (let i = 0; i < n; i++) {
3719
+ const t = (i / n) * DAY_SHAPE.length;
3720
+ const a = DAY_SHAPE[Math.floor(t) % DAY_SHAPE.length];
3721
+ const b = DAY_SHAPE[(Math.floor(t) + 1) % DAY_SHAPE.length];
3722
+ out.push(a + (b - a) * (t - Math.floor(t)));
2762
3723
  }
2763
-
2764
- function fmtUSD(n) {
2765
- if (n === 0) return '$0.00';
2766
- if (n < 0.001) return '$' + n.toFixed(6);
2767
- if (n < 1) return '$' + n.toFixed(4);
2768
- return '$' + n.toFixed(2);
3724
+ return out;
3725
+ }
3726
+ function buildSeries(total, n, jitterSeed = 1) {
3727
+ const shape = shapeFor(n);
3728
+ const j = shape.map((v, i) => v * (0.82 + 0.36 * Math.abs(Math.sin(i * 12.9898 * jitterSeed))));
3729
+ const s = j.reduce((a, b) => a + b, 0);
3730
+ return j.map((v) => (v / s) * total);
3731
+ }
3732
+ function seriesForRange(range) {
3733
+ const { cost } = kpisForRange(range);
3734
+ const n = RANGES[range].points;
3735
+ return { current: buildSeries(cost, n, 1), previous: buildSeries(cost / 1.12, n, 1.7), n };
3736
+ }
3737
+ const FEATURES = ['chat', 'rag-search', 'summarize', 'classify', 'agent-loop', 'embeddings', 'code-review', 'extract'];
3738
+ const FEATURE_COLOR = {
3739
+ 'chat': '#58a6ff', 'rag-search': '#3fb950', 'summarize': '#bc8cff', 'classify': '#e3b341',
3740
+ 'agent-loop': '#f778ba', 'embeddings': '#56d4dd', 'code-review': '#ff7b72', 'extract': '#7ee787',
3741
+ };
3742
+ let __callSeq = 48213;
3743
+ function rng(seed) { let x = Math.sin(seed) * 10000; return x - Math.floor(x); }
3744
+ function makeCall(secondsAgo, seed) {
3745
+ const m = BASE_MODELS[Math.floor(rng(seed) * BASE_MODELS.length)];
3746
+ const feat = FEATURES[Math.floor(rng(seed * 1.3) * FEATURES.length)];
3747
+ const inTok = Math.round(800 + rng(seed * 2.1) * 14000);
3748
+ const outTok = Math.round(60 + rng(seed * 3.7) * 2200);
3749
+ const cost = (inTok / 1e6) * 0.4 + (outTok / 1e6) * 3.2;
3750
+ const r = rng(seed * 5.9);
3751
+ const status = r > 0.965 ? 'error' : r > 0.9 ? 'slow' : 'ok';
3752
+ return {
3753
+ id: ++__callSeq, secondsAgo, ts: Date.now() - secondsAgo * 1000,
3754
+ model: m.id, modelColor: m.color,
3755
+ session: 'sess_' + (seed * 7919 % 1e6 | 0).toString(36).padStart(4, '0'),
3756
+ feature: feat, featureColor: FEATURE_COLOR[feat],
3757
+ inTok, outTok, cost, latency: Math.round(m.latency * (0.6 + rng(seed * 8.3) * 1.2)), status,
3758
+ };
3759
+ }
3760
+ function seedFeed(count) {
3761
+ const arr = [];
3762
+ for (let i = 0; i < count; i++) arr.push(makeCall(2 + i * 7 + Math.floor(rng(i * 3.3) * 6), 100 + i));
3763
+ return arr;
3764
+ }
3765
+ function callsForModel(modelId, count = 5) {
3766
+ const arr = [];
3767
+ let sa = 12;
3768
+ for (let i = 0; i < count; i++) {
3769
+ const c = makeCall(sa, 900 + i + modelId.length);
3770
+ c.model = modelId;
3771
+ c.modelColor = (BASE_MODELS.find((m) => m.id === modelId) || {}).color || '#58a6ff';
3772
+ arr.push(c);
3773
+ sa += 40 + Math.floor(rng(i * 2.2) * 220);
2769
3774
  }
3775
+ return arr;
3776
+ }
3777
+ const BUDGET = { used: 45.0, limit: 100.0, daysLeft: 18, cycleDays: 30 };
2770
3778
 
2771
- function fmtNum(n) {
2772
- return n.toLocaleString('en-US');
2773
- }
3779
+ Object.assign(window, {
3780
+ TW: {
3781
+ fmtUSD, fmtMoney, fmtInt, fmtCompact, fmtAgo,
3782
+ BASE_MODELS, RANGES, modelsForRange, kpisForRange,
3783
+ seriesForRange, seedFeed, makeCall, callsForModel,
3784
+ FEATURES, FEATURE_COLOR, BUDGET, _buildSeries: buildSeries,
3785
+ },
3786
+ });
2774
3787
 
2775
- function fmtDate(iso) {
2776
- try { return new Date(iso).toLocaleString(); } catch { return iso; }
3788
+ // SSE overlay \u2014 patches window.TW functions when real data arrives
3789
+ (function () {
3790
+ var MC = ['#bc8cff','#3fb950','#58a6ff','#f778ba','#e3b341','#56d4dd','#79c0ff','#ffa657','#ff7b72','#a5d6ff'];
3791
+ function guessProv(id) {
3792
+ if (/claude/i.test(id)) return 'Anthropic';
3793
+ if (/gpt|o1|o3|o4/i.test(id)) return 'OpenAI';
3794
+ if (/gemini/i.test(id)) return 'Google';
3795
+ return 'Other';
2777
3796
  }
2778
-
2779
- function totalCalls(byModel) {
2780
- return Object.values(byModel).reduce(function(s, m) { return s + m.calls; }, 0);
3797
+ function buildRealModels(byModel) {
3798
+ return Object.entries(byModel).map(function(e, i) {
3799
+ var id = e[0], s = e[1];
3800
+ return { id: id, provider: guessProv(id), color: MC[i % MC.length],
3801
+ calls: s.calls || 0, inTok: (s.tokens && s.tokens.input) || 0,
3802
+ outTok: (s.tokens && s.tokens.output) || 0, cost: s.costUSD || 0, latency: 1200 };
3803
+ }).sort(function(a, b) { return b.cost - a.cost; });
2781
3804
  }
2782
-
2783
- // \u2500\u2500 Tab setup \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2784
- document.querySelectorAll('.tab').forEach(function(btn) {
2785
- btn.addEventListener('click', function() {
2786
- document.querySelectorAll('.tab').forEach(function(b) { b.classList.remove('active'); });
2787
- btn.classList.add('active');
2788
- activeFilter = btn.dataset.filter;
2789
- reconnect();
2790
- });
2791
- });
2792
-
2793
- // \u2500\u2500 SSE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2794
- function reconnect() {
2795
- if (evtSource) { evtSource.close(); evtSource = null; }
2796
- evtSource = new EventSource('/events?filter=' + encodeURIComponent(activeFilter));
2797
- evtSource.onmessage = function(e) {
2798
- try { updateUI(JSON.parse(e.data)); } catch (_) {}
3805
+ function applySSEData(data) {
3806
+ var r = data.report, fc = data.forecast, ts = data.timeSeries || [];
3807
+ if (!r || !r.byModel || Object.keys(r.byModel).length === 0) return;
3808
+ var mods = buildRealModels(r.byModel);
3809
+ var totalCalls = mods.reduce(function(s, m) { return s + m.calls; }, 0);
3810
+ var totalCost = r.totalCostUSD || 0;
3811
+ var totalIn = 0, totalOut = 0;
3812
+ if (r.totalTokens) { totalIn = r.totalTokens.input || 0; totalOut = r.totalTokens.output || 0; }
3813
+ else { mods.forEach(function(m) { totalIn += m.inTok; totalOut += m.outTok; }); }
3814
+ var costs = ts.map(function(b) { return b.cost || 0; });
3815
+ window.TW.kpisForRange = function() {
3816
+ return { cost: totalCost, calls: totalCalls, inTok: totalIn, outTok: totalOut,
3817
+ models: mods, burnHr: (fc && fc.burnRatePerHour) || 0 };
2799
3818
  };
3819
+ if (costs.length >= 2) {
3820
+ window.TW.seriesForRange = function() {
3821
+ return { current: costs, previous: buildSeries(totalCost / 1.12, costs.length, 1.7), n: costs.length };
3822
+ };
3823
+ }
3824
+ if (fc && fc.projectedDailyCostUSD) window.TW.BUDGET.daily = fc.projectedDailyCostUSD;
3825
+ if (fc && fc.burnRatePerHour) {
3826
+ var elapsed = window.TW.BUDGET.cycleDays - window.TW.BUDGET.daysLeft;
3827
+ window.TW.BUDGET.used = fc.burnRatePerHour * 24 * Math.max(elapsed, 1);
3828
+ }
3829
+ window.dispatchEvent(new CustomEvent('tw-data-update'));
3830
+ }
3831
+ var evtSource = null;
3832
+ function connect(filter) {
3833
+ if (evtSource) { try { evtSource.close(); } catch(e) {} }
3834
+ var f = filter === 'All' ? 'all' : filter;
3835
+ evtSource = new EventSource('/events?filter=' + encodeURIComponent(f));
3836
+ evtSource.onmessage = function(e) { try { applySSEData(JSON.parse(e.data)); } catch(_) {} };
2800
3837
  evtSource.onerror = function() {
2801
- document.getElementById('live-label').textContent = 'reconnecting\u2026';
2802
- };
2803
- evtSource.onopen = function() {
2804
- document.getElementById('live-label').textContent = 'live';
3838
+ try { evtSource.close(); } catch(e) {}
3839
+ setTimeout(function() { connect(f); }, 5000);
2805
3840
  };
2806
3841
  }
3842
+ window.__twSSEConnect = connect;
3843
+ connect('24h');
3844
+ })();
3845
+ </script>
2807
3846
 
2808
- // \u2500\u2500 UI update \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2809
- function updateUI(data) {
2810
- const r = data.report;
2811
- const fc = data.forecast;
2812
- const ts = data.timeSeries;
2813
-
2814
- // Cards
2815
- document.getElementById('card-cost').textContent = fmtUSD(r.totalCostUSD);
2816
- document.getElementById('card-input').textContent = fmtNum(r.totalTokens.input);
2817
- document.getElementById('card-output').textContent = fmtNum(r.totalTokens.output);
2818
- document.getElementById('card-calls').textContent = fmtNum(totalCalls(r.byModel));
2819
- document.getElementById('card-burn').textContent = fmtUSD(fc.burnRatePerHour);
2820
- document.getElementById('card-period').textContent =
2821
- r.period.from !== r.period.to
2822
- ? fmtDate(r.period.from) + ' \u2013 ' + fmtDate(r.period.to)
2823
- : '';
3847
+ <script type="text/babel">
3848
+ // tw-app.jsx
3849
+ const { useState: useStateApp, useEffect: useEffectApp, useMemo: useMemoApp } = React;
2824
3850
 
2825
- // Line chart
2826
- const labels = ts.map(function(b) {
2827
- try { return new Date(b.bucket).toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'}); }
2828
- catch { return b.bucket; }
2829
- });
2830
- const costs = ts.map(function(b) { return b.cost; });
2831
3851
 
2832
- if (!lineChart) {
2833
- const ctx = document.getElementById('chart-line').getContext('2d');
2834
- lineChart = new Chart(ctx, {
2835
- type: 'line',
2836
- data: {
2837
- labels: labels,
2838
- datasets: [{
2839
- label: 'Cost (USD)',
2840
- data: costs,
2841
- borderColor: '#58a6ff',
2842
- backgroundColor: 'rgba(88,166,255,0.08)',
2843
- borderWidth: 2,
2844
- pointRadius: 3,
2845
- pointBackgroundColor: '#58a6ff',
2846
- fill: true,
2847
- tension: 0.3,
2848
- }],
2849
- },
2850
- options: {
2851
- responsive: true, maintainAspectRatio: false,
2852
- plugins: { legend: { display: false } },
2853
- scales: {
2854
- x: { ticks: { color: '#8b949e', maxTicksLimit: 8 }, grid: { color: '#21262d' } },
2855
- y: {
2856
- ticks: {
2857
- color: '#8b949e',
2858
- callback: function(v) { return '$' + Number(v).toFixed(4); },
2859
- },
2860
- grid: { color: '#21262d' },
2861
- },
2862
- },
2863
- },
2864
- });
2865
- } else {
2866
- lineChart.data.labels = labels;
2867
- lineChart.data.datasets[0].data = costs;
2868
- lineChart.update('none');
2869
- }
3852
+ function LoadingSkeleton() {
3853
+ return (
3854
+ <div className="tw-skel-wrap">
3855
+ <div className="tw-skel" style={{ height: 56 }} />
3856
+ <div className="tw-kpis">{[0,0,0,0,0].map((_,i) => <div key={i} className="tw-skel" style={{ height: 96 }} />)}</div>
3857
+ <div className="tw-charts">
3858
+ <div className="tw-skel tw-chart-main" style={{ height: 320 }} />
3859
+ <div className="tw-skel tw-chart-side" style={{ height: 320 }} />
3860
+ </div>
3861
+ <div className="tw-skel" style={{ height: 260 }} />
3862
+ </div>
3863
+ );
3864
+ }
3865
+ function EmptyState() {
3866
+ return (
3867
+ <div className="tw-empty">
3868
+ <div className="tw-empty-art">
3869
+ <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
3870
+ <rect x="8" y="14" width="48" height="36" rx="4" stroke="#30363d" strokeWidth="2" />
3871
+ <path d="M16 40l8-9 7 6 9-13 8 10" stroke="#484f58" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
3872
+ <circle cx="24" cy="31" r="2" fill="#484f58" />
3873
+ </svg>
3874
+ </div>
3875
+ <h2>No usage yet</h2>
3876
+ <p>Once your app starts making LLM calls through tokenwatch, cost &amp; token metrics show up here in real time.</p>
3877
+ <div className="tw-empty-actions">
3878
+ <button className="tw-btn-primary">View integration guide <Ico.arrow /></button>
3879
+ <button className="tw-btn-2">Copy API key</button>
3880
+ </div>
3881
+ <div className="tw-empty-snippet">
3882
+ <span className="tw-snip-c">import</span> TokenWatch <span className="tw-snip-c">from</span> <span className="tw-snip-s">'@diogonzafe/tokenwatch'</span>
3883
+ </div>
3884
+ </div>
3885
+ );
3886
+ }
3887
+ function ChartsRow({ range, models, kpis, series, t }) {
3888
+ const { fmtUSD, RANGES } = window.TW;
3889
+ const [activeSlice, setActiveSlice] = useStateApp(null);
3890
+ const animate = t.animLevel !== 'minimal';
3891
+ const rangeConfig = RANGES[range] || RANGES['24h'];
3892
+ const safeTotal = kpis.cost || 0.0001;
3893
+ return (
3894
+ <div className="tw-charts">
3895
+ <div className="tw-card tw-chart-main">
3896
+ <div className="tw-sec-head">
3897
+ <h3>Cost over time</h3>
3898
+ <div className="tw-chart-legend">
3899
+ <span><i style={{ background: t.accent }} /> current</span>
3900
+ {t.compareMode && series.previous && <span className="muted"><i className="dash" /> previous</span>}
3901
+ <span className="tw-sec-sub">&middot; per {rangeConfig.step}</span>
3902
+ </div>
3903
+ </div>
3904
+ <LineChart current={series.current} previous={t.compareMode ? series.previous : null}
3905
+ n={series.n} color={t.accent} compare={t.compareMode && !!series.previous}
3906
+ animate={animate} fmt={(v) => fmtUSD(v, 4)} />
3907
+ </div>
3908
+ <div className="tw-card tw-chart-side">
3909
+ <div className="tw-sec-head"><h3>By model</h3></div>
3910
+ <div className="tw-doughnut-wrap">
3911
+ <Doughnut data={models} total={safeTotal} fmt={(v) => fmtUSD(v, 4)} active={activeSlice} onHover={setActiveSlice} />
3912
+ </div>
3913
+ <div className="tw-legend">
3914
+ {[...models].sort((a, b) => b.cost - a.cost).map((m) => (
3915
+ <div key={m.id} className={'tw-legend-row' + (activeSlice === m.id ? ' on' : '')}
3916
+ onMouseEnter={() => setActiveSlice(m.id)} onMouseLeave={() => setActiveSlice(null)}>
3917
+ <span className="tw-model-dot" style={{ background: m.color }} />
3918
+ <span className="tw-legend-name">{m.id}</span>
3919
+ <span className="tw-legend-val">{fmtUSD(m.cost, 4)}</span>
3920
+ <span className="tw-legend-pct">{((m.cost / safeTotal) * 100).toFixed(0)}%</span>
3921
+ </div>
3922
+ ))}
3923
+ </div>
3924
+ </div>
3925
+ </div>
3926
+ );
3927
+ }
3928
+ const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
3929
+ "density": "compact",
3930
+ "kpiSparklines": true,
3931
+ "smartHighlight": true,
3932
+ "compareMode": false,
3933
+ "tableSort": true,
3934
+ "budgetAlerts": true,
3935
+ "forecastScenario": 20,
3936
+ "liveFeed": true,
3937
+ "animLevel": "lively",
3938
+ "commandPalette": true,
3939
+ "appState": "data",
3940
+ "accent": "#58a6ff"
3941
+ }/*EDITMODE-END*/;
3942
+ function App() {
3943
+ const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
3944
+ const [range, setRange] = useStateApp('24h');
3945
+ const [selModel, setSelModel] = useStateApp(null);
3946
+ const [paletteOpen, setPaletteOpen] = useStateApp(false);
3947
+ const [_sseV, setSseV] = useStateApp(0);
2870
3948
 
2871
- // Doughnut chart
2872
- const modelEntries = Object.entries(r.byModel);
2873
- const dLabels = modelEntries.map(function(x) { return x[0]; });
2874
- const dData = modelEntries.map(function(x) { return x[1].costUSD; });
2875
- const dColors = dLabels.map(function(_, i) { return PALETTE[i % PALETTE.length]; });
3949
+ useEffectApp(() => {
3950
+ const h = function() { setSseV(function(v) { return v + 1; }); };
3951
+ window.addEventListener('tw-data-update', h);
3952
+ return function() { window.removeEventListener('tw-data-update', h); };
3953
+ }, []);
2876
3954
 
2877
- if (!doughnutChart) {
2878
- const ctx2 = document.getElementById('chart-doughnut').getContext('2d');
2879
- doughnutChart = new Chart(ctx2, {
2880
- type: 'doughnut',
2881
- data: { labels: dLabels, datasets: [{ data: dData, backgroundColor: dColors, borderWidth: 0, hoverOffset: 4 }] },
2882
- options: {
2883
- responsive: true, maintainAspectRatio: false,
2884
- cutout: '65%',
2885
- plugins: {
2886
- legend: {
2887
- position: 'bottom',
2888
- labels: { color: '#8b949e', boxWidth: 10, padding: 12, font: { size: 11 } },
2889
- },
2890
- },
2891
- },
2892
- });
2893
- } else {
2894
- doughnutChart.data.labels = dLabels;
2895
- doughnutChart.data.datasets[0].data = dData;
2896
- doughnutChart.data.datasets[0].backgroundColor = dColors;
2897
- doughnutChart.update('none');
2898
- }
3955
+ useEffectApp(() => {
3956
+ if (window.__twSSEConnect) window.__twSSEConnect(range);
3957
+ }, [range]);
2899
3958
 
2900
- // Model table
2901
- const modelWrap = document.getElementById('model-table-wrap');
2902
- if (modelEntries.length === 0) {
2903
- modelWrap.innerHTML = '<p class="empty">No data for this period.</p>';
2904
- } else {
2905
- const totalCost = r.totalCostUSD || 1;
2906
- let html = '<table><thead><tr>' +
2907
- '<th>Model</th>' +
2908
- '<th class="num">Calls</th>' +
2909
- '<th class="num">In tokens</th>' +
2910
- '<th class="num">Out tokens</th>' +
2911
- '<th class="num">Cost</th>' +
2912
- '<th class="num">Share</th>' +
2913
- '</tr></thead><tbody>';
2914
- const sorted = modelEntries.slice().sort(function(a, b) { return b[1].costUSD - a[1].costUSD; });
2915
- sorted.forEach(function(entry) {
2916
- const name = entry[0]; const m = entry[1];
2917
- const pct = (m.costUSD / totalCost * 100).toFixed(1);
2918
- const barW = Math.round(m.costUSD / totalCost * 80);
2919
- html += '<tr>' +
2920
- '<td>' + escHtml(name) + '</td>' +
2921
- '<td class="num">' + fmtNum(m.calls) + '</td>' +
2922
- '<td class="num">' + fmtNum(m.tokens.input) + '</td>' +
2923
- '<td class="num">' + fmtNum(m.tokens.output) + '</td>' +
2924
- '<td class="num">' + fmtUSD(m.costUSD) + '</td>' +
2925
- '<td class="num">' + pct + '%' +
2926
- '<span class="bar-wrap"><span class="bar-fill" style="width:' + barW + 'px"></span></span>' +
2927
- '</td></tr>';
2928
- });
2929
- html += '</tbody></table>';
2930
- modelWrap.innerHTML = html;
2931
- }
3959
+ const kpis = useMemoApp(() => {
3960
+ const { kpisForRange } = window.TW;
3961
+ return kpisForRange(range);
3962
+ }, [range, _sseV]);
2932
3963
 
2933
- // User table
2934
- const userEntries = Object.entries(r.byUser);
2935
- const usersSection = document.getElementById('users-section');
2936
- usersSection.style.display = userEntries.length === 0 ? 'none' : '';
2937
- if (userEntries.length > 0) {
2938
- let html = '<table><thead><tr><th>User</th><th class="num">Calls</th><th class="num">Cost</th></tr></thead><tbody>';
2939
- userEntries.slice().sort(function(a,b) { return b[1].costUSD - a[1].costUSD; }).forEach(function(e) {
2940
- html += '<tr><td>' + escHtml(e[0]) + '</td><td class="num">' + fmtNum(e[1].calls) + '</td><td class="num">' + fmtUSD(e[1].costUSD) + '</td></tr>';
2941
- });
2942
- html += '</tbody></table>';
2943
- document.getElementById('user-table-wrap').innerHTML = html;
2944
- }
3964
+ const series = useMemoApp(() => {
3965
+ const { seriesForRange } = window.TW;
3966
+ return seriesForRange(range);
3967
+ }, [range, _sseV]);
2945
3968
 
2946
- // Feature table
2947
- const featureEntries = Object.entries(r.byFeature);
2948
- const featuresSection = document.getElementById('features-section');
2949
- featuresSection.style.display = featureEntries.length === 0 ? 'none' : '';
2950
- if (featureEntries.length > 0) {
2951
- let html = '<table><thead><tr><th>Feature</th><th class="num">Calls</th><th class="num">Cost</th></tr></thead><tbody>';
2952
- featureEntries.slice().sort(function(a,b) { return b[1].costUSD - a[1].costUSD; }).forEach(function(e) {
2953
- html += '<tr><td>' + escHtml(e[0]) + '</td><td class="num">' + fmtNum(e[1].calls) + '</td><td class="num">' + fmtUSD(e[1].costUSD) + '</td></tr>';
2954
- });
2955
- html += '</tbody></table>';
2956
- document.getElementById('feature-table-wrap').innerHTML = html;
2957
- }
3969
+ const models = kpis.models;
2958
3970
 
2959
- // Forecast
2960
- document.getElementById('fc-daily').textContent = fmtUSD(fc.projectedDailyCostUSD);
2961
- document.getElementById('fc-monthly').textContent = fmtUSD(fc.projectedMonthlyCostUSD);
2962
- document.getElementById('fc-burn').textContent = fmtUSD(fc.burnRatePerHour);
2963
- document.getElementById('fc-window').textContent =
2964
- fc.basedOnHours > 0 ? 'based on ' + fc.basedOnHours.toFixed(1) + 'h of data' : 'insufficient data';
3971
+ useEffectApp(() => {
3972
+ const onKey = (e) => {
3973
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
3974
+ e.preventDefault();
3975
+ if (t.commandPalette) setPaletteOpen((v) => !v);
3976
+ }
3977
+ };
3978
+ window.addEventListener('keydown', onKey);
3979
+ return () => window.removeEventListener('keydown', onKey);
3980
+ }, [t.commandPalette]);
2965
3981
 
2966
- // Footer
2967
- document.getElementById('footer-updated').textContent =
2968
- 'Last updated: ' + fmtDate(data.lastUpdated);
2969
- }
3982
+ const handleAction = (act) => {
3983
+ if (!act) return;
3984
+ if (act.range) setRange(act.range);
3985
+ if (act.model) {
3986
+ const m = models.find((x) => x.id === act.model);
3987
+ if (m) setSelModel({ ...m, share: m.cost / Math.max(kpis.cost, 0.0001) });
3988
+ }
3989
+ };
2970
3990
 
2971
- // \u2500\u2500 Boot \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2972
- reconnect();
2973
- })();
3991
+ return (
3992
+ <div className="tw-root" style={{ '--accent': t.accent }}>
3993
+ <Header t={t} onOpenPalette={() => setPaletteOpen(true)} />
3994
+ {t.appState === 'loading' ? (
3995
+ <main className="tw-main"><LoadingSkeleton /></main>
3996
+ ) : t.appState === 'empty' ? (
3997
+ <main className="tw-main"><EmptyState /></main>
3998
+ ) : (
3999
+ <main className="tw-main">
4000
+ <BudgetBar t={t} />
4001
+ <KpiRow kpis={kpis} range={range} t={t} />
4002
+ <TimeFilter range={range} setRange={setRange} t={t} setTweak={setTweak} />
4003
+ <ChartsRow range={range} models={models} kpis={kpis} series={series} t={t} />
4004
+ <ModelTable models={models} total={kpis.cost} t={t} exampleHover={t.smartHighlight}
4005
+ onRowClick={(m) => setSelModel({ ...m, share: m.cost / Math.max(kpis.cost, 0.0001) })} />
4006
+ <ForecastSection t={t} />
4007
+ <LiveActivity t={t} />
4008
+ </main>
4009
+ )}
4010
+ <SlideOver model={selModel} onClose={() => setSelModel(null)} t={t} />
4011
+ <CommandPalette open={paletteOpen} onClose={() => setPaletteOpen(false)} onAction={handleAction} />
4012
+ <TweaksPanel title="Tweaks \xB7 UX">
4013
+ <TweakSection label="Hierarquia &amp; densidade" />
4014
+ <TweakRadio label="Densidade" value={t.density} options={[{ value: 'compact', label: 'Compacto' }, { value: 'comfy', label: 'Confort.' }]} onChange={(v) => setTweak('density', v)} />
4015
+ <TweakToggle label="Sparklines nos KPIs" value={t.kpiSparklines} onChange={(v) => setTweak('kpiSparklines', v)} />
4016
+ <TweakToggle label="Smart highlight" value={t.smartHighlight} onChange={(v) => setTweak('smartHighlight', v)} />
4017
+ <TweakSection label="An\xE1lise" />
4018
+ <TweakToggle label="Comparar c/ per\xEDodo anterior" value={t.compareMode} onChange={(v) => setTweak('compareMode', v)} />
4019
+ <TweakToggle label="Sorting + a\xE7\xF5es na tabela" value={t.tableSort} onChange={(v) => setTweak('tableSort', v)} />
4020
+ <TweakSection label="Custo proativo" />
4021
+ <TweakToggle label="Alertas de budget" value={t.budgetAlerts} onChange={(v) => setTweak('budgetAlerts', v)} />
4022
+ <TweakSlider label="Cen\xE1rio: crescimento" value={t.forecastScenario} min={0} max={300} step={5} unit="%" onChange={(v) => setTweak('forecastScenario', v)} />
4023
+ <TweakSection label="Tempo real" />
4024
+ <TweakToggle label="Live feed" value={t.liveFeed} onChange={(v) => setTweak('liveFeed', v)} />
4025
+ <TweakRadio label="Anima\xE7\xE3o" value={t.animLevel} options={[{ value: 'lively', label: 'Vivo' }, { value: 'subtle', label: 'Sutil' }, { value: 'minimal', label: 'M\xEDn.' }]} onChange={(v) => setTweak('animLevel', v)} />
4026
+ <TweakSection label="Navega\xE7\xE3o &amp; estado" />
4027
+ <TweakToggle label="Command palette (\u2318K)" value={t.commandPalette} onChange={(v) => setTweak('commandPalette', v)} />
4028
+ <TweakRadio label="Estado" value={t.appState} options={[{ value: 'data', label: 'Dados' }, { value: 'loading', label: 'Load' }, { value: 'empty', label: 'Vazio' }]} onChange={(v) => setTweak('appState', v)} />
4029
+ <TweakSection label="Visual" />
4030
+ <TweakColor label="Accent" value={t.accent} options={['#58a6ff', '#3fb950', '#bc8cff', '#f778ba']} onChange={(v) => setTweak('accent', v)} />
4031
+ </TweaksPanel>
4032
+ </div>
4033
+ );
4034
+ }
4035
+ ReactDOM.createRoot(document.getElementById('root')).render(React.createElement(App));
2974
4036
  </script>
2975
4037
  </body>
2976
4038
  </html>`;