# Troubleshooting: the browser, the network and applications that stay open

What surprises when a JumPHP game or application runs **for a long time in a browser** and talks to a server (a chat, an
online game, a connected tool): disconnections "for no reason", lost messages, a wrong time, notifications that never come.
Each point below was met for real (the CaraChat chat, November 2026): the cause, then what to do.

## 1. A hidden tab draws nothing: PHP used to stop

**Symptom**: the user switches to another tab (or minimizes the window); a few minutes later the server drops them for
inactivity, although their connection was fine.

**Cause**: the engine runs PHP one frame per `requestAnimationFrame` (Emscripten's main loop). A hidden tab gets **no**
`requestAnimationFrame` at all: not one line of PHP runs. The WebSocket stays open (the browser keeps it), but nobody reads
what arrives nor answers the application's pings: the server believes the client is dead.

**What the engine does (0.5.63 and later)**: while the tab is hidden, the page runs **one frame a second** itself
(`keepRunningWhenHidden()` in `engine/web/jumphp.js`). No new WebAssembly build is needed: the JavaScript calls
`jumphp_frame()` between two frames, as it already calls `jumphp_events()` when the tab is being hidden. It does what a
normal frame does around the call (page events, bridge, modules). The clock is a **Web Worker**'s: the page's own timers
are slowed to once a minute after 5 minutes in the background, a worker's are not. The main loop being stopped, nothing
runs twice; back in sight, the normal frames go on. `project.yaml` `hidden_frames: false` turns it off (a game with nothing
to do while hidden).

- The time step stays capped at 0.1 s a frame: a second away teleports nothing.
- The sound is muted while hidden (`mute_when_hidden`); `pause_scene` pauses the game if it has one.

**What stays impossible**: a **phone freezes the whole tab** (Android Chrome after a few minutes, iOS Safari almost at once),
as Chrome's "Memory Saver" does on a computer. No JavaScript runs any more: neither the page nor the worker. To reach someone
then, the server sends a **push notification** (§5) and keeps their place (§3).

## 2. The server must count the network layer's signs of life

**Symptom**: `drop …: timeout` in the server's logs.

**Cause**: the server counted only the application's own messages (the chat's `667`). But the browser's network layer
(`php-wasm-network`) sends `{"t":"ping"}` by itself **every 15 seconds**, from JavaScript, even while PHP does not run.

**On the server**:
- count **that transport ping** as presence (the CaraChat server: `ChatServer::touch()` called by `WsSession` on `ping`);
- send a WebSocket ping (opcode `0x9`) itself every **30 s**: **Cloudflare cuts a silent WebSocket after 100 s**, other
  proxies sooner;
- pick a long inactivity delay (minutes), and do **not** take "no longer answers" for "left" (§3).

## 3. A socket can be dead without knowing it: take the line again

**Symptom**: back on a phone's tab after a few minutes: the application looks connected but nothing arrives any more; or the
user is connected again and lost the messages that came meanwhile.

**Causes**: a sleeping phone, a network change (Wi-Fi → 4G), a proxy restarting. The WebSocket may stay "open" on both sides
while carrying nothing; or close with code **1006** (abnormal closure, no reason given).

