dsh-remote-vs 0.18.0 → 0.19.1

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/lib/index.js CHANGED
@@ -1710,7 +1710,7 @@ const ALIAS_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
1710
1710
  * underscores and an IPv6 literal with brackets are both legal here.
1711
1711
  */
1712
1712
  const REMOTE_HOST_RE = /^[A-Za-z0-9._:[\]%-]{1,255}$/;
1713
- function messageOf$1(error) {
1713
+ function messageOf$2(error) {
1714
1714
  return error instanceof Error ? error.message : String(error ?? "");
1715
1715
  }
1716
1716
  /**
@@ -1906,7 +1906,7 @@ var ForwardManager = class {
1906
1906
  });
1907
1907
  forward.localPort = server.address().port;
1908
1908
  server.on("error", (error) => {
1909
- forward.lastError = messageOf$1(error);
1909
+ forward.lastError = messageOf$2(error);
1910
1910
  this.log("warn", `forward ${id} listener error: ${forward.lastError}`);
1911
1911
  });
1912
1912
  return forward;
@@ -1952,7 +1952,7 @@ var ForwardManager = class {
1952
1952
  try {
1953
1953
  channel = await this.deps.pool.forwardOut(forward.alias, forward.remoteHost, forward.remotePort);
1954
1954
  } catch (error) {
1955
- forward.lastError = messageOf$1(error);
1955
+ forward.lastError = messageOf$2(error);
1956
1956
  this.log("warn", `forward ${forward.id} -> ${forward.remoteHost}:${forward.remotePort} failed: ${forward.lastError}`);
1957
1957
  forward.sockets.delete(socket);
1958
1958
  socket.destroy();
@@ -2192,7 +2192,9 @@ const REMOTE_API = {
2192
2192
  /** Local TCP forwards (`ssh -L` semantics) for the port panel. */
2193
2193
  forwards: "/api/dsh-remote/forwards",
2194
2194
  /** Remote listening TCP sockets for the port panel (one bounded probe). */
2195
- listenPorts: "/api/dsh-remote/listen-ports"
2195
+ listenPorts: "/api/dsh-remote/listen-ports",
2196
+ /** Live system metrics for the monitor panel (one bounded probe per host). */
2197
+ metrics: "/api/dsh-remote/metrics"
2196
2198
  };
2197
2199
  /** Suggested/attachment file name for one multi-selection archive. */
2198
2200
  function selectionDownloadName(count) {
@@ -3027,6 +3029,351 @@ function parseListenPorts(stdout, exitCode) {
3027
3029
  };
3028
3030
  }
3029
3031
  //#endregion
