Repository navigation
Swift: resume a text session's socket, and notice when it's gone - #2802
martinmitrevski wants to merge 4 commits into
Conversation
04adf4f to
9a9eb57
Compare
34268bc to
d096cff
Compare
👋 Thanks, Martin! I'm on it.How to work with me
CommandsComment any of these on the PR:
|
There was a problem hiding this comment.
Round 1 · 🆕 3 new · 1 should-fix to go
| Finding | Where | |
|---|---|---|
| 🟡 Should Fix | Reconnect backoff restarts on every accepted upgrade | AgentSession.swift:323 |
🆕 New commit 85beb56 · the next round starts at 11:55 UTC, once you've stopped pushing.
- Start the next round now
| let recovery = recovery | ||
| // Isolated to the main actor as this is, so it runs only once `lifecycle` names it. | ||
| let retrying = Task { [weak self] in | ||
| var retries = reconnection.retries() |
There was a problem hiding this comment.
[Should Fix] Reconnect backoff restarts on every accepted upgrade
Issue: A router that accepts the upgrade and then closes at once gets an immediate retry every time, so each client loops upgrade, close, token fetch with no growing wait.
Cause: reconnect builds a fresh reconnection.retries() at line 323 whose first delay is zero, and reopen returns true as soon as the upgrade opens (lines 370-380), so the backoff never grows.
Fix: Keep the retry strategy across drops and start a new one only after a frame is read from the reconnected socket. Or: enforce a minimum wait when the last socket lived only briefly.
Side effect: everyReconnectStartsAtOnce in SessionsTests.swift pins the current behaviour and needs updating.
Evidence
- AgentSession.swift:300-301 follow() sends every socketClosed of a resumable session to reconnect(), whatever the close code
- AgentSession.swift:323 each reconnect() creates a new retries() strategy; its first delay is zero
- AgentSession.swift:370-380 reopen() returns true once the upgrade opens, so nothing carries the failure count forward
- SessionsTests.swift ~909-926 everyReconnectStartsAtOnce has the server close 1012 right after each upgrade and expects the next request at once
- Nothing in the diff caps attempts or total time
| private func connect(_ attempt: UUID) async { | ||
| // A text session outlives its socket, so its socket can be resumed. A call's cannot: | ||
| // the call is the router's, and ends with it. | ||
| let resumable = session.callID.isEmpty |
There was a problem hiding this comment.
consider: Resumable is fixed at connect but a session can move onto a call
resumable is read once from session.callID here, while lost() and mayTry read callID live. A text session that calls startVoice() keeps reconnecting with a cursor, which the docs say a call's socket does not do. Either re-read callID at drop time or say in the docs that such a session keeps being resumed.
| approvals = [] | ||
| unsent = [] | ||
| // Asked before the session is stopped, so the router does not carry it on after. | ||
| await askingAgain?.value |
There was a problem hiding this comment.
consider: detach() and delete() wait on the re-ask request
finish awaits askingAgain for detach() and delete() too, though only close() needs the re-ask to land before the stop. Guarding it with if stopping stops them blocking on an HTTP call.
| await askingAgain?.value | |
| if stopping { await askingAgain?.value } |
9653db9 to
298f8ad
Compare
A text session's socket that drops is opened again after the last cursor, asking after the question waited on, with StreamCore's retry strategy, network monitor and app-state notifications deciding when. Readers of events(), approvals and running tools carry on across it, and a tool result that could not be sent goes on the next socket. A question the router interrupted on its way down is asked once more. URLSession reports the router's 1012 as 1005, so the code is read back from the close payload. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A fresh retry strategy for each reconnect: StreamCore's counts its failures in a class every copy shares, so the backoff never reset. - Calls waiting for approval are dropped when a reconnected socket missed frames: a restarted router no longer has them, and allowing one would run the tool for nothing. The router asks again about the ones it still has. - A reconnected socket's resumed cursor is taken only when complete is false, so a drop before the missed frames arrive asks for them again. - An interrupted question is asked again only if asked in the last five minutes, and closing waits for that request before stopping. - Declined results go through deliver, so a drop doesn't lose them. - The network wakes a reconnect only when it comes back, not on the monitor's first reading. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
URLSession never reads a connection that went away without a close as gone: receive() waits on, and the request timeout does not apply once the socket is open. A text session now: - asks for the router's healthchecks (#2811) and, once one has come, takes three intervals with nothing read as a lost connection. Nothing is timed before a socket's first, so a router without them is not taken for dead; - lets its socket go when the network goes, and makes no attempt to reopen it until the network is back. Only a change counts: a first reading of no network is not believed; - keeps its socket for one background task, then lets it go, and makes no attempt until the app is back. A socket that opens in the background with no time left is let go at once, and a session moved onto a call keeps its socket. The background task ends on every way out. A socket let go here ends its stream with socketClosed itself, for the opening it was decided for, so it reads as a drop and is resumed. Reviewed by a fresh agent: a first reading of no network stopped every reconnect, the app going to the background while a socket opened was missed, and two test checks could not fail. All fixed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The backoff is one strategy for the session, counted across reconnects and started over only after a socket stayed open 10 s (one healthcheck interval). Started over on every accepted upgrade, a router that took the socket and closed it at once was asked again with no wait, for good. - detach() and delete() no longer wait for a question being asked again: only close() stops the session, which is what that wait is for. - Say that a text session moved onto a call is still resumed: whether a socket is resumable is decided when it first opens, and the conversation outlives the call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
298f8ad to
85beb56
Compare
Why
When a text session's socket drops today, the conversation stops updating on this device. The network going, a while in the background, or a router deploy all leave
session.turnsfrozen andevents()finished, and the app has to notice and attach again. The router has been able to resume a socket since #1211 (2026-10-26), and Go resumes with it; Swift never did.Worse, some drops are never noticed at all.
URLSessionWebSocketTaskanswers the router's pings but never says one came. It never reads a connection that went away without a close as gone, whether out of a network's range or a router node lost. I checked this with a macOS command-line client against a local server that took the upgrade and went silent:receive()was still waiting after 20 s, even with a 3 s request timeout. I haven't checked it on iOS, but it's the same URLSession, and nothing in this PR depends on iOS behaving differently. Such a session stays "connected" and frozen.This uses the
healthcheckframe from #2811 (merged) for those silent drops. Until a router with #2811 is deployed, the healthcheck part does nothing: a router without it sends no healthchecks, and nothing is timed before the first one.It replaces the Swift skill paragraph #2794 wrote, which said reconnection was not built yet.
How it works
resumable=trueandhealthcheck=true.AgentSessionkeeps the lastcursora frame carried and skips theresumeda first socket starts with.request_idof the last question asked throughresponses.events().Recovery(Reconnection.swift) watches the network for as long as the session is followed, as StreamCore'sDefaultConnectionRecoveryHandlerdoes for Stream Chat.staysConnectedInBackground), so a reply in flight or a tool running can finish.startVoice()keeps its socket, as Video exempts a call in progress: the call keeps the app running, and the agent still calls its tools.close(),detach(), the socket stopping, and the session being released. One left running past its time gets the app killed.isAppActive. That reads false where there is noUIApplication, as in an app extension or a test, and would stop every reconnect there.SessionSocket.dropends the stream withsocketCloseditself, then cancels the task, and only for the opening it was decided for. A plainclose()would finish the stream quietly, which reads as the session ending.DefaultRetryStrategygives the backoff Stream Chat and Video use: the first retry at once, growing to 25 s.Reconnection.steadyAfter, one healthcheck interval), as Chat starts over once a socket is connected.WebSocketClientand ping controller are not used. Both wait for Stream's own health-check event, which the router never sends, and the client retries a refused upgrade forever.isConnectedis false, but readers ofevents()read on, approvals wait, and tools keep running.resumedreachesevents(). Whencompleteis false:resumed, it asks again about any it still waits on.Conversationwhen the receipt says the question is settled, or there is no receipt, so nothing streams forever.interruptedis asked once more under a new request id, as the contract says. That happens once only, and only if the question was asked in the last five minutes.close()waits for that request before stopping the session, so the router doesn't carry on a conversation that was just ended.resumednames the newest frame, and the missed frames follow it, so its cursor is taken only whencompleteis false. A drop before the missed frames arrive then asks for them again.closeReason.SessionSocket.closingreads the code back.Docs: no public API changes, so no CHANGELOG line. The Swift skill, the
sdkskill's resume paragraph and the README describe it. #2811's healthcheck note is corrected where it says Swift neither asks for healthchecks nor resumes..claude/skills/sdk/notes/2026-11-30-swift-resumes-text-sockets.mdtells the other SDKs what they'll meet, including starting the healthcheck watch again on every opening.Differences from Go
sdks/go/stream/accelerated.go:1257); Swift keeps it. The note flags it for Go, along with approvals, theresumedcursor and the re-ask's time limit.Not done
session.turnswhencompleteis false. Responses list oldest first and carry no turn ids to match, so it needs its own design. A conversation kept in Stream Chat is unaffected, since its views read the channel.replaceswith empty text may be the better retry; that's a contract question for the router.isConnectedfalse andfailurenil.tool_ranwas among the lost frames stays "running" in a reply that is otherwise finished. The existinginterruptedhandling leaves steps the same way, and Swift: a tool call's state is kept in its turn's steps #2800 rewrites these steps.Validation
SessionsTests, against a local server scripting each upgrade:complete;events();close(), ondetach(), and when the router ends the session;ConversationTestsfor settling the reply in flight.close()waiting for a re-ask in flight;main, in several runs in a row, since the suite runs tests concurrently.mainwith Swift: every published failure is an AgentsError #2798, whoseAgentsError(reporting:)replacesSelf.reasonbeside therecoverylines. It merges cleanly with the Swift PRs still open, Swift: every call by session id is on Sessions #2797 and Swift: a tool call's state is kept in its turn's steps #2800, and the three together passed 279 tests before Swift: every published failure is an AgentsError #2798 landed.swift_demoandswift_assistantbuilt at the first commit and weren't rebuilt after. Nothing public was added since;AgentEvent.Kind.healthcheckis Send a healthcheck a browser can read on the session events socket #2811's.Self-review
Two fresh reviewers read the diff, and the review bot read it after.
First round (resume):
resumedcursor skipping the missed frames;close();Second round (healthcheck, network, background):
The review bot:
detach()anddelete()waiting on a question being asked again;Everything is fixed except the spinning tool step, which is left as described above. My own testing found:
🤖 Generated with Claude Code