TermClose callback crashes with 'Invalid buffer id' when closing terminal with Ctrl+D
Description
When closing a terminal pane with Ctrl+D (sending EOF to the shell), the TermClose autocommand in file_refresh.lua crashes because the buffer is already invalid by the time the callback fires.
Error
Error in TermClose Autocommands for "*":
Lua callback: ...m/lazy/claude-code.nvim/lua/claude-code/file_refresh.lua:104: Invalid buffer id: 7
stack traceback:
[C]: in function 'nvim_buf_get_name'
...m/lazy/claude-code.nvim/lua/claude-code/file_refresh.lua:104: in function <...m/lazy/claude-code.nvim/lua/claude-code/file_refresh.lua:103>
Steps to Reproduce
- Open Neovim
- Open any terminal in a split (
:sp | teor:vs | te) - Press
Ctrl+Dto close the terminal shell
Suggested Fix
Add a buffer validity check before calling nvim_buf_get_name in the TermClose callback:
callback = function(args)
if not vim.api.nvim_buf_is_valid(args.buf) then
return
end
local buf_name = vim.api.nvim_buf_get_name(args.buf)
-- ...
end
https://github.com/greggh/claude-code.nvim/blob/main/lua/claude-code/file_refresh.lua#L103-L104
Environment
- Neovim: v0.10+
- Plugin version: latest (via lazy.nvim)
- OS: macOS
Thanks for the detailed repro steps and suggested fix. I can confirm this issue reproduces reliably on Neovim 0.10+ when using Ctrl+D to close a terminal pane.
The root cause is that the TermClose autocommand fires after the buffer is already deleted, so nvim_buf_get_name(args.buf) fails with "Invalid buffer id". The suggested fix is correct — a guard clause with vim.api.nvim_buf_is_valid(args.buf) before the get_name call will prevent the crash.
Looking at the code flow in file_refresh.lua:104, the sequence is:
Ctrl+Dsends EOF to shell- Terminal buffer is deleted by Neovim
TermCloseautocommand fires with now-invalid buffer referencenvim_buf_get_name(args.buf)throws because buffer no longer exists
A secondary consideration: after adding the validity check, you may also want to check vim.api.nvim_buf_is_loaded(args.buf) to handle edge cases where the buffer exists but isn't fully initialized.