Skip to content

Maintain focus history per tag#245

Merged
paperbenni merged 1 commit intomainfrom
fix-tag-focus-history-1143635075217860583
Mar 22, 2026
Merged

Maintain focus history per tag#245
paperbenni merged 1 commit intomainfrom
fix-tag-focus-history-1143635075217860583

Conversation

@paperbenni
Copy link
Copy Markdown
Member

@paperbenni paperbenni commented Mar 22, 2026

Fixes an issue where switching back to a tag would always select the window at the top of the stack, rather than the window that was previously active when the user left the tag.

  • Added tag_focus_history: HashMap<u32, WindowId> to Monitor.
  • Updated update_focus_state to store the newly focused window into the active tag mask's history.
  • Modified resolve_focus_target to consult tag_focus_history before using first_visible_client as a fallback.

PR created automatically by Jules for task 1143635075217860583 started by @paperbenni

Summary by Sourcery

Maintain per-tag focus history so returning to a tag restores the previously focused window instead of always selecting the top of the stack.

Bug Fixes:

  • Fix incorrect focus behavior when switching back to a tag by restoring the window that was last active on that tag instead of the top-of-stack window.

Enhancements:

  • Track focus history per tag on each monitor and consult it when resolving focus, falling back to the top-of-stack window only when no valid history exists.

Summary by CodeRabbit

  • New Features
    • Window managers now track and restore the previously focused window for each tag, providing seamless navigation when switching between workspaces.

Added `tag_focus_history` to `Monitor` to maintain the last focused window
for each tag combination. When switching views, `resolve_focus_target`
now checks this history before falling back to the topmost window in
the visible stack. This prevents focus from resetting to the top window
every time the user switches back to a previously visited tag.

Co-authored-by: paperbenni <15818888+paperbenni@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Mar 22, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Tracks and restores the last focused window per tag on each monitor by storing focus history and consulting it when resolving focus targets, falling back to the existing top-of-stack behavior when necessary.

Sequence diagram for resolving and updating focus with tag history

sequenceDiagram
    actor User
    participant WindowManager
    participant CoreCtx
    participant Monitor
    participant ClientsStore

    User->>WindowManager: switch_tag(new_tag_mask)
    WindowManager->>CoreCtx: resolve_focus_target(core, None)
    CoreCtx->>Monitor: get_selected_tags()
    Monitor-->>CoreCtx: selected_tag_mask

    Note over CoreCtx,Monitor: Resolve focus target
    CoreCtx->>Monitor: lookup tag_focus_history[selected_tag_mask]
    alt history entry exists
        Monitor-->>CoreCtx: hist_win
        CoreCtx->>ClientsStore: get(hist_win)
        ClientsStore-->>CoreCtx: client
        alt client visible_on_tags(selected_tag_mask) and not hidden
            CoreCtx-->>WindowManager: FocusTargetResult(target = hist_win)
        else client invalid
            CoreCtx->>Monitor: first_visible_client(clients_map)
            Monitor-->>CoreCtx: top_win or None
            CoreCtx-->>WindowManager: FocusTargetResult(target = top_win or None)
        end
    else no history entry
        CoreCtx->>Monitor: first_visible_client(clients_map)
        Monitor-->>CoreCtx: top_win or None
        CoreCtx-->>WindowManager: FocusTargetResult(target = top_win or None)
    end

    Note over WindowManager,Monitor: Update focus state
    WindowManager->>CoreCtx: update_focus_state(core, result)
    CoreCtx->>Monitor: set sel = result.target
    alt result.target is Some(t)
        CoreCtx->>Monitor: tag_focus_history.insert(selected_tags(), t)
    end
    Monitor-->>User: last focused window on tag is restored
Loading

Class diagram for updated Monitor focus history

classDiagram
    class Monitor {
        +Vec~u32~ tags
        +Vec~WindowId~ clients
        +Option~WindowId~ sel
        +HashMap~u32, WindowId~ tag_focus_history
        +Option~WindowId~ overlay
        +Vec~WindowId~ stack
        +Option~WindowId~ fullscreen
        +selected_tags() u32
        +first_visible_client(clients_map) Option~WindowId~
    }
Loading

