-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathsession_manager.lua
More file actions
1471 lines (1272 loc) · 50.4 KB
/
session_manager.lua
File metadata and controls
1471 lines (1272 loc) · 50.4 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
-- The session manager class glues together the Chat widget, the agent instance, and the message writer.
-- It is responsible for managing the session state, routing messages between components, and handling user interactions.
-- When the user creates a new session, the SessionManager should be responsible for cleaning the existing session (if any) and initializing a new one.
-- When the user switches the provider, the SessionManager should handle the transition smoothly,
-- ensuring that the new session is properly set up and all the previous messages are sent to the new agent provider without duplicating them in the chat widget
local ACPPayloads = require("agentic.acp.acp_payloads")
local ChatHistory = require("agentic.ui.chat_history")
local Config = require("agentic.config")
local DiffPreview = require("agentic.ui.diff_preview")
local DiagnosticsList = require("agentic.ui.diagnostics_list")
local FileSystem = require("agentic.utils.file_system")
local Logger = require("agentic.utils.logger")
local SlashCommands = require("agentic.acp.slash_commands")
--- @class agentic._SessionManagerPrivate
local P = {}
--- Tool call kinds that mutate files on disk.
--- When these complete, buffers must be reloaded via checktime.
local FILE_MUTATING_KINDS = {
edit = true,
create = true,
write = true,
delete = true,
move = true,
}
--- Safely invoke a user-configured hook
--- @param hook_name "on_create_session_response" | "on_prompt_submit" | "on_response_complete" | "on_session_update" | "on_file_edit" | "on_request_permission"
--- @param data agentic.UserConfig.CreateSessionResponseData | agentic.UserConfig.PromptSubmitData | agentic.UserConfig.ResponseCompleteData | agentic.UserConfig.SessionUpdateData | agentic.UserConfig.FileEditData | agentic.UserConfig.RequestPermissionData
function P.invoke_hook(hook_name, data)
local hook = Config.hooks and Config.hooks[hook_name]
if hook and type(hook) == "function" then
vim.schedule(function()
local ok, err = pcall(hook, data)
if not ok then
Logger.debug(
string.format("Hook '%s' error: %s", hook_name, err)
)
end
end)
end
end
--- @class agentic.SessionManager
--- @field session_id? string
--- @field tab_page_id integer
--- @field _is_first_message boolean
--- @field is_generating boolean
--- @field widget agentic.ui.ChatWidget
--- @field agent agentic.acp.ACPClient
--- @field message_writer agentic.ui.MessageWriter
--- @field permission_manager agentic.ui.PermissionManager
--- @field status_animation agentic.ui.StatusAnimation
--- @field file_list agentic.ui.FileList
--- @field code_selection agentic.ui.CodeSelection
--- @field diagnostics_list agentic.ui.DiagnosticsList
--- @field config_options agentic.acp.AgentConfigOptions
--- @field todo_list agentic.ui.TodoList
--- @field chat_history agentic.ui.ChatHistory
--- @field history_to_send agentic.ui.ChatHistory.Message[]|nil
--- @field _is_restoring_session boolean
--- @field _connection_error boolean
--- @field _session_ready_callbacks fun()[]
--- @field _header_refresh_scheduled boolean Guards coalesced header refresh
local SessionManager = {}
SessionManager.__index = SessionManager
--- @param provider_name string
--- @param session_id string|nil
--- @param version string|nil
--- @param timestamp string|integer|nil Formatted string, unix timestamp, or nil for now
--- @return string header
function SessionManager._generate_welcome_header(
provider_name,
session_id,
version,
timestamp
)
local date_str
if type(timestamp) == "string" then
date_str = timestamp
else
date_str = os.date("%Y-%m-%d %H:%M:%S", timestamp)
end
local name = provider_name
if version then
name = name .. " v" .. version
end
return string.format(
"# Agentic - %s\n- session id: %s\n- %s\n--- --",
name,
session_id or "unknown",
date_str
)
end
--- @param tab_page_id integer
function SessionManager:new(tab_page_id)
local AgentInstance = require("agentic.acp.agent_instance")
local ChatWidget = require("agentic.ui.chat_widget")
local CodeSelection = require("agentic.ui.code_selection")
local FileList = require("agentic.ui.file_list")
local FilePicker = require("agentic.ui.file_picker")
local MessageWriter = require("agentic.ui.message_writer")
local PermissionManager = require("agentic.ui.permission_manager")
local StatusAnimation = require("agentic.ui.status_animation")
local TodoList = require("agentic.ui.todo_list")
local AgentConfigOptions = require("agentic.acp.agent_config_options")
self = setmetatable({
session_id = nil,
tab_page_id = tab_page_id,
_is_first_message = true,
is_generating = false,
_is_restoring_session = false,
_connection_error = false,
history_to_send = nil,
_session_ready_callbacks = {},
_header_refresh_scheduled = false,
}, self)
local agent = AgentInstance.get_instance(Config.provider, function(_client)
vim.schedule(function()
-- Guard: cached client may be dead
if
self.agent.state == "error"
or self.agent.state == "disconnected"
then
self:_handle_connection_error()
return
end
self:new_session()
end)
end)
if not agent then
-- no log, it was already logged in AgentInstance
return
end
self.agent = agent
self.chat_history = ChatHistory:new()
self.widget = ChatWidget:new(tab_page_id, function(input_text)
return self:_handle_input_submit(input_text)
end)
self.message_writer = MessageWriter:new(self.widget.buf_nrs.chat)
self.message_writer:set_provider_name(self.agent.provider_config.name)
self.status_animation = StatusAnimation:new(self.widget.buf_nrs.chat)
self.status_animation:start("busy")
-- Check for sync failure during ACPClient construction
-- Guard with _connection_error to avoid double-fire if async callback already ran
if
not self._connection_error
and (self.agent.state == "error" or self.agent.state == "disconnected")
then
vim.schedule(function()
if not self._connection_error then
self:_handle_connection_error()
end
end)
end
self.permission_manager = PermissionManager:new(self.message_writer)
FilePicker:new(self.widget.buf_nrs.input)
SlashCommands.setup_completion(self.widget.buf_nrs.input)
self.config_options = AgentConfigOptions:new(self.widget.buf_nrs, {
set_mode = function(mode_id, is_legacy)
self:_handle_mode_change(mode_id, is_legacy)
end,
set_model = function(model_id, is_legacy)
self:_handle_model_change(model_id, is_legacy)
end,
set_thought_level = function(value)
self:_handle_thought_level_change(value)
end,
})
self.file_list = FileList:new(self.widget.buf_nrs.files, function(file_list)
if file_list:is_empty() then
self.widget:close_optional_window("files")
self.widget:move_cursor_to(self.widget.win_nrs.input)
else
self.widget:render_header("files", tostring(#file_list:get_files()))
self.widget:show({ focus_prompt = false })
end
end)
self.code_selection = CodeSelection:new(
self.widget.buf_nrs.code,
function(code_selection)
if code_selection:is_empty() then
self.widget:close_optional_window("code")
self.widget:move_cursor_to(self.widget.win_nrs.input)
else
self.widget:render_header(
"code",
tostring(#code_selection:get_selections())
)
self.widget:show({ focus_prompt = false })
end
end
)
self.diagnostics_list = DiagnosticsList:new(
self.widget.buf_nrs.diagnostics,
function(diagnostics_list)
if diagnostics_list:is_empty() then
self.widget:close_optional_window("diagnostics")
self.widget:move_cursor_to(self.widget.win_nrs.input)
else
-- show() opens layouts but does not update the diagnostics header count
self.widget:render_header(
"diagnostics",
tostring(#diagnostics_list:get_diagnostics())
)
self.widget:show({ focus_prompt = false })
end
end
)
self.todo_list = TodoList:new(self.widget.buf_nrs.todos, function(todo_list)
if not todo_list:is_empty() then
self.widget:show({ focus_prompt = false })
end
end, function()
self.widget:close_optional_window("todos")
end)
return self
end
--- Handle provider connection failure.
--- Stops busy animation and writes error to chat buffer.
function SessionManager:_handle_connection_error()
self._connection_error = true
self._session_ready_callbacks = {}
self.status_animation:stop()
self.message_writer:write_message(
ACPPayloads.generate_agent_message(
"⚠️ Failed to connect to "
.. self.agent.provider_config.name
.. ". Check that the provider is"
.. " installed and try again"
.. " with a new session."
)
)
end
--- Register callback for when ACP session is ready.
--- Fires immediately (via vim.schedule) if session
--- already exists.
--- @param callback fun(session: agentic.SessionManager)
function SessionManager:on_session_ready(callback)
if self.session_id then
Logger.debug(
"on_session_ready: session already ready, scheduling callback immediately"
)
vim.schedule(function()
callback(self)
end)
return
end
Logger.debug(
"on_session_ready: queueing callback, will fire when session ready"
)
table.insert(self._session_ready_callbacks, function()
callback(self)
end)
end
--- Check if a prompt can be submitted to the session.
--- Returns false if provider connection failed, session not
--- initialized, or session is restoring. Notifies user of the reason.
--- @return boolean can_submit
function SessionManager:can_submit_prompt()
if self._connection_error then
Logger.notify(
"Provider connection failed. Start a new session.",
vim.log.levels.ERROR
)
return false
end
if not self.session_id then
Logger.notify(
"Session not ready. Wait for initialization to complete.",
vim.log.levels.WARN
)
return false
end
if self._is_restoring_session then
Logger.notify(
"Session is restoring. Please wait...",
vim.log.levels.WARN
)
return false
end
return true
end
--- @param update agentic.acp.SessionUpdateMessage
function SessionManager:_on_session_update(update)
if update.sessionUpdate == "user_message_chunk" then
if self._is_restoring_session then
local text = update.content
and update.content.type == "text"
and update.content.text
if text and text ~= "" then
self.message_writer:write_restoring_message(
ACPPayloads.generate_user_message(text)
)
self.chat_history:add_message({
type = "user",
text = text,
timestamp = os.time(),
provider_name = self.agent.provider_config.name,
})
end
end
elseif update.sessionUpdate == "plan" then
if Config.windows.todos.display then
self.todo_list:render(update.entries)
end
elseif update.sessionUpdate == "agent_message_chunk" then
self:_start_spinner("generating")
self.message_writer:write_message_chunk(update)
if update.content and update.content.text then
self.chat_history:append_agent_text({
type = "agent",
text = update.content.text,
provider_name = self.agent.provider_config.name,
})
end
elseif update.sessionUpdate == "agent_thought_chunk" then
self:_start_spinner("thinking")
self.message_writer:write_message_chunk(update)
if update.content and update.content.text then
self.chat_history:append_agent_text({
type = "thought",
text = update.content.text,
provider_name = self.agent.provider_config.name,
})
end
elseif update.sessionUpdate == "available_commands_update" then
SlashCommands.setCommands(
self.widget.buf_nrs.input,
update.availableCommands
)
elseif update.sessionUpdate == "current_mode_update" then
-- only for legacy modes, not for config_options
if
self.config_options.legacy_agent_modes:handle_agent_update_mode(
update.currentModeId
)
then
self:_set_mode_to_chat_header(update.currentModeId)
end
elseif update.sessionUpdate == "config_option_update" then
self:_handle_new_config_options(update.configOptions)
elseif update.sessionUpdate == "usage_update" then
-- Usage updates contain token/cost information - currently informational only
-- Fields: used (tokens), size (context window), cost (optional: amount, currency)
-- Keeping silent for now to avoid "press any key" prompts on large JSON output
elseif update.sessionUpdate == "session_info_update" then
-- Session metadata is currently informational only
else
-- TODO: Move this to Logger from notify to debug when confidence is high
Logger.notify(
"Unknown session update type: "
.. tostring(
--- @diagnostic disable-next-line: undefined-field -- expected it to be unknown
update.sessionUpdate
),
vim.log.levels.WARN,
{ title = "⚠️ Unknown session update" }
)
end
-- Skip the hook during restore replay: the provider re-emits historical
-- updates and users expect hooks to reflect live activity.
if self._is_restoring_session then
return
end
-- This is being done after handling specific updates but one could argue
-- there should be pre/post hooks for everything.
--- @type agentic.UserConfig.SessionUpdateData
local hook_data = {
session_id = self.session_id,
tab_page_id = self.tab_page_id,
update = update,
}
P.invoke_hook("on_session_update", hook_data)
end
--- @param tool_call agentic.ui.MessageWriter.ToolCallBlock
function SessionManager:_on_tool_call(tool_call)
if self.message_writer.tool_call_blocks[tool_call.tool_call_id] then
-- fallback for bad ACP implementations which sends multiple `tool_call` with different data (initially added for Mistral)
self:_on_tool_call_update(tool_call)
return
end
self.message_writer:write_tool_call_block(tool_call)
-- Store merged block from MessageWriter (has normalized/accumulated fields)
local merged = self.message_writer.tool_call_blocks[tool_call.tool_call_id]
--- @type agentic.ui.ChatHistory.ToolCall
local tool_msg = vim.tbl_deep_extend("force", {
type = "tool_call",
}, merged)
self.chat_history:add_message(tool_msg)
end
--- Handle tool call update: update UI, history, diff preview, permissions, and reload buffers
--- @param tool_call_update agentic.ui.MessageWriter.ToolCallBlock
function SessionManager:_on_tool_call_update(tool_call_update)
if
not self.message_writer.tool_call_blocks[tool_call_update.tool_call_id]
then
self:_on_tool_call(tool_call_update)
else
self.message_writer:update_tool_call_block(tool_call_update)
-- Store merged block from MessageWriter (has accumulated body and normalized fields)
local merged =
self.message_writer.tool_call_blocks[tool_call_update.tool_call_id]
--- @type agentic.ui.ChatHistory.ToolCall
local tool_msg = vim.tbl_deep_extend("force", {
type = "tool_call",
}, merged)
self.chat_history:update_tool_call(
tool_call_update.tool_call_id,
tool_msg
)
end
-- pre-emptively clear diff preview when tool call update is received, as it's either done or failed
local is_rejection = tool_call_update.status == "failed"
self:_clear_diff_in_buffer(tool_call_update.tool_call_id, is_rejection)
-- Remove the permission request when the tool call reaches a terminal status.
-- `failed` covers user rejection or agent-side error;
-- `completed` covers cases where the agent finishes the tool without (or alongside) user resolution.
-- Both should clear the inline buttons.
if
tool_call_update.status == "failed"
or tool_call_update.status == "completed"
then
self.permission_manager:remove_request_by_tool_call_id(
tool_call_update.tool_call_id
)
end
-- Reload buffers when file-mutating tool calls complete
if tool_call_update.status == "completed" then
local tracker =
self.message_writer.tool_call_blocks[tool_call_update.tool_call_id]
if tracker and tracker.kind and FILE_MUTATING_KINDS[tracker.kind] then
vim.cmd.checktime()
DiffPreview.cleanup_suggestion_buffer(tracker.file_path)
-- Skip the hook during restore replay: the provider replays
-- historical tool calls as "completed" but no write happened now.
if
not self._is_restoring_session
and type(tracker.file_path) == "string"
and tracker.file_path ~= ""
then
local abs_path = FileSystem.to_absolute_path(tracker.file_path)
local raw_bufnr = vim.fn.bufnr(abs_path)
--- @type number|nil
local bufnr = (
raw_bufnr ~= -1 and vim.api.nvim_buf_is_loaded(raw_bufnr)
)
and raw_bufnr
or nil
--- @type agentic.UserConfig.FileEditData
local hook_data = {
filepath = abs_path,
session_id = self.session_id,
tab_page_id = self.tab_page_id,
bufnr = bufnr,
}
P.invoke_hook("on_file_edit", hook_data)
end
end
end
if not self.permission_manager:has_pending() then
self:_start_spinner("generating")
end
end
--- Send the newly selected mode to the agent and handle the response
--- @param mode_id string
--- @param is_legacy boolean|nil
function SessionManager:_handle_mode_change(mode_id, is_legacy)
if not self.session_id then
return
end
local request_session_id = self.session_id
local function callback(result, err)
if self.session_id ~= request_session_id then
Logger.debug("Stale mode change response, ignoring")
return
end
if err then
Logger.notify(
string.format(
"Failed to change mode to '%s': %s",
mode_id,
err.message
),
vim.log.levels.ERROR
)
else
-- needed for backward compatibility
self.config_options.legacy_agent_modes.current_mode_id = mode_id
if result and result.configOptions then
Logger.debug("received result after setting mode")
self:_handle_new_config_options(result.configOptions)
end
self:_set_mode_to_chat_header(mode_id)
local mode_name = self.config_options:get_mode_name(mode_id)
Logger.notify(
"Mode changed to: " .. mode_name,
vim.log.levels.INFO,
{
title = "Agentic Mode changed",
}
)
end
end
if is_legacy then
self.agent:set_mode(self.session_id, mode_id, callback)
else
self.agent:set_config_option(self.session_id, "mode", mode_id, callback)
end
end
--- Send the newly selected model to the agent
--- @param model_id string
--- @param is_legacy boolean|nil
--- @param on_done fun()|nil Called after the agent responds successfully.
--- Used by session-creation wiring to chain `default_thought_level` after
--- the model change has refreshed the available effort/thought_level
--- options server-side. Without this chain, applying the thought level
--- before the model response validates against the OLD model's options,
--- which can silently reject the configured value or warn that a valid
--- option is unavailable.
function SessionManager:_handle_model_change(model_id, is_legacy, on_done)
if not self.session_id then
return
end
local request_session_id = self.session_id
local callback = function(result, err)
if self.session_id ~= request_session_id then
Logger.debug("Stale model change response, ignoring")
return
end
if err then
Logger.notify(
string.format(
"Failed to change model to '%s': %s",
model_id,
err.message
),
vim.log.levels.ERROR
)
else
-- Always update legacy state on success (mirrors _handle_mode_change pattern)
self.config_options.legacy_agent_models.current_model_id = model_id
if result and result.configOptions then
Logger.debug("received result after setting model")
self:_handle_new_config_options(result.configOptions)
end
Logger.notify(
"Model changed to: " .. model_id,
vim.log.levels.INFO,
{ title = "Agentic Model changed" }
)
if on_done then
on_done()
end
end
end
if is_legacy then
self.agent:set_model(self.session_id, model_id, callback)
else
self.agent:set_config_option(
self.session_id,
"model",
model_id,
callback
)
end
end
--- Send the newly selected thought level / effort to the agent.
--- Reads `id` from the stored config option to determine the actual
--- configId — Claude sends `effort`, Codex sends `thought_level`.
--- @param value string
function SessionManager:_handle_thought_level_change(value)
if not self.session_id then
return
end
local thought = self.config_options.thought_level
if not thought then
Logger.debug("no thought_level option available")
return
end
local request_session_id = self.session_id
local config_id = thought.id
local function callback(result, err)
if self.session_id ~= request_session_id then
Logger.debug("Stale thought_level change response, ignoring")
return
end
if err then
Logger.notify(
string.format(
"Failed to change thought effort level to '%s': %s",
value,
err.message
),
vim.log.levels.ERROR
)
else
if result and result.configOptions then
Logger.debug("received result after setting thought_level")
self:_handle_new_config_options(result.configOptions)
end
Logger.notify(
"Thought effort level changed to: " .. value,
vim.log.levels.INFO,
{ title = "Agentic Thought Effort Level changed" }
)
end
end
self.agent:set_config_option(self.session_id, config_id, value, callback)
end
--- Schedule a coalesced re-render of function-based headers.
--- Multiple calls within the same event loop tick collapse into one render.
function SessionManager:schedule_header_refresh()
if self._header_refresh_scheduled then
return
end
if not Config.headers then
return
end
self._header_refresh_scheduled = true
-- Debounce updates within 150ms of each other to avoid excessive
-- re-renders when multiple updates come in quick succession
vim.defer_fn(function()
self._header_refresh_scheduled = false
for panel_name, header_config in pairs(Config.headers) do
if type(header_config) == "function" then
self.widget:render_header(panel_name)
end
end
end, 150)
end
--- @param mode_id string
function SessionManager:_set_mode_to_chat_header(mode_id)
local mode_name = self.config_options:get_mode_name(mode_id)
self.widget:render_header(
"chat",
string.format("Mode: %s", mode_name or mode_id)
)
end
--- @param input_text string
--- @return boolean submitted
function SessionManager:_handle_input_submit(input_text)
self.todo_list:close_if_all_completed()
-- Intercept /new command BEFORE the generation guard so users can
-- escape a stuck state from the chat input
if input_text:match("^/new%s") or input_text:match("^/new$") then
self:new_session()
return true
end
-- Guard: cannot submit if connection failed, session not initialized, or restoring
if not self:can_submit_prompt() then
return false
end
--- @type agentic.acp.Content[]
local prompt = {}
-- If restored/switched session, prepend history on first submit
if self.history_to_send then
self.chat_history.title = input_text -- Update title for restored session
ChatHistory.prepend_restored_messages(self.history_to_send, prompt)
self.history_to_send = nil
elseif self.chat_history.title == "" then
self.chat_history.title = input_text -- Set title for new session
end
table.insert(prompt, {
type = "text",
text = input_text,
})
-- Add system info on first message only (after user text so resume picker shows the prompt)
if self._is_first_message then
self._is_first_message = false
table.insert(prompt, {
type = "text",
text = self:_get_system_info(),
})
end
--- The message to be written to the chat widget
local message_lines = {}
table.insert(message_lines, input_text)
if not self.code_selection:is_empty() then
table.insert(message_lines, "\n- **Selected code**:\n")
table.insert(prompt, {
type = "text",
text = table.concat({
"IMPORTANT: Focus and respect the line numbers provided in the <line_start> and <line_end> tags for each <selected_code> tag.",
"The selection shows ONLY the specified line range, not the entire file!",
"The file may contain duplicated content of the selected snippet.",
"When using edit tools, on the referenced files, MAKE SURE your changes target the correct lines by including sufficient surrounding context to make the match unique.",
"After you make edits to the referenced files, go back and read the file to verify your changes were applied correctly.",
}, "\n"),
})
local selections = self.code_selection:get_selections()
self.code_selection:clear()
for _, selection in ipairs(selections) do
if selection and #selection.lines > 0 then
-- Add line numbers to each line in the snippet
local numbered_lines = {}
for i, line in ipairs(selection.lines) do
local line_num = selection.start_line + i - 1
table.insert(
numbered_lines,
string.format("Line %d: %s", line_num, line)
)
end
local numbered_snippet = table.concat(numbered_lines, "\n")
table.insert(prompt, {
type = "text",
text = string.format(
table.concat({
"<selected_code>",
"<path>%s</path>",
"<line_start>%s</line_start>",
"<line_end>%s</line_end>",
"<snippet>",
"%s",
"</snippet>",
"</selected_code>",
}, "\n"),
FileSystem.to_absolute_path(selection.file_path),
selection.start_line,
selection.end_line,
numbered_snippet
),
})
table.insert(
message_lines,
string.format(
"```%s %s#L%d-L%d\n%s\n```",
selection.file_type,
selection.file_path,
selection.start_line,
selection.end_line,
table.concat(selection.lines, "\n")
)
)
end
end
end
if not self.file_list:is_empty() then
table.insert(message_lines, "\n- **Referenced files**:")
local files = self.file_list:get_files()
self.file_list:clear()
for _, file_path in ipairs(files) do
table.insert(prompt, ACPPayloads.create_file_content(file_path))
table.insert(
message_lines,
string.format(" - @%s", FileSystem.to_smart_path(file_path))
)
end
end
if not self.diagnostics_list:is_empty() then
table.insert(message_lines, "\n- **Diagnostics**:")
local diagnostics = self.diagnostics_list:get_diagnostics()
self.diagnostics_list:clear()
local WidgetLayout = require("agentic.ui.widget_layout")
local chat_width = WidgetLayout.calculate_width(Config.windows.width)
local chat_winid = self.widget.win_nrs.chat
if chat_winid and vim.api.nvim_win_is_valid(chat_winid) then
chat_width = vim.api.nvim_win_get_width(chat_winid)
end
local DiagnosticsContext = require("agentic.ui.diagnostics_context")
local formatted_diagnostics =
DiagnosticsContext.format_diagnostics(diagnostics, chat_width)
for _, prompt_entry in ipairs(formatted_diagnostics.prompt_entries) do
table.insert(prompt, prompt_entry)
end
for _, summary_line in ipairs(formatted_diagnostics.summary_lines) do
table.insert(message_lines, summary_line)
end
end
local user_message = ACPPayloads.generate_user_message(message_lines)
self.message_writer:write_message(user_message)
--- @type agentic.ui.ChatHistory.UserMessage
local user_msg = {
type = "user",
text = input_text,
timestamp = os.time(),
provider_name = self.agent.provider_config.name,
}
self.chat_history:add_message(user_msg)
self.status_animation:start("thinking")
--- @type agentic.UserConfig.PromptSubmitData
local prompt_hook_data = {
prompt = input_text,
session_id = self.session_id,
tab_page_id = self.tab_page_id,
}
P.invoke_hook("on_prompt_submit", prompt_hook_data)
local session_id = self.session_id
local tab_page_id = self.tab_page_id
self.is_generating = true
self.agent:send_prompt(self.session_id, prompt, function(response, err)
vim.schedule(function()
-- Guard: skip stale response if session changed (cancel/restore/new)
if self.session_id ~= session_id then
return
end
self.is_generating = false
local finish_message = string.format(
"\n### %s %s\n-----",
Config.message_icons.finished,
os.date("%Y-%m-%d %H:%M:%S")
)
if err then
finish_message = string.format(
"\n### %s Agent finished with error: %s\n%s",
Config.message_icons.error,
vim.inspect(err),
finish_message
)
elseif response and response.stopReason == "cancelled" then
finish_message = string.format(
"\n### %s Generation stopped by the user request\n%s",
Config.message_icons.stopped,
finish_message
)
end
self.message_writer:write_message(
ACPPayloads.generate_agent_message(finish_message)
)
self.status_animation:stop()
--- @type agentic.UserConfig.ResponseCompleteData
local response_hook_data = {
session_id = session_id --[[@as string]],
tab_page_id = tab_page_id,
success = err == nil,
error = err,
}
P.invoke_hook("on_response_complete", response_hook_data)
end)
end)
return true
end
--- Build the standard ACP client handlers for session subscriptions
--- @return agentic.acp.ClientHandlers handlers
function SessionManager:_build_handlers()
--- @type agentic.acp.ClientHandlers
local handlers = {
on_error = function(err)
Logger.debug("Agent error: ", err)
self.message_writer:write_message(
ACPPayloads.generate_agent_message({
"🐞 Agent Error:",
"",
vim.inspect(err),
})
)
end,
on_session_update = function(update)
self:_on_session_update(update)
end,
on_tool_call = function(tool_call)
self:_on_tool_call(tool_call)
end,
on_tool_call_update = function(tool_call_update)
self:_on_tool_call_update(tool_call_update)
end,
on_request_permission = function(request, callback)
P.invoke_hook("on_request_permission", {
request = request,
session_id = self.session_id,
tab_page_id = self.tab_page_id,
})
self.status_animation:stop()
local function wrapped_callback(option_id)
callback(option_id)
local is_rejection = option_id == "reject_once"
or option_id == "reject_always"
self:_clear_diff_in_buffer(
request.toolCall.toolCallId,
is_rejection
)
if not self.permission_manager:has_pending() then
self:_start_spinner("generating")
end