cctop 0.12.0

An htop-like terminal monitor for AI coding agent sessions (Claude Code, Codex, Cursor, Gemini CLI, OpenCode, Pi, Windsurf)
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
<title>cctop</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<style>__CCTOP_CSS__
  .totals { display: flex; gap: 18px; flex-wrap: wrap; align-items: baseline; }
  .totals b { font-family: var(--mono); font-weight: 600; }
  .totals .k { color: var(--faint); font-size: 11px; text-transform: uppercase; letter-spacing: .06em; }

  .controls { display: flex; gap: 8px; align-items: center; margin-bottom: 14px; flex-wrap: wrap; }
  input[type=search] {
    flex: 1 1 200px; min-width: 0; padding: 7px 11px; font: inherit; font-size: 14px;
    background: var(--panel); color: var(--ink);
    border: 1px solid var(--line); border-radius: 8px;
  }
  input[type=search]:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
  button {
    padding: 7px 11px; font: inherit; font-size: 13px; cursor: pointer;
    background: var(--panel); color: var(--dim);
    border: 1px solid var(--line); border-radius: 8px;
  }
  button[aria-pressed=true] { color: var(--accent); border-color: var(--accent); }
  select {
    padding: 7px 9px; font: inherit; font-size: 13px; cursor: pointer;
    background: var(--panel); color: var(--dim);
    border: 1px solid var(--line); border-radius: 8px;
  }

  /* Sessions waiting on a person get their own block at the top. The whole
     reason to look at this on a phone is to find them. */
  .attention { border-color: var(--amber); margin-bottom: 16px; }
  .attention h2 { font-size: 12px; text-transform: uppercase; letter-spacing: .06em;
                  color: var(--amber); padding: 11px 14px 0; }

  .rows { display: block; }
  .row {
    display: grid; gap: 2px 10px; padding: 11px 14px; border-top: 1px solid var(--line);
    grid-template-columns: 8px minmax(0, 1fr) auto;
    text-decoration: none; color: inherit; cursor: pointer;
  }
  .row:first-of-type { border-top: 0; }
  .row:hover, .row:focus-visible { background: color-mix(in srgb, var(--accent) 7%, transparent); }
  .row .dot { margin-top: 7px; }
  .row .name { min-width: 0; font-weight: 500; }
  .row .name .title { color: var(--dim); font-weight: 400; }
  .row .meta { grid-column: 2; display: flex; gap: 8px; flex-wrap: wrap; font-size: 12px; color: var(--faint); }
  .row .figures { grid-row: 1 / span 2; grid-column: 3; text-align: right; font-family: var(--mono);
                  font-variant-numeric: tabular-nums; font-size: 13px; white-space: nowrap; }
  .row .figures .sub { font-size: 11px; color: var(--faint); }
  .trunc { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

  /* The context bar, the one figure that is a proportion rather than a count. */
  .ctx { display: inline-block; width: 46px; height: 5px; border-radius: 3px;
         background: var(--line); overflow: hidden; vertical-align: middle; }
  .ctx i { display: block; height: 100%; background: var(--dim); }

  /* A session that is waiting, with the box for answering it. The row stays a
     link to the whole session; the form sits under it rather than inside it,
     because a form inside an anchor is neither valid nor operable. */
  .wanting { border-top: 1px solid var(--line); }
  .wanting:first-child { border-top: 0; }
  .wanting .row { border-top: 0; }
  form.say { display: flex; gap: 8px; padding: 0 14px 11px 32px; }
  form.say input {
    flex: 1 1 auto; min-width: 0; font: inherit; font-size: 13px; padding: 6px 9px;
    border-radius: 7px; border: 1px solid var(--line); background: var(--bg); color: var(--ink);
  }
  form.say input:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
  form.say button {
    font: inherit; font-size: 13px; padding: 0 13px; border-radius: 7px; cursor: pointer;
    border: 1px solid var(--accent); background: var(--accent); color: var(--panel);
  }
  form.say button:disabled { opacity: .5; cursor: default; }
  form.say .said { font-size: 12px; align-self: center; color: var(--faint); }
  form.say .said.bad { color: var(--red); }
  .ctx i.hot { background: var(--amber); }
  .ctx i.full { background: var(--red); }

  footer { margin-top: 20px; font-size: 12px; color: var(--faint);
           display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
  .live { display: inline-flex; align-items: center; gap: 6px; }
</style>

<div class="wrap">
  <header class="top">
    <h1>cctop<span class="v mono">__CCTOP_VERSION__</span></h1>
    <div class="spacer"></div>
    <div class="totals" id="totals"></div>
  </header>

  <div id="banners"></div>

  <div class="controls">
    <input type="search" id="filter" placeholder="Filter on project, model, branch, title…" autocomplete="off" spellcheck="false">
    <button id="running" aria-pressed="false" title="Show only sessions with a live process">Running</button>
    <button id="bell" aria-pressed="false" title="Notify when a session starts waiting on you">Notify</button>
    <select id="sort" title="Order the table">
      <option value="recent">Recent</option>
      <option value="cost">Cost</option>
      <option value="tokens">Tokens</option>
      <option value="context">Context</option>
    </select>
  </div>

  <section class="card attention" id="attention" hidden>
    <h2 id="attention-heading"></h2>
    <div class="rows" id="attention-rows"></div>
  </section>

  <section class="card">
    <div class="rows" id="rows"></div>
    <div class="empty" id="empty">Waiting for the first refresh…</div>
  </section>

  <footer>
    <span class="live"><span class="dot idle" id="link"></span><span id="link-text">connecting…</span></span>
    <span class="spacer"></span>
    <span id="counts"></span>
  </footer>
</div>

<script>
"use strict";
const TOKEN = "__CCTOP_TOKEN__";
const QUERY = TOKEN ? "?t=" + encodeURIComponent(TOKEN) : "";
// Whether this run serves the routes that act on a session. Substituted by the
// server, so the answer box is never drawn for a page that could not send it.
const CAN_ACT = "__CCTOP_ACTIONS__";

// Every string from a transcript — titles, branches, paths, model names — is
// written through textContent or this. None of it is trusted markup, and a
// project directory is perfectly free to be called `<img onerror=…>`.
const el = (tag, cls, text) => {
  const node = document.createElement(tag);
  if (cls) node.className = cls;
  if (text !== undefined && text !== null) node.textContent = String(text);
  return node;
};

const money = (n) => {
  if (n === null || n === undefined) return "";
  const v = Number(n);
  if (!isFinite(v)) return "";
  if (v === 0) return "$0";
  if (v < 0.01) return "<$0.01";
  return "$" + (v < 10 ? v.toFixed(2) : Math.round(v).toLocaleString());
};

const tokens = (n) => {
  const v = Number(n) || 0;
  if (v >= 1e9) return (v / 1e9).toFixed(1) + "G";
  if (v >= 1e6) return (v / 1e6).toFixed(1) + "M";
  if (v >= 1e3) return (v / 1e3).toFixed(1) + "k";
  return String(v);
};

const ago = (iso) => {
  const then = Date.parse(iso);
  if (!isFinite(then)) return "";
  const secs = Math.max(0, (Date.now() - then) / 1000);
  if (secs < 60) return Math.floor(secs) + "s";
  if (secs < 3600) return Math.floor(secs / 60) + "m";
  if (secs < 86400) return Math.floor(secs / 3600) + "h";
  return Math.floor(secs / 86400) + "d";
};

// The cost a row shows. `total` arrives as a six-decimal string — the JSON
// document is exact on purpose — so it is reformatted here rather than printed,
// which would put `$0.000000` in a column four characters wide.
//
// `incl`, `—` and a figure are three different claims: the plan bundles this,
// the provider records no usage at all, and here is what it cost. None of them
// may be rendered as either of the others.
const rowCost = (s) => {
  if (s.cost.included) return "incl";
  if (!s.cost.available) return "";
  if (s.cost.total === null || s.cost.total === undefined) return "";
  return money(Number(s.cost.total));
};

// The home directory, so paths under it read as `~/…` the way they do in the
// terminal. Substituted by the server rather than derived here, because a
// browser cannot know it — and this page may be open on a different machine.
const HOME = "__CCTOP_HOME__";

// A working directory is often deep enough to fill a phone's width on its own,
// and the part that says which checkout this is lives at the end. The whole
// path stays on the element's title.
const shortPath = (path) => {
  const full = String(path);
  if (HOME && full.startsWith(HOME + "/")) return "~" + full.slice(HOME.length);
  if (HOME && full === HOME) return "~";
  const parts = full.split("/").filter(Boolean);
  return parts.length <= 2 ? full : "…/" + parts.slice(-2).join("/");
};

// Model names arrive fully qualified from gateways and proxies
// (`vendor/publisher/model`). The last segment is the part anyone reads.
const shortModel = (model) => {
  const parts = String(model).split("/").filter(Boolean);
  return parts.length ? parts[parts.length - 1] : model;
};

let sessions = [];
let filter = "";
let runningOnly = false;
let sortBy = "recent";

// How the table is ordered, by what the reader picked.
//
// Every one of these is descending, because every one of them is a question of
// the form "which is the most" — the most recent, the most expensive, the
// fullest window. An ascending sort would answer a question nobody asks of this
// table.
//
// `recent` is what the server already sends, and re-sorting it here rather than
// leaning on that keeps the order a property of the page: a payload that ever
// arrives in a different order does not silently change what "Recent" means.
const ORDER = {
  recent: (a, b) => String(b.last_active).localeCompare(String(a.last_active)),
  cost: (a, b) => (Number(b.cost.total) || 0) - (Number(a.cost.total) || 0),
  tokens: (a, b) => (Number(b.tokens.total) || 0) - (Number(a.tokens.total) || 0),
  // A session whose harness reports no window sorts last rather than as zero:
  // "nothing is known" is not "the window is empty".
  context: (a, b) => share(b) - share(a),
};
const share = (s) => (s.context && s.context.max ? s.context.used / s.context.max : -1);
// What each session's state was last render, so a *transition* into waiting can
// be told from a session that has been waiting since before the page opened.
// Without it every refresh would re-notify about the same idle agent.
let previousState = new Map();
let firstRender = true;

const matches = (s, needle) => {
  if (!needle) return true;
  const hay = [
    s.project, s.title, s.model, s.harness, s.branch, s.provider,
    s.session_id, s.user, s.state,
  ].filter(Boolean).join(" ").toLowerCase();
  return needle.split(/\s+/).filter(Boolean).every((word) => hay.includes(word));
};

function contextBar(s) {
  const box = el("span", "ctx");
  const ctx = s.context;
  if (!ctx || !ctx.max) return null;
  const pct = Math.min(100, (ctx.used / ctx.max) * 100);
  const fill = el("i");
  fill.style.width = pct.toFixed(1) + "%";
  if (pct >= 90) fill.className = "full";
  else if (pct >= 70) fill.className = "hot";
  box.appendChild(fill);
  box.title = Math.round(pct) + "% of the context window";
  return box;
}

function rowFor(s) {
  const row = el("a", "row");
  row.href = "/session/" + encodeURIComponent(s.session_id) + QUERY;
  row.setAttribute("role", "listitem");

  row.appendChild(el("span", "dot " + (s.running || s.state === "error" ? s.state : "idle")));

  const name = el("div", "name trunc");
  name.appendChild(el("span", null, s.project ? shortPath(s.project) : s.session_id.slice(0, 8)));
  if (s.title) {
    name.appendChild(el("span", "title", " · " + s.title));
  }
  // The full path is worth having, but not worth the width. `title` is also
  // what a screen reader reads out, which is the same trade.
  if (s.project) name.title = s.project;
  row.appendChild(name);

  const meta = el("div", "meta");
  const tag = (text, cls) => { if (text) meta.appendChild(el("span", cls || null, text)); };
  tag(s.model ? shortModel(s.model) : s.provider);
  if (s.branch) tag(s.branch);
  tag(ago(s.last_active) + " ago");
  if (s.running && s.state === "waiting") tag("waiting on you", "pill warn");
  // Louder than "waiting on you", and deliberately so: that one is your move
  // whenever you get to it, this one is an agent stopped mid-tool until you say.
  if (s.running && s.state === "asking") tag("needs permission", "pill bad");
  // "api error" in the present tense is a claim about now. For a stopped
  // session it is something that happened, and the row's last-active time is
  // already saying when.
  if (s.state === "error") tag(s.running ? "api error" : "ended on an api error", "pill bad");
  // A session with a quarter of its tool calls failing is retrying something
  // that will not work, and paying for every attempt.
  if (s.activity.tool_errors > 0 && s.activity.tool_count > 0) {
    const rate = s.activity.tool_errors / s.activity.tool_count;
    if (rate >= 0.25) tag(Math.round(rate * 100) + "% tool errors", "pill bad");
  }
  if (s.conflict) tag(s.conflict.level === "file" ? "same file as another agent" : "same repo as another agent", "pill warn");
  if (s.user) tag(s.user);
  // Which Claude login this ran under. Absent for a machine with one profile
  // and for every harness that has no such concept, so the tag appears exactly
  // where it distinguishes something.
  if (s.profile && s.profile !== "default") tag(s.profile);
  const bar = contextBar(s);
  if (bar) meta.appendChild(bar);
  row.appendChild(meta);

  const figures = el("div", "figures");
  figures.appendChild(el("div", null, rowCost(s)));
  figures.appendChild(el("div", "sub", tokens(s.tokens.total) + " tok"));
  row.appendChild(figures);

  return row;
}

// --- talking to the server -------------------------------------------------

// What went wrong, in words worth showing. A cctop error is short and arrives
// as text/plain; anything else in the body was written by something between
// this page and the server — a tunnel whose far end has gone answers with a
// whole HTML error page, and that page used to land on screen verbatim.
async function problem(response) {
  const kind = (response.headers.get("content-type") || "").split(";")[0].trim();
  const said = kind === "text/plain" ? (await response.text()).trim() : "";
  if (said) return said.length > 400 ? said.slice(0, 400) + "" : said;
  if (response.status >= 502 && response.status <= 504) return "cctop is not answering";
  if (response.status === 401 || response.status === 403) return "this link is no longer authorised";
  return "the server answered " + response.status;
}

// The body as JSON, or a sentence saying why it is not. A 200 is not a promise
// of JSON: a captive portal or a proxy answers with an HTML page and a good
// status, and the parser's complaint about it is not something to show anyone.
async function asJson(response) {
  const text = await response.text();
  try {
    return JSON.parse(text);
  } catch (e) {
    throw new Error("whatever answered this page, it was not cctop");
  }
}

// Every request the page makes. A dropped connection rejects the fetch itself
// with nothing in it worth reading, so it is named here instead.
async function ask(url, init) {
  let response;
  try {
    response = await fetch(url, init);
  } catch (e) {
    throw new Error("cctop is unreachable");
  }
  if (!response.ok) throw new Error(await problem(response));
  return response;
}

// Answering a waiting agent from the list, which is the whole point of the
// card it sits in: a page that says "this one needs you" and cannot be replied
// to has shown someone a problem and kept the fix.
//
// One line, because that is what submitting to a pty is — the server refuses a
// newline rather than sending half of a paragraph.
function answerBox(s) {
  if (!CAN_ACT || !s.running) return null;
  const form = el("form", "say");
  const input = el("input");
  input.type = "text";
  input.maxLength = 4000;
  input.autocomplete = "off";
  input.placeholder = "Answer this session…";
  const send = el("button", null, "Send");
  send.type = "submit";
  const said = el("span", "said", "");
  form.appendChild(input);
  form.appendChild(send);
  form.appendChild(said);
  // A picture pasted into the box, which is the one way an image reaches an
  // agent on a machine you are only sshed into: a terminal carries text and
  // never an image, but a browser reads a real one off the clipboard. The
  // bytes go over this connection, land in a file on the agent's machine, and
  // the box is filled with the path — which is how every one of these agents
  // reads an image. Text pastes are left entirely alone.
  input.addEventListener("paste", (event) => {
    const items = Array.from(event.clipboardData?.items || []);
    const picture = items.find((i) => i.type && i.type.startsWith("image/"));
    if (!picture) return;
    const file = picture.getAsFile();
    if (!file) return;
    event.preventDefault();
    said.className = "said";
    said.textContent = "filing the image…";
    const reader = new FileReader();
    reader.onerror = () => {
      said.className = "said bad";
      said.textContent = "could not read that image";
    };
    reader.onload = async () => {
      try {
        const response = await ask(
          "/api/act/image/" + encodeURIComponent(s.session_id) + QUERY,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ data: String(reader.result) }),
          },
        );
        const filed = await response.json();
        // Appended rather than replacing: the sentence about the picture is
        // usually already half typed by the time it is pasted.
        const room = input.value && !input.value.endsWith(" ") ? " " : "";
        input.value = input.value + room + filed.path + " ";
        input.focus();
        said.textContent = "image filed on that machine";
      } catch (e) {
        said.className = "said bad";
        said.textContent = String(e.message || e);
      }
    };
    // A data: URL, which is the spelling the server already recognises from
    // the terminal side.
    reader.readAsDataURL(file);
  });
  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    const text = input.value.trim();
    if (!text) return;
    send.disabled = true;
    said.className = "said";
    said.textContent = "";
    try {
      await ask(
        "/api/act/send/" + encodeURIComponent(s.session_id) + QUERY,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ text }),
        },
      );
      input.value = "";
      said.textContent = "sent";
    } catch (e) {
      said.className = "said bad";
      said.textContent = String(e.message || e);
    } finally {
      send.disabled = false;
    }
  });
  return form;
}

