From 43b5a817712b35e2e412f5c53b1cd56800d7aa91 Mon Sep 17 00:00:00 2001 From: NicolasGB Date: Thu, 11 Dec 2025 16:59:52 +1100 Subject: [PATCH] fix: prevent invalid buffer access in terminal on_exit callbacks When closing a terminal buffer (floating or regular), a race condition could occur where the BufWipeout/BufDelete autocmd clears the buffer reference, but the job's on_exit handler later tries to operate on it via vim.schedule. This caused 'Invalid buffer' errors. Add validity checks in both floating and regular buffer on_exit handlers to safely handle the case where the buffer has already been cleaned up. --- lua/jj/ui/terminal.lua | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/lua/jj/ui/terminal.lua b/lua/jj/ui/terminal.lua index 6ae896d..b064618 100644 --- a/lua/jj/ui/terminal.lua +++ b/lua/jj/ui/terminal.lua @@ -179,8 +179,10 @@ function M.run_floating(cmd, keymaps) end, on_exit = function(_, _) --[[ exit_code ]] vim.schedule(function() - buffer.set_modifiable(state.floating_buf, false) - buffer.stop_insert(state.floating_buf) + if state.floating_buf and vim.api.nvim_buf_is_valid(state.floating_buf) then + buffer.set_modifiable(state.floating_buf, false) + buffer.stop_insert(state.floating_buf) + end end) end, }) @@ -309,6 +311,10 @@ function M.run(cmd, keymaps) end, on_exit = function(_, exit_code) vim.schedule(function() + -- Check buffer still exists (it might have been closed) + if not state.buf or not vim.api.nvim_buf_is_valid(state.buf) then + return + end -- Store the subcommand on successful exit if exit_code == 0 then state.buf_cmd = cmd[2] or nil