Skip to content

Commit ecb4468

Browse files
authored
feat(desktop): apply WebKit rendering workarounds at startup on Linux (#3271)
On some Linux GPU/driver/compositor combinations, WebKitGTK's dmabuf renderer aborts the web process during startup, so Buzz comes up with no window at all and the user has no way to fix it. Setting `WEBKIT_DISABLE_DMABUF_RENDERER=1` avoids the abort by falling back to the shared-memory buffer path. WebKit reads each of its rendering variables exactly once per process, so the choice has to be made before anything initializes — there is no runtime toggle and no second chance later in the same process. This decides up front from two cheap preflight signals rather than reacting to a crash: - **NVIDIA GPU** — any DRM device under `/sys/class/drm` reporting PCI vendor `0x10de`, the driver family behind most upstream reports. - **AppImage** — the `APPIMAGE` environment variable. linuxdeploy's AppRun hook pins `GDK_BACKEND=x11`, and the dmabuf renderer buys nothing on that XWayland path. Either signal disables the dmabuf renderer. Neither signal leaves the environment untouched. ## Escape hatches `--safe-rendering` forces the safest configuration for one launch — `WEBKIT_DISABLE_DMABUF_RENDERER` plus `WEBKIT_DISABLE_COMPOSITING_MODE` — for a machine neither signal recognises. Any user assignment of a variable this module may set stands the heuristic down **wholesale**. Presence is the test, not truthiness, so `VAR=0` and `VAR=` both count: a user asking for the dmabuf renderer *on* gets it, even on a machine the heuristic would have opted out. `--safe-rendering` against such an assignment is refused with a diagnostic naming both the assignment and the key to unset, and exits non-zero — the flag and the environment are two incompatible answers to one question, and neither is guessed. ## Placement `webkit_rendering::apply()` runs at the top of `fn main()`, before `buzz_lib::run()`. That is the only point where the process is still single threaded with no GTK object alive, which is what makes `std::env::set_var` sound; the module doc and the call site both say so. The whole module is `#[cfg(target_os = "linux")]` — macOS and Windows compile none of it. The decision is a pure function of argv, an injected environment lookup, and an injected DRM root, so all of it is unit-testable without mutating the process environment. Closes #2338. Upstream: [tauri#9394](tauri-apps/tauri#9394). Same approach and same variable as [clash-verge-rev](https://github.com/clash-verge-rev/clash-verge-rev/blob/main/src-tauri/src/utils/linux/workarounds.rs) `workarounds.rs` and [screenpipe](https://github.com/screenpipe/screenpipe/blob/main/apps/screenpipe-app-tauri/src-tauri/src/linux_webkit_env.rs) `linux_webkit_env.rs`. Signed-off-by: Will Pfleger <[email protected]>
1 parent 4637c60 commit ecb4468

4 files changed

Lines changed: 470 additions & 0 deletions

File tree

‎desktop/src-tauri/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ mod secret_store;
2929
mod shutdown;
3030
mod templates;
3131
mod util;
32+
#[cfg(target_os = "linux")]
33+
pub mod webkit_rendering;
3234
use app_state::{build_app_state, resolve_persisted_identity, AppState};
3335
use builderlab::*;
3436
use commands::*;

‎desktop/src-tauri/src/main.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,15 @@
22
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
33

44
fn main() {
5+
// Before anything else: WebKitGTK reads its rendering environment once at
6+
// process start, and this is the only point where the process is still
7+
// single threaded and no GTK object exists yet, which is what makes
8+
// `std::env::set_var` sound.
9+
#[cfg(target_os = "linux")]
10+
if let Err(diagnostic) = buzz_lib::webkit_rendering::apply() {
11+
eprintln!("buzz-desktop: {diagnostic}");
12+
std::process::exit(1);
13+
}
14+
515
buzz_lib::run()
616
}
Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
//! WebKit rendering workarounds for Linux, applied before WebKit initializes.
2+
//!
3+
//! WebKitGTK's dmabuf renderer aborts the web process during startup on some
4+
//! GPU/driver/compositor combinations, so Buzz comes up with no window at all
5+
//! and the user has no way to fix it (#2338, upstream tauri#9394). Setting
6+
//! `WEBKIT_DISABLE_DMABUF_RENDERER=1` avoids the abort by falling back to the
7+
//! shared-memory buffer path.
8+
//!
9+
//! WebKit reads each of these variables exactly once per process, so the choice
10+
//! has to be made before anything initializes — there is no runtime toggle and
11+
//! no second chance later in the same process. This module therefore decides
12+
//! from cheap preflight signals instead of reacting to a crash:
13+
//!
14+
//! * an NVIDIA GPU, the driver family behind most upstream reports; and
15+
//! * AppImage packaging, where linuxdeploy's AppRun hook pins `GDK_BACKEND=x11`
16+
//! and the dmabuf renderer buys nothing on that XWayland path (#2338).
17+
//!
18+
//! `--safe-rendering` is the manual escape hatch for a machine neither signal
19+
//! recognises; it also disables accelerated compositing, for that launch only.
20+
//!
21+
//! This is the shape the Tauri ecosystem converged on: clash-verge-rev's
22+
//! `utils/linux/workarounds.rs` and screenpipe's `linux_webkit_env.rs` both set
23+
//! the same variable from the same signals at the same point in startup.
24+
25+
use std::ffi::{OsStr, OsString};
26+
use std::path::Path;
27+
28+
/// Force the safest rendering configuration for this launch.
29+
const SAFE_RENDERING: &str = "--safe-rendering";
30+
31+
/// PCI vendor ID reported by NVIDIA devices under `/sys/class/drm`.
32+
const NVIDIA_PCI_VENDOR: &str = "0x10de";
33+
34+
/// Where DRM devices advertise their PCI vendor.
35+
const DRM_ROOT: &str = "/sys/class/drm";
36+
37+
/// Drops the zero-copy dmabuf buffer path. The workaround for #2338.
38+
const DISABLE_DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
39+
/// Drops accelerated compositing as well. `--safe-rendering` only.
40+
const DISABLE_COMPOSITING: &str = "WEBKIT_DISABLE_COMPOSITING_MODE";
41+
42+
/// What the heuristic applies: the #2338 workaround alone, matching the
43+
/// ecosystem precedents. `DISABLE_COMPOSITING` is deliberately not here — no
44+
/// report has isolated it as necessary, and it costs more rendering than this.
45+
const HEURISTIC: [&str; 1] = [DISABLE_DMABUF];
46+
47+
/// What `--safe-rendering` applies, which is also every variable this module may
48+
/// set and therefore every variable a user assignment takes away from it. Being
49+
/// the same list is the invariant: nothing outside it is ever written, so a user
50+
/// value for any other WebKit variable is not a conflict.
51+
const OWNED: [&str; 2] = [DISABLE_DMABUF, DISABLE_COMPOSITING];
52+
53+
/// Reads one environment variable. Injected so the decision is testable without
54+
/// mutating the process environment. `OsString` rather than `String` because
55+
/// presence is the test — a non-UTF-8 assignment is still the user's.
56+
type EnvLookup<'a> = &'a dyn Fn(&str) -> Option<OsString>;
57+
58+
/// What this launch should do about its rendering environment.
59+
#[derive(Debug, PartialEq, Eq)]
60+
enum Plan {
61+
/// Set each of these to `1`, then report `why`.
62+
Apply {
63+
vars: &'static [&'static str],
64+
why: String,
65+
},
66+
/// Change nothing, and report `why`.
67+
Leave { why: String },
68+
/// The request cannot be delivered. Report it and exit non-zero rather than
69+
/// starting an app that silently ignores what the user asked for.
70+
Fatal { diagnostic: String },
71+
}
72+
73+
/// Applies the workaround for this launch.
74+
///
75+
/// Must be called from `main()` before `crate::run()`: WebKit memoizes these
76+
/// variables at process start, and `std::env::set_var` is only sound while the
77+
/// process is still single threaded, which it is nowhere else in Buzz.
78+
///
79+
/// `Err` carries a user-facing diagnostic; the caller reports it and exits.
80+
pub fn apply() -> Result<(), String> {
81+
match plan(
82+
std::env::args_os(),
83+
&|key| std::env::var_os(key),
84+
Path::new(DRM_ROOT),
85+
) {
86+
Plan::Apply { vars, why } => {
87+
for var in vars {
88+
// Safe here and only here — see the doc comment above.
89+
std::env::set_var(var, "1");
90+
}
91+
let applied: Vec<String> = vars.iter().map(|var| format!("{var}=1")).collect();
92+
eprintln!("buzz-desktop: {} — {why}", applied.join(" "));
93+
Ok(())
94+
}
95+
Plan::Leave { why } => {
96+
eprintln!("buzz-desktop: WebKit rendering left as-is — {why}");
97+
Ok(())
98+
}
99+
Plan::Fatal { diagnostic } => Err(diagnostic),
100+
}
101+
}
102+
103+
/// The whole decision, as a pure function of argv, the environment, and the DRM
104+
/// device tree.
105+
fn plan(
106+
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
107+
env: EnvLookup<'_>,
108+
drm_root: &Path,
109+
) -> Plan {
110+
let safe_rendering = args
111+
.into_iter()
112+
.any(|arg| arg.as_ref() == OsStr::new(SAFE_RENDERING));
113+
let user_set = user_set(env);
114+
115+
if !user_set.is_empty() {
116+
// A user who has assigned one of these has taken over the decision, so
117+
// the heuristic stands down wholesale — writing the *other* variable
118+
// behind their back would be exactly the surprise they opted out of.
119+
return match safe_rendering {
120+
// Two incompatible answers to one question, and no basis for
121+
// picking: honouring the flag would overwrite configuration the
122+
// user typed, honouring the environment would silently ignore a
123+
// rescue flag from a user whose app does not start.
124+
true => Plan::Fatal {
125+
diagnostic: conflict(&user_set),
126+
},
127+
false => Plan::Leave {
128+
why: format!("{} set in the environment", describe(&user_set)),
129+
},
130+
};
131+
}
132+
133+
if safe_rendering {
134+
return Plan::Apply {
135+
vars: &OWNED,
136+
why: format!("{SAFE_RENDERING} requested, this launch only"),
137+
};
138+
}
139+
140+
let signals = [
141+
(nvidia_gpu(drm_root), "NVIDIA GPU"),
142+
(env("APPIMAGE").is_some(), "AppImage"),
143+
];
144+
let hits: Vec<&str> = signals
145+
.iter()
146+
.filter_map(|(hit, label)| hit.then_some(*label))
147+
.collect();
148+
149+
match hits.is_empty() {
150+
true => Plan::Leave {
151+
why: "no NVIDIA GPU and not an AppImage".to_string(),
152+
},
153+
false => Plan::Apply {
154+
vars: &HEURISTIC,
155+
why: hits.join(", "),
156+
},
157+
}
158+
}
159+
160+
/// Owned variables the environment already carries, keyed by name.
161+
///
162+
/// Presence is the test, not truthiness: `VAR=0` and `VAR=` are both genuine
163+
/// user assignments, and both take the decision away from this module.
164+
fn user_set(env: EnvLookup<'_>) -> Vec<(&'static str, OsString)> {
165+
OWNED
166+
.iter()
167+
.filter_map(|key| env(key).map(|value| (*key, value)))
168+
.collect()
169+
}
170+
171+
/// User assignments rendered as `KEY=value`, for a log line or a diagnostic.
172+
fn describe(user_set: &[(&str, OsString)]) -> String {
173+
let shown: Vec<String> = user_set
174+
.iter()
175+
.map(|(key, value)| format!("{key}={}", value.to_string_lossy()))
176+
.collect();
177+
shown.join(", ")
178+
}
179+
180+
/// Whether any DRM device reports NVIDIA's PCI vendor ID. An unreadable device
181+
/// tree is not a hit — the workaround has a real cost, so it needs evidence.
182+
fn nvidia_gpu(drm_root: &Path) -> bool {
183+
let Ok(entries) = std::fs::read_dir(drm_root) else {
184+
return false;
185+
};
186+
entries.flatten().any(|entry| {
187+
std::fs::read_to_string(entry.path().join("device/vendor"))
188+
.is_ok_and(|vendor| vendor.trim().eq_ignore_ascii_case(NVIDIA_PCI_VENDOR))
189+
})
190+
}
191+
192+
/// The diagnostic for `--safe-rendering` against a user-set owned variable.
193+
///
194+
/// The message both shows what is set and names the keys to unset — the two
195+
/// things a user whose app will not start needs in order to act on it.
196+
fn conflict(user_set: &[(&str, OsString)]) -> String {
197+
let keys: Vec<&str> = user_set.iter().map(|(key, _)| *key).collect();
198+
format!(
199+
"{SAFE_RENDERING} cannot be applied: {} already set in the environment. \
200+
Either unset {} and run {SAFE_RENDERING} again, or keep that \
201+
environment and drop the flag.",
202+
describe(user_set),
203+
keys.join(", "),
204+
)
205+
}
206+
207+
#[cfg(test)]
208+
mod tests;

0 commit comments

Comments
 (0)