Skip to content

text: Prevent stale selections from returning after remount - #3588

Merged
huacnlee merged 2 commits into
longbridge:mainfrom
TomiXRM:fix/selection-unmount-lifecycle
Oct 19, 2026
Merged

huacnlee merged 2 commits into
longbridge:mainfrom
TomiXRM:fix/selection-unmount-lifecycle

Conversation

@TomiXRM

@TomiXRM TomiXRM commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

Problem

A completed-frame sweep clears an unmounted participant's snapshot but leaves the window's anchor/cursor alive. Registering the same retained TextView state later republishes those endpoints, making its old selection copyable again without a new gesture.

Change

Retire the existing window selection state when an actually removed participant owns the anchor, cursor, or pending extension anchor. Reuse the existing clear path so auto-scroll stops before its anchor disappears, touch state resets, and clear callbacks still run outside the window-state update borrow. Cached views that remain rendered and unrelated participant removal preserve selection. No public API, dependency, or compatibility layer is added.

Verification

  • Failing-before regression: retained participant remount copies “stale” instead of an empty selection. It passes after the fix; fresh selection after remount still works.
  • Regressions also cover either shared-range endpoint departing, unrelated participant removal, and held-edge cancellation on unmount. The retained local-selection test no longer manually clears before remount.
  • 1,413 Base + 702 Component + 400 Kit integration + 1 UI tests pass.
  • 13 real offscreen Metal rendering checks pass.
  • A public consumer probe passes in hidden real AppKit/Metal windows for both partial drag and Select All: cached frames retain selection; completed-frame unmount rejects Copy and Select All/Copy; remount alone cannot revive it; fresh physical selection and Select All/Copy work.
  • Formatting and Base/Component/Kit all-target Clippy pass, with only the pre-existing inline_flow.rs manual_option_zip warning and block 0.1.6 future-compatibility notice.
  • Independent read-only review found no implementation defect; it correctly identified that native frame/effect boundaries must be completed rather than drawing repeatedly inside one App update.
Reproducible native consumer probe

Temporarily place this in crates/kit/examples/selection_lifecycle.rs, then run on macOS:

cargo run -p gpui-kit --features test-support,component --example selection_lifecycle --locked

The probe preserves the clipboard and never activates or shows its windows. App effects are flushed between completed frames. The temporary example is removed from the contribution after verification.

use gpui_kit::{
    AppContext, Bounds, ClipboardItem, Context, Entity, Modifiers, MouseButton, MouseDownEvent,
    MouseMoveEvent, MouseUpEvent, PlatformInput, Render, VisualTestAppContext, Window,
    WindowBounds, WindowOptions,
    assets::Assets,
    component::text::{TextView, TextViewState},
    div, point,
    prelude::*,
    px, size,
    test::{TestSupportExt, TestWindowExt},
};
use std::sync::Arc;

const POISON: &str = "NOTHING_SHOULD_BE_COPIED";

struct RetainedPost {
    text: Entity<TextViewState>,
    mounted: bool,
}

impl Render for RetainedPost {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div().size_full().p_4().when(self.mounted, |root| {
            root.child(
                div().id("post").test_support().w(px(300.)).child(
                    TextView::new(&self.text)
                        .text_size(px(16.))
                        .line_height(px(20.))
                        .selectable(true)
                        .scrollable(false),
                ),
            )
        })
    }
}

fn select_first_paragraph(window: &mut Window, cx: &mut gpui_kit::App) {
    let bounds = window.find("post").bounds();
    let start = point(bounds.left() + px(1.), bounds.top() + px(8.));
    window.dispatch_event(
        PlatformInput::MouseDown(MouseDownEvent {
            position: start,
            button: MouseButton::Left,
            modifiers: Modifiers::none(),
            click_count: 1,
            first_mouse: false,
        }),
        cx,
    );
    for x in [24., 100.] {
        window.dispatch_event(
            PlatformInput::MouseMove(MouseMoveEvent {
                position: point(bounds.left() + px(x), start.y),
                modifiers: Modifiers::none(),
                pressed_button: Some(MouseButton::Left),
            }),
            cx,
        );
    }
    window.dispatch_event(
        PlatformInput::MouseUp(MouseUpEvent {
            position: point(bounds.left() + px(100.), start.y),
            button: MouseButton::Left,
            modifiers: Modifiers::none(),
            click_count: 1,
        }),
        cx,
    );
    window.render_frame(cx);
}

