Skip to content

Commit 946936f

Browse files
committed
fix(opencode): add cwd-scoped process kill on exit for Linux/macOS
OpenCode (Bun/TS) ignores SIGHUP which Neovim sends on terminal buffer delete. The built-in stop() closes the buffer but the process survives as an orphan on Unix. Add explicit SIGTERM/SIGKILL safety net that matches processes by cwd to only kill opencode for the current project. Refs: anomalyco/opencode#14504, anomalyco/opencode#12767
1 parent 9c09fad commit 946936f

1 file changed

Lines changed: 39 additions & 4 deletions

File tree

‎nvim/lua/nairovim/plugins/ai/opencode.lua‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,15 +81,50 @@ return {
8181
common_utils.map(mappings)
8282

8383
----------------------------------------------------------------------
84-
-- Auto-cleanup OpenCode server process on exit
84+
-- Auto-cleanup OpenCode server processes on exit
8585
----------------------------------------------------------------------
86-
-- Simply call the configured stop() function when Neovim exits.
87-
-- This leverages the built-in server lifecycle management.
88-
86+
-- OpenCode (Bun/TS) ignores SIGHUP, which is what Neovim sends when
87+
-- a terminal buffer is deleted. The built-in stop() alone is
88+
-- insufficient on Linux/macOS — the process survives as an orphan.
89+
-- On Windows, Neovim uses TerminateProcess() so stop() works fine.
90+
-- See: https://github.com/anomalyco/opencode/issues/14504
91+
-- https://github.com/anomalyco/opencode/issues/12767
92+
8993
vim.api.nvim_create_autocmd("VimLeavePre", {
9094
group = vim.api.nvim_create_augroup("OpenCodeCleanup", { clear = true }),
9195
callback = function()
96+
-- Graceful: close the Snacks terminal buffer
9297
pcall(require("opencode").stop)
98+
99+
-- Safety net: explicitly kill processes for this project
100+
if vim.fn.has("unix") == 1 then
101+
local cwd = vim.fn.getcwd()
102+
local pids = vim.fn.systemlist("pgrep -f 'opencode --port' 2>/dev/null")
103+
104+
for _, pid in ipairs(pids) do
105+
pid = vim.trim(pid)
106+
if pid ~= "" then
107+
local proc_cwd = ""
108+
if vim.fn.has("linux") == 1 then
109+
proc_cwd = vim.trim(vim.fn.system(
110+
string.format("readlink /proc/%s/cwd 2>/dev/null", pid)
111+
))
112+
elseif vim.fn.has("mac") == 1 then
113+
proc_cwd = vim.trim(vim.fn.system(
114+
string.format("lsof -a -p %s -d cwd -Fn 2>/dev/null | grep '^n' | cut -c2-", pid)
115+
))
116+
end
117+
118+
if proc_cwd == cwd then
119+
-- Negative PID kills the entire process group (child LSPs too)
120+
vim.fn.system(string.format("kill -15 -%s 2>/dev/null", pid))
121+
vim.defer_fn(function()
122+
vim.fn.system(string.format("kill -9 -%s 2>/dev/null", pid))
123+
end, 500)
124+
end
125+
end
126+
end
127+
end
93128
end,
94129
})
95130
end,

0 commit comments

Comments
 (0)