-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglimpse-cache-client.js
More file actions
3149 lines (2755 loc) · 110 KB
/
glimpse-cache-client.js
File metadata and controls
3149 lines (2755 loc) · 110 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
/**
* Workflowy GLIMPSE Cache - Standalone WebSocket Client
*
* Injected directly into Workflowy desktop app (Electron).
* No Chrome extension APIs - pure WebSocket + DOM extraction.
*/
(function() {
'use strict';
// @beacon[
// id=glimpse-loading@standalone-client-config,
// role=standalone client websocket/config defaults,
// slice_labels=nexus--glimpse-extension,nexus--config,nexus-loading-flow,
// kind=span,
// show_span=true,
// comment=Standalone Electron client bootstrap constants: version log, websocket endpoint, reconnect timing, and feature flags,
// ]
const GLIMPSE_VERSION = '3.14.0';
console.log(`[GLIMPSE Cache v${GLIMPSE_VERSION}] Standalone client initializing...`);
let ws = null;
let reconnectInterval = null;
let isConnecting = false;
const WS_URL = 'ws://localhost:8765';
const RECONNECT_DELAY = 3000; // 3 seconds
const F12_POPUP_ENABLED = true;
const F12_BULK_VISIBLE_APPLY_ENABLED = true;
// @beacon-close[
// id=glimpse-loading@standalone-client-config,
// ]
// ------------------------------------------------------------
// 🔎 NEXUS-ROOT EXPANSION HELPERS (#nexus-- tags)
// ------------------------------------------------------------
// REMOVED: Obsolete expandSubtreeSafeById with isExpanded guard.
// The working version (below) unconditionally calls WF.expandItem(item)
// to handle tag-filtered views where isExpanded=true but children are
// only partially visible.
// Extract Workflowy UUID from a DOM node representing a bullet row
function extractItemIdFromDomNode(node) {
if (!node) return null;
const id = node.getAttribute('projectid');
if (id) return id;
// Fallback: in case of short IDs, try WF.shortIdToId
const shortId = node.getAttribute('data-projectid');
if (shortId && WF.shortIdToId) {
try {
return WF.shortIdToId(shortId);
} catch (e) {
console.warn('[GLIMPSE Cache] Failed to convert shortId to UUID:', e);
}
}
return null;
}
// Check if a node name contains any token that starts with "#nexus--" (for expansion)
function nameHasNexusExpandTag(nameText) {
if (!nameText) return false;
const parts = nameText.split(/\s+/);
return parts.some(p => p.startsWith('#nexus--'));
}
// Check if a node name contains the collapse tag "#collapse-nexus" (for full subtree reset)
// @beacon[
// id=extract-node-name@23224,
// role=extract-node-name,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function nameHasNexusCollapseTag(nameText) {
if (!nameText) return false;
const parts = nameText.split(/\s+/);
return parts.some(p => p === '#collapse-nexus');
}
// [DEPRECATED] kept for backwards compatibility if referenced elsewhere
// prior nameHasNexusTag behavior: expansion only
// @beacon[
// id=extract-node-name@222246,
// role=extract-node-name,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function nameHasNexusTag(nameText) {
return nameHasNexusExpandTag(nameText);
}
// Robust check: does this row have any Workflowy tag whose value starts with "#nexus--"?
// We look both at the plain text (for older structures) and at the .contentTag
// elements Workflowy uses for clickable tags (data-val="#tag")...
// @beacon[
// id=extract-node-name@22225,
// role=extract-node-name,
// slice_labels=glimpse-core,
// kind=ast,
// comment=foo,
// ]
function rowHasNexusExpandTag(row) {
if (!row) return false;
// First: fall back to the plain-text name check (historical behavior).
const nameText = extractNodeName(row);
if (nameHasNexusExpandTag(nameText)) {
return true;
}
// Second: inspect tag widgets rendered in the name container.
// Workflowy renders tags roughly as:
// <span class="contentTag" data-val="#nexus--cartographer">#<span class="contentTagText">nexus--cartographer</span>...</span>
try {
const tagEls = row.querySelectorAll(':scope > .name .contentTag');
for (const tagEl of tagEls) {
const dataVal = (tagEl.getAttribute('data-val') || '').trim();
const textVal = (tagEl.textContent || '').trim();
if (dataVal.startsWith('#nexus--') || textVal.startsWith('#nexus--')) {
return true;
}
}
} catch (e) {
// Non-fatal: if DOM structure changes, we simply fall back to text-only behavior.
}
return false;
}
// Find all visible nodes whose name contains a #nexus-- tag (expansion)
// @beacon[
// id=auto-beacon@findVisibleNexusExpandNodes-rlf8,
// role=findVisibleNexusExpandNodes,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function findVisibleNexusExpandNodes() {
const results = [];
const rows = document.querySelectorAll('div[projectid]');
rows.forEach(row => {
if (!rowHasNexusExpandTag(row)) return;
const id = extractItemIdFromDomNode(row);
if (!id) return;
const name = extractNodeName(row);
results.push({ id, name, el: row });
});
return results;
}
// Find all visible nodes whose name contains the collapse tag #collapse-nexus
function findVisibleNexusCollapseNodes() {
const results = [];
const rows = document.querySelectorAll('div[projectid]');
rows.forEach(row => {
const name = extractNodeName(row);
if (!nameHasNexusCollapseTag(name)) return;
const id = extractItemIdFromDomNode(row);
if (!id) return;
results.push({ id, name, el: row });
});
return results;
}
// Prune nested NEXUS-tagged nodes so we only operate on highest-level roots
// among the currently visible set.
// @beacon[
// id=auto-beacon@pruneNestedNexusRoots,
// role=pruneNestedNexusRoots,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function pruneNestedNexusRoots(nodes) {
if (!nodes || nodes.length === 0) return [];
const byId = new Map();
const keep = new Set();
// Index by id and initialize as "keep"
nodes.forEach(node => {
byId.set(node.id, node);
keep.add(node.id);
});
// For each candidate node, walk up its ancestor chain; if it finds another
// candidate ancestor, mark this node as nested and drop it from the keep set.
nodes.forEach(node => {
let current = node.el.parentElement && node.el.parentElement.closest('div[projectid]');
while (current) {
const ancestorId = current.getAttribute('projectid');
if (ancestorId && byId.has(ancestorId)) {
// This node is nested under another #nexus-- root; drop it
keep.delete(node.id);
break;
}
current = current.parentElement && current.parentElement.closest('div[projectid]');
}
});
const pruned = nodes.filter(node => keep.has(node.id));
console.log(
`[GLIMPSE Cache v${GLIMPSE_VERSION}] GLIMPSE-EXPAND: Found ${nodes.length} #nexus-- nodes, pruned to ${pruned.length} top-level roots.`
);
return pruned;
}
const DEFAULT_NEXUS_EXPAND_OPTIONS = {
maxDepth: 50,
maxNodes: 4000,
log: true,
};
// Expand all visible top-level #nexus-- roots
// @beacon[
// id=auto-beacon@expandAllVisibleNexusRoots,
// role=expandAllVisibleNexusRoots,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function expandAllVisibleNexusRoots(options) {
const candidates = findVisibleNexusExpandNodes();
const roots = pruneNestedNexusRoots(candidates);
if (!roots.length) {
console.log('[GLIMPSE Cache] GLIMPSE-EXPAND: No visible #nexus-- roots found.');
return;
}
const mergedOptions = Object.assign({}, DEFAULT_NEXUS_EXPAND_OPTIONS, options || {});
console.log('[GLIMPSE Cache] GLIMPSE-EXPAND: Expanding #nexus-- roots:', roots.map(r => r.name));
roots.forEach(root => {
expandSubtreeSafeById(root.id, mergedOptions);
});
}
// Collapse an entire subtree (bottom-up) under a given UUID
function collapseSubtreeById(id, {
maxDepth = 50,
maxNodes = 4000,
log = true,
} = {}) {
const root = WF.getItemById(id);
if (!root) {
console.warn(`[GLIMPSE Cache v${GLIMPSE_VERSION}] GLIMPSE-COLLAPSE: No item found for id ${id}`);
return;
}
const queue = [{ item: root, depth: 0 }];
const collected = [];
let count = 0;
// Collect nodes in breadth-first order up to bounds
while (queue.length && count < maxNodes) {
const { item, depth } = queue.shift();
collected.push(item);
count++;
if (depth >= maxDepth) continue;
const children = item.getChildren();
for (const child of children) {
queue.push({ item: child, depth: depth + 1 });
}
}
// Collapse from deepest to shallowest
for (let i = collected.length - 1; i >= 0; i--) {
const it = collected[i];
if (it.data.isExpanded) {
WF.collapseItem(it);
}
}
if (log) {
console.log(
`[GLIMPSE Cache v${GLIMPSE_VERSION}] GLIMPSE-COLLAPSE: Collapsed ${collected.length} nodes (maxNodes=${maxNodes}, maxDepth=${maxDepth}) under "${root.getNameInPlainText()}"`
);
}
}
// Collapse all visible top-level #collapse-nexus roots (full subtree reset)
function collapseAllVisibleNexusRoots(options) {
const candidates = findVisibleNexusCollapseNodes();
const roots = pruneNestedNexusRoots(candidates);
if (!roots.length) {
console.log('[GLIMPSE Cache] GLIMPSE-COLLAPSE: No visible #nexus-- roots found.');
return;
}
const mergedOptions = Object.assign({}, DEFAULT_NEXUS_EXPAND_OPTIONS, options || {});
console.log('[GLIMPSE Cache] GLIMPSE-COLLAPSE: Collapsing #collapse-nexus roots:', roots.map(r => r.name));
roots.forEach(root => {
collapseSubtreeById(root.id, mergedOptions);
});
}
// Expand an entire subtree (top-down) under a given UUID
function expandSubtreeSafeById(id, {
maxDepth = 6,
maxNodes = 2000,
log = true,
} = {}) {
const root = WF.getItemById(id);
if (!root) {
console.warn(`[GLIMPSE Cache v${GLIMPSE_VERSION}] GLIMPSE-EXPAND: No item found for id ${id}`);
return;
}
const queue = [{ item: root, depth: 0 }];
let count = 0;
while (queue.length && count < maxNodes) {
const { item, depth } = queue.shift();
// Always call expandItem – even if Workflowy thinks the node is already
// expanded, this guarantees we don't miss partially expanded branches.
WF.expandItem(item);
count++;
if (depth >= maxDepth) continue;
const children = item.getChildren();
for (const child of children) {
queue.push({ item: child, depth: depth + 1 });
}
}
if (log) {
console.log(
`[GLIMPSE Cache v${GLIMPSE_VERSION}] GLIMPSE-EXPAND: Expanded ${count} nodes (maxNodes=${maxNodes}, maxDepth=${maxDepth}) from "${root.getNameInPlainText()}"`
);
}
}
// Allow external callers (e.g., MCP or DevTools) to trigger expansion or collapse
window.GlimpseExpandNexusRoots = function(options) {
expandAllVisibleNexusRoots(options);
};
window.GlimpseCollapseNexusRoots = function(options) {
collapseAllVisibleNexusRoots(options);
};
// ------------------------------------------------------------
// Existing GLIMPSE logic below
// ------------------------------------------------------------
/**
* Detect if Workflowy search is active
*/
function isSearchActive() {
// Check for search results by looking for nodes with 'matches' class
const matchedNodes = document.querySelectorAll('div[projectid].matches');
return matchedNodes.length > 0;
}
/**
* Extract complete node tree from DOM
*
* Behavior:
* - If Workflowy search is active: extract only matching nodes + their ancestor paths
* - If no search: extract based on expansion state (existing behavior)
*/
// @beacon[
// id=extract-dom-tree@glimpse-ext,
// role=extract-dom-tree,
// slice_labels=f9-f12-handlers,glimpse-core,
// kind=ast,
// comment=Main DOM extraction - converts visible Workflowy tree to JSON for MCP server,
// ]
function extractDOMTree(nodeId) {
console.log('[GLIMPSE Cache] 🔍 Extracting DOM tree for node:', nodeId);
try {
const rootElement = document.querySelector(`div[projectid="${nodeId}"]`);
if (!rootElement) {
console.warn('[GLIMPSE Cache] ❌ Node not found in DOM:', nodeId);
return {
success: false,
error: `Node ${nodeId} not found in DOM (may be collapsed or not loaded)`
};
}
const rootName = extractNodeNameHtml(rootElement);
const rootNote = extractNodeNoteHtml(rootElement);
// Check if search is active
const searchActive = isSearchActive();
console.log(`[GLIMPSE Cache] Search active: ${searchActive}`);
const children = searchActive ?
extractSearchResults(rootElement, true) :
extractChildren(rootElement, true);
const nodeCount = 1 + countNodesRecursive(children);
const depth = calculateDepth(children);
console.log(`[GLIMPSE Cache] ✅ Extracted ${nodeCount} nodes, depth ${depth}`);
console.log('[GLIMPSE Cache] 📊 TREE STRUCTURE:');
printTree(children, 0);
return {
success: true,
root: {
id: nodeId,
name: rootName,
note: rootNote,
parent_id: rootElement.parentElement?.closest('div[projectid]')?.getAttribute('projectid') || null
},
children: children,
node_count: nodeCount,
depth: depth,
_source: searchActive ? 'search_results' : 'expansion'
};
} catch (error) {
console.error('[GLIMPSE Cache] Error during extraction:', error);
return {
success: false,
error: error.message
};
}
}
function extractVisibleActionTree(nodeId) {
console.log('[GLIMPSE Cache] 🏷️ Extracting visible action tree for node:', nodeId);
try {
const rootElement = document.querySelector(`div[projectid="${nodeId}"]`);
if (!rootElement) {
console.warn('[GLIMPSE Cache] ❌ Action root not found in DOM:', nodeId);
return {
success: false,
error: `Node ${nodeId} not found in DOM (may be collapsed or not loaded)`
};
}
const rootName = extractNodeName(rootElement);
const rootNote = extractNodeNote(rootElement);
const searchActive = isSearchActive();
const children = searchActive ?
extractSearchResults(rootElement, false) :
extractChildren(rootElement, false);
const nodeCount = 1 + countNodesRecursive(children);
const depth = calculateDepth(children);
return {
success: true,
root: {
id: nodeId,
name: rootName,
note: rootNote,
parent_id: rootElement.parentElement?.closest('div[projectid]')?.getAttribute('projectid') || null
},
children: children,
node_count: nodeCount,
depth: depth,
_source: searchActive ? 'search_results' : 'expansion'
};
} catch (error) {
console.error('[GLIMPSE Cache] Error during visible action tree extraction:', error);
return {
success: false,
error: error.message
};
}
}
function extractNodeName(element) {
// @beacon[
// id=extract-node-name@glimpse-ext,
// slice_labels=glimpse-core,
// kind=span,
// comment=Extract node name text from Workflowy DOM element,
// ]
// SPAN DEMO START: lines inside function, wrapped by span beacon
const spanDemoData = [
'SPAN_DEMO_01',
'SPAN_DEMO_02',
'SPAN_DEMO_03',
'SPAN_DEMO_04',
'SPAN_DEMO_05',
'SPAN_DEMO_06',
'SPAN_DEMO_07',
'SPAN_DEMO_08',
'SPAN_DEMO_09',
'SPAN_DEMO_10',
'SPAN_DEMO_11',
'SPAN_DEMO_12',
'SPAN_DEMO_13',
'SPAN_DEMO_14',
'SPAN_DEMO_15',
'SPAN_DEMO_16',
'SPAN_DEMO_17',
'SPAN_DEMO_18',
'SPAN_DEMO_19',
'SPAN_DEMO_20',
'SPAN_DEMO_21',
'SPAN_DEMO_22',
'SPAN_DEMO_23',
'SPAN_DEMO_24',
'SPAN_DEMO_25',
];
void spanDemoData;
// @beacon-close[
// id=extract-node-name@glimpse-ext,
// ]
// SPAN DEMO END
const nameContainer = element.querySelector(':scope > .name > .content > .innerContentContainer');
return nameContainer ? nameContainer.textContent.trim() : 'Untitled';
}
// @beacon[
// id=extract-node-note@glimpse-ext,
// role=extract-node-note,
// slice_labels=glimpse-core,
// kind=ast,
// comment=Extract node note text from Workflowy DOM element,
// ]
function extractNodeNote(element) {
const noteContainer = element.querySelector(':scope > .notes > .content > .innerContentContainer');
if (!noteContainer || !noteContainer.textContent.trim()) {
return null;
}
return noteContainer.textContent;
}
// Dewhiten HTML entities: < > & → < > &
// @beacon[
// id=auto-beacon@dewhitenText-ol8k,
// role=dewhitenText,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function dewhitenText(text) {
if (!text || typeof text !== 'string') return text;
return text.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
}
// Markup-preserving variants for GLIMPSE JSON (do not strip HTML tags).
// @beacon[
// id=auto-beacon@extractNodeNameHtml,
// role=extractNodeNameHtml,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function extractNodeNameHtml(element) {
const nameContainer = element.querySelector(':scope > .name > .content > .innerContentContainer');
if (!nameContainer) {
return 'Untitled';
}
// Preserve semantics of "empty = Untitled" while returning innerHTML
const text = nameContainer.textContent.trim();
if (!text) {
return 'Untitled';
}
return dewhitenText(nameContainer.innerHTML);
}
// @beacon[
// id=auto-beacon@extractNodeNoteHtml,
// role=extractNodeNoteHtml,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function extractNodeNoteHtml(element) {
const noteContainer = element.querySelector(':scope > .notes > .content > .innerContentContainer');
if (!noteContainer) {
return null;
}
if (!noteContainer.textContent.trim()) {
return null;
}
// Return raw HTML so formatted notes (bold/italic/code/color spans) round-trip.
return dewhitenText(noteContainer.innerHTML);
}
/**
* Extract search results from DOM (when Workflowy search is active)
*
* Returns hierarchical structure containing only nodes that match the search,
* plus their ancestor path elements (for context and proper nesting).
*/
// @beacon[
// id=auto-beacon@extractSearchResults-v534,
// role=extractSearchResults,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function extractSearchResults(rootElement, useHtml = false) {
const results = [];
const processedIds = new Set();
// Find all matching nodes under this root
const matchedElements = rootElement.querySelectorAll('div[projectid].matches, div[projectid].terminalMatch');
console.log(`[GLIMPSE Cache] Found ${matchedElements.length} search result nodes`);
// For each matched node, build its path from root and collect all ancestors
matchedElements.forEach(matchedEl => {
const matchedId = matchedEl.getAttribute('projectid');
if (!matchedId || processedIds.has(matchedId)) return;
// Build path from root to this matched node
const path = [];
let current = matchedEl;
while (current && current !== rootElement) {
const id = current.getAttribute('projectid');
if (id) {
path.unshift({
id: id,
element: current,
isMatch: current.classList.contains('matches') || current.classList.contains('terminalMatch')
});
}
current = current.parentElement?.closest('div[projectid]');
}
// Insert this path into the results tree
let currentLevel = results;
let currentParentId = rootElement.getAttribute('projectid');
path.forEach((pathNode, depth) => {
if (processedIds.has(pathNode.id)) {
// Already added - find it and descend
const existing = currentLevel.find(n => n.id === pathNode.id);
if (existing) {
currentLevel = existing.children;
currentParentId = existing.id;
}
return;
}
processedIds.add(pathNode.id);
const node = {
id: pathNode.id,
name: useHtml ? extractNodeNameHtml(pathNode.element) : extractNodeName(pathNode.element),
note: useHtml ? extractNodeNoteHtml(pathNode.element) : extractNodeNote(pathNode.element),
parent_id: currentParentId,
children: [],
has_hidden_children: !pathNode.isMatch // Path elements might have hidden children
};
currentLevel.push(node);
currentLevel = node.children;
currentParentId = node.id;
});
});
return results;
}
// @beacon[
// id=auto-beacon@extractChildren,
// role=extractChildren,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function extractChildren(parentElement, useHtml = false) {
const children = [];
const childrenContainer = parentElement.querySelector(':scope > .children');
if (!childrenContainer) {
return children;
}
const childElements = childrenContainer.querySelectorAll(':scope > div[projectid]');
childElements.forEach(childElement => {
const childId = childElement.getAttribute('projectid');
const childName = useHtml ? extractNodeNameHtml(childElement) : extractNodeName(childElement);
const childNote = useHtml ? extractNodeNoteHtml(childElement) : extractNodeNote(childElement);
// Detect hidden children metadata for NEXUS safety
const isCollapsed = childElement.classList.contains('collapsed');
const expandButton = childElement.querySelector('a[data-handbook="expand.toggle"] svg');
const hasExpandIcon = expandButton !== null;
const grandchildrenContainer = childElement.querySelector(':scope > .children');
const visibleGrandchildCount = grandchildrenContainer ?
grandchildrenContainer.querySelectorAll(':scope > div[projectid]').length : 0;
const hasHiddenChildren = isCollapsed || (hasExpandIcon && visibleGrandchildCount === 0);
const grandchildren = grandchildrenContainer ? extractChildren(childElement, useHtml) : [];
children.push({
id: childId,
name: childName,
note: childNote,
parent_id: parentElement.getAttribute('projectid'),
children: grandchildren,
has_hidden_children: hasHiddenChildren
});
});
return children;
}
// @beacon[
// id=auto-beacon@countNodesRecursive,
// role=countNodesRecursive,
// slice_labels=glimpse-core,
// kind=ast,
// ]
function countNodesRecursive(nodes) {
let count = nodes.length;
nodes.forEach(node => {
if (node.children && node.children.length > 0) {
count += countNodesRecursive(node.children);
}
});
return count;
}
function calculateDepth(nodes, currentDepth = 1) {
if (!nodes || nodes.length === 0) {
return currentDepth - 1;
}
let maxDepth = currentDepth;
nodes.forEach(node => {
if (node.children && node.children.length > 0) {
const childDepth = calculateDepth(node.children, currentDepth + 1);
maxDepth = Math.max(maxDepth, childDepth);
}
});
return maxDepth;
}
function printTree(nodes, level) {
const indent = ' '.repeat(level);
nodes.forEach(node => {
// Determine bullet emoji based on whether node has children
const bullet = (node.children && node.children.length > 0) ? '◉' : '●';
console.log(`${indent}${bullet} ${node.name}`);
if (node.children && node.children.length > 0) {
printTree(node.children, level + 1);
}
});
}
/**
* Connect to Python MCP WebSocket server
*/
// @beacon[
// id=auto-beacon@connectWebSocket-fh7i,
// role=connectWebSocket,
// slice_labels=ra-websocket,nexus--config,nexus-loading-flow,
// kind=ast,
// ]
function connectWebSocket() {
if (isConnecting || (ws && ws.readyState === WebSocket.OPEN)) {
return;
}
isConnecting = true;
console.log(`[GLIMPSE Cache v${GLIMPSE_VERSION}] Connecting to`, WS_URL);
try {
ws = new WebSocket(WS_URL);
// Expose WebSocket globally for UI helpers (e.g., CARTO CANCEL button).
try {
// eslint-disable-next-line no-undef
window.ws = ws;
} catch (e) {
// In case window is not available for some reason, ignore.
}
ws.onopen = () => {
console.log(`[GLIMPSE Cache v${GLIMPSE_VERSION}] ✅ Connected to Python MCP server`);
isConnecting = false;
if (reconnectInterval) {
clearInterval(reconnectInterval);
reconnectInterval = null;
}
// Send initial ping to keep connection alive
ws.send(JSON.stringify({action: 'ping'}));
console.log(`[GLIMPSE Cache v${GLIMPSE_VERSION}] Sent initial ping`);
// @beacon[
// id=carto-jobs@ws-open-polling,
// role=Start polling for CARTO_REFRESH job status via carto_list_jobs,
// slice_labels=ra-carto-jobs,nexus--config,
// kind=span,
// comment=Start polling for CARTO_REFRESH job status via carto_list_jobs,
// ]
// Start polling for CARTO_REFRESH job status once per second (best-effort)
if (!cartoJobsInterval) {
cartoJobsInterval = setInterval(() => {
try {
if (!ws || ws.readyState !== WebSocket.OPEN) {
return;
}
ws.send(JSON.stringify({ action: 'carto_list_jobs' }));
} catch (err) {
console.error(`[GLIMPSE Cache v${GLIMPSE_VERSION}] carto_list_jobs poll failed:`, err);
}
}, 1000);
}
// @beacon-close[
// id=carto-jobs@ws-open-polling,
// ]
};
// @beacon[
// id=ws-onmessage@glimpse-ext,
// role=WebSocket message handler - dispatches MCP server requests to client handlers,
// slice_labels=f9-f12-handlers,ra-websocket,
// kind=span,
// comment=WebSocket message handler - dispatches MCP server requests to client handlers,
// ]
ws.onmessage = (event) => {
try {
const request = JSON.parse(event.data);
if (request.action !== 'carto_list_jobs_result' && request.action !== 'carto_cancel_job_result') {
console.log(`[GLIMPSE Cache v${GLIMPSE_VERSION}] 📩 Request from Python:`, request.action);
}
if (request.action === 'extract_dom') {
const result = extractDOMTree(request.node_id);
ws.send(JSON.stringify(result));
console.log(`[GLIMPSE Cache v${GLIMPSE_VERSION}] ✅ Sent response:`, result.node_count || 0, 'nodes');
} else if (request.action === 'uuid_path_result') {
handleUuidPathResult(request);
} else if (request.action === 'refresh_nodes_export_cache_status') {
handleRefreshCacheStatus(request);
} else if (request.action === 'refresh_nodes_export_cache_result') {
handleRefreshCacheResult(request);
} else if (request.action === 'bulk_apply_visible_nodes_result') {
handleBulkApplyVisibleResult(request);
} else if (request.action === 'expand_nexus_roots') {
// Agent-triggered: expand all visible #nexus-- roots
const opts = request.options || {};
expandAllVisibleNexusRoots(opts);
ws.send(JSON.stringify({
success: true,
action: 'expand_nexus_roots_result',
expanded: true
}));
} else if (request.action === 'carto_list_jobs_result') {
// @beacon[
// id=carto-jobs@ws-carto-result-branch,
// slice_labels=ra-carto-jobs,
// kind=span,
// role=Dispatch CARTO_REFRESH job list updates to handleCartoJobsResult,
// comment=Dispatch CARTO_REFRESH job list updates to handleCartoJobsResult,
// ]
handleCartoJobsResult(request);
// @beacon-close[
// id=carto-jobs@ws-carto-result-branch,
// ]
} else if (request.action === 'carto_cancel_job_result') {
if (!request.success) {
console.error(`[GLIMPSE Cache v${GLIMPSE_VERSION}] carto_cancel_job_result error:`, request.error);
}
// No further action required; the next carto_list_jobs poll will update the UI.
}
} catch (error) {
console.error(`[GLIMPSE Cache v${GLIMPSE_VERSION}] Error handling message:`, error);
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
success: false,
error: error.message
}));
}
}
};
// @beacon-close[
// id=ws-onmessage@glimpse-ext,
// ]
ws.onerror = (error) => {
console.error(`[GLIMPSE Cache v${GLIMPSE_VERSION}] WebSocket error:`, error);
isConnecting = false;
};
ws.onclose = () => {
console.log(`[GLIMPSE Cache v${GLIMPSE_VERSION}] ⚠️ Disconnected from Python MCP server`);
ws = null;
try {
// eslint-disable-next-line no-undef
window.ws = null;
} catch (e) {
// Ignore if window not available.
}
isConnecting = false;
if (!reconnectInterval) {
reconnectInterval = setInterval(connectWebSocket, RECONNECT_DELAY);
}
};
} catch (error) {
console.error(`[GLIMPSE Cache v${GLIMPSE_VERSION}] Failed to create WebSocket:`, error);
isConnecting = false;
if (!reconnectInterval) {
reconnectInterval = setInterval(connectWebSocket, RECONNECT_DELAY);
}
}
}
/**
* UUID Hover Helper - copy Workflowy node UUIDs without DevTools
*
* Algorithm (v3.9.0+):
* - Tracks cursor position on mousemove
* - F2 keyup → copy all UUIDs in path (instant)
* - F3 keyup → copy leaf UUID only (instant)
* - Mousemove hides tooltip
* - No park timer needed (F2/F3 press is explicit intent)
*/
let lastMousePos = null;
let uuidTooltipEl = null;
// UUID Navigator widget state
let uuidNavigatorEl = null;
let uuidNavigatorInputEl = null;
let uuidNavigatorOutputEl = null;
let uuidNavigatorToggleEl = null;
let uuidNavigatorExpanded = false;
// Container for async CARTO_REFRESH job summaries (F12)
let cartoJobsEl = null;
// Polling interval handle for CARTO job status
let cartoJobsInterval = null;
// Tracks whether the next uuid_path_result should be rendered in FULL
// (verbose) mode rather than compact mode.
let uuidNavigatorFullMode = false;
// F12 action popup state
let f12PopupEl = null;
let f12PopupState = null;
// @beacon[
// id=auto-beacon@ensureUuidTooltipElement-pm6x,
// role=ensureUuidTooltipElement,
// slice_labels=nexus--glimpse-extension,
// kind=ast,
// ]
function ensureUuidTooltipElement() {
if (uuidTooltipEl) return uuidTooltipEl;
const el = document.createElement('div');
el.id = 'glimpse-uuid-tooltip';
el.style.position = 'absolute';
el.style.zIndex = '9999';
el.style.padding = '4px 8px';
el.style.background = 'rgba(0, 0, 0, 0.85)';
el.style.color = '#fff';
el.style.fontSize = '11px';
el.style.borderRadius = '4px';
el.style.pointerEvents = 'none';
el.style.maxWidth = '800px';
el.style.maxHeight = '80vh'; // Use viewport height (allows up to 80% of screen)
el.style.overflowY = 'auto';
el.style.whiteSpace = 'pre-wrap';
el.style.wordWrap = 'break-word';
el.style.overflow = 'hidden';
el.style.textOverflow = 'ellipsis';
el.style.fontFamily = 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
el.style.boxShadow = '0 2px 6px rgba(0,0,0,0.4)';
el.style.display = 'none';
document.body.appendChild(el);
uuidTooltipEl = el;
return el;
}
function hideUuidTooltip() {
if (uuidTooltipEl) {
uuidTooltipEl.style.display = 'none';
}
}
function showUuidTooltip(targetEl, uuid, copied, verboseMode) {
const el = ensureUuidTooltipElement();
const rect = targetEl.getBoundingClientRect();
// Hide any existing tooltip first to prevent ghost positioning
hideUuidTooltip();
// Build hierarchical path (same as clipboard format)
const pathData = [];
let current = targetEl;
while (current) {
const name = extractNodeName(current) || 'Untitled';