-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy patheca-chat-context.el
More file actions
1074 lines (970 loc) · 49.8 KB
/
Copy patheca-chat-context.el
File metadata and controls
1074 lines (970 loc) · 49.8 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-context.el --- ECA chat context and completion -*- lexical-binding: t; -*-
;; Copyright (C) 2025 Eric Dallo
;;
;; SPDX-License-Identifier: Apache-2.0
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;;
;; Context management, completion-at-point, cursor tracking, and
;; media/image handling for ECA chat.
;;
;;; Code:
(require 'f)
(require 'eca-util)
(require 'eca-api)
(require 'eca-chat-expandable)
;; Forward declarations for eca-chat.el core
(defvar eca-chat-mode-map)
(defvar eca-chat--id)
(defvar eca-chat-window-width)
(declare-function eca-chat--insert "eca-chat")
(declare-function eca-chat--prompt-field-start-point "eca-chat")
(declare-function eca-chat--refine-context "eca-chat")
(declare-function eca-chat--prompt-context-field-ov "eca-chat")
(declare-function eca-chat--point-at-new-context-p "eca-chat")
(declare-function eca-chat--point-at-prompt-field-p "eca-chat")
(declare-function eca-chat--new-context-start-point "eca-chat")
(declare-function eca-chat--select-window "eca-chat")
(declare-function eca-chat--get-last-buffer "eca-chat")
(declare-function eca-chat--insert-prompt "eca-chat")
(declare-function eca-chat--relativize-filename-for-workspace-root "eca-chat")
(declare-function eca-chat--task-find-by-id "eca-chat")
;;;; Customization
(defcustom eca-chat-auto-add-repomap nil
"Whether to auto include repoMap context when opening eca."
:type 'boolean
:group 'eca)
(defcustom eca-chat-auto-add-cursor t
"Whether to auto track cursor opened files/position and add them to context."
:type 'boolean
:group 'eca)
(defcustom eca-chat-cursor-context-debounce 0.3
"Seconds to debounce updates when tracking cursor to context."
:type 'number
:group 'eca)
(defcustom eca-chat-context-prefix "@"
"The context prefix string used in eca chat buffer."
:type 'string
:group 'eca)
(defcustom eca-chat-filepath-prefix "#"
"The filepath prefix string used in eca chat buffer."
:type 'string
:group 'eca)
(defcustom eca-chat-yank-image-context-location 'user
"Where to paste images from clipboard."
:type '(choice (const :tag "System context area" system)
(const :tag "user context area" user))
:group 'eca)
(defcustom eca-chat-context-buffer-predicate #'eca-chat-context-buffer-include-p
"Predicate deciding if a buffer can be offered as text context.
Called with a buffer, should return non-nil to offer it in the
`@' completion and DWIM context commands."
:type 'function
:group 'eca)
(defcustom eca-chat-context-buffer-max-chars 100000
"Max chars of buffer content sent as text context, keeping its tail.
When nil, send the whole buffer content."
:type '(choice (const :tag "No limit" nil) integer)
:group 'eca)
;;;; Faces
(defface eca-chat-context-unlinked-face
'((((background dark)) (:foreground "gold" :height 0.9))
(((background light)) (:foreground "dark goldenrod" :height 0.9)))
"Face for contexts to be added."
:group 'eca)
(defface eca-chat-context-file-face
'((((background dark)) (:foreground "coral" :underline t :height 0.9))
(((background light)) (:foreground "firebrick" :underline t :height 0.9)))
"Face for contexts of file type."
:group 'eca)
(defface eca-chat-context-repo-map-face
'((((background dark)) (:foreground "turquoise" :underline t :height 0.9))
(((background light)) (:foreground "dark cyan" :underline t :height 0.9)))
"Face for contexts of repoMap type."
:group 'eca)
(defface eca-chat-context-mcp-resource-face
'((((background dark)) (:foreground "lime green" :underline t :height 0.9))
(((background light)) (:foreground "dark green" :underline t :height 0.9)))
"Face for contexts of mcpResource type."
:group 'eca)
(defface eca-chat-context-cursor-face
'((((background dark)) (:foreground "gainsboro" :underline t :height 0.9))
(((background light)) (:foreground "dim gray" :underline t :height 0.9)))
"Face for contexts of cursor type."
:group 'eca)
(defface eca-chat-context-buffer-face
'((((background dark)) (:foreground "orchid" :underline t :height 0.9))
(((background light)) (:foreground "dark magenta" :underline t :height 0.9)))
"Face for contexts of text (buffer) type."
:group 'eca)
;;;; Variables
(defvar-local eca-chat--context-completion-cache nil)
(defvar-local eca-chat--file-completion-cache nil)
(defvar-local eca-chat--command-completion-cache nil)
(defvar-local eca-chat--context '())
(defvar-local eca-chat--cursor-context nil)
;; Timer used to debounce post-command driven context updates
(defvar eca-chat--cursor-context-timer nil)
;;;; Constants
(defconst eca-chat--kind->symbol
'(("file" . file)
("directory" . folder)
("repoMap" . module)
("cursor" . class)
("mcpPrompt" . function)
("mcpResource" . file)
("text" . text)
("native" . variable)
("custom-prompt" . method)))
(defconst eca-chat-media--mime-extension-map
'(("image/png" . "png")
("image/x-png" . "png")
("image/jpeg" . "jpg")
("image/jpg" . "jpg")
("image/gif" . "gif")
("image/webp" . "webp")
("image/heic" . "heic")
("image/heif" . "heif")
("image/svg+xml" . "svg"))
"Mapping of mime types to screenshot file extensions.")
;;;; Context functions
(defun eca-chat--context-presentable-path (filename)
"Return the presentable string for FILENAME."
(or (when (-first (lambda (root) (f-ancestor-of? root filename))
(eca--session-workspace-folders (eca-session)))
(f-filename filename))
filename))
(defun eca-chat-context-buffer-include-p (buffer)
"Return non-nil when BUFFER can be offered as a text context.
Excludes file-visiting, hidden, minibuffer and ECA own buffers."
(let ((name (buffer-name buffer)))
(and (buffer-live-p buffer)
(not (buffer-file-name buffer))
(not (minibufferp buffer))
(not (string-prefix-p " " name))
(not (string-match-p "\\`\\(\\*eca\\|<eca-\\)" name)))))
(defun eca-chat--buffer-context (buffer &optional lines-range)
"Return the text context plist for BUFFER.
When LINES-RANGE is non-nil, a (:start N :end M) plist, restrict
the context to those lines of BUFFER."
(append (list :type "text" :label (buffer-name buffer))
(when lines-range (list :linesRange lines-range))))
(defvar eca-chat--buffer-list-tick 0
"Counter bumped whenever the buffer list changes.")
(defvar eca-chat--buffer-contexts-cache nil
"Cons of (TICK . CONTEXTS) caching eligible buffer contexts.")
(defvar eca-chat--buffer-completion-items-cache nil
"Cons of (TICK . ITEMS) caching buffer completion items.")
(defun eca-chat--buffer-list-changed ()
"Invalidate buffer context caches after a buffer list update."
(setq eca-chat--buffer-list-tick (1+ eca-chat--buffer-list-tick)))
(add-hook 'buffer-list-update-hook #'eca-chat--buffer-list-changed)
(defun eca-chat--all-buffer-contexts ()
"Return text contexts for all eligible buffers.
Recomputed only when the buffer list changes."
(let ((tick eca-chat--buffer-list-tick))
(unless (and eca-chat--buffer-contexts-cache
(eq (car eca-chat--buffer-contexts-cache) tick))
(setq eca-chat--buffer-contexts-cache
(cons tick
(->> (buffer-list)
(-filter (lambda (buffer)
(funcall eca-chat-context-buffer-predicate buffer)))
(-map #'eca-chat--buffer-context)))))
(cdr eca-chat--buffer-contexts-cache)))
(defun eca-chat--buffer-contexts ()
"Return text contexts for eligible buffers not already added."
(-remove (lambda (context) (member context eca-chat--context))
(eca-chat--all-buffer-contexts)))
(defun eca-chat--buffer-context-content (buffer &optional lines-range)
"Return BUFFER text limited to `eca-chat-context-buffer-max-chars'.
When LINES-RANGE is non-nil, a (:start N :end M) plist, restrict
to those lines first, resolved against the live buffer state.
When over the limit the tail is kept, where recent output lives."
(with-current-buffer buffer
(save-restriction
(widen)
(-let* (((&plist :start start-line :end end-line) lines-range)
(region-start (if start-line
(save-excursion
(goto-char (point-min))
(forward-line (1- start-line))
(point))
(point-min)))
(region-end (if end-line
(save-excursion
(goto-char (point-min))
(forward-line (1- end-line))
(line-end-position))
(point-max)))
(max-chars eca-chat-context-buffer-max-chars)
(start (if (and max-chars (> (- region-end region-start) max-chars))
(- region-end max-chars)
region-start)))
(buffer-substring-no-properties start region-end)))))
(defun eca-chat--materialize-context (context)
"Return CONTEXT filled with content needed right before sending.
Text contexts get fresh buffer content by label, sliced to their
lines range when present (the range is resolved client-side and
not sent); contexts of killed buffers return nil so callers can
drop them. Cursor contexts with no tracked position return nil
too."
(pcase (plist-get context :type)
("text" (let* ((label (plist-get context :label))
(buffer (get-buffer label)))
(if (buffer-live-p buffer)
(list :type "text"
:label label
:content (eca-chat--buffer-context-content
buffer (plist-get context :linesRange)))
(progn (eca-info "Skipping killed buffer context: %s" label)
nil))))
("cursor" (when (plist-get context :position)
context))
(_ context)))
(defun eca-chat--context->str (context &optional static?)
"Convert CONTEXT to a presentable str in buffer.
If STATIC? return strs with no dynamic values."
(-let* (((&plist :type type) context)
(context-str
(pcase type
("file" (let ((path (plist-get context :path))
(lines-range (plist-get context :linesRange)))
(propertize (concat eca-chat-context-prefix
(eca-chat--context-presentable-path path)
(-when-let ((&plist :start start :end end) lines-range)
(format "(%d-%d)" start end)))
'eca-chat-expanded-item-str (concat eca-chat-context-prefix path
(-when-let ((&plist :start start :end end) lines-range)
(format ":L%d-L%d" start end)))
'font-lock-face 'eca-chat-context-file-face)))
("directory" (propertize (concat eca-chat-context-prefix (eca-chat--context-presentable-path (plist-get context :path)))
'eca-chat-expanded-item-str (concat eca-chat-context-prefix (plist-get context :path))
'font-lock-face 'eca-chat-context-file-face))
("repoMap" (propertize (concat eca-chat-context-prefix "repoMap")
'eca-chat-expanded-item-str (concat eca-chat-context-prefix "repoMap")
'font-lock-face 'eca-chat-context-repo-map-face))
("mcpResource" (propertize (concat eca-chat-context-prefix (plist-get context :server) ":" (plist-get context :name))
'eca-chat-expanded-item-str (concat eca-chat-context-prefix (plist-get context :server) ":" (plist-get context :name))
'font-lock-face 'eca-chat-context-mcp-resource-face))
("cursor" (propertize (cond
(static? (concat eca-chat-context-prefix "cursor"))
((not eca-chat--cursor-context)
(concat eca-chat-context-prefix "cursor" "(no file)"))
(t (concat eca-chat-context-prefix "cursor"
"("
(-some-> (plist-get eca-chat--cursor-context :path)
(f-filename))
" "
(-some->>
(-> eca-chat--cursor-context
(plist-get :position)
(plist-get :start)
(plist-get :line))
(funcall #'number-to-string))
":"
(-some->>
(-> eca-chat--cursor-context
(plist-get :position)
(plist-get :start)
(plist-get :character))
(funcall #'number-to-string))
")")))
'eca-chat-expanded-item-str (concat eca-chat-context-prefix "cursor")
'font-lock-face 'eca-chat-context-cursor-face))
("text" (let ((label (plist-get context :label))
(lines-range (plist-get context :linesRange)))
(propertize (concat eca-chat-context-prefix
label
(-when-let ((&plist :start start :end end) lines-range)
(format "(%d-%d)" start end)))
'eca-chat-expanded-item-str (concat eca-chat-context-prefix label
(-when-let ((&plist :start start :end end) lines-range)
(format ":L%d-L%d" start end)))
'font-lock-face 'eca-chat-context-buffer-face)))
(_ (concat eca-chat-context-prefix "unknown:" type)))))
(propertize context-str
'eca-chat-item-type 'context
'eca-chat-item-str-length (length context-str)
'eca-chat-context-item context)))
(defun eca-chat--filepath->str (filepath lines-range)
"Convert FILEPATH and LINES-RANGE to a presentable str in buffer."
(let* ((item-str (concat eca-chat-filepath-prefix
(eca-chat--context-presentable-path filepath)
(-when-let ((&plist :start start :end end) lines-range)
(format "(%d-%d)" start end)))))
(propertize item-str
'eca-chat-item-type 'filepath
'eca-chat-item-str-length (length item-str)
'eca-chat-expanded-item-str (concat eca-chat-filepath-prefix
filepath
(-when-let ((&plist :start start :end end) lines-range)
(format ":L%d-L%d" start end)))
'font-lock-face 'eca-chat-context-file-face)))
(defun eca-chat--refresh-context ()
"Refresh chat context."
(save-excursion
(-some-> (eca-chat--prompt-context-field-ov)
(overlay-start)
(goto-char))
(delete-region (point) (line-end-position))
(seq-doseq (context eca-chat--context)
(eca-chat--insert (eca-chat--context->str context))
(eca-chat--insert " "))
(eca-chat--insert (propertize eca-chat-context-prefix 'font-lock-face 'eca-chat-context-unlinked-face))))
(defun eca-chat--add-context (context)
"Add to chat CONTEXT."
(add-to-list 'eca-chat--context context t)
(eca-chat--refresh-context))
(defun eca-chat--remove-context (context)
"Remove from chat CONTEXT."
(setq eca-chat--context (remove context eca-chat--context))
(eca-chat--refresh-context))
;;;; Cursor tracking
(defun eca-chat--cur-position ()
"Return the start and end positions for current point.
Resteps a cons cell (START . END) where START and END are cons cells
of (LINE . CHARACTER) representing the current selection or cursor position."
(save-excursion
(let* ((start-pos (if (use-region-p) (region-beginning) (point)))
(end-pos (if (use-region-p) (region-end) (point)))
(start-line (line-number-at-pos start-pos t))
(start-char (1+ (progn
(goto-char start-pos)
(current-column))))
(end-line (line-number-at-pos end-pos t))
(end-char (1+ (progn
(goto-char end-pos)
(current-column)))))
(cons (cons start-line start-char)
(cons end-line end-char)))))
(defun eca-chat--get-last-visited-buffer ()
"Return the last visited file buffer inside a session workspace.
More recent file buffers outside any session workspace root are
skipped so the cursor context keeps pointing to workspace files."
(-first (lambda (buff)
(when (buffer-live-p buff)
(-some-> (buffer-file-name buff)
(eca-chat--session-for-path))))
(buffer-list)))
(defun eca-chat--session-for-path (path)
"Return the session whose workspace folders contain PATH, or nil.
Pure in-memory lookup over existing sessions, unlike `eca-session'
which may probe project.el and shell out to git, so it is cheap
enough for timers running in arbitrary buffers."
(-first (lambda (session)
(--any? (and it (f-ancestor-of? it path))
(eca--session-workspace-folders session)))
(eca-vals eca--sessions)))
(defun eca-chat--track-cursor (&rest _args)
"Change chat context considering current open file and point."
(when-let* ((buffer (eca-chat--get-last-visited-buffer))
(path (buffer-file-name buffer))
(session (eca-chat--session-for-path path)))
(with-current-buffer buffer
(when-let (chat-buffer (eca-chat--get-last-buffer session))
(when (buffer-live-p chat-buffer)
(-let* (((start . end) (eca-chat--cur-position))
((start-line . start-character) start)
((end-line . end-character) end))
(eca-chat--with-current-buffer chat-buffer
(let ((new-context (list :path path
:position (list :start (list :line start-line :character start-character)
:end (list :line end-line :character end-character)))))
(when (not (eca-plist-equal eca-chat--cursor-context new-context))
(setq eca-chat--cursor-context new-context)
(eca-chat--refresh-context))))))))))
(defun eca-chat--track-cursor-position-schedule ()
"Debounce `eca-chat--track-cursor' via an idle timer."
(unless eca-chat--cursor-context-timer
(setq eca-chat--cursor-context-timer
(run-with-idle-timer eca-chat-cursor-context-debounce t
#'eca-chat--track-cursor))))
;;;; Media/yank functions
(defun eca-chat-media--extension-for-type (type)
"Return file extension (without dot) for mime TYPE.
TYPE can be a string or symbol."
(let* ((type-str (if (symbolp type) (symbol-name type) type))
(clean (and type-str (string-trim type-str))))
(or (cdr (assoc-string clean eca-chat-media--mime-extension-map t))
(when clean
(let* ((parts (split-string clean "/"))
(raw-subtype (cadr parts))
(subtype (car (split-string (or raw-subtype "") "\\+"))))
(unless (string-empty-p subtype)
subtype)))
"png")))
(defun eca-chat-media--save-clipboard-image (type data)
"Write clipboard image DATA of mime TYPE to a temp file.
Returns the path to the written file, or nil (after reporting the
failure via `eca-error') when writing fails. Shared by the eca
chat buffer and the compose buffer clipboard-paste handlers."
(let* ((extension (eca-chat-media--extension-for-type type))
(output-path (make-temp-file "eca-screenshot-" nil (concat "." extension))))
(condition-case err
(progn
(let ((coding-system-for-write 'no-conversion))
(write-region data nil output-path nil 'silent))
(and (f-exists? output-path) output-path))
(error
(eca-error "Failed to save yanked image: %s" (error-message-string err))
nil))))
(defun eca-chat--yank-image-handler (type data)
"Handler for `yank-media' to insert images from clipboard.
TYPE is the MIME type (e.g., image/png).
DATA is the binary image data as a string."
(when-let* ((session (eca-session))
(chat-buffer (eca-chat--get-last-buffer session))
(output-path (eca-chat-media--save-clipboard-image type data)))
(eca-chat--with-current-buffer chat-buffer
(let ((context (list :type "file" :path output-path))
(file-size (file-size-human-readable (file-attribute-size (file-attributes output-path)))))
(eca-chat--select-window)
(if (eq 'system eca-chat-yank-image-context-location)
(eca-chat--add-context context)
(progn
(eca-chat--insert-prompt (concat (eca-chat--context->str context 'static) " "))
(goto-char (+ (point) (+ 2 (length output-path))))))
(eca-info "Image added, size: %s" file-size)))))
(defun eca-chat--clipboard-image-p ()
"Return non-nil when an image is available on the clipboard."
(when-let* ((targets (and (display-graphic-p)
(gui-get-selection 'CLIPBOARD 'TARGETS))))
(seq-some (lambda (type)
(and (symbolp type)
(string-match-p "^image/" (symbol-name type))))
(if (vectorp targets) (append targets nil) targets))))
(defun eca-chat--yank-considering-image (orig-fun &rest args)
"Around advice for paste commands to use `yank-media' for images.
Call ORIG-FUN with ARGS if not media."
(if (and (derived-mode-p 'eca-chat-mode)
(fboundp 'yank-media)
(boundp 'yank-media--registered-handlers)
yank-media--registered-handlers
(eca-chat--clipboard-image-p))
(call-interactively #'yank-media)
(apply orig-fun args)))
;;;; DWIM / query functions
(defun eca-chat--find-typed-query (prefix)
"Return the text typed after the last item after PREFIX (@ or #).
For example: `@foo @bar @baz` => `baz`. If nothing is typed, resteps an empty
string."
(when (eca-chat--point-at-new-context-p)
(save-excursion
(goto-char (eca-chat--new-context-start-point))
(end-of-line)))
(save-excursion
(let* ((start (line-beginning-position))
(end (point))
(last-prefix-pos (search-backward prefix start t)))
(if last-prefix-pos
(string-trim (buffer-substring-no-properties (+ last-prefix-pos (length prefix)) end))
""))))
(defun eca-chat--resolve-path-token (token)
"Resolve TOKEN to an existing absolute path, else nil.
TOKEN may be absolute, start with ~, or be relative to one of
the session workspace roots (including ./ and ../ tokens)."
(when (and token (not (string-empty-p token)))
(if (file-name-absolute-p token)
(let ((expanded (directory-file-name (expand-file-name token))))
(when (f-exists? expanded) expanded))
(-some (lambda (root)
(let ((expanded (directory-file-name (expand-file-name token root))))
(when (f-exists? expanded) expanded)))
(eca--session-workspace-folders (eca-session))))))
(defun eca-chat--raw-prompt-contexts ()
"Return contexts for raw @path tokens typed in the prompt field.
Only workspace-relative tokens are considered: absolute, ~ and
dot prefixed mentions are already parsed by the server from the
message text, and tokens already linked to a context chip are
skipped."
(when-let ((prompt-start (eca-chat--prompt-field-start-point)))
(let ((contexts '())
(regexp (concat "\\(?:^\\|[^[:alnum:]]\\)"
(regexp-quote eca-chat-context-prefix)
"\\([^[:space:]]+\\)")))
(save-excursion
(goto-char prompt-start)
(while (re-search-forward regexp nil t)
(let ((token (match-string-no-properties 1)))
(unless (or (get-text-property (match-beginning 1) 'eca-chat-context-item)
(file-name-absolute-p token)
(string-prefix-p "." token))
(when-let ((path (eca-chat--resolve-path-token token)))
(let ((context (list :type (if (f-dir? path) "directory" "file")
:path path)))
(unless (member context contexts)
(push context contexts))))))))
(nreverse contexts))))
(defun eca-chat--maybe-finalize-context-token ()
"Turn a raw @path or #path token before point into a proper item.
Meant to be called right after a space was inserted. Does
nothing when the previous word does not resolve to an existing
file or directory."
(let* ((end (1- (point)))
(start (save-excursion
(goto-char end)
(if (re-search-backward "[[:space:]]" (line-beginning-position) t)
(1+ (point))
(line-beginning-position)))))
(when (< start end)
(let ((word (buffer-substring-no-properties start end)))
(when (and (> (length word) 1)
(or (string-prefix-p eca-chat-context-prefix word)
(string-prefix-p eca-chat-filepath-prefix word))
(not (get-text-property start 'eca-chat-item-type)))
(when-let ((path (eca-chat--resolve-path-token (substring word 1))))
(let ((context? (string-prefix-p eca-chat-context-prefix word)))
(cond
;; On the context line: add to the context list; the
;; refresh wipes the typed text.
((and context? (eca-chat--point-at-new-context-p))
(eca-chat--add-context
(list :type (if (f-dir? path) "directory" "file")
:path path)))
;; In the prompt: replace the raw token with an item.
((eca-chat--point-at-prompt-field-p)
(let ((item-str (if context?
(eca-chat--context->str
(list :type (if (f-dir? path) "directory" "file")
:path path)
'static)
(eca-chat--filepath->str path nil))))
(delete-region start (point))
(eca-chat--insert item-str)
(eca-chat--insert " ")))))))))))
(defun eca-chat--post-self-insert ()
"Finalize raw context tokens after inserting a space."
(when (eq last-command-event ?\s)
(eca-chat--maybe-finalize-context-token)))
(declare-function dired-get-marked-files "dired")
(declare-function treemacs-node-at-point "treemacs")
(declare-function treemacs-button-get "treemacs")
(defun eca-chat--region-lines-range ()
"Return the active region as a lines range plist (:start N :end M).
Lines are absolute (1-based, ignoring narrowing) since consumers
resolve them against the whole file or buffer. A region ending at
the beginning of a line (whole-lines selection) does not include
that line."
(let* ((rb (region-beginning))
(re (region-end))
(re (if (and (> re rb)
(save-excursion (goto-char re) (bolp)))
(1- re)
re)))
(list :start (line-number-at-pos rb t)
:end (line-number-at-pos re t))))
(defun eca-chat--get-contexts-dwim ()
"Get contexts in a DWIM manner."
(cond
((and (buffer-file-name)
(use-region-p))
(list
(list :type "file"
:path (buffer-file-name)
:linesRange (eca-chat--region-lines-range))))
((derived-mode-p 'dired-mode)
(--map (list :type (if (f-dir? it) "directory" "file")
:path it)
(dired-get-marked-files)))
((derived-mode-p 'treemacs-mode)
(when-let (path (-some-> (treemacs-node-at-point)
(treemacs-button-get :path)))
(list
(list :type (if (f-dir? path) "directory" "file")
:path path))))
((buffer-file-name)
(list
(list :type "file" :path (buffer-file-name))))
;; Explicit selection in a non-file buffer (magit, vterm, the
;; chat itself, ...): intentional, so no predicate check.
((use-region-p)
(list (eca-chat--buffer-context (current-buffer)
(eca-chat--region-lines-range))))
((funcall eca-chat-context-buffer-predicate (current-buffer))
(list (eca-chat--buffer-context (current-buffer))))))
;;;; Completion functions
(defun eca-chat--completion-item-kind (item)
"Return the kind for ITEM."
(alist-get (plist-get item :type)
eca-chat--kind->symbol
nil
nil
#'string=))
(defun eca-chat--completion-item-label-kind (item-label)
"Return the kind for ITEM-LABEL."
(eca-chat--completion-item-kind (get-text-property 0 'eca-chat-completion-item item-label)))
(defun eca-chat--completion-item-company-box-icon (item-label)
"Return the kind for ITEM-LABEL."
(let ((symbol (eca-chat--completion-item-label-kind item-label)))
(intern (capitalize (symbol-name symbol)))))
(defun eca-chat--completion-context-annotate (roots item-label)
"Annonate ITEM-LABEL detail for ROOTS."
(-let (((&plist :type type :path path :description description) (get-text-property 0 'eca-chat-completion-item item-label)))
(pcase type
("file" (eca-chat--relativize-filename-for-workspace-root path roots 'hide-filename))
("directory" (eca-chat--relativize-filename-for-workspace-root path roots 'hide-filename))
("repoMap" "Summary view of workspaces files")
("cursor" "Current cursor file + position")
("mcpResource" description)
("text" "Buffer content")
(_ ""))))
(defun eca-chat--completion-file-annotate (roots item-label)
"Annonate ITEM-LABEL detail for ROOTS."
(-let (((&plist :path path) (get-text-property 0 'eca-chat-completion-item item-label)))
(eca-chat--relativize-filename-for-workspace-root path roots 'hide-filename)))
(defun eca-chat--completion-prompts-annotate (item-label)
"Annotate prompt ITEM-LABEL."
(-let (((&plist :description description :arguments args)
(get-text-property 0 'eca-chat-completion-item item-label)))
(concat "(" (string-join (--map (plist-get it :name) args) ", ")
") "
(when description
(truncate-string-to-width description (* 100 eca-chat-window-width))))))
(defvar eca-chat--completion-retrigger-timer nil)
(defun eca-chat--completion-retrigger ()
"Schedule a new completion session at point.
Used after completing a directory so the user can keep
completing its contents without retyping the trigger."
(when (timerp eca-chat--completion-retrigger-timer)
(cancel-timer eca-chat--completion-retrigger-timer))
(let ((buffer (current-buffer)))
(setq eca-chat--completion-retrigger-timer
(run-at-time
0 nil
(lambda ()
(setq eca-chat--completion-retrigger-timer nil)
(when (and (buffer-live-p buffer)
(eq buffer (window-buffer (selected-window))))
(with-current-buffer buffer
(cond
((and (bound-and-true-p company-mode)
(fboundp 'company-manual-begin))
(company-manual-begin))
(t (completion-at-point))))))))))
(defun eca-chat--completion-drill-in (prefix)
"Keep completing after PREFIX instead of finalizing the item.
Strips the completion text properties from the just inserted
directory text and re-triggers completion so the user can drill
into the directory contents."
(let ((start-pos (save-excursion
(search-backward prefix (line-beginning-position) t))))
(when start-pos
(remove-text-properties (+ start-pos (length prefix)) (point)
'(eca-chat-completion-item nil face nil))))
(eca-chat--completion-retrigger))
(defun eca-chat--completion-item-directory-p (item)
"Return non-nil when completion ITEM points to a directory."
(string= "directory"
(plist-get (get-text-property 0 'eca-chat-completion-item item)
:type)))
(defun eca-chat--completion-context-from-new-context-exit-function (item _status)
"Add to context the selected ITEM.
Directories are not finalized: completion keeps going inside
them; typing a space adds the directory itself as context."
(if (eca-chat--completion-item-directory-p item)
(eca-chat--completion-drill-in eca-chat-context-prefix)
(eca-chat--add-context (get-text-property 0 'eca-chat-completion-item item))
(end-of-line)))
(defun eca-chat--completion-context-from-prompt-exit-function (item _status)
"Add to context the selected ITEM.
Add text property to prompt text to match context. Directories
are not finalized: completion keeps going inside them; typing a
space turns the directory into a context."
(if (eca-chat--completion-item-directory-p item)
(eca-chat--completion-drill-in eca-chat-context-prefix)
(let ((context (get-text-property 0 'eca-chat-completion-item item)))
(let ((start-pos (save-excursion
(search-backward eca-chat-context-prefix (line-beginning-position) t)))
(end-pos (point)))
(delete-region start-pos end-pos)
(eca-chat--insert (eca-chat--context->str context 'static))))
(eca-chat--insert " ")))
(defun eca-chat--completion-file-from-prompt-exit-function (item _status)
"Add to files the selected ITEM.
Directories are not finalized: completion keeps going inside
them; typing a space turns the directory into a filepath."
(if (eca-chat--completion-item-directory-p item)
(eca-chat--completion-drill-in eca-chat-filepath-prefix)
(let* ((file (get-text-property 0 'eca-chat-completion-item item))
(start-pos (save-excursion
(search-backward eca-chat-filepath-prefix (line-beginning-position) t)))
(end-pos (point)))
(delete-region start-pos end-pos)
(eca-chat--insert (eca-chat--filepath->str (plist-get file :path) nil)))
(eca-chat--insert " ")))
(defun eca-chat--completion-prompt-exit-function (item _status)
"Finish prompt completion for ITEM."
(-let* (((&plist :arguments arguments) (get-text-property 0 'eca-chat-completion-item item)))
(when (> (length arguments) 0)
(seq-doseq (arg arguments)
(-let (((&plist :name name :description description :required required) arg))
(eca-chat--insert " ")
(let* ((desc-part (if (and description (not (string-empty-p description)))
(format "\nDescription: %s" description)
""))
(value-suffix (if required "" " (leave blank for default)"))
(prompt (format "Arg: %s%s\nValue%s: " name desc-part value-suffix))
(arg-text (read-string prompt)))
(if (and arg-text (string-match-p " " arg-text))
(eca-chat--insert (format "\"%s\"" arg-text))
(eca-chat--insert arg-text)))))
(end-of-line))))
(defun eca-chat--completion-path-label (query roots path directory?)
"Return the completion label for PATH given typed QUERY and ROOTS.
Keeps the directory part the user typed as the label prefix so
the probe keeps matching while drilling into folders, falling
back to a workspace-relative path. Appends a trailing slash
when DIRECTORY? is non-nil."
(let* ((qdir (file-name-directory query))
(label
(or
;; Keep what the user typed as prefix (handles ~, ./, ../,
;; absolute and workspace-relative directory parts).
(when qdir
(-some (lambda (base)
(let ((resolved (file-name-as-directory
(expand-file-name qdir base))))
(when (string-prefix-p resolved path)
(concat qdir (substring path (length resolved))))))
(if (file-name-absolute-p qdir) (list nil) roots)))
;; Fallback: relativize to a workspace root.
(-some (lambda (root)
(when (f-ancestor-of? root path)
(f-relative path root)))
roots)
path)))
(if directory? (file-name-as-directory label) label)))
(defun eca-chat--context-to-completion (query roots context)
"Convert CONTEXT to a completion item for typed QUERY and ROOTS."
(let* ((ctx-type (plist-get context :type))
(ctx-path (plist-get context :path))
(raw-label (pcase ctx-type
("file" (eca-chat--completion-path-label query roots ctx-path nil))
("directory" (eca-chat--completion-path-label query roots ctx-path t))
("repoMap" "repoMap")
("cursor" "cursor")
("mcpResource" (concat (plist-get context :server) ":" (plist-get context :name)))
("text" (plist-get context :label))
(_ (concat "Unknown - " ctx-type))))
(face (pcase ctx-type
("file" 'eca-chat-context-file-face)
("directory" 'eca-chat-context-file-face)
("repoMap" 'eca-chat-context-repo-map-face)
("cursor" 'eca-chat-context-cursor-face)
("mcpResource" 'eca-chat-context-mcp-resource-face)
("text" 'eca-chat-context-buffer-face)
(_ nil))))
(propertize raw-label
'eca-chat-completion-item context
'face face)))
(defun eca-chat--buffer-completion-items ()
"Return completion items for eligible buffers not already added.
Items are recomputed only when the buffer list changes; the
already-added filter always runs against the live context list."
(let ((tick eca-chat--buffer-list-tick))
(unless (and eca-chat--buffer-completion-items-cache
(eq (car eca-chat--buffer-completion-items-cache) tick))
(setq eca-chat--buffer-completion-items-cache
(cons tick
(-map (lambda (context)
(eca-chat--context-to-completion nil nil context))
(eca-chat--all-buffer-contexts)))))
(let ((items (cdr eca-chat--buffer-completion-items-cache))
(added-text-contexts (-filter (lambda (context)
(equal "text" (plist-get context :type)))
eca-chat--context)))
(if added-text-contexts
(-remove (lambda (item)
(member (get-text-property 0 'eca-chat-completion-item item)
added-text-contexts))
items)
items))))
(defun eca-chat--file-to-completion (query roots file)
"Convert FILE to a completion item for typed QUERY and ROOTS."
(propertize (eca-chat--completion-path-label
query roots
(plist-get file :path)
(string= "directory" (plist-get file :type)))
'eca-chat-completion-item file
'face 'eca-chat-context-file-face))
(defun eca-chat--command-to-completion (command)
"Convert COMMAND to a completion item."
(propertize (plist-get command :name)
'eca-chat-completion-item command))
;;;; Eldoc function
(defun eca-chat-eldoc-function (cb &rest _ignored)
"Eldoc function to show details of context and prompt in eldoc.
Calls CB with the resulting message."
(cond
;; Task eldoc: show description and blocked-by
((when-let* ((task (get-text-property (point) 'eca-chat-task)))
(let* ((subject (plist-get task :subject))
(description (plist-get task :description))
(blocked-by (append (plist-get task :blockedBy) nil))
(blocked-subjects
(when blocked-by
(mapcar (lambda (id)
(if-let* ((tk (eca-chat--task-find-by-id id)))
(plist-get tk :subject)
(format "#%s" id)))
blocked-by)))
(doc (concat
(propertize subject 'face 'bold)
(when description
(concat "\n" description))
(when blocked-subjects
(concat "\n"
(propertize "Blocked by: " 'face 'font-lock-keyword-face)
(string-join blocked-subjects ", "))))))
(funcall cb doc)
t)))
;; Context/filepath eldoc
((when-let ((item-type (get-text-property (point) 'eca-chat-item-type)))
(when-let ((item-str (get-text-property (point) 'eca-chat-expanded-item-str)))
(when-let ((face (get-text-property (point) 'font-lock-face)))
(funcall cb (format "%s: %s"
(pcase item-type
('context "Context")
('filepath "Filepath"))
(propertize item-str 'face face)))
t))))))
;;;; Completion-at-point function
(defun eca-chat--completion-type-at-point ()
"Return the kind of completion available at point, or nil."
(let ((full-text (buffer-substring-no-properties (line-beginning-position) (point))))
(cond
;; completing contexts
((eca-chat--point-at-new-context-p)
'contexts-from-new-context)
((when-let (last-word (car (last (string-split full-text "[\s]"))))
(string-match-p (concat "\\(?:^\\|[^[:alnum:]]\\)" (regexp-quote eca-chat-context-prefix)) last-word))
'contexts-from-prompt)
((when-let (last-word (car (last (string-split full-text "[\s]"))))
(string-match-p (concat "\\(?:^\\|[^[:alnum:]]\\)" (regexp-quote eca-chat-filepath-prefix)) last-word))
'files-from-prompt)
;; completing commands with `/`
((and (eca-chat--point-at-prompt-field-p)
(string-prefix-p "/" full-text))
'prompts)
(t nil))))
(defun eca-chat--completion-prefix-end (prefix)
"Return the position right after the last PREFIX before point.
Searches only in the current line; return nil when PREFIX is not
found."
(save-excursion
(when (search-backward prefix (line-beginning-position) t)
(+ (point) (length prefix)))))
(defconst eca-chat--completion-cache-max-size 100
"Max cached queries per completion cache before it is reset.")
(defun eca-chat--completion-cached-items (cache-var query fetch-fn key to-item-fn)
"Return completion items for QUERY, caching them in CACHE-VAR.
CACHE-VAR is a buffer-local hash table variable, created on
demand. On cache miss call FETCH-FN; when it returns a response
plist, convert each element of its KEY list with TO-ITEM-FN and
cache the result. Interrupted requests (nil response) are not
cached so they are retried on the next keystroke."
(let* ((cache (or (symbol-value cache-var)
(set cache-var (make-hash-table :test 'equal))))
(cached (gethash query cache :eca-chat--miss)))
(if (not (eq cached :eca-chat--miss))
cached
(when-let ((resp (funcall fetch-fn)))
(let ((items (-map to-item-fn (append (plist-get resp key) nil))))
(when (> (hash-table-count cache) eca-chat--completion-cache-max-size)
(clrhash cache))
(puthash query items cache)
items)))))
(defun eca-chat-completion-at-point ()
"Complete at point in the chat."
(when-let ((type (eca-chat--completion-type-at-point)))
(let* ((bounds-start (pcase type
('prompts (1+ (line-beginning-position)))
('files-from-prompt (or (eca-chat--completion-prefix-end eca-chat-filepath-prefix)
(point)))
(_ (or (eca-chat--completion-prefix-end eca-chat-context-prefix)
(point)))))
(candidates-fn (lambda ()
(eca-api-catch 'input
(eca-api-while-no-input
(pcase type
((or 'contexts-from-prompt
'contexts-from-new-context)
(let* ((query (eca-chat--find-typed-query eca-chat-context-prefix))
(roots (eca--session-workspace-folders (eca-session)))
(server-items (eca-chat--completion-cached-items
'eca-chat--context-completion-cache query
(lambda ()
(eca-api-request-while-no-input