oficina / meet Public

Calls: the apps mend a connection that stops working, and say who is on an old app

ConnectionRecovery (spec 15.27): ICE failed, disconnected for 5 s, or
never connected 15 s after it was made, is trouble; attempts 0, 2, 5,
10, 20 s apart and then every 30 s: an ICE restart, another, then the
pair rebuilt through the hub's reset, and round again. The impolite side
leads; the polite side follows 3 s behind and only when the leader has
not acted, so an app from before this is mended from this side alone.
Restarts on credentials due for renewal fetch /ice first. The tile says
Reconnecting to ... while it tries; the failure notice waits a minute
and goes with the trouble.

Every app now says which it is (X-Calls-Client: mac 0.4.12); the server
puts that in every roster as client, and "native" for a Go client with
no header (an app from before). A tile says "... is on an old version of
Calls" below 0.4.2, and "... may be on an old version" for an app that
does not say, once its connection has failed for a minute.

Quality reports count autoRestarts and autoRebuilds per peer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a5d6528d7a7196d1caf9d9ee01dbd0fde9ac8dc1 parent ed9916d
22 files changed, +1,126 −28
  • callscore/client.go +50 −0
  • callscore/client_test.go +60 −0
  • callscore/transport.go +3 −0
  • internal/calls/hub/admission.go +2 −2
  • internal/calls/hub/hub.go +21 −0
  • internal/calls/stream.go +3 −0
  • internal/callstest/client_test.go +63 −0
  • internal/callstest/harness_test.go +4 −0
  • internal/callstest/native_ice_test.go +45 −7
  • internal/callstest/sse_test.go +5 −0
  • native/apple/Sources/CallsInterop/Interop.swift +11 −0
  • native/apple/Sources/CallsKit/Call.swift +134 −9
  • native/apple/Sources/CallsKit/ConnectionRecovery.swift +214 −0
  • native/apple/Sources/CallsKit/Media.swift +96 −8
  • native/apple/Sources/CallsKit/QualityReport.swift +11 −1
  • native/apple/Sources/CallsKit/Wire.swift +4 −0
  • native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift +190 −0
  • native/bridge/bridge.go +10 −1
  • protocol/client.go +116 −0
  • protocol/client_test.go +72 −0
  • protocol/messages.go +7 −0
  • protocol/quality.go +5 −0
