Calls: the browser mends a connection that stops working too (spec 15.27)
room.js's recoveryStep is ConnectionRecovery's twin: the same trouble
rules, schedule, escalation to a reset, leader and follower, and the
failure note ("Could not connect.", Retry kept) only after a minute. A
tile's note adds "... may be on an old version of Calls" for an app that
does not say its version once that minute has passed, and "... is on an
old version" for one below 0.4.2 at any time. Quality reports count
autoRestarts and autoRebuilds.
Gates: room-recovery.test.mjs; the browser scenario icerecover (with an
0.4.10 baseline that stays down); TestNativeMacIceBrowser between the Mac
app and Chromium, both ways round; TestNativeMacIceRecovery in
native-pair. Spec 15.27 records the incident, what reproduced and why,
and the rules.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+1,015
−24
Makefile+5 −3docs/superpowers/specs/2026-09-07-meet-design.md+122 −0internal/calls/static/room.js+337 −13internal/callstest/browser_test.go+1 −0internal/callstest/native_ice_test.go+53 −1internal/callstest/quality_test.go+13 −3native/apple/Sources/CallsKit/ConnectionRecovery.swift+5 −2native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift+5 −2test/browser/call.mjs+142 −0test/browser/native-ice.mjs+145 −0test/browser/room-mute.test.mjs+8 −0test/browser/room-recovery.test.mjs+179 −0
diff --git a/Makefile b/Makefile| index 976b7e1..eb56f30 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -152,6 +152,7 @@ browser: |
| node --test test/browser/room-hearing.test.mjs |
| node --test test/browser/room-screen.test.mjs |
| node --test test/browser/room-reconnect.test.mjs |
| + node --test test/browser/room-recovery.test.mjs |
| node --test test/browser/room-connecting.test.mjs |
| node --test test/browser/room-glow.test.mjs |
| node --test test/browser/room-layout.test.mjs |
| @@ -180,7 +181,7 @@ native-browser: native-mac |
| # The gate runs CallsInterop, which native-mac does not build; without |
| # this it runs whatever binary a previous build left behind. |
| swift build --package-path native/apple --product CallsInterop |
| - CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CGO_ENABLED=0 go test -tags browser -count=1 -timeout 25m -run 'TestNative(MacBarLayout|MacCallsBrowser|MacChat|MacScreenMotion|MacScreenRecovery|BrowserAuthentication|BrowserAppLink|MacAudioSelfTest|MacAudioStartStall)' -v ./internal/callstest/ |
| + CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CGO_ENABLED=0 go test -tags browser -count=1 -timeout 25m -run 'TestNative(MacBarLayout|MacCallsBrowser|MacChat|MacScreenMotion|MacScreenRecovery|BrowserAuthentication|BrowserAppLink|MacAudioSelfTest|MacAudioStartStall|MacIceBrowser)' -v ./internal/callstest/ |
| # The Mac app in a call with Playwright's WebKit (not iOS Safari; see |
| # test/browser/native-webkit.mjs): codecs, Opus FEC, a thin path, and the |
| @@ -193,13 +194,14 @@ native-webkit: native-mac |
| npx playwright install webkit |
| CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CGO_ENABLED=0 go test -tags browser -count=1 -timeout 10m -run 'TestNativeMacWebKit' -v ./internal/callstest/ |
| -# Two apps in one call, sharing screens to each other. Separate from |
| +# Two apps in one call, sharing screens to each other, and spec §15.27's |
| +# connection that never comes up (TestNativeMacIceRecovery). Separate from |
| # native-browser because two unsigned apps on one Mac do not reliably |
| # connect, which looks like the macOS firewall: see TestNativeMacScreenShare. |
| # It runs CallsInterop too, so it builds it for the same reason. |
| native-pair: native-mac |
| swift build --package-path native/apple --product CallsInterop |
| - CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CGO_ENABLED=0 go test -tags browser -count=1 -timeout 20m -run 'TestNativeMacScreen(Share|PairRecovery)' -v ./internal/callstest/ |
| + CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CGO_ENABLED=0 go test -tags browser -count=1 -timeout 30m -run 'TestNativeMac(Screen(Share|PairRecovery)|IceRecovery)' -v ./internal/callstest/ |
| .PHONY: iphone iphone-device iphone-browser |
| iphone: |
diff --git a/docs/superpowers/specs/2026-09-07-meet-design.md b/docs/superpowers/specs/2026-09-07-meet-design.md| index 4904922..68d8632 100644 |
| --- a/docs/superpowers/specs/2026-09-07-meet-design.md |
| +++ b/docs/superpowers/specs/2026-09-07-meet-design.md |
| @@ -768,6 +768,8 @@ offer. This is what lets either side add a screen track or restart ICE |
| without an offer-request message. All candidates trickle as `candidate` |
| messages. A connection that reaches `failed` shows the tile as "could |
| not connect" with a retry that restarts ICE; nothing is silently spun. |
| +(Since §15.27 a connection that fails is restarted and rebuilt on its |
| +own first, and "could not connect" waits a minute.) |
| ### 5.2 ICE servers from the platform |
| @@ -2901,3 +2903,123 @@ a new call; both rate limits; the kill switch; a problem report's reference, |
| parts and scrubbing. `hub/report_test.go`: the sweep and the bound. The |
| browser gate's `quality` scenario and the native gate's check: real clients' |
| lines in the log, a shared call tag, no names. |
| + |
| +### 15.27 §5.1, §5.3, §4.6, §15.23, §15.26 — a connection that stops working is mended, and an old app is named (2026-10-21) |
| + |
| +**Why.** 21 October, about 14:41 UTC: Paul, on the Mac app (0.4.10) and |
| +sharing his screen; Farshad, in the call from Safari, left and came back |
| +from the Mac app (a version from before 0.4.9: it sent no quality reports). |
| +Paul saw a frozen picture, "Reconnecting to Farshad (Mac)…" and "A |
| +participant's media could not connect", and it never came back until |
| +Farshad left and joined again (from the browser, at 14:41:52). The server |
| +had also restarted at 14:38:10, mid-call (investigated apart). Nothing in |
| +the apps or the browser ever restarted ICE on a connection that failed: |
| +§5.3's renewals were the only restarts, a peer's `reset` the only rebuild, |
| +and the tile's Retry, which nobody pressed, the only nudge. |
| + |
| +**What the gate reproduced.** `TestNativeMacIceRecovery`: app A shares, B |
| +joins and leaves, C (the same person) joins with every ICE candidate it |
| +sends or receives pointed at the discard port for 25–40 s (`ICETestBlock`, |
| +the browser's `blockIceForTest`; test-only). Nothing exchanged during the |
| +block is any use afterwards, so only fresh candidates mend the pair. On |
| +0.4.10's code, with the sharer's screen watchdog out of the way, the pair |
| +was still down two and a half minutes after the block lifted, the tile |
| +still saying "Reconnecting to …" — and libwebrtc never called it `failed`: |
| +it sat in `checking`. With the watchdog on, its re-add of the screen |
| +renegotiated, the offer carried fresh candidates in its SDP, and that mended |
| +it 29–42 s after the block, by accident. In Chromium the same accident is |
| +§15.16's camera watch, which resets a pair whose camera stops encoding |
| +(three resets each side, mended 3 s after the block); with both cameras off |
| +— a person with no camera, or theirs turned off — nothing did, and the pair |
| +stayed down for the two minutes the scenario waited. The incident's own |
| +quality lines cannot say which it was: the Mac app on the far side sent |
| +none, and `carlos logs` now prints a line's top-level fields only, not its |
| +`report` member, so `cmd/quality-summary` reads nothing from it. |
| + |
| +**Decision: the recovery.** Per remote peer, across that pair's |
| +connections (a rebuild is the same episode), the apps' `ConnectionRecovery` |
| +and room.js's `recoveryStep`, twins with unit tests either side: |
| + |
| +- *In trouble*: ICE `failed`; `disconnected` for 5 s; never connected 15 s |
| + after the connection was made (the incident's shape); or at once when a |
| + description refused to apply on a connection that is not up. A connection |
| + that is up is never in trouble, whatever a negotiation step said. |
| +- *Attempts*, 0, 2, 5, 10 and 20 s apart, then every 30 s, for as long as |
| + the trouble lasts and the peer is in the call: an ICE restart, another, |
| + then the pair rebuilt through the hub's `reset` (§4.6: a new generation to |
| + both sides, a new connection, what leaving and joining again did — for one |
| + person, keeping the call), and round again. A restart on relay credentials |
| + due for renewal fetches `/ice` first (§5.3; the browser's is the tile's |
| + Retry path, the apps' a core `RefreshICE`). While the signalling stream is |
| + down nothing is attempted — an offer could not go out — and an attempt |
| + that fell due waits for it, so a server restart is ridden out, not fought. |
| +- *Who acts*: the impolite side (§5.1, the higher peer id) leads, on the |
| + schedule. The polite side follows 3 s behind and only if the leader has not |
| + acted since its own last attempt fell due: a remote ICE restart (an offer |
| + with a new username fragment) for a restart, a new connection for a |
| + rebuild. Two new clients never both rebuild; a client from before this, |
| + which never leads, is mended from this side alone, because every client |
| + since the rename answers an ICE restart and rebuilds on `pair`. |
| +- *Recovered* is ICE `connected` or `completed`. Trouble again within 60 s |
| + of a recovery carries on where the schedule was, so a link that comes and |
| + goes is not restarted every two seconds. |
| +- *What is said*: the tile's "Reconnecting to Farshad…" (§15.23) while it |
| + tries — after §15.24's "… is connecting" for someone in their first |
| + moments — and the failure notice only once the trouble has lasted a |
| + minute: the apps' status line "A participant's media could not connect.", |
| + the browser's "Could not connect." with its Retry, which stays as a manual |
| + nudge. Both go when it recovers. The apps no longer treat a refused |
| + candidate as a broken connection (one from before an ICE restart is |
| + refused as a matter of course); ICE says whether it works. |
| +- *Logged*: the apps' connection log (`os_log` category `connection`, and |
| + "Copy call diagnostics") has every ICE state, trouble, attempt and |
| + recovery, with six characters of the peer id; the browser's console the |
| + same. |
| + |
| +**Decision: the client, and "an old version".** Every app now says which it |
| +is on every request its core makes: `X-Calls-Client: mac 0.4.12` (`iphone`, |
| +`ipad`; a version of one to four parts of at most four digits). The stream |
| +that opens a participation records it, and every roster and `peer` event |
| +carries it as `client` on the peer's entry, set once and never by a peer. |
| +An app from before this sends no header and Go's own `Go-http-client/…` |
| +user agent, and the server calls that `"native"`; a browser has no key (its |
| +page is the server's own). Old clients ignore the key (Go, Swift and the |
| +browser all drop unknown roster members); an old server never sends it. |
| + |
| +- `protocol.MinNativeVersion` is **0.4.2**: before it, an app restarted ICE |
| + on every connection on every `/ice` answer (twelve times an hour, §15.21) |
| + and sent a Mac screen to browsers at a size their H.264 level refused, so |
| + it broke calls for the people it was in them with. Nothing the wire needs |
| + to recover a connection is newer: `pair` and generations, answering an ICE |
| + restart and ignoring unknown keys are in every app since 0.2. |
| +- A tile says "Farshad is on an old version of Calls — ask them to update" |
| + for an app that says it is older than that, whatever its connection is |
| + doing, and "Farshad may be on an old version of Calls — ask them to update" |
| + for an app that does not say, once its connection has been failing for the |
| + minute — when its age may be the reason, which is all this side can know. |
| + A browser is never old. On the apps the line is with the tile's other |
| + notices; in the browser it follows "Could not connect." in the tile's note, |
| + and alone it comes without the Retry. Every app that sends a version is |
| + this release or later, so until the minimum moves the first sentence is |
| + for the future, and the second is the one an incident like this one gets. |
| + |
| +**Telemetry.** §15.26's per-peer `events` gain `autoRestarts` and |
| +`autoRebuilds`, counts in the window, bounded as every count is and |
| +validated by the same walk; an older server drops them as unknown members. |
| + |
| +**Tests.** `ConnectionRecoveryTests` and `test/browser/room-recovery.test.mjs` |
| +(the schedule, the escalation, the five-second, fifteen-second and minute |
| +thresholds, the follower standing back, a beat-late follower not rebuilding |
| +twice, the stream down, the flap window, the version rule and the minimum |
| +agreeing with the server's); `protocol/client_test.go` (parsing, ordering, |
| +the header-or-agent rule); `TestRosterNamesEachPeersClient`; |
| +`callscore/client_test.go`; the quality tests' new counts and refusals. |
| +End to end, with the block: `TestNativeMacIceRecovery` (both apps new; C as |
| +an app from before, which A mends alone; and against a real 0.4.9 build, |
| +`ICE_RECOVERY_PEER`), the browser gate's `icerecover` (`ICE_RECOVER_OFF=both` |
| +is the 0.4.10 baseline and expects the pair to stay down; |
| +`ICE_RECOVER_OFF=c` has A mend it alone; `ICE_RECOVER_CAMERA=on` lets §15.16 |
| +get there first), and `TestNativeMacIceBrowser` (both, the app as an old |
| +one, the browser's recovery off). An 80 s block checks the minute-later |
| +sentence and "may be on an old version". |
| + |
diff --git a/internal/calls/static/room.js b/internal/calls/static/room.js| index 4fd5382..f0a22b8 100644 |
| --- a/internal/calls/static/room.js |
| +++ b/internal/calls/static/room.js |
| @@ -327,6 +327,26 @@ |
| const RECONNECT_AUDIO_AFTER = 2000; |
| const RECONNECT_HOLD = 1000; |
| const RECONNECT_EVERY = 200; |
| + // §15.27 (2026-10-21): a connection that stops working is mended without |
| + // anyone asking. ICE failed, disconnected RECOVER_DISCONNECTED_AFTER, or |
| + // never connected RECOVER_CONNECT_AFTER after the connection was made is |
| + // trouble; attempts follow RECOVER_BACKOFF and then RECOVER_EVERY: an ICE |
| + // restart, another, then the pair rebuilt (a reset), and round again. The |
| + // impolite side leads; the polite side follows RECOVER_FOLLOW behind, |
| + // only if the leader has not acted. The failure is said after |
| + // RECOVER_NOTICE_AFTER. Trouble again within RECOVER_FLAP of a recovery |
| + // carries on where the schedule was. The apps' ConnectionRecovery is the |
| + // twin. |
| + const RECOVER_DISCONNECTED_AFTER = 5000; |
| + const RECOVER_CONNECT_AFTER = 15000; |
| + const RECOVER_BACKOFF = [0, 2000, 5000, 10000, 20000]; |
| + const RECOVER_EVERY = 30000; |
| + const RECOVER_FOLLOW = 3000; |
| + const RECOVER_NOTICE_AFTER = 60000; |
| + const RECOVER_FLAP = 60000; |
| + // §15.27: the oldest app that does not break a call for the people in |
| + // it with it (protocol.MinNativeVersion carries the reason). |
| + const MIN_NATIVE_VERSION = '0.4.2'; |
| // §15.24 (2026-10-01), "<name> is connecting and can't hear you yet": |
| // said on a person's tile from the moment they appear until their own |
| // report says they hear us — but only once CONNECTING_GRACE has passed |
| @@ -405,6 +425,17 @@ |
| // §15.19: peer id -> {muted, cameraOff}, for the peers that have |
| // reported. A peer absent here is unknown and is drawn as neither. |
| const remoteMedia = new Map(); |
| + // §15.27: peer id -> what their participation was opened from, as the |
| + // roster says ("mac 0.4.12", "native", or '' for a browser); peer id -> |
| + // the recovery record of their connections; and, for the gate only, |
| + // until when every ICE candidate either way is pointed at nothing. |
| + const clients = new Map(); |
| + const recovery = new Map(); |
| + let iceBlockUntil = 0; |
| + let iceBlockMangled = 0; |
| + let autoRestartsTotal = 0; |
| + let recoveryOn = true; |
| + let autoRebuildsTotal = 0; |
| // The state this tab last put on the broadcast lane, as mediaKey |
| // writes it, so a toggle that changes nothing sends nothing. |
| let mediaSent = ''; |
| @@ -1488,9 +1519,9 @@ |
| case 'pair': return onPair(msg); |
| case 'gap': return onGap(msg); |
| case 'lost': return onLost(msg); |
| - case 'offer': return onOffer(msg); |
| - case 'answer': return onAnswer(msg); |
| - case 'candidate': return onCandidate(msg); |
| + case 'offer': return onOffer(testBlockedMessage(msg)); |
| + case 'answer': return onAnswer(testBlockedMessage(msg)); |
| + case 'candidate': return onCandidate(testBlockedMessage(msg)); |
| case 'chat': return onChat(msg); |
| case 'share': return onShare(msg); |
| case 'media': return onMedia(msg); |
| @@ -1566,6 +1597,7 @@ |
| const rp = (msg.roster && msg.roster.peers && msg.roster.peers[0]) || {}; |
| const g = rp.gen || 1; |
| if (rp.name) names.set(id, rp.name); |
| + clients.set(id, rp.client || ''); |
| learnMedia(id, rp.media); |
| ensurePC(id, g); |
| renderTiles(); |
| @@ -1574,6 +1606,8 @@ |
| function onGone(msg) { |
| if (!msg.from) return; |
| remoteMedia.delete(msg.from); |
| + clients.delete(msg.from); |
| + recovery.delete(msg.from); |
| closePC(msg.from, true); |
| dropWaiting(msg.from); |
| renderTiles(); |
| @@ -1856,6 +1890,14 @@ |
| pending: [], |
| descSeq: 0, |
| gen: g, |
| + // §15.27, what the recovery reads: when this connection was made, |
| + // when the far side last restarted ICE on it (an offer with a new |
| + // username fragment), the fragment it is on, and whether a |
| + // description refused to apply. |
| + builtAt: Date.now(), |
| + remoteRestartAt: 0, |
| + remoteUfrag: '', |
| + errored: false, |
| stream: null, |
| failed: false, |
| // §5.2: true while this connection is running on the empty list, |
| @@ -1955,7 +1997,8 @@ |
| pc.addEventListener('connectionstatechange', () => { |
| if (pcs.get(id) !== entry) return; |
| - entry.failed = pc.connectionState === 'failed'; |
| + // Whether it has failed for long enough to say so is the |
| + // recovery's verdict (§15.27), not this event's. |
| renderTiles(); |
| }); |
| @@ -2358,6 +2401,11 @@ |
| await entry.pc.setRemoteDescription(desc); |
| entry.ignoreOffer = false; |
| entry.descSeq = msg.seq || entry.descSeq; |
| + // §15.27: a new username fragment is the far side restarting ICE. |
| + const m = /(?:^|\r\n)a=ice-ufrag:([^\r\n]+)/.exec(desc.sdp || ''); |
| + const ufrag = m ? m[1] : ''; |
| + if (ufrag && entry.remoteUfrag && ufrag !== entry.remoteUfrag) entry.remoteRestartAt = Date.now(); |
| + if (ufrag) entry.remoteUfrag = ufrag; |
| await drainCandidates(entry); |
| await entry.pc.setLocalDescription(); |
| // One exchange completed, on the answering side (§5.3 step 2) — |
| @@ -2367,8 +2415,9 @@ |
| answeredExchange(entry); |
| send(msg.from, 'answer', { description: describe(entry.pc.localDescription) }); |
| } catch { |
| - // A description that will not apply leaves the pair to recover |
| - // through a reset rather than throwing into the event handler. |
| + // A description that will not apply leaves the pair to its |
| + // recovery (§15.27) rather than throwing into the event handler. |
| + entry.errored = true; |
| } |
| } |
| @@ -2399,7 +2448,8 @@ |
| entry.desc += 1; |
| await drainCandidates(entry); |
| } catch { |
| - // Same as above: a stale answer is not worth an exception. |
| + // Same as above: an answer that will not apply is the recovery's. |
| + entry.errored = true; |
| } |
| } |
| @@ -3215,6 +3265,7 @@ |
| function send(to, type, payload) { |
| if (!state.peer) return; |
| + payload = testBlockedPayload(payload); |
| // A target the hub has already said it does not have. Queueing for |
| // it would buy one more 404 and one more recovery round each time, |
| // and ICE alone produces a dozen candidates a renegotiation; the |
| @@ -4396,6 +4447,8 @@ |
| for (const rp of roster.peers || []) { |
| if (!rp || !rp.peer) continue; |
| if (rp.peer !== state.peer) { |
| + // §15.27: and what their participation was opened from. |
| + clients.set(rp.peer, rp.client || ''); |
| learnMedia(rp.peer, rp.media); |
| continue; |
| } |
| @@ -5002,7 +5055,8 @@ |
| let p = rec.peers.get(id); |
| if (!p) { |
| p = { present: true, reconnecting: { shown: false, count: 0, ms: 0 }, cantHear: { shown: false, count: 0, ms: 0 }, |
| - noSound: false, noSoundFromUs: false, audioBlocked: false, screenStalled: false }; |
| + noSound: false, noSoundFromUs: false, audioBlocked: false, screenStalled: false, |
| + autoRestarts: 0, autoRebuilds: 0 }; |
| rec.peers.set(id, p); |
| } |
| p.present = true; |
| @@ -5017,6 +5071,23 @@ |
| } |
| } |
| + function qualityPeerRecord() { |
| + return { present: true, reconnecting: { shown: false, count: 0, ms: 0 }, cantHear: { shown: false, count: 0, ms: 0 }, |
| + noSound: false, noSoundFromUs: false, audioBlocked: false, screenStalled: false, |
| + autoRestarts: 0, autoRebuilds: 0 }; |
| + } |
| + |
| + // qualityCount counts one of the recovery's steps toward a peer (§15.27) |
| + // into the window's events: autoRestarts or autoRebuilds. |
| + function qualityCount(id, key) { |
| + let p = qualityEvents.peers.get(id); |
| + if (!p) { |
| + p = qualityPeerRecord(); |
| + qualityEvents.peers.set(id, p); |
| + } |
| + p[key] = (p[key] || 0) + 1; |
| + } |
| + |
| // qualityTake is the window's events, in the report's shape — only what |
| // happened, so a quiet window says nothing — and the record started on |
| // the next window. A notice still showing goes on counting there, and |
| @@ -5038,6 +5109,8 @@ |
| if (p.reconnecting.ms) qualitySet(e, 'reconnectingSeconds', secs(p.reconnecting.ms)); |
| if (p.cantHear.ms) qualitySet(e, 'cantHearSeconds', secs(p.cantHear.ms)); |
| for (const k of ['noSound', 'noSoundFromUs', 'audioBlocked', 'screenStalled']) if (p[k]) e[k] = true; |
| + if (p.autoRestarts) qualitySet(e, 'autoRestarts', p.autoRestarts); |
| + if (p.autoRebuilds) qualitySet(e, 'autoRebuilds', p.autoRebuilds); |
| if (Object.keys(e).length) peers.set(id, e); |
| if (!p.present) { |
| rec.peers.delete(id); |
| @@ -5048,6 +5121,7 @@ |
| p.cantHear.count = 0; |
| p.cantHear.ms = 0; |
| p.noSound = p.noSoundFromUs = p.audioBlocked = p.screenStalled = false; |
| + p.autoRestarts = p.autoRebuilds = 0; |
| } |
| return { call, peers }; |
| } |
| @@ -5364,6 +5438,214 @@ |
| rec.peers = shown; |
| } |
| + // --------------------------------------------------------------- |
| + // A connection that stops working is mended (§15.27, 2026-10-21) |
| + // --------------------------------------------------------------- |
| + // |
| + // Paul, on the Mac app and sharing, saw "Reconnecting to Farshad (Mac)…" |
| + // and "A participant's media could not connect" when Farshad moved from |
| + // the browser to the app, and it never came back until Farshad left and |
| + // joined again. Nothing restarted ICE on a connection that failed; the |
| + // Retry on a tile was the only way, and nobody pressed it. |
| + |
| + function recoveryRecord() { |
| + return { troubleSince: null, disconnectedSince: null, attempts: 0, nextAt: null, lastDue: null, |
| + recoveredAt: null, attemptsAtRecovery: 0, restarts: 0, rebuilds: 0 }; |
| + } |
| + |
| + // recoveryGap is the wait before attempt k (from nought) after the last; |
| + // recoveryKind is two restarts, then a rebuild, and round again. |
| + function recoveryGap(k) { |
| + return k < RECOVER_BACKOFF.length ? RECOVER_BACKOFF[k] : RECOVER_EVERY; |
| + } |
| + function recoveryKind(k) { |
| + return k % 3 === 2 ? 'rebuild' : 'restart'; |
| + } |
| + |
| + // recoveryStep is one look at one person's connection: `look` is {ice |
| + // (iceConnectionState), builtAt, leader (the impolite side), signalling |
| + // (the stream is up), remoteRestartAt (the far side's last ICE restart |
| + // here, 0 for none), errored}. Moves `rec` on and answers '' or what to |
| + // do now, 'restart' or 'rebuild'. A connection that is up is well, |
| + // whatever a negotiation step said on the way. Nothing is attempted |
| + // while the stream is down: an offer could not go out. The follower |
| + // stands back when the leader has acted since its own last attempt fell |
| + // due. Pure, and lifted by name in the node test; the apps' |
| + // ConnectionRecovery.observe is its twin. |
| + function recoveryStep(rec, now, look) { |
| + const ice = look.ice; |
| + if (ice === 'closed') return ''; |
| + if (ice === 'connected' || ice === 'completed') { |
| + rec.disconnectedSince = null; |
| + if (rec.troubleSince !== null) { |
| + rec.troubleSince = null; |
| + rec.nextAt = null; |
| + rec.recoveredAt = now; |
| + rec.attemptsAtRecovery = rec.attempts; |
| + } |
| + return ''; |
| + } |
| + rec.disconnectedSince = ice === 'disconnected' ? (rec.disconnectedSince === null ? now : rec.disconnectedSince) : null; |
| + if (rec.troubleSince === null) { |
| + let bad = false; |
| + if (ice === 'failed') bad = true; |
| + else if (ice === 'disconnected') bad = now - rec.disconnectedSince >= RECOVER_DISCONNECTED_AFTER; |
| + else bad = now - look.builtAt >= RECOVER_CONNECT_AFTER; // new, checking |
| + if (!bad && !look.errored) return ''; |
| + rec.troubleSince = now; |
| + rec.attempts = rec.recoveredAt !== null && now - rec.recoveredAt < RECOVER_FLAP ? rec.attemptsAtRecovery : 0; |
| + rec.nextAt = now + (rec.attempts === 0 ? 0 : recoveryGap(rec.attempts)); |
| + rec.lastDue = now; |
| + } |
| + if (!look.signalling || rec.nextAt === null) return ''; |
| + const due = rec.nextAt; |
| + const offset = look.leader ? 0 : RECOVER_FOLLOW; |
| + if (now < due + offset) return ''; |
| + const kind = recoveryKind(rec.attempts); |
| + let leaderActed = false; |
| + if (!look.leader) { |
| + const since = rec.lastDue === null ? due : rec.lastDue; |
| + leaderActed = kind === 'restart' ? (look.remoteRestartAt || -Infinity) > since : look.builtAt > since; |
| + } |
| + rec.lastDue = due; |
| + rec.attempts += 1; |
| + rec.nextAt = Math.max(due, now - offset) + recoveryGap(rec.attempts); |
| + if (leaderActed) return ''; |
| + if (kind === 'restart') rec.restarts += 1; |
| + else rec.rebuilds += 1; |
| + return kind; |
| + } |
| + |
| + function recoveryTrying(rec) { |
| + return !!rec && rec.troubleSince !== null; |
| + } |
| + function recoveryFailing(rec, now) { |
| + return !!rec && rec.troubleSince !== null && now - rec.troubleSince >= RECOVER_NOTICE_AFTER; |
| + } |
| + |
| + // parseClient reads a roster's `client`: {app, version} for "mac 0.4.12", |
| + // {app: 'native', version: ''} for an app that did not say, null for |
| + // anything else (a browser has no key). compareVersions is numeric, part |
| + // by part. clientNotice is the tile's sentence about someone's app, or |
| + // '': an app older than MIN_NATIVE_VERSION always, an app that does not |
| + // say only once the connection to it has failed for a minute — when it |
| + // may be the reason, which is all this side can know. Pure, and lifted |
| + // by name in the node test; the apps' ClientVersion is the twin. |
| + function parseClient(client) { |
| + if (client === 'native') return { app: 'native', version: '' }; |
| + const m = /^(mac|iphone|ipad) (\d{1,4}(?:\.\d{1,4}){0,3})$/.exec(client || ''); |
| + return m ? { app: m[1], version: m[2] } : null; |
| + } |
| + function compareVersions(a, b) { |
| + const x = String(a).split('.').map((n) => parseInt(n, 10) || 0); |
| + const y = String(b).split('.').map((n) => parseInt(n, 10) || 0); |
| + for (let i = 0; i < Math.max(x.length, y.length); i++) { |
| + const l = x[i] || 0; |
| + const r = y[i] || 0; |
| + if (l !== r) return l < r ? -1 : 1; |
| + } |
| + return 0; |
| + } |
| + function clientNotice(name, client, failing) { |
| + const c = parseClient(client); |
| + if (!c) return ''; |
| + if (c.version) { |
| + return compareVersions(c.version, MIN_NATIVE_VERSION) < 0 |
| + ? name + ' is on an old version of Calls \u2014 ask them to update' : ''; |
| + } |
| + return failing ? name + ' may be on an old version of Calls \u2014 ask them to update' : ''; |
| + } |
| + |
| + // For the gate only (window.meet.blockIceForTest): while the block lasts |
| + // every candidate this tab sends or receives, trickled or written into a |
| + // description, has its port replaced by 9, which nothing listens on. Both |
| + // ends then hold only candidates that lead nowhere, and only fresh ones |
| + // (an ICE restart, or a new connection) mend the pair afterwards. The |
| + // apps' ICETestBlock is the twin. Inert unless a gate asks. |
| + function blockCandidateLine(line) { |
| + const f = String(line).split(' '); |
| + if (f.length > 7 && /^(a=)?candidate:/.test(f[0]) && f[6] === 'typ') f[5] = '9'; |
| + return f.join(' '); |
| + } |
| + // The gate's block on one targeted payload, or message, either way. |
| + function testBlockedPayload(payload) { |
| + if (!payload || !iceBlockUntil || Date.now() >= iceBlockUntil) return payload; |
| + if (payload.candidate) return Object.assign({}, payload, { candidate: testBlockedCandidate(payload.candidate) }); |
| + if (payload.description) return Object.assign({}, payload, { description: testBlockedDesc(payload.description) }); |
| + return payload; |
| + } |
| + function testBlockedMessage(msg) { |
| + if (!msg || !msg.payload || !iceBlockUntil || Date.now() >= iceBlockUntil) return msg; |
| + return Object.assign({}, msg, { payload: testBlockedPayload(msg.payload) }); |
| + } |
| + function testBlockedCandidate(c) { |
| + if (!c || !iceBlockUntil || Date.now() >= iceBlockUntil || !c.candidate) return c; |
| + iceBlockMangled += 1; |
| + return Object.assign({}, c, { candidate: blockCandidateLine(c.candidate) }); |
| + } |
| + function testBlockedDesc(d) { |
| + if (!d || !d.sdp || !iceBlockUntil || Date.now() >= iceBlockUntil) return d; |
| + iceBlockMangled += 1; |
| + const sdp = d.sdp.split('\r\n').map((l) => (l.startsWith('a=candidate:') ? blockCandidateLine(l) : l)).join('\r\n'); |
| + return { type: d.type, sdp }; |
| + } |
| + |
| + // watchRecovery runs every connection's recovery, five times a second, |
| + // and does what it asks; it answers the peers it is trying to mend now, |
| + // whose tiles say "Reconnecting to …". |
| + function watchRecovery(now) { |
| + const trying = new Set(); |
| + for (const id of Array.from(recovery.keys())) if (!pcs.has(id)) recovery.delete(id); |
| + let redraw = false; |
| + for (const [id, entry] of pcs) { |
| + let rec = recovery.get(id); |
| + if (!rec) { |
| + rec = recoveryRecord(); |
| + recovery.set(id, rec); |
| + } |
| + if (!recoveryOn) continue; |
| + const was = recoveryTrying(rec); |
| + const action = recoveryStep(rec, now, { |
| + ice: entry.pc.iceConnectionState, |
| + builtAt: entry.builtAt, |
| + leader: !entry.polite, |
| + signalling: !streamDownSince && !!state.peer && state.admitted, |
| + remoteRestartAt: entry.remoteRestartAt, |
| + errored: entry.errored, |
| + }); |
| + if (recoveryTrying(rec) !== was) { |
| + console.info('calls: recovery: ' + id.slice(0, 6) + (was ? ' recovered' : ' in trouble (ICE ' + entry.pc.iceConnectionState + ')')); |
| + } |
| + if (recoveryTrying(rec)) trying.add(id); |
| + const failing = recoveryFailing(rec, now); |
| + if (failing !== !!entry.failed) { |
| + entry.failed = failing; |
| + redraw = true; |
| + } |
| + if (action === 'restart') { |
| + autoRestartsTotal += 1; |
| + qualityCount(id, 'autoRestarts'); |
| + console.info('calls: recovery: attempt ' + rec.attempts + ', ICE restart for ' + id.slice(0, 6)); |
| + // On credentials due for renewal, a fetch first (§5.3), as the |
| + // tile's Retry does. |
| + if (iceStale()) { |
| + retryRenewal(id, '').catch((err) => { |
| + console.error('meet: renew', err); |
| + }); |
| + } else { |
| + bareRestart(id, entry); |
| + } |
| + } else if (action === 'rebuild') { |
| + autoRebuildsTotal += 1; |
| + qualityCount(id, 'autoRebuilds'); |
| + console.info('calls: recovery: attempt ' + rec.attempts + ', rebuilding the connection to ' + id.slice(0, 6)); |
| + requestReset(id); |
| + } |
| + } |
| + if (redraw) renderTiles(); |
| + return trying; |
| + } |
| + |
| // --------------------------------------------------------------- |
| // "… is connecting and can't hear you yet" (§15.24, 2026-10-01) |
| // --------------------------------------------------------------- |
| @@ -5543,6 +5825,7 @@ |
| if (state.stopped) return; |
| const now = Date.now(); |
| const joiningMoved = watchConnecting(now); |
| + const trying = watchRecovery(now); |
| const people = new Map(); |
| for (const [id, entry] of pcs) { |
| // Someone in their first moments has not lost anything yet: §15.24 |
| @@ -5555,7 +5838,7 @@ |
| const rec = hearing.get(id); |
| const media = remoteMedia.get(id); |
| people.set(id, { |
| - connectionBad: ice === 'disconnected' || ice === 'failed', |
| + connectionBad: ice === 'disconnected' || ice === 'failed' || trying.has(id), |
| // Two level polls without a packet: stopped, as far as a poll can tell. |
| audioMissing: !!(rec && rec.packetAt && media && !media.muted && now - rec.packetAt > 500), |
| }); |
| @@ -6747,7 +7030,7 @@ |
| // S4-9). Undefined for a tile whose role has never named one, in |
| // which case tile() falls back to the stream's own first video |
| // track, which is unambiguous by then. |
| - tile(id, name, entry.stream, false, tileNote(id, entry), entry.cameraTrack); |
| + tile(id, name, entry.stream, false, peerNote(id, entry), entry.cameraTrack); |
| markTile(id, remoteMedia.get(id) || null); |
| // The screen's own tile carries no note: §5.3's and §5.5's |
| // sentences are about a connection, and this is the same |
| @@ -6766,6 +7049,18 @@ |
| // §5.5's own wording depends on whether there was a relay to fail — |
| // "even through the relay" is a claim about this instance, and |
| // data-relay is where the server states it. |
| + // peerNote is the tile's note: tileNote's sentence about the connection, |
| + // and §15.27's about their app when that is worth saying. Alone, that |
| + // one is about their app and not this connection, so it comes without |
| + // the Retry. |
| + function peerNote(id, entry) { |
| + const connection = tileNote(id, entry); |
| + const old = clientNotice(names.get(id) || 'Someone', clients.get(id) || '', !!entry.failed); |
| + if (!old) return connection; |
| + if (!connection) return { text: old, retry: false }; |
| + return connection + ' ' + old; |
| + } |
| + |
| function tileNote(id, entry) { |
| const record = renewals.get(id); |
| if (record && record.trouble === 'expired') return ICE_EXPIRED; |
| @@ -6905,10 +7200,13 @@ |
| // One note element and one Retry beside it, whichever sentence the |
| // tile is carrying: `restartIce` is the handler for both, and it |
| // decides whether a retry means a bare ICE restart or a renewal. |
| - const show = !!noteText; |
| + // A note is a sentence, with the Retry beside it, or {text, retry} for |
| + // one that has nothing to retry (§15.27's note about someone's app). |
| + const note = noteText && typeof noteText === 'object' ? noteText : { text: noteText || '', retry: !!noteText }; |
| + const show = !!note.text; |
| t.note.hidden = !show; |
| - t.retry.hidden = !show; |
| - t.note.textContent = noteText || ''; |
| + t.retry.hidden = !show || !note.retry; |
| + t.note.textContent = note.text; |
| } |
| // startPlaying asks the element to play and, if the browser refuses |
| @@ -7988,6 +8286,17 @@ |
| qualityEveryForTest(ms) { |
| qualityEvery = Math.max(QUALITY_EVERY_MIN, Math.min(Number(ms) || QUALITY_EVERY, QUALITY_EVERY)); |
| }, |
| + // §15.27, for the gate: every ICE candidate this tab sends or receives |
| + // leads nowhere for `ms` (at most five minutes), so its connections |
| + // fail and only the recovery mends them. |
| + blockIceForTest(ms) { |
| + iceBlockUntil = Date.now() + Math.max(0, Math.min(Number(ms) || 0, 300000)); |
| + }, |
| + // §15.27, for the gate: the recovery switched off (false) and on, so a |
| + // scenario can stand in for a client from before it. |
| + recoveryForTest(on) { |
| + recoveryOn = !!on; |
| + }, |
| stallScreenForTest(ms) { |
| screenStallTestUntil = Date.now() + Math.max(0, Math.min(Number(ms) || 0, 60000)); |
| }, |
| @@ -8020,6 +8329,21 @@ |
| shareRecovery, |
| // §15.22: what the ladder and the receiver's own mending have done. |
| shareRecoveries: Object.assign({ reattaches: screenReattaches }, shareCounts), |
| + // §15.27: each connection's recovery — trying, failing for a |
| + // minute, attempts this episode, restarts and rebuilds — the |
| + // totals, the gate's block, and the peers' clients as the roster |
| + // has them. |
| + recovery: Object.fromEntries(Array.from(recovery, ([id, r]) => [id, { |
| + trying: recoveryTrying(r), failing: recoveryFailing(r, Date.now()), attempts: r.attempts, |
| + restarts: r.restarts, rebuilds: r.rebuilds }])), |
| + autoRestarts: autoRestartsTotal, |
| + autoRebuilds: autoRebuildsTotal, |
| + iceBlockMangled, |
| + clients: Object.fromEntries(clients), |
| + notes: Object.fromEntries(Array.from(pcs, ([id, entry]) => { |
| + const n = peerNote(id, entry); |
| + return [id, typeof n === 'object' ? n.text : n]; |
| + })), |
| // §15.23: whether "Reconnecting…" is said, for the call and by tile. |
| reconnect: { call: reconnect.call, peers: Array.from(reconnect.peers), streamDown: !!streamDownSince }, |
| // Targets a 404 has marked stale: nothing is sent to them and |
diff --git a/internal/callstest/browser_test.go b/internal/callstest/browser_test.go| index 8851e48..f192c54 100644 |
| --- a/internal/callstest/browser_test.go |
| +++ b/internal/callstest/browser_test.go |
| @@ -104,6 +104,7 @@ var scenarios = []string{ |
| "icerenewal", |
| "icefail", |
| "icestuck", |
| + "icerecover", |
| "guest", |
| "speaker", |
| "chat", |
diff --git a/internal/callstest/native_ice_test.go b/internal/callstest/native_ice_test.go| index d474a1b..2f1afbd 100644 |
| --- a/internal/callstest/native_ice_test.go |
| +++ b/internal/callstest/native_ice_test.go |
| @@ -4,7 +4,9 @@ package callstest |
| import ( |
| "context" |
| + "encoding/json" |
| "os" |
| + "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -129,6 +131,15 @@ func TestNativeMacIceRecovery(t *testing.T) { |
| for _, notes := range s.Notices { |
| for _, n := range notes { |
| sawReconnecting = sawReconnecting || strings.HasPrefix(n, "Reconnecting to ") |
| + } |
| + } |
| + // Someone in their first moments is "connecting and can't hear you |
| + // yet" (§15.24) before they are "Reconnecting to …" (§15.23). |
| + if s.Stats["connectingShown"] > 0 { |
| + sawReconnecting = true |
| + } |
| + for _, notes := range s.Notices { |
| + for _, n := range notes { |
| sawMaybeOld = sawMaybeOld || strings.Contains(n, "may be on an old version of Calls") |
| } |
| } |
| @@ -141,7 +152,7 @@ func TestNativeMacIceRecovery(t *testing.T) { |
| time.Sleep(250 * time.Millisecond) |
| } |
| if !sawReconnecting { |
| - t.Fatalf("A's tile for C never said Reconnecting to … while the block lasted") |
| + t.Fatalf("A's tile for C never said it was connecting, or Reconnecting to …, while the block lasted") |
| } |
| if block >= 75*time.Second { |
| if !sawNotice { |
| @@ -193,3 +204,44 @@ func TestNativeMacIceRecovery(t *testing.T) { |
| t.Fatalf("the notices outlived the recovery: %q %v", a.sample().Status, a.sample().Notices) |
| } |
| } |
| + |
| +// TestNativeMacIceBrowser is the same incident between the Mac app and a |
| +// browser (test/browser/native-ice.mjs): the app's ICE is blocked from the |
| +// start, and once the block lifts the two must hear each other again with |
| +// nobody acting — when both are this release, when the app is a stand-in |
| +// for one from before it (the browser mends it alone), and when the |
| +// browser's recovery is off (the app mends it alone). ICE_BLOCK_MS=80000 |
| +// also checks the minute-later failure sentence and "may be old". |
| +func TestNativeMacIceBrowser(t *testing.T) { |
| + root, err := filepath.Abs("../..") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + binary := filepath.Join(root, "native/apple/.build/debug/CallsInterop") |
| + if _, err := os.Stat(binary); err != nil { |
| + t.Fatal("build native interop executable with make native-mac first") |
| + } |
| + cases := []string{"both", "app-old", "web-old"} |
| + if only := os.Getenv("ICE_BROWSER_CASES"); only != "" { |
| + cases = strings.Split(only, ",") |
| + } |
| + for _, kase := range cases { |
| + t.Run(kase, func(t *testing.T) { |
| + rig := newBrowserRig(t) |
| + room, _ := rig.createMeeting(t) |
| + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Minute) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, "node", filepath.Join(root, "test/browser/native-ice.mjs"), rig.origin, room, binary, kase) |
| + cookies, _ := json.Marshal([]map[string]string{{"name": rig.cookieName, "value": rig.cookieB}}) |
| + input, _ := json.Marshal(map[string]string{"origin": rig.origin, "room": room, "cookies": string(cookies)}) |
| + cmd.Env = append(os.Environ(), "CALLS_COOKIE_NAME="+rig.cookieName, "CALLS_COOKIE_A="+rig.cookieA, "CALLS_NATIVE_INPUT="+string(input)) |
| + out, err := cmd.CombinedOutput() |
| + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { |
| + t.Log(line) |
| + } |
| + if err != nil { |
| + t.Fatalf("native-ice %s: %v", kase, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/callstest/quality_test.go b/internal/callstest/quality_test.go| index 82255d8..321a690 100644 |
| --- a/internal/callstest/quality_test.go |
| +++ b/internal/callstest/quality_test.go |
| @@ -172,7 +172,7 @@ func sampleQuality(remote string) protocol.QualityReport { |
| Audio: &protocol.InAudio{Packets: num(1490), Lost: num(10), Concealed: num(4800), Samples: num(1440000), JitterBufferMs: num(62)}, |
| Video: &protocol.InVideo{Packets: num(2700), Lost: num(300), Freezes: num(2), FreezeSeconds: num(1.5), Decoded: num(890), Dropped: num(4), Width: num(640), Height: num(360), FPS: num(29.7)}, |
| }, |
| - Events: &protocol.PeerEvents{CantHearSeconds: num(2), NoSound: true}, |
| + Events: &protocol.PeerEvents{CantHearSeconds: num(2), NoSound: true, AutoRestarts: num(2), AutoRebuilds: num(1)}, |
| }}, |
| } |
| } |
| @@ -237,6 +237,10 @@ func TestQualityReportsShareACallTagAndNameNothing(t *testing.T) { |
| t.Errorf("line[%q] = %v (%T), want %v", k, a[k], a[k], want) |
| } |
| } |
| + // §15.27: the connection's own recovery toward that peer. |
| + if ev, _ := peers[0].(map[string]any)["events"].(map[string]any); ev["autoRestarts"] != 2.0 || ev["autoRebuilds"] != 1.0 { |
| + t.Errorf("the recovery's counts are not in the line: %v", ev) |
| + } |
| if got := peers[0].(map[string]any)["rtt"]; got != 48.3 { |
| t.Errorf("rtt %v, want rounded to a tenth (48.3)", got) |
| } |
| @@ -278,7 +282,12 @@ func TestQualityReportSchemaIsStrict(t *testing.T) { |
| "an unknown limit": func(m map[string]any) { |
| peer0(m)["out"].(map[string]any)["video"].(map[string]any)["limit"] = "thermal" |
| }, |
| - "a name for a peer": func(m map[string]any) { peer0(m)["peer"] = "Ana" }, |
| + "a name for a peer": func(m map[string]any) { peer0(m)["peer"] = "Ana" }, |
| + "negative restarts": func(m map[string]any) { peer0(m)["events"].(map[string]any)["autoRestarts"] = -1 }, |
| + "a billion rebuilds and more": func(m map[string]any) { |
| + peer0(m)["events"].(map[string]any)["autoRebuilds"] = 1e10 |
| + }, |
| + "restarts as words": func(m map[string]any) { peer0(m)["events"].(map[string]any)["autoRestarts"] = "many" }, |
| "the same peer twice": func(m map[string]any) { m["peers"] = append(m["peers"].([]any), peer0(m)) }, |
| "a peer list for a room": func(m map[string]any) { m["peers"] = "everyone" }, |
| "five peers": func(m map[string]any) { |
| @@ -357,7 +366,8 @@ func TestTheLargestQualityLineFitsThePlatformsLine(t *testing.T) { |
| Video: in(), Screen: in(), |
| }, |
| Events: &protocol.PeerEvents{Reconnecting: big(), ReconnectingSeconds: num(599.9), CantHearSeconds: num(599.9), |
| - NoSound: true, NoSoundFromUs: true, AudioBlocked: true, ScreenStalled: true}, |
| + NoSound: true, NoSoundFromUs: true, AudioBlocked: true, ScreenStalled: true, |
| + AutoRestarts: big(), AutoRebuilds: big()}, |
| }) |
| } |
| if resp, _ := r.a.report(r.sqid, "quality", r.tokA, mustJSON(t, q)); resp.StatusCode != http.StatusAccepted { |
diff --git a/native/apple/Sources/CallsKit/ConnectionRecovery.swift b/native/apple/Sources/CallsKit/ConnectionRecovery.swift| index dfa92de..3777a66 100644 |
| --- a/native/apple/Sources/CallsKit/ConnectionRecovery.swift |
| +++ b/native/apple/Sources/CallsKit/ConnectionRecovery.swift |
| @@ -17,7 +17,8 @@ import Foundation |
| /// |
| /// - **In trouble**: ICE `failed`; `disconnected` for `disconnectedAfter` |
| /// (5 s); never connected `connectAfter` (15 s) after the connection was |
| -/// made; or a negotiation step on it threw. |
| +/// made, or at once when a negotiation step on it threw. A connection |
| +/// that is up is never in trouble, whatever a step said on the way. |
| /// - **Attempts**, `backoff` apart — 0, 2, 5, 10, 20 s, then every 30 s — |
| /// for as long as the trouble lasts and the peer is in the call: an ICE |
| /// restart, another, then the pair rebuilt from nothing (`reset`, which |
| @@ -99,7 +100,9 @@ struct ConnectionRecovery: Equatable { |
| /// One look; what to do now, if anything. |
| mutating func observe(at now: Double, _ look: Look) -> Action? { |
| if look.ice == .closed { return nil } |
| - let healthy = (look.ice == .connected || look.ice == .completed) && !look.errored |
| + // A connection that is up is well, whatever a negotiation step said on |
| + // the way: an error only hastens the verdict on one that is not. |
| + let healthy = look.ice == .connected || look.ice == .completed |
| if healthy { |
| disconnectedSince = nil |
| if troubleSince != nil { |
diff --git a/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift b/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift| index 0f20f84..3ff2146 100644 |
| --- a/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift |
| +++ b/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift |
| @@ -104,9 +104,12 @@ final class ConnectionRecoveryTests: XCTestCase { |
| XCTAssertEqual(r.observe(at: 30.2, Look(ice: .failed, builtAt: -100, leader: true)), .restart) |
| } |
| - func testANegotiationStepThatThrewIsTrouble() { |
| + func testANegotiationStepThatThrewHastensTroubleOnlyWhileNotConnected() { |
| var r = ConnectionRecovery() |
| - XCTAssertEqual(r.observe(at: 0, Look(ice: .connected, builtAt: -100, leader: true, errored: true)), .restart) |
| + XCTAssertEqual(r.observe(at: 1, Look(ice: .checking, builtAt: 0, leader: true, errored: true)), .restart) |
| + var up = ConnectionRecovery() |
| + XCTAssertNil(up.observe(at: 1, Look(ice: .connected, builtAt: 0, leader: true, errored: true))) |
| + XCTAssertFalse(up.trying) |
| } |
| func testAClosedConnectionIsLeftAlone() { |
diff --git a/test/browser/call.mjs b/test/browser/call.mjs| index 05a98ac..7bf963c 100644 |
| --- a/test/browser/call.mjs |
| +++ b/test/browser/call.mjs |
| @@ -429,6 +429,16 @@ function state(page) { |
| // are still in their first moments and the words are showing. |
| hearingList: s.hearingList, |
| connecting: s.connecting, |
| + // §15.27: each connection's recovery, the totals, the gate's own |
| + // block, the peers' clients and every tile's note, word for word; |
| + // and §15.23's words. |
| + recovery: s.recovery, |
| + autoRestarts: s.autoRestarts, |
| + autoRebuilds: s.autoRebuilds, |
| + iceBlockMangled: s.iceBlockMangled, |
| + clients: s.clients, |
| + notes: s.notes, |
| + reconnect: s.reconnect, |
| }; |
| }); |
| } |
| @@ -3019,6 +3029,138 @@ const run = { |
| await ctxB.close(); |
| }, |
| + // §15.27, the incident of 2026-10-21 in browsers: A and B in a call, B |
| + // leaves, A's ICE is blocked (every candidate it sends or receives |
| + // pointed at nothing) and C — the same person as B — comes back. Nothing |
| + // exchanged during the block is any use afterwards, so the pair is |
| + // mended only by fresh candidates. Nobody presses Retry; A has to decode |
| + // C again on its own. ICE_RECOVER_OFF=c switches C's recovery off (a |
| + // client from before §15.27, which A must mend alone); =both switches off |
| + // both, the 0.4.10 baseline, and expects the pair to stay down. |
| + // |
| + // Both cameras are off unless ICE_RECOVER_CAMERA=on. With a camera |
| + // sending, §15.16's encoder watch already resets a pair whose camera has |
| + // stopped encoding, and in 0.4.10 that reset was what mended a blocked |
| + // pair in a browser, three seconds after the block, by accident; a |
| + // person with their camera off, or no camera, had nothing. Off, the |
| + // recovery is the only thing that can, and "mended" is A hearing C. |
| + async icerecover() { |
| + const off = process.env.ICE_RECOVER_OFF || ''; |
| + const blockMs = Number(process.env.ICE_BLOCK_MS || 25000); |
| + const cameras = process.env.ICE_RECOVER_CAMERA === 'on'; |
| + const ctxA = await newContext('member A', { cookie: cookieA }); |
| + const ctxB = await newContext('member B', { cookie: cookieB }); |
| + const pageA = await openRoom(ctxA); |
| + const pageB = await openRoom(ctxB); |
| + const pair = await assertPair(pageA, pageB, 'member A', 'member B'); |
| + if (!pair) { |
| + await ctxA.close(); |
| + await ctxB.close(); |
| + return; |
| + } |
| + await leaveRoom(pageB); |
| + await ctxB.close(); |
| + if (!cameras) await pageA.click('#camera'); |
| + check(await until(async () => (await state(pageA)).peers.length === 0, 15000), |
| + 'A sees B go — ' + (await diagnose(pageA, 'member A'))); |
| + if (off === 'both') await pageA.evaluate(() => window.meet.recoveryForTest(false)); |
| + |
| + // Every reset either side asks the hub for, whoever asks: the |
| + // recovery's rebuilds, and §15.16's camera watch, which resets a pair |
| + // whose camera has stopped encoding. |
| + const resets = { a: 0, c: 0 }; |
| + const countResets = (who) => (req) => { |
| + if (req.method() === 'POST' && /\/signal$/.test(req.url()) && /"type":"reset"/.test(req.postData() || '')) resets[who] += 1; |
| + }; |
| + pageA.on('request', countResets('a')); |
| + await pageA.evaluate((ms) => window.meet.blockIceForTest(ms), blockMs); |
| + const blockedAt = Date.now(); |
| + const ctxC = await newContext('member B again', { cookie: cookieB }); |
| + ctxC.on('request', countResets('c')); |
| + const pageC = await openRoom(ctxC); |
| + if (!cameras) await pageC.click('#camera'); |
| + if (off) await pageC.evaluate(() => window.meet.recoveryForTest(false)); |
| + const joined = await until(async () => { |
| + const s = await state(pageA); |
| + return s.peers.length === 1 ? s : false; |
| + }, 20000); |
| + if (!check(joined, 'C is in the call with A — ' + (await diagnose(pageA, 'member A')))) { |
| + await ctxA.close(); |
| + await ctxC.close(); |
| + return; |
| + } |
| + const peerC = joined.peers[0]; |
| + |
| + // While the block lasts the pair does not come up, A's tile says |
| + // "Reconnecting to …" once C's first moments are over, and the failure |
| + // sentence waits for its minute. |
| + let sawReconnecting = false; |
| + let sawFailure = false; |
| + let early = ''; |
| + while (Date.now() - blockedAt < blockMs) { |
| + const s = await state(pageA); |
| + if (s.connection[peerC] === 'connected') { |
| + check(false, 'A connected to C through the block — ' + JSON.stringify(s.candidates)); |
| + break; |
| + } |
| + // Someone in their first moments is "connecting and can't hear you |
| + // yet" (§15.24) before they are "Reconnecting to …" (§15.23). |
| + if (s.reconnect.peers.includes(peerC) || (s.connecting[peerC] && s.connecting[peerC].shown)) sawReconnecting = true; |
| + if (s.notes[peerC] && Date.now() - blockedAt < 50000) early = s.notes[peerC]; |
| + if (/^Could not connect/.test(s.notes[peerC] || '')) sawFailure = true; |
| + await sleep(250); |
| + } |
| + const blocked = await state(pageA); |
| + line('block over: A ' + JSON.stringify({ connection: blocked.connection[peerC], recovery: blocked.recovery[peerC], |
| + mangled: blocked.iceBlockMangled, reconnect: blocked.reconnect })); |
| + if (off !== 'both') { |
| + check(sawReconnecting, "A's tile for C said it was connecting, or Reconnecting to …, while the block lasted"); |
| + check(!early, 'no failure sentence before its minute (' + early + ')'); |
| + if (blockMs >= 75000) check(sawFailure, 'the failure sentence came once the minute had passed'); |
| + } |
| + |
| + // Nobody does anything. |
| + const before = (await state(pageA)).frames[peerC] || 0; |
| + const within = Number(process.env.ICE_RECOVER_WITHIN || 90000); |
| + const mended = await until(async () => { |
| + const s = await state(pageA); |
| + if (s.connection[peerC] !== 'connected') return false; |
| + return (cameras ? (s.frames[peerC] || 0) > before + 15 : s.hearingList.includes(peerC)) ? s : false; |
| + }, within); |
| + const a = await state(pageA); |
| + const c = await state(pageC); |
| + line('A: ' + JSON.stringify({ connection: a.connection[peerC], recovery: a.recovery[peerC], |
| + autoRestarts: a.autoRestarts, autoRebuilds: a.autoRebuilds, notes: a.notes, clients: a.clients })); |
| + line('C: ' + JSON.stringify({ recovery: c.recovery, autoRestarts: c.autoRestarts, autoRebuilds: c.autoRebuilds })); |
| + line('resets asked for: ' + JSON.stringify(resets)); |
| + if (off === 'both') { |
| + // The baseline: with no recovery anywhere, the pair stays down. |
| + check(!mended, 'with no recovery on either side the pair stayed down for ' + within / 1000 + ' s after the block'); |
| + line(mended ? 'BASELINE recovered on its own' : 'BASELINE STUCK ' + within / 1000 + ' s after the block lifted'); |
| + } else { |
| + check(mended, 'A decodes C again, with nobody pressing Retry, within ' + within / 1000 + ' s of the block lifting — ' + |
| + (await diagnose(pageA, 'member A'))); |
| + if (mended) line('recovered ' + Math.round((Date.now() - blockedAt - blockMs) / 1000) + ' s after the block lifted'); |
| + // With cameras on, §15.16's watch may get there first, and the |
| + // recovery then has nothing to do: either is a mended pair. |
| + if (!cameras) check(a.autoRestarts + c.autoRestarts > 0, 'a restart was made on its own (A ' + a.autoRestarts + ', C ' + c.autoRestarts + ')'); |
| + if (off === 'c' && !cameras) check(c.autoRestarts === 0 && c.autoRebuilds === 0 && a.autoRestarts > 0, |
| + 'A mended it alone (A ' + a.autoRestarts + '/' + a.autoRebuilds + ', C ' + c.autoRestarts + '/' + c.autoRebuilds + ')'); |
| + const quiet = await until(async () => { |
| + const s = await state(pageA); |
| + return !s.notes[peerC] && !s.reconnect.peers.includes(peerC) ? s : false; |
| + }, 5000); |
| + check(quiet, 'the words go with the trouble (' + JSON.stringify((await state(pageA)).notes) + ')'); |
| + // A browser is never "on an old version". |
| + check(!(a.clients[peerC] || ''), 'a browser has no client in the roster (' + JSON.stringify(a.clients) + ')'); |
| + } |
| + |
| + await leaveRoom(pageA); |
| + await leaveRoom(pageC); |
| + await ctxA.close(); |
| + await ctxC.close(); |
| + }, |
| + |
| async icefail() { |
| const ctxA = await newContext('member A', { cookie: cookieA }); |
| const ctxB = await newContext('member B', { cookie: cookieB }); |
diff --git a/test/browser/native-ice.mjs b/test/browser/native-ice.mjs| new file mode 100644 |
| index 0000000..ef3c964 |
| --- /dev/null |
| +++ b/test/browser/native-ice.mjs |
| @@ -0,0 +1,145 @@ |
| +// native-ice.mjs — spec §15.27 between the Mac app and a browser: a |
| +// connection that cannot come up for a while (ICETestBlock, the app's |
| +// every candidate either way pointed at nothing) is mended once the path |
| +// is back, with nobody pressing anything. Driven by TestNativeMacIceBrowser. |
| +// |
| +// node native-ice.mjs <origin> <room> <interop binary> <case> |
| +// |
| +// case "both": both sides are this release. "app-old": the app neither |
| +// mends nor says its version (an app from before §15.27), so the browser |
| +// mends it alone, and once a minute has passed says the app may be old. |
| +// "web-old": the browser's recovery is off, so the app mends it alone. |
| +// The browser's camera is off: its own camera watch (§15.16) resets a pair |
| +// whose camera stops encoding, which mends a blocked pair by accident and |
| +// would hide whether the recovery did. |
| +import { chromium } from 'playwright'; |
| +import { spawn } from 'node:child_process'; |
| +import { createInterface } from 'node:readline'; |
| + |
| +const [origin, room, binary, kase] = process.argv.slice(2); |
| +const blockMs = Number(process.env.ICE_BLOCK_MS || 25000); |
| +const within = Number(process.env.ICE_RECOVER_WITHIN || 90000); |
| +let failed = false; |
| +const check = (ok, what) => { |
| + console.log((ok ? 'PASS ' : 'FAIL ') + what); |
| + if (!ok) failed = true; |
| + return ok; |
| +}; |
| +const browser = await chromium.launch({ headless: true, args: [ |
| + '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', |
| + '--autoplay-policy=no-user-gesture-required', '--disable-features=WebRtcHideLocalIpsWithMdns', '--mute-audio', |
| +] }); |
| +const context = await browser.newContext({ permissions: ['camera', 'microphone'] }); |
| +await context.addCookies([{ name: process.env.CALLS_COOKIE_NAME, value: process.env.CALLS_COOKIE_A, url: origin }]); |
| +const page = await context.newPage(); |
| +let native; |
| +try { |
| + await page.goto(`${origin}/m/${room}`); |
| + await page.waitForFunction(() => !!window.meet); |
| + await page.waitForFunction(() => window.meet.state().admitted, null, { timeout: 20000 }); |
| + await page.click('#camera'); |
| + if (kase === 'web-old') await page.evaluate(() => window.meet.recoveryForTest(false)); |
| + |
| + const env = { ...process.env, CALLS_TEST_ICE_BLOCK_MS: String(blockMs) }; |
| + if (kase === 'app-old') Object.assign(env, { CALLS_AUTO_RECOVERY: '0', CALLS_TEST_NO_CLIENT: '1' }); |
| + const blockedAt = Date.now(); |
| + native = spawn(binary, [], { stdio: ['pipe', 'pipe', 'pipe'], env }); |
| + native.stdin.write(process.env.CALLS_NATIVE_INPUT + '\n'); |
| + let sample = null; |
| + let exited = false; |
| + native.on('exit', () => { exited = true; }); |
| + // Only the gate's own observations: never library output, which can |
| + // carry SDP and candidates. |
| + createInterface({ input: native.stdout }).on('line', (line) => { |
| + try { |
| + const v = JSON.parse(line); |
| + if (v.stats) sample = v; |
| + } catch { /* not ours */ } |
| + }); |
| + native.stderr.resume(); |
| + const until = async (pred, ms) => { |
| + const end = Date.now() + ms; |
| + while (Date.now() < end) { |
| + if (exited) return false; |
| + const v = await pred(); |
| + if (v) return v; |
| + await new Promise((r) => setTimeout(r, 250)); |
| + } |
| + return false; |
| + }; |
| + const web = (id) => page.evaluate((id) => { |
| + const s = window.meet.state(); |
| + return { connection: Object.fromEntries(s.connection)[id] || '', hearing: s.hearingList.includes(id), |
| + recovery: s.recovery[id] || null, autoRestarts: s.autoRestarts, autoRebuilds: s.autoRebuilds, |
| + note: s.notes[id] || '', client: s.clients[id], reconnecting: s.reconnect.peers.includes(id), |
| + connecting: !!(s.connecting[id] && s.connecting[id].shown) }; |
| + }, id); |
| + |
| + const inCall = await until(() => sample && sample.phase === 'admitted' && sample.peer ? sample : false, 30000); |
| + if (!check(inCall, 'the app is in the call')) throw new Error('no app'); |
| + const app = inCall.peer; |
| + |
| + // The block: nothing comes up, and nothing worse than "connecting" or |
| + // "Reconnecting to …" is said before the minute. |
| + let said = false; |
| + let early = ''; |
| + let failure = false; |
| + let maybeOld = false; |
| + while (Date.now() - blockedAt < blockMs) { |
| + const w = await web(app); |
| + if (w.connection === 'connected') { |
| + check(false, 'the browser connected to the app through the block'); |
| + break; |
| + } |
| + if (w.reconnecting || w.connecting) said = true; |
| + if (/^Could not connect/.test(w.note)) { |
| + if (Date.now() - blockedAt < 50000) early = w.note; |
| + failure = true; |
| + } |
| + if (/may be on an old version of Calls/.test(w.note)) maybeOld = true; |
| + await new Promise((r) => setTimeout(r, 250)); |
| + } |
| + console.log('block over: browser ' + JSON.stringify(await web(app)) + '; app ' + |
| + JSON.stringify({ iceConnected: sample.stats.iceConnectedPeers, recoveryTrying: sample.stats.recoveryTrying, |
| + autoRestarts: sample.stats.autoRestarts, autoRebuilds: sample.stats.autoRebuilds, mangled: sample.stats.iceBlockMangled })); |
| + check(said, 'the browser’s tile for the app said it was connecting, or Reconnecting to …'); |
| + check(!early, 'no failure sentence before its minute (' + early + ')'); |
| + if (blockMs >= 75000) { |
| + check(failure, 'the failure sentence came once the minute had passed'); |
| + check(maybeOld === (kase === 'app-old'), 'the tile says the app may be old exactly when it does not say its version (' + maybeOld + ')'); |
| + } |
| + check((await web(app)).client === (kase === 'app-old' ? 'native' : 'mac 9.9.9'), |
| + 'the roster names the app’s client (' + (await web(app)).client + ')'); |
| + |
| + // Nobody does anything. |
| + const audio = sample.stats.audioBytesReceived; |
| + const mended = await until(async () => { |
| + const w = await web(app); |
| + return w.connection === 'connected' && w.hearing && sample.stats.iceConnectedPeers === 1 && |
| + sample.stats.audioBytesReceived > audio + 10000 ? w : false; |
| + }, within); |
| + const w = await web(app); |
| + console.log('browser: ' + JSON.stringify(w)); |
| + console.log('app: ' + JSON.stringify({ status: sample.status, notices: sample.notices, autoRestarts: sample.stats.autoRestarts, |
| + autoRebuilds: sample.stats.autoRebuilds })); |
| + if (check(mended, 'the browser and the app hear each other again within ' + within / 1000 + ' s of the block lifting, with nobody acting')) { |
| + console.log('recovered ' + Math.round((Date.now() - blockedAt - blockMs) / 1000) + ' s after the block lifted'); |
| + } |
| + if (kase === 'app-old') check(sample.stats.autoRestarts === 0 && w.autoRestarts > 0, 'the browser mended it alone'); |
| + if (kase === 'web-old') check(w.autoRestarts === 0 && sample.stats.autoRestarts > 0, 'the app mended it alone'); |
| + const quiet = await until(async () => { |
| + const v = await web(app); |
| + return !v.note && !v.reconnecting && !sample.status.includes('could not connect') ? v : false; |
| + }, 5000); |
| + check(quiet, 'the words go with the trouble, both sides'); |
| +} catch (err) { |
| + check(false, String(err && err.message || err)); |
| +} finally { |
| + if (native) { |
| + try { native.stdin.write('leave\n'); } catch { /* gone */ } |
| + await new Promise((r) => setTimeout(r, 1500)); |
| + native.kill(); |
| + } |
| + await browser.close(); |
| +} |
| +process.exit(failed ? 1 : 0); |
diff --git a/test/browser/room-mute.test.mjs b/test/browser/room-mute.test.mjs| index cce4d08..ba84ae9 100644 |
| --- a/test/browser/room-mute.test.mjs |
| +++ b/test/browser/room-mute.test.mjs |
| @@ -171,6 +171,8 @@ function reporter({ admitted = true, local = { muted: false, cameraOff: false }, |
| '\nlet mediaExtras = true;' + |
| '\nlet audioBlocked = false;' + |
| '\nlet screenStalled = [];' + |
| + // §15.27: rosterMedia also records each peer's client. |
| + '\nconst clients = env.clients = new Map();' + |
| '\nconst noSoundList = () => env.noSound;' + |
| '\nconst hearingList = () => env.heard;' + |
| '\nreturn { rosterMedia, reportMedia, memo: () => mediaSent, extras: () => mediaExtras,' + |
| @@ -193,6 +195,12 @@ function reporter({ admitted = true, local = { muted: false, cameraOff: false }, |
| return { ...made, sent, env }; |
| } |
| +test('a roster records each other peer\'s client, and a browser as none (§15.27)', () => { |
| + const r = reporter(); |
| + r.rosterMedia({ peers: [{ peer: 'me', client: 'mac 0.4.12' }, { peer: 'bea', client: 'native' }, { peer: 'cal' }] }); |
| + assert.deepEqual(Array.from(r.env.clients), [['bea', 'native'], ['cal', '']]); |
| +}); |
| + |
| test('a roster that has never heard from us is answered with a report', () => { |
| const r = reporter({ local: { muted: true, cameraOff: false } }); |
| r.rosterMedia({ peers: [{ peer: 'me' }, { peer: 'bea' }] }); |
diff --git a/test/browser/room-recovery.test.mjs b/test/browser/room-recovery.test.mjs| new file mode 100644 |
| index 0000000..5a89330 |
| --- /dev/null |
| +++ b/test/browser/room-recovery.test.mjs |
| @@ -0,0 +1,179 @@ |
| +// room-recovery.test.mjs — a connection that stops working is mended |
| +// without anyone asking (spec §15.27, 2026-10-21), gated without a browser. |
| +// |
| +// node --test test/browser/room-recovery.test.mjs |
| +// |
| +// recoveryStep and its helpers, clientNotice and the gate's own candidate |
| +// block, lifted out of the shipped room.js by name with the constants they |
| +// read. The apps' ConnectionRecoveryTests are the twin of these. |
| +import { test } from 'node:test'; |
| +import assert from 'node:assert/strict'; |
| +import { readFileSync } from 'node:fs'; |
| +import { fileURLToPath } from 'node:url'; |
| + |
| +const src = readFileSync(fileURLToPath(new URL('../../internal/calls/static/room.js', import.meta.url)), 'utf8'); |
| + |
| +function lift(name) { |
| + const start = src.indexOf('function ' + name + '('); |
| + assert.notEqual(start, -1, name + ' is not in room.js any more — this test is stale, not passing'); |
| + let depth = 0; |
| + for (let i = src.indexOf('{', start); i < src.length; i++) { |
| + if (src[i] === '{') depth += 1; |
| + else if (src[i] === '}') { |
| + depth -= 1; |
| + if (depth === 0) return src.slice(start, i + 1); |
| + } |
| + } |
| + assert.fail('unbalanced braces reading ' + name); |
| +} |
| +function liftConst(name) { |
| + const m = src.match(new RegExp('const ' + name + ' = ([^;]+);')); |
| + assert.ok(m, name + ' is not a const in room.js any more'); |
| + return 'const ' + name + ' = ' + m[1] + ';'; |
| +} |
| +const CONSTS = ['RECOVER_DISCONNECTED_AFTER', 'RECOVER_CONNECT_AFTER', 'RECOVER_BACKOFF', 'RECOVER_EVERY', |
| + 'RECOVER_FOLLOW', 'RECOVER_NOTICE_AFTER', 'RECOVER_FLAP', 'MIN_NATIVE_VERSION'].map(liftConst).join('\n'); |
| +const NAMES = ['recoveryRecord', 'recoveryGap', 'recoveryKind', 'recoveryStep', 'recoveryTrying', 'recoveryFailing', |
| + 'parseClient', 'compareVersions', 'clientNotice', 'blockCandidateLine']; |
| +// eslint-disable-next-line no-new-func |
| +const r = new Function(CONSTS + '\n' + NAMES.map(lift).join('\n') + '; return { ' + NAMES.join(', ') + ' };')(); |
| + |
| +// Five looks a second, in whole ticks, from `from` to `to` seconds; each |
| +// action with the second it was asked for. |
| +function run(rec, from, to, look) { |
| + const out = []; |
| + for (let tick = Math.round(from * 5); tick <= Math.round(to * 5); tick++) { |
| + const t = tick / 5; |
| + const a = r.recoveryStep(rec, t * 1000, look(t)); |
| + if (a) out.push([t, a]); |
| + } |
| + return out; |
| +} |
| +const look = (ice, o = {}) => Object.assign({ ice, builtAt: -100000, leader: true, signalling: true, remoteRestartAt: 0, errored: false }, o); |
| + |
| +test('a failed connection is restarted twice, then rebuilt, on the backoff', () => { |
| + const rec = r.recoveryRecord(); |
| + const seen = run(rec, 0, 160, () => look('failed')); |
| + assert.deepEqual(seen.map((a) => a[0]), [0, 2, 7, 17, 37, 67, 97, 127, 157]); |
| + assert.deepEqual(seen.map((a) => a[1]), |
| + ['restart', 'restart', 'rebuild', 'restart', 'restart', 'rebuild', 'restart', 'restart', 'rebuild']); |
| + assert.equal(rec.restarts, 6); |
| + assert.equal(rec.rebuilds, 3); |
| +}); |
| + |
| +test('disconnected is trouble after five seconds, and a blip is nothing', () => { |
| + const rec = r.recoveryRecord(); |
| + assert.deepEqual(run(rec, 0, 4.8, () => look('disconnected')), []); |
| + assert.equal(r.recoveryStep(rec, 5000, look('disconnected')), 'restart'); |
| + const blips = r.recoveryRecord(); |
| + assert.deepEqual(run(blips, 0, 20, (t) => look(Math.floor(t) % 6 < 4 ? 'disconnected' : 'connected')), []); |
| +}); |
| + |
| +test('a connection that never comes up is trouble fifteen seconds after it was made', () => { |
| + for (const ice of ['new', 'checking']) { |
| + const rec = r.recoveryRecord(); |
| + assert.deepEqual(run(rec, 0, 14.8, () => look(ice, { builtAt: 0 })), []); |
| + assert.equal(r.recoveryStep(rec, 15000, look(ice, { builtAt: 0 })), 'restart'); |
| + } |
| +}); |
| + |
| +test('the failure is said after a minute, and goes with the trouble', () => { |
| + const rec = r.recoveryRecord(); |
| + run(rec, 0, 59.8, () => look('failed')); |
| + assert.equal(r.recoveryTrying(rec), true); |
| + assert.equal(r.recoveryFailing(rec, 59800), false); |
| + assert.equal(r.recoveryFailing(rec, 60000), true); |
| + assert.equal(r.recoveryStep(rec, 61000, look('connected')), ''); |
| + assert.equal(r.recoveryTrying(rec), false); |
| + assert.equal(r.recoveryFailing(rec, 61000), false); |
| +}); |
| + |
| +test('trouble soon after a recovery carries on where the schedule was', () => { |
| + const rec = r.recoveryRecord(); |
| + run(rec, 0, 8, () => look('failed')); |
| + assert.equal(rec.attempts, 3); |
| + r.recoveryStep(rec, 9000, look('connected')); |
| + const again = run(rec, 20, 60, () => look('failed')); |
| + assert.deepEqual(again[0], [30, 'restart']); |
| + const later = r.recoveryRecord(); |
| + run(later, 0, 8, () => look('failed')); |
| + r.recoveryStep(later, 9000, look('connected')); |
| + assert.equal(r.recoveryStep(later, 80000, look('failed')), 'restart'); |
| +}); |
| + |
| +test('nothing is attempted while the signalling stream is down', () => { |
| + const rec = r.recoveryRecord(); |
| + assert.deepEqual(run(rec, 0, 30, () => look('failed', { signalling: false })), []); |
| + assert.equal(r.recoveryTrying(rec), true); |
| + assert.equal(r.recoveryStep(rec, 30200, look('failed')), 'restart'); |
| +}); |
| + |
| +test('a description that would not apply hastens trouble only while not connected', () => { |
| + const rec = r.recoveryRecord(); |
| + assert.equal(r.recoveryStep(rec, 1000, look('checking', { builtAt: 0, errored: true })), 'restart'); |
| + const up = r.recoveryRecord(); |
| + assert.equal(r.recoveryStep(up, 1000, look('connected', { builtAt: 0, errored: true })), ''); |
| + assert.equal(r.recoveryTrying(up), false); |
| +}); |
| + |
| +test('a closed connection is left alone', () => { |
| + const rec = r.recoveryRecord(); |
| + assert.deepEqual(run(rec, 0, 30, () => look('closed')), []); |
| +}); |
| + |
| +test('the polite side follows three seconds behind, and only when the leader does not act', () => { |
| + const alone = r.recoveryRecord(); |
| + const seen = run(alone, 0, 21, () => look('failed', { leader: false })); |
| + assert.deepEqual(seen, [[3, 'restart'], [5, 'restart'], [10, 'rebuild'], [20, 'restart']]); |
| + |
| + const follower = r.recoveryRecord(); |
| + let built = -100000; |
| + const none = run(follower, 0, 40, (t) => { |
| + const restart = t >= 17.1 ? 17100 : t >= 2.1 ? 2100 : t >= 0.1 ? 100 : 0; |
| + if (t >= 7.1) built = 7100; |
| + return look('failed', { leader: false, builtAt: built, remoteRestartAt: restart }); |
| + }); |
| + assert.deepEqual(none, []); |
| +}); |
| + |
| +test('a follower a beat behind the leader does not rebuild a second time', () => { |
| + const follower = r.recoveryRecord(); |
| + const seen = run(follower, 0, 12, (t) => look('failed', { |
| + leader: false, builtAt: t >= 6.1 ? 6100 : -100000, remoteRestartAt: t >= 1.1 ? 1100 : 0 })); |
| + assert.equal(seen.some((a) => a[1] === 'rebuild'), false, JSON.stringify(seen)); |
| +}); |
| + |
| +test('the version notice: old apps always, apps that do not say only when failing, browsers never', () => { |
| + assert.equal(r.clientNotice('Farshad', 'mac 0.4.1', false), 'Farshad is on an old version of Calls — ask them to update'); |
| + assert.equal(r.clientNotice('Farshad', 'iphone 0.3.9', true), 'Farshad is on an old version of Calls — ask them to update'); |
| + assert.equal(r.clientNotice('Farshad', 'mac 0.4.2', true), ''); |
| + assert.equal(r.clientNotice('Farshad', 'mac 0.4.12', true), ''); |
| + assert.equal(r.clientNotice('Farshad', 'native', false), ''); |
| + assert.equal(r.clientNotice('Farshad', 'native', true), 'Farshad may be on an old version of Calls — ask them to update'); |
| + assert.equal(r.clientNotice('Farshad', '', true), ''); |
| + assert.equal(r.clientNotice('Farshad', 'web 882eab8', true), ''); |
| + assert.equal(r.clientNotice('Farshad', 'mac latest', true), ''); |
| +}); |
| + |
| +test('versions compare numerically, part by part', () => { |
| + assert.equal(r.compareVersions('0.4.10', '0.4.2'), 1); |
| + assert.equal(r.compareVersions('0.4.1', '0.4.2'), -1); |
| + assert.equal(r.compareVersions('0.4', '0.4.0'), 0); |
| + assert.equal(r.compareVersions('0.10', '0.9.9'), 1); |
| +}); |
| + |
| +test('the minimum is the server\'s', () => { |
| + const go = readFileSync(fileURLToPath(new URL('../../protocol/client.go', import.meta.url)), 'utf8'); |
| + const m = src.match(/const MIN_NATIVE_VERSION = '([0-9.]+)';/); |
| + assert.ok(m); |
| + assert.ok(go.includes('const MinNativeVersion = "' + m[1] + '"'), 'MIN_NATIVE_VERSION and protocol.MinNativeVersion disagree'); |
| +}); |
| + |
| +test('the gate\'s block points a candidate at the discard port and leaves everything else', () => { |
| + assert.equal(r.blockCandidateLine('candidate:1 1 udp 2122260223 192.168.1.5 54321 typ host generation 0'), |
| + 'candidate:1 1 udp 2122260223 192.168.1.5 9 typ host generation 0'); |
| + assert.equal(r.blockCandidateLine('a=candidate:1 1 tcp 1518280447 ::1 9999 typ host tcptype passive'), |
| + 'a=candidate:1 1 tcp 1518280447 ::1 9 typ host tcptype passive'); |
| + assert.equal(r.blockCandidateLine('a=ice-ufrag:abcd'), 'a=ice-ufrag:abcd'); |
| + assert.equal(r.blockCandidateLine(''), ''); |
| +}); |