-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude.lua
More file actions
943 lines (800 loc) · 30.9 KB
/
Copy pathclaude.lua
File metadata and controls
943 lines (800 loc) · 30.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
--[[
Claude Code Protocol Handler for diffusion.nvim
Implements MCP (Model Context Protocol) over WebSocket for Claude Code integration.
This is a thin translation layer that delegates all business logic to core services.
Step 36 Complete: Now uses MessageService for provider-agnostic MCP message processing.
All MCP message handling delegated to MessageService. Handler only manages:
- WebSocket connection management
- Claude authentication and discovery (lock files)
- Deferred operations (openDiff blocking)
Provider-specific responsibilities:
- WebSocket connection management
- MCP message format translation
- Claude authentication and discovery
- 0-based line number conversion
Target size: 300-400 lines (ultra-slim handler pattern)
--]]
-- Claude Code protocol handler for diffusion.nvim
-- Implements MCP (Model Context Protocol) over WebSocket following claudecode.nvim pattern
local ClaudeHandler = {}
-- Load modules
local UIService = require('diffusion.services.ui')
local TmuxService = require('diffusion.services.tmux')
local MessageService = require('diffusion.services.messages')
local tools = require('diffusion.protocol.mcp.tools')
local diff = require('diffusion.protocol.claude.diff')
local messages = require('diffusion.protocol.mcp.messages')
local selection = require('diffusion.protocol.mcp.selection')
local diff_events = require('diffusion.protocol.mcp.diff_events')
-- Load schemas from external files
local tool_schemas = require('diffusion.schemas.mcp.tools')
local tool_descriptions = require('diffusion.schemas.mcp.descriptions')
function ClaudeHandler:new(config, events, diff_manager, provider_lock)
-- Initialize provider-agnostic services
local ToolService = require('diffusion.services.tools')
local WorkspaceService = require('diffusion.services.workspace')
local DiscoveryService = require('diffusion.services.discovery')
local tool_service = ToolService:new({ events = events })
local workspace_service = WorkspaceService:new()
local discovery_service = DiscoveryService:new({ provider = 'claude' })
local logger = require('diffusion.utils.logger'):child("Claude")
-- Create MessageService for provider-agnostic MCP message processing
local message_service = MessageService:new({
tool_service = tool_service,
tool_schemas = tool_schemas,
tool_descriptions = tool_descriptions,
config = config,
logger = logger:child("Messages")
})
local instance = {
_config = config,
_events = events,
_logger = logger,
_server = nil,
_port = nil,
_auth_token = nil,
_running = false,
_connected = false,
_connection_time = nil,
_tools = nil, -- Legacy: kept for backwards compatibility, use _message_service._tools
_message_service = message_service, -- Provider-agnostic MCP message processing
_diff_manager = diff_manager,
_provider_lock = provider_lock, -- Cross-handler "first connection wins" mutex
_tool_service = tool_service, -- Provider-agnostic tool service
_workspace_service = workspace_service, -- Provider-agnostic workspace service
_discovery_service = discovery_service, -- Provider-agnostic discovery service
_tmux_service = TmuxService:new(config),
_tmux_same_window = false, -- Cached; updated on connect, not on every get_status()
_ui = UIService:new({ events = events, provider = 'claude', logger = require('diffusion.utils.logger') }),
_claude_client_pid = nil, -- Cached PID of connected Claude client
_event_subscriptions = {}, -- Selection MCP module writes here ({event,handler} pairs)
_event_unsubs = {}, -- Diff lifecycle (shared mcp/diff_events) writes unsub fns here
-- Selection change debounce: reuse one table, fire after cursor settles
_selection_msg = { jsonrpc = "2.0", method = "selection_changed", params = {} },
_selection_timer = nil,
_selection_data = nil,
_stats = {
selections_sent = 0,
tools_called = 0,
messages_received = 0
}
}
setmetatable(instance, { __index = self })
return instance
end
-- Module-level cache for is_available() — file I/O + process check is expensive.
-- 5s TTL balances freshness vs cost. TTL is the only mechanism here (no events)
-- because availability depends on external Claude processes, not our own state.
local _availability_cache = { value = nil, timestamp = 0, ttl = 5 }
-- Simple availability check based on existing lockfiles or environment
function ClaudeHandler:is_available()
local now = os.time()
if _availability_cache.value ~= nil and
(now - _availability_cache.timestamp) < _availability_cache.ttl then
return _availability_cache.value
end
local result
-- Check environment variables first (if Claude was launched from another IDE)
local env_port = vim.env.CLAUDE_CODE_SSE_PORT
local env_enabled = vim.env.ENABLE_IDE_INTEGRATION
if env_port and env_enabled == "true" then
result = true
_availability_cache.value = result
_availability_cache.timestamp = now
return result
end
-- Check for existing valid Claude lockfiles matching current workspace
local DiscoveryService = require('diffusion.services.discovery')
local discovery_service = DiscoveryService:new({ provider = 'claude' })
local lock_dir = discovery_service:get_lock_dir()
if vim.fn.isdirectory(lock_dir) == 1 then
local lock_files = vim.fn.glob(lock_dir .. "/*.lock", false, true)
if #lock_files > 0 then
local utils = require('diffusion.utils')
local current_cwd = vim.fn.getcwd()
for _, lock_file in ipairs(lock_files) do
-- Check if lockfile is valid by reading and checking PID
local file = io.open(lock_file, "r")
if file then
local content = file:read("*all")
file:close()
if content and content ~= "" then
local ok, lock_data = pcall(vim.json.decode, content)
if ok and type(lock_data) == "table" and lock_data.pid then
-- Only check alive processes (dead lock files are ignored)
if utils.is_process_alive(lock_data.pid) then
-- Check if this lock file matches the current workspace
-- Lock files use camelCase: workspaceFolders
local workspace_folders = lock_data.workspaceFolders or lock_data.workspace_folders
if workspace_folders and type(workspace_folders) == "table" then
for _, folder in ipairs(workspace_folders) do
-- Check if current CWD is within this workspace folder
if current_cwd:find(folder, 1, true) == 1 then
_availability_cache.value = true
_availability_cache.timestamp = now
return true
end
end
end
end
end
end
end
end
end
end
-- No matching Claude workspace found - allow fallback to OpenCode
_availability_cache.value = false
_availability_cache.timestamp = now
return false
end
-- Start the Claude handler
function ClaudeHandler:start()
if self._running then
self._logger:warn("Claude handler already running", { port = self._port })
return false, "Already running"
end
self._logger:info("Starting Claude handler (hybrid simplified)")
-- Generate auth token
self._auth_token = self._discovery_service:generate_auth_token()
-- Find available port
local utils = require('diffusion.utils')
self._port = utils.find_available_port(10000, 65535)
if not self._port then
return false, "No available ports in range 10000-65535"
end
-- Set environment variables for Claude discovery
vim.env.CLAUDE_CODE_SSE_PORT = tostring(self._port)
vim.env.ENABLE_IDE_INTEGRATION = "true"
-- Start WebSocket server directly
local WebSocketServer = require('diffusion.server.websocket_server')
self._server = WebSocketServer:new(self._config.server or {}, self._events)
-- Wire provider mutex: rejects handshakes when another protocol owns the
-- slot. Server releases automatically on disconnect.
if self._provider_lock then
self._server:set_provider_mutex({
acquire = function() return self._provider_lock:try_acquire("claude") end,
release = function() self._provider_lock:release("claude") end,
})
end
-- Set up connection status callbacks
self._server:on_client_connected(function()
self._connected = true
self._connection_time = os.time()
self._logger:info("Claude connected!", { port = self._port })
-- Notify the event bus immediately so lualine and other listeners update without delay
self._events:emit("client:connected", { protocol = "claude", port = self._port })
-- Cache tmux window state once on connect rather than on every get_status() call
self._tmux_same_window = self:is_same_tmux_window()
-- Clean up stale deferred responses from previous connections
-- This prevents orphaned state from interfering with new tool calls
if self._diff_manager then
local stale = self._diff_manager:get_all_deferred_responses("claude")
local stale_count = vim.tbl_count(stale)
if stale_count > 0 then
self._logger:warn("Clearing stale deferred responses from previous connection", {
count = stale_count
})
for diff_id, _ in pairs(stale) do
self._diff_manager:clear_deferred_response(diff_id)
end
end
end
vim.notify("Claude Code connected on port " .. self._port, vim.log.levels.INFO, {
title = "diffusion.nvim"
})
end)
self._server:on_client_disconnected(function(client, reason)
self._connected = false
self._events:emit("client:disconnected", { protocol = "claude", port = self._port, reason = reason })
self._logger:info("Claude disconnected", {
port = self._port,
reason = reason,
client_id = client and client.id
})
-- Clean up all pending deferred responses for this connection.
-- Without this, Claude's MCP client never receives its openDiff response,
-- causing it to enter a degraded state where it stops calling diff tools.
if self._diff_manager then
local pending = self._diff_manager:get_all_deferred_responses("claude")
local pending_count = vim.tbl_count(pending)
if pending_count > 0 then
self._logger:warn("Cleaning up orphaned deferred responses after disconnect", {
count = pending_count,
reason = reason
})
for diff_id, _ in pairs(pending) do
self._diff_manager:clear_deferred_response(diff_id)
-- Also clean up the active diff entry if it exists
if self._diff_manager._active_diffs and self._diff_manager._active_diffs[diff_id] then
self._diff_manager._active_diffs[diff_id] = nil
self._diff_manager._stats.concurrent_diffs = math.max(0, self._diff_manager._stats.concurrent_diffs - 1)
end
end
end
end
end)
-- Start the server
local success, error_msg = self._server:start(self._port, self._auth_token)
if not success then
self._logger:error("Failed to start WebSocket server", { error = error_msg })
return false, error_msg
end
-- Clean up orphaned lockfiles BEFORE creating ours, so Claude doesn't
-- connect to a stale port from a dead Neovim process.
local lock_dir = self._discovery_service:get_lock_dir()
vim.fn.mkdir(lock_dir, 'p')
local existing_locks = vim.fn.glob(lock_dir .. "/*.lock", false, true)
local utils = require('diffusion.utils')
for _, lf in ipairs(existing_locks) do
local f = io.open(lf, "r")
if f then
local content = f:read("*all")
f:close()
if content and content ~= "" then
local ok, data = pcall(vim.json.decode, content)
if ok and data.pid and not utils.is_process_alive(data.pid) then
os.remove(lf)
self._logger:debug("Cleaned up orphaned lockfile", { path = lf, pid = data.pid })
end
end
end
end
-- Create lockfile
local lock_path = lock_dir .. "/" .. self._port .. ".lock"
local lock_content = {
pid = vim.fn.getpid(),
port = self._port, -- Critical: Claude Code needs this to know which port to connect to
workspaceFolders = self._discovery_service:get_workspace_folders(),
ideName = "Neovim",
transport = "ws",
authToken = self._auth_token,
}
local json = vim.json.encode(lock_content)
local file = io.open(lock_path, 'w')
if file then
file:write(json)
file:close()
self._logger:info("Created lockfile", { path = lock_path })
else
self._logger:warn("Failed to create lockfile - continuing anyway")
end
-- Fallback auto-reconnect: if Claude doesn't connect on its own within
-- 500ms, send /ide to its tmux pane. This covers two scenarios:
-- 1. Neovim restarted while Claude is still running (Claude only
-- auto-connects on its own startup, not when new lockfiles appear)
-- 2. Multiple diffusion sessions for the same project (Claude doesn't
-- know which to connect to, so it connects to none)
-- Checks server client count directly (not self._connected which depends
-- on vim.schedule ordering).
local tmux_cfg = self._config.tmux or {}
if tmux_cfg.auto_reconnect then
vim.defer_fn(function()
-- Check for authenticated, handshake-completed clients only
local connected_clients = 0
if self._server and self._server._clients then
for _, client in pairs(self._server._clients) do
if client.state == "connected" then
connected_clients = connected_clients + 1
end
end
end
if connected_clients > 0 then
self._logger:info("Auto-reconnect skipped — Claude already connected")
else
self._logger:info("Claude did not auto-connect, sending /ide as fallback")
self:_trigger_claude_auto_reconnection()
end
end, 1000)
end
-- Initialize tools
self:_init_tools()
-- Setup message handlers
self:_setup_message_handlers()
-- Subscribe to selection_changed via shared MCP module
selection._setup_selection_notifications(self)
-- Wire diff lifecycle subscriptions through the shared MCP helper. Each
-- callback filters by `data.protocol == "claude"` so events for other
-- providers are ignored cheaply.
diff_events.setup(self, { protocol = "claude" })
-- Subscribe to selection change events
local selection_handler = function(data)
self:_handle_selection_change(data)
end
self._events:on('ui:selection_changed', selection_handler)
table.insert(self._event_subscriptions, {
event = 'ui:selection_changed',
handler = selection_handler
})
self._logger:info("Subscribed to ui:selection_changed events")
self._running = true
self._logger:info("Claude handler started", {
port = self._port,
pid = vim.fn.getpid()
})
return true, self._port
end
-- Stop the Claude handler
function ClaudeHandler:stop()
if not self._running then
return true, nil
end
self._logger:info("Stopping Claude handler")
-- Clean up event subscriptions (selection module uses {event,handler} pairs;
-- shared diff_events helper stores unsub functions in _event_unsubs).
for _, sub in ipairs(self._event_subscriptions) do
self._events:off(sub.event, sub.handler)
end
self._event_subscriptions = {}
for _, unsub in ipairs(self._event_unsubs) do
pcall(unsub)
end
self._event_unsubs = {}
self._logger:debug("Cleaned up event subscriptions")
if self._server then
self._server:stop()
end
-- Remove lockfile
if self._port then
local lock_path = self._discovery_service:get_lock_dir() .. "/" .. self._port .. ".lock"
if vim.fn.filereadable(lock_path) == 1 then
os.remove(lock_path)
self._logger:info("Removed lockfile", { path = lock_path })
end
end
-- Clean up any orphaned lock files (dead processes)
local lock_dir = self._discovery_service:get_lock_dir()
if vim.fn.isdirectory(lock_dir) == 1 then
local lock_files = vim.fn.glob(lock_dir .. "/*.lock", false, true)
local utils = require('diffusion.utils')
for _, lock_file in ipairs(lock_files) do
local file = io.open(lock_file, "r")
if file then
local content = file:read("*all")
file:close()
if content and content ~= "" then
local ok, lock_data = pcall(vim.json.decode, content)
if ok and lock_data.pid and not utils.is_process_alive(lock_data.pid) then
os.remove(lock_file)
self._logger:debug("Cleaned up orphaned lockfile", { path = lock_file, pid = lock_data.pid })
end
end
end
end
end
self._running = false
self._connected = false
self._connection_time = nil
-- Cancel any pending selection debounce timer
if self._selection_timer then
self._selection_timer:stop()
self._selection_timer:close()
self._selection_timer = nil
end
self._logger:info("Claude handler stopped")
return true, nil
end
-- Send selection to Claude
function ClaudeHandler:send_selection(selection_data)
if not self._server or not self._server:is_running() then
self._logger:error("WebSocket server not running")
return false
end
-- Delegate to shared MCP selection module to broadcast selection_changed
local ok = pcall(function()
require('diffusion.protocol.mcp.selection')._send_selection_notification(self, selection_data)
end)
if ok then
self._stats.selections_sent = self._stats.selections_sent + 1
return true
end
return false
end
-- Send at-mention notification to Claude (explicit user action)
function ClaudeHandler:send_at_mention(file_path, start_line, end_line)
-- Validate server and clients
if not self._server then
self._logger:error("WebSocket server not initialized")
return false, "No server available"
end
if not self._server:has_clients() then
self._logger:error("No clients connected")
return false, "No clients connected"
end
-- Convert to 0-based line numbers (Claude requirement)
local at_mentioned_message = {
jsonrpc = "2.0",
method = "at_mentioned",
params = {
filePath = file_path,
lineStart = start_line - 1,
lineEnd = end_line - 1,
}
}
self._logger:info("Sending at_mentioned to Claude", {
file = file_path,
lines = string.format("%d-%d", start_line, end_line)
})
-- Broadcast via WebSocket
local success = self._server:broadcast_message(at_mentioned_message)
if not success then
self._logger:error("Failed to broadcast at_mentioned message")
return false, "Broadcast failed"
end
-- Handle tmux pane focusing if configured (async to avoid blocking UI)
if self._config.tmux and self._config.tmux.focus_after_send and vim.env.TMUX then
self._logger:debug("Focusing tmux pane +1")
-- Use vim.loop.spawn for non-blocking tmux call
vim.loop.spawn("tmux", {
args = { "select-pane", "-t", "+1" },
}, function() end)
end
self._logger:info("Successfully sent at_mentioned notification")
return true, nil
end
-- Send message to Claude (selection change notification)
-- Uses async chaining to avoid blocking the UI thread
function ClaudeHandler:send_message(message, callback)
-- Delegate to TmuxService for all tmux operations
if not vim.env.TMUX then
self._logger:debug("Not in tmux environment, cannot send message")
if callback then callback(false, "Not in tmux environment") end
return false, "Not in tmux environment"
end
self._logger:info("Sending message to neighboring pane (+1): " .. message)
-- Clear any existing input with Ctrl-C
local cleared = self._tmux_service:send_to_pane("+1", "C-c")
if not cleared then
if callback then callback(false, "Failed to clear pane") end
return false, "Failed to clear pane"
end
-- Chain operations asynchronously to avoid blocking UI
vim.defer_fn(function()
-- Send the text
local sent = self._tmux_service:send_to_pane("+1", message)
if not sent then
self._logger:error("Failed to send message text")
if callback then callback(false, "Failed to send message") end
return
end
vim.defer_fn(function()
-- Send Enter to submit
local submitted = self._tmux_service:send_to_pane("+1", "Enter")
if not submitted then
self._logger:error("Failed to submit message")
if callback then callback(false, "Failed to submit message") end
return
end
self._logger:info("Message sent successfully to +1 pane via TmuxService")
if callback then callback(true, nil) end
end, 100)
end, 50)
-- Return immediately - actual result delivered via callback
return true, nil
end
-- Handle diff opening (this will be called by tools)
function ClaudeHandler:open_diff(diff_params)
-- This method will be called by the openDiff MCP tool
return self._diff_manager:show_diff(diff_params)
end
-- Check connection status
function ClaudeHandler:is_connected()
return self._connected and self._server and self._server:is_running()
end
-- Get PID of Claude process connected to our server port
-- Uses cached value or async lookup to avoid blocking
function ClaudeHandler:_get_connected_claude_pid()
if not self._port then
return nil
end
-- Return cached PID if available and process is still alive
if self._claude_client_pid then
-- Fast process check using os.execute (doesn't block like io.popen)
local result = os.execute("kill -0 " .. self._claude_client_pid .. " 2>/dev/null")
local is_alive = (type(result) == "number" and result == 0) or (type(result) == "boolean" and result)
if is_alive then
return self._claude_client_pid
end
self._claude_client_pid = nil
end
-- For non-cached lookup, use vim.system with timeout if available
local cmd = string.format(
"lsof -iTCP:%d -n -P 2>/dev/null | grep -v LISTEN | grep -v nvim | awk 'NR==2 {print $2}'",
self._port
)
local output
if vim.system then
-- Non-blocking with timeout (Neovim 0.10+)
local result = vim.system({ "sh", "-c", cmd }, { timeout = 1000 }):wait()
output = result.stdout or ""
else
-- Fallback - still blocking but we keep it for compatibility
local handle = io.popen(cmd)
if not handle then
return nil
end
output = handle:read("*a")
handle:close()
end
local pid = tonumber(output:match("^%s*(%d+)"))
if pid then
self._claude_client_pid = pid -- Cache it
end
return pid
end
-- Check if Claude is in the same tmux window as Neovim
function ClaudeHandler:is_same_tmux_window()
if not vim.env.TMUX then
return false
end
-- Use TmuxService to find Claude pane
local claude_pane = self._tmux_service:find_claude_pane()
if not claude_pane then
return false
end
-- Check if Claude pane is in same window using TmuxService
return self._tmux_service:is_same_window(claude_pane)
end
-- Get detailed status
function ClaudeHandler:get_status()
-- Calculate client count
local clients = 0
if self._server and self._server.get_client_count then
clients = self._server:get_client_count()
elseif self._server and self._server.has_clients then
clients = self._server:has_clients() and 1 or 0
end
-- Calculate uptime
local uptime = nil
if self._connection_time then
uptime = os.time() - self._connection_time
end
-- Get lock file path
local lock_file = nil
if self._port then
lock_file = self._discovery_service:get_lock_dir() .. "/" .. self._port .. ".lock"
end
local status = {
-- Required interface fields
available = self:is_available(),
connected = self:is_connected(),
-- Recommended: Server connection information
server_info = {
host = "127.0.0.1",
port = self._port,
protocol = "websocket",
has_clients = clients > 0,
client_count = clients,
},
-- Recommended: Workspace information
workspace_info = {
path = vim.fn.getcwd(),
lock_file = lock_file,
},
-- Recommended: Usage statistics
stats = {
messages_sent = self._stats.messages_sent or 0,
selections_sent = self._stats.selections_sent or 0,
connections_total = self._stats.connections or 0,
uptime = uptime,
},
-- Recommended: Configuration
config = {
enabled = self._config.enabled,
tmux = self._config.tmux,
},
-- Claude-specific fields
running = self._running,
tmux = {
in_tmux = vim.env.TMUX ~= nil,
same_window = self._tmux_same_window, -- Cached on connect; avoids shell spawns per status query
}
}
return status
end
-- Initialize tools
function ClaudeHandler:_init_tools()
return tools._init_tools(self)
end
-- Tool handlers - most are now delegated directly from claude/tools.lua to ToolService
-- Only diff-related handlers remain here due to protocol-specific blocking behavior
-- Handle openDiff tool call (should not be called directly - openDiff is handled specially)
function ClaudeHandler:_handle_open_diff(args)
return diff._handle_open_diff(self, args)
end
-- Handle openDiff in a deferred way (non-blocking but waits for response)
function ClaudeHandler:_handle_open_diff_deferred(request_info)
return diff._handle_open_diff_deferred(self, request_info)
end
-- Handle closeAllDiffTabs tool call
-- closeAllDiffTabs handled in diff module
-- Dismiss diff instantly - delegate to DiffManager
function ClaudeHandler:_dismiss_diff_instantly(args)
self._logger:info("🚀 INSTANT DIFF DISMISSAL - Delegating to DiffManager")
-- Delegate to DiffManager which handles all buffer cleanup logic
local success = self._diff_manager:cleanup_all()
if success then
self._logger:info("✅ INSTANT DISMISSAL COMPLETED via DiffManager")
return {
success = true,
message = "All diffs dismissed"
}
else
self._logger:warn("❌ INSTANT DISMISSAL FAILED")
return {
success = false,
message = "Failed to dismiss diffs"
}
end
end
-- close_tab handled in diff module
-- Handle acceptDiff tool call
function ClaudeHandler:_handle_accept_diff(args)
local diff_id = args.diff_id
self._logger:info("Handling acceptDiff tool call", { diff_id = diff_id })
if not diff_id then
return {
content = {{
type = "text",
text = "Error: diff_id is required"
}}
}
end
-- Delegate to DiffManager for proper diff handling
local success = self._diff_manager:dismiss_diff(diff_id, { reason = 'accepted' })
return {
content = {{
type = "text",
text = success and "FILE_SAVED" or "ERROR"
}}
}
end
-- Handle rejectDiff tool call
function ClaudeHandler:_handle_reject_diff(args)
local diff_id = args.diff_id
self._logger:info("Handling rejectDiff tool call", { diff_id = diff_id })
if not diff_id then
return {
content = {{
type = "text",
text = "Error: diff_id is required"
}}
}
end
-- Delegate to DiffManager for proper diff handling
local success = self._diff_manager:dismiss_diff(diff_id, { reason = 'rejected' })
return {
content = {{
type = "text",
text = success and "DIFF_REJECTED" or "ERROR"
}}
}
end
-- Handle showDiff tool call (alias for openDiff)
function ClaudeHandler:_handle_show_diff(args)
return diff._handle_show_diff(self, args)
end
-- Handle dismissDiff tool call
function ClaudeHandler:_handle_dismiss_diff(args)
return diff._handle_dismiss_diff(self, args)
end
-- Handle closeAllDiffTabs tool call
function ClaudeHandler:_handle_close_all_diffs(args)
return diff._handle_close_all_diffs(self, args)
end
-- Handle close_tab tool call
function ClaudeHandler:_handle_close_tab(args)
return diff._handle_close_tab(self, args)
end
-- Delegate to tools module
function ClaudeHandler:_handle_open_file(args)
return tools._handle_open_file(self, args)
end
function ClaudeHandler:_handle_get_selection(args)
return tools._handle_get_selection(self, args)
end
function ClaudeHandler:_handle_save_document(args)
return tools._handle_save_document(self, args)
end
function ClaudeHandler:_handle_get_diagnostics(args)
return tools._handle_get_diagnostics(self, args)
end
function ClaudeHandler:_handle_get_open_editors(args)
return tools._handle_get_open_editors(self, args)
end
function ClaudeHandler:_handle_get_workspace_folders(args)
return tools._handle_get_workspace_folders(self, args)
end
function ClaudeHandler:_handle_check_document_dirty(args)
return tools._handle_check_document_dirty(self, args)
end
-- Translate selection data to MCP format
-- Selection translation/sending handled in events module
-- Setup message handlers
function ClaudeHandler:_setup_message_handlers()
return messages._setup_message_handlers(self)
end
-- Send selection change notification to Claude Code
-- Selection translation/sending handled in events module
-- Handle selection change events from UI layer
function ClaudeHandler:_handle_selection_change(data)
if not self._server or not self._server:has_clients() then return end
-- Cancel any previous pending send (cursor is still moving)
if self._selection_timer then
self._selection_timer:stop()
self._selection_timer:close()
self._selection_timer = nil
end
-- Store latest data and wait for cursor to settle (50ms)
self._selection_data = data
self._selection_timer = vim.loop.new_timer()
self._selection_timer:start(50, 0, vim.schedule_wrap(function()
self._selection_timer = nil
if not self._server or not self._server:has_clients() then return end
-- Mutate pre-allocated table rather than allocating a new one each call
self._selection_msg.params = self._selection_data
local success = self._server:broadcast_message(self._selection_msg)
if success then
self._stats.selections_sent = self._stats.selections_sent + 1
local d = self._selection_data
self._logger:debug("Sent selection_changed notification to Claude", {
file = d.file_path,
lines = d.line_start and d.line_end and string.format("%d-%d", d.line_start, d.line_end) or "cursor"
})
else
self._logger:warn("Failed to send selection_changed notification")
end
end))
end
-- Handle diff user response events
-- Diff event handlers are handled by services/events.lua and protocol/claude/diff.lua
-- Handle incoming WebSocket messages
-- Message handlers are provided by protocol/claude/messages.lua
-- Get tool description
function ClaudeHandler:_get_tool_description(tool_name)
return tools._get_tool_description(self, tool_name)
end
-- Get tool schema
function ClaudeHandler:_get_tool_schema(tool_name)
return tools._get_tool_schema(self, tool_name)
end
-- Trigger Claude Code auto-reconnection by sending /ide command
function ClaudeHandler:_trigger_claude_auto_reconnection()
-- Delegate to TmuxService for auto-reconnection logic
return self._tmux_service:trigger_auto_reconnection(self._config, self._port)
end
-- Immersive Mode: Stream Claude tmux content to split buffer (proof of concept)
function ClaudeHandler:toggle_immersive_mode()
return self._ui:toggle_immersive()
end
function ClaudeHandler:_start_immersive_mode()
return self._ui:start_immersive()
end
function ClaudeHandler:_stop_immersive_mode()
return self._ui:stop_immersive()
end
-- Private method to get pending diffs from this handler's diff manager
function ClaudeHandler:_get_pending_diffs()
return diff._get_pending_diffs(self)
end
return ClaudeHandler