Repository navigation
Expand file tree
/
Copy patheca-chat.el
More file actions
7153 lines (6592 loc) · 331 KB
/
Copy patheca-chat.el
File metadata and controls
7153 lines (6592 loc) · 331 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
;;; eca-chat.el --- ECA (Editor Code Assistant) chat -*- lexical-binding: t; -*-
;; Copyright (C) 2025 Eric Dallo
;;
;; SPDX-License-Identifier: Apache-2.0
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;; The ECA (Editor Code Assistant) chat.
;;
;;; Code:
(require 'f)
(require 'find-func)
(require 'markdown-mode)
(require 'compat)
(require 'text-property-search)
(require 'eca-util)
(require 'eca-api)
(require 'eca-mcp)
(require 'eca-diff)
(require 'eca-table)
(require 'eca-chat-expandable)
(require 'eca-chat-context)
(require 'eca-chat-image)
(require 'evil nil t)
;; Variables
(eval-and-compile
(defcustom eca-chat-parent-mode 'gfm-mode
"The parent mode to eca-chat-mode inherit."
:type 'symbol
:group 'eca))
(defcustom eca-chat-mode-hook '()
"Hooks to run after entering in eca chat mode hook."
:type 'hook
:group 'eca)
(defcustom eca-chat-finished-hook nil
"List of functions to be called after ECA chat is finished.
For when chat went back to idle state."
:type 'hook
:group 'eca)
(defcustom eca-chat-tool-call-functions nil
"Abnormal hook run when a tool call changes state in a live chat.
Each function is called with SESSION and CONTENT, the raw tool call
content plist whose `:type' is one of \"toolCallRun\",
\"toolCallRunning\", \"toolCalled\" or \"toolCallRejected\". CONTENT
also carries `:id', `:name', `:server', `:arguments' and `:details';
for file edits `:details' has `:type' \"fileChange\" plus `:path',
`:diff', `:linesAdded' and `:linesRemoved'. Functions run with the
chat buffer current after the content was rendered, and only for live
notifications, not when history is loaded. Errors are demoted so they
never break chat rendering."
:type 'hook
:group 'eca)
(defcustom eca-chat-auto-revert-changed-files t
"Whether to revert buffers visiting files edited by ECA tool calls.
When non-nil, once a tool call that changes a file finishes, the buffer
visiting that file is reverted from disk so it shows the new content,
like `auto-revert-mode' would but without waiting for its polling.
Buffers with unsaved changes are never reverted, so no edit is lost;
Emacs then asks about the file having changed on disk on the next save."
:type 'boolean
:group 'eca)
(defvar eca-chat-session-status-changed-functions nil
"Abnormal hook run when a session aggregated status may have changed.
Each function is called with a single argument, the session. It is
invoked on transitions that can change `eca-chat-session-status' (a chat
starting or finishing, a tool call requesting or resolving an approval, a
question being asked or answered). Subscribers should be idempotent: the
hook may run even when the status is unchanged. Used by integrations
such as the Doom workspaces tabline to refresh external indicators.")
(defvar eca-chat-content-received-functions nil
"Abnormal hook run for every `chat/contentReceived' notification.
Each function is called with SESSION and PARAMS (the raw notification
plist carrying :chatId, :role and :content) before the content is
rendered in the chat buffer. Errors in subscribers are demoted so
they never break chat rendering. Used by integrations such as
`eca-chat-inline' to mirror streamed content elsewhere.")
(defvar eca-chat-deleted-functions nil
"Abnormal hook run after a chat deletion is processed.
Each function is called with SESSION and CHAT-ID after the chat is
removed from the session registry and its buffer killed, when it
was known; the hook runs even for chat ids unknown to the client.")
(defcustom eca-chat-window-side 'right
"Where the ECA chat window should appear.
Can be `'left', `'right', `'top', `'bottom', or nil. When nil, a chat
that is not already visible on the selected frame opens in the selected
window. A visible chat on that frame remains in its existing window.
Dedicated and minibuffer windows cannot be reused. Otherwise,
`eca-chat-use-side-window' controls whether the chat uses a dedicated
side window or a regular directional window."
:type '(choice (const :tag "Current window" nil)
(const :tag "Left" left)
(const :tag "Right" right)
(const :tag "Top" top)
(const :tag "Bottom" bottom))
:group 'eca)
(defcustom eca-chat-window-width 0.40
"Width of ECA chat windows opened on the left or right."
:type 'number
:group 'eca)
(defcustom eca-chat-window-height 0.30
"Height of ECA chat windows opened on the top or bottom."
:type 'number
:group 'eca)
(defcustom eca-chat-use-side-window t
"Whether to display ECA chat in a dedicated side window.
When non-nil (default), ECA chat opens in a dedicated side window.
When nil, it opens in a regular directional window. This setting is
ignored when `eca-chat-window-side' is nil, which displays the chat in
the selected window."
:type 'boolean
:group 'eca)
(defcustom eca-chat-focus-on-open t
"Whether to focus the ECA chat window when it opens.
This has no effect when a new chat replaces the selected window because
that window is already focused."
:type 'boolean
:group 'eca)
(defcustom eca-chat-prompt-separator "\n---"
"The separator text between chat and prompt area."
:type 'string
:group 'eca)
(defcustom eca-chat-prompt-prefix "> "
"The prompt prefix string used in eca chat buffer."
:type 'string
:group 'eca)
(defcustom eca-chat-read-only-history t
"When non-nil, make the chat history/output area read-only.
Only the prompt block at the bottom stays editable, which prevents
accidental edits to previous messages and assistant output. Set
to nil to keep the whole chat buffer writable."
:type 'boolean
:group 'eca)
(defcustom eca-chat-prompt-prefix-loading "⏳ "
"The prompt prefix string used in eca chat buffer when loading."
:type 'string
:group 'eca)
(defcustom eca-chat-prompt-prefix-question "Answer> "
"The prompt prefix string used when a question is pending."
:type 'string
:group 'eca)
(defcustom eca-chat-mcp-tool-call-loading-symbol "⏳"
"The string used in eca chat buffer for mcp tool calls while loading."
:type 'string
:group 'eca)
(defcustom eca-chat-mcp-tool-call-pending-approval-symbol "🚧"
"The string used in eca chat buffer for mcp tool calls waiting for approval."
:type 'string
:group 'eca)
(defcustom eca-chat-mcp-tool-call-error-symbol "❌"
"The string used in eca chat buffer for mcp tool calls when error."
:type 'string
:group 'eca)
(defcustom eca-chat-mcp-tool-call-success-symbol "✅"
"The string used in eca chat buffer for mcp tool calls when success."
:type 'string
:group 'eca)
(defcustom eca-chat-trust-on-symbol "🔥"
"The string used in eca chat buffer mode-line when trust is ON."
:type 'string
:group 'eca)
(defcustom eca-chat-trust-off-symbol "🛡️"
"The string used in eca chat buffer mode-line when trust is OFF."
:type 'string
:group 'eca)
(defcustom eca-chat-trust-on-symbol-tty "●"
"Mode-line trust ON glyph used on terminal (non-graphic) frames."
:type 'string
:group 'eca)
(defcustom eca-chat-trust-off-symbol-tty "○"
"Mode-line trust OFF glyph used on terminal (non-graphic) frames."
:type 'string
:group 'eca)
(defcustom eca-chat-expand-pending-approval-tools t
"Whether to auto expand tool calls when pending approval."
:type 'boolean
:group 'eca)
(defcustom eca-chat-shrink-called-tools t
"Whether to auto shrink tool calls after called."
:type 'boolean
:group 'eca)
(defcustom eca-chat-tab-line t
"Whether to show a tab line with chat tabs at the top of each chat window.
When non-nil, enables `tab-line-mode' in chat buffers with tabs
for every open chat in the session. Each tab shows the chat status
\(pending approval, loading), title and elapsed time."
:type 'boolean
:group 'eca)
(defcustom eca-chat-tab-line-close-button-show t
"Whether to show close buttons on ECA chat tab-line tabs.
When nil, chat tabs are still shown but the close button is hidden."
:type 'boolean
:group 'eca)
(defcustom eca-chat-custom-model nil
"Which model to use during chat, nil means use server's default.
Must be a valid model supported by server, check `eca-chat-select-model`."
:type 'string
:group 'eca)
(defcustom eca-chat-custom-agent nil
"Which chat agent to use, if nil use server's default."
:type 'string
:group 'eca)
(defcustom eca-chat-trust-enable nil
"When non-nil, auto-accept all tool calls."
:type 'boolean
:group 'eca)
(defcustom eca-chat-usage-string-format '(:session-tokens " / " :context-limit " (" :session-cost ")")
"Format to show about chat usage tokens/costs."
:type '(repeat
(choice
(string :tag "any string like separators")
(const :tag "Total tokens sent + received" :session-tokens)
(const :tag "Total session cost" :session-cost)
(const :tag "The context limit" :context-limit)
(const :tag "The output limit" :output-limit)
(const :tag "Last message cost" :last-message-cost)
(const :tag "The percentage of context limt used in the current session" :session-tokens-percentage)))
:group 'eca)
(defcustom eca-chat-mode-line-format
'(:workspace-folders :add-workspace-button :remove-workspace-button :spacer :init-progress " " :bg-jobs " " :elapsed-time " " :context-bar :usage " " :trust)
"Format for the ECA chat mode line.
When set to a list, each element is a module keyword or a
literal string. Modules are rendered in order; use `:spacer'
to separate left-aligned and right-aligned content.
Available modules:
`:workspace-folders' - project root paths
`:add-workspace-button' - clickable [+] button
`:remove-workspace-button' - clickable [-] button
`:title' - chat title
`:elapsed-time' - turn duration timer
`:context-bar' - colored context-window usage bar (hover for details)
`:usage' - token/cost info (see `eca-chat-usage-string-format')
`:server-version' - shows \"ECA <version>\"
`:init-progress' - init progress (auto-hides when done)
`:trust' - trust mode indicator (🔥 when ON, 🛡 when OFF)
`:spacer' - elastic space that right-aligns everything after it
When set to a function, it receives the session as its sole
argument and should return a valid `mode-line-format' value.
The function is called once at buffer creation; include
`:eval' forms in the result for dynamic content.
This gives full control for powerline or doom-modeline users."
:type '(choice
(repeat
(choice
(string :tag "Literal string")
(const :tag "Workspace folders" :workspace-folders)
(const :tag "Add workspace button" :add-workspace-button)
(const :tag "Remove workspace button" :remove-workspace-button)
(const :tag "Background jobs" :bg-jobs)
(const :tag "Chat title" :title)
(const :tag "Elapsed time" :elapsed-time)
(const :tag "Context usage bar" :context-bar)
(const :tag "Usage info" :usage)
(const :tag "ECA server version" :server-version)
(const :tag "Init progress" :init-progress)
(const :tag "Trust mode indicator" :trust)
(const :tag "Right-align spacer" :spacer)))
(function :tag "Custom function (receives session)"))
:group 'eca)
(defcustom eca-chat-override-mode-line t
"When non-nil, ECA chat sets a custom mode line for chat buffers.
Set this to nil to keep the default Emacs mode line (including buffer name)."
:type 'boolean
:group 'eca)
(defcustom eca-chat-diff-tool 'smerge
"Select the method for displaying file-change diffs in ECA chat."
:type '(choice (const :tag "Side-by-side Ediff" ediff)
(const :tag "Merge-style Smerge" smerge))
:group 'eca)
(defcustom eca-chat-tool-call-prepare-throttle 'smart
"Throttle strategy for handling `toolCallPrepare` events.
Possible values: `all` or `smart` (default)."
:type '(choice (const :tag "Process all updates" all)
(const :tag "Smart throttle" smart))
:group 'eca)
(defcustom eca-chat-tool-call-prepare-update-interval 5
"When `smart`, process every Nth `toolCallPrepare` update.
Must be a positive integer."
:type 'integer
:group 'eca)
(defcustom eca-chat-stream-flush-interval 0.05
"Seconds to buffer assistant text chunks before rendering.
Default is 0.05. When nil, assistant text renders immediately.
When set to a non-negative number, top-level assistant text chunks
are combined and rendered on a timer."
:type '(choice (const :tag "Immediate rendering" nil)
(number :tag "Seconds"))
:group 'eca)
(defcustom eca-chat-fontify-debounce-interval 0.15
"Idle delay in seconds before a deferred fontify runs during streaming.
Instead of calling `font-lock-ensure' on every streamed chunk,
`eca-chat--render-content' schedules it via an idle timer with this
delay. A single guaranteed `font-lock-ensure' always runs when the
response finishes, before table alignment.
When nil, no intermediate fontify is scheduled and the buffer is
only fontified at end-of-stream (jit-lock still handles visible-area
updates during streaming)."
:type '(choice (const :tag "Disabled (final ensure only)" nil)
(number :tag "Seconds"))
:group 'eca)
(defcustom eca-chat-hide-markdown-markup t
"Whether ECA chat renders `markdown-markup' as invisible.
When non-nil, preserve the historical hidden-markup look. When
nil, keep markup visible while leaving `markdown-hide-markup'
enabled. This is recommended if fenced code blocks jump while
typing or streaming."
:type 'boolean
:group 'eca)
(defcustom eca-chat-fontify-prompt t
"Whether ECA chat applies Markdown fontification to prompt text.
When non-nil, preserve the historical prompt rendering behavior.
When nil, prompt edits skip Markdown block scans over chat history.
Set this to nil if typing in large ECA chat buffers is slow."
:type 'boolean
:group 'eca)
(defun eca-chat--apply-markdown-markup-visibility ()
"Apply `eca-chat-hide-markdown-markup' in current buffer."
(if eca-chat-hide-markdown-markup
(add-to-invisibility-spec 'markdown-markup)
(remove-from-invisibility-spec 'markdown-markup)))
(defvar-local eca-chat--syntax-propertize-function nil
"Original syntax propertizer wrapped by ECA chat.")
(defun eca-chat--fontification-history-end (end)
"Return END clipped at the prompt when prompt fontification is nil."
(if eca-chat-fontify-prompt
end
(if-let* ((prompt-start (eca-chat--prompt-area-start-point)))
(min end prompt-start)
end)))
(defun eca-chat--syntax-propertize (beg end)
"Apply syntax properties from BEG to END, respecting prompt settings."
(let ((fontify-end (eca-chat--fontification-history-end end)))
(when (and eca-chat--syntax-propertize-function
(< beg fontify-end))
(funcall eca-chat--syntax-propertize-function beg fontify-end))))
(defun eca-chat--font-lock-extend-region-function (beg end old-len)
"Extend Markdown font-lock region from BEG to END with OLD-LEN."
(when (fboundp 'markdown-font-lock-extend-region-function)
(if eca-chat-fontify-prompt
(markdown-font-lock-extend-region-function beg end old-len)
(let ((fontify-end (eca-chat--fontification-history-end end)))
(when (< beg fontify-end)
(markdown-font-lock-extend-region-function
beg fontify-end old-len))))))
(defun eca-chat--syntax-propertize-extend-region-function (beg end)
"Extend Markdown syntax region from BEG to END, respecting prompt."
(when (fboundp 'markdown-syntax-propertize-extend-region)
(if eca-chat-fontify-prompt
(markdown-syntax-propertize-extend-region beg end)
(if-let* ((prompt-start (eca-chat--prompt-area-start-point)))
(when (<= end prompt-start)
(save-restriction
(narrow-to-region (point-min) prompt-start)
(markdown-syntax-propertize-extend-region beg end)))
(markdown-syntax-propertize-extend-region beg end)))))
(defun eca-chat--install-fontification-overrides ()
"Install ECA chat fontification wrappers in current buffer."
(unless (eq syntax-propertize-function #'eca-chat--syntax-propertize)
(setq-local eca-chat--syntax-propertize-function syntax-propertize-function)
(setq-local syntax-propertize-function #'eca-chat--syntax-propertize))
(remove-hook 'syntax-propertize-extend-region-functions
#'markdown-syntax-propertize-extend-region t)
(add-hook 'syntax-propertize-extend-region-functions
#'eca-chat--syntax-propertize-extend-region-function nil t)
(remove-hook 'jit-lock-after-change-extend-region-functions
#'markdown-font-lock-extend-region-function t)
(add-hook 'jit-lock-after-change-extend-region-functions
#'eca-chat--font-lock-extend-region-function t t)
(setq-local font-lock-fontify-region-function #'eca-chat--fontify-region))
(defvar-local eca-chat--tool-call-prepare-counters (make-hash-table :test 'equal)
"Hash table mapping toolCall ID to message count.")
(defvar-local eca-chat--tool-call-prepare-content-cache (make-hash-table :test 'equal)
"Hash table mapping toolCall ID to accumulated argument text.")
(defvar-local eca-chat--pending-approvals-cache 'dirty
"Cached result of `eca-chat--has-pending-approvals-p'.
Either a boolean or the symbol `dirty' when the buffer must be
rescanned.")
(defvar eca-chat--tab-line-cache-by-session
(make-hash-table :test 'eq :weakness 'key)
"Stable chat tab-line descriptors keyed by session.")
(defun eca-chat--invalidate-pending-approvals-cache ()
"Mark the pending approvals cache of the current buffer stale."
(setq-local eca-chat--pending-approvals-cache 'dirty))
(defun eca-chat--invalidate-tab-line-cache (&optional session)
"Invalidate stable tab-line cache for SESSION.
When SESSION is nil, use the current buffer session if available."
(when-let* ((target (or session (ignore-errors (eca-session)))))
(remhash target eca-chat--tab-line-cache-by-session)))
(add-hook 'eca-session-deleting-functions
#'eca-chat--invalidate-tab-line-cache)
(defcustom eca-chat-tool-call-approval-content-size 0.9
"The size of font of tool call approval."
:type 'number
:group 'eca)
(defcustom eca-chat-save-chat-initial-path 'workspace-root
"The initial path to show in the `eca-chat-save-to-file' prompt."
:type '(choice
(const :tag "Workspace root" workspace-root)
(string :tag "Custom path"))
:group 'eca)
(defcustom eca-chat-table-beautify t
"When non-nil, apply enhanced visual styling to markdown tables.
Adds header highlighting, dimmed separators, zebra-striped rows,
and subtler pipe characters. Only affects visual presentation via
overlays — the underlying buffer text is unchanged, so copy/paste
works normally."
:type 'boolean
:group 'eca)
(defcustom eca-chat-history-page-size 50
"Number of newest messages to load when opening a persisted chat.
When non-nil, `eca-chat-resume' opens chats with a bounded window of the
newest messages and shows a \"Load older messages\" control to page
through earlier history on demand, avoiding a full replay of very long
chats. When nil, the entire history is replayed on open (legacy
behavior)."
:type '(choice (const :tag "Full replay (no pagination)" nil)
(integer :tag "Newest messages per page"))
:group 'eca)
;; Faces
(defface eca-chat-prompt-prefix-face
'((((background dark)) (:foreground "lime green" :weight bold))
(((background light)) (:foreground "dark green" :weight bold)))
"Face for the `eca-chat-prompt-prefix`."
:group 'eca)
(defface eca-chat-prompt-stop-face
'((t (:inherit error :underline t :weight bold)))
"Face for the stop action when loading."
:group 'eca)
(defface eca-chat-queued-prompt-face
'((t :inherit font-lock-comment-face :slant italic :underline nil))
"Face for the queued prompt indicator."
:group 'eca)
(defface eca-chat-steer-prompt-face
'((t :inherit font-lock-keyword-face :slant italic :underline nil))
"Face for the steer prompt indicator."
:group 'eca)
(defface eca-chat-tool-call-approval-content-face
`((t :height ,eca-chat-tool-call-approval-content-size))
"Face for the MCP tool calls approval content in chat."
:group 'eca)
(defface eca-chat-tool-call-accept-face
`((t (:inherit success :height ,eca-chat-tool-call-approval-content-size :underline t :weight bold)))
"Face for the accept tool call action."
:group 'eca)
(defface eca-chat-tool-call-accept-and-remember-face
`((t (:inherit success :height ,eca-chat-tool-call-approval-content-size :underline t :weight bold)))
"Face for the accept and remember tool call action."
:group 'eca)
(defface eca-chat-tool-call-reject-face
`((t (:inherit error :height ,eca-chat-tool-call-approval-content-size :underline t :weight bold)))
"Face for the cancel tool call action."
:group 'eca)
(defface eca-chat-tool-call-keybinding-face
`((t :inherit font-lock-comment-face :height ,eca-chat-tool-call-approval-content-size))
"Face for the tool call keybinding in chat."
:group 'eca)
(defface eca-chat-tool-call-spacing-face
`((t :height ,eca-chat-tool-call-approval-content-size))
"Face for the tool call spacing in chat."
:group 'eca)
(defface eca-chat-diff-view-face
'((((background dark)) (:foreground "dodger blue" :underline t :weight bold))
(((background light)) (:foreground "blue3" :underline t :weight bold)))
"Face for the diff view button."
:group 'eca)
(defface eca-chat-title-face
'((t :height 0.9))
"Face for the chat title."
:group 'eca)
(defface eca-chat-user-messages-face
'((t :inherit eca-chat-expandable-block-1-face :weight bold :extend t))
"Face for the user sent messages in chat.
Bold on the theme-derived block background, so each turn stands out
from the assistant text and matches the expanded rollback area below
the message. Falls back to plain bold where no background is
available (TTY)."
:group 'eca)
(defface eca-chat-rollback-face
'((t (:inherit eca-chat-user-messages-face
:weight bold
:underline t)))
"Face for the rollback button."
:group 'eca)
(defface eca-chat-system-messages-face
'((t :inherit font-lock-builtin-face))
"Face for the system messages in chat."
:group 'eca)
(defface eca-chat-reason-label-face
'((t :inherit font-lock-comment-face))
"Face for the reason messages in chat."
:group 'eca)
(defface eca-chat-hook-label-face
'((t :inherit font-lock-keyword-face))
"Face for the hook messages in chat."
:group 'eca)
(defface eca-chat-time-face
'((t :inherit font-lock-comment-face :slant italic :height 0.8))
"Face for times spent in chat."
:group 'eca)
(defface eca-chat-mcp-tool-call-label-face
'((t :inherit font-lock-function-call-face))
"Face for the MCP tool calls in chat."
:group 'eca)
(defface eca-chat-subagent-tool-call-label-face
'((t :inherit font-lock-constant-face))
"Face for subagent tool call labels in chat."
:group 'eca)
(defface eca-chat-subagent-steps-info-face
'((t :inherit font-lock-comment-face :slant italic :height 0.9))
"Face for the steps done by subagent."
:group 'eca)
(defface eca-chat-file-change-label-face
'((t :inherit diff-file-header))
"Face for file changes labels in chat."
:group 'eca)
(defface eca-chat-file-path-face
'((t :inherit link))
"Face for file paths in chat."
:group 'eca)
(defface eca-chat-shell-command-face
'((t :weight bold))
"Face for breakdown commands that can never be auto-approved."
:group 'eca)
(defface eca-chat-shell-command-remembered-face
'((t :inherit success :weight bold))
"Face for breakdown commands already approved or remembered."
:group 'eca)
(defface eca-chat-shell-command-not-remembered-face
'((t :inherit warning :weight bold))
"Face for breakdown commands whose approval is not remembered yet."
:group 'eca)
(defface eca-chat-shell-command-breakdown-prefix-face
'((t :inherit font-lock-comment-face))
"Face for the prefix of derived lines in shell command breakdowns."
:group 'eca)
(defface eca-chat-shell-command-always-asks-face
'((t :inherit font-lock-comment-face :slant italic :height 0.9))
"Face for the annotation of commands that always ask for approval."
:group 'eca)
(defface eca-chat--tool-call-table-key-face
'((t :height 0.9 :inherit font-lock-comment-face))
"Face for the MCP tool call table keys in chat."
:group 'eca)
(defface eca-chat--tool-call-argument-key-face
'()
"Face for the MCP tool calls's argument key in chat."
:group 'eca)
(defface eca-chat--tool-call-argument-value-face
'((t :weight bold))
"Face for the MCP tool calls's argument value in chat."
:group 'eca)
(defface eca-chat-task-prefix-face
'((t :inherit font-lock-operator-face :slant italic))
"Face for the task text prefix in task label."
:group 'eca)
(defface eca-chat-task-label-face
'((t :height 0.9))
"Face for the task area label in chat."
:group 'eca)
(defface eca-chat-task-label-in-progress-face
'((t :inherit font-lock-string-face))
"Face for the task area label when a task is in progress."
:group 'eca)
(defface eca-chat-task-in-progress-face
'((t :inherit font-lock-string-face :weight bold))
"Face for in-progress tasks in the task area."
:group 'eca)
(defface eca-chat-task-progress-face
'((t :inherit font-lock-comment-face :slant italic :height 0.9))
"Face for the progress counter (e.g. 1/5) in the task label."
:group 'eca)
(defface eca-chat-task-done-face
'((t :inherit font-lock-comment-face :strike-through t))
"Face for completed tasks in the task area."
:group 'eca)
(defface eca-chat-welcome-face
'((t :inherit font-lock-builtin-face))
"Face for the welcome message in chat."
:group 'eca)
(defface eca-chat-resume-link-face
'((((background dark)) (:foreground "deep sky blue" :underline t))
(((background light)) (:foreground "dark cyan" :underline t)))
"Face for the resume session link in the welcome area."
:group 'eca)
(defface eca-chat-load-more-face
'((((background dark)) (:foreground "deep sky blue" :underline t))
(((background light)) (:foreground "dark cyan" :underline t)))
"Face for the \"Load older messages\" control in the chat."
:group 'eca)
(defface eca-chat-option-key-face
'((t :inherit font-lock-doc-face))
"Face for the option keys in header-line of the chat."
:group 'eca)
(defface eca-chat-option-value-face
'((t :weight bold))
"Face for the option values in header-line of the chat."
:group 'eca)
(defface eca-chat-trust-on-face
'((t :weight bold :inherit 'error))
"Face for trust mode when on in mode-line."
:group 'eca)
(defface eca-chat-trust-off-face
'((t :inherit shadow))
"Face for trust mode when off in mode-line."
:group 'eca)
(defface eca-chat-usage-string-face
'((t :height 0.9 :inherit font-lock-doc-face))
"Face for the strings segments in usage string in mode-line of the chat."
:group 'eca)
(defface eca-chat-context-system-prompt-face
'((((background dark)) (:foreground "#61afef"))
(((background light)) (:foreground "#2c6fbf")))
"Face for the system-prompt segment of the context-usage bar."
:group 'eca)
(defface eca-chat-context-tool-definitions-face
'((((background dark)) (:foreground "#e8924a"))
(((background light)) (:foreground "#c2772e")))
"Face for the tool-definitions segment of the context-usage bar."
:group 'eca)
(defface eca-chat-context-conversation-face
'((((background dark)) (:foreground "#98c379"))
(((background light)) (:foreground "#4f8f2f")))
"Face for the conversation segment of the context-usage bar."
:group 'eca)
(defface eca-chat-context-rules-face
'((((background dark)) (:foreground "#c678dd"))
(((background light)) (:foreground "#8a3fa0")))
"Face for the rules segment of the context-usage bar."
:group 'eca)
(defface eca-chat-context-skills-face
'((((background dark)) (:foreground "#e5c07b"))
(((background light)) (:foreground "#b58900")))
"Face for the skills segment of the context-usage bar."
:group 'eca)
(defface eca-chat-context-agents-face
'((((background dark)) (:foreground "#d19a66"))
(((background light)) (:foreground "#b5651d")))
"Face for the AGENTS.md segment of the context-usage bar."
:group 'eca)
(defface eca-chat-context-tool-calls-face
'((((background dark)) (:foreground "#e06c75"))
(((background light)) (:foreground "#c0392b")))
"Face for the tool-calls segment of the context-usage bar."
:group 'eca)
(defface eca-chat-context-free-face
'((t :inherit shadow))
"Face for the free-space segment of the context-usage bar."
:group 'eca)
(defface eca-chat-context-compaction-marker-face
'((((background dark)) (:foreground "#d7dae0"))
(((background light)) (:foreground "#383a42")))
"Face for the auto-compaction threshold marker on the context bar.
Its foreground is also used as the marker color in graphical frames."
:group 'eca)
(defface eca-chat-elapsed-time-face
'((t :height 0.9 :inherit font-lock-comment-face))
"Face for the elapsed time indicator in mode-line of the chat."
:group 'eca)
(defface eca-chat-command-description-face
'((t :inherit font-lock-comment-face))
"Face for the descriptions in chat command completion."
:group 'eca)
(defface eca-chat-approval-modeline-face
'((((background dark)) :background "#4a4000")
(((background light)) :background "#fff8dc"))
"Face for modeline when approval is pending."
:group 'eca)
(defface eca-tab-inactive-face
'((t :inherit shadow))
"Face for non-selected idle tab-line tabs."
:group 'eca)
(defface eca-chat-tab-active-face
'((t :inherit warning))
"Face for selected active chat tabs.
Active means loading or pending approval."
:group 'eca)
(defface eca-chat-tab-inactive-active-face
'((((background dark)) :foreground "#b8860b")
(((background light)) :foreground "#8b6914"))
"Face for non-selected active chat tabs.
A dimmer yellow for loading/approval tabs that
are not currently selected."
:group 'eca)
(defface eca-chat-flag-face
'((t :inherit font-lock-number-face))
"Face for flag markers in chat."
:group 'eca)
(defface eca-chat-question-face
'((t :inherit font-lock-string-face :weight bold))
"Face for the question text in ask-question blocks."
:group 'eca)
(defface eca-chat-question-option-face
'((t :inherit font-lock-function-name-face :underline t))
"Face for selectable option labels in ask-question blocks."
:group 'eca)
(defface eca-chat-question-description-face
'((t :inherit font-lock-comment-face))
"Face for option descriptions in ask-question blocks."
:group 'eca)
;; Internal
(defvar-local eca-chat--closed nil)
(defvar-local eca-chat--history '())
(defvar-local eca-chat--history-index -1)
(defvar-local eca-chat--welcome-shown nil
"Non-nil when this buffer still displays the welcome banner.
Set when the welcome message and resume link are inserted in
`eca-chat-mode'; cleared by `eca-chat--clear'. Used to decide
whether the first user prompt should erase the banner first.")
(defvar-local eca-chat--prompt-after-clear nil
"Prompt text to restore after the next server-initiated clear.
Set by `eca-chat--rollback' so the rolled-back user message and
any prompt draft survive the `chat/cleared' redraw; consumed
once by `eca-chat-cleared'.")
(defvar-local eca-chat--id nil)
(defvar-local eca-chat--title nil)
(defvar-local eca-chat--custom-title nil)
(defvar-local eca-chat--selected-model nil)
(defvar-local eca-chat--selected-agent nil)
(defvar-local eca-chat--selected-variant nil)
(defvar-local eca-chat--available-variants nil)
(defvar-local eca-chat--selected-trust nil)
(defvar-local eca-chat--last-request-id 0)
(defvar-local eca-chat--spinner-string "")
(defvar-local eca-chat--spinner-timer nil)
(defvar-local eca-chat--prompt-start-time nil
"Start time of the current prompt, from `current-time'.")
(defvar-local eca-chat--turn-duration-secs nil
"Duration in seconds of the last completed turn.")
(defvar-local eca-chat--modeline-timer nil
"Timer that refreshes the mode-line every second during loading.")
(defvar-local eca-chat--tool-call-elapsed-times (make-hash-table :test 'equal)
"Mapping tool-call ID to `current-time' when toolCallRunning was received.")
(defvar-local eca-chat--tool-call-elapsed-timer nil
"Repeating timer that updates elapsed-time display for running tool calls.")
(defvar-local eca-chat--table-resize-timer nil)
(defvar-local eca-chat--stream-pending-chunks nil
"Pending top-level assistant text chunks for buffered stream rendering.")
(defvar-local eca-chat--stream-flush-timer nil
"Timer that flushes pending assistant stream text.")
(defvar-local eca-chat--fontify-timer nil
"Idle timer that defers `font-lock-ensure' during streaming.")
(defvar-local eca-chat--progress-text "")
(defvar-local eca-chat--last-user-message-pos nil)
(defvar-local eca-chat--last-response-copy-start nil
"Buffer position where the latest assistant response starts.")
(defvar-local eca-chat--last-response-copy-kind nil
"Kind of latest top-level assistant content for copy scoping.")
(defvar-local eca-chat--chat-loading nil)
(defvar-local eca-chat--session-cost nil)
(defvar-local eca-chat--message-cost nil)
(defvar-local eca-chat--message-input-tokens nil)
(defvar-local eca-chat--message-output-tokens nil)
(defvar-local eca-chat--session-tokens nil)
(defvar-local eca-chat--session-limit-context nil)
(defvar-local eca-chat--session-limit-output nil)
(defvar-local eca-chat--session-auto-compact-percentage nil
"Context-window percentage at which the server auto-compacts.
Nil when auto-compaction is disabled or unknown.")
(defvar-local eca-chat--context-breakdown nil
"Latest context-window usage breakdown plist for the current chat.
Keys: :categories (vector of :name/:tokens plists), :usedTokens,
:freeTokens and :contextLimit, as sent in the `usage' content.")
(defvar-local eca-chat--context-bar-cache-key nil
"Cache key for the rendered context-usage mode-line bar.")
(defvar-local eca-chat--context-bar-cache-value nil
"Cached rendered context-usage mode-line bar string.")
(defvar-local eca-chat--queued-prompt nil)
(defvar-local eca-chat--steered-prompt nil)
(defvar-local eca-chat--subagent-chat-id->tool-call-id (make-hash-table :test 'equal)
"Hash table mapping subagent chatId to the parent tool call expandable block id.")
(defvar-local eca-chat--subagent-usage (make-hash-table :test 'equal)
"Hash table mapping tool-call-id to a plist (:session-tokens N :context-limit N).
Stores the latest usage data received for each running subagent.")
(defvar-local eca-chat--history-before-cursor nil
"Opaque cursor for loading the older history page, or nil at the start.")
(defvar-local eca-chat--history-after-cursor nil
"Opaque cursor for loading the newer history page, or nil at the tail.")
(defvar-local eca-chat--history-compaction-cursor nil
"Opaque cursor at the last compaction boundary, or nil when never compacted.")
(defvar-local eca-chat--history-total nil
"Total number of messages in the full chat history, from pagination meta.")
(defvar-local eca-chat--history-loading nil
"Non-nil while an older-history page request is in flight.")
(defvar-local eca-chat--server-version nil
"Cached ECA server version string for mode-line display.")
(defvar-local eca-chat--task-state nil
"Current task state plist with :goal and :tasks.
Each task is a plist with :id, :content, :status, :priority, etc.")
(defvar-local eca-chat--stopping-safety-timer nil
"Safety timer to force-clear \='stopping state.
Used when server never responds to stop request.")
(defvar-local eca-chat--pending-questions nil
"Unanswered questions, oldest first.
Parallel `ask_user' tool calls leave several pending at once. Each
is a plist with :session :request :question :options :tool-call-id
:allow-freeform, and :block-ov, the overlay of its block when it has
no tool call block to render in.")
;; Buffer-local caches for singleton overlays. The chat buffer
;; contains a fixed set of overlays that are created once at chat
;; setup (prompt-area, prompt-field, progress-area, context-area,
;; task-area). Each lookup
;; historically scanned every overlay in the buffer via
;; `(overlays-in (point-min) (point-max))', which scales linearly
;; with chat length and is exercised on every streamed chunk.
;; Caching the overlay reference per buffer turns those lookups
;; into O(1). The cache is invalidated automatically when the
;; cached overlay is deleted (its `overlay-buffer' becomes nil)
;; and explicitly in `eca-chat--clear'.
(defvar-local eca-chat--prompt-area-ov-cache nil)
(defvar-local eca-chat--prompt-field-ov-cache nil)
(defvar-local eca-chat--progress-area-ov-cache nil)
(defvar-local eca-chat--context-area-ov-cache nil)
(defvar-local eca-chat--task-area-ov-cache nil)
(defvar eca-chat--new-chat-id 0)
(defvar eca--chat-init-session nil
"Dynamically bound session during `eca-chat-mode' initialization.")
(defvar eca--chat-init-skip-welcome nil
"When non-nil, skip welcome message during `eca-chat-mode' init.
Bound while creating a buffer for a server-initiated chat (resume,
fork) whose content will be streamed in next, so the welcome text
and resume link are not left behind under the replayed messages.")
(defun eca-chat-new-buffer-name (session)
"Return the chat buffer name for SESSION."
(format "<eca-chat[%s]:%s:%s>"
(eca--session-project-name session)
(eca--session-id session)
eca-chat--new-chat-id))
(defvar eca-chat-mode-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map markdown-mode-map)
(define-key map (kbd "S-<return>") #'eca-chat--key-pressed-newline)
(define-key map (kbd "C-<return>") #'eca-chat--key-pressed-queue)
(define-key map (kbd "C-<up>") #'eca-chat--key-pressed-previous-prompt-history)
(define-key map (kbd "C-<down>") #'eca-chat--key-pressed-next-prompt-history)
(define-key map (kbd "RET") #'eca-chat--key-pressed-return)
;; evil-collection (and Spacemacs) bind RET to `markdown-do' in normal
;; state on `markdown-mode-map', which this map inherits and evil
;; ranks above it. `markdown-do' follows links but inserts a GFM
;; checkbox anywhere else, e.g. next to a question option. Remap it
;; so RET ends in the chat handler whichever keymap resolved it.
(define-key map [remap markdown-do] #'eca-chat--key-pressed-return)
(define-key map (kbd "C-c C-<return>") #'eca-chat-send-prompt-at-chat)
;; Bind only TAB, never the raw <tab> function-key event: binding
;; <tab> would block Emacs's <tab> -> TAB key translation in GUI
;; frames and shadow completion UIs' TAB bindings (e.g. corfu-map),