fix(replace,wm,autostart): preserve workspaces across slow/3rd-party replace and guard polkit agent startup

This commit is contained in:
Luxferre committed 2026-11-27 09:06:02 +02:00
1 parent 4ec3f59e02
commit c5ce065c33
6 files changed
+759 -53

No files matched your search

+120
View File
@@ -512,6 +512,125 @@ def test_dwm_sighup_reload_xvfb():
terminate(xvfb)
def test_xdg_desktop_dedup_and_polkit_guard():
with tempfile.TemporaryDirectory() as tmp:
env, _, xdg_home, xdg_sys, _, bin_dir = make_base_env(tmp)
conf_dir = os.path.join(xdg_home, "anode")
markers = os.path.join(tmp, "markers")
os.makedirs(markers, exist_ok=True)
app_bin = os.path.join(bin_dir, "anode_xdg_app")
compile_sleep_dummy(app_bin)
lxpolkit_bin = os.path.join(bin_dir, "lxpolkit")
shutil.copy2(app_bin, lxpolkit_bin)
m_app = os.path.join(markers, "app.pid")
m_pre_app = os.path.join(markers, "pre_app.pid")
m_xdg_dup = os.path.join(markers, "xdg_dup.pid")
m_polkit_pre = os.path.join(markers, "polkit_pre.pid")
m_polkit_new = os.path.join(markers, "polkit_new.pid")
m_polkit_bad_sess = os.path.join(markers, "polkit_bad_sess.pid")
# 1) exec_once + XDG .desktop of the same app in a single start must only launch once
write_text(os.path.join(conf_dir, "autostart"), f"exec_once anode_xdg_app '{m_app}'\n")
write_text(
os.path.join(xdg_sys, "autostart", "app.desktop"),
f"[Desktop Entry]\nType=Application\nTryExec=anode_xdg_app\nExec=anode_xdg_app '{m_app}'\n",
)
res = run_autostart(["start"], env)
assert res.returncode == 0, f"start failed: {res.stderr}"
assert wait_until(lambda: os.path.exists(m_app), timeout=4.0), "anode_xdg_app did not launch"
time.sleep(0.35)
try:
with open(m_app, "r", encoding="utf-8") as f:
pids = [line.strip() for line in f if line.strip()]
assert len(pids) == 1, f"expected 1 launch for exec_once + XDG .desktop, got {pids}"
finally:
kill_pids_from_file(m_app)
# Wait briefly for previous process cleanup before testing pre-running XDG dedup
time.sleep(0.15)
# 2) Already-running process referenced by XDG .desktop must be skipped
write_text(os.path.join(conf_dir, "autostart"), "# empty\n")
write_text(
os.path.join(xdg_sys, "autostart", "app.desktop"),
f"[Desktop Entry]\nType=Application\nTryExec=anode_xdg_app\nExec=anode_xdg_app '{m_xdg_dup}'\n",
)
pre_app = subprocess.Popen([app_bin, m_pre_app], env=env)
try:
assert wait_until(lambda: os.path.exists(m_pre_app), timeout=3.0)
res2 = run_autostart(["start"], env)
assert res2.returncode == 0, f"start failed: {res2.stderr}"
time.sleep(0.35)
assert not os.path.exists(m_xdg_dup), "XDG .desktop launched duplicate of already-running app"
finally:
terminate(pre_app)
kill_pids_from_file(m_xdg_dup)
# 3) Polkit agent running on DISPLAY=:97 in sess-active must block duplicate on :97 even from stale XDG_SESSION_ID
os.remove(os.path.join(xdg_sys, "autostart", "app.desktop"))
write_text(os.path.join(conf_dir, "autostart"), f"exec_once lxpolkit '{m_polkit_new}'\n")
write_text(
os.path.join(xdg_sys, "autostart", "lxpolkit.desktop"),
f"[Desktop Entry]\nType=Application\nTryExec=lxpolkit\nExec=lxpolkit '{m_polkit_new}'\n",
)
active_env = dict(env)
active_env["DISPLAY"] = ":97"
active_env["XDG_SESSION_ID"] = "sess-active"
active_env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=/tmp/anode-active-dbus"
stale_env = dict(env)
stale_env["DISPLAY"] = ":97"
stale_env["XDG_SESSION_ID"] = "sess-stale"
stale_env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=/tmp/anode-stale-dbus"
stale_env["ANODE_FORCE_POLKIT_AGENT"] = "1"
pre_pk = subprocess.Popen([lxpolkit_bin, m_polkit_pre], env=active_env)
try:
assert wait_until(lambda: os.path.exists(m_polkit_pre), timeout=3.0)
res3 = run_autostart(["start"], stale_env)
assert res3.returncode == 0, f"polkit dedup run failed: {res3.stderr}"
time.sleep(0.35)
assert not os.path.exists(m_polkit_new), (
"duplicate polkit agent was started on same DISPLAY across different XDG_SESSION_ID"
)
finally:
terminate(pre_pk)
kill_pids_from_file(m_polkit_new)
# 4) Dead/invalid loginctl session must skip launching polkit agent
loginctl_stub = os.path.join(bin_dir, "loginctl")
write_text(
loginctl_stub,
"#!/bin/sh\n"
"if [ \"${1:-}\" = \"list-sessions\" ]; then\n"
" printf 'SESSION UID USER SEAT\\n c11 1000 lux seat0\\n'\n"
" exit 0\n"
"fi\n"
"exit 1\n",
0o755,
)
write_text(os.path.join(conf_dir, "autostart"), f"exec_once lxpolkit '{m_polkit_bad_sess}'\n")
write_text(
os.path.join(xdg_sys, "autostart", "lxpolkit.desktop"),
f"[Desktop Entry]\nType=Application\nTryExec=lxpolkit\nExec=lxpolkit '{m_polkit_bad_sess}'\n",
)
bad_sess_env = dict(env)
bad_sess_env["DISPLAY"] = ":98"
bad_sess_env["XDG_SESSION_ID"] = "sess-dead"
bad_sess_env.pop("ANODE_FORCE_POLKIT_AGENT", None)
res4 = run_autostart(["start"], bad_sess_env)
assert res4.returncode == 0, f"dead-session guard run failed: {res4.stderr}"
time.sleep(0.35)
try:
assert not os.path.exists(m_polkit_bad_sess), (
"polkit agent launched despite invalid loginctl session"
)
finally:
kill_pids_from_file(m_polkit_bad_sess)
if __name__ == "__main__":
test_directives_includes_once_and_reload()
test_exec_once_session_isolation()
@@ -519,4 +638,5 @@ if __name__ == "__main__":
test_dropins_desktop_filters_and_xdg_masking()
test_check_errors()
test_dwm_sighup_reload_xvfb()
test_xdg_desktop_dedup_and_polkit_guard()
print("test_autostart: OK")
+223
View File
@@ -1197,6 +1197,228 @@ def test_replace_preserves_workspaces_and_states():
terminate(xvfb)
def test_replace_autostart_reload_default_and_slow_snapshot_guard():
# Part 1: Default anode-replace runs anode-autostart reload (not start / not XDG .desktop),
# while anode-replace --autostart explicitly runs full anode-autostart start.
disp1 = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp1)
os.symlink(os.path.join(ROOT, "scripts", "anode-autostart"), os.path.join(tmp, "bin", "anode-autostart"))
xdg_sys = os.path.join(tmp, "xdg_sys")
os.makedirs(os.path.join(xdg_sys, "autostart"), exist_ok=True)
os.makedirs(os.path.join(env["XDG_CONFIG_HOME"], "anode"), exist_ok=True)
env["XDG_CONFIG_DIRS"] = xdg_sys
env["ANODE_XDG_AUTOSTART"] = "1"
env["ANODE_FORCE_POLKIT_AGENT"] = "1"
m_exec = os.path.join(tmp, "exec.log")
m_once = os.path.join(tmp, "once.log")
m_always = os.path.join(tmp, "always.log")
m_polkit = os.path.join(tmp, "lxpolkit.log")
lx_stub = os.path.join(tmp, "bin", "lxpolkit")
with open(lx_stub, "w", encoding="utf-8") as f:
f.write(f"#!/bin/sh\nprintf 'pk\\n' >> '{m_polkit}'\n")
os.chmod(lx_stub, 0o755)
once_stub = os.path.join(tmp, "bin", "anode_once_stub")
with open(once_stub, "w", encoding="utf-8") as f:
f.write(f"#!/bin/sh\nprintf 'o\\n' >> '{m_once}'\n")
os.chmod(once_stub, 0o755)
with open(os.path.join(env["XDG_CONFIG_HOME"], "anode", "autostart"), "w", encoding="utf-8") as f:
f.write(
f"exec sh -c \"printf 'e\\n' >> '{m_exec}'\"\n"
"exec_once anode_once_stub\n"
f"exec_always sh -c \"printf 'a\\n' >> '{m_always}'\"\n"
)
with open(os.path.join(xdg_sys, "autostart", "lxpolkit.desktop"), "w", encoding="utf-8") as f:
f.write("[Desktop Entry]\nType=Application\nTryExec=lxpolkit\nExec=lxpolkit\n")
xvfb = subprocess.Popen(
["Xvfb", disp1, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dwm1 = None
dpy = None
cur_pid = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp1.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
rep1 = subprocess.run([REPLACE_BIN, "--keep-panels"], env=env, capture_output=True, text=True)
assert rep1.returncode == 0, f"default replace failed: stdout={rep1.stdout} stderr={rep1.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
cur_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
assert wait_until(lambda: os.path.exists(m_always), timeout=4.0), "default replace did not run exec_always"
time.sleep(0.35)
assert not os.path.exists(m_exec), "default replace must not re-run exec"
assert not os.path.exists(m_once), "default replace must not re-run exec_once"
assert not os.path.exists(m_polkit), "default replace must not re-run XDG lxpolkit.desktop"
rep2 = subprocess.run([REPLACE_BIN, "--autostart", "--keep-panels"], env=env, capture_output=True, text=True)
assert rep2.returncode == 0, f"--autostart replace failed: stdout={rep2.stdout} stderr={rep2.stderr}"
wm3 = wait_until(
lambda: (lambda w: w if w and w != wm2 else None)(get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")),
timeout=5.0,
)
assert wm3
cur_pid = get_win_prop_ulong(dpy, wm3, "_NET_WM_PID")
assert wait_until(lambda: os.path.exists(m_exec), timeout=4.0), "--autostart did not run exec"
assert wait_until(lambda: os.path.exists(m_once), timeout=4.0), "--autostart did not run exec_once"
assert wait_until(lambda: os.path.exists(m_polkit), timeout=4.0), "--autostart did not run XDG desktop"
finally:
terminate(dwm1)
kill_pid_and_wait(cur_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
# Part 2: Slow pre-dwm setup (>1.5s) + third-party WM resetting _NET_WM_DESKTOP=0 / _NET_CURRENT_DESKTOP=0
# on SIGTERM + sparse _NET_DESKTOP_NAMES ("1", "3:code", "5").
disp2 = pick_display()
cc = os.environ.get("CC", "cc")
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp2)
with open(os.path.join(env["HOME"], ".Xresources"), "w", encoding="utf-8") as f:
f.write("theme.name: Anodized\n")
xrdb_shim = os.path.join(tmp, "bin", "xrdb")
with open(xrdb_shim, "w", encoding="utf-8") as f:
f.write("#!/bin/sh\nsleep 1.8\n")
os.chmod(xrdb_shim, 0o755)
ewmh_c = os.path.join(tmp, "mock_ewmh_reset.c")
ewmh_bin = os.path.join(tmp, "bin", "mock_ewmh_reset")
with open(ewmh_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <stdlib.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void on_sig(int s) { (void)s; alive = 0; }\n"
"int main(int argc, char **argv) {\n"
" signal(SIGTERM, on_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window wmc = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n"
" Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n"
" Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n"
" Atom ap = XInternAtom(d, \"_NET_WM_PID\", False);\n"
" Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n"
" Atom acd = XInternAtom(d, \"_NET_CURRENT_DESKTOP\", False);\n"
" Atom awd = XInternAtom(d, \"_NET_WM_DESKTOP\", False);\n"
" Atom adn = XInternAtom(d, \"_NET_DESKTOP_NAMES\", False);\n"
" unsigned long pid = (unsigned long)getpid();\n"
" const char names[] = \"1\\0\" \"3:code\\0\" \"5\";\n"
" XChangeProperty(d, wmc, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmc, 1);\n"
" XChangeProperty(d, wmc, an, au, 8, PropModeReplace, (unsigned char *)\"MockResetWM\", 11);\n"
" XChangeProperty(d, wmc, ap, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmc, 1);\n"
" XChangeProperty(d, root, adn, au, 8, PropModeReplace, (const unsigned char *)names, sizeof(names));\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 50000000L}; nanosleep(&ts, NULL); }\n"
" unsigned long zero = 0;\n"
" XChangeProperty(d, root, acd, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&zero, 1);\n"
" for (int i = 1; i < argc; i++) {\n"
" Window cw = (Window)strtoul(argv[i], NULL, 0);\n"
" if (cw != None)\n"
" XChangeProperty(d, cw, awd, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&zero, 1);\n"
" }\n"
" XDestroyWindow(d, wmc);\n"
" XSync(d, False);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", ewmh_c, "-o", ewmh_bin] + compile_x11_flags(), check=True)
xvfb = subprocess.Popen(
["Xvfb", disp2, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
mwm = None
dpy = None
new_pid = None
app_wins = []
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp2.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
a_card = X11.XInternAtom(dpy, b"CARDINAL", 0)
a_win = X11.XInternAtom(dpy, b"WINDOW", 0)
a_cl = X11.XInternAtom(dpy, b"_NET_CLIENT_LIST", 0)
a_cd = X11.XInternAtom(dpy, b"_NET_CURRENT_DESKTOP", 0)
a_wd = X11.XInternAtom(dpy, b"_NET_WM_DESKTOP", 0)
a_act = X11.XInternAtom(dpy, b"_NET_ACTIVE_WINDOW", 0)
wa = X11.XCreateSimpleWindow(dpy, root, 10, 40, 280, 180, 0, 0, 0xffffff)
wb = X11.XCreateSimpleWindow(dpy, root, 40, 60, 300, 200, 0, 0, 0xffffff)
wc = X11.XCreateSimpleWindow(dpy, root, 70, 80, 320, 220, 0, 0, 0xffffff)
app_wins = [wa, wb, wc]
X11.XMapWindow(dpy, wb)
for w, desk in ((wa, 0), (wb, 1), (wc, 2)):
dv = ctypes.c_ulong(desk)
X11.XChangeProperty(dpy, w, a_wd, a_card, 32, 0, ctypes.byref(dv), 1)
cl_arr = (ctypes.c_ulong * 3)(wa, wb, wc)
X11.XChangeProperty(dpy, root, a_cl, a_win, 32, 0, cl_arr, 3)
cd_v = ctypes.c_ulong(1)
X11.XChangeProperty(dpy, root, a_cd, a_card, 32, 0, ctypes.byref(cd_v), 1)
act_v = ctypes.c_ulong(wb)
X11.XChangeProperty(dpy, root, a_act, a_win, 32, 0, ctypes.byref(act_v), 1)
X11.XSync(dpy, 0)
mwm = subprocess.Popen([ewmh_bin, hex(wa), hex(wb), hex(wc)], env=env)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"slow/sparse replace failed: stdout={rep.stdout} stderr={rep.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
def sparse_ok():
return (
get_win_prop_ulong(dpy, root, "_NET_CURRENT_DESKTOP") == 2
and get_win_prop_ulong(dpy, wa, "_NET_WM_DESKTOP") == 0
and get_win_prop_ulong(dpy, wb, "_NET_WM_DESKTOP") == 2
and get_win_prop_ulong(dpy, wc, "_NET_WM_DESKTOP") == 4
and get_win_prop_ulong(dpy, root, "_NET_ACTIVE_WINDOW") == wb
)
assert wait_until(sparse_ok, timeout=5.0), (
f"sparse/slow restore mismatch: cur={get_win_prop_ulong(dpy, root, '_NET_CURRENT_DESKTOP')} "
f"desks={[get_win_prop_ulong(dpy, w, '_NET_WM_DESKTOP') for w in app_wins]} "
f"act={get_win_prop_ulong(dpy, root, '_NET_ACTIVE_WINDOW')}"
)
finally:
if dpy:
for w in app_wins:
X11.XDestroyWindow(dpy, w)
terminate(mwm)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def main():
if not shutil.which("Xvfb"):
print("test_replace: Xvfb not installed (skipping)")
@@ -1211,6 +1433,7 @@ def main():
test_switch_session_stale_i3sock_fallback()
test_replace_display_scoped_daemon_cleanup()
test_replace_preserves_workspaces_and_states()
test_replace_autostart_reload_default_and_slow_snapshot_guard()
print("test_replace: OK")
return 0