-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1937 lines (1724 loc) · 70.7 KB
/
Copy pathcontent.js
File metadata and controls
1937 lines (1724 loc) · 70.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
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
'\'': '''
};
return text.replace(/[&<>"']/g, m => map[m]);
}
/**
* VoiceInputHandler - Manages speech recognition for voice input
*/
class VoiceInputHandler {
constructor(textarea, voiceBtn, setStatus, updateClearVisibility) {
this.textarea = textarea;
this.voiceBtn = voiceBtn;
this.setStatus = setStatus;
this.updateClearVisibility = updateClearVisibility;
this.recognition = null;
this.isRecording = false;
this.recordingStartPosition = 0;
this.currentInterimLength = 0;
this.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (this.SpeechRecognition) {
this.init();
} else {
// Browser doesn't support speech recognition
this.voiceBtn.style.display = 'none';
}
}
init() {
this.recognition = new this.SpeechRecognition();
this.recognition.continuous = true;
this.recognition.interimResults = true;
this.recognition.lang = 'en-US';
this.recognition.onstart = () => this.handleStart();
this.recognition.onresult = (event) => this.handleResult(event);
this.recognition.onerror = (event) => this.handleError(event);
this.recognition.onend = () => this.handleEnd();
this.voiceBtn.addEventListener('click', () => {
if (this.isRecording) {
this.stop();
} else {
this.start();
}
});
}
handleStart() {
this.isRecording = true;
this.voiceBtn.classList.add('is-recording');
this.voiceBtn.setAttribute('aria-label', 'Stop voice input');
this.voiceBtn.setAttribute('title', 'Stop voice input');
this.setStatus('Listening...', 'info');
// Ensure we capture the cursor position correctly
// If cursor is at the start (0) but there's existing text, move to end
const currentCursor = this.textarea.selectionStart;
const hasText = this.textarea.value.trim().length > 0;
if (currentCursor === 0 && hasText) {
// Cursor is at start but there's text - move to end for appending
this.textarea.focus();
const endPos = this.textarea.value.length;
this.textarea.setSelectionRange(endPos, endPos);
this.recordingStartPosition = endPos;
} else {
// Use current cursor position
this.recordingStartPosition = currentCursor;
}
// Add a space before new voice input if there's existing text at the insertion point
if (this.recordingStartPosition > 0) {
const charBefore = this.textarea.value[this.recordingStartPosition - 1];
// Only add space if the character before is not already a space or newline
if (charBefore && charBefore !== ' ' && charBefore !== '\n') {
const textBefore = this.textarea.value.substring(0, this.recordingStartPosition);
const textAfter = this.textarea.value.substring(this.recordingStartPosition);
this.textarea.value = textBefore + ' ' + textAfter;
this.recordingStartPosition += 1; // Adjust position to account for the space we added
this.textarea.setSelectionRange(this.recordingStartPosition, this.recordingStartPosition);
}
}
this.currentInterimLength = 0;
}
handleResult(event) {
let interimTranscript = '';
const finalParts = [];
for (let i = event.resultIndex; i < event.results.length; i++) {
const transcript = event.results[i][0].transcript;
if (event.results[i].isFinal) {
finalParts.push(transcript);
} else {
interimTranscript += transcript;
}
}
const finalTranscript = finalParts.join(' ');
// On first result in this recording session, verify and correct the insertion position
// This ensures we insert at the current cursor position, not an old/stale position
if (event.resultIndex === 0 && this.currentInterimLength === 0) {
const currentCursor = this.textarea.selectionStart;
const textLength = this.textarea.value.length;
// Always use the current cursor position for new recording sessions
// This ensures text is inserted where the user expects it
this.recordingStartPosition = currentCursor;
}
// Calculate the end of the recording area
const recordingEndPosition = this.recordingStartPosition + this.currentInterimLength;
// Get text before and after the recording area
const textBefore = this.textarea.value.substring(0, this.recordingStartPosition);
const textAfter = this.textarea.value.substring(recordingEndPosition);
// Build new value: existing text before + all final transcripts + current interim (if any)
let newValue = textBefore + finalTranscript;
if (interimTranscript) {
newValue += interimTranscript;
}
newValue += textAfter;
// Update textarea with the new value
this.textarea.value = newValue;
// Update tracking: move start position forward by finalized text, track new interim length
if (finalTranscript) {
this.recordingStartPosition += finalTranscript.length;
}
this.currentInterimLength = interimTranscript.length;
// Set cursor at the end of the transcribed text (after final + interim)
const cursorPos = this.recordingStartPosition + this.currentInterimLength;
this.textarea.selectionStart = this.textarea.selectionEnd = cursorPos;
// Update clear button visibility when text changes
this.updateClearVisibility();
this.textarea.dispatchEvent(new Event('input', { bubbles: true }));
}
handleError(event) {
console.error('Speech recognition error:', event.error);
if (event.error === 'no-speech') {
this.setStatus('No speech detected. Try again.', 'error');
} else if (event.error === 'not-allowed') {
this.setStatus('Microphone permission denied. Please allow microphone access.', 'error');
// Disable the voice button since permission was denied
this.voiceBtn.disabled = true;
this.voiceBtn.setAttribute('title', 'Microphone permission denied');
} else if (event.error === 'aborted') {
// User stopped recording, don't show error
return;
} else {
this.setStatus(`Voice input error: ${event.error}`, 'error');
}
this.stop();
}
handleEnd() {
this.stop();
}
start() {
if (!this.recognition || this.voiceBtn.disabled) return;
try {
this.recognition.start();
} catch (err) {
console.error('Failed to start recognition:', err);
this.setStatus('Unable to start voice input.', 'error');
}
}
stop() {
if (this.isRecording && this.recognition) {
this.isRecording = false;
try {
this.recognition.stop();
} catch (err) {
// Ignore errors when stopping
}
this.voiceBtn.classList.remove('is-recording');
this.voiceBtn.setAttribute('aria-label', 'Start voice input');
this.voiceBtn.setAttribute('title', 'Start voice input');
this.setStatus('', 'info');
// Reset tracking variables
this.recordingStartPosition = 0;
this.currentInterimLength = 0;
}
}
}
function stripMarkdownFences(text) {
if (!text) return '';
let trimmed = text.trim();
// First, try to extract content from markdown code blocks
// Match: ```sparql ... ``` or ``` ... ```
const markdownBlockMatch = trimmed.match(/```(?:\w+)?\s*\n?([\s\S]*?)```/);
if (markdownBlockMatch) {
trimmed = markdownBlockMatch[1].trim();
} else {
// Remove leading/trailing fences if present
const fenceStart = /^```[\w-]*\s*/;
const fenceEnd = /```$/;
trimmed = trimmed.replace(fenceStart, '').replace(fenceEnd, '').trim();
}
// SPARQL keywords that indicate the start of a query
const sparqlStartKeywords = /\b(SELECT|ASK|CONSTRUCT|DESCRIBE|INSERT|DELETE|PREFIX|BASE)\b/i;
const lines = trimmed.split('\n');
// Find the start of the actual query (first line with SPARQL keywords)
let queryStart = lines.findIndex(line => sparqlStartKeywords.test(line));
// If we found a SPARQL keyword, extract from there to the end
// Otherwise, return the whole text (might already be just the query)
if (queryStart >= 0) {
trimmed = lines.slice(queryStart).join('\n').trim();
// Try to find where explanatory text starts after the query
// Look for patterns that suggest the query has ended
const explanationPatterns = /^\s*(Note|This|That|The query|The SPARQL|Explanation|Here'?s|For|This query)/i;
const queryLines = trimmed.split('\n');
let queryEnd = queryLines.length;
for (let i = 1; i < queryLines.length; i++) {
const line = queryLines[i].trim();
// If we hit a blank line followed by explanatory text, stop there
if (line === '' && i + 1 < queryLines.length && explanationPatterns.test(queryLines[i + 1])) {
queryEnd = i;
break;
}
// If a line starts with explanatory text, stop before it
if (line && explanationPatterns.test(line)) {
queryEnd = i;
break;
}
}
trimmed = queryLines.slice(0, queryEnd).join('\n').trim();
}
// Remove any remaining explanatory prefixes/suffixes
trimmed = trimmed.replace(/^(?:here'?s?|the|a)?\s*(?:sparql\s+)?query\s*[:\-–—]\s*/i, '');
return trimmed;
}
function getGeneratedQuery() {
const codeElem = document.querySelector('#sparql-output code');
if (!codeElem) return '';
const rawText = codeElem.innerText || codeElem.textContent || '';
return stripMarkdownFences(rawText);
}
let pasteBridgeReadyPromise = null;
function ensurePasteBridge() {
if (pasteBridgeReadyPromise) return pasteBridgeReadyPromise;
pasteBridgeReadyPromise = new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = chrome.runtime.getURL('js/pasteBridge.js');
script.onload = () => {
script.remove();
resolve();
};
script.onerror = err => {
script.remove();
pasteBridgeReadyPromise = null;
reject(new Error('Failed to load YASGUI bridge script.'));
};
document.documentElement.appendChild(script);
});
return pasteBridgeReadyPromise;
}
async function insertIntoYasgui(query) {
await ensurePasteBridge();
const messageId = `nl-paste-${Date.now()}-${Math.random().toString(16).slice(2)}`;
return new Promise((resolve, reject) => {
const listener = event => {
if (event.source !== window) return;
if (!event.data || event.data.type !== 'NL_TO_SPARQL_PASTE_RESPONSE') return;
if (event.data.id !== messageId) return;
window.removeEventListener('message', listener);
clearTimeout(timeout);
if (event.data.success) {
resolve();
} else {
reject(new Error(event.data.error || 'Unable to paste into YASGUI.'));
}
};
const timeout = setTimeout(() => {
window.removeEventListener('message', listener);
reject(new Error('Timed out while contacting YASGUI.'));
}, 2000);
window.addEventListener('message', listener);
window.postMessage({ type: 'NL_TO_SPARQL_PASTE_REQUEST', id: messageId, query }, '*');
});
}
function setStatus(message, type = 'info') {
const statusEl = document.getElementById('nl-status');
if (!statusEl) return;
statusEl.textContent = message || '';
if (message) {
statusEl.setAttribute('data-status-type', type);
} else {
statusEl.removeAttribute('data-status-type');
}
}
function toggleActionButtons(disabled) {
const buttons = document.querySelectorAll('#nl-submit, #nl-clear, #nl-copy, #nl-paste');
buttons.forEach(btn => {
btn.disabled = disabled;
});
}
function renderLoadingState() {
const output = document.getElementById('sparql-output');
if (!output) return;
output.innerHTML = `
<div class="nl-loading">
<span class="nl-spinner" aria-hidden="true"></span>
<span>Generating SPARQL…</span>
</div>
`;
}
function renderQuery(query) {
const output = document.getElementById('sparql-output');
if (!output) return;
output.innerHTML = `<pre><code class="sparql">${escapeHtml(query)}</code></pre>`;
if (window.hljs) {
window.hljs.highlightAll();
}
}
function injectUI() {
if (document.getElementById('nl-to-sparql-box')) return;
const box = document.createElement('div');
box.id = 'nl-to-sparql-box';
box.className = 'nl-to-sparql-box';
box.innerHTML = `
<div class="nl-to-sparql-box__title nl-drag-handle">
<span class="nl-to-sparql-box__title-text">Ask your SPARQL query:</span>
<button type="button" class="nl-minimize-btn" aria-label="Minimize panel" title="Minimize">
<span class="nl-minimize-icon" aria-hidden="true">−</span>
</button>
</div>
<div class="nl-to-sparql-box__content">
<div class="nl-input-wrapper">
<textarea id="nl-input" class="nl-input" rows="3" placeholder="Describe the query you need…"></textarea>
<div class="nl-input-actions">
<button type="button" id="nl-voice-btn" class="nl-voice-btn" aria-label="Start voice input" title="Start voice input">
<span class="nl-voice-icon" aria-hidden="true">🎤</span>
</button>
<button type="button" id="nl-input-clear" class="nl-input-clear-btn" aria-label="Clear input" title="Clear input" style="display: none;">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<label class="nl-model-label" for="nl-model-select">OpenAI model</label>
<select id="nl-model-select" class="nl-model-select">
<option value="gpt-4.1">gpt-4.1</option>
</select>
<div class="nl-context-collapsible">
<label class="nl-context-label" for="nl-context-input">
<span class="nl-context-toggle-icon">▼</span>
Optional prompt context
<button type="button" class="nl-context-help" aria-label="Help with context" title="Help with context">
<span aria-hidden="true">?</span>
</button>
<div id="nl-context-help-tooltip" class="nl-context-help-tooltip" role="tooltip" hidden>
<p>The context field allows you to provide additional information about your ontology that helps generate more accurate SPARQL queries. You can paste ontology snippets, prefixes, or upload a file containing relevant context.</p>
<p>Need help creating a context file for your ontology? <a href="https://github.com/twhetzel/sparql-chrome-extension/issues" target="_blank" rel="noopener noreferrer">Ask for help on our issue tracker</a>.</p>
<button type="button" class="nl-context-help-close" aria-label="Close help">×</button>
</div>
</label>
<div class="nl-context-section">
<div class="nl-context-source-row">
<label for="nl-context-source">
Context source
<span class="nl-context-note">(Context is sent to OpenAI; don’t include sensitive data.)</span>
</label>
<select id="nl-context-source" class="nl-context-select">
<option value="none">None</option>
<option value="omnigraph">Omnigraph repo URL…</option>
<option value="custom">Custom URL…</option>
</select>
</div>
<div class="nl-context-url-row" id="nl-context-url-row" hidden>
<div id="nl-context-omnigraph-file-list" class="nl-context-omnigraph-file-list" hidden>
<div id="nl-context-omnigraph-checkboxes" class="nl-context-omnigraph-checkboxes">
<div class="nl-context-loading">Loading context files...</div>
</div>
<button id="nl-context-omnigraph-load" type="button" class="nl-button nl-button--secondary">Load Selected Files</button>
</div>
<input id="nl-context-url" type="url" class="nl-context-url" placeholder="">
<button id="nl-context-url-load" type="button" class="nl-button nl-button--secondary">Load URL</button>
</div>
<textarea id="nl-context-input" class="nl-context-input" rows="4" placeholder="Paste supplemental notes or ontology snippets that should inform the query (optional)."></textarea>
<div class="nl-context-actions">
<label class="nl-context-upload">
<input type="file" id="nl-context-file" accept=".txt,.md,.json,.sparql,.csv,.tsv,.ttl,.rdf" hidden>
<span class="nl-context-upload-btn">Upload context file</span>
</label>
<button id="nl-context-clear" type="button" class="nl-button nl-button--secondary">Clear context</button>
</div>
<div id="nl-context-status" class="nl-context-status" aria-live="polite"></div>
</div>
<hr class="nl-divider" aria-hidden="true">
</div>
<div id="nl-controls" class="nl-controls">
<button id="nl-submit" class="nl-button nl-button--primary">Convert</button>
<button id="nl-clear" class="nl-button">Clear</button>
<button id="nl-copy" class="nl-button">Copy</button>
<button id="nl-paste" class="nl-button">Paste Query</button>
<button id="nl-reset-position" class="nl-button">Reset Position</button>
</div>
<div id="sparql-output" class="nl-output"></div>
<div id="nl-status" class="nl-status" aria-live="polite"></div>
<div class="nl-footer">
<a href="https://github.com/twhetzel/sparql-chrome-extension/issues" target="_blank" rel="noopener noreferrer" class="nl-footer-link">Report an issue</a>
</div>
<section id="nl-history" class="nl-history" aria-label="Generated query history">
<div class="nl-history-header">
<span class="nl-history-title">History</span>
<div class="nl-history-actions">
<button id="nl-history-export" class="nl-button nl-button--secondary">Export JSON</button>
<label class="nl-history-import-label">
<input type="file" id="nl-history-import" accept=".json" hidden>
<span class="nl-button nl-button--secondary">Import JSON</span>
</label>
<button id="nl-history-clear" class="nl-button nl-button--secondary">Clear</button>
</div>
</div>
<p id="nl-history-empty" class="nl-history-empty">No history yet.</p>
<div id="nl-history-list" class="nl-history-list" role="list"></div>
</section>
</div>
`;
document.body.appendChild(box);
const textarea = document.getElementById('nl-input');
// Get DOM elements early so they're available to functions
const contextTextarea = document.getElementById('nl-context-input');
const contextFileInput = document.getElementById('nl-context-file');
const contextClearButton = document.getElementById('nl-context-clear');
const contextStatus = document.getElementById('nl-context-status');
const contextSourceSelect = document.getElementById('nl-context-source');
const contextUrlRow = document.getElementById('nl-context-url-row');
const contextUrlInput = document.getElementById('nl-context-url');
const contextUrlLoad = document.getElementById('nl-context-url-load');
const contextOmnigraphFileList = document.getElementById('nl-context-omnigraph-file-list');
const contextOmnigraphLoadButton = document.getElementById('nl-context-omnigraph-load');
const persistContextSelection = (value, urlValue) => {
chrome.storage.local.set({
nl_context_source: value,
nl_context_custom_url: urlValue || ''
});
};
const updateContextSourceUI = () => {
const value = contextSourceSelect?.value || 'none';
const isCustom = value === 'custom';
const isOmnigraph = value === 'omnigraph';
const needsUrl = isCustom || isOmnigraph;
const hasContext = contextTextarea?.value.trim().length > 0;
if (contextUrlRow) {
contextUrlRow.hidden = !needsUrl;
}
// Show/hide file selector vs URL input based on selection
if (contextOmnigraphFileList) {
contextOmnigraphFileList.hidden = !isOmnigraph;
}
if (contextUrlInput) {
if (isOmnigraph) {
// Hide URL input for omnigraph - users select files via checkboxes
contextUrlInput.style.display = 'none';
} else if (isCustom) {
contextUrlInput.style.display = 'block';
contextUrlInput.placeholder = 'https://example.com/context.json';
} else {
contextUrlInput.style.display = 'none';
}
}
if (contextUrlLoad) {
// Show load button for custom URL, hide for omnigraph (uses Load Selected Files button)
contextUrlLoad.style.display = isCustom ? 'block' : 'none';
}
// Disable textarea when URL options are selected but no content loaded yet
// Enable when "None" is selected (for manual input) or when content exists
if (contextTextarea) {
if (value === 'none') {
// Always enable when "None" is selected (allows manual paste/upload)
contextTextarea.disabled = false;
contextTextarea.placeholder = 'Paste supplemental notes or ontology snippets that should inform the query (optional).';
} else if (needsUrl && !hasContext) {
// Disable when URL option is selected but no content loaded yet
contextTextarea.disabled = true;
contextTextarea.placeholder = 'Load context from URL to enable editing.';
} else {
// Enable when content exists
contextTextarea.disabled = false;
contextTextarea.placeholder = 'Paste supplemental notes or ontology snippets that should inform the query (optional).';
}
}
};
const removeMetadataFields = (context) => {
// Remove metadata fields that aren't useful for the LLM
// These are only used for tracking which files were loaded, not for query generation
const cleaned = JSON.parse(JSON.stringify(context));
delete cleaned.graph_id;
delete cleaned.endpoint;
delete cleaned.source_id;
delete cleaned.repository_filter;
delete cleaned.inherits_from;
return cleaned;
};
const resetContextSourceState = () => {
// Set source selector to "none"
if (contextSourceSelect) {
contextSourceSelect.value = 'none';
}
// Clear omnigraph checkboxes
if (contextOmnigraphFileList) {
const checkboxes = contextOmnigraphFileList.querySelectorAll('.nl-context-omnigraph-checkbox-input');
checkboxes.forEach(cb => cb.checked = false);
}
// Clear URL input
if (contextUrlInput) {
contextUrlInput.value = '';
}
// Clear storage
chrome.storage.local.set({
nl_context_source: 'none',
nl_context_custom_url: '',
nl_context_omnigraph_files: ''
});
};
const loadContextFromSource = async () => {
const value = contextSourceSelect?.value || 'none';
const isCustom = value === 'custom';
const isOmnigraph = value === 'omnigraph';
const needsUrl = isCustom || isOmnigraph;
if (value === 'none') {
setContextStatus('Context source set to none.', 'info');
return;
}
try {
if (needsUrl) {
const url = (contextUrlInput?.value || '').trim();
if (!url) {
setContextStatus('Enter a URL to load context.', 'warning');
return;
}
if (!/^https:\/\//i.test(url)) {
setContextStatus('Only https URLs are allowed for context.', 'warning');
return;
}
const text = await loadRemoteContext(url);
// Parse and clean metadata if it's JSON
try {
const parsed = JSON.parse(text);
const cleaned = removeMetadataFields(parsed);
const cleanedText = JSON.stringify(cleaned, null, 2);
applyLoadedContext(cleanedText, url);
} catch (parseErr) {
// If not valid JSON, use text as-is (might be plain text context)
applyLoadedContext(text, url);
}
persistContextSelection(value, url);
}
} catch (err) {
console.error('Context load failed', err);
setContextStatus(err.message || 'Failed to load context.', 'error');
}
};
// Handle omnigraph file loading - load and merge selected files
const loadSelectedOmnigraphFiles = async () => {
const checkboxes = contextOmnigraphFileList?.querySelectorAll('.nl-context-omnigraph-checkbox-input:checked');
if (!checkboxes || checkboxes.length === 0) {
setContextStatus('Select at least one file to load.', 'warning');
return;
}
const filenames = Array.from(checkboxes).map(cb => cb.value);
// Limit number of files to prevent memory issues
if (filenames.length > MAX_FILES_TO_LOAD) {
setContextStatus(`Too many files selected (${filenames.length}). Maximum is ${MAX_FILES_TO_LOAD}.`, 'error');
return;
}
setContextStatus(`Loading ${filenames.length} file(s) from omnigraph repo...`, 'info');
try {
const contexts = [];
let totalSize = 0;
// Load all selected files with size tracking
for (const filename of filenames) {
const url = `${OMNIGRAPH_AGENT_BASE_URL}${filename}`;
const text = await loadRemoteContext(url);
// Track total size across all files (use byte length for consistency with loadRemoteContext limits)
const textBytes = new TextEncoder().encode(text).length;
totalSize += textBytes;
if (totalSize > MAX_TOTAL_REMOTE_FILE_SIZE) {
throw new Error(`Total size of selected files (${(totalSize / 1024 / 1024).toFixed(1)}MB) exceeds limit (${(MAX_TOTAL_REMOTE_FILE_SIZE / 1024 / 1024).toFixed(1)}MB). Please select fewer files.`);
}
try {
const parsed = JSON.parse(text);
contexts.push(parsed);
} catch (parseErr) {
throw new Error(`Failed to parse ${filename}: ${parseErr.message}`);
}
}
// Merge contexts
const merged = mergeContextFiles(contexts);
const mergedText = JSON.stringify(merged, null, 2);
// Update URL input with first file's URL for reference
if (contextUrlInput && filenames.length > 0) {
contextUrlInput.value = `${OMNIGRAPH_AGENT_BASE_URL}${filenames[0]}`;
}
applyLoadedContext(mergedText, filenames.length === 1 ? filenames[0] : `${filenames.length} files merged`);
// Persist selection
const selectedFiles = filenames.join(',');
chrome.storage.local.set({
nl_context_source: 'omnigraph',
nl_context_omnigraph_files: selectedFiles,
nl_context_custom_url: contextUrlInput?.value || ''
});
} catch (err) {
console.error('Failed to load omnigraph files', err);
setContextStatus(err.message || 'Failed to load files from omnigraph repo.', 'error');
}
};
contextOmnigraphLoadButton?.addEventListener('click', loadSelectedOmnigraphFiles);
contextSourceSelect?.addEventListener('change', () => {
const value = contextSourceSelect?.value || 'none';
// Update UI visibility first (this hides/shows elements based on selection)
updateContextSourceUI();
// Clear context textarea whenever source changes (prepare for new content)
if (contextTextarea) {
contextTextarea.value = '';
}
// If "None" is selected, clear all context-related state
if (value === 'none') {
resetContextSourceState();
setContextStatus('Context cleared.', 'info');
} else {
// Reset checkboxes when switching away from omnigraph
if (contextOmnigraphFileList && value !== 'omnigraph') {
const checkboxes = contextOmnigraphFileList.querySelectorAll('.nl-context-omnigraph-checkbox-input');
checkboxes.forEach(cb => cb.checked = false);
}
// Update status message based on selection
if (value === 'omnigraph') {
setContextStatus('Select one or more files and click "Load Selected Files" to load context.', 'info');
} else {
setContextStatus('Enter a URL and click "Load URL" to load context.', 'info');
}
}
});
contextUrlLoad?.addEventListener('click', loadContextFromSource);
chrome.storage.local.get(['nl_context_source', 'nl_context_custom_url', 'nl_context_omnigraph_files'], async (result) => {
const savedSource = result?.nl_context_source || 'none';
const savedUrl = result?.nl_context_custom_url || '';
const savedFiles = result?.nl_context_omnigraph_files || '';
if (contextSourceSelect) {
contextSourceSelect.value = savedSource;
updateContextSourceUI();
}
// If "None" was saved, ensure context is cleared
if (savedSource === 'none') {
if (contextTextarea) {
contextTextarea.value = '';
}
if (contextOmnigraphFileList) {
const checkboxes = contextOmnigraphFileList.querySelectorAll('.nl-context-omnigraph-checkbox-input');
checkboxes.forEach(cb => cb.checked = false);
}
if (contextUrlInput) {
contextUrlInput.value = '';
}
setContextStatus('Context source set to none.', 'info');
} else {
// Note: Omnigraph checkbox restoration is handled inside populateOmnigraphFileList()
// after the file list is fetched from GitHub API
if (contextUrlInput && savedUrl) {
contextUrlInput.value = savedUrl;
}
// Auto-load if there's a saved URL for custom source (but not omnigraph with files, already handled above)
if (savedUrl && savedSource === 'custom') {
loadContextFromSource();
}
}
// Update UI state after initial load
updateContextSourceUI();
// Populate Omnigraph file list from GitHub API (after storage restoration)
// This will also restore saved checkbox states if applicable
populateOmnigraphFileList();
});
// Clear input button (show/hide based on content)
const inputClearBtn = document.getElementById('nl-input-clear');
const updateInputClearVisibility = () => {
inputClearBtn.style.display = textarea.value.trim() ? 'flex' : 'none';
};
textarea.addEventListener('input', updateInputClearVisibility);
updateInputClearVisibility(); // Initial check
// Initialize voice input handler
const voiceBtn = document.getElementById('nl-voice-btn');
const voiceHandler = new VoiceInputHandler(textarea, voiceBtn, setStatus, updateInputClearVisibility);
inputClearBtn.addEventListener('click', () => {
textarea.value = '';
textarea.focus();
updateInputClearVisibility();
// Also stop voice recording if active
voiceHandler.stop();
});
const MAX_CONTEXT_CHARS = 50000;
const MAX_REMOTE_FILE_SIZE = 2 * 1024 * 1024; // 2MB limit for remote files
const MAX_TOTAL_REMOTE_FILE_SIZE = MAX_REMOTE_FILE_SIZE * 2; // 4MB total limit (allows 2 files at max per-file size)
const MAX_FILES_TO_LOAD = 10; // Maximum number of files to load at once
const FETCH_TIMEOUT = 30000; // 30 seconds timeout
const OMNIGRAPH_AGENT_BASE_URL = 'https://raw.githubusercontent.com/twhetzel/omnigraph-agent/main/dist/context/';
const OMNIGRAPH_AGENT_API_URL = 'https://api.github.com/repos/twhetzel/omnigraph-agent/contents/dist/context';
// Helper function to format filename for display (converts "nde_file_name.json" to "NDE File Name")
const formatDisplayName = (filename) => {
let displayName = filename.replace(/\.json$/, '');
// Special handling for acronym prefixes to preserve uppercase
if (displayName.startsWith('nde_')) {
displayName = 'NDE ' + displayName.slice(4);
} else if (displayName.startsWith('vbo_')) {
displayName = 'VBO ' + displayName.slice(4);
}
return displayName
.replace(/_/g, ' ')
.replace(/\b\w/g, l => l.toUpperCase());
};
// Fetch and populate Omnigraph context file list from GitHub API
const populateOmnigraphFileList = async () => {
const checkboxesContainer = document.getElementById('nl-context-omnigraph-checkboxes');
if (!checkboxesContainer) return;
try {
const response = await fetch(OMNIGRAPH_AGENT_API_URL);
if (!response.ok) {
throw new Error(`GitHub API error: ${response.status}`);
}
const files = await response.json();
// Filter for .json files only
const jsonFiles = files
.filter(file => file.type === 'file' && file.name.endsWith('.json'))
.sort((a, b) => a.name.localeCompare(b.name));
// Clear loading message and populate checkboxes
checkboxesContainer.innerHTML = '';
if (jsonFiles.length === 0) {
checkboxesContainer.innerHTML = '<div class="nl-context-loading" data-status-type="warning">No context files found.</div>';
return;
}
const fragment = document.createDocumentFragment();
jsonFiles.forEach(file => {
const label = document.createElement('label');
label.className = 'nl-context-omnigraph-checkbox';
const input = document.createElement('input');
input.type = 'checkbox';
input.value = file.name;
input.className = 'nl-context-omnigraph-checkbox-input';
const span = document.createElement('span');
span.textContent = formatDisplayName(file.name);
label.appendChild(input);
label.appendChild(span);
fragment.appendChild(label);
});
checkboxesContainer.appendChild(fragment);
// Restore saved checkbox states after populating
chrome.storage.local.get(['nl_context_source', 'nl_context_omnigraph_files'], (result) => {
const savedSource = result?.nl_context_source || 'none';
const savedFiles = result?.nl_context_omnigraph_files || '';
if (savedSource === 'omnigraph' && savedFiles) {
const filenames = savedFiles.split(',').filter(f => f);
const checkboxes = checkboxesContainer.querySelectorAll('.nl-context-omnigraph-checkbox-input');
checkboxes.forEach(cb => {
if (filenames.includes(cb.value)) {
cb.checked = true;
}
});
if (filenames.length > 0) {
setContextStatus('Previous file selection restored. Click "Load Selected Files" to load context.', 'info');
}
}
});
} catch (err) {
console.error('Failed to fetch Omnigraph file list:', err);
checkboxesContainer.innerHTML = `<div class="nl-context-loading" data-status-type="error">Failed to load context files. ${escapeHtml(err.message)}</div>`;
}
};
const modelSelect = document.getElementById('nl-model-select');
const allowedModels = ['gpt-4.1'];
const DEFAULT_MODEL = 'gpt-4.1';
const controls = document.getElementById('nl-controls');
const historyList = document.getElementById('nl-history-list');
const historyEmpty = document.getElementById('nl-history-empty');
const historyImportInput = document.getElementById('nl-history-import');
const historyExportButton = document.getElementById('nl-history-export');
const historyClearButton = document.getElementById('nl-history-clear');
const getPasteButton = () => document.getElementById('nl-paste');
let selectedModel = DEFAULT_MODEL;
const HISTORY_KEY = 'sparqlprompt_history';
const OLD_HISTORY_KEY = 'ontoprompt_history'; // Legacy key for migration
const MAX_HISTORY_ENTRIES = 50;
let historyEntries = [];
const formatTimestamp = timestamp => {
try {
return new Date(timestamp).toLocaleString(undefined, {
dateStyle: 'short',
timeStyle: 'short'
});
} catch (err) {
return '';
}
};
const truncate = (text, limit = 160) => {
if (!text) return '';
if (text.length <= limit) return text;
return `${text.slice(0, limit - 1)}…`;
};
const setContextStatus = (message, type = 'info') => {
contextStatus.textContent = message;
contextStatus.setAttribute('data-status-type', type);
contextStatus.style.display = message ? 'block' : 'none';
};
const loadRemoteContext = async (url) => {
// Create abort controller for timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT);
try {
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) {
throw new Error(`Failed to fetch URL (${res.status})`);
}
// Check content-length header if available
const contentLength = res.headers.get('content-length');
const size = parseInt(contentLength, 10);
if (contentLength && size > MAX_REMOTE_FILE_SIZE) {
throw new Error(`File too large (${(size / 1024 / 1024).toFixed(1)}MB). Maximum size is ${(MAX_REMOTE_FILE_SIZE / 1024 / 1024).toFixed(1)}MB.`);
}
// Read response with size limit
const reader = res.body.getReader();
const decoder = new TextDecoder();
let text = '';
let totalSize = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalSize += value.length;
if (totalSize > MAX_REMOTE_FILE_SIZE) {
reader.cancel();
throw new Error(`File too large (exceeds ${(MAX_REMOTE_FILE_SIZE / 1024 / 1024).toFixed(1)}MB limit).`);
}
text += decoder.decode(value, { stream: true });
}
// Decode any remaining bytes
text += decoder.decode();
return text;
} catch (err) {
if (err.name === 'AbortError') {
throw new Error('Request timed out. The file may be too large or the server is slow.');
}
throw err;
} finally {
clearTimeout(timeoutId);
}
};
const mergeContextFiles = (contexts) => {
if (!contexts || contexts.length === 0) return null;
if (contexts.length === 1) return removeMetadataFields(contexts[0]);
// Start with the first context as the base
const merged = JSON.parse(JSON.stringify(contexts[0]));
// Merge additional contexts
for (let i = 1; i < contexts.length; i++) {
const ctx = contexts[i];
// Merge entity_types (combine arrays, remove duplicates)
if (ctx.entity_types && Array.isArray(ctx.entity_types)) {
merged.entity_types = [...(merged.entity_types || []), ...ctx.entity_types];
merged.entity_types = [...new Set(merged.entity_types)];
}
// Merge dimensions by name
if (ctx.dimensions && Array.isArray(ctx.dimensions)) {
const dimensionMap = new Map();
// Add existing dimensions to map
(merged.dimensions || []).forEach(dim => {
dimensionMap.set(dim.name, dim);
});
// Merge new dimensions
ctx.dimensions.forEach(dim => {
const existing = dimensionMap.get(dim.name);
if (existing) {
// Merge: combine top_values, take max coverage, sum distinct values
const existingValues = new Map();
(existing.top_values || []).forEach(tv => {
existingValues.set(tv.value, tv.count);
});
(dim.top_values || []).forEach(tv => {
const currentCount = existingValues.get(tv.value) || 0;
existingValues.set(tv.value, currentCount + tv.count);
});
existing.top_values = Array.from(existingValues.entries())
.map(([value, count]) => ({ value, count }))
.sort((a, b) => b.count - a.count)
.slice(0, 10); // Keep top 10
existing.coverage = Math.max(existing.coverage || 0, dim.coverage || 0);
existing.approx_distinct_values = Math.max(