aboutsummaryrefslogtreecommitdiffstats
path: root/static/dashboard.js
blob: 5dc89392fcfa491208e26216139a257456ec1490 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// deck-it - the Dashboard: one fixed screen
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

// The Dashboard tab: a top band of chips, music and spending always on, a
// row of one to three busy modules, and the action icons. The page keeps the
// trend history; the modules' APIs are the existing ones.

import { offline } from "./offline.js";

export const HISTORY = 120;   // trend samples: two minutes at 1 s
const RUNNING = ["k1c", "sbbuilder", "obs"];   // the running row's order

const G = { cpu: "", mem: "\u{f035b}", gpu: "\u{f08ae}", net: "\u{f04e1}",
            wifi: "", charging: "\u{f0084}", tux: "" };
const BATTERY = ["", "", "", "", ""];
// Nerd Font distro logos by os-release ID.
const DISTRO = {
  slackware: "", arch: "", debian: "", fedora: "",
  ubuntu: "", gentoo: "", opensuse: "", void: "",
};
const SPEND = ["var(--udt-accent)", "var(--udt-blue, #89b4fa)", "var(--udt-green, #a6e3a1)"];
const OTHER = "var(--udt-surface2)";

const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
const rate = (b) => (b >= 1048576 ? `${(b / 1048576).toFixed(1)}M` : `${Math.round((b ?? 0) / 1024)}k`);
const gib = (b) => (b / 2 ** 30).toFixed(1);
const money = (v) => (v == null ? "—" : `$${Number(v).toFixed(2)}`);
const tok = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : n >= 1e6 ? `${(n / 1e6).toFixed(1)}M`
  : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n ?? 0));
const pct = (v) => (v == null ? "—" : `${Math.round(v)}%`);
const short = (m) => String(m ?? "").split("/").pop();
const uptime = (s) => {
  const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600);
  return d ? `${d}d ${h}h` : `${h}h`;
};

export function push(list, v, n = HISTORY) {
  list.push(v);
  if (list.length > n) list.shift();
  return list;
}

// A filled area over a 120x100 viewBox, the newest sample at the right edge;
// the largest value reaches 12% from the top.
export function area(samples, max, n = HISTORY) {
  if (!samples.length) return "";
  const x = (i) => ((n - samples.length + i) * 120) / (n - 1);
  const y = (v) => 100 - Math.min(1, v / (max || 1)) * 88;
  return `M${x(0)},100 ` + samples.map((v, i) => `L${x(i)},${y(v)}`).join(" ") + " L120,100 Z";
}

// The top 3 paid models (llm.py sorts them by cost), then the rest as "other".
export function spendParts(models) {
  const paid = (models ?? []).filter((m) => m.cost > 0);
  const rest = paid.slice(3).reduce((a, m) => a + m.cost, 0);
  return rest > 0 ? [...paid.slice(0, 3), { model: "other", cost: rest }] : paid.slice(0, 3);
}

export function batteryGlyph(b) {
  if (b?.status === "charging" || b?.status === "full") return G.charging;
  return BATTERY[Math.min(4, Math.max(0, Math.round((b?.level ?? 0) / 25)))];
}

// A line too long for its slot slides to its end and back (deck.css .marq);
// one that fits stays still. Only changed values are written, so the
// animation is not restarted by every poll.
function marquee(el) {
  for (const line of el.querySelectorAll(".what, .meta")) {
    const over = line.firstElementChild.offsetWidth - line.clientWidth;
    line.classList.toggle("marq", over > 0);
    const d = `${-Math.max(0, over)}px`;
    if (line.style.getPropertyValue("--d") !== d) {
      line.style.setProperty("--d", d);
      line.style.setProperty("--t", `${2 + Math.max(0, over) / 30}s`);   // ~30 px/s plus the pauses
    }
  }
}