3032
+ //#region src/metrics.ts
3033
+ /**
3034
+ * One bounded POSIX probe for the host monitor panel, and its pure parser.
3035
+ *
3036
+ * Why a shell one-liner instead of the helper or Python on the remote:
3037
+ * - the plugin targets bare POSIX hosts (the doctor probe already works this
3038
+ * way); requiring `python3`/`psutil` would make the panel dead on a stock
3039
+ * router or NAS;
3040
+ * - one `exec` over the pooled SSH channel needs no helper deploy and no
3041
+ * version handshake, so the panel also works on a host the deploy pipeline
3042
+ * never touched.
3043
+ *
3044
+ * Every fact is a marker line (`@@RVS-MET key detail`), so a banner printed by
3045
+ * a login shell or a stray line of a command can never be mistaken for a
3046
+ * measurement. A metric the host cannot answer is `null` (rendered as unknown),
3047
+ * never zero: a VM without a thermal zone has no temperature, it does not have
3048
+ * 0 °C.
3049
+ *
3050
+ * CPU% and the network rate are DELTAS over the previous sample: the caller
3051
+ * keeps the counters (`cpuPercent` / `netRateBps` below). The first sample is
3052
+ * honestly unknown instead of a made-up number.
3053
+ *
3054
+ * Linux is the supported source (`/proc`). A host that is not Linux simply
3055
+ * answers `unknown`, which the UI renders as "unknown", not as an empty host.
3056
+ */
3057
+ /** Prefix of every control line the probe prints (also the "did it answer" proof). */
3058
+ const METRICS_MARK = "@@RVS-MET";
3059
+ /**
3060
+ * Budget for the whole probe.
3061
+ *
3062
+ * A handful of `/proc` reads over one channel: if the host itself is stuck (a
3063
+ * hung mount, a thief of a process, a network blip) the route must answer with
3064
+ * the exec deadline instead of holding the monitor's poll forever.
3065
+ */
3066
+ const METRICS_TIMEOUT_MS = 8e3;
3067
+ /**
3068
+ * The remote probe line.
3069
+ *
3070
+ * `printf` never interpolates the input; every value comes from a fixed local
3071
+ * command. `2>/dev/null` is only used where the missing tool/file is itself a
3072
+ * normal answer (`/proc` on a non-Linux host); the parser then sees an empty
3073
+ * value and reports it as unknown rather than as a zero.
3074
+ */
3075
+ function metricsCommand() {
3076
+ const mark = METRICS_MARK;
3077
+ return [
3078
+ "export LC_ALL=C",
3079
+ `printf '%s begin\\n' '${mark}'`,
3080
+ `printf '%s kernel %s\\n' '${mark}' "$(uname -srm 2>/dev/null)"`,
3081
+ `printf '%s cores %s\\n' '${mark}' "$(getconf _NPROCESSORS_ONLN 2>/dev/null || nproc 2>/dev/null)"`,
3082
+ `printf '%s uptime %s\\n' '${mark}' "$(cut -d' ' -f1 /proc/uptime 2>/dev/null)"`,
3083
+ `printf '%s load %s\\n' '${mark}' "$(cut -d' ' -f1-3 /proc/loadavg 2>/dev/null)"`,
3084
+ `printf '%s cpu %s\\n' '${mark}' "$(awk '/^cpu /{print $2,$3,$4,$5,$6,$7,$8,$9; exit}' /proc/stat 2>/dev/null)"`,
3085
+ `printf '%s mem %s\\n' '${mark}' "$(awk '/^MemTotal:/{t=$2} /^MemAvailable:/{a=$2} /^MemFree:/{f=$2} /^Buffers:/{b=$2} /^Cached:/{c=$2} END{if(t=="")exit; if(a=="")a=f+b+c; printf "%s %s", t, a}' /proc/meminfo 2>/dev/null)"`,
3086
+ `printf '%s disk %s\\n' '${mark}' "$(df -Pk / 2>/dev/null | awk 'NR==2{print $2, $3}')"`,
3087
+ `printf '%s net %s\\n' '${mark}' "$(awk 'NR>2{iface=$1; sub(/:$/,"",iface); if(iface=="lo")next; rx+=$2; tx+=$10} END{printf "%s %s", rx+0, tx+0}' /proc/net/dev 2>/dev/null)"`,
3088
+ `printf '%s temp %s\\n' '${mark}' "$(for f in /sys/class/thermal/thermal_zone*/temp; do if [ -r "$f" ]; then cat "$f"; break; fi; done 2>/dev/null)"`,
3089
+ `printf '%s model %s\\n' '${mark}' "$(awk -F: '/model name/{sub(/^[ \\t]+/,"",$2); print $2; exit}' /proc/cpuinfo 2>/dev/null)"`,
3090
+ `printf '%s ip %s\\n' '${mark}' "$(hostname -I 2>/dev/null | awk '{print $1}')"`,
3091
+ `printf '%s end\\n' '${mark}'`
3092
+ ].join("\n");
3093
+ }
3094
+ /** Anchored marker: a metric line's content can never forge or split a marker. */
3095
+ const LINE_RE = new RegExp(`^${METRICS_MARK} ([a-z]+)(?: (.*))?$`);
3096
+ const EMPTY = {
3097
+ kernel: null,
3098
+ cpuCores: null,
3099
+ cpuModel: null,
3100
+ ip: null,
3101
+ uptimeSeconds: null,
3102
+ load: null,
3103
+ cpu: null,
3104
+ memTotalBytes: null,
3105
+ memUsedBytes: null,
3106
+ diskTotalBytes: null,
3107
+ diskUsedBytes: null,
3108
+ temperatureC: null,
3109
+ net: null
3110
+ };
3111
+ function unavailable(reason) {
3112
+ return {
3113
+ state: "unknown",
3114
+ reason,
3115
+ ...EMPTY
3116
+ };
3117
+ }
3118
+ function numberFrom(text) {
3119
+ if (text === void 0 || text.trim() === "") return null;
3120
+ const value = Number(text.trim());
3121
+ return Number.isFinite(value) ? value : null;
3122
+ }
3123
+ function intFrom(text) {
3124
+ const value = numberFrom(text);
3125
+ return value === null ? null : Math.trunc(value);
3126
+ }
3127
+ function tokensOf(detail) {
3128
+ return detail === void 0 ? [] : detail.trim().split(/\s+/).filter((token) => token !== "");
3129
+ }
3130
+ function textOf(facts, key) {
3131
+ const value = facts.get(key);
3132
+ if (value === void 0) return null;
3133
+ const trimmed = value.trim();
3134
+ return trimmed === "" ? null : trimmed;
3135
+ }
3136
+ /**
3137
+ * Parse the probe's stdout.
3138
+ *
3139
+ * Exit-code/timed-out/transport outcomes are answered BEFORE the markers so a
3140
+ * half-written probe can never be reported as a complete sample.
3141
+ */
3142
+ function parseMetrics(stdout, options) {
3143
+ if (options.error !== void 0 && options.error !== "") return unavailable(options.error);
3144
+ if (options.timedOut === true) return unavailable(`probe timed out after ${METRICS_TIMEOUT_MS / 1e3}s`);
3145
+ if (options.exitCode === null) return unavailable("the SSH channel closed before the probe exited");
3146
+ if (options.exitCode !== 0) {
3147
+ const first = (options.stderr ?? "").trim().split(/\r?\n/)[0] ?? "";
3148
+ return unavailable(`probe exited with code ${options.exitCode}${first === "" ? "" : `: ${first}`}`);
3149
+ }
3150
+ const facts = /* @__PURE__ */ new Map();
3151
+ let sawBegin = false;
3152
+ let sawEnd = false;
3153
+ for (const raw of stdout.split(/\r?\n/)) {
3154
+ const match = LINE_RE.exec(raw.trim());
3155
+ if (match === null) continue;
3156
+ const key = match[1];
3157
+ const detail = match[2] ?? "";
3158
+ if (key === "begin") {
3159
+ sawBegin = true;
3160
+ continue;
3161
+ }
3162
+ if (key === "end") {
3163
+ sawEnd = true;
3164
+ continue;
3165
+ }
3166
+ facts.set(key, detail);
3167
+ }
3168
+ if (!sawBegin) return unavailable("the probe did not start (no begin marker)");
3169
+ if (!sawEnd) return unavailable("the probe did not finish (no end marker)");
3170
+ const cpuTokens = tokensOf(facts.get("cpu"));
3171
+ const cpu = cpuTokens.length >= 8 ? {
3172
+ total: cpuTokens.slice(0, 8).reduce((sum, token) => sum + (Number(token) || 0), 0),
3173
+ idle: (Number(cpuTokens[3]) || 0) + (Number(cpuTokens[4]) || 0)
3174
+ } : null;
3175
+ const memTokens = tokensOf(facts.get("mem"));
3176
+ const memTotalKb = memTokens.length >= 2 ? numberFrom(memTokens[0]) : null;
3177
+ const memAvailableKb = memTokens.length >= 2 ? numberFrom(memTokens[1]) : null;
3178
+ const memTotalBytes = memTotalKb === null ? null : memTotalKb * 1024;
3179
+ const memUsedBytes = memTotalBytes === null || memAvailableKb === null ? null : Math.max(0, memTotalBytes - memAvailableKb * 1024);
3180
+ const diskTokens = tokensOf(facts.get("disk"));
3181
+ const diskTotalKb = diskTokens.length >= 2 ? numberFrom(diskTokens[0]) : null;
3182
+ const diskUsedKb = diskTokens.length >= 2 ? numberFrom(diskTokens[1]) : null;
3183
+ const diskTotalBytes = diskTotalKb === null ? null : diskTotalKb * 1024;
3184
+ const diskUsedBytes = diskUsedKb === null ? null : diskUsedKb * 1024;
3185
+ const loadTokens = tokensOf(facts.get("load"));
3186
+ const load = loadTokens.length >= 3 ? [
3187
+ Number(loadTokens[0]) || 0,
3188
+ Number(loadTokens[1]) || 0,
3189
+ Number(loadTokens[2]) || 0
3190
+ ] : null;
3191
+ const netTokens = tokensOf(facts.get("net"));
3192
+ const net = netTokens.length >= 2 ? {
3193
+ rx: Number(netTokens[0]) || 0,
3194
+ tx: Number(netTokens[1]) || 0
3195
+ } : null;
3196
+ const temperatureMilli = intFrom(facts.get("temp"));
3197
+ const temperatureC = temperatureMilli === null ? null : temperatureMilli / 1e3;
3198
+ if (cpu === null && memTotalBytes === null) return unavailable("the probe answered without /proc CPU or memory (not a Linux host?)");
3199
+ return {
3200
+ state: "ok",
3201
+ kernel: textOf(facts, "kernel"),
3202
+ cpuCores: intFrom(facts.get("cores")),
3203
+ cpuModel: textOf(facts, "model"),
3204
+ ip: tokensOf(facts.get("ip"))[0] ?? null,
3205
+ uptimeSeconds: numberFrom(facts.get("uptime")),
3206
+ load,
3207
+ cpu,
3208
+ memTotalBytes,
3209
+ memUsedBytes,
3210
+ diskTotalBytes,
3211
+ diskUsedBytes,
3212
+ temperatureC,
3213
+ net
3214
+ };
3215
+ }
3216
+ /**
3217
+ * CPU busy percentage between two counter samples.
3218
+ *
3219
+ * Null when a counter is missing, the sum did not advance, or the counters
3220
+ * went backwards (a reboot between the two samples): all three mean "unknown",
3221
+ * not "0%".
3222
+ */
3223
+ function cpuPercent(previous, next) {
3224
+ if (previous === null || previous === void 0 || next === null || next === void 0) return null;
3225
+ const total = next.total - previous.total;
3226
+ const idle = next.idle - previous.idle;
3227
+ if (total <= 0 || idle < 0 || idle > total) return null;
3228
+ return Math.min(100, Math.max(0, (1 - idle / total) * 100));
3229
+ }
3230
+ /**
3231
+ * Network bytes-per-second between two counter samples.
3232
+ *
3233
+ * Null when either counter is missing, the interval is not positive, or a
3234
+ * counter went backwards (a reboot): a rate computed from a reset counter is
3235
+ * noise, and showing it as a huge spike would be worse than "unknown".
3236
+ */
3237
+ function netRateBps(previous, next, elapsedMs) {
3238
+ if (previous === null || previous === void 0 || next === null || next === void 0) return null;
3239
+ if (elapsedMs === null || elapsedMs === void 0 || !Number.isFinite(elapsedMs) || elapsedMs <= 0) return null;
3240
+ const rx = next.rx - previous.rx;
3241
+ const tx = next.tx - previous.tx;
3242
+ if (rx < 0 || tx < 0) return null;
3243
+ const seconds = elapsedMs / 1e3;
3244
+ return {
3245
+ rx: rx / seconds,
3246
+ tx: tx / seconds
3247
+ };
3248
+ }
3249
+ /** Bytes as a percentage of a total; null when either side is unknown. */
3250
+ function usedPercent(used, total) {
3251
+ if (used === null || total === null || total <= 0) return null;
3252
+ return Math.min(100, Math.max(0, used / total * 100));
3253
+ }
3254
+ function messageOf$1(error) {
3255
+ return error instanceof Error ? error.message : String(error);
3256
+ }
3257
+ /** Every field null: an honest "we did not get an answer". */
3258
+ function emptyMetrics(alias, state, reason, sampledAt) {
3259
+ return {
3260
+ alias,
3261
+ state,
3262
+ reason,
3263
+ sampledAt,
3264
+ kernel: null,
3265
+ cpuCores: null,
3266
+ cpuModel: null,
3267
+ ip: null,
3268
+ uptimeSeconds: null,
3269
+ load1: null,
3270
+ load5: null,
3271
+ load15: null,
3272
+ cpuPercent: null,
3273
+ memUsedBytes: null,
3274
+ memTotalBytes: null,
3275
+ memPercent: null,
3276
+ diskUsedBytes: null,
3277
+ diskTotalBytes: null,
3278
+ diskPercent: null,
3279
+ temperatureC: null,
3280
+ netRxBps: null,
3281
+ netTxBps: null
3282
+ };
3283
+ }
3284
+ var HostMonitor = class {
3285
+ pool;
3286
+ now;
3287
+ freshMs;
3288
+ cache = /* @__PURE__ */ new Map();
3289
+ inflight = /* @__PURE__ */ new Map();
3290
+ /**
3291
+ * Bumped by `forget`. A probe that started before a host edit/delete must not
3292
+ * write its answer into the cache afterwards — the counters belong to the old
3293
+ * connection, and a re-created host with the same alias would briefly read a
3294
+ * stale sample.
3295
+ */
3296
+ generations = /* @__PURE__ */ new Map();
3297
+ constructor(pool, options = {}) {
3298
+ this.pool = pool;
3299
+ this.now = options.now ?? (() => Date.now());
3300
+ this.freshMs = options.freshMs ?? 3e3;
3301
+ }
3302
+ /** One sample for one alias; `force` bypasses the reuse window (manual refresh). */
3303
+ async sample(alias, force = false) {
3304
+ const cached = this.cache.get(alias);
3305
+ if (!force && cached !== void 0 && this.now() - cached.snapshot.sampledAt < this.freshMs) return cached.snapshot;
3306
+ const running = this.inflight.get(alias);
3307
+ if (running !== void 0) return running;
3308
+ const task = this.probe(alias).finally(() => {
3309
+ if (this.inflight.get(alias) === task) this.inflight.delete(alias);
3310
+ });
3311
+ this.inflight.set(alias, task);
3312
+ return task;
3313
+ }
3314
+ /** Drop everything known about one alias (host edited or deleted). */
3315
+ forget(alias) {
3316
+ this.cache.delete(alias);
3317
+ this.inflight.delete(alias);
3318
+ this.generations.set(alias, (this.generations.get(alias) ?? 0) + 1);
3319
+ }
3320
+ async probe(alias) {
3321
+ const generation = this.generations.get(alias) ?? 0;
3322
+ const startedAt = this.now();
3323
+ let result;
3324
+ try {
3325
+ result = await this.pool.exec(alias, metricsCommand(), { timeoutMs: METRICS_TIMEOUT_MS });
3326
+ } catch (error) {
3327
+ return emptyMetrics(alias, "error", messageOf$1(error), startedAt);
3328
+ }
3329
+ if (result.error !== void 0 && result.error !== "") return emptyMetrics(alias, "error", result.error, startedAt);
3330
+ const parsed = parseMetrics(result.stdout, {
3331
+ exitCode: result.exitCode,
3332
+ timedOut: result.timedOut,
3333
+ stderr: result.stderr
3334
+ });
3335
+ const sampledAt = this.now();
3336
+ const previous = this.cache.get(alias);
3337
+ const elapsedMs = previous?.counterAt === null || previous?.counterAt === void 0 ? null : Math.max(0, sampledAt - previous.counterAt);
3338
+ const cpu = cpuPercent(previous?.cpu ?? null, parsed.cpu);
3339
+ const rate = netRateBps(previous?.net ?? null, parsed.net, elapsedMs);
3340
+ const snapshot = {
3341
+ alias,
3342
+ state: parsed.state === "ok" ? "ok" : "unknown",
3343
+ ...parsed.reason === void 0 ? {} : { reason: parsed.reason },
3344
+ sampledAt,
3345
+ kernel: parsed.kernel,
3346
+ cpuCores: parsed.cpuCores,
3347
+ cpuModel: parsed.cpuModel,
3348
+ ip: parsed.ip,
3349
+ uptimeSeconds: parsed.uptimeSeconds,
3350
+ load1: parsed.load?.[0] ?? null,
3351
+ load5: parsed.load?.[1] ?? null,
3352
+ load15: parsed.load?.[2] ?? null,
3353
+ cpuPercent: cpu,
3354
+ memUsedBytes: parsed.memUsedBytes,
3355
+ memTotalBytes: parsed.memTotalBytes,
3356
+ memPercent: usedPercent(parsed.memUsedBytes, parsed.memTotalBytes),
3357
+ diskUsedBytes: parsed.diskUsedBytes,
3358
+ diskTotalBytes: parsed.diskTotalBytes,
3359
+ diskPercent: usedPercent(parsed.diskUsedBytes, parsed.diskTotalBytes),
3360
+ temperatureC: parsed.temperatureC,
3361
+ netRxBps: rate?.rx ?? null,
3362
+ netTxBps: rate?.tx ?? null
3363
+ };
3364
+ const counters = parsed.cpu ?? previous?.cpu ?? null;
3365
+ const countersAt = parsed.cpu === null ? previous?.counterAt ?? null : sampledAt;
3366
+ const net = parsed.net ?? previous?.net ?? null;
3367
+ if ((this.generations.get(alias) ?? 0) === generation) this.cache.set(alias, {
3368
+ snapshot,
3369
+ cpu: counters,
3370
+ net,
3371
+ counterAt: countersAt
3372
+ });
3373
+ return snapshot;
3374
+ }
3375
+ };
3376
+ //#endregion
3030
3377
  //#region src/routes.ts
