aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-11-10 13:06:18 +0100
committerDanilo M. <danix@danix.xyz>2026-11-10 13:06:18 +0100
commitea5a277c6b8bb2ba48b0ca8822797cf6ab0b3405 (patch)
treed2ce1c0fe156dcd9c53196c151bdfed091a25618
parent8ec2352c22780202fcd39982f1c3e65d2dae0cc1 (diff)
downloaddeck-it-ea5a277c6b8bb2ba48b0ca8822797cf6ab0b3405.tar.gz
deck-it-ea5a277c6b8bb2ba48b0ca8822797cf6ab0b3405.zip
feat: the PC tells the tablet it is going to sleep
deckit/sleep.py holds an elogind delay inhibitor and watches PrepareForSleep with dbus-monitor. On a suspend the server marks its answers with X-Deckit-Sleep for 2 s, so the tablet's next poll shows "The PC is asleep" at once and drops its wake lock, then lets the inhibitor go. On resume it takes the inhibitor again. The 15 s silence fallback stays, worded "The PC is not answering", for a crash or a dropped tunnel. The inhibitor's command is `tail --pid=<server>` and dbus-monitor has a parent-death signal, so a killed server leaves no lock delaying every suspend (checked with kill -9: both gone within 2 s). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--AGENTS.md8
-rw-r--r--deckit/server.py5
-rw-r--r--deckit/sleep.py82
-rw-r--r--static/app.js20
-rw-r--r--static/index.html4
-rw-r--r--tests/test_server.py12
-rw-r--r--tests/test_sleep.py75
7 files changed, 192 insertions, 14 deletions
diff --git a/AGENTS.md b/AGENTS.md
index 83beff5..0d0bc63 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -64,9 +64,11 @@ Keep the server dependency-free apart from that one package.
(vendored `marked`, HTML escaped, images never fetched).
- The page holds a Screen Wake Lock while visible, so the tablet never sleeps
over the dashboard; nothing on the tablet's settings is changed.
- After 15s with no answer from the server (the PC asleep, or deck-it
- gone) `app.js` covers the page with a "The PC is asleep" overlay and
- drops the lock, so the tablet sleeps too; the first answer takes both back.
+ Before a suspend `deckit/sleep.py` (an elogind delay inhibitor plus
+ `dbus-monitor` on PrepareForSleep) marks answers with `X-Deckit-Sleep` for
+ 2s, and `app.js` covers the page with "The PC is asleep" and drops the
+ lock, so the tablet sleeps too; 15s with no answer at all gives the same
+ overlay as "The PC is not answering". The first plain answer takes both back.
- Launchers are `[launch] apps`, desktop ids run with `gtk-launch`; label and
icon come from the `.desktop` file. The client sends the id, which must be
configured and installed.
diff --git a/deckit/server.py b/deckit/server.py
index 38de5d3..835b612 100644
--- a/deckit/server.py
+++ b/deckit/server.py
@@ -36,7 +36,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse, urlsplit
-from . import config, module, theme
+from . import config, module, sleep, theme
ROOT = Path(__file__).resolve().parent.parent
STATIC = ROOT / "static"
@@ -153,6 +153,8 @@ class Handler(BaseHTTPRequestHandler):
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "max-age=86400" if cache else "no-store")
+ if sleep.sleeping.is_set():
+ self.send_header("X-Deckit-Sleep", "1") # the tablet shows "asleep" at once
self.end_headers()
self.wfile.write(body)
@@ -258,6 +260,7 @@ def serve():
TOKEN = load_token()
REGISTRY = build(CFG)
REGISTRY.start_all()
+ threading.Thread(target=sleep.watch, daemon=True).start()
RUNDIR.mkdir(mode=0o700, parents=True, exist_ok=True)
RUNDIR.chmod(0o700)
SOCKET.unlink(missing_ok=True)
diff --git a/deckit/sleep.py b/deckit/sleep.py
new file mode 100644
index 0000000..69b5a05
--- /dev/null
+++ b/deckit/sleep.py
@@ -0,0 +1,82 @@
+# deck-it - telling the tablet the PC is going to sleep
+# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+"""Tells the tablet the PC is about to sleep.
+
+elogind announces a suspend with PrepareForSleep on the system bus, and
+waits for it only while someone holds a delay inhibitor (at most
+InhibitDelayMaxSec, 5 s by default). deck-it holds one; on the announcement
+the server marks every answer for SHOW seconds, so the tablet's next poll
+sees it, then lets the inhibitor go and the PC sleeps. On resume it takes
+the inhibitor again.
+"""
+
+import ctypes
+import os
+import signal
+import subprocess
+import threading
+import time
+
+SHOW = 2.0 # the tablet polls every second (0.5 s on the assistant tab)
+sleeping = threading.Event()
+
+
+def _die_with_parent():
+ # PR_SET_PDEATHSIG: a server that dies takes dbus-monitor with it.
+ ctypes.CDLL(None, use_errno=True).prctl(1, signal.SIGTERM)
+
+
+def _inhibit():
+ # elogind-inhibit holds the lock while its command runs. The command
+ # ends with the server (tail --pid), so a crashed server never leaves a
+ # lock delaying every suspend; its own session, so letting go on purpose
+ # kills the tail too.
+ return subprocess.Popen(
+ ["elogind-inhibit", "--what=sleep", "--mode=delay", "--who=deck-it",
+ "--why=Tell the tablet the PC is going to sleep",
+ "tail", f"--pid={os.getpid()}", "-f", "/dev/null"],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+
+
+def _release(p):
+ try:
+ os.killpg(p.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+ p.wait()
+
+
+def watch():
+ """Runs for the server's life; without elogind or dbus-monitor it does nothing."""
+ try:
+ mon = subprocess.Popen(
+ ["dbus-monitor", "--system",
+ "type='signal',interface='org.freedesktop.login1.Manager',member='PrepareForSleep'"],
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
+ preexec_fn=_die_with_parent)
+ lock = _inhibit()
+ except OSError:
+ return
+ for line in mon.stdout:
+ line = line.strip()
+ if line == "boolean true":
+ sleeping.set()
+ time.sleep(SHOW)
+ _release(lock)
+ elif line == "boolean false":
+ sleeping.clear()
+ lock = _inhibit()
diff --git a/static/app.js b/static/app.js
index fb92352..3ec7dc2 100644
--- a/static/app.js
+++ b/static/app.js
@@ -228,6 +228,7 @@ function startPoll(name, panel, el) {
const poll = async () => {
try {
const r = await fetch(`/api/${name}`);
+ if (r.headers.get("X-Deckit-Sleep")) return goodnight("The PC is asleep");
awake();
if (r.ok) panel.update?.(await r.json(), el);
} catch {
@@ -348,11 +349,17 @@ async function keepAwake() {
}
keepAwake();
-// A sleeping PC answers nothing: every poll fails or hangs. After 15 s
-// without any answer the page says so and drops the wake lock, so the tablet
-// sleeps too; the first answer takes both back.
-// ponytail: a crashed server or a dropped tunnel reads as asleep as well.
+// The server marks its answers for a moment before the PC suspends
+// (deckit/sleep.py), so the page says "asleep" at once; a PC that stops
+// answering without saying so (a crash, a dropped tunnel) gets the same
+// overlay after 15 s. Either way the wake lock goes, so the tablet sleeps
+// too, and the first plain answer takes both back.
const ASLEEP_AFTER = 15000;
+function goodnight(title) {
+ document.getElementById("asleep-title").textContent = title;
+ asleep.hidden = false;
+ wakeLock?.release();
+}
let lastAnswer = Date.now();
function awake() {
lastAnswer = Date.now();
@@ -362,10 +369,7 @@ function awake() {
}
}
setInterval(() => {
- if (asleep.hidden && Date.now() - lastAnswer > ASLEEP_AFTER) {
- asleep.hidden = false;
- wakeLock?.release();
- }
+ if (asleep.hidden && Date.now() - lastAnswer > ASLEEP_AFTER) goodnight("The PC is not answering");
}, 2000);
document.addEventListener("visibilitychange", () => {
diff --git a/static/index.html b/static/index.html
index d199a35..ca3e827 100644
--- a/static/index.html
+++ b/static/index.html
@@ -42,8 +42,8 @@
<div id="tab-body"></div>
<div id="asleep" hidden>
<div class="asleep-moon nf"></div>
- <div class="off-title">The PC is asleep</div>
- <div class="off-detail">The dashboard comes back when it wakes. Until then the tablet can sleep too.</div>
+ <div class="off-title" id="asleep-title"></div>
+ <div class="off-detail">The dashboard comes back when it answers again. Until then the tablet can sleep too.</div>
</div>
<script src="vendor/gridstack/gridstack-all.js"></script>
<script type="module" src="app.js"></script>
diff --git a/tests/test_server.py b/tests/test_server.py
index 668b5d2..d37723e 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -90,6 +90,18 @@ class Server(unittest.TestCase):
{"Host": "127.0.0.1:8765", **ORIGIN, "Content-Type": "audio/wav"},
b"RIFF")[0], 401)
+ def test_answers_say_the_pc_is_going_to_sleep(self):
+ conn = UnixConnection(self.sock)
+ srv.sleep.sleeping.set()
+ try:
+ conn.request("GET", "/api/demo", headers=HOST)
+ r = conn.getresponse()
+ r.read()
+ finally:
+ srv.sleep.sleeping.clear()
+ conn.close()
+ self.assertEqual(r.getheader("X-Deckit-Sleep"), "1")
+
def test_nerd_font(self):
from unittest import mock
import tempfile
diff --git a/tests/test_sleep.py b/tests/test_sleep.py
new file mode 100644
index 0000000..99e819c
--- /dev/null
+++ b/tests/test_sleep.py
@@ -0,0 +1,75 @@
+# deck-it - tests for sleep
+# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along
+# with this program; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import os
+import shutil
+import stat
+import subprocess
+import tempfile
+import threading
+import time
+import unittest
+
+from deckit import sleep
+
+
+def until(fn, secs=3):
+ end = time.monotonic() + secs
+ while time.monotonic() < end:
+ if fn():
+ return True
+ time.sleep(0.02)
+ return False
+
+
+class Watch(unittest.TestCase):
+ def test_flags_then_releases_and_takes_the_lock_again(self):
+ bin_ = tempfile.mkdtemp(dir="/tmp")
+ self.addCleanup(shutil.rmtree, bin_)
+ log = Path(bin_) / "log"
+ # A suspend announced at 0.3 s, the resume at 1.2 s.
+ for name, body in {
+ "dbus-monitor": "sleep 0.3; echo ' boolean true'; sleep 0.9; echo ' boolean false'; sleep 1",
+ "elogind-inhibit": f"echo take >> {log}; exec sleep 100",
+ }.items():
+ p = Path(bin_) / name
+ p.write_text("#!/bin/sh\n" + body + "\n")
+ p.chmod(p.stat().st_mode | stat.S_IXUSR)
+ path = os.environ["PATH"]
+ os.environ["PATH"] = bin_ + ":" + path
+ self.addCleanup(os.environ.__setitem__, "PATH", path)
+ sleep.SHOW = 0.2
+ taken = []
+ real = sleep._inhibit
+ sleep._inhibit = lambda: taken.append(real()) or taken[-1]
+ self.addCleanup(setattr, sleep, "_inhibit", real)
+ self.addCleanup(lambda: [subprocess.run(["pkill", "-g", str(p.pid)]) for p in taken])
+ threading.Thread(target=sleep.watch, daemon=True).start()
+
+ self.assertTrue(until(sleep.sleeping.is_set))
+ self.assertTrue(until(lambda: taken[0].poll() is not None)) # let go: the PC may sleep
+ self.assertTrue(until(lambda: not sleep.sleeping.is_set()))
+ self.assertTrue(until(lambda: len(taken) == 2 and taken[1].poll() is None))
+ self.assertTrue(until(lambda: log.read_text().split() == ["take", "take"]))
+
+
+if __name__ == "__main__":
+ unittest.main()