claude-code.nvim icon indicating copy to clipboard operation
claude-code.nvim copied to clipboard

TermClose callback crashes with 'Invalid buffer id' when closing terminal with Ctrl+D

Open daniel-san-pedro opened this issue 7 months ago • 1 comments

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

  1. Open Neovim
  2. Open any terminal in a split (:sp | te or :vs | te)
  3. Press Ctrl+D to 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

daniel-san-pedro avatar Apr 30 '26 17:04 daniel-san-pedro

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:

  1. Ctrl+D sends EOF to shell
  2. Terminal buffer is deleted by Neovim
  3. TermClose autocommand fires with now-invalid buffer reference
  4. nvim_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.

daveCode-dot avatar May 14 '26 03:05 daveCode-dot