Skip to content

[CTX-1808] feat(platform): per-window focus tracking and graceful per-window close (bitty#1765 slice 3) - #3138

Merged
Xuepoo merged 2 commits into
mainfrom
ctx-1808/window-focus-close
Nov 13, 2026
Merged

Xuepoo merged 2 commits into
mainfrom
ctx-1808/window-focus-close

Conversation

@Xuepoo

@Xuepoo Xuepoo commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Priority: P0 | Area: platform | Labels: feat, P0, area:platform | Milestone: v0.1.0 | RFC: OQ-none | Task: CTX-1808

Related #1765

Summary

Slice 3 of bitty#1765. Slices 1 and 2 gave the process a window registry
(#3133) and per-window presentation surfaces with second-window paint fan-out
(#3134). This slice makes the registry the single owner of which window is
focused
and of what one close event means for the instance, and wires
both into the event path without a second registry and without touching the
single-window behaviour.

No new window machinery, no new platform seam, no new crate edge. Three files,
one commit, headless only.

Per-window state model

Attribution and focus are two states, not one:

state moved by purpose
active (slice 1) every window event that names a registered window event attribution / "who produced this"
focused (this slice) Focused(true) / Focused(false) only the window the compositor reports focused; target of window-scoped commands
  • focus_edge(kind) is the one place that decides which events count as focus;
    a key press, a resize, an occlusion edge or a close request never moves focus.
  • focus(id) / blur(id) validate the identity first. A focus edge for an
    identity this process never admitted changes nothing, and blur clears only
    when it names the window currently focused — focus edges cross in flight (the
    platform reports the new window focused before the old one blurred), so a late
    blur cannot clear a newer focus.
  • Creation and destruction never leave a hole: a new row takes focus only when
    nothing was focused (there is no platform seam to ask for focus, so creation
    never steals it), and removing the focused window hands focus to a surviving
    row — the same deterministic first-survivor rule slice 1 uses for active.
  • TerminalApp::focused_window() is the target a window-scoped command resolves
    to: focused, else the first registered window, else the single-window identity.
    With one window this is byte-identical to today (self.window.id).

Close is one decision, answered by the registry:

CloseDecision meaning app behaviour
Unknown identity not registered (headless run, foreign id) existing single-window close path, unchanged
WindowOnly another registered window survives release only that window's surface, drop its row, re-home focus, keep running
LastWindow the last registered row existing save + shutdown + exit path

Per-window close bookkeeping:

  • a secondary window's Closed event now runs the same teardown as
    CloseRequested (release its surface, drop its row, clear a deferred attach),
    so a window the platform destroyed no longer leaves a stale registry row;
  • the survivors' rows, surface states and identities are untouched;
  • closing the last window still exits exactly as before.

Headless tests

Registry (crates/bitty-terminal/src/window_registry.rs, constructible window
payload — a WindowHandle cannot exist without a display server, which is why
the row semantics live here):

  • only_focus_events_move_window_focus — the focus/attribution split, enumerated
    over resize, scale, redraw, cursor-enter/leave, close, closed, occlusion.
  • a_registered_window_starts_focused_only_when_nothing_was_focused — creation
    does not steal focus; a registry with no focus takes the new window.
  • focus_edges_move_focus_and_unknown_identities_are_refused
  • a_stale_blur_from_the_previously_focused_window_cannot_clear_a_newer_focus
  • closing_the_focused_window_rehomes_focus_to_a_survivor — no focus hole, no
    dangling identity, survivor surface state intact, survivor becomes LastWindow.
  • closing_an_unfocused_window_leaves_focus_on_its_window
  • closing_the_last_window_leaves_no_focus_and_no_registry_row
  • close_decision_separates_window_only_last_window_and_unknown

App (crates/bitty-terminal/src/tests.rs):

  • a_focus_sensitive_command_targets_the_only_window_of_a_single_window_instance
    — the single-window target is unchanged and resolving a target never fabricates
    a row.
  • window_registry_command::a_close_request_for_an_unregistered_window_still_takes_the_exit_path
    (feature input-vm-test-support, driven through the real AppHandler with the
    recording context) — a close the registry does not own still exits the instance
    and leaves no row or focus behind.

Gates

gate result
cargo fmt --check exit 0
cargo clippy --workspace --all-targets --offline -- -D warnings exit 0
cargo test -p bitty-terminal --offline --bin bitty exit 0, 1559 passed / 0 failed
cargo test -p bitty-terminal --offline --features input-vm-test-support --bin bitty -- window_registry focus_sensitive exit 0, 21 passed / 0 failed
cargo +1.85 check --workspace --tests --offline (MSRV, no let-chains) exit 0
RUSTFLAGS='-D warnings' cargo check -p bitty-terminal --tests --target x86_64-pc-windows-gnu --offline exit 0
rustfmt +stable --edition 2024 --check on the three touched files exit 0

Mutation evidence (each hunk mutated in a throwaway copy outside the worktree,
with its own CARGO_TARGET_DIR, then restored — the lane worktree was never
mutated):

mutation discriminating test result
drop the focus re-home in remove closing_the_focused_window_rehomes_focus_to_a_survivor, closing_the_last_window_leaves_no_focus_and_no_registry_row 2 failed, rc 101
make blur clear unconditionally a_stale_blur_from_the_previously_focused_window_cannot_clear_a_newer_focus, focus_edges_move_focus_and_unknown_identities_are_refused 2 failed, rc 101
make focus_edge answer Some(true) for every event only_focus_events_move_window_focus 1 failed, rc 101
make close_decision always answer LastWindow close_decision_separates_window_only_last_window_and_unknown 1 failed, rc 101

Pre-existing, not introduced here: cargo clippy -p bitty-terminal --all-targets --features input-vm-test-support -D warnings reports four drop_non_drop
errors at tests.rs:1372/1391/1414/1433 on origin/main as well. That feature
combination is not a repository gate (just check-window runs nextest for those
tests), so this PR leaves it alone rather than widen scope.

Reference behaviour

A new window is a peer of the focused one and focus follows the compositor's
Focused edges (ghostty/kitty/wezterm default: the platform focuses the window
it created). Deliberate deviation: Bitty has no focus_window platform seam, so
the registry never claims a window is focused on creation — it only records the
edge the OS sends. X on a secondary window closes only that window, as
kitty @ close-window / a wezterm per-window close does.

What remains in #1765

  1. Closing the first window while other windows remain. The close decision
    is already WindowOnly for it, but the app cannot complete it: the primary
    swap chain, presenter and GPU context are process-wide, so promoting a
    survivor to the primary role needs a bitty-runtime seam (release the primary
    surface without dropping the per-window fleet, then rebuild the primary
    surface for the survivor on the existing device) that does not exist yet.
    Until it lands the request is declined loudly (warning: + stderr line
    naming the window) instead of terminating an instance the user still has a
    window in — deliberately not a half-wired teardown.
  2. Closed from the primary while survivors exist still takes the exit path:
    it cannot be declined (the window is already gone) and there is no survivor
    promotion yet. It is unreachable from the graceful flow because (1) declines
    the request first.
  3. core.window.list still reports a single hardcoded window
    ({"windows":[{"id":"w:1"}]} in ctl/apply.rs). Threading registry state
    into ctl::apply is the command/CLI half of the issue's "Actions & CLI"
    bullet (launching new windows in a running instance), not this slice.
  4. Per-window panels/leases do not exist: the layout tree is still
    process-global, so a window's close has only its presentation surface and its
    registry row to tear down. When per-window layout lands, that teardown joins
    the WindowOnly path.
  5. Requesting focus (WindowHandle::focus) if background window creation is
    ever added; today focus is only ever reported, never requested.
  6. Per-window input routing. A secondary window's key/mouse events are still
    contained and dropped (slice 1 behaviour): the layout tree, PTY and IME
    session are process-global, so typing in a second window goes nowhere yet.
    This slice records which window is focused; routing input to the focused
    window needs the per-window layout ownership the same promotion seam unlocks.

Summary by CodeRabbit

  • Bug Fixes
    • Closing the primary window no longer exits the app while other windows remain open; the primary window stays available.
    • Closing a secondary window now updates the active window appropriately, including transferring focus to a remaining window.
    • Window focus is tracked more reliably when switching between windows, and closing an unknown window preserves the existing close behavior.

…-window close

bitty#1765 slice 3. The window registry becomes the single owner of the
focused window and of what one close event means for the instance.

Per-window focus (A):
- `WindowRegistry::focused` is a separate state from event attribution:
  `active` follows the last handled event, focus moves only on `Focused`
  edges, so a background window's key press, resize or occlusion edge can
  never claim focus.
- `focus_edge` keeps that rule in one place instead of re-deriving it in the
  event handler; the app forwards every window event through it.
- focus is validated by identity: `focus`/`blur` refuse an identity this
  process never registered, and `blur` only clears when it names the window
  currently focused, so a late blur from the previously focused window cannot
  clear a newer focus.
- creation and destruction never leave a focus hole: a new row takes focus
  only when nothing was focused, and removing the focused window hands focus
  to a surviving row (same deterministic rule as attribution).
- `TerminalApp::focused_window()` is the target a window-scoped command
  resolves to (focused, else the first registered, else the single-window
  identity), so the single-window case is unchanged.

Graceful per-window close (B):
- `WindowRegistry::close_decision` states the consequence of one close:
  `WindowOnly` while another window survives, `LastWindow` for the last row,
  `Unknown` for an identity the registry does not own (headless run).
- a secondary window's `Closed` event now runs the same bookkeeping as
  `CloseRequested` (release that window's surface, drop its row, clear a
  deferred attach), so a destroyed window no longer leaves a stale row.
- closing a secondary window releases only its surface and row; focus and
  attribution re-home to a survivor and the instance keeps running.
- closing the last window still takes the existing save/shutdown/exit path.
- the first window of a multi-window instance refuses to close: promoting a
  survivor to the primary role needs a runtime surface seam that does not
  exist yet, so the request is declined loudly instead of terminating an
  instance the user still has a window in (see the PR for the exact remainder).
@Xuepoo Xuepoo added feat Feature P0 Priority: highest area:platform Area: platform / windowing labels Nov 13, 2026
@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Explain Change →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 29 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: dd61a08c-fe68-45d2-8bbe-badba84d5ec6
Commits

Reviewing files that changed from the base of the PR and between baf3a41 and 2b02d31.

Files selected for processing: 1

  • crates/bitty-terminal/src/window_registry.rs

No actionable comments were generated in the recent review.

Walkthrough

The window registry now tracks focused-window identity and classifies close decisions. The terminal app uses these states when handling window events, including focus fallback, primary-window close requests, and secondary-window cleanup.

Changes: Window Focus and Close Handling

Layer / File(s) Summary
Registry focus and close rules
crates/bitty-terminal/src/window_registry.rs
The registry tracks focus separately from active event attribution. Registration and removal update focus, and close decisions distinguish unknown, window-only, and last-window cases. Tests cover focus edges and close behavior.
Terminal app event handling
crates/bitty-terminal/src/terminal_app.rs, crates/bitty-terminal/src/tests.rs
The app tracks focus and provides a focused-window fallback. It defers a primary-window close request when another window remains and applies cleanup to secondary-window CloseRequested and Closed events. Tests cover fallback and unregistered close requests.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant WindowEvent
  participant TerminalApp
  participant WindowRegistry
  WindowEvent->>TerminalApp: CloseRequested(primary window)
  TerminalApp->>WindowRegistry: close_decision(primary window)
  WindowRegistry-->>TerminalApp: WindowOnly
  Note over TerminalApp: Defer the close event
Loading
Merge Risk: Minimal · previous review baf3a

This change adds per-window focus tracking and secondary-window close handling. No remaining merge-blocking risk was found. Closing the primary window while other windows remain is declined by design until survivor promotion lands.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names per-window focus tracking and graceful per-window close, which are the main changes in the registry and terminal_app.rs. The changeset implements focus edges, a focused_window() access…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names per-window focus tracking and graceful per-window close, which are the main changes in the registry and terminal_app.rs. The changeset implements focus edges, a focused_window() accessor, and CloseDecision handling for secondary and primary windows. The ticket and slice tags add noise but do not make the title inaccurate. The title is long at 103 characters, but it stays on-topic.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 76af1f81-1922-4e55-9959-bef1b7b9f9e3
Commits

Reviewing files that changed from the base of the PR and between f785dcf and baf3a41.

Files selected for processing: 3

  • crates/bitty-terminal/src/terminal_app.rs
  • crates/bitty-terminal/src/tests.rs
  • crates/bitty-terminal/src/window_registry.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@Xuepoo Xuepoo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Independent review (CTX-1808, commit baf3a416): NEEDS-FIX

Verified (passing)

  • Per-window focus tracking (crates/bitty-terminal/src/window_registry.rs, terminal_app.rs): focus_edge restricts focus changes to Focused(true)/Focused(false); focus/blur reject unknown IDs and prevent stale blurs from clearing newer focus; insert only sets focus when self.focused.is_none(); remove deterministically re-homes focus to the first survivor.
  • Graceful per-window close: CloseDecision (Unknown, WindowOnly, LastWindow) cleanly separates pre-registry exit, multi-window close, and last-window exit. Secondary CloseRequested and Closed share is_window_close teardown (release_window_surface, windows.remove, deferred_window_surfaces.retain) without mutating survivor rows/surfaces. Primary CloseRequested with WindowOnly declines loudly while survivor promotion is unimplemented.
  • Single-window invariance & scope: TerminalApp::focused_window() preserves self.window.id fallback; 3-file diff, no hardcoded host paths/secrets, no unrelated edits.
  • Local checks:
    • cargo fmt --check: pass
    • cargo clippy -p bitty-terminal --offline -- -D warnings: pass
    • cargo test -p bitty-terminal --offline --bin bitty -- window_registry focus_sensitive: 18 passed, 0 failed
    • cargo test -p bitty-terminal --offline --features input-vm-test-support --bin bitty -- window_registry focus_sensitive: 21 passed, 0 failed

Blocking finding

  1. just doc-check / CI Quality gates (1) (Check rustdoc) failure:
    RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --locked fails with 3 rustdoc::broken-intra-doc-links errors in crates/bitty-terminal/src/window_registry.rs:
    • Line 33: [Self::active]
    • Line 35: [Self::focused]
    • Line 43: [Self::close_decision]
      Self is not in scope in module-level //! documentation; replace those links with [WindowRegistry::active], [WindowRegistry::focused], and [WindowRegistry::close_decision], then re-run just doc-check.

Non-blocking PR hygiene

  • PR #3138 currently has milestone: null (missing v0.1.0) and lacks the Priority: ... | Area: ... | Labels: ... | Milestone: ... | Task: CTX-1808 body line required by bitty/AGENTS.md.

@Xuepoo Xuepoo added this to the v0.1.0 milestone Nov 13, 2026

@Xuepoo Xuepoo left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Independent re-review (CTX-1808, commit 2b02d310): APPROVE

  • Verified crates/bitty-terminal/src/window_registry.rs qualifies WindowRegistry::active, WindowRegistry::focused, and WindowRegistry::close_decision in the module-level documentation.
  • Verified just doc-check (RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --locked) exits 0 with zero warnings/errors.
  • Verified cargo test -p bitty-terminal --offline --bin bitty -- window_registry passes (17 passed, 0 failed).
  • Verified PR #3138 carries milestone v0.1.0, labels feat, P0, area:platform, and the required Priority: P0 | Area: platform | ... | Task: CTX-1808 metadata line.

@Xuepoo
Xuepoo merged commit d8bbb92 into main Nov 13, 2026
21 checks passed
@Xuepoo
Xuepoo deleted the ctx-1808/window-focus-close branch November 13, 2026 14:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:platform Area: platform / windowing feat Feature P0 Priority: highest

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant