-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathNodeDetailModal.tsx
More file actions
2401 lines (2340 loc) · 112 KB
/
Copy pathNodeDetailModal.tsx
File metadata and controls
2401 lines (2340 loc) · 112 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
/* eslint-disable react-hooks/set-state-in-effect, react-hooks/refs, react-hooks/purity */
import { PARENT_HOVER_ATTR, X } from 'lucide-react-motion';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { errLikeToLogString } from '@/renderer/lib/errLikeToLogString';
import { formatDisplayTime } from '@/renderer/lib/formatDisplayTime';
import { useParentIconTrigger } from '@/renderer/lib/icons/iconMotionContext';
import { getIdentityIdForProtocol } from '@/renderer/lib/identityByProtocol';
import {
isValidMeshtasticAdminKeyBase64,
normalizeMeshtasticAdminKeyInput,
} from '@/renderer/lib/meshtasticRemoteAdminKeyStorage';
import { getOfflineIdentityIdForProtocol } from '@/renderer/lib/offlineProtocolIdentities';
import { writeClipboardText } from '@/renderer/lib/writeClipboardText';
import { formatIsoDateTime } from '@/shared/formatIsoDate';
import { buildMeshcoreContactAddUri, type MeshcoreContactType } from '@/shared/meshClientDeepLink';
import { meshcoreContactDisplayName } from '@/shared/meshcoreContactSanitize';
import { isDeleteActiveMqttIdentityError } from '@/shared/meshtasticDeleteNodeError';
import { formatMeshtasticNodeId } from '@/shared/nodeNameUtils';
import { touch } from '@/shared/touch';
import { MESHCORE_NEIGHBORS_MAX_RECOMMENDED_HOPS } from '../hooks/meshcore/meshcoreHookPreamble';
import { useMeshcoreRepeaterRemoteAuth } from '../hooks/useMeshcoreRepeaterRemoteAuth';
import { formatCoordPair } from '../lib/coordUtils';
import { downloadBlob } from '../lib/downloadBlob';
import { meshtasticHwModelDisplay } from '../lib/hardwareModels';
import type {
MeshCoreNeighborResult,
MeshCoreNodeTelemetry,
MeshCoreRepeaterStatus,
MeshcoreRequestNeighborsOpts,
MeshcoreTraceResultEntry,
} from '../lib/meshcore/meshcoreHookTypes';
import { translateMeshcoreUserMessage } from '../lib/meshcore/meshcoreMessageI18n';
import {
buildMeshcorePathChainSegments,
buildMeshcorePathResolutionFromNodes,
meshcoreDisplayRouteFromPathSelection,
meshcoreHopSegmentTooltip,
meshcorePathBytesEqual,
meshcoreTraceHopDisplayRows,
} from '../lib/meshcorePathChainDisplay';
import {
isMeshcoreDmExcludedHwModel,
MESHCORE_CHAT_STUB_ID_MAX,
MESHCORE_CHAT_STUB_ID_MIN,
MESHCORE_CONTACTS_CRITICAL_THRESHOLD,
MESHCORE_MAX_CONTACTS,
meshcoreContactTypeFromHwModel,
meshcoreTracePathLenToHops,
} from '../lib/meshcoreUtils';
import {
bytesToHex,
computeRangeTestLossRate,
latestPaxPoint,
type ModulePortEvent,
parseRangeTestPayload,
type PaxCounterPoint,
} from '../lib/meshtastic/meshtasticModuleEvents';
import { meshtasticNodeAwaitingNodeInfo } from '../lib/meshtastic/meshtasticNodeAwaitingNodeInfo';
import { Z_NODE_DETAIL_MODAL } from '../lib/modalZIndex';
import { getNodeStatus } from '../lib/nodeStatus';
import { useRadioProvider } from '../lib/radio/providerFactory';
import { MESHCORE_TRACE_PING_TOTAL_TIMEOUT_MS } from '../lib/timeConstants';
import type { MeshCoreLocalStats, MeshNode, MeshProtocol, NeighborInfoRecord } from '../lib/types';
import { useBlockStore } from '../stores/blockStore';
import { useCoordFormatStore } from '../stores/coordFormatStore';
import { useDiagnosticsStore } from '../stores/diagnosticsStore';
import { useNodeStore } from '../stores/nodeStore';
import { usePathHistoryStore } from '../stores/pathHistoryStore';
import { useTimeFormatStore } from '../stores/timeFormatStore';
import { useWatchedNodesStore } from '../stores/watchedNodesStore';
import { HelpTooltip } from './HelpTooltip';
import { MeshcoreRepeaterPasswordControls } from './MeshcoreRepeaterPasswordControls';
import { MeshcoreRouteChain } from './MeshcoreRouteChain';
import NodeInfoBody, { formatSecondsAgo } from './NodeInfoBody';
import QrCodeImage from './QrCodeImage';
import SnrIndicator from './SnrIndicator';
const TRACE_ROUTE_UI_TIMEOUT_MS = 120_000;
const POSITION_HISTORY_MAX_ROWS = 100;
interface NodeDetailModalProps {
/** Optional: enables originator list for Mesh Congestion (RF duplicate-prone by node). */
nodes?: Map<number, MeshNode>;
node: MeshNode | null;
onClose: () => void;
onRequestPosition?: (nodeNum: number) => Promise<void>;
onTraceRoute?: (nodeNum: number) => Promise<boolean | undefined>;
traceRouteHops?: string[];
onDeleteNode?: (nodeNum: number) => Promise<void>;
onMessageNode?: (nodeNum: number) => void;
/** MeshCore room server: open Rooms tab for BBS posts (not DM). */
onOpenRoom?: (nodeNum: number) => void;
onToggleFavorite: (nodeId: number, favorited: boolean) => void;
isConnected: boolean;
mqttConnected?: boolean;
radioConnected?: boolean;
homeNode?: MeshNode | null;
neighborInfo?: Map<number, NeighborInfoRecord>;
useFahrenheit?: boolean;
protocol?: MeshProtocol;
meshcoreTraceResult?: MeshcoreTraceResultEntry;
meshcorePingError?: string;
meshcoreRepeaterStatus?: MeshCoreRepeaterStatus;
meshcoreStatusError?: string;
onRequestRepeaterStatus?: (nodeId: number) => Promise<void>;
meshcoreNodeTelemetry?: MeshCoreNodeTelemetry;
meshcoreTelemetryError?: string;
onRequestTelemetry?: (nodeId: number) => Promise<void>;
meshcoreNeighbors?: MeshCoreNeighborResult;
onRequestNeighbors?: (nodeId: number, opts?: MeshcoreRequestNeighborsOpts) => Promise<void>;
meshcoreNeighborError?: string;
/** PaxCounter history from Meshtastic (capped session series per node) */
paxCounterData?: Map<number, PaxCounterPoint[]>;
/** DetectionSensor events from Meshtastic (capped session list per node) */
detectionSensorEvents?: Map<number, ModulePortEvent[]>;
/** Range Test packets from Meshtastic (capped session list per node) */
rangeTestPackets?: Map<number, ModulePortEvent[]>;
/** MapReport data from Meshtastic (location/position reports per node) */
mapReports?: Map<number, { from: number; data: unknown; timestamp: number }>;
/** Export contact advert bytes (MeshCore only) */
onExportContact?: (nodeId: number) => Promise<Uint8Array | null>;
/** Share contact via mesh (MeshCore only) */
onShareContact?: (nodeId: number) => Promise<boolean>;
/** Local stats for MeshCore connected node (Type 1 & 2) */
meshcoreLocalStats?: MeshCoreLocalStats | null;
/** MeshCore: local radio manufacturer/model from `deviceQuery` (our node only in body). */
meshcoreManufacturerModel?: string;
/** GPS position history (tracking path) for mobile nodes */
positionHistory?: Map<number, { t: number; lat: number; lon: number }[]>;
onShowOnMap?: (nodeId: number, lat: number, lon: number) => void;
/** Meshtastic PKC: base64 admin public key saved for this node (one per node). */
remoteAdminKey?: string;
/** Persist admin key for remote admin (base64, 32-byte public key). */
onSaveRemoteAdminKey?: (nodeNum: number, adminKeyBase64: string | null) => Promise<void>;
/** Open Radio tab with this node as remote configure target. */
onConfigureRemotely?: (nodeNum: number) => void;
/** Saved admin key for this node (enables configure remotely). */
hasRemoteAdminKey?: boolean;
}
function meshcorePublicKeyToHex(publicKey: Uint8Array): string {
return Array.from(publicKey)
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
function NodeBlockButton({
protocol,
node,
publicKeyHex,
}: {
protocol: MeshProtocol | undefined;
node: MeshNode;
publicKeyHex?: string;
}) {
const { t } = useTranslation();
const identityId =
protocol && protocol !== 'reticulum'
? (getIdentityIdForProtocol(protocol) ?? getOfflineIdentityIdForProtocol(protocol))
: null;
const blockedHash =
protocol === 'meshcore' && publicKeyHex
? publicKeyHex
: protocol && protocol !== 'reticulum'
? String(node.node_id)
: '';
const isBlocked = useBlockStore((s) => (blockedHash ? s.isBlocked(blockedHash) : false));
const block = useBlockStore((s) => s.block);
const unblock = useBlockStore((s) => s.unblock);
if (!protocol || protocol === 'reticulum' || !identityId || !blockedHash) return null;
return (
<button
type="button"
className={`hover:bg-secondary-dark shrink-0 rounded-lg px-2 py-1 text-xs font-medium transition-colors ${isBlocked ? 'text-red-400' : 'text-gray-500 hover:text-red-400'}`}
aria-label={
isBlocked ? t('nodeDetailModal.unblockContact') : t('nodeDetailModal.blockContact')
}
onClick={() => {
void (isBlocked
? unblock(protocol, identityId, blockedHash)
: block(protocol, identityId, blockedHash));
}}
>
{isBlocked ? t('nodeDetailModal.unblockContact') : t('nodeDetailModal.blockContact')}
</button>
);
}
function WatchToggleButton({ nodeId }: { nodeId: number }) {
const { t } = useTranslation();
const isWatched = useWatchedNodesStore((s) => s.watchedNodeIds.has(nodeId));
const toggleWatch = useWatchedNodesStore((s) => s.toggleWatch);
return (
<button
type="button"
aria-label={isWatched ? t('nodeDetailModal.unwatchNode') : t('nodeDetailModal.watchNode')}
aria-pressed={isWatched}
className={`hover:bg-secondary-dark shrink-0 rounded-lg px-2 py-1 text-xs font-medium transition-colors ${isWatched ? 'text-blue-400' : 'text-gray-500 hover:text-blue-400'}`}
onClick={() => {
toggleWatch(nodeId);
}}
>
{isWatched ? t('nodeDetailModal.unwatchNode') : t('nodeDetailModal.watchNode')}
</button>
);
}
export default function NodeDetailModal({
nodes,
node,
onClose,
onRequestPosition,
onTraceRoute,
traceRouteHops,
onDeleteNode,
onMessageNode,
onOpenRoom,
onToggleFavorite,
isConnected,
mqttConnected = false,
radioConnected = false,
homeNode = null,
neighborInfo,
useFahrenheit,
protocol,
meshcoreTraceResult,
meshcorePingError,
meshcoreRepeaterStatus,
meshcoreStatusError,
onRequestRepeaterStatus,
meshcoreNodeTelemetry,
meshcoreTelemetryError,
onRequestTelemetry,
meshcoreNeighbors,
onRequestNeighbors,
meshcoreNeighborError,
paxCounterData,
detectionSensorEvents,
rangeTestPackets,
mapReports,
onExportContact,
onShareContact,
meshcoreLocalStats,
meshcoreManufacturerModel,
positionHistory,
onShowOnMap,
remoteAdminKey,
onSaveRemoteAdminKey,
onConfigureRemotely,
hasRemoteAdminKey,
}: NodeDetailModalProps) {
const { t } = useTranslation();
const parentIconTrigger = useParentIconTrigger();
const use24HourTime = useTimeFormatStore((s) => s.use24HourTime);
const { ensureRepeaterAuth, promptRepeaterPassword, RemoteAuthModal } =
useMeshcoreRepeaterRemoteAuth();
const [repeaterSecretsEpoch, setRepeaterSecretsEpoch] = useState(0);
const refreshRepeaterSecrets = useCallback(() => {
setRepeaterSecretsEpoch((n) => n + 1);
}, []);
const meshcoreIdentityId = protocol === 'meshcore' ? getIdentityIdForProtocol('meshcore') : null;
const storeContactPublicKey = useNodeStore((s) => {
if (!meshcoreIdentityId || node == null) return undefined;
return s.nodes[meshcoreIdentityId]?.[node.node_id]?.publicKey;
});
const pathHistoryRecordsForNode = usePathHistoryStore((s) =>
protocol === 'meshcore' && node != null ? (s.records.get(node.node_id) ?? null) : null,
);
const pathResolution = useMemo(
() => buildMeshcorePathResolutionFromNodes(nodes ?? new Map()),
[nodes],
);
const currentRoute = useMemo(() => {
if (protocol !== 'meshcore' || node == null || !pathHistoryRecordsForNode?.length) return null;
return meshcoreDisplayRouteFromPathSelection(
usePathHistoryStore.getState().selectBestPath(node.node_id),
);
}, [protocol, node, pathHistoryRecordsForNode]);
const currentRouteSegments = useMemo(() => {
if (!currentRoute) return [];
return buildMeshcorePathChainSegments({
pathBytes: currentRoute.pathBytes,
hashSizeBytes: currentRoute.hashSizeBytes,
getNodeLabel: pathResolution.getNodeLabel,
pubKeyByNodeId: pathResolution.pubKeyByNodeId,
candidates: pathResolution.candidates,
});
}, [currentRoute, pathResolution]);
const traceMatchesCurrentRoute =
meshcoreTraceResult != null &&
currentRoute != null &&
meshcorePathBytesEqual(meshcoreTraceResult.pathHashes, currentRoute.pathBytes);
const traceHopRows = useMemo(() => {
if (!meshcoreTraceResult || !node) return [];
const hashSizeBytes = meshcoreTraceResult.hashSizeBytes ?? 1;
return meshcoreTraceHopDisplayRows({
pathHashes: meshcoreTraceResult.pathHashes ?? [],
pathSnrs: meshcoreTraceResult.pathSnrs ?? [],
hashSizeBytes,
destNodeId: node.node_id,
getNodeLabel: pathResolution.getNodeLabel,
pubKeyByNodeId: pathResolution.pubKeyByNodeId,
candidates: pathResolution.candidates,
});
}, [meshcoreTraceResult, node, pathResolution]);
const coordinateFormat = useCoordFormatStore((s) => s.coordinateFormat);
const [actionStatus, setActionStatus] = useState<string | null>(null);
const [actionStatusIsDeleteMqttError, setActionStatusIsDeleteMqttError] = useState(false);
const [adminKeyStatus, setAdminKeyStatus] = useState<string | null>(null);
const [adminKeyDraft, setAdminKeyDraft] = useState('');
const [adminKeyError, setAdminKeyError] = useState<string | null>(null);
const [repeaterStatusPending, setRepeaterStatusPending] = useState(false);
const [showRepeaterStats, setShowRepeaterStats] = useState(false);
const [positionRequestedAt, setPositionRequestedAt] = useState<number | null>(null);
const [traceRoutePending, setTraceRoutePending] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [telemetryPending, setTelemetryPending] = useState(false);
const [showTelemetry, setShowTelemetry] = useState(false);
const [neighborsPending, setNeighborsPending] = useState(false);
const [showMeshcoreNeighbors, setShowMeshcoreNeighbors] = useState(false);
const meshcoreNeighborsRef = useRef(meshcoreNeighbors);
meshcoreNeighborsRef.current = meshcoreNeighbors;
const [exportContactPending, setExportContactPending] = useState(false);
const [shareContactPending, setShareContactPending] = useState(false);
const [showMeshcoreContactQr, setShowMeshcoreContactQr] = useState(false);
const [radioContactCount, setRadioContactCount] = useState<number | null>(null);
const [contactOnRadio, setContactOnRadio] = useState<boolean | null>(null);
const [addRemoveLoading, setAddRemoveLoading] = useState(false);
const [nodeNote, setNodeNote] = useState('');
const noteSaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pendingNoteRef = useRef<string | null>(null);
const noteSaveAllowedRef = useRef(true);
const mqttIgnoredNodes = useDiagnosticsStore((s) => s.mqttIgnoredNodes);
const setNodeMqttIgnored = useDiagnosticsStore((s) => s.setNodeMqttIgnored);
const getForeignLoraDetectionsList = useDiagnosticsStore((s) => s.getForeignLoraDetectionsList);
const closeButtonRef = useRef<HTMLButtonElement>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);
const nodeRef = useRef(node);
nodeRef.current = node;
const positionRequestedAtRef = useRef(positionRequestedAt);
positionRequestedAtRef.current = positionRequestedAt;
// Focus trap and focus management
useEffect(() => {
if (!nodeRef.current) return;
previousFocusRef.current = document.activeElement as HTMLElement;
closeButtonRef.current?.focus();
return () => {
previousFocusRef.current?.focus();
};
}, [node?.node_id]);
useEffect(() => {
setAdminKeyDraft(remoteAdminKey ?? '');
setAdminKeyError(null);
}, [node?.node_id, remoteAdminKey]);
useEffect(() => {
if (!node) return;
const nodeId = node.node_id;
noteSaveAllowedRef.current = true;
let cancelled = false;
void window.electronAPI.db
.getNodeNote(nodeId)
.then((note: string | null) => {
if (!cancelled) setNodeNote(note ?? '');
})
.catch((e: unknown) => {
console.warn('[NodeDetailModal] getNodeNote failed ' + errLikeToLogString(e));
});
return () => {
cancelled = true;
noteSaveAllowedRef.current = false;
if (noteSaveTimerRef.current) {
clearTimeout(noteSaveTimerRef.current);
noteSaveTimerRef.current = null;
}
const pending = pendingNoteRef.current;
pendingNoteRef.current = null;
if (pending !== null) {
void window.electronAPI.db.setNodeNote(nodeId, pending).catch((e: unknown) => {
console.warn('[NodeDetailModal] setNodeNote (unmount) failed ' + errLikeToLogString(e));
});
}
};
}, [node?.node_id]); // eslint-disable-line react-hooks/exhaustive-deps
// Close on Escape
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
document.addEventListener('keydown', handleKey);
return () => {
document.removeEventListener('keydown', handleKey);
};
}, [onClose]);
// Reset all state when node changes
useEffect(() => {
setActionStatus(null);
setActionStatusIsDeleteMqttError(false);
setAdminKeyStatus(null);
setPositionRequestedAt(null);
setTraceRoutePending(false);
setShowDeleteConfirm(false);
setRepeaterStatusPending(false);
setShowRepeaterStats(false);
setTelemetryPending(false);
setShowTelemetry(false);
setNeighborsPending(false);
setShowMeshcoreNeighbors(false);
setExportContactPending(false);
setShareContactPending(false);
setShowMeshcoreContactQr(false);
}, [node?.node_id]);
// Detect position update after a request was sent (gate on state, not ref — avoids flash on open)
useEffect(() => {
if (positionRequestedAt === null) return;
setPositionRequestedAt(null);
setActionStatus(t('nodeDetailModal.positionUpdated'));
}, [node?.latitude, node?.longitude, positionRequestedAt, t]);
// 30-second timeout for position request
useEffect(() => {
if (!positionRequestedAt) return;
const timer = setTimeout(() => {
setPositionRequestedAt(null);
setActionStatus(t('nodeDetailModal.positionRequestTimedOut'));
}, 30_000);
return () => {
clearTimeout(timer);
};
}, [positionRequestedAt, t]);
// Auto-show repeater stats when they arrive
useEffect(() => {
if (meshcoreRepeaterStatus) {
setRepeaterStatusPending(false);
setShowRepeaterStats(true);
}
}, [meshcoreRepeaterStatus]);
// Auto-show telemetry when it arrives
useEffect(() => {
if (meshcoreNodeTelemetry) {
setTelemetryPending(false);
setShowTelemetry(true);
}
}, [meshcoreNodeTelemetry]);
// Auto-show neighbors when they arrive
useEffect(() => {
if (meshcoreNeighbors) {
setNeighborsPending(false);
setShowMeshcoreNeighbors(true);
}
}, [meshcoreNeighbors]);
// Fetch on_radio status and contact count for MeshCore
const [contactPubkey, setContactPubkey] = useState<string | null>(null);
const {
nodeStaleThresholdMs,
nodeOfflineThresholdMs,
protocol: activeProtocol,
} = useRadioProvider(protocol ?? 'meshtastic');
const isMeshcoreProtocol = activeProtocol === 'meshcore';
const meshcoreContactQrUri = useMemo(() => {
if (!isMeshcoreProtocol || !contactPubkey || !node) return null;
const typeRaw = meshcoreContactTypeFromHwModel(node.hw_model ?? 'Chat') ?? 1;
const type = (typeRaw >= 1 && typeRaw <= 4 ? typeRaw : 1) as MeshcoreContactType;
try {
return buildMeshcoreContactAddUri({
name: node.long_name || node.short_name || `Node-${node.node_id.toString(16)}`,
publicKeyHex: contactPubkey,
type,
});
} catch {
// catch-no-log-ok Invalid pubkey simply hides the share QR.
return null;
}
}, [isMeshcoreProtocol, contactPubkey, node]);
const ensureRemoteRpcAccess = useCallback(
async (
nodeId: number,
hwModel: string | undefined,
mode: 'guest' | 'admin',
): Promise<boolean> => {
// Infra ops (status/telemetry/neighbors) use ops admin secrets like RepeatersPanel —
// not the Rooms BBS guest/admin overlay.
if (hwModel === 'Room' || hwModel === 'Repeater') {
const fallbackLabel =
hwModel === 'Room'
? t('repeatersPanel.savedPasswordOrphanRoomLabel', {
nodeId: nodeId.toString(16),
})
: t('repeatersPanel.savedPasswordOrphanLabel', {
nodeId: nodeId.toString(16),
});
const auth = await ensureRepeaterAuth(nodeId, node?.long_name ?? fallbackLabel, hwModel);
if (!auth.ok) {
setActionStatus(t('nodeDetailModal.remoteAuthCancelled'));
return false;
}
if (auth.saved) refreshRepeaterSecrets();
return true;
}
touch(mode);
return true;
},
[ensureRepeaterAuth, node?.long_name, refreshRepeaterSecrets, t],
);
useEffect(() => {
if (protocol !== 'meshcore' || !node) {
setContactOnRadio(null);
setRadioContactCount(null);
setContactPubkey(null);
return;
}
let cancelled = false;
const storeHex =
storeContactPublicKey?.length === 32 ? meshcorePublicKeyToHex(storeContactPublicKey) : null;
const fetchStatus = async () => {
try {
const contact = await window.electronAPI.db.getMeshcoreContactById(node.node_id);
if (!cancelled) {
if (contact && 'on_radio' in contact) {
// on_radio: 1 = on radio, 0 = only in DB, null = treat as on radio (legacy data)
setContactOnRadio(contact.on_radio !== 0);
setContactPubkey(contact.public_key ?? storeHex ?? null);
} else {
setContactOnRadio(true);
setContactPubkey(storeHex ?? null);
}
}
} catch {
// catch-no-log-ok handle gracefully - show as unknown
if (!cancelled) {
setContactOnRadio(null);
setContactPubkey(storeHex ?? null);
}
}
try {
const count = await window.electronAPI.db.getMeshcoreContactCount();
if (!cancelled) {
setRadioContactCount(count);
}
} catch {
// catch-no-log-ok handle gracefully - show as unknown
if (!cancelled) setRadioContactCount(null);
}
};
void fetchStatus();
return () => {
cancelled = true;
};
}, [protocol, node, storeContactPublicKey]);
// Align with MESHCORE_TRACE_PING_TOTAL_TIMEOUT_MS (queue + tracePath in useMeshcoreRuntime)
useEffect(() => {
if (!traceRoutePending) return;
const timer = setTimeout(
() => {
setTraceRoutePending(false);
setActionStatus(t('nodeDetailModal.traceRouteTimedOut'));
},
Math.max(MESHCORE_TRACE_PING_TOTAL_TIMEOUT_MS, TRACE_ROUTE_UI_TIMEOUT_MS),
);
return () => {
clearTimeout(timer);
};
}, [traceRoutePending, t]);
if (!node) return null;
const hexId = formatMeshtasticNodeId(node.node_id);
const awaitingNodeInfo =
protocol === 'meshtastic' && meshtasticNodeAwaitingNodeInfo(node, { isConnected });
const displayName =
protocol === 'meshcore'
? meshcoreContactDisplayName(node.node_id, node.long_name)
: node.short_name || node.long_name || hexId;
const isOurNode = node.node_id === homeNode?.node_id;
const nodeStatus = getNodeStatus(node.last_heard, nodeStaleThresholdMs, nodeOfflineThresholdMs);
const nodeStatusUi =
nodeStatus === 'online'
? {
label: t('nodeDetailModal.statusOnline'),
dotClass: 'bg-brand-green',
textClass: 'text-brand-green',
}
: nodeStatus === 'stale'
? {
label: t('nodeDetailModal.statusStale'),
dotClass: 'bg-violet-400',
textClass: 'text-violet-300',
}
: {
label: t('nodeDetailModal.statusOffline'),
dotClass: 'bg-slate-400',
textClass: 'text-slate-300',
};
const headerHardwareSubtitle =
protocol === 'meshtastic'
? meshtasticHwModelDisplay(node.hw_model)
: protocol === 'meshcore' && isOurNode && meshcoreManufacturerModel
? meshcoreManufacturerModel
: node.hw_model?.trim() || null;
const headerHopsDisplay =
protocol === 'meshcore' && meshcoreTraceResult != null
? meshcoreTracePathLenToHops(meshcoreTraceResult.pathLen)
: node.hops_away;
const handleRequestPosition = async () => {
setPositionRequestedAt(Date.now());
setActionStatus(t('nodeDetailModal.requestingPosition'));
try {
await onRequestPosition?.(node.node_id);
} catch (e) {
console.warn('[NodeDetailModal] request position failed ' + errLikeToLogString(e));
setPositionRequestedAt(null);
setActionStatus(t('nodeDetailModal.positionRequestFailed'));
}
};
const handleTraceRoute = async () => {
setTraceRoutePending(true);
setActionStatus(t('nodeDetailModal.traceRouteRequested'));
try {
await onTraceRoute?.(node.node_id);
} finally {
setTraceRoutePending(false);
}
};
const traceHardDisabled = !isConnected;
const traceBlockReason = !isConnected ? t('nodeDetailModal.connectRadioFirst') : null;
return (
<>
<div
className="fixed inset-0 flex items-center justify-center p-4"
style={{ zIndex: Z_NODE_DETAIL_MODAL }}
>
<button
type="button"
aria-label={t('aria.closeDialog')}
className="absolute inset-0 cursor-pointer border-0 bg-black/50 p-0"
onClick={onClose}
/>
<div
role="dialog"
aria-modal="true"
aria-labelledby="node-modal-title"
className="bg-deep-black relative z-10 flex max-h-[90vh] min-h-0 w-full max-w-lg flex-col overflow-hidden rounded-xl border border-gray-700 shadow-2xl"
>
{/* Header */}
<div className="flex shrink-0 items-start justify-between border-b border-gray-700 px-5 py-4">
<div className="min-w-0">
<div className="flex items-center gap-2">
<h3 id="node-modal-title" className="truncate text-lg font-semibold text-gray-100">
{displayName}
</h3>
{mqttIgnoredNodes.has(node.node_id) && (
<span className="shrink-0 rounded border border-yellow-500/30 bg-yellow-500/20 px-1.5 py-0.5 text-[10px] font-medium text-yellow-300">
{t('nodeDetailModal.mqttIgnoredBadge')}
</span>
)}
{awaitingNodeInfo && (
<span
className="shrink-0 rounded border border-blue-500/30 bg-blue-500/20 px-1.5 py-0.5 text-[10px] font-medium text-blue-300"
title={t('nodeDetailModal.nodeIncomplete')}
>
{t('nodeDetailModal.loadingBadge')}
</span>
)}
</div>
<div className="mt-0.5 flex items-center gap-2">
{protocol !== 'meshcore' && (
<span className="text-muted font-mono text-xs">{hexId}</span>
)}
{headerHopsDisplay != null && (
<span
className={`text-xs ${headerHopsDisplay === 0 ? 'text-bright-green' : 'text-gray-400'}`}
title={
protocol === 'meshcore' && meshcoreTraceResult != null
? t('nodeDetailModal.hopsFromTraceTitle')
: t('nodeDetailModal.hopsFromRoutingTitle')
}
>
{t('nodeDetailModal.hopLabel', { count: headerHopsDisplay })}
</span>
)}
{headerHardwareSubtitle != null && (
<span className="text-muted text-xs">{headerHardwareSubtitle}</span>
)}
{/* MeshCore contact status badges */}
{protocol === 'meshcore' && contactPubkey && (
<span
className="shrink-0 rounded border border-green-500/30 bg-green-500/20 px-1.5 py-0.5 text-[10px] font-medium text-green-300"
title={
isMeshcoreDmExcludedHwModel(node.hw_model)
? t('nodeDetailModal.hasPublicKeyNoDm')
: t('nodeDetailModal.hasPublicKey')
}
>
{isMeshcoreDmExcludedHwModel(node.hw_model) ? '🔑' : '🔑 DM'}
</span>
)}
{protocol === 'meshcore' &&
node.node_id >= MESHCORE_CHAT_STUB_ID_MIN &&
node.node_id <= MESHCORE_CHAT_STUB_ID_MAX && (
<span
className="shrink-0 rounded border border-blue-500/30 bg-blue-500/20 px-1.5 py-0.5 text-[10px] font-medium text-blue-300"
title={t('nodeDetailModal.chatOnlyNode')}
>
{t('nodeDetailModal.chatBadge')}
</span>
)}
{protocol === 'meshcore' && contactOnRadio === false && contactPubkey && (
<span
className="shrink-0 rounded border border-orange-500/30 bg-orange-500/20 px-1.5 py-0.5 text-[10px] font-medium text-orange-300"
title={t('nodeDetailModal.dbOnlyContact')}
>
{t('nodeDetailModal.onlyInDbBadge')}
</span>
)}
{protocol === 'meshcore' && contactOnRadio === true && contactPubkey && (
<span
className="shrink-0 rounded border border-green-500/30 bg-green-500/20 px-1.5 py-0.5 text-[10px] font-medium text-green-300"
title={t('nodeDetailModal.syncedContact')}
>
{t('nodeDetailModal.syncedBadge')}
</span>
)}
{protocol === 'meshcore' && contactOnRadio === true && !contactPubkey && (
<span
className="shrink-0 rounded border border-blue-500/30 bg-blue-500/20 px-1.5 py-0.5 text-[10px] font-medium text-blue-300"
title={t('nodeDetailModal.radioOnlyContact')}
>
{t('nodeDetailModal.onRadioBadge')}
</span>
)}
{protocol === 'meshcore' &&
radioContactCount !== null &&
typeof MESHCORE_CONTACTS_CRITICAL_THRESHOLD === 'number' &&
radioContactCount >= MESHCORE_CONTACTS_CRITICAL_THRESHOLD && (
<span
className="shrink-0 rounded border border-red-500/30 bg-red-500/20 px-1.5 py-0.5 text-[10px] font-medium text-red-300"
title={t('nodeDetailModal.radioCapacityTitle', {
current: radioContactCount,
max: MESHCORE_MAX_CONTACTS ?? 'unknown',
})}
>
⚠️ {radioContactCount}/{MESHCORE_MAX_CONTACTS ?? 'unknown'}
</span>
)}
</div>
{protocol === 'meshcore' && contactPubkey && (
<div className="mt-1 flex w-full items-start gap-2">
<span className="text-muted font-mono text-[10px] break-all whitespace-normal">
{contactPubkey}
</span>
<button
type="button"
aria-label={t('nodeDetailModal.copyPublicKey')}
title={t('nodeDetailModal.copyPublicKey')}
onClick={() => {
void writeClipboardText(contactPubkey)
.then(() => {
setActionStatus(t('nodeDetailModal.publicKeyCopied'));
})
.catch((e: unknown) => {
console.warn(
'[NodeDetailModal] copy pubkey failed ' + errLikeToLogString(e),
);
});
}}
className="shrink-0 text-xs text-gray-400 hover:text-gray-200"
>
📋
</button>
</div>
)}
</div>
<div className="ml-3 flex shrink-0 flex-col items-end gap-1">
<div className="flex items-center gap-1">
<WatchToggleButton nodeId={node.node_id} />
<NodeBlockButton
protocol={protocol}
node={node}
publicKeyHex={
storeContactPublicKey
? meshcorePublicKeyToHex(storeContactPublicKey)
: node.public_key_hex
}
/>
<button
type="button"
onClick={() => {
onToggleFavorite(node.node_id, !node.favorited);
}}
className="hover:bg-secondary-dark shrink-0 rounded-lg p-1.5 transition-colors"
aria-label={
node.favorited
? t('nodeDetailModal.removeFromFavorites')
: t('nodeDetailModal.addToFavorites')
}
aria-pressed={node.favorited}
>
<span
className={`text-xl ${node.favorited ? 'text-yellow-400' : 'text-gray-500 hover:text-yellow-400'}`}
aria-hidden="true"
>
{node.favorited ? '★' : '☆'}
</span>
</button>
<button
type="button"
ref={closeButtonRef}
onClick={onClose}
aria-label={t('aria.closeDialog')}
{...{ [PARENT_HOVER_ATTR]: '' }}
className="hover:bg-secondary-dark text-muted shrink-0 rounded-lg p-1.5 transition-colors hover:text-gray-200"
>
<X aria-hidden className="h-5 w-5" trigger={parentIconTrigger} size={20} />
</button>
</div>
<span
className={`flex items-center gap-1 text-[11px] font-medium ${nodeStatusUi.textClass}`}
title={t('nodeDetailModal.currentNodeStatus')}
>
<span className={`inline-block h-2 w-2 rounded-full ${nodeStatusUi.dotClass}`} />
{nodeStatusUi.label}
</span>
</div>
</div>
{/* Body + footer actions — single scroll region so remote admin and controls stay reachable */}
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
<div className="px-5 py-3">
<NodeInfoBody
node={node}
homeNode={homeNode}
traceRouteHops={isOurNode ? undefined : traceRouteHops}
nodes={nodes}
useFahrenheit={useFahrenheit}
protocol={protocol}
meshcoreManufacturerModel={meshcoreManufacturerModel}
positionHistory={positionHistory}
onShowOnMap={onShowOnMap}
awaitingNodeInfo={awaitingNodeInfo}
mqttConnected={mqttConnected}
radioConnected={radioConnected}
/>
{protocol === 'meshcore' && !isOurNode && node.hw_model === 'Repeater' && (
<MeshcoreRepeaterPasswordControls
nodeId={node.node_id}
nodeName={node.long_name}
secretsEpoch={repeaterSecretsEpoch}
onPromptPassword={promptRepeaterPassword}
onSecretsChanged={refreshRepeaterSecrets}
onStatusMessage={setActionStatus}
/>
)}
{protocol === 'meshcore' &&
!isOurNode &&
(node.hw_model === 'Repeater' || node.hw_model === 'Room') &&
meshcoreNeighborError &&
!showMeshcoreNeighbors && (
<div className="mt-3 rounded-lg border border-red-800/60 bg-red-950/40 px-3 py-2 text-xs text-red-300">
{translateMeshcoreUserMessage(t, meshcoreNeighborError)}
</div>
)}
{/* MeshCore: trace error */}
{protocol === 'meshcore' && !isOurNode && meshcorePingError && (
<div className="mt-3 rounded-lg border border-red-800/60 bg-red-950/40 px-3 py-2 text-xs text-red-300">
{translateMeshcoreUserMessage(t, meshcorePingError)}
</div>
)}
{protocol === 'meshcore' &&
!isOurNode &&
meshcoreStatusError &&
!showRepeaterStats && (
<div className="mt-3 rounded-lg border border-red-800/60 bg-red-950/40 px-3 py-2 text-xs text-red-300">
{translateMeshcoreUserMessage(t, meshcoreStatusError)}
</div>
)}
{protocol === 'meshcore' &&
!isOurNode &&
meshcoreTelemetryError &&
!showTelemetry && (
<div className="mt-3 rounded-lg border border-red-800/60 bg-red-950/40 px-3 py-2 text-xs text-red-300">
{translateMeshcoreUserMessage(t, meshcoreTelemetryError)}
</div>
)}
{/* MeshCore: live outbound route (no trace required) */}
{protocol === 'meshcore' &&
!isOurNode &&
currentRoute &&
!traceMatchesCurrentRoute && (
<div className="mt-3 space-y-1">
<h4 className="text-muted text-xs font-medium tracking-wide uppercase">
{t('nodeDetailModal.currentRouteHeading')}
</h4>
<div className="bg-secondary-dark rounded p-2">
<MeshcoreRouteChain
segments={currentRouteSegments}
destLabel={node.long_name}
/>
</div>
</div>
)}
{/* MeshCore: trace path result */}
{protocol === 'meshcore' && !isOurNode && meshcoreTraceResult && (
<div className="mt-3 space-y-1">
<h4 className="text-muted text-xs font-medium tracking-wide uppercase">
{t('nodeDetailModal.pathTraceHeading')}
</h4>
<div className="text-xs text-gray-400">
{t('nodeDetailModal.hopsLabel')}{' '}
<span className="font-mono text-gray-200">
{meshcoreTracePathLenToHops(meshcoreTraceResult.pathLen)}
</span>
</div>
<div className="bg-secondary-dark space-y-1 rounded p-2">
{traceHopRows.map((hop, i) => (
<div key={i} className="flex items-center gap-2 text-xs">
<span
className="text-muted max-w-[10rem] min-w-10 truncate"
title={meshcoreHopSegmentTooltip(t, hop)}
>
{hop.label
? t('nodeDetailModal.hopNameLabel', { name: hop.label })
: t('nodeDetailModal.hopNLabel', { n: i + 1 })}
</span>
<SnrIndicator snr={hop.snr} />
</div>
))}
<div className="flex items-center gap-2 border-t border-gray-700 pt-1 text-xs">
<span
className="text-muted max-w-[10rem] min-w-10 truncate"
title={node.long_name}
>
{node.long_name || t('nodeDetailModal.destLabel')}
</span>
<SnrIndicator snr={meshcoreTraceResult.lastSnr} />
</div>
</div>
{traceMatchesCurrentRoute && currentRouteSegments.length > 0 ? (
<div className="pt-1">
<MeshcoreRouteChain
segments={currentRouteSegments}
destLabel={node.long_name}
/>
</div>
) : null}
</div>
)}
{/* MeshCore: telemetry */}
{protocol === 'meshcore' && !isOurNode && meshcoreNodeTelemetry && showTelemetry && (
<div className="mt-3 space-y-1">
<div className="flex items-center justify-between">
<h4 className="text-muted text-xs font-medium tracking-wide uppercase">
{t('nodeDetailModal.sensorTelemetryHeading')}
</h4>
<div className="flex items-center gap-2">
<span className="text-muted text-xs">
{formatDisplayTime(meshcoreNodeTelemetry.fetchedAt, {
use24Hour: use24HourTime,
})}
</span>
<button
type="button"
onClick={() => {
setShowTelemetry(false);
}}
className="text-muted text-xs hover:text-gray-300"
>
{t('common.hide')}