const SKELETON = `
  <svg class="dash-defs" width="0" height="0" aria-hidden="true"><defs>
    <linearGradient id="hyline"><stop offset="0" style="stop-color:var(--udt-border-1)"/>
      <stop offset=".5" style="stop-color:var(--udt-border-2)"/><stop offset="1" style="stop-color:var(--udt-border-3)"/></linearGradient>
    <linearGradient id="hyfill" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0" style="stop-color:var(--udt-border-2);stop-opacity:.45"/>
      <stop offset="1" style="stop-color:var(--udt-border-1);stop-opacity:.05"/></linearGradient>
  </defs></svg>
  <section class="dash-top">
    <div class="dash-id"><i class="nf logo"></i><b class="os"></b><span class="kernel"></span>
      <span class="sep">·</span><span class="up"></span></div>
    <div class="chips sys">
      <div class="chip c-cpu"><svg viewBox="0 0 120 100" preserveAspectRatio="none"><path class="hy"/></svg>
        <i class="nf ic">${G.cpu}</i><span class="col"><span class="n"></span><span class="v num"></span></span><span class="s"></span></div>
      <div class="chip c-mem"><i class="fill"></i><i class="nf ic">${G.mem}</i><span class="v num"></span><span class="s"></span></div>
      <div class="chip c-gpu"><i class="fill"></i>
        <i class="nf ic">${G.gpu}</i><span class="col"><span class="n"></span><span class="v num"></span></span><span class="s"></span></div>
      <div class="chip c-net"><svg viewBox="0 0 120 100" preserveAspectRatio="none"><path class="hy"/><path class="up"/></svg>
        <i class="nf ic">${G.net}</i><span class="v num"></span></div>
    </div>
    <div class="chips aux">
      <div class="chip c-ctx"><i class="fill"></i><span class="brand claude ic"></span><span class="v num"></span><span class="k">context</span></div>
      <div class="chip c-5h"><i class="fill"></i><span class="brand claude ic"></span><span class="v num"></span><span class="k">5h</span></div>
      <div class="chip c-7d"><i class="fill"></i><span class="brand claude ic"></span><span class="v num"></span><span class="k">7d</span></div>
      <div class="chip c-bat"><i class="fill"></i><i class="nf ic"></i><span class="v num"></span></div>
      <div class="chip c-wifi"><i class="fill"></i><i class="nf ic">${G.wifi}</i><span class="v num"></span><span class="s"></span></div>
    </div>
  </section>
  <section class="dash-mid">
    <div class="dash-always"><div class="card dash-music"></div><div class="card dash-spend"></div></div>
    <div class="dash-running" hidden></div>
  </section>
  <section class="dash-acts"></section>`;

