Repository navigation
Expand file tree
/
Copy pathrenderer.lua
More file actions
1433 lines (1313 loc) · 45.9 KB
/
Copy pathrenderer.lua
File metadata and controls
1433 lines (1313 loc) · 45.9 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 state = require('opencode.state')
local config = require('opencode.config')
local output_window = require('opencode.ui.output_window')
local reference_facts = require('opencode.ui.reference_facts')
local contexts = require('opencode.ui.renderer.ctx')
local RenderSession = require('opencode.ui.renderer.session')
local flush = require('opencode.ui.renderer.flush')
local rendered_entries = require('opencode.ui.renderer.entries')
local symbol_refresh = require('opencode.ui.renderer.symbol_refresh')
local scroll = require('opencode.ui.renderer.scroll')
local session_tabs = require('opencode.state.session_tabs')
local M = {}
local REVERT_MESSAGE_ID = '__opencode_revert_message__'
local REVERT_PART_ID = '__opencode_revert_message_part__'
local HIDDEN_MESSAGES_NOTICE_MESSAGE_ID = '__opencode_hidden_messages_notice__'
local HIDDEN_MESSAGES_NOTICE_PART_ID = '__opencode_hidden_messages_notice_part__'
local PERMISSION_DISPLAY_MESSAGE_ID = 'permission-display-message'
local QUESTION_DISPLAY_MESSAGE_ID = 'question-display-message'
local LAZYRENDER_EST_LINES_PER_MSG = 5
local LAZYRENDER_VIEWPORT_BUFFER = 1.5
---@param ctx RendererCtx
local function detach_render_session(ctx)
if ctx.render_session then
ctx.render_session:close()
ctx.render_session = nil
end
ctx.observation = nil
end
---Calculate how many messages to render initially based on window height.
---@return integer
local function get_initial_render_count()
local win = state.windows and state.windows.output_win
if not win or not vim.api.nvim_win_is_valid(win) then
return math.huge --[[@as integer]] -- no window: render all (tests, headless)
end
local ok, height = pcall(vim.api.nvim_win_get_height, win)
if not ok or not height or height <= 0 then
return math.huge --[[@as integer]]
end
return math.ceil(height / LAZYRENDER_EST_LINES_PER_MSG * LAZYRENDER_VIEWPORT_BUFFER)
end
---@return integer|nil
local function get_max_rendered_messages()
local limit = config.ui and config.ui.output and config.ui.output.max_messages
if type(limit) ~= 'number' or limit <= 0 then
return nil
end
return math.floor(limit)
end
---@param message table|nil
---@return boolean
local function is_renderer_owned_message(message)
local message_id = message and message.id
return message_id == REVERT_MESSAGE_ID
or message_id == HIDDEN_MESSAGES_NOTICE_MESSAGE_ID
or message_id == PERMISSION_DISPLAY_MESSAGE_ID
or message_id == QUESTION_DISPLAY_MESSAGE_ID
end
---@param message table
---@return boolean
local function is_non_conversation_record(message)
return message.kind == 'agent-switched' or message.kind == 'model-switched' or message.kind == 'synthetic'
end
---@param message table|nil
---@return boolean
local function is_active_session_message(message)
local session_id = message and message.session_id
return (session_id ~= nil and state.active_session and state.active_session.id == session_id) --[[@as boolean]]
end
---@param messages table[]|nil
---@return table[]
local function get_real_session_messages(messages)
return vim.tbl_filter(function(message)
return is_active_session_message(message)
and not is_renderer_owned_message(message)
and not is_non_conversation_record(message)
end, messages or {})
end
---@param messages table[]|nil
---@param session table|nil
---@return integer|nil
local function get_revert_index(messages, session)
local revert = session and session.revert
local revert_message_id = revert and revert.messageID
if not revert_message_id then
return nil
end
local real_messages = get_real_session_messages(messages)
for i, message in ipairs(real_messages) do
if message.id == revert_message_id then
return i
end
end
return nil
end
local function build_revert_message(entries, session)
local revert_index = get_revert_index(entries, session)
if not revert_index then
return nil
end
return {
id = REVERT_MESSAGE_ID,
session_id = session.id,
kind = 'system',
entries = entries,
content = {
{
id = REVERT_PART_ID,
kind = 'revert_display',
revert_index = revert_index,
revert = session.revert,
},
},
}
end
---@param messages table[]|nil
---@param session table|nil
---@param ctx RendererCtx
---@return table[] visible_messages
---@return integer hidden_count
local function get_visible_session_messages(messages, session, ctx)
local real_messages = get_real_session_messages(messages)
local revert_index = get_revert_index(messages, session)
if revert_index then
real_messages = vim.list_slice(real_messages, 1, revert_index - 1)
end
local limit = not ctx.history_expanded and get_max_rendered_messages()
if not limit or #real_messages <= limit then
return real_messages, 0
end
local start_index = #real_messages - limit + 1
return vim.list_slice(real_messages, start_index, #real_messages), start_index - 1
end
---@return table session The observed session, or the active session's id alone
---when no observation is bound yet.
---@param ctx RendererCtx
local function current_session(ctx)
return ctx.observation and ctx.observation:read().session or { id = state.active_session and state.active_session.id }
end
---@return integer Messages the current session would show at full window size.
---@param ctx RendererCtx
local function visible_message_count(ctx)
return #get_visible_session_messages(ctx.entries, current_session(ctx), ctx)
end
---@param hidden_count integer
---@return table
local function build_hidden_messages_notice(hidden_count)
local session_id = state.active_session and state.active_session.id or ''
return {
id = HIDDEN_MESSAGES_NOTICE_MESSAGE_ID,
session_id = session_id,
kind = 'synthetic',
content = {
{
id = HIDDEN_MESSAGES_NOTICE_PART_ID,
kind = 'hidden_messages_display',
hidden_count = hidden_count,
},
},
}
end
---@param message table
---@param ctx RendererCtx
local function ensure_message_rendered(ctx, message)
local message_id = message.id
if not message_id or ctx.render_state:get_message(message_id) then
return
end
ctx.render_state:set_message(message)
flush.mark_message_dirty(message_id, ctx)
for index, part in ipairs(message.content or {}) do
if part.kind ~= 'step_start' and part.kind ~= 'step_finish' then
local part_id = ctx.content_key(message, index)
ctx.render_state:set_part(part, message_id, part_id)
flush.mark_part_dirty(part_id, message_id, ctx)
end
end
end
---@param message_id string
---@param ctx RendererCtx
local function hide_rendered_message(ctx, message_id)
local rendered_message = ctx.render_state:get_message(message_id)
local message = rendered_message and rendered_message.message
if not message then
return
end
for part_id, part in pairs(ctx.render_state._parts) do
if part.message_id == message_id then
flush.queue_part_removal(part_id, ctx)
end
end
flush.queue_message_removal(message_id, ctx)
end
---@param hidden_count integer
---@param ctx RendererCtx
local function upsert_hidden_messages_notice(ctx, hidden_count)
local existing_message = ctx.render_state:get_message(HIDDEN_MESSAGES_NOTICE_MESSAGE_ID)
local notice_message = build_hidden_messages_notice(hidden_count)
if not existing_message then
ensure_message_rendered(ctx, notice_message)
else
local existing_part = ctx.render_state:get_part(HIDDEN_MESSAGES_NOTICE_PART_ID)
if not existing_part or not existing_part.part then
hide_rendered_message(ctx, HIDDEN_MESSAGES_NOTICE_MESSAGE_ID)
ensure_message_rendered(ctx, notice_message)
else
ctx.render_state:set_message(notice_message, existing_message.line_start, existing_message.line_end)
ctx.render_state:set_part(
notice_message.content[1],
notice_message.id,
HIDDEN_MESSAGES_NOTICE_PART_ID,
existing_part.line_start,
existing_part.line_end
)
end
end
local part_data = ctx.render_state:get_part(HIDDEN_MESSAGES_NOTICE_PART_ID)
if part_data then
ctx.render_state:add_actions(HIDDEN_MESSAGES_NOTICE_PART_ID, {
{
text = 'Toggle Max Messages',
type = 'toggle_max_messages',
args = {},
key = 'm',
range = { from = part_data.line_start, to = part_data.line_end },
display_line = part_data.line_start,
},
})
flush.mark_part_dirty(HIDDEN_MESSAGES_NOTICE_PART_ID, HIDDEN_MESSAGES_NOTICE_MESSAGE_ID, ctx)
end
end
---@param ctx RendererCtx
local function reconcile_rendered_message_limit(ctx)
if not ctx.observation then
return
end
local limit = not ctx.history_expanded and get_max_rendered_messages()
if not limit then
if ctx.render_state:get_message(HIDDEN_MESSAGES_NOTICE_MESSAGE_ID) then
hide_rendered_message(ctx, HIDDEN_MESSAGES_NOTICE_MESSAGE_ID)
end
return
end
local observation_state = ctx.observation:read()
local visible_messages, hidden_count = get_visible_session_messages(ctx.entries, observation_state.session, ctx)
local visible_ids = {}
for _, message in ipairs(visible_messages) do
local message_id = message.id
if message_id then
visible_ids[message_id] = true
ensure_message_rendered(ctx, message)
end
end
for _, message in ipairs(get_real_session_messages(ctx.entries)) do
local message_id = message.id
if message_id and not visible_ids[message_id] and ctx.render_state:get_message(message_id) then
hide_rendered_message(ctx, message_id)
end
end
if hidden_count > 0 then
upsert_hidden_messages_notice(ctx, hidden_count)
elseif ctx.render_state:get_message(HIDDEN_MESSAGES_NOTICE_MESSAGE_ID) then
hide_rendered_message(ctx, HIDDEN_MESSAGES_NOTICE_MESSAGE_ID)
end
end
---@param message_id string|nil
---@return boolean
---@param ctx RendererCtx
local function is_message_visible(ctx, message_id)
if not message_id then
return false
end
for _, message in ipairs(get_visible_session_messages(ctx.entries, current_session(ctx), ctx)) do
if message.id == message_id then
return true
end
end
return false
end
local function ordered_entries(observation)
local observed = observation:read()
local entries = {}
for _, id in ipairs(observed.entry_order or {}) do
local entry = observed.entries_by_id and observed.entries_by_id[id]
if entry then
entries[#entries + 1] = entry
end
end
return entries
end
local function total_tokens(tokens)
return (tokens.input or 0)
+ (tokens.output or 0)
+ (tokens.reasoning or 0)
+ (tokens.cache and tokens.cache.read or 0)
+ (tokens.cache and tokens.cache.write or 0)
end
local function update_stats(tokens, cost)
local count = total_tokens(tokens)
if count > 0 then
if type(cost) == 'number' then
state.renderer.set_stats(count, cost)
else
state.renderer.set_tokens_count(count)
end
return true
elseif type(cost) == 'number' and cost > 0 then
state.renderer.set_cost(cost)
return true
end
return false
end
local function update_observation_stats(observation)
local observed = observation:read()
local session = observed.sync
and observed.sync.session
and observed.sync.session.state == 'current'
and observed.session
or nil
for index = #(observed.entry_order or {}), 1, -1 do
local entry = observed.entries_by_id and observed.entries_by_id[observed.entry_order[index]]
if entry and entry.kind == 'assistant' and entry.tokens and total_tokens(entry.tokens) > 0 then
local cost = session and session.cost or entry.cost
update_stats(entry.tokens, cost)
return
end
end
if session and session.tokens and update_stats(session.tokens, session.cost) then
return
end
end
---@param ctx RendererCtx
local function get_child_parts(ctx, session_id)
local observation = ctx.render_session and ctx.render_session:child(session_id)
if not observation then
return nil
end
local parts = {}
for _, entry in ipairs(ordered_entries(observation)) do
for _, content in ipairs(entry.content or {}) do
if content.kind == 'tool' then
parts[#parts + 1] = content
end
end
end
return parts
end
---@param ctx RendererCtx
---@return boolean appeared Whether the prompt was not displayed before
local function reconcile_prompt_display(ctx, message_id, part_id, kind, visible)
if not visible then
if ctx.render_state:get_message(message_id) then
hide_rendered_message(ctx, message_id)
end
return false
end
local session_id = state.active_session and state.active_session.id or ''
local content = { id = part_id, kind = kind }
local entry = { id = message_id, session_id = session_id, kind = 'system', content = { content } }
local rendered_message = ctx.render_state:get_message(message_id)
local rendered_part = ctx.render_state:get_part(part_id)
ctx.render_state:set_message(
entry,
rendered_message and rendered_message.line_start,
rendered_message and rendered_message.line_end
)
ctx.render_state:set_part(
content,
message_id,
part_id,
rendered_part and rendered_part.line_start,
rendered_part and rendered_part.line_end
)
flush.mark_message_dirty(message_id, ctx)
flush.mark_part_dirty(part_id, message_id, ctx)
return rendered_message == nil
end
---@param ctx? RendererCtx
function M.refresh_prompts(ctx)
ctx = ctx or contexts.current()
local permission = ctx.prompt_controllers.permission
local question = ctx.prompt_controllers.question
local permission_appeared = reconcile_prompt_display(
ctx,
PERMISSION_DISPLAY_MESSAGE_ID,
'permission-display-part',
'permissions-display',
permission and #permission.get_all_permissions() > 0
)
local request = question and question.get_current_request()
local question_appeared = reconcile_prompt_display(
ctx,
QUESTION_DISPLAY_MESSAGE_ID,
'question-display-part',
'questions-display',
question and question.has_question() and not question.uses_vim_ui_select(request)
)
flush.schedule(ctx)
-- A pending prompt blocks the agent, so reveal it even when the user scrolled away.
-- Scheduled after flush.schedule so the prompt lines exist when scrolling.
if permission_appeared or question_appeared then
local generation = ctx.generation
vim.schedule(function()
if not ctx.closed and ctx.generation == generation and ctx:is_active() then
M.scroll_to_bottom(true, ctx)
end
end)
end
end
---@param ctx RendererCtx
local function sync_prompt_controllers(ctx, observations)
local permission = ctx.prompt_controllers.permission
if permission and permission.sync then
permission.sync(observations)
end
local question = ctx.prompt_controllers.question
if question and question.sync then
question.sync(observations)
end
M.refresh_prompts(ctx)
end
---@param ctx RendererCtx
local function apply_file_changes(ctx, observed)
local files = observed.files
if not files or files.revision <= ctx.file_revision then
return false
end
ctx.file_revision = files.revision
vim.cmd('checktime')
if config.hooks and config.hooks.on_file_edited and files.last then
pcall(config.hooks.on_file_edited, files.last.path)
end
reference_facts.refresh_current_files()
return true
end
---@param ctx RendererCtx
local function invalidate_text_references(ctx)
for part_id, rendered in pairs(ctx.render_state._parts) do
if rendered.part.kind == 'text' then
flush.mark_part_dirty(part_id, rendered.message_id, ctx)
end
end
end
---Read the current conversation for display.
---@param observation table
---@return table session
---@return table[] entries
---@param ctx RendererCtx
local function read_conversation(ctx, observation)
local observed = observation:read()
local sync = observed.sync or {}
local synced_session = sync.session and sync.session.state == 'current' and observed.session or nil
local entries = ordered_entries(observation)
ctx.entries = entries
update_observation_stats(observation)
return synced_session or { id = state.active_session and state.active_session.id }, entries
end
---@param ctx RendererCtx
---@param entries table[]
---@return boolean
local function has_pending_local_submission(ctx, entries)
for _, entry in ipairs(entries) do
if
entry.kind == 'user'
and not ctx.render_state:get_message(entry.id)
and (state.user_message_count[entry.session_id] or 0) > 0
then
return true
end
end
return false
end
---@param ctx RendererCtx
local function reconcile_conversation(ctx, session, entries, files_changed)
local previous_refs = reference_facts.current_refs()
reference_facts.rebuild(session.id, entries, session.location)
local references_changed = not vim.deep_equal(previous_refs, reference_facts.current_refs())
local visible, hidden_count = get_visible_session_messages(entries, session, ctx)
if ctx.lazy_render_count == nil then
local initial = get_initial_render_count()
if #visible > initial then
ctx.lazy_render_count = initial
end
end
if ctx.lazy_render_count and #visible > ctx.lazy_render_count then
visible = vim.list_slice(visible, #visible - ctx.lazy_render_count + 1)
end
local local_submission = has_pending_local_submission(ctx, visible)
local desired = {}
for _, entry in ipairs(visible) do
desired[entry.id] = true
end
for message_id in pairs(ctx.render_state._messages) do
if not desired[message_id] and not is_renderer_owned_message({ id = message_id }) then
hide_rendered_message(ctx, message_id)
end
end
local initial_render = #visible > 0
and next(ctx.render_state._messages) == nil
and output_window.mounted()
and state.ui.is_window_in_current_tab(state.windows.output_win)
and not ctx.bulk_mode
if initial_render then
flush.begin_bulk_mode(ctx)
end
if hidden_count > 0 then
upsert_hidden_messages_notice(ctx, hidden_count)
elseif ctx.render_state:get_message(HIDDEN_MESSAGES_NOTICE_MESSAGE_ID) then
hide_rendered_message(ctx, HIDDEN_MESSAGES_NOTICE_MESSAGE_ID)
end
local revert_message = build_revert_message(entries, session)
if revert_message then
visible[#visible + 1] = revert_message
elseif ctx.render_state:get_message(REVERT_MESSAGE_ID) then
hide_rendered_message(ctx, REVERT_MESSAGE_ID)
end
rendered_entries.reconcile(visible, references_changed or files_changed, ctx)
return initial_render, local_submission
end
---Which areas of the display a set of changed resources affects. `activity` names
---no area: execution and inbox render nothing, they only release held-back writes.
---@param resources? table<string, boolean> Omitted for an explicit full refresh
---@return {conversation: boolean, prompts: boolean, files: boolean, activity: boolean}
local function affected_areas(resources)
if not resources then
return { conversation = true, prompts = false, files = false, activity = false }
end
return {
conversation = resources.messages or resources.session or resources.children or false,
prompts = resources.permissions or resources.questions or false,
files = resources.files or false,
activity = resources.execution or resources.inbox or false,
}
end
---A child's conversation is visible only through its task part in the root.
---@param observation table
---@return boolean rendered Whether the child still has somewhere to render
---@param ctx RendererCtx
local function mark_child_task_dirty(ctx, observation)
local session_id = ctx.render_session and ctx.render_session:child_id(observation)
if not session_id then
return false
end
local task_part_id = ctx.render_state:get_task_part_by_child_session(session_id)
if task_part_id then
flush.mark_part_dirty(task_part_id, nil, ctx)
end
return true
end
---@param observation table The observation that changed, root or descendant
---@param resources? table<string, boolean> Omitted for an explicit full refresh
---@param ctx RendererCtx
local function reconcile_observation(ctx, observation, resources)
if not ctx:is_active() then
ctx.needs_reconcile = true
return
end
ctx.needs_reconcile = not output_window.mounted()
local root = ctx.observation
if not root then
return
end
local affected = affected_areas(resources)
-- Nothing on screen depends on this change; only held-back writes need releasing.
if not (affected.conversation or affected.prompts or affected.files) then
flush.flush_pending_on_data_rendered(ctx)
return
end
if affected.conversation and observation ~= root and not mark_child_task_dirty(ctx, observation) then
return
end
local observations = ctx.render_session and ctx.render_session:sync_children() or { root }
local files_changed = (affected.conversation or affected.files) and apply_file_changes(ctx, root:read()) or false
if affected.conversation or affected.prompts or files_changed then
local initial_render = false
local local_submission = false
if affected.conversation then
local session, entries = read_conversation(ctx, root)
initial_render, local_submission = reconcile_conversation(ctx, session, entries, files_changed)
elseif files_changed then
invalidate_text_references(ctx)
end
if affected.conversation or affected.prompts then
sync_prompt_controllers(ctx, observations)
end
flush.flush({ resolve_symbol_targets = initial_render }, ctx)
if initial_render then
flush.end_bulk_mode(ctx)
M.scroll_to_bottom(true, ctx)
elseif local_submission then
M.scroll_to_bottom(true, ctx)
end
end
if affected.activity then
flush.flush_pending_on_data_rendered(ctx)
end
end
---Effective size of the rendered window: `lazy_render_count` capped by the
---cached total (nil means everything cached is rendered).
---@return number
---@param ctx RendererCtx
local function window_size(ctx)
local total = visible_message_count(ctx)
return math.min(ctx.lazy_render_count or total, total)
end
---Grow the rendered window to `target` messages (capped at the cached
---total) and re-render. Single write primitive for the lazy window.
---@param target number desired window size
---@return boolean Whether the window grew
---@param ctx RendererCtx
local function apply_window_growth(ctx, target)
local total = visible_message_count(ctx)
target = math.min(target, total)
local current = math.min(ctx.lazy_render_count or total, total)
if target <= current then
return false
end
ctx.lazy_render_count = target --[[@as integer]]
M.render_from_cache(ctx, { scroll_to_bottom = false })
return true
end
---Capture the top visible line as a message anchor so the view survives a
---re-render that prepends older history.
---@return table|nil { id: string, offset: number }
---@param ctx? RendererCtx
function M.capture_top_anchor(ctx)
ctx = ctx or contexts.current()
local win = state.windows and state.windows.output_win
if not win or not vim.api.nvim_win_is_valid(win) then
return nil
end
local top_line = output_window.get_visible_top_line(win)
if not top_line then
return nil
end
for _, entry in ipairs(ctx.entries) do
local rendered = ctx.render_state:get_message(entry.id)
if rendered and rendered.line_start and rendered.line_end and rendered.line_end >= top_line then
return { id = entry.id, offset = math.max(0, top_line - rendered.line_start) }
end
end
return nil
end
---@param anchor table|nil
---@param ctx? RendererCtx
---@return integer|nil
local function anchor_topline(anchor, ctx)
ctx = ctx or contexts.current()
if not anchor then
return nil
end
local rendered = ctx.render_state:get_message(anchor.id)
if not rendered or not rendered.line_start then
return nil
end
return math.max(1, rendered.line_start + anchor.offset)
end
---Restore a view captured by `capture_top_anchor` after a re-render.
---@param anchor table|nil
---@param ctx? RendererCtx
function M.restore_top_anchor(anchor, ctx)
ctx = ctx or contexts.current()
if not anchor then
return
end
local win = state.windows and state.windows.output_win
if not win or not vim.api.nvim_win_is_valid(win) then
return
end
local restored = anchor_topline(anchor, ctx)
if restored then
pcall(output_window.restore_view_topline, win, restored)
end
end
---@return { offset: integer, col: integer }|nil
local function capture_cursor_anchor()
local win = state.windows and state.windows.output_win
if not win or not vim.api.nvim_win_is_valid(win) then
return nil
end
local top_line = output_window.get_visible_top_line(win)
if not top_line then
return nil
end
local cursor = vim.api.nvim_win_get_cursor(win)
return { offset = cursor[1] - top_line, col = cursor[2] }
end
---@param anchor { offset: integer, col: integer }|nil
---@param top_line? integer
local function restore_cursor_anchor(anchor, top_line)
if not anchor then
return
end
local win = state.windows and state.windows.output_win
local buf = state.windows and state.windows.output_buf
if not win or not buf or not vim.api.nvim_win_is_valid(win) or not vim.api.nvim_buf_is_valid(buf) then
return
end
top_line = top_line or output_window.get_visible_top_line(win) or 1
local line_count = vim.api.nvim_buf_line_count(buf)
local line = math.max(1, math.min(line_count, top_line + anchor.offset))
pcall(vim.api.nvim_win_set_cursor, win, { line, anchor.col })
end
local function notify_history_failure(err)
local message = type(err) == 'table' and (err.message or err.cause) or err
vim.notify('Failed to load older messages: ' .. tostring(message), vim.log.levels.WARN)
end
---The cached window is exhausted but the protocol may still hold older
---pages: pull one page, grow the rendered window by one viewport past the
---merge, and keep the view anchored where it was. The protocol short-circuits
---to a no-op when the history is already complete, so no pre-check is needed.
---@return boolean Whether a page load was started
---@param ctx RendererCtx
local function grow_window_with_older_page(ctx)
local observation = ctx.observation
if not observation or type(observation.load_older) ~= 'function' then
return false
end
local window_before = window_size(ctx)
local entries_before = #ordered_entries(observation)
local navigation_revision = ctx.history_navigation_revision
local anchor = M.capture_top_anchor(ctx)
local cursor_anchor = capture_cursor_anchor()
local ok, request = pcall(function()
return observation:load_older()
end)
if not ok then
return false
end
request:and_then(function()
if not ctx:is_active() or ctx.observation ~= observation then
return
end
if ctx.history_navigation_revision ~= navigation_revision then
return
end
-- nothing merged (complete history or a concurrent pull elsewhere):
-- leave the window alone
if #ordered_entries(observation) <= entries_before then
return
end
ctx.entries = ordered_entries(observation)
if not apply_window_growth(ctx, window_before + get_initial_render_count()) then
-- the window already covered everything cached: drop the window limit
-- so the merged prefix renders, without pulling more pages
ctx.lazy_render_count = nil
M.render_from_cache(ctx, { scroll_to_bottom = false })
end
restore_cursor_anchor(cursor_anchor, anchor_topline(anchor, ctx))
M.restore_top_anchor(anchor, ctx)
end, notify_history_failure)
return true
end
---Pull the complete remaining history and render all of it.
---@return boolean Whether a history load was started
---@param ctx RendererCtx
---@param scroll_to_top boolean
local function load_complete_history(ctx, scroll_to_top)
local observation = ctx.observation
if not observation or type(observation.load_complete_history) ~= 'function' then
return false
end
local win = state.windows and state.windows.output_win
local navigation_revision = ctx.history_navigation_revision
local ok, request = pcall(function()
return observation:load_complete_history()
end)
if not ok then
ctx.history_top_pending = false
return false
end
request
:and_then(function()
if
not ctx:is_active()
or ctx.observation ~= observation
or ctx.history_navigation_revision ~= navigation_revision
then
return
end
-- grow to the merged total only; the rendering primitive does not
-- touch the protocol, so this callback cannot re-enter the pull
ctx.entries = ordered_entries(observation)
apply_window_growth(ctx, math.huge)
if scroll_to_top and win and vim.api.nvim_win_is_valid(win) then
pcall(vim.api.nvim_win_set_cursor, win, { 1, 0 })
pcall(output_window.restore_view_topline, win, 1)
end
ctx.history_top_pending = false
end)
:catch(function(err)
if ctx.history_navigation_revision == navigation_revision then
ctx.history_top_pending = false
end
notify_history_failure(err)
end)
return true
end
---Reset all renderer state and clear the output buffer
---@param ctx? RendererCtx
function M.reset(ctx)
ctx = ctx or contexts.current()
ctx:reset()
reference_facts.clear()
output_window.clear()
if ctx.prompt_controllers.permission then
ctx.prompt_controllers.permission.clear_all()
end
if ctx.prompt_controllers.question then
ctx.prompt_controllers.question.clear_all()
end
state.renderer.reset()
flush.trigger_on_data_rendered(ctx)
end
---Unsubscribe from all events and reset
---@param ctx? RendererCtx
function M.teardown(ctx)
ctx = ctx or contexts.current()
M.setup_subscriptions(false, ctx)
detach_render_session(ctx)
M.reset(ctx)
end
---Subscribe to (or unsubscribe from) all renderer events
---@param subscribe? boolean false to unsubscribe (default true)
---@param ctx? RendererCtx
function M.setup_subscriptions(subscribe, ctx)
ctx = ctx or contexts.current()
subscribe = subscribe == nil and true or subscribe
if subscribe then
state.store.subscribe('is_opencode_focused', M.on_focus_changed)
state.store.subscribe('last_focused_opencode_window', M.on_focus_changed)
state.store.subscribe('active_session', M.on_session_changed)
state.store.subscribe('active_session_tab', M.on_session_tab_changed)
else
state.store.unsubscribe('is_opencode_focused', M.on_focus_changed)
state.store.unsubscribe('last_focused_opencode_window', M.on_focus_changed)
state.store.unsubscribe('active_session', M.on_session_changed)
state.store.unsubscribe('active_session_tab', M.on_session_tab_changed)
end
if subscribe and state.active_session then
M.on_session_changed(nil, state.active_session, nil, ctx)
end
end
---@param entries table[]
---@param session? table
---@param ctx? RendererCtx
---@param opts? {scroll_to_bottom?: boolean}
function M._render_full_session_data(entries, session, ctx, opts)
ctx = ctx or contexts.current()
local lazy_limit = ctx.lazy_render_count
local history_expanded = ctx.history_expanded
local navigation_revision = ctx.history_navigation_revision
local history_top_pending = ctx.history_top_pending
M.reset(ctx)
ctx.history_expanded = history_expanded
ctx.history_navigation_revision = navigation_revision
ctx.history_top_pending = history_top_pending
if ctx.observation then
update_observation_stats(ctx.observation)
end
ctx.entries = entries or {}
session = session or current_session(ctx)
reference_facts.rebuild(session.id, ctx.entries, session.location)
local visible_messages, hidden_count = get_visible_session_messages(ctx.entries, session, ctx)
if lazy_limit == nil then
local initial = get_initial_render_count()
if #visible_messages > initial then
lazy_limit = initial
end
end
ctx.lazy_render_count = lazy_limit
if lazy_limit and #visible_messages > lazy_limit then
visible_messages = vim.list_slice(visible_messages, #visible_messages - lazy_limit + 1)
end
flush.begin_bulk_mode(ctx)
if hidden_count > 0 then
ensure_message_rendered(ctx, build_hidden_messages_notice(hidden_count))
end
for _, entry in ipairs(visible_messages) do
ensure_message_rendered(ctx, entry)
end
local revert_message = build_revert_message(ctx.entries, session)
if revert_message then
ensure_message_rendered(ctx, revert_message)
end
flush.flush(nil, ctx)
flush.end_bulk_mode(ctx)
if not opts or opts.scroll_to_bottom ~= false then
M.scroll_to_bottom(true, ctx)
end
if config.hooks and config.hooks.on_session_loaded then
pcall(config.hooks.on_session_loaded, session)
end
end
---@param ctx? RendererCtx
---@param opts? {scroll_to_bottom?: boolean}
function M.render_from_cache(ctx, opts)
ctx = ctx or contexts.current()
if not output_window.mounted() or #ctx.entries == 0 then
return
end
local entries = ctx.observation and ordered_entries(ctx.observation) or ctx.entries
---@cast entries table[]
M._render_full_session_data(entries, current_session(ctx), ctx, opts)
end
---Load more older messages into the output buffer.
---Called when user scrolls to the top of the output window.
---@return boolean Whether more messages were loaded
---@param ctx? RendererCtx
function M.load_more_messages(ctx)
ctx = ctx or contexts.current()
if #ctx.entries == 0 or ctx.history_top_pending then
return false
end