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.

Linux: "Open terminal" brings the session's own window forward

Claude574deec5b5e2
diff --git a/windows/Cargo.lock b/windows/Cargo.lock
index 777a49ea..02343119 100644
--- a/windows/Cargo.lock
+++ b/windows/Cargo.lock
@@ -612,6 +612,7 @@ dependencies = [
name = "coucou"
version = "0.2.0"
dependencies = [
+ "dbus",
"gtk",
"keyring",
"libc",
@@ -627,6 +628,7 @@ dependencies = [
"webview2-com",
"windows 0.61.3",
"windows-core 0.62.2",
+ "x11rb",
]
[[package]]
diff --git a/windows/README.md b/windows/README.md
index cf48b882..dcb73724 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -397,7 +397,8 @@ own window.
process to the terminal or editor that runs it. A session in a classic
console window (`cmd.exe` or PowerShell without Windows Terminal) has no such
ancestor — conhost owns that window — so its folder opens in VS Code instead,
- as it does when `code` is on your `PATH` and nothing was found.
+ as it does when `code` is on your `PATH` and nothing was found. Linux walks
+ the same tree; what it can bring forward depends on the desktop (see Linux).
- No global keyboard shortcuts yet: a waiting card is folded with its **⌃** or
`Esc` in the island, and reopened by clicking the island or Open in the tray.
- Apple Music, the one pill from the Mac catalog with nothing behind it here,
@@ -553,7 +554,20 @@ What changes on Linux:
where it is missing, the island says so and Save still works.
- What the Windows build leaves out, this one does too: sending a file by
email and dragging Mochi onto a window.
-- **Open terminal** opens the folder in VS Code: Wayland lets no app bring
- another app's window forward, and X11 would need a window-manager client this
- build doesn't carry.
+- **Open terminal** walks up from the relay through `/proc` (stopping at
+ systemd, logins, ssh, session managers and panels, and at any process of
+ another user) to the terminal or editor the session runs in, then brings its
+ window forward — the one titled after the session's folder if it has several:
+ - **X11** (any desktop): EWMH — the window whose `_NET_WM_PID` is the nearest
+ ancestor gets a `_NET_ACTIVE_WINDOW` request, on its workspace. A terminal
+ that doesn't set `_NET_WM_PID` (some old `xterm` builds) isn't found.
+ - **KDE Plasma on Wayland**: a few lines of KWin script, loaded over D-Bus
+ from `$XDG_RUNTIME_DIR`, activate the window by process ID and are unloaded
+ right after; Plasma 5 and 6.
+ - **kitty**, anywhere: its tab is selected too when remote control listens on
+ a socket (`allow_remote_control` and `listen_on` in kitty.conf).
+ - **GNOME on Wayland** and other Wayland compositors let no app bring another
+ app's native window forward (an XWayland one, such as VS Code's by default,
+ still can be). There, and for a session under tmux, screen or ssh, whose
+ terminal is no ancestor, the folder opens in VS Code as before.
- No **Claude Desktop** pill: the Claude app has no Linux build.
diff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.toml
index 741b0081..ba601355 100644
--- a/windows/src-tauri/Cargo.toml
+++ b/windows/src-tauri/Cargo.toml
@@ -50,3 +50,8 @@ libc = "0.2"
# The GTK that Tauri already runs on, to reach its window for layer-shell and
# the input region. libgtk-layer-shell itself is called directly (platform/linux.rs).
gtk = "0.18"
+# "Open terminal" (platform/linux_focus.rs): KWin's scripting over D-Bus, and
+# EWMH on X11. Both already in the tree (keyring, global-hotkey): nothing new
+# to download or build.
+dbus = "0.9.12"
+x11rb = { version = "0.13", default-features = false }
diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs
index 3667b5e8..6d2c70c6 100644
--- a/windows/src-tauri/src/lib.rs
+++ b/windows/src-tauri/src/lib.rs
@@ -222,17 +222,33 @@ fn open_in_vscode(path: Option<String>) -> bool {
}
/// "Open terminal": brings forward the terminal or editor window the session
-/// runs in, when it was found (Windows, see session_window.rs); otherwise opens
-/// the folder in VS Code, as before.
+/// runs in, when it was found (see session_window.rs); otherwise opens the
+/// folder in VS Code, as before.
#[tauri::command]
fn open_session(session_id: Option<String>, path: Option<String>) -> bool {
- if let Some(owner) = session_id.as_deref().and_then(session_window::lookup) {
- let folder = path.as_deref().map(session_window::folder_name).unwrap_or_default();
- if platform::focus_process_window(owner, folder) {
+ let Some(owners) = session_id.as_deref().and_then(session_window::lookup) else {
+ return open_in_vscode(path);
+ };
+ let folder = path.as_deref().map(session_window::folder_name).unwrap_or_default().to_string();
+ #[cfg(windows)]
+ {
+ if platform::focus_session_window(&owners, &folder) {
return true;
}
+ open_in_vscode(path)
+ }
+ // Linux asks the display server, KWin or the terminal, which can take a
+ // moment: never on the UI thread a sync command runs on. VS Code still
+ // opens when none of them could bring the window forward.
+ #[cfg(target_os = "linux")]
+ {
+ std::thread::spawn(move || {
+ if !platform::focus_session_window(&owners, &folder) {
+ open_in_vscode(path);
+ }
+ });
+ true
}
- open_in_vscode(path)
}
/// The Claude Desktop pill's target: the Claude app (Windows only — it has no
diff --git a/windows/src-tauri/src/pipe.rs b/windows/src-tauri/src/pipe.rs
index e668728d..2a6a1d12 100644
--- a/windows/src-tauri/src/pipe.rs
+++ b/windows/src-tauri/src/pipe.rs
@@ -174,7 +174,13 @@ impl Relay for NamedPipeServer {
/// Dropping the stream closes it; the relay reads up to our newline first.
#[cfg(target_os = "linux")]
-impl Relay for tokio::net::UnixStream {}
+impl Relay for tokio::net::UnixStream {
+ /// SO_PEERCRED: the process that connected, as the kernel saw it.
+ fn client_pid(&self) -> Option<u32> {
+ let pid = self.peer_cred().ok()?.pid()?;
+ u32::try_from(pid).ok().filter(|pid| *pid > 1)
+ }
+}
async fn handle(app: AppHandle, mut pipe: impl Relay) {
let mut buf = Vec::new();
@@ -263,8 +269,7 @@ fn note_session_window(pipe: &impl Relay, payload: &Value, event: &str) {
// No ancestors: the relay was already gone, so try again next time. Some,
// but none with a window (a classic console): settled, VS Code it is.
if !ancestors.is_empty() {
- let owner = crate::platform::first_with_window(&ancestors);
- session_window::remember(session, owner.unwrap_or(session_window::NO_WINDOW));
+ session_window::remember(session, crate::platform::window_owners(&ancestors));
}
}
diff --git a/windows/src-tauri/src/platform/linux.rs b/windows/src-tauri/src/platform/linux.rs
index 38dff741..ac9941dd 100644
--- a/windows/src-tauri/src/platform/linux.rs
+++ b/windows/src-tauri/src/platform/linux.rs
@@ -261,22 +261,8 @@ pub fn find_on_path(stem: &str) -> Option<PathBuf> {
// ── Session windows ("Open terminal") ─────────────────────────────────────────
//
-// Wayland lets no app raise another app's window, and X11 would need a window
-// manager protocol client this build does not carry, so "Open terminal" opens
-// the folder in VS Code here, as before. There is no Claude desktop app for
-// Linux either.
-
-pub fn process_ancestors(_pid: u32) -> Vec<u32> {
- Vec::new()
-}
-
-pub fn first_with_window(_pids: &[u32]) -> Option<u32> {
- None
-}
-
-pub fn focus_process_window(_pid: u32, _folder: &str) -> bool {
- false
-}
+// Finding and raising a session's window lives in linux_focus.rs. There is no
+// Claude desktop app for Linux.
pub fn open_claude_desktop() -> bool {
false
diff --git a/windows/src-tauri/src/platform/linux_focus.rs b/windows/src-tauri/src/platform/linux_focus.rs
new file mode 100644
index 00000000..1f5176b8
--- /dev/null
+++ b/windows/src-tauri/src/platform/linux_focus.rs
@@ -0,0 +1,565 @@
+// Linux "Open terminal": bringing a session's terminal or editor window forward.
+//
+// session_window.rs keeps, per session, the relay's ancestors read from /proc
+// (nearest first). When the button is clicked, the window one of them owns is
+// brought forward by the best way the desktop offers:
+// * KDE Plasma on Wayland: a tiny KWin script, loaded over D-Bus, finds the
+// window by process ID, activates it, reports back and is unloaded;
+// * an X11 session (or an XWayland window): EWMH — `_NET_CLIENT_LIST` and
+// `_NET_WM_PID` to find it, a `_NET_ACTIVE_WINDOW` request to the window
+// manager to raise it, over the x11rb that global-hotkey already brings;
+// * kitty, whatever the session, also selects the session's tab when its
+// remote control listens on a socket.
+// GNOME on Wayland has no such door for native windows: nothing is found, and
+// the caller opens the folder in VS Code as before.
+//
+// Everything handed to a script or a command is a number read from /proc of a
+// process we found ourselves (or our own D-Bus name, checked); nothing from a
+// hook payload. Commands get their arguments one by one, never through a shell.
+// This all runs off the UI thread (lib.rs `open_session`).
+
+use std::collections::HashMap;
+use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use crate::session_window::{self, Proc};
+
+// ── The process tree ──────────────────────────────────────────────────────────
+
+/// One process of ours: its parent and name from /proc. PID 1 and processes of
+/// another user (sshd, a display manager, sudo) are not ours, which ends any
+/// walk there.
+fn read_proc(pid: u32, uid: u32) -> Option<Proc> {
+ if pid <= 1 {
+ return None;
+ }
+ let dir = format!("/proc/{pid}");
+ if std::fs::metadata(&dir).ok()?.uid() != uid {
+ return None;
+ }
+ let stat = std::fs::read_to_string(format!("{dir}/stat")).ok()?;
+ let (exe, parent) = session_window::parse_stat(&stat)?;
+ Some(Proc { parent, exe })
+}
+
+fn my_uid() -> u32 {
+ unsafe { libc::getuid() }
+}
+
+/// The ancestors of a process, nearest first, below the top of the tree.
+pub fn process_ancestors(pid: u32) -> Vec<u32> {
+ let uid = my_uid();
+ let mut procs = HashMap::new();
+ let mut current = pid;
+ // The relay, its ancestors, and the one that ends the walk.
+ for _ in 0..session_window::MAX_DEPTH + 2 {
+ let Some(p) = read_proc(current, uid) else { break };
+ let parent = p.parent;
+ procs.insert(current, p);
+ if procs.contains_key(&parent) {
+ break;
+ }
+ current = parent;
+ }
+ session_window::ancestors(&procs, pid)
+}
+
+/// What a session remembers: every ancestor. Which one owns a window is asked
+/// when the button is clicked.
+pub fn window_owners(ancestors: &[u32]) -> Vec<u32> {
+ ancestors.to_vec()
+}
+
+/// The remembered ancestors still alive and still each other's parents, with
+/// their names: a closed terminal's IDs may since belong to someone else.
+fn still_linked(owners: &[u32]) -> Vec<(u32, String)> {
+ let uid = my_uid();
+ let procs: Vec<Option<Proc>> = owners.iter().map(|pid| read_proc(*pid, uid)).collect();
+ linked_chain(owners, &procs)
+}
+
+/// `procs[i]` is what /proc says now of `owners[i]`. The nearest ones may have
+/// exited — the `sh -c` that ran the relay does — so the chain starts at the
+/// first one alive and still the child of the next, and ends where a process
+/// is gone or its parent is no longer the next one.
+fn linked_chain(owners: &[u32], procs: &[Option<Proc>]) -> Vec<(u32, String)> {
+ let linked = |i: usize| {
+ procs[i].as_ref().is_some_and(|p| owners.get(i + 1).is_none_or(|next| p.parent == *next))
+ };
+ let Some(start) = (0..owners.len().min(procs.len())).find(|i| linked(*i)) else { return Vec::new() };
+ let mut out = Vec::new();
+ for i in start..owners.len().min(procs.len()) {
+ let Some(p) = &procs[i] else { break };
+ out.push((owners[i], p.exe.clone()));
+ if !linked(i) {
+ break;
+ }
+ }
+ out
+}
+
+// ── Bringing the window forward ───────────────────────────────────────────────
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Method {
+ KWin,
+ X11,
+}
+
+/// Best first. On Plasma's Wayland session KWin sees every window, native or
+/// XWayland; elsewhere EWMH is the standard way, with KWin's script as a
+/// second try on Plasma's X11 session.
+fn methods(session_type: &str, wayland_display: &str, display: &str, desktop: &str) -> Vec<Method> {
+ let wayland = session_type.eq_ignore_ascii_case("wayland") || !wayland_display.trim().is_empty();
+ let x11 = !display.trim().is_empty();
+ let kde = desktop.split(':').any(|d| d.eq_ignore_ascii_case("kde"));
+ let mut out = Vec::new();
+ if kde && wayland {
+ out.push(Method::KWin);
+ }
+ if x11 {
+ out.push(Method::X11);
+ }
+ if kde && !wayland {
+ out.push(Method::KWin);
+ }
+ out
+}
+
+/// Brings forward the window a session remembered: the nearest ancestor's,
+/// the one titled after `folder` if it has several. False when no way worked,
+/// so the caller falls back to VS Code.
+pub fn focus_session_window(owners: &[u32], folder: &str) -> bool {
+ let chain = still_linked(owners);
+ if chain.is_empty() {
+ return false;
+ }
+ let pids: Vec<u32> = chain.iter().map(|(pid, _)| *pid).collect();
+ let tab = kitty::focus_tab(&chain);
+ let env = |k: &str| std::env::var(k).unwrap_or_default();
+ let raised = methods(
+ &env("XDG_SESSION_TYPE"),
+ &env("WAYLAND_DISPLAY"),
+ &env("DISPLAY"),
+ &env("XDG_CURRENT_DESKTOP"),
+ )
+ .into_iter()
+ .any(|method| {
+ let done = match method {
+ Method::KWin => kwin::activate(&pids, folder),
+ Method::X11 => x11::activate(&pids, folder),
+ };
+ if done {
+ crate::log::line(format!("open terminal: window raised ({method:?})"));
+ }
+ done
+ });
+ tab || raised
+}
+
+/// Runs a helper with nothing attached and a time limit; true when it exits 0.
+fn run_quietly(cmd: &mut Command, limit: Duration) -> bool {
+ let Ok(mut child) = cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else {
+ return false;
+ };
+ let deadline = Instant::now() + limit;
+ loop {
+ match child.try_wait() {
+ Ok(Some(status)) => return status.success(),
+ Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)),
+ _ => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return false;
+ }
+ }
+ }
+}
+
+// ── X11: EWMH ─────────────────────────────────────────────────────────────────
+
+mod x11 {
+ use x11rb::connection::Connection;
+ use x11rb::protocol::xproto::{AtomEnum, ClientMessageEvent, ConnectionExt, EventMask, Window};
+ use x11rb::rust_connection::RustConnection;
+
+ use crate::session_window;
+
+ type Fallible<T> = Result<T, Box<dyn std::error::Error>>;
+
+ pub fn activate(ancestors: &[u32], folder: &str) -> bool {
+ try_activate(ancestors, folder).unwrap_or(false)
+ }
+
+ fn atom(conn: &RustConnection, name: &str) -> Fallible<u32> {
+ Ok(conn.intern_atom(false, name.as_bytes())?.reply()?.atom)
+ }
+
+ fn cardinal(conn: &RustConnection, window: Window, prop: u32) -> Option<u32> {
+ let reply = conn.get_property(false, window, prop, AtomEnum::CARDINAL, 0, 1).ok()?.reply().ok()?;
+ let value = reply.value32()?.next();
+ value
+ }
+
+ /// `_NET_WM_NAME` (UTF-8), else the legacy `WM_NAME`.
+ fn title(conn: &RustConnection, window: Window, net_wm_name: u32, utf8: u32) -> String {
+ let read = |prop: u32, kind: u32| {
+ conn.get_property(false, window, prop, kind, 0, 1024)
+ .ok()
+ .and_then(|c| c.reply().ok())
+ .map(|r| String::from_utf8_lossy(&r.value).into_owned())
+ .filter(|t| !t.is_empty())
+ };
+ read(net_wm_name, utf8)
+ .or_else(|| read(AtomEnum::WM_NAME.into(), AtomEnum::STRING.into()))
+ .unwrap_or_default()
+ }
+
+ fn try_activate(ancestors: &[u32], folder: &str) -> Fallible<bool> {
+ let (conn, screen) = x11rb::connect(None)?;
+ let root = conn.setup().roots.get(screen).ok_or("no screen")?.root;
+ let client_list = atom(&conn, "_NET_CLIENT_LIST")?;
+ let wm_pid = atom(&conn, "_NET_WM_PID")?;
+ let net_wm_name = atom(&conn, "_NET_WM_NAME")?;
+ let utf8 = atom(&conn, "UTF8_STRING")?;
+ let active = atom(&conn, "_NET_ACTIVE_WINDOW")?;
+ let wm_desktop = atom(&conn, "_NET_WM_DESKTOP")?;
+ let current_desktop = atom(&conn, "_NET_CURRENT_DESKTOP")?;
+
+ let clients: Vec<Window> = conn
+ .get_property(false, root, client_list, AtomEnum::WINDOW, 0, 4096)?
+ .reply()?
+ .value32()
+ .map(|v| v.collect())
+ .unwrap_or_default();
+ // Every window's process in one round trip; a window gone meanwhile is skipped.
+ let cookies: Vec<_> = clients
+ .iter()
+ .map(|w| conn.get_property(false, *w, wm_pid, AtomEnum::CARDINAL, 0, 1))
+ .collect::<Result<_, _>>()?;
+ let mut windows: Vec<(Window, u32, String)> = Vec::new();
+ for (window, cookie) in clients.iter().zip(cookies) {
+ let Ok(reply) = cookie.reply() else { continue };
+ let pid = reply.value32().and_then(|mut v| v.next());
+ let Some(pid) = pid else { continue };
+ if ancestors.contains(&pid) {
+ windows.push((*window, pid, title(&conn, *window, net_wm_name, utf8)));
+ }
+ }
+ let Some(&target) = session_window::choose_window(ancestors, &windows, folder) else {
+ return Ok(false);
+ };
+
+ let to_root = EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY;
+ // Its workspace first, for the window managers that won't switch on their own.
+ if let Some(desktop) = cardinal(&conn, target, wm_desktop).filter(|d| *d != u32::MAX) {
+ let ev = ClientMessageEvent::new(32, root, current_desktop, [desktop, 0, 0, 0, 0]);
+ conn.send_event(false, root, to_root, ev)?;
+ }
+ // Source 2: a pager acting for the user, which window managers honour
+ // over their focus-stealing prevention. Timestamp 0: "now".
+ let ev = ClientMessageEvent::new(32, target, active, [2, 0, 0, 0, 0]);
+ conn.send_event(false, root, to_root, ev)?;
+ conn.flush()?;
+ Ok(true)
+ }
+}
+
+// ── KDE Plasma: a KWin script over D-Bus ──────────────────────────────────────
+
+mod kwin {
+ use std::io::Write;
+ use std::sync::atomic::{AtomicU32, AtomicU8, Ordering};
+ use std::sync::Arc;
+
+ use dbus::blocking::Connection;
+ use dbus::channel::MatchingReceiver;
+ use dbus::message::MatchRule;
+
+ use super::*;
+
+ /// Where the script says what it did: our own connection, this interface.
+ const REPLY_INTERFACE: &str = "fr.louisraille.Coucou.Focus";
+ const KWIN: &str = "org.kde.KWin";
+ const TIMEOUT: Duration = Duration::from_secs(2);
+
+ static COUNTER: AtomicU32 = AtomicU32::new(0);
+
+ /// A unique bus name as the bus hands it out (`:1.42`), nothing else: it is
+ /// the one string the script holds.
+ fn is_unique_name(name: &str) -> bool {
+ let Some(rest) = name.strip_prefix(':') else { return false };
+ let mut parts = rest.split('.');
+ let ok = |p: Option<&str>| p.is_some_and(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()));
+ ok(parts.next()) && ok(parts.next()) && parts.next().is_none()
+ }
+
+ /// The script: finds the windows of the nearest ancestor that has any —
+ /// the one whose caption names the folder, else the first — activates it,
+ /// and calls `reply_to` back with `Activated` or `NotFound`. Process IDs
+ /// are numbers and the folder name travels as character codes, so nothing
+ /// in it can be read as code. Works on Plasma 6 (`windowList`,
+ /// `activeWindow`) and Plasma 5 (`clientList`, `activeClient`).
+ pub(super) fn script(pids: &[u32], folder: &str, reply_to: &str) -> Option<String> {
+ if !is_unique_name(reply_to) || pids.is_empty() {
+ return None;
+ }
+ let pids = pids.iter().map(u32::to_string).collect::<Vec<_>>().join(", ");
+ let folder = folder.to_lowercase().encode_utf16().map(|c| c.to_string()).collect::<Vec<_>>().join(", ");
+ Some(format!(
+ r#"(function () {{
+ var pids = [{pids}];
+ var folder = String.fromCharCode({folder});
+ var plasma6 = typeof workspace.windowList === "function";
+ var windows = plasma6 ? workspace.windowList() : workspace.clientList();
+ var found = null;
+ for (var i = 0; i < pids.length && !found; i++) {{
+ var first = null;
+ for (var j = 0; j < windows.length; j++) {{
+ var w = windows[j];
+ if (w.pid !== pids[i] || !w.normalWindow) continue;
+ if (!first) first = w;
+ if (folder && String(w.caption).toLowerCase().indexOf(folder) >= 0) {{ found = w; break; }}
+ }}
+ if (!found) found = first;
+ }}
+ if (found) {{
+ if (found.minimized) found.minimized = false;
+ if (plasma6) workspace.activeWindow = found; else workspace.activeClient = found;
+ }}
+ callDBus("{reply_to}", "/", "{REPLY_INTERFACE}", found ? "Activated" : "NotFound");
+}})();
+"#
+ ))
+ }
+
+ /// Unloads the script and removes its file, whatever happened.
+ struct Loaded<'a> {
+ conn: &'a Connection,
+ name: String,
+ path: PathBuf,
+ }
+
+ impl Drop for Loaded<'_> {
+ fn drop(&mut self) {
+ let proxy = self.conn.with_proxy(KWIN, "/Scripting", TIMEOUT);
+ let _: Result<(bool,), _> = proxy.method_call("org.kde.kwin.Scripting", "unloadScript", (self.name.as_str(),));
+ let _ = std::fs::remove_file(&self.path);
+ }
+ }
+
+ /// The runtime directory, checked private, where the script file is written.
+ fn script_dir() -> Option<PathBuf> {
+ super::super::relay_socket_path()?.parent().map(Path::to_path_buf)
+ }
+
+ pub fn activate(pids: &[u32], folder: &str) -> bool {
+ let Ok(conn) = Connection::new_session() else { return false };
+ let reply_to = conn.unique_name().to_string();
+ let Some(text) = script(pids, folder, &reply_to) else { return false };
+ let Some(dir) = script_dir() else { return false };
+
+ // 0 unanswered, 1 activated, 2 not found.
+ let outcome = Arc::new(AtomicU8::new(0));
+ let seen = outcome.clone();
+ conn.start_receive(
+ MatchRule::new_method_call(),
+ Box::new(move |msg, c| {
+ if msg.interface().as_deref() == Some(REPLY_INTERFACE) {
+ let result = if msg.member().as_deref() == Some("Activated") { 1 } else { 2 };
+ seen.store(result, Ordering::SeqCst);
+ let _ = dbus::channel::Sender::send(c, msg.method_return());
+ }
+ true
+ }),
+ );
+
+ let name = format!("coucou-focus-{}-{}", std::process::id(), COUNTER.fetch_add(1, Ordering::Relaxed));
+ let path = dir.join(format!("{name}.js"));
+ let written = std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o600)
+ .open(&path)
+ .and_then(|mut f| f.write_all(text.as_bytes()));
+ if written.is_err() {
+ let _ = std::fs::remove_file(&path);
+ return false;
+ }
+ let loaded = Loaded { conn: &conn, name, path };
+
+ let scripting = conn.with_proxy(KWIN, "/Scripting", TIMEOUT);
+ let Some(path_str) = loaded.path.to_str() else { return false };
+ let id: i32 = match scripting.method_call("org.kde.kwin.Scripting", "loadScript", (path_str, loaded.name.as_str())) {
+ Ok((id,)) => id,
+ Err(_) => return false,
+ };
+ if id < 0 {
+ return false;
+ }
+ // Plasma 6 puts the script at /Scripting/Script<id>, Plasma 5 at /<id>.
+ let run = |path: String| {
+ conn.with_proxy(KWIN, path, TIMEOUT).method_call::<(), _, _, _>("org.kde.kwin.Script", "run", ())
+ };
+ if run(format!("/Scripting/Script{id}")).is_err() && run(format!("/{id}")).is_err() {
+ return false;
+ }
+
+ // KWin reads the file and runs it on its own time; wait for the answer.
+ let deadline = Instant::now() + TIMEOUT;
+ while outcome.load(Ordering::SeqCst) == 0 && Instant::now() < deadline {
+ let _ = conn.process(Duration::from_millis(50));
+ }
+ let activated = outcome.load(Ordering::SeqCst) == 1;
+ drop(loaded);
+ activated
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn only_a_bus_unique_name_is_put_in_the_script() {
+ assert!(is_unique_name(":1.42"));
+ assert!(is_unique_name(":12.3456"));
+ for bad in ["", ":", ":1", ":1.", ":.1", "1.42", ":1.42.3", ":1.4a", "org.kde.KWin", ":1.42\"); x(\""] {
+ assert!(!is_unique_name(bad), "{bad}");
+ }
+ assert!(script(&[1], "x", "org.kde.KWin").is_none());
+ assert!(script(&[], "x", ":1.2").is_none());
+ }
+
+ #[test]
+ fn the_script_holds_numbers_only() {
+ let text = script(&[4242, 17], "Café \"); evil(); //", ":1.42").unwrap();
+ assert!(text.contains("var pids = [4242, 17];"));
+ // The folder travels as UTF-16 codes, lower-cased: no quote, no word of it.
+ assert!(text.contains("String.fromCharCode(99, 97, 102, 233, 32, 34, 41, 59, 32"));
+ assert!(!text.contains("evil"));
+ assert!(text.contains(r#"callDBus(":1.42", "/", "fr.louisraille.Coucou.Focus""#));
+ // Apart from the code itself, every quoted string is one we wrote.
+ let quoted: Vec<&str> = text.split('"').skip(1).step_by(2).collect();
+ assert_eq!(quoted, ["function", ":1.42", "/", "fr.louisraille.Coucou.Focus", "Activated", "NotFound"]);
+
+ let empty = script(&[1], "", ":1.2").unwrap();
+ assert!(empty.contains("String.fromCharCode();"));
+ assert!(empty.contains("workspace.activeWindow = found") && empty.contains("workspace.activeClient = found"));
+ }
+ }
+}
+
+// ── kitty: the session's tab ──────────────────────────────────────────────────
+
+mod kitty {
+ use super::*;
+
+ /// `KITTY_LISTEN_ON` from a process environment (NUL-separated), when it is
+ /// a Unix socket address made of plain path characters.
+ pub(super) fn listen_on(environ: &[u8]) -> Option<String> {
+ let value = environ
+ .split(|b| *b == 0)
+ .find_map(|entry| entry.strip_prefix(b"KITTY_LISTEN_ON="))?;
+ let value = std::str::from_utf8(value).ok()?;
+ let path = value.strip_prefix("unix:")?;
+ let plain = |c: char| c.is_ascii_alphanumeric() || "/_.-@+:".contains(c);
+ (!path.is_empty() && path.len() <= 107 && path.chars().all(plain)).then(|| value.to_string())
+ }
+
+ /// `kitten` beside the running kitty, else on $PATH.
+ fn kitten(kitty_pid: u32) -> Option<PathBuf> {
+ let beside = std::fs::read_link(format!("/proc/{kitty_pid}/exe"))
+ .ok()
+ .and_then(|exe| exe.parent().map(|d| d.join("kitten")));
+ beside
+ .filter(|p| std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0))
+ .or_else(|| super::super::find_on_path("kitten"))
+ }
+
+ /// When the session runs in kitty and kitty's remote control listens on a
+ /// socket (`listen_on` and `allow_remote_control`), focuses the session's
+ /// tab and window. Quietly nothing otherwise.
+ pub fn focus_tab(chain: &[(u32, String)]) -> bool {
+ let Some(at) = chain.iter().position(|(_, name)| name == "kitty") else { return false };
+ let Some((shell, _)) = at.checked_sub(1).and_then(|i| chain.get(i)) else { return false };
+ let kitty_pid = chain[at].0;
+ let Ok(environ) = std::fs::read(format!("/proc/{shell}/environ")) else { return false };
+ let Some(to) = listen_on(&environ) else { return false };
+ let Some(kitten) = kitten(kitty_pid) else { return false };
+ run_quietly(
+ Command::new(kitten).args(["@", "--to", &to, "focus-window", "--match", &format!("pid:{shell}")]),
+ Duration::from_secs(2),
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_best_way_comes_first_for_each_desktop() {
+ use Method::*;
+ // Plasma on Wayland: KWin sees everything; XWayland as a second try.
+ assert_eq!(methods("wayland", "wayland-0", ":0", "KDE"), [KWin, X11]);
+ assert_eq!(methods("", "wayland-0", "", "KDE"), [KWin]);
+ // Plasma on X11: EWMH, then KWin.
+ assert_eq!(methods("x11", "", ":0", "KDE"), [X11, KWin]);
+ // Any X11 session.
+ assert_eq!(methods("x11", "", ":0", "XFCE"), [X11]);
+ // GNOME on Wayland: only XWayland windows can be reached.
+ assert_eq!(methods("wayland", "wayland-0", ":0", "ubuntu:GNOME"), [X11]);
+ assert_eq!(methods("wayland", "wayland-0", "", "GNOME"), []);
+ assert_eq!(methods("tty", "", "", ""), []);
+ }
+
+ #[test]
+ fn kitty_sockets_are_read_from_the_shell_environment() {
+ let env = b"HOME=/home/me\0KITTY_LISTEN_ON=unix:/tmp/kitty-4242\0TERM=xterm-kitty\0";
+ assert_eq!(kitty::listen_on(env).as_deref(), Some("unix:/tmp/kitty-4242"));
+ assert_eq!(kitty::listen_on(b"KITTY_LISTEN_ON=unix:@mykitty\0").as_deref(), Some("unix:@mykitty"));
+ // Not a socket of the expected shape: left alone.
+ assert_eq!(kitty::listen_on(b"KITTY_LISTEN_ON=tcp:localhost:5000\0"), None);
+ assert_eq!(kitty::listen_on(b"KITTY_LISTEN_ON=unix:/tmp/a b\0"), None);
+ assert_eq!(kitty::listen_on(b"KITTY_LISTEN_ON=unix:$(rm)\0"), None);
+ assert_eq!(kitty::listen_on(b"KITTY_LISTEN_ON=unix:\0"), None);
+ assert_eq!(kitty::listen_on(b"XKITTY_LISTEN_ON=unix:/x\0"), None);
+ assert_eq!(kitty::listen_on(b""), None);
+ }
+
+ #[test]
+ fn our_own_ancestors_are_read_from_proc() {
+ // This test process's parent is ours (cargo) or the walk stops above it:
+ // either way every ID found is a live process of ours, nearest first.
+ let me = std::process::id();
+ let found = process_ancestors(me);
+ let linked = still_linked(&found);
+ assert_eq!(linked.len(), found.len());
+ assert!(!found.contains(&me) && !found.contains(&1));
+ assert!(still_linked(&[u32::MAX - 1]).is_empty());
+ }
+
+ #[test]
+ fn a_chain_starts_past_exited_shells_and_ends_where_it_breaks() {
+ let p = |parent: u32, name: &str| Some(Proc { parent, exe: name.to_string() });
+ let names = |chain: Vec<(u32, String)>| chain.into_iter().map(|(pid, _)| pid).collect::<Vec<_>>();
+ // sh (gone) → claude → bash → kitty
+ let owners = [10, 20, 30, 40];
+ let alive = [None, p(30, "claude"), p(40, "bash"), p(1, "kitty")];
+ assert_eq!(names(linked_chain(&owners, &alive)), [20, 30, 40]);
+ assert_eq!(linked_chain(&owners, &alive)[2].1, "kitty");
+ // An ID reused by an unrelated process is not a start.
+ let reused = [p(999, "other"), p(30, "claude"), p(40, "bash"), p(1, "kitty")];
+ assert_eq!(names(linked_chain(&owners, &reused)), [20, 30, 40]);
+ // The terminal closed and its ID went to someone else: cut there.
+ let closed = [None, p(30, "claude"), p(40, "bash"), None];
+ assert_eq!(names(linked_chain(&owners, &closed)), [20, 30]);
+ let moved = [None, p(30, "claude"), p(77, "bash"), p(1, "kitty")];
+ assert_eq!(names(linked_chain(&owners, &moved)), [20, 30]);
+ // Nothing left.
+ assert!(linked_chain(&owners, &[None, None, None, None]).is_empty());
+ assert!(linked_chain(&[], &[]).is_empty());
+ }
+}
diff --git a/windows/src-tauri/src/platform/mod.rs b/windows/src-tauri/src/platform/mod.rs
index 73ce61f9..c26fb117 100644
--- a/windows/src-tauri/src/platform/mod.rs
+++ b/windows/src-tauri/src/platform/mod.rs
@@ -14,6 +14,11 @@ pub use self::windows::*;
mod linux;
#[cfg(target_os = "linux")]
pub use self::linux::*;
+// "Open terminal" on Linux: the process tree from /proc, then KWin, EWMH, kitty.
+#[cfg(target_os = "linux")]
+mod linux_focus;
+#[cfg(target_os = "linux")]
+pub use self::linux_focus::{focus_session_window, process_ancestors, window_owners};
/// Wall-clock time in the user's time zone, for log lines and backup names.
pub struct LocalTime {
diff --git a/windows/src-tauri/src/platform/windows.rs b/windows/src-tauri/src/platform/windows.rs
index 8e7efc07..1085da69 100644
--- a/windows/src-tauri/src/platform/windows.rs
+++ b/windows/src-tauri/src/platform/windows.rs
@@ -425,6 +425,11 @@ pub fn first_with_window(pids: &[u32]) -> Option<u32> {
pids.iter().copied().find(|pid| windows.iter().any(|(_, owner, _)| owner == pid))
}
+/// What a session remembers: the ancestor that owns a window, or nothing.
+pub fn window_owners(ancestors: &[u32]) -> Vec<u32> {
+ first_with_window(ancestors).into_iter().collect()
+}
+
fn bring_forward(raw: isize) -> bool {
let hwnd = HWND(raw as *mut _);
unsafe {
@@ -446,6 +451,11 @@ pub fn focus_process_window(pid: u32, folder: &str) -> bool {
session_window::pick_window(&candidates, folder).is_some_and(|hwnd| bring_forward(*hwnd))
}
+/// Brings forward the window a session remembered (`window_owners`).
+pub fn focus_session_window(owners: &[u32], folder: &str) -> bool {
+ owners.first().is_some_and(|pid| focus_process_window(*pid, folder))
+}
+
/// Brings forward the window of a running app, by executable name.
fn focus_app(exe: &str) -> bool {
let pids: Vec<u32> = process_table()
diff --git a/windows/src-tauri/src/session_window.rs b/windows/src-tauri/src/session_window.rs
index 8d094e1a..09688de1 100644
--- a/windows/src-tauri/src/session_window.rs
+++ b/windows/src-tauri/src/session_window.rs
@@ -9,11 +9,13 @@
// window belongs to a conhost that is no ancestor, or Linux — the island falls
// back to VS Code as before.
//
+// On Linux the same walk reads /proc. Which ancestor owns the window is only
+// asked when the button is clicked (the display server answers then, not from
+// the relay's thread), so every ancestor is kept, nearest first; on Windows
+// only the one that owns a window.
+//
// The OS calls live in platform/; this file is the logic, tested on fixtures.
-// The process-tree half only runs on Windows; Linux keeps the fallback.
-#![cfg_attr(not(windows), allow(dead_code))]
-
use std::collections::HashMap;
use std::sync::Mutex;
@@ -21,25 +23,60 @@ use std::sync::Mutex;
#[derive(Debug, Clone)]
pub struct Proc {
pub parent: u32,
- /// The executable's file name, as the snapshot gives it (`Code.exe`).
+ /// The executable's file name, as the snapshot gives it (`Code.exe`); on
+ /// Linux the process name from /proc (`gnome-terminal-`, at most 15 bytes).
pub exe: String,
}
/// Never the window of a session: the desktop shell and the services that sit
/// at the top of every process tree. Reaching one of them means the terminal
/// window was not an ancestor (a classic console window belongs to conhost).
-const TREE_TOPS: &[&str] = &[
+#[cfg_attr(not(windows), allow(dead_code))]
+const WINDOWS_TREE_TOPS: &[&str] = &[
"explorer.exe", "services.exe", "wininit.exe", "winlogon.exe", "svchost.exe",
"smss.exe", "csrss.exe", "system", "sihost.exe", "userinit.exe",
];
+/// The same on Linux, lower-cased and cut to the 15 bytes /proc keeps of a
+/// name: init and the user's service manager, logins (local, display manager,
+/// ssh), session managers, and the compositors, window managers and panels
+/// that own windows of their own — reaching one means the session's terminal
+/// was not an ancestor (tmux, screen, ssh), and raising the panel would be
+/// wrong. PID 1 and processes of other users end the walk anyway
+/// (platform/linux.rs leaves them out of the table).
+#[cfg_attr(windows, allow(dead_code))]
+const LINUX_TREE_TOPS: &[&str] = &[
+ "systemd", "init", "sshd", "sshd-session", "login", "su", "sudo", "doas",
+ "gdm-session-wor", "gdm-x-session", "gdm-wayland-ses", "sddm", "sddm-helper",
+ "lightdm", "lxdm-session", "greetd", "xinit", "xorg", "xwayland",
+ "dbus-daemon", "dbus-broker", "dbus-broker-lau",
+ "gnome-session-b", "gnome-session", "gnome-shell",
+ "startplasma-x11", "startplasma-way", "plasma_session", "ksmserver",
+ "plasmashell", "kwin_x11", "kwin_wayland",
+ "xfce4-session", "xfce4-panel", "xfdesktop", "xfwm4",
+ "cinnamon-sessio", "cinnamon", "cinnamon-launch", "mate-session", "mate-panel",
+ "marco", "lxsession", "lxqt-session", "lxqt-panel", "lxpanel", "openbox",
+ "budgie-wm", "budgie-panel", "cosmic-session", "cosmic-comp", "cosmic-panel",
+ "sway", "hyprland", "niri", "labwc", "wayfire", "river", "i3", "awesome",
+ "bspwm", "waybar",
+];
+
+#[cfg(windows)]
+const TREE_TOPS: &[&str] = WINDOWS_TREE_TOPS;
+#[cfg(not(windows))]
+const TREE_TOPS: &[&str] = LINUX_TREE_TOPS;
+
/// How far up we look. A session sits a handful of levels below its window.
-const MAX_DEPTH: usize = 16;
+pub const MAX_DEPTH: usize = 16;
/// The ancestors of `start`, nearest first, stopping before the top of the
/// tree. `start` itself — the relay — is not included. A loop in the parent
/// links (a parent ID reused by a newer process) ends the walk.
pub fn ancestors(procs: &HashMap<u32, Proc>, start: u32) -> Vec<u32> {
+ ancestors_below(procs, start, TREE_TOPS)
+}
+
+fn ancestors_below(procs: &HashMap<u32, Proc>, start: u32, tops: &[&str]) -> Vec<u32> {
let mut out = Vec::new();
let mut seen = vec![start];
let mut current = start;
@@ -50,7 +87,7 @@ pub fn ancestors(procs: &HashMap<u32, Proc>, start: u32) -> Vec<u32> {
break;
}
let Some(up) = procs.get(&parent) else { break };
- if TREE_TOPS.contains(&up.exe.to_ascii_lowercase().as_str()) {
+ if tops.contains(&up.exe.to_ascii_lowercase().as_str()) {
break;
}
out.push(parent);
@@ -65,7 +102,39 @@ pub fn ancestors(procs: &HashMap<u32, Proc>, start: u32) -> Vec<u32> {
/// rule the tests pin down.
#[cfg(test)]
pub fn window_owner(procs: &HashMap<u32, Proc>, start: u32, has_window: impl Fn(u32) -> bool) -> Option<u32> {
- ancestors(procs, start).into_iter().find(|pid| has_window(*pid))
+ ancestors_below(procs, start, WINDOWS_TREE_TOPS).into_iter().find(|pid| has_window(*pid))
+}
+
+/// `/proc/<pid>/stat` → (name, parent). The name sits between the first `(`
+/// and the LAST `)`: it may itself hold spaces and parentheses (`tmux: server`,
+/// `Web Content`, `a) b (c`), so splitting on spaces would misread the parent.
+#[cfg_attr(windows, allow(dead_code))]
+pub fn parse_stat(line: &str) -> Option<(String, u32)> {
+ let open = line.find('(')?;
+ let close = line.rfind(')')?;
+ if close < open {
+ return None;
+ }
+ let name = &line[open + 1..close];
+ let mut rest = line[close + 1..].split_ascii_whitespace();
+ let _state = rest.next()?;
+ let parent = rest.next()?.parse().ok()?;
+ Some((name.to_string(), parent))
+}
+
+/// Of the windows on screen — (window, owner process, title) — the one to
+/// bring forward: the windows of the nearest ancestor that has any, and among
+/// them the one titled after the session's folder (see `pick_window`).
+#[cfg_attr(windows, allow(dead_code))]
+pub fn choose_window<'a, W>(ancestors: &[u32], windows: &'a [(W, u32, String)], folder: &str) -> Option<&'a W> {
+ ancestors.iter().find_map(|pid| {
+ let mine: Vec<(&'a W, String)> = windows
+ .iter()
+ .filter(|(_, owner, _)| owner == pid)
+ .map(|(w, _, title)| (w, title.clone()))
+ .collect();
+ pick_window(&mine, folder).copied()
+ })
}
/// Which of a process's windows to bring forward: the one whose title names
@@ -85,15 +154,13 @@ pub fn folder_name(path: &str) -> &str {
// ── Sessions seen so far ──────────────────────────────────────────────────────
-/// Session ID → the process that owns its window. Small: an old session is
-/// dropped once there are more than this many.
+/// Session ID → the processes that may own its window, nearest first: the one
+/// that does on Windows, every ancestor on Linux. Empty for a session whose
+/// window could not be found, so it is not looked for on every event. Small:
+/// an old session is dropped once there are more than this many.
const MAX_SESSIONS: usize = 64;
-static SESSIONS: Mutex<Vec<(String, u32)>> = Mutex::new(Vec::new());
-
-/// Remembered for a session whose window could not be found, so it is not
-/// looked for on every event. No process has this ID.
-pub const NO_WINDOW: u32 = 0;
+static SESSIONS: Mutex<Vec<(String, Vec<u32>)>> = Mutex::new(Vec::new());
/// A session ID arrives in a hook payload: only what Claude Code sends (a
/// UUID) is kept, at most 128 characters.
@@ -101,13 +168,14 @@ fn valid_session(id: &str) -> bool {
!id.is_empty() && id.len() <= 128 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}
-pub fn remember(session: &str, owner: u32) {
+pub fn remember(session: &str, mut owners: Vec<u32>) {
if !valid_session(session) {
return;
}
+ owners.truncate(MAX_DEPTH);
let mut list = SESSIONS.lock().unwrap_or_else(|e| e.into_inner());
list.retain(|(s, _)| s != session);
- list.push((session.to_string(), owner));
+ list.push((session.to_string(), owners));
let excess = list.len().saturating_sub(MAX_SESSIONS);
list.drain(..excess);
}
@@ -118,10 +186,10 @@ pub fn known(session: &str) -> bool {
list.iter().any(|(s, _)| s == session)
}
-/// The process owning the session's window, if one was found.
-pub fn lookup(session: &str) -> Option<u32> {
+/// The processes that may own the session's window, nearest first, if any.
+pub fn lookup(session: &str) -> Option<Vec<u32>> {
let list = SESSIONS.lock().unwrap_or_else(|e| e.into_inner());
- list.iter().find(|(s, _)| s == session).map(|(_, pid)| *pid).filter(|pid| *pid != NO_WINDOW)
+ list.iter().find(|(s, _)| s == session).map(|(_, pids)| pids.clone()).filter(|pids| !pids.is_empty())
}
pub fn forget(session: &str) {
@@ -151,7 +219,7 @@ mod tests {
(500, 400, "bash.exe"),
(600, 500, "coucou-hook.exe"),
]);
- assert_eq!(ancestors(&procs, 600), [500, 400, 300, 200]);
+ assert_eq!(ancestors_below(&procs, 600, WINDOWS_TREE_TOPS), [500, 400, 300, 200]);
assert_eq!(window_owner(&procs, 600, |pid| pid == 200 || pid == 100), Some(200));
}
@@ -190,6 +258,109 @@ mod tests {
assert_eq!(ancestors(&tree(&deep), 1).len(), MAX_DEPTH);
}
+ // ── Linux ──
+
+ fn linux(entries: &[(u32, u32, &str)]) -> Vec<u32> {
+ // platform/linux.rs leaves PID 1 out of the table; so do the fixtures.
+ let start = entries.last().unwrap().0;
+ ancestors_below(&tree(entries), start, LINUX_TREE_TOPS)
+ }
+
+ #[test]
+ fn stat_lines_are_read_around_odd_process_names() {
+ let line = "4242 (gnome-terminal-) S 1337 4242 4242 0 -1 4194560 2 0 0 0";
+ assert_eq!(parse_stat(line), Some(("gnome-terminal-".to_string(), 1337)));
+ // Spaces and parentheses in the name: only the last ')' ends it.
+ let odd = "77 (a) b (c) S 12 77 77 34816 77";
+ assert_eq!(parse_stat(odd), Some(("a) b (c".to_string(), 12)));
+ assert_eq!(parse_stat("9 (tmux: server) S 1 9 9 0"), Some(("tmux: server".to_string(), 1)));
+ assert_eq!(parse_stat("10 (Web Content) R 8 8 8"), Some(("Web Content".to_string(), 8)));
+ assert_eq!(parse_stat("11 () S 2 0"), Some((String::new(), 2)));
+ // Broken or cut short: nothing.
+ assert_eq!(parse_stat(""), None);
+ assert_eq!(parse_stat("12 (x S 3"), None);
+ assert_eq!(parse_stat("13 )x( S 3"), None);
+ assert_eq!(parse_stat("14 (x) S"), None);
+ assert_eq!(parse_stat("15 (x) S -3"), None);
+ assert_eq!(parse_stat("16 (x) S abc"), None);
+ }
+
+ #[test]
+ fn linux_terminals_are_found_below_the_service_manager() {
+ // systemd --user → gnome-terminal-server → bash → claude → sh → coucou-hook
+ let gnome = [
+ (900, 1, "systemd"),
+ (1000, 900, "gnome-terminal-"),
+ (1100, 1000, "bash"),
+ (1200, 1100, "claude"),
+ (1300, 1200, "sh"),
+ (1400, 1300, "coucou-hook"),
+ ];
+ assert_eq!(linux(&gnome), [1300, 1200, 1100, 1000]);
+
+ // A terminal started from the panel stops before the panel, which has
+ // windows of its own.
+ let panel = [
+ (500, 400, "plasmashell"),
+ (600, 500, "konsole"),
+ (700, 600, "zsh"),
+ (800, 700, "node"),
+ (810, 800, "coucou-hook"),
+ ];
+ assert_eq!(linux(&panel), [800, 700, 600]);
+
+ // VS Code: the pty host and the zygote lead up to the main process.
+ let code = [
+ (20, 1, "systemd"),
+ (30, 20, "code"),
+ (31, 30, "code"),
+ (32, 31, "code"),
+ (40, 32, "bash"),
+ (41, 40, "node"),
+ (42, 41, "coucou-hook"),
+ ];
+ assert_eq!(linux(&code), [41, 40, 32, 31, 30]);
+ }
+
+ #[test]
+ fn linux_walks_end_at_logins_and_session_managers() {
+ // Over ssh: nothing above the shell may be raised.
+ let ssh = [(10, 1, "sshd"), (11, 10, "sshd-session"), (12, 11, "bash"), (13, 12, "claude"), (14, 13, "coucou-hook")];
+ assert_eq!(linux(&ssh), [13, 12]);
+ // tmux's server is daemonised under the service manager: no terminal.
+ let tmux = [(5, 1, "systemd"), (6, 5, "tmux: server"), (7, 6, "bash"), (8, 7, "claude"), (9, 8, "coucou-hook")];
+ assert_eq!(linux(&tmux), [8, 7, 6]);
+ // An X session started by hand ends at xinit, names compared lower-cased.
+ let xinit = [(2, 1, "xinit"), (3, 2, "Xorg"), (4, 2, "i3"), (50, 4, "xterm"), (51, 50, "bash"), (52, 51, "coucou-hook")];
+ assert_eq!(linux(&xinit), [51, 50]);
+ }
+
+ #[test]
+ fn linux_tree_tops_fit_in_a_process_name() {
+ for top in LINUX_TREE_TOPS {
+ assert!(top.len() <= 15, "{top} is longer than /proc keeps");
+ assert_eq!(*top, top.to_ascii_lowercase());
+ }
+ }
+
+ #[test]
+ fn the_nearest_ancestor_with_a_window_is_chosen() {
+ let windows = vec![
+ ("panel", 500, "Panel".to_string()),
+ ("notes", 30, "notes — Visual Studio Code".to_string()),
+ ("coucou", 30, "lib.rs — coucou — Visual Studio Code".to_string()),
+ ("other", 99, "coucou — elsewhere".to_string()),
+ ];
+ // The shell and node own nothing; VS Code's main process does.
+ assert_eq!(choose_window(&[41, 40, 30, 500], &windows, "coucou"), Some(&"coucou"));
+ assert_eq!(choose_window(&[41, 40, 30], &windows, "missing"), Some(&"notes"));
+ // A nearer ancestor wins even when a farther one's title matches.
+ assert_eq!(choose_window(&[500, 30], &windows, "coucou"), Some(&"panel"));
+ // A title alone never picks a window of another process.
+ assert_eq!(choose_window(&[41, 40], &windows, "coucou"), None);
+ assert_eq!(choose_window::<&str>(&[1], &[], "x"), None);
+ }
+
#[test]
fn the_window_named_after_the_project_wins() {
let windows = vec![
@@ -206,23 +377,23 @@ mod tests {
#[test]
fn sessions_are_remembered_by_id_and_only_plausible_ids_are_kept() {
- remember("s-test-1", 42);
- remember("s-test-1", 43);
- assert_eq!(lookup("s-test-1"), Some(43));
- remember("not a session/../x", 7);
+ remember("s-test-1", vec![42]);
+ remember("s-test-1", vec![43, 44]);
+ assert_eq!(lookup("s-test-1"), Some(vec![43, 44]));
+ remember("not a session/../x", vec![7]);
assert!(!known("not a session/../x"));
forget("s-test-1");
assert!(!known("s-test-1"));
// A session without a window is settled, with nothing to show.
- remember("s-test-2", NO_WINDOW);
+ remember("s-test-2", Vec::new());
assert!(known("s-test-2"));
assert_eq!(lookup("s-test-2"), None);
forget("s-test-2");
// Only the latest sessions are kept. (One test: the list is shared.)
for i in 0..(MAX_SESSIONS + 5) {
- remember(&format!("s-cap-{i}"), 1);
+ remember(&format!("s-cap-{i}"), vec![1]);
}
assert!(!known("s-cap-0"));
assert!(known(&format!("s-cap-{}", MAX_SESSIONS + 4)));
diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.ts
index 1bbf25fc..95b038ed 100644
--- a/windows/src/core/bridge.ts
+++ b/windows/src/core/bridge.ts
@@ -63,7 +63,7 @@ export const Bridge = {
/**
* "Open terminal": the window the session runs in when Rust found it
- * (Windows), else the folder in VS Code.
+ * (Windows; Linux on X11 and KDE Plasma), else the folder in VS Code.
*/
openSession: (sessionId: string | null, path: string | null) =>
call<boolean>("open_session", { sessionId, path }),