-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProxmuxSidebarPanel.tsx
More file actions
1409 lines (1333 loc) · 58.5 KB
/
Copy pathProxmuxSidebarPanel.tsx
File metadata and controls
1409 lines (1333 loc) · 58.5 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 { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
import { pluginInvoke } from "../tauri-api";
import { InlineSpinner } from "./InlineSpinner";
import { PROXMUX_PLUGIN_ID } from "../features/builtin-plugin-ids";
import { buildProxmoxConsoleUrl } from "../features/proxmox-console-urls";
type ProxmuxClusterRow = {
id: string;
name: string;
proxmoxUrl: string;
/** Omitted on older plugin payloads; treated as false. */
allowInsecureTls?: boolean;
tlsTrustedCertPem?: string | null;
tlsTrustedLeafSha256?: string | null;
};
type ListStateResponse = {
activeClusterId: string | null;
clusters: ProxmuxClusterRow[];
favoritesByCluster?: Record<string, string[]>;
};
type ResourceRow = Record<string, unknown>;
const RESOURCE_TTL_MS = 9_000;
const GUEST_STATUS_TTL_MS = 5_000;
const GUEST_POLL_BASELINE_MS = 5_000;
const GUEST_POLL_JITTER_MS = 1_200;
type TimedCacheEntry<T> = {
value: T;
fetchedAt: number;
};
export function isSufficientlyFresh(fetchedAt: number, ttlMs: number, now = Date.now()): boolean {
if (!Number.isFinite(fetchedAt) || fetchedAt <= 0) return false;
if (!Number.isFinite(ttlMs) || ttlMs <= 0) return false;
return now - fetchedAt <= ttlMs;
}
export function computeAdaptiveGuestPollDelayMs(randomValue = Math.random()): number {
const clamped = Math.min(1, Math.max(0, randomValue));
return GUEST_POLL_BASELINE_MS + Math.round(clamped * GUEST_POLL_JITTER_MS);
}
export function shouldRunAdaptiveGuestPollTick(
appVisible: boolean,
docVisibility: DocumentVisibilityState | string,
): boolean {
return appVisible && docVisibility === "visible";
}
function proxmuxDebugEnabled(): boolean {
if (typeof window === "undefined") return false;
return window.localStorage.getItem("nss.proxmux.debugCache") === "1";
}
function proxmuxDebugMark(event: string, details: string) {
if (!proxmuxDebugEnabled()) return;
// Debug-only trace to inspect refresh cadence and cache reuse.
console.debug(`[proxmux][${event}] ${details}`);
}
function rowText(row: ResourceRow): string {
const parts = [row.type, row.vmid, row.name, row.node, row.status, row.ip4, row.ip6].map((v) =>
v == null ? "" : String(v),
);
return parts.join(" ").toLowerCase();
}
/** Display string for enriched `ip4` / `ip6` fields from `fetchResources` (English em dash when unset). */
export function resourceIpStat(row: ResourceRow, kind: "ip4" | "ip6"): string {
const raw = row[kind];
if (raw == null) return "—";
const s = String(raw).trim();
return s.length > 0 ? s : "—";
}
function guestKey(row: ResourceRow): string {
const t = String(row.type ?? "");
const vmid = row.vmid != null ? String(row.vmid) : "";
const node = row.node != null ? String(row.node) : "";
return `${t}:${node}:${vmid}`;
}
/** Parses `guestKey` values (`type:node:vmid`). Node may contain `:`, so use first/last colon. */
function parseGuestKey(key: string): { guestType: "qemu" | "lxc"; node: string; vmid: string } | null {
const first = key.indexOf(":");
const last = key.lastIndexOf(":");
if (first <= 0 || last <= first) return null;
const rawType = key.slice(0, first);
const node = key.slice(first + 1, last);
const vmid = key.slice(last + 1);
const guestType = rawType.toLowerCase();
if (guestType !== "qemu" && guestType !== "lxc") return null;
if (!node || !vmid) return null;
return { guestType: guestType as "qemu" | "lxc", node, vmid };
}
function formatBytes(n: unknown): string | null {
const v = typeof n === "number" ? n : typeof n === "string" ? Number(n) : NaN;
if (!Number.isFinite(v) || v < 0) return null;
const u = ["B", "KiB", "MiB", "GiB", "TiB"];
let x = v;
let i = 0;
while (x >= 1024 && i < u.length - 1) {
x /= 1024;
i += 1;
}
const digits = i === 0 ? 0 : x >= 100 ? 0 : x >= 10 ? 1 : 2;
return `${x.toFixed(digits)} ${u[i]}`;
}
function formatUptimeSeconds(sec: unknown): string | null {
const s = typeof sec === "number" ? sec : typeof sec === "string" ? Number(sec) : NaN;
if (!Number.isFinite(s) || s < 0) return null;
const d = Math.floor(s / 86400);
const h = Math.floor((s % 86400) / 3600);
const m = Math.floor((s % 3600) / 60);
const parts: string[] = [];
if (d > 0) parts.push(`${d}d`);
if (d > 0 || h > 0) parts.push(`${h}h`);
parts.push(`${m}m`);
return parts.join(" ");
}
function formatCpu(cpu: unknown): string | null {
if (typeof cpu !== "number" || !Number.isFinite(cpu)) return null;
if (cpu >= 0 && cpu <= 1) return `${(cpu * 100).toFixed(1)}%`;
return `${cpu.toFixed(2)}`;
}
function guestStatusRunning(data: Record<string, unknown>): boolean {
return String(data.status ?? "").toLowerCase() === "running";
}
function guestQemuPaused(data: Record<string, unknown>, guestType: string): boolean {
if (guestType !== "qemu") return false;
const q = String(data.qmpstatus ?? "").toLowerCase();
return q === "paused";
}
function isGuestRow(row: ResourceRow): boolean {
const t = String(row.type ?? "").toLowerCase();
return t === "qemu" || t === "lxc";
}
/** Stable favorite / API key: `node:{name}` or `guestKey` for qemu/lxc. */
function proxmuxResourceKey(row: ResourceRow): string | null {
const t = String(row.type ?? "").toLowerCase();
if (t === "node") {
const node = row.node != null ? String(row.node) : "";
return node ? `node:${node}` : null;
}
if (t === "qemu" || t === "lxc") {
return guestKey(row);
}
return null;
}
/** Expansion key for slide menu: guests use `guestKey`, nodes use `node:{name}`. */
export function expansionKeyForRow(row: ResourceRow): string | null {
if (isGuestRow(row)) {
return guestKey(row);
}
if (String(row.type ?? "").toLowerCase() === "node") {
return proxmuxResourceKey(row);
}
return null;
}
/** True when the row opens the same slide UX as guests (nodes + qemu/lxc). */
export function expandableProxmuxRow(row: ResourceRow): boolean {
return expansionKeyForRow(row) != null;
}
/** Parse `node:{nodename}` from unified expansion state (guest keys never start with `node:`). */
function parseNodeExpansionKey(key: string): string | null {
if (!key.startsWith("node:")) return null;
const nodename = key.slice("node:".length);
return nodename.length > 0 ? nodename : null;
}
function resourceMemLine(row: ResourceRow): string | null {
const mem = formatBytes(row.mem);
const max = formatBytes(row.maxmem);
if (mem && max) return `${mem} / ${max}`;
if (max) return `n/a / ${max}`;
if (mem) return mem;
return null;
}
function resourceDiskLine(row: ResourceRow): string | null {
const d = formatBytes(row.disk);
const max = formatBytes(row.maxdisk);
if (d && max) return `${d} / ${max}`;
if (max) return `n/a / ${max}`;
if (d) return d;
return null;
}
function rowIsUp(row: ResourceRow): boolean {
const s = String(row.status ?? "").toLowerCase();
if (String(row.type ?? "").toLowerCase() === "node") {
return s === "online";
}
return s === "running";
}
/** Proxmox cluster resources mark QEMU templates with `template` truthy / 1. */
function rowIsQemuTemplate(row: ResourceRow): boolean {
const v = row.template;
if (v === true || v === 1) return true;
if (typeof v === "number" && v !== 0) return true;
if (typeof v === "string") {
const t = v.trim().toLowerCase();
return t === "1" || t === "true" || t === "yes";
}
return false;
}
export type ProxmuxRowCategory = "node" | "qemu" | "qemu-template" | "lxc";
/** Row tint category for styling (templates are still `type: qemu` in the API). */
export function proxmuxCategory(row: ResourceRow): ProxmuxRowCategory {
const t = String(row.type ?? "").toLowerCase();
if (t === "node") return "node";
if (t === "lxc") return "lxc";
if (t === "qemu") return rowIsQemuTemplate(row) ? "qemu-template" : "qemu";
return "node";
}
/** Power / health strip: templates use neutral styling, not red "stopped". */
export type ProxmuxRowPower = "up" | "down" | "template";
export function proxmuxPower(row: ResourceRow): ProxmuxRowPower {
if (proxmuxCategory(row) === "qemu-template") return "template";
return rowIsUp(row) ? "up" : "down";
}
export type ProxmuxSidebarPanelProps = {
searchQuery: string;
onResourceCountChange: (count: number) => void;
/** Open an SSH session to the PVE node hostname in a new pane (in-app). */
onSshToProxmoxNode?: (ctx: { clusterId: string; node: string }) => void | Promise<void>;
/** Open a Proxmox web console URL in a pane or the system browser (see Settings → Connection → PROXMUX). */
onOpenProxmoxExternalUrl?: (
url: string,
label?: string,
options?: { allowInsecureTls?: boolean; tlsTrustedCertPem?: string | null },
) => void | Promise<void>;
/** Fetch SPICE proxy via plugin and open a virt-viewer file (handled in App / shell). */
onOpenProxmoxSpice?: (ctx: { clusterId: string; node: string; vmid: string }) => void | Promise<void>;
/** When true with the handlers below, QEMU/LXC/node shell use pane-native clients instead of the web UI URL. */
usePaneNativeProxmoxConsoles?: boolean;
onOpenProxmoxQemuVncInPane?: (ctx: {
clusterId: string;
node: string;
vmid: string;
label: string;
allowInsecureTls: boolean;
proxmoxBaseUrl: string;
tlsTrustedCertPem?: string;
}) => void | Promise<void>;
onOpenProxmoxLxcConsoleInPane?: (ctx: {
clusterId: string;
node: string;
vmid: string;
label: string;
allowInsecureTls: boolean;
proxmoxBaseUrl: string;
tlsTrustedCertPem?: string;
}) => void | Promise<void>;
onOpenProxmoxNodeShellInPane?: (ctx: {
clusterId: string;
node: string;
label: string;
allowInsecureTls: boolean;
proxmoxBaseUrl: string;
tlsTrustedCertPem?: string;
}) => void | Promise<void>;
};
function stopRowEvent(e: MouseEvent | KeyboardEvent) {
e.stopPropagation();
if ("preventDefault" in e) e.preventDefault();
}
export function ProxmuxSidebarPanel({
searchQuery,
onResourceCountChange,
onSshToProxmoxNode,
onOpenProxmoxExternalUrl,
onOpenProxmoxSpice,
usePaneNativeProxmoxConsoles = false,
onOpenProxmoxQemuVncInPane,
onOpenProxmoxLxcConsoleInPane,
onOpenProxmoxNodeShellInPane,
}: ProxmuxSidebarPanelProps) {
const [clusters, setClusters] = useState<ProxmuxClusterRow[]>([]);
const [clusterId, setClusterId] = useState<string | null>(null);
const [resources, setResources] = useState<ResourceRow[]>([]);
const [appVisible, setAppVisible] = useState(() =>
typeof document !== "undefined" && typeof document.hasFocus === "function" ? document.hasFocus() : true,
);
/** Expanded slide row: `guestKey` for qemu/lxc or `node:{name}` for PVE nodes. */
const [expandedRowKey, setExpandedRowKey] = useState("");
const [loadError, setLoadError] = useState("");
/** True after the first `listState` attempt finishes (success or error). */
const [clustersListReady, setClustersListReady] = useState(false);
const [busy, setBusy] = useState(false);
const [guestStatus, setGuestStatus] = useState<Record<string, unknown> | null>(null);
const [guestDetailError, setGuestDetailError] = useState("");
const [guestStatusLoading, setGuestStatusLoading] = useState(false);
const [powerBusy, setPowerBusy] = useState(false);
const guestStatusReq = useRef(0);
const [favoritesByCluster, setFavoritesByCluster] = useState<Record<string, string[]>>({});
const [favoritesOnly, setFavoritesOnly] = useState(false);
const [spiceBusyKey, setSpiceBusyKey] = useState<string | null>(null);
/** After probing `/qemu/{vmid}/config` (vga): only running guests with QXL/spice/virtio show SPICE. */
const [spiceCapableByGuestKey, setSpiceCapableByGuestKey] = useState<Record<string, boolean>>({});
const spiceProbeDoneRef = useRef<Set<string>>(new Set());
const spiceProbeInflightRef = useRef<Set<string>>(new Set());
const resourcesCacheRef = useRef<Record<string, TimedCacheEntry<ResourceRow[]>>>({});
const resourcesInflightRef = useRef<Record<string, Promise<void> | undefined>>({});
const guestStatusCacheRef = useRef<Record<string, TimedCacheEntry<Record<string, unknown>>>>({});
const expandedGuestParsed = useMemo(
() => (expandedRowKey ? parseGuestKey(expandedRowKey) : null),
[expandedRowKey],
);
const expandedGuestCacheKey = useMemo(
() =>
clusterId && expandedGuestParsed
? `${clusterId}:${expandedGuestParsed.guestType}:${expandedGuestParsed.node}:${expandedGuestParsed.vmid}`
: null,
[clusterId, expandedGuestParsed],
);
const expandedNodeName = useMemo(
() => (expandedRowKey ? parseNodeExpansionKey(expandedRowKey) : null),
[expandedRowKey],
);
const expandedNodeResource = useMemo(() => {
if (!expandedNodeName) return null;
return (
resources.find(
(r) => String(r.type ?? "").toLowerCase() === "node" && String(r.node ?? "") === expandedNodeName,
) ?? null
);
}, [resources, expandedNodeName]);
const refreshClusters = useCallback(async () => {
setLoadError("");
try {
const raw = await pluginInvoke(PROXMUX_PLUGIN_ID, "listState", {});
const parsed = raw as ListStateResponse;
const list = parsed.clusters ?? [];
setFavoritesByCluster(parsed.favoritesByCluster ?? {});
setClusters(list);
setClusterId((prev) => {
if (prev && list.some((c) => c.id === prev)) return prev;
if (parsed.activeClusterId && list.some((c) => c.id === parsed.activeClusterId)) {
return parsed.activeClusterId;
}
return list[0]?.id ?? null;
});
} catch (e) {
setLoadError(e instanceof Error ? e.message : String(e));
setClusters([]);
setClusterId(null);
setFavoritesByCluster({});
} finally {
setClustersListReady(true);
}
}, []);
useEffect(() => {
void refreshClusters();
}, [refreshClusters]);
useEffect(() => {
const onFocus = () => setAppVisible(true);
const onBlur = () => setAppVisible(false);
const onVisibilityChange = () => {
if (document.visibilityState === "visible" && typeof document.hasFocus === "function") {
setAppVisible(document.hasFocus());
return;
}
if (document.visibilityState !== "visible") {
setAppVisible(false);
}
};
window.addEventListener("focus", onFocus);
window.addEventListener("blur", onBlur);
document.addEventListener("visibilitychange", onVisibilityChange);
return () => {
window.removeEventListener("focus", onFocus);
window.removeEventListener("blur", onBlur);
document.removeEventListener("visibilitychange", onVisibilityChange);
};
}, []);
const fetchResources = useCallback(async (opts?: { force?: boolean }) => {
if (!clusterId) {
setResources([]);
return;
}
const now = Date.now();
const cacheEntry = resourcesCacheRef.current[clusterId];
const force = Boolean(opts?.force);
if (cacheEntry) {
setResources(cacheEntry.value);
proxmuxDebugMark("resources-cache-read", `cluster=${clusterId}`);
}
if (!force && cacheEntry && isSufficientlyFresh(cacheEntry.fetchedAt, RESOURCE_TTL_MS, now)) {
proxmuxDebugMark("resources-cache-hit", `cluster=${clusterId}`);
return;
}
const existingInflight = resourcesInflightRef.current[clusterId];
if (existingInflight) {
await existingInflight;
return;
}
const cacheStaleOrMissing = !cacheEntry || !isSufficientlyFresh(cacheEntry.fetchedAt, RESOURCE_TTL_MS, now);
const showBusy = force || cacheStaleOrMissing;
if (showBusy) {
setBusy(true);
}
setLoadError("");
const run = (async () => {
try {
proxmuxDebugMark("resources-fetch", `cluster=${clusterId} force=${String(force)}`);
const out = (await pluginInvoke(PROXMUX_PLUGIN_ID, "fetchResources", {
clusterId,
})) as { ok?: boolean; resources?: ResourceRow[] };
const nextResources = out.resources ?? [];
resourcesCacheRef.current[clusterId] = {
value: nextResources,
fetchedAt: Date.now(),
};
setResources(nextResources);
proxmuxDebugMark("resources-store", `cluster=${clusterId} count=${nextResources.length}`);
} catch (e) {
setLoadError(e instanceof Error ? e.message : String(e));
if (!cacheEntry) {
setResources([]);
}
} finally {
if (showBusy) {
setBusy(false);
}
}
})();
resourcesInflightRef.current[clusterId] = run;
try {
await run;
} finally {
resourcesInflightRef.current[clusterId] = undefined;
}
}, [clusterId]);
useEffect(() => {
void fetchResources();
}, [fetchResources]);
useEffect(() => {
setExpandedRowKey("");
}, [clusterId]);
useEffect(() => {
spiceProbeDoneRef.current.clear();
spiceProbeInflightRef.current.clear();
setSpiceCapableByGuestKey({});
}, [clusterId]);
useEffect(() => {
if (!clusterId) return;
const targets = resources.filter(
(r) => proxmuxCategory(r) === "qemu" && rowIsUp(r),
);
const gkSet = new Set(targets.map((r) => guestKey(r)));
for (const k of [...spiceProbeDoneRef.current]) {
if (!gkSet.has(k)) spiceProbeDoneRef.current.delete(k);
}
for (const k of [...spiceProbeInflightRef.current]) {
if (!gkSet.has(k)) spiceProbeInflightRef.current.delete(k);
}
setSpiceCapableByGuestKey((prev) => {
const next: Record<string, boolean> = {};
for (const k of gkSet) {
if (k in prev) next[k] = prev[k];
}
return next;
});
let cancelled = false;
for (const row of targets) {
const gk = guestKey(row);
if (spiceProbeDoneRef.current.has(gk) || spiceProbeInflightRef.current.has(gk)) continue;
const node = row.node != null ? String(row.node) : "";
const vmid = row.vmid != null ? String(row.vmid) : "";
if (!node || !vmid) continue;
spiceProbeInflightRef.current.add(gk);
void (async () => {
try {
const out = (await pluginInvoke(PROXMUX_PLUGIN_ID, "qemuSpiceCapable", {
clusterId,
node,
vmid,
guestType: "qemu",
})) as { ok?: boolean; spiceCapable?: boolean };
if (cancelled) return;
const cap = Boolean(out?.ok && out.spiceCapable);
spiceProbeDoneRef.current.add(gk);
setSpiceCapableByGuestKey((prev) => ({ ...prev, [gk]: cap }));
} catch {
if (!cancelled) {
spiceProbeDoneRef.current.add(gk);
setSpiceCapableByGuestKey((prev) => ({ ...prev, [gk]: false }));
}
} finally {
spiceProbeInflightRef.current.delete(gk);
}
})();
}
return () => {
cancelled = true;
};
}, [clusterId, resources]);
useEffect(() => {
if (!expandedRowKey) return;
const exists = resources.some((r) => expansionKeyForRow(r) === expandedRowKey);
if (!exists) setExpandedRowKey("");
}, [resources, expandedRowKey]);
const loadGuestStatus = useCallback(async (opts?: { silent?: boolean; force?: boolean }) => {
if (!clusterId || !expandedGuestParsed) {
setGuestStatus(null);
setGuestDetailError("");
return;
}
const my = ++guestStatusReq.current;
const silent = Boolean(opts?.silent);
const now = Date.now();
const cacheKey = expandedGuestCacheKey;
const cachedStatus = cacheKey ? guestStatusCacheRef.current[cacheKey] : undefined;
if (cachedStatus) {
setGuestStatus(cachedStatus.value);
proxmuxDebugMark("guest-cache-read", `key=${cacheKey ?? "n/a"}`);
}
const shouldSkipFetch =
silent &&
!opts?.force &&
cachedStatus != null &&
isSufficientlyFresh(cachedStatus.fetchedAt, GUEST_STATUS_TTL_MS, now);
if (shouldSkipFetch) {
proxmuxDebugMark("guest-cache-hit", `key=${cacheKey ?? "n/a"}`);
setGuestStatusLoading(false);
setGuestDetailError("");
return;
}
if (!silent && !cachedStatus) {
setGuestStatusLoading(true);
}
setGuestDetailError("");
try {
proxmuxDebugMark(
"guest-fetch",
`cluster=${clusterId} node=${expandedGuestParsed.node} vmid=${expandedGuestParsed.vmid} force=${String(Boolean(opts?.force))}`,
);
const out = (await pluginInvoke(PROXMUX_PLUGIN_ID, "guestStatus", {
clusterId,
node: expandedGuestParsed.node,
guestType: expandedGuestParsed.guestType,
vmid: expandedGuestParsed.vmid,
})) as { ok?: boolean; data?: Record<string, unknown> };
if (my !== guestStatusReq.current) return;
if (out.ok && out.data != null && typeof out.data === "object" && !Array.isArray(out.data)) {
const nextStatus = out.data as Record<string, unknown>;
if (cacheKey) {
guestStatusCacheRef.current[cacheKey] = {
value: nextStatus,
fetchedAt: Date.now(),
};
}
setGuestStatus(nextStatus);
proxmuxDebugMark("guest-store", `key=${cacheKey ?? "n/a"}`);
} else {
setGuestStatus(null);
setGuestDetailError("Unexpected guest status response.");
}
} catch (e) {
if (my !== guestStatusReq.current) return;
setGuestStatus(null);
setGuestDetailError(e instanceof Error ? e.message : String(e));
} finally {
if (my === guestStatusReq.current && !silent) {
setGuestStatusLoading(false);
}
}
}, [clusterId, expandedGuestParsed, expandedGuestCacheKey]);
useEffect(() => {
if (!clusterId || !expandedGuestParsed) {
guestStatusReq.current += 1;
setGuestStatus(null);
setGuestDetailError("");
setGuestStatusLoading(false);
return;
}
void loadGuestStatus();
}, [clusterId, expandedGuestParsed, loadGuestStatus]);
useEffect(() => {
if (!clusterId || !expandedGuestParsed) return;
let cancelled = false;
let timeoutId: number | null = null;
const schedule = () => {
if (cancelled) return;
const delay = computeAdaptiveGuestPollDelayMs();
timeoutId = window.setTimeout(() => {
if (cancelled) return;
if (shouldRunAdaptiveGuestPollTick(appVisible, document.visibilityState)) {
void loadGuestStatus({ silent: true, force: true });
}
schedule();
}, delay);
};
schedule();
return () => {
cancelled = true;
if (timeoutId != null) {
window.clearTimeout(timeoutId);
}
};
}, [clusterId, expandedGuestParsed, loadGuestStatus, appVisible]);
const runPowerAction = useCallback(
async (action: string) => {
if (!clusterId || !expandedGuestParsed) return;
setPowerBusy(true);
setGuestDetailError("");
try {
await pluginInvoke(PROXMUX_PLUGIN_ID, "guestPower", {
clusterId,
node: expandedGuestParsed.node,
guestType: expandedGuestParsed.guestType,
vmid: expandedGuestParsed.vmid,
action,
});
await loadGuestStatus({ force: true });
} catch (e) {
setGuestDetailError(e instanceof Error ? e.message : String(e));
} finally {
setPowerBusy(false);
}
},
[clusterId, expandedGuestParsed, loadGuestStatus],
);
const favoriteSet = useMemo(() => {
if (!clusterId) return new Set<string>();
return new Set(favoritesByCluster[clusterId] ?? []);
}, [clusterId, favoritesByCluster]);
const toggleProxmuxFavorite = useCallback(
async (resourceKey: string) => {
if (!clusterId) return;
try {
const out = (await pluginInvoke(PROXMUX_PLUGIN_ID, "toggleProxmuxFavorite", {
clusterId,
resourceKey,
})) as { ok?: boolean; favorites?: string[] };
if (out.ok && Array.isArray(out.favorites)) {
setFavoritesByCluster((prev) => ({ ...prev, [clusterId]: out.favorites as string[] }));
}
} catch (e) {
setLoadError(e instanceof Error ? e.message : String(e));
}
},
[clusterId],
);
const normalizedSearch = searchQuery.trim().toLowerCase();
const filteredResources = useMemo(() => {
let rows = resources;
if (normalizedSearch) {
rows = rows.filter((row) => rowText(row).includes(normalizedSearch));
}
if (favoritesOnly && clusterId) {
rows = rows.filter((row) => {
const k = proxmuxResourceKey(row);
return k != null && favoriteSet.has(k);
});
}
return rows;
}, [resources, normalizedSearch, favoritesOnly, clusterId, favoriteSet]);
useEffect(() => {
onResourceCountChange(filteredResources.length);
}, [filteredResources.length, onResourceCountChange]);
const grouped = useMemo(() => {
const sortRows = (rows: ResourceRow[]): ResourceRow[] =>
[...rows].sort((a, b) => {
const aUp = rowIsUp(a) ? 0 : 1;
const bUp = rowIsUp(b) ? 0 : 1;
if (aUp !== bUp) return aUp - bUp;
const aKey = proxmuxResourceKey(a);
const bKey = proxmuxResourceKey(b);
const aFav = aKey != null && favoriteSet.has(aKey) ? 0 : 1;
const bFav = bKey != null && favoriteSet.has(bKey) ? 0 : 1;
if (aFav !== bFav) return aFav - bFav;
const aName = String(a.name ?? a.node ?? "").toLowerCase();
const bName = String(b.name ?? b.node ?? "").toLowerCase();
return aName.localeCompare(bName);
});
const nodes = sortRows(filteredResources.filter((r) => r.type === "node"));
const qemus = sortRows(filteredResources.filter((r) => r.type === "qemu"));
const lxcs = sortRows(filteredResources.filter((r) => r.type === "lxc"));
return [
{ title: "Nodes", rows: nodes },
{ title: "Virtual machines", rows: qemus },
{ title: "Containers", rows: lxcs },
];
}, [filteredResources, favoriteSet]);
const powerDisabled = powerBusy || busy;
const guestMemLine = guestStatus ? resourceMemLine(guestStatus as ResourceRow) : null;
const guestStatusLine =
guestStatus &&
(() => {
const main = String(guestStatus.status ?? "").trim() || "n/a";
if (expandedGuestParsed?.guestType !== "qemu") return main;
const qmp = String(guestStatus.qmpstatus ?? "").trim();
if (qmp && qmp.toLowerCase() !== main.toLowerCase()) return `${main} (${qmp})`;
return main;
})();
const toggleExpandRow = useCallback((key: string) => {
setExpandedRowKey((prev) => (prev === key ? "" : key));
}, []);
const activeCluster = useMemo(
() => clusters.find((c) => c.id === clusterId) ?? null,
[clusters, clusterId],
);
const proxmoxBaseUrl = activeCluster?.proxmoxUrl ?? "";
const allowInsecureTlsForOpens = activeCluster?.allowInsecureTls === true;
const tlsTrustedCertPemForOpens = typeof activeCluster?.tlsTrustedCertPem === "string" ? activeCluster.tlsTrustedCertPem.trim() : "";
const runOpenUrl = useCallback(
async (url: string, label?: string) => {
if (!onOpenProxmoxExternalUrl) return;
try {
await onOpenProxmoxExternalUrl(url, label, {
allowInsecureTls: allowInsecureTlsForOpens,
tlsTrustedCertPem: tlsTrustedCertPemForOpens,
});
} catch {
/* App surfaces errors */
}
},
[onOpenProxmoxExternalUrl, allowInsecureTlsForOpens],
);
const runSpice = useCallback(
async (node: string, vmid: string) => {
if (!clusterId || !onOpenProxmoxSpice) return;
const key = `${node}:${vmid}`;
setSpiceBusyKey(key);
try {
await onOpenProxmoxSpice({ clusterId, node, vmid });
} finally {
setSpiceBusyKey((k) => (k === key ? null : k));
}
},
[clusterId, onOpenProxmoxSpice],
);
function rowActionStrip(row: ResourceRow) {
const spacer = () => <span className="proxmux-sidebar-actions-spacer" aria-hidden />;
if (!clusterId || !proxmoxBaseUrl) {
return spacer();
}
const cat = proxmuxCategory(row);
const node = row.node != null ? String(row.node) : "";
const vmid = row.vmid != null ? String(row.vmid) : "";
const running = rowIsUp(row);
const spiceKey = `${node}:${vmid}`;
const spiceBusy = spiceBusyKey === spiceKey;
if (cat === "qemu-template") {
return spacer();
}
if (cat === "node") {
if (
!onSshToProxmoxNode &&
!onOpenProxmoxExternalUrl &&
!(usePaneNativeProxmoxConsoles && onOpenProxmoxNodeShellInPane)
) {
return spacer();
}
if (!node) return spacer();
return (
<div className="proxmux-sidebar-actions" onMouseDown={(e) => e.stopPropagation()}>
{onSshToProxmoxNode ? (
<button
type="button"
className="proxmux-action-btn proxmux-action-ssh"
title="Open SSH session in a new pane"
aria-label="Open SSH session in a new pane"
onClick={(e) => {
stopRowEvent(e);
void onSshToProxmoxNode({ clusterId, node });
}}
>
SSH
</button>
) : null}
{onOpenProxmoxExternalUrl || (usePaneNativeProxmoxConsoles && onOpenProxmoxNodeShellInPane) ? (
<button
type="button"
className="proxmux-action-btn proxmux-action-shell"
title="Open Proxmox node shell (app pane or browser — Settings → Connection → PROXMUX)"
aria-label="Open Proxmox node shell"
onClick={(e) => {
stopRowEvent(e);
if (usePaneNativeProxmoxConsoles && onOpenProxmoxNodeShellInPane && clusterId) {
void onOpenProxmoxNodeShellInPane({
clusterId,
node,
label: "Node shell",
allowInsecureTls: allowInsecureTlsForOpens,
proxmoxBaseUrl,
...(tlsTrustedCertPemForOpens ? { tlsTrustedCertPem: tlsTrustedCertPemForOpens } : {}),
});
return;
}
void runOpenUrl(buildProxmoxConsoleUrl(proxmoxBaseUrl, { kind: "node", node }), "Node shell");
}}
>
Shell
</button>
) : null}
</div>
);
}
if (cat === "qemu") {
const gk = guestKey(row);
const spiceCapable = spiceCapableByGuestKey[gk] === true;
const showVnc = Boolean(
onOpenProxmoxExternalUrl || (usePaneNativeProxmoxConsoles && onOpenProxmoxQemuVncInPane),
);
const showSpice = Boolean(onOpenProxmoxSpice && spiceCapable);
if (!running || !node || !vmid || (!showVnc && !showSpice)) {
return spacer();
}
return (
<div className="proxmux-sidebar-actions" onMouseDown={(e) => e.stopPropagation()}>
{showVnc ? (
<button
type="button"
className="proxmux-action-btn proxmux-action-novnc"
title="Open noVNC (app pane or browser — Settings → Connection → PROXMUX)"
aria-label="Open noVNC console"
onClick={(e) => {
stopRowEvent(e);
if (usePaneNativeProxmoxConsoles && onOpenProxmoxQemuVncInPane && clusterId) {
void onOpenProxmoxQemuVncInPane({
clusterId,
node,
vmid,
label: "noVNC",
allowInsecureTls: allowInsecureTlsForOpens,
proxmoxBaseUrl,
...(tlsTrustedCertPemForOpens ? { tlsTrustedCertPem: tlsTrustedCertPemForOpens } : {}),
});
return;
}
void runOpenUrl(buildProxmoxConsoleUrl(proxmoxBaseUrl, { kind: "qemu", node, vmid }), "noVNC");
}}
>
VNC
</button>
) : null}
{showSpice ? (
<button
type="button"
className="proxmux-action-btn proxmux-action-spice"
disabled={spiceBusy}
title="Open SPICE console (virt-viewer)"
aria-label="Open SPICE console"
onClick={(e) => {
stopRowEvent(e);
void runSpice(node, vmid);
}}
>
{spiceBusy ? "…" : "SPICE"}
</button>
) : null}
</div>
);
}
if (cat === "lxc") {
if ((!onOpenProxmoxExternalUrl && !(usePaneNativeProxmoxConsoles && onOpenProxmoxLxcConsoleInPane)) || !node || !vmid) {
return spacer();
}
return (
<div className="proxmux-sidebar-actions" onMouseDown={(e) => e.stopPropagation()}>
<button
type="button"
className="proxmux-action-btn proxmux-action-shell"
disabled={!running}
title={
running
? "Open LXC console (app pane or browser — Settings → Connection → PROXMUX)"
: "Start the container to open the console"
}
aria-label="Open LXC console"
onClick={(e) => {
stopRowEvent(e);
if (!running) return;
if (usePaneNativeProxmoxConsoles && onOpenProxmoxLxcConsoleInPane && clusterId) {
void onOpenProxmoxLxcConsoleInPane({
clusterId,
node,
vmid,
label: "LXC console",
allowInsecureTls: allowInsecureTlsForOpens,
proxmoxBaseUrl,
...(tlsTrustedCertPemForOpens ? { tlsTrustedCertPem: tlsTrustedCertPemForOpens } : {}),
});
return;
}
void runOpenUrl(buildProxmoxConsoleUrl(proxmoxBaseUrl, { kind: "lxc", node, vmid }), "LXC console");
}}
>
Shell
</button>
</div>
);
}
return spacer();
}
if (!clustersListReady && !loadError) {
return (
<div className="proxmux-sidebar-panel proxmux-sidebar-panel--boot" role="status" aria-busy="true" aria-label="Loading PROXMUX">
<p className="muted-copy proxmux-sidebar-loading proxmux-sidebar-loading-row proxmux-sidebar-boot-loading">
<InlineSpinner label="Loading PROXMUX" />
<span>Loading clusters…</span>
</p>
</div>
);
}
if (clusters.length === 0 && !loadError) {
return (
<div className="proxmux-sidebar-panel">
<div className="empty-pane">
<p>No Proxmox clusters</p>
<span>Add a cluster under Settings → Connection → PROXMUX.</span>
</div>
</div>
);
}
return (
<div className="proxmux-sidebar-panel">
{loadError ? <p className="error-text proxmux-sidebar-error">{loadError}</p> : null}
<div className="proxmux-sidebar-toolbar">
<label className="proxmux-sidebar-cluster-label">
<span className="proxmux-sidebar-field-label">Cluster</span>
<select
className="input proxmux-sidebar-cluster-select"
value={clusterId ?? ""}
onChange={(e) => setClusterId(e.target.value || null)}
disabled={busy || clusters.length === 0}
aria-label="Proxmox cluster"
>
{clusters.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</label>
<button