Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(linux): retry the portal app id registration for a just-written desktop entry (#3285)
Richie McIlroy60ef63232c9e
diff --git a/.github/workflows/linux-desktop-reliability.yml b/.github/workflows/linux-desktop-reliability.ymlindex 3ab34ac46..775063a4c 100644--- a/.github/workflows/linux-desktop-reliability.yml+++ b/.github/workflows/linux-desktop-reliability.yml@@ -158,6 +158,21 @@ jobs:grep -qx attempt1_control=shortcut "$RUNNER_TEMP/out/gnome-terminal/result.txt"grep -qx app_id_required=0 "$RUNNER_TEMP/out/gnome-terminal/result.txt"+ # Every shell launch names itself to the portals, including the ones+ # that have just written the desktop entry the portal looks the id up in.+ - name: GNOME 50 shell launches register Cap's app id+ env:+ DEV_BIN: ${{ github.workspace }}/apps/desktop-gpui/target/debug/cap-gpui+ DEV_LIBS: ${{ github.workspace }}/target/native-deps/lib+ SCENARIO: register+ run: |+ sudo -E bash scripts/linux-desktop-harness/run-desktop.sh gnome "$RUNNER_TEMP/cap.deb" \+ "$RUNNER_TEMP/out/gnome-register" ROUNDS=4+ cat "$RUNNER_TEMP/out/gnome-register/result.txt"+ for line in fresh_registered=4 again_registered=4 entry_written=yes panics=0; do+ grep -qx "$line" "$RUNNER_TEMP/out/gnome-register/result.txt"+ done+# Fedora's GNOME without the AppIndicator extension, launched where the# portal grants no shortcut: no tray and no Stop shortcut. Cap records# with its controls visible instead of refusing to start.diff --git a/apps/desktop-gpui/src/linux_portal_id.rs b/apps/desktop-gpui/src/linux_portal_id.rsindex 1a2e104f8..647ef18a2 100644--- a/apps/desktop-gpui/src/linux_portal_id.rs+++ b/apps/desktop-gpui/src/linux_portal_id.rs@@ -84,25 +84,44 @@ fn exec_argument(value: &str) -> String {format!("\"{}\"", quoted.replace('\\', "\\\\").replace('%', "%%"))}-/// Finds or writes the `.desktop` file for [`PORTAL_APP_ID`], returning-/// whether one exists afterwards.-pub fn ensure_desktop_entry(user_dir: &Path, dirs: &[PathBuf], exec: &Path) -> bool {+#[derive(Debug, PartialEq, Eq)]+pub enum DesktopEntry {+ Found,+ Written,+ Unavailable,+}++/// Finds or writes the `.desktop` file for [`PORTAL_APP_ID`].+pub fn ensure_desktop_entry(user_dir: &Path, dirs: &[PathBuf], exec: &Path) -> DesktopEntry {let file = format!("{PORTAL_APP_ID}.desktop");if dirs.iter().any(|dir| dir.join(&file).is_file()) {- return true;+ return DesktopEntry::Found;}let path = user_dir.join(&file);let written =std::fs::create_dir_all(user_dir).and_then(|()| std::fs::write(&path, desktop_entry(exec)));match written {- Ok(()) => true,+ Ok(()) => DesktopEntry::Written,Err(error) => {tracing::info!(path = %path.display(), %error, "could not write the portal app id's desktop entry");- false+ DesktopEntry::Unavailable}}}+/// The portal can look an entry up before its index has seen the new file and+/// answer "App info not found". Delays before each retry of a new entry.+const NEW_ENTRY_RETRY_DELAYS: [Duration; 4] = [+ Duration::from_millis(50),+ Duration::from_millis(150),+ Duration::from_millis(400),+ Duration::from_millis(1000),+];++fn app_info_not_found(error: &str) -> bool {+ error.contains("App info not found")+}+/// Registers [`PORTAL_APP_ID`] when the portal has no app id for Cap. Must/// run before any portal call on the process's portal connection, gpui's/// appearance read included, and on the runtime that keeps that connection.@@ -132,19 +151,51 @@ pub async fn register() {) else {return;};- if !ensure_desktop_entry(&user_dir, &dirs, &exec) {+ let entry = ensure_desktop_entry(&user_dir, &dirs, &exec);+ if entry == DesktopEntry::Unavailable {return;}let Ok(app_id) = ashpd::AppID::try_from(PORTAL_APP_ID) else {return;};- match tokio::time::timeout(Duration::from_secs(3), ashpd::register_host_app(app_id)).await {- Ok(Ok(())) => tracing::info!(- app_id = PORTAL_APP_ID,- "registered Cap's app id with the portals"- ),- Ok(Err(error)) => tracing::info!(%error, "the portals did not take Cap's app id"),- Err(_) => tracing::info!("the portal registry did not answer"),+ let mut retries = match entry {+ DesktopEntry::Written => NEW_ENTRY_RETRY_DELAYS.as_slice(),+ _ => &[],+ }+ .iter();+ let mut attempt = 1;+ loop {+ match tokio::time::timeout(+ Duration::from_secs(3),+ ashpd::register_host_app(app_id.clone()),+ )+ .await+ {+ Ok(Ok(())) => {+ tracing::info!(+ app_id = PORTAL_APP_ID,+ attempt,+ "registered Cap's app id with the portals"+ );+ return;+ }+ Ok(Err(error)) => {+ let error = error.to_string();+ if app_info_not_found(&error)+ && let Some(delay) = retries.next()+ {+ tokio::time::sleep(*delay).await;+ attempt += 1;+ continue;+ }+ tracing::info!(%error, attempt, "the portals did not take Cap's app id");+ return;+ }+ Err(_) => {+ tracing::info!("the portal registry did not answer");+ return;+ }+ }}}@@ -191,7 +242,8 @@ mod tests {.unwrap();assert_eq!(user, root.path().join("home/.local/share/applications"));let exec = Path::new(r#"/opt/100% Cap/"beta" $HOME `x`\.AppImage"#);- assert!(ensure_desktop_entry(&user, &dirs, exec));+ assert_eq!(ensure_desktop_entry(&user, &dirs, exec), DesktopEntry::Written);+ assert_eq!(ensure_desktop_entry(&user, &dirs, exec), DesktopEntry::Found);let entry = std::fs::read_to_string(user.join("so.cap.Cap.desktop")).unwrap();assert!(entry.contains("NoDisplay=true"));assert!(entry.contains(@@ -209,11 +261,24 @@ mod tests {None,).unwrap();- assert!(ensure_desktop_entry(&user, &dirs, exec));+ assert_eq!(ensure_desktop_entry(&user, &dirs, exec), DesktopEntry::Found);assert!(!user.join("so.cap.Cap.desktop").exists());// Without a home there is nowhere safe to write.assert!(application_dirs(None, None, None).is_none());assert!(application_dirs(Some("relative".into()), None, None).is_none());}++ #[test]+ fn only_a_missing_entry_is_retried() {+ assert!(app_info_not_found(+ "ZBus Error: org.freedesktop.portal.Error.Failed: Could not register app ID: App info not found for 'so.cap.Cap'"+ ));+ assert!(!app_info_not_found(+ "ZBus Error: org.freedesktop.portal.Error.Failed: Could not register app ID: Connection already associated with an application ID"+ ));+ assert!(!app_info_not_found(+ "ZBus Error: org.freedesktop.DBus.Error.UnknownMethod: No such interface"+ ));+ }}diff --git a/scripts/linux-desktop-harness/README.md b/scripts/linux-desktop-harness/README.mdindex f87b3aaab..8f3ce8cf1 100644--- a/scripts/linux-desktop-harness/README.md+++ b/scripts/linux-desktop-harness/README.md@@ -55,6 +55,9 @@ leads every session with a Shift tap.desktop's wallpaper as its background (`CAP_GPUI_AUTO_DESKTOP_BACKGROUND=1`).GNOME keeps its default JPEG XL wallpaper; `WALLPAPER=swaybg` starts swaybgwith a PNG first, as Omarchy does on Hyprland.+`SCENARIO=register` launches Cap from a shell `ROUNDS` times, each time once+with its `so.cap.Cap.desktop` entry removed and once with it in place, and+counts the launches that registered the app id with the portals.`report.sh <out-dir>` prints the results with Cap's own log lines. TheHyprland image needs `modprobe vkms` on the host. With `GNOME_UNSAFE=1`,diff --git a/scripts/linux-desktop-harness/scenario-register.sh b/scripts/linux-desktop-harness/scenario-register.shnew file mode 100755index 000000000..049adea78--- /dev/null+++ b/scripts/linux-desktop-harness/scenario-register.sh@@ -0,0 +1,63 @@+#!/usr/bin/env bash+# Cap launched from a shell, which gives the portals no app id, names itself+# so.cap.Cap through the host portal registry. Other apps' entries are written+# and looked up first, as on a desktop in use: the portal then can miss a+# just-written entry ("App info not found"). Launches Cap ROUNDS times+# (default 4), first with its desktop entry removed (Cap writes it) and then+# with the entry in place, and counts the launches that registered. Prints+# key=value results to $HARNESS_OUT/result.txt.+set -uo pipefail+here=$(cd "$(dirname "$0")" && pwd)+export XDG_RUNTIME_DIR=/run/user/$(id -u)+export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus+export HARNESS_OUT=${HARNESS_OUT:-/out}+out=$HARNESS_OUT+eval "$(systemctl --user show-environment | grep -E "^(WAYLAND_DISPLAY|XDG_SESSION_TYPE|XDG_CURRENT_DESKTOP|XDG_SESSION_DESKTOP|LIBGL_ALWAYS_SOFTWARE)=" | sed 's/^/export /')"+entry=$HOME/.local/share/applications/so.cap.Cap.desktop+rounds=${ROUNDS:-4}+: >"$out/result.txt"+result() { printf '%s=%s\n' "$1" "$2" >>"$out/result.txt"; }++launch() {+ local name=$1 log=$out/$1.log line=""+ bash "$here/launch-cap.sh" "$name" >/dev/null+ for _ in $(seq 60); do+ line=$(sed 's/\x1b\[[0-9;]*m//g' "$log" 2>/dev/null |+ grep -aoE "registered Cap's app id.*|did not take Cap's app id.*|registry did not answer|portals know Cap.*|could not write the portal app id.*" | head -1)+ [[ -n $line ]] && break+ sleep 0.25+ done+ echo "$name: ${line:-no registration line}" >>"$out/actions.log"+ kill "$(cat "$XDG_RUNTIME_DIR/$name.pid")" 2>/dev/null+ for _ in $(seq 20); do+ kill -0 "$(cat "$XDG_RUNTIME_DIR/$name.pid")" 2>/dev/null || break+ sleep 0.25+ done+ [[ $line == "registered Cap's app id"* ]] && echo yes || echo no+}++register() {+ gdbus call --session --dest org.freedesktop.portal.Desktop --object-path /org/freedesktop/portal/desktop \+ --method org.freedesktop.host.portal.Registry.Register "$1" '{}' >/dev/null 2>&1+}+mkdir -p "$(dirname "$entry")"+register so.cap.Missing+for n in 1 2 3; do+ printf '[Desktop Entry]\nType=Application\nName=Other %s\nExec=env true\nNoDisplay=true\n' "$n" \+ >"$(dirname "$entry")/so.cap.Other$n.desktop"+ register "so.cap.Other$n"+ sleep 1+done++fresh=0 again=0+for n in $(seq "$rounds"); do+ rm -f "$entry"+ [[ $(launch "fresh$n") == yes ]] && fresh=$((fresh + 1))+ [[ $(launch "again$n") == yes ]] && again=$((again + 1))+done+result rounds "$rounds"+result fresh_registered "$fresh"+result again_registered "$again"+result entry_written "$([[ -f $entry ]] && echo yes || echo no)"+result panics "$(cat "$out"/fresh*.log "$out"/again*.log 2>/dev/null | grep -ac 'panicked at')"+cat "$out/result.txt"