// A row in the attention card: the link, and the box for replying to it.
function wantingNode(s) {
  const box = el("div", "wanting");
  box.appendChild(rowFor(s));
  const say = answerBox(s);
  if (say) box.appendChild(say);
  return box;
}

function render() {
  const shown = sessions
    .filter((s) => matches(s, filter))
    .filter((s) => !runningOnly || s.running)
    .sort(ORDER[sortBy] || ORDER.recent);

  // Anything a person has to answer, first and on its own.
  //
  // Live sessions only. A session that hit an API error in May and has not run
  // since is history, not a call to action — promoting it puts four dead rows
  // above the one agent actually waiting, which is the opposite of what this
  // block is for. The row keeps its red dot either way; that is the table
  // saying what happened, which is a different claim from "answer me".
  const wanting = shown.filter(
    (s) =>
      s.running &&
      (s.state === "waiting" || s.state === "asking" || s.state === "error"),
  );
  const rest = shown.filter((s) => !wanting.includes(s));

  const attention = document.getElementById("attention");
  const attentionRows = document.getElementById("attention-rows");
  // Rebuilt on every refresh, so a half-typed answer would be thrown away
  // twice a second — along with the focus and the cursor, which is worse: the
  // rest of the word goes into a box that no longer exists. What is typed, what
  // was focused and where the caret sat all cross over.
  const typed = new Map();
  let focused = null;
  let caret = 0;
  for (const form of attentionRows.querySelectorAll("form.say")) {
    const input = form.querySelector("input");
    if (!form.dataset.session) continue;
    if (input.value) typed.set(form.dataset.session, input.value);
    if (document.activeElement === input) {
      focused = form.dataset.session;
      caret = input.selectionStart;
    }
  }
  attentionRows.replaceChildren(...wanting.map((s) => {
    const node = wantingNode(s);
    const form = node.querySelector("form.say");
    if (!form) return node;
    form.dataset.session = s.session_id;
    const input = form.querySelector("input");
    const carried = typed.get(s.session_id);
    if (carried) input.value = carried;
    if (focused === s.session_id) {
      input.focus();
      input.setSelectionRange(caret, caret);
    }
    return node;
  }));
  attention.hidden = wanting.length === 0;
  document.getElementById("attention-heading").textContent =
    wanting.length === 1 ? "1 session needs you" : wanting.length + " sessions need you";

  document.getElementById("rows").replaceChildren(...rest.map(rowFor));
  const empty = document.getElementById("empty");
  empty.hidden = shown.length > 0;
  if (shown.length === 0 && sessions.length > 0) empty.textContent = "Nothing matches that filter.";

  const running = sessions.filter((s) => s.running).length;
  document.getElementById("counts").textContent =
    sessions.length + " sessions · " + running + " running" +
    (shown.length !== sessions.length ? " · " + shown.length + " shown" : "");

  const totals = document.getElementById("totals");
  const today = sessions.reduce((sum, s) => sum + (s.cost.today || 0), 0);
  const hour = sessions.reduce((sum, s) => sum + (s.cost.this_hour || 0), 0);
  totals.replaceChildren();
  for (const [label, value] of [["today", money(today)], ["this hour", money(hour)]]) {
    const box = el("span");
    box.appendChild(el("b", null, value));
    box.appendChild(document.createTextNode(" "));
    box.appendChild(el("span", "k", label));
    totals.appendChild(box);
  }
}