diff --git a/callscore/client.go b/callscore/client.go
new file mode 100644
index 0000000..7b409ff
--- /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.27 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.27 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.27: 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..4d71653
--- /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.27 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/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..6507b2a 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.27,
+ // 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.27). 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/stream.go b/internal/calls/stream.go
index 18b76b3..af71c6d 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.27: 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/client_test.go b/internal/callstest/client_test.go
new file mode 100644
index 0000000..d717a8d
--- /dev/null
+++ b/internal/callstest/client_test.go
@@ -0,0 +1,63 @@
+package callstest
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+// Spec §15.27: 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..3598aeb 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.27 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_ice_test.go b/internal/callstest/native_ice_test.go
index ae17047..d474a1b 100644
--- a/internal/callstest/native_ice_test.go
+++ b/internal/callstest/native_ice_test.go
@@ -111,17 +111,46 @@ func TestNativeMacIceRecovery(t *testing.T) {
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.
- sawFailed := false
+ // 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.27) 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 {
- if a.stat("iceFailedPeers") > 0 {
+ s := a.sample()
+ if s.Stats["iceFailedPeers"] > 0 {
sawFailed = true
}
- if a.stat("iceConnectedPeers") > 0 && a.stat("framesDecoded") > 0 {
- t.Fatalf("A connected to C through the block: %+v", a.sample())
+ 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 ")
+ 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 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)
@@ -151,7 +180,16 @@ func TestNativeMacIceRecovery(t *testing.T) {
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))
- if strings.Contains(a.sample().Status, "could not connect") {
- t.Fatalf("the failure notice outlived the recovery: %q", a.sample().Status)
+ // 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)
}
}
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 9b7ce8f..03883ed 100644
--- a/native/apple/Sources/CallsInterop/Interop.swift
+++ b/native/apple/Sources/CallsInterop/Interop.swift
@@ -124,6 +124,12 @@ struct Input: Decodable {
if let ms = ProcessInfo.processInfo.environment["CALLS_TEST_ICE_BLOCK_MS"].flatMap(Double.init), ms > 0 {
call.blockICEForTest(ms: ms)
}
+ // §15.27: 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(
@@ -338,6 +344,11 @@ struct Input: Decodable {
// 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.27).
+ "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 {
diff --git a/native/apple/Sources/CallsKit/Call.swift b/native/apple/Sources/CallsKit/Call.swift
index 5f51136..7824395 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.27): 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.27.
+ @_spi(Fixtures) public static var autoRecovery = true
+ /// Whether this app says which it is (§15.27); 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.
@@ -277,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")
@@ -364,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.27: 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)
@@ -430,6 +454,9 @@ private final class Events: NSObject, BridgeListenerProtocol {
endLevelWatch()
qualityWatch?.cancel()
qualityWatch = nil
+ recovery = [:]
+ restartsAwaitingICE = []
+ failingPeers = []
currentCamera = nil
cameraStatus = nil
cameraNote = ""
@@ -739,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) {
@@ -755,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.27: 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)
@@ -803,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.27), 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.27), 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.27'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.27'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.
@@ -886,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
@@ -927,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.27: 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 {
@@ -1213,7 +1333,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) }
@@ -1289,6 +1408,12 @@ private final class Events: NSObject, BridgeListenerProtocol {
values["iceConnectedPeers"] = UInt64(iceConnectedPeers)
values["iceFailedPeers"] = UInt64(iceFailedPeers)
values["iceBlockMangled"] = ICETestBlock.mangled
+ // §15.27: 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..dfa92de
--- /dev/null
+++ b/native/apple/Sources/CallsKit/ConnectionRecovery.swift
@@ -0,0 +1,214 @@
+import Foundation
+
+/// A connection that stops working is mended without anyone asking (spec
+/// §15.27, 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 a negotiation step on it threw.
+/// - **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 }
+ let healthy = (look.ice == .connected || look.ice == .completed) && !look.errored
+ 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.27): 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/Media.swift b/native/apple/Sources/CallsKit/Media.swift
index 0b7f5a6..ba38a33 100644
--- a/native/apple/Sources/CallsKit/Media.swift
+++ b/native/apple/Sources/CallsKit/Media.swift
@@ -297,10 +297,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.27): 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.27'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.
@@ -565,6 +584,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.27, 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
@@ -831,7 +858,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.27: 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 +909,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.27).
+ do { try await self.add(candidate) } catch {}
}
return
}
@@ -889,6 +925,13 @@ struct PeerAudioReading: Equatable, Sendable {
if self.ignoreOffer { return }
if collision { try await self.setLocal(RTCSessionDescription(type: .rollback, 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)
@@ -901,6 +944,13 @@ struct PeerAudioReading: Equatable, Sendable {
}
}
}
+ /// 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 {
@@ -923,7 +973,7 @@ struct PeerAudioReading: Equatable, Sendable {
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 +983,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 +998,27 @@ struct PeerAudioReading: Equatable, Sendable {
try await self.offer(restart: true)
}
}
+ return restart
+ }
+
+ /// §15.27: 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)
+ }
}
// -------------------------------------------------------------
@@ -1088,7 +1159,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.27: 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 aa52bba..195fd80 100644
--- a/native/apple/Sources/CallsKit/QualityReport.swift
+++ b/native/apple/Sources/CallsKit/QualityReport.swift
@@ -166,6 +166,9 @@ public struct QualityPeerEvents: Encodable, Equatable, Sendable {
public var noSoundFromUs: Bool?
public var audioBlocked: Bool?
public var screenStalled: Bool?
+ /// §15.27: ICE restarts and rebuilds this app's recovery made.
+ public var autoRestarts: Double?
+ public var autoRebuilds: Double?
}
// MARK: - The snapshot
@@ -443,7 +446,7 @@ enum QualityWords {
public struct QualityEventTally: Equatable, Sendable {
/// A screen recovery step, toward a peer (the sharer's) or for their
/// screen here (the receiver's).
- public enum Step: Sendable { case keyframe, rebuild, reshare, failure, reattach }
+ public enum Step: Sendable { case keyframe, rebuild, reshare, failure, reattach, autoRestart, autoRebuild }
struct Peer: Equatable, Sendable {
var reconnecting = 0
@@ -458,6 +461,9 @@ public struct QualityEventTally: Equatable, Sendable {
var reshares = 0
var failures = 0
var reattaches = 0
+ /// The connection's own recovery (§15.27).
+ var autoRestarts = 0
+ var autoRebuilds = 0
}
/// The longest a look is taken to cover: the level watch looks five
@@ -507,6 +513,8 @@ public struct QualityEventTally: Equatable, Sendable {
case .reshare: peers[peer, default: Peer()].reshares += 1
case .failure: peers[peer, default: Peer()].failures += 1
case .reattach: peers[peer, default: Peer()].reattaches += 1
+ case .autoRestart: peers[peer, default: Peer()].autoRestarts += 1
+ case .autoRebuild: peers[peer, default: Peer()].autoRebuilds += 1
}
}
@@ -604,6 +612,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..2c5930a 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.27): "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..0f20f84
--- /dev/null
+++ b/native/apple/Tests/CallsKitTests/ConnectionRecoveryTests.swift
@@ -0,0 +1,190 @@
+import XCTest
+
+@testable import CallsKit
+
+/// A connection that stops working is mended without anyone asking (spec
+/// §15.27, 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 testANegotiationStepThatThrewIsTrouble() {
+ var r = ConnectionRecovery()
+ XCTAssertEqual(r.observe(at: 0, Look(ice: .connected, builtAt: -100, leader: true, errored: true)), .restart)
+ }
+
+ 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.27, 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..7c0f8f5 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.27), 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.27), 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/protocol/client.go b/protocol/client.go
new file mode 100644
index 0000000..e955f83
--- /dev/null
+++ b/protocol/client.go
@@ -0,0 +1,116 @@
+package protocol
+
+import (
+ "strconv"
+ "strings"
+)
+
+// The client a participation was opened from (spec §15.27, 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.27.
+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.27). 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.27 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.27), 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..d549f3b 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.27): "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.27, 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 1619aa4..869bcf2 100644
--- a/protocol/quality.go
+++ b/protocol/quality.go
@@ -174,6 +174,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.27) 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