Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

fix(linux): collapse Flow toolbar after missed pointer leave

Douglas Lopes6f456d7fb6ce
diff --git a/changelog/unreleased/linux-flow-pill-hover.md b/changelog/unreleased/linux-flow-pill-hover.md
new file mode 100644
index 00000000..ee5128fe
--- /dev/null
+++ b/changelog/unreleased/linux-flow-pill-hover.md
@@ -0,0 +1 @@
+Corrigido: a barra de ditado no Linux recolhe os botões ao retirar o mouse, mesmo quando o navegador perde o evento de saída.
diff --git a/windows/README.md b/windows/README.md
index 33efc0a7..1c093ed4 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -647,6 +647,12 @@ own window.
## Linux
+To check toolbar collapse even when WebKitGTK loses the pointer-leave event,
+run `python3 scripts/test-linux-pill-hover.py target/release/coucou` from
+`windows/` after building. This native regression test uses a separate Xvfb
+display and temporary preferences; it requires Xvfb, xdotool, xwd, a C compiler
+and GTK3 development headers. It leaves captures under `target/pill-hover-test/`.
+
The same app builds for Linux: everything that differs lives in
`src-tauri/src/platform/`, and the relay's transport in `hook/src/unix.rs`.
diff --git a/windows/screenshots/pill-hover-after.png b/windows/screenshots/pill-hover-after.png
new file mode 100644
index 00000000..395ac06a
Binary files /dev/null and b/windows/screenshots/pill-hover-after.png differ
diff --git a/windows/screenshots/pill-hover-before.png b/windows/screenshots/pill-hover-before.png
new file mode 100644
index 00000000..1e0e530a
Binary files /dev/null and b/windows/screenshots/pill-hover-before.png differ
diff --git a/windows/scripts/test-linux-pill-hover.c b/windows/scripts/test-linux-pill-hover.c
new file mode 100644
index 00000000..c3e238f2
--- /dev/null
+++ b/windows/scripts/test-linux-pill-hover.c
@@ -0,0 +1,12 @@
+#define _GNU_SOURCE
+#include <dlfcn.h>
+#include <gtk/gtk.h>
+
+// Reproduce a lost WebKitGTK leave event without faking the pointer position
+// read by the native watcher. This library is preloaded only in the test.
+void gtk_main_do_event(GdkEvent *event) {
+ static void (*real_event)(GdkEvent *) = NULL;
+ if (!real_event) real_event = dlsym(RTLD_NEXT, "gtk_main_do_event");
+ if (event->type == GDK_LEAVE_NOTIFY) return;
+ real_event(event);
+}
diff --git a/windows/scripts/test-linux-pill-hover.py b/windows/scripts/test-linux-pill-hover.py
new file mode 100644
index 00000000..3d74619b
--- /dev/null
+++ b/windows/scripts/test-linux-pill-hover.py
@@ -0,0 +1,175 @@
+#!/usr/bin/env python3
+"""Check native toolbar collapse when WebKitGTK misses pointerleave.
+
+Uses a virtual X display and temporary preferences. Requires Xvfb, xdotool,
+xwd, dbus-run-session, cc and GTK3 development headers. Captures remain under
+--output so a failing interaction can be inspected.
+"""
+
+import argparse
+import json
+import os
+import pathlib
+import shlex
+import shutil
+import signal
+import struct
+import subprocess
+import tempfile
+import time
+
+parser = argparse.ArgumentParser(description=__doc__)
+parser.add_argument("binary", type=pathlib.Path)
+parser.add_argument("--tools", type=pathlib.Path, help="directory with Xvfb, xdotool and xwd")
+parser.add_argument("--output", type=pathlib.Path, default=pathlib.Path("target/pill-hover-test"))
+parser.add_argument("--display", type=int, default=97)
+args = parser.parse_args()
+args.output.mkdir(parents=True, exist_ok=True)
+output = pathlib.Path(tempfile.mkdtemp(prefix="run-", dir=args.output)).resolve()
+# Keep Unix socket paths short even when --output is deep in a checkout.
+runtime = tempfile.TemporaryDirectory(prefix="coucou-hover-")
+
+
+def tool(name):
+ path = str(args.tools.resolve() / name) if args.tools else shutil.which(name)
+ if not path or not pathlib.Path(path).is_file():
+ raise RuntimeError(f"{name} is required")
+ return path
+
+
+if pathlib.Path(f"/tmp/.X11-unix/X{args.display}").exists():
+ raise RuntimeError("The test display is in use; choose another --display")
+
+shim = output / "drop-leave.so"
+cflags = shlex.split(subprocess.check_output(["pkg-config", "--cflags", "gtk+-3.0"], text=True))
+subprocess.run(
+ ["cc", "-shared", "-fPIC", "-o", str(shim),
+ str(pathlib.Path(__file__).with_suffix(".c")), *cflags, "-ldl"],
+ check=True,
+)
+
+env = os.environ.copy()
+env.update(
+ DISPLAY=f":{args.display}",
+ XDG_SESSION_TYPE="x11",
+ XDG_CURRENT_DESKTOP="TEST",
+ XDG_CONFIG_HOME=str(output / "config"),
+ XDG_DATA_HOME=str(output / "data"),
+ XDG_RUNTIME_DIR=runtime.name,
+ LD_PRELOAD=str(shim),
+)
+for directory in [output / "data/coucou/Flow", output / "config"]:
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+(output / "data/coucou/Flow/prefs.json").write_text(
+ json.dumps({"enabled": True, "openAtLaunch": False})
+)
+
+
+def command(name, *arguments):
+ return subprocess.check_output(
+ [tool(name), *map(str, arguments)], env=env,
+ stderr=subprocess.DEVNULL, text=True, timeout=5,
+ ).strip()
+
+
+def capture(window, name, offset=20):
+ path = output / (name + ".xwd")
+ command("xwd", "-silent", "-id", window, "-out", path)
+ raw = path.read_bytes()
+ header = struct.unpack(">25I", raw[:100])
+ header_size, width, height = header[0], header[4], header[5]
+ byte_order, bits_per_pixel, stride = header[7], header[11], header[12]
+ red_mask, green_mask, blue_mask, colors = header[14], header[15], header[16], header[19]
+ start = header_size + colors * 12
+ row = raw[start + (height - offset) * stride : start + (height - offset + 1) * stride]
+ pixel_size = bits_per_pixel // 8
+ # Twenty pixels above the bottom intersects an open toolbar, but not the
+ # resting 8px capsule. The virtual display's background is black.
+ pixels = [
+ int.from_bytes(row[x * pixel_size : (x + 1) * pixel_size],
+ "little" if byte_order == 0 else "big")
+ for x in range(width // 2 - 80, width // 2 + 80)
+ ]
+ lit = sum(bool(pixel & (red_mask | green_mask | blue_mask)) for pixel in pixels)
+ print(f"{name}: {lit} visible pixels at toolbar height", flush=True)
+ return lit
+
+
+xvfb_env = os.environ.copy()
+xvfb_env.pop("LD_PRELOAD", None)
+xvfb = subprocess.Popen(
+ [tool("Xvfb"), f":{args.display}", "-screen", "0", "1280x720x24", "-ac", "-nolisten", "tcp"],
+ env=xvfb_env, stdout=(output / "xvfb.log").open("w"), stderr=subprocess.STDOUT,
+)
+app = None
+try:
+ for attempt in range(50):
+ try:
+ command("xdotool", "getdisplaygeometry")
+ break
+ except subprocess.CalledProcessError:
+ if xvfb.poll() is not None or attempt == 49:
+ raise RuntimeError(f"Virtual display failed; see {output / 'xvfb.log'}")
+ time.sleep(0.1)
+
+ app = subprocess.Popen(
+ ["dbus-run-session", "--", str(args.binary.resolve())],
+ env=env, stdout=(output / "app.log").open("w"),
+ stderr=subprocess.STDOUT, start_new_session=True,
+ )
+ pill = None
+ for _ in range(60):
+ time.sleep(0.25)
+ if app.poll() is not None:
+ break
+ try:
+ windows = command("xdotool", "search", "--onlyvisible", "--name", "^Coucou$").splitlines()
+ except subprocess.CalledProcessError:
+ continue
+ for window in windows:
+ geometry = dict(
+ line.split("=", 1)
+ for line in command("xdotool", "getwindowgeometry", "--shell", window).splitlines()
+ )
+ if int(geometry["WIDTH"]) == 520 and int(geometry["HEIGHT"]) == 170:
+ pill = window
+ break
+ if pill:
+ break
+ if not pill:
+ raise RuntimeError(f"Pill window not found; see {output / 'app.log'}")
+
+ x, y, width, height = (int(geometry[key]) for key in ["X", "Y", "WIDTH", "HEIGHT"])
+ command("xdotool", "mousemove", 30, 30)
+ for attempt in range(100):
+ # Mapping the GTK window precedes the async webview boot. Wait for the
+ # resting capsule itself instead of assuming a fixed startup time.
+ if capture(pill, "ready", offset=5) > 0:
+ break
+ if attempt == 99:
+ raise RuntimeError(f"The pill did not finish loading; see {output / 'app.log'}")
+ time.sleep(0.1)
+ time.sleep(0.6)
+ assert capture(pill, "resting") == 0, "Toolbar should start collapsed"
+ for attempt in range(5):
+ command("xdotool", "mousemove", x + width // 2, y + height - 5)
+ time.sleep(0.6)
+ assert capture(pill, f"open-{attempt}") > 0, "Toolbar did not open"
+ command("xdotool", "mousemove", 30, 30)
+ time.sleep(0.9)
+ assert capture(pill, f"closed-{attempt}") == 0, (
+ "Toolbar stayed expanded after mouse exit with leave event suppressed"
+ )
+ print(f"Captures: {output}", flush=True)
+ print("PASS: five mouse exits collapsed the toolbar despite lost leave events", flush=True)
+finally:
+ if app and app.poll() is None:
+ os.killpg(app.pid, signal.SIGTERM)
+ try:
+ app.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ os.killpg(app.pid, signal.SIGKILL)
+ app.wait(timeout=5)
+ xvfb.terminate()
+ xvfb.wait(timeout=5)
+ runtime.cleanup()
diff --git a/windows/src-tauri/src/flow/mod.rs b/windows/src-tauri/src/flow/mod.rs
index 3f77842f..894a954c 100644
--- a/windows/src-tauri/src/flow/mod.rs
+++ b/windows/src-tauri/src/flow/mod.rs
@@ -669,6 +669,10 @@ pub fn pill_hover(app: AppHandle, inside: bool) {
if let Some(p) = pill::get(&app) {
p.hovered.store(inside, Ordering::Relaxed);
}
+ #[cfg(target_os = "linux")]
+ if inside {
+ pill::watch_pointer_leave(&app);
+ }
}
#[tauri::command]
diff --git a/windows/src-tauri/src/flow/pill.rs b/windows/src-tauri/src/flow/pill.rs
index 21de293b..5aded2a6 100644
--- a/windows/src-tauri/src/flow/pill.rs
+++ b/windows/src-tauri/src/flow/pill.rs
@@ -65,6 +65,8 @@ pub struct Pill {
shown: AtomicBool,
/// The pointer is on the pill or its bubble: a message waits for it to leave.
pub hovered: AtomicBool,
+ #[cfg(target_os = "linux")]
+ pointer_watch: AtomicBool,
/// Parks the Windows cursor poll while the pill is hidden.
poll: (Mutex<bool>, Condvar),
announce_seq: std::sync::atomic::AtomicU64,
@@ -134,6 +136,8 @@ pub fn setup(app: &AppHandle) {
hot: Mutex::new(Vec::new()),
shown: AtomicBool::new(false),
hovered: AtomicBool::new(false),
+ #[cfg(target_os = "linux")]
+ pointer_watch: AtomicBool::new(false),
poll: (Mutex::new(false), Condvar::new()),
announce_seq: std::sync::atomic::AtomicU64::new(1),
});
@@ -152,6 +156,52 @@ pub fn get(app: &AppHandle) -> Option<Arc<Pill>> {
app.try_state::<Arc<Pill>>().map(|s| s.inner().clone())
}
+/// WebKitGTK can miss pointerleave when the window's input region changes.
+/// Check GTK's pointer focus while hovered, as the island does, and park the
+/// timer as soon as the page folds the toolbar or the pill is hidden.
+#[cfg(target_os = "linux")]
+pub fn watch_pointer_leave(app: &AppHandle) {
+ use gtk::prelude::*;
+
+ let Some(pill) = get(app) else { return };
+ if pill.pointer_watch.swap(true, Ordering::Relaxed) {
+ return;
+ }
+ let app_for_watch = app.clone();
+ let watched = pill.clone();
+ if app.run_on_main_thread(move || {
+ let Some(win) = window(&app_for_watch) else {
+ watched.pointer_watch.store(false, Ordering::Relaxed);
+ return;
+ };
+ let Ok(gw) = win.gtk_window() else {
+ watched.pointer_watch.store(false, Ordering::Relaxed);
+ return;
+ };
+ gtk::glib::timeout_add_local(Duration::from_millis(100), move || {
+ if !watched.shown.load(Ordering::Relaxed)
+ || !watched.hovered.load(Ordering::Relaxed)
+ || !gw.is_visible()
+ {
+ watched.pointer_watch.store(false, Ordering::Relaxed);
+ return gtk::glib::ControlFlow::Break;
+ }
+ if let (Some(ours), Some(pointer)) = (
+ gw.window(),
+ gtk::gdk::Display::default().and_then(|d| d.default_seat()).and_then(|s| s.pointer()),
+ ) {
+ let (under, _, _) = pointer.window_at_position();
+ if !under.is_some_and(|w| w.toplevel() == ours.toplevel()) {
+ let _ = win.emit("pill-pointer", false);
+ }
+ }
+ gtk::glib::ControlFlow::Continue
+ });
+ }).is_err() {
+ pill.pointer_watch.store(false, Ordering::Relaxed);
+ }
+}
+
fn window(app: &AppHandle) -> Option<WebviewWindow> {
app.get_webview_window(LABEL)
}