-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.lua
More file actions
1399 lines (1204 loc) · 47.2 KB
/
Copy pathmanager.lua
File metadata and controls
1399 lines (1204 loc) · 47.2 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
-- Enhanced diff manager for diffusion.nvim
-- Unified coordinator that delegates to specialized modules following the new architecture
--
-- ============================================================================
-- PROVIDER-AGNOSTIC DESIGN VIOLATIONS - REFACTORING REQUIRED
-- ============================================================================
--
-- This file contains provider-specific conditionals that violate provider agnosticism.
-- Core modules should use configuration or strategy patterns, not hardcoded checks.
--
-- CRITICAL VIOLATIONS:
-- 1. Protocol-Specific Conditionals (line 600):
-- if data.protocol ~= "claude" then
-- self:accept_diff(diff_id) -- Claude skips this
-- end
-- VIOLATION: Hardcoded provider check in core logic
-- FIX: Use provider configuration/strategy pattern
--
-- 2. Missing Abstraction for Provider Behaviors:
-- - No strategy pattern for different provider behaviors
-- - No configuration-driven behavior selection
-- - Direct protocol checks instead of capability queries
--
-- 3. State Management Issues:
-- - Should handle _pending_diff_responses from Claude protocol
-- - Should abstract deferred response handling
--
-- PLANNED REFACTORING:
-- Phase 1: Remove protocol conditionals
-- Replace: if data.protocol ~= "claude" then
-- With: if self:_get_provider_config(data.protocol).handle_file_operations then
--
-- Phase 2: Implement provider strategies
-- Create: diff/strategies/claude_strategy.lua
-- Create: diff/strategies/opencode_strategy.lua
-- Use strategy pattern for provider-specific behaviors
--
-- Phase 3: Add deferred response handling
-- - Move _pending_diff_responses from protocol/claude/diff.lua here
-- - Create unified deferred response management
--
-- Phase 4: Configuration-driven behavior
-- provider_behaviors = {
-- claude = { file_operations = "external", diff_dismissal = "manual" },
-- opencode = { file_operations = "internal", diff_dismissal = "auto" }
-- }
--
-- TARGET: Zero protocol checks in core logic, all behavior configuration-driven
-- ============================================================================
local DiffManager = {}
-- Singleton instance
local _instance = nil
-- Module-level caches for performance (avoid per-call allocation and dynamic require)
local _cached_diff_engine = nil
local _cached_display_modules = {}
local function get_diff_engine()
if not _cached_diff_engine then
_cached_diff_engine = require('diffusion.diff.engine'):new()
end
return _cached_diff_engine
end
-- Get display module with caching (avoid dynamic require in hot path)
local function get_display_module(mode)
if not _cached_display_modules[mode] then
local ok, module = pcall(require, "diffusion.diff.display." .. mode)
if ok then
_cached_display_modules[mode] = module
end
end
return _cached_display_modules[mode]
end
-- Get or create the singleton DiffManager instance.
-- On first call: creates instance and subscribes to events.
-- On subsequent calls: updates config/events refs, returns existing instance.
function DiffManager.get_instance(config, events)
if _instance then
-- Update refs for new start cycle (events bus may be recreated)
_instance._config = config or _instance._config
if events and events ~= _instance._events then
-- Events bus changed — re-subscribe
_instance:_teardown_event_subscriptions()
_instance._events = events
_instance:_setup_event_handlers()
-- Navigation also needs the new events bus
if _instance._navigation then
_instance._navigation:cleanup()
_instance._navigation = nil
end
_instance:_setup_navigation()
end
_instance._logger:info("DiffManager singleton reused (start/stop cycle)")
return _instance
end
local instance = {
_config = config or {},
_events = events,
_logger = require('diffusion.utils.logger'):child("DiffManager"),
_active_diffs = {},
_active_diff_count = 0, -- O(1) count tracking (avoids vim.tbl_count)
_file_to_diff_ids = {}, -- Index: filename -> {diff_id = true, ...} for O(1) lookup
_cleanup_handlers = {},
_call_id_map = {}, -- Maps call_id → diff_id for provider lookups
_event_subscriptions = {}, -- Track event subscriptions for cleanup
_stats = {
diffs_created = 0,
diffs_accepted = 0,
diffs_rejected = 0,
diffs_dismissed = 0,
concurrent_diffs = 0,
max_concurrent = 0
},
_pending_deferred = {}
}
setmetatable(instance, { __index = DiffManager })
instance:_setup_event_handlers()
instance:_setup_navigation()
-- Debug logging for config received (after instance is fully set up)
instance._logger:debug("DiffManager created with config", {
config_received = config ~= nil,
default_mode = config and config.default_mode,
config_keys = config and vim.tbl_keys(config) or {}
})
_instance = instance
return instance
end
-- Main entry point for showing diffs
function DiffManager:show_diff(params)
-- Generate unique diff ID if not provided
local diff_id = params.diff_id or require('diffusion.utils').generate_id("diff")
-- Validate parameters
local valid, error_msg = self:_validate_diff_params(params)
if not valid then
self._logger:error("Invalid diff parameters", { error = error_msg })
return { success = false, error = error_msg }
end
-- Check concurrent diff limits (use O(1) count instead of O(n) vim.tbl_count)
local concurrent_limit = self:_get_concurrent_limit(params.protocol)
if self._active_diff_count >= concurrent_limit then
self:_cleanup_oldest_diff()
end
-- Determine display mode and handler
local display_mode = params.display_mode or self._config.default_mode or "split"
local blocking = params.blocking or false
-- Debug logging for display mode selection
self._logger:debug("Display mode selection", {
params_display_mode = params.display_mode,
config_default_mode = self._config.default_mode,
final_display_mode = display_mode,
config_keys = vim.tbl_keys(self._config or {})
})
-- ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
-- ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ STEP 1.1: DIFFUSION DISPLAYS DIFF ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
-- ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
self._logger:info("📋 STEP 1.1: DIFFUSION DISPLAYS DIFF - Creating diff view in manager", {
id = diff_id,
file = params.file_path,
mode = display_mode,
blocking = blocking,
protocol = params.protocol
})
-- Create diff entry
local diff_entry = self:_create_diff_entry(diff_id, params, display_mode)
self._active_diffs[diff_id] = diff_entry
self._active_diff_count = self._active_diff_count + 1
-- Add to file index for O(1) cleanup lookups
if diff_entry.file_path then
local filename = diff_entry.file_path:match("([^/]+)$") or diff_entry.file_path
self._file_to_diff_ids[filename] = self._file_to_diff_ids[filename] or {}
self._file_to_diff_ids[filename][diff_id] = true
end
-- Store call_id mapping if provided (for provider lookups)
if params.metadata and params.metadata.call_id then
self._call_id_map[params.metadata.call_id] = diff_id
diff_entry.call_id = params.metadata.call_id
self._logger:debug("Stored call_id mapping", {
call_id = params.metadata.call_id,
diff_id = diff_id
})
elseif params.call_id then
-- Also support direct call_id parameter
self._call_id_map[params.call_id] = diff_id
diff_entry.call_id = params.call_id
self._logger:debug("Stored call_id mapping (direct)", {
call_id = params.call_id,
diff_id = diff_id
})
end
-- Update statistics (use O(1) count)
self._stats.diffs_created = self._stats.diffs_created + 1
self._stats.concurrent_diffs = self._active_diff_count
if self._stats.concurrent_diffs > self._stats.max_concurrent then
self._stats.max_concurrent = self._stats.concurrent_diffs
end
-- Create diff view directly (no handler delegation)
local success = self:_create_diff_view_direct(diff_entry)
if not success then
self._active_diffs[diff_id] = nil
self._stats.concurrent_diffs = self._stats.concurrent_diffs - 1
return { success = false, error = "Failed to create diff view" }
end
-- Collect changed lines AFTER buffer is created for later navigation use
local first_change_line = self:_get_first_change_line(diff_entry)
local changed_lines = self:_get_changed_lines(diff_entry)
-- Store navigation data in diff entry
diff_entry.first_change_line = first_change_line
diff_entry.navigation_line = first_change_line and math.max(1, first_change_line - 5) or nil
diff_entry.changed_lines = changed_lines
-- Setup cleanup handlers
self:_setup_cleanup_handlers(diff_entry)
-- Emit diff created event
self._events:emit("diff:created", {
diff_id = diff_id,
file_path = diff_entry.file_path,
protocol = params.protocol,
mode = display_mode,
blocking = blocking
})
return {
success = true,
diff_id = diff_id,
blocking = blocking,
display_mode = display_mode
}
end
-- Wait for user response (blocking mode)
function DiffManager:wait_for_response(diff_id, timeout_ms)
local diff_entry = self._active_diffs[diff_id]
if not diff_entry then
return "error"
end
if not diff_entry.blocking then
self._logger:warn("wait_for_response called on non-blocking diff", { id = diff_id })
return "error"
end
-- Direct blocking wait implementation (no handler delegation)
return self:_wait_for_response_direct(diff_entry, timeout_ms)
end
-- Accept diff changes
function DiffManager:accept_diff(diff_id)
local diff_entry = self._active_diffs[diff_id]
if not diff_entry then
return false
end
local success = self:_apply_changes(diff_entry)
if success then
self._stats.diffs_accepted = self._stats.diffs_accepted + 1
diff_entry.status = "accepted"
local first_change_line = self:_get_first_change_line(diff_entry)
local nav_line = first_change_line and math.max(1, first_change_line - 5) or nil
local changed_lines = self:_get_changed_lines(diff_entry)
self._events:emit("diff:accepted", {
diff_id = diff_id,
file_path = diff_entry.file_path,
protocol = diff_entry.protocol,
navigation_line = nav_line,
changed_lines = changed_lines
})
self._logger:info("Diff accepted", { id = diff_id, file = diff_entry.file_path })
end
return success
end
-- Reject diff changes
function DiffManager:reject_diff(diff_id)
local diff_entry = self._active_diffs[diff_id]
if not diff_entry then
return false
end
self._stats.diffs_rejected = self._stats.diffs_rejected + 1
diff_entry.status = "rejected"
self._events:emit("diff:rejected", {
diff_id = diff_id,
file_path = diff_entry.file_path,
protocol = diff_entry.protocol
})
self._logger:info("Diff rejected", { id = diff_id, file = diff_entry.file_path })
return true
end
-- Dismiss diff (cleanup)
function DiffManager:dismiss_diff(diff_id)
local diff_entry = self._active_diffs[diff_id]
if not diff_entry then
return false
end
-- ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
-- ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ STEP 2.1: DIFFUSION CLOSES DIFF ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
-- ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
self._logger:info("🔚 STEP 2.1: DIFFUSION CLOSES DIFF - Dismissing diff", {
id = diff_id,
file = diff_entry.file_path
})
-- Window position was captured in user_response_handler BEFORE windows
-- were torn down (winsaveview on the main/new diff window). Capturing
-- here is too late — diff windows are already closed by this point and
-- Neovim would report topline=1 from whatever buffer replaced them.
local window_position = diff_entry.window_position
self._stats.diffs_dismissed = self._stats.diffs_dismissed + 1
-- Guard against re-entry from BufDelete autocmd firing during cleanup
diff_entry._cleanup_in_progress = true
-- Clean up resources
self:_cleanup_diff_resources(diff_entry)
-- Clean up call_id mapping if present
if diff_entry.call_id then
self._call_id_map[diff_entry.call_id] = nil
self._logger:debug("Cleaned up call_id mapping", {
call_id = diff_entry.call_id,
diff_id = diff_id
})
end
-- Remove from file index
if diff_entry.file_path then
local filename = diff_entry.file_path:match("([^/]+)$") or diff_entry.file_path
if self._file_to_diff_ids[filename] then
self._file_to_diff_ids[filename][diff_id] = nil
-- Clean up empty index entries
if not next(self._file_to_diff_ids[filename]) then
self._file_to_diff_ids[filename] = nil
end
end
end
-- Remove from active diffs (use O(1) count)
self._active_diffs[diff_id] = nil
self._active_diff_count = self._active_diff_count - 1
self._stats.concurrent_diffs = self._active_diff_count
-- Single navigation: pass new_content and changed_lines for accepted diffs
-- so navigation can populate buffer from memory (instant) and highlight changes.
-- Rejected diffs get nil — navigation falls to edit! (old content from disk)
-- with no highlighting.
local was_rejected = diff_entry.status == "rejected"
-- Strip nav fields when optimistic already ran — handler short-circuits on
-- nil navigation_line. Rejected path (no optimistic) still gets full payload
-- so navigation reloads from disk via edit!, reverting the user's view.
local skip_nav = diff_entry.optimistic_nav_done
self._events:emit("diff:dismissed", {
diff_id = diff_id,
file_path = diff_entry.file_path,
protocol = diff_entry.protocol,
navigation_line = not skip_nav and diff_entry.navigation_line or nil,
changed_lines = (not skip_nav and not was_rejected) and diff_entry.changed_lines or nil,
window_position = window_position,
new_content = (not skip_nav and not was_rejected) and diff_entry.new_content or nil
})
self._logger:info("Diff dismissed", { id = diff_id, file = diff_entry.file_path })
return true
end
-- Cleanup diffs for specific file (called by close_tab)
-- Optimized: O(1) lookup using file index instead of O(n) iteration
function DiffManager:cleanup_diffs_for_file(file_name)
if not file_name then
return false
end
self._logger:debug("Cleaning up diffs for file", {
file = file_name,
active_diff_count = self._active_diff_count
})
-- O(1) lookup using file index
local diff_ids = self._file_to_diff_ids[file_name]
if not diff_ids or not next(diff_ids) then
self._logger:debug("No diffs found for file (index lookup)", { file = file_name })
return false
end
-- Collect diff_ids to clean (copy keys since dismiss_diff modifies the index)
local diff_ids_to_clean = {}
for diff_id in pairs(diff_ids) do
table.insert(diff_ids_to_clean, diff_id)
self._logger:debug("Matched diff for cleanup", {
diff_id = diff_id,
filename = file_name
})
end
-- Clean up matching diffs
local cleaned_count = 0
for _, diff_id in ipairs(diff_ids_to_clean) do
if self:dismiss_diff(diff_id) then
cleaned_count = cleaned_count + 1
end
end
if cleaned_count > 0 then
self._logger:info("Cleaned up diffs for file", {
file = file_name,
count = cleaned_count
})
return true
else
self._logger:debug("No diffs found for file", { file = file_name })
return false
end
end
-- Toggle display mode
function DiffManager:toggle_display_mode(diff_id)
local diff_entry = self._active_diffs[diff_id]
if not diff_entry then
return false
end
local current_mode = diff_entry.display_mode
local new_mode = current_mode == "split" and "unified" or "split"
local new_handler = get_display_module(new_mode)
if not new_handler then
self._logger:error("Failed to load display module", { mode = new_mode })
return false
end
-- Preserve cursor across the swap (best-effort).
local saved_cursor
local cur_win = vim.api.nvim_get_current_win()
if vim.api.nvim_win_is_valid(cur_win) then
local ok, pos = pcall(vim.api.nvim_win_get_cursor, cur_win)
if ok then saved_cursor = pos end
end
-- Full teardown: handler cleanup() only clears extmarks/vars by design;
-- window/buffer disposal lives in _cleanup_diff_resources. The toggle
-- must call it, otherwise the new handler inherits a fragmented layout
-- (leftover windows, leaked buffers) and :diffthis lands on the wrong
-- windows, producing a vsplit with no diff highlighting.
self:_cleanup_diff_resources(diff_entry)
diff_entry.buffers = nil
diff_entry.windows = nil
diff_entry.cleanup_handlers = {}
-- Re-arm deferred-response keymaps (Claude) so accept/reject still work
-- after a toggle. Skip if the user already responded — don't let them
-- respond twice.
local already_responded = diff_entry.responded
if not already_responded then
diff_entry.responded = false
end
-- Pass events so deferred-mode interactive keybindings rebind.
local success = new_handler:create(diff_entry, self._events)
if not success then
self._logger:error("Toggle failed during new handler create", { mode = new_mode })
local prev_handler = get_display_module(current_mode)
if prev_handler then
pcall(function() prev_handler:create(diff_entry, self._events) end)
end
return false
end
diff_entry.display_mode = new_mode
diff_entry.display_handler = new_handler
if saved_cursor then
local now_win = vim.api.nvim_get_current_win()
if vim.api.nvim_win_is_valid(now_win) then
pcall(vim.api.nvim_win_set_cursor, now_win, saved_cursor)
end
end
self._logger:info("Display mode toggled", {
id = diff_id,
from = current_mode,
to = new_mode
})
return true
end
-- Update diff content (for streaming)
function DiffManager:update_diff(diff_id, update_params)
local diff_entry = self._active_diffs[diff_id]
if not diff_entry then
return false
end
-- Update content
if update_params.new_content then
diff_entry.new_content = update_params.new_content
end
-- Use cached display handler from diff_entry, or get from cache
local display_handler = diff_entry.display_handler or get_display_module(diff_entry.display_mode)
if not display_handler then
return false
end
return display_handler:update(diff_entry, update_params)
end
-- Get current diff context
function DiffManager:get_current_diff()
local current_buf = 0
local success, buf = pcall(vim.api.nvim_get_current_buf)
if success then
current_buf = buf
end
-- If we can't get current buffer (fast context), return nil
if current_buf == 0 then
return nil
end
for diff_id, diff_entry in pairs(self._active_diffs) do
if diff_entry.buffers then
for _, bufnr in pairs(diff_entry.buffers) do
if bufnr == current_buf then
return diff_entry
end
end
end
end
return nil
end
-- Get active diff by ID
function DiffManager:get_active_diff(diff_id)
return self._active_diffs[diff_id]
end
-- Get all active diffs
function DiffManager:get_active_diffs()
return vim.deepcopy(self._active_diffs)
end
-- Find diff by provider call_id
-- Returns diff_id if found, nil otherwise
function DiffManager:find_diff_by_call_id(call_id)
if not call_id then
return nil
end
return self._call_id_map[call_id]
end
-- Get diff entry by call_id (convenience method)
-- Returns full diff entry if found, nil otherwise
function DiffManager:get_diff_by_call_id(call_id)
local diff_id = self:find_diff_by_call_id(call_id)
if diff_id then
return self._active_diffs[diff_id]
end
return nil
end
-- Get statistics
function DiffManager:get_stats()
local stats = vim.deepcopy(self._stats)
stats.active_diffs = self._active_diff_count -- O(1) instead of O(n)
return stats
end
-- Clean up all diffs
function DiffManager:cleanup_all()
local diff_ids = vim.tbl_keys(self._active_diffs)
local cleaned_count = 0
self._logger:info("🧹 STARTING CLEANUP_ALL", {
total_diffs = #diff_ids,
active_diffs = vim.tbl_keys(self._active_diffs)
})
for _, diff_id in ipairs(diff_ids) do
self._logger:info("🔄 Processing diff in cleanup_all", {
diff_id = diff_id,
diff_entry = self._active_diffs[diff_id] and "exists" or "missing"
})
local success, err = pcall(function()
self:dismiss_diff(diff_id)
end)
if success then
cleaned_count = cleaned_count + 1
self._logger:info("✅ Successfully cleaned diff", { diff_id = diff_id })
else
self._logger:error("❌ Failed to clean diff in cleanup_all", {
diff_id = diff_id,
error = err,
error_type = type(err)
})
end
end
self._logger:info("🏁 CLEANUP_ALL COMPLETED", {
attempted = #diff_ids,
succeeded = cleaned_count,
failed = #diff_ids - cleaned_count,
remaining_active = self._active_diff_count -- O(1) instead of O(n)
})
end
-- Unsubscribe event listeners without destroying instance state.
-- Used when the events bus is being replaced (start/stop cycle).
function DiffManager:_teardown_event_subscriptions()
for _, sub in ipairs(self._event_subscriptions or {}) do
self._events:off(sub.event, sub.handler)
end
self._event_subscriptions = {}
end
-- Full cleanup including event subscriptions (call when destroying the manager)
function DiffManager:destroy()
self._logger:info("Destroying DiffManager instance")
-- Clean up all active diffs first
self:cleanup_all()
-- Unsubscribe from all events
self:_teardown_event_subscriptions()
-- Clean up navigation module if it exists
if self._navigation and self._navigation.cleanup then
self._navigation:cleanup()
self._navigation = nil
end
-- Clear singleton reference
_instance = nil
self._logger:debug("DiffManager destroyed")
end
-- Private methods
function DiffManager:_validate_diff_params(params)
if not params.file_path then
return false, "file_path is required"
end
if not params.old_content and not params.new_content then
return false, "either old_content or new_content is required"
end
if params.display_mode and params.display_mode ~= "split" and params.display_mode ~= "unified" then
return false, "display_mode must be 'split' or 'unified'"
end
return true
end
function DiffManager:_create_diff_entry(diff_id, params, display_mode)
local entry = {
id = diff_id,
file_path = params.file_path,
old_content = params.old_content or "",
new_content = params.new_content or "",
title = params.title or ("Diff: " .. vim.fn.fnamemodify(params.file_path, ":t")),
protocol = params.protocol or "unknown",
display_mode = display_mode,
blocking = params.blocking or false,
session_id = params.session_id,
status = "pending",
created_at = os.time(),
buffers = {},
windows = {},
cleanup_handlers = {},
events = self._events, -- Pass the events object to enable proper event emission
behavior = self:_get_provider_behavior(params.protocol),
-- Cached diff data (generated once, used by display modules and navigation)
hunks = {},
diff_output = nil
}
-- Generate diff ONCE here - display modules and _get_changed_lines will use cached data
-- Note: Using git diff for now as DiffEngine has field name issues (hunk.lines vs hunk.diff)
if entry.old_content and entry.new_content then
entry.diff_output = self:_generate_git_diff(entry)
if entry.diff_output and entry.diff_output ~= "" then
entry.hunks = self:_parse_unified_diff(entry.diff_output)
end
end
return entry
end
function DiffManager:_get_concurrent_limit(protocol)
local config = self._config
-- Protocol-specific limit
if protocol and config.services and config.services[protocol] and
config.services[protocol].diff and config.services[protocol].diff.concurrent_limit then
return config.services[protocol].diff.concurrent_limit
end
-- Global limit
return config.diff and config.diff.max_concurrent_diffs or 10
end
function DiffManager:_cleanup_oldest_diff()
local oldest_id = nil
local oldest_time = math.huge
for diff_id, diff_entry in pairs(self._active_diffs) do
if diff_entry.created_at < oldest_time then
oldest_time = diff_entry.created_at
oldest_id = diff_id
end
end
if oldest_id then
self._logger:info("Auto-dismissing oldest diff due to limit", { id = oldest_id })
self:dismiss_diff(oldest_id)
end
end
function DiffManager:_apply_changes(diff_entry)
local file_utils = require('diffusion.utils.file')
local success, error = file_utils.write_file(diff_entry.file_path, diff_entry.new_content)
if not success then
self._logger:error("Failed to apply diff changes", {
file = diff_entry.file_path,
error = error
})
return false
end
-- Note: Buffer reload is handled by navigation module to avoid race conditions
-- The navigation will open the file with fresh content from disk
return true
end
function DiffManager:_setup_cleanup_handlers(diff_entry)
local diff_id = diff_entry.id
-- Auto-cleanup on buffer delete - use more specific events to prevent recursion
for _, bufnr in pairs(diff_entry.buffers or {}) do
if bufnr and pcall(vim.api.nvim_buf_is_valid, bufnr) then
local autocmd_id = vim.api.nvim_create_autocmd("BufDelete", {
buffer = bufnr,
once = true,
callback = function()
-- Only trigger dismiss if this diff is still active
if self._active_diffs[diff_id] and not self._active_diffs[diff_id]._cleanup_in_progress then
self._logger:debug("BufDelete autocmd triggered for diff", { id = diff_id, buf = bufnr })
self:dismiss_diff(diff_id)
end
end
})
table.insert(diff_entry.cleanup_handlers, {
type = "autocmd",
id = autocmd_id
})
end
end
end
-- The window the user owns for this diff. Both display modes hand us the
-- user's editing window inside diff_entry.windows: unified reuses the current
-- window (as .unified/.main), split records the original as .user_win.
-- Diffusion must NEVER close this window — it's the user's, and the optimistic
-- paint reuses it to show the accepted file. Single source of truth for the
-- two window-cleanup sites (accept handler + _cleanup_diff_resources).
function DiffManager:_user_window(diff_entry)
local w = diff_entry.windows
if not w then return nil end
return w.user_win or w.unified or w.main
end
function DiffManager:_cleanup_diff_resources(diff_entry)
-- Clean up display (use cached handler to avoid dynamic require overhead)
if diff_entry.display_handler then
diff_entry.display_handler:cleanup(diff_entry)
elseif diff_entry.display_mode then
-- Fallback: use module cache instead of dynamic require
local display_handler = get_display_module(diff_entry.display_mode)
if display_handler then
display_handler:cleanup(diff_entry)
end
end
-- Clean up autocmds
for _, handler in ipairs(diff_entry.cleanup_handlers or {}) do
if handler.type == "autocmd" and handler.id then
pcall(vim.api.nvim_del_autocmd, handler.id)
end
end
-- Clean up windows — but NEVER the user's own window (see _user_window).
-- Closing it destroys the optimistic paint the accept handler just put
-- there (and tears down the user's editing context in multi-window layouts).
local keep_win = self:_user_window(diff_entry)
for _, win in pairs(diff_entry.windows or {}) do
if win ~= keep_win and vim.api.nvim_win_is_valid(win) then
pcall(vim.api.nvim_win_close, win, true)
end
end
-- Clean up buffers
for _, buf in pairs(diff_entry.buffers or {}) do
if vim.api.nvim_buf_is_valid(buf) then
pcall(vim.api.nvim_buf_delete, buf, { force = true })
end
end
end
function DiffManager:_setup_event_handlers()
self._logger:info("🔥 MANAGER SETTING UP EVENT HANDLERS", {
events_object = tostring(self._events)
})
-- Handler for user responses
local user_response_handler = function(data)
local diff_id = data.diff_id
local response = data.response
self._logger:info("🔥 MANAGER RECEIVED diff:user_response event", {
diff_id = diff_id,
response = response,
active_diffs = vim.tbl_keys(self._active_diffs),
protocol = data.protocol
})
-- Decide whether DiffManager should apply file operations for this provider
local behavior = self:_get_provider_behavior(data.protocol)
if behavior.handle_file_operations then
if response == "accepted" or response == "always_accept" then
self._logger:info("🔥 MANAGER CALLING accept_diff", { diff_id = diff_id })
self:accept_diff(diff_id)
else
self._logger:info("🔥 MANAGER CALLING reject_diff", { diff_id = diff_id })
self:reject_diff(diff_id)
end
else
-- External file operations (Claude)
local diff_entry = self._active_diffs[diff_id]
if diff_entry then
-- Capture the user's actual view of the diff (topline + cursor)
-- from the new/main window BEFORE any teardown. Used as the
-- authoritative view state for post-nav positioning — replaces
-- the previous `first_change - 5` guess.
local new_win = diff_entry.windows and (
diff_entry.windows.unified -- unified mode
or diff_entry.windows.right -- split mode: new/right side
or diff_entry.windows.main
)
if new_win and vim.api.nvim_win_is_valid(new_win) then
-- Capture the cursor's SCREEN ROW in the diff window (winline()).
-- This is fold-aware and independent of the diff buffer's line
-- numbering (which in unified mode differs from file lines because
-- removed lines are interleaved). After nav we reproduce this
-- same screen row in the file window — "what the user saw at
-- row N, they see at row N again". No buffer-line math needed.
local screen_row = vim.api.nvim_win_call(new_win, function()
return vim.fn.winline()
end)
diff_entry.window_position = { diff_screen_row = screen_row }
end
if response == "accepted" or response == "always_accept" then
diff_entry.status = "accepted"
-- Close diff windows, but KEEP the user's editing window. Both
-- display modes hand us that window inside diff_entry.windows
-- (unified reuses the current window as .unified/.main; split
-- records it as .user_win). Closing it moves focus to an arbitrary
-- surviving window, so the optimistic paint — which does `buffer!`
-- in the CURRENT window — lands where the user isn't looking and
-- never appears to render. Keep that window, close only the
-- diff-created ones, then focus it so the paint lands there.
local keep_win = self:_user_window(diff_entry)
for _, win in pairs(diff_entry.windows or {}) do
if win ~= keep_win and vim.api.nvim_win_is_valid(win) then
pcall(vim.api.nvim_win_close, win, true)
end
end
if keep_win and vim.api.nvim_win_is_valid(keep_win) then
pcall(vim.api.nvim_set_current_win, keep_win)
end
-- Instant buffer population (optimistic). Mark so dismiss_diff skips
-- the redundant second nav pass — it does the same buffer load +
-- winrestview + highlight work, blocking the next queued showDiff.
-- Rejection correction is handled by schedule_deferred_disk_check.
--
-- Content source priority: event payload (data.buffer_content) first,
-- diff_entry.new_content as fallback. The event payload is captured
-- at user-response emit time and survives any subsequent diff_entry
-- mutation (cleanup, dismissal, concurrent show_diff for same file).
-- The cached fallback exists for legacy event emitters that don't
-- include buffer_content.
local paint_content = data.buffer_content
if not paint_content or paint_content == "" then
paint_content = diff_entry.new_content
end
-- Last resort: read the live proposed-side diff buffer. Covers the
-- new_content cache-lifecycle race (concurrent show_diff / cleanup
-- emptied the cache) where both the event payload and the cache are
-- empty — without this the optimistic paint is silently skipped and
-- the buffer only updates when Claude's disk write lands (or never).
-- The proposed buffer is still valid here; windows close below.
-- This also captures any in-diff user edits (the content Claude
-- expects back in FILE_SAVED).
if (not paint_content or paint_content == "") and diff_entry.buffers then
local proposed_bufnr = diff_entry.buffers.unified_bufnr
or diff_entry.buffers.main_bufnr
or diff_entry.buffers.new_bufnr
or diff_entry.buffers.right_bufnr
if proposed_bufnr and vim.api.nvim_buf_is_valid(proposed_bufnr) then
local lines = vim.api.nvim_buf_get_lines(proposed_bufnr, 0, -1, false)
paint_content = table.concat(lines, "\n")
end
end
if self._navigation and paint_content and paint_content ~= "" then
diff_entry.optimistic_nav_done = true
self._navigation:navigate_to_file(
diff_entry.file_path,
diff_entry.navigation_line,
diff_entry.changed_lines,
diff_entry.window_position,
paint_content
)
-- Release the optimistic lock once the provider's write lands
-- (disk == painted). This runs for EVERY accept path because the
-- paint engages the lock (modified=true + FCS augroup + content
-- record) on every accept — without a matching release the buffer
-- leaks a [+] flag and a per-buffer augroup. Only close_tab — which
-- carries no explicit reject signal — also infers rejection on
-- window exhaustion; explicit providers (diff-UI accept, opencode,
-- codex) just release the lock and let autoread reconcile.
self._navigation:schedule_deferred_disk_check(
diff_entry.file_path,
paint_content, -- the authoritative accepted content; the check
-- keeps the FCS suppressor until disk MATCHES this
{ infer_rejection = data.source == "close_tab" }
)
end
else
diff_entry.status = "rejected"
end
end
end
-- Always dismiss after user response. For "auto" providers this was
-- already the behaviour. For "manual" providers (Claude) the user's <CR>
-- accept/reject IS the manual dismissal — close_tab just happens to also
-- call dismiss_diff, which is a safe no-op once the diff is removed.
self:dismiss_diff(diff_id)
end
self._events:on("diff:user_response", user_response_handler)
table.insert(self._event_subscriptions, {
event = "diff:user_response",
handler = user_response_handler
})