-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsidebar.lua
More file actions
3152 lines (2672 loc) · 103 KB
/
sidebar.lua
File metadata and controls
3152 lines (2672 loc) · 103 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
local Utils = require("eca.utils")
local Logger = require("eca.logger")
local Config = require("eca.config")
local StreamQueue = require("eca.stream_queue")
-- Load nui.nvim components (required dependency)
local Split = require("nui.split")
---@class eca.Sidebar
---@field public id integer The tab ID
---@field public containers table<string, NuiSplit> The nui containers
---@field public extmarks table The extmarks for various UI elements
---@field mediator eca.Mediator mediator to send server requests to
---@field private _initialized boolean Whether the sidebar has been initialized
---@field private _current_response_buffer string Buffer for accumulating streaming response
---@field private _is_streaming boolean Whether we're currently receiving a streaming response
---@field private _usage_info string Current usage information
---@field private _last_user_message string Last user message to avoid duplicates
---@field private _current_tool_call table Current tool call being accumulated
---@field private _is_tool_call_streaming boolean Whether we're currently receiving a streaming tool call
---@field private _force_welcome boolean Whether to force show welcome content on next open
---@field private _current_status string Current processing status message
---@field private _augroup integer Autocmd group ID
---@field private _response_start_time number Timestamp when streaming started
---@field private _max_response_length number Maximum allowed response length
---@field private _headers table Table of headers for the chat
---@field private _welcome_message_applied boolean Whether the welcome message has been applied
---@field private _contexts_placeholder_line string Placeholder line for contexts in input
---@field private _reasons table Map of in-flight reasoning entries keyed by id
---@field private _stream_queue eca.StreamQueue Queue for streaming text display
---@field private _stream_visible_buffer string Accumulated visible text during streaming
local M = {}
M.__index = M
-- Height calculation constants
local MIN_CHAT_HEIGHT = 10 -- Minimum lines for chat container to remain usable
local WINDOW_MARGIN = 3 -- Additional margin for window borders and spacing
local UI_ELEMENTS_HEIGHT = 2 -- Reserve space for statusline and tabline
local SAFETY_MARGIN = 2 -- Extra margin to prevent "Not enough room" errors
local function _format_usage(tokens, limit, costs)
local usage_cfg = (Config.windows and Config.windows.usage) or {}
local fmt = usage_cfg.format
or Config.usage_string_format -- backwards compatibility
or "{session_tokens_short} / {limit_tokens_short} (${session_cost})"
local placeholders = {
session_tokens = tostring(tokens or 0),
limit_tokens = tostring(limit or 0),
session_tokens_short = Utils.shorten_tokens(tokens),
limit_tokens_short = Utils.shorten_tokens(limit),
session_cost = tostring(costs or "0.00"),
}
local result = fmt:gsub("{(.-)}", function(key)
return placeholders[key] or ""
end)
return result
end
---@param id integer Tab ID
---@param mediator eca.Mediator
---@return eca.Sidebar
function M.new(id, mediator)
local chat_cfg = Utils.get_chat_config()
local instance = setmetatable({}, M)
instance.id = id
instance.mediator = mediator
instance.containers = {}
instance.extmarks = {}
instance._initialized = false
instance._current_response_buffer = ""
instance._is_streaming = false
instance._usage_info = ""
instance._last_user_message = ""
instance._current_tool_call = nil
instance._is_tool_call_streaming = false
instance._force_welcome = false
instance._current_status = ""
instance._augroup = vim.api.nvim_create_augroup("eca_sidebar_" .. id, { clear = true })
instance._response_start_time = 0
instance._max_response_length = 50000 -- 50KB max response
instance._headers = {
user = (chat_cfg.headers and chat_cfg.headers.user) or "> ",
assistant = (chat_cfg.headers and chat_cfg.headers.assistant) or "",
}
instance._welcome_message_applied = false
instance._contexts_placeholder_line = ""
instance._contexts = {}
instance._tool_calls = {}
instance._reasons = {}
instance._stream_visible_buffer = ""
-- Get typing configuration
local typing_cfg = chat_cfg.typing or {}
local typing_enabled = typing_cfg.enabled ~= false -- Default to true
local chars_per_tick = typing_enabled and (typing_cfg.chars_per_tick or 1) or 1000 -- Large number = instant
local tick_delay = typing_enabled and (typing_cfg.tick_delay or 10) or 0
-- Initialize stream queue with callback to update display
instance._stream_queue = StreamQueue.new(function(chunk, is_complete)
instance._stream_visible_buffer = (instance._stream_visible_buffer or "") .. chunk
instance:_update_streaming_message(instance._stream_visible_buffer)
end, {
chars_per_tick = chars_per_tick,
tick_delay = tick_delay,
should_continue = function()
return instance._is_streaming
end,
})
require("eca.observer").subscribe("sidebar-" .. id, function(message)
instance:handle_chat_content(message)
end)
return instance
end
---@return boolean
function M:is_open()
return self.containers.chat and self.containers.chat.winid and vim.api.nvim_win_is_valid(self.containers.chat.winid)
end
---@param opts? table
function M:open(opts)
opts = opts or {}
if self:is_open() then
self:_focus_input()
return
end
-- Clean up any invalid containers
self:_cleanup_invalid_containers()
-- Create/recreate containers using nui.split
self:_create_containers()
-- Setup containers if not initialized or if we need to refresh content
if not self._initialized then
Logger.debug("Setting up containers (first time)")
self:_setup_containers()
else
Logger.debug("Reusing existing containers")
self:_refresh_container_content()
end
-- Always focus input when opening
self:_focus_input()
Logger.debug("ECA sidebar opened")
end
function M:close()
self:_close_windows_only()
end
function M:_close_windows_only()
for name, container in pairs(self.containers) do
if container and container.winid and vim.api.nvim_win_is_valid(container.winid) then
container:unmount()
-- Keep the container reference but mark window as invalid
container.winid = nil
end
end
Logger.debug("ECA sidebar windows closed")
end
function M:_close_and_cleanup()
for name, container in pairs(self.containers) do
if container then
if container.winid and vim.api.nvim_win_is_valid(container.winid) then
container:unmount()
end
-- Check if buffer is displayed elsewhere before deleting
if container.bufnr and vim.api.nvim_buf_is_valid(container.bufnr) then
local wins = vim.fn.win_findbuf(container.bufnr)
if #wins == 0 then
pcall(vim.api.nvim_buf_delete, container.bufnr, { force = true })
end
end
end
end
self.containers = {}
Logger.debug("ECA sidebar closed and cleaned up")
end
---@param opts? table
---@return boolean
function M:toggle(opts)
if self:is_open() then
self:close()
return false
else
self:open(opts)
return true
end
end
function M:focus()
if self:is_open() then
self:_focus_input()
else
self:open()
end
end
function M:resize()
if not self:is_open() then
return
end
-- Recalculate and update container sizes
self:_update_container_sizes()
end
function M:reset()
if self:is_open() then
self:_close_and_cleanup()
else
self:_close_and_cleanup()
end
-- Reset all state
self.containers = {}
self.extmarks = {}
self._initialized = false
self._is_streaming = false
self._current_response_buffer = ""
self._usage_info = ""
self._last_user_message = ""
self._current_tool_call = nil
self._is_tool_call_streaming = false
self._force_welcome = false
self._current_status = ""
self._welcome_message_applied = false
self._contexts_placeholder_line = ""
self._contexts = {}
self._tool_calls = {}
self._reasons = {}
self._stream_visible_buffer = ""
if self._stream_queue then
self._stream_queue:clear()
end
end
function M:new_chat()
self:reset()
self._force_welcome = true
Logger.debug("New chat initiated - will show welcome content on next open")
end
---@private
function M:_cleanup_invalid_containers()
for name, container in pairs(self.containers) do
if container then
-- Check if window is still valid
if container.winid and not vim.api.nvim_win_is_valid(container.winid) then
container.winid = nil
end
-- Check if buffer is still valid
if container.bufnr and not vim.api.nvim_buf_is_valid(container.bufnr) then
container.bufnr = nil
end
end
end
end
---@private
function M:_create_containers()
local width = Config.get_window_width()
-- Calculate dynamic heights using existing methods
local input_height = Config.windows.input.height
local usage_height = 1
local original_chat_height = self:get_chat_height()
local chat_height = original_chat_height
local config_height = 1
-- Validate total height to prevent "Not enough room" error
local total_height = chat_height
+ input_height
+ usage_height
+ config_height
-- Always calculate from total screen minus UI elements (more accurate than current window)
local available_height = vim.o.lines - UI_ELEMENTS_HEIGHT
if total_height > available_height then
Logger.debug(
string.format(
"Total height (%d) exceeds available height (%d), adjusting chat height",
total_height,
available_height
)
)
local extra_height = total_height - (available_height - SAFETY_MARGIN)
chat_height = math.max(MIN_CHAT_HEIGHT, chat_height - extra_height)
Logger.debug(string.format("Adjusted chat height from %d to %d", original_chat_height, chat_height))
end
-- Base options for all containers
local base_buf_options = {
buftype = "nofile",
bufhidden = "hide",
swapfile = false,
}
local base_win_options = {
wrap = Config.windows.wrap,
number = false,
relativenumber = false,
signcolumn = "no",
foldcolumn = "0",
cursorline = false,
winfixheight = true,
winfixwidth = false,
}
-- Create and mount main chat container first
self.containers.chat = Split({
relative = "editor",
position = "right",
size = {
width = width,
height = chat_height,
},
buf_options = vim.tbl_deep_extend("force", base_buf_options, {
modifiable = true,
filetype = "markdown",
}),
win_options = base_win_options,
})
self.containers.chat:mount()
self:_setup_container_events(self.containers.chat, "chat")
-- Track the current container for hierarchical mounting with proper space management
local current_winid = self.containers.chat.winid
Logger.debug("Mounted container: chat (winid: " .. current_winid .. ")")
-- Create config container in top of chat
self.containers.config = Split({
relative = {
type = "win",
winid = current_winid,
},
position = "top",
size = { height = config_height },
buf_options = vim.tbl_deep_extend("force", base_buf_options, {
modifiable = false,
}),
win_options = vim.tbl_deep_extend("force", base_win_options, {
winhighlight = "Normal:Normal",
}),
})
self.containers.config:mount()
self:_setup_container_events(self.containers.config, "config")
Logger.debug("Mounted container: config (winid: " .. self.containers.config.winid .. ")")
-- Create input container (always present)
self.containers.input = Split({
relative = {
type = "win",
winid = current_winid,
},
position = "bottom",
size = { height = input_height },
buf_options = vim.tbl_deep_extend("force", base_buf_options, {
modifiable = true,
filetype = "eca-input",
}),
win_options = vim.tbl_deep_extend("force", base_win_options, {
statusline = " ",
}),
})
self.containers.input:mount()
self:_setup_container_events(self.containers.input, "input")
current_winid = self.containers.input.winid
Logger.debug("Mounted container: input (winid: " .. current_winid .. ")")
-- Create usage container (always present) - moved to bottom
self.containers.usage = Split({
relative = {
type = "win",
winid = current_winid,
},
enter = false,
position = "bottom",
size = { height = usage_height },
buf_options = vim.tbl_deep_extend("force", base_buf_options, {
modifiable = false,
}),
win_options = vim.tbl_deep_extend("force", base_win_options, {
winhighlight = "Normal:EcaLabel",
statusline = " ",
}),
})
self.containers.usage:mount()
self:_setup_container_events(self.containers.usage, "usage")
Logger.debug("Mounted container: usage (winid: " .. self.containers.usage.winid .. ")")
Logger.debug(
string.format(
"Created containers: chat=%d, input=%d, usage=%d, config=%d",
chat_height,
input_height,
usage_height,
config_height
)
)
end
---@private
---@param container NuiSplit
---@param name string
function M:_setup_container_events(container, name)
-- Setup container-specific keymaps
if name == "input" then
self:_setup_input_events(container)
self:_setup_input_keymaps(container)
elseif name == "chat" then
self:_setup_chat_keymaps(container)
end
end
---@private
---@param name string
function M:_handle_container_closed(name)
-- Handle when a container window is closed
if self.containers[name] then
self.containers[name].winid = nil
end
end
---@private
---@param container NuiSplit
function M:_setup_input_events(container)
vim.api.nvim_create_autocmd("User", {
pattern = { "CompletionItemSelected" },
callback = function(event)
if not event.data or not event.data.context_item or not event.data.label then
return
end
if self._contexts then
self._contexts.to_add = {
name = event.data.label,
type = event.data.context_item.type,
data = {
path = event.data.context_item.path
}
}
end
end,
})
-- contexts area and input handler
vim.api.nvim_buf_attach(container.bufnr, false, {
on_lines = function(_, buf, _changedtick, first, _last, _new_last, _bytecount)
vim.schedule(function()
local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
-- handle empty buffer
if not lines or #lines < 1 then
self:_update_input_display()
return
end
local prefix_extmark = self.extmarks.prefix or nil
local contexts_extmark = self.extmarks.contexts or nil
if not prefix_extmark or not contexts_extmark then
return
end
local prefix_ns = prefix_extmark._ns or nil
local prefix_id = prefix_extmark._id and prefix_extmark._id[1] or nil
if not prefix_ns or not prefix_id then
return
end
local prefix_mark = vim.api.nvim_buf_get_extmark_by_id(buf, prefix_ns, prefix_id, {})
local prefix_row = 1
if prefix_mark and type(prefix_mark) == "table" and prefix_mark[1] ~= nil then
prefix_row = tonumber(prefix_mark[1]) or 1
end
local contexts_row = 0
local prefix_line = lines[prefix_row + 1] or nil
local contexts_line = lines[contexts_row + 1] or nil
local contexts_placeholder_line = self._contexts_placeholder_line or ""
if prefix_row == contexts_row then
-- prefix line missing, restore
if contexts_line == contexts_placeholder_line then
self:_update_input_display()
return
end
-- we can consider that contexts were deleted
self.mediator:clear_contexts()
return
end
-- prefix line missing, restore
if not prefix_line and contexts_line == contexts_placeholder_line then
self:_update_input_display()
return
end
-- something wrong, restore
if prefix_row - contexts_row ~= 1 then
self:_update_input_display()
return
end
local context_to_add = self._contexts.to_add or {}
if contexts_line ~= contexts_placeholder_line then
-- a context was removed
if #contexts_line < #self._contexts_placeholder_line then
local contexts = self.mediator:contexts()
local row, col = unpack(vim.api.nvim_win_get_cursor(container.winid))
local context = contexts[col + 1]
if row == 1 and context then
self.mediator:remove_context(context)
return
end
end
-- contexts line modified
if #contexts_line > #self._contexts_placeholder_line then
local placeholders = vim.split(contexts_line, "@", { plain = true, trimempty = true })
for i = 1, #placeholders do
if context_to_add.name and context_to_add.name == placeholders[i] then
self.mediator:add_context(context_to_add)
self._contexts.to_add = {}
end
end
return
end
self:_update_input_display()
return
end
end)
end
})
end
---@private
---@param container NuiSplit
function M:_setup_input_keymaps(container)
-- Setup keymaps for input container
container:map("n", "<C-s>", function()
self:_handle_input()
end, { noremap = true, silent = true })
container:map("i", "<C-s>", function()
self:_handle_input()
end, { noremap = true, silent = true })
end
---@private
---@param container NuiSplit
function M:_setup_chat_keymaps(container)
-- Toggle tool call details when pressing <CR> on a tool call line
container:map("n", "<CR>", function()
self:_toggle_tool_call_at_cursor()
end, { noremap = true, silent = true })
end
---@private
function M:_update_container_sizes()
if not self:is_open() then
return
end
-- Recalculate heights
local new_heights = {
chat = self:get_chat_height(),
input = Config.windows.input.height,
usage = 1,
}
-- Update container sizes
for name, height in pairs(new_heights) do
local container = self.containers[name]
if container and container.winid and vim.api.nvim_win_is_valid(container.winid) then
if height > 0 then
vim.api.nvim_win_set_height(container.winid, height)
end
end
end
end
function M:get_chat_height()
local total_height = vim.o.lines - vim.o.cmdheight - 1
local input_height = Config.windows.input.height
local usage_height = 1
local config_height = 1
return math.max(
MIN_CHAT_HEIGHT,
total_height
- input_height
- usage_height
- WINDOW_MARGIN
- config_height
)
end
-- Placeholder methods for the display and setup functions
-- These will use the same logic as the original sidebar but with nui containers
function M:_setup_containers()
-- Setup each container's content and behavior
self:_setup_chat_container()
self:_update_config_display()
self:_setup_input_container()
self:_setup_usage_container()
self._initialized = true
end
function M:_refresh_container_content()
-- Refresh content without full setup
if self.containers.chat then
self:_set_welcome_content()
end
if self.containers.config then
self:_update_config_display()
end
if self.containers.input then
self:_update_input_display()
end
if self.containers.usage then
self:_update_usage_info()
end
end
function M:_handle_state_updated(state)
if state.contexts then
self:_update_input_display()
end
if state.usage or state.status then
self:_update_usage_info()
end
if state.config or state.tools then
self:_update_config_display()
self:_update_welcome_content()
end
end
-- Placeholder for all the other methods from original sidebar
-- (These would be copied over with minimal modifications to work with nui containers)
function M:_setup_chat_container()
local chat = self.containers.chat
if not chat then
return
end
-- Set buffer options for chat
vim.api.nvim_set_option_value("buftype", "nofile", { buf = chat.bufnr })
vim.api.nvim_set_option_value("bufhidden", "hide", { buf = chat.bufnr })
vim.api.nvim_set_option_value("swapfile", false, { buf = chat.bufnr })
vim.api.nvim_set_option_value("modifiable", true, { buf = chat.bufnr })
-- Disable treesitter initially to prevent highlighting errors during setup
vim.api.nvim_set_option_value("syntax", "off", { buf = chat.bufnr })
-- Set initial content first
self:_set_welcome_content()
-- Set filetype to markdown for syntax highlighting
vim.defer_fn(function()
if vim.api.nvim_buf_is_valid(chat.bufnr) then
vim.api.nvim_set_option_value("filetype", "markdown", { buf = chat.bufnr })
vim.api.nvim_set_option_value("syntax", "on", { buf = chat.bufnr })
end
end, 200)
end
function M:_setup_usage_container()
local usage = self.containers.usage
if not usage then
return
end
-- Set initial usage info
self:_update_usage_info()
end
function M:_setup_input_container()
local input = self.containers.input
if not input then
return
end
-- Set initial input prompt
self:_update_input_display()
end
-- Placeholder methods that need to be implemented
-- (These would be copied from the original sidebar with minimal modifications)
function M:_set_welcome_content()
-- Implementation from original sidebar
local chat = self.containers.chat
if not chat then
return
end
-- Check if we should force welcome content (new chat)
if not self._force_welcome then
-- Check if buffer already has content (more than just empty lines)
local existing_lines = vim.api.nvim_buf_get_lines(chat.bufnr, 0, -1, false)
local has_content = false
for _, line in ipairs(existing_lines) do
if line:match("%S") then -- Has non-whitespace content
has_content = true
break
end
end
-- Only set welcome content if buffer is empty or has no meaningful content
if has_content then
Logger.debug("Preserving existing chat content")
return
end
else
-- Force welcome content and reset the flag
Logger.debug("Forcing welcome content for new chat")
self._force_welcome = false
end
self:_update_welcome_content()
end
function M:_update_input_display(opts)
return vim.schedule(function()
local input = self.containers.input
if not input then
return
end
local contexts = (self.mediator and self.mediator:contexts()) or {}
local contexts_name = {}
if #contexts > 0 then
for _, context in ipairs(contexts) do
local path = context.data.path
if not path or path == "" then
break
end
local name
if context.type == "web" then
name = path
local max_len = (Config.windows and Config.windows.input and Config.windows.input.web_context_max_len) or 20
if #name > max_len then
name = string.sub(name, 1, max_len - 3) .. "..."
end
else
name = vim.fn.fnamemodify(path, ":t")
end
local lines_range = context.data.lines_range
if lines_range and lines_range.line_start and lines_range.line_end then
name = string.format("%s:%d-%d", name, lines_range.line_start, lines_range.line_end)
end
table.insert(contexts_name, name .. " ")
end
end
self._contexts_placeholder_line = "@"
for _ = 1, #contexts_name do
self._contexts_placeholder_line = self._contexts_placeholder_line .. "@"
end
local prefix_extmark = self.extmarks.prefix or nil
local prefix_ns = prefix_extmark and prefix_extmark._ns or nil
local prefix_id = prefix_extmark and prefix_extmark._id and prefix_extmark._id[1] or nil
local prefix_row = 1
if prefix_ns and prefix_id then
local prefix_mark = vim.api.nvim_buf_get_extmark_by_id(input.bufnr, prefix_ns, prefix_id, {})
prefix_row = prefix_mark and #prefix_mark > 0 and prefix_mark[1] or 1
end
-- Get existing lines to preserve user input (lines after the header)
local existing_lines = vim.api.nvim_buf_get_lines(input.bufnr, prefix_row, -1, false)
vim.api.nvim_buf_set_lines(input.bufnr, 0, -1, false, { self._contexts_placeholder_line, "" })
if not self.extmarks.contexts then
self.extmarks.contexts = {
_ns = vim.api.nvim_create_namespace('extmarks_contexts'),
}
end
if not self.extmarks.contexts._id then
self.extmarks.contexts._id = {}
end
vim.api.nvim_buf_clear_namespace(input.bufnr, self.extmarks.contexts._ns, 0, -1)
for i, context_name in ipairs(contexts_name) do
self.extmarks.contexts._id[i] = vim.api.nvim_buf_set_extmark(
input.bufnr,
self.extmarks.contexts._ns,
0,
i,
vim.tbl_extend("force",
{ virt_text = { { context_name, "EcaLabel" } }, virt_text_pos = "inline", hl_mode = "replace" },
{ id = self.extmarks.contexts._id[i] })
)
end
local prefix = Config.windows.input.prefix or "> "
if not self.extmarks.prefix then
self.extmarks.prefix = {
_ns = vim.api.nvim_create_namespace('extmarks_prefix'),
}
end
local clear = opts and opts.clear
if #existing_lines > 0 and not clear then
vim.api.nvim_buf_set_lines(input.bufnr, 1, 1 + #existing_lines, false, existing_lines)
end
if not self.extmarks.prefix._id then
self.extmarks.prefix._id = {}
end
self.extmarks.prefix._id[1] = vim.api.nvim_buf_set_extmark(
input.bufnr,
self.extmarks.prefix._ns,
1,
0,
vim.tbl_extend("force", { virt_text = { { prefix, "Normal" } }, virt_text_pos = "inline", right_gravity = false },
{ id = self.extmarks.prefix._id[1] })
)
-- Set cursor to end of input line
if vim.api.nvim_win_is_valid(input.winid) then
local row = 1 + ((not clear and existing_lines and #existing_lines > 0) and #existing_lines or 1)
local col = #prefix +
((not clear and existing_lines and #existing_lines > 0) and #existing_lines[#existing_lines] or 0)
vim.api.nvim_win_set_cursor(input.winid, { row, col })
end
end)
end
function M:_focus_input()
local input = self.containers.input
if not input or not vim.api.nvim_win_is_valid(input.winid) then
Logger.notify("Cannot focus input: invalid window", vim.log.levels.ERROR)
return
end
vim.defer_fn(function()
if vim.api.nvim_win_is_valid(input.winid) and vim.api.nvim_buf_is_valid(input.bufnr) then
vim.api.nvim_set_current_win(input.winid)
local lines = vim.api.nvim_buf_get_lines(input.bufnr, 0, -1, false)
local prefix = Config.windows.input.prefix or "> "
local row = 2
local col = #prefix
-- Ensure there is at least a header and a prefix line
if #lines < 2 then
row = 1
col = 0
end
vim.api.nvim_win_set_cursor(input.winid, { row, col })
-- Enter insert mode
if Config.windows and Config.windows.edit and Config.windows.edit.start_insert then
local mode = vim.api.nvim_get_mode().mode
if mode == "n" then
vim.cmd("startinsert!")
end
end
end
end, 100)
end
function M:_handle_input()
local input = self.containers.input
if not input then
return
end
local lines = vim.api.nvim_buf_get_lines(input.bufnr, 0, -1, false)
if #lines < 2 then
return
end
-- Process input: ignore first line (contexts header) and use second line onwards as input
local message_lines = {}
local prefix = Config.windows.input.prefix or "> "
for i = 2, #lines do
local line = lines[i]
local content = line
if i == 2 and vim.startswith(line, prefix) then
content = line:sub(#prefix + 1)
end
if content ~= "" then
table.insert(message_lines, content)
end
end
local message = table.concat(message_lines, "\n")
if message == "" then
return
end
-- Send message
self:_send_message(message)
-- Add new input line and focus
self:_update_input_display({ clear = true })
self:_focus_input()
end
function M:_update_config_display()
local config = self.containers.config
if not config or not config.bufnr or not vim.api.nvim_buf_is_valid(config.bufnr) then
return
end
local model = self.mediator:selected_model() or "unknown"
local behavior = self.mediator:selected_behavior() or "unknown"
local mcps = self.mediator:mcps()
local registered_count = vim.tbl_count(mcps)
local starting_count = 0
local running_count = 0
local has_failed = false
for _, mcp in pairs(mcps) do
if mcp.status == "starting" then
starting_count = starting_count + 1
elseif mcp.status == "running" then
running_count = running_count + 1
end
if mcp.status == "failed" then
has_failed = true
end
end
-- Active MCPs include both starting and running
local active_count = starting_count + running_count
-- While any MCP is still starting, dim the active count
local active_hl = "Normal"
if starting_count > 0 then
active_hl = "EcaLabel"
end
local registered_hl = "Normal"
if has_failed then
registered_hl = "Exception" -- highlight registered count in red when any MCP failed
elseif active_hl == "EcaLabel" then
-- While MCPs are still starting, dim the total count as well
registered_hl = "EcaLabel"
end
local texts = {
{ "model:", "EcaLabel" }, { model, "Normal" }, { " " },
{ "behavior:", "EcaLabel" }, { behavior, "Normal" }, { " " },
{ "mcps:", "EcaLabel" }, { tostring(active_count), active_hl }, { "/", "EcaLabel" },
{ tostring(registered_count), registered_hl },
}