-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy patheca-chat.el
More file actions
4224 lines (3860 loc) · 188 KB
/
eca-chat.el
File metadata and controls
4224 lines (3860 loc) · 188 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 'markdown-mode)
(require 'compat)
(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-window-side 'right
"Side of the frame where the ECA chat window should appear.
Can be `'left', `'right', `'top', or `'bottom'. This setting will only
be used when `eca-chat-use-side-window' is non-nil."
:type '(choice (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 the ECA chat side window when opened on left or right."
:type 'number
:group 'eca)
(defcustom eca-chat-window-height 0.30
"Height of the ECA chat side window when opened on top or bottom."
:type 'number
:group 'eca)
(defcustom eca-chat-use-side-window t
"Whether to display ECA chat in a side window.
When non-nil (default), ECA chat opens in a dedicated side window
controlled by `eca-chat-window-side' and related settings. When nil,
ECA chat opens in a regular buffer that follows standard
`display-buffer' behavior."
:type 'boolean
:group 'eca)
(defcustom eca-chat-focus-on-open t
"Whether to focus the ECA chat window when it opens."
: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-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-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 " " :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
`: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 "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-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)
(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.")
(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)
;; 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 font-lock-doc-face))
"Face for the user sent messages in chat."
: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--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-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-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--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--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--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--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--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--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-question nil
"When non-nil, holds the active question state.
A plist with :session :request :question :options :tool-call-id :allow-freeform.")
;; 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) plus optionally one question-block. 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-local eca-chat--question-block-ov-cache nil)
(defvar eca-chat--new-chat-id 0)
(defvar eca-chat--last-known-model nil)
(defvar eca-chat--last-known-agent nil)
(defvar eca-chat--last-known-variant nil)
(defvar eca--chat-init-session nil
"Dynamically bound session during `eca-chat-mode' initialization.")
(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 "<return>") #'eca-chat--key-pressed-return)
(define-key map (kbd "RET") #'eca-chat--key-pressed-return)
(define-key map (kbd "C-c C-<return>") #'eca-chat-send-prompt-at-chat)
(define-key map (kbd "<tab>") #'eca-chat--key-pressed-tab)
(define-key map (kbd "TAB") #'eca-chat--key-pressed-tab)
(define-key map (kbd "C-c C-k") #'eca-chat-reset)
(define-key map (kbd "C-c C-l") #'eca-chat-clear)
(define-key map (kbd "C-c C-t") #'eca-chat-toggle-trust)
(define-key map (kbd "C-c C-S-t") #'eca-chat-talk)
(define-key map (kbd "C-c C-S-b") #'eca-chat-select-agent)
(define-key map (kbd "C-c C-b") #'eca-chat-cycle-agent)
(define-key map (kbd "C-c C-m") #'eca-chat-select-model)
(define-key map (kbd "C-c C-v") #'eca-chat-select-variant)
(define-key map (kbd "C-c C-n") #'eca-chat-new)
(define-key map (kbd "C-c C-f") #'eca-chat-select)
(define-key map (kbd "C-c C-p") #'eca-chat-repeat-prompt)
(define-key map (kbd "C-c C-d") #'eca-chat-clear-prompt)
(define-key map (kbd "C-c C-S-h") #'eca-chat-timeline)
(define-key map (kbd "C-c C-a") #'eca-chat-tool-call-accept-all)
(define-key map (kbd "C-c C-S-a") #'eca-chat-tool-call-accept-next)
(define-key map (kbd "C-c C-y") #'eca-chat-tool-call-accept-all-and-remember)
(define-key map (kbd "C-c C-r") #'eca-chat-tool-call-reject-next)
(define-key map (kbd "C-c C-S-r") #'eca-chat-rename)
(define-key map (kbd "C-c .") #'eca-transient-menu)
(define-key map (kbd "C-c C-,") #'eca-settings)
(define-key map (kbd "C-c C-<up>") #'eca-chat-go-to-prev-user-message)
(define-key map (kbd "C-c C-<down>") #'eca-chat-go-to-next-user-message)
(define-key map (kbd "C-c <up>") #'eca-chat-go-to-prev-expandable-block)
(define-key map (kbd "C-c <down>") #'eca-chat-go-to-next-expandable-block)
(define-key map (kbd "C-c <tab>") #'eca-chat-toggle-expandable-block)
;; Per-chat inline image zoom (browser-style). Uses `C-c C-z' as
;; the prefix because `C-c <letter>' sequences are reserved for
;; users by the Emacs key binding conventions; `C-c' followed by
;; a control character is reserved for major modes. `=' is a
;; no-Shift alias for `+' so users on US layouts don't need to
;; press Shift.
(define-key map (kbd "C-c C-z +") #'eca-chat-image-zoom-in)
(define-key map (kbd "C-c C-z =") #'eca-chat-image-zoom-in)
(define-key map (kbd "C-c C-z -") #'eca-chat-image-zoom-out)
(define-key map (kbd "C-c C-z 0") #'eca-chat-image-zoom-reset)
(define-key map (kbd "C-c C-z s") #'eca-chat-save-image-at-point)
map)
"Keymap used by `eca-chat-mode'.")
(defun eca-chat--get-last-buffer (session)
"Get the eca chat buffer for SESSION."
(or (when-let (last-buff (eca--session-last-chat-buffer session))
(when (buffer-live-p last-buff)
last-buff))
(get-buffer (eca-chat-new-buffer-name session))))
(defun eca-chat--create-buffer (session)
"Create the eca chat buffer for SESSION."
(get-buffer-create (generate-new-buffer-name (eca-chat-new-buffer-name session))))
(defun eca-chat--get-chat-buffer (session chat-id)
"Get chat buffer for SESSION and CHAT-ID, or nil when none registered.
Since the client now generates the chat-id at buffer creation
time (see `eca-chat-open'), every known chat is registered under
its real id and there is no `'empty' placeholder to migrate from."
(eca-get (eca--session-chats session) chat-id))
(defun eca-chat--delete-chat ()
"Delete current chat."
(when (and (or (eq #'kill-current-buffer this-command)
(eq #'kill-buffer this-command)
(and (symbolp this-command)
(string-prefix-p "eca-" (symbol-name this-command))))
eca-chat--id
(not eca-chat--closed)
(yes-or-no-p "Delete chat from server side (otherwise it will just kill the buffer) ?"))
(eca-api-request-sync (eca-session)
:method "chat/delete"
:params (list :chatId eca-chat--id))))
(defun eca-chat--insert (&rest contents)
"Insert CONTENTS reseting undo-list to avoid buffer inconsistencies."
(apply #'insert contents)
(setq-local buffer-undo-list nil))
(defun eca-chat--spinner-start (callback)
"Start modeline spinner calling CALLBACK when updating."
(eca-chat--allow-write
(setq eca-chat--spinner-timer
(run-with-timer
0
0.5
(lambda ()
(when eca-chat--spinner-timer
(if (eq 3 (length eca-chat--spinner-string))
(setq eca-chat--spinner-string ".")
(setq eca-chat--spinner-string (concat eca-chat--spinner-string ".")))
(funcall callback)))))))
(defun eca-chat--spinner-stop ()
"Stop modeline spinner."
(when eca-chat--spinner-timer
(cancel-timer eca-chat--spinner-timer)
(setq eca-chat--spinner-timer nil))
(setq eca-chat--spinner-string ""))
(defun eca-chat--time->presentable-time (ms)
"Return a propertized presentable time for MS."
(let ((secs (/ ms 1000)))
(propertize (eca-chat--format-duration secs)
'font-lock-face 'eca-chat-time-face)))
(defun eca-chat--elapsed-time-string (start-time)
"Return a propertized elapsed-time string since START-TIME.
Uses `eca-chat--format-duration' for display, with
`eca-chat-time-face' and a `eca-chat--elapsed-time' text
property so the timer can locate it."
(let* ((elapsed (floor (float-time (time-subtract (current-time) start-time))))
(str (concat " " (propertize (eca-chat--format-duration elapsed)
'font-lock-face 'eca-chat-time-face))))
(propertize str 'eca-chat--elapsed-time t)))
(defun eca-chat--tool-call-elapsed-start (id)
"Start tracking elapsed time for tool call ID.
Records current time (only on first call for ID) and ensures the shared
update timer is running."
(unless (gethash id eca-chat--tool-call-elapsed-times)
(puthash id (current-time) eca-chat--tool-call-elapsed-times))
(unless eca-chat--tool-call-elapsed-timer
(let ((buf (current-buffer))
(timer nil))
(setq timer
(run-with-timer
1 1
(lambda ()
(if (buffer-live-p buf)
(with-current-buffer buf
(eca-chat--tool-call-elapsed-tick))
;; Buffer was killed — cancel ourselves to avoid leak
(cancel-timer timer)))))
(setq eca-chat--tool-call-elapsed-timer timer))))
(defun eca-chat--tool-call-elapsed-stop (id)
"Stop tracking elapsed time for tool call ID.
Cancels the shared timer when no more tool calls are being tracked."
(remhash id eca-chat--tool-call-elapsed-times)
(when (and eca-chat--tool-call-elapsed-timer
(zerop (hash-table-count eca-chat--tool-call-elapsed-times)))
(cancel-timer eca-chat--tool-call-elapsed-timer)
(setq eca-chat--tool-call-elapsed-timer nil)))
(defun eca-chat--tool-call-elapsed-tick ()
"Timer callback: update elapsed-time display for all running tool call."
(eca-chat--allow-write
(maphash
(lambda (id start-time)
(when-let* ((ov-label (eca-chat--get-expandable-content id)))
(let* ((label-start (overlay-start ov-label))
(ov-content (overlay-get ov-label 'eca-chat--expandable-content-ov-content))
(new-time (eca-chat--elapsed-time-string start-time)))
(when ov-content
(let ((label-end (1- (overlay-start ov-content))))
(save-excursion
;; Find the text span with eca-chat--elapsed-time property
(goto-char label-start)
(let ((prop-start (text-property-any label-start label-end
'eca-chat--elapsed-time t)))
(when prop-start
(let ((prop-end (next-single-property-change
prop-start 'eca-chat--elapsed-time nil label-end)))
(goto-char prop-start)
(delete-region prop-start prop-end)
(insert new-time)))))))
;; Keep the overlay property in sync so that functions which
;; rebuild the label from stored properties (e.g.
;; eca-chat--update-parent-subagent-status) use the latest value.
(when (overlay-get ov-label 'eca-chat--tool-call-time)
(overlay-put ov-label 'eca-chat--tool-call-time new-time)))))
eca-chat--tool-call-elapsed-times)))
(defun eca-chat--tool-call-elapsed-stop-all ()
"Cancel the elapsed-time timer and clear all tracked tool call."
(when eca-chat--tool-call-elapsed-timer
(cancel-timer eca-chat--tool-call-elapsed-timer)
(setq eca-chat--tool-call-elapsed-timer nil))
(clrhash eca-chat--tool-call-elapsed-times))
(defun eca-chat--update-bg-job-emoji (tool-call-id new-emoji)
"Update background job status emoji in TOOL-CALL-ID.
Replace the job status emoji with NEW-EMOJI."
(when-let* ((ov (eca-chat--get-expandable-content
tool-call-id))
(ov-content (overlay-get ov 'eca-chat--expandable-content-ov-content)))
(let ((start (overlay-start ov))
(end (overlay-start ov-content))
(inhibit-read-only t))
(save-excursion
(goto-char start)
(when (re-search-forward "🟡\\|✅\\|🔴\\|⚫" end t)
(replace-match new-emoji t t))))))
(defun eca-chat--agent ()
"The chat agent considering default and user option."
(or eca-chat-custom-agent
eca-chat--selected-agent
eca-chat--last-known-agent))
(defun eca-chat--model ()
"The chat model considering default and user option."
(or eca-chat-custom-model
eca-chat--selected-model
eca-chat--last-known-model))
(defun eca-chat--variant ()
"The chat variant for the current model."
(or eca-chat--selected-variant
eca-chat--last-known-variant))
(defun eca-chat--trust ()
"Non-nil when trust mode is on, auto-accepts tool call."
eca-chat--selected-trust)
(defun eca-chat--mcps-summary (session)
"The summary of MCP servers for SESSION."
(let* ((running 0) (starting 0) (failed 0)
(propertize-fn (lambda (n face &optional add-slash?)
(unless (zerop n)
(concat
(propertize (number-to-string n) 'font-lock-face face)
(when add-slash? (propertize "/" 'font-lock-face 'font-lock-comment-face))))))
(mcp-servers (eca-mcp-servers session)))
(if (seq-empty-p mcp-servers)
"0"
(progn
(seq-doseq (mcp-server mcp-servers)
(pcase (plist-get mcp-server :status)
("running" (cl-incf running))
("starting" (cl-incf starting))
("requires-auth" (cl-incf starting))
("failed" (cl-incf failed))))
(let ((result (concat (funcall propertize-fn failed 'error (or (> running 0) (> starting 0)))
(funcall propertize-fn starting 'warning (> running 0))
(funcall propertize-fn running 'success))))
(if (string-empty-p result) "0" result))))))
(defun eca-chat--build-tool-call-approval-str-content (session id spacing-line-prefix &optional chat-id)
"Build the tool call approval string for SESSION, ID and SPACING-LINE-PREFIX.
CHAT-ID overrides the buffer-local `eca-chat--id' for the approval
request, useful for subagent tool calls."
(let ((keybinding-for (lambda (command)
(concat "("
(key-description (car (where-is-internal command eca-chat-mode-map)))
")")))
(effective-chat-id (or chat-id eca-chat--id)))
(concat (propertize "\n" 'font-lock-face 'eca-chat-tool-call-spacing-face)
(eca-buttonize
eca-chat-mode-map
(propertize "Accept"
'eca-tool-call-pending-approval-accept t
'line-prefix spacing-line-prefix
'font-lock-face 'eca-chat-tool-call-accept-face)
(lambda ()
(eca-api-notify session
:method "chat/toolCallApprove"
:params (list :chatId effective-chat-id
:toolCallId id))))
(propertize " " 'font-lock-face 'eca-chat-tool-call-approval-content-face)
(propertize (funcall keybinding-for #'eca-chat-tool-call-accept-all)
'font-lock-face 'eca-chat-tool-call-keybinding-face)
(propertize "\n" 'font-lock-face 'eca-chat-tool-call-spacing-face)
(eca-buttonize
eca-chat-mode-map
(propertize "Accept and remember"
'eca-tool-call-pending-approval-accept-and-remember t
'line-prefix spacing-line-prefix
'font-lock-face 'eca-chat-tool-call-accept-and-remember-face)
(lambda ()
(eca-api-notify session
:method "chat/toolCallApprove"
:params (list :chatId effective-chat-id
:save "session"
:toolCallId id))))
(propertize " for this session "
'font-lock-face 'eca-chat-tool-call-approval-content-face)
(propertize (funcall keybinding-for #'eca-chat-tool-call-accept-all-and-remember)
'font-lock-face 'eca-chat-tool-call-keybinding-face)
(propertize "\n" 'font-lock-face 'eca-chat-tool-call-spacing-face)
(eca-buttonize
eca-chat-mode-map
(propertize "Reject"
'eca-tool-call-pending-approval-reject t
'line-prefix spacing-line-prefix
'font-lock-face 'eca-chat-tool-call-reject-face)
(lambda ()
(eca-api-notify session
:method "chat/toolCallReject"
:params (list :chatId effective-chat-id
:toolCallId id))))
(propertize " and tell ECA what to do differently "
'font-lock-face 'eca-chat-tool-call-approval-content-face)
(propertize (funcall keybinding-for #'eca-chat-tool-call-reject-next)
'font-lock-face 'eca-chat-tool-call-keybinding-face))))
(defun eca-chat--insert-prompt-string ()
"Insert the prompt and context string adding overlay metadatas."
(let ((prompt-area-ov (make-overlay (line-beginning-position) (1+ (line-beginning-position)) (current-buffer))))
(overlay-put prompt-area-ov 'eca-chat-prompt-area t))
(eca-chat--insert eca-chat-prompt-separator)
(let ((task-area-ov (make-overlay (1+ (point)) (line-end-position) (current-buffer) nil t)))
(overlay-put task-area-ov 'eca-chat-task-area t)
(eca-chat--insert " ")
(move-overlay task-area-ov (overlay-start task-area-ov) (1- (overlay-end task-area-ov))))
(let ((progress-area-ov (make-overlay (1+ (point)) (line-end-position) (current-buffer) nil t)))
(overlay-put progress-area-ov 'eca-chat-progress-area t)
(eca-chat--insert "\n")
(move-overlay progress-area-ov (overlay-start progress-area-ov) (1- (overlay-end progress-area-ov))))
(let ((context-area-ov (make-overlay (line-beginning-position) (line-end-position) (current-buffer) nil t)))
(overlay-put context-area-ov 'eca-chat-context-area t)
(eca-chat--insert (propertize eca-chat-context-prefix 'font-lock-face 'eca-chat-context-unlinked-face))
(eca-chat--insert "\n")
(move-overlay context-area-ov (overlay-start context-area-ov) (1- (overlay-end context-area-ov))))
(let ((prompt-field-ov (make-overlay (line-beginning-position) (1+ (line-beginning-position)) (current-buffer))))
(overlay-put prompt-field-ov 'eca-chat-prompt-field t)
(overlay-put prompt-field-ov 'before-string (propertize eca-chat-prompt-prefix 'font-lock-face 'eca-chat-prompt-prefix-face))))
(defun eca-chat--clear (&optional new-prompt-content)
"Clear the chat for SESSION and then insert NEW-PROMPT-CONTENT."
(erase-buffer)
(remove-overlays (point-min) (point-max))
(eca-chat--invalidate-overlay-caches)
(eca-chat-expandable--reset-id-table)
(setq-local eca-chat--task-state nil)
;; Cancel loading-related timers and reset state
(when eca-chat--stopping-safety-timer
(cancel-timer eca-chat--stopping-safety-timer)
(setq-local eca-chat--stopping-safety-timer nil))
(when eca-chat--modeline-timer
(cancel-timer eca-chat--modeline-timer)
(setq-local eca-chat--modeline-timer nil))
(setq-local eca-chat--chat-loading nil)
(setq-local eca-chat--steered-prompt nil)
(setq-local eca-chat--queued-prompt nil)
(clrhash eca-chat--subagent-chat-id->tool-call-id)
(clrhash eca-chat--subagent-usage)
(eca-chat--insert "\n")
(eca-chat--insert-prompt-string)
(eca-chat--refresh-context)
(when new-prompt-content
(eca-chat--set-prompt new-prompt-content)))
(defun eca-chat--stop-prompt (session)
"Stop the running chat prompt for SESSION."