@drakonkat/ai-helper 1.1.1 → 1.2.3

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/src/tui.js CHANGED
@@ -1,6 +1,4 @@
1
- import { homedir } from "node:os";
2
- import { join } from "node:path";
3
- import { SERVICES, APP_NAME, VERSION } from "./config.js";
1
+ import { APP_NAME, VERSION } from "./config.js";
4
2
  import { manager } from "./manager.js";
5
3
  import {
6
4
  badgeStatus,
@@ -17,19 +15,18 @@ import {
17
15
  white,
18
16
  yellow,
19
17
  } from "./utils/format.js";
20
- import { killProcessTree, openBrowser } from "./utils/process.js";
18
+ import { killProcessTree } from "./utils/process.js";
19
+ import { getProxyStatsPath, readProxyStats } from "./proxy-stats.js";
20
+ import { getServiceVersions } from "./utils/versions.js";
21
21
  import {
22
- baseUrl,
23
22
  diffRates,
24
- fetchText,
25
- parseProm,
26
23
  probeChain,
27
- readSavingsBreakdown,
28
- tailJsonl,
29
24
  } from "./utils/metrics.js";
30
25
 
31
26
  const TICK_MS = 1000;
32
- const MAX_EVENTS = 200;
27
+ const STALE_MS = 5 * TICK_MS;
28
+ const VERSION_CHECK_MS = 5 * 60 * 1000;
29
+ const MAX_EVENTS = 20;
33
30
 
34
31
  const ALT_SCREEN_ON = "\x1b[?1049h";
35
32
  const ALT_SCREEN_OFF = "\x1b[?1049l";
@@ -42,17 +39,6 @@ const RESET = "\x1b[0m";
42
39
  const KEY_UP = "\x1b[A";
43
40
  const KEY_DOWN = "\x1b[B";
44
41
 
45
- /**
46
- * Location of headroom's append-only savings event log: the only real-time
47
- * per-request source in the ecosystem (pxpipe exposes no API).
48
- * @returns {string}
49
- */
50
- function getEventsFilePath() {
51
- const custom = process.env.HEADROOM_HOME;
52
- const base = custom && custom.trim().length > 0 ? custom : join(homedir(), ".headroom");
53
- return join(base, "savings_events.jsonl");
54
- }
55
-
56
42
  /**
57
43
  * Truncates a possibly coloured string to a visible width, keeping escape
58
44
  * sequences intact and always closing with a reset.
@@ -105,39 +91,118 @@ function pct(value) {
105
91
  return `${(value * 100).toFixed(1)}%`;
106
92
  }
107
93
 
94
+ function age(timestamp, now) {
95
+ const seconds = Math.max(0, Math.floor((now - timestamp) / 1000));
96
+ if (seconds < 60) return `${seconds}s`;
97
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
98
+ return `${Math.floor(seconds / 3600)}h`;
99
+ }
100
+
101
+ // Snapshot strings are data, never terminal escape sequences or extra rows.
102
+ function plain(value, fallback = "-") {
103
+ return stripAnsi(String(value ?? fallback)).replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
104
+ }
105
+
106
+ function timestamp(value) {
107
+ if (typeof value !== "string") return null;
108
+ const parsed = Date.parse(value);
109
+ return Number.isFinite(parsed) ? parsed : null;
110
+ }
111
+
112
+ function stageList(event) {
113
+ return Array.isArray(event?.stages) ? event.stages.filter(s => s && typeof s === "object") : [];
114
+ }
115
+
116
+ function savedTokens(value) {
117
+ if (!Number.isFinite(value)) return dim("non misurato");
118
+ if (value > 0) return green(`-${num(value)} tok`);
119
+ if (value < 0) return yellow(`+${num(-value)} tok`);
120
+ return dim("0 tok");
121
+ }
122
+
123
+ /** Wrap complete fields, falling back to words for long descriptions. */
124
+ function wrapCells(cells, width, separator = " | ", indent = " ") {
125
+ const lines = [];
126
+ let line = indent;
127
+ for (const cell of cells) {
128
+ if (stripAnsi(cell).length > width - indent.length) {
129
+ if (line !== indent) lines.push(line);
130
+ line = indent;
131
+ for (const word of cell.split(" ")) {
132
+ if (line !== indent && stripAnsi(line + " " + word).length > width) {
133
+ lines.push(line);
134
+ line = indent;
135
+ }
136
+ if (stripAnsi(word).length > width - indent.length) {
137
+ if (line !== indent) lines.push(line);
138
+ let remaining = stripAnsi(word);
139
+ const chunkWidth = Math.max(1, width - indent.length);
140
+ while (remaining.length > chunkWidth) {
141
+ lines.push(indent + remaining.slice(0, chunkWidth));
142
+ remaining = remaining.slice(chunkWidth);
143
+ }
144
+ line = indent + remaining;
145
+ } else line += (line === indent ? "" : " ") + word;
146
+ }
147
+ continue;
148
+ }
149
+ const next = line === indent ? cell : dim(separator) + cell;
150
+ if (line !== indent && stripAnsi(line + next).length > width) {
151
+ lines.push(line);
152
+ // Do not let the continuation arrow clip a field that just fits.
153
+ const arrow = separator === " -> " && stripAnsi(cell).length + indent.length + 3 <= width ? dim("-> ") : "";
154
+ line = indent + arrow + cell;
155
+ } else line += next;
156
+ }
157
+ if (line !== indent) lines.push(line);
158
+ return lines.map(line => clip(line, width));
159
+ }
160
+
108
161
  /**
109
162
  * Colours a pipeline node by its live state.
110
163
  * @param {{ label: string; state: string }} node
111
164
  * @returns {string}
112
165
  */
113
166
  function paintNode(node) {
114
- const label = `[ ${node.label} ]`;
115
167
  switch (node.state) {
168
+ case "healthy":
169
+ return green(`[ ${node.label}: verificato ]`);
116
170
  case "running":
117
- return green(bold(label));
171
+ return `[ ${node.label}: processo attivo ]`;
118
172
  case "error":
119
- return red(bold(label));
173
+ return red(bold(`[ ${node.label}: errore ]`));
120
174
  case "stopped":
121
- return gray(label);
175
+ return dim(`[ ${node.label}: fermo ]`);
176
+ case "static":
177
+ return `[ ${node.label} ]`;
122
178
  default:
123
- return dim(label);
179
+ return yellow(`[ ${node.label}: non verificato ]`);
124
180
  }
125
181
  }
126
182
 
127
183
  export class Dashboard {
128
- constructor() {
184
+ constructor({ getVersions = getServiceVersions, getProxyStats = readProxyStats } = {}) {
129
185
  this.statuses = [];
130
- this.metrics = null;
186
+ this.getVersions = getVersions;
187
+ this.versions = {};
188
+ this.versionsKey = "";
189
+ this.versionsAt = 0;
190
+ this.versionsLoading = false;
191
+ this.versionsGeneration = 0;
192
+ this.getProxyStats = getProxyStats;
193
+ this.metricsFile = getProxyStatsPath();
194
+ this.metricsAt = null;
195
+ this.metricsError = null;
196
+ this.metricsKey = "";
197
+ this.sampleMs = null;
131
198
  this.rates = {};
132
199
  this.prevMetrics = null;
133
200
  this.prevAt = 0;
134
201
  this.chain = [];
135
- this.health = null;
202
+ this.chainAt = null;
203
+ this.showPipelineDetails = false;
136
204
  this.events = [];
137
- this.eventsOffset = undefined;
138
- this.eventsFile = getEventsFilePath();
139
- this.eventsFileSeen = false;
140
- this.savings = null;
205
+ this.proxyStats = null;
141
206
  this.selected = 0;
142
207
  this.status = "";
143
208
  this.busy = false;
@@ -151,6 +216,31 @@ export class Dashboard {
151
216
  return this.statuses[this.selected];
152
217
  }
153
218
 
219
+ /** Checks versions independently of the one-second status/metrics refresh. */
220
+ async refreshVersions() {
221
+ const key = JSON.stringify(this.statuses.map(s => [s.id, s.status, s.pid, s.url]));
222
+ if (key !== this.versionsKey) {
223
+ this.versionsKey = key;
224
+ this.invalidateVersions();
225
+ }
226
+ if (this.busy || this.versionsLoading || (this.versionsAt && Date.now() - this.versionsAt < VERSION_CHECK_MS)) return;
227
+
228
+ const generation = this.versionsGeneration;
229
+ const isCurrent = () => key === this.versionsKey && generation === this.versionsGeneration;
230
+ this.versionsLoading = true;
231
+ try {
232
+ const versions = await this.getVersions(this.statuses);
233
+ if (isCurrent()) this.versions = versions;
234
+ } catch {
235
+ // An unavailable registry must not interrupt service controls or metrics.
236
+ if (isCurrent()) this.versions = {};
237
+ } finally {
238
+ if (isCurrent()) this.versionsAt = Date.now();
239
+ this.versionsLoading = false;
240
+ this.render();
241
+ }
242
+ }
243
+
154
244
  /**
155
245
  * One data tick. Every source is optional: a failing fetch degrades its own
156
246
  * panel and never breaks the loop.
@@ -160,46 +250,181 @@ export class Dashboard {
160
250
  this.refreshing = true;
161
251
  try {
162
252
  this.statuses = await manager.getStatus();
253
+ void this.refreshVersions();
163
254
  if (this.selected >= this.statuses.length) {
164
255
  this.selected = Math.max(0, this.statuses.length - 1);
165
256
  }
166
257
 
167
- const headroom = this.statuses.find(s => s.id === "headroom");
168
- const headroomBase = headroom && headroom.status === "running" ? baseUrl(headroom.url) : "";
169
-
170
- const metricsText = headroomBase ? await fetchText(`${headroomBase}/metrics`, 2000) : null;
171
- if (metricsText) {
172
- const parsed = parseProm(metricsText);
173
- const now = Date.now();
174
- this.rates = diffRates(this.prevMetrics, parsed, now - this.prevAt);
175
- this.prevMetrics = parsed;
258
+ const proxy = this.statuses.find(s => s.id === "proxy");
259
+ const stats = await this.getProxyStats();
260
+ const probed = await probeChain(this.statuses, { nativeOnly: true });
261
+ const now = Date.now();
262
+ const metricsKey = JSON.stringify([proxy?.url, proxy?.pid, proxy?.status, stats?.since]);
263
+ if (metricsKey !== this.metricsKey || (stats && stats.requests < this.prevMetrics?.requests)) this.prevMetrics = null;
264
+ this.metricsKey = metricsKey;
265
+ if (stats) {
266
+ // updatedAt is the last preset event, not a heartbeat. An idle proxy's
267
+ // unchanged snapshot is still readable; retain its real last-event age.
268
+ this.proxyStats = stats;
269
+ this.metricsAt = now;
270
+ this.events = stats.recent.filter(ev => ev && typeof ev === "object" && !Array.isArray(ev)).slice(-MAX_EVENTS);
271
+ }
272
+ this.metricsError = !proxy ? "Proxy AIH non configurato"
273
+ : proxy.status !== "running" ? "Proxy AIH non in esecuzione"
274
+ : !stats ? "Statistiche proxy assenti o non valide" : null;
275
+ if (!this.metricsError) {
276
+ const counters = { requests: stats.requests };
277
+ this.sampleMs = this.prevMetrics ? now - this.prevAt : null;
278
+ this.rates = diffRates(this.prevMetrics, counters, this.sampleMs);
279
+ this.prevMetrics = counters;
176
280
  this.prevAt = now;
177
- this.metrics = parsed;
178
281
  } else {
179
- this.metrics = null;
282
+ // Keep the last totals and events for diagnosis, but never old rates.
180
283
  this.rates = {};
181
284
  this.prevMetrics = null;
285
+ this.sampleMs = null;
182
286
  }
183
287
 
184
- const probed = await probeChain(this.statuses);
185
288
  this.chain = probed.nodes;
186
- this.health = probed.health;
187
-
188
- const tail = tailJsonl(this.eventsFile, this.eventsOffset, MAX_EVENTS);
189
- this.eventsOffset = tail.offset;
190
- if (tail.offset > 0) this.eventsFileSeen = true;
191
- if (tail.events.length > 0) {
192
- this.events = this.events.concat(tail.events).slice(-MAX_EVENTS);
193
- }
194
-
195
- this.savings = readSavingsBreakdown();
289
+ this.chainAt = now;
196
290
  } catch (err) {
291
+ this.metricsError = "aggiornamento fallito";
292
+ this.rates = {};
293
+ this.prevMetrics = null;
294
+ this.sampleMs = null;
295
+ this.chainAt = null;
197
296
  this.status = red(`Refresh error: ${err?.message || err}`);
198
297
  } finally {
199
298
  this.refreshing = false;
200
299
  }
201
300
  }
202
301
 
302
+ /** Pipeline rows wrap whole fields rather than clipping useful values. */
303
+ pipelineLines(width, now = Date.now()) {
304
+ const lines = [bold("PIPELINE") + dim(" metriche proxy AIH")];
305
+ const add = (cells, separator) => lines.push(...wrapCells(cells, width, separator));
306
+ const chainFresh = this.chainAt !== null && now - this.chainAt <= STALE_MS;
307
+ add(this.chain.map(node => paintNode(chainFresh || node.state === "static"
308
+ ? node : { ...node, state: "unknown" })), " -> ");
309
+
310
+ const stale = this.metricsStale(now);
311
+ const freshness = this.metricsAt === null ? "nessun campione"
312
+ : `ultimo campione ${age(this.metricsAt, now)} fa`;
313
+ const freshnessText = stale ? yellow(`Dati non aggiornati: ${freshness}`) : `Letti ${age(this.metricsAt, now)} fa`;
314
+ if (stripAnsi(lines[0] + " | " + freshnessText).length <= width) lines[0] += dim(" | ") + freshnessText;
315
+ else add([freshnessText]);
316
+ if (this.metricsError) add([yellow(this.metricsError)]);
317
+
318
+ const preset = this.statuses.find(s => s.id === "proxy")?.proxyOptions?.preset;
319
+ if (preset === "none") add([yellow("Preset none: traffico non registrato nelle metriche")]);
320
+ if (this.proxyStats) {
321
+ const m = this.proxyStats;
322
+ const lastAt = timestamp(m.updatedAt);
323
+ add([bold("Elaborazioni preset"), stale ? dim("attivita non disponibile")
324
+ : `${cyan(bold(num(this.rates.requests, 2)))} elab/s`,
325
+ `Ultimo evento ${lastAt === null ? "-" : age(lastAt, now) + " fa"}`]);
326
+ const changedRatio = Number.isFinite(m.changed) && m.requests > 0 ? m.changed / m.requests : null;
327
+ add([bold("Dall'avvio dei contatori") + (stale ? yellow(" (ultimo campione)") : "")]);
328
+ add([`Richieste ${bold(num(m.requests))}`, `Modificate ${bold(num(m.changed))} (${pct(changedRatio)})`,
329
+ `Errori preset ${m.errors > 0 ? red(bold(num(m.errors))) : num(m.errors)}`]);
330
+ add([`risparmio stimato ${bold(num(m.estimatedSavedTokens))} token${m.unmeasuredStages > 0 ? yellow(" (parziale)") : ""}`]);
331
+ for (const [name, stage] of Object.entries(m.stages || {})) {
332
+ if (!stage || typeof stage !== "object") continue;
333
+ add([`${plain(name)}: ${bold(num(stage.saved))} token`, `applicato ${num(stage.applied)}/${num(stage.requests)}`,
334
+ ...(stage.unmeasured > 0 ? [yellow(`non misurati ${num(stage.unmeasured)}`)] : [])]);
335
+ }
336
+ }
337
+ add([dim("Stime dei preset; esclusi interceptor, cache e fatturazione.")]);
338
+
339
+ if (this.showPipelineDetails) {
340
+ add([`Fonte: ${plain(this.metricsFile)}`]);
341
+ if (this.proxyStats?.since) add([`Contatori dal ${plain(this.proxyStats.since)} (persistono ai riavvii)`]);
342
+ for (const node of this.chain) {
343
+ if (node.detail) add([`${node.label}: ${plain(node.detail)}`]);
344
+ if (node.state === "running") add([yellow(`${node.label}: health non verificato`)]);
345
+ }
346
+ if (!chainFresh) add([yellow("Stati della catena non aggiornati")]);
347
+ if (this.proxyStats && !stale) {
348
+ add([dim(this.sampleMs === null ? "Velocita: in attesa del secondo campione"
349
+ : `Velocita: ultimo intervallo di ${(this.sampleMs / 1000).toFixed(1)} s`)]);
350
+ }
351
+ add([dim("elab/s: richieste elaborate dai preset, non tutto il traffico proxy")]);
352
+ add([dim("Risparmio: somma dei delta misurati per stadio; basi non sommabili")]);
353
+ add([dim("Errori preset != errori upstream; latenza e richieste in corso non misurate")]);
354
+ }
355
+ return lines.map(line => clip(line, width));
356
+ }
357
+
358
+ /** Updates can change an installed version without changing status or PID. */
359
+ invalidateVersions() {
360
+ this.versionsGeneration++;
361
+ this.versionsAt = 0;
362
+ this.versions = {};
363
+ }
364
+
365
+ metricsStale(now = Date.now()) {
366
+ return this.metricsAt === null || Boolean(this.metricsError) || now - this.metricsAt > STALE_MS;
367
+ }
368
+
369
+ /** Native recent events are a bounded snapshot, not an append-only log. */
370
+ requestLines(event, width) {
371
+ const at = timestamp(event.at);
372
+ const time = at === null ? "--:--:--" : new Date(at).toLocaleTimeString("it-IT", { hour12: false });
373
+ const stages = stageList(event);
374
+ const partial = !event.error && stages.some(stage => !Number.isFinite(stage.saved));
375
+ const unmeasured = partial && stages.every(stage => !Number.isFinite(stage.saved));
376
+ const status = event.error ? red(bold("errore preset")) : event.changed === true ? green("modificata")
377
+ : event.changed === false ? dim("invariata") : dim("esito non disponibile");
378
+ const lines = wrapCells([gray(time), cyan(plain(event.transport)), magenta(plain(event.model, "?")),
379
+ plain(event.preset), status,
380
+ ...(event.error ? [] : [savedTokens(unmeasured ? null : event.saved) + (partial && !unmeasured ? yellow(" (parziale)") : "")]),
381
+ ...(!this.showPipelineDetails ? stages.map(s => dim(`${plain(s.name)}: ${plain(s.reason)}`)) : []),
382
+ ], width, " ");
383
+ if (this.showPipelineDetails) {
384
+ for (const stage of stages) {
385
+ const ratio = Number.isFinite(stage.before) && stage.before > 0 && Number.isFinite(stage.saved)
386
+ ? stage.saved / stage.before : null;
387
+ lines.push(...wrapCells([`${plain(stage.name)}: ${stage.applied ? "applicato" : "bypass"}`,
388
+ `${num(stage.before)} -> ${num(stage.after)} tok (${pct(ratio)})`,
389
+ plain(stage.reason), dim(plain(stage.method)),
390
+ ], width, " | ", " "));
391
+ }
392
+ }
393
+ return lines;
394
+ }
395
+
396
+ streamLines(width, maxRows = Infinity, now = Date.now()) {
397
+ if (maxRows <= 0) return [];
398
+ const lines = [clip(bold("STREAM RICHIESTE")
399
+ + (this.metricsStale(now) && this.proxyStats ? yellow(" (storico)") : "")
400
+ + dim(" proxy AIH / elaborazioni preset"), width)];
401
+ if (maxRows === 1) return lines;
402
+ if (!this.events.length) {
403
+ const preset = this.statuses.find(s => s.id === "proxy")?.proxyOptions?.preset;
404
+ const message = preset === "none" ? "preset none: nessun evento di elaborazione"
405
+ : this.proxyStats ? "in attesa di richieste elaborate dai preset..."
406
+ : "nessun evento proxy disponibile";
407
+ return lines.concat(wrapCells([dim(message)], width).slice(0, maxRows - 1));
408
+ }
409
+ const groups = [];
410
+ let available = maxRows - lines.length;
411
+ // Keep newest complete entries, then show them in chronological order.
412
+ for (const event of this.events.slice().reverse()) {
413
+ const group = this.requestLines(event, width);
414
+ if (group.length > available) {
415
+ if (!groups.length) {
416
+ const clipped = group.slice(0, available);
417
+ if (clipped.length) clipped[clipped.length - 1] = clip(clipped.at(-1), Math.max(0, width - 4)) + dim(" ...");
418
+ groups.unshift(clipped);
419
+ }
420
+ break;
421
+ }
422
+ groups.unshift(group);
423
+ available -= group.length;
424
+ }
425
+ return lines.concat(groups.flat());
426
+ }
427
+
203
428
  /**
204
429
  * Builds the whole screen as an array of lines.
205
430
  * @returns {string[]}
@@ -208,6 +433,21 @@ export class Dashboard {
208
433
  const width = Math.max(40, process.stdout.columns || 100);
209
434
  const height = Math.max(12, process.stdout.rows || 30);
210
435
  const lines = [];
436
+ const svc = this.currentService();
437
+ const target = svc ? bold(svc.id) : dim("-");
438
+ const keyLines = wrapCells([
439
+ `${dim("d")} ${this.showPipelineDetails ? "riduci" : "dettagli"}`,
440
+ `${dim("q")} esci`,
441
+ `${dim("up/down")} seleziona (${target})`,
442
+ `${dim("s")} start`,
443
+ `${dim("x")} stop`,
444
+ `${dim("r")} restart`,
445
+ `${dim("u")} update`,
446
+ `${dim("k")} kill`,
447
+ ...(svc?.dashboardUrl ? [`${dim("o")} dashboard`] : []),
448
+ ...(svc?.repositoryUrl ? [`${dim("g")} GitHub`] : []),
449
+ ], width, " ", "");
450
+ const footerLines = keyLines.length + 2;
211
451
 
212
452
  const title = `${bold(cyan(APP_NAME))} ${gray("v" + VERSION)} ${dim("live dashboard")}`;
213
453
  const clock = dim(new Date().toLocaleTimeString());
@@ -219,19 +459,31 @@ export class Dashboard {
219
459
  " ",
220
460
  "SERVICE",
221
461
  "STATUS",
462
+ "VERSION",
463
+ "UPDATE",
222
464
  { header: "PID", align: "right" },
223
465
  { header: "UPTIME", align: "right" },
466
+ "REPO",
224
467
  "URL",
225
468
  ];
226
469
  const rows = this.statuses.map((s, idx) => {
227
470
  const active = idx === this.selected;
471
+ const version = this.versions[s.id];
472
+ const update = version?.updateAvailable === true
473
+ ? yellow(bold(`↑ ${version.latestVersion}`))
474
+ : version?.updateAvailable === false
475
+ ? green("aggiornato")
476
+ : dim(this.versionsLoading && !version ? "verifica..." : "n/d");
228
477
  return [
229
478
  active ? cyan(bold(">")) : " ",
230
479
  active ? bold(white(s.id)) : bold(s.id),
231
480
  badgeStatus(s.status),
481
+ version?.version || dim("n/d"),
482
+ update,
232
483
  s.pid ? String(s.pid) : dim("-"),
233
484
  s.status === "running" ? s.uptime : dim("-"),
234
- s.status === "running" && s.url && s.url !== "-" ? cyan(underline(s.url)) : dim(s.url || "-"),
485
+ s.repositoryUrl ? cyan(underline(s.repositoryUrl.replace("https://github.com/", ""))) : dim("-"),
486
+ s.id === "proxy" ? dim(`${s.url} (proxy)`) : s.status === "running" && s.url && s.url !== "-" ? cyan(underline(s.url)) : dim(s.url || "-"),
235
487
  ];
236
488
  });
237
489
  if (rows.length > 0) {
@@ -240,115 +492,50 @@ export class Dashboard {
240
492
  } else {
241
493
  lines.push(dim(" No services."));
242
494
  }
243
- lines.push("");
244
-
245
- lines.push(bold("PIPELINE"));
246
- lines.push(" " + this.chain.map(paintNode).join(gray(" --> ")));
247
-
248
- const details = this.chain
249
- .map(n => (n.detail ? dim(`${n.label}: ${n.detail}`) : ""))
250
- .filter(Boolean)
251
- .join(dim(" | "));
252
- if (details) lines.push(" " + details);
253
-
254
- if (this.metrics) {
255
- const m = this.metrics;
256
- const r = this.rates;
257
- const inTok = m.headroom_tokens_input_total;
258
- const savedTok = m.headroom_tokens_saved_total;
259
- const savingRatio =
260
- Number.isFinite(inTok) && Number.isFinite(savedTok) && inTok + savedTok > 0
261
- ? savedTok / (inTok + savedTok)
262
- : null;
263
- const cacheRatio =
264
- Number.isFinite(m.headroom_requests_cached_total) && m.headroom_requests_total > 0
265
- ? m.headroom_requests_cached_total / m.headroom_requests_total
266
- : null;
267
- const avgLatency =
268
- Number.isFinite(m.headroom_latency_ms_sum) && m.headroom_latency_ms_count > 0
269
- ? m.headroom_latency_ms_sum / m.headroom_latency_ms_count
270
- : null;
271
- const latencyText = avgLatency === null ? "-" : `${Math.round(avgLatency)}ms`;
272
-
273
- const cells = [
274
- `${dim("req/s")} ${bold(num(r.headroom_requests_total, 2))}`,
275
- `${dim("attive")} ${bold(num(m.headroom_inbound_requests_active))}`,
276
- `${dim("tok in/s")} ${bold(num(r.headroom_tokens_input_total, 1))}`,
277
- `${dim("tok out/s")} ${bold(num(r.headroom_tokens_output_total, 1))}`,
278
- `${dim("risparmio")} ${green(bold(pct(savingRatio)))}`,
279
- `${dim("cache")} ${bold(pct(cacheRatio))}`,
280
- `${dim("latenza")} ${bold(latencyText)}`,
281
- ];
282
- lines.push(" " + cells.join(dim(" . ")));
283
- } else {
284
- lines.push(" " + dim("metriche non disponibili (headroom non raggiungibile)"));
495
+ if (svc?.repositoryUrl) {
496
+ // Keep both full links accessible when terminal width clips their columns.
497
+ lines.push(...wrapCells([
498
+ ...(svc.url && svc.url !== "-" ? [`${dim("URL:")} ${cyan(underline(svc.url))}`] : []),
499
+ `${dim("GitHub (g):")} ${cyan(underline(svc.repositoryUrl))}`,
500
+ ], width));
285
501
  }
286
502
  lines.push("");
287
503
 
288
- lines.push(bold("STREAM RICHIESTE") + dim(" " + this.eventsFile));
289
-
290
- // Every event in the stream is source "proxy": headroom is the only service
291
- // that reports per-request savings. The split below is the one place that
292
- // says how much came from compression versus provider cache reuse.
293
- if (this.savings) {
294
- const sv = this.savings;
295
- const savingsCells = [
296
- `${dim("risparmio")} ${green(bold(num(sv.total)))}`,
297
- `${dim("compress")} ${bold(num(sv.compression))}`,
298
- `${dim("cache")} ${bold(num(sv.cacheReads))}`,
299
- `${dim("inviati")} ${bold(num(sv.submitted))}`,
300
- `${dim("efficienza")} ${green(bold(pct(sv.ratio)))}`,
301
- ];
302
- lines.push(" " + savingsCells.join(dim(" . ")));
504
+ const bodyLimit = height - footerLines;
505
+ if (lines.length > bodyLimit - 4) {
506
+ lines.length = Math.max(0, bodyLimit - 4);
507
+ if (lines.length) lines[lines.length - 1] = dim(" ... servizi: aumenta l'altezza");
303
508
  }
304
-
305
- const footerLines = 3;
306
- const slots = Math.max(1, height - lines.length - footerLines);
307
-
308
- if (this.events.length === 0) {
309
- lines.push(
310
- " " +
311
- dim(
312
- this.eventsFileSeen
313
- ? "in attesa di richieste..."
314
- : "nessun file eventi: headroom non ha ancora scritto savings_events.jsonl"
315
- )
316
- );
317
- } else {
318
- for (const ev of this.events.slice(-slots)) {
319
- const time = ev.ts ? String(ev.ts).slice(11, 19) : "--:--:--";
320
- const before = Number(ev.before);
321
- const after = Number(ev.after);
322
- const saved = Number(ev.saved);
323
- const ratio = Number.isFinite(before) && before > 0 ? saved / before : null;
324
- const cost = Number(ev.cost_usd);
325
- const cells = [
326
- gray(time),
327
- magenta(String(ev.model || "?").padEnd(16).slice(0, 16)),
328
- `${dim("tok")} ${num(before)}${gray("->")}${num(after)}`,
329
- green(`-${num(saved)} (${pct(ratio)})`),
330
- dim(Number.isFinite(cost) ? "$" + cost.toFixed(4) : "-"),
331
- dim(String(ev.source || ev.client || "")),
332
- ];
333
- lines.push(" " + cells.join(" "));
334
- }
509
+ const room = bodyLimit - lines.length;
510
+ const streamRows = this.events.length ? Math.min(6, Math.max(2, Math.floor(room / 3))) : 2;
511
+ const pipelineBudget = room - streamRows - 1;
512
+ let pipeline = this.pipelineLines(width);
513
+ if (pipeline.length > pipelineBudget) {
514
+ // Never let expanded pipeline explanations consume the request stream.
515
+ // On small screens prioritize native totals over the topology/details.
516
+ const m = this.proxyStats;
517
+ const header = m && this.metricsStale() ? bold("PIPELINE") + yellow(" (storico)") + dim(" metriche proxy AIH") : pipeline[0];
518
+ pipeline = [header, ...wrapCells(m ? [
519
+ `Richieste ${num(m.requests)}`, `Modificate ${num(m.changed)}`, `Errori preset ${num(m.errors)}`,
520
+ `risparmio stimato ${num(m.estimatedSavedTokens)} token${m.unmeasuredStages > 0 ? " (parziale)" : ""}`,
521
+ ...(this.metricsStale() ? [yellow("Dati storici / attivita non disponibile")] : []),
522
+ ] : [yellow(this.metricsError || "nessun campione")], width)];
523
+ pipeline = pipeline.slice(0, Math.max(1, pipelineBudget - 1));
524
+ if (pipelineBudget > 1) pipeline.push(dim(" ... aumenta l'altezza per la pipeline"));
335
525
  }
526
+ lines.push(...pipeline);
527
+ lines.push("");
528
+ lines.push(...this.streamLines(width, Math.max(2, height - lines.length - footerLines)));
336
529
 
337
530
  while (lines.length < height - footerLines) lines.push("");
531
+ // Keep controls reachable even when expanded details exceed the terminal.
532
+ if (lines.length > height - footerLines) {
533
+ lines.length = height - footerLines;
534
+ lines[lines.length - 1] = dim(" ... aumenta l'altezza o premi d per ridurre i dettagli");
535
+ }
338
536
  lines.push(gray("-".repeat(width)));
339
537
 
340
- const svc = this.currentService();
341
- const target = svc ? bold(svc.id) : dim("-");
342
- const keys = [
343
- `${dim("up/down")} seleziona (${target})`,
344
- `${dim("s")} start`,
345
- `${dim("x")} stop`,
346
- `${dim("r")} restart`,
347
- `${dim("k")} kill`,
348
- `${dim("o")} dashboard`,
349
- `${dim("q")} esci`,
350
- ];
351
- lines.push(keys.join(" "));
538
+ lines.push(...keyLines);
352
539
  lines.push(this.busy ? yellow(this.status) : this.status || dim("pronto"));
353
540
 
354
541
  return lines.slice(0, height).map(line => clip(line, width));
@@ -377,8 +564,9 @@ export class Dashboard {
377
564
 
378
565
  try {
379
566
  const res = await action(svc);
380
- const message = res?.message || `${label} ${svc.id}: fatto`;
381
- this.status = res && res.success === false ? red(message) : green(message);
567
+ const message = [res?.message || `${label} ${svc.id}: fatto`, res?.codexConfig?.message].filter(Boolean).join(" | ");
568
+ this.status = res && res.success === false ? red(message)
569
+ : res?.codexConfig?.status === "warning" ? yellow(message) : green(message);
382
570
  } catch (err) {
383
571
  this.status = red(`${label} ${svc.id}: ${err?.message || err}`);
384
572
  } finally {
@@ -399,6 +587,10 @@ export class Dashboard {
399
587
  }
400
588
 
401
589
  switch (key) {
590
+ case "d":
591
+ this.showPipelineDetails = !this.showPipelineDetails;
592
+ this.render();
593
+ return;
402
594
  case KEY_UP:
403
595
  this.selected = Math.max(0, this.selected - 1);
404
596
  this.render();
@@ -416,6 +608,16 @@ export class Dashboard {
416
608
  case "r":
417
609
  this.runAction("Riavvio", svc => manager.restartService(svc.id));
418
610
  return;
611
+ case "u":
612
+ return this.runAction("Aggiornamento", async svc => {
613
+ this.invalidateVersions();
614
+ try {
615
+ return await manager.updateService(svc.id);
616
+ } finally {
617
+ // Drop pre-update and mid-update checks even if installation failed.
618
+ this.invalidateVersions();
619
+ }
620
+ });
419
621
  case "k":
420
622
  this.runAction("Kill", async svc => {
421
623
  if (!svc.pid) return { success: false, message: `${svc.id}: nessun PID da terminare` };
@@ -423,11 +625,17 @@ export class Dashboard {
423
625
  });
424
626
  return;
425
627
  case "o":
628
+ if (!this.currentService()?.dashboardUrl) return;
426
629
  this.runAction("Dashboard", async svc => {
427
- const url = svc.url && svc.url !== "-" ? svc.url : SERVICES[svc.id]?.defaultUrl;
428
- if (!url) return { success: false, message: `${svc.id}: nessuna URL disponibile` };
429
- openBrowser(url);
430
- return { success: true, message: `Aperto ${url}` };
630
+ const opened = await manager.openDashboard([svc.id]);
631
+ return { success: opened.length > 0, message: opened.length ? `Aperto ${opened[0].url}` : "Nessuna dashboard disponibile" };
632
+ });
633
+ return;
634
+ case "g":
635
+ if (!this.currentService()?.repositoryUrl) return;
636
+ this.runAction("GitHub", async svc => {
637
+ const opened = await manager.openRepository([svc.id]);
638
+ return { success: opened.length > 0, message: opened.length ? `Aperto ${opened[0].url}` : "Nessun repository disponibile" };
431
639
  });
432
640
  return;
433
641
  default: