-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.lua
More file actions
365 lines (311 loc) · 12.4 KB
/
Copy pathinit.lua
File metadata and controls
365 lines (311 loc) · 12.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
--[[
================================================================================
CORE INITIALIZATION MODULE - PROVIDER-AGNOSTIC REFACTORING GUIDE
================================================================================
PURPOSE:
Main entry point that initializes all diffusion.nvim components and provides
the public API used by commands and external integrations. Should delegate
all operations to appropriate subsystems (protocol, diff, ui).
ARCHITECTURAL PRINCIPLES:
1. Initialization and lifecycle management only
2. Delegates all operations to subsystems
3. Provides clean public API surface
4. No provider-specific logic
5. No business logic implementation
CURRENT ARCHITECTURAL VIOLATIONS:
☐ send_selection() implementation may be redundant with protocol layer
☐ Direct access to _protocol internals in send_message()
☐ No validation of protocol interface compliance
REQUIRED REFACTORING:
1. CLARIFY API SURFACE (Priority: HIGH)
CURRENT PUBLIC METHODS:
- Diffusion:setup(config) → Initializes plugin
- Diffusion:start() → Starts protocol and UI layers
- Diffusion:stop() → Stops all subsystems
- Diffusion.send_selection(selection_data) → Sends selection to AI
- Diffusion.send_message(message, service) → Sends message to AI
- Diffusion.status() → Returns plugin status
QUESTIONS TO RESOLVE:
- Is send_selection() needed at top level or just delegate to protocol?
- Should send_message() be public or only via commands?
- Does status() expose enough detail for debugging?
2. ADD PROTOCOL VALIDATION (Priority: MEDIUM)
ADD TO: _init_components() after protocol setup
- Validate each handler implements required interface
- Methods: start, stop, is_available, is_connected, get_status
- Methods: send_message, send_selection, send_at_mention (NEW)
- Warn if handler missing required methods
- Prevents runtime errors from incomplete handlers
3. IMPROVE ERROR HANDLING (Priority: MEDIUM)
CURRENT: Basic pcall wrappers
SHOULD: Structured error reporting
- Categorize errors (config, initialization, runtime)
- Provide actionable error messages
- Log errors with full context
- Graceful degradation when subsystems fail
PROVIDER-SPECIFIC VS GENERIC OPERATIONS:
GENERIC (belongs in this file):
- Component initialization order
- Configuration loading and merging
- Event system setup
- Lifecycle management (setup/start/stop)
- Public API delegation
- Status aggregation
- Auto-start logic
- Cleanup on exit
PROVIDER-SPECIFIC (does NOT belong here):
- Service selection logic (belongs in Protocol)
- Connection establishment (belongs in handlers)
- Message formatting (belongs in handlers)
- Tool registration (belongs in ToolService)
- Diff display (belongs in DiffManager)
COMPONENT INITIALIZATION ORDER:
1. Configuration (config.lua)
- Load defaults
- Merge user config
- Validate structure
2. Events (utils/events.lua)
- Create pub/sub system
- No listeners yet
3. Logging (utils/logger.lua)
- Setup file/console output
- Set log level
4. Diff Manager (diff/manager.lua)
- Provider-agnostic diff system
- Register event listeners
5. Protocol Layer (protocol/init.lua)
- Initialize all enabled handlers
- Detect available services
- Don't start connections yet
6. UI Layer (ui/init.lua)
- Setup selection tracking if enabled
- Setup immersive mode if enabled
7. Start (only if auto_start=true)
- Protocol:start() → connects to active service
- UI:start() → activates UI features
REFACTORING CHECKLIST:
☐ Add protocol interface validation
☐ Clarify send_selection() vs protocol:send_selection()
☐ Improve error categorization and messages
☐ Document component initialization dependencies
☐ Add integration tests for initialization sequence
☐ Verify cleanup runs on all exit paths
☐ Update this header as refactoring progresses
NOTE: This header must be updated as each refactoring task is completed.
Mark checkboxes with ☑ when done.
================================================================================
--]]
-- Minimal bootstrap for diffusion.nvim (restored)
-- Provides a light-weight initialization that wires core components.
local Diffusion = {}
Diffusion.version = "1.0.0"
Diffusion._initialized = false
Diffusion._config = nil
Diffusion._protocol = nil
Diffusion._diff = nil
Diffusion._ui = nil
Diffusion._events = nil
-- Internal helper to initialize components
local function _init_components(self, user_config)
-- Load runtime config with user overrides
local config = require('diffusion.config')
self._config = config:setup(user_config or {})
-- Setup events
self._events = require('diffusion.utils.events'):new()
-- Setup logging early using the same logger module
local logger_ok, logger = pcall(function()
return require('diffusion.utils.logger'):setup(self._config.logging)
end)
if logger_ok and logger then
logger:set_level(self._config.logging and self._config.logging.level or "DEBUG")
logger:info("diffusion.nvim bootstrap init", { version = self.version })
else
vim.notify("diffusion.nvim logger setup failed: " .. tostring(logger), vim.log.levels.WARN)
end
-- Diff system (singleton — survives start/stop cycles without leaking listeners)
self._diff = require('diffusion.diff.manager').get_instance(self._config.diff, self._events)
-- Protocol layer (pass diff manager to share with handlers)
self._protocol = require('diffusion.protocol'):new(self._config, self._events, self._diff)
-- Debug logging for diff config (after logger is properly initialized)
if self._diff and self._diff._logger then
self._diff._logger:debug("Diff manager initialized with config", {
diff_config = self._config.diff,
default_mode = self._config.diff and self._config.diff.default_mode
})
end
-- UI system
self._ui = require('diffusion.ui'):init(self._events, self._config.ui)
-- Initialize protocol state
self._protocol:setup()
end
function Diffusion.setup(self_or_config, user_config)
-- Support both .setup({config}) and :setup({config})
if self_or_config ~= Diffusion then
user_config = self_or_config
end
if Diffusion._initialized then
vim.notify("diffusion.nvim already initialized", vim.log.levels.WARN)
return
end
-- Skip initialization in headless mode
if vim.fn.has('gui_running') == 0 and vim.fn.has('nvim') == 1 and #vim.api.nvim_list_uis() == 0 then
vim.notify("diffusion.nvim: Skipping initialization in headless mode", vim.log.levels.INFO)
return true
end
-- Initialize components in a protected call to catch errors early
local ok, err = pcall(function()
_init_components(Diffusion, user_config)
end)
if not ok then
-- Fallback logging when normal logger setup fails
local logger_ok, logger = pcall(function()
return require('diffusion.utils.logger'):setup({})
end)
if logger_ok and logger then
logger:error("Initialization failed: " .. tostring(err))
else
-- Ultimate fallback to vim.notify if logger completely fails
vim.notify("diffusion.nvim initialization failed (logger also failed): " .. tostring(err), vim.log.levels.ERROR)
end
vim.notify("diffusion.nvim initialization failed: " .. tostring(err), vim.log.levels.ERROR)
return false
end
Diffusion._initialized = true
-- Setup commands after successful initialization
Diffusion._setup_commands()
-- Setup cleanup on exit
vim.api.nvim_create_autocmd("VimLeavePre", {
callback = function()
if Diffusion._initialized then
Diffusion:stop()
end
end,
desc = "Clean up diffusion.nvim on exit"
})
-- Auto-start if configured (but not in headless mode)
if Diffusion._config and Diffusion._config.auto_start then
-- Double-check we're not in headless mode for auto-start
if vim.fn.has('gui_running') == 0 and vim.fn.has('nvim') == 1 and #vim.api.nvim_list_uis() == 0 then
vim.notify("diffusion.nvim: Skipping auto-start in headless mode", vim.log.levels.DEBUG)
else
vim.defer_fn(function()
local start_ok = Diffusion:start()
if start_ok then
vim.notify("diffusion.nvim auto-started", vim.log.levels.TRACE)
else
vim.notify("diffusion.nvim auto-start failed", vim.log.levels.WARN)
end
end, 10) -- DELAY: 10ms auto-start delay to ensure everything is ready
end
end
return true
end
function Diffusion:start()
if not Diffusion._initialized then
vim.notify("diffusion.nvim not initialized. Call setup() first.", vim.log.levels.ERROR)
return false
end
-- Start protocol and UI
if Diffusion._protocol and Diffusion._protocol.start then
local ok, err = Diffusion._protocol:start()
if not ok then
vim.notify("diffusion.nvim protocol start failed: " .. tostring(err), vim.log.levels.ERROR)
return false
end
end
if Diffusion._ui and Diffusion._ui.start then
Diffusion._ui:start(Diffusion._config.ui)
end
vim.notify("diffusion.nvim started", vim.log.levels.TRACE)
return true
end
function Diffusion:stop()
if not Diffusion._initialized then return end
if Diffusion._protocol and Diffusion._protocol.stop then Diffusion._protocol:stop() end
if Diffusion._diff and Diffusion._diff.destroy then Diffusion._diff:destroy() end
Diffusion._diff = nil
if Diffusion._ui and Diffusion._ui.stop then Diffusion._ui:stop() end
Diffusion._initialized = false
vim.notify("diffusion.nvim stopped", vim.log.levels.INFO)
end
-- Expose an API used by other components
function Diffusion.send_selection(selection_data)
if not Diffusion._initialized then
vim.notify("diffusion.nvim not initialized", vim.log.levels.ERROR)
return false
end
selection_data = selection_data or (Diffusion._ui and Diffusion._ui:get_current_selection())
if not selection_data or selection_data.text == "" then
vim.notify("No selection to send", vim.log.levels.WARN)
return false
end
Diffusion._events:emit("diffusion:send_selection", { data = selection_data })
if Diffusion._protocol and Diffusion._protocol.send_selection then
return Diffusion._protocol:send_selection(selection_data)
end
return false
end
function Diffusion.send_message(message, service)
if not Diffusion._initialized then
vim.notify("diffusion.nvim not initialized", vim.log.levels.ERROR)
return false
end
if service then
local current = Diffusion._protocol:get_active_service()
if current ~= service then Diffusion._protocol:switch_service(service) end
end
if Diffusion._protocol and Diffusion._protocol.send_message then
return Diffusion._protocol:send_message(message)
end
return false
end
function Diffusion.status()
if not Diffusion._initialized then return { initialized = false } end
local active_service = Diffusion._protocol and Diffusion._protocol:get_active_service()
local service_statuses = Diffusion._protocol and Diffusion._protocol:get_all_service_statuses() or {}
local active_diffs_table = Diffusion._diff and Diffusion._diff:get_active_diffs() or {}
local active_diffs_count = 0
if active_diffs_table then
for _ in pairs(active_diffs_table) do
active_diffs_count = active_diffs_count + 1
end
end
return {
initialized = true,
version = Diffusion.version,
active_service = active_service,
service_statuses = service_statuses,
active_diffs = active_diffs_count
}
end
-- Command setup for all providers
function Diffusion._setup_commands()
-- Core diffusion commands
vim.api.nvim_create_user_command('DiffusionStatus', function()
local status = Diffusion.status()
print(vim.inspect(status))
end, { desc = "Show diffusion.nvim status" })
vim.api.nvim_create_user_command('DiffusionStart', function()
local success = Diffusion:start()
if success then
vim.notify("diffusion.nvim started", vim.log.levels.INFO)
else
vim.notify("Failed to start diffusion.nvim", vim.log.levels.ERROR)
end
end, { desc = "Start diffusion.nvim" })
vim.api.nvim_create_user_command('DiffusionStop', function()
Diffusion:stop()
vim.notify("diffusion.nvim stopped", vim.log.levels.INFO)
end, { desc = "Stop diffusion.nvim" })
-- Setup provider-specific commands
Diffusion._setup_provider_commands()
end
function Diffusion._setup_provider_commands()
-- Setup Gemini commands
local gemini_ok, gemini_init = pcall(require, 'diffusion.protocol.gemini.init')
if gemini_ok then
gemini_init.setup_commands()
end
-- Setup other provider commands as needed
end
return Diffusion