// A desktop notification for the moment a session crosses into waiting — the
// same event the terminal's `w` rings a bell for, and the reason this page is
// worth having open on a second screen at all.
const bell = document.getElementById("bell");
let notifying = false;
bell.addEventListener("click", async () => {
  if (notifying) {
    notifying = false;
    bell.setAttribute("aria-pressed", "false");
    return;
  }
  if (!("Notification" in window)) {
    bell.textContent = "No notifications";
    bell.disabled = true;
    return;
  }
  // Must be inside the click: browsers refuse a permission prompt that no
  // gesture asked for, and refusing it once is remembered.
  const granted = await Notification.requestPermission();
  notifying = granted === "granted";
  bell.setAttribute("aria-pressed", String(notifying));
  if (!notifying) bell.title = "Your browser refused notification permission for this page";
});

function announce(next) {
  if (!notifying || firstRender) return;
  for (const s of next) {
    const was = previousState.get(s.session_id);
    if (was && was !== "asking" && s.state === "asking") {
      new Notification("Needs permission", {
        body: (s.project || s.session_id.slice(0, 8)) + (s.title ? " · " + s.title : ""),
        tag: s.session_id,
      });
    }
    if (was && was !== "waiting" && s.state === "waiting") {
      new Notification("Waiting on you", {
        body: (s.project || s.session_id.slice(0, 8)) + (s.title ? " · " + s.title : ""),
        tag: s.session_id,
      });
    }
  }
}

