-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathpi-coding-agent-render.el
More file actions
2255 lines (2111 loc) · 107 KB
/
pi-coding-agent-render.el
File metadata and controls
2255 lines (2111 loc) · 107 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
;;; pi-coding-agent-render.el --- Chat rendering and tool display -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Daniel Nouri
;; Author: Daniel Nouri <daniel.nouri@gmail.com>
;; Maintainer: Daniel Nouri <daniel.nouri@gmail.com>
;; URL: https://github.com/dnouri/pi-coding-agent
;; SPDX-License-Identifier: GPL-3.0-or-later
;; This file is not part of GNU Emacs.
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Rendering module for pi-coding-agent: streaming chat display, tool output,
;; and fontification.
;;
;; This module handles everything that appears in the chat buffer:
;; - Streaming message display (text deltas, thinking blocks)
;; - Tool call output (overlay creation, streaming preview, toggle)
;; - Event dispatching (handle-display-event)
;; - Streaming fontification (incremental syntax highlighting)
;; - Diff overlay highlighting
;; - Compaction display
;; - File navigation from tool blocks
;; - Session history display and rendering
;;; Code:
(require 'pi-coding-agent-ui)
(require 'pi-coding-agent-table)
(require 'cl-lib)
(require 'ansi-color)
;; Forward references for functions in other modules
(declare-function pi-coding-agent-compact "pi-coding-agent-menu" (&optional custom-instructions))
;;;; Response Display
(defun pi-coding-agent--display-user-message (text &optional timestamp)
"Display user message TEXT in the chat buffer.
If TIMESTAMP (Emacs time value) is provided, display it in the header."
(let ((start (with-current-buffer (pi-coding-agent--get-chat-buffer) (point-max))))
(pi-coding-agent--append-to-chat
(concat "\n" (pi-coding-agent--make-separator "You" timestamp) "\n"
text "\n"))
(with-current-buffer (pi-coding-agent--get-chat-buffer)
(pi-coding-agent--decorate-tables-in-region start (point-max)))))
(defun pi-coding-agent--display-agent-start ()
"Display separator for new agent turn.
Only shows the Assistant header once per prompt, even during retries.
Note: status is set to `streaming' by the event handler."
(pi-coding-agent--set-aborted nil) ; Reset abort flag for new turn
;; Only show header if not already shown for this prompt.
(unless pi-coding-agent--assistant-header-shown
(pi-coding-agent--append-to-chat
(concat "\n" (pi-coding-agent--make-separator "Assistant") "\n"))
(setq pi-coding-agent--assistant-header-shown t))
;; Create markers at current end position
;; message-start-marker: where content begins (for later replacement)
;; streaming-marker: where new deltas are inserted
(pi-coding-agent--set-message-start-marker (copy-marker (point-max) nil))
(pi-coding-agent--set-streaming-marker (copy-marker (point-max) t))
;; Reset streaming parse state - content starts at line beginning, outside code/thinking block
(setq pi-coding-agent--line-parse-state 'line-start)
(setq pi-coding-agent--in-code-block nil)
(setq pi-coding-agent--in-thinking-block nil)
(pi-coding-agent--set-activity-phase "thinking"))
(defun pi-coding-agent--process-streaming-char (char state in-block)
"Process CHAR with current STATE and IN-BLOCK flag.
Returns (NEW-STATE . NEW-IN-BLOCK).
STATE is one of: `line-start', `fence-1', `fence-2', `mid-line'."
(pcase state
('line-start
(cond
((eq char ?`) (cons 'fence-1 in-block))
((eq char ?\n) (cons 'line-start in-block))
(t (cons 'mid-line in-block))))
('fence-1
(cond
((eq char ?`) (cons 'fence-2 in-block))
((eq char ?\n) (cons 'line-start in-block))
(t (cons 'mid-line in-block))))
('fence-2
(cond
((eq char ?`) (cons 'mid-line (not in-block))) ; Toggle code block!
((eq char ?\n) (cons 'line-start in-block)) ; Was just ``
(t (cons 'mid-line in-block)))) ; Was inline ``x
('mid-line
(if (eq char ?\n)
(cons 'line-start in-block)
(cons 'mid-line in-block)))))
(defun pi-coding-agent--transform-delta (delta)
"Transform DELTA for display, handling code blocks and heading levels.
Uses and updates buffer-local state variables for parse state.
Returns the transformed string.
Performance: Uses a two-pass approach. First checks if transformation
is needed (rare), then only does the work when necessary. The common
case of no headings is O(n) with no allocations."
(let ((state pi-coding-agent--line-parse-state)
(in-block pi-coding-agent--in-code-block)
(len (length delta))
(needs-transform nil)
(i 0))
;; First pass: check if any transformation is needed and track state
;; Also collect positions where we need to insert extra #
(let ((insert-positions nil))
(while (< i len)
(let ((char (aref delta i)))
;; Check if we need to add # at this position
(when (and (eq state 'line-start)
(not in-block)
(eq char ?#))
(push i insert-positions)
(setq needs-transform t))
;; Update state
(let ((new-state (pi-coding-agent--process-streaming-char char state in-block)))
(setq state (car new-state))
(setq in-block (cdr new-state)))
(setq i (1+ i))))
;; Save final state
(setq pi-coding-agent--line-parse-state state)
(setq pi-coding-agent--in-code-block in-block)
;; Fast path: no transformation needed
(if (not needs-transform)
delta
;; Slow path: build result with extra # at marked positions
;; insert-positions is in reverse order (last position first)
(let ((positions (nreverse insert-positions))
(result nil)
(prev-pos 0))
(dolist (pos positions)
;; Add content before this position
(when (< prev-pos pos)
(push (substring delta prev-pos pos) result))
;; Add the extra #
(push "#" result)
(setq prev-pos pos))
;; Add remaining content
(when (< prev-pos len)
(push (substring delta prev-pos) result))
(apply #'concat (nreverse result)))))))
(defun pi-coding-agent--display-message-delta (delta)
"Display streaming message DELTA at the streaming marker.
Transforms ATX headings (outside code blocks) by adding one # level
to keep our setext H1 separators as the top-level document structure.
Modification hooks fire normally so jit-lock marks inserted text for
fontification; tree-sitter re-parses at the C level on each insert."
(when (and delta pi-coding-agent--streaming-marker)
(let* ((inhibit-read-only t)
;; Strip leading newlines from first content after header
(delta (if (and pi-coding-agent--message-start-marker
(= (marker-position pi-coding-agent--message-start-marker)
(marker-position pi-coding-agent--streaming-marker)))
(string-trim-left delta "\n+")
delta))
(transformed (pi-coding-agent--transform-delta delta)))
(pi-coding-agent--with-scroll-preservation
(save-excursion
(goto-char (marker-position pi-coding-agent--streaming-marker))
(insert transformed)
(set-marker pi-coding-agent--streaming-marker (point))))
;; After inserting text with completed lines, check for active table
(when (string-match-p "\n" delta)
(pi-coding-agent--maybe-decorate-streaming-table)))))
(defun pi-coding-agent--thinking-insert-position ()
"Return insertion position for thinking text.
Prefers `pi-coding-agent--thinking-marker' when available so interleaved
tool headers do not move the thinking insertion point."
(if (and pi-coding-agent--thinking-marker
(marker-position pi-coding-agent--thinking-marker))
(marker-position pi-coding-agent--thinking-marker)
(marker-position pi-coding-agent--streaming-marker)))
(defun pi-coding-agent--thinking-normalize-text (text)
"Normalize streaming thinking TEXT for stable markdown rendering.
Removes boundary blank lines and collapses internal blank-line runs to
at most one empty paragraph separator while preserving indentation."
(let* ((source (or text ""))
(without-leading-blank-lines
(replace-regexp-in-string "\\`\\(?:[ \t]*\n\\)+" "" source))
(without-boundary-blank-lines
(replace-regexp-in-string "\\(?:\n[ \t]*\\)+\\'" ""
without-leading-blank-lines)))
(if (string-empty-p without-boundary-blank-lines)
""
(replace-regexp-in-string
"\n\\(?:[ \t]*\n\\)\\{2,\\}" "\n\n"
without-boundary-blank-lines))))
(defun pi-coding-agent--thinking-blockquote-text (text)
"Convert normalized thinking TEXT to markdown blockquote lines."
(if (string-empty-p text)
""
(concat "> " (replace-regexp-in-string "\n" "\n> " text))))
(defun pi-coding-agent--render-thinking-content ()
"Render normalized accumulated thinking content in place.
Returns non-nil when meaningful content remains after normalization."
(when (and (markerp pi-coding-agent--thinking-start-marker)
(markerp pi-coding-agent--thinking-marker)
(marker-position pi-coding-agent--thinking-start-marker)
(marker-position pi-coding-agent--thinking-marker))
(let* ((start (marker-position pi-coding-agent--thinking-start-marker))
(end (marker-position pi-coding-agent--thinking-marker))
(normalized (pi-coding-agent--thinking-normalize-text
pi-coding-agent--thinking-raw))
(rendered (pi-coding-agent--thinking-blockquote-text normalized))
(prev pi-coding-agent--thinking-prev-rendered))
(when (<= start end)
(cond
;; Fast path: new rendered text extends previous — just append suffix.
((and prev
(not (string-empty-p prev))
(string-prefix-p prev rendered))
(let ((suffix (substring rendered (length prev))))
(unless (string-empty-p suffix)
(goto-char end)
(insert suffix)
(set-marker pi-coding-agent--thinking-marker (point)))))
;; Slow path: full rewrite; skip if buffer already matches.
(t
(let ((existing (buffer-substring-no-properties start end)))
(unless (equal existing rendered)
(goto-char start)
(delete-region start end)
(insert rendered)
(set-marker pi-coding-agent--thinking-marker (point))))))
(setq pi-coding-agent--thinking-prev-rendered rendered))
(and (<= start end)
(not (string-empty-p normalized))))))
(defun pi-coding-agent--ensure-blank-line-separator ()
"Ensure exactly one blank line separator at point.
Normalizes any existing newline run to two newlines."
(let ((start (point))
(scan (point))
(newline-count 0))
(while (eq (char-after scan) ?\n)
(setq newline-count (1+ newline-count))
(setq scan (1+ scan)))
(cond
((< newline-count 2)
(insert (make-string (- 2 newline-count) ?\n)))
((> newline-count 2)
(delete-region (+ start 2) (+ start newline-count))))))
(defun pi-coding-agent--ensure-blank-line-before-block ()
"Ensure point is on a fresh line with a blank line above.
Used before inserting a new block (thinking, tool) so it is visually
separated from preceding content."
(unless (bolp)
(insert "\n"))
(unless (save-excursion
(forward-line -1)
(looking-at-p "^$"))
(insert "\n")))
(defun pi-coding-agent--reset-thinking-state ()
"Detach and clear all thinking-stream state for the current turn."
(when (markerp pi-coding-agent--thinking-marker)
(set-marker pi-coding-agent--thinking-marker nil))
(when (markerp pi-coding-agent--thinking-start-marker)
(set-marker pi-coding-agent--thinking-start-marker nil))
(setq pi-coding-agent--thinking-marker nil
pi-coding-agent--thinking-start-marker nil
pi-coding-agent--thinking-raw nil
pi-coding-agent--thinking-prev-rendered nil))
(defun pi-coding-agent--display-thinking-start ()
"Insert opening marker for thinking block (blockquote)."
(when pi-coding-agent--streaming-marker
(setq pi-coding-agent--in-thinking-block t)
(let ((inhibit-read-only t))
(pi-coding-agent--with-scroll-preservation
(save-excursion
(goto-char (marker-position pi-coding-agent--streaming-marker))
;; No separator needed when this is the first content in the message.
(when (and pi-coding-agent--message-start-marker
(> (point)
(marker-position pi-coding-agent--message-start-marker)))
(pi-coding-agent--ensure-blank-line-before-block))
;; Track thinking insertion separately so it stays anchored even if
;; other block types (tool headers) interleave in the same message.
;; Keep insertion-type nil so inserts at this exact point happen
;; after the marker (we then advance it explicitly per delta).
(pi-coding-agent--reset-thinking-state)
(setq pi-coding-agent--thinking-raw "")
(let ((start (point)))
(insert "> ")
(setq pi-coding-agent--thinking-start-marker
(copy-marker start nil))
(setq pi-coding-agent--thinking-marker
(copy-marker (point) nil))))))))
(defun pi-coding-agent--display-thinking-delta (delta)
"Display streaming thinking DELTA in the current thinking block.
Normalizes boundary and paragraph whitespace while streaming."
(when (and delta pi-coding-agent--streaming-marker)
(let ((inhibit-read-only t))
(if (and pi-coding-agent--thinking-start-marker
pi-coding-agent--thinking-marker)
(progn
(setq pi-coding-agent--thinking-raw
(concat (or pi-coding-agent--thinking-raw "") delta))
(pi-coding-agent--with-scroll-preservation
(save-excursion
(pi-coding-agent--render-thinking-content))))
;; Fallback for malformed event streams that skip thinking_start.
(let ((transformed (replace-regexp-in-string "\n" "\n> " delta)))
(pi-coding-agent--with-scroll-preservation
(save-excursion
(goto-char (pi-coding-agent--thinking-insert-position))
(insert transformed)
(when pi-coding-agent--thinking-marker
(set-marker pi-coding-agent--thinking-marker (point))))))))))
(defun pi-coding-agent--display-thinking-end (_content)
"End thinking block (blockquote).
CONTENT is ignored - we use what was already streamed."
(when pi-coding-agent--streaming-marker
(setq pi-coding-agent--in-thinking-block nil)
(let ((inhibit-read-only t))
(pi-coding-agent--with-scroll-preservation
(save-excursion
(if (and pi-coding-agent--thinking-start-marker
pi-coding-agent--thinking-marker)
(when (pi-coding-agent--render-thinking-content)
(goto-char (pi-coding-agent--thinking-insert-position))
(pi-coding-agent--ensure-blank-line-separator))
;; Fallback for malformed event streams that skip thinking_start.
(goto-char (pi-coding-agent--thinking-insert-position))
(pi-coding-agent--ensure-blank-line-separator))
(pi-coding-agent--reset-thinking-state))))))
(defun pi-coding-agent--display-agent-end ()
"Finalize agent turn: normalize whitespace, handle abort, process queue.
Note: status is set to `idle' by the event handler."
;; Reset per-turn state for clean next turn.
(setq pi-coding-agent--local-user-message nil)
(setq pi-coding-agent--in-thinking-block nil)
(pi-coding-agent--reset-thinking-state)
(let ((was-aborted pi-coding-agent--aborted))
(let ((inhibit-read-only t))
(pi-coding-agent--finalize-live-tool-blocks 'pi-coding-agent-tool-block-error)
(when pi-coding-agent--tool-args-cache
(clrhash pi-coding-agent--tool-args-cache))
;; Abort means "stop everything" — discard queued follow-ups too
(when pi-coding-agent--aborted
(pi-coding-agent--with-scroll-preservation
(save-excursion
(goto-char (point-max))
;; Remove trailing whitespace before adding indicator
(skip-chars-backward " \t\n")
(delete-region (point) (point-max))
(insert "\n\n" (propertize "[Aborted]" 'face 'error) "\n")))
(pi-coding-agent--set-aborted nil)
(pi-coding-agent--clear-followup-queue))
(pi-coding-agent--with-scroll-preservation
(save-excursion
(goto-char (point-max))
(skip-chars-backward "\n")
(delete-region (point) (point-max))
(insert "\n"))))
(pi-coding-agent--set-activity-phase "idle")
(pi-coding-agent--refresh-header)
;; Check follow-up queue and send next message if any (unless aborted)
(unless was-aborted
(pi-coding-agent--process-followup-queue))))
(defun pi-coding-agent--dispatch-builtin-command (text)
"Try to dispatch TEXT as a built-in slash command.
Returns non-nil if TEXT matched a built-in command and was handled."
(when (string-prefix-p "/" text)
(let* ((without-slash (substring text 1))
(words (split-string without-slash))
(cmd-name (car words))
(entry (assoc cmd-name pi-coding-agent--builtin-commands)))
(when entry
(let ((handler (plist-get (cdr entry) :handler))
(args-spec (plist-get (cdr entry) :args))
(arg-str (let ((rest (string-trim
(substring without-slash (length cmd-name)))))
(and (not (string-empty-p rest)) rest))))
(pcase args-spec
('optional (funcall handler arg-str))
('required (if arg-str
(funcall handler arg-str)
(call-interactively handler)))
(_ (funcall handler)))
t)))))
(defun pi-coding-agent--prepare-and-send (text)
"Prepare chat buffer state and send TEXT to pi.
Built-in slash commands are dispatched locally via the dispatch table.
Other slash commands (extensions, skills, prompts) are sent to pi.
Regular text is displayed locally for responsiveness, then sent.
Must be called with chat buffer current.
Status transitions are handled by pi events (agent_start, agent_end)."
(cond
;; Built-in slash commands: dispatch locally
((pi-coding-agent--dispatch-builtin-command text))
;; Other slash commands: don't display locally, send to pi
((string-prefix-p "/" text)
(pi-coding-agent--send-prompt text))
;; Regular text: display locally for responsiveness, then send
(t
(pi-coding-agent--display-user-message text (current-time))
(setq pi-coding-agent--local-user-message text)
(setq pi-coding-agent--assistant-header-shown nil)
(pi-coding-agent--send-prompt text))))
(defun pi-coding-agent--process-followup-queue ()
"Dequeue and send the oldest follow-up message.
Does nothing if queue is empty. Messages are processed in FIFO order."
(when-let* ((text (pi-coding-agent--dequeue-followup)))
(pi-coding-agent--prepare-and-send text)))
(defun pi-coding-agent--display-retry-start (event)
"Display retry notice from auto_retry_start EVENT.
Shows attempt number, delay, and raw error message."
(let* ((attempt (plist-get event :attempt))
(max-attempts (plist-get event :maxAttempts))
(delay-ms (plist-get event :delayMs))
(error-msg (or (plist-get event :errorMessage) "transient error"))
(delay-sec (/ (or delay-ms 0) 1000.0))
(notice (format "⟳ Retry %d/%d in %.0fs — %s"
(or attempt 1)
(or max-attempts 3)
delay-sec
error-msg)))
(pi-coding-agent--append-to-chat
(concat (propertize notice 'face 'pi-coding-agent-retry-notice) "\n"))))
(defun pi-coding-agent--display-retry-end (event)
"Display retry result from auto_retry_end EVENT.
Shows success or final failure with raw error."
(let* ((success (plist-get event :success))
(attempt (plist-get event :attempt))
(final-error (or (plist-get event :finalError) "unknown error")))
(if (eq success t)
(pi-coding-agent--append-to-chat
(concat (propertize (format "✓ Retry succeeded on attempt %d"
(or attempt 1))
'face 'pi-coding-agent-retry-notice)
"\n\n"))
;; Final failure
(pi-coding-agent--append-to-chat
(concat (propertize (format "✗ Retry failed after %d attempts — %s"
(or attempt 1)
final-error)
'face 'pi-coding-agent-error-notice)
"\n\n")))))
(defun pi-coding-agent--display-error (error-msg)
"Display ERROR-MSG from the server."
(pi-coding-agent--append-to-chat
(concat "\n" (propertize (format "[Error: %s]" (or error-msg "unknown"))
'face 'pi-coding-agent-error-notice)
"\n")))
(defun pi-coding-agent--display-extension-error (event)
"Display extension error from extension_error EVENT."
(let* ((extension-path (plist-get event :extensionPath))
(extension-event (plist-get event :event))
(error-msg (plist-get event :error))
(extension-name (if extension-path (file-name-nondirectory extension-path) "unknown")))
(pi-coding-agent--append-to-chat
(concat "\n"
(propertize (format "[Extension error in %s (%s): %s]"
extension-name
(or extension-event "unknown")
(or error-msg "unknown error"))
'face 'pi-coding-agent-error-notice)
"\n"))))
(defun pi-coding-agent--extension-ui-notify (event)
"Handle notify method from EVENT."
(let ((msg (plist-get event :message))
(notify-type (plist-get event :notifyType)))
(message "Pi: %s%s"
(pcase notify-type
("warning" "⚠ ")
("error" "✗ ")
(_ ""))
msg)))
(defun pi-coding-agent--extension-ui-confirm (event proc)
"Handle confirm method from EVENT, responding via PROC."
(let* ((id (plist-get event :id))
(title (plist-get event :title))
(msg (plist-get event :message))
;; Don't add colon if title already ends with one
(separator (if (string-suffix-p ":" title) " " ": "))
(prompt (format "%s%s%s " title separator msg))
(confirmed (yes-or-no-p prompt)))
(when proc
(pi-coding-agent--send-extension-ui-response proc
(list :type "extension_ui_response"
:id id
:confirmed (if confirmed t :json-false))))))
(defun pi-coding-agent--extension-ui-select (event proc)
"Handle select method from EVENT, responding via PROC."
(let* ((id (plist-get event :id))
(title (plist-get event :title))
(options (append (plist-get event :options) nil))
(selected (completing-read (concat title " ") options nil t)))
(when proc
(pi-coding-agent--send-extension-ui-response proc
(list :type "extension_ui_response"
:id id
:value selected)))))
(defun pi-coding-agent--extension-ui-input (event proc)
"Handle input method from EVENT, responding via PROC."
(let* ((id (plist-get event :id))
(title (plist-get event :title))
(placeholder (plist-get event :placeholder))
(value (read-string (concat title " ") placeholder)))
(when proc
(pi-coding-agent--send-extension-ui-response proc
(list :type "extension_ui_response"
:id id
:value value)))))
(defun pi-coding-agent--extension-ui-set-editor-text (event)
"Handle set_editor_text method from EVENT."
(let ((text (plist-get event :text)))
(when-let* ((input-buf pi-coding-agent--input-buffer))
(when (buffer-live-p input-buf)
(with-current-buffer input-buf
(erase-buffer)
(insert text))))))
(defun pi-coding-agent--extension-ui-set-status (event)
"Handle setStatus method from EVENT."
(let ((key (plist-get event :statusKey))
(text (plist-get event :statusText)))
(when text
(setq text (ansi-color-filter-apply text)))
(if text
(setq pi-coding-agent--extension-status
(cons (cons key text)
(assoc-delete-all key pi-coding-agent--extension-status)))
(setq pi-coding-agent--extension-status
(assoc-delete-all key pi-coding-agent--extension-status)))
(force-mode-line-update t)))
(defun pi-coding-agent--extension-ui-set-working-message (event)
"Handle setWorkingMessage method from EVENT."
(let ((msg (plist-get event :message)))
(when msg
(setq msg (ansi-color-filter-apply msg)))
(setq pi-coding-agent--working-message msg)
(force-mode-line-update t)))
(defun pi-coding-agent--extension-ui-unsupported (event proc)
"Handle unsupported method from EVENT by sending cancelled via PROC."
(when proc
(pi-coding-agent--rpc-async proc
(list :type "extension_ui_response"
:id (plist-get event :id)
:cancelled t)
#'ignore)))
(defun pi-coding-agent--handle-extension-ui-request (event)
"Handle extension_ui_request EVENT from pi.
Dispatches to appropriate handler based on method."
(let ((method (plist-get event :method))
(proc pi-coding-agent--process))
(pcase method
("notify" (pi-coding-agent--extension-ui-notify event))
("confirm" (pi-coding-agent--extension-ui-confirm event proc))
("select" (pi-coding-agent--extension-ui-select event proc))
("input" (pi-coding-agent--extension-ui-input event proc))
("set_editor_text" (pi-coding-agent--extension-ui-set-editor-text event))
("setStatus" (pi-coding-agent--extension-ui-set-status event))
("setWorkingMessage" (pi-coding-agent--extension-ui-set-working-message event))
(_ (pi-coding-agent--extension-ui-unsupported event proc)))))
(defun pi-coding-agent--display-no-model-warning ()
"Display warning when no model is available.
Shown when the session starts without a configured model/API key."
(pi-coding-agent--append-to-chat
(concat "\n"
(propertize "⚠ No models available"
'face 'pi-coding-agent-error-notice)
"\n\n"
(propertize "To get started, either:\n"
'face 'pi-coding-agent-retry-notice)
(propertize " • Set an API key: "
'face 'pi-coding-agent-retry-notice)
"ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, etc.\n"
(propertize " • Or run "
'face 'pi-coding-agent-retry-notice)
(propertize "pi --login"
'face 'pi-coding-agent-tool-command)
(propertize " in a terminal to authenticate via OAuth\n"
'face 'pi-coding-agent-retry-notice)
"\n")))
(defun pi-coding-agent--cleanup-on-kill ()
"Clean up resources when chat buffer is killed.
Also kills the linked input buffer and fontification cache buffers.
Note: This runs from `kill-buffer-hook', which executes AFTER the kill
decision is made. For proper cancellation support, use `pi-coding-agent-quit'
which asks upfront before any buffers are touched."
(when (derived-mode-p 'pi-coding-agent-chat-mode)
(when pi-coding-agent--process
(pi-coding-agent--unregister-display-handler pi-coding-agent--process)
(when (process-live-p pi-coding-agent--process)
(delete-process pi-coding-agent--process)))
(when (and pi-coding-agent--input-buffer (buffer-live-p pi-coding-agent--input-buffer))
(let ((input-buf pi-coding-agent--input-buffer))
(pi-coding-agent--set-input-buffer nil) ; break cycle before kill
(kill-buffer input-buf)))
(pi-coding-agent--cleanup-visible-string-buffer)))
(defun pi-coding-agent--cleanup-input-on-kill ()
"Clean up when input buffer is killed.
Also kills the linked chat buffer (which handles process cleanup).
Note: This runs from `kill-buffer-hook', which executes AFTER the kill
decision is made. For proper cancellation support, use `pi-coding-agent-quit'
which asks upfront before any buffers are touched."
(when (derived-mode-p 'pi-coding-agent-input-mode)
(when (and pi-coding-agent--chat-buffer (buffer-live-p pi-coding-agent--chat-buffer))
(let* ((chat-buf pi-coding-agent--chat-buffer)
(proc (buffer-local-value 'pi-coding-agent--process chat-buf)))
(pi-coding-agent--set-chat-buffer nil) ; break cycle before kill
(when (and proc (process-live-p proc))
(set-process-query-on-exit-flag proc nil))
(kill-buffer chat-buf)))))
(defun pi-coding-agent--register-display-handler (process)
"Register display event handler for PROCESS."
(let ((handler (pi-coding-agent--make-display-handler process)))
(process-put process 'pi-coding-agent-display-handler handler)))
(defun pi-coding-agent--unregister-display-handler (process)
"Unregister display event handler for PROCESS."
(process-put process 'pi-coding-agent-display-handler nil))
(defun pi-coding-agent--make-display-handler (process)
"Create a display event handler for PROCESS."
(lambda (event)
(when-let* ((chat-buf (process-get process 'pi-coding-agent-chat-buffer)))
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--handle-display-event event))))))
(defun pi-coding-agent--handle-display-event (event)
"Handle EVENT for display purposes.
Updates buffer-local state and renders display updates."
;; Update state first (now buffer-local)
(pi-coding-agent--update-state-from-event event)
;; Then handle display
(pcase (plist-get event :type)
("agent_start"
(pi-coding-agent--display-agent-start))
("message_start"
(let* ((message (plist-get event :message))
(role (plist-get message :role)))
;; A new message starts a fresh rendering context.
(setq pi-coding-agent--in-thinking-block nil)
(pi-coding-agent--reset-thinking-state)
(pcase role
("user"
;; User message from pi - check if we displayed it locally
(let* ((content (plist-get message :content))
(timestamp (plist-get message :timestamp))
(text (when content
(pi-coding-agent--extract-user-message-text content)))
(local-msg pi-coding-agent--local-user-message))
;; Clear local tracking
(setq pi-coding-agent--local-user-message nil)
;; Display if: no local message, OR pi's message differs (expanded template)
(when (and text
(or (null local-msg)
(not (string= text local-msg))))
(pi-coding-agent--display-user-message
text
(pi-coding-agent--ms-to-time timestamp))
;; Reset so next assistant message shows its header
(setq pi-coding-agent--assistant-header-shown nil))))
("custom"
;; Custom message from extension (e.g., /pisay)
;; Display content directly if display flag is set
(when (plist-get message :display)
(let ((content (plist-get message :content)))
(when (and content (stringp content) (> (length content) 0))
(let ((start (point-max)))
(pi-coding-agent--append-to-chat (concat "\n" content "\n"))
(pi-coding-agent--decorate-tables-in-region start (point-max)))
;; Reset so next assistant message shows its header
(setq pi-coding-agent--assistant-header-shown nil)))))
(_
;; Assistant message - show header if needed, reset markers
(unless pi-coding-agent--assistant-header-shown
(pi-coding-agent--append-to-chat
(concat "\n" (pi-coding-agent--make-separator "Assistant") "\n"))
(setq pi-coding-agent--assistant-header-shown t))
(pi-coding-agent--set-message-start-marker (copy-marker (point-max) nil))
(pi-coding-agent--set-streaming-marker (copy-marker (point-max) t))))))
("message_update"
(when-let* ((msg-event (plist-get event :assistantMessageEvent))
(event-type (plist-get msg-event :type)))
(pcase event-type
("text_start") ; No-op: text block started, nothing to render
("text_delta"
(pi-coding-agent--set-activity-phase "replying")
(pi-coding-agent--display-message-delta (plist-get msg-event :delta)))
("text_end"
;; Text block ended — finalize any active table that may have
;; a trailing row without newline (backstop for streaming).
(pi-coding-agent--maybe-decorate-streaming-table))
("thinking_start"
(pi-coding-agent--display-thinking-start))
("thinking_delta"
(pi-coding-agent--display-thinking-delta (plist-get msg-event :delta)))
("thinking_end"
(pi-coding-agent--display-thinking-end (plist-get msg-event :content)))
((or "toolcall_start" "toolcall_delta" "toolcall_end")
;; Preview reconciliation follows the authoritative assistant
;; message content, not a singleton streaming-tool state machine.
(pi-coding-agent--set-activity-phase "running")
(pi-coding-agent--reconcile-toolcall-previews
(plist-get event :message)))
("error"
;; Error during streaming (e.g., API error)
(pi-coding-agent--display-error (plist-get msg-event :reason))))))
("message_end"
(let* ((message (plist-get event :message))
(assistant-p (equal (plist-get message :role) "assistant")))
;; Display error if message ended with error (e.g., API error)
(when (equal (plist-get message :stopReason) "error")
(pi-coding-agent--display-error (plist-get message :errorMessage)))
;; Capture usage from assistant messages for context % calculation.
;; Skip aborted messages - they may have incomplete usage data and
;; would reset context percentage. Matches TUI footer.ts behavior.
;; Note: error messages DO have valid usage data (tokens were consumed).
(when (and assistant-p
(not (equal (plist-get message :stopReason) "aborted"))
(plist-get message :usage))
(pi-coding-agent--set-last-usage (plist-get message :usage)))
;; Refresh cumulative stats after each assistant message_end so
;; cost and totals update without waiting for agent_end.
(when assistant-p
(pi-coding-agent--refresh-header)))
(pi-coding-agent--render-complete-message))
("tool_execution_start"
(pi-coding-agent--set-activity-phase "running")
(let* ((tool-call-id (plist-get event :toolCallId))
(args (plist-get event :args))
(block (pi-coding-agent--tool-block-get tool-call-id)))
;; Cache args for tool_execution_end (which doesn't include args)
(when (and tool-call-id pi-coding-agent--tool-args-cache)
(puthash tool-call-id args pi-coding-agent--tool-args-cache))
;; Reuse the keyed preview block when it already exists.
(unless block
(setq block (pi-coding-agent--display-tool-start
(plist-get event :toolName) args tool-call-id)))
;; Update header and path from authoritative args.
;; During streaming, the header may show placeholders since delta
;; args can be partial. Execution start carries the real args.
(pi-coding-agent--display-tool-update-header
(plist-get event :toolName) args block)
(when-let* ((path (pi-coding-agent--tool-path args)))
(pi-coding-agent--tool-block-set-path block path))))
("tool_execution_end"
(pi-coding-agent--set-activity-phase "thinking")
(let* ((tool-call-id (plist-get event :toolCallId))
(result (plist-get event :result))
(block (pi-coding-agent--tool-block-get tool-call-id))
;; Retrieve cached args since tool_execution_end doesn't include args
(args (when (and tool-call-id pi-coding-agent--tool-args-cache)
(prog1 (gethash tool-call-id pi-coding-agent--tool-args-cache)
(remhash tool-call-id pi-coding-agent--tool-args-cache)))))
(pi-coding-agent--display-tool-end (plist-get event :toolName)
args
(plist-get result :content)
(plist-get result :details)
(plist-get event :isError)
block)))
("tool_execution_update"
(pi-coding-agent--display-tool-update
(plist-get event :partialResult)
(pi-coding-agent--tool-block-get (plist-get event :toolCallId))))
("auto_compaction_start"
(setq pi-coding-agent--status 'compacting)
(pi-coding-agent--set-activity-phase "compact")
(let ((reason (plist-get event :reason)))
(message "Pi: %sAuto-compacting... (C-c C-k to cancel)"
(if (equal reason "overflow") "Context overflow, " ""))))
("auto_compaction_end"
(setq pi-coding-agent--status 'idle)
(pi-coding-agent--set-activity-phase "idle")
(if (pi-coding-agent--normalize-boolean (plist-get event :aborted))
(progn
(message "Pi: Auto-compaction cancelled")
;; Clear queue on abort (user wanted to stop)
(pi-coding-agent--clear-followup-queue))
(when-let* ((result (plist-get event :result)))
(pi-coding-agent--handle-compaction-success
(plist-get result :tokensBefore)
(plist-get result :summary)
(pi-coding-agent--ms-to-time (plist-get result :timestamp))))
;; Process followup queue after successful compaction
(pi-coding-agent--process-followup-queue)))
("agent_end"
(pi-coding-agent--display-agent-end)
(pi-coding-agent--update-hot-tail-boundary)
(pi-coding-agent--cool-completed-tool-blocks-outside-hot-tail))
("auto_retry_start"
(pi-coding-agent--display-retry-start event))
("auto_retry_end"
(pi-coding-agent--display-retry-end event))
("extension_error"
(pi-coding-agent--display-extension-error event))
("extension_ui_request"
(pi-coding-agent--handle-extension-ui-request event))))
;;;; Tool Output
(defun pi-coding-agent--truncate-to-visual-lines (content max-lines width)
"Truncate CONTENT to fit within MAX-LINES visual lines at WIDTH.
Also respects `pi-coding-agent-preview-max-bytes'.
Strips blank lines for compact display but tracks original line numbers.
Returns a plist with:
:content - the truncated content (or original if no truncation)
:visual-lines - number of visual lines in result
:hidden-lines - raw lines hidden (including stripped blanks)
:line-map - vector mapping displayed line to original line number"
(let* ((safe-max-lines (max 0 (or max-lines 0)))
(safe-width (max 1 (or width 1)))
(trimmed (string-trim-right content "\n+"))
(all-lines (if (string-empty-p trimmed)
nil
(split-string trimmed "\n")))
(total-raw-lines (length all-lines))
(visual-count 0)
(byte-count 0)
(max-bytes pi-coding-agent-preview-max-bytes)
(result-lines nil)
(line-map nil) ; list of original line numbers for kept lines
(truncated-first-line nil)
(original-line-num 0))
(if (= safe-max-lines 0)
(list :content ""
:visual-lines 0
:hidden-lines total-raw-lines
:line-map [])
;; Accumulate non-blank lines until we'd exceed limits
(catch 'done
(dolist (line all-lines)
(setq original-line-num (1+ original-line-num))
;; Skip blank lines (they don't count toward visual limit)
(unless (string-empty-p line)
(let* ((line-len (length line))
;; Visual lines: ceiling(length / width), minimum 1
(line-visual-lines (max 1 (ceiling (float line-len) safe-width)))
(new-visual-count (+ visual-count line-visual-lines))
;; +1 for newline between lines
(new-byte-count (+ byte-count line-len (if result-lines 1 0))))
;; Check if adding this line would exceed limits
(cond
;; Not first line and exceeds limits: stop
((and result-lines
(or (> new-visual-count safe-max-lines)
(> new-byte-count max-bytes)))
(throw 'done nil))
;; First line exceeds limits: truncate it to fit
((and (null result-lines)
(or (> new-visual-count safe-max-lines)
(> new-byte-count max-bytes)))
(let* ((max-chars-by-visual (* safe-max-lines safe-width))
(max-chars (min max-chars-by-visual max-bytes)))
(setq line (substring line 0 (min line-len max-chars)))
(setq line-len (length line))
(setq line-visual-lines (max 1 (ceiling (float line-len) safe-width)))
(setq new-visual-count line-visual-lines)
(setq new-byte-count line-len)
(setq truncated-first-line t))))
(setq visual-count new-visual-count)
(setq byte-count new-byte-count)
(push line result-lines)
(push original-line-num line-map)))))
(let* ((kept-lines (nreverse result-lines))
(line-map-vec (vconcat (nreverse line-map)))
(last-displayed (if (> (length line-map-vec) 0)
(aref line-map-vec (1- (length line-map-vec)))
0))
(hidden (- total-raw-lines last-displayed)))
(list :content (string-join kept-lines "\n")
:visual-lines visual-count
;; Report hidden lines; truncated first line means there's hidden content even with 1 line
:hidden-lines (if (and truncated-first-line (= hidden 0)) 1 hidden)
:line-map line-map-vec)))))
(defun pi-coding-agent--clear-render-artifacts ()
"Delete pi-owned render overlays in the current chat buffer.
This removes completed/pending tool overlays and diff overlays before
buffer reset or history rebuild, then clears keyed live-tool state,
cached execution args, and the compatibility pending overlay slot so
buffer state and overlay state stay consistent. Tree-sitter overlays
are left alone."
(remove-overlays (point-min) (point-max) 'pi-coding-agent-tool-block t)
(remove-overlays (point-min) (point-max) 'pi-coding-agent-diff-overlay t)
(setq pi-coding-agent--pending-tool-overlay nil
pi-coding-agent--tool-block-order-counter 0)
(when pi-coding-agent--tool-args-cache
(clrhash pi-coding-agent--tool-args-cache))
(when pi-coding-agent--live-tool-blocks
(clrhash pi-coding-agent--live-tool-blocks)))
(cl-defstruct (pi-coding-agent--tool-block
(:constructor pi-coding-agent--make-tool-block))
tool-call-id
overlay
header-end
end-marker
order
path
offset
line-map
last-tail)
(defun pi-coding-agent--ensure-live-tool-blocks ()
"Return the live tool block registry for the current buffer."
(or pi-coding-agent--live-tool-blocks
(setq pi-coding-agent--live-tool-blocks
(make-hash-table :test 'equal))))
(defun pi-coding-agent--next-tool-block-order ()
"Return the next monotonically increasing live tool block order."
(let ((order (or pi-coding-agent--tool-block-order-counter 0)))
(setq pi-coding-agent--tool-block-order-counter (1+ order))
order))
(defun pi-coding-agent--reserve-tool-block-order (&optional order)
"Return ORDER, or allocate the next implicit live tool block order.
When ORDER is non-nil, advance the monotonic counter past it so later
implicit insertions still sort after explicitly ordered preview blocks."
(if order
(progn
(setq pi-coding-agent--tool-block-order-counter
(max (or pi-coding-agent--tool-block-order-counter 0)
(1+ order)))
order)
(pi-coding-agent--next-tool-block-order)))
(defun pi-coding-agent--tool-block-get (tool-call-id)
"Return the live tool block for TOOL-CALL-ID, or nil."
(when (and tool-call-id pi-coding-agent--live-tool-blocks)
(gethash tool-call-id pi-coding-agent--live-tool-blocks)))
(defun pi-coding-agent--live-tool-blocks-in-order ()
"Return all live tool blocks sorted by their recorded order."
(let (blocks)
(when pi-coding-agent--live-tool-blocks
(maphash (lambda (_tool-call-id block)
(push block blocks))
pi-coding-agent--live-tool-blocks))
(sort blocks
(lambda (left right)
(< (pi-coding-agent--tool-block-order left)
(pi-coding-agent--tool-block-order right))))))
(defun pi-coding-agent--tool-block-next-after-order (order)
"Return the first live tool block whose order is greater than ORDER."
(seq-find (lambda (block)
(> (pi-coding-agent--tool-block-order block) order))
(pi-coding-agent--live-tool-blocks-in-order)))
(defun pi-coding-agent--tool-block-register (block)
"Register BLOCK in the keyed live registry when it has a tool call ID."
(when-let* ((tool-call-id (pi-coding-agent--tool-block-tool-call-id block)))