3031
3378
  /** One noServer WebSocket server for terminal upgrades (RFC 6455). */
3032
3379
  const terminalWss = new WebSocketServer({
@@ -3203,6 +3550,7 @@ function makeRoutes(deps) {
3203
3550
  const timeouts = () => deps.timeouts?.() ?? DEFAULT_TIMEOUTS;
3204
3551
  const files = new RemoteFiles(pool);
3205
3552
  const terminalSessions = new TerminalSessionRegistry(pool);
3553
+ const monitor = new HostMonitor(pool);
3206
3554
  const forwards = deps.forwards;
3207
3555
  /**
3208
3556
  * Stream one remote `tar -czf -` command into a `.tar.gz` download response.
@@ -3347,6 +3695,7 @@ function makeRoutes(deps) {
3347
3695
  if (method === "DELETE") {
3348
3696
  forwards?.stopAlias(alias);
3349
3697
  pool.forget(alias);
3698
+ monitor.forget(alias);
3350
3699
  worlds.dropHost(alias).catch(() => void 0);
3351
3700
  if (!store.remove(alias)) {
3352
3701
  writeJson(res, 404, { error: `unknown host alias: ${alias}` });
@@ -3365,6 +3714,7 @@ function makeRoutes(deps) {
3365
3714
  }
3366
3715
  try {
3367
3716
  pool.forget(alias);
3717
+ monitor.forget(alias);
3368
3718
  worlds.dropHost(alias).catch(() => void 0);
3369
3719
  const entry = store.update(alias, body);
3370
3720
  writeJson(res, 200, { host: store.summarize(entry) });
@@ -4238,6 +4588,33 @@ function makeRoutes(deps) {
4238
4588
  writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
4239
4589
  }
4240
4590
  }
4591
+ },
4592
+ {
4593
+ kind: "exact",
4594
+ path: REMOTE_API.metrics,
4595
+ handler: async (req, res) => {
4596
+ if (!isLoopbackRequest(req)) {
4597
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
4598
+ return;
4599
+ }
4600
+ if (req.method !== "GET") {
4601
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` });
4602
+ return;
4603
+ }
4604
+ const url = new URL(req.url ?? "/", "http://localhost");
4605
+ const alias = queryParam(url, "alias");
4606
+ const refresh = queryParam(url, "refresh") === "1";
4607
+ if (alias !== void 0 && alias !== "" && store.get(alias) === void 0) {
4608
+ writeJson(res, 404, { error: `unknown host alias: ${alias}` });
4609
+ return;
4610
+ }
4611
+ const aliases = alias === void 0 || alias === "" ? store.list().map((host) => host.alias) : [alias];
4612
+ try {
4613
+ writeJson(res, 200, { hosts: await Promise.all(aliases.map((host) => monitor.sample(host, refresh))) });
4614
+ } catch (error) {
4615
+ writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
4616
+ }
4617
+ }
4241
4618
  }
4242
4619
  ],
4243
4620
  upgrade: {
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Sidebar monitor: live CPU / memory / disk / network / temperature for one
3
+ * host (or every host at once).
4
+ *
5
+ * Costs are shaped by the plugin's channel budget: the panel polls only while
6
+ * it is the visible view AND the page is visible (5 s), the Host reuses a
7
+ * sample for a few seconds, and a per-alias in-flight set means a manual
8
+ * refresh cannot open a second channel for a host that is already sampling.
9
+ * The first sample is honest about deltas: CPU% and the network rate read
10
+ * "unknown" until a second sample exists.
11
+ */
12
+ import { type ReactNode } from 'react';
13
+ import type { RemoteHostSummary } from '../protocol.ts';
14
+ /** Visible-panel poll cadence. The Host's own reuse window is shorter (3 s). */
15
+ export declare const MONITOR_POLL_MS = 5000;
16
+ /**
17
+ * The refresh-interval setting.
18
+ *
19
+ * `MONITOR_POLL_MS` stays the default and the documented cadence; the other
20
+ * choices exist for slow links / many hosts. The value is validated against
21
+ * this list on read, so a hand-edited localStorage value cannot turn the poll
22
+ * into a 1 ms loop.
23
+ */
24
+ export declare const INTERVAL_CHOICES: readonly [5000, 10000, 30000];
25
+ /** One rail icon: a screen with a pulse line. */
26
+ export declare function IconMonitor(props: {
27
+ size?: number;
28
+ }): ReactNode;
29
+ export declare function MonitorView(props: {
30
+ t: (key: string) => string;
31
+ hosts: RemoteHostSummary[];
32
+ visible: boolean;
33
+ }): ReactNode;
@@ -257,6 +257,14 @@ export declare const api: {
257
257
  * found" (see `RemoteListenPortsResult`).
258
258
  */
259
259
  listenPorts: (alias: string) => Promise<RemoteListenPortsResult>;
260
+ /**
261
+ * One host's live metrics sample.
262
+ *
263
+ * `refresh` bypasses the Host's few-second reuse window (manual refresh).
264
+ * The route always answers one entry for `alias`; a host that disappeared
265
+ * between the panel's host list and this call is a normal 404.
266
+ */
267
+ hostMetrics: (alias: string, refresh?: boolean) => Promise<import("../protocol.ts").RemoteHostMetrics>;
260
268
  git: {
261
269
  status(alias: string, path: string): Promise<GitStatus>;
262
270
  log(alias: string, path: string, max: number, branch?: string): Promise<GitCommit[]>;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Pure model for the host monitor panel.
3
+ *
4
+ * Kept free of React and DOM so the node gate can drive it: history windows,
5
+ * sparkline geometry, number formatting and the health tone all live here.
6
+ * The panel only renders what these functions return.
7
+ *
8
+ * Honesty rules carried by this module:
9
+ * - a null measurement is never formatted as a number (the panel shows "—");
10
+ * - a flat series still draws a line (a flat 30 °C history is a real answer,
11
+ * not "no data");
12
+ * - history windows are bounded (`HISTORY_POINTS`), so a panel left open for
13
+ * hours cannot grow the page's memory.
14
+ */
15
+ import type { RemoteHostMetrics } from '../protocol.ts';
16
+ /** How many samples one sparkline keeps (5 s poll → 5 minutes). */
17
+ export declare const HISTORY_POINTS = 60;
18
+ /** One host's rolling history, oldest first. */
19
+ export interface MetricHistory {
20
+ cpu: number[];
21
+ mem: number[];
22
+ netRx: number[];
23
+ netTx: number[];
24
+ temp: number[];
25
+ }
26
+ /** A fresh, empty window (a new array each call: the panel owns its history). */
27
+ export declare function emptyHistory(): MetricHistory;
28
+ /**
29
+ * The snapshot the panel shows when a request failed before the Host answered.
30
+ *
31
+ * Every value is null on purpose: an HTTP failure is not "0% CPU", and the
32
+ * reason line says what actually happened.
33
+ */
34
+ export declare function placeholderMetrics(alias: string, state: 'unknown' | 'error', reason: string, sampledAt?: number): RemoteHostMetrics;
35
+ /** Append one sample, dropping the oldest past `HISTORY_POINTS` (identity when unchanged). */
36
+ export declare function pushPoint(points: number[], value: number | null): number[];
37
+ /** One metrics answer → the next history (same object when nothing changed). */
38
+ export declare function appendMetrics(history: MetricHistory, metrics: RemoteHostMetrics): MetricHistory;
39
+ /** One shared y-domain for two series (so RX and TX are comparable). */
40
+ export interface SparkDomain {
41
+ min: number;
42
+ max: number;
43
+ }
44
+ /**
45
+ * The y-domain covering BOTH series.
46
+ *
47
+ * Two series drawn on independent auto-scales look identical even when one is
48
+ * 100× the other (the RX/TX bug this exists to prevent). Null when neither
49
+ * series has a finite value.
50
+ */
51
+ export declare function combineDomain(first: readonly number[], second?: readonly number[]): SparkDomain | undefined;
52
+ /**
53
+ * SVG path for a sparkline inside a `width × height` viewBox.
54
+ *
55
+ * The y axis is auto-scaled to the window's own min/max unless `domain` is
56
+ * supplied; a flat window draws a line through the middle instead of dividing
57
+ * by zero. A one-point window draws a dot-sized path on the right edge (the
58
+ * line grows as samples arrive). Returns '' only when there is no finite value
59
+ * at all.
60
+ */
61
+ export declare function sparklinePath(values: readonly number[], width: number, height: number, domain?: SparkDomain): string;
62
+ /** `1536` → `1.5 KB`; `0` stays `0 B` (bytes are integers, not fractions). */
63
+ export declare function formatBytes(bytes: number): string;
64
+ /**
65
+ * `used / total` in ONE unit, for a tile's sub line.
66
+ *
67
+ * `formatBytes` on each side doubles the unit ("5.1 GB / 16 GB"), which is
68
+ * longer than the narrow tile can show and gets ellipsised exactly where the
69
+ * capacity matters. This picks the total's unit for both numbers.
70
+ */
71
+ export declare function formatCapacity(usedBytes: number, totalBytes: number): string;
72
+ /** `42.4` → `42%`. Percentages are whole numbers in this panel. */
73
+ export declare function formatPercent(value: number): string;
74
+ /** `1536` B/s → `1.5 KB/s`. */
75
+ export declare function formatRate(bytesPerSecond: number): string;
76
+ /** `3600 * 26 + 120` → `1d 2h`; short so it fits a narrow tile. */
77
+ export declare function formatUptime(seconds: number): string;
78
+ /** `42.1` → `42.1 °C`. */
79
+ export declare function formatTemperature(celsius: number): string;
80
+ /** Age of a sample, short form for "updated … ago" (`12s`, `3m`, `2h`). */
81
+ export declare function formatAgeShort(ms: number): string;
82
+ export type MetricTone = 'ok' | 'warn' | 'hot';
83
+ /** Bar tone: quiet below 75%, amber 75–89%, red from 90%. */
84
+ export declare function metricTone(percent: number | null): MetricTone;
@@ -117,7 +117,7 @@ export interface HeadInfo {
117
117
  behind: number;
118
118
  }
119
119
  /** The sidebar rail destinations. */
120
- export type RailView = 'explorer' | 'search' | 'scm' | 'history' | 'editor' | 'terminal' | 'ports' | 'workspaces';
120
+ export type RailView = 'explorer' | 'search' | 'scm' | 'history' | 'editor' | 'terminal' | 'ports' | 'monitor' | 'workspaces';
121
121
  /** One "search this folder" request coming from the tree. */
122
122
  export interface SearchRequest {
123
123
  /** Monotonic id so a repeated request still re-triggers the view. */