Repository navigation
Expand file tree
/
Copy pathPanel.qml
More file actions
2511 lines (2262 loc) · 90.8 KB
/
Copy pathPanel.qml
File metadata and controls
2511 lines (2262 loc) · 90.8 KB
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Quickshell
import Quickshell.Io
import qs.Commons
import qs.Ui
import "ThemePalette.js" as ThemePalette
Panel {
id: root
moduleName: "io.github.nixfred.tailscale-host-monitor"
ipcTarget: "io.github.nixfred.tailscale-host-monitor"
// Kept in step with manifest.json by a test, rather than read from disk at
// runtime: the panel should not gain a file read and a failure mode just to
// print its own version.
readonly property string pluginVersion: "0.10.1"
readonly property string pluginName: "Tailscale Host Monitor"
readonly property string repoUrl: "https://github.com/nixfred/omarchy-server-status"
readonly property string authorUrl: "https://nixfred.com"
property bool refreshing: false
property string processOutput: ""
property string processError: ""
property string lastError: ""
// The backend needs the bun runtime. PATH inside the shell process is the
// systemd user session's, not the interactive shell's, so a bare "bun"
// command can fail to start even when bun works in a terminal. Resolve the
// binary once before any backend spawn; on failure the panel reports a
// named, actionable error instead of a silent dead widget.
property bool runtimeResolved: false
property bool runtimeMissing: false
property string runtimePath: ""
property string runtimeProbeOutput: ""
property string fetchHost: ""
property var pendingHosts: []
property var snapshotsByHost: ({})
property var previousByHost: ({})
property var notifiedKeyByHost: ({})
property string activeHost: ""
property bool tailnetRefreshing: false
property double lastTailnetScanAtMs: 0
property string tailnetOutput: ""
property string tailnetProcessError: ""
property string tailnetError: ""
property string tailnetBackendState: "Unknown"
property var tailnetDevices: []
property bool pickerOpen: false
property bool selectionReady: false
property var selectedHosts: []
property var mutedWarningsByHost: ({})
property var mutedHostAlerts: []
// QML cannot reliably observe reads nested inside plain JS maps. Bump this
// whenever alert policy changes so bar/host-state bindings repaint now,
// rather than waiting for the next telemetry snapshot.
property int alertPolicyRevision: 0
property var hostFetchFailedByHost: ({})
property string copiedValue: ""
property string draggedHost: ""
property string draggedHostName: ""
property string dragTargetHost: ""
property bool dragAfterTarget: false
property real dragPointerX: 0
property real dragPointerY: 0
property real dragGhostWidth: 0
property real dragGhostHeight: 0
property bool snapshotCacheReady: false
property bool startupSelectionCaptured: false
property var startupSelectedHosts: []
property bool tailnetInitialScanComplete: false
property bool startupSweepStarted: false
property bool startupSweepComplete: false
property var startupAwaitingHosts: []
property int startupSweepTotal: 0
property int startupSweepFinished: 0
readonly property string sshHosts: String(setting("sshHosts", ""))
readonly property int legacyRefreshIntervalSec: boundedInt(setting("refreshIntervalSec", 30), 10, 3600)
readonly property string hostScanPreset: String(setting("hostScanPreset", "30 seconds"))
readonly property int customHostScanSec: boundedInt(setting("customHostScanSec", legacyRefreshIntervalSec), 10, 3600)
readonly property string tailnetScanPreset: String(setting("tailnetScanPreset", "5 minutes"))
readonly property int customTailnetScanSec: boundedInt(setting("customTailnetScanSec", 300), 30, 3600)
readonly property string allHostsScanPreset: String(setting("allHostsScanPreset", "5 minutes"))
readonly property int customAllHostsScanSec: boundedInt(setting("customAllHostsScanSec", 300), 60, 86400)
readonly property int hostScanIntervalSec: cadenceSeconds(hostScanPreset, customHostScanSec, legacyRefreshIntervalSec)
readonly property int tailnetScanIntervalSec: cadenceSeconds(tailnetScanPreset, customTailnetScanSec, 300)
readonly property int allHostsScanIntervalSec: cadenceSeconds(allHostsScanPreset, customAllHostsScanSec, 300)
readonly property int panelWidth: boundedInt(setting("panelWidth", 1000), 320, 1200)
readonly property bool privacyMode: String(setting("privacyMode", false)).toLowerCase() === "true"
// Backend output is byte-capped at the producer (backend/collect.ts and
// backend/tailnet.ts); these budgets are defense in depth so no
// whole-stream collector remains in the shell process. .length counts
// UTF-16 units, which is fine for a backstop.
readonly property int maxBackendOutputChars: 2097152
readonly property int maxBackendErrorChars: 16384
readonly property string backendPath: decodeURIComponent(
String(Qt.resolvedUrl("backend/server-status.ts")).replace(/^file:\/\//, ""))
readonly property string selectionPath: Quickshell.env("HOME") + "/.config/omarchy/server-status.json"
readonly property string themeColorsPath:
Quickshell.env("HOME") + "/.local/state/omarchy/current/theme/colors.toml"
// Raw colors.toml contents, reloaded on theme change and on panel open.
property var themeColorValues: ({})
// Built-in traffic lights, used when a theme's own palette cannot carry the
// meaning. See ThemePalette.js for what disqualifies one.
readonly property var fallbackStatusColors: ({
pass: "#69c58a",
warn: "#e5b45d",
fail: "#e66a6a"
})
readonly property var statusColors: ThemePalette.statusPalette(
themeColorValues, fallbackStatusColors, String(Color.background))
readonly property string snapshotCachePath: {
var configured = String(Quickshell.env("XDG_CACHE_HOME") || "").trim()
var directory = configured !== "" ? configured : Quickshell.env("HOME") + "/.cache"
return directory + "/omarchy-server-status-snapshots.json"
}
readonly property var legacyHostList: sshHosts.split(":").map(function(entry) {
return entry.trim()
}).filter(function(entry) { return entry !== "" })
readonly property var hostList: selectionReady ? selectedHosts : legacyHostList
readonly property var monitoredDevices: hostList.map(function(host) {
return root.deviceForTarget(host)
}).filter(function(device) { return device !== null })
readonly property var activeDevice: deviceForTarget(activeHost)
readonly property var snapshot: snapshotsByHost[activeHost] || ({ host: null, containers: [], error: "" })
readonly property var hostInfo: snapshot.host || null
readonly property var containers: snapshot.containers instanceof Array ? snapshot.containers : []
readonly property var appContainers: containers.filter(function(item) {
return String(item && item.runtime || "") !== "kvm"
})
readonly property var virtualMachines: containers.filter(function(item) {
return String(item && item.runtime || "") === "kvm"
})
readonly property color foreground: bar ? bar.foreground : Color.foreground
readonly property color urgent: bar ? bar.urgent : Color.urgent
readonly property color dim: Qt.darker(foreground, 1.55)
readonly property string fontFamily: bar ? bar.fontFamily : Style.font.family
readonly property string barState: {
var observedAlertPolicyRevision = alertPolicyRevision
if (!startupSweepComplete) return "pass"
var state = worstState()
if (state === "fail") return "fail"
if (state === "pass") return "pass"
return "warn"
}
implicitWidth: button.implicitWidth
implicitHeight: button.implicitHeight
Component.onCompleted: {
activeHost = hostList.length > 0 ? hostList[0] : ""
resolveBackendRuntime()
}
function backendReady() {
return runtimeResolved && runtimePath !== ""
}
function resolveBackendRuntime() {
if (runtimeResolved || runtimeProbe.running) return
runtimeProbeOutput = ""
runtimeProbe.command = ["timeout", "-k", "2", "1", "/bin/sh", "-c",
"for candidate in bun \"$HOME/.bun/bin/bun\" /usr/bin/bun /usr/local/bin/bun; do" +
" case \"$candidate\" in" +
" /*) if [ -x \"$candidate\" ]; then printf '%s\\n' \"$candidate\"; exit 0; fi;;" +
" *) p=$(command -v -- \"$candidate\") && case \"$p\" in /*) printf '%s\\n' \"$p\"; exit 0;; esac;;" +
" esac; done; exit 1"]
runtimeProbe.running = true
runtimeProbeKillTimer.start()
}
function storeRuntimeProbe(raw) {
var candidate = String(raw || "").trim().split("\n")[0].trim()
runtimeResolved = true
if (candidate !== "" && candidate.indexOf("/") === 0) {
runtimePath = candidate
runtimeMissing = false
refresh()
} else {
runtimePath = ""
runtimeMissing = true
tailnetRefreshing = false
refreshing = false
lastError = runtimeMissingError()
// Nothing can be scanned without the runtime: close the startup
// bookkeeping so the header stops reading "Preparing startup scan".
tailnetInitialScanComplete = true
startupSweepStarted = true
startupSweepComplete = true
}
}
function normalizedHost(value) {
var host = String(value || "").trim().toLowerCase()
var at = host.lastIndexOf("@")
if (at >= 0) host = host.substring(at + 1)
return host.replace(/\.+$/, "")
}
function deviceAliases(device) {
if (!device) return []
var values = [device.name, device.hostName, device.dnsName, device.sshHost]
var dnsShort = normalizedHost(device.dnsName).split(".")[0]
if (dnsShort !== "") values.push(dnsShort)
return values.map(normalizedHost).filter(function(value, index, all) {
return value !== "" && all.indexOf(value) === index
})
}
function deviceMatchesHost(device, host) {
var normalized = normalizedHost(host)
if (normalized === "") return false
var aliases = deviceAliases(device)
if (aliases.indexOf(normalized) >= 0) return true
var shortName = normalized.split(".")[0]
return aliases.indexOf(shortName) >= 0
}
function deviceForTarget(host) {
for (var index = 0; index < tailnetDevices.length; index += 1) {
if (deviceMatchesHost(tailnetDevices[index], host)) return tailnetDevices[index]
}
return null
}
function monitoredTarget(device) {
for (var index = 0; index < hostList.length; index += 1) {
if (deviceMatchesHost(device, hostList[index])) return hostList[index]
}
return ""
}
function configuredTarget(device) {
var monitored = monitoredTarget(device)
if (monitored !== "") return monitored
return device ? String(device.sshHost || device.name || "") : ""
}
function isMonitored(device) {
return monitoredTarget(device) !== ""
}
function saveSelection(hosts) {
var clean = hosts.map(function(host) { return String(host || "").trim() })
.filter(function(host, index, all) { return host !== "" && all.indexOf(host) === index })
selectedHosts = clean
selectionReady = true
writeSelection()
}
function sameHostList(left, right) {
if (!(left instanceof Array) || !(right instanceof Array) || left.length !== right.length) return false
for (var index = 0; index < left.length; index += 1)
if (String(left[index]) !== String(right[index])) return false
return true
}
function writeSelection() {
if (!selectionReady) return
selectionFile.setText(JSON.stringify({
version: 1,
monitoredHosts: selectedHosts,
activeHost: activeHost,
mutedHosts: mutedHostAlerts,
mutedWarnings: mutedWarningsByHost
}, null, 2) + "\n")
}
function loadSelection(raw) {
try {
var parsed = JSON.parse(String(raw || ""))
if (!parsed || parsed.version !== 1 || !(parsed.monitoredHosts instanceof Array))
throw new Error("Unsupported selection file")
var loadedHosts = parsed.monitoredHosts.map(String).filter(function(host) { return host.trim() !== "" })
if (!startupSelectionCaptured) {
startupSelectedHosts = loadedHosts.slice()
startupSelectionCaptured = true
}
if (!sameHostList(selectedHosts, loadedHosts)) selectedHosts = loadedHosts
var loadedMutes = ({})
if (parsed.mutedWarnings && typeof parsed.mutedWarnings === "object") {
var muteHosts = Object.keys(parsed.mutedWarnings)
for (var muteIndex = 0; muteIndex < muteHosts.length; muteIndex += 1) {
var muteHost = String(muteHosts[muteIndex])
var muteIds = parsed.mutedWarnings[muteHost]
if (muteIds instanceof Array)
loadedMutes[muteHost] = muteIds.map(String).filter(function(id, index, all) {
return id !== "" && all.indexOf(id) === index
})
}
}
mutedWarningsByHost = loadedMutes
mutedHostAlerts = parsed.mutedHosts instanceof Array
? parsed.mutedHosts.map(String).filter(function(host, index, all) {
return host !== "" && all.indexOf(host) === index
})
: []
alertPolicyRevision += 1
var savedActive = String(parsed.activeHost || "")
activeHost = loadedHosts.indexOf(savedActive) >= 0
? savedActive
: (loadedHosts.length > 0 ? loadedHosts[0] : "")
} catch (error) {
selectedHosts = legacyHostList.slice()
mutedHostAlerts = []
alertPolicyRevision += 1
if (!startupSelectionCaptured) {
startupSelectedHosts = selectedHosts.slice()
startupSelectionCaptured = true
}
activeHost = selectedHosts.length > 0 ? selectedHosts[0] : ""
}
selectionReady = true
maybeStartStartupSweep()
if (opened) Qt.callLater(function() {
if (typeof root === "undefined" || !root || typeof root.refreshSelectedHost !== "function") return
root.refreshSelectedHost()
})
}
function loadSnapshotCache(raw) {
try {
var parsed = JSON.parse(String(raw || ""))
if (!parsed || parsed.version !== 1 || !parsed.snapshots || typeof parsed.snapshots !== "object")
throw new Error("Unsupported snapshot cache")
var loaded = ({})
var hosts = Object.keys(parsed.snapshots)
for (var index = 0; index < hosts.length; index += 1) {
var hostAlias = String(hosts[index])
var snapshotValue = parsed.snapshots[hostAlias]
if (snapshotValue && snapshotValue.schemaVersion === 1)
loaded[hostAlias] = snapshotValue
}
// A live response can beat the disk read during shell startup. Current
// in-memory values win so an older cache never rolls fresh data back.
snapshotsByHost = Object.assign({}, loaded, snapshotsByHost)
} catch (error) {
// Cache corruption is non-fatal. The next successful host response
// replaces the file with a clean cache.
}
snapshotCacheReady = true
if (Object.keys(snapshotsByHost).length > 0) snapshotCacheWriteTimer.restart()
}
function writeSnapshotCache() {
if (!snapshotCacheReady) return
var kept = ({})
var hosts = Object.keys(snapshotsByHost)
for (var index = 0; index < hosts.length; index += 1) {
var hostAlias = String(hosts[index])
var value = snapshotsByHost[hostAlias]
if (value && value.schemaVersion === 1) kept[hostAlias] = value
}
snapshotCacheFile.setText(JSON.stringify({
version: 1,
savedAt: new Date().toISOString(),
snapshots: kept
}, null, 2) + "\n")
snapshotCachePermissionsTimer.restart()
}
function scheduleSnapshotCacheWrite() {
if (snapshotCacheReady) snapshotCacheWriteTimer.restart()
}
function snapshotIsFresh(hostAlias, maxAgeSec) {
var value = snapshotsByHost[String(hostAlias || "")]
if (!value || !value.generatedAt) return false
var generatedAtMs = new Date(value.generatedAt).getTime()
if (!isFinite(generatedAtMs)) return false
return Date.now() - generatedAtMs < Math.max(1, Number(maxAgeSec) || 1) * 1000
}
function toggleMonitored(device) {
if (!device) return
var next = hostList.filter(function(host) { return !deviceMatchesHost(device, host) })
if (next.length === hostList.length) next.push(String(device.sshHost || device.name))
saveSelection(next)
if (isMonitored(device)) {
selectHost(configuredTarget(device))
} else if (deviceMatchesHost(device, activeHost)) {
selectHost(next.length > 0 ? next[0] : "")
}
}
function moveHostRelative(sourceHost, targetHost, afterTarget) {
var source = String(sourceHost || "")
var target = String(targetHost || "")
if (source === "" || target === "" || source === target) return
var next = hostList.slice()
var sourceIndex = next.indexOf(source)
if (sourceIndex < 0 || next.indexOf(target) < 0) return
var moved = next.splice(sourceIndex, 1)[0]
var targetIndex = next.indexOf(target)
next.splice(targetIndex + (afterTarget ? 1 : 0), 0, moved)
if (!sameHostList(next, hostList)) saveSelection(next)
}
function updateHostDrag(sourceHost, flowX, flowY) {
draggedHost = String(sourceHost || "")
dragPointerX = flowX
dragPointerY = flowY
if (flowX < -Style.space(16) || flowY < -Style.space(16)
|| flowX > monitoredFlow.width + Style.space(16)
|| flowY > monitoredFlow.height + Style.space(16)) {
dragTargetHost = ""
return
}
var nearestHost = ""
var nearestAfter = false
var nearestDistance = Number.POSITIVE_INFINITY
for (var index = 0; index < monitoredRepeater.count; index += 1) {
var item = monitoredRepeater.itemAt(index)
if (!item || item.target === draggedHost) continue
var origin = item.mapToItem(monitoredFlow, 0, 0)
var centerX = origin.x + item.width / 2
var centerY = origin.y + item.height / 2
var dx = flowX - centerX
var dy = flowY - centerY
var distance = dx * dx + dy * dy
if (distance < nearestDistance) {
nearestDistance = distance
nearestHost = item.target
nearestAfter = Math.abs(dy) <= item.height ? flowX >= centerX : flowY >= centerY
}
}
dragTargetHost = nearestHost
dragAfterTarget = nearestAfter
}
function finishHostDrag() {
var source = draggedHost
var target = dragTargetHost
var after = dragAfterTarget
draggedHost = ""
draggedHostName = ""
dragTargetHost = ""
dragAfterTarget = false
if (source !== "" && target !== "") moveHostRelative(source, target, after)
}
function cancelHostDrag() {
draggedHost = ""
draggedHostName = ""
dragTargetHost = ""
dragAfterTarget = false
}
function warningIds(hostAlias) {
var ids = mutedWarningsByHost[String(hostAlias || "")]
return ids instanceof Array ? ids : []
}
function isWarningMuted(hostAlias, warningId) {
var ids = warningIds(hostAlias)
var id = String(warningId || "")
if (ids.indexOf(id) >= 0) return true
// Container warning ids gained a runtime segment when Docker and Podman
// became collectable together ("container-docker-web-1" rather than
// "container-web-1"). Mutes recorded before that still name the old id, and
// a mute silently reverting is worse than a stale entry: someone muted that
// card on purpose. Accept the legacy form for docker, which is what every
// pre-existing mute was.
var legacy = legacyWarningId(id)
return legacy !== "" && ids.indexOf(legacy) >= 0
}
function legacyWarningId(warningId) {
var id = String(warningId || "")
return id.indexOf("container-docker-") === 0
? "container-" + id.slice("container-docker-".length)
: ""
}
function isHostMuted(hostAlias) {
return mutedHostAlerts.indexOf(String(hostAlias || "")) >= 0
}
function toggleHostMute(hostAlias) {
var host = String(hostAlias || "")
if (host === "") return
var next = mutedHostAlerts.slice()
var index = next.indexOf(host)
if (index >= 0) next.splice(index, 1)
else next.push(host)
mutedHostAlerts = next
alertPolicyRevision += 1
writeSelection()
}
function setHostFetchFailed(hostAlias, failed) {
var host = String(hostAlias || "")
if (host === "") return
var next = Object.assign({}, hostFetchFailedByHost)
if (failed) next[host] = true
else delete next[host]
hostFetchFailedByHost = next
}
function toggleWarningMute(hostAlias, warningId) {
var host = String(hostAlias || "")
var id = String(warningId || "")
if (host === "" || id === "") return
var nextMap = Object.assign({}, mutedWarningsByHost)
var nextIds = warningIds(host).slice()
var index = nextIds.indexOf(id)
// Unmuting must also clear a legacy entry, or the card would re-mute itself
// on the next read through the compatibility path above.
var legacy = legacyWarningId(id)
var legacyIndex = legacy !== "" ? nextIds.indexOf(legacy) : -1
if (index >= 0 || legacyIndex >= 0) {
if (index >= 0) nextIds.splice(index, 1)
legacyIndex = legacy !== "" ? nextIds.indexOf(legacy) : -1
if (legacyIndex >= 0) nextIds.splice(legacyIndex, 1)
} else nextIds.push(id)
if (nextIds.length > 0) nextMap[host] = nextIds
else delete nextMap[host]
mutedWarningsByHost = nextMap
alertPolicyRevision += 1
writeSelection()
}
function containerWarningId(container) {
var runtime = String(container && container.runtime || "docker")
return "container-" + runtime + "-" + String(container && container.name || "")
}
function copyText(value) {
var text = String(value || "")
if (text === "") return
Quickshell.execDetached(["wl-copy", "--", text])
copiedValue = text
copyReset.restart()
}
// Tooltips, PanelHero and notifications are rendered by the shell with
// Text.AutoText; this plugin cannot pin the format there. Remote-derived
// strings (hostnames, DNS names, container names) must lose markup and
// control characters and get a length cap before crossing that boundary.
function plain(value) {
return String(value || "")
.replace(/[<>&]/g, " ")
.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "")
.slice(0, 200)
}
function osIcon(os) {
var value = String(os || "").toLowerCase()
if (value === "linux") return ""
if (value === "windows") return ""
if (value === "macos" || value === "darwin" || value === "ios") return ""
if (value === "android") return ""
return ""
}
function privateHostNumber(hostAlias, device) {
var index = hostList.indexOf(String(hostAlias || ""))
if (index < 0 && device) index = tailnetDevices.indexOf(device)
return String(Math.max(0, index) + 1).padStart(2, "0")
}
function displayHostName(hostAlias, actual, device) {
if (!privacyMode) return String(actual || hostAlias || "Unknown")
return "Host " + privateHostNumber(hostAlias, device)
}
function displayDns(hostAlias, actual, device) {
if (!privacyMode) return String(actual || "")
return "host-" + privateHostNumber(hostAlias, device) + ".tailnet.example"
}
function displayIp(actual) {
return privacyMode && String(actual || "") !== "" ? "100.x.x.x" : String(actual || "")
}
function displayMetricLabel(metric) {
var label = String(metric && metric.label || "")
if (privacyMode && String(metric && metric.id || "").indexOf("disk-") === 0) {
var grouped = label.match(/ \+\d+$/)
return "Disk volume" + (grouped ? grouped[0] : "")
}
return label
}
function displayMetricDetail(metric) {
var detail = String(metric && metric.detail || "")
if (!privacyMode) return detail
var id = String(metric && metric.id || "")
if (id === "uptime") return detail.split(" · ")[0]
if (id === "tailscale-ip") return "100.x.x.x"
if (id === "magic-dns") return "host.tailnet.example"
if (id === "tailscale-tags") return "Private tags"
return detail
}
function displayContainerName(container, sourceContainers) {
if (!privacyMode) return String(container && container.name || "")
var list = sourceContainers instanceof Array ? sourceContainers : containers
var index = list.indexOf(container)
return "Container " + String(Math.max(0, index) + 1).padStart(2, "0")
}
// A backend spawn can never work without the runtime; this is the single
// actionable message shown in the error row. Ordinary non-zero backend
// exits are quoted as before via stderr/exitCode.
function runtimeMissingError() {
return "Backend runtime not found: install bun (e.g. pacman -S bun), or symlink your bun binary into ~/.local/bin, then restart the shell."
}
function displayError(value) {
if (!privacyMode) return String(value || "")
return String(value || "") !== "" ? "Host telemetry is currently unavailable." : ""
}
function primaryIp(device) {
if (!device || !(device.ips instanceof Array)) return ""
for (var index = 0; index < device.ips.length; index += 1)
if (String(device.ips[index]).indexOf(":") < 0) return String(device.ips[index])
return device.ips.length > 0 ? String(device.ips[0]) : ""
}
function lastSeenText(device) {
if (!device) return ""
if (device.online) return "Online now"
if (!device.lastSeen) return "Offline"
return "Last seen " + new Date(device.lastSeen).toLocaleString()
}
function boundedInt(value, minimum, maximum) {
var parsed = parseInt(String(value), 10)
if (!isFinite(parsed)) parsed = minimum
return Math.max(minimum, Math.min(maximum, parsed))
}
function cadenceSeconds(preset, customSeconds, fallback) {
var value = String(preset || "")
if (value === "15 seconds") return 15
if (value === "30 seconds") return 30
if (value === "1 minute") return 60
if (value === "5 minutes") return 300
if (value === "15 minutes") return 900
if (value === "30 minutes") return 1800
if (value === "1 hour") return 3600
if (value === "Custom") return Number(customSeconds) || fallback
return fallback
}
function cadenceText(seconds) {
var value = Number(seconds) || 0
if (value >= 3600 && value % 3600 === 0) return (value / 3600) + "h"
if (value >= 60 && value % 60 === 0) return (value / 60) + "m"
return value + "s"
}
function stateColor(state) {
if (state === "pass") return statusColors.pass
if (state === "running") return Color.accent
if (state === "warn") return statusColors.warn
if (state === "fail") return statusColors.fail
if (state === "muted") return root.dim
return root.dim
}
function barStateText() {
if (!startupSweepComplete) return startupProgressText()
if (barState === "fail") return "Critical"
if (barState === "warn") return "Warning / awaiting data"
return "Healthy"
}
function stateGlyph(state) {
if (state === "pass") return "✓"
if (state === "running") return "↻"
if (state === "warn") return "!"
if (state === "fail") return "×"
if (state === "idle") return "·"
if (state === "muted") return "−"
return "?"
}
function formatBytes(bytes) {
var value = Number(bytes) || 0
var units = ["B", "KiB", "MiB", "GiB", "TiB"]
var unit = 0
while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1 }
return (value >= 10 ? Math.round(value) : Math.round(value * 10) / 10) + " " + units[unit]
}
function formatUptime(seconds) {
var total = Number(seconds) || 0
var days = Math.floor(total / 86400)
var hours = Math.floor((total % 86400) / 3600)
return days > 0 ? days + "d " + hours + "h" : hours + "h " + Math.floor((total % 3600) / 60) + "m"
}
// Thresholds from the capacity plan: warn at mem>75% / disk>70% /
// load-per-core>0.7, red at mem>85% / disk>80% / load-per-core>1.0.
function levelFor(fraction, warnAt, failAt) {
if (!isFinite(fraction)) return "unknown"
if (fraction >= failAt) return "fail"
if (fraction >= warnAt) return "warn"
return "pass"
}
function sharedMountsOf(disk) {
return disk && disk.sharedMounts instanceof Array ? disk.sharedMounts : []
}
// The backend reports one card per filesystem, not per mount point, because
// btrfs subvolumes and bind mounts share an allocation pool and would
// otherwise raise the same warning several times.
//
// The count goes in the LABEL, not the detail. The detail line is a single
// elided row on a quarter-width tile, so anything appended there is cut off
// before it can be read — which made a grouped card indistinguishable from a
// host that had simply lost three filesystems. The label is short, bold, and
// drawn first, so "Disk / +3" survives.
function diskShareSuffix(disk) {
var fstype = String(disk && disk.fstype || "")
return sharedMountsOf(disk).length > 0 && fstype !== "" ? " · " + fstype : ""
}
// Full membership lives in the hover tooltip, where there is room for it.
function diskTooltip(disk) {
var shared = sharedMountsOf(disk)
if (shared.length < 1) return ""
var fstype = String(disk && disk.fstype || "")
var mounts = [String(disk.mount)].concat(shared)
// Mount paths and the filesystem type come from the remote host and land in
// PanelToolTip, a shell-owned component this plugin cannot pin to
// PlainText. Sanitize each entry separately: plain() strips C0 controls,
// newline included, so cleaning the joined string would flatten the list.
return (fstype !== "" ? plain(fstype) + " · " : "") + mounts.length
+ " volumes on one filesystem\n" + mounts.map(plain).join("\n")
}
function displayMetricTooltip(metric) {
var text = String(metric && metric.tooltip || "")
if (text === "" || !privacyMode) return text
// Mount paths name real directories. Keep the summary line, drop the list.
return String(metric && metric.id || "").indexOf("disk-") === 0
? text.split("\n")[0] : text
}
function hostRows(info, previous, elapsedSec) {
if (!info) return []
var rows = []
// Judge the 5-minute average, not load1. Opening the SSH session for a
// refresh briefly spikes the remote run queue itself: PAM session hooks
// and /etc/update-motd.d scripts (fail2ban, podman, incus, log greps) run
// on connect, concurrently with this plugin's own docker/podman queries. A load1
// sample read inside that burst reports a critical alert on a host that is
// sitting idle, immediately followed by a recovery notification.
//
// A consecutive-sample debounce would not catch this: the burst is caused
// by our own connection, so it recurs on every single refresh rather than
// flapping randomly. A longer averaging window is what actually rejects a
// two-second spike, and sustained load — the thing worth alerting on —
// still reaches load5 within a couple of scans.
//
// Diagnosed by @kanthi with sar -q evidence from a 4-vCPU Azure VM.
var loadPerCore = info.cpuCount > 0 ? info.load5 / info.cpuCount : 0
rows.push({
id: "cpu",
label: "CPU load",
state: levelFor(loadPerCore, 0.7, 1.0),
detail: "1m " + info.load1.toFixed(2) + " · 5m " + info.load5.toFixed(2)
+ " · 15m " + info.load15.toFixed(2) + " · " + info.cpuCount + " cores",
value: Math.min(1, loadPerCore)
})
var memFrac = info.memTotalBytes > 0 ? (info.memTotalBytes - info.memAvailableBytes) / info.memTotalBytes : 0
rows.push({
id: "mem",
label: "Memory",
state: levelFor(memFrac, 0.75, 0.85),
detail: formatBytes(info.memTotalBytes - info.memAvailableBytes) + " / " + formatBytes(info.memTotalBytes)
+ (info.swapUsedBytes > 0 ? " · swap " + formatBytes(info.swapUsedBytes) : ""),
value: memFrac
})
for (var index = 0; index < info.disks.length; index += 1) {
var disk = info.disks[index]
var frac = disk.totalBytes > 0 ? disk.usedBytes / disk.totalBytes : 0
var sharedCount = sharedMountsOf(disk).length
rows.push({
id: "disk-" + disk.mount,
label: "Disk " + disk.mount + (sharedCount > 0 ? " +" + sharedCount : ""),
state: levelFor(frac, 0.7, 0.8),
detail: formatBytes(disk.usedBytes) + " / " + formatBytes(disk.totalBytes) + diskShareSuffix(disk),
value: frac,
tooltip: diskTooltip(disk)
})
}
var netDetail = "rx " + formatBytes(info.netRxBytes) + " · tx " + formatBytes(info.netTxBytes) + " total"
if (previous && previous.host && elapsedSec > 0) {
var rx = (info.netRxBytes - previous.host.netRxBytes) / elapsedSec
var tx = (info.netTxBytes - previous.host.netTxBytes) / elapsedSec
if (rx >= 0 && tx >= 0)
netDetail = "↓ " + formatBytes(rx) + "/s · ↑ " + formatBytes(tx) + "/s"
}
rows.push({ id: "net", label: "Network", state: "pass", detail: netDetail, value: 0 })
rows.push({
id: "uptime",
label: "Uptime",
state: "pass",
detail: formatUptime(info.uptimeSeconds) + " · " + info.hostname,
value: 0
})
return rows
}
function tailnetRows(device) {
if (!device) return []
var rows = [{
id: "tailscale-status",
label: "Tailscale",
state: device.online ? "pass" : "fail",
detail: lastSeenText(device),
value: 0
}, {
id: "device-type",
label: "Device type",
state: "pass",
detail: device.kind + " · " + String(device.os || "unknown"),
value: 0
}]
var ip = primaryIp(device)
if (ip !== "") rows.push({ id: "tailscale-ip", label: "Tailscale IP", state: "pass", detail: ip, value: 0 })
if (device.dnsName) rows.push({ id: "magic-dns", label: "MagicDNS", state: "pass", detail: device.dnsName, value: 0 })
if (device.tags instanceof Array && device.tags.length > 0)
rows.push({ id: "tailscale-tags", label: "Tags", state: "pass", detail: device.tags.join(", "), value: 0 })
return rows
}
function containerState(container) {
if (container.oomKilled) return "fail"
if (container.state === "running") {
if (container.health === "unhealthy") return "fail"
if (container.health === "starting") return "running"
return "pass"
}
if (container.state === "restarting") return "fail"
if (container.state === "paused") return "warn"
if (container.state === "exited" || container.state === "dead") return "warn"
return "unknown"
}
function containerDetail(container) {
var parts = []
if (container.runtime) parts.push(String(container.runtime))
if (container.cpuPercent !== null) parts.push("cpu " + container.cpuPercent.toFixed(1) + "%")
if (container.memPercent !== null)
parts.push("mem " + formatBytes(container.memUsageBytes) + " (" + container.memPercent.toFixed(0) + "%)")
if (container.restarts > 0) parts.push(container.restarts + " restarts")
if (container.health !== "none") parts.push(container.health)
else parts.push(container.state)
return parts.join(" · ")
}
function vmDetail(vm) {
var parts = []
if (vm.memLimitBytes !== null && vm.memLimitBytes > 0) {
if (vm.state === "running" && vm.memUsageBytes !== null) {
parts.push("mem " + formatBytes(vm.memUsageBytes) + " (" + vm.memPercent.toFixed(0) + "%)")
} else {
parts.push("alloc " + formatBytes(vm.memLimitBytes))
}
}
if (vm.status) parts.push(String(vm.status))
else parts.push(String(vm.state))
return parts.join(" · ")
}
function summaryFor(hostAlias) {
if (isHostMuted(hostAlias)) return "pass"
var device = deviceForTarget(hostAlias)
if (!device) return tailnetInitialScanComplete ? "fail" : "unknown"
if (device && !device.online) return "fail"
if (device && !device.supportsMetrics) return "pass"
if (hostFetchFailedByHost[hostAlias] === true) return "fail"
var snap = snapshotsByHost[hostAlias]
if (!snap) return "unknown"
if (snap.error) return "fail"
var worst = "pass"
var rows = hostRows(snap.host, null, 0)
for (var index = 0; index < rows.length; index += 1) {
if (isWarningMuted(hostAlias, rows[index].id)) continue
if (rows[index].state === "fail") return "fail"
if (rows[index].state === "warn") worst = "warn"
}
var list = snap.containers instanceof Array ? snap.containers : []
for (var c = 0; c < list.length; c += 1) {
if (isWarningMuted(hostAlias, containerWarningId(list[c]))) continue
var state = containerState(list[c])
if (state === "fail") return "fail"
if (state === "warn") worst = "warn"
}
return worst
}
function worstState() {
if (tailnetError !== "") return "unknown"
var order = ["fail", "warn", "unknown", "pass"]
var worst = "unknown"
var rank = order.length
var sawAny = false
var targets = hostList
for (var index = 0; index < targets.length; index += 1) {
sawAny = true
var state = summaryFor(targets[index])
var current = order.indexOf(state)
if (current >= 0 && current < rank) { rank = current; worst = order[current] }
}
return sawAny ? worst : "unknown"
}
function hostIndicatorState(hostAlias) {
var observedAlertPolicyRevision = alertPolicyRevision
return startupSweepComplete ? summaryFor(hostAlias) : "pass"
}
function maybeStartStartupSweep() {
if (startupSweepStarted || !selectionReady || !tailnetInitialScanComplete) return
startupSweepStarted = true
startupSweepTotal = startupSelectedHosts.length
var targets = []
for (var index = 0; index < startupSelectedHosts.length; index += 1) {
var hostAlias = String(startupSelectedHosts[index] || "")
var device = deviceForTarget(hostAlias)
if (device && device.online && device.supportsMetrics) targets.push(hostAlias)
}
startupAwaitingHosts = targets.slice()
startupSweepFinished = Math.max(0, startupSweepTotal - targets.length)
if (targets.length === 0) {
startupSweepComplete = true
return
}
enqueue(targets)
}
function finishStartupHost(hostAlias) {
var waiting = startupAwaitingHosts.slice()
var index = waiting.indexOf(String(hostAlias || ""))
if (index < 0) return
waiting.splice(index, 1)
startupAwaitingHosts = waiting
startupSweepFinished = Math.min(startupSweepTotal, startupSweepFinished + 1)
if (waiting.length === 0) startupSweepComplete = true
}
function startupProgressText() {
if (startupSweepComplete) return "Startup scan complete"
if (!startupSweepStarted) return "Preparing startup scan"
return `Startup scan ${startupSweepFinished}/${startupSweepTotal}`
}
function selectHost(hostAlias) {
if (activeHost === hostAlias) return
activeHost = hostAlias
writeSelection()
refreshSelectedHost(false)
}
function selectDevice(device) {
if (!device || !isMonitored(device)) return
selectHost(configuredTarget(device))
}
function metricTargets() {
if (tailnetDevices.length === 0) return []
var targets = []
for (var index = 0; index < monitoredDevices.length; index += 1) {
var device = monitoredDevices[index]
if (device.online && device.supportsMetrics) targets.push(configuredTarget(device))
}
return targets
}
function refresh() {
refreshTailnet()
refreshSelectedHost(true)
}
function refreshSelectedHost(force) {
if (!startupSweepComplete) return
var device = activeDevice
if (!device || !device.online || !device.supportsMetrics) return
if (!force && snapshotIsFresh(activeHost, hostScanIntervalSec)) return
enqueue([activeHost])
}
function refreshAll() {
refreshTailnet()
refreshAllHosts()