-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstore.ts
More file actions
2195 lines (1980 loc) · 93.7 KB
/
store.ts
File metadata and controls
2195 lines (1980 loc) · 93.7 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 { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { toast } from 'react-toastify';
import type {
SovdEntity,
SovdEntityDetails,
EntityTreeNode,
ComponentTopic,
TopicNodeData,
Parameter,
Operation,
Execution,
CreateExecutionRequest,
CreateExecutionResponse,
Fault,
App,
VersionInfo,
SovdFunction,
} from './types';
import { createMedkitClient, normalizeBaseUrl, type MedkitClient } from '@selfpatch/ros2-medkit-client-ts';
import type { SovdResourceEntityType } from './types';
import {
transformFaultsResponse,
transformOperationsResponse,
transformDataResponse,
transformConfigurationsResponse,
transformFault,
unwrapItems,
} from './transforms';
import {
getEntityDetail,
getEntityConfigurations,
getEntityOperations,
getEntityData,
getEntityDataItem,
getEntityFaults,
getEntityFaultDetail,
getEntityExecution,
postEntityExecution,
deleteEntityExecution,
deleteEntityFault,
putEntityConfiguration,
putEntityDataItem,
deleteEntityConfiguration,
deleteEntityConfigurations,
getEntityBulkData,
getEntityLogs,
getEntityLogsConfiguration,
putEntityLogsConfiguration,
} from './api-dispatch';
import type { LogCollection, LogsConfiguration, LogsFetchResult, LogsQueryParams } from './log-types';
const STORAGE_KEY = 'ros2_medkit_web_ui_server_url';
const EXECUTION_POLL_INTERVAL_MS = 1000;
const EXECUTION_CLEANUP_AFTER_MS = 5 * 60 * 1000; // 5 minutes
export type TreeViewMode = 'logical' | 'functional';
/**
* Extended Execution with metadata needed for polling
*/
export interface TrackedExecution extends Execution {
/** Entity ID for API calls */
entityId: string;
/** Operation name for API calls */
operationName: string;
/** Entity type for API calls */
entityType: SovdResourceEntityType;
/** Timestamp when execution reached terminal state (for cleanup) */
completedAt?: number;
}
export interface AppState {
// Connection state
serverUrl: string | null;
isConnected: boolean;
isConnecting: boolean;
connectionError: string | null;
client: MedkitClient | null;
// Entity tree state
treeViewMode: TreeViewMode;
rootEntities: EntityTreeNode[];
loadingPaths: string[];
expandedPaths: string[];
// Selection state
selectedPath: string | null;
selectedEntity: SovdEntityDetails | null;
isLoadingDetails: boolean;
isRefreshing: boolean;
// Configurations state (ROS 2 Parameters)
configurations: Map<string, Parameter[]>; // entityId -> parameters
isLoadingConfigurations: boolean;
// Operations state (ROS 2 Services & Actions)
operations: Map<string, Operation[]>; // entityId -> operations
isLoadingOperations: boolean;
// Active executions (for monitoring async actions) - SOVD Execution Model
activeExecutions: Map<string, TrackedExecution>; // executionId -> tracked execution with metadata
autoRefreshExecutions: boolean; // flag for auto-refresh polling
executionPollingIntervalId: ReturnType<typeof setInterval> | null; // polling interval ID
// Faults state (diagnostic trouble codes)
faults: Fault[];
isLoadingFaults: boolean;
faultStreamCleanup: (() => void) | null;
// Actions
connect: (url: string) => Promise<boolean>;
disconnect: () => void;
setTreeViewMode: (mode: TreeViewMode) => Promise<void>;
loadRootEntities: () => Promise<void>;
loadChildren: (path: string) => Promise<void>;
toggleExpanded: (path: string) => void;
selectEntity: (path: string) => Promise<void>;
refreshSelectedEntity: () => Promise<void>;
clearSelection: () => void;
// Configurations actions
fetchConfigurations: (entityId: string, entityType?: SovdResourceEntityType, signal?: AbortSignal) => Promise<void>;
setParameter: (
entityId: string,
paramName: string,
value: unknown,
entityType?: SovdResourceEntityType
) => Promise<boolean>;
resetParameter: (entityId: string, paramName: string, entityType?: SovdResourceEntityType) => Promise<boolean>;
resetAllConfigurations: (
entityId: string,
entityType?: SovdResourceEntityType
) => Promise<{ reset_count: number; failed_count: number }>;
// Operations actions - updated for SOVD Execution model
fetchOperations: (entityId: string, entityType?: SovdResourceEntityType) => Promise<void>;
createExecution: (
entityId: string,
operationName: string,
request: CreateExecutionRequest,
entityType?: SovdResourceEntityType
) => Promise<CreateExecutionResponse | null>;
refreshExecutionStatus: (
entityId: string,
operationName: string,
executionId: string,
entityType?: SovdResourceEntityType
) => Promise<void>;
cancelExecution: (
entityId: string,
operationName: string,
executionId: string,
entityType?: SovdResourceEntityType
) => Promise<boolean>;
setAutoRefreshExecutions: (enabled: boolean) => void;
startExecutionPolling: () => void;
stopExecutionPolling: () => void;
// Faults actions
fetchFaults: () => Promise<void>;
clearFault: (entityType: SovdResourceEntityType, entityId: string, faultCode: string) => Promise<boolean>;
subscribeFaultStream: () => void;
unsubscribeFaultStream: () => void;
// Component-facing actions (replace direct client usage in components)
fetchEntityData: (
entityType: SovdResourceEntityType,
entityId: string,
signal?: AbortSignal
) => Promise<ComponentTopic[]>;
fetchEntityOperations: (
entityType: SovdResourceEntityType,
entityId: string,
signal?: AbortSignal
) => Promise<Operation[]>;
listEntityFaults: (
entityType: SovdResourceEntityType,
entityId: string,
signal?: AbortSignal
) => Promise<{ items: Fault[]; count: number }>;
fetchEntityLogs: (
entityType: SovdResourceEntityType,
entityId: string,
params: LogsQueryParams,
signal?: AbortSignal
) => Promise<LogsFetchResult>;
getLogsConfiguration: (entityType: SovdResourceEntityType, entityId: string) => Promise<LogsConfiguration | null>;
updateLogsConfiguration: (
entityType: SovdResourceEntityType,
entityId: string,
config: LogsConfiguration
) => Promise<boolean>;
getFaultWithEnvironmentData: (
entityType: SovdResourceEntityType,
entityId: string,
faultCode: string
) => Promise<unknown>;
publishToEntityData: (
entityType: SovdResourceEntityType,
entityId: string,
dataId: string,
request: { value: unknown }
) => Promise<void>;
getServerCapabilities: () => Promise<unknown>;
getVersionInfoAction: () => Promise<VersionInfo | null>;
downloadBulkData: (
entityType: SovdResourceEntityType,
entityId: string,
category: string,
fileId: string
) => Promise<{ blob: Blob; filename: string } | null>;
getFunctionHosts: (functionId: string) => Promise<unknown[]>;
prefetchResourceCounts: (
entityType: SovdResourceEntityType,
entityId: string
) => Promise<{ data: number; operations: number; configurations: number; faults: number }>;
}
/**
* Convert SovdEntity to EntityTreeNode
*
* Structure - flat hierarchy with type tags:
* - Area: subareas and components loaded as direct children on expand
* - Subarea: same as Area
* - Component: subcomponents and apps loaded as direct children on expand
* - Subcomponent: same as Component
* - App: leaf node (no children in tree)
*
* Resources (data, operations, configurations, faults) are shown in the detail panel,
* not as tree nodes.
*/
export function toTreeNode(entity: SovdEntity, parentPath: string = ''): EntityTreeNode {
const path = parentPath ? `${parentPath}/${entity.id}` : `/${entity.id}`;
const entityType = entity.type.toLowerCase();
// Determine hasChildren based on explicit metadata or type heuristic
// Note: hasChildren controls whether expand button is shown
// children: undefined means "not loaded yet" (lazy loading on expand)
let hasChildren: boolean;
const entityAny = entity as unknown as Record<string, unknown>;
if (Object.prototype.hasOwnProperty.call(entityAny, 'hasChildren') && typeof entityAny.hasChildren === 'boolean') {
// Explicit hasChildren metadata from API - use as-is
hasChildren = entityAny.hasChildren as boolean;
} else if (Array.isArray(entityAny.children)) {
// Children array provided - check if non-empty
hasChildren = (entityAny.children as unknown[]).length > 0;
} else {
// No explicit metadata - use type-based heuristic:
// Areas and components typically have children (components, apps, subareas)
// Apps are leaf nodes - their resources shown in detail panel, not tree
hasChildren = entityType !== 'app';
}
return {
...entity,
path,
children: undefined, // Children always loaded lazily on expand
isLoading: false,
isExpanded: false,
hasChildren, // Controls whether expand button is shown
};
}
/**
* Recursively update a node in the tree
*/
export function updateNodeInTree(
nodes: EntityTreeNode[],
targetPath: string,
updater: (node: EntityTreeNode) => EntityTreeNode
): EntityTreeNode[] {
return nodes.map((node) => {
if (node.path === targetPath) {
return updater(node);
}
if (node.children && targetPath.startsWith(node.path)) {
return {
...node,
children: updateNodeInTree(node.children, targetPath, updater),
};
}
return node;
});
}
/**
* Find a node in the tree by path
*/
export function findNode(nodes: EntityTreeNode[], path: string): EntityTreeNode | null {
for (const node of nodes) {
if (node.path === path) {
return node;
}
if (node.children) {
const found = findNode(node.children, path);
if (found) return found;
}
}
return null;
}
// =============================================================================
// Entity Selection Handlers
// =============================================================================
/** Result from an entity selection handler */
interface SelectionResult {
selectedPath: string;
selectedEntity: SovdEntityDetails;
expandedPaths?: string[];
rootEntities?: EntityTreeNode[];
isLoadingDetails: boolean;
}
/** Context passed to entity selection handlers */
interface SelectionContext {
node: EntityTreeNode;
path: string;
expandedPaths: string[];
rootEntities: EntityTreeNode[];
}
/**
* Handle topic node selection
* Distinguished between TopicNodeData (partial) and ComponentTopic (full)
*/
async function handleTopicSelection(ctx: SelectionContext, client: MedkitClient): Promise<SelectionResult | null> {
const { node, path, rootEntities } = ctx;
if (node.type !== 'topic' || !node.data) return null;
const data = node.data as TopicNodeData | ComponentTopic;
const isTopicNodeData = 'isPublisher' in data && 'isSubscriber' in data && !('type' in data);
if (isTopicNodeData) {
// TopicNodeData - need to fetch full topic details from the parent entity
const { isPublisher, isSubscriber } = data as TopicNodeData;
const topicName = node.id;
// Find parent entity by walking up the tree path
const parentPath = path.split('/').slice(0, -1).join('/');
const parentNode = findNode(rootEntities, parentPath);
const parentType = parentNode?.type || 'component';
const entityType = `${parentType}s` as SovdResourceEntityType;
const entityId = parentNode?.id || '';
// Fetch the specific data item and transform to ComponentTopic
const { data: topicDetail } = await getEntityDataItem(client, entityType, entityId, topicName);
const transformed = topicDetail ? transformDataResponse({ items: [topicDetail] }) : [];
const topicData = transformed[0] || null;
if (topicData) {
// Update tree with full data merged with direction info
const updatedTree = updateNodeInTree(rootEntities, path, (n) => ({
...n,
data: { ...topicData, isPublisher, isSubscriber },
}));
return {
selectedPath: path,
selectedEntity: {
id: node.id,
name: node.name,
href: node.href,
topicData: { ...topicData, isPublisher, isSubscriber },
rosType: topicData.type,
type: 'topic',
},
rootEntities: updatedTree,
isLoadingDetails: false,
};
}
// Fallback if topic fetch fails
return {
selectedPath: path,
selectedEntity: {
id: node.id,
name: node.name,
type: 'topic',
href: node.href,
error: 'Failed to load topic details',
},
isLoadingDetails: false,
};
}
// Full ComponentTopic data available
const topicData = data as ComponentTopic;
return {
selectedPath: path,
selectedEntity: {
id: node.id,
name: node.name,
href: node.href,
topicData,
rosType: topicData.type,
type: 'topic',
},
isLoadingDetails: false,
};
}
/** Handle server node selection */
function handleServerSelection(ctx: SelectionContext): SelectionResult | null {
const { node, path, expandedPaths } = ctx;
if (node.type !== 'server') return null;
const serverData = node.data as {
versionInfo?: VersionInfo;
serverVersion?: string;
sovdVersion?: string;
serverUrl?: string;
};
return {
selectedPath: path,
expandedPaths: expandedPaths.includes(path) ? expandedPaths : [...expandedPaths, path],
selectedEntity: {
id: node.id,
name: node.name,
type: 'server',
href: node.href,
versionInfo: serverData?.versionInfo,
serverVersion: serverData?.serverVersion,
sovdVersion: serverData?.sovdVersion,
serverUrl: serverData?.serverUrl,
},
isLoadingDetails: false,
};
}
/** Handle component/subcomponent node selection */
function handleComponentSelection(ctx: SelectionContext): SelectionResult | null {
const { node, path, expandedPaths } = ctx;
if (node.type !== 'component' && node.type !== 'subcomponent') return null;
return {
selectedPath: path,
expandedPaths: expandedPaths.includes(path) ? expandedPaths : [...expandedPaths, path],
selectedEntity: {
id: node.id,
name: node.name,
type: node.type,
href: node.href,
topicsInfo: node.topicsInfo,
},
isLoadingDetails: false,
};
}
/** Handle area/subarea node selection */
function handleAreaSelection(ctx: SelectionContext): SelectionResult | null {
const { node, path, expandedPaths } = ctx;
if (node.type !== 'area' && node.type !== 'subarea') return null;
return {
selectedPath: path,
expandedPaths: expandedPaths.includes(path) ? expandedPaths : [...expandedPaths, path],
selectedEntity: {
id: node.id,
name: node.name,
type: node.type,
href: node.href,
},
isLoadingDetails: false,
};
}
/** Handle function node selection */
function handleFunctionSelection(ctx: SelectionContext): SelectionResult | null {
const { node, path, expandedPaths } = ctx;
if (node.type !== 'function') return null;
const functionData = node.data as SovdFunction | undefined;
return {
selectedPath: path,
expandedPaths: expandedPaths.includes(path) ? expandedPaths : [...expandedPaths, path],
selectedEntity: {
id: node.id,
name: node.name,
type: 'function',
href: node.href,
description: functionData?.description,
},
isLoadingDetails: false,
};
}
/** Handle app node selection */
function handleAppSelection(ctx: SelectionContext): SelectionResult | null {
const { node, path, expandedPaths } = ctx;
if (node.type !== 'app') return null;
const appData = node.data as App | undefined;
return {
selectedPath: path,
expandedPaths: expandedPaths.includes(path) ? expandedPaths : [...expandedPaths, path],
selectedEntity: {
id: node.id,
name: node.name,
type: 'app',
href: node.href,
fqn: appData?.fqn || node.name,
node_name: appData?.node_name,
namespace: appData?.namespace,
component_id: appData?.component_id,
},
isLoadingDetails: false,
};
}
/** Handle fault node selection */
function handleFaultSelection(ctx: SelectionContext): SelectionResult | null {
const { node, path } = ctx;
if (node.type !== 'fault' || !node.data) return null;
const fault = node.data as Fault;
const pathSegments = path.split('/').filter(Boolean);
const entityId = pathSegments.length >= 2 ? pathSegments[pathSegments.length - 3] : '';
return {
selectedPath: path,
selectedEntity: {
id: node.id,
name: fault.message,
type: 'fault',
href: node.href,
data: fault,
entityId,
},
isLoadingDetails: false,
};
}
/** Handle parameter node selection */
function handleParameterSelection(ctx: SelectionContext): SelectionResult | null {
const { node, path } = ctx;
if (node.type !== 'parameter' || !node.data) return null;
const pathSegments = path.split('/').filter(Boolean);
const componentId = (pathSegments.length >= 2 ? pathSegments[1] : pathSegments[0]) ?? '';
return {
selectedPath: path,
selectedEntity: {
id: node.id,
name: node.name,
type: 'parameter',
href: node.href,
data: node.data,
componentId,
},
isLoadingDetails: false,
};
}
/** Handle service/action node selection */
function handleOperationSelection(ctx: SelectionContext): SelectionResult | null {
const { node, path } = ctx;
if ((node.type !== 'service' && node.type !== 'action') || !node.data) return null;
const pathSegments = path.split('/').filter(Boolean);
const opsIndex = pathSegments.indexOf('operations');
const componentId = opsIndex > 0 ? pathSegments[opsIndex - 1] : (pathSegments[0] ?? '');
return {
selectedPath: path,
selectedEntity: {
id: node.id,
name: node.name,
type: node.type,
href: node.href,
data: node.data,
componentId,
},
isLoadingDetails: false,
};
}
/**
* Infer entity type from tree path depth.
* Tree paths: /server/<areaId> (depth 1), /server/<areaId>/<componentId> (depth 2),
* /server/<areaId>/<componentId>/<appId> (depth 3)
*/
export function inferEntityTypeFromDepth(depth: number): SovdResourceEntityType {
if (depth <= 1) return 'areas';
if (depth === 2) return 'components';
return 'apps';
}
/**
* Parse a tree path to find the parent entity and any resource segment.
* Tree paths: /server/<areaId>/<componentId>/<appId>/data/<topicName>
* Returns: { entityType, entityId, resource?, resourceId? }
*/
export function parseTreePath(path: string): {
entityType: SovdResourceEntityType;
entityId: string;
resource?: 'data' | 'operations' | 'configurations' | 'faults';
resourceId?: string;
} {
const apiPath = path.replace(/^\/server/, '');
const segments = apiPath.split('/').filter(Boolean);
// Check for resource segments: .../data/<id>, .../operations/<id>, etc.
const resourceTypes = ['data', 'operations', 'configurations', 'faults'] as const;
for (const res of resourceTypes) {
const resIndex = segments.indexOf(res);
if (resIndex > 0) {
// Entity is the segment before the resource
const entityId = segments[resIndex - 1] || '';
const entityType = inferEntityTypeFromDepth(resIndex);
const resourceId = segments[resIndex + 1] ? decodeURIComponent(segments[resIndex + 1]!) : undefined;
return { entityType, entityId, resource: res, resourceId };
}
}
// No resource segment - it's an entity path
const entityId = segments[segments.length - 1] || '';
const entityType = inferEntityTypeFromDepth(segments.length);
return { entityType, entityId };
}
/**
* Filter apps that belong to a given component by checking
* the top-level `component_id` field, `x-medkit.component_id`,
* or `_links.is-located-on`.
*
* Used as a fallback when `/components/{id}/hosts` returns empty
* (peer-sourced components).
*/
export function filterAppsByComponent(apps: Record<string, unknown>[], componentId: string): Record<string, unknown>[] {
return apps.filter((app) => {
if (app['component_id'] === componentId) return true;
const xMedkit = app['x-medkit'] as Record<string, unknown> | undefined;
if (xMedkit?.component_id === componentId) return true;
const links = app['_links'] as Record<string, string> | undefined;
return links?.['is-located-on']?.endsWith(`/components/${componentId}`);
});
}
/**
* Detect whether a component node is peer-sourced (aggregated from a
* remote gateway). Peer-sourced components have `x-medkit.source`
* starting with `"peer:"`.
*
* Components with unknown source metadata are treated as peer-sourced
* so the fallback still discovers their apps; this errs on the side of
* completeness over saving one extra request.
*/
export function isPeerSourcedComponent(node: Record<string, unknown>): boolean {
const xMedkit = node['x-medkit'] as Record<string, unknown> | undefined;
const source = xMedkit?.source;
if (typeof source !== 'string') return true;
return source.startsWith('peer:');
}
/**
* Module-level dedupe for `GET /apps`. When multiple peer-sourced
* components are expanded concurrently, each needs the full apps list
* for its fallback; without dedupe that would trigger N identical
* requests. Holding the in-flight promise here collapses them into one.
*
* The promise is cleared on settlement so subsequent expansions refetch
* fresh data (no stale caching across time).
*/
let inFlightAppsRequest: Promise<Record<string, unknown>[]> | null = null;
/** Reset the dedupe cache. Exposed for tests. */
export function __resetAppsRequestCache(): void {
inFlightAppsRequest = null;
}
export async function fetchAllAppsDeduped(client: MedkitClient): Promise<Record<string, unknown>[]> {
if (inFlightAppsRequest) return inFlightAppsRequest;
inFlightAppsRequest = client
.GET('/apps')
.then((res) => (res.data ? unwrapItems<Record<string, unknown>>(res.data) : []))
.catch(() => [] as Record<string, unknown>[])
.finally(() => {
inFlightAppsRequest = null;
});
return inFlightAppsRequest;
}
/** Fallback: fetch entity details from API when not in tree */
async function fetchEntityFromApi(
path: string,
client: MedkitClient,
set: (state: Partial<AppState>) => void
): Promise<void> {
set({ selectedPath: path, isLoadingDetails: true, selectedEntity: null });
try {
const parsed = parseTreePath(path);
if (parsed.resource === 'data' && parsed.resourceId) {
// Topic detail: fetch specific data item and transform it
const { data: rawItem } = await getEntityDataItem(
client,
parsed.entityType,
parsed.entityId,
parsed.resourceId
);
// Transform raw API response to ComponentTopic (same as list transform but for single item)
const transformed = rawItem ? transformDataResponse({ items: [rawItem] }) : [];
const topicData = transformed[0] || null;
set({
selectedEntity: {
id: parsed.resourceId,
name: topicData?.topic || parsed.resourceId,
href: path,
topicData: topicData || undefined,
rosType: topicData?.type,
type: 'topic',
},
isLoadingDetails: false,
});
return;
}
if (parsed.resource === 'operations' && parsed.resourceId) {
// Operation detail
set({
selectedEntity: {
id: parsed.resourceId,
name: parsed.resourceId,
type: 'service',
href: path,
componentId: parsed.entityId,
entityType: parsed.entityType,
},
isLoadingDetails: false,
});
return;
}
// Entity detail
const { data } = await getEntityDetail(client, parsed.entityType, parsed.entityId);
const details = (data || {
id: parsed.entityId,
name: parsed.entityId,
type: parsed.entityType.slice(0, -1),
href: path,
}) as SovdEntityDetails;
set({ selectedEntity: details, isLoadingDetails: false });
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
console.error('[fetchEntityFromApi] Error:', message, { path });
const parsed = parseTreePath(path);
set({
selectedEntity: {
id: parsed.entityId,
name: parsed.entityId,
type: parsed.entityType.slice(0, -1),
href: path,
error: 'Failed to load details',
},
isLoadingDetails: false,
});
}
}
export const useAppStore = create<AppState>()(
persist(
(set, get) => ({
// Initial state
serverUrl: null,
isConnected: false,
isConnecting: false,
connectionError: null,
client: null,
treeViewMode: 'logical',
rootEntities: [],
loadingPaths: [],
expandedPaths: [],
// Selection state
selectedPath: null,
selectedEntity: null,
isLoadingDetails: false,
isRefreshing: false,
// Configurations state
configurations: new Map(),
isLoadingConfigurations: false,
// Operations state
operations: new Map(),
isLoadingOperations: false,
// Active executions state - SOVD Execution model
activeExecutions: new Map(),
autoRefreshExecutions: true,
executionPollingIntervalId: null,
// Faults state
faults: [],
isLoadingFaults: false,
faultStreamCleanup: null,
// Connect to ros2_medkit gateway
connect: async (url: string) => {
set({ isConnecting: true, connectionError: null });
try {
const client = createMedkitClient({ baseUrl: url, fetch: fetch.bind(globalThis) });
// Health check with 5s timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
const { error: healthError } = await client
.GET('/health', {
signal: controller.signal,
})
.finally(() => clearTimeout(timeoutId));
if (healthError) {
set({
isConnecting: false,
connectionError: 'Unable to connect to server. Check the URL and try again.',
});
return false;
}
set({
serverUrl: url,
isConnected: true,
isConnecting: false,
connectionError: null,
client,
});
// Load root entities after successful connection
await get().loadRootEntities();
// Subscribe to fault stream for real-time toast notifications
get().subscribeFaultStream();
return true;
} catch (error) {
const isTimeout = error instanceof DOMException && error.name === 'AbortError';
const message = isTimeout
? 'Connection timed out. Check the URL and ensure the gateway is running.'
: error instanceof Error
? error.message
: 'Connection failed';
console.error('[store] connect failed:', error);
set({
isConnecting: false,
connectionError: message,
});
return false;
}
},
// Disconnect from server
disconnect: () => {
// Stop execution polling
get().stopExecutionPolling();
// Unsubscribe from fault stream
get().unsubscribeFaultStream();
set({
serverUrl: null,
isConnected: false,
isConnecting: false,
connectionError: null,
client: null,
rootEntities: [],
loadingPaths: [],
expandedPaths: [],
selectedPath: null,
selectedEntity: null,
activeExecutions: new Map(),
});
},
// Set tree view mode (logical vs functional) and reload entities
setTreeViewMode: async (mode: TreeViewMode) => {
set({ treeViewMode: mode, rootEntities: [], expandedPaths: [] });
await get().loadRootEntities();
},
// Load root entities - creates a server node as root
// In logical mode: Areas -> Components -> Apps
// In functional mode: Functions -> Apps (hosts)
loadRootEntities: async () => {
const { client, serverUrl, treeViewMode } = get();
if (!client) return;
try {
// Fetch version info - critical for server identification and feature detection
const versionInfo = await client
.GET('/version-info')
.then(({ data }) => data ?? null)
.catch((error: unknown) => {
const message = error instanceof Error ? error.message : 'Unknown error';
toast.warn(
`Failed to fetch server version info: ${message}. ` +
'Server will be shown with generic name and version info may be incomplete.'
);
return null as VersionInfo | null;
});
// Extract server info from version-info response (fallback to generic values if unavailable)
const sovdInfo = versionInfo?.items?.[0];
const serverName = sovdInfo?.vendor_info?.name || 'ros2_medkit Gateway';
const serverVersion = sovdInfo?.vendor_info?.version || '';
const sovdVersion = sovdInfo?.version || '';
let children: EntityTreeNode[] = [];
if (treeViewMode === 'functional') {
// Functional view: Functions -> Apps (hosts)
const functionsRes = await client.GET('/functions').catch(() => null);
const functions = (
functionsRes?.data ? unwrapItems<SovdFunction>(functionsRes.data) : []
) as SovdFunction[];
children = functions.map((fn: SovdFunction) => {
// Validate function data quality
if (!fn.id || (typeof fn.id !== 'string' && typeof fn.id !== 'number')) {
console.warn('[Store] Malformed function data - missing or invalid id:', fn);
}
if (!fn.name && !fn.id) {
console.warn('[Store] Malformed function data - missing both name and id:', fn);
}
const fnName = typeof fn.name === 'string' ? fn.name : fn.id || 'Unknown';
const fnId = typeof fn.id === 'string' ? fn.id : String(fn.id);
return {
id: fnId,
name: fnName,
type: 'function',
href: fn.href || '',
path: `/server/${fnId}`,
children: undefined,
isLoading: false,
isExpanded: false,
// Functions always potentially have hosts - load on expand
hasChildren: true,
data: fn,
};
});
} else {
// Logical view: Areas -> Components -> Apps
// Areas are optional - if none exist, fall back to components
const areasRes = await client.GET('/areas');
const rawAreas = areasRes.data ? unwrapItems<Record<string, unknown>>(areasRes.data) : [];
if (rawAreas.length > 0) {
const entities = rawAreas.map((e) => ({ ...e, type: 'area' }) as unknown as SovdEntity);
children = entities.map((e: SovdEntity) => toTreeNode(e, '/server'));
} else {
// No areas - load components directly under server
const compsRes = await client.GET('/components');
const rawComps = compsRes.data ? unwrapItems<Record<string, unknown>>(compsRes.data) : [];
const entities = rawComps.map(
(e) => ({ ...e, type: 'component' }) as unknown as SovdEntity
);
children = entities.map((e: SovdEntity) => toTreeNode(e, '/server'));
}
}
// Create server root node
const serverNode: EntityTreeNode = {
id: 'server',
name: serverName,
type: 'server',
href: serverUrl || '',
path: '/server',
hasChildren: children.length > 0,
isLoading: false,
isExpanded: false,
children,
data: {
versionInfo,
serverVersion,
sovdVersion,
serverUrl,
treeViewMode,
},
};
set({ rootEntities: [serverNode], expandedPaths: ['/server'] });
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
console.error('[store]', error);
toast.error(`Failed to load entities: ${message}`);
}
},
// Load children for a specific node
loadChildren: async (path: string) => {
const { client, loadingPaths, rootEntities, isLoadingDetails } = get();
if (!client || loadingPaths.includes(path)) return;