**The model that works** (CaraChat's, `caramail-server` `Relay`):
1. at login the server gives a **resume token** (not numbered);
2. every message sent to the client is **numbered**, and the server keeps the last ones;
3. when the socket goes, the member **stays** (shown "away" to the others) for a grace period (CaraChat: 12 h);
4. the client reconnects by itself (0.3 s, 1, 2, 4, 8, 15, then 30 s) with `token + number of the last message received`: the
   server sends what is missing; an unknown token (too late, server restarted) → a normal new login, and the user is put
   back where they were (the same room);
5. what the user does during the cut **waits** in a queue and goes once back;
6. a tab coming back after more than ~20 s hidden **takes its line again at once** (closes and reopens): its socket may have
   died silently; the resume is free thanks to the numbers;
7. **no** reconnection after an ejection or a "Quit"; "Quit" and the page going away (`lifecycle()`'s `close`, the
   `pagehide` event) tell the server "I am leaving" (else the member stays a ghost until the grace ends).

Measure the time away with `Time::now()` (the real clock), **not** `$engine->time()`: game time stops with the tab.

## 4. The PHP server itself (a `stream_select` loop)

- **Never give a closed stream to `stream_select()`**: PHP 8 throws a `TypeError` ("supplied resource is not a valid stream
  resource"), the server dies and **everybody is disconnected** at once. It happens when a client is dropped outside the read
  loop (the `tick()` that drops silent ones): remove closed sessions **before** building the `select` lists, and skip what is
  no longer a resource (`is_resource()`).
- Block nothing: an outgoing HTTP call (sending a notification) goes through `curl_multi`, advanced at each pass.
- Log **why** each connection ends: closed by the client (WebSocket code: 1000 normal, 1001 page left, 1006 cut), end of
  stream, write failure, inactivity, ejection. And have the client tell, once back, what it saw (the browser's reason, how
  long the tab was hidden): without that, "there are cuts" stays a mystery.
- The disk: a machine that deploys often with Docker piles up images and build cache. A full disk breaks the server's saves
  (`No space left on device`). `docker image prune -f`, `docker builder prune -f`, and watch `df -h`.
- Restarting the server cuts everybody: do it when `status` shows few people, with clients that reconnect (§3).

## 5. Notifications

Two paths that complete each other:

| | Browser notification | Push notification (JumPHP runtime) |
|---|---|---|
| When | the page is open, even hidden (§1) | even with the page closed, the phone asleep |
| Where | computers; not Android Chrome (it requires a service worker) | Android phones with the JumPHP runtime |
| Code | `JumPHP\Native\Notification::show($title, $text)` | the extension `jumphp/notification` (docs/notifications.md), sent by the **server** |
| Consent | `Notification::requestPermission()` **from a click**; `Notification::permission()` | the runtime's window on the phone |

- A permission is asked from a user **gesture** (click, key): browsers refuse it otherwise.
- A page **in a frame of another origin** (the playground's games) may not ask for the permission: the engine then goes
  through the parent page (`postMessage` `jumphp:notify`, `jumphp:notify-permission`, and `jumphp:notify-state` at the start), which shows the notification itself.
- Push: the application's server knows the id the page subscribed (`subscribe($id)`) and sends with the owner's `jnt_…` token
  (in **its** configuration, never in a repository). Three doors: the `notify` right approved by the administrator, the token,
  the person's consent.
- Notify only when useful: the person is **away** (tab hidden or line cut), a message **for them** (private, their nickname),
  a session about to end; one notification of a kind every few minutes at most.

## 6. Time, numbers, clocks

- PHP in the browser runs in **UTC**: `date('H:i')` shows Greenwich time. Set the time zone
  (`date_default_timezone_set('Europe/Paris')`, or the one the page gives).
- `Time::now()` counts from its first call (it starts at 0): it is **not** a date. A date: `time()` / `microtime(true)` (float).
- **32-bit** integers in the browser (`PHP_INT_SIZE === 4`): no milliseconds since 1970 as an int, no `pack('J')` (AGENTS.md
  golden rules §2).

## 7. The page's life

- `lifecycle()`: `hide` and `close` are delivered **at once**, between two frames (PHP can still save or warn the server);
  `show` when it comes back.
- `close` comes from `pagehide`: the page is going (closed, reloaded, navigated away). A page may **come back** from the cache
  (bfcache): the application must be able to reconnect after a `close`.
- On phones the on-screen keyboard shrinks or covers the page; do not focus a field by yourself (it opens the keyboard).

## 8. Checklist of a connected application

- [ ] The server counts transport pings and sends its own (≤ 30 s).
- [ ] Long inactivity delay; a lost socket is not a departure (grace, member "away").
- [ ] Automatic reconnection with resume (token + numbers), queue of what is sent, back-off, none after an ejection.
- [ ] Immediate resume when the tab comes back after a long absence.
- [ ] "Quit" and `close` tell the server.
- [ ] The server never gives a closed stream to `stream_select()`, never blocks, logs why connections end.
- [ ] The client tells the server about its cuts once back.
- [ ] Time zone set; no 64-bit integers.
- [ ] Notifications: browser (permission from a click) + push through the runtime for phones.
- [ ] Server disk watched; restarts at quiet hours.