function apply(next) {
  announce(next);
  previousState = new Map(next.map((s) => [s.session_id, s.state]));
  sessions = next;
  firstRender = false;
  render();
}

// --- the live connection ---------------------------------------------------

const link = document.getElementById("link");
const linkText = document.getElementById("link-text");
function setLink(state, text) {
  link.className = "dot " + state;
  linkText.textContent = text;
}

let source;
function connect() {
  source = new EventSource("/api/events" + QUERY);
  source.addEventListener("sessions", (event) => {
    setLink("working", "live");
    try { apply(JSON.parse(event.data)); } catch (e) { setLink("error", "bad payload"); }
  });
  // EventSource reconnects on its own, but only from a stream that broke. An
  // answer that was never a stream — the HTML error page a tunnel serves once
  // its far end is gone — closes it for good, and the page would sit on
  // "reconnecting…" for ever. So a closed source is reopened here, on a timer,
  // because a stale table that looks live is the one failure this page must
  // not have.
  source.addEventListener("error", () => {
    if (source.readyState !== EventSource.CLOSED) {
      setLink("waiting", "reconnecting…");
      return;
    }
    setLink("error", "cctop is unreachable");
    setTimeout(connect, 5000);
  });
  source.addEventListener("open", () => setLink("working", "live"));
}

ask("/api/hosts" + QUERY)
  .then(asJson)
  .then((failed) => {
    const banners = document.getElementById("banners");
    for (const [host, why] of failed) {
      banners.appendChild(el("div", "banner", host + " could not be read: " + why));
    }
  })
  .catch(() => {});

document.getElementById("filter").addEventListener("input", (e) => {
  filter = e.target.value.trim().toLowerCase();
  render();
});
document.getElementById("sort").addEventListener("change", (e) => {
  sortBy = e.target.value;
  render();
});
document.getElementById("running").addEventListener("click", (e) => {
  runningOnly = !runningOnly;
  e.currentTarget.setAttribute("aria-pressed", String(runningOnly));
  render();
});

// Ages are relative and nothing else changes between snapshots, so a slow tick
// keeps "4m ago" honest without waiting on the next refresh.
setInterval(() => { if (sessions.length) render(); }, 15000);

connect();
</script>