diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 786942f9..35845e4d 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -71,7 +71,7 @@ jobs: if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf xdg-utils xvfb xauth + sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf xdg-utils xvfb xauth xdotool - name: Install uv uses: astral-sh/setup-uv@v5 @@ -249,12 +249,17 @@ jobs: assert parse_qs(url.query) == {"bind_session": ["smoke"]}, url print("both windows rendered the app shell") PY + # TD-5427: the host heard the ready signal, so the window painted. + LOG="$HOME/.local/share/tst-desk/logs/host.log" + grep "main window painted" "$LOG" || { + echo "::error::the packaged app's window never sent the ready signal"; tail -20 "$LOG"; exit 1; } # The 0.5.4 start-up failure: a long-used install (183 chats) never # connected, because every chat was revived before the daemon wrote # port.json and the host gave up after 30 s. Gate every release on a # data folder like that one: 300 chats, long event logs, a project - # tree each. The packaged app must connect within 10 s of launch. + # tree each. The packaged app must connect within 10 s of launch, and + # its window must paint (TD-5427: a blank window also connects). - name: Gate a long-used install's start (Linux) if: runner.os == 'Linux' run: | @@ -274,11 +279,13 @@ jobs: APP=$! # Watch for up to 60 s so a miss reports how long it really took. ELAPSED="" + PAINTED="" for i in $(seq 1 600); do - if grep -q "connected to tstd" "$LOG" 2>/dev/null; then + if [ -z "$ELAPSED" ] && grep -q "connected to tstd" "$LOG" 2>/dev/null; then ELAPSED=$(python3 -c "import sys,time; print(round(time.time() - float(sys.argv[1]), 2))" "$START") - break fi + if grep -q "main window painted" "$LOG" 2>/dev/null; then PAINTED=yes; fi + if [ -n "$ELAPSED" ] && [ -n "$PAINTED" ]; then break; fi sleep 0.1 done kill "$APP" 2>/dev/null || true @@ -289,8 +296,21 @@ jobs: tail -20 "$DATA/logs/tstd.stderr.log" 2>/dev/null || true tail -20 "$OUT" || true [ -n "$ELAPSED" ] || { echo "::error::the packaged app never connected to tstd on a 300-chat data folder"; exit 1; } + [ -n "$PAINTED" ] || { echo "::error::the packaged app's window never sent the ready signal (60 s)"; exit 1; } + if grep -q "relaunching once" "$LOG"; then + echo "::warning::the window painted only after a relaunch without compositing" + fi python3 -c "import sys; sys.exit(0 if float(sys.argv[1]) <= 10 else 1)" "$ELAPSED" || { echo "::error::the packaged app took ${ELAPSED} s to connect to tstd on a 300-chat data folder (limit 10 s)"; exit 1; } + # TD-5427: with EGL made to fail, the packaged app either relaunches + # and paints or says why in a dialog and exits 1. Never a blank window. + - name: Force an EGL failure on the packaged Linux app + if: runner.os == 'Linux' + run: | + set -e + AI=$(ls "$PWD"/shell/target/release/bundle/appimage/*.AppImage) + shell/scripts/egl-fallback-smoke.sh "$AI" + - name: Smoke the bundled sidecar (Windows) if: runner.os == 'Windows' shell: pwsh diff --git a/DECISIONS.md b/DECISIONS.md index 8832e864..8a8553c9 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -22344,3 +22344,86 @@ field plus plumbing through dispatch; and the audit pairs a result, a card and a decision with its call by id, so the second call's row and result would still be ambiguous there. Two calls alike in one reply is a provider fault; showing both runs on their own, in both views, says what is known. + +--- + +### TD-5427: a web view that cannot draw + +**The whole app is replaced, not the web view.** WebKitGTK reads +`WEBKIT_DISABLE_COMPOSITING_MODE` once, in the UI process, and holds the +answer for the life of that process, so a new web view would not see it. The +host stops tstd and the embeddings sidecar as Quit does, releases the +single-instance name and `exec`s its own binary with the same arguments. The +process id stays, so a launcher, the AppImage runtime and tstd's +`--parent-pid` still name the app, and there is no second instance to race. +The wait for tstd has no limit of its own: a tstd still starting is stopped +once it answers, so the next one finds the data folder free; the supervisor +already bounds that start. The cost is that the old web view's helper +processes stay as zombies until the relaunched app exits. + +**At most one relaunch per start.** The relaunched process carries +`TST_DESK_COMPOSITING_RELAUNCH=`, read and removed before any thread +starts. A process with that mark, or with the compositing variable set to +anything at all, goes to the dialog instead. The updater drops the variable +from the process that applies an update when the host set it, so the new +version does not take it for the person's choice. + +**The ready signal is two animation frames after the root layout mounts** +(`ui_painted`, main window only). The first callback runs before its frame is +drawn; the second shows one was. It is evidence that the web process runs +frames, not a reading of the pixels on screen. + +**N is 20 s** (`TST_DESK_PAINT_TIMEOUT_SECS` overrides it, for tests). A dead +web process is acted on at once through WebKitGTK's +`web-process-terminated`; Tauri reports that on Apple platforms only, so the +host connects the signal itself. The timer is for a view that stays alive and +silent. Healthy starts signalled in about 1 s on the test machine; the wait is +long because a false positive restarts the app, and a second one ends it. A +hidden or minimised window draws no frames, so it is not judged until shown. + +**After the first paint nothing is relaunched.** The requirement is a start +that never draws. A later crash of the web process is logged. + +**The web process's last words come through a stderr relay.** WebKitGTK +starts that process itself and it inherits the host's stderr. Before GTK +starts, the host forks (twice, so no zombie) a small copier that passes +stderr on unchanged and gives the host a second copy, from which the last +abort or graphics-failure line is kept. A process rather than a thread: if the +host aborts, its message still reaches the terminal, and no writer gets a +broken pipe after the host exits. + +**The failing exit code is set by the host.** Tauri's `exit(code)` ends with +status 0 on Linux whatever the code, so a quit after the dialog runs the same +cleanup and calls `process::exit(1)`. + +**Doctor learns of it from the daemon's environment.** The host sets +`TST_DESK_DISPLAY_NOTICE=` on the tstd it spawns; the daemon takes it +out of its own environment and adds a `display` row (warn). No file, so no +stale row after a normal start. A daemon the host attached to rather than +spawned has no row. + +**The remedy does not cure every EGL failure.** Tested: with an EGL vendor +file naming a missing library, the web process aborts with or without +compositing, so that start ends in the dialog. A Mesa override that breaks GL +context creation (`MESA_GLES_VERSION_OVERRIDE=1.0` with the Mesa vendor file) +leaves the view silent with compositing and drawing without it; the smoke +script uses one of each. No other variable is set: only the one asked for. + +## 2026-12-01 — TD-5427: review round 1 (Class A) + +- **The dialog's OK ends the process** (`end_process`): it called + `request_quit`, which does nothing once the relaunch has begun a quit, so + a failed relaunch left a hidden process running. +- **The dialog text is escaped for GTK** (`%` doubled, NULs stripped on + Linux): rfd hands the message to GTK as a printf format, so a `%` in an + environment variable or a path crashed the dialog. +- **Quit wins over a waiting relaunch.** A relaunch waits, unbounded, for a + starting tstd to stop (a tstd mid-upgrade is never killed); a tray Quit + during that wait used to do nothing and the app relaunched anyway. Now Quit + cancels the relaunch and the process ends. The window stays empty during + that wait; that is disclosed, not hidden. +- **Disclosed, not fixed:** GTK3 on Wayland cannot report "minimised", so a + window minimised before its first paint may be judged blank and relaunched + once; and after a failed relaunch with no EGL override set, the dialog names + the variable already tried but no other fix. + diff --git a/core/tests/test_display_notice.py b/core/tests/test_display_notice.py new file mode 100644 index 00000000..8a964843 --- /dev/null +++ b/core/tests/test_display_notice.py @@ -0,0 +1,40 @@ +"""Doctor's ``display`` row after the host relaunched its window (TD-5427).""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + +from tstd import display_notice + +from .test_diagnostics import _report, _row + +_REASON = "the web process crashed" + + +def test_the_reason_is_taken_once_so_nothing_else_inherits_it() -> None: + env = {display_notice.NOTICE_ENV: f" {_REASON} ", "PATH": "/bin"} + assert display_notice.take(env) == _REASON + assert env == {"PATH": "/bin"} + assert display_notice.take(env) is None + + +async def test_doctor_says_the_window_was_relaunched( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv(display_notice.NOTICE_ENV, _REASON) + row = _row(await _report(tmp_path), "display") + assert row["status"] == "warn" + assert row["detail"] == ( + "relaunched without compositing because the web view did not draw (the web process crashed)" + ) + assert display_notice.NOTICE_ENV not in os.environ + + +async def test_doctor_has_no_display_row_without_a_relaunch( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv(display_notice.NOTICE_ENV, raising=False) + assert "display" not in [c["name"] for c in await _report(tmp_path)] diff --git a/core/tstd/daemon.py b/core/tstd/daemon.py index cbf6dde5..21e7ec6e 100644 --- a/core/tstd/daemon.py +++ b/core/tstd/daemon.py @@ -34,6 +34,7 @@ cu_gate, cu_stopfile, data_backup, + display_notice, fast_switch, keychain_mcp, managed_guard, @@ -1388,6 +1389,8 @@ def __init__( # so a step stuck on an await reads as a stall to the host. self.start_heartbeat = start_heartbeat self.data_dir = data_dir or user_data_dir() + # TD-5427: why the desktop host relaunched its window, if it did. + self._display_notice = display_notice.take() # UPGRADE-02: first, before any store opens. A folder a newer version # wrote is read-only for this process: nothing in it changes. found = stamped_format(self.data_dir) @@ -2833,8 +2836,9 @@ def walk(node: object) -> None: async def _diagnostics_report(self) -> DiagnosticsReport: """Run the doctor checks (TD-1104) and return the report. - Rows in display order: daemon → key → provider → git → grok_cli → - workspace → steering → skills → optional ``mcp:`` (only when + Rows in display order: daemon → ``display`` (only after a relaunch, + TD-5427) → key → provider → git → grok_cli → workspace → steering → + skills → optional ``mcp:`` (only when ``mcp.servers`` is non-empty). Blocking filesystem calls ride worker threads; the live provider probe is the only slow row (one token, worst case the provider timeout). @@ -2850,6 +2854,8 @@ async def _diagnostics_report(self) -> DiagnosticsReport: detail=f"responding (v{self._version()}, up {self.state.uptime:.1f}s)", ) ] + if self._display_notice: + checks.append(display_notice.doctor_row(self._display_notice)) # API key presence first — presence is free, validity needs the probe. needed: list[str] = [] diff --git a/core/tstd/display_notice.py b/core/tstd/display_notice.py new file mode 100644 index 00000000..67d50e2a --- /dev/null +++ b/core/tstd/display_notice.py @@ -0,0 +1,29 @@ +"""Doctor's ``display`` row: the host relaunched its window (TD-5427). + +The desktop host sets ``TST_DESK_DISPLAY_NOTICE`` on the daemon it spawns +after relaunching itself because its web view did not draw. The value is the +reason. Without a relaunch there is no variable and no row. +""" + +from __future__ import annotations + +import os +from collections.abc import MutableMapping + +from .protocol import DiagnosticCheck + +NOTICE_ENV = "TST_DESK_DISPLAY_NOTICE" + + +def take(env: MutableMapping[str, str] | None = None) -> str | None: + """Read and remove the reason, so nothing this daemon starts inherits it.""" + source = os.environ if env is None else env + return source.pop(NOTICE_ENV, "").strip() or None + + +def doctor_row(reason: str) -> DiagnosticCheck: + return DiagnosticCheck( + name="display", + status="warn", + detail=f"relaunched without compositing because the web view did not draw ({reason})", + ) diff --git a/docs/linux.md b/docs/linux.md index a1f59264..abc87bac 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -207,3 +207,37 @@ reply), and AppImage `--appimage-extract` of the same sidecar. It does not tick the four-platform packaging boxes. macOS and Windows guests use `core/scripts/smoke_macos_bundle.sh` and `core/scripts/smoke_windows_bundle.ps1` (TD-4906). GitHub Actions `package.yml` is a separate gate. + +--- + +## 9. A window that cannot draw + +A WebKitGTK web process that cannot create an EGL display aborts at start +("Could not create default EGL display: EGL_BAD_PARAMETER. Aborting..."). +An EGL vendor override (`__EGL_VENDOR_LIBRARY_FILENAMES`) on a remote-desktop +X display is one way to get there. The window would show its menu and nothing +else, so the app does not leave it that way (TD-5427): + +1. The window tells the host when it has drawn its first frame. `host.log` + says `main window painted (UI ready signal)`. +2. If the web process dies first, or no signal comes within 20 s while the + window is shown, the app replaces itself once with + `WEBKIT_DISABLE_COMPOSITING_MODE=1`, keeping its process id. `host.log` + gives the reason, and Doctor shows a `display` row for that run. +3. If that start cannot draw either, an error dialog quotes the log line and + the web process's last graphics error, and the app exits with status 1. + With the variable already set in your environment there is no relaunch: + the dialog comes at once. + +Compositing off does not cure every EGL failure. With no usable EGL library +at all, only removing the override or repairing the drivers helps, and the +dialog names `__EGL_VENDOR_LIBRARY_FILENAMES` when it is set. + +Each start decides again; nothing is saved. To skip the failed first attempt +on a computer that always needs it, set the variable yourself. +`TST_DESK_PAINT_TIMEOUT_SECS` changes the 20 s wait; it is meant for tests. + +A web process that dies after the window has drawn is logged and nothing more. + +`shell/scripts/egl-fallback-smoke.sh ` forces both +outcomes under Xvfb, and `package.yml` runs it on the Linux AppImages. diff --git a/docs/tst-desk-backlog.md b/docs/tst-desk-backlog.md index b3bea882..df93572a 100644 --- a/docs/tst-desk-backlog.md +++ b/docs/tst-desk-backlog.md @@ -15980,6 +15980,19 @@ A11Y-03's Fix ("make an accidental cancel recoverable") and INTERACT-01 (b), con **Size:** 1 · **Status:** In review +### TD-5427 — A web view that cannot draw is relaunched without compositing, never left blank + +From a live Linux install: the WebKitGTK web process aborted at start ("Could not create default EGL display: EGL_BAD_PARAMETER. Aborting..."), the window showed only the File and Edit menu, nothing said why, and the host still logged "connected to tstd". The manager's requirements: + +- [x] The host detects that the web process died or never painted (no ready signal from the UI within N seconds) and relaunches once with compositing disabled. Log that, and say so in Doctor. +- [x] If it still fails, show a native error dialog with the log line and the env var that fixes it, never a blank window. +- [x] The packaged-launch gate in package.yml checks that the UI actually painted (the ready signal), not just that tstd connected. +- [x] A test that forces an EGL failure. + +N is 20 s. A web process that dies after the window has painted is logged only: the story is the start. Linux only, since the remedy is WebKitGTK's. See `docs/linux.md` §9. + +**Size:** 5 · **Status:** In review + ## 0.5.13 — dialogs, keyboard and accessibility (the UI inspection of 2026-11-28, item 11) The report's "Fix first" item 11: one dialog and keyboard foundation, Undo on Linux, native controls that follow the app's theme, and the four failures a VPAT would have to list as blocking. Each story is one PR with a before/after repro. diff --git a/shell/scripts/egl-fallback-smoke.sh b/shell/scripts/egl-fallback-smoke.sh new file mode 100755 index 00000000..685ceecd --- /dev/null +++ b/shell/scripts/egl-fallback-smoke.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# TD-5427: a forced EGL failure must never leave a blank window. +# +# Usage: egl-fallback-smoke.sh +# +# Needs xvfb-run, dbus-run-session, xdotool and Mesa's EGL vendor file +# (Ubuntu: xvfb xauth dbus xdotool libegl-mesa0). SHOTS= also saves a +# screenshot of each case (needs ImageMagick's `import`). Each case runs on its +# own virtual display with an empty home folder and a private session bus, so +# no real data folder or keychain is touched. package.yml runs it on the +# x86_64 and aarch64 AppImages. +# +# Both failures are real ones, forced from the environment: +# recovers Mesa asked for OpenGL ES 1.0. The web view stays up and draws +# nothing until compositing is off. +# gives-up an EGL vendor file naming a library that does not exist. The web +# process aborts with "Could not create default EGL display" and no +# setting helps: a dialog, then exit 1. +# preset the same, with WEBKIT_DISABLE_COMPOSITING_MODE already set: no +# relaunch. + +set -euo pipefail + +if [[ -z "${EGL_SMOKE_INSIDE:-}" ]]; then + APP=${1:?usage: egl-fallback-smoke.sh } + APP=$(cd "$(dirname "$APP")" && pwd)/$(basename "$APP") + CASES=${CASES:-"recovers gives-up preset"} + for case in $CASES; do + EGL_SMOKE_INSIDE=$case xvfb-run -a -s "-screen 0 1280x860x24" "$0" "$APP" + done + echo "egl fallback smoke passed: $CASES" + exit 0 +fi + +APP=$1 +CASE=$EGL_SMOKE_INSIDE +MESA=/usr/share/glvnd/egl_vendor.d/50_mesa.json +SANDBOX=$(mktemp -d) +mkdir -m 700 "$SANDBOX/run" +LOG="$SANDBOX/.local/share/tst-desk/logs/host.log" +OUT="$SANDBOX/app.out" +echo '{"file_format_version":"1.0.0","ICD":{"library_path":"libEGL_tst_missing.so.0"}}' \ + >"$SANDBOX/missing-vendor.json" + +case "$CASE" in + recovers) + test -f "$MESA" || { echo "no Mesa EGL vendor file at $MESA" >&2; exit 1; } + # A shorter wait than the shipped 20 s, still far above a healthy paint. + VARS=("__EGL_VENDOR_LIBRARY_FILENAMES=$MESA" MESA_GLES_VERSION_OVERRIDE=1.0 + TST_DESK_PAINT_TIMEOUT_SECS=10) ;; + gives-up) + VARS=("__EGL_VENDOR_LIBRARY_FILENAMES=$SANDBOX/missing-vendor.json") ;; + preset) + VARS=("__EGL_VENDOR_LIBRARY_FILENAMES=$SANDBOX/missing-vendor.json" + WEBKIT_DISABLE_COMPOSITING_MODE=1) ;; + *) echo "unknown case $CASE" >&2; exit 1 ;; +esac + +env -i HOME="$SANDBOX" PATH=/usr/bin:/bin LANG=C.UTF-8 XDG_RUNTIME_DIR="$SANDBOX/run" \ + DISPLAY="$DISPLAY" XAUTHORITY="${XAUTHORITY:-}" APPIMAGE_EXTRACT_AND_RUN=1 "${VARS[@]}" \ + setsid dbus-run-session -- "$APP" >"$OUT" 2>&1 & +PID=$! + +finish() { + kill -- "-$PID" 2>/dev/null || true + rm -rf "$SANDBOX" 2>/dev/null || true +} +trap finish EXIT + +fail() { + echo "::error::egl fallback ($CASE): $1" + echo "--- host.log"; cat "$LOG" 2>/dev/null || true + echo "--- app output"; tail -40 "$OUT" || true + exit 1 +} + +# wait_for : up to 90 s. +wait_for() { + local what=$1 + shift + for _ in $(seq 1 900); do + "$@" >/dev/null 2>&1 && return 0 + kill -0 "$PID" 2>/dev/null || fail "the app ended while waiting for $what" + sleep 0.1 + done + fail "no $what after 90 s" +} + +shot() { + [[ -n "${SHOTS:-}" ]] || return 0 + mkdir -p "$SHOTS" && import -window root "$SHOTS/egl-$CASE.png" +} + +count() { grep -c -- "$1" "$LOG" 2>/dev/null || true; } + +if [[ "$CASE" == recovers ]]; then + wait_for "relaunch" grep -q "relaunching once with WEBKIT_DISABLE_COMPOSITING_MODE=1" "$LOG" + wait_for "painted window after the relaunch" \ + grep -q "main window painted.*relaunched without compositing" "$LOG" + sleep 3 # for the screenshot: let the first view settle + shot + [[ $(count "relaunching once") == 1 ]] || fail "relaunched more than once" + [[ $(count "giving up") == 0 ]] || fail "gave up after painting" +else + TITLE="TST Desk cannot draw its window" + wait_for "error dialog" xdotool search --name "$TITLE" + sleep 1 + shot + grep -q "Could not create default EGL display" "$OUT" || fail "EGL did not fail as forced" + grep -q "Log line: the web view did not draw" "$OUT" || fail "the dialog names no log line" + grep -q "Web process: Could not create default EGL display" "$OUT" || + fail "the dialog does not quote the web process" + [[ $(count "giving up") == 1 ]] || fail "no single give-up line in host.log" + RELAUNCHES=1 + [[ "$CASE" == preset ]] && RELAUNCHES=0 + [[ $(count "relaunching once") == "$RELAUNCHES" ]] || + fail "expected $RELAUNCHES relaunch(es)" + [[ $(count "main window painted") == 0 ]] || fail "a window that cannot draw claimed to paint" + # Close the dialog as a person would (Enter on its button). + xdotool windowfocus --sync "$(xdotool search --name "$TITLE" | head -1)" key Return + for _ in $(seq 1 300); do + kill -0 "$PID" 2>/dev/null || break + sleep 0.1 + done + kill -0 "$PID" 2>/dev/null && fail "still running 30 s after the dialog was closed" + STATUS=0 + wait "$PID" || STATUS=$? + [[ "$STATUS" == 1 ]] || fail "exit status $STATUS, expected 1" +fi + +echo "--- egl fallback ($CASE) passed" +grep -E "host started|web view|relaunch|main window painted|giving up|stop shortcut" "$LOG" || true diff --git a/shell/src/daemon/mod.rs b/shell/src/daemon/mod.rs index 8c398df3..72b7ba20 100644 --- a/shell/src/daemon/mod.rs +++ b/shell/src/daemon/mod.rs @@ -685,6 +685,8 @@ pub fn spawn_daemon_with( crate::cu_agent::sock_path(data_dir), ); } + // TD-5427: Doctor says when the window was relaunched. + crate::webview_watch::tell_daemon(&mut cmd); daemon_pid::apply_process_group(&mut cmd); cmd.spawn().map_err(|e| format!("spawn failed: {e}")) } diff --git a/shell/src/lib.rs b/shell/src/lib.rs index 559abe4c..834746ab 100644 --- a/shell/src/lib.rs +++ b/shell/src/lib.rs @@ -22,6 +22,7 @@ mod stop_hotkey; mod tray; mod updater; mod webview_menu; +mod webview_watch; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; @@ -139,6 +140,9 @@ fn raise_window(app: &tauri::AppHandle, window: &WebviewWindow) { /// window closed under Keep running (TD-5020) there is nothing to /// raise, so this opens a desk window instead of doing nothing. pub(crate) fn show_any_window(app: &tauri::AppHandle) { + if webview_watch::window_withheld() { + return; + } let windows = app.webview_windows(); match show_target(windows.keys().map(String::as_str), is_quitting()) { ShowTarget::Existing(label) => { @@ -179,6 +183,9 @@ fn approval_notice( } fn open_desk_window(app: &tauri::AppHandle) -> tauri::Result<()> { + if webview_watch::window_withheld() { + return Ok(()); + } let n = WINDOW_SEQ.fetch_add(1, Ordering::SeqCst); let label = format!("desk-{n}"); WebviewWindowBuilder::new(app, &label, WebviewUrl::App("index.html".into())) @@ -226,6 +233,9 @@ fn build_tray(app: &tauri::App) -> tauri::Result<()> { pub(crate) fn request_quit(app: &tauri::AppHandle) { if !begin_quit() { + // A relaunch may be waiting for tstd to stop: Quit then means quit, + // not relaunch (TD-5427 review round 1). + webview_watch::cancel_relaunch(); return; } log::info!("quit requested; stopping tstd"); @@ -242,8 +252,30 @@ pub(crate) fn request_quit(app: &tauri::AppHandle) { tokio::join!(handle.wait_for_done(), embeddings.wait_for_done()); }) .await; + end_process(app, webview_watch::exit_code()); + }); +} + +/// The last step of a quit. Tauri's `exit` ends the process with 0 whatever +/// code it is given (the event loop just exits), so a failing code is applied +/// here, after the same cleanup its `Exit` event would run. +pub(crate) fn end_process(app: tauri::AppHandle, code: i32) { + if code == 0 { app.exit(0); + return; + } + let handle = app.clone(); + let queued = app.run_on_main_thread(move || { + daemon::on_host_exit( + &handle.state::(), + &handle.state::(), + ); + handle.cleanup_before_exit(); + std::process::exit(code); }); + if queued.is_err() { + std::process::exit(code); + } } /// First hide only: stamp the user-data flag and say close is not quit. @@ -345,6 +377,8 @@ fn build_app_menu(app: &tauri::App) -> tauri::Result> { #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { + // TD-5427: before any thread and any web view exists. + webview_watch::before_start(); tauri::Builder::default() // TD-5024: first, so a second launch hands over and exits before // any other plugin, window or daemon supervisor starts in it. @@ -352,6 +386,8 @@ pub fn run() { // RENDERSEC-01: no webview navigates away from the app. .plugin(nav_guard::plugin()) .plugin(webview_menu::plugin()) + // TD-5427: a web view that cannot draw is never left blank. + .plugin(webview_watch::plugin()) .plugin( tauri_plugin_window_state::Builder::default() .with_denylist(&[quick_entry::WINDOW_LABEL]) @@ -399,6 +435,7 @@ pub fn run() { stop_hotkey::setup(app.handle(), &daemon::data_dir()); quick_entry::setup(app)?; updater::start(app.handle()); + webview_watch::start(app.handle()); // WEBKIT-03: only with TST_DESK_SMOKE_REPORT set (package.yml). smoke::start(app.handle()); Ok(()) @@ -426,6 +463,7 @@ pub fn run() { tray::set_tray_running_count, session_window::open_session_window, smoke::smoke_report, + webview_watch::ui_painted, updater::check_for_updates, updater::update_status, updater::download_update, diff --git a/shell/src/updater/apply.rs b/shell/src/updater/apply.rs index 75f16e48..d4a3f1e5 100644 --- a/shell/src/updater/apply.rs +++ b/shell/src/updater/apply.rs @@ -309,6 +309,8 @@ pub fn spawn_helper( .stdin(Stdio::null()) .stdout(log) .stderr(err); + // TD-5427: the new version decides about compositing itself. + crate::webview_watch::drop_own_variable(&mut cmd); #[cfg(unix)] { use std::os::unix::process::CommandExt; diff --git a/shell/src/webview_watch/decide.rs b/shell/src/webview_watch/decide.rs new file mode 100644 index 00000000..97f009e9 --- /dev/null +++ b/shell/src/webview_watch/decide.rs @@ -0,0 +1,326 @@ +//! What to do about a start whose web view does not draw (TD-5427). No +//! Tauri and no clock here, so every outcome is tested directly. + +use std::time::Duration; + +/// WebKitGTK reads this once per process, before it starts a web process. +pub const COMPOSITING_VAR: &str = "WEBKIT_DISABLE_COMPOSITING_MODE"; +/// The variable behind the failure seen in the field: a graphics override +/// that leaves WebKitGTK no EGL display. +pub const EGL_VENDOR_VAR: &str = "__EGL_VENDOR_LIBRARY_FILENAMES"; + +/// How this process was started. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Start { + /// Why the previous process relaunched into this one, if it did. + pub relaunched: Option, + /// [`COMPOSITING_VAR`] as this process found it, whoever set it. + pub compositing_var: Option, +} + +/// What kept the main window from drawing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Failure { + /// The web process ended; the text says how. + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] // only Linux watches + ProcessDied(&'static str), + /// No ready signal arrived in this long. + NoPaint(Duration), +} + +impl Failure { + pub fn reason(self) -> String { + match self { + Self::ProcessDied(how) => format!("the web process {how}"), + Self::NoPaint(waited) => format!("no ready signal within {} s", waited.as_secs()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Action { + /// Start the app again with compositing disabled. + Relaunch { reason: String }, + /// Say so in a native dialog and exit with an error. + GiveUp { reason: String }, +} + +/// The main window as it stands when the wait runs out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Window { + Shown, + /// Hidden or minimised: WebKit draws no frames then, so silence says nothing. + Hidden, + Closed, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Tick { + Act(Action), + WaitAgain, + Stop, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Phase { + Waiting, + Painted, + Acted, +} + +/// One start's watch. It acts at most once. +#[derive(Debug)] +pub struct Watch { + start: Start, + phase: Phase, +} + +impl Watch { + pub fn new(start: Start) -> Self { + Self { + start, + phase: Phase::Waiting, + } + } + + pub fn start(&self) -> &Start { + &self.start + } + + /// The ready signal. True the first time, while the watch is still waiting. + pub fn painted(&mut self) -> bool { + let first = self.phase == Phase::Waiting; + if first { + self.phase = Phase::Painted; + } + first + } + + /// A failed start. `None` once the window has painted or an action is + /// under way. A process that already has [`COMPOSITING_VAR`] set, by the + /// relaunch or by the person, is never relaunched. + pub fn failed(&mut self, failure: Failure) -> Option { + if self.phase != Phase::Waiting { + return None; + } + self.phase = Phase::Acted; + let reason = failure.reason(); + let tried = self.start.relaunched.is_some() || self.start.compositing_var.is_some(); + Some(if tried { + Action::GiveUp { reason } + } else { + Action::Relaunch { reason } + }) + } + + /// The wait of length `waited` ran out. + pub fn deadline(&mut self, window: Window, waited: Duration) -> Tick { + if self.phase != Phase::Waiting { + return Tick::Stop; + } + match window { + Window::Closed => Tick::Stop, + Window::Hidden => Tick::WaitAgain, + Window::Shown => self + .failed(Failure::NoPaint(waited)) + .map_or(Tick::Stop, Tick::Act), + } + } +} + +/// The error dialog's text: what happened, the log line, what the web +/// process printed, and the variable that fixes it. +pub fn dialog_text( + start: &Start, + log_line: &str, + web_line: Option<&str>, + egl_override: Option<&str>, + log_file: &str, +) -> String { + let tried = match (&start.relaunched, start.compositing_var.as_deref()) { + (Some(_), _) => format!( + "TST Desk could not draw its window, and relaunching it with \ + {COMPOSITING_VAR}=1 did not help." + ), + (None, Some("1")) => format!( + "TST Desk could not draw its window. {COMPOSITING_VAR}=1 is already set, \ + so it was not relaunched." + ), + (None, value) => format!( + "TST Desk could not draw its window. {COMPOSITING_VAR} is already set to \ + \"{}\", so it was not relaunched. Set {COMPOSITING_VAR}=1 and start TST Desk \ + again.", + value.unwrap_or_default() + ), + }; + let mut text = format!("{tried}\n\nLog line: {log_line}"); + if let Some(line) = web_line { + text.push_str(&format!("\n\nWeb process: {line}")); + } + match egl_override { + Some(value) => text.push_str(&format!( + "\n\n{EGL_VENDOR_VAR} is set to \"{value}\". Unset it and start TST Desk again." + )), + None if start.relaunched.is_some() || start.compositing_var.as_deref() == Some("1") => { + text.push_str( + "\n\nCheck this computer's graphics drivers and any EGL or WebKit \ + variables TST Desk is started with.", + ); + } + None => {} + } + text.push_str(&format!("\n\nThe full log is {log_file}.")); + text +} + +#[cfg(test)] +mod tests { + use super::*; + + const WAIT: Duration = Duration::from_secs(20); + + fn fresh() -> Watch { + Watch::new(Start::default()) + } + + fn relaunched() -> Watch { + Watch::new(Start { + relaunched: Some("the web process crashed".into()), + compositing_var: Some("1".into()), + }) + } + + #[test] + fn ready_in_time_means_no_relaunch() { + let mut watch = fresh(); + assert!(watch.painted()); + assert_eq!(watch.deadline(Window::Shown, WAIT), Tick::Stop); + assert!(!watch.painted(), "a second signal is not news"); + } + + #[test] + fn never_ready_relaunches_once() { + let mut watch = fresh(); + assert_eq!( + watch.deadline(Window::Shown, WAIT), + Tick::Act(Action::Relaunch { + reason: "no ready signal within 20 s".into() + }) + ); + assert_eq!(watch.deadline(Window::Shown, WAIT), Tick::Stop); + assert_eq!(watch.failed(Failure::ProcessDied("crashed")), None); + assert!(!watch.painted()); + } + + #[test] + fn a_dead_web_process_relaunches_without_waiting() { + let mut watch = fresh(); + assert_eq!( + watch.failed(Failure::ProcessDied("crashed")), + Some(Action::Relaunch { + reason: "the web process crashed".into() + }) + ); + assert_eq!(watch.deadline(Window::Shown, WAIT), Tick::Stop); + } + + #[test] + fn still_not_ready_after_the_relaunch_gives_up() { + let mut silent = relaunched(); + assert_eq!( + silent.deadline(Window::Shown, WAIT), + Tick::Act(Action::GiveUp { + reason: "no ready signal within 20 s".into() + }) + ); + let mut dead = relaunched(); + assert_eq!( + dead.failed(Failure::ProcessDied("crashed")), + Some(Action::GiveUp { + reason: "the web process crashed".into() + }) + ); + } + + #[test] + fn the_relaunch_mark_alone_stops_a_second_relaunch() { + // Even if the variable were lost on the way. + let mut watch = Watch::new(Start { + relaunched: Some("x".into()), + compositing_var: None, + }); + assert!(matches!( + watch.failed(Failure::ProcessDied("crashed")), + Some(Action::GiveUp { .. }) + )); + } + + #[test] + fn a_variable_the_person_set_is_never_relaunched() { + for value in ["1", "0", ""] { + let mut watch = Watch::new(Start { + relaunched: None, + compositing_var: Some(value.into()), + }); + assert!( + matches!( + watch.deadline(Window::Shown, WAIT), + Tick::Act(Action::GiveUp { .. }) + ), + "{value:?}" + ); + } + } + + #[test] + fn a_window_that_is_not_shown_is_not_judged() { + let mut watch = fresh(); + assert_eq!(watch.deadline(Window::Hidden, WAIT), Tick::WaitAgain); + assert!(matches!( + watch.deadline(Window::Shown, WAIT), + Tick::Act(Action::Relaunch { .. }) + )); + assert_eq!(fresh().deadline(Window::Closed, WAIT), Tick::Stop); + } + + #[test] + fn a_web_process_that_dies_after_painting_changes_nothing() { + let mut watch = fresh(); + watch.painted(); + assert_eq!(watch.failed(Failure::ProcessDied("crashed")), None); + } + + #[test] + fn the_dialog_names_the_log_line_the_web_line_and_the_variables() { + let text = dialog_text( + relaunched().start(), + "the web view did not draw (the web process crashed)", + Some("Could not create default EGL display: EGL_BAD_PARAMETER. Aborting..."), + Some("/etc/vendor.json"), + "/data/logs/host.log", + ); + for want in [ + "WEBKIT_DISABLE_COMPOSITING_MODE=1 did not help", + "Log line: the web view did not draw (the web process crashed)", + "Web process: Could not create default EGL display", + "__EGL_VENDOR_LIBRARY_FILENAMES is set to \"/etc/vendor.json\". Unset it", + "/data/logs/host.log", + ] { + assert!(text.contains(want), "{want}\n{text}"); + } + } + + #[test] + fn the_dialog_says_what_to_set_when_the_person_set_something_else() { + let start = Start { + relaunched: None, + compositing_var: Some("0".into()), + }; + let text = dialog_text(&start, "line", None, None, "log"); + assert!( + text.contains("Set WEBKIT_DISABLE_COMPOSITING_MODE=1"), + "{text}" + ); + assert!(!text.contains("Web process:"), "{text}"); + } +} diff --git a/shell/src/webview_watch/mod.rs b/shell/src/webview_watch/mod.rs new file mode 100644 index 00000000..b723c16a --- /dev/null +++ b/shell/src/webview_watch/mod.rs @@ -0,0 +1,411 @@ +//! A web view that cannot draw is never left blank (TD-5427). +//! +//! On Linux a WebKitGTK web process that aborts at start (an EGL display it +//! cannot create, for one) left a window with a menu bar, nothing in it and +//! nothing said. The host now waits for the window's ready signal +//! ([`ui_painted`]). If the web process dies first, or the signal does not +//! come, the app replaces itself once with compositing disabled; if that +//! fails too, a native dialog says why and the app exits with an error. +//! +//! The whole app is replaced rather than the web view because WebKitGTK reads +//! [`decide::COMPOSITING_VAR`] once per process. macOS and Windows log the +//! ready signal and do nothing else: the remedy is WebKitGTK's. + +mod decide; +#[cfg(target_os = "linux")] +mod stderr_relay; + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use tauri::plugin::{Builder, TauriPlugin}; +use tauri::{AppHandle, Manager, WebviewWindow, Wry}; +use tauri_plugin_dialog::{DialogExt, MessageDialogKind}; + +use crate::daemon::coworker::MAIN_WINDOW_LABEL; +#[cfg(target_os = "linux")] +use decide::Failure; +use decide::{dialog_text, Action, Start, Tick, Watch, Window}; +use decide::{COMPOSITING_VAR, EGL_VENDOR_VAR}; + +/// Set on the relaunched process, holding why. Read and removed at start. +const RELAUNCH_VAR: &str = "TST_DESK_COMPOSITING_RELAUNCH"; +/// How tstd learns of the relaunch, for Doctor (`core/tstd/display_notice.py`). +const DAEMON_NOTICE_VAR: &str = "TST_DESK_DISPLAY_NOTICE"; +/// Overrides [`PAINT_WAIT`], in whole seconds, so a test need not sit it out. +const WAIT_VAR: &str = "TST_DESK_PAINT_TIMEOUT_SECS"; +/// A working window signals within a couple of seconds, and a web process +/// that dies is acted on at once. This long wait is only for a view that +/// stays alive and silent; it is generous because acting on a slow but +/// healthy start would restart the app, and a second slow start would end it. +const PAINT_WAIT: Duration = Duration::from_secs(20); +/// Time for the relay to hand over the lines a dead web process printed. +const RELAY_DRAIN: Duration = Duration::from_millis(200); + +static START: OnceLock = OnceLock::new(); +static LAUNCHED: OnceLock = OnceLock::new(); +/// A relaunch or the error dialog is under way: no window is to be shown. +static ACTING: AtomicBool = AtomicBool::new(false); +static GAVE_UP: AtomicBool = AtomicBool::new(false); + +struct Shared(Mutex); + +/// Read how this process was started and set up the stderr relay. First in +/// `run()`: it forks, and it edits the environment, before any thread exists. +pub(crate) fn before_start() { + LAUNCHED.get_or_init(Instant::now); + #[cfg(target_os = "linux")] + stderr_relay::install(); + let start = Start { + relaunched: std::env::var(RELAUNCH_VAR).ok(), + compositing_var: std::env::var_os(COMPOSITING_VAR) + .map(|v| v.to_string_lossy().into_owned()), + }; + // Not for tstd, an update's relaunch or anything else this app starts. + std::env::remove_var(RELAUNCH_VAR); + START.get_or_init(|| start); +} + +fn relaunch_reason() -> Option<&'static str> { + START.get()?.relaunched.as_deref() +} + +/// Whether this host set [`COMPOSITING_VAR`] itself. A process it starts to +/// replace the app (the updater) must not inherit it as the person's choice. +pub(crate) fn drop_own_variable(command: &mut std::process::Command) { + if relaunch_reason().is_some() { + command.env_remove(COMPOSITING_VAR); + } +} + +/// Tell the daemon being spawned why the window was relaunched, if it was. +pub(crate) fn tell_daemon(command: &mut tokio::process::Command) { + match relaunch_reason() { + Some(reason) => command.env(DAEMON_NOTICE_VAR, reason), + None => command.env_remove(DAEMON_NOTICE_VAR), + }; +} + +/// A relaunch or the error dialog is under way, so a blank window must not +/// be raised by the tray or a second launch. +pub(crate) fn window_withheld() -> bool { + ACTING.load(Ordering::SeqCst) +} + +/// The exit code a quit should end with. +/// Set when Quit is asked for while a relaunch waits for tstd to stop. +static RELAUNCH_CANCELLED: AtomicBool = AtomicBool::new(false); + +/// Quit wins over a relaunch still waiting (TD-5427 review round 1): before, +/// tray Quit did nothing, as a quit was already under way for the relaunch. +pub(crate) fn cancel_relaunch() { + RELAUNCH_CANCELLED.store(true, Ordering::SeqCst); +} + +/// Text GTK's message dialog shows as written: it reads the message as a +/// printf format, so a `%` from an environment variable or a path crashed +/// it, and a NUL cut it short (TD-5427 review round 1). +fn dialog_safe(text: &str) -> String { + let clean = text.replace('\0', ""); + if cfg!(target_os = "linux") { + clean.replace('%', "%%") + } else { + clean + } +} + +pub(crate) fn exit_code() -> i32 { + i32::from(GAVE_UP.load(Ordering::SeqCst)) +} + +pub(crate) fn plugin() -> TauriPlugin { + Builder::new("webview-watch") + .setup(|app, _| { + let start = START.get().cloned().unwrap_or_default(); + app.manage(Shared(Mutex::new(Watch::new(start)))); + Ok(()) + }) + .on_webview_ready(|webview| { + #[cfg(target_os = "linux")] + if webview.label() == MAIN_WINDOW_LABEL { + watch_web_process(&webview); + } + #[cfg(not(target_os = "linux"))] + let _ = webview; + }) + .build() +} + +/// Tauri reports a dead web process on Apple platforms only, so this takes +/// WebKitGTK's own signal. +#[cfg(target_os = "linux")] +fn watch_web_process(webview: &tauri::Webview) { + use webkit2gtk::{WebProcessTerminationReason as Reason, WebViewExt}; + + let app = webview.app_handle().clone(); + let connected = webview.with_webview(move |platform| { + platform + .inner() + .connect_web_process_terminated(move |_, reason| { + let how = match reason { + Reason::Crashed => "crashed", + Reason::ExceededMemoryLimit => "exceeded its memory limit", + _ => "was terminated", + }; + web_process_died(&app, how); + }); + }); + if let Err(e) = connected { + log::warn!("the web process is not watched: {e}"); + } +} + +#[cfg(target_os = "linux")] +fn web_process_died(app: &AppHandle, how: &'static str) { + if crate::is_quitting() { + return; + } + let action = watch(app).failed(Failure::ProcessDied(how)); + match action { + Some(action) => act(app, action), + None => log::warn!("the web process {how}"), + } +} + +fn watch(app: &AppHandle) -> std::sync::MutexGuard<'_, Watch> { + app.state::() + .inner() + .0 + .lock() + .unwrap_or_else(|e| e.into_inner()) +} + +/// The window drew its first frame (`ui/src/lib/paint-signal.ts`). +#[tauri::command] +pub(crate) fn ui_painted(window: WebviewWindow) { + if window.label() != MAIN_WINDOW_LABEL { + return; + } + if watch(window.app_handle()).painted() { + let after = LAUNCHED.get().map(|t| t.elapsed()).unwrap_or_default(); + // package.yml's launch gate looks for the first three words. + log::info!( + "main window painted (UI ready signal) {:.1} s after launch{}", + after.as_secs_f32(), + if relaunch_reason().is_some() { + ", relaunched without compositing" + } else { + "" + } + ); + } +} + +fn paint_wait(value: Option<&str>) -> Duration { + value + .and_then(|v| v.trim().parse().ok()) + .filter(|secs| *secs > 0) + .map_or(PAINT_WAIT, Duration::from_secs) +} + +/// Start waiting for the ready signal. Call once the daemon is managed. +pub(crate) fn start(app: &AppHandle) { + if let Some(reason) = relaunch_reason() { + log::warn!( + "relaunched with {COMPOSITING_VAR}=1 because the web view did not draw ({reason})" + ); + } + if !cfg!(target_os = "linux") { + return; + } + let wait = paint_wait(std::env::var(WAIT_VAR).ok().as_deref()); + let app = app.clone(); + tauri::async_runtime::spawn(async move { + loop { + tokio::time::sleep(wait).await; + if crate::is_quitting() { + return; + } + let state = window_state(&app); + let tick = watch(&app).deadline(state, wait); + match tick { + Tick::WaitAgain => continue, + Tick::Stop => return, + Tick::Act(action) => { + let handle = app.clone(); + if let Err(e) = app.run_on_main_thread(move || act(&handle, action)) { + log::error!("could not act on the blank window: {e}"); + } + return; + } + } + } + }); +} + +fn window_state(app: &AppHandle) -> Window { + match app.get_webview_window(MAIN_WINDOW_LABEL) { + None => Window::Closed, + Some(w) => { + let hidden = !w.is_visible().unwrap_or(true) || w.is_minimized().unwrap_or(false); + if hidden { + Window::Hidden + } else { + Window::Shown + } + } + } +} + +/// Runs on the main thread. +fn act(app: &AppHandle, action: Action) { + ACTING.store(true, Ordering::SeqCst); + for window in app.webview_windows().values() { + let _ = window.hide(); + } + match action { + Action::Relaunch { reason } => relaunch(app, reason), + Action::GiveUp { reason } => give_up(app, reason), + } +} + +fn web_line() -> Option { + #[cfg(target_os = "linux")] + return stderr_relay::last_line(); + #[cfg(not(target_os = "linux"))] + None +} + +fn said(line: Option<&str>) -> String { + line.map(|l| format!("; the web process said: {l}")) + .unwrap_or_default() +} + +/// Stop tstd the way Quit does, then replace this process. +fn relaunch(app: &AppHandle, reason: String) { + if !crate::begin_quit() { + return; + } + let app = app.clone(); + tauri::async_runtime::spawn(async move { + tokio::time::sleep(RELAY_DRAIN).await; + log::warn!( + "the web view did not draw ({reason}){}; relaunching once with {COMPOSITING_VAR}=1", + said(web_line().as_deref()) + ); + // No time limit: a tstd still starting is stopped once it answers, + // so the next one finds the data folder free. The supervisor bounds + // that start itself. + let daemon = app.state::().inner().clone(); + let embeddings = app.state::().inner().clone(); + daemon.request_shutdown(); + embeddings.request_shutdown(); + tokio::join!(daemon.wait_for_done(), embeddings.wait_for_done()); + if RELAUNCH_CANCELLED.load(Ordering::SeqCst) { + log::info!("quit was asked for while the relaunch waited; quitting instead"); + crate::end_process(app, exit_code()); + return; + } + let handle = app.clone(); + if let Err(e) = app.run_on_main_thread(move || replace_process(&handle, reason)) { + log::error!("could not relaunch: {e}"); + } + }); +} + +/// Same program, arguments and process id, with compositing disabled. +fn replace_process(app: &AppHandle, reason: String) { + app.cleanup_before_exit(); + // The new process must be able to claim the single-instance name. + tauri_plugin_single_instance::destroy(app); + #[cfg(unix)] + let error = { + use std::os::unix::process::CommandExt; + match std::env::current_exe() { + Ok(exe) => { + #[cfg(target_os = "linux")] + stderr_relay::restore(); + std::process::Command::new(exe) + .args(std::env::args_os().skip(1)) + .env(COMPOSITING_VAR, "1") + .env(RELAUNCH_VAR, &reason) + .exec() + .to_string() + } + Err(e) => e.to_string(), + } + }; + #[cfg(not(unix))] + let error = "relaunching is not supported here".to_string(); + // exec returns only when it failed. + log::error!("could not relaunch: {error}"); + give_up(app, format!("{reason}; the relaunch failed: {error}")); +} + +/// Say what happened in a native dialog, then quit with an error. +fn give_up(app: &AppHandle, reason: String) { + GAVE_UP.store(true, Ordering::SeqCst); + let app = app.clone(); + tauri::async_runtime::spawn(async move { + tokio::time::sleep(RELAY_DRAIN).await; + let start = watch(&app).start().clone(); + let line = web_line(); + let log_line = format!("the web view did not draw ({reason}); giving up"); + log::error!("{log_line}{}", said(line.as_deref())); + let log_file = crate::daemon::log_files::logs_dir(&crate::daemon::data_dir()) + .join("host.log") + .display() + .to_string(); + let egl = std::env::var(EGL_VENDOR_VAR).ok(); + let text = dialog_text( + &start, + &log_line, + line.as_deref(), + egl.as_deref(), + &log_file, + ); + // Also on stderr, for a launch from a terminal or a script. + eprintln!("TST Desk: {}", text.replace('\0', "")); + let handle = app.clone(); + // OK ends the process: request_quit did nothing once the relaunch had + // begun the quit, leaving a hidden process (TD-5427 review round 1). + app.dialog() + .message(dialog_safe(&text)) + .title("TST Desk cannot draw its window") + .kind(MessageDialogKind::Error) + .show(move |_| crate::end_process(handle, exit_code())); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dialog_text_with_percent_and_nul_is_shown_as_written() { + let raw = "__EGL_VENDOR_LIBRARY_FILENAMES=/x/%s%n.json\0tail"; + let safe = dialog_safe(raw); + assert!(!safe.contains('\0')); + if cfg!(target_os = "linux") { + assert!(safe.contains("%%s%%n")); + } + } + + #[test] + fn quit_during_a_relaunch_cancels_it() { + RELAUNCH_CANCELLED.store(false, Ordering::SeqCst); + cancel_relaunch(); + assert!(RELAUNCH_CANCELLED.load(Ordering::SeqCst)); + RELAUNCH_CANCELLED.store(false, Ordering::SeqCst); + } + + + #[test] + fn the_wait_defaults_and_can_be_overridden() { + assert_eq!(paint_wait(None), PAINT_WAIT); + assert_eq!(paint_wait(Some("3")), Duration::from_secs(3)); + assert_eq!(paint_wait(Some("0")), PAINT_WAIT); + assert_eq!(paint_wait(Some("soon")), PAINT_WAIT); + } +} diff --git a/shell/src/webview_watch/stderr_relay.rs b/shell/src/webview_watch/stderr_relay.rs new file mode 100644 index 00000000..676f2ce7 --- /dev/null +++ b/shell/src/webview_watch/stderr_relay.rs @@ -0,0 +1,184 @@ +//! Remembers what the web process printed before it died (TD-5427). +//! +//! WebKitGTK starts its web process itself and the child inherits the host's +//! stderr, so the only way to read its last words is to stand between that +//! stderr and where it went. A small forked process does the copying: it +//! passes every byte on unchanged and hands the host a second copy. It is a +//! process rather than a thread so that nothing printed is lost, and no +//! writer gets a broken pipe, if the host itself aborts or exits first. + +use std::io::{BufRead, BufReader}; +use std::os::fd::{FromRawFd, RawFd}; +use std::sync::atomic::{AtomicI32, Ordering}; +use std::sync::Mutex; + +/// The stderr this process was started with, while the relay stands. +static ORIGINAL: AtomicI32 = AtomicI32::new(-1); +static LAST: Mutex> = Mutex::new(None); + +/// How much a line says about a view that cannot draw. +fn rank(line: &str) -> u8 { + let lower = line.to_ascii_lowercase(); + let graphics = lower.contains("egl") || lower.contains("gbm"); + // Mesa follows a failure with lines that only list devices; skip those. + let failure = ["error", "fail", "could not"] + .iter() + .any(|w| lower.contains(w)); + if line.contains("Aborting") { + 2 + } else { + u8::from(graphics && failure) + } +} + +/// Keep the newest line of the highest rank seen. +fn remember(slot: &mut Option<(u8, String)>, line: &str) { + let line = line.trim(); + let found = rank(line); + if found > 0 && slot.as_ref().map_or(true, |(kept, _)| found >= *kept) { + *slot = Some((found, line.to_string())); + } +} + +/// The web process's last graphics error, if it printed one. +pub fn last_line() -> Option { + let slot = LAST.lock().unwrap_or_else(|e| e.into_inner()); + slot.as_ref().map(|(_, line)| line.clone()) +} + +fn pipe() -> Option<(RawFd, RawFd)> { + let mut fds = [0; 2]; + // SAFETY: pipe2 writes two descriptors into the array it is given. + (unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) } == 0).then(|| (fds[0], fds[1])) +} + +/// The forked copier. Only async-signal-safe calls: read, write, _exit. +/// +/// # Safety +/// Must run in the child of a fork, and never returns. +unsafe fn copy_until_closed(from: RawFd, original: RawFd, tap: RawFd) -> ! { + let mut buf = [0u8; 4096]; + loop { + let read = libc::read(from, buf.as_mut_ptr().cast(), buf.len()); + if read < 0 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted { + continue; + } + if read <= 0 { + // Every writer is gone. + libc::_exit(0); + } + let mut sent = 0; + while sent < read as usize { + let n = libc::write(original, buf[sent..].as_ptr().cast(), read as usize - sent); + if n <= 0 { + break; + } + sent += n as usize; + } + // Non-blocking: a host that stopped reading must not stall stderr. + libc::write(tap, buf.as_ptr().cast(), read as usize); + } +} + +/// Put the relay in place. Call before any thread and any web view starts. +/// If it cannot be set up, stderr stays as it was and no line is captured. +pub fn install() { + let Some((data_read, data_write)) = pipe() else { + return; + }; + let Some((tap_read, tap_write)) = pipe() else { + return; + }; + // SAFETY: plain descriptor calls; the fork happens while this process has + // one thread, and the child only reads, writes and exits. + unsafe { + let original = libc::fcntl(libc::STDERR_FILENO, libc::F_DUPFD_CLOEXEC, 3); + if original < 0 { + return; + } + libc::fcntl(tap_write, libc::F_SETFL, libc::O_NONBLOCK); + // Forked twice, so the copier is not this process's child and no + // zombie is left when it ends. + match libc::fork() { + -1 => return, + 0 => { + libc::close(data_write); + libc::close(tap_read); + match libc::fork() { + 0 => copy_until_closed(data_read, original, tap_write), + pid => libc::_exit(i32::from(pid < 0)), + } + } + first => { + let mut status = 0; + while libc::waitpid(first, &mut status, 0) < 0 + && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted + { + } + if status != 0 { + return; + } + } + } + libc::close(data_read); + libc::close(tap_write); + // dup2 leaves fd 2 open across exec, so children write to the relay. + if libc::dup2(data_write, libc::STDERR_FILENO) >= 0 { + ORIGINAL.store(original, Ordering::SeqCst); + } + libc::close(data_write); + } + // SAFETY: tap_read is an open descriptor that nothing else owns. + let tap = unsafe { std::fs::File::from_raw_fd(tap_read) }; + std::thread::spawn(move || { + for line in BufReader::new(tap).split(b'\n').map_while(Result::ok) { + let mut slot = LAST.lock().unwrap_or_else(|e| e.into_inner()); + remember(&mut slot, &String::from_utf8_lossy(&line)); + } + }); +} + +/// Point stderr back where it was, so a relaunched process starts clean. +pub fn restore() { + let original = ORIGINAL.swap(-1, Ordering::SeqCst); + if original >= 0 { + // SAFETY: `original` is the descriptor `install` duplicated. + unsafe { libc::dup2(original, libc::STDERR_FILENO) }; + } +} + +#[cfg(test)] +mod tests { + use super::remember; + + const ABORT: &str = "Could not create default EGL display: EGL_BAD_PARAMETER. Aborting..."; + + fn kept(lines: &[&str]) -> Option { + let mut slot = None; + for line in lines { + remember(&mut slot, line); + } + slot.map(|(_, line)| line) + } + + #[test] + fn the_abort_line_outlasts_later_graphics_warnings() { + let lines = ["unrelated", ABORT, "libEGL warning: DRI3 error", "other"]; + assert_eq!(kept(&lines).as_deref(), Some(ABORT)); + } + + #[test] + fn the_newest_graphics_failure_is_kept_without_an_abort() { + let lines = [ + "libEGL warning: DRI3 error: Could not get DRI3 device", + "libEGL warning: egl: failed to create dri2 screen", + "libEGL warning: pci id for fd 20: 10de:2204, driver (null)", + "a library failed to load", + ]; + assert_eq!( + kept(&lines).as_deref(), + Some("libEGL warning: egl: failed to create dri2 screen") + ); + assert_eq!(kept(&["noise"]), None); + } +} diff --git a/ui/src/lib/paint-signal.test.ts b/ui/src/lib/paint-signal.test.ts new file mode 100644 index 00000000..e29e8aa4 --- /dev/null +++ b/ui/src/lib/paint-signal.test.ts @@ -0,0 +1,81 @@ +// @vitest-environment jsdom +// +// TD-5427: the host takes a window that never signals as blank and relaunches +// the app, so the root layout must send the ready signal after its first drawn +// frame, once. + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { flushSync, mount, unmount } from "svelte"; + +const mocks = vi.hoisted(() => ({ + invoked: [] as string[], + tauri: true, +})); + +vi.mock("@tauri-apps/api/core", () => ({ + invoke: async (command: string) => { + mocks.invoked.push(command); + }, +})); +vi.mock("./open-file", () => ({ isTauri: () => mocks.tauri })); +// The layout's other work has its own tests; only its mount matters here. +vi.mock("#lib/connection-status.svelte.js", () => ({ connect: () => {}, disconnect: () => {} })); +vi.mock("#lib/machines.svelte.js", () => ({ startMachines: () => () => {} })); +vi.mock("#lib/safe-start.svelte.js", () => ({ beginSafeStart: () => {} })); +vi.mock("#lib/backgrounds/store.svelte.js", () => ({ startBackground: () => () => {} })); +vi.mock("#lib/components/backgrounds/BackgroundHost.svelte", () => ({ default: () => {} })); + +import Layout from "../routes/+layout.svelte"; +import { resetPaintSignal, signalPainted } from "./paint-signal"; + +let frames: FrameRequestCallback[] = []; + +/** Run the callbacks queued for one frame. */ +async function drawFrame(): Promise { + for (const callback of frames.splice(0)) callback(0); + await vi.dynamicImportSettled(); +} + +function mountLayout(): () => void { + const target = document.createElement("div"); + const app = mount(Layout, { target, props: { children: (() => {}) as never } }); + flushSync(); + return () => void unmount(app); +} + +beforeEach(() => { + resetPaintSignal(); + frames = []; + mocks.invoked.length = 0; + mocks.tauri = true; + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => frames.push(callback)); +}); + +afterEach(() => vi.unstubAllGlobals()); + +describe("the ready signal", () => { + it("is sent once after the root layout mounts and a frame is drawn", async () => { + const off = mountLayout(); + expect(mocks.invoked).toEqual([]); + await drawFrame(); + expect(mocks.invoked, "the first callback runs before its frame is drawn").toEqual([]); + await drawFrame(); + await vi.waitFor(() => expect(mocks.invoked).toEqual(["ui_painted"])); + + off(); + const offAgain = mountLayout(); + await drawFrame(); + await drawFrame(); + expect(mocks.invoked).toEqual(["ui_painted"]); + offAgain(); + }); + + it("is not sent from a browser attach", async () => { + mocks.tauri = false; + signalPainted(); + await drawFrame(); + await drawFrame(); + expect(frames).toEqual([]); + expect(mocks.invoked).toEqual([]); + }); +}); diff --git a/ui/src/lib/paint-signal.ts b/ui/src/lib/paint-signal.ts new file mode 100644 index 00000000..58fa7f48 --- /dev/null +++ b/ui/src/lib/paint-signal.ts @@ -0,0 +1,39 @@ +// The ready signal (TD-5427): tells the host this window drew. +// +// A web view that cannot draw says nothing at all, so the host takes silence +// as failure and relaunches the app without compositing +// (shell/src/webview_watch). The first animation-frame callback runs before +// its frame is drawn; the second runs only once a frame has been. + +import { isTauri } from "./open-file"; + +export interface PaintDeps { + inTauri?: () => boolean; + frame?: (callback: () => void) => void; + invoke?: (command: string) => Promise; +} + +let asked = false; + +/** Reset for tests. */ +export function resetPaintSignal(): void { + asked = false; +} + +async function send(invoke: PaintDeps["invoke"]): Promise { + try { + const call = invoke ?? (await import("@tauri-apps/api/core")).invoke; + await call("ui_painted"); + } catch (error) { + console.error("the host did not take the ready signal", error); + } +} + +/** Signal the host after the first drawn frame. Once per window; a browser + attach has no host to tell. */ +export function signalPainted(deps: PaintDeps = {}): void { + if (asked || !(deps.inTauri ?? isTauri)()) return; + asked = true; + const frame = deps.frame ?? ((callback: () => void) => requestAnimationFrame(callback)); + frame(() => frame(() => void send(deps.invoke))); +} diff --git a/ui/src/routes/+layout.svelte b/ui/src/routes/+layout.svelte index 277e50a9..ccb70a7a 100644 --- a/ui/src/routes/+layout.svelte +++ b/ui/src/routes/+layout.svelte @@ -8,6 +8,7 @@ import { connect, disconnect } from '#lib/connection-status.svelte.js'; import { startMachines } from '#lib/machines.svelte.js'; import { beginSafeStart } from '#lib/safe-start.svelte.js'; + import { signalPainted } from '#lib/paint-signal.js'; let { children } = $props(); @@ -23,6 +24,8 @@ // CHAT-01: a safe start, if one was asked for, before the first list. if (!isQuickEntry) beginSafeStart(); connect(); + // TD-5427: without this the host treats the window as blank. + signalPainted(); return () => { offMachines(); offBackground(); diff --git a/ui/src/test-stubs/app-state.ts b/ui/src/test-stubs/app-state.ts new file mode 100644 index 00000000..53efef62 --- /dev/null +++ b/ui/src/test-stubs/app-state.ts @@ -0,0 +1,3 @@ +// SvelteKit's `$app/state` for vitest, which runs without the SvelteKit +// plugin. Only what a mounted route reads. +export const page = { url: new URL("tauri://localhost/") }; diff --git a/ui/vitest.config.ts b/ui/vitest.config.ts index 369ec3cd..a69368fc 100644 --- a/ui/vitest.config.ts +++ b/ui/vitest.config.ts @@ -1,3 +1,4 @@ +import { fileURLToPath } from 'node:url'; import { svelte } from '@sveltejs/vite-plugin-svelte'; import { defineConfig } from 'vitest/config'; @@ -17,6 +18,8 @@ export default defineConfig({ // build: the default node resolution picks the server build, whose // mount() throws. Vitest-only file — the app build reads vite.config. resolve: { - conditions: ['browser'] + conditions: ['browser'], + // SvelteKit's virtual module, which a mounted route imports (TD-5427). + alias: { '$app/state': fileURLToPath(new URL('./src/test-stubs/app-state.ts', import.meta.url)) } } }); \ No newline at end of file