Skip to content

fix(diff): keep terminal focus for floating terminals - #178

Merged
ThomasK33 merged 1 commit into
mainfrom
fix/keep-terminal-focus-floating
Jan 26, 2026
Merged

ThomasK33 merged 1 commit into
mainfrom
fix/keep-terminal-focus-floating

Conversation

@ThomasK33

Copy link
Copy Markdown
Member

Fixes #150.

When diff_opts.keep_terminal_focus = true and the Claude terminal is a floating window (e.g. Snacks position="float"), opening a diff no longer steals focus to the hidden diff split.

Changes

  • Allow find_claudecode_terminal_window() to fall back to floating windows (still preferring split terminals)
  • Avoid resizing floating terminals when restoring terminal widths
  • Add a unit regression test for floating-terminal focus

Tests

  • make check
  • make test

📋 Implementation Plan

Plan: Investigate + fix #150 (keep_terminal_focus skips floating terminal windows)

Context / Why

Issue #150 reports that when diff_opts.keep_terminal_focus = true and the Claude terminal is displayed as a floating window (e.g. via Snacks snacks_win_opts = { position = "float" }), opening a diff steals focus to the diff split behind the float. Because focus never returns to the terminal, user input goes to the hidden diff window and the UX breaks.

Goal: confirm whether this is a bug (vs expected behavior) and, if so, outline a safe fix + regression coverage.

Evidence (what was verified)

  • GitHub issue [BUG] keep_terminal_focus = true skips floating windows #150 text explicitly points to find_claudecode_terminal_window() in lua/claudecode/diff.lua as skipping floats.
  • lua/claudecode/diff.lua:
    • find_claudecode_terminal_window() currently returns the terminal window only if it is not floating (checks win_config.relative).
    • setup_new_buffer() uses this helper under diff_opts.keep_terminal_focus to restore focus after opening a diff.
  • Config intent: lua/claudecode/config.lua documents diff_opts.keep_terminal_focus as “moves focus back to terminal after diff opens”, with no caveat about floating windows.

Bug assessment

Confirmed bug.

With keep_terminal_focus = true, the plugin intends to refocus the Claude terminal after creating the diff window. When the terminal lives in a floating window, find_claudecode_terminal_window() returns nil, so the scheduled refocus never happens. This matches the issue report and is inconsistent with the documented meaning of keep_terminal_focus.

Implementation plan (fix + prove)

1) Add a regression test that fails on current main

Add a unit test that simulates a floating terminal window:

  • Test location: add to an existing diff blocking spec (e.g. tests/unit/diff_mcp_spec.lua) or create a focused new spec (e.g. tests/unit/diff_keep_terminal_focus_float_spec.lua).
  • Arrange:
    • diff.setup({ diff_opts = { keep_terminal_focus = true } }).
    • Stub package.loaded["claudecode.terminal"] = { get_active_terminal_bufnr = function() return TERM_BUF end }.
    • Create a terminal buffer in the vim mock (vim.api.nvim_create_buf) and a floating window entry for it by setting vim._windows[TERM_WIN].config = { relative = "editor" } and ensuring TERM_WIN is in vim._tab_windows[current_tab].
  • Act: call diff.open_diff_blocking(...) inside a coroutine and coroutine.resume once (it should suspend after setup).
  • Assert: after the first resume, vim.api.nvim_get_current_win() (or vim._current_window) should equal TERM_WIN.
    • This fails today because the float is filtered out.

Optional: add a second assertion for the non-floating case to ensure we don’t regress existing behavior.

2) Fix find_claudecode_terminal_window() to support floats

In lua/claudecode/diff.lua, update the helper so that it can return floating windows:

  • Preferred behavior:
    • If multiple windows show the terminal buffer, prefer a non-floating window.
    • Otherwise, fall back to the floating window.

This preserves the original intent (prefer split terminals) while making keep_terminal_focus work for floats.

Fix sketch (for the implementer)
  • Iterate windows; when buf == terminal_bufnr:
    • If win_config.relative is empty/nil → return immediately.
    • Else store as floating_fallback.
  • After loop: return floating_fallback.