fn assert_copy(window: &mut Window, cx: &mut gpui_kit::App, expected: &str) {
    cx.write_to_clipboard(ClipboardItem::new_string(POISON.into()));
    window.press("secondary-c", cx);
    assert_eq!(
        cx.read_from_clipboard()
            .and_then(|item| item.text())
            .as_deref(),
        Some(expected)
    );
}

fn run(cx: &mut VisualTestAppContext) {
    for select_all in [false, true] {
        let (handle, view) = cx.update(|cx| {
            gpui_kit::open_window(
                WindowOptions {
                    window_bounds: Some(WindowBounds::Windowed(Bounds {
                        origin: point(px(-10000.), px(-10000.)),
                        size: size(px(600.), px(400.)),
                    })),
                    focus: false,
                    show: false,
                    ..Default::default()
                },
                cx,
                |_, cx| {
                    cx.new(|cx| RetainedPost {
                        text: cx.new(|cx| TextViewState::markdown("PRIVATE\n\nSECOND", cx)),
                        mounted: true,
                    })
                },
            )
            .unwrap()
        });
        cx.run_until_parked();
        cx.update_window(handle, |_, window, cx| {
            window.render_frame(cx);
            select_first_paragraph(window, cx);
            if select_all {
                window.press("secondary-a", cx);
            }
            let expected = if select_all {
                "PRIVATE\nSECOND"
            } else {
                "PRIVATE"
            };
            assert_copy(window, cx, expected);
            for _ in 0..4 {
                window.render_frame(cx);
                window.simulate_next_frame(cx);
            }
            assert_copy(window, cx, expected);
            view.update(cx, |view, cx| {
                view.mounted = false;
                cx.notify();
            });
        })
        .unwrap();
        for _ in 0..3 {
            cx.run_until_parked();
            cx.update_window(handle, |_, window, cx| {
                window.render_frame(cx);
                window.simulate_next_frame(cx);
            })
            .unwrap();
        }
        cx.run_until_parked();
        cx.update_window(handle, |_, window, cx| {
            println!("native unmounted: select_all={select_all}");
            assert!(window.try_find("post").is_none());
            assert_copy(window, cx, POISON);
            window.press("secondary-a", cx);
            assert_copy(window, cx, POISON);
            view.update(cx, |view, cx| {
                view.mounted = true;
                cx.notify();
            });
        })
        .unwrap();
        cx.run_until_parked();
        cx.update_window(handle, |_, window, cx| {
            window.render_frame(cx);
            println!("native remounted: select_all={select_all}");
            assert!(window.find("post").visible());
            assert_copy(window, cx, POISON);
            select_first_paragraph(window, cx);
            assert_copy(window, cx, "PRIVATE");
            window.press("secondary-a", cx);
            assert_copy(window, cx, "PRIVATE\nSECOND");
            window.remove_window();
        })
        .unwrap();
        drop(view);
        cx.run_until_parked();
        println!(
            "native retained TextView: select_all={select_all}, cached frames, unmount, remount and fresh Copy passed"
        );
    }
}

fn main() {
    let mut cx = VisualTestAppContext::with_asset_source(
        gpui_kit::platform::current_platform(false),
        Arc::new(Assets),
    );
    cx.update(gpui_kit::init);
    let clipboard = cx.read_from_clipboard();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&mut cx)));
    cx.write_to_clipboard(clipboard.unwrap_or_else(|| ClipboardItem::new_string(String::new())));
    if let Err(error) = result {
        std::panic::resume_unwind(error);
    }
}

@huacnlee huacnlee changed the title fix(selection): retire endpoints when participants unmount text: Prevent stale selections from returning after remount Oct 19, 2026
@huacnlee
huacnlee merged commit 2c11365 into longbridge:main Oct 19, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants