The site
Notifications and offline play
How the site tells a player it’s their move when the table’s page is closed, through the browsers’ own push services, and how its puzzles play without a connection.
On this page
A table’s page tells you it’s your move while it’s open: the Your move prompt and ring, the tab’s title, and a chime if you turn it on (Design: Your move). Close the tab or lock the phone and the page stops checking in; after 45 seconds a bot plays your seat (The table service). Notifications reach you in that gap, and are what Take your time tables will lean on. The decision is ADR 0092; the design and David’s calls are in docs/your-move.md.
Built so far: the push app, which keeps and sends them; the site’s service worker, which shows them and keeps the puzzles playable offline; and the places a player turns them on and off (the waiting room’s ask, a table game’s Options, the account page: Front-end kits). And the events: your move, your table is starting, and a bot playing for you.
Where it lives#
push/ is a small Django app with one model.
| File | What it does |
|---|---|
push/models.py |
Subscription: one device, for an account or a guest’s seat, with its choices and quiet hours. |
push/views.py |
Turning notifications on and off, the public key, and Send a test. |
push/send.py |
Notice, the message’s shape, and sending after the change commits. |
push/management/commands/push.py |
manage.py push keys (a VAPID key pair) and push status. |
A subscription#
When a player taps Turn on, their browser asks its push service (Apple’s, Google’s, Mozilla’s, Microsoft’s) for an address to send to, and hands the page that address and two keys. The page posts them here, and the server keeps them:
push/models.py Subscription · lines 22–73class Subscription(models.Model):
endpoint = models.URLField(max_length=1000, db_index=True, help_text="Where the browser's push service takes messages for it.")
p256dh = models.CharField(max_length=200, help_text="The browser's public key, for encrypting messages to it.")
auth = models.CharField(max_length=100, help_text="The browser's shared secret, for the same.")
origin = models.CharField(max_length=200, help_text="The site's address as the browser saw it, so a tap opens the same site.")
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE, related_name="push_subscriptions")
seat = models.ForeignKey("cards.Seat", null=True, blank=True, on_delete=models.CASCADE, related_name="push_subscriptions",
help_text="A guest's: this seat only.")
device = models.CharField(max_length=60, blank=True, help_text="What the page called the device, in a few words.")
zone = models.CharField(max_length=64, blank=True, help_text="The device's time zone, for quiet hours.")
moves = models.BooleanField(default=True, help_text="Tell me when it's my move.")
starts = models.BooleanField(default=True, help_text="Tell me when a table I'm at starts.")
quiet = models.BooleanField(default=True, help_text="Quiet hours on.")
quiet_from = models.TimeField(default=QUIET_FROM)
quiet_to = models.TimeField(default=QUIET_TO)
created = models.DateTimeField(auto_now_add=True)
sent = models.DateTimeField(null=True, blank=True, help_text="When a message last reached its push service.")
failures = models.PositiveSmallIntegerField(default=0, help_text="Sends that failed in a row.")
class Meta:
ordering = ["-created"]
constraints = [
models.CheckConstraint(
condition=models.Q(user__isnull=False, seat__isnull=True) | models.Q(user__isnull=True, seat__isnull=False),
name="push_for_an_account_or_a_seat"),
models.UniqueConstraint(fields=["endpoint"], condition=models.Q(user__isnull=False), name="one_account_subscription_per_device"),
models.UniqueConstraint(fields=["endpoint", "seat"], condition=models.Q(seat__isnull=False), name="one_guest_subscription_per_seat"),
]
def __str__(self):
return f"{self.device or 'a device'} for {self.user or self.seat}"
def info(self) -> dict:
"""What pywebpush wants to know about the browser."""
return {"endpoint": self.endpoint, "keys": {"p256dh": self.p256dh, "auth": self.auth}}
def local(self, at: datetime) -> datetime:
"""`at` on the device's clock (the server's day, if its zone's unknown)."""
try:
return at.astimezone(ZoneInfo(self.zone)) if self.zone else at.astimezone(ZoneInfo(settings.TIME_ZONE))
except (ZoneInfoNotFoundError, ValueError):
return at.astimezone(ZoneInfo(settings.TIME_ZONE))
def is_quiet(self, at: datetime) -> bool:
"""Whether `at` falls in this device's quiet hours. They may run over
midnight (10 pm to 8 am) or not (1 pm to 3 pm)."""
if not self.quiet or self.quiet_from == self.quiet_to:
return False
now = self.local(at).time()
if self.quiet_from < self.quiet_to:
return self.quiet_from <= now < self.quiet_to
return now >= self.quiet_from or now < self.quiet_to
A subscription is an account’s or one seat’s, never both, never neither (the check constraint):
- An account’s reaches the player at every table they sit at, on that device. A signed-in player’s seat is linked to their account (Accounts), so the table knows whose devices to reach. One device is one account’s: signing in to another account there and turning them on moves it.
- A guest’s reaches them at one table only, through their seat. It’s posted with the seat’s
X-Seatlike every table call and reads no session, so a guest still never gets a cookie. It goes when the seat does: a table is deleted after 14 idle days. The same browser at two tables has one for each.
Deleting an account deletes its devices. A seat reaches its guest’s device and its account’s, once each:
push/models.py for_seat · lines 76–87def for_seat(seat) -> list[Subscription]:
"""Every device that should hear about this seat: its guest's, and its
account's (a signed-in player's seat is linked to their account). One
each, if a device is both."""
subs = Subscription.objects.filter(models.Q(seat=seat) | (models.Q(user_id=seat.user_id) if seat.user_id else models.Q(pk__in=[])))
seen, out = set(), []
# (the account's first: it holds the choices the account page sets)
for sub in sorted(subs, key=lambda s: s.user_id is None):
if sub.endpoint not in seen:
seen.add(sub.endpoint)
out.append(sub)
return out
What’s checked when one arrives#
push/views.py _subscription · lines 75–94def _subscription(body) -> dict:
sub = body.get("subscription")
if not isinstance(sub, dict) or not isinstance(sub.get("keys"), dict):
raise Refused("That subscription didn't make sense.")
endpoint = sub.get("endpoint")
if not isinstance(endpoint, str) or len(endpoint) > 1000:
raise Refused("That subscription didn't make sense.")
parts = urlsplit(endpoint)
host = (parts.hostname or "").lower()
if parts.scheme != "https" or not any(host.endswith(h) or host == h[1:] for h in PUSH_HOSTS):
raise Refused("That isn't a push service this site sends to.")
zone = body.get("zone") if isinstance(body.get("zone"), str) and body["zone"] in _zones() else ""
device = body.get("device") if isinstance(body.get("device"), str) else ""
return {
"endpoint": endpoint,
"p256dh": _key(sub["keys"].get("p256dh"), 65),
"auth": _key(sub["keys"].get("auth"), 16),
"device": device.strip()[:60],
"zone": zone,
}
The address has to be one of the browsers’ push services, so no one can have the server post to an address of their choosing:
push/views.py PUSH_HOSTS · lines 29–31# The browsers' own push services. A subscription naming anywhere else is
# refused, so no one can have the server post to an address of their choosing.
PUSH_HOSTS = (".googleapis.com", ".push.apple.com", ".mozilla.com", ".mozaws.net", ".notify.windows.com")
The browser’s key has to be a P-256 point (65 bytes) and its secret 16 bytes. The time zone is kept only if it’s a real one; the device’s name is the page’s few words, as Feedback’s is.
The calls#
| Call | Who | What it does |
|---|---|---|
GET /push/key/ |
anyone | The site’s public VAPID key, which a browser subscribes with; null while the site has none. |
POST /push/subscribe/ |
signed in | This device, for the account. A new device starts with the account’s choices from another. |
POST /push/unsubscribe/ |
signed in | Forgets this device (endpoint), or one from the account page’s list (id). |
POST /push/test/ |
signed in | Sends one device “This is a test from Unnecessary Obstacles”. |
POST /push/choices/ |
signed in | The account page’s choices (which events, quiet hours and their times), for every device of the account at once. |
POST /games/<slug>/tables/<code>/push/ |
the seat (X-Seat) |
A guest’s device for this seat; {"off": true} forgets it. |
The three account calls read the session, so each is csrf_protect, like the table kit’s account calls. The guest’s is csrf_exempt, like every X-Seat call: another site can’t make a browser send that header.
The events#
push/events.py decides who’s told what, and when. The table service calls it as things happen, so nothing here needs a scheduler:
| When | From | What it says |
|---|---|---|
| A decision the table waits on becomes a person’s, and their page has been quiet 15 seconds | _advance, every time a table moves on |
“Your move at {game}”, then the game’s own line (its notice, The table service) or “The table is waiting on you.” |
| A bot takes the seat of someone away whose turn it was | _cover_away |
“A bot is playing for you at {game}”, “Your turn came while you were away. Tap to take your seat back.” |
| The host starts | _start |
“Your table is starting”, “{host} started {game}. You’re with {others}.” To everyone sitting there but the host whose page is quiet. |
push/events.py moves · lines 93–122def moves(table, rules, seats, now) -> float | None:
"""After a table moved on: tell each person whose decision the table now
waits on, and whose page is quiet, that it's their move. Returns when to
look again for someone whose page isn't quiet long enough yet (so the
service can wake the table then), or None."""
if not sending.configured() or not table.state or rules.over(table.state):
return None
left = set((table.room or {}).get("left", []))
people = {s.index: s for s in seats if s.person and not s.bot and s.index not in left}
holds = getattr(rules, "holds_up", None)
wake = None
for index, kind, key in rules.deciding(table.state):
seat = people.get(index)
if not seat or kind == "ready" or (holds and not holds(table.state, index, kind)):
continue
if _kept(table).get(str(index), {}).get("key") == key:
continue # (told already)
if not _quiet(seat, now):
due = (seat.seen or now) + QUIET
wake = due if wake is None else min(wake, due)
continue
if not _may(table, seat, now):
continue
_sent(table, seat, key, now)
line = getattr(rules, "notice", None)
body = (line(table.state, index, kind) if line else None) or "The table is waiting on you."
sending.send(_devices(seat, now, "moves"), sending.Notice(
title=f"Your move at {_title(table)}", body=body, path=_path(table), tag=f"{table.game}-{table.code}",
urgency="high", badge=_badge(seat)))
return wake
- Never while the page is open. A page that checks in has its own ring, title and chime; a stream checks in every 10 seconds, so a page quiet for 15 is gone. A page that’s only just gone quiet wakes the table again when it will be (
movesreturns when), so the notice still goes. With 1.3.0’s clock unchanged (David’s call), it lands before the host’s Wait for them at 20 seconds and the bot at 45. - Once per decision. What was sent to each seat is kept in the table’s
roomunderpushed: the decision’s key, when, and how many in a row. - Three, then quiet. After 3 notices at one table that the player hasn’t come back from, none until their page checks in there again.
- Quiet hours hold everything, except from a table the player was at in the last 600 seconds (ten minutes): they’re up.
- Their choices: a device that turned off “It’s my move” or “A table I’m sitting at starts” isn’t sent that event.
- The icon’s count: a signed-in player’s notice carries how many of their tables wait on them now, for the Home Screen icon.
- A ready between rounds is never a notice, and without the keys nothing here reads the database.
Every notice from a table has the table’s tag, so a newer one replaces the older on the lock screen, and a tap opens the table at your seat, where your page checking in makes a covering bot step aside by itself.
The account page#
The account page’s section is there only while the site can send (push_account, a template tag, returns nothing without the keys). It’s drawn from account(user): the account’s devices (what each page called itself, since when, when last sent) and their choices.
push/views.py account · lines 189–197def account(user) -> dict:
"""What the account page's Notifications section is drawn from
(house/notify.js, accountSection): the account's devices and their
choices (the newest's: the page sets them on every device at once)."""
subs = list(Subscription.objects.filter(user=user))
when = lambda d: f"{d:%b} {d.day}"
devices = [{"id": s.pk, "device": s.device, "endpoint": s.endpoint, "since": when(s.created), "sent": when(s.sent) if s.sent else None} for s in subs]
first = subs[0] if subs else None
return {"devices": devices, "choices": _shown(first) if first else None}
Quiet hours#
On by default, 22:00:00 to 08:00:00 on the device’s own clock (David’s call, 2026-11-09), and a player can change both or turn them off. Nothing is sent in them, and nothing is saved for later.
push/models.py Subscription.def is_quiet(self, at: datetime) -> bool:
"""Whether `at` falls in this device's quiet hours. They may run over
midnight (10 pm to 8 am) or not (1 pm to 3 pm)."""
if not self.quiet or self.quiet_from == self.quiet_to:
return False
now = self.local(at).time()
if self.quiet_from < self.quiet_to:
return self.quiet_from <= now < self.quiet_to
return now >= self.quiet_from or now < self.quiet_to
The exception, a table the player was at in the last ten minutes, belongs to the events, which aren’t built yet.
Sending#
A Notice is what a device shows:
push/send.py Notice · lines 38–46@dataclass(frozen=True)
class Notice:
title: str
body: str
path: str # where a tap goes, on this site ("/games/euchre/t/KQ7M2X/")
tag: str = "" # a newer notice with the same tag replaces the older (a table's code)
urgency: str = "normal" # "high" for your move
ttl: int = TTL
badge: int | None = None # the number on the Home Screen icon, if it changes
The message is in Declarative Web Push’s shape (WebKit’s, iOS 18.4 and Safari 18.5). Safari shows it without waking a service worker, so it can’t fail to show there; every other browser hands it to the site’s worker, which reads the same fields.
push/send.py payload · lines 58–72def payload(notice: Notice, origin: str) -> dict:
"""The message, as Declarative Web Push describes a notification."""
shown = {
"title": notice.title,
"body": notice.body,
"navigate": f"{origin.rstrip('/')}{notice.path}",
"lang": "en-US",
"dir": "ltr",
"silent": False,
}
if notice.tag:
shown["tag"] = notice.tag
if notice.badge is not None:
shown["app_badge"] = str(notice.badge)
return {"web_push": 8030, "notification": shown}
send waits for the transaction that caused the notice to commit, then hands it to a pool of two threads, so a move never waits on a push service. Without both VAPID keys it sends nothing, and nothing fails: the site works as it did.
push/send.py send · lines 75–84def send(subscriptions, notice: Notice) -> None:
"""Send `notice` to these devices once the current transaction commits
(at once outside one). Nothing, without VAPID keys."""
ids = [s.pk for s in subscriptions]
if not ids or not configured():
return
if settings.PUSH_INLINE:
transaction.on_commit(lambda: deliver_all(ids, notice))
else:
transaction.on_commit(lambda: _pool.submit(_in_thread, ids, notice))
Each device’s message goes through pywebpush, which encrypts it for that browser (aes128gcm, RFC 8291) and signs the request with the site’s key (VAPID, RFC 8292):
push/send.py deliver · lines 102–131def deliver(sub: Subscription, notice: Notice) -> bool:
"""One device. A push service that says the browser's gone (404, 410)
loses the subscription; one that keeps failing loses it after
FAILURES_KEPT in a row."""
headers = {"Urgency": notice.urgency}
if notice.tag:
headers["Topic"] = topic(notice.tag)
try:
webpush(
subscription_info=sub.info(),
data=json.dumps(payload(notice, sub.origin)),
vapid_private_key=settings.VAPID_PRIVATE_KEY,
vapid_claims={"sub": settings.VAPID_SUBJECT},
ttl=notice.ttl,
headers=headers,
timeout=TIMEOUT,
)
except WebPushException as e:
status = getattr(e.response, "status_code", None)
if status in GONE:
sub.delete()
return False
log.warning("A push service refused notification %s (status %s)", sub.pk, status)
return _failed(sub)
except Exception:
# (a push service that can't be reached at all: the network, a timeout)
log.warning("Couldn't reach a push service for notification %s", sub.pk, exc_info=True)
return _failed(sub)
Subscription.objects.filter(pk=sub.pk).update(sent=timezone.now(), failures=0)
return True
- TTL is 900 seconds: a push service gives up after that, because “your move” is worthless an hour later.
- Urgency is
highfor your move, so a phone saving its battery still wakes for it. - Topic is the notice’s tag (a table’s code, say), so a newer message replaces one the push service hasn’t delivered yet. The tag does the same on the lock screen.
- A push service that answers 404 or 410 is saying the browser unsubscribed: the subscription goes. One that fails 5 times in a row goes too; a send that gets through starts the count again.
The keys#
Push services know the site by a VAPID key pair, set only in the environment: VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY (VAPID_SUBJECT says how a push service can reach the site, https://unnecessaryobstacles.com by default). manage.py push keys makes a pair; setting them on Heroku is David’s step after a release ships, never a session’s. Changing the pair later turns notifications off on every device until each player turns them on again. manage.py push status says how many devices have them on and whether the site can send.
The service worker#
obstacles/sw.js is the site’s one service worker. pwa.worker serves it at /sw.js, at the root so its scope is every page, with Cache-Control: no-cache and what it needs to know put in for /*CONFIG*/:
obstacles/pwa.py worker_config · lines 94–106def worker_config() -> dict:
"""What the worker is told: which games' pages to keep, the offline page
and what it needs, the icon a notification shows, and the site's version
(so every release installs a new worker)."""
from feedback.context_processors import version
return {
"version": version(),
"offline": [g.slug for g in offline_games()],
"offlinePage": reverse("offline"),
"precache": [static(p) for p in OFFLINE_PAGE_NEEDS],
"icon": static("img/app-icon-192.png"),
}
The site’s version is in it, so every release changes the file and browsers install the new one. The head every page includes (templates/house/app_head.html) registers it once the page has loaded, so it never slows a page; tests/test_home_screen.py fails if anything else registers one.
It does three things, and leaves everything else (tables, streams, the API, every post) to the network:
obstacles/sw.js route · lines 28–45/** What to do with a request: 'page' (an offline game's page), 'file' (a
* static file one of them loads), 'other-page' (any other page: the offline
* page if the network fails), or null (leave it to the network). */
function route(request, clientUrl) {
if (request.method !== 'GET') return null;
const url = new URL(request.url);
if (url.origin !== self.location.origin) return null;
if (request.mode === 'navigate') return offlineGame(url.pathname) ? 'page' : 'other-page';
if (url.pathname.startsWith('/static/')) {
// (a page's own files, or a worker's, which is itself under /static/)
const from = clientUrl ? new URL(clientUrl).pathname : '';
return offlineGame(from) || from.startsWith('/static/') ? 'file' : null;
}
// A puzzle's daily, so today's can be played offline once seen today.
const daily = /^\/games\/([a-z0-9-]+)\/(?:api\/)?daily\/$/.exec(url.pathname);
if (daily && CONFIG.offline.includes(daily[1])) return 'file';
return null;
}
- It shows a push. On Chrome, Edge and Firefox the message comes to the worker, which shows it with the site’s icon, the notice’s tag (
renotify, so a newer one from the same table replaces the older and still sounds) and where a tap goes, and sets the Home Screen icon’s count (setAppBadge) if the message carries one. A message it can’t read still shows something, because every push must. On Safari the message shows by itself (Declarative Web Push). - A tap opens the table. If a tab at that address is open, it comes forward; otherwise the address opens.
- It keeps the puzzles for offline play (below).
Offline puzzles#
Every game whose puzzles are made on the device plays without a connection once it’s been opened online (David’s call, 2026-11-09): every game on the shelf that isn’t played at a table, which offline_games() reads from the catalog.
- The game’s page is answered from the network, and a copy is kept. Only when the network fails is the copy used. So nothing is served stale while there’s a connection, which was ADR 0029’s worry about a worker.
- Its files (
/static/…) are the same: from the network, kept when an offline game’s page or a worker it started asked for them, and the copy used only when the network fails. Chess Puzzles keeps only the shards it loaded, so the puzzles you’ve seen. - Today’s daily (
/games/<slug>/api/daily/) is kept the same way, so a daily seen today can be played offline. - The first visit counts. A page that opened before the worker was running sends it the list of what it loaded (
performance.getEntriesByType('resource')), and the worker keeps those. - One cache,
uo-offline-1, renamed only if what it holds changes shape; olderuo-caches go when a worker activates.
A solve made offline waits on the device and is posted when the connection’s back, counting on its day only if it’s still that day (Front-end kits).
The offline page#
Any other page the network can’t reach (a table, the shelf, your account) gets /offline/ instead, kept when the worker installs with the files it draws with (OFFLINE_PAGE_NEEDS):
obstacles/pwa.py offline · lines 128–136@require_safe
def offline(request):
"""What a page that needs the network shows without one: the puzzles that
play on this device. Kept by the worker when it installs, so the same for
everyone (nothing of anyone's account on it)."""
games = {g.slug: g.title for g in offline_games()}
response = render(request, "house/offline.html", {"games": games, "pages": {slug: reverse("games:play", args=[slug]) for slug in games}})
response["Cache-Control"] = "no-cache"
return response
It says “You’re offline” and “Tables need a connection. These play without one, on this device:”, then lists the games whose pages this device kept, newest first, each with the day it was last opened (the kept copy’s Date), read from the cache by the page’s own script. With none, it says to open a puzzle once while online. It’s the same for everyone, with nothing of an account on it, and search engines are told not to list it.
Tests#
tools/house/sw.test.mjs runs the worker under Node with a fake network, caches and clients: what it answers and what it leaves alone, a page and its files kept and used only offline, a table’s files never kept, the offline page, a push shown and its count set, and a tap bringing the tab forward or opening it. tests/test_home_screen.py holds where it’s served, what it’s told and that only the head registers it, and what the offline page needs.
tests/test_push.py: turning them on and off for an account and a guest (no cookie for a guest), the push services and keys that are taken and refused, a seat reaching its account’s devices and its guest’s once each, a real message signed and encrypted by pywebpush with only the network faked, the Declarative Web Push shape, sending only after commit and never without keys, forgetting a device that’s gone or keeps failing, and quiet hours across time zones and midnight.
Push on a phone (and Safari’s offline Home Screen app) can only be checked on the live site, over its secure address, and on a real iPhone’s Home Screen app: those are the release’s after-ship playtest lines. The playtest server has its own key pair, so on the laptop’s Chrome the ask, the account’s section and a push itself can be tried before then (Releases, the notify Test it).