Merge branch 'fix/auto-ice-restart' into main
Merge branch 'fix/auto-ice-restart' into main: connections that stop working are mended without anyone asking, and old apps are named (spec 15.28) Reproduced the 2026-10-21 incident (TestNativeMacIceRecovery): on 0.4.10 a pair whose ICE never came up stayed down 2.5 min after the path returned. Apps and browser now restart ICE and then rebuild the pair on a 0/2/5/10/20/30 s schedule, impolite side leading; failure notice after a minute; X-Calls-Client and roster client; old-version tile notices; autoRestarts/autoRebuilds telemetry. iPhone 0.4.13.
34 files changed,
+2,403
−47
Makefile+5 −3callscore/client.go+50 −0callscore/client_test.go+60 −0callscore/transport.go+3 −0docs/superpowers/specs/2026-09-07-meet-design.md+123 −0internal/calls/hub/admission.go+2 −2internal/calls/hub/hub.go+21 −0internal/calls/static/room.js+337 −13internal/calls/stream.go+3 −0internal/callstest/browser_test.go+1 −0internal/callstest/client_test.go+63 −0internal/callstest/harness_test.go+4 −0internal/callstest/native_browser_test.go+17 −1internal/callstest/native_ice_test.go+247 −0internal/callstest/quality_test.go+13 −3internal/callstest/sse_test.go+5 −0native/apple/Sources/CallsInterop/Interop.swift+31 −0native/apple/Sources/CallsKit/Call.swift+149 −9native/apple/Sources/CallsKit/ConnectionRecovery.swift+217 −0native/apple/Sources/CallsKit/ICETestBlock.swift+41 −0native/apple/Sources/CallsKit/Media.swift+117 −14native/apple/Sources/CallsKit/QualityReport.swift+12 −0native/apple/Sources/CallsKit/Wire.swift+4 −0native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift+193 −0native/bridge/bridge.go+10 −1native/ios/project.yml+1 −1protocol/client.go+116 −0protocol/client_test.go+72 −0protocol/messages.go+7 −0protocol/quality.go+5 −0test/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
CI failed — run details
diff --git a/Makefile b/Makefile| index 3ebbc25..09e2561 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 |
| @@ -184,7 +185,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|MacPortraitVideo|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 30m -run 'TestNative(MacBarLayout|MacCallsBrowser|MacChat|MacScreenMotion|MacScreenRecovery|MacPortraitVideo|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 |
| @@ -199,13 +200,14 @@ native-webkit: native-mac |
| npx playwright install webkit chromium |
| CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CALLS_SYNTHETIC_SCREEN_HEIGHT=1246 CGO_ENABLED=0 go test -tags browser -count=1 -timeout 45m -run 'TestNativeMac(WebKit|ScreenReceivers)' -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.28'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/callscore/client.go b/callscore/client.go| new file mode 100644 |
| index 0000000..13ec43f |
| --- /dev/null |
| +++ b/callscore/client.go |
| @@ -0,0 +1,50 @@ |
| +package callscore |
| + |
| +import ( |
| + "sync" |
| + |
| + "amadan.net/oficina/calls/protocol" |
| +) |
| + |
| +// The app this core is running in, as spec §15.28 has every app say on |
| +// its requests (protocol.ClientHeader): "mac 0.4.12". Set once by the |
| +// host before it joins; nothing is sent until it has been, which is how |
| +// an app from before §15.28 looks to the server, and the server calls |
| +// that "native". |
| +var client struct { |
| + sync.Mutex |
| + label string |
| +} |
| + |
| +// SetClient records the host app and its version. An app that is not |
| +// one protocol.ParseClient knows, or a version that is not digits and |
| +// dots, is refused and leaves nothing set. |
| +func SetClient(app, version string) bool { |
| + label := app + " " + version |
| + if parsed, _, ok := protocol.ParseClient(label); !ok || parsed == protocol.ClientNative { |
| + return false |
| + } |
| + client.Lock() |
| + client.label = label |
| + client.Unlock() |
| + return true |
| +} |
| + |
| +// ClientLabel is what SetClient recorded, or "". |
| +func ClientLabel() string { |
| + client.Lock() |
| + defer client.Unlock() |
| + return client.label |
| +} |
| + |
| +// RefreshICE asks the core for a fresh /ice answer now rather than at the |
| +// schedule's time (spec §15.28: a connection about to be restarted on |
| +// relay credentials that are due for renewal renews them first). The |
| +// answer arrives as the usual "ice" event; nothing happens before |
| +// admission, as for any fetch. |
| +func (r *Room) RefreshICE() { |
| + select { |
| + case r.iceWake <- struct{}{}: |
| + default: |
| + } |
| +} |
diff --git a/callscore/client_test.go b/callscore/client_test.go| new file mode 100644 |
| index 0000000..fb47251 |
| --- /dev/null |
| +++ b/callscore/client_test.go |
| @@ -0,0 +1,60 @@ |
| +package callscore |
| + |
| +import ( |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| + |
| + "amadan.net/oficina/calls/protocol" |
| +) |
| + |
| +func TestSetClient(t *testing.T) { |
| + t.Cleanup(func() { client.label = "" }) |
| + for _, c := range []struct { |
| + app, version string |
| + ok bool |
| + }{ |
| + {"mac", "0.4.12", true}, |
| + {"iphone", "0.4.12", true}, |
| + {"ipad", "0.4.12", true}, |
| + {"native", "", false}, |
| + {"mac", "", false}, |
| + {"mac", "0.4.12 (26)", false}, |
| + {"web", "882eab8", false}, |
| + } { |
| + client.label = "" |
| + if got := SetClient(c.app, c.version); got != c.ok { |
| + t.Errorf("SetClient(%q, %q) = %v, want %v", c.app, c.version, got, c.ok) |
| + } |
| + if want := map[bool]string{true: c.app + " " + c.version}[c.ok]; ClientLabel() != want { |
| + t.Errorf("after SetClient(%q, %q): label %q, want %q", c.app, c.version, ClientLabel(), want) |
| + } |
| + } |
| +} |
| + |
| +// Every request the core makes says which app it is, once set; and says |
| +// nothing before, as an app from before §15.28 does. |
| +func TestRequestsCarryTheClient(t *testing.T) { |
| + t.Cleanup(func() { client.label = "" }) |
| + var got []string |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + got = append(got, r.Header.Get(protocol.ClientHeader)) |
| + w.WriteHeader(http.StatusNoContent) |
| + })) |
| + defer srv.Close() |
| + tr, err := newTransport(srv.URL, "abc123", srv.Client()) |
| + if err != nil { |
| + t.Skipf("transport refuses the test origin: %v", err) |
| + } |
| + client.label = "" |
| + if res, err := tr.request(t.Context(), http.MethodGet, "info", nil, nil); err == nil { |
| + res.Body.Close() |
| + } |
| + SetClient("mac", "0.4.12") |
| + if res, err := tr.request(t.Context(), http.MethodGet, "info", nil, nil); err == nil { |
| + res.Body.Close() |
| + } |
| + if len(got) != 2 || got[0] != "" || got[1] != "mac 0.4.12" { |
| + t.Fatalf("headers seen %q, want [\"\" \"mac 0.4.12\"]", got) |
| + } |
| +} |
diff --git a/callscore/transport.go b/callscore/transport.go| index e64b3d7..bf8a396 100644 |
| --- a/callscore/transport.go |
| +++ b/callscore/transport.go |
| @@ -123,6 +123,9 @@ func (t *transport) request(ctx context.Context, method, endpoint string, q url. |
| req.Header.Set("Content-Type", "application/json") |
| req.Header.Set("Origin", t.origin) |
| } |
| + if c := ClientLabel(); c != "" { |
| + req.Header.Set(protocol.ClientHeader, c) |
| + } |
| res, err := t.http.Do(req) |
| if err != nil { |
| return nil, errors.New("cannot reach Calls") |
diff --git a/docs/superpowers/specs/2026-09-07-meet-design.md b/docs/superpowers/specs/2026-09-07-meet-design.md| index 1ec1e1a..7b184b3 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.28 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 |
| @@ -2978,3 +2980,124 @@ that costs it once the browser and the server are new. |
| **Not done.** WebKit's slow start (its screen starts at 480×310 where |
| Chromium's starts at full size, the same before and after) is WebKit's |
| bandwidth estimate, and is left alone. |
| + |
| +### 15.28 §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 Paul's say only, at 14:41:26, `remotes=2` and `reconnecting=1` |
| +(`carlos logs` prints a line's top-level fields, not its `report` |
| +member, so the per-peer path and packets are not readable after the fact). |
| + |
| +**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/hub/admission.go b/internal/calls/hub/admission.go| index 0bc7871..4bb1024 100644 |
| --- a/internal/calls/hub/admission.go |
| +++ b/internal/calls/hub/admission.go |
| @@ -31,7 +31,7 @@ func (h *Hub) rosterFor(r *room, viewer *Participation) *Roster { |
| if !p.Admitted { |
| continue |
| } |
| - rp := RosterPeer{Peer: p.Peer, Name: p.Name, Kind: p.Kind.String(), Media: p.Media} |
| + rp := RosterPeer{Peer: p.Peer, Name: p.Name, Kind: p.Kind.String(), Media: p.Media, Client: p.Client} |
| if p.Peer != viewer.Peer { |
| rp.Gen = h.genLocked(r, viewer.Peer, p.Peer) |
| } |
| @@ -77,7 +77,7 @@ func (h *Hub) admitLocked(r *room, p *Participation) bool { |
| // generation with the newcomer; browsers read it from |
| // roster.peers[0]. |
| q.sub.send(Message{Type: TypePeer, Peer: p.Peer, Name: p.Name, |
| - Roster: &Roster{Peers: []RosterPeer{{Peer: p.Peer, Name: p.Name, Kind: p.Kind.String(), Gen: h.genLocked(r, q.Peer, p.Peer), Media: p.Media}}}}) |
| + Roster: &Roster{Peers: []RosterPeer{{Peer: p.Peer, Name: p.Name, Kind: p.Kind.String(), Gen: h.genLocked(r, q.Peer, p.Peer), Media: p.Media, Client: p.Client}}}}) |
| } |
| } |
| if wasWaiting { |
diff --git a/internal/calls/hub/hub.go b/internal/calls/hub/hub.go| index 5a6bd2e..ffd9892 100644 |
| --- a/internal/calls/hub/hub.go |
| +++ b/internal/calls/hub/hub.go |
| @@ -15,6 +15,8 @@ import ( |
| "log/slog" |
| "sync" |
| "time" |
| + |
| + "amadan.net/oficina/calls/protocol" |
| ) |
| const ( |
| @@ -102,6 +104,10 @@ type Participation struct { |
| // (§15.19), nil until it makes one. It lives and dies with the |
| // participation, so a resume keeps it and a fresh join starts unknown. |
| Media *MediaState |
| + // Client is what the participation was opened from (§15.28, |
| + // protocol.ClientFor): "mac 0.4.12", "native", or "" for a browser. |
| + // Set once, by the stream that opened it; carried in every roster. |
| + Client string |
| sub *Sub |
| resumeUntil time.Time // zero while a stream is attached |
| @@ -253,6 +259,21 @@ func (h *Hub) Open(sqid, session string, personID int64, name string, kind Kind) |
| return OpenResult{Peer: p.Peer, Sub: p.sub, ReportToken: p.reportToken}, nil |
| } |
| +// SetClient records what a participation this session has just opened |
| +// was opened from (§15.28). Only a well-formed value is kept, and only on |
| +// a participation not yet admitted, so the roster that admits it is the |
| +// first to carry it and no roster ever changes it. |
| +func (h *Hub) SetClient(sqid, session string, peer PeerID, client string) { |
| + if _, _, ok := protocol.ParseClient(client); !ok { |
| + return |
| + } |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + if p, ok := h.findLocked(sqid, session, peer); ok && !p.Admitted && p.Client == "" { |
| + p.Client = client |
| + } |
| +} |
| + |
| // Find answers a peer only through its own room and session. |
| func (h *Hub) Find(sqid, session string, peer PeerID) (*Participation, bool) { |
| h.mu.Lock() |
diff --git a/internal/calls/static/room.js b/internal/calls/static/room.js| index 66c2b9b..82a46ac 100644 |
| --- a/internal/calls/static/room.js |
| +++ b/internal/calls/static/room.js |
| @@ -346,6 +346,26 @@ |
| const RECONNECT_AUDIO_AFTER = 2000; |
| const RECONNECT_HOLD = 1000; |
| const RECONNECT_EVERY = 200; |
| + // §15.28 (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.28: 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 |
| @@ -424,6 +444,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.28: 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 = ''; |
| @@ -1513,9 +1544,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); |
| @@ -1591,6 +1622,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(); |
| @@ -1599,6 +1631,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(); |
| @@ -1881,6 +1915,14 @@ |
| pending: [], |
| descSeq: 0, |
| gen: g, |
| + // §15.28, 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, |
| @@ -1980,7 +2022,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.28), not this event's. |
| renderTiles(); |
| }); |
| @@ -2383,6 +2426,11 @@ |
| await entry.pc.setRemoteDescription(desc); |
| entry.ignoreOffer = false; |
| entry.descSeq = msg.seq || entry.descSeq; |
| + // §15.28: 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) — |
| @@ -2392,8 +2440,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.28) rather than throwing into the event handler. |
| + entry.errored = true; |
| } |
| } |
| @@ -2424,7 +2473,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; |
| } |
| } |
| @@ -3240,6 +3290,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 |
| @@ -4421,6 +4472,8 @@ |
| for (const rp of roster.peers || []) { |
| if (!rp || !rp.peer) continue; |
| if (rp.peer !== state.peer) { |
| + // §15.28: and what their participation was opened from. |
| + clients.set(rp.peer, rp.client || ''); |
| learnMedia(rp.peer, rp.media); |
| continue; |
| } |
| @@ -5051,7 +5104,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; |
| @@ -5066,6 +5120,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.28) |
| + // 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 |
| @@ -5087,6 +5158,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); |
| @@ -5097,6 +5170,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 }; |
| } |
| @@ -5420,6 +5494,214 @@ |
| rec.peers = shown; |
| } |
| + // --------------------------------------------------------------- |
| + // A connection that stops working is mended (§15.28, 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) |
| // --------------------------------------------------------------- |
| @@ -5599,6 +5881,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 |
| @@ -5611,7 +5894,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), |
| }); |
| @@ -6927,7 +7210,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 |
| @@ -6946,6 +7229,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.28'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; |
| @@ -7129,10 +7424,13 @@ |
| drawSelfNote(t); |
| return; |
| } |
| - const show = !!noteText; |
| + // A note is a sentence, with the Retry beside it, or {text, retry} for |
| + // one that has nothing to retry (§15.28'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; |
| } |
| // playSelf asks our own element to play. Never startPlaying: a |
| @@ -8329,6 +8627,17 @@ |
| qualityEveryForTest(ms) { |
| qualityEvery = Math.max(QUALITY_EVERY_MIN, Math.min(Number(ms) || QUALITY_EVERY, QUALITY_EVERY)); |
| }, |
| + // §15.28, 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.28, 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)); |
| }, |
| @@ -8361,6 +8670,21 @@ |
| shareRecovery, |
| // §15.22: what the ladder and the receiver's own mending have done. |
| shareRecoveries: Object.assign({ reattaches: screenReattaches }, shareCounts), |
| + // §15.28: 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/calls/stream.go b/internal/calls/stream.go| index 18b76b3..9f02474 100644 |
| --- a/internal/calls/stream.go |
| +++ b/internal/calls/stream.go |
| @@ -15,6 +15,7 @@ import ( |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "amadan.net/oficina/calls/internal/calls/hub" |
| + "amadan.net/oficina/calls/protocol" |
| ) |
| const ( |
| @@ -284,6 +285,8 @@ func (a *app) stream(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| sub, peer = res.Sub, res.Peer |
| + // §15.28: which app, at which version, for the people in the call. |
| + a.hub.SetClient(sqid, session, peer, protocol.ClientFor(r.Header.Get(protocol.ClientHeader), r.UserAgent())) |
| first = append(first, hub.Message{Type: hub.TypeHello, Peer: peer, Boot: a.hub.Boot(), Report: res.ReportToken}) |
| } |
diff --git a/internal/callstest/browser_test.go b/internal/callstest/browser_test.go| index 52a08d4..65293df 100644 |
| --- a/internal/callstest/browser_test.go |
| +++ b/internal/callstest/browser_test.go |
| @@ -105,6 +105,7 @@ var scenarios = []string{ |
| "icerenewal", |
| "icefail", |
| "icestuck", |
| + "icerecover", |
| "guest", |
| "speaker", |
| "chat", |
diff --git a/internal/callstest/client_test.go b/internal/callstest/client_test.go| new file mode 100644 |
| index 0000000..e0c2738 |
| --- /dev/null |
| +++ b/internal/callstest/client_test.go |
| @@ -0,0 +1,63 @@ |
| +package callstest |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// Spec §15.28: every roster names what each peer's participation was |
| +// opened from — an app's own "<app> <version>" header, "native" for an |
| +// app from before it (the Go HTTP client's agent and no header), nothing |
| +// for a browser — and the `peer` event that admits a newcomer carries it. |
| +func TestRosterNamesEachPeersClient(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + headers map[string]string |
| + want string // the roster's client for Bob; "" is no key at all |
| + }{ |
| + {"an app that says", map[string]string{"User-Agent": "Go-http-client/1.1", "X-Calls-Client": "mac 0.4.12"}, `"client":"mac 0.4.12"`}, |
| + {"an app from before", map[string]string{"User-Agent": "Go-http-client/1.1"}, `"client":"native"`}, |
| + {"a browser", nil, ""}, |
| + {"a header that is not one", map[string]string{"User-Agent": "Go-http-client/1.1", "X-Calls-Client": "mac <script>"}, ""}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + x, sqid, _ := memberWithMeeting(t) |
| + a := x.browser(t) |
| + a.signIn("paul@example.com") |
| + sa := a.stream("/m/" + sqid + "/stream") |
| + defer sa.close() |
| + pa, _ := sa.hello() |
| + a.signal(sqid, pa, `{"type":"join"}`) |
| + sa.nextOf("roster", 2*time.Second) |
| + |
| + b := newMemberBrowser(t, x, "paul@rslw.com") |
| + b.streamHeaders = c.headers |
| + sb := b.stream("/m/" + sqid + "/stream") |
| + defer sb.close() |
| + pb, _ := sb.hello() |
| + b.signal(sqid, pb, `{"type":"join"}`) |
| + _, roster, ok := sb.nextOf("roster", 2*time.Second) |
| + if !ok { |
| + t.Fatal("Bob got no roster") |
| + } |
| + _, peer, ok := sa.nextOf("peer", 2*time.Second) |
| + if !ok { |
| + t.Fatal("Paul was not told Bob arrived") |
| + } |
| + // Paul's stream is a browser's: no client key for him, ever. |
| + if c.want == "" { |
| + if strings.Contains(string(roster), `"client"`) || strings.Contains(string(peer), `"client"`) { |
| + t.Fatalf("no client expected: roster %s, peer %s", roster, peer) |
| + } |
| + return |
| + } |
| + if strings.Count(string(roster), `"client"`) != 1 || !strings.Contains(string(roster), c.want) { |
| + t.Fatalf("Bob's own roster entry should carry %s, and only it: %s", c.want, roster) |
| + } |
| + if !strings.Contains(string(peer), c.want) { |
| + t.Fatalf("the peer event Paul gets should carry %s: %s", c.want, peer) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/callstest/harness_test.go b/internal/callstest/harness_test.go| index 1039fbd..a3753fa 100644 |
| --- a/internal/callstest/harness_test.go |
| +++ b/internal/callstest/harness_test.go |
| @@ -313,6 +313,10 @@ type client struct { |
| t *testing.T |
| x *harness |
| cookies map[string]*http.Cookie |
| + // streamHeaders, when set, go on the client's stream GETs in place of |
| + // the browser's user agent the stream otherwise sends (§15.28 reads |
| + // the app's header and the Go HTTP client's agent there). |
| + streamHeaders map[string]string |
| } |
| func (x *harness) browser(t *testing.T) *client { |
diff --git a/internal/callstest/native_browser_test.go b/internal/callstest/native_browser_test.go| index 2c8ed00..967c520 100644 |
| --- a/internal/callstest/native_browser_test.go |
| +++ b/internal/callstest/native_browser_test.go |
| @@ -266,7 +266,13 @@ type nativeSample struct { |
| ScreenCaptions []string `json:"screenCaptions"` |
| SharingScreen *bool `json:"sharingScreen"` |
| ScreenRecovery string `json:"screenRecovery"` |
| - Diagnostics string `json:"diagnostics"` |
| + Status string `json:"status"` |
| + Reconnecting bool `json:"reconnecting"` |
| + // Tile notices by peer, and the peers' client strings as the roster |
| + // has them (the auto-ice-restart release on; absent before). |
| + Notices map[string][]string `json:"notices"` |
| + Clients map[string]string `json:"clients"` |
| + Diagnostics string `json:"diagnostics"` |
| } |
| // nativeApp is one CallsInterop process and the last observation it |
| @@ -282,10 +288,20 @@ type nativeApp struct { |
| } |
| func startNative(ctx context.Context, t *testing.T, binary string, rig *browserRig, room, cookie, label string) *nativeApp { |
| + t.Helper() |
| + return startNativeEnv(ctx, t, binary, rig, room, cookie, label, nil) |
| +} |
| + |
| +// startNativeEnv is startNative with extra environment for this one app |
| +// (KEY=value), on top of the test's own. |
| +func startNativeEnv(ctx context.Context, t *testing.T, binary string, rig *browserRig, room, cookie, label string, env []string) *nativeApp { |
| t.Helper() |
| cookies, _ := json.Marshal([]map[string]string{{"name": rig.cookieName, "value": cookie}}) |
| input, _ := json.Marshal(map[string]string{"origin": rig.origin, "room": room, "cookies": string(cookies)}) |
| cmd := exec.CommandContext(ctx, binary) |
| + if len(env) > 0 { |
| + cmd.Env = append(os.Environ(), env...) |
| + } |
| stdin, err := cmd.StdinPipe() |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/callstest/native_ice_test.go b/internal/callstest/native_ice_test.go| new file mode 100644 |
| index 0000000..9d3e6cf |
| --- /dev/null |
| +++ b/internal/callstest/native_ice_test.go |
| @@ -0,0 +1,247 @@ |
| +//go:build browser && darwin |
| + |
| +package callstest |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// TestNativeMacIceRecovery is the incident of 2026-10-21, about 14:41 UTC: |
| +// Paul on the Mac app, sharing his screen; Farshad, in the call from a |
| +// browser, left it and came back from the Mac app; the connection between |
| +// Paul's app and Farshad's never came up. Paul saw a frozen picture, |
| +// "Reconnecting to Farshad (Mac)…" and "A participant's media could not |
| +// connect", and it never recovered on its own. Farshad leaving and joining |
| +// again mended it. |
| +// |
| +// Here: app A shares; app B (the stand-in for Farshad's first client) |
| +// joins and leaves; app C, the same person, joins with its ICE blocked |
| +// (ICETestBlock: every candidate either way leads nowhere) for |
| +// ICE_BLOCK_SECONDS. The block lifts by itself, and nothing that was |
| +// exchanged while it lasted is any use afterwards — only fresh candidates |
| +// (an ICE restart) or a fresh connection get the pair talking. Up to |
| +// 0.4.10 nothing ever made either, and the pair stayed down until someone |
| +// left. The test then asks that A decodes C's camera and screen again with |
| +// nobody doing anything. |
| +// |
| +// Variants (ICE_RECOVERY_CASE): |
| +// - "both" (default): C is the same build as A. |
| +// - "old-peer": C does nothing to recover (CALLS_AUTO_RECOVERY=0) and |
| +// sends no client version (CALLS_TEST_NO_CLIENT=1), as an app from |
| +// before this release; A has to mend the pair on its own. |
| +// - ICE_RECOVERY_PEER=<path to an older CallsInterop>: C is that |
| +// binary, which has no block of its own, so the block is A's (every |
| +// candidate A sends or receives) — the old app really is old. |
| +// |
| +// The firewall flake TestNativeMacScreenShare describes (two unsigned |
| +// apps on one Mac connecting only some of the time) is handled the way |
| +// TestNativeMacScreenPairRecovery handles it: A and B get three tries to |
| +// connect before anything else happens. |
| +func TestNativeMacIceRecovery(t *testing.T) { |
| + root, err := filepath.Abs("../..") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + current := filepath.Join(root, "native/apple/.build/debug/CallsInterop") |
| + peerBin := current |
| + if v := os.Getenv("ICE_RECOVERY_PEER"); v != "" { |
| + peerBin = v |
| + } |
| + for _, b := range []string{current, peerBin} { |
| + if _, err := os.Stat(b); err != nil { |
| + t.Fatalf("no interop executable at %s: build with make native-mac first", b) |
| + } |
| + } |
| + block := 25 * time.Second |
| + if v, err := time.ParseDuration(os.Getenv("ICE_BLOCK_SECONDS") + "s"); err == nil && v > 0 { |
| + block = v |
| + } |
| + mode := envOr("ICE_RECOVERY_CASE", "both") |
| + oldBinary := peerBin != current |
| + |
| + rig := newBrowserRig(t) |
| + room, _ := rig.createMeeting(t) |
| + ctx, cancel := context.WithTimeout(t.Context(), block+6*time.Minute) |
| + defer cancel() |
| + |
| + var a, b *nativeApp |
| + for attempt := 1; ; attempt++ { |
| + a = startNative(ctx, t, current, rig, room, rig.cookieA, "a") |
| + waitNative(t, "the sharing app is in", func() bool { return a.sample().Phase == "admitted" }, a) |
| + b = startNative(ctx, t, current, rig, room, rig.cookieB, "b") |
| + if pollNative(35*time.Second, func() bool { return a.stat("framesDecoded") > 15 && b.stat("framesDecoded") > 15 }) { |
| + break |
| + } |
| + a.leave(t) |
| + b.leave(t) |
| + if attempt == 3 { |
| + t.Fatal("the two apps never connected") |
| + } |
| + t.Logf("RETRY the two apps did not connect (attempt %d)", attempt) |
| + } |
| + defer a.leave(t) |
| + a.command(t, "screen-on") |
| + waitNative(t, "the first client sees the screen", func() bool { |
| + return b.stat("remoteScreens") == 1 && b.stat("screenFramesDecoded") > 15 |
| + }, a, b) |
| + t.Log("A is sharing, and B sees it") |
| + |
| + // Farshad leaves, and comes back from the app. |
| + b.leave(t) |
| + waitNative(t, "A sees B go", func() bool { return a.stat("rosterPeers") == 1 }, a) |
| + |
| + var env []string |
| + switch { |
| + case oldBinary: |
| + // The old app has no block of its own; A's blocks both ways. |
| + a.command(t, "ice-block "+strconv.FormatInt(block.Milliseconds(), 10)) |
| + case mode == "old-peer": |
| + env = []string{"CALLS_TEST_ICE_BLOCK_MS=" + strconv.FormatInt(block.Milliseconds(), 10), "CALLS_AUTO_RECOVERY=0", "CALLS_TEST_NO_CLIENT=1"} |
| + default: |
| + env = []string{"CALLS_TEST_ICE_BLOCK_MS=" + strconv.FormatInt(block.Milliseconds(), 10)} |
| + } |
| + blockedAt := time.Now() |
| + c := startNativeEnv(ctx, t, peerBin, rig, room, rig.cookieB, "c", env) |
| + defer c.leave(t) |
| + waitNative(t, "C is in the call", func() bool { return c.sample().Phase == "admitted" && a.stat("rosterPeers") == 2 }, a, c) |
| + |
| + // The connection does not come up while the block lasts. For its |
| + // first fifty seconds nothing worse than "Reconnecting to …" is said; |
| + // past a minute (spec §15.28) the failure notice is, and for an app |
| + // that does not say its version, that it may be old. |
| + const failure = "A participant’s media could not connect." |
| + oldPeer := oldBinary || mode == "old-peer" |
| + sawFailed, sawReconnecting, sawNotice, sawMaybeOld := false, false, false, false |
| + for time.Since(blockedAt) < block { |
| + s := a.sample() |
| + if s.Stats["iceFailedPeers"] > 0 { |
| + sawFailed = true |
| + } |
| + if s.Stats["iceConnectedPeers"] > 0 && s.Stats["framesDecoded"] > 0 { |
| + t.Fatalf("A connected to C through the block: %+v", s) |
| + } |
| + 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") |
| + } |
| + } |
| + if s.Status == failure { |
| + if time.Since(blockedAt) < 50*time.Second { |
| + t.Fatalf("the failure notice came %s in, before its minute", time.Since(blockedAt).Round(time.Second)) |
| + } |
| + sawNotice = true |
| + } |
| + time.Sleep(250 * time.Millisecond) |
| + } |
| + if !sawReconnecting { |
| + 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 { |
| + t.Fatalf("a connection failing for %s never said %q", block, failure) |
| + } |
| + if oldPeer != sawMaybeOld { |
| + t.Fatalf("old peer %v, but the tile's \"may be on an old version\" was %v", oldPeer, sawMaybeOld) |
| + } |
| + } |
| + t.Logf("block over after %s: A has seen ICE failed: %v; A says %q, notices %v", time.Since(blockedAt).Round(time.Second), |
| + sawFailed, a.sample().Status, a.sample().Notices) |
| + |
| + // Nobody does anything. A must decode C's camera and screen again. |
| + frames := a.stat("framesDecoded") |
| + limit := 90 * time.Second |
| + if v, err := time.ParseDuration(os.Getenv("ICE_RECOVERY_WITHIN")); err == nil { |
| + limit = v |
| + } |
| + until := time.Now().Add(limit) |
| + recovered := false |
| + for time.Now().Before(until) { |
| + if a.stat("framesDecoded") > frames+15 && c.stat("screenFramesDecoded") > 15 { |
| + recovered = true |
| + break |
| + } |
| + time.Sleep(500 * time.Millisecond) |
| + } |
| + sa, sc := a.sample(), c.sample() |
| + t.Logf("A: status %q, notices %v, clients %v, iceConnected %d, iceFailed %d, autoRestarts %d, autoRebuilds %d, iceRestarts %d", |
| + sa.Status, sa.Notices, sa.Clients, sa.Stats["iceConnectedPeers"], sa.Stats["iceFailedPeers"], |
| + sa.Stats["autoRestarts"], sa.Stats["autoRebuilds"], sa.Stats["iceRestarts"]) |
| + t.Logf("C: status %q, iceConnected %d, iceFailed %d, autoRestarts %d, autoRebuilds %d, mangled %d", |
| + sc.Status, sc.Stats["iceConnectedPeers"], sc.Stats["iceFailedPeers"], sc.Stats["autoRestarts"], |
| + sc.Stats["autoRebuilds"], sc.Stats["iceBlockMangled"]) |
| + if !recovered { |
| + t.Fatalf("STUCK: %s after the block lifted, A still decodes nothing from C (A %+v)", limit, sa) |
| + } |
| + t.Logf("PASS recovered %s after the block lifted, with nobody acting", time.Since(blockedAt.Add(block)).Round(time.Second)) |
| + // The words go with the trouble (a second's hold, and a sample's lag). |
| + if !pollNative(5*time.Second, func() bool { |
| + s := a.sample() |
| + for _, notes := range s.Notices { |
| + if len(notes) > 0 { |
| + return false |
| + } |
| + } |
| + return s.Status != failure |
| + }) { |
| + 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 8fe8e43..268f3a0 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)}, |
| }}, |
| } |
| } |
| @@ -243,6 +243,10 @@ func TestQualityReportsShareACallTagAndNameNothing(t *testing.T) { |
| t.Errorf("a quiet screen still put %q on the line", k) |
| } |
| } |
| + // §15.28: 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) |
| } |
| @@ -284,7 +288,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) { |
| @@ -363,7 +372,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/internal/callstest/sse_test.go b/internal/callstest/sse_test.go| index 2c7f84e..511fd04 100644 |
| --- a/internal/callstest/sse_test.go |
| +++ b/internal/callstest/sse_test.go |
| @@ -50,6 +50,11 @@ func (c *client) stream(target string) *sseReader { |
| req.AddCookie(ck) |
| } |
| req.Header.Set("Accept", "text/event-stream") |
| + // A browser's EventSource, unless the test says it is an app. |
| + req.Header.Set("User-Agent", "Mozilla/5.0 (callstest)") |
| + for k, v := range c.streamHeaders { |
| + req.Header.Set(k, v) |
| + } |
| resp, err := srv.Client().Do(req) |
| if err != nil { |
| cancel() |
diff --git a/native/apple/Sources/CallsInterop/Interop.swift b/native/apple/Sources/CallsInterop/Interop.swift| index 9a3efcb..9dbdbc3 100644 |
| --- a/native/apple/Sources/CallsInterop/Interop.swift |
| +++ b/native/apple/Sources/CallsInterop/Interop.swift |
| @@ -128,6 +128,17 @@ struct Input: Decodable { |
| } |
| // 0.4.1's motion sizing, without the H.264 level cap, for measuring it. |
| if ProcessInfo.processInfo.environment["CALLS_SCREEN_UNCAPPED"] == "1" { ScreenSendPolicy.levelCapped = false } |
| + // The gate's ICE block (ICETestBlock) from the start, before any |
| + // connection exists: a peer joining whose connections cannot come up. |
| + if let ms = ProcessInfo.processInfo.environment["CALLS_TEST_ICE_BLOCK_MS"].flatMap(Double.init), ms > 0 { |
| + call.blockICEForTest(ms: ms) |
| + } |
| + // §15.28: the stand-in for an app from before it, which neither mends |
| + // its connections nor says which app it is; and the version this |
| + // bundle-less executable says it is otherwise. |
| + if ProcessInfo.processInfo.environment["CALLS_AUTO_RECOVERY"] == "0" { Call.autoRecovery = false } |
| + if ProcessInfo.processInfo.environment["CALLS_TEST_NO_CLIENT"] == "1" { Call.sendsClientInfo = false } |
| + Call.clientVersion = ProcessInfo.processInfo.environment["CALLS_TEST_CLIENT_VERSION"] ?? "9.9.9" |
| let preview = input.chatSnapshot.map { ChatPreview(call: call, path: $0) } |
| do { |
| try await call.join( |
| @@ -315,6 +326,13 @@ struct Input: Decodable { |
| fflush(stdout) |
| } |
| } |
| + // Every candidate either way leads nowhere for this long. |
| + if command.hasPrefix("ice-block ") { |
| + let ms = Double(command.dropFirst("ice-block ".count)) ?? 0 |
| + await call.blockICEForTest(ms: ms) |
| + print("{\"iceBlocked\":true}") |
| + fflush(stdout) |
| + } |
| if command == "screen-reshare-test" { |
| await call.reshareScreenForTest() |
| print("{\"reshared\":true}") |
| @@ -359,6 +377,19 @@ struct Input: Decodable { |
| "screenRecovery": call.screenRecovery, |
| // §15.23: "Reconnecting…" said for the call, and on how many tiles. |
| "reconnecting": call.reconnecting, |
| + // The call's status line, word for word ("A participant's media |
| + // could not connect." among them). |
| + "status": call.status, |
| + // Each remote peer's client as the roster has it (§15.28). |
| + "clients": Dictionary( |
| + uniqueKeysWithValues: (call.state?.peers ?? []).filter { $0.peer != call.state?.peer }.map { |
| + ($0.peer, $0.client ?? "") |
| + }), |
| + // What each remote tile says above the name, word for word. |
| + "notices": Dictionary( |
| + uniqueKeysWithValues: (call.state?.peers ?? []).filter { $0.peer != call.state?.peer }.map { |
| + ($0.peer, call.levels.peer($0.peer).notices) |
| + }), |
| "reconnectingPeers": call.reconnectingPeers.count, |
| "syntheticScreenFrames": Interop.screen?.produced ?? 0, |
| "cameraOpens": Interop.camera.opens, |
diff --git a/native/apple/Sources/CallsKit/Call.swift b/native/apple/Sources/CallsKit/Call.swift| index cc0fd0c..beffa0a 100644 |
| --- a/native/apple/Sources/CallsKit/Call.swift |
| +++ b/native/apple/Sources/CallsKit/Call.swift |
| @@ -93,6 +93,24 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| private var reconnectWatch = ReconnectWatch() |
| @Published public private(set) var reconnecting = false |
| @Published public private(set) var reconnectingPeers: Set<String> = [] |
| + /// A connection that stops working is mended without anyone asking (spec |
| + /// §15.28): each remote peer's recovery, the restarts waiting on a fresh |
| + /// `/ice` answer, and the peers whose connection has been failing for a |
| + /// minute, which is when "A participant's media could not connect." is |
| + /// said (and their tile may say their app is old). |
| + private var recovery: [String: ConnectionRecovery] = [:] |
| + private var restartsAwaitingICE: Set<String> = [] |
| + @Published public private(set) var failingPeers: Set<String> = [] |
| + private var autoRestartsTotal: UInt64 = 0 |
| + private var autoRebuildsTotal: UInt64 = 0 |
| + /// Off only for the gate's stand-in for an app from before §15.28. |
| + @_spi(Fixtures) public static var autoRecovery = true |
| + /// Whether this app says which it is (§15.28); off only for the same |
| + /// stand-in. `clientVersion` stands in for a bundle that has none (the |
| + /// interop executable). |
| + @_spi(Fixtures) public static var sendsClientInfo = true |
| + @_spi(Fixtures) public static var clientVersion: String? |
| + static let failureWords = "A participant’s media could not connect." |
| /// "<name> is connecting and can't hear you yet" (spec §15.24): the |
| /// watch, and the people it is said for now — on their tiles, and as a |
| /// dot in the mini window when they are not the one it shows. |
| @@ -200,6 +218,9 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| /// peer sampling, five times a second; the microphone warning waits on |
| /// it (MicSample.sending). |
| private var sendingAudio = false |
| + /// Connections up, and connections in ICE `failed`, at the last look. |
| + private var iceConnectedPeers = 0 |
| + private var iceFailedPeers = 0 |
| /// The loudest remote sound since the gate last asked (sampleStats). |
| private var remotePeakSinceSample: Float = 0 |
| private var micPeakSinceSample: Float = 0 |
| @@ -274,7 +295,8 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| guard let state else { return [] } |
| var lines: [String] = [] |
| for person in state.peers where person.peer != state.peer { |
| - var facts = ["connection \(person.gen ?? 0)"] |
| + var facts = ["connection \(person.gen ?? 0)", "app \(person.client ?? "browser or unknown")"] |
| + if let r = recovery[person.peer], r.trying { facts.append("recovering, \(r.attempts) attempts") } |
| if let media = person.media { |
| facts.append(media.muted ? "muted" : "unmuted") |
| facts.append(media.cameraOff ? "camera off" : "camera on") |
| @@ -361,6 +383,11 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| if let old { await Task.detached { old.leave() }.value } |
| guard epoch == joiningEpoch else { throw CancellationError() } |
| let listener = Events(call: self, epoch: epoch) |
| + // §15.28: which app this is, on every request the core makes. |
| + if Self.sendsClientInfo { |
| + let info = QualityClientInfo.current() |
| + if let version = info.version ?? Self.clientVersion { _ = BridgeSetClientInfo(info.app, version) } |
| + } |
| var error: NSError? |
| guard let client = BridgeNewClient(origin, room, cookies, listener, &error) else { |
| throw error ?? NSError(domain: "Calls", code: 1) |
| @@ -427,6 +454,9 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| endLevelWatch() |
| qualityWatch?.cancel() |
| qualityWatch = nil |
| + recovery = [:] |
| + restartsAwaitingICE = [] |
| + failingPeers = [] |
| currentCamera = nil |
| cameraStatus = nil |
| cameraNote = "" |
| @@ -708,6 +738,8 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| let readings = await media.peerAudio(stats: stats, detail: detail, acks: acks) |
| guard levelWatch != nil, let state else { return } |
| sendingAudio = readings.values.contains { $0.connected } |
| + iceConnectedPeers = readings.values.filter(\.connected).count |
| + iceFailedPeers = readings.values.filter(\.failed).count |
| let me = state.peer |
| var present = Set<String>() |
| var people: [String: ReconnectWatch.Peer] = [:] |
| @@ -734,6 +766,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| epoch: epoch, hearsMe: HearingRule.hearsYou(person.media, me: me), reported: person.media != nil, |
| connected: reading.connected, acked: ackedBy[person.peer] == epoch) |
| } |
| + let trying = watchRecovery(now: now, state: state) |
| for id in Array(heardFrom.keys) where !present.contains(id) { heardFrom.removeValue(forKey: id) } |
| for id in Array(ackedBy.keys) where !present.contains(id) { ackedBy.removeValue(forKey: id) } |
| for id in connectingWatch.observe(at: now, people: arrivals) { |
| @@ -750,19 +783,26 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| nowJoining.contains(person.peer) |
| ? ReconnectWatch.Peer() |
| : ReconnectWatch.Peer( |
| - connectionBad: reading.connectionBad, |
| + connectionBad: reading.connectionBad || trying.contains(person.peer), |
| audioMissing: audioArriving[person.peer] == false && person.media?.muted != true) |
| let said = ConnectingWatch.tile( |
| name: person.name, media: person.media, me: me, muted: muted, |
| joining: nowJoining.contains(person.peer), shown: connectingPeers.contains(person.peer), |
| reconnecting: reconnectingPeers.contains(person.peer)) |
| remotePeakSinceSample = max(remotePeakSinceSample, reading.peak) |
| + // §15.28: and what their app is, when that is worth saying. |
| + var notices = said.notices |
| + if let old = ClientVersion.notice( |
| + name: person.name, client: person.client, failing: failingPeers.contains(person.peer)) |
| + { |
| + notices.append(old) |
| + } |
| levels.updatePeer( |
| person.peer, name: person.name, |
| sample: PeerAudioSample( |
| reported: person.media, connected: reading.connected, |
| arriving: audioArriving[person.peer] ?? false, level: reading.peak), |
| - notices: said.notices, connecting: said.connecting, |
| + notices: notices, connecting: said.connecting, |
| now: now) |
| } |
| watchReconnect(now: now, people: people) |
| @@ -798,12 +838,87 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| reconnecting = reconnectWatch.call |
| CallLog.info(reconnecting ? "reconnecting: shown (a problem that lasted)" : "reconnecting: cleared") |
| switch state?.phase { |
| - case "reconnecting": status = reconnecting ? ReconnectWords.call : "In the meeting" |
| - case "admitted": status = reconnecting ? ReconnectWords.call : "In the meeting" |
| + case "reconnecting", "admitted": status = admittedStatus |
| default: break |
| } |
| } |
| + /// What the status line says while admitted: "Reconnecting…" for the |
| + /// whole call (§15.23), the failure notice once a connection has been |
| + /// failing for a minute (§15.28), or that all is well. |
| + private var admittedStatus: String { |
| + if reconnecting { return ReconnectWords.call } |
| + if !failingPeers.isEmpty { return Self.failureWords } |
| + return "In the meeting" |
| + } |
| + |
| + /// One look by every connection's recovery (spec §15.28), and whatever it |
| + /// asks for. Returns the peers it is trying to mend now, whose tiles say |
| + /// "Reconnecting to …". |
| + private func watchRecovery(now: Double, state: RoomState) -> Set<String> { |
| + guard Self.autoRecovery else { return [] } |
| + let looks = media.recoveryLooks() |
| + for id in Array(recovery.keys) where looks[id] == nil { |
| + recovery.removeValue(forKey: id) |
| + restartsAwaitingICE.remove(id) |
| + } |
| + let signalling = state.phase == "admitted" |
| + var trying: Set<String> = [] |
| + var failing: Set<String> = [] |
| + for (id, var look) in looks where id != state.peer { |
| + look.signalling = signalling |
| + var r = recovery[id] ?? ConnectionRecovery() |
| + let was = r.trying |
| + let action = r.observe(at: now, look) |
| + if r.trying != was { |
| + CallLog.info(r.trying ? "recovery: \(id.prefix(6)) in trouble (ICE \(look.ice))" : "recovery: \(id.prefix(6)) recovered") |
| + } |
| + recovery[id] = r |
| + if r.trying { trying.insert(id) } |
| + if r.failing(at: now) { failing.insert(id) } |
| + switch action { |
| + case .restart?: recoveryRestart(id, attempt: r.attempts) |
| + case .rebuild?: recoveryRebuild(id, attempt: r.attempts) |
| + case nil: break |
| + } |
| + } |
| + if failingPeers != failing { |
| + for id in failing.subtracting(failingPeers) { CallLog.info("recovery: \(id.prefix(6)) still failing after a minute: said") } |
| + failingPeers = failing |
| + if state.phase == "admitted" || state.phase == "reconnecting" { status = admittedStatus } |
| + } |
| + return trying |
| + } |
| + |
| + /// §15.28's restart, after fresh relay credentials when the ones in hand |
| + /// are due for renewal (§5.3): a restart onto a credential the relay is |
| + /// about to stop honouring would only fail again. |
| + private func recoveryRestart(_ peer: String, attempt: Int) { |
| + autoRestartsTotal += 1 |
| + qualityTally.count(.autoRestart, for: peer) |
| + if let ice, !ice.iceServers.isEmpty, ice.renewAt > 0, Int64(Date().timeIntervalSince1970) >= ice.renewAt, |
| + let client = bridge |
| + { |
| + CallLog.info("recovery: attempt \(attempt), ICE restart for \(peer.prefix(6)) after fresh relay credentials") |
| + restartsAwaitingICE.insert(peer) |
| + DispatchQueue.global().async { client.refreshICE() } |
| + return |
| + } |
| + CallLog.info("recovery: attempt \(attempt), ICE restart for \(peer.prefix(6))") |
| + media.restartICE(peer) |
| + } |
| + |
| + /// §15.28's rebuild: the hub's pair reset (§4.6), which gives both sides |
| + /// a new generation and so a new connection, exactly as a leave and a |
| + /// join did — for this one person, and keeping the call. |
| + private func recoveryRebuild(_ peer: String, attempt: Int) { |
| + autoRebuildsTotal += 1 |
| + qualityTally.count(.autoRebuild, for: peer) |
| + CallLog.info("recovery: attempt \(attempt), rebuilding the connection to \(peer.prefix(6))") |
| + guard let client = bridge else { return } |
| + DispatchQueue.global().async { try? client.send("reset", to: peer, generation: 0, payload: "") } |
| + } |
| + |
| /// §15.20's receiving half: who is reaching this app as silence. The |
| /// core keeps only roster peers and reports on a change; this sends only |
| /// on a change too, in order, off the main thread. |
| @@ -881,7 +996,7 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| KnockNotice.announce( |
| knocks.arrivals(waiting: state.waiting, visible: KnockNotice.appIsFrontmost)) |
| switch state.phase { |
| - case "admitted": status = reconnecting ? ReconnectWords.call : "In the meeting" |
| + case "admitted": status = admittedStatus |
| case "waiting": status = "Waiting to be let in" |
| case "full": status = "The meeting is full. Try joining again shortly." |
| // Said only once it has lasted (ReconnectWatch, spec §15.23): a |
| @@ -922,11 +1037,21 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| ice = config |
| floor = config.iceServers.isEmpty |
| if let state { media.reconcile(state: state, ice: config) } |
| - if renewing { media.updateICE(config) } |
| + if renewing { |
| + // §15.28: recovery restarts that waited for this answer go now, on |
| + // whichever connections the renewal itself did not restart. |
| + let restarted = media.updateICE(config) |
| + for peer in restartsAwaitingICE.subtracting(restarted) { media.restartICE(peer) } |
| + restartsAwaitingICE = [] |
| + } |
| let pending = pendingMedia |
| pendingMedia = [] |
| for message in pending { media.receive(message) } |
| - case "ice-unavailable": status = "Could not refresh the call connection. Retrying…" |
| + case "ice-unavailable": |
| + status = "Could not refresh the call connection. Retrying…" |
| + // The restarts that waited for it go on what is in hand. |
| + for peer in restartsAwaitingICE { media.restartICE(peer) } |
| + restartsAwaitingICE = [] |
| case "message": |
| guard let message = event.message else { return } |
| if message.type == "chat", let text = message.payload?.text { |
| @@ -1211,7 +1336,6 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| screens.removeAll { $0 == peer } |
| remoteScreens.removeValue(forKey: peer) |
| } |
| - func mediaFailed() { status = "A participant’s media could not connect." } |
| /// Caps the call's uplink estimate at `bps` (nil lifts it): the gate's |
| /// stand-in for a thin connection, which it has no other way to get. |
| public func limitUplink(_ bps: Int?) { media.limitUplink(bps) } |
| @@ -1221,6 +1345,11 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| @_spi(Fixtures) public func freezeScreenWatchForTest(seconds: Double) { |
| screenWatchFrozenUntil = ProcessInfo.processInfo.systemUptime + seconds |
| } |
| + /// For the gate: every ICE candidate this app sends or receives leads |
| + /// nowhere for `ms` (ICETestBlock), so its connections fail. |
| + @_spi(Fixtures) public func blockICEForTest(ms: Double) { |
| + ICETestBlock.until = ProcessInfo.processInfo.systemUptime + max(0, ms) / 1000 |
| + } |
| /// For the gate's encoder stall (see MediaEngine). |
| @_spi(Fixtures) public func stallScreenEncoderForTest() { media.stallScreenEncoderForTest() } |
| /// For the gate: the watchdog's share again (spec §15.22), on demand. |
| @@ -1277,6 +1406,17 @@ private final class Events: NSObject, BridgeListenerProtocol { |
| values["screenWatchdogFailures"] = UInt64(screenWatchdog.failures) |
| values["screenReattaches"] = UInt64(screenReattaches) |
| values["iceRestarts"] = media.iceRestarts |
| + // Connections up, and connections ICE has given up on, at the last |
| + // look; and the gate's own ICE block (ICETestBlock). |
| + values["iceConnectedPeers"] = UInt64(iceConnectedPeers) |
| + values["iceFailedPeers"] = UInt64(iceFailedPeers) |
| + values["iceBlockMangled"] = ICETestBlock.mangled |
| + // §15.28: the recovery's restarts and rebuilds so far, and the people |
| + // it is trying to mend now, and has been for a minute. |
| + values["autoRestarts"] = autoRestartsTotal |
| + values["autoRebuilds"] = autoRebuildsTotal |
| + values["recoveryTrying"] = UInt64(recovery.values.filter(\.trying).count) |
| + values["recoveryFailing"] = UInt64(failingPeers.count) |
| values["screenKeyframes"] = screenReport?.keyFramesEncoded ?? 0 |
| if let capture = media.screenCaptureCounts { |
| values["screenCaptureHeartbeats"] = capture.heartbeats ?? 0 |
diff --git a/native/apple/Sources/CallsKit/ConnectionRecovery.swift b/native/apple/Sources/CallsKit/ConnectionRecovery.swift| new file mode 100644 |
| index 0000000..483874a |
| --- /dev/null |
| +++ b/native/apple/Sources/CallsKit/ConnectionRecovery.swift |
| @@ -0,0 +1,217 @@ |
| +import Foundation |
| + |
| +/// A connection that stops working is mended without anyone asking (spec |
| +/// §15.28, 2026-10-21). |
| +/// |
| +/// Paul, on the Mac app and sharing his screen, saw "Reconnecting to Farshad |
| +/// (Mac)…" and "A participant's media could not connect" when Farshad moved |
| +/// from the browser to the Mac app, and it never came back until Farshad left |
| +/// and joined again. Up to 0.4.10 nothing in the apps ever restarted ICE on |
| +/// a connection that failed: the only restarts were §5.3's renewals, and the |
| +/// only rebuild a `pair` someone else asked for. The gate's reproduction |
| +/// (TestNativeMacIceRecovery) showed the pair staying down for as long as it |
| +/// watched, with libwebrtc never even calling it `failed`. |
| +/// |
| +/// Per remote peer, across that pair's connections (a rebuild is a new |
| +/// connection, and the same episode): |
| +/// |
| +/// - **In trouble**: ICE `failed`; `disconnected` for `disconnectedAfter` |
| +/// (5 s); never connected `connectAfter` (15 s) after the connection was |
| +/// 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 |
| +/// the hub answers with a new generation to both sides, §4.6), and round |
| +/// again. While the signalling stream is down nothing can be negotiated, |
| +/// so an attempt that falls due then waits for it to come back. |
| +/// - **Who acts.** The impolite side (§5.1, the higher peer id) leads, on |
| +/// the schedule. The polite side follows `followerDelay` (3 s) behind it, |
| +/// and only if the leader has not acted: no remote offer has arrived for a |
| +/// restart, no new connection for a rebuild, since the attempt fell due. |
| +/// So two new apps never both rebuild, and an app from before this, which |
| +/// never leads, is still mended from this side: it answers an ICE restart |
| +/// and rebuilds on `pair`, as every app has since 0.2. |
| +/// - **Recovered** is ICE connected or completed. A connection that goes |
| +/// wrong again within `flapWindow` (60 s) carries on where its schedule |
| +/// was, rather than starting at nought again: a link that comes and goes |
| +/// is not restarted every two seconds. |
| +/// - **What is said**: "Reconnecting to Farshad…" on their tile while it |
| +/// tries (ReconnectWatch, fed `trying`); the failure notice only once it |
| +/// has gone on `noticeAfter` (60 s), and gone again when it recovers. |
| +/// |
| +/// Pure: fed the facts as they are, with the time. The browser's |
| +/// `recoveryStep` is its twin. |
| +struct ConnectionRecovery: Equatable { |
| + static let disconnectedAfter = 5.0 |
| + static let connectAfter = 15.0 |
| + static let backoff: [Double] = [0, 2, 5, 10, 20] |
| + static let every = 30.0 |
| + static let followerDelay = 3.0 |
| + static let noticeAfter = 60.0 |
| + static let flapWindow = 60.0 |
| + |
| + enum ICE: Equatable { case new, checking, connected, completed, disconnected, failed, closed } |
| + enum Action: Equatable { case restart, rebuild } |
| + |
| + /// One connection as it is now. |
| + struct Look: Equatable { |
| + var ice: ICE |
| + /// When this connection was made: a rebuild makes a new one. |
| + var builtAt: Double |
| + /// The impolite side of the pair (§5.1), which leads. |
| + var leader: Bool |
| + /// The signalling stream is up, so a negotiation can go out. |
| + var signalling = true |
| + /// When a remote ICE restart (an offer with a new username fragment) |
| + /// was last applied on this connection. |
| + var remoteOfferAt: Double? |
| + /// A negotiation step on this connection threw. |
| + var errored = false |
| + } |
| + |
| + private(set) var troubleSince: Double? |
| + private var disconnectedSince: Double? |
| + /// Attempts made (or left to the leader) this episode, which says what |
| + /// the next one is and how long after the last it falls due. |
| + private(set) var attempts = 0 |
| + /// When the next attempt falls due on the leader's schedule, and when |
| + /// the one before it did (the episode's start, for the first). |
| + private var nextAt: Double? |
| + private var lastDue: Double? |
| + private var recoveredAt: Double? |
| + private var attemptsAtRecovery = 0 |
| + /// Every restart and rebuild this side has made, for the gate. |
| + private(set) var restarts = 0 |
| + private(set) var rebuilds = 0 |
| + |
| + init() {} |
| + |
| + /// Trying to mend it now: their tile says "Reconnecting to …". |
| + var trying: Bool { troubleSince != nil } |
| + /// Trying for `noticeAfter` and more: the failure notice. |
| + func failing(at now: Double) -> Bool { troubleSince.map { now - $0 >= Self.noticeAfter } ?? false } |
| + |
| + /// The wait before attempt `k` (counting from nought), after the last. |
| + static func gap(_ k: Int) -> Double { k < backoff.count ? backoff[k] : every } |
| + /// Two restarts, then a rebuild, and round again. |
| + static func kind(_ k: Int) -> Action { k % 3 == 2 ? .rebuild : .restart } |
| + |
| + /// One look; what to do now, if anything. |
| + mutating func observe(at now: Double, _ look: Look) -> Action? { |
| + if look.ice == .closed { return nil } |
| + // 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 { |
| + troubleSince = nil |
| + nextAt = nil |
| + recoveredAt = now |
| + attemptsAtRecovery = attempts |
| + } |
| + return nil |
| + } |
| + disconnectedSince = look.ice == .disconnected ? (disconnectedSince ?? now) : nil |
| + if troubleSince == nil { |
| + let bad: Bool |
| + switch look.ice { |
| + case .failed: bad = true |
| + case .disconnected: bad = now - (disconnectedSince ?? now) >= Self.disconnectedAfter |
| + case .new, .checking: bad = now - look.builtAt >= Self.connectAfter |
| + case .connected, .completed, .closed: bad = false |
| + } |
| + guard bad || look.errored else { return nil } |
| + troubleSince = now |
| + attempts = recoveredAt.map { now - $0 < Self.flapWindow } == true ? attemptsAtRecovery : 0 |
| + nextAt = now + (attempts == 0 ? 0 : Self.gap(attempts)) |
| + lastDue = now |
| + } |
| + guard look.signalling, let due = nextAt else { return nil } |
| + let offset = look.leader ? 0 : Self.followerDelay |
| + guard now >= due + offset else { return nil } |
| + let kind = Self.kind(attempts) |
| + // The follower stands back when the leader has already acted: a remote |
| + // offer (the leader's restart), or a new connection (its rebuild), |
| + // since the follower's own last attempt fell due. Either side's |
| + // episode can start a beat before the other's, so it is that window |
| + // and not this attempt's instant that counts. |
| + var leaderActed = false |
| + if !look.leader { |
| + let since = lastDue ?? due |
| + switch kind { |
| + case .restart: leaderActed = (look.remoteOfferAt ?? -.infinity) > since |
| + case .rebuild: leaderActed = look.builtAt > since |
| + } |
| + } |
| + lastDue = due |
| + attempts += 1 |
| + nextAt = max(due, now - offset) + Self.gap(attempts) |
| + if leaderActed { return nil } |
| + switch kind { |
| + case .restart: restarts += 1 |
| + case .rebuild: rebuilds += 1 |
| + } |
| + return kind |
| + } |
| +} |
| + |
| +/// "Farshad is on an old version of Calls" (spec §15.28): what a tile says |
| +/// about the app at the other end, from the roster's `client`. |
| +enum ClientVersion { |
| + /// The oldest app that does not break a call for the people in it with |
| + /// it: protocol.MinNativeVersion, and the reason is written there. |
| + static let minimum = "0.4.2" |
| + static let nativeApps: Set<String> = ["mac", "iphone", "ipad"] |
| + |
| + /// "mac 0.4.12" as its two halves; "native" as ("native", nil); nil for |
| + /// anything else, a browser's absent key included. |
| + static func parse(_ client: String?) -> (app: String, version: String?)? { |
| + guard let client else { return nil } |
| + if client == "native" { return ("native", nil) } |
| + let parts = client.split(separator: " ", omittingEmptySubsequences: false) |
| + guard parts.count == 2, nativeApps.contains(String(parts[0])), valid(String(parts[1])) else { return nil } |
| + return (String(parts[0]), String(parts[1])) |
| + } |
| + |
| + static func valid(_ version: String) -> Bool { |
| + let parts = version.split(separator: ".", omittingEmptySubsequences: false) |
| + return (1...4).contains(parts.count) |
| + && parts.allSatisfy { !$0.isEmpty && $0.count <= 4 && $0.allSatisfy { $0.isASCII && $0.isNumber } } |
| + } |
| + |
| + /// Numeric, part by part, a missing part counting as nought. |
| + static func compare(_ a: String, _ b: String) -> Int { |
| + let x = a.split(separator: ".").map { Int($0) ?? 0 } |
| + let y = b.split(separator: ".").map { Int($0) ?? 0 } |
| + for i in 0..<max(x.count, y.count) { |
| + let l = i < x.count ? x[i] : 0 |
| + let r = i < y.count ? y[i] : 0 |
| + if l != r { return l < r ? -1 : 1 } |
| + } |
| + return 0 |
| + } |
| + |
| + /// The tile's words, or nil. An app that says it is older than |
| + /// `minimum` is told so whatever the connection is doing. An app that |
| + /// does not say at all ("native": every app from before this) is only |
| + /// worth a sentence once the connection to it has been failing for |
| + /// ConnectionRecovery's minute — and then it *may* be the reason, which |
| + /// is all this side can know. A browser is never old: its page is the |
| + /// server's own. |
| + static func notice(name: String, client: String?, failing: Bool) -> String? { |
| + guard let (app, version) = parse(client) else { return nil } |
| + if let version { |
| + return compare(version, minimum) < 0 ? VersionWords.old(name) : nil |
| + } |
| + return app == "native" && failing ? VersionWords.mayBeOld(name) : nil |
| + } |
| +} |
| + |
| +public enum VersionWords { |
| + public static func old(_ name: String) -> String { "\(name) is on an old version of Calls — ask them to update" } |
| + public static func mayBeOld(_ name: String) -> String { |
| + "\(name) may be on an old version of Calls — ask them to update" |
| + } |
| +} |
diff --git a/native/apple/Sources/CallsKit/ICETestBlock.swift b/native/apple/Sources/CallsKit/ICETestBlock.swift| new file mode 100644 |
| index 0000000..b1268ce |
| --- /dev/null |
| +++ b/native/apple/Sources/CallsKit/ICETestBlock.swift |
| @@ -0,0 +1,41 @@ |
| +import Foundation |
| + |
| +/// For the gate only: a connection's ICE made to fail, as a path that |
| +/// stops carrying anything does (2026-10-21's incident, a peer whose |
| +/// connection never came up). |
| +/// |
| +/// While the block lasts every ICE candidate this app sends or receives — |
| +/// trickled, or written into a description — has its port replaced by 9, |
| +/// the discard port, which nothing on the gate's Mac listens on. Both ends |
| +/// then hold only candidates that lead nowhere, neither receives a check |
| +/// from the other (so neither can learn a peer-reflexive address), and ICE |
| +/// runs to `failed`. When the block lifts nothing is undone: the candidates |
| +/// already exchanged stay wrong, and only an ICE restart (new candidates) |
| +/// or a new connection gets the pair talking. That is the incident's shape. |
| +/// |
| +/// Inert unless the interop harness sets `until`; the apps never do. |
| +enum ICETestBlock { |
| + /// Until when (system uptime) candidates are mangled; 0 is never. |
| + @MainActor static var until: Double = 0 |
| + /// Candidates mangled so far, for the gate. |
| + @MainActor static var mangled: UInt64 = 0 |
| + |
| + @MainActor static var active: Bool { until > 0 && ProcessInfo.processInfo.systemUptime < until } |
| + |
| + /// One candidate line, `candidate:…` or `a=candidate:…`, with its port |
| + /// replaced. Anything that is not a candidate line comes back as it was. |
| + static func mangle(candidate line: String) -> String { |
| + var fields = line.split(separator: " ", omittingEmptySubsequences: false).map(String.init) |
| + guard fields.count > 7, fields[0].hasPrefix("candidate:") || fields[0].hasPrefix("a=candidate:"), |
| + fields[6] == "typ" |
| + else { return line } |
| + fields[5] = "9" |
| + return fields.joined(separator: " ") |
| + } |
| + |
| + /// A description with every candidate line in it mangled. |
| + static func mangle(sdp: String) -> String { |
| + let lines = sdp.components(separatedBy: "\r\n") |
| + return lines.map { $0.hasPrefix("a=candidate:") ? mangle(candidate: $0) : $0 }.joined(separator: "\r\n") |
| + } |
| +} |
diff --git a/native/apple/Sources/CallsKit/Media.swift b/native/apple/Sources/CallsKit/Media.swift| index 8c20dfd..31a1c74 100644 |
| --- a/native/apple/Sources/CallsKit/Media.swift |
| +++ b/native/apple/Sources/CallsKit/Media.swift |
| @@ -303,10 +303,29 @@ import LiveKitWebRTC |
| } |
| /// ICE restarts this app has started for a renewal, for the gate. |
| var iceRestarts: UInt64 = 0 |
| - func updateICE(_ config: ICEConfig) { |
| + /// A fresh `/ice` answer for every connection; the peers whose |
| + /// connections it restarted (§5.3's renewal falling due). |
| + @discardableResult func updateICE(_ config: ICEConfig) -> Set<String> { |
| let now = Int64(Date().timeIntervalSince1970) |
| - for p in peers.values { p.updateICE(config, now: now) } |
| + var restarted: Set<String> = [] |
| + for (id, p) in peers where p.updateICE(config, now: now) { restarted.insert(id) } |
| + return restarted |
| } |
| + |
| + /// Each connection as ConnectionRecovery reads it (spec §15.28): its ICE |
| + /// state as the delegate last reported it, when it was made, which side |
| + /// leads, its last remote offer, and whether a step on it threw. No hop |
| + /// into WebRTC: all of it is kept on the main actor as it happens. |
| + func recoveryLooks() -> [String: ConnectionRecovery.Look] { |
| + peers.mapValues { |
| + ConnectionRecovery.Look( |
| + ice: $0.iceState, builtAt: $0.builtAt, leader: !$0.polite, remoteOfferAt: $0.remoteOfferAt, |
| + errored: $0.errored) |
| + } |
| + } |
| + |
| + /// §15.28's ICE restart, for one connection, on the list it holds now. |
| + func restartICE(_ peer: String) { peers[peer]?.recoveryRestart() } |
| /// The five audio-health fields, gathered alongside the byte counts. |
| /// |
| /// Bytes say audio arrived; they say nothing about what it sounded like. |
| @@ -418,6 +437,7 @@ import LiveKitWebRTC |
| peak: peak, buffers: buffers, connected: state == .connected || state == .completed, |
| connectionBad: state == .disconnected || state == .failed) |
| reading.gone = state == .failed || state == .closed |
| + reading.failed = state == .failed |
| if deep { |
| var bytes: UInt64 = 0 |
| var packets: UInt64 = 0 |
| @@ -522,6 +542,8 @@ struct PeerAudioReading: Equatable, Sendable { |
| var connectionBad = false |
| /// ICE `failed` or `closed`: whatever was heard on it is gone (§15.24). |
| var gone = false |
| + /// ICE `failed`. |
| + var failed = false |
| var bytes: UInt64? |
| /// Audio packets received, the receiver there at all, and its track |
| /// live (§15.24); read with `bytes`. |
| @@ -568,6 +590,14 @@ struct PeerAudioReading: Equatable, Sendable { |
| // but could not make yet, because it was in the middle of another. |
| private var screenTx: RTCRtpTransceiver? |
| private var owesOffer = false |
| + // §15.28, what ConnectionRecovery reads: when this connection was made, |
| + // its ICE state as the delegate last said, when a remote offer was last |
| + // applied, and whether a negotiation step on it threw. |
| + let builtAt = ProcessInfo.processInfo.systemUptime |
| + private(set) var iceState = ConnectionRecovery.ICE.new |
| + private(set) var remoteOfferAt: Double? |
| + private var remoteUfrag: String? |
| + private(set) var errored = false |
| init(id: String, generation: Int64, polite: Bool, engine: MediaEngine) { |
| self.id = id |
| @@ -843,7 +873,13 @@ struct PeerAudioReading: Equatable, Sendable { |
| work = Task { [weak self] in |
| await previous?.value |
| guard let self, !self.closed, !Task.isCancelled else { return } |
| - do { try await action() } catch { if !self.closed { self.engine?.call?.mediaFailed() } } |
| + do { try await action() } catch { |
| + // §15.28: a step that threw leaves this connection to its recovery |
| + // (an ICE restart, then a rebuild), which says so if it lasts. |
| + guard !self.closed else { return } |
| + if !self.errored { CallLog.info("connection to \(self.id.prefix(6)): a negotiation step failed: \(error.localizedDescription)") } |
| + self.errored = true |
| + } |
| } |
| } |
| private func send(_ type: String, _ payload: [String: Any]) { |
| @@ -876,7 +912,7 @@ struct PeerAudioReading: Equatable, Sendable { |
| let desc = try await makeDescription(answer: false, restart: restart) |
| guard !closed else { return } |
| try await setLocal(desc) |
| - send("offer", ["description": ["type": "offer", "sdp": desc.sdp]]) |
| + send("offer", ["description": ["type": "offer", "sdp": Self.testBlocked(sdp: desc.sdp)]]) |
| } |
| func receive(_ message: Message) { |
| guard message.gen == generation else { return } |
| @@ -888,7 +924,10 @@ struct PeerAudioReading: Equatable, Sendable { |
| guard self.candidates.count < 256 else { throw CancellationError() } |
| self.candidates.append(candidate) |
| } else { |
| - try await self.add(candidate) |
| + // A candidate refused is not a connection broken: one from the |
| + // generation before an ICE restart is refused as a matter of |
| + // course. ICE says whether the connection works (§15.28). |
| + do { try await self.add(candidate) } catch {} |
| } |
| return |
| } |
| @@ -900,30 +939,56 @@ struct PeerAudioReading: Equatable, Sendable { |
| self.ignoreOffer = collision && !self.polite |
| if self.ignoreOffer { return } |
| if collision { try await self.setLocal(RTCSessionDescription(type: .rollback, sdp: "")) } |
| - try await self.setRemote(RTCSessionDescription(type: .offer, sdp: desc.sdp)) |
| + try await self.setRemote(RTCSessionDescription(type: .offer, sdp: Self.testBlocked(sdp: desc.sdp))) |
| + // An ICE restart is an offer with a new username fragment (§5.3); |
| + // only that is the leader acting for ConnectionRecovery. |
| + let ufrag = Self.iceUfrag(desc.sdp) |
| + if let ufrag, let before = self.remoteUfrag, ufrag != before { |
| + self.remoteOfferAt = ProcessInfo.processInfo.systemUptime |
| + } |
| + if let ufrag { self.remoteUfrag = ufrag } |
| self.ignoreOffer = false |
| try await self.drain() |
| let answer = try await self.makeDescription(answer: true) |
| try await self.setLocal(answer) |
| - self.send("answer", ["description": ["type": "answer", "sdp": answer.sdp]]) |
| + self.send("answer", ["description": ["type": "answer", "sdp": Self.testBlocked(sdp: answer.sdp)]]) |
| } else if message.type == "answer", desc.type == "answer", signaling == .haveLocalOffer { |
| - try await self.setRemote(RTCSessionDescription(type: .answer, sdp: desc.sdp)) |
| + try await self.setRemote(RTCSessionDescription(type: .answer, sdp: Self.testBlocked(sdp: desc.sdp))) |
| self.ignoreOffer = false |
| try await self.drain() |
| } |
| } |
| } |
| + /// The first `a=ice-ufrag:` in a description. |
| + static func iceUfrag(_ sdp: String) -> String? { |
| + for line in sdp.components(separatedBy: "\r\n") where line.hasPrefix("a=ice-ufrag:") { |
| + return String(line.dropFirst("a=ice-ufrag:".count)) |
| + } |
| + return nil |
| + } |
| + /// The gate's ICE block (ICETestBlock), on every candidate either way; |
| + /// what it was otherwise. |
| + private static func testBlocked(sdp: String) -> String { |
| + guard ICETestBlock.active else { return sdp } |
| + ICETestBlock.mangled += 1 |
| + return ICETestBlock.mangle(sdp: sdp) |
| + } |
| + private static func testBlocked(candidate: String) -> String { |
| + guard ICETestBlock.active else { return candidate } |
| + ICETestBlock.mangled += 1 |
| + return ICETestBlock.mangle(candidate: candidate) |
| + } |
| private func add(_ candidate: Candidate) async throws { |
| guard let pc, !closed, !candidate.candidate.isEmpty else { return } |
| let ice = RTCIceCandidate( |
| - sdp: candidate.candidate, sdpMLineIndex: candidate.sdpMLineIndex ?? 0, |
| + sdp: Self.testBlocked(candidate: candidate.candidate), sdpMLineIndex: candidate.sdpMLineIndex ?? 0, |
| sdpMid: candidate.sdpMid) |
| try await PeerCalls.add(pc, ice) |
| } |
| private func drain() async throws { |
| let saved = candidates |
| candidates = [] |
| - for c in saved { try await add(c) } |
| + for c in saved { do { try await add(c) } catch {} } |
| } |
| /// A fresh `/ice` answer (§5.2, §5.3). The core fetches one on every |
| /// roster, and a roster answers every stream resume — every five |
| @@ -933,8 +998,8 @@ struct PeerAudioReading: Equatable, Sendable { |
| /// screen and camera to find their way back onto. Now only a renewal |
| /// that is due restarts (ICERenewal.restart); anything else is adopted |
| /// quietly, for whatever this connection gathers next. |
| - func updateICE(_ ice: ICEConfig, now: Int64) { |
| - guard ice.renewAt != lastICE?.renewAt || ice.iceServers.count != lastICE?.iceServers.count else { return } |
| + @discardableResult func updateICE(_ ice: ICEConfig, now: Int64) -> Bool { |
| + guard ice.renewAt != lastICE?.renewAt || ice.iceServers.count != lastICE?.iceServers.count else { return false } |
| lastICE = ice |
| let restart = ICERenewal.restart(gathered: gatheredICE, next: ice, now: now) |
| if restart { gatheredICE = ice } |
| @@ -948,6 +1013,27 @@ struct PeerAudioReading: Equatable, Sendable { |
| try await self.offer(restart: true) |
| } |
| } |
| + return restart |
| + } |
| + |
| + /// §15.28: an ICE restart because this connection is not working, on the |
| + /// list it holds now (`updateICE` has handed it every list since it was |
| + /// made). An offer of this side's still waiting for its answer is rolled |
| + /// back first, because an outstanding offer is the one thing that keeps |
| + /// a restart from going out, and an answer that has not come in seconds |
| + /// is not coming; an offer of the far side's being answered right now is |
| + /// left to finish, and that exchange carries on. |
| + func recoveryRestart() { |
| + if let lastICE { gatheredICE = lastICE } |
| + enqueue { [weak self] in |
| + guard let self, let pc = self.pc else { return } |
| + let signaling = await PeerCalls.read(pc) { $0.signalingState } |
| + guard !self.closed, signaling != .haveRemoteOffer else { return } |
| + if signaling == .haveLocalOffer { |
| + try await self.setLocal(RTCSessionDescription(type: .rollback, sdp: "")) |
| + } |
| + try await self.offer(restart: true) |
| + } |
| } |
| // ------------------------------------------------------------- |
| @@ -1035,7 +1121,7 @@ struct PeerAudioReading: Equatable, Sendable { |
| "candidate", |
| [ |
| "candidate": [ |
| - "candidate": candidate.sdp, "sdpMid": candidate.sdpMid as Any? ?? NSNull(), |
| + "candidate": Self.testBlocked(candidate: candidate.sdp), "sdpMid": candidate.sdpMid as Any? ?? NSNull(), |
| "sdpMLineIndex": candidate.sdpMLineIndex, |
| ] |
| ]) |
| @@ -1088,7 +1174,24 @@ struct PeerAudioReading: Equatable, Sendable { |
| nonisolated func peerConnection( |
| _ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState |
| ) { |
| - if newState == .failed { Task { @MainActor [weak self] in self?.engine?.call?.mediaFailed() } } |
| + // §15.28: kept for ConnectionRecovery, which decides what a failure |
| + // means and when it is worth saying. |
| + let state: ConnectionRecovery.ICE |
| + switch newState { |
| + case .new: state = .new |
| + case .checking: state = .checking |
| + case .connected: state = .connected |
| + case .completed: state = .completed |
| + case .disconnected: state = .disconnected |
| + case .failed: state = .failed |
| + case .closed: state = .closed |
| + default: state = .new |
| + } |
| + Task { @MainActor [weak self] in |
| + guard let self, !self.closed, self.pc == nil || self.pc === peerConnection else { return } |
| + if state != self.iceState { CallLog.info("connection to \(self.id.prefix(6)): ICE \(state)") } |
| + self.iceState = state |
| + } |
| } |
| nonisolated func peerConnection( |
| _ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState |
diff --git a/native/apple/Sources/CallsKit/QualityReport.swift b/native/apple/Sources/CallsKit/QualityReport.swift| index f63bae9..1856d39 100644 |
| --- a/native/apple/Sources/CallsKit/QualityReport.swift |
| +++ b/native/apple/Sources/CallsKit/QualityReport.swift |
| @@ -175,6 +175,9 @@ public struct QualityPeerEvents: Encodable, Equatable, Sendable { |
| public var noSoundFromUs: Bool? |
| public var audioBlocked: Bool? |
| public var screenStalled: Bool? |
| + /// §15.28: ICE restarts and rebuilds this app's recovery made. |
| + public var autoRestarts: Double? |
| + public var autoRebuilds: Double? |
| } |
| // MARK: - The snapshot |
| @@ -454,6 +457,8 @@ public struct QualityEventTally: Equatable, Sendable { |
| /// screen here (the receiver's). |
| public enum Step: Sendable { |
| case keyframe, rebuild, reshare, failure, reattach, damped, encoderStall |
| + /// The connection's own recovery (§15.28). |
| + case autoRestart, autoRebuild |
| /// The receiver judged the screen stalled: `arriving` false when no |
| /// packets came since it last moved, `decoding` false when they came |
| /// and nothing was decoded. |
| @@ -478,6 +483,9 @@ public struct QualityEventTally: Equatable, Sendable { |
| var stalls = 0 |
| var stallsNoPackets = 0 |
| var stallsUndecoded = 0 |
| + /// The connection's own recovery (§15.28). |
| + var autoRestarts = 0 |
| + var autoRebuilds = 0 |
| } |
| /// The longest a look is taken to cover: the level watch looks five |
| @@ -534,6 +542,8 @@ public struct QualityEventTally: Equatable, Sendable { |
| if !arriving { peers[peer, default: Peer()].stallsNoPackets += 1 } else if !decoding { |
| peers[peer, default: Peer()].stallsUndecoded += 1 |
| } |
| + case .autoRestart: peers[peer, default: Peer()].autoRestarts += 1 |
| + case .autoRebuild: peers[peer, default: Peer()].autoRebuilds += 1 |
| } |
| } |
| @@ -631,6 +641,8 @@ public struct QualityReportBuilder: Equatable, Sendable { |
| if e.noSoundFromUs { events.noSoundFromUs = true } |
| if e.audioBlocked { events.audioBlocked = true } |
| if e.screenStalled { events.screenStalled = true } |
| + events.autoRestarts = steps(e.autoRestarts) |
| + events.autoRebuilds = steps(e.autoRebuilds) |
| if events != QualityPeerEvents() { peer.events = events } |
| // The sharer's recovery steps toward this peer belong with the screen |
| // going out to them, even in a window where it sent nothing. |
diff --git a/native/apple/Sources/CallsKit/Wire.swift b/native/apple/Sources/CallsKit/Wire.swift| index 28d290e..7f4157a 100644 |
| --- a/native/apple/Sources/CallsKit/Wire.swift |
| +++ b/native/apple/Sources/CallsKit/Wire.swift |
| @@ -9,6 +9,10 @@ public struct RosterPeer: Decodable, Identifiable { |
| /// §15.19). Nil is unknown — a client that predates the report, or one |
| /// that has not made it yet — and is shown as neither muted nor off. |
| public let media: PeerMedia? |
| + /// What their participation was opened from (spec §15.28): "mac 0.4.12", |
| + /// "native" for an app from before that, nil for a browser or a server |
| + /// from before it. |
| + public let client: String? |
| public var id: String { peer } |
| } |
| /// What a peer says about its own outgoing media (spec §15.19), and about |
diff --git a/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift b/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift| new file mode 100644 |
| index 0000000..be78e70 |
| --- /dev/null |
| +++ b/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift |
| @@ -0,0 +1,193 @@ |
| +import XCTest |
| + |
| +@testable import CallsKit |
| + |
| +/// A connection that stops working is mended without anyone asking (spec |
| +/// §15.28, 2026-10-21): when it counts as broken, the backoff, the |
| +/// escalation to a rebuild, who acts, and when the failure is said. |
| +final class ConnectionRecoveryTests: XCTestCase { |
| + private typealias Look = ConnectionRecovery.Look |
| + |
| + /// Runs the recovery at 5 Hz from `from` to `to`, with the look `look(t)` |
| + /// gives; returns each action with the time it was asked for. |
| + private func run( |
| + _ r: inout ConnectionRecovery, from: Double, to: Double, look: (Double) -> Look |
| + ) -> [(Double, ConnectionRecovery.Action)] { |
| + var out: [(Double, ConnectionRecovery.Action)] = [] |
| + // Whole ticks of a fifth of a second, so the clock does not drift. |
| + for tick in Int((from * 5).rounded())...Int((to * 5).rounded()) { |
| + let t = Double(tick) / 5 |
| + if let a = r.observe(at: t, look(t)) { out.append((t, a)) } |
| + } |
| + return out |
| + } |
| + |
| + func testAFailedConnectionIsRestartedTwiceThenRebuiltOnTheBackoff() { |
| + var r = ConnectionRecovery() |
| + let actions = run(&r, from: 0, to: 160) { _ in Look(ice: .failed, builtAt: -100, leader: true) } |
| + XCTAssertEqual(actions.map(\.0), [0, 2, 7, 17, 37, 67, 97, 127, 157]) |
| + XCTAssertEqual( |
| + actions.map(\.1), |
| + [.restart, .restart, .rebuild, .restart, .restart, .rebuild, .restart, .restart, .rebuild]) |
| + XCTAssertEqual(r.restarts, 6) |
| + XCTAssertEqual(r.rebuilds, 3) |
| + } |
| + |
| + func testDisconnectedCountsAfterFiveSeconds() { |
| + var r = ConnectionRecovery() |
| + let actions = run(&r, from: 0, to: 4.8) { _ in Look(ice: .disconnected, builtAt: -100, leader: true) } |
| + XCTAssertTrue(actions.isEmpty, "a blip is not a failure") |
| + XCTAssertFalse(r.trying) |
| + XCTAssertEqual(r.observe(at: 5, Look(ice: .disconnected, builtAt: -100, leader: true)), .restart) |
| + XCTAssertTrue(r.trying) |
| + } |
| + |
| + func testADisconnectionThatComesBackInTimeIsNothing() { |
| + var r = ConnectionRecovery() |
| + let actions = run(&r, from: 0, to: 20) { t in |
| + Look(ice: Int(t) % 6 < 4 ? .disconnected : .connected, builtAt: -100, leader: true) |
| + } |
| + XCTAssertTrue(actions.isEmpty) |
| + } |
| + |
| + /// The incident's shape: a connection that never comes up, which |
| + /// libwebrtc leaves in `checking` rather than calling failed. |
| + func testAConnectionThatNeverComesUpIsTroubleAfterFifteenSeconds() { |
| + var r = ConnectionRecovery() |
| + XCTAssertTrue(run(&r, from: 0, to: 14.8) { _ in Look(ice: .checking, builtAt: 0, leader: true) }.isEmpty) |
| + XCTAssertEqual(r.observe(at: 15, Look(ice: .checking, builtAt: 0, leader: true)), .restart) |
| + var fresh = ConnectionRecovery() |
| + XCTAssertTrue(run(&fresh, from: 0, to: 14.8) { _ in Look(ice: .new, builtAt: 0, leader: true) }.isEmpty) |
| + XCTAssertEqual(fresh.observe(at: 15, Look(ice: .new, builtAt: 0, leader: true)), .restart) |
| + } |
| + |
| + func testRecoveryEndsTheEpisodeAndClearsTheWords() { |
| + var r = ConnectionRecovery() |
| + _ = run(&r, from: 0, to: 61) { _ in Look(ice: .failed, builtAt: -100, leader: true) } |
| + XCTAssertTrue(r.trying) |
| + XCTAssertTrue(r.failing(at: 61)) |
| + XCTAssertNil(r.observe(at: 61.2, Look(ice: .connected, builtAt: -100, leader: true))) |
| + XCTAssertFalse(r.trying) |
| + XCTAssertFalse(r.failing(at: 61.2)) |
| + } |
| + |
| + func testTheFailureIsSaidOnlyAfterAMinute() { |
| + var r = ConnectionRecovery() |
| + _ = run(&r, from: 0, to: 59.8) { _ in Look(ice: .failed, builtAt: -100, leader: true) } |
| + XCTAssertTrue(r.trying) |
| + XCTAssertFalse(r.failing(at: 59.8)) |
| + XCTAssertTrue(r.failing(at: 60)) |
| + } |
| + |
| + /// A link that comes and goes is not hammered from nought each time. |
| + func testTroubleSoonAfterARecoveryCarriesOnWhereTheScheduleWas() { |
| + var r = ConnectionRecovery() |
| + _ = run(&r, from: 0, to: 8) { _ in Look(ice: .failed, builtAt: -100, leader: true) } // 0, 2, 7 |
| + XCTAssertEqual(r.attempts, 3) |
| + XCTAssertNil(r.observe(at: 9, Look(ice: .connected, builtAt: 8, leader: true))) |
| + let again = run(&r, from: 20, to: 60) { _ in Look(ice: .failed, builtAt: 8, leader: true) } |
| + // Attempt 4 is due its own gap (10 s) after the trouble, not at once. |
| + XCTAssertEqual(again.first?.0, 30) |
| + XCTAssertEqual(again.first?.1, .restart) |
| + // Well after a recovery it starts from nought again. |
| + var later = ConnectionRecovery() |
| + _ = run(&later, from: 0, to: 8) { _ in Look(ice: .failed, builtAt: -100, leader: true) } |
| + XCTAssertNil(later.observe(at: 9, Look(ice: .connected, builtAt: 8, leader: true))) |
| + XCTAssertEqual(later.observe(at: 80, Look(ice: .failed, builtAt: 8, leader: true)), .restart) |
| + } |
| + |
| + func testNothingIsAttemptedWhileTheSignallingStreamIsDown() { |
| + var r = ConnectionRecovery() |
| + let down = run(&r, from: 0, to: 30) { _ in Look(ice: .failed, builtAt: -100, leader: true, signalling: false) } |
| + XCTAssertTrue(down.isEmpty) |
| + XCTAssertTrue(r.trying, "still in trouble, and still said") |
| + XCTAssertEqual(r.observe(at: 30.2, Look(ice: .failed, builtAt: -100, leader: true)), .restart) |
| + } |
| + |
| + func testANegotiationStepThatThrewHastensTroubleOnlyWhileNotConnected() { |
| + var r = ConnectionRecovery() |
| + 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() { |
| + var r = ConnectionRecovery() |
| + XCTAssertTrue(run(&r, from: 0, to: 30) { _ in Look(ice: .closed, builtAt: -100, leader: true) }.isEmpty) |
| + XCTAssertFalse(r.trying) |
| + } |
| + |
| + /// The polite side follows three seconds behind, and stands back for |
| + /// whatever the leader has already done. |
| + func testTheFollowerActsOnlyWhenTheLeaderDoesNot() { |
| + // A leader from before this release: it never acts, so the follower |
| + // runs the whole schedule three seconds late. |
| + var alone = ConnectionRecovery() |
| + let actions = run(&alone, from: 0, to: 21) { _ in Look(ice: .failed, builtAt: -100, leader: false) } |
| + XCTAssertEqual(actions.map(\.0), [3, 5, 10, 20]) |
| + XCTAssertEqual(actions.map(\.1), [.restart, .restart, .rebuild, .restart]) |
| + |
| + // A leader that does act: its restart offers arrive, and its rebuild |
| + // gives this side a new connection; the follower asks for nothing. |
| + var follower = ConnectionRecovery() |
| + var built = -100.0 |
| + let none = run(&follower, from: 0, to: 40) { t in |
| + // The leader's restarts land 0.1 s after 0 and 2, its rebuild after 7. |
| + let offer: Double? = t >= 7.1 ? (t >= 17.1 ? 17.1 : 7.1) : t >= 2.1 ? 2.1 : t >= 0.1 ? 0.1 : nil |
| + if t >= 7.1 { built = 7.1 } |
| + return Look(ice: .failed, builtAt: built, leader: false, remoteOfferAt: offer) |
| + } |
| + XCTAssertTrue(none.isEmpty, "the follower acted beside the leader: \(none)") |
| + } |
| + |
| + /// Two sides whose episodes started a beat apart still rebuild once. |
| + func testAFollowerAStepBehindDoesNotRebuildAgain() { |
| + var follower = ConnectionRecovery() |
| + // The follower notices one second after the leader: the leader's |
| + // rebuild (at its 7 s) lands at the follower's 6.1 s. |
| + let actions = run(&follower, from: 0, to: 12) { t in |
| + Look(ice: .failed, builtAt: t >= 6.1 ? 6.1 : -100, leader: false, remoteOfferAt: t >= 1.1 ? 1.1 : nil) |
| + } |
| + XCTAssertFalse(actions.contains { $0.1 == .rebuild }, "\(actions)") |
| + } |
| + |
| + func testTheVersionNoticeRule() { |
| + XCTAssertEqual( |
| + ClientVersion.notice(name: "Farshad", client: "mac 0.4.1", failing: false), |
| + "Farshad is on an old version of Calls — ask them to update") |
| + XCTAssertEqual( |
| + ClientVersion.notice(name: "Farshad", client: "iphone 0.3.9", failing: true), |
| + "Farshad is on an old version of Calls — ask them to update") |
| + XCTAssertNil(ClientVersion.notice(name: "Farshad", client: "mac 0.4.2", failing: true)) |
| + XCTAssertNil(ClientVersion.notice(name: "Farshad", client: "mac 0.4.12", failing: true)) |
| + // No version at all: an app from before §15.28, only worth a word |
| + // once the connection to it has been failing. |
| + XCTAssertNil(ClientVersion.notice(name: "Farshad", client: "native", failing: false)) |
| + XCTAssertEqual( |
| + ClientVersion.notice(name: "Farshad", client: "native", failing: true), |
| + "Farshad may be on an old version of Calls — ask them to update") |
| + // A browser, or a server from before the key: never. |
| + XCTAssertNil(ClientVersion.notice(name: "Farshad", client: nil, failing: true)) |
| + XCTAssertNil(ClientVersion.notice(name: "Farshad", client: "web 882eab8", failing: true)) |
| + XCTAssertNil(ClientVersion.notice(name: "Farshad", client: "mac latest", failing: true)) |
| + } |
| + |
| + func testVersionsCompareNumerically() { |
| + XCTAssertEqual(ClientVersion.compare("0.4.10", "0.4.2"), 1) |
| + XCTAssertEqual(ClientVersion.compare("0.4.1", "0.4.2"), -1) |
| + XCTAssertEqual(ClientVersion.compare("0.4", "0.4.0"), 0) |
| + XCTAssertEqual(ClientVersion.compare("0.10", "0.9.9"), 1) |
| + XCTAssertEqual(ClientVersion.compare("1", "0.99"), 1) |
| + } |
| + |
| + func testTheMinimumIsTheServers() throws { |
| + // protocol.MinNativeVersion, which carries the reason; the two must agree. |
| + let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent() |
| + .appendingPathComponent("../../../../protocol/client.go").standardized |
| + let source = try String(contentsOf: url, encoding: .utf8) |
| + XCTAssertTrue( |
| + source.contains("const MinNativeVersion = \"\(ClientVersion.minimum)\""), |
| + "ClientVersion.minimum and protocol.MinNativeVersion disagree") |
| + } |
| +} |
diff --git a/native/bridge/bridge.go b/native/bridge/bridge.go| index 57b3dc7..eca9ad9 100644 |
| --- a/native/bridge/bridge.go |
| +++ b/native/bridge/bridge.go |
| @@ -107,7 +107,16 @@ func (c *Client) Send(typ, to string, generation int64, payload string) error { |
| return c.room.Send(typ, to, uint64(generation), payload) |
| } |
| func (c *Client) Leave() { c.room.Leave() } |
| -func (c *Client) Close() { c.room.Close() } |
| + |
| +// RefreshICE asks for a fresh /ice answer now (spec §15.28), delivered as |
| +// the usual "ice" event. |
| +func (c *Client) RefreshICE() { c.room.RefreshICE() } |
| + |
| +// SetClientInfo is the app and its version, said on every request the |
| +// core makes (spec §15.28), so the people in a call can tell when |
| +// someone's app is too old. Call it before NewClient; false is refused. |
| +func SetClientInfo(app, version string) bool { return callscore.SetClient(app, version) } |
| +func (c *Client) Close() { c.room.Close() } |
| // SetMedia is this app's own microphone and camera state (spec §15.19). |
| // The core reports it once admitted, again whenever a roster says the |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index df87a13..bce97bd 100644 |
| --- a/native/ios/project.yml |
| +++ b/native/ios/project.yml |
| @@ -10,7 +10,7 @@ settings: |
| base: |
| SWIFT_VERSION: '5.0' |
| CODE_SIGN_STYLE: Automatic |
| - MARKETING_VERSION: '0.4.11' |
| + MARKETING_VERSION: '0.4.13' |
| CURRENT_PROJECT_VERSION: '1' |
| # The App Group the app and its broadcast extension share: the socket |
| # the iPhone's screen crosses lives in its container. One setting |
diff --git a/protocol/client.go b/protocol/client.go| new file mode 100644 |
| index 0000000..e722ab3 |
| --- /dev/null |
| +++ b/protocol/client.go |
| @@ -0,0 +1,116 @@ |
| +package protocol |
| + |
| +import ( |
| + "strconv" |
| + "strings" |
| +) |
| + |
| +// The client a participation was opened from (spec §15.28, 2026-10-21): |
| +// which app, at which version, so that the people in a call can tell |
| +// someone their app is too old to talk to theirs. |
| + |
| +// ClientHeader carries an app's own "<app> <version>" on every request |
| +// its core makes. A browser sends none: its page is the server's own. |
| +const ClientHeader = "X-Calls-Client" |
| + |
| +// ClientNative is the roster's client for an app that did not say which it |
| +// is: the core's requests carry Go's default user agent and no |
| +// ClientHeader, which is every app from before §15.28. |
| +const ClientNative = "native" |
| + |
| +// MinNativeVersion is the oldest app version that does not break a call |
| +// for the people it is in it with (spec §15.28). Before 0.4.2 an app |
| +// restarted ICE on every connection on every /ice answer — twelve times |
| +// an hour, each one a pause for the screen and camera (§15.21) — and |
| +// sent a Mac screen to browsers at a size their H.264 level refused, so |
| +// the browser's picture froze for seconds at a time. Everything the wire |
| +// needs to recover a connection — `pair` and generations (§4.6), answering |
| +// an ICE restart, ignoring keys it does not know — every app has had |
| +// since the rename (0.2), and the recovery of §15.28 needs nothing of the |
| +// far side but those. |
| +const MinNativeVersion = "0.4.2" |
| + |
| +// maxClientLen bounds the header: "ipad 9999.9999.9999.9999" is 24 bytes. |
| +const maxClientLen = 32 |
| + |
| +// ClientApps are the apps a ClientHeader may name. |
| +var ClientApps = []string{"mac", "iphone", "ipad"} |
| + |
| +// ParseClient splits "<app> <version>" into its two halves, ok only for a |
| +// known app and a version of one to four dot-separated numbers of at most |
| +// four digits each. "native" parses to ("native", "") with ok true. |
| +func ParseClient(s string) (app, version string, ok bool) { |
| + if s == ClientNative { |
| + return ClientNative, "", true |
| + } |
| + if len(s) > maxClientLen { |
| + return "", "", false |
| + } |
| + app, version, found := strings.Cut(s, " ") |
| + if !found || !validVersion(version) { |
| + return "", "", false |
| + } |
| + for _, a := range ClientApps { |
| + if a == app { |
| + return app, version, true |
| + } |
| + } |
| + return "", "", false |
| +} |
| + |
| +func validVersion(v string) bool { |
| + parts := strings.Split(v, ".") |
| + if len(parts) < 1 || len(parts) > 4 { |
| + return false |
| + } |
| + for _, p := range parts { |
| + if p == "" || len(p) > 4 { |
| + return false |
| + } |
| + for _, c := range p { |
| + if c < '0' || c > '9' { |
| + return false |
| + } |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// CompareVersions orders two versions of digits and dots numerically, |
| +// part by part, a missing part counting as zero: -1, 0 or 1. |
| +func CompareVersions(a, b string) int { |
| + pa, pb := strings.Split(a, "."), strings.Split(b, ".") |
| + for i := 0; i < max(len(pa), len(pb)); i++ { |
| + var x, y int |
| + if i < len(pa) { |
| + x, _ = strconv.Atoi(pa[i]) |
| + } |
| + if i < len(pb) { |
| + y, _ = strconv.Atoi(pb[i]) |
| + } |
| + if x != y { |
| + if x < y { |
| + return -1 |
| + } |
| + return 1 |
| + } |
| + } |
| + return 0 |
| +} |
| + |
| +// ClientFor is the roster's client for a request: the app's own header |
| +// when it is well formed, ClientNative for a request from the Go HTTP |
| +// client with none (an app from before §15.28), and "" otherwise — a |
| +// browser, or a header that is not one this server can read. |
| +func ClientFor(header, userAgent string) string { |
| + if header != "" { |
| + if _, _, ok := ParseClient(header); ok && header != ClientNative { |
| + return header |
| + } |
| + return "" |
| + } |
| + if strings.HasPrefix(userAgent, "Go-http-client/") { |
| + return ClientNative |
| + } |
| + return "" |
| +} |
diff --git a/protocol/client_test.go b/protocol/client_test.go| new file mode 100644 |
| index 0000000..fd9eae3 |
| --- /dev/null |
| +++ b/protocol/client_test.go |
| @@ -0,0 +1,72 @@ |
| +package protocol |
| + |
| +import "testing" |
| + |
| +func TestParseClient(t *testing.T) { |
| + for _, c := range []struct { |
| + in, app, version string |
| + ok bool |
| + }{ |
| + {"mac 0.4.12", "mac", "0.4.12", true}, |
| + {"iphone 0.4.12", "iphone", "0.4.12", true}, |
| + {"ipad 1", "ipad", "1", true}, |
| + {"native", "native", "", true}, |
| + {"mac 9999.9999.9999.9999", "mac", "9999.9999.9999.9999", true}, |
| + {"mac 10000.1", "", "", false}, |
| + {"mac 0.4.12.1.2", "", "", false}, |
| + {"mac", "", "", false}, |
| + {"mac ", "", "", false}, |
| + {"mac 0..4", "", "", false}, |
| + {"mac 0.4a", "", "", false}, |
| + {"web 882eab8", "", "", false}, |
| + {"windows 1.0", "", "", false}, |
| + {"Mac 0.4.12", "", "", false}, |
| + {"mac 0.4.12", "", "", false}, |
| + {"mac 0.4.12 extra", "", "", false}, |
| + } { |
| + app, version, ok := ParseClient(c.in) |
| + if app != c.app || version != c.version || ok != c.ok { |
| + t.Errorf("ParseClient(%q) = %q, %q, %v; want %q, %q, %v", c.in, app, version, ok, c.app, c.version, c.ok) |
| + } |
| + } |
| +} |
| + |
| +func TestCompareVersions(t *testing.T) { |
| + for _, c := range []struct { |
| + a, b string |
| + want int |
| + }{ |
| + {"0.4.2", "0.4.2", 0}, |
| + {"0.4.10", "0.4.2", 1}, |
| + {"0.4.1", "0.4.2", -1}, |
| + {"0.4", "0.4.0", 0}, |
| + {"0.4", "0.4.1", -1}, |
| + {"1.0", "0.99.99", 1}, |
| + {"0.10.0", "0.9.9", 1}, |
| + } { |
| + if got := CompareVersions(c.a, c.b); got != c.want { |
| + t.Errorf("CompareVersions(%q, %q) = %d, want %d", c.a, c.b, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +func TestClientFor(t *testing.T) { |
| + const browser = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.5 Safari/605.1.15" |
| + for _, c := range []struct{ header, ua, want string }{ |
| + {"mac 0.4.12", "Go-http-client/1.1", "mac 0.4.12"}, |
| + {"iphone 0.4.12", "Go-http-client/2.0", "iphone 0.4.12"}, |
| + {"", "Go-http-client/1.1", "native"}, |
| + {"", "Go-http-client/2.0", "native"}, |
| + {"", browser, ""}, |
| + {"", "", ""}, |
| + // A header that is not one: never trusted, and never turned |
| + // into "native" either, because it did say something. |
| + {"mac latest", "Go-http-client/1.1", ""}, |
| + {"native", "Go-http-client/1.1", ""}, |
| + {"mac 0.4.12", browser, "mac 0.4.12"}, |
| + } { |
| + if got := ClientFor(c.header, c.ua); got != c.want { |
| + t.Errorf("ClientFor(%q, %q) = %q, want %q", c.header, c.ua, got, c.want) |
| + } |
| + } |
| +} |
diff --git a/protocol/messages.go b/protocol/messages.go| index 627eced..8b9618b 100644 |
| --- a/protocol/messages.go |
| +++ b/protocol/messages.go |
| @@ -114,6 +114,13 @@ type RosterPeer struct { |
| // neither muted nor camera-off. Never written through: a snapshot |
| // copies the pointer, so a change replaces it. |
| Media *MediaState `json:"media,omitempty"` |
| + // Client is what the peer's participation was opened from (spec |
| + // §15.28): "mac 0.4.12", "iphone 0.4.12" or "ipad 0.4.12" for an app |
| + // that says (ClientHeader), "native" for an app that does not — every |
| + // app from before §15.28, recognised by the Go HTTP client's own user |
| + // agent — and absent for a browser, or anything else. Set once, at |
| + // open, by the server; a peer cannot set another's. |
| + Client string `json:"client,omitempty"` |
| } |
| // MediaState is what a peer says about its own outgoing media (spec |
diff --git a/protocol/quality.go b/protocol/quality.go| index 74e8827..4e79e49 100644 |
| --- a/protocol/quality.go |
| +++ b/protocol/quality.go |
| @@ -185,6 +185,11 @@ type PeerEvents struct { |
| NoSoundFromUs bool `json:"noSoundFromUs,omitempty"` // they listed this client |
| AudioBlocked bool `json:"audioBlocked,omitempty"` // they said their browser blocked sound |
| ScreenStalled bool `json:"screenStalled,omitempty"` // this client reported their screen stalled (§15.21) |
| + // The connection's own recovery (§15.28) during the window: ICE |
| + // restarts this client made on its own, and times it had the pair |
| + // rebuilt from nothing (a `reset`). Older servers drop both. |
| + AutoRestarts *float64 `json:"autoRestarts,omitempty"` |
| + AutoRebuilds *float64 `json:"autoRebuilds,omitempty"` |
| } |
| // ProblemReport is "Report a problem": what the person typed, and the |
diff --git a/test/browser/call.mjs b/test/browser/call.mjs| index e9f0029..f40e349 100644 |
| --- a/test/browser/call.mjs |
| +++ b/test/browser/call.mjs |
| @@ -430,6 +430,16 @@ function state(page) { |
| // are still in their first moments and the words are showing. |
| hearingList: s.hearingList, |
| connecting: s.connecting, |
| + // §15.28: 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, |
| }; |
| }); |
| } |
| @@ -3141,6 +3151,138 @@ const run = { |
| await ctxB.close(); |
| }, |
| + // §15.28, 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.28, 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..4df4870 |
| --- /dev/null |
| +++ b/test/browser/native-ice.mjs |
| @@ -0,0 +1,145 @@ |
| +// native-ice.mjs — spec §15.28 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.28), 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..9cf47d6 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.28: 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.28)', () => { |
| + 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..62d10a1 |
| --- /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.28, 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(''), ''); |
| +}); |