-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtaskpane.js
More file actions
2504 lines (2151 loc) · 97.7 KB
/
taskpane.js
File metadata and controls
2504 lines (2151 loc) · 97.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
/*
* Gemini AI for Office - Task Pane Implementation
* Author: Anson Lai
* Location: Vancouver, Canada
* Description: Word add-in integrating Google Gemini AI for document editing and analysis
*/
/* global document, Office, Word, localStorage */
import { marked } from 'marked';
import { diff_match_patch } from 'diff-match-patch';
import "./taskpane.css";
import {
registerChatUiHandlers,
setupScrollToBottom,
createTypingIndicator,
shakeInput,
addMessageToChat,
updateSystemMessage,
addRetryButton,
hideAllRetryButtons,
removeMessage
} from './modules/chat/chat-ui.js';
import {
maintainHistoryWindow,
validateHistoryPairs,
sanitizeHistory,
removeAllFunctionPairs,
createFreshStartWithContext
} from './modules/chat/chat-history.js';
import {
initAgenticTools,
executeRedline,
executeComment,
executeHighlight,
executeNavigate,
executeResearch,
executeInsertListItem,
executeEditList,
executeConvertHeadersToList,
executeEditTable,
executeEditSection
} from './modules/commands/agentic-tools.js';
import { setPlatform } from '@ansonlai/docx-redline-js';
// Configure marked for GFM (GitHub Flavored Markdown) with tables, breaks, etc.
marked.setOptions({
gfm: true, // Enable GitHub Flavored Markdown
breaks: true, // Convert \n to <br>
});
// ==================== CONFIGURATION CONSTANTS ====================
const DEFAULT_AUTHOR = "Gemini AI";
const GLANCE_COLLAPSED_STORAGE_KEY = "glanceCollapsed";
// Safety settings for Gemini API (disable all safety blocks)
const SAFETY_SETTINGS_BLOCK_NONE = [
{ category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_NONE" },
{ category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_NONE" },
{ category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "BLOCK_NONE" },
{ category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "BLOCK_NONE" }
];
// Search and text limits
const SEARCH_LIMITS = {
MAX_LENGTH: 100, // Max search string length for comments/highlights
MAX_LENGTH_MODIFY: 80, // Max search string length for modify_text operations
SUFFIX_LENGTH: 60, // Suffix length for range expansion
RETRY_LENGTH: 30 // Fallback shorter search length for retries
};
// Document processing limits
const DOCUMENT_LIMITS = {
MAX_WORDS: 30000, // Approx 40 pages, ~40k tokens
MAX_LOOPS: 6, // Maximum tool execution loops
MAX_NO_PROGRESS_TOOL_LOOPS: 2, // Stop when the same mutation tool cycle keeps applying 0 changes
TOKEN_MULTIPLIER: 1.33 // Words to tokens conversion factor
};
// Storage quotas
const STORAGE_LIMITS = {
SAFE_LIMIT: 4500000, // ~4.5MB safe limit for localStorage
MIN_PRUNE_COUNT: 5 // Minimum checkpoints to prune when quota exceeded
};
// API generation limits
const API_LIMITS = {
MAX_OUTPUT_TOKENS: 48000 // Maximum tokens for AI response output
};
// Timeout limits for API calls
const TIMEOUT_LIMITS = {
FETCH_TIMEOUT_MS: 60000, // 60s timeout per individual API call
TOTAL_REQUEST_TIMEOUT_MS: 180000 // 3 min total timeout for entire request (including tool loops)
};
// Global abort controller for cancelling requests
let currentRequestController = null;
/**
* Extracts enhanced document context with rich formatting metadata.
* Returns an object with enhanced paragraph notation and section mapping.
*
* Format: [P#|Style|ListInfo|TableInfo|SectionInfo] Text
* Examples:
* [P1|Normal] Regular paragraph
* [P2|Heading1] Chapter heading
* [P3|ListNumber|L1:0|§] 1. Section header (starts section 1)
* [P4|Normal|§1] Body text belonging to section 1
* [P5|Normal|T:1,2] Table cell at row 1, column 2
*/
async function extractEnhancedDocumentContext(context) {
const body = context.document.body;
const paragraphs = body.paragraphs;
// Load all relevant paragraph properties
paragraphs.load("items");
await context.sync();
// Load detailed properties for each paragraph
for (const para of paragraphs.items) {
para.load("text, style, listItemOrNullObject, parentTableOrNullObject, parentTableCellOrNullObject");
}
await context.sync();
// Load list details for paragraphs that are list items
for (const para of paragraphs.items) {
if (!para.listItemOrNullObject.isNullObject) {
para.listItemOrNullObject.load("level, listString");
}
if (!para.parentTableCellOrNullObject.isNullObject) {
para.parentTableCellOrNullObject.load("rowIndex, cellIndex");
}
}
await context.sync();
// Build enhanced paragraph data
const enhancedParagraphs = [];
let currentSection = null; // Current section number (e.g., "1", "2")
let currentSubSection = null; // Current subsection (e.g., "1.1", "2.3")
let sectionCounter = 0; // Tracks top-level sections
let lastListLevel = -1; // Tracks list nesting level
let sectionStack = []; // Stack for tracking nested sections
for (let i = 0; i < paragraphs.items.length; i++) {
const para = paragraphs.items[i];
const text = para.text || "";
const style = para.style || "Normal";
// Build metadata parts
const metaParts = [style];
// Check if paragraph is a list item
let isListItem = false;
let listLevel = -1;
let listString = "";
if (!para.listItemOrNullObject.isNullObject) {
isListItem = true;
listLevel = para.listItemOrNullObject.level || 0;
listString = para.listItemOrNullObject.listString || "";
// Determine list type from style name
const isNumbered = style.toLowerCase().includes("number") ||
style.toLowerCase().includes("list number") ||
/^\d+[.)]/.test(listString);
const listType = isNumbered ? "ListNumber" : "ListBullet";
// Replace style with more specific list type
metaParts[0] = listType;
// Add list ID and level (using a simple counter-based ID)
metaParts.push(`L:${listLevel}`);
}
// Check if paragraph is in a table
let isInTable = false;
if (!para.parentTableCellOrNullObject.isNullObject) {
isInTable = true;
const rowIndex = para.parentTableCellOrNullObject.rowIndex || 0;
const cellIndex = para.parentTableCellOrNullObject.cellIndex || 0;
metaParts.push(`T:${rowIndex},${cellIndex}`);
}
// Section detection for legal contract patterns
let sectionMarker = "";
if (isListItem && !isInTable) {
// This list item could be a section header
// Detect section headers: list items at level 0 or items that start new sections
if (listLevel === 0) {
// Top-level list item = new section
sectionCounter++;
currentSection = String(sectionCounter);
currentSubSection = null;
sectionStack = [currentSection];
sectionMarker = "§"; // Mark as section header
lastListLevel = listLevel;
} else if (listLevel > lastListLevel) {
// Nested list item = subsection
const parentSection = sectionStack[sectionStack.length - 1] || currentSection;
const subNum = sectionStack.length;
currentSubSection = `${parentSection}.${listLevel}`;
sectionStack.push(currentSubSection);
sectionMarker = "§"; // Also mark as subsection header
lastListLevel = listLevel;
} else if (listLevel <= lastListLevel && listLevel > 0) {
// Same or shallower nested level - pop stack and create new subsection
while (sectionStack.length > listLevel + 1) {
sectionStack.pop();
}
const parentSection = sectionStack[0] || currentSection;
currentSubSection = `${parentSection}.${listLevel}`;
sectionStack[listLevel] = currentSubSection;
sectionMarker = "§";
lastListLevel = listLevel;
}
if (sectionMarker) {
metaParts.push(sectionMarker);
}
} else if (!isListItem && !isInTable && currentSection) {
// Non-list paragraph following a section header = section body
const belongsTo = currentSubSection || currentSection;
metaParts.push(`§${belongsTo}`);
}
// Build the enhanced notation
const metaString = metaParts.join("|");
const enhancedLine = `[P${i + 1}|${metaString}] ${text}`;
enhancedParagraphs.push({
index: i + 1,
text: text,
style: style,
isListItem: isListItem,
listLevel: listLevel,
isInTable: isInTable,
section: currentSection,
subSection: currentSubSection,
isSectionHeader: sectionMarker === "§",
enhancedLine: enhancedLine
});
}
return {
paragraphs: enhancedParagraphs,
formattedText: enhancedParagraphs.map(p => p.enhancedLine).join("\n"),
sectionCount: sectionCounter
};
}
let chatHistory = [];
let toolsExecutedInCurrentRequest = []; // Track successful tool executions for recovery
Office.onReady((info) => {
if (info.host === Office.HostType.Word) {
setPlatform(Office?.context?.platform);
document.getElementById("sideload-msg").style.display = "none";
// Show main view by default
showMainView();
// Add event listener for the chat send button (Fast)
document.getElementById("send-button").onclick = () => sendChatMessage('fast');
// Add event listener for the THINK button (Slow)
document.getElementById("think-button").onclick = () => sendChatMessage('slow');
// Add Enter key support for chat (Shift+Enter for new line)
document.getElementById("chat-input").addEventListener("keydown", (e) => {
if (e.key === "Enter") {
if (e.shiftKey) {
// Shift+Enter: New line (default behavior)
return;
}
e.preventDefault();
if (e.ctrlKey || e.metaKey) {
// Ctrl+Enter or Cmd+Enter: Thinking chat (slow)
sendChatMessage('slow');
} else {
// Enter: Regular chat (fast)
sendChatMessage('fast');
}
}
});
// Add event listeners for settings UI
document.getElementById("settings-button").onclick = showSettingsView;
document.getElementById("save-api-key").onclick = saveApiKey;
document.getElementById("back-to-main").onclick = showMainView;
// Add event listener for refresh chat button
document.getElementById("refresh-chat-button").onclick = refreshChat;
// Add event listener for Glance refresh
document.getElementById("refresh-glance-button").onclick = runGlanceChecks;
document.getElementById("toggle-glance-button").onclick = () => {
const container = document.getElementById("glance-container");
if (!container) return;
const shouldCollapse = !container.classList.contains("collapsed");
saveGlanceCollapsedState(shouldCollapse);
applyGlanceCollapsedState(shouldCollapse);
};
// Add event listener for Add Glance Card
document.getElementById("add-glance-card-button").onclick = () => {
const settings = loadGlanceSettings();
settings.push({
id: 'q' + Date.now(),
title: 'New Question',
question: 'What would you like to check?'
});
saveGlanceSettings(settings);
renderGlanceSettings();
};
// Check for API key on load
if (!loadApiKey()) {
showWelcomeScreen();
} else {
// Run Glance checks if key exists
renderGlanceMain();
runGlanceChecks();
}
// Accordion Event Listeners
setupAccordion("glance-settings-header", "glance-settings-content");
setupAccordion("advanced-settings-header", "advanced-settings-content");
// Scroll-to-bottom button setup
setupScrollToBottom();
// Add event listener for refresh author button
document.getElementById("refresh-author-button").onclick = async () => {
const author = await fetchDocumentAuthor();
if (author) {
document.getElementById("redline-author-input").value = author;
saveRedlineAuthor(author);
}
};
// Add event listeners for Redline settings
document.getElementById("redline-toggle").onchange = (e) => {
saveRedlineSetting(e.target.checked);
};
document.getElementById("redline-author-input").oninput = (e) => {
saveRedlineAuthor(e.target.value);
};
// Update checkpoint status on load (internal only now)
// updateCheckpointStatus(); // UI removed, but we can keep tracking internally if needed, or just remove this call.
}
});
function showWelcomeScreen() {
const chatMessages = document.getElementById("chat-messages");
chatMessages.innerHTML = ""; // Clear existing messages
const welcomeContainer = document.createElement("div");
welcomeContainer.className = "welcome-container";
welcomeContainer.innerHTML = `
<div class="welcome-header">
<h2>Get Started in 30 Seconds</h2>
</div>
<div class="welcome-step">
<div class="step-number">1</div>
<div class="step-content">
<p>Go to <a href="https://aistudio.google.com/app/api-keys" target="_blank">Google AI Studio</a>.</p>
</div>
</div>
<div class="welcome-step">
<div class="step-number">2</div>
<div class="step-content">
<p>Click <strong>Create API key</strong> (top left).</p>
</div>
</div>
<div class="welcome-step">
<div class="step-number">3</div>
<div class="step-content">
<p>Select your project (or create new) and copy the key string starting with <code style="color: #ff0000ff;">AIza...</code></p>
</div>
</div>
<div class="welcome-step">
<div class="step-number">4</div>
<div class="step-content">
<p>Click the <strong>Gear Icon</strong> <span style="font-size: 1.2em;">⚙</span> at the top right corner to enter your key.</p>
</div>
</div>
<div class="welcome-note">
<p style="text-align: right;">The free tier is <em>plenty</em> for personal use.</p>
</div>
<hr class="welcome-divider">
<div class="welcome-header">
<h2 >Features</h2>
</div>
<div class="feature-explanation">
<h3>Document Tools</h3>
<p>Chat with an assistant who can access to tools that can <strong>edit text</strong>, <strong>search Google</strong>, <strong>highlight key info</strong>, and <strong>leave comments</strong>. These tools allow the assistant to interact with your document naturally and help you with your tasks.</p>
</div>
<div class="feature-explanation">
<h3>Glance Checks</h3>
<p>Set up custom criteria (like <em>Grammar</em> or <em>Factual Accuracy</em>) to automatically check every document you open. You can customize these questions in Settings.</p>
</div>
<div class="feature-explanation">
<h3>System Prompts</h3>
<p>Customize how the AI behaves. You can tell it to be a <em>Grade 10 student working on an English paper</em> or an <em>associate lawyer at a New York law firm specializing in contracts</em>. Give it context and instructions you think would be helpful.</p>
</div>
<div class="feature-explanation">
<h3>Model Choices</h3>
<p><strong>Fast Model:</strong> This model is used for regular chats and is great for quick edits and simple questions. It is fast and cheap.</p>
<p><strong>Slow Model:</strong> This model is used when you select "Think". It provides deep analysis and basic online searches. It is slower and more expensive, but provides more thorough results.</p>
</div>
<div class="welcome-footer">
<p><em>If you have any questions, please reach out to us at <a href="mailto:support@reference.legal">support@reference.legal</a>.</em></p>
</div>
`;
chatMessages.appendChild(welcomeContainer);
}
// --- Settings & View Management ---
function switchView(hideId, showId) {
const hideEl = document.getElementById(hideId);
const showEl = document.getElementById(showId);
if (!hideEl || !showEl) return;
// Fade out current
hideEl.classList.add("view-hidden");
hideEl.classList.remove("view-container"); // Ensure it doesn't conflict
setTimeout(() => {
hideEl.style.display = "none";
showEl.style.display = "block";
// Force reflow
void showEl.offsetWidth;
// Fade in new
showEl.classList.remove("view-hidden");
showEl.classList.add("view-container");
}, 200); // Match CSS transition speed
}
function showSettingsView() {
document.getElementById("settings-button").style.display = "none";
document.getElementById("refresh-chat-button").style.display = "none";
switchView("main-view", "settings-view");
// Load current key into input
const currentKey = loadApiKey();
if (currentKey) {
document.getElementById("api-key-input").value = currentKey;
}
// Load current models
const currentFastModel = loadModel('fast');
if (currentFastModel) {
document.getElementById("model-select-fast").value = currentFastModel;
}
const currentSlowModel = loadModel('slow');
if (currentSlowModel) {
document.getElementById("model-select-slow").value = currentSlowModel;
}
// Load current system message
const currentSystemMessage = loadSystemMessage();
if (currentSystemMessage) {
document.getElementById("system-message-input").value = currentSystemMessage;
}
// Render Glance settings
renderGlanceSettings();
// Load redline setting
const redlineEnabled = loadRedlineSetting();
document.getElementById("redline-toggle").checked = redlineEnabled;
// Load redline author setting
const redlineAuthor = loadRedlineAuthor();
document.getElementById("redline-author-input").value = redlineAuthor;
}
function showMainView() {
document.getElementById("settings-button").style.display = "block";
document.getElementById("refresh-chat-button").style.display = "block";
switchView("settings-view", "main-view");
renderGlanceMain();
}
function refreshChat() {
// Cancel any ongoing request
if (currentRequestController) {
currentRequestController.abort();
currentRequestController = null;
console.log("Active request cancelled by refresh.");
}
// Immediately unlock UI (in case it was locked by an active request)
const chatInput = document.getElementById("chat-input");
const sendButton = document.getElementById("send-button");
const thinkButton = document.getElementById("think-button");
if (chatInput) {
chatInput.disabled = false;
chatInput.value = "";
chatInput.focus();
}
if (sendButton) sendButton.disabled = false;
if (thinkButton) thinkButton.disabled = false;
// Clear chat history
chatHistory = [];
// Clear the chat messages UI
const chatMessages = document.getElementById("chat-messages");
chatMessages.innerHTML = "";
// Add the welcome message back
const welcomeMessage = document.createElement("div");
welcomeMessage.className = "chat-message system";
welcomeMessage.textContent = "Welcome! Ask me to assist you in editing this document.";
chatMessages.appendChild(welcomeMessage);
// Add a system message confirming the refresh
addMessageToChat("System", "Chat history cleared. Starting new conversation.");
}
function saveApiKey() {
const apiKey = document.getElementById("api-key-input").value;
const fastModel = document.getElementById("model-select-fast").value;
const slowModel = document.getElementById("model-select-slow").value;
const systemMessage = document.getElementById("system-message-input").value;
const redlineEnabled = document.getElementById("redline-toggle").checked;
const redlineAuthor = document.getElementById("redline-author-input").value;
if (apiKey && apiKey.trim() !== "") {
localStorage.setItem("geminiApiKey", apiKey);
localStorage.setItem("geminiModelFast", fastModel);
localStorage.setItem("geminiModelSlow", slowModel);
localStorage.setItem("geminiSystemMessage", systemMessage);
saveRedlineSetting(redlineEnabled);
saveRedlineAuthor(redlineAuthor);
// Glance settings are saved automatically on change
showMainView();
addMessageToChat("System", "Settings saved successfully.");
// Re-run checks with new settings
runGlanceChecks();
} else {
addMessageToChat("System", "API Key cannot be empty.");
}
}
function loadApiKey() {
// First check localStorage (user-provided key takes precedence)
const storedKey = localStorage.getItem("geminiApiKey");
if (storedKey && storedKey.trim() !== "") {
return storedKey;
}
}
function loadModel(type = 'fast') {
const key = type === 'slow' ? "geminiModelSlow" : "geminiModelFast";
const storedModel = localStorage.getItem(key);
if (storedModel && storedModel.trim() !== "") {
return storedModel;
}
// Defaults
return type === 'slow' ? "gemini-2.5-pro" : "gemini-flash-latest";
}
function loadSystemMessage() {
const storedMessage = localStorage.getItem("geminiSystemMessage");
if (storedMessage && storedMessage.trim() !== "") {
return storedMessage;
}
return "Example: You are assisting an undergraduate student with their academic paper. You must be specific, precise, and double-check all your advice and suggested changes. Maintain a cheerful and helpful tone.";
}
function loadRedlineSetting() {
const storedSetting = localStorage.getItem("redlineEnabled");
return storedSetting !== null ? storedSetting === "true" : true; // Default to true (enabled)
}
function saveRedlineSetting(enabled) {
localStorage.setItem("redlineEnabled", enabled.toString());
}
function loadRedlineAuthor() {
const storedAuthor = localStorage.getItem("redlineAuthor");
if (storedAuthor && storedAuthor.trim() !== "") {
return storedAuthor;
}
return DEFAULT_AUTHOR; // Unified default fallback
}
function saveRedlineAuthor(author) {
if (author !== undefined && author !== null) {
localStorage.setItem("redlineAuthor", author.toString());
}
}
async function setChangeTrackingForAi(context, redlineEnabled, sourceLabel = "AI") {
let originalMode = null;
let changed = false;
let available = false;
try {
const doc = context.document;
doc.load("changeTrackingMode");
await context.sync();
available = true;
originalMode = doc.changeTrackingMode;
const desiredMode = redlineEnabled ? Word.ChangeTrackingMode.trackAll : Word.ChangeTrackingMode.off;
if (originalMode !== desiredMode) {
doc.changeTrackingMode = desiredMode;
await context.sync();
changed = true;
}
} catch (error) {
console.warn(`[ChangeTracking] ${sourceLabel}: unavailable`, error);
}
return { available, originalMode, changed };
}
async function restoreChangeTracking(context, trackingState, sourceLabel = "AI") {
if (!trackingState || !trackingState.available || !trackingState.changed || trackingState.originalMode === null) {
return;
}
try {
context.document.changeTrackingMode = trackingState.originalMode;
await context.sync();
} catch (error) {
console.warn(`[ChangeTracking] ${sourceLabel}: restore failed`, error);
}
}
initAgenticTools({
loadApiKey,
loadModel,
loadSystemMessage,
loadRedlineSetting,
loadRedlineAuthor,
setChangeTrackingForAi,
restoreChangeTracking,
SEARCH_LIMITS,
SAFETY_SETTINGS_BLOCK_NONE,
API_LIMITS
});
/**
* Fetches the document's author from Word properties.
*/
async function fetchDocumentAuthor() {
try {
let author = "";
await Word.run(async (context) => {
const properties = context.document.properties;
properties.load("lastAuthor, author");
await context.sync();
// Use lastAuthor if available, otherwise author
author = properties.lastAuthor || properties.author || "";
});
return author;
} catch (error) {
console.warn("Could not fetch document author:", error);
return "";
}
}
function loadGlanceSettings() {
const stored = localStorage.getItem("glanceSettings");
if (stored) {
try {
return JSON.parse(stored);
} catch (e) {
console.error("Error parsing glance settings", e);
}
}
// Default fallback
return [
{ id: 'q1', title: 'Grammar & Spelling', question: 'Are there any glaring spelling or grammatical issues?' },
{ id: 'q2', title: 'Factual Accuracy', question: 'Is this document factually accurate?' }
];
}
function saveGlanceSettings(settings) {
localStorage.setItem("glanceSettings", JSON.stringify(settings));
}
function loadGlanceCollapsedState() {
return localStorage.getItem(GLANCE_COLLAPSED_STORAGE_KEY) === "true";
}
function saveGlanceCollapsedState(isCollapsed) {
localStorage.setItem(GLANCE_COLLAPSED_STORAGE_KEY, isCollapsed.toString());
}
function applyGlanceCollapsedState(isCollapsed = loadGlanceCollapsedState()) {
const container = document.getElementById("glance-container");
const toggleButton = document.getElementById("toggle-glance-button");
if (!container || !toggleButton) return;
container.classList.toggle("collapsed", isCollapsed);
toggleButton.setAttribute("aria-expanded", (!isCollapsed).toString());
toggleButton.setAttribute("title", isCollapsed ? "Show Glance results" : "Hide Glance results");
}
function setupAccordion(headerId, contentId) {
const header = document.getElementById(headerId);
const content = document.getElementById(contentId);
if (header && content) {
header.onclick = () => {
const isOpen = content.classList.contains("open");
if (isOpen) {
content.classList.remove("open");
header.classList.remove("active");
// Wait for transition then hide (optional, but keep display block for anim)
// We rely on max-height: 0 hiding it
} else {
content.classList.add("open");
header.classList.add("active");
}
};
}
}
function renderGlanceMain() {
const list = document.getElementById("glance-list");
const container = document.getElementById("glance-container");
list.innerHTML = "";
const settings = loadGlanceSettings();
if (settings.length === 0) {
if (container) container.style.display = "none";
return;
}
if (container) container.style.display = "block";
applyGlanceCollapsedState();
settings.forEach(item => {
const div = document.createElement("div");
div.className = "glance-item";
div.id = `glance-item-${item.id}`;
div.innerHTML = `
<div class="glance-header">
<span id="glance-indicator-${item.id}" class="glance-indicator gray"></span>
<span class="glance-title">${item.title}</span>
</div>
<p id="glance-summary-${item.id}" class="glance-summary">Waiting for analysis...</p>
`;
list.appendChild(div);
});
}
function renderGlanceSettings() {
const list = document.getElementById("glance-settings-list");
list.innerHTML = "";
const settings = loadGlanceSettings();
settings.forEach((item, index) => {
const card = document.createElement("div");
card.className = "glance-settings-card";
card.dataset.index = index;
card.dataset.id = item.id;
// Slimmer layout: Drag handle on left, inputs stacked but compact
card.innerHTML = `
<div class="glance-card-header-row">
<input type="text" class="ms-TextField-field glance-title-input" value="${item.title}" placeholder="Title">
<span class="drag-handle" title="Drag to reorder">☰</span>
<button class="delete-card-btn" title="Delete">✕</button>
</div>
<textarea class="ms-TextField-field glance-question-input" placeholder="Question (e.g. Is the grammar correct?)" rows="2">${item.question}</textarea>
`;
// Event Listeners
card.querySelector(".delete-card-btn").onclick = () => {
settings.splice(index, 1);
saveGlanceSettings(settings);
renderGlanceSettings();
};
const titleInput = card.querySelector(".glance-title-input");
titleInput.onchange = (e) => {
settings[index].title = e.target.value;
saveGlanceSettings(settings);
};
const questionInput = card.querySelector(".glance-question-input");
questionInput.onchange = (e) => {
settings[index].question = e.target.value;
saveGlanceSettings(settings);
};
// Drag Events - Attach start/end to HANDLE only
const handle = card.querySelector('.drag-handle');
handle.draggable = true;
handle.addEventListener('dragstart', handleDragStart);
handle.addEventListener('dragend', handleDragEnd);
// Drop targets are still the CARDS
card.addEventListener('dragover', handleDragOver);
card.addEventListener('drop', handleDrop);
card.addEventListener('dragenter', handleDragEnter);
card.addEventListener('dragleave', handleDragLeave);
list.appendChild(card);
});
}
// Drag and Drop Handlers
let dragSrcEl = null;
function handleDragStart(e) {
const card = this.closest('.glance-settings-card');
card.style.opacity = '0.4';
dragSrcEl = card;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', card.innerHTML);
}
function handleDragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
return false;
}
function handleDragToggleClass(e, addClass) {
const card = e.target.closest('.glance-settings-card');
if (card) {
card.classList.toggle('over', addClass);
}
}
function handleDragEnter(e) {
handleDragToggleClass(e, true);
}
function handleDragLeave(e) {
handleDragToggleClass(e, false);
}
function handleDrop(e) {
e.stopPropagation();
const targetCard = e.target.closest('.glance-settings-card');
if (dragSrcEl !== targetCard && targetCard) {
const list = document.getElementById("glance-settings-list");
const items = Array.from(list.children);
const srcIndex = items.indexOf(dragSrcEl);
const destIndex = items.indexOf(targetCard);
const settings = loadGlanceSettings();
const [movedItem] = settings.splice(srcIndex, 1);
settings.splice(destIndex, 0, movedItem);
saveGlanceSettings(settings);
renderGlanceSettings();
}
return false;
}
function handleDragEnd(e) {
const card = this.closest('.glance-settings-card');
if (card) card.style.opacity = '1';
const items = document.querySelectorAll('.glance-settings-card');
items.forEach(function (item) {
item.classList.remove('over');
});
}
async function runGlanceChecks() {
const geminiApiKey = loadApiKey();
if (!geminiApiKey) return;
const settings = loadGlanceSettings();
if (settings.length === 0) return;
// Update UI to showing loading
settings.forEach(item => {
const indicator = document.getElementById(`glance-indicator-${item.id}`);
const summary = document.getElementById(`glance-summary-${item.id}`);
if (indicator) indicator.className = "glance-indicator gray";
if (summary) summary.innerText = "Checking...";
});
try {
let docText = "";
await Word.run(async (context) => {
const body = context.document.body;
body.load("text");
await context.sync();
docText = body.text;
});
const model = loadModel('fast'); // Use fast model for glance checks
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${geminiApiKey}`;
// Prepare prompt for dynamic checks
let questionsPrompt = "";
settings.forEach((item, index) => {
questionsPrompt += `Question ${index + 1} (ID: "${item.id}"): ${item.question}\n`;
});
const prompt = `
Analyze the following document text and answer the following questions.
Return the result as a JSON object where keys are the Question IDs (e.g., "q1", "q2").
For each question, provide:
- "status": "green" (no issues/good), "yellow" (minor issues/caution), or "red" (major issues/bad).
- "summary": A very brief summary (max 10 words).
IMPORTANT: Return ONLY the JSON object. Do not include any markdown formatting (like \`\`\`json), conversational text, or explanations.
Questions:
${questionsPrompt}
Document Text:
"""${docText}"""
`;
const payload = {
contents: [{ parts: [{ text: prompt }] }],
tools: [{ google_search: {} }],
safetySettings: SAFETY_SETTINGS_BLOCK_NONE
};
const response = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
const result = await response.json();
const candidate = result.candidates[0];
let text = candidate.content.parts[0].text;
// Robust JSON Extraction: Find the first '{' and the last '}'
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (jsonMatch) {
text = jsonMatch[0];
} else {
// Fallback cleanup if regex fails (though regex is preferred)
text = text.replace(/^```json\s*/, "").replace(/^```\s*/, "").replace(/```$/, "").trim();
}
const json = JSON.parse(text);
// Update UI
settings.forEach(item => {
const res = json[item.id];
if (res) {
const indicator = document.getElementById(`glance-indicator-${item.id}`);
const summary = document.getElementById(`glance-summary-${item.id}`);
if (indicator) {
indicator.className = `glance-indicator ${res.status}`;
// Add pulse animation
indicator.classList.add("pulse");
setTimeout(() => indicator.classList.remove("pulse"), 500);
}
if (summary) summary.innerText = res.summary;
}
});
} catch (error) {
console.error("Glance check failed:", error);
settings.forEach(item => {
const summary = document.getElementById(`glance-summary-${item.id}`);
if (summary) summary.innerText = "Error running check.";
});
}
}
// --- Checkpoint Management ---