3) Ensure terminal-resize code remains sane for floats

find_claudecode_terminal_window() is also used in diff cleanup and terminal width restoration paths.

  • Decide whether resizing should apply to floats:
    • If yes: do nothing special (current width logic is “percentage of columns” and is valid for floats too).
    • If no: gate nvim_win_set_width calls behind win_config.relative == "".

Whichever behavior is chosen, add/adjust a test so the behavior is explicit.

4) Validate locally

  • Run: make test, make check.
  • Manual sanity check:
    • Configure Snacks terminal as float and diff_opts.keep_terminal_focus = true.
    • Trigger a diff (via Claude suggestion / openDiff tool).
    • Confirm focus stays/returns to the float terminal and typing goes to the terminal, not the hidden diff.

5) Close the loop on the issue


Generated with mux • Model: openai:gpt-5.2 • Thinking: xhigh

Fixes #150 by allowing terminal focus restoration when the Claude terminal is shown in a floating window (e.g. Snacks).

Adds a regression test and avoids resizing floating terminals when restoring widths.

Change-Id: I24229878842c383624e3e7e51ab7c7c5f02f3c60
Signed-off-by: Thomas Kosiewski <tk@coder.com>
@ThomasK33
ThomasK33 merged commit 8f521fb into main Jan 26, 2026
@ThomasK33
ThomasK33 deleted the fix/keep-terminal-focus-floating branch January 26, 2026 12:41
gogongxt pushed a commit to gogongxt/claudecode.nvim that referenced this pull request Jan 30, 2026
snirt pushed a commit to snirt/claudecode.nvim that referenced this pull request Mar 23, 2026
@github-actions github-actions Bot mentioned this pull request Jun 15, 2026
MichaelPachec0 added a commit to MichaelPachec0/claudecode.nvim that referenced this pull request Oct 28, 2026
coder#164

Resolved against upstream 0.4.0 plus integrated PRs. Stale copies of upstream
coder#163/coder#165/coder#175/coder#176/coder#178 resolve to upstream. coder#164's on_disconnect_cleanup hook
is dropped in favour of coder#317. Modules are now import-safe (no vim.api/vim.loop
access at require time) and coder#164's own failing specs are fixed. Terminal
features dropped by the restructure are re-ported in follow-up commits.

The manual cleanup scripts tests/integration/test_cleanup_real.lua and
tests/verify_cleanup.lua are kept, with headers giving their run commands.
29 upstream terminal specs are temporarily pending, tagged with the task that re-ports their feature.
hareki pushed a commit to hareki/claudecode.nvim that referenced this pull request Nov 10, 2026
The next claudecode.nvim release. Merging this PR creates the release
tag and GitHub Release, then starts Communique GitHub Release note
generation.
---


## [0.4.0] - 2026-11-09

### Added