File-Level Changes

Change Details Files
Persist and use per-tag focus history when resolving focus targets.
  • Extend Monitor with a tag_focus_history HashMap keyed by tag bitmask and initialize it in the Default implementation.
  • Update update_focus_state to record the newly focused window for the currently selected tag mask on the active monitor.
  • Modify resolve_focus_target to first try restoring focus from tag_focus_history if the stored window is still visible and not hidden, and only fall back to first_visible_client when no valid history entry exists.
src/types/monitor.rs
src/focus.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 22, 2026

📝 Walkthrough

Walkthrough

Implements tag-based focus history for monitors. When resolving a focus target, the system now checks the monitor's focus history for the current tag mask before falling back to the first visible client. Focus state updates record the target window to this history, enabling retention of window focus across tag switches.

Changes

Cohort / File(s) Summary
Monitor State Addition
src/types/monitor.rs
Added tag_focus_history: HashMap<u32, WindowId> field to track focus history per tag mask and initialized in Default implementation.
Focus Resolution Enhancement
src/focus.rs
Modified focus target resolution to consult tag_focus_history before falling back to first visible client, and record focus updates to history under currently selected tags.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A rabbit hops through tags with glee,
Each window's home now history!
Remember me, when tags do dance,
No losing focus—second chance! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Maintain focus history per tag' directly and concisely summarizes the main change: adding per-tag focus history tracking to preserve window focus when switching between tags.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-tag-focus-history-1143635075217860583

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

You can enable review details to help with troubleshooting, context usage and more.

Enable the reviews.review_details setting to include review details such as the model used, the time taken for each step and more in the review comments.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • Consider using a single consistent source for the tag mask key (e.g., always selected_tags() or always selected.bits()) in both resolve_focus_target and update_focus_state to avoid subtle mismatches if the representation changes.
  • It might be worth pruning or updating tag_focus_history entries when a window is removed or no longer matches a tag mask so the map does not accumulate stale window IDs over time.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider using a single consistent source for the tag mask key (e.g., always `selected_tags()` or always `selected.bits()`) in both `resolve_focus_target` and `update_focus_state` to avoid subtle mismatches if the representation changes.
- It might be worth pruning or updating `tag_focus_history` entries when a window is removed or no longer matches a tag mask so the map does not accumulate stale window IDs over time.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/types/monitor.rs (1)

117-117: Add cleanup for stale tag_focus_history entries when clients are destroyed.

The tag_focus_history map accumulates entries pointing to dead windows as clients are closed. While the lookup in resolve_focus_target validates that windows still exist (preventing crashes), entries for destroyed windows remain in the map. The pattern for this cleanup already exists in unmanage()—overlay and fullscreen references are explicitly cleared for destroyed windows. Extend this to tag_focus_history by removing entries that reference the destroyed window, or periodically prune entries for non-existent windows.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/types/monitor.rs` at line 117, When a client is destroyed unmanage()
should remove any entries in tag_focus_history that point to that client's
window to avoid accumulating stale references; update unmanage() to iterate
tag_focus_history (the HashMap) and remove keys whose value == client.win (or
otherwise reference the destroyed window), similar to how overlay and fullscreen
are cleared, or add a helper prune_tag_focus_history(window) and call it from
unmanage(); ensure resolve_focus_target still validates existence after this
cleanup.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/types/monitor.rs`:
- Line 117: When a client is destroyed unmanage() should remove any entries in
tag_focus_history that point to that client's window to avoid accumulating stale
references; update unmanage() to iterate tag_focus_history (the HashMap) and
remove keys whose value == client.win (or otherwise reference the destroyed
window), similar to how overlay and fullscreen are cleared, or add a helper
prune_tag_focus_history(window) and call it from unmanage(); ensure
resolve_focus_target still validates existence after this cleanup.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1516927c-ecb3-4ae1-850e-2e25c8d66929

📥 Commits

Reviewing files that changed from the base of the PR and between befc5ba and b2069e6.

📒 Files selected for processing (2)
  • src/focus.rs
  • src/types/monitor.rs

@paperbenni paperbenni merged commit 96b88c8 into main Mar 22, 2026
5 checks passed
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.

1 participant