export default {
  // names: the enabled modules; poll(name, seconds, update) and open(tab)
  // come from app.js.
  mount(section, names, { poll, open }) {
    const on = new Set(names);
    const root = document.createElement("div");
    root.className = "dash";
    root.innerHTML = SKELETON;
    section.append(root);
    const $ = (s) => root.querySelector(s);
    const chip = (sel, v, s, fill, warn) => {
      const c = $(sel);
      c.querySelector(".v").textContent = v;
      if (s != null) c.querySelector(".s").textContent = s;
      if (fill != null) c.querySelector(".fill").style.width = `${Math.max(0, Math.min(100, fill))}%`;
      c.classList.toggle("hot", Boolean(warn));
    };

    // A disabled module's parts are left out.
    $(".dash-id").hidden = !on.has("stats");
    $(".chips.sys").hidden = !on.has("stats");
    for (const c of [".c-ctx", ".c-5h", ".c-7d"]) $(c).hidden = !on.has("llm");
    $(".dash-spend").hidden = !on.has("llm");
    $(".c-bat").hidden = $(".c-wifi").hidden = !on.has("tablet");
    $(".dash-music").hidden = !on.has("music");

    const hist = { cpu: [], down: [], up: [] };
    if (on.has("stats")) poll("stats", 1, (st) => {
      $(".logo").textContent = DISTRO[st.os?.id] ?? G.tux;
      $(".os").textContent = st.os?.name ?? "";
      $(".kernel").textContent = [st.os?.codename, `Linux ${st.os?.kernel ?? ""}`].filter(Boolean).join(" · ");
      $(".up").textContent = `up ${uptime(st.uptime)}`;
      push(hist.cpu, st.cpu); push(hist.down, st.net.down); push(hist.up, st.net.up);
      $(".c-cpu .n").textContent = st.cpuName ?? "";
      $(".c-cpu path").setAttribute("d", area(hist.cpu, Math.max(25, ...hist.cpu)));
      chip(".c-cpu", `${st.cpu}%`, st.cpuTemp != null ? `${st.cpuTemp}°C` : "", null, st.cpuTemp >= 85);
      chip(".c-mem", gib(st.memUsed * 1024), `/ ${Math.round(st.memTotal / 1048576)} GiB`,
           (100 * st.memUsed) / st.memTotal);
      const g = st.gpu;
      $(".c-gpu").hidden = !g;
      if (g) {
        $(".c-gpu .n").textContent = g.name ?? "";
        chip(".c-gpu", g.temp != null ? `${g.temp}°C` : "—",
             g.memTotal ? `${gib(g.memUsed)} / ${Math.round(g.memTotal / 2 ** 30)} GiB` : `${gib(g.memUsed)} GiB`,
             g.memTotal ? (100 * g.memUsed) / g.memTotal : 0, g.temp >= 85);
      }
      const max = Math.max(1, ...hist.down, ...hist.up);
      const [down, up] = $(".c-net").querySelectorAll("path");
      down.setAttribute("d", area(hist.down, max));
      up.setAttribute("d", area(hist.up, max));
      chip(".c-net", `↓${rate(st.net.down)} ↑${rate(st.net.up)}`);
    });

    const program = (title, p) => {
      const model = `<span class="model">${esc(p.model ? short(p.model) : "—")}</span>`;
      if (!(p.cost > 0)) {   // local or free models: tokens, not dollars
        return `<div class="prog inline"><h3>${esc(title)}</h3>${model}
          <span class="tok"><span class="lbl">session</span><b class="num">${tok(p.session_tokens)}</b></span>
          <span class="tok"><span class="lbl">total</span><b class="num">${tok(p.tokens)}</b></span></div>`;
      }
      const parts = spendParts(p.models);
      const total = parts.reduce((a, m) => a + m.cost, 0);
      const color = (m, i) => (m.model === "other" ? OTHER : SPEND[i]);
      return `<div class="prog"><header><h3>${esc(title)}</h3>${model}</header>
        <div class="nums">
          <div><div class="lbl">session</div><div class="big num">${money(p.session_cost)}</div>
            <div class="sub">${tok(p.session_tokens)} · ${p.session_calls ?? 0} calls</div></div>
          <div><div class="lbl">total</div><div class="big num">${money(p.cost)}</div>
            <div class="sub">${tok(p.tokens)} · ${p.calls ?? 0} calls</div></div>
        </div>
        <div class="stack">${parts.map((m, i) =>
          `<i style="width:${(100 * m.cost) / total}%;background:${color(m, i)}"></i>`).join("")}</div>
        <div class="legend">${parts.map((m, i) =>
          `<span style="--c:${color(m, i)}">${esc(short(m.model))} ${money(m.cost)}</span>`).join("")}</div>
      </div>`;
    };
    if (on.has("llm")) poll("llm", 5, (st) => {
      const spend = $(".dash-spend");
      if (st.offline) {
        offline(spend, { icon: "/logos/claude.svg", title: "Usage dashboard is off",
                         detail: "Start llm-cost-dashboard and the spending appears here." });
        for (const c of [".c-ctx", ".c-5h", ".c-7d"]) chip(c, "—", null, 0);
        return;
      }
      const c = st.claude ?? {};
      chip(".c-ctx", pct(c.context_pct), null, c.context_pct, c.context_pct >= 80);
      chip(".c-5h", pct(c.five_hour_pct), null, c.five_hour_pct, c.five_hour_pct >= 80);
      chip(".c-7d", pct(c.seven_day_pct), null, c.seven_day_pct, c.seven_day_pct >= 80);
      spend._offline = null;
      spend.innerHTML = program("opencode", st.opencode ?? {}) + program("Local Agent", st.assistant ?? {});
    });

    if (on.has("tablet")) poll("tablet", 10, (t) => {
      const b = t.battery ?? {}, w = t.wifi ?? {};
      const charging = b.status === "charging" || b.status === "full";
      $(".c-bat .ic").textContent = batteryGlyph(b);
      chip(".c-bat", b.level != null ? `${b.level}%` : "—", null, b.level, b.level < 20 && !charging);
      chip(".c-wifi", w.rssi != null ? `${w.rssi} dBm` : "—", w.band ?? "",
           w.rssi == null ? 0 : 2 * (w.rssi + 100));   // -100 dBm empty, -50 full
    });

    if (on.has("music")) import("./modules/music.js").then(({ default: music }) => {
      const el = $(".dash-music");
      music.mount(el);
      poll("music", music.interval ?? 2, (st) => music.update(st, el));
    });

    // The running row: slots are created now, in RUNNING order, and shown
    // while their module is busy.
    const row = $(".dash-running");
    for (const name of RUNNING.filter((n) => on.has(n))) {
      const el = document.createElement("div");
      el.className = `card slot slot-${name}`;
      el.hidden = true;
      row.append(el);
      import(`./modules/${name}.js`).then((mod) => {
        if (!mod.busy || !mod.slot) return;
        const tab = mod.default?.tab;
        el.addEventListener("click", (e) => { if (tab && !e.target.closest("button")) open(tab); });
        // ponytail: the K1C and OBS tabs poll the same API; two polls a second, one cache if it matters.
        poll(name, mod.interval ?? mod.default?.interval ?? 2, (st) => {
          el.hidden = !mod.busy(st);
          if (!el.hidden) {
            mod.slot(st, el);
            marquee(el);
          }
          row.hidden = !row.querySelector(".slot:not([hidden])");
        });
      });
    }

    if (on.has("actions")) poll("actions", 30, (st) => {
      const acts = $(".dash-acts");
      const key = (st.actions ?? []).map((a) => a.id).join(",");
      if (acts._key === key) return;
      acts._key = key;
      acts.textContent = "";
      for (const a of st.actions ?? []) {
        const b = document.createElement("button");
        b.className = "nf";
        b.textContent = a.icon;
        b.title = a.label;
        b.setAttribute("aria-label", a.label);
        b.onclick = async () => {
          let ok = false;
          try {
            ok = (await fetch(`/api/actions/${a.id}`, {
              method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })).ok;
          } catch {}
          if (!ok) {
            b.classList.add("fail");
            setTimeout(() => b.classList.remove("fail"), 1500);
          }
        };
        acts.append(b);
      }
    });
  },
};