From 99f78a7d1f698b82bcda6787d18ed17720828c82 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 6 Aug 2026 02:58:14 -0700 Subject: [PATCH] perf(swift-ios): cut hot-path waste in networking, state, and caches - Cache EnvironmentStore's decoded document; publishes read it several times per second and previously hit disk + JSON decode every time - Memoize parsed ISO8601 dates in NativeFeatureClient; every publish re-parsed ~10 timestamps per thread through two formatters - Cache the mapped provider catalog per environment, invalidated on server config writes, instead of rebuilding hundreds of structs per publish - Sort activity logs by raw ISO string instead of parsing dates inside the comparator (O(n log n) formatter calls per detail rebuild) - Skip attachment hydration entirely for text-only threads - Dedupe emitConnection so per-event yields only publish transitions - Early-out acknowledgeDeliveredMessages when the outbox is empty - Cap terminal buffers at 256KB; unbounded append could OOM on verbose commands and re-layout megabyte strings per chunk - Key the markdown document cache by content fingerprint instead of the whole source string, stop inserting streaming intermediates (which churned completed messages out), and promote the final streamed render on completion instead of reparsing on the main thread - Throttle streaming markdown renders (150ms leading-edge) instead of a 200ms trailing debounce that never fired at an 80ms publish cadence, which left streaming messages as plain text for whole turns - Share JSONEncoder/Decoder.t3 instances (were rebuilt per call) and skip sortedKeys on throwaway JSONValue bridging encodes - Weak-capture the RPC connection loop and keepalive so released clients can actually deinit; snapshot dictionary keys before reentrant iteration in connected(); scope subscription Interrupts to the connection that assigned the request ID; add reconnect jitter - Cache DPoP JWK + thumbprint (SHA-256 per managed request before) and the proof encoder; reuse ISO8601 formatter in command builders - Replace crash-prone Dictionary(uniqueKeysWithValues:) on server-supplied IDs with first-wins reduces (model picker, agent awareness); retain per-thread states instead of full FeatureThread copies for transition signals; idle the home list timer to 60s when nothing is working Co-Authored-By: Claude Fable 5 --- apps/swift-ios/App/Cloud/T3ConnectDPoP.swift | 30 ++++- apps/swift-ios/App/NativeFeatureClient.swift | 121 +++++++++++++++--- .../App/Platform/PlatformAgentAwareness.swift | 6 +- .../App/Platform/PlatformFeedback.swift | 8 +- .../App/Platform/PlatformRootView.swift | 10 +- apps/swift-ios/Core/JSONValue.swift | 23 +++- apps/swift-ios/Core/Persistence.swift | 10 +- apps/swift-ios/Core/T3Client.swift | 8 +- apps/swift-ios/Core/WebSocketRPC.swift | 30 ++++- .../Features/Chat/MarkdownMessageView.swift | 32 ++++- .../Features/Chat/MarkdownRenderCache.swift | 38 +++++- .../Features/Root/FeatureRootModel.swift | 3 + .../Features/Workspace/DailyUXModels.swift | 6 +- .../Workspace/HomeThreadCollectionView.swift | 21 ++- .../xcshareddata/swiftpm/Package.resolved | 33 +++++ .../PlatformTests/PlatformFeedbackTests.swift | 11 +- 16 files changed, 318 insertions(+), 72 deletions(-) create mode 100644 apps/swift-ios/T3Code.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved diff --git a/apps/swift-ios/App/Cloud/T3ConnectDPoP.swift b/apps/swift-ios/App/Cloud/T3ConnectDPoP.swift index 1770df8a59..0257069a03 100644 --- a/apps/swift-ios/App/Cloud/T3ConnectDPoP.swift +++ b/apps/swift-ios/App/Cloud/T3ConnectDPoP.swift @@ -87,12 +87,24 @@ public actor T3ConnectDPoPSigner { account = "in-memory" } + /// The signing key never rotates (see type docs), so the derived JWK and + /// its SHA-256 thumbprint are stable and cached. Both are recomputed on + /// every managed request otherwise. + private var cachedJWK: T3ConnectDPoPPublicJWK? + private var cachedThumbprint: String? + public func publicJWK() throws -> T3ConnectDPoPPublicJWK { - try T3ConnectDPoPPublicJWK(publicKey: try loadPrivateKey().publicKey) + if let cachedJWK { return cachedJWK } + let jwk = try T3ConnectDPoPPublicJWK(publicKey: try loadPrivateKey().publicKey) + cachedJWK = jwk + return jwk } public func thumbprint() throws -> String { - try publicJWK().thumbprint + if let cachedThumbprint { return cachedThumbprint } + let thumbprint = try publicJWK().thumbprint + cachedThumbprint = thumbprint + return thumbprint } public func proof( @@ -107,7 +119,7 @@ public actor T3ConnectDPoPSigner { } let key = try loadPrivateKey() - let jwk = try T3ConnectDPoPPublicJWK(publicKey: key.publicKey) + let jwk = try publicJWK() let header = Header(typ: "dpop+jwt", alg: "ES256", jwk: jwk) let payload = Payload( htm: method.uppercased(), @@ -116,11 +128,9 @@ public actor T3ConnectDPoPSigner { iat: Int(issuedAt.timeIntervalSince1970.rounded(.down)), ath: accessToken.map(Self.accessTokenHash) ) - let encoder = JSONEncoder() - encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] guard - let headerPart = try? encoder.encode(header).base64URLEncodedString(), - let payloadPart = try? encoder.encode(payload).base64URLEncodedString() + let headerPart = try? Self.proofEncoder.encode(header).base64URLEncodedString(), + let payloadPart = try? Self.proofEncoder.encode(payload).base64URLEncodedString() else { throw T3ConnectDPoPError.encoding } @@ -218,6 +228,12 @@ public actor T3ConnectDPoPSigner { } } + private static let proofEncoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return encoder + }() + private struct Header: Encodable { let typ: String let alg: String diff --git a/apps/swift-ios/App/NativeFeatureClient.swift b/apps/swift-ios/App/NativeFeatureClient.swift index 92ffd09937..d7ff6630fb 100644 --- a/apps/swift-ios/App/NativeFeatureClient.swift +++ b/apps/swift-ios/App/NativeFeatureClient.swift @@ -365,6 +365,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, environmentClients.removeAll() shellsByEnvironmentID.removeAll() serverConfigsByEnvironmentID.removeAll() + providerCatalogCache.removeAll() archivedThreadsByEnvironmentID.removeAll() archivedShellThreadsByEnvironmentID.removeAll() projectEnvironmentIDs.removeAll() @@ -1840,6 +1841,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, if let coreSnapshot = event.snapshot { var snapshot = NativeWorkspaceMapper.terminal(coreSnapshot) snapshot.threadID = threadID + snapshot.buffer = Self.cappedTerminalBuffer(snapshot.buffer) terminalIDs[threadID] = coreSnapshot.terminalId terminalSnapshots[threadID] = snapshot return snapshot @@ -1850,6 +1852,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, switch event.type { case "output": snapshot.buffer.append(NativeWorkspaceMapper.terminalText(event.data ?? "")) + snapshot.buffer = Self.cappedTerminalBuffer(snapshot.buffer) case "exited": snapshot.state = .exited snapshot.exitCode = event.exitCode @@ -1869,6 +1872,20 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, return snapshot } + /// A verbose command can stream megabytes; the viewer only ever shows the + /// tail, so cap retained history to keep layout and memory bounded. + private static let terminalBufferLimit = 256 * 1024 + + private static func cappedTerminalBuffer(_ buffer: String) -> String { + guard buffer.utf8.count > terminalBufferLimit else { return buffer } + let tail = buffer.suffix(terminalBufferLimit) + // Trim to the next line boundary so the top of the view isn't a torn line. + if let newline = tail.firstIndex(of: "\n") { + return String(tail[tail.index(after: newline)...]) + } + return String(tail) + } + private func publishTerminal( _ snapshot: FeatureTerminalSnapshot, threadID: String @@ -1895,13 +1912,19 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, pollingTask = Task { [weak self] in do { await activeClient.connect() - guard let self, - self.isCurrentSession(client: activeClient, generation: generation) else { + guard self?.isCurrentSession( + client: activeClient, + generation: generation + ) == true else { return } - let sequence = self.latestShell?.snapshotSequence - for try await item in await activeClient.shellEvents(after: sequence) { + let sequence = self?.latestShell?.snapshotSequence + let events = await activeClient.shellEvents(after: sequence) + // Re-bind self per event instead of holding it strongly across + // the indefinite stream, so the client can deinit mid-stream. + for try await item in events { guard !Task.isCancelled, + let self, self.isCurrentSession( client: activeClient, generation: generation @@ -2015,7 +2038,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, switch event { case let .snapshot(config): self.latestServerConfig = config - self.serverConfigsByEnvironmentID[activeClient.environment.id] = config + self.setServerConfig(config, environmentID: activeClient.environment.id) case let .providerStatuses(providers): let settings = self.serverConfigsByEnvironmentID[ activeClient.environment.id @@ -2025,7 +2048,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, settings: settings ) self.latestServerConfig = config - self.serverConfigsByEnvironmentID[activeClient.environment.id] = config + self.setServerConfig(config, environmentID: activeClient.environment.id) case let .settingsUpdated(settings): let providers = self.serverConfigsByEnvironmentID[ activeClient.environment.id @@ -2035,7 +2058,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, settings: settings ) self.latestServerConfig = config - self.serverConfigsByEnvironmentID[activeClient.environment.id] = config + self.setServerConfig(config, environmentID: activeClient.environment.id) case .unrelated: continue } @@ -2598,6 +2621,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, serverConfigsByEnvironmentID = serverConfigsByEnvironmentID.filter { savedIDs.contains($0.key) } + providerCatalogCache = providerCatalogCache.filter { + savedIDs.contains($0.key) + } archivedThreadsByEnvironmentID = archivedThreadsByEnvironmentID.filter { savedIDs.contains($0.key) } @@ -2614,7 +2640,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, for load in loads { environmentClients[load.environment.id] = load.client if let config = load.config { - serverConfigsByEnvironmentID[load.environment.id] = config + setServerConfig(config, environmentID: load.environment.id) if load.environment.id == activeEnvironment?.id { latestServerConfig = config } @@ -3041,6 +3067,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, detail: String? = nil ) { guard let environment = activeEnvironment else { return } + // Shell event loops call this per event; only publish real transitions. + guard environmentConnectionStates[environment.id] != state + || environmentConnectionDetails[environment.id] != detail else { return } environmentConnectionStates[environment.id] = state environmentConnectionDetails[environment.id] = detail let connection = FeatureConnection( @@ -3103,7 +3132,8 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, ) { catalogues, environment in guard let shell = shellsByEnvironmentID[environment.id] else { return } catalogues[environment.id] = mapProviders( - shell, + environmentID: environment.id, + shell: shell, config: serverConfigsByEnvironmentID[environment.id] ) } @@ -3393,13 +3423,22 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, upsertMergedMessage(message, cache: cache) } + /// Wire timestamps are fixed-width ISO8601 UTC, so lexicographic order is + /// chronological order. Comparing raw strings avoids running the date + /// formatter O(n log n) times over a long activity log. + private func sortedByCreation( + _ activities: [OrchestrationActivity] + ) -> [OrchestrationActivity] { + activities.sorted { $0.createdAt < $1.createdAt } + } + private func seedWorkLogs( _ activities: [OrchestrationActivity], cache: NativeDetailRenderCache ) { cache.workLogsByGroupID.removeAll(keepingCapacity: true) cache.workLogActivityIDs.removeAll(keepingCapacity: true) - for activity in activities.sorted(by: { $0.createdAt < $1.createdAt }) + for activity in sortedByCreation(activities) where NativeWorkLogAccumulator.accepts(activity) { cache.workLogActivityIDs.insert(activity.id) let groupID = activity.turnId ?? "unscoped" @@ -3587,9 +3626,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, environmentID: environment.id, wireID: thread.id ) - for activity in thread.activities.sorted(by: { - parseDate($0.createdAt) < parseDate($1.createdAt) - }) { + for activity in sortedByCreation(thread.activities) { let requestID = activity.payload["requestId"]?.stringValue let uiRequestID = requestID.map { FeatureScopedID.approval(environmentID: environment.id, wireID: $0) @@ -3642,9 +3679,7 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, environmentID: environment.id, wireID: thread.id ) - for activity in thread.activities.sorted(by: { - parseDate($0.createdAt) < parseDate($1.createdAt) - }) { + for activity in sortedByCreation(thread.activities) { let requestID = activity.payload["requestId"]?.stringValue let uiRequestID = requestID.map { FeatureScopedID.input(environmentID: environment.id, wireID: $0) @@ -3769,12 +3804,38 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, .default } + /// The mapped catalog for the config-driven branch of mapProviders. Every + /// publish rebuilds the snapshot, but the catalog only changes when a new + /// server config arrives, so mapping hundreds of models per publish is + /// wasted work. Entries are invalidated wherever + /// serverConfigsByEnvironmentID is written. + private var providerCatalogCache: [String: [FeatureProvider]] = [:] + + /// Single write path for server configs so the provider catalog cache can + /// never go stale against the config that feeds it. + private func setServerConfig(_ config: ServerConfigSnapshot, environmentID: String) { + serverConfigsByEnvironmentID[environmentID] = config + providerCatalogCache[environmentID] = nil + } + private func mapProviders( - _ shell: OrchestrationShellSnapshot, + environmentID: String, + shell: OrchestrationShellSnapshot, config: ServerConfigSnapshot? ) -> [FeatureProvider] { if let providers = config?.providers, !providers.isEmpty { - return Self.normalizedProviders(providers.map { provider in + if let cached = providerCatalogCache[environmentID] { return cached } + let mapped = mapConfigProviders(providers) + providerCatalogCache[environmentID] = mapped + return mapped + } + return mapShellFallbackProviders(shell) + } + + private func mapConfigProviders( + _ providers: [ServerProviderSnapshot] + ) -> [FeatureProvider] { + Self.normalizedProviders(providers.map { provider in FeatureProvider( id: provider.instanceId, name: provider.displayName ?? providerDisplayName(provider.driver), @@ -3825,8 +3886,13 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, } ) }) - } + } + /// Without a server config the catalog is inferred from selections in the + /// shell, which is cheap enough to rebuild per publish. + private func mapShellFallbackProviders( + _ shell: OrchestrationShellSnapshot + ) -> [FeatureProvider] { var modelsByProvider: [String: Set] = [:] for selection in shell.projects.compactMap(\.defaultModelSelection) + shell.threads.map(\.modelSelection) { @@ -4163,6 +4229,9 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, .filter { $0.mimeType.hasPrefix("image/") } .map(\.id) ) + // Text-only threads refresh every couple of seconds; skip the resolve + // pass and the full message walk when there is nothing to hydrate. + guard !imageIDs.isEmpty else { return detail } let missingIDs = Array(imageIDs.filter { cachedAttachmentURL(for: $0, environmentID: environmentID) == nil }) @@ -4346,11 +4415,21 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, parseValidDate(value) ?? .distantPast } + /// Every publish re-maps every thread, and most timestamps are unchanged + /// between publishes, so parsed dates are memoized. ISO8601DateFormatter + /// costs microseconds per call, which adds up to milliseconds per publish + /// across hundreds of threads during streaming. private func parseValidDate(_ value: String) -> Date? { - Self.fractionalDateFormatter.date(from: value) - ?? Self.dateFormatter.date(from: value) + if let cached = parsedDates[value] { return cached } + guard let parsed = Self.fractionalDateFormatter.date(from: value) + ?? Self.dateFormatter.date(from: value) else { return nil } + if parsedDates.count >= 4096 { parsedDates.removeAll(keepingCapacity: true) } + parsedDates[value] = parsed + return parsed } + private var parsedDates: [String: Date] = [:] + private static let settingsKey = "swift-ios.feature-settings.v1" private static let fractionalDateFormatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() diff --git a/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift b/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift index 0f76cb83ce..711b7cb019 100644 --- a/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift +++ b/apps/swift-ios/App/Platform/PlatformAgentAwareness.swift @@ -16,7 +16,11 @@ enum PlatformAgentAwarenessProjection { snapshot: FeatureSnapshot, now: Date = .now ) -> T3RelayAgentActivityAggregateState { - let projects = Dictionary(uniqueKeysWithValues: snapshot.projects.map { ($0.id, $0) }) + // Defensive against duplicate project IDs in aggregate snapshots; this + // runs on every snapshot revision, so it must never trap. + let projects = snapshot.projects.reduce(into: [String: FeatureProject]()) { + $0[$1.id] = $0[$1.id] ?? $1 + } let eligible = snapshot.threads.filter { thread in guard !thread.isArchived else { return false } if isActive(thread.state) { return true } diff --git a/apps/swift-ios/App/Platform/PlatformFeedback.swift b/apps/swift-ios/App/Platform/PlatformFeedback.swift index eca0ce0e06..4f95ea712d 100644 --- a/apps/swift-ios/App/Platform/PlatformFeedback.swift +++ b/apps/swift-ios/App/Platform/PlatformFeedback.swift @@ -12,20 +12,22 @@ struct PlatformThreadSignal: Equatable, Sendable { } enum PlatformThreadTransitionClassifier { + /// Previous states are kept as a bare `[id: state]` map so each home + /// revision retains a dictionary of enums, not a copy of every thread. static func signals( - previous: [String: FeatureThread]?, + previous: [String: FeatureThreadState]?, current: [FeatureThread] ) -> [PlatformThreadSignal] { guard let previous else { return [] } return current.compactMap { thread in - guard let old = previous[thread.id], old.state != thread.state else { return nil } + guard let oldState = previous[thread.id], oldState != thread.state else { return nil } let kind: PlatformFeedbackKind? = switch thread.state { case .waitingForApproval, .waitingForInput: .warning case .failed: .error - case .completed where old.state == .working || old.state == .queued: + case .completed where oldState == .working || oldState == .queued: .success default: nil diff --git a/apps/swift-ios/App/Platform/PlatformRootView.swift b/apps/swift-ios/App/Platform/PlatformRootView.swift index 98150c3577..294aa9fc9c 100644 --- a/apps/swift-ios/App/Platform/PlatformRootView.swift +++ b/apps/swift-ios/App/Platform/PlatformRootView.swift @@ -6,7 +6,7 @@ struct PlatformRootView: View { @State private var navigationRequest: FeatureWorkspaceNavigationRequest? @State private var pendingRoute: PlatformRoute? - @State private var previousThreads: [String: FeatureThread]? + @State private var previousThreadStates: [String: FeatureThreadState]? @State private var lastNotificationPreference: Bool? @State private var incomingShareCoordinator = PlatformIncomingShareCoordinator() @State private var incomingShareNeedsProject = false @@ -310,12 +310,14 @@ struct PlatformRootView: View { /// Home revisions are coalesced by FeatureRootModel, so this performs one /// bounded scan per meaningful snapshot change rather than on every render. private func processThreadChanges() { - let current = Dictionary(uniqueKeysWithValues: model.snapshot.threads.map { ($0.id, $0) }) + let current = model.snapshot.threads.reduce(into: [String: FeatureThreadState]()) { + $0[$1.id] = $1.state + } let signals = PlatformThreadTransitionClassifier.signals( - previous: previousThreads, + previous: previousThreadStates, current: model.snapshot.threads ) - previousThreads = current + previousThreadStates = current PlatformRecentThreadStore.shared.update(from: model.snapshot.threads) synchronizeAgentAwareness() diff --git a/apps/swift-ios/Core/JSONValue.swift b/apps/swift-ios/Core/JSONValue.swift index afe65c00b0..c149d9a190 100644 --- a/apps/swift-ios/Core/JSONValue.swift +++ b/apps/swift-ios/Core/JSONValue.swift @@ -81,20 +81,31 @@ public enum JSONValue: Codable, Equatable, Sendable { _ type: T.Type, decoder: JSONDecoder = .t3 ) throws -> T { - try decoder.decode(type, from: JSONEncoder.t3.encode(self)) + // The intermediate bytes are discarded immediately, so skip the + // deterministic-output formatting the wire encoder pays for. + try decoder.decode(type, from: JSONEncoder.t3Intermediate.encode(self)) } } +// Encoders and decoders are configured once and never mutated afterwards, so +// shared instances are safe for concurrent use and avoid rebuilding coder +// state on every RPC message. extension JSONEncoder { - public static var t3: JSONEncoder { + /// Deterministic output for wire payloads. + public static let t3: JSONEncoder = { let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] return encoder - } + }() + + /// Throwaway intermediate encoding (JSONValue -> concrete type bridging). + static let t3Intermediate: JSONEncoder = { + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + return encoder + }() } extension JSONDecoder { - public static var t3: JSONDecoder { - JSONDecoder() - } + public static let t3 = JSONDecoder() } diff --git a/apps/swift-ios/Core/Persistence.swift b/apps/swift-ios/Core/Persistence.swift index bfc1c8fdcb..02c4a94605 100644 --- a/apps/swift-ios/Core/Persistence.swift +++ b/apps/swift-ios/Core/Persistence.swift @@ -125,6 +125,10 @@ public actor EnvironmentStore { public let fileURL: URL + /// Snapshot publishes read the catalog several times a second, so the + /// decoded document is cached and invalidated by writes on this actor. + private var cached: Document? + public init(fileURL: URL? = nil) { if let fileURL { self.fileURL = fileURL @@ -187,11 +191,14 @@ public actor EnvironmentStore { } private func loadDocument() throws -> Document { + if let cached { return cached } guard FileManager.default.fileExists(atPath: fileURL.path) else { return Document(version: 1, environments: [], activeEnvironmentID: nil) } let data = try Data(contentsOf: fileURL) - return try JSONDecoder.t3.decode(Document.self, from: data) + let document = try JSONDecoder.t3.decode(Document.self, from: data) + cached = document + return document } private func save(_ document: Document) throws { @@ -200,5 +207,6 @@ public actor EnvironmentStore { withIntermediateDirectories: true ) try JSONEncoder.t3.encode(document).write(to: fileURL, options: .atomic) + cached = document } } diff --git a/apps/swift-ios/Core/T3Client.swift b/apps/swift-ios/Core/T3Client.swift index 9e74e8c10e..d2d15e7dba 100644 --- a/apps/swift-ios/Core/T3Client.swift +++ b/apps/swift-ios/Core/T3Client.swift @@ -1428,7 +1428,7 @@ public enum OrchestrationCommands { "type": .string("thread.snooze"), "commandId": .string(commandID), "threadId": .string(threadID), - "snoozedUntil": .string(ISO8601DateFormatter().string(from: until)), + "snoozedUntil": .string(iso8601.string(from: until)), ]) } return .object([ @@ -1490,6 +1490,10 @@ public enum OrchestrationCommands { } public static func now() -> String { - ISO8601DateFormatter().string(from: Date()) + iso8601.string(from: Date()) } + + /// ISO8601DateFormatter is expensive to construct and thread-safe to use; + /// `now()` runs as the default argument of nearly every outbound command. + static let iso8601 = ISO8601DateFormatter() } diff --git a/apps/swift-ios/Core/WebSocketRPC.swift b/apps/swift-ios/Core/WebSocketRPC.swift index c7a101bbb8..1388e323d1 100644 --- a/apps/swift-ios/Core/WebSocketRPC.swift +++ b/apps/swift-ios/Core/WebSocketRPC.swift @@ -166,6 +166,9 @@ public actor WebSocketRPCClient { let payload: JSONValue let reconnect: Bool var requestID: Int? + /// The connection that assigned `requestID`. Request IDs are reissued + /// after reconnects, so an Interrupt is only valid on this connection. + var requestConnectionID: UUID? let yield: @Sendable (JSONValue) -> Void let finish: @Sendable (Error?) -> Void } @@ -207,7 +210,9 @@ public actor WebSocketRPCClient { guard loopTask == nil else { return } let id = UUID() loopID = id - loopTask = Task { await self.connectionLoop(id: id) } + // Weak: the loop must not keep a released client (and its socket plus + // keepalive heartbeat) alive forever; deinit cancels it as a backstop. + loopTask = Task { [weak self] in await self?.connectionLoop(id: id) } } public func isConnected() -> Bool { @@ -352,7 +357,10 @@ public actor WebSocketRPCClient { } guard isCurrentConnectionLoop(loopID), !Task.isCancelled else { break } retry += 1 - let delay = min(5.0, 0.35 * pow(1.7, Double(retry - 1))) + // Jitter desynchronizes reconnects across environments so a + // server restart doesn't trigger simultaneous ticket mints. + let backoff = min(5.0, 0.35 * pow(1.7, Double(retry - 1))) + let delay = backoff * Double.random(in: 0.5...1.0) try? await Task.sleep(for: .seconds(delay)) } } @@ -368,12 +376,14 @@ public actor WebSocketRPCClient { private func connected() async { keepaliveTask?.cancel() - keepaliveTask = Task { await self.keepaliveLoop() } - for id in unary.keys { + keepaliveTask = Task { [weak self] in await self?.keepaliveLoop() } + // Snapshot the keys: the sends suspend, and reentrant completions or + // failures mutate these dictionaries mid-iteration. + for id in Array(unary.keys) { await sendUnary(id) } subscriptionByRequestID.removeAll() - for id in subscriptions.keys { + for id in Array(subscriptions.keys) { await sendSubscription(id) } } @@ -394,8 +404,9 @@ public actor WebSocketRPCClient { subscriptions.removeValue(forKey: id) subscription.finish(RPCError.disconnected) } - for id in subscriptions.keys { + for id in Array(subscriptions.keys) { subscriptions[id]?.requestID = nil + subscriptions[id]?.requestConnectionID = nil } await closingConnection?.close() } @@ -478,6 +489,7 @@ public actor WebSocketRPCClient { do { try await connection.send(JSONEncoder.t3.encode(envelope)) subscription.requestID = requestID + subscription.requestConnectionID = connectionID subscriptions[subscriptionID] = subscription subscriptionByRequestID[requestID] = subscriptionID } catch { @@ -491,7 +503,11 @@ public actor WebSocketRPCClient { guard let subscription = subscriptions.removeValue(forKey: id) else { return } if let requestID = subscription.requestID { subscriptionByRequestID.removeValue(forKey: requestID) - try? await sendControl("Interrupt", requestID: requestID) + // A termination racing a reconnect must not interrupt whichever + // subscription now owns this request ID on the new connection. + if subscription.requestConnectionID == connectionID { + try? await sendControl("Interrupt", requestID: requestID) + } } } diff --git a/apps/swift-ios/Features/Chat/MarkdownMessageView.swift b/apps/swift-ios/Features/Chat/MarkdownMessageView.swift index eba2580c58..29584d2333 100644 --- a/apps/swift-ios/Features/Chat/MarkdownMessageView.swift +++ b/apps/swift-ios/Features/Chat/MarkdownMessageView.swift @@ -12,6 +12,7 @@ struct MarkdownMessageView: View { private let revision: MarkdownContentRevision private let isStreaming: Bool @State private var renderedDocument: MarkdownRenderedDocument? + @State private var lastStreamRenderAt: Date? @State private var isSelectingText = false init(_ source: String, isStreaming: Bool = false) { @@ -63,6 +64,12 @@ struct MarkdownMessageView: View { } .task(id: RenderRequest(revision: revision, isStreaming: isStreaming)) { if !isStreaming { + // Streaming -> complete usually keeps the final text; promote + // the last streamed render instead of reparsing synchronously. + if let renderedDocument, renderedDocument.revision == revision { + MarkdownRenderCache.shared.promote(renderedDocument) + return + } renderedDocument = MarkdownRenderCache.shared.documentImmediately(for: revision) return } @@ -72,18 +79,33 @@ struct MarkdownMessageView: View { return } - do { - try await Task.sleep(for: .milliseconds(200)) - } catch { - return + // Streamed revisions arrive faster than a trailing debounce could + // ever fire, so throttle instead: render right away when the last + // render is old enough, otherwise wait out the remainder. The + // message stays live markdown while streaming instead of falling + // back to plain text for the whole turn. + let throttle: Duration = .milliseconds(150) + if let lastStreamRenderAt { + let elapsed = Duration.seconds(-lastStreamRenderAt.timeIntervalSinceNow) + if elapsed < throttle { + do { + try await Task.sleep(for: throttle - elapsed) + } catch { + return + } + } } guard !Task.isCancelled else { return } - guard let rendered = await MarkdownRenderCache.shared.document(for: revision), + guard let rendered = await MarkdownRenderCache.shared.document( + for: revision, + isIntermediate: true + ), !Task.isCancelled, rendered.revision == revision else { return } + lastStreamRenderAt = .now renderedDocument = rendered } } diff --git a/apps/swift-ios/Features/Chat/MarkdownRenderCache.swift b/apps/swift-ios/Features/Chat/MarkdownRenderCache.swift index d335a68b94..583a680ba2 100644 --- a/apps/swift-ios/Features/Chat/MarkdownRenderCache.swift +++ b/apps/swift-ios/Features/Chat/MarkdownRenderCache.swift @@ -142,8 +142,15 @@ final class MarkdownRenderCache: @unchecked Sendable { inlineRuns.totalCostLimit = inlineCostLimit } + /// Keys use the precomputed fingerprint instead of the full source so each + /// lookup avoids bridging and hashing the entire message body. The stored + /// document's revision equality check below makes collisions safe. + private func cacheKey(for revision: MarkdownContentRevision) -> NSString { + "\(revision.fingerprint):\(revision.utf8Count)" as NSString + } + func cachedDocument(for revision: MarkdownContentRevision) -> MarkdownRenderedDocument? { - let document = documents.object(forKey: revision.source as NSString) + let document = documents.object(forKey: cacheKey(for: revision)) return document?.revision == revision ? document : nil } @@ -159,13 +166,20 @@ final class MarkdownRenderCache: @unchecked Sendable { guard let document = renderDocument(revision) else { return nil } documents.setObject( document, - forKey: revision.source as NSString, + forKey: cacheKey(for: revision), cost: documentCost(document) ) return document } - func document(for revision: MarkdownContentRevision) async -> MarkdownRenderedDocument? { + /// Set `isIntermediate` for in-progress streaming revisions: they are + /// superseded within milliseconds, and inserting each one would churn + /// completed messages out of the bounded document cache. Unchanged inline + /// runs are still shared through the inline cache either way. + func document( + for revision: MarkdownContentRevision, + isIntermediate: Bool = false + ) async -> MarkdownRenderedDocument? { guard !Task.isCancelled else { return nil } if let cached = cachedDocument(for: revision) { return cached @@ -181,12 +195,26 @@ final class MarkdownRenderCache: @unchecked Sendable { releaseWaiter(for: revision, waiterID: waiterID, cancelIfLast: true) } guard !Task.isCancelled, let document else { return nil } + if !isIntermediate { + documents.setObject( + document, + forKey: cacheKey(for: revision), + cost: documentCost(document) + ) + } + return document + } + + /// Adopts a document that was rendered as a streaming intermediate. Called + /// when its message completes so the final revision becomes a durable + /// cache entry without reparsing on the main thread. + func promote(_ document: MarkdownRenderedDocument) { + guard cachedDocument(for: document.revision) == nil else { return } documents.setObject( document, - forKey: revision.source as NSString, + forKey: cacheKey(for: document.revision), cost: documentCost(document) ) - return document } func removeAll() { diff --git a/apps/swift-ios/Features/Root/FeatureRootModel.swift b/apps/swift-ios/Features/Root/FeatureRootModel.swift index 52f0841500..e1ccd519f9 100644 --- a/apps/swift-ios/Features/Root/FeatureRootModel.swift +++ b/apps/swift-ios/Features/Root/FeatureRootModel.swift @@ -900,6 +900,9 @@ public final class FeatureRootModel { } private func acknowledgeDeliveredMessages(_ messages: [FeatureMessage]) { + // Runs on every detail publish; skip the full message-ID scan in the + // common case where nothing is waiting in the outbox. + guard !pendingSubmissionsByID.isEmpty else { return } // Local optimistic rows reuse the final message ID but are not proof // that the server accepted the turn. Only authoritative, non-queued // rows can retire a durable outbox entry. diff --git a/apps/swift-ios/Features/Workspace/DailyUXModels.swift b/apps/swift-ios/Features/Workspace/DailyUXModels.swift index 1782468d36..48e1ee68e8 100644 --- a/apps/swift-ios/Features/Workspace/DailyUXModels.swift +++ b/apps/swift-ios/Features/Workspace/DailyUXModels.swift @@ -523,7 +523,11 @@ struct DailyUXModelCatalog { all = matches favorites = matches.filter { favoriteIDs.contains($0.id) } - let byID = Dictionary(uniqueKeysWithValues: matches.map { ($0.id, $0) }) + // Provider catalogs can repeat an ID (see matchingThreads above); keep + // the first occurrence instead of trapping on duplicate keys. + let byID = matches.reduce(into: [String: DailyUXModelOption]()) { + $0[$1.id] = $0[$1.id] ?? $1 + } recents = recentIDs.compactMap { byID[$0] }.filter { !favoriteIDs.contains($0.id) } providerGroups = available.compactMap { provider in diff --git a/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift b/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift index f15772a85e..365b5ec2e5 100644 --- a/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift +++ b/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift @@ -75,6 +75,7 @@ struct HomeThreadCollectionView: UIViewRepresentable { private weak var collectionView: UICollectionView? private var timer: Timer? private var timerTick = 0 + private var timerInterval: TimeInterval = 0 init(parent: HomeThreadCollectionView) { self.parent = parent @@ -427,20 +428,34 @@ struct HomeThreadCollectionView: UIViewRepresentable { return actions } + /// Working rows show a live per-second duration, so they need a 1 Hz + /// tick. Without any, relative ages only change by the minute, and the + /// timer idles down to match instead of waking the main thread every + /// second for the lifetime of the sidebar. private func startTimer() { + let interval: TimeInterval = itemsByID.values.contains { + if case let .thread(thread, _, _, _, _) = $0 { + return thread.homeStatus == .working + } + return false + } ? 1 : 60 + + if timer != nil, timerInterval == interval { return } invalidateTimer() - timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in + timerInterval = interval + timerTick = 0 + timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.refreshVisibleTimes() } } - timer?.tolerance = 0.12 + timer?.tolerance = interval * 0.12 } private func refreshVisibleTimes() { guard let collectionView, let dataSource else { return } timerTick = (timerTick + 1) % 60 - let refreshRelativeAges = timerTick == 0 + let refreshRelativeAges = timerInterval >= 60 || timerTick == 0 let now = Date.now for indexPath in collectionView.indexPathsForVisibleItems { diff --git a/apps/swift-ios/T3Code.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/apps/swift-ios/T3Code.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000000..f9969cee64 --- /dev/null +++ b/apps/swift-ios/T3Code.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,33 @@ +{ + "originHash" : "0da9fa23290c75a06cf2d88ffeab37061a648ea0656f8262ec633d415fa7466a", + "pins" : [ + { + "identity" : "clerk-ios", + "kind" : "remoteSourceControl", + "location" : "https://github.com/clerk/clerk-ios.git", + "state" : { + "revision" : "d0a5f2231dcb4b66e091a514ce2d0bead9056404", + "version" : "1.2.0" + } + }, + { + "identity" : "nuke", + "kind" : "remoteSourceControl", + "location" : "https://github.com/kean/Nuke.git", + "state" : { + "revision" : "63a8fcbd6621340a2410bc3e9575ac97058615f4", + "version" : "13.0.6" + } + }, + { + "identity" : "phonenumberkit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/marmelroy/PhoneNumberKit", + "state" : { + "revision" : "169ab10234347fb19b37441f2867ace896a284b0", + "version" : "4.3.0" + } + } + ], + "version" : 3 +} diff --git a/apps/swift-ios/Tests/PlatformTests/PlatformFeedbackTests.swift b/apps/swift-ios/Tests/PlatformTests/PlatformFeedbackTests.swift index 23dd610b9c..136b8899f1 100644 --- a/apps/swift-ios/Tests/PlatformTests/PlatformFeedbackTests.swift +++ b/apps/swift-ios/Tests/PlatformTests/PlatformFeedbackTests.swift @@ -13,13 +13,12 @@ struct PlatformFeedbackTests { @Test func classifiesAttentionFailureAndCompletionTransitions() { - let previousThreads = [ - thread(id: "approval", state: .working), - thread(id: "failure", state: .working), - thread(id: "complete", state: .working), - thread(id: "idle-complete", state: .idle), + let previous: [String: FeatureThreadState] = [ + "approval": .working, + "failure": .working, + "complete": .working, + "idle-complete": .idle, ] - let previous = Dictionary(uniqueKeysWithValues: previousThreads.map { ($0.id, $0) }) let current = [ thread(id: "approval", state: .waitingForApproval), thread(id: "failure", state: .failed),