- `:ClaudeCodeSendText {text}` command and
`require("claudecode.terminal").send_to_terminal(text, opts)` to send
arbitrary text to the open Claude terminal as if typed at the prompt
(submitting by default; `:ClaudeCodeSendText!` inserts without
submitting). Multi-line text is sent via bracketed paste. Works with the
in-editor `native`/`snacks` providers only.
([coder#197](coder#197),
[coder#272](coder#272))
- `:checkhealth claudecode` health check that verifies Neovim version,
`setup()`, the Claude CLI, terminal provider, WebSocket server, lock
file, and live connection state.
([coder#275](coder#275))
- `:ClaudeCodeCloseAllDiffs` command to close pending Claude diffs at
once. A diff accepted with `:w` closes once the file holds the accepted
text; otherwise the accepted text is put into the buffer as unsaved
changes for `:w`/`:e!` so edits are never discarded.
([coder#248](coder#248),
[coder#261](coder#261))
- `diff_opts.layout = "unified"`: a VS Code-style unified diff rendered
in a single buffer with interleaved deleted/added lines, as a compact
alternative to `"vertical"`/`"horizontal"`. Documented to require Neovim
>= 0.9.0. Customizable via the
`ClaudeCodeInlineDiffAdd`/`Delete`/`AddSign`/`DeleteSign` highlight
groups. ([coder#195](coder#195),
[coder#295](coder#295),
[coder#297](coder#297))
- `User ClaudeCodeSendComplete` autocmd, fired once per file when a send
is accepted while Claude is connected, with `data = { file_path,
start_line, end_line, context }` (lines 0-indexed). Enables post-send
logic such as focusing a Claude session running outside Neovim.
([coder#228](coder#228),
[coder#265](coder#265))
- `User ClaudeCodeDiffOpened` / `ClaudeCodeDiffClosed` autocmds carrying
diff metadata, plus `diff_opts.auto_resize_terminal` (default `true`) to
opt out of plugin-managed terminal width during diffs and
`terminal.diff_split_width_percentage` to set a distinct terminal width
while a diff is open.
([coder#270](coder#270))
- `terminal.auto_insert` option (default `true`): set to `false` to stay
in Normal mode when refocusing the Claude terminal and preserve your
scroll position instead of jumping to the prompt.
([coder#233](coder#233))
- `ClaudeCodeTreeAdd` / `<leader>as` support in snacks.nvim pickers
(`snacks_picker_list`), covering `Snacks.explorer()` and modal
`Snacks.picker.files()`/`grep()`.
([coder#192](coder#192),
[coder#269](coder#269))
- netrw file selection for `<leader>as` / `:ClaudeCodeTreeAdd`,
supporting marked files and the file under the cursor.
([coder#62](coder#62))

### Changed

- Model picker labels are now version-free evergreen aliases (`Claude
Opus (Latest)`, `Claude Sonnet (Latest)`, `Claude Haiku (Latest)`), with
new 1M-context variants (`opus[1m]`, `sonnet[1m]`) and a `Default
(account recommended)` entry.
([coder#146](coder#146),
[coder#256](coder#256))
- `:checkhealth claudecode` and the MCP `serverInfo.version` now report
the real plugin version from the `VERSION` file instead of a hard-coded
value. ([coder#437](coder#437))

### Fixed

- The Snacks provider no longer fails to launch Claude when a model
alias contains shell-glob characters (e.g. `opus[1m]`); the command is
now passed as an argv list with no shell interpretation.
([coder#256](coder#256))
- The native terminal now adopts only terminal buffers it started
(marked with `b:claudecode_native_terminal`), instead of any visible
terminal whose name contains `claude`. Upgrade note: a terminal that an
older plugin version started (for example after `:Lazy reload` following
an upgrade), or that a session file restored, carries no mark and is no
longer adopted. The next open starts a second Claude session, and the
old terminal keeps running until you close its buffer or quit Claude in
it. ([coder#349](coder#349),
[coder#352](coder#352),
[coder#364](coder#364))
- `closeAllDiffTabs` is now scoped to claudecode's own tracked diffs and
no longer wipes out an open diffview.nvim, fugitive, or native
`:diffsplit` review; `openFile`/`openDiff` also never reuse a window
that is in diff mode.
([coder#277](coder#277),
[coder#290](coder#290))
- `close_tab` now closes only the diff with that tab name and never
deletes a user buffer.
([coder#373](coder#373))
- Closing the native terminal, for example with `:ClaudeCodeClose`, now
stops the Claude job instead of leaving it running.
([coder#336](coder#336))
- The Claude terminal now adds loopback hosts to `no_proxy`/`NO_PROXY`
so a configured proxy no longer tunnels Claude's `ws://127.0.0.1` IDE
connection and times out queued @ mentions.
([coder#70](coder#70),
[coder#268](coder#268))
- `focus_after_send = true` with `provider = "none"`/`"external"` now
emits a one-time warning pointing to the `User ClaudeCodeSendComplete`
autocmd instead of failing silently.
([coder#228](coder#228),
[coder#265](coder#265))
- Rejecting a Claude diff with `:q` / `:close` / `<C-w>c` (or closing
the tab) now resolves it as rejected via a `WinClosed` autocmd.
([coder#266](coder#266))
- Quickly-made and single-line visual selections are now pushed to
Claude reliably; selections are flushed synchronously on visual-mode
exit and persist until the cursor moves, including in the external
`/ide` flow and Select mode.
([coder#246](coder#246),
[coder#267](coder#267),
[coder#367](coder#367),
[coder#381](coder#381),
[coder#388](coder#388))
- Pending diffs are now automatically closed when the client that opened
them disconnects or the integration stops, so orphaned proposals no
longer linger.
([coder#248](coder#248),
[coder#261](coder#261))
- `openDiff` now works when the Claude terminal is the only window,
creating a split to host the diff instead of failing with "No suitable
editor window found".
([coder#260](coder#260))
- Fixed the "climbing cursor" in the Snacks terminal, where the cursor
sat one row above Claude's prompt after hide and show. On Neovim >= 0.10
a floating terminal is now hidden instead of closed. A split is still
closed on hide and created again on show, which keeps the cursor in
place. Floating terminals on Neovim < 0.10 keep the old behavior.
([coder#240](coder#240),
[coder#183](coder#183),
[coder#271](coder#271))
- Worked around a Neovim core bug (< 0.12.2) that fragmented large
bracketed pastes into the terminal; controlled by
`terminal.fix_streamed_paste` (`"auto"` by default).
([coder#252](coder#252))
- `openFile` now selects exactly the requested line range or matched
text, keeps the user's Visual mode, unsaved changes, focus and preview
window intact, never prompts W11/W12, and never picks the preview window
as the main editor window.
([coder#353](coder#353),
[coder#365](coder#365),
[coder#370](coder#370),
[coder#375](coder#375),
[coder#382](coder#382),
[coder#384](coder#384),
[coder#387](coder#387),
[coder#396](coder#396),
[coder#408](coder#408))
- `getDiagnostics` now handles plain file paths without a `file://` URI
scheme, and IDE diagnostics return grouped URI-based payloads with
editor-native ranges and severity names.
([coder#163](coder#163),
[coder#274](coder#274))
- `:ClaudeCodeAdd` and `openFile` now handle `$` in file paths.
([coder#286](coder#286))
- Prevented a segfault when accepting a new-file diff with
`render-markdown.nvim` installed, by turning off diff mode before the
post-write redraw.
([coder#224](coder#224))
- The auth token is now generated from a CSPRNG and the lock file is
written atomically with mode `0600` in a `0700` directory.
([coder#259](coder#259))
- Detect system sleep/wake and reset client keepalive timestamps to
prevent false disconnections.
([coder#141](coder#141))
- The WebSocket server now retries port binding on `EADDRINUSE`
(parallel instances), closes connections on malformed/oversized or
binary frames with the correct status, joins fragmented messages,
validates UTF-8 per message, and never repeats a client id within a
process. ([coder#258](coder#258),
[coder#283](coder#283),
[coder#378](coder#378),
[coder#383](coder#383),
[coder#390](coder#390),
[coder#395](coder#395),
[coder#405](coder#405),
[coder#422](coder#422),
[coder#431](coder#431))
- Legacy `diff_opts` (e.g. `vertical_split`, `open_in_current_tab`) now
take effect again after the config merge-order regression.
([coder#142](coder#142))
- `:q` on a diff window no longer hangs; floating diff terminals keep
focus; empty buffers are wiped when the terminal provider is `none`; and
accepted diffs are handed over in the buffer's own line-ending format.
([coder#178](coder#178),
[coder#223](coder#223),
[coder#266](coder#266),
[coder#392](coder#392))

### Compatibility

- Integration tests now run on Neovim v0.8.0, and a new-tab diff no
longer fails there because Neovim 0.8 has no `statuscolumn`. The unified
layout is documented to require Neovim >= 0.9.0, and the v0.8.0
integration tests skip it.
([coder#369](coder#369),
[coder#394](coder#394))

---
Maintained by the release-please workflow. CHANGELOG.md and the release
PR body are regenerated by Communique on every push to main, so manual
edits to this PR are overwritten.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Thomas Kosiewski <tk@coder.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] keep_terminal_focus = true skips floating windows

1 participant