-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathAIChatPanel.js
More file actions
1721 lines (1578 loc) · 70.6 KB
/
Copy pathAIChatPanel.js
File metadata and controls
1721 lines (1578 loc) · 70.6 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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/**
* AI Chat Panel — renders the chat UI in the AI sidebar tab, handles streaming
* responses from Claude Code, and manages edit application to documents.
*/
define(function (require, exports, module) {
const SidebarTabs = require("view/SidebarTabs"),
DocumentManager = require("document/DocumentManager"),
CommandManager = require("command/CommandManager"),
Commands = require("command/Commands"),
ProjectManager = require("project/ProjectManager"),
EditorManager = require("editor/EditorManager"),
FileSystem = require("filesystem/FileSystem"),
LiveDevMain = require("LiveDevelopment/main"),
WorkspaceManager = require("view/WorkspaceManager"),
SnapshotStore = require("core-ai/AISnapshotStore"),
PhoenixConnectors = require("core-ai/aiPhoenixConnectors"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
marked = require("thirdparty/marked.min");
let _nodeConnector = null;
let _isStreaming = false;
let _currentRequestId = null;
let _segmentText = ""; // text for the current segment only
let _autoScroll = true;
let _hasReceivedContent = false; // tracks if we've received any text/tool in current response
let _currentEdits = []; // edits in current response, for summary card
let _firstEditInResponse = true; // tracks first edit per response for initial PUC
let _undoApplied = false; // whether undo/restore has been clicked on any card
// --- AI event trace logging (compact, non-flooding) ---
let _traceTextChunks = 0;
let _traceToolStreamCounts = {}; // toolId → count
let _toolStreamStaleTimer = null; // timer to start rotating activity text
let _toolStreamRotateTimer = null; // interval for cycling activity phrases
// Context bar state
let _selectionDismissed = false; // user dismissed selection chip
let _lastSelectionInfo = null; // {filePath, fileName, startLine, endLine, selectedText}
let _lastCursorLine = null; // cursor line when no selection
let _lastCursorFile = null; // file name for cursor chip
let _cursorDismissed = false; // user dismissed cursor chip
let _cursorDismissedLine = null; // line that was dismissed
let _livePreviewActive = false; // live preview panel is open
let _livePreviewDismissed = false; // user dismissed live preview chip
let $contextBar; // DOM ref
// DOM references
let $panel, $messages, $status, $statusText, $textarea, $sendBtn, $stopBtn;
// Live DOM query for $messages — the cached $messages reference can become stale
// after SidebarTabs reparents the panel. Use this for any deferred operations
// (click handlers, callbacks) where the cached reference may no longer be in the DOM.
function _$msgs() {
return $(".ai-chat-messages");
}
const PANEL_HTML =
'<div class="ai-chat-panel">' +
'<div class="ai-chat-header">' +
'<span class="ai-chat-title">' + Strings.AI_CHAT_TITLE + '</span>' +
'<button class="ai-new-session-btn" title="' + Strings.AI_CHAT_NEW_SESSION_TITLE + '">' +
'<i class="fa-solid fa-plus"></i> ' + Strings.AI_CHAT_NEW_BTN +
'</button>' +
'</div>' +
'<div class="ai-chat-messages"></div>' +
'<div class="ai-chat-status">' +
'<span class="ai-status-spinner"></span>' +
'<span class="ai-status-text">' + Strings.AI_CHAT_THINKING + '</span>' +
'</div>' +
'<div class="ai-chat-input-area">' +
'<div class="ai-chat-context-bar"></div>' +
'<div class="ai-chat-input-wrap">' +
'<textarea class="ai-chat-textarea" placeholder="' + Strings.AI_CHAT_PLACEHOLDER + '" rows="1"></textarea>' +
'<button class="ai-send-btn" title="' + Strings.AI_CHAT_SEND_TITLE + '">' +
'<i class="fa-solid fa-paper-plane"></i>' +
'</button>' +
'<button class="ai-stop-btn" title="' + Strings.AI_CHAT_STOP_TITLE + '" style="display:none">' +
'<i class="fa-solid fa-stop"></i>' +
'</button>' +
'</div>' +
'</div>' +
'</div>';
const UNAVAILABLE_HTML =
'<div class="ai-chat-panel">' +
'<div class="ai-unavailable">' +
'<div class="ai-unavailable-icon"><i class="fa-solid fa-wand-magic-sparkles"></i></div>' +
'<div class="ai-unavailable-title">' + Strings.AI_CHAT_CLI_NOT_FOUND + '</div>' +
'<div class="ai-unavailable-message">' +
Strings.AI_CHAT_CLI_INSTALL_MSG +
'</div>' +
'<button class="ai-retry-btn">' + Strings.AI_CHAT_RETRY + '</button>' +
'</div>' +
'</div>';
const PLACEHOLDER_HTML =
'<div class="ai-chat-panel">' +
'<div class="ai-unavailable">' +
'<div class="ai-unavailable-icon"><i class="fa-solid fa-wand-magic-sparkles"></i></div>' +
'<div class="ai-unavailable-title">' + Strings.AI_CHAT_TITLE + '</div>' +
'<div class="ai-unavailable-message">' +
Strings.AI_CHAT_DESKTOP_ONLY +
'</div>' +
'</div>' +
'</div>';
/**
* Initialize the chat panel with a NodeConnector instance.
* @param {Object} nodeConnector - NodeConnector for communicating with the node-side Claude agent.
*/
function init(nodeConnector) {
_nodeConnector = nodeConnector;
// Wire up events from node side
_nodeConnector.on("aiTextStream", _onTextStream);
_nodeConnector.on("aiProgress", _onProgress);
_nodeConnector.on("aiToolInfo", _onToolInfo);
_nodeConnector.on("aiToolStream", _onToolStream);
_nodeConnector.on("aiToolEdit", _onToolEdit);
_nodeConnector.on("aiError", _onError);
_nodeConnector.on("aiComplete", _onComplete);
// Check availability and render appropriate UI
_checkAvailability();
}
/**
* Show placeholder UI for non-native (browser) builds.
*/
function initPlaceholder() {
const $placeholder = $(PLACEHOLDER_HTML);
SidebarTabs.addToTab("ai", $placeholder);
}
/**
* Check if Claude CLI is available and render the appropriate UI.
*/
function _checkAvailability() {
_nodeConnector.execPeer("checkAvailability")
.then(function (result) {
if (result.available) {
_renderChatUI();
} else {
_renderUnavailableUI(result.error);
}
})
.catch(function (err) {
_renderUnavailableUI(err.message || String(err));
});
}
/**
* Render the full chat UI.
*/
function _renderChatUI() {
$panel = $(PANEL_HTML);
$messages = $panel.find(".ai-chat-messages");
$status = $panel.find(".ai-chat-status");
$statusText = $panel.find(".ai-status-text");
$textarea = $panel.find(".ai-chat-textarea");
$sendBtn = $panel.find(".ai-send-btn");
$stopBtn = $panel.find(".ai-stop-btn");
// Event handlers
$sendBtn.on("click", _sendMessage);
$stopBtn.on("click", _cancelQuery);
$panel.find(".ai-new-session-btn").on("click", _newSession);
// Hide "+ New" button initially (no conversation yet)
$panel.find(".ai-new-session-btn").hide();
$textarea.on("keydown", function (e) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
_sendMessage();
}
if (e.key === "Escape") {
if (_isStreaming) {
_cancelQuery();
} else {
$textarea.val("");
}
}
});
// Auto-resize textarea
$textarea.on("input", function () {
this.style.height = "auto";
this.style.height = Math.min(this.scrollHeight, 96) + "px"; // max ~6rem
});
// Track scroll position for auto-scroll
$messages.on("scroll", function () {
const el = $messages[0];
_autoScroll = (el.scrollHeight - el.scrollTop - el.clientHeight) < 50;
});
// Context bar
$contextBar = $panel.find(".ai-chat-context-bar");
// Track editor selection/cursor for context chips
EditorManager.off("activeEditorChange.aiChat");
EditorManager.on("activeEditorChange.aiChat", function (_event, newEditor, oldEditor) {
if (oldEditor) {
oldEditor.off("cursorActivity.aiContext");
}
if (newEditor) {
newEditor.off("cursorActivity.aiContext");
newEditor.on("cursorActivity.aiContext", function (_evt, editor) {
_updateSelectionChip(editor);
});
}
_updateSelectionChip(newEditor);
});
// Bind to current editor if already active
const currentEditor = EditorManager.getActiveEditor();
if (currentEditor) {
currentEditor.off("cursorActivity.aiContext");
currentEditor.on("cursorActivity.aiContext", function (_evt, editor) {
_updateSelectionChip(editor);
});
}
_updateSelectionChip(currentEditor);
// Track live preview status — listen to both LiveDev status changes
// and panel show/hide events so the chip updates when the panel is closed
LiveDevMain.off("statusChange.aiChat");
LiveDevMain.on("statusChange.aiChat", _updateLivePreviewChip);
LiveDevMain.off(LiveDevMain.EVENT_OPEN_PREVIEW_URL + ".aiChat");
LiveDevMain.on(LiveDevMain.EVENT_OPEN_PREVIEW_URL + ".aiChat", function () {
_livePreviewDismissed = false;
_updateLivePreviewChip();
});
WorkspaceManager.off(WorkspaceManager.EVENT_WORKSPACE_PANEL_SHOWN + ".aiChat");
WorkspaceManager.on(WorkspaceManager.EVENT_WORKSPACE_PANEL_SHOWN + ".aiChat", _updateLivePreviewChip);
WorkspaceManager.off(WorkspaceManager.EVENT_WORKSPACE_PANEL_HIDDEN + ".aiChat");
WorkspaceManager.on(WorkspaceManager.EVENT_WORKSPACE_PANEL_HIDDEN + ".aiChat", _updateLivePreviewChip);
_updateLivePreviewChip();
// Refresh context bar when the AI tab becomes active (DOM updates
// are deferred while the tab is hidden to avoid layout interference)
SidebarTabs.off("tabChanged.aiChat");
SidebarTabs.on("tabChanged.aiChat", function (_event, tabId) {
if (tabId === "ai") {
_updateSelectionChip();
_updateLivePreviewChip();
}
});
// When a screenshot is captured, attach the image to the awaiting tool indicator
PhoenixConnectors.off("screenshotCaptured.aiChat");
PhoenixConnectors.on("screenshotCaptured.aiChat", function (_event, base64) {
const $tool = _$msgs().find('.ai-msg-tool').filter(function () {
return $(this).data("awaitingScreenshot");
}).last();
if ($tool.length) {
$tool.data("awaitingScreenshot", false);
const $detail = $tool.find(".ai-tool-detail");
const $img = $('<img class="ai-tool-screenshot" src="data:image/png;base64,' + base64 + '">');
$img.on("click", function (e) {
e.stopPropagation();
$img.toggleClass("expanded");
_scrollToBottom();
});
$img.on("load", function () {
// Force scroll — the image load changes height after insertion,
// which can cause the scroll listener to clear _autoScroll
if ($messages && $messages.length) {
$messages[0].scrollTop = $messages[0].scrollHeight;
}
});
$detail.html($img);
$tool.addClass("ai-tool-expanded");
_scrollToBottom();
}
});
SidebarTabs.addToTab("ai", $panel);
}
/**
* Render the unavailable UI (CLI not found).
*/
function _renderUnavailableUI(error) {
const $unavailable = $(UNAVAILABLE_HTML);
$unavailable.find(".ai-retry-btn").on("click", function () {
$unavailable.remove();
_checkAvailability();
});
SidebarTabs.addToTab("ai", $unavailable);
}
// --- Context bar chip management ---
/**
* Update the selection/cursor chip based on the active editor state.
* Skipped when the AI tab isn't active — calling getSelection()/getSelectedText()
* from both activeEditorChange and cursorActivity during inline editor operations
* interferes with the inline editor's cursor position tracking.
*/
function _updateSelectionChip(editor) {
if (SidebarTabs.getActiveTab() !== "ai") {
return;
}
if (!editor) {
editor = EditorManager.getActiveEditor();
}
if (!editor) {
_lastSelectionInfo = null;
_lastCursorLine = null;
_lastCursorFile = null;
_renderContextBar();
return;
}
let filePath = editor.document.file.fullPath;
if (filePath.startsWith("/tauri/")) {
filePath = filePath.replace("/tauri", "");
}
const fileName = filePath.split("/").pop();
if (editor.hasSelection()) {
const sel = editor.getSelection();
const startLine = sel.start.line + 1;
const endLine = sel.end.line + 1;
const selectedText = editor.getSelectedText();
// Reset dismissed flag when selection changes
if (!_lastSelectionInfo ||
_lastSelectionInfo.startLine !== startLine ||
_lastSelectionInfo.endLine !== endLine ||
_lastSelectionInfo.filePath !== filePath) {
_selectionDismissed = false;
}
_lastSelectionInfo = {
filePath: filePath,
fileName: fileName,
startLine: startLine,
endLine: endLine,
selectedText: selectedText
};
_lastCursorLine = null;
_lastCursorFile = null;
} else {
const cursor = editor.getCursorPos();
const cursorLine = cursor.line + 1;
// Reset cursor dismissed when cursor moves to a different line
if (_cursorDismissed && _cursorDismissedLine !== cursorLine) {
_cursorDismissed = false;
}
_lastSelectionInfo = null;
_lastCursorLine = cursorLine;
_lastCursorFile = fileName;
}
_renderContextBar();
}
/**
* Update the live preview chip based on panel visibility.
*/
function _updateLivePreviewChip() {
if (SidebarTabs.getActiveTab() !== "ai") {
return;
}
const panel = WorkspaceManager.getPanelForID("live-preview-panel");
const wasActive = _livePreviewActive;
_livePreviewActive = !!(panel && panel.isVisible());
// Reset dismissed when live preview is re-opened
if (_livePreviewActive && !wasActive) {
_livePreviewDismissed = false;
}
_renderContextBar();
}
/**
* Rebuild the context bar chips from current state.
*/
function _renderContextBar() {
if (!$contextBar) {
return;
}
$contextBar.empty();
// Live preview chip
if (_livePreviewActive && !_livePreviewDismissed) {
const $lpChip = $(
'<span class="ai-context-chip ai-context-chip-livepreview">' +
'<span class="ai-context-chip-icon"><i class="fa-solid fa-eye"></i></span>' +
'<span class="ai-context-chip-label">' + Strings.AI_CHAT_CONTEXT_LIVE_PREVIEW + '</span>' +
'<button class="ai-context-chip-close">×</button>' +
'</span>'
);
$lpChip.find(".ai-context-chip-close").on("click", function () {
_livePreviewDismissed = true;
_renderContextBar();
});
$contextBar.append($lpChip);
}
// Selection or cursor chip
if (_lastSelectionInfo && !_selectionDismissed) {
const label = StringUtils.format(Strings.AI_CHAT_CONTEXT_SELECTION,
_lastSelectionInfo.startLine, _lastSelectionInfo.endLine) +
" in " + _lastSelectionInfo.fileName;
const $chip = $(
'<span class="ai-context-chip ai-context-chip-selection">' +
'<span class="ai-context-chip-icon"><i class="fa-solid fa-i-cursor"></i></span>' +
'<span class="ai-context-chip-label"></span>' +
'<button class="ai-context-chip-close">×</button>' +
'</span>'
);
$chip.find(".ai-context-chip-label").text(label);
$chip.find(".ai-context-chip-close").on("click", function () {
_selectionDismissed = true;
_renderContextBar();
});
$contextBar.append($chip);
} else if (_lastCursorLine !== null && !_lastSelectionInfo && !_cursorDismissed) {
const label = StringUtils.format(Strings.AI_CHAT_CONTEXT_CURSOR, _lastCursorLine) +
" in " + _lastCursorFile;
const $cursorChip = $(
'<span class="ai-context-chip ai-context-chip-selection">' +
'<span class="ai-context-chip-icon"><i class="fa-solid fa-i-cursor"></i></span>' +
'<span class="ai-context-chip-label"></span>' +
'<button class="ai-context-chip-close">×</button>' +
'</span>'
);
$cursorChip.find(".ai-context-chip-label").text(label);
$cursorChip.find(".ai-context-chip-close").on("click", function () {
_cursorDismissed = true;
_cursorDismissedLine = _lastCursorLine;
_renderContextBar();
});
$contextBar.append($cursorChip);
}
// Toggle visibility
$contextBar.toggleClass("has-chips", $contextBar.children().length > 0);
}
/**
* Send the current input as a message to Claude.
*/
function _sendMessage() {
const text = $textarea.val().trim();
if (!text || _isStreaming) {
return;
}
// Show "+ New" button once a conversation starts
$panel.find(".ai-new-session-btn").show();
// Append user message
_appendUserMessage(text);
// Clear input
$textarea.val("");
$textarea.css("height", "auto");
// Set streaming state
_setStreaming(true);
// Reset segment tracking and show thinking indicator
_segmentText = "";
_hasReceivedContent = false;
_currentEdits = [];
_firstEditInResponse = true;
SnapshotStore.startTracking();
_appendThinkingIndicator();
// Remove restore highlights from previous interactions
_$msgs().find(".ai-restore-highlighted").removeClass("ai-restore-highlighted");
// Get project path
const projectPath = _getProjectRealPath();
_traceTextChunks = 0;
_traceToolStreamCounts = {};
const prompt = text;
console.log("[AI UI] Sending prompt:", text.slice(0, 60));
// Gather selection context if available and not dismissed
let selectionContext = null;
if (_lastSelectionInfo && !_selectionDismissed && _lastSelectionInfo.selectedText) {
const MAX_INLINE_SELECTION = 500;
const MAX_PREVIEW_LINES = 3;
const MAX_PREVIEW_LINE_LEN = 80;
let selectedText = _lastSelectionInfo.selectedText;
let selectionPreview = null;
if (selectedText.length > MAX_INLINE_SELECTION) {
const lines = selectedText.split("\n");
const headLines = lines.slice(0, MAX_PREVIEW_LINES).map(function (l) {
return l.length > MAX_PREVIEW_LINE_LEN ? l.slice(0, MAX_PREVIEW_LINE_LEN) + "..." : l;
});
const tailLines = lines.length > MAX_PREVIEW_LINES * 2
? lines.slice(-MAX_PREVIEW_LINES).map(function (l) {
return l.length > MAX_PREVIEW_LINE_LEN ? l.slice(0, MAX_PREVIEW_LINE_LEN) + "..." : l;
})
: [];
selectionPreview = headLines.join("\n") +
(tailLines.length ? "\n...\n" + tailLines.join("\n") : "");
selectedText = null;
}
selectionContext = {
filePath: _lastSelectionInfo.filePath,
startLine: _lastSelectionInfo.startLine,
endLine: _lastSelectionInfo.endLine,
selectedText: selectedText,
selectionPreview: selectionPreview
};
}
_nodeConnector.execPeer("sendPrompt", {
prompt: prompt,
projectPath: projectPath,
sessionAction: "continue",
locale: brackets.getLocale(),
selectionContext: selectionContext
}).then(function (result) {
_currentRequestId = result.requestId;
console.log("[AI UI] RequestId:", result.requestId);
}).catch(function (err) {
_setStreaming(false);
_appendErrorMessage(StringUtils.format(Strings.AI_CHAT_SEND_ERROR, err.message || String(err)));
});
}
/**
* Cancel the current streaming query.
*/
function _cancelQuery() {
if (_nodeConnector && _isStreaming) {
_nodeConnector.execPeer("cancelQuery").catch(function () {
// ignore cancel errors
});
}
}
/**
* Start a new session: destroy server-side session and clear chat.
*/
function _newSession() {
if (_nodeConnector) {
_nodeConnector.execPeer("destroySession").catch(function () {
// ignore
});
}
_currentRequestId = null;
_segmentText = "";
_hasReceivedContent = false;
_isStreaming = false;
_firstEditInResponse = true;
_undoApplied = false;
_selectionDismissed = false;
_lastSelectionInfo = null;
_lastCursorLine = null;
_lastCursorFile = null;
_cursorDismissed = false;
_cursorDismissedLine = null;
_livePreviewDismissed = false;
SnapshotStore.reset();
PhoenixConnectors.clearPreviousContentMap();
if ($messages) {
$messages.empty();
}
// Hide "+ New" button since we're back to empty state
if ($panel) {
$panel.find(".ai-new-session-btn").hide();
}
if ($status) {
$status.removeClass("active");
}
if ($textarea) {
$textarea.prop("disabled", false);
$textarea[0].focus({ preventScroll: true });
}
if ($sendBtn) {
$sendBtn.prop("disabled", false);
}
}
// --- Event handlers for node-side events ---
function _onTextStream(_event, data) {
_traceTextChunks++;
if (_traceTextChunks === 1) {
console.log("[AI UI]", "First text chunk");
}
// Remove thinking indicator on first content
if (!_hasReceivedContent) {
_hasReceivedContent = true;
$messages.find(".ai-thinking").remove();
}
// If no active stream target exists, create a new text segment
if (!$messages.find(".ai-stream-target").length) {
_appendAssistantSegment();
}
_segmentText += data.text;
_renderAssistantStream();
}
// Tool type configuration: icon, color, label
const TOOL_CONFIG = {
Glob: { icon: "fa-solid fa-magnifying-glass", color: "#6b9eff", label: Strings.AI_CHAT_TOOL_SEARCH_FILES },
Grep: { icon: "fa-solid fa-magnifying-glass-location", color: "#6b9eff", label: Strings.AI_CHAT_TOOL_SEARCH_CODE },
Read: { icon: "fa-solid fa-file-lines", color: "#6bc76b", label: Strings.AI_CHAT_TOOL_READ },
Edit: { icon: "fa-solid fa-pen", color: "#e8a838", label: Strings.AI_CHAT_TOOL_EDIT },
Write: { icon: "fa-solid fa-file-pen", color: "#e8a838", label: Strings.AI_CHAT_TOOL_WRITE },
Bash: { icon: "fa-solid fa-terminal", color: "#c084fc", label: Strings.AI_CHAT_TOOL_RUN_CMD },
Skill: { icon: "fa-solid fa-puzzle-piece", color: "#e0c060", label: Strings.AI_CHAT_TOOL_SKILL },
"mcp__phoenix-editor__getEditorState": { icon: "fa-solid fa-code", color: "#6bc76b", label: Strings.AI_CHAT_TOOL_EDITOR_STATE },
"mcp__phoenix-editor__takeScreenshot": { icon: "fa-solid fa-camera", color: "#c084fc", label: Strings.AI_CHAT_TOOL_SCREENSHOT },
"mcp__phoenix-editor__execJsInLivePreview": { icon: "fa-solid fa-eye", color: "#66bb6a", label: Strings.AI_CHAT_TOOL_LIVE_PREVIEW_JS },
"mcp__phoenix-editor__controlEditor": { icon: "fa-solid fa-code", color: "#6bc76b", label: Strings.AI_CHAT_TOOL_CONTROL_EDITOR },
"mcp__phoenix-editor__resizeLivePreview": { icon: "fa-solid fa-arrows-left-right", color: "#66bb6a", label: Strings.AI_CHAT_TOOL_RESIZE_PREVIEW },
"mcp__phoenix-editor__wait": { icon: "fa-solid fa-hourglass-half", color: "#adb9bd", label: Strings.AI_CHAT_TOOL_WAIT },
TodoWrite: { icon: "fa-solid fa-list-check", color: "#66bb6a", label: Strings.AI_CHAT_TOOL_TASKS }
};
function _onProgress(_event, data) {
console.log("[AI UI]", "Progress:", data.phase, data.toolName ? data.toolName + " #" + data.toolId : "");
if ($statusText) {
const toolName = data.toolName || "";
const config = TOOL_CONFIG[toolName];
$statusText.text(config ? config.label + "..." : Strings.AI_CHAT_THINKING);
}
if (data.phase === "tool_use") {
_appendToolIndicator(data.toolName, data.toolId);
}
}
function _onToolInfo(_event, data) {
const uid = (_currentRequestId || "") + "-" + data.toolId;
const streamCount = _traceToolStreamCounts[uid] || 0;
console.log("[AI UI]", "ToolInfo:", data.toolName, "#" + data.toolId,
"file=" + (data.toolInput && data.toolInput.file_path || "?").split("/").pop(),
"streamEvents=" + streamCount);
_updateToolIndicator(data.toolId, data.toolName, data.toolInput);
// Capture content of files the AI reads (for snapshot delete tracking)
if (data.toolName === "Read" && data.toolInput && data.toolInput.file_path) {
const filePath = data.toolInput.file_path;
const vfsPath = SnapshotStore.realToVfsPath(filePath);
const openDoc = DocumentManager.getOpenDocumentForPath(vfsPath);
if (openDoc) {
SnapshotStore.recordFileRead(filePath, openDoc.getText());
} else {
const file = FileSystem.getFileForPath(vfsPath);
file.read(function (err, readData) {
if (!err && readData) {
SnapshotStore.recordFileRead(filePath, readData);
}
});
}
}
}
/**
* Start an elapsed-time counter on a tool indicator. Called when the tool's
* stale timer fires (no streaming activity for 2s).
*/
function _startElapsedTimer($tool) {
if ($tool.data("elapsedTimer")) {
return; // already running
}
const startTime = $tool.data("startTime") || Date.now();
const $header = $tool.find(".ai-tool-header");
let $elapsed = $header.find(".ai-tool-elapsed");
if (!$elapsed.length) {
$elapsed = $('<span class="ai-tool-elapsed"></span>');
$header.append($elapsed);
}
function update() {
const secs = Math.floor((Date.now() - startTime) / 1000);
if (secs < 60) {
$elapsed.text(secs + "s");
} else {
const m = Math.floor(secs / 60);
const s = secs % 60;
$elapsed.text(m + "m " + (s < 10 ? "0" : "") + s + "s");
}
}
update();
const timerId = setInterval(function () {
if ($tool.hasClass("ai-tool-done")) {
clearInterval(timerId);
return;
}
update();
}, 1000);
$tool.data("elapsedTimer", timerId);
}
function _onToolStream(_event, data) {
const uniqueToolId = (_currentRequestId || "") + "-" + data.toolId;
_traceToolStreamCounts[uniqueToolId] = (_traceToolStreamCounts[uniqueToolId] || 0) + 1;
const $tool = $messages.find('.ai-msg-tool[data-tool-id="' + uniqueToolId + '"]');
if (!$tool.length) {
return;
}
// Update label with filename as soon as file_path is available
if (!$tool.data("labelUpdated")) {
const filePath = _extractJsonStringValue(data.partialJson, "file_path");
if (filePath) {
const fileName = filePath.split("/").pop();
const config = TOOL_CONFIG[data.toolName] || {};
$tool.find(".ai-tool-label").text((config.label || data.toolName) + " " + fileName + "...");
$tool.data("labelUpdated", true);
}
}
const preview = _extractToolPreview(data.toolName, data.partialJson);
const count = _traceToolStreamCounts[uniqueToolId];
if (count === 1) {
console.log("[AI UI]", "ToolStream first:", data.toolName, "#" + data.toolId,
"json=" + (data.partialJson || "").length + "ch");
}
if (preview) {
$tool.find(".ai-tool-preview").text(preview);
_scrollToBottom();
}
// Reset staleness timer — if no new stream event arrives within 2s,
// rotate through activity phrases so the user sees something is happening.
clearTimeout(_toolStreamStaleTimer);
clearInterval(_toolStreamRotateTimer);
_toolStreamStaleTimer = setTimeout(function () {
const phrases = [
Strings.AI_CHAT_WORKING,
Strings.AI_CHAT_WRITING,
Strings.AI_CHAT_PROCESSING
];
let idx = 0;
const $livePreview = $tool.find(".ai-tool-preview");
if ($livePreview.length && !$tool.hasClass("ai-tool-done")) {
$livePreview.text(phrases[idx]);
}
_startElapsedTimer($tool);
_toolStreamRotateTimer = setInterval(function () {
idx = (idx + 1) % phrases.length;
const $p = $tool.find(".ai-tool-preview");
if ($p.length && !$tool.hasClass("ai-tool-done")) {
$p.text(phrases[idx]);
} else {
clearInterval(_toolStreamRotateTimer);
}
}, 3000);
}, 2000);
}
/**
* Extract a complete string value for a given key from partial JSON.
* Returns null if the key isn't found or the value isn't complete yet.
*/
function _extractJsonStringValue(partialJson, key) {
// Try both with and without space after colon: "key":"val" or "key": "val"
let pattern = '"' + key + '":"';
let idx = partialJson.indexOf(pattern);
if (idx === -1) {
pattern = '"' + key + '": "';
idx = partialJson.indexOf(pattern);
}
if (idx === -1) {
return null;
}
const start = idx + pattern.length;
// Find the closing quote (not escaped)
let end = start;
while (end < partialJson.length) {
if (partialJson[end] === '"' && partialJson[end - 1] !== '\\') {
return partialJson.slice(start, end).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
end++;
}
return null; // value not complete yet
}
/**
* Extract a readable one-line preview from partial tool input JSON.
* Looks for the "interesting" key per tool type (e.g. content for Write).
*/
function _extractToolPreview(toolName, partialJson) {
if (!partialJson) {
return "";
}
// Map tool names to the key whose value we want to preview.
// Tools not listed here get no streaming preview.
const interestingKey = {
Write: "content",
Edit: "new_string",
Bash: "command",
Grep: "pattern",
Glob: "pattern",
"mcp__phoenix-editor__execJsInLivePreview": "code"
}[toolName];
if (!interestingKey) {
return "";
}
let raw = "";
// Find the interesting key and grab everything after it
const keyPattern = '"' + interestingKey + '":';
const idx = partialJson.indexOf(keyPattern);
if (idx !== -1) {
raw = partialJson.slice(idx + keyPattern.length).slice(-120);
}
// If the interesting key hasn't appeared yet, show a byte counter
// so the user sees streaming activity during the file_path phase
if (!raw && partialJson.length > 3) {
return StringUtils.format(Strings.AI_CHAT_RECEIVING_BYTES, partialJson.length);
}
if (!raw) {
return "";
}
// Clean up JSON syntax noise into readable text
let preview = raw
.replace(/\\n/g, " ")
.replace(/\\t/g, " ")
.replace(/\\"/g, '"')
.replace(/\s+/g, " ")
.trim();
// Strip leading JSON artifacts (quotes, whitespace)
preview = preview.replace(/^[\s"]+/, "");
// Strip trailing incomplete JSON artifacts
preview = preview.replace(/["{}\[\]]*$/, "").trim();
return preview;
}
function _onToolEdit(_event, data) {
const edit = data.edit;
const uniqueToolId = (_currentRequestId || "") + "-" + data.toolId;
console.log("[AI UI]", "ToolEdit:", edit.file.split("/").pop(), "#" + data.toolId);
// Track for summary card
const oldLines = edit.oldText ? edit.oldText.split("\n").length : 0;
const newLines = edit.newText ? edit.newText.split("\n").length : 0;
_currentEdits.push({
file: edit.file,
linesAdded: newLines,
linesRemoved: oldLines
});
// Capture pre-edit content for snapshot tracking
const previousContent = PhoenixConnectors.getPreviousContent(edit.file);
const isNewFile = (edit.oldText === null && (previousContent === undefined || previousContent === ""));
// On first edit per response, insert initial PUC if needed.
// Create initial snapshot *before* recordFileBeforeEdit so it pushes
// an empty {} that recordFileBeforeEdit will back-fill directly.
if (_firstEditInResponse) {
_firstEditInResponse = false;
if (SnapshotStore.getSnapshotCount() === 0) {
const initialIndex = SnapshotStore.createInitialSnapshot();
// Insert initial restore point PUC before the current tool indicator
const $puc = $(
'<div class="ai-msg ai-msg-restore-point" data-snapshot-index="' + initialIndex + '">' +
'<button class="ai-restore-point-btn" disabled>' + Strings.AI_CHAT_RESTORE_POINT + '</button>' +
'</div>'
);
$puc.find(".ai-restore-point-btn").on("click", function () {
if (!_isStreaming) {
_onRestoreClick(initialIndex);
}
});
// Find the last tool indicator and insert the PUC right before it
const $liveMsg = _$msgs();
const $lastTool = $liveMsg.find(".ai-msg-tool").last();
if ($lastTool.length) {
$lastTool.before($puc);
} else {
$liveMsg.append($puc);
}
}
}
// Record pre-edit content into pending snapshot and back-fill
SnapshotStore.recordFileBeforeEdit(edit.file, previousContent, isNewFile);
// Find the oldest Edit/Write tool indicator for this file that doesn't
// already have edit actions. This is more robust than matching by toolId
// because the SDK with includePartialMessages may re-emit tool_use blocks
// as phantom indicators, causing toolId mismatches.
const fileName = edit.file.split("/").pop();
const $tool = $messages.find('.ai-msg-tool').filter(function () {
const label = $(this).find(".ai-tool-label").text();
const hasActions = $(this).find(".ai-tool-edit-actions").length > 0;
return !hasActions && (label.includes("Edit " + fileName) || label.includes("Write " + fileName));
}).first();
if (!$tool.length) {
return;
}
// Remove any existing edit actions (in case of duplicate events)
$tool.find(".ai-tool-edit-actions").remove();
// Build the inline edit actions (diff toggle only — undo is on summary card)
const $actions = $('<div class="ai-tool-edit-actions"></div>');
// Diff toggle
const $diffToggle = $('<button class="ai-tool-diff-toggle">' + Strings.AI_CHAT_SHOW_DIFF + '</button>');
const $diff = $('<div class="ai-tool-diff"></div>');
if (edit.oldText) {
edit.oldText.split("\n").forEach(function (line) {
$diff.append($('<div class="ai-diff-old"></div>').text("- " + line));
});
edit.newText.split("\n").forEach(function (line) {
$diff.append($('<div class="ai-diff-new"></div>').text("+ " + line));
});
} else {
// Write (new file) — show all as new
edit.newText.split("\n").forEach(function (line) {
$diff.append($('<div class="ai-diff-new"></div>').text("+ " + line));
});
}
$diffToggle.on("click", function () {
$diff.toggleClass("expanded");
$diffToggle.text($diff.hasClass("expanded") ? Strings.AI_CHAT_HIDE_DIFF : Strings.AI_CHAT_SHOW_DIFF);
});
$actions.append($diffToggle);
$tool.append($actions);
$tool.append($diff);
_scrollToBottom();
}
function _onError(_event, data) {
console.log("[AI UI]", "Error:", (data.error || "").slice(0, 200));
_appendErrorMessage(data.error);
// Don't stop streaming — the node side may continue (partial results)
}
async function _onComplete(_event, data) {
console.log("[AI UI]", "Complete. textChunks=" + _traceTextChunks,
"toolStreams=" + JSON.stringify(_traceToolStreamCounts));
// Reset trace counters for next query
_traceTextChunks = 0;
_traceToolStreamCounts = {};
// Append edit summary if there were edits (finalizeResponse called inside)
if (_currentEdits.length > 0) {
await _appendEditSummary();
}
SnapshotStore.stopTracking();
_setStreaming(false);
}
/**
* Append a compact summary card showing all files modified during this response.
*/
async function _appendEditSummary() {
// Finalize snapshot and get the after-snapshot index
const afterIndex = await SnapshotStore.finalizeResponse();
_undoApplied = false;
// Aggregate per-file stats
const fileStats = {};
const fileOrder = [];
_currentEdits.forEach(function (e) {
if (!fileStats[e.file]) {
fileStats[e.file] = { added: 0, removed: 0 };
fileOrder.push(e.file);
}
fileStats[e.file].added += e.linesAdded;
fileStats[e.file].removed += e.linesRemoved;
});
const fileCount = fileOrder.length;
const $summary = $('<div class="ai-msg ai-msg-edit-summary" data-snapshot-index="' + afterIndex + '"></div>');