Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 80 additions & 6 deletions aw_watcher_window/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,37 @@ def swift_helper_exit_status(returncode):
return returncode


def _is_xconn_error(exc: BaseException) -> bool:
"""Return True if *exc* is an Xlib display-connection or authorisation error."""
try:
import Xlib.error

return isinstance(exc, Xlib.error.DisplayConnectionError)
except ImportError:
return False


def _warn_wayland_once() -> None:
"""Log a one-time warning when a Wayland session is detected.

X11 tracking (via Xlib) only sees XWayland apps; native Wayland windows
appear as 'unknown'. Users running a pure Wayland compositor should switch
to aw-watcher-window-wayland instead.
"""
xdg_session = os.environ.get("XDG_SESSION_TYPE", "").lower()
wayland_display = os.environ.get("WAYLAND_DISPLAY", "")
if xdg_session == "wayland" or wayland_display:
logger.warning(
"Wayland session detected (XDG_SESSION_TYPE=%r, WAYLAND_DISPLAY=%r). "
"aw-watcher-window uses X11/Xlib and will only track XWayland apps — "
"native Wayland windows will show as 'unknown'. "
"For full Wayland support see aw-watcher-window-wayland: "
"https://github.com/ActivityWatch/aw-watcher-window-wayland",
xdg_session or "unset",
wayland_display or "unset",
)


def try_compile_title_regex(title):
try:
return re.compile(title, re.IGNORECASE)
Expand All @@ -115,18 +146,25 @@ def main():

args = parse_args()

if sys.platform.startswith("linux") and (
"DISPLAY" not in os.environ or not os.environ["DISPLAY"]
):
raise Exception("DISPLAY environment variable not set")

setup_logging(
name="aw-watcher-window",
testing=args.testing,
verbose=args.verbose,
log_stderr=True,
log_file=True,
)

if sys.platform.startswith("linux"):
# Warn about Wayland *before* the DISPLAY check so pure-Wayland users
# (no DISPLAY set) still see the actionable message and the link to
# aw-watcher-window-wayland instead of a bare exception.
_warn_wayland_once()
Comment thread
TimeToBuildBob marked this conversation as resolved.
Resolved

if sys.platform.startswith("linux") and (
"DISPLAY" not in os.environ or not os.environ["DISPLAY"]
):
raise Exception("DISPLAY environment variable not set")

if sys.platform == "darwin":
background_ensure_permissions()

Expand Down Expand Up @@ -209,6 +247,10 @@ def heartbeat_loop(
research_category_map=None,
research_app_category_map=None,
):
# State for X display-connection error backoff (Linux only).
_xconn_error_logged = False
_xconn_backoff = poll_time # grows exponentially up to 60s on repeated failures

while True:
if os.getppid() == 1:
logger.info("window-watcher stopped because parent process died")
Expand All @@ -218,14 +260,46 @@ def heartbeat_loop(
try:
current_window = get_current_window(strategy)
logger.debug(current_window)
# Reset backoff and the one-shot log flag on a successful poll so
# a new X connection failure episode logs once again.
_xconn_backoff = poll_time
_xconn_error_logged = False
except (FatalError, OSError):
# Fatal exceptions should quit the program
try:
logger.exception("Fatal error, stopping")
except OSError:
pass
break
except Exception:
except Exception as exc:
# Check for X display connection / authorisation failures before
# falling through to the generic "log full traceback" path.
if sys.platform.startswith("linux") and _is_xconn_error(exc):
if not _xconn_error_logged:
_xconn_error_logged = True
_xauth = os.environ.get("XAUTHORITY", "")
logger.error(
"Cannot connect to X display: %s. "
"Most likely cause: aw-watcher-window is running as a different user "
"or with sudo. Fix: run it as the display owner, or point XAUTHORITY "
"to the correct .Xauthority file (currently %r). "
"See: https://docs.activitywatch.net/en/latest/faq.html",
exc,
_xauth if _xauth else "unset",
)
# Sleep in 1-second chunks so parent death is noticed within
# ~1 s even when the backoff is at its 60 s cap.
_remaining = _xconn_backoff
while _remaining > 0:
sleep(min(1.0, _remaining))
_remaining -= 1.0
if os.getppid() == 1:
logger.info("window-watcher stopped because parent process died")
break
else:
_xconn_backoff = min(_xconn_backoff * 2, 60.0)
continue
break
# Non-fatal exceptions should be logged
try:
# If stdout has been closed, this exception-print can cause (I think)
Expand Down
85 changes: 85 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,88 @@ def __exit__(self, exc_type, exc, tb):
with pytest.raises(SystemExit) as exc:
main_module.main()
assert exc.value.code == 134


# --- Wayland / X-auth diagnostic tests ---


def test_warn_wayland_once_logs_on_wayland_display(monkeypatch, caplog):
monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")
monkeypatch.delenv("XDG_SESSION_TYPE", raising=False)
import logging

with caplog.at_level(logging.WARNING, logger="aw_watcher_window.main"):
main_module._warn_wayland_once()

assert any("Wayland" in r.message for r in caplog.records)
assert any("aw-watcher-window-wayland" in r.message for r in caplog.records)


def test_warn_wayland_once_logs_on_xdg_session_type(monkeypatch, caplog):
monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)
monkeypatch.setenv("XDG_SESSION_TYPE", "wayland")
import logging

with caplog.at_level(logging.WARNING, logger="aw_watcher_window.main"):
main_module._warn_wayland_once()

assert any("Wayland" in r.message for r in caplog.records)


def test_warn_wayland_once_silent_on_x11(monkeypatch, caplog):
monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)
monkeypatch.setenv("XDG_SESSION_TYPE", "x11")
import logging

with caplog.at_level(logging.WARNING, logger="aw_watcher_window.main"):
main_module._warn_wayland_once()

assert not caplog.records


def test_heartbeat_loop_xconn_error_logs_once_and_backs_off(monkeypatch, caplog):
"""DisplayConnectionError must log exactly once and apply exponential backoff."""
import logging

# Minimal fake DisplayConnectionError that _is_xconn_error will recognise.
# Skip only when python-xlib is unavailable; a construction error below must
# fail the test rather than masquerade as a missing dependency (#155 CodeQL
# flagged `Xlib` as possibly uninitialised after the try/except import).
Xlib_error = pytest.importorskip("Xlib.error")

fake_exc = Xlib_error.DisplayConnectionError(":0", b"Authorization required")

call_count = [0]
sleep_calls = []

def fake_get_window(_strategy):
call_count[0] += 1
if call_count[0] <= 3:
raise fake_exc
# After 3 auth errors, raise FatalError to exit the loop cleanly.
raise main_module.FatalError()

class FakeClient:
def heartbeat(self, *args, **kwargs):
pass

monkeypatch.setattr(main_module, "get_current_window", fake_get_window)
monkeypatch.setattr(main_module, "sleep", lambda s: sleep_calls.append(s))
monkeypatch.setattr(main_module.os, "getppid", lambda: 999)
monkeypatch.setattr(main_module.sys, "platform", "linux")

with caplog.at_level(logging.ERROR, logger="aw_watcher_window.main"):
main_module.heartbeat_loop(
FakeClient(),
"bucket",
poll_time=1.0,
strategy="xlib",
)

error_records = [r for r in caplog.records if "Cannot connect to X display" in r.message]
assert len(error_records) == 1, "Should log the auth error exactly once"

# Backoff doubles each failure (1s, 2s, 4s) and is slept in <=1s chunks so
# parent death is noticed promptly.
assert all(s <= 1.0 for s in sleep_calls)
assert sum(sleep_calls) == 7.0
Loading