From 3de618774381d6547a411a26ff24628218d6b106 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 3 Oct 2026 06:53:24 -0400 Subject: [PATCH 01/10] perf(ios): coalesce Live Activity updates to about once per second (EXT-9) Streamed tokens, reasoning, and tool churn now write ActivityKit at most once per second with the newest state. Status changes, approval, stale, and end bypass the window and supersede any pending write, so a phase change is never delayed or overwritten by an older coalesced update. Co-Authored-By: Claude Opus 5.5 --- ios/AidenOnTheGo.xcodeproj/project.pbxproj | 8 + .../AidenLatestValueThrottle.swift | 109 +++++++++++ .../AidenRemoteLiveActivityManager.swift | 65 +++++-- .../AidenStreamingPerformanceTests.swift | 171 ++++++++++++++++++ 4 files changed, 342 insertions(+), 11 deletions(-) create mode 100644 ios/AidenOnTheGo/LiveActivities/AidenLatestValueThrottle.swift create mode 100644 ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift diff --git a/ios/AidenOnTheGo.xcodeproj/project.pbxproj b/ios/AidenOnTheGo.xcodeproj/project.pbxproj index f98cbf27d4..37a0e6656f 100644 --- a/ios/AidenOnTheGo.xcodeproj/project.pbxproj +++ b/ios/AidenOnTheGo.xcodeproj/project.pbxproj @@ -22,6 +22,7 @@ A0D700000000000000000003 /* AidenChatCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000013 /* AidenChatCache.swift */; }; A0D700000000000000000004 /* AidenChatFeature.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000014 /* AidenChatFeature.swift */; }; A0D700000000000000000005 /* AidenChatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000015 /* AidenChatTests.swift */; }; + A0F100000000000000000021 /* AidenStreamingPerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0F100000000000000000020 /* AidenStreamingPerformanceTests.swift */; }; A0D800000000000000000001 /* AidenAppearance.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D800000000000000000011 /* AidenAppearance.swift */; }; A0D800000000000000000004 /* AidenChromeGlass.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D800000000000000000014 /* AidenChromeGlass.swift */; }; A0D800000000000000000003 /* AidenVoiceInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D800000000000000000013 /* AidenVoiceInput.swift */; }; @@ -57,6 +58,7 @@ A04500000000000000000007 /* AidenLiveActivityWidget.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = A04500000000000000000017 /* AidenLiveActivityWidget.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; A04500000000000000000008 /* aiden-sidebar-logo.png in Resources */ = {isa = PBXBuildFile; fileRef = A04500000000000000000018 /* aiden-sidebar-logo.png */; }; A0DB00000000000000000001 /* AidenRemoteLiveActivityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0DB00000000000000000011 /* AidenRemoteLiveActivityManager.swift */; }; + A0F100000000000000000011 /* AidenLatestValueThrottle.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0F100000000000000000010 /* AidenLatestValueThrottle.swift */; }; A0DB00000000000000000002 /* AidenNativeIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0DB00000000000000000012 /* AidenNativeIntegrationTests.swift */; }; B07200000000000000000001 /* AidenBotPrototypeSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B07200000000000000000011 /* AidenBotPrototypeSnapshotTests.swift */; }; B07300000000000000000001 /* AidenBot.swift in Sources */ = {isa = PBXBuildFile; fileRef = B07300000000000000000011 /* AidenBot.swift */; }; @@ -144,6 +146,7 @@ A0D700000000000000000012 /* AidenSSEParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenSSEParser.swift; sourceTree = ""; }; A0D700000000000000000013 /* AidenChatCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatCache.swift; sourceTree = ""; }; A0D700000000000000000014 /* AidenChatFeature.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatFeature.swift; sourceTree = ""; }; + A0F100000000000000000020 /* AidenStreamingPerformanceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenStreamingPerformanceTests.swift; sourceTree = ""; }; A0D700000000000000000015 /* AidenChatTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatTests.swift; sourceTree = ""; }; A0D800000000000000000011 /* AidenAppearance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenAppearance.swift; sourceTree = ""; }; A0D800000000000000000013 /* AidenVoiceInput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenVoiceInput.swift; sourceTree = ""; }; @@ -201,6 +204,7 @@ A04500000000000000000014 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; A04500000000000000000018 /* aiden-sidebar-logo.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "aiden-sidebar-logo.png"; path = AidenOnTheGo/Resources/Assets.xcassets/AidenSidebarLogo.imageset/aiden-sidebar-logo.png; sourceTree = SOURCE_ROOT; }; A04500000000000000000017 /* AidenLiveActivityWidget.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = AidenLiveActivityWidget.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + A0F100000000000000000010 /* AidenLatestValueThrottle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenLatestValueThrottle.swift; sourceTree = ""; }; A0DB00000000000000000011 /* AidenRemoteLiveActivityManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenRemoteLiveActivityManager.swift; sourceTree = ""; }; A0DB00000000000000000012 /* AidenNativeIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenNativeIntegrationTests.swift; sourceTree = ""; }; B07200000000000000000011 /* AidenBotPrototypeSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenBotPrototypeSnapshotTests.swift; sourceTree = ""; }; @@ -314,6 +318,7 @@ A0D000000000000000000013 /* AidenRemotePhase0Tests.swift */, A0D600000000000000000013 /* AidenRemoteClientTests.swift */, A0D700000000000000000015 /* AidenChatTests.swift */, + A0F100000000000000000020 /* AidenStreamingPerformanceTests.swift */, A0D800000000000000000012 /* AidenAppearanceV1.json */, A0D000000000000000000014 /* AidenRemoteContractV1.json */, A0D000000000000000000015 /* AidenManualPairingVectorV1.json */, @@ -502,6 +507,7 @@ A04500000000000000000010 /* AgentRunActivityAttributes.swift */, A04500000000000000000011 /* AidenDeepLink.swift */, A0DB00000000000000000011 /* AidenRemoteLiveActivityManager.swift */, + A0F100000000000000000010 /* AidenLatestValueThrottle.swift */, ); path = LiveActivities; sourceTree = ""; @@ -733,6 +739,7 @@ A04500000000000000000001 /* AgentRunActivityAttributes.swift in Sources */, A04500000000000000000002 /* AidenDeepLink.swift in Sources */, A0DB00000000000000000001 /* AidenRemoteLiveActivityManager.swift in Sources */, + A0F100000000000000000011 /* AidenLatestValueThrottle.swift in Sources */, A710739233F64F4FA4C2B700 /* ComposerVoiceInputController.swift in Sources */, A711739233F64F4FA4C2B700 /* AidenAttachmentPicker.swift in Sources */, A712739233F64F4FA4C2B700 /* AidenAttachmentCamera.swift in Sources */, @@ -781,6 +788,7 @@ A0D000000000000000000003 /* AidenRemotePhase0Tests.swift in Sources */, A0D600000000000000000003 /* AidenRemoteClientTests.swift in Sources */, A0D700000000000000000005 /* AidenChatTests.swift in Sources */, + A0F100000000000000000021 /* AidenStreamingPerformanceTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/ios/AidenOnTheGo/LiveActivities/AidenLatestValueThrottle.swift b/ios/AidenOnTheGo/LiveActivities/AidenLatestValueThrottle.swift new file mode 100644 index 0000000000..0f4d194511 --- /dev/null +++ b/ios/AidenOnTheGo/LiveActivities/AidenLatestValueThrottle.swift @@ -0,0 +1,109 @@ +import Foundation + +/// Coalesces a high-frequency value stream into at most one delivery per +/// `interval`, always delivering the newest value. Urgent values bypass the +/// window and discard any older pending value, so phase changes are never +/// delayed behind (or overwritten by) a stale coalesced update. +/// +/// The clock and sleep are injected so the window is testable without waiting +/// on wall time. +@MainActor +final class AidenLatestValueThrottle { + typealias Deliver = @MainActor (Value) async -> Void + + private let interval: Duration + private let now: @MainActor () -> ContinuousClock.Instant + private let sleep: @MainActor (Duration) async throws -> Void + private let deliver: Deliver + + private var lastDelivered: Value? + private var lastDeliveredAt: ContinuousClock.Instant? + private(set) var pendingValue: Value? + private var flushTask: Task? + private var generation = 0 + + init( + interval: Duration, + now: @escaping @MainActor () -> ContinuousClock.Instant = { ContinuousClock.now }, + sleep: @escaping @MainActor (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, + deliver: @escaping Deliver + ) { + self.interval = interval + self.now = now + self.sleep = sleep + self.deliver = deliver + } + + /// Records a value that reached the consumer outside the throttle, such as + /// the initial content passed to `Activity.request`. + func markDelivered(_ value: Value) { + lastDelivered = value + lastDeliveredAt = now() + } + + /// Delivers now when the window is open; otherwise keeps only the newest + /// value and schedules a single trailing delivery when the window closes. + func submit(_ value: Value) async { + if pendingValue == nil, value == lastDelivered { return } + let current = now() + if let lastDeliveredAt { + let elapsed = current - lastDeliveredAt + if elapsed < interval { + pendingValue = value + scheduleFlush(after: interval - elapsed) + return + } + } + cancelPending() + await deliverNow(value) + } + + /// Delivers immediately, superseding any pending coalesced value. + func submitUrgent(_ value: Value) async { + cancelPending() + await deliverNow(value) + } + + /// Drops any pending value without delivering it. + func cancel() { + cancelPending() + } + + /// Waits for a scheduled trailing delivery, if any. Test seam. + func waitForScheduledFlush() async { + await flushTask?.value + } + + private func cancelPending() { + pendingValue = nil + generation &+= 1 + flushTask?.cancel() + flushTask = nil + } + + private func deliverNow(_ value: Value) async { + lastDelivered = value + lastDeliveredAt = now() + await deliver(value) + } + + private func scheduleFlush(after delay: Duration) { + guard flushTask == nil else { return } + generation &+= 1 + let scheduledGeneration = generation + let sleep = sleep + flushTask = Task { @MainActor [weak self] in + do { + try await sleep(delay) + } catch { + return + } + guard let self, self.generation == scheduledGeneration else { return } + self.flushTask = nil + guard let value = self.pendingValue else { return } + self.pendingValue = nil + guard value != self.lastDelivered else { return } + await self.deliverNow(value) + } + } +} diff --git a/ios/AidenOnTheGo/LiveActivities/AidenRemoteLiveActivityManager.swift b/ios/AidenOnTheGo/LiveActivities/AidenRemoteLiveActivityManager.swift index 2c37eedef6..8fd29ec834 100644 --- a/ios/AidenOnTheGo/LiveActivities/AidenRemoteLiveActivityManager.swift +++ b/ios/AidenOnTheGo/LiveActivities/AidenRemoteLiveActivityManager.swift @@ -9,9 +9,22 @@ final class AidenRemoteLiveActivityManager { static let responseExcerptPreferenceKey = "aiden.live-activities.response-excerpts" + /// ActivityKit budgets updates, so streamed tokens, reasoning, and tool + /// churn coalesce to the newest state at most once per interval. Phase + /// changes (status, approval, stale, end) bypass the window. + static let coalescedUpdateInterval: Duration = .seconds(1) + + private enum UpdateUrgency { + case coalesced + case immediate + } + + private typealias ContentState = AgentRunActivityAttributes.ContentState + private let defaults: UserDefaults private var currentActivity: Activity? - private var stateByActivityID: [String: AgentRunActivityAttributes.ContentState] = [:] + private var stateByActivityID: [String: ContentState] = [:] + private var throttleByActivityID: [String: AidenLatestValueThrottle] = [:] init(defaults: UserDefaults = .standard) { self.defaults = defaults @@ -48,7 +61,7 @@ final class AidenRemoteLiveActivityManager { if let existing = activity(instanceID: instanceID, streamID: streamID) { currentActivity = existing stateByActivityID[existing.id] = state - await existing.update(content(for: state)) + await throttle(for: existing).submitUrgent(state) return } @@ -60,6 +73,7 @@ final class AidenRemoteLiveActivityManager { ) currentActivity = activity stateByActivityID[activity.id] = state + throttle(for: activity).markDelivered(state) } catch { currentActivity = nil AidenDiagnostics.record(.liveActivity, event: .liveActivityFailed, outcome: .degraded, code: .unavailable) @@ -73,7 +87,7 @@ final class AidenRemoteLiveActivityManager { ) async { switch state { case .queued, .reconciling: - await update(instanceID: instanceID, streamID: streamID) { + await update(instanceID: instanceID, streamID: streamID, urgency: .immediate) { AgentRunActivityStateReducer.refreshedStatus( .starting, activity: String(localized: "Starting response"), @@ -81,7 +95,7 @@ final class AidenRemoteLiveActivityManager { ) } case .running: - await update(instanceID: instanceID, streamID: streamID) { + await update(instanceID: instanceID, streamID: streamID, urgency: .immediate) { AgentRunActivityStateReducer.refreshedStatus( .responding, activity: String(localized: "Writing response"), @@ -89,7 +103,7 @@ final class AidenRemoteLiveActivityManager { ) } case .waitingForApproval: - await update(instanceID: instanceID, streamID: streamID) { + await update(instanceID: instanceID, streamID: streamID, urgency: .immediate) { AgentRunActivityStateReducer.refreshedStatus( .waitingForApproval, activity: String(localized: "Waiting for approval"), @@ -136,13 +150,13 @@ final class AidenRemoteLiveActivityManager { } func approvalRequired(instanceID: String, streamID: String) async { - await update(instanceID: instanceID, streamID: streamID) { + await update(instanceID: instanceID, streamID: streamID, urgency: .immediate) { AgentRunActivityStateReducer.waitingForApproval(state: $0) } } func markStale(instanceID: String, streamID: String) async { - await update(instanceID: instanceID, streamID: streamID) { + await update(instanceID: instanceID, streamID: streamID, urgency: .immediate) { AgentRunActivityStateReducer.stale(state: $0) } } @@ -151,7 +165,7 @@ final class AidenRemoteLiveActivityManager { for activity in Activity.activities where isLive(activity) { let state = AgentRunActivityStateReducer.stale(state: state(for: activity)) stateByActivityID[activity.id] = state - await activity.update(content(for: state)) + await throttle(for: activity).submitUrgent(state) } } @@ -164,6 +178,7 @@ final class AidenRemoteLiveActivityManager { state: state(for: activity) ) stateByActivityID[activity.id] = state + discardThrottle(for: activity.id) await activity.end(content(for: state), dismissalPolicy: .immediate) stateByActivityID[activity.id] = nil if currentActivity?.id == activity.id { currentActivity = nil } @@ -185,6 +200,7 @@ final class AidenRemoteLiveActivityManager { errorSummary: errorSummary ) stateByActivityID[activity.id] = state + discardThrottle(for: activity.id) let policy: ActivityUIDismissalPolicy = status == .complete ? .after(Date().addingTimeInterval(300)) : .after(Date().addingTimeInterval(30)) @@ -204,6 +220,7 @@ final class AidenRemoteLiveActivityManager { where activity.attributes.instanceID == instanceID && isLive(activity) { guard isCurrent() else { return } guard let streamID = activity.attributes.streamID else { + discardThrottle(for: activity.id) await activity.end(nil, dismissalPolicy: .immediate) stateByActivityID[activity.id] = nil continue @@ -224,7 +241,7 @@ final class AidenRemoteLiveActivityManager { guard isCurrent() else { return } let state = AgentRunActivityStateReducer.stale(state: state(for: activity)) stateByActivityID[activity.id] = state - await activity.update(content(for: state)) + await throttle(for: activity).submitUrgent(state) } } } @@ -232,7 +249,8 @@ final class AidenRemoteLiveActivityManager { private func update( instanceID: String, streamID: String, - transform: (AgentRunActivityAttributes.ContentState) -> AgentRunActivityAttributes.ContentState + urgency: UpdateUrgency = .coalesced, + transform: (ContentState) -> ContentState ) async { guard let activity = activity(instanceID: instanceID, streamID: streamID), isLive(activity) else { return } currentActivity = activity @@ -240,8 +258,33 @@ final class AidenRemoteLiveActivityManager { if !includesResponseExcerpts, !state.responseExcerpt.isEmpty { state = AgentRunActivityStateReducer.clearingResponseExcerpt(state: state) } + // The reducer state always advances; only the ActivityKit write is + // coalesced, so a later urgent update or end carries every token. stateByActivityID[activity.id] = state - await activity.update(content(for: state)) + switch urgency { + case .coalesced: + await throttle(for: activity).submit(state) + case .immediate: + await throttle(for: activity).submitUrgent(state) + } + } + + private func throttle( + for activity: Activity + ) -> AidenLatestValueThrottle { + if let existing = throttleByActivityID[activity.id] { return existing } + let throttle = AidenLatestValueThrottle( + interval: Self.coalescedUpdateInterval + ) { [weak self, weak activity] state in + guard let self, let activity, self.isLive(activity) else { return } + await activity.update(self.content(for: state)) + } + throttleByActivityID[activity.id] = throttle + return throttle + } + + private func discardThrottle(for activityID: String) { + throttleByActivityID.removeValue(forKey: activityID)?.cancel() } private func state( diff --git a/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift b/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift new file mode 100644 index 0000000000..5d0eb5d923 --- /dev/null +++ b/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift @@ -0,0 +1,171 @@ +import XCTest +@testable import AidenOnTheGo + +/// Behavioral coverage for the streaming hot paths: Live Activity update +/// coalescing, markdown prefix reuse, SSE framing, and bounded caches. +final class AidenStreamingPerformanceTests: XCTestCase { + + // MARK: - Live Activity coalescing + + @MainActor + func testFirstUpdateDeliversImmediatelyAndBurstCoalescesToTheNewestValue() async throws { + let harness = ThrottleHarness() + let throttle = harness.makeThrottle() + + await throttle.submit("token-1") + XCTAssertEqual(harness.delivered, ["token-1"]) + + harness.advance(by: .milliseconds(200)) + await throttle.submit("token-2") + harness.advance(by: .milliseconds(200)) + await throttle.submit("token-3") + XCTAssertEqual(harness.delivered, ["token-1"], "Updates inside the window must wait.") + try await harness.waitForSleepRequests(1) + XCTAssertEqual(harness.sleeper.requested, [.milliseconds(800)], "The trailing write lands when the window closes.") + + harness.advance(by: .milliseconds(600)) + harness.sleeper.resumeAll() + await throttle.waitForScheduledFlush() + XCTAssertEqual(harness.delivered, ["token-1", "token-3"], "Only the newest coalesced value is written.") + } + + @MainActor + func testUrgentUpdateBypassesTheWindowAndSupersedesPendingValues() async throws { + let harness = ThrottleHarness() + let throttle = harness.makeThrottle() + + await throttle.submit("token-1") + harness.advance(by: .milliseconds(100)) + await throttle.submit("token-2") + try await harness.waitForSleepRequests(1) + + await throttle.submitUrgent("waiting-for-approval") + XCTAssertEqual(harness.delivered, ["token-1", "waiting-for-approval"]) + XCTAssertNil(throttle.pendingValue) + + // The superseded trailing write must not land after the urgent state. + harness.sleeper.resumeAll() + await throttle.waitForScheduledFlush() + for _ in 0..<5 { await Task.yield() } + XCTAssertEqual(harness.delivered, ["token-1", "waiting-for-approval"]) + } + + @MainActor + func testUpdatesAfterTheWindowDeliverInlineAndDuplicatesAreSkipped() async { + let harness = ThrottleHarness() + let throttle = harness.makeThrottle() + + // The initial content handed to ActivityKit opens the window too. + throttle.markDelivered("started") + await throttle.submit("started") + XCTAssertEqual(harness.delivered, [], "Re-submitting the delivered state is a no-op.") + + harness.advance(by: .seconds(1)) + await throttle.submit("token-1") + harness.advance(by: .milliseconds(1_500)) + await throttle.submit("token-2") + XCTAssertEqual(harness.delivered, ["token-1", "token-2"]) + XCTAssertTrue(harness.sleeper.requested.isEmpty) + } + + @MainActor + func testCancelDropsThePendingValue() async throws { + let harness = ThrottleHarness() + let throttle = harness.makeThrottle() + + await throttle.submit("token-1") + await throttle.submit("token-2") + try await harness.waitForSleepRequests(1) + throttle.cancel() + XCTAssertNil(throttle.pendingValue) + harness.sleeper.resumeAll() + for _ in 0..<5 { await Task.yield() } + XCTAssertEqual(harness.delivered, ["token-1"]) + } + + @MainActor + func testATwoThousandTokenReplyWritesAboutOncePerSecond() async throws { + let harness = ThrottleHarness() + let throttle = harness.makeThrottle() + + // 2,000 tokens at 40 tokens/s span 50 s of streaming. + for token in 0..<2_000 { + await throttle.submit("token-\(token)") + harness.advance(by: .milliseconds(25)) + if !harness.sleeper.isEmpty { + if harness.elapsedSinceLastDelivery >= .seconds(1) { + harness.sleeper.resumeAll() + await throttle.waitForScheduledFlush() + } + } + } + await throttle.submitUrgent("complete") + harness.sleeper.resumeAll() + + XCTAssertLessThanOrEqual(harness.delivered.count, 52) + XCTAssertGreaterThanOrEqual(harness.delivered.count, 40) + XCTAssertEqual(harness.delivered.last, "complete") + } +} + +// MARK: - Test doubles + +@MainActor +private final class ThrottleHarness { + let sleeper = ManualSleeper() + private(set) var delivered: [String] = [] + private let origin = ContinuousClock.now + private var offset: Duration = .zero + private var lastDeliveryOffset: Duration? + + var elapsedSinceLastDelivery: Duration { + offset - (lastDeliveryOffset ?? .zero) + } + + func advance(by duration: Duration) { + offset += duration + } + + func makeThrottle() -> AidenLatestValueThrottle { + AidenLatestValueThrottle( + interval: .seconds(1), + now: { [unowned self] in self.origin + self.offset }, + sleep: { [sleeper] duration in try await sleeper.sleep(for: duration) }, + deliver: { [unowned self] value in + self.delivered.append(value) + self.lastDeliveryOffset = self.offset + } + ) + } + + func waitForSleepRequests(_ count: Int) async throws { + for _ in 0..<200 where sleeper.requested.count < count { + await Task.yield() + } + XCTAssertGreaterThanOrEqual(sleeper.requested.count, count) + } +} + +@MainActor +private final class ManualSleeper { + private(set) var requested: [Duration] = [] + private var waiters: [CheckedContinuation] = [] + + var isEmpty: Bool { waiters.isEmpty } + + /// Suspends until the test resumes it, then reports cancellation the same + /// way `Task.sleep` does. + func sleep(for duration: Duration) async throws { + requested.append(duration) + await withCheckedContinuation { (continuation: CheckedContinuation) in + waiters.append(continuation) + } + try Task.checkCancellation() + } + + func resumeAll() { + let pending = waiters + waiters.removeAll() + pending.forEach { $0.resume() } + } +} From 7ad06da17d430609dcd77f2df52a1691f8ddfcf4 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 3 Oct 2026 06:53:25 -0400 Subject: [PATCH 02/10] perf(ios): single progress snapshot owner and jittered backoff (EXT-12, EXT-17) Chat open fetched the progress snapshot in load() and again in the observer before its live channel delivered the same snapshot. load() now hands its snapshot to the observer, and a reload while the observer runs leaves progress to it. Reconnects use capped exponential backoff with equal jitter instead of a fixed one-second retry, resetting after any delivered event; stream reconciliation shares the jittered policy. Co-Authored-By: Claude Opus 5.5 --- .../Features/Remote/AidenChatFeature.swift | 47 ++++++++++++--- ios/AidenOnTheGoTests/AidenChatTests.swift | 60 ++++++++++++++++--- 2 files changed, 92 insertions(+), 15 deletions(-) diff --git a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift index 0181a6dd3a..e88ed9b7c7 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift @@ -490,9 +490,21 @@ struct AidenTerminalReplayGate { } enum AidenTerminalReconciliation { - static func retryDelayMilliseconds(attempt: Int) -> Int { + static let maximumRetryDelayMilliseconds = 30_000 + + /// Capped exponential backoff with equal jitter: the delay lands in + /// `[ceiling / 2, ceiling)`, where the ceiling doubles from 1 s to 30 s. + /// Keeping half the ceiling preserves real back-off while the random half + /// spreads reconnects from many devices after a Mac restart or network flap. + static func retryDelayMilliseconds( + attempt: Int, + randomUnit: () -> Double = { Double.random(in: 0..<1) } + ) -> Int { let safeAttempt = max(0, min(attempt, 5)) - return min(30_000, 1_000 * (1 << safeAttempt)) + let ceiling = min(maximumRetryDelayMilliseconds, 1_000 * (1 << safeAttempt)) + let floor = ceiling / 2 + let unit = min(max(randomUnit(), 0), 1) + return min(ceiling, floor + Int(Double(ceiling - floor) * unit)) } static func isDefinitiveMissingStream(_ error: Error) -> Bool { @@ -1600,12 +1612,15 @@ final class AidenChatViewModel { guard !isRemoved, coordinator.isCurrent(context) else { return } guard observeProgress, isCurrentProgressObservation(observationGeneration, context: context) else { return } + // A running observer already owns a live progress channel whose + // snapshots supersede a one-off fetch, so a reload does not duplicate it. + guard progressTask == nil else { return } await loadProgressSnapshot( context: context, observationGeneration: observationGeneration ) guard isCurrentProgressObservation(observationGeneration, context: context) else { return } - startProgressObservation() + startProgressObservation(initialSnapshotLoaded: true) } private func refreshModelCatalog(context: AidenRemoteRequestContext) async { @@ -1764,7 +1779,10 @@ final class AidenChatViewModel { return historicalAgentRosters.first { $0.turnId == turnId } } - func startProgressObservation() { + /// Starts the single progress owner for this chat. `initialSnapshotLoaded` + /// lets `load()` hand over the snapshot it just fetched so the observer goes + /// straight to the live channel instead of fetching the same state again. + func startProgressObservation(initialSnapshotLoaded: Bool = false) { guard !isReadOnlyFixture else { return } guard !isRemoved else { return } clearProgressStateForLostAccess() @@ -1773,7 +1791,10 @@ final class AidenChatViewModel { progressObservationGeneration &+= 1 let generation = progressObservationGeneration progressTask = Task { [weak self] in - await self?.observeProgress(generation: generation) + await self?.observeProgress( + generation: generation, + initialSnapshotLoaded: initialSnapshotLoaded + ) self?.finishProgressObservation(generation: generation) } } @@ -1846,7 +1867,9 @@ final class AidenChatViewModel { isAgentRosterStale = rosterFetchFailed && agentRoster != nil } - private func observeProgress(generation: UInt64) async { + private func observeProgress(generation: UInt64, initialSnapshotLoaded: Bool = false) async { + var skipsSnapshot = initialSnapshotLoaded + var failedAttempts = 0 while !Task.isCancelled { guard let context = try? coordinator.requestContext(for: instanceId) else { clearProgressState() @@ -1854,7 +1877,10 @@ final class AidenChatViewModel { } guard isCurrentProgressObservation(generation, context: context), canReadTaskProgress || canReadAgentRoster else { return } - await loadProgressSnapshot(context: context, observationGeneration: generation) + if !skipsSnapshot { + await loadProgressSnapshot(context: context, observationGeneration: generation) + } + skipsSnapshot = false guard isCurrentProgressObservation(generation, context: context) else { return } do { let events = try coordinator.remoteClient(for: context).progressEvents( @@ -1865,6 +1891,9 @@ final class AidenChatViewModel { try Task.checkCancellation() guard isCurrentProgressObservation(generation, context: context), event.streamId == chat.id else { return } + // A delivered event proves the channel is healthy, so the + // next reconnect starts again from the shortest delay. + failedAttempts = 0 applyProgress(event) } if isCurrentProgressObservation(generation, context: context) { @@ -1884,8 +1913,10 @@ final class AidenChatViewModel { isTaskProgressStale = taskProgress != nil isAgentRosterStale = agentRoster != nil } + let delay = AidenTerminalReconciliation.retryDelayMilliseconds(attempt: failedAttempts) + failedAttempts += 1 do { - try await Task.sleep(for: .seconds(1)) + try await Task.sleep(for: .milliseconds(delay)) } catch { return } diff --git a/ios/AidenOnTheGoTests/AidenChatTests.swift b/ios/AidenOnTheGoTests/AidenChatTests.swift index 12b9c19688..344f7bbd17 100644 --- a/ios/AidenOnTheGoTests/AidenChatTests.swift +++ b/ios/AidenOnTheGoTests/AidenChatTests.swift @@ -339,6 +339,35 @@ final class AidenChatTests: XCTestCase { XCTAssertTrue(model.isProgressStale, "A finished stream should retain a last-known label while reconnecting.") } + @MainActor + func testChatOpenFetchesTheProgressSnapshotOnceAndReloadsDoNotDuplicateIt() async throws { + let root = FileManager.default.temporaryDirectory.appending(path: "aiden-progress-once-\(UUID())") + defer { try? FileManager.default.removeItem(at: root) } + let model = try await makeProgressLifecycleModel(mode: .finite, cache: AidenChatCache(root: root)) + defer { + model.stopProgressObservation() + AidenChatProgressLifecycleURLProtocol.reset() + } + + await model.load() + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.agentRequestCount, 1) + XCTAssertNotNil(model.agentRoster) + + // The observer that load() hands off to opens the live channel, which + // carries its own initial snapshot, without fetching the roster again. + try await waitForProgressRequestCount(1) + XCTAssertTrue(model.isProgressObservationRunning) + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.agentRequestCount, 1) + + // A pull-to-refresh while the observer owns progress reloads the + // transcript but leaves progress to that single owner. The finite + // channel's reconnect waits at least half a second, so no retry + // snapshot can land inside this window. + await model.load() + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.agentRequestCount, 1) + XCTAssertEqual(AidenChatProgressLifecycleURLProtocol.progressRequestCount, 1) + } + @MainActor func testRosterRefreshFailureDoesNotMarkFreshTaskProgressStale() async throws { let model = try await makeProgressLifecycleModel(mode: .rosterFailsAfterFirst) @@ -6044,13 +6073,30 @@ final class AidenChatTests: XCTestCase { XCTAssertFalse(gate.shouldReplay(.error)) } - func testTerminalReconciliationRetriesIndefinitelyWithACappedBackoff() { - XCTAssertEqual(AidenTerminalReconciliation.retryDelayMilliseconds(attempt: -1), 1_000) - XCTAssertEqual(AidenTerminalReconciliation.retryDelayMilliseconds(attempt: 0), 1_000) - XCTAssertEqual(AidenTerminalReconciliation.retryDelayMilliseconds(attempt: 1), 2_000) - XCTAssertEqual(AidenTerminalReconciliation.retryDelayMilliseconds(attempt: 4), 16_000) - XCTAssertEqual(AidenTerminalReconciliation.retryDelayMilliseconds(attempt: 5), 30_000) - XCTAssertEqual(AidenTerminalReconciliation.retryDelayMilliseconds(attempt: 500), 30_000) + func testTerminalReconciliationRetriesIndefinitelyWithACappedJitteredBackoff() { + func delay(_ attempt: Int, _ unit: Double) -> Int { + AidenTerminalReconciliation.retryDelayMilliseconds(attempt: attempt, randomUnit: { unit }) + } + // The lowest draw keeps half of each exponential step, so retries + // still back off; the highest draw never exceeds that step. + XCTAssertEqual(delay(-1, 0), 500) + XCTAssertEqual(delay(0, 0), 500) + XCTAssertEqual(delay(1, 0), 1_000) + XCTAssertEqual(delay(4, 0), 8_000) + XCTAssertEqual(delay(0, 0.999_999), 999) + XCTAssertEqual(delay(4, 0.999_999), 15_999) + // Attempts past the cap never wait longer than 30 seconds, even with + // an out-of-range random source. + XCTAssertEqual(delay(500, 0), 15_000) + XCTAssertEqual(delay(500, 1), 30_000) + XCTAssertEqual(delay(500, 7), 30_000) + XCTAssertEqual(delay(500, -3), 15_000) + + // The default source spreads simultaneous reconnects instead of + // aligning every device on the same instant. + let draws = Set((0..<64).map { _ in AidenTerminalReconciliation.retryDelayMilliseconds(attempt: 3) }) + XCTAssertGreaterThan(draws.count, 1) + XCTAssertTrue(draws.allSatisfy { (4_000...8_000).contains($0) }) } func testTypedMissingStreamFallsBackToDurableChatReconciliation() throws { From 48aa8940a536989492ae6c971449c315970be4fa Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 3 Oct 2026 15:26:31 -0400 Subject: [PATCH 03/10] perf(ios): reuse parsed markdown chunks while streaming (EXT-10) Settled blank-line-delimited blocks are parsed once and cached in a bounded LRU; each streamed update reparses only the open tail. The live response view evaluates its transcript projections once per render. Co-Authored-By: Claude Opus 5.5 --- ios/AidenOnTheGo.xcodeproj/project.pbxproj | 4 + .../Features/Remote/AidenChatFeature.swift | 13 +- .../Remote/AidenMarkdownContentCache.swift | 243 ++++++++++++++++++ .../AidenStreamingPerformanceTests.swift | 110 ++++++++ 4 files changed, 365 insertions(+), 5 deletions(-) create mode 100644 ios/AidenOnTheGo/Features/Remote/AidenMarkdownContentCache.swift diff --git a/ios/AidenOnTheGo.xcodeproj/project.pbxproj b/ios/AidenOnTheGo.xcodeproj/project.pbxproj index 37a0e6656f..538a534864 100644 --- a/ios/AidenOnTheGo.xcodeproj/project.pbxproj +++ b/ios/AidenOnTheGo.xcodeproj/project.pbxproj @@ -21,6 +21,7 @@ A0D700000000000000000002 /* AidenSSEParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000012 /* AidenSSEParser.swift */; }; A0D700000000000000000003 /* AidenChatCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000013 /* AidenChatCache.swift */; }; A0D700000000000000000004 /* AidenChatFeature.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000014 /* AidenChatFeature.swift */; }; + A0F100000000000000000031 /* AidenMarkdownContentCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0F100000000000000000030 /* AidenMarkdownContentCache.swift */; }; A0D700000000000000000005 /* AidenChatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000015 /* AidenChatTests.swift */; }; A0F100000000000000000021 /* AidenStreamingPerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0F100000000000000000020 /* AidenStreamingPerformanceTests.swift */; }; A0D800000000000000000001 /* AidenAppearance.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D800000000000000000011 /* AidenAppearance.swift */; }; @@ -145,6 +146,7 @@ A0DC00000000000000000011 /* AidenChatProgress.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatProgress.swift; sourceTree = ""; }; A0D700000000000000000012 /* AidenSSEParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenSSEParser.swift; sourceTree = ""; }; A0D700000000000000000013 /* AidenChatCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatCache.swift; sourceTree = ""; }; + A0F100000000000000000030 /* AidenMarkdownContentCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenMarkdownContentCache.swift; sourceTree = ""; }; A0D700000000000000000014 /* AidenChatFeature.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatFeature.swift; sourceTree = ""; }; A0F100000000000000000020 /* AidenStreamingPerformanceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenStreamingPerformanceTests.swift; sourceTree = ""; }; A0D700000000000000000015 /* AidenChatTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatTests.swift; sourceTree = ""; }; @@ -409,6 +411,7 @@ A0D600000000000000000015 /* AidenPairingView.swift */, A0D600000000000000000016 /* AidenWorkspaceShellView.swift */, A0D700000000000000000014 /* AidenChatFeature.swift */, + A0F100000000000000000030 /* AidenMarkdownContentCache.swift */, ); path = Remote; sourceTree = ""; @@ -762,6 +765,7 @@ A0D700000000000000000002 /* AidenSSEParser.swift in Sources */, A0D700000000000000000003 /* AidenChatCache.swift in Sources */, A0D700000000000000000004 /* AidenChatFeature.swift in Sources */, + A0F100000000000000000031 /* AidenMarkdownContentCache.swift in Sources */, A0D800000000000000000001 /* AidenAppearance.swift in Sources */, A0D800000000000000000003 /* AidenVoiceInput.swift in Sources */, A0D800000000000000000004 /* AidenChromeGlass.swift in Sources */, diff --git a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift index e88ed9b7c7..60adf170ba 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift @@ -6050,7 +6050,7 @@ struct AidenMarkdownView: View { .font(.body) .fixedSize(horizontal: false, vertical: true) } else { - MarkdownUI.Markdown(content) + MarkdownUI.Markdown(AidenMarkdownContentCache.shared.content(for: content)) .markdownTheme(.aidenChat(colorScheme: colorScheme)) .markdownImageProvider(AidenMarkdownNoNetworkImageProvider()) .markdownCodeSyntaxHighlighter(.plainText) @@ -6116,10 +6116,6 @@ private struct AidenLiveResponseView: View { ) } - private var visibleText: String { - botReply?.finalText ?? model.liveText - } - private var reasoningActive: Bool { guard model.isStreaming else { return false } if AidenAgentActivityPresentation.hasActiveThinkingStep(model.activityTimeline) { @@ -6170,6 +6166,12 @@ private struct AidenLiveResponseView: View { } var body: some View { + // Each projection walks the whole live transcript, so evaluate them + // once per render rather than once per reference. + let botReply = botReply + let chronologicalRows = chronologicalRows + let visibleText = botReply?.finalText ?? model.liveText + let visibleActivitySteps = chronologicalRows == nil ? visibleActivitySteps : [] VStack(alignment: .leading, spacing: 12) { if model.isStreaming, let start = AidenTurnElapsed.liveStart( @@ -6179,6 +6181,7 @@ private struct AidenLiveResponseView: View { AidenLiveElapsedLabel(start: start) } if chronologicalRows == nil && model.isStreaming && model.reasoning.isEmpty && model.activityTimeline?.steps.isEmpty != false { + let activity = activity HStack(spacing: 8) { ThinkingOrb(state: activity.orb, size: .px20) Text(activity.label) diff --git a/ios/AidenOnTheGo/Features/Remote/AidenMarkdownContentCache.swift b/ios/AidenOnTheGo/Features/Remote/AidenMarkdownContentCache.swift new file mode 100644 index 0000000000..2a32c1ed00 --- /dev/null +++ b/ios/AidenOnTheGo/Features/Remote/AidenMarkdownContentCache.swift @@ -0,0 +1,243 @@ +import Foundation +import MarkdownUI + +/// Splits Markdown into independently parseable chunks at blank-line block +/// boundaries, so a growing (streamed) document can reuse the parse of every +/// settled chunk and re-parse only the open tail. +/// +/// A split is made only where CommonMark guarantees every open block has +/// closed: after a blank line outside a fenced code block, before a complete +/// line that starts at column 0 and cannot continue a list. Documents with +/// constructs whose meaning crosses blank lines (link reference or footnote +/// definitions, and HTML blocks that ignore blank lines) are never split. +enum AidenMarkdownBlockSplitter { + struct Split: Equatable { + var settled: [Substring] + var tail: Substring + } + + static func split(_ text: String) -> Split { + guard allowsSplitting(text) else { return Split(settled: [], tail: text[...]) } + let utf8 = text.utf8 + var settled: [Substring] = [] + var chunkStart = text.startIndex + var lineStart = text.startIndex + var previousLineWasBlank = false + var openFence: Fence? + + while let newline = utf8[lineStart...].firstIndex(of: 0x0A) { + var lineEnd = newline + if lineEnd > lineStart, utf8[utf8.index(before: lineEnd)] == 0x0D { + lineEnd = utf8.index(before: lineEnd) + } + let line = utf8[lineStart.. chunkStart, + startsIndependentBlock(line) { + settled.append(text[chunkStart.. Bool { + // HTML block types 1-5 (comments, CDATA, declarations, processing + // instructions, and raw pre/script/style/textarea) continue across + // blank lines. Rare in model output, so any occurrence opts out. + let lowered = text.lowercased() + for marker in [" Bool { + var index = line.startIndex + var indent = 0 + while index < line.endIndex, line[index] == 0x20, indent < 4 { + indent += 1 + index = line.index(after: index) + } + guard indent <= 3, index < line.endIndex, line[index] == 0x5B /* [ */ else { return false } + guard let close = line[index...].firstIndex(of: 0x5D /* ] */) else { return false } + let afterClose = line.index(after: close) + return afterClose < line.endIndex && line[afterClose] == 0x3A /* : */ + } + + /// True when a complete line, following a blank line, cannot belong to any + /// block opened before that blank line. + private static func startsIndependentBlock(_ line: Substring.UTF8View) -> Bool { + guard let first = line.first, first != 0x20, first != 0x09 else { return false } + return !startsListItem(line) + } + + private static func startsListItem(_ line: Substring.UTF8View) -> Bool { + var bytes = line.makeIterator() + guard let first = bytes.next() else { return false } + func isMarkerTerminator(_ byte: UInt8?) -> Bool { + byte == nil || byte == 0x20 || byte == 0x09 || byte == 0x0D + } + if first == 0x2D || first == 0x2A || first == 0x2B { // - * + + return isMarkerTerminator(bytes.next()) + } + guard (0x30...0x39).contains(first) else { return false } + var digits = 1 + while let byte = bytes.next() { + if (0x30...0x39).contains(byte) { + digits += 1 + if digits > 9 { return false } + continue + } + guard byte == 0x2E || byte == 0x29 else { return false } // . ) + return isMarkerTerminator(bytes.next()) + } + return false + } + + private struct Fence { + let marker: UInt8 + let length: Int + + /// Recognizes a fenced code opener: up to three spaces, then at least + /// three backticks or tildes (a backtick info string has no backticks). + init?(opening line: Substring.UTF8View) { + guard let (marker, length, rest) = Self.run(in: line) else { return nil } + if marker == 0x60, rest.contains(0x60) { return nil } + self.marker = marker + self.length = length + } + + func isClosed(by line: Substring.UTF8View) -> Bool { + guard let (marker, length, rest) = Self.run(in: line) else { return false } + return marker == self.marker + && length >= self.length + && rest.allSatisfy { $0 == 0x20 || $0 == 0x09 } + } + + private static func run( + in line: Substring.UTF8View + ) -> (marker: UInt8, length: Int, rest: Substring.UTF8View.SubSequence)? { + var index = line.startIndex + var indent = 0 + while index < line.endIndex, line[index] == 0x20 { + indent += 1 + if indent > 3 { return nil } + index = line.index(after: index) + } + guard index < line.endIndex else { return nil } + let marker = line[index] + guard marker == 0x60 || marker == 0x7E else { return nil } // ` ~ + var length = 0 + while index < line.endIndex, line[index] == marker { + length += 1 + index = line.index(after: index) + } + guard length >= 3 else { return nil } + return (marker, length, line[index...]) + } + } +} + +/// Parses Markdown for display, reusing the parsed blocks of settled chunks. +/// +/// Streaming previously re-parsed the whole accumulated reply on every token +/// (quadratic in reply length). With chunk reuse, each update parses only the +/// open tail; settled transcript messages become dictionary lookups on +/// re-render. The cache is bounded by entry count and retained characters. +@MainActor +final class AidenMarkdownContentCache { + static let shared = AidenMarkdownContentCache() + + private struct Entry { + let content: MarkdownContent + var lastAccess: UInt64 + } + + private let maximumEntries: Int + private let maximumCharacters: Int + private var entries: [String: Entry] = [:] + private var retainedCharacters = 0 + private var accessClock: UInt64 = 0 + + /// Characters handed to the Markdown parser, for measuring reuse. + private(set) var parsedCharacterCount = 0 + + init(maximumEntries: Int = 512, maximumCharacters: Int = 400_000) { + self.maximumEntries = maximumEntries + self.maximumCharacters = maximumCharacters + } + + var entryCount: Int { entries.count } + + func content(for markdown: String) -> MarkdownContent { + let split = AidenMarkdownBlockSplitter.split(markdown) + guard !split.settled.isEmpty else { return parse(markdown) } + var chunks = split.settled.map { cachedContent(for: String($0)) } + if !split.tail.isEmpty { + chunks.append(parse(String(split.tail))) + } + return MarkdownContent { + for chunk in chunks { chunk } + } + } + + func removeAll() { + entries.removeAll() + retainedCharacters = 0 + } + + private func parse(_ markdown: String) -> MarkdownContent { + parsedCharacterCount += markdown.utf8.count + return MarkdownContent(markdown) + } + + private func cachedContent(for chunk: String) -> MarkdownContent { + accessClock &+= 1 + if var entry = entries[chunk] { + entry.lastAccess = accessClock + entries[chunk] = entry + return entry.content + } + let content = parse(chunk) + // A single chunk larger than the whole budget is parsed but not kept. + guard chunk.utf8.count <= maximumCharacters else { return content } + entries[chunk] = Entry(content: content, lastAccess: accessClock) + retainedCharacters += chunk.utf8.count + evictIfNeeded() + return content + } + + private func evictIfNeeded() { + guard entries.count > maximumEntries || retainedCharacters > maximumCharacters else { return } + // Evict least recently used chunks down to 3/4 of each budget so a + // burst of new chunks does not rescan the table on every insert. + let entryTarget = maximumEntries * 3 / 4 + let characterTarget = maximumCharacters * 3 / 4 + let oldestFirst = entries.sorted { $0.value.lastAccess < $1.value.lastAccess } + for (key, _) in oldestFirst { + guard entries.count > entryTarget || retainedCharacters > characterTarget else { break } + entries.removeValue(forKey: key) + retainedCharacters -= key.utf8.count + } + } +} diff --git a/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift b/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift index 5d0eb5d923..457239f564 100644 --- a/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift +++ b/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift @@ -1,4 +1,5 @@ import XCTest +import MarkdownUI @testable import AidenOnTheGo /// Behavioral coverage for the streaming hot paths: Live Activity update @@ -106,6 +107,115 @@ final class AidenStreamingPerformanceTests: XCTestCase { XCTAssertGreaterThanOrEqual(harness.delivered.count, 40) XCTAssertEqual(harness.delivered.last, "complete") } + + // MARK: - Markdown prefix reuse + + private static let markdownFixtures: [String] = [ + """ + # Plan + + First paragraph with **bold** and `code`. + It continues on a second line. + + - item one + - item two + + nested paragraph in item two + + - item three + 1. ordered + 2. list + + Paragraph after the list. + + ```swift + let a = 1 + + let b = 2 + ``` + + ~~~ + tilde fence + ~~~ + + | a | b | + |---|---| + | 1 | 2 | + + > quote line + + > another quote + + indented code + + Setext heading + ============== + + * * * + + Final words. + + """, + "Line one\r\n\r\nLine two\r\n\r\n- a\r\n\r\n b\r\n\r\nEnd\r\n", + "See [the docs][docs].\n\nMore text.\n\n[docs]: https://example.invalid\n", + "Intro\n\n\n\nAfter.\n", + "Unclosed fence\n\n```\ncode\n\nmore code\n\nstill code\n", + "````\n```\n\nnot closed by a shorter fence\n````\n\nAfter.\n", + ] + + @MainActor + func testChunkedParseMatchesAFullParseForEveryStreamedPrefix() { + for fixture in Self.markdownFixtures { + let cache = AidenMarkdownContentCache() + var prefix = "" + for character in fixture { + prefix.append(character) + XCTAssertEqual( + cache.content(for: prefix), + MarkdownContent(prefix), + "Chunked parse diverged at prefix: \(prefix.debugDescription)" + ) + } + } + } + + @MainActor + func testStreamingALongReplyParsesRoughlyLinearCharacters() { + let paragraphs = (0..<200).map { "Paragraph \($0) with some **markdown** text to render." } + let reply = paragraphs.joined(separator: "\n\n") + let cache = AidenMarkdownContentCache() + var prefix = "" + var updates = 0 + for word in reply.split(separator: " ", omittingEmptySubsequences: false) { + prefix += prefix.isEmpty ? String(word) : " " + word + _ = cache.content(for: prefix) + updates += 1 + } + // A full reparse per update would hand the parser about + // updates * reply.count / 2 characters; chunk reuse keeps it to the + // settled chunks once plus a short tail per update. + let quadratic = updates * reply.utf8.count / 2 + XCTAssertLessThan(cache.parsedCharacterCount, quadratic / 20) + XCTAssertEqual(cache.content(for: reply), MarkdownContent(reply)) + } + + @MainActor + func testMarkdownCacheStaysWithinItsEntryAndCharacterBudgets() { + let cache = AidenMarkdownContentCache(maximumEntries: 8, maximumCharacters: 400) + for message in 0..<50 { + let text = (0..<4).map { "Message \(message) paragraph \($0)." }.joined(separator: "\n\n") + XCTAssertEqual(cache.content(for: text), MarkdownContent(text)) + XCTAssertLessThanOrEqual(cache.entryCount, 8) + } + + // A recently used message keeps its settled chunks: rendering it + // again parses only the final block, which may still be growing. + let recent = "Recent one.\n\nRecent two.\n\nTail.\n" + _ = cache.content(for: recent) + let parsedBefore = cache.parsedCharacterCount + XCTAssertEqual(cache.content(for: recent), MarkdownContent(recent)) + XCTAssertEqual(cache.parsedCharacterCount - parsedBefore, "Tail.\n".utf8.count) + } } // MARK: - Test doubles From a256636321614a1d83aa2ae7787c6289e9dddd21 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 3 Oct 2026 15:53:56 -0400 Subject: [PATCH 04/10] perf(ios): decode SSE lines with per-line cancellation and validation (EXT-19) Extracts the SSE line splitter so the stream loop does one compare and one append per byte, checking cancellation and validating UTF-8 once per line. Framing is unchanged: LF/CRLF endings, blank delimiters, EOF discard, and the frame-size limit. Co-Authored-By: Claude Opus 5.5 --- .../Networking/AidenRemoteClient.swift | 21 +----- .../Networking/AidenSSEParser.swift | 38 ++++++++++ .../AidenStreamingPerformanceTests.swift | 75 +++++++++++++++++++ 3 files changed, 116 insertions(+), 18 deletions(-) diff --git a/ios/AidenOnTheGo/Networking/AidenRemoteClient.swift b/ios/AidenOnTheGo/Networking/AidenRemoteClient.swift index a16b377b59..00c14b3fd8 100644 --- a/ios/AidenOnTheGo/Networking/AidenRemoteClient.swift +++ b/ios/AidenOnTheGo/Networking/AidenRemoteClient.swift @@ -1997,24 +1997,9 @@ final class AidenRemoteClient: @unchecked Sendable { } var parser = AidenSSEParser() - var lineBytes: [UInt8] = [] - lineBytes.reserveCapacity(512) - for try await byte in bytes { - try Task.checkCancellation() - if byte == 0x0A { - if lineBytes.last == 0x0D { lineBytes.removeLast() } - guard let line = String(bytes: lineBytes, encoding: .utf8) else { - throw AidenRemoteClientError.invalidResponse - } - lineBytes.removeAll(keepingCapacity: true) - if let event = try parser.consume(line: line) { - try yield(event) - } - } else { - lineBytes.append(byte) - guard lineBytes.count <= AidenRemoteProtocol.maxSSEFrameBytes else { - throw AidenSSEParserError.frameTooLarge - } + try await AidenSSELineDecoder.forEachLine(in: bytes) { line in + if let event = try parser.consume(line: line) { + try yield(event) } } // EOF is not an SSE frame delimiter. Discard the pending diff --git a/ios/AidenOnTheGo/Networking/AidenSSEParser.swift b/ios/AidenOnTheGo/Networking/AidenSSEParser.swift index 0f3fb5e53c..3dc1658ad3 100644 --- a/ios/AidenOnTheGo/Networking/AidenSSEParser.swift +++ b/ios/AidenOnTheGo/Networking/AidenSSEParser.swift @@ -72,3 +72,41 @@ struct AidenSSEParser { frameBytes = 0 } } + +/// Splits an SSE byte stream into lines for `AidenSSEParser`. +/// +/// Lines end at LF; a trailing CR is stripped, so CRLF streams parse the same +/// as LF streams. Empty lines are delivered because they delimit frames. A +/// line that is not valid UTF-8 throws `AidenRemoteClientError.invalidResponse` +/// and a line longer than the SSE frame limit throws `frameTooLarge`. Bytes +/// after the last LF are discarded at EOF, since EOF never completes a frame. +/// +/// `URLSession.AsyncBytes` already reads the socket in buffered chunks, so the +/// per-byte work here is kept to a compare and an append: cancellation is +/// checked once per line, and validation runs once per line. +enum AidenSSELineDecoder { + static func forEachLine( + in bytes: Bytes, + maximumLineBytes: Int = AidenRemoteProtocol.maxSSEFrameBytes, + _ body: (String) throws -> Void + ) async throws where Bytes.Element == UInt8 { + var lineBytes: [UInt8] = [] + lineBytes.reserveCapacity(512) + for try await byte in bytes { + guard byte == 0x0A else { + guard lineBytes.count < maximumLineBytes else { + throw AidenSSEParserError.frameTooLarge + } + lineBytes.append(byte) + continue + } + try Task.checkCancellation() + if lineBytes.last == 0x0D { lineBytes.removeLast() } + guard let line = String(validating: lineBytes, as: UTF8.self) else { + throw AidenRemoteClientError.invalidResponse + } + lineBytes.removeAll(keepingCapacity: true) + try body(line) + } + } +} diff --git a/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift b/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift index 457239f564..a51d2292b8 100644 --- a/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift +++ b/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift @@ -216,6 +216,81 @@ final class AidenStreamingPerformanceTests: XCTestCase { XCTAssertEqual(cache.content(for: recent), MarkdownContent(recent)) XCTAssertEqual(cache.parsedCharacterCount - parsedBefore, "Tail.\n".utf8.count) } + + // MARK: - SSE line decoding + + private func decodeLines(_ text: String) async throws -> [String] { + try await decodeLines(Array(text.utf8)) + } + + private func decodeLines(_ bytes: [UInt8], maximumLineBytes: Int = 1_024) async throws -> [String] { + var lines: [String] = [] + try await AidenSSELineDecoder.forEachLine( + in: AsyncStream { continuation in + bytes.forEach { continuation.yield($0) } + continuation.finish() + }, + maximumLineBytes: maximumLineBytes + ) { lines.append($0) } + return lines + } + + func testSSELineDecoderKeepsBlankDelimitersAndNormalizesCRLF() async throws { + let lines = try await decodeLines(": heartbeat\r\n\r\nid: 7\nevent: x\r\ndata: a\ndata: b\n\n") + XCTAssertEqual(lines, [": heartbeat", "", "id: 7", "event: x", "data: a", "data: b", ""]) + } + + func testSSELineDecoderDiscardsAnUnterminatedTailAtEOF() async throws { + let lines = try await decodeLines("data: done\n\ndata: partial") + XCTAssertEqual(lines, ["data: done", ""]) + // A multi-byte scalar split by EOF is discarded, not rejected. + let truncated = Array("data: ok\n".utf8) + Array("é".utf8).prefix(1) + let truncatedLines = try await decodeLines(truncated) + XCTAssertEqual(truncatedLines, ["data: ok"]) + } + + func testSSELineDecoderRejectsInvalidUTF8AndOversizedLines() async throws { + do { + _ = try await decodeLines(Array("data: ".utf8) + [0xFF, 0x0A]) + XCTFail("Invalid UTF-8 must be rejected") + } catch { + guard case .invalidResponse? = error as? AidenRemoteClientError else { + return XCTFail("Expected invalidResponse, received \(error)") + } + } + let exact = try await decodeLines(Array(repeating: 0x78, count: 16) + [0x0A], maximumLineBytes: 16) + XCTAssertEqual(exact, [String(repeating: "x", count: 16)]) + do { + _ = try await decodeLines(Array(repeating: 0x78, count: 17) + [0x0A], maximumLineBytes: 16) + XCTFail("An oversized line must be rejected") + } catch { + XCTAssertEqual(error as? AidenSSEParserError, .frameTooLarge) + } + } + + func testSSELineDecoderFeedsTheParserMultiLineDataFrames() async throws { + let frame = """ + : keep-alive\r + id: 3\r + event: heartbeat\r + data: {"protocolVersion":1,"streamId":"stream-1","sequence":3,\r + data: "timestamp":"2026-08-19T07:00:00.000Z","type":"heartbeat","terminal":false,"payload":{}}\r + \r + + """ + var parser = AidenSSEParser() + var events: [AidenRemoteStreamEvent] = [] + try await AidenSSELineDecoder.forEachLine( + in: AsyncStream { continuation in + frame.utf8.forEach { continuation.yield($0) } + continuation.finish() + } + ) { line in + if let event = try parser.consume(line: line) { events.append(event) } + } + XCTAssertEqual(events.map(\.sequence), [3]) + XCTAssertEqual(events.first?.streamId, "stream-1") + } } // MARK: - Test doubles From 1dce58ed29ca358a30224fa42da7e9287d58a187 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 3 Oct 2026 15:57:02 -0400 Subject: [PATCH 05/10] perf(ios): bound interactive calls, split stream session, release sessions (EXT-14, EXT-16) Request/response calls use a session with a 5 minute resource budget; SSE streams keep the 1 hour budget with the 30 s idle timeout as liveness (two missed 15 s heartbeats). Clients invalidate the sessions they create when released, so replaced clients no longer leak sessions and delegates. Co-Authored-By: Claude Opus 5.5 --- .../Networking/AidenRemoteClient.swift | 106 ++++++++++++++---- 1 file changed, 87 insertions(+), 19 deletions(-) diff --git a/ios/AidenOnTheGo/Networking/AidenRemoteClient.swift b/ios/AidenOnTheGo/Networking/AidenRemoteClient.swift index 00c14b3fd8..06bd8aad8d 100644 --- a/ios/AidenOnTheGo/Networking/AidenRemoteClient.swift +++ b/ios/AidenOnTheGo/Networking/AidenRemoteClient.swift @@ -552,32 +552,97 @@ final class AidenRemoteClient: @unchecked Sendable { private let endpoint: URL private let credential: String? + /// Request/response calls, bounded by `SessionPolicy.interactive`. private let session: URLSession + /// Long-lived SSE streams, bounded by `SessionPolicy.stream`. + private let streamSession: URLSession + /// Sessions this client created. They hold their delegates strongly until + /// invalidated, so the client invalidates them when it is released. + private let ownedSessions: [URLSession] init( installation: AidenInstallation, credential: String, waitsForConnectivity: Bool = true, - requestTimeout: TimeInterval = 30 + requestTimeout: TimeInterval = SessionPolicy.idleTimeout ) throws { guard let pairingTrust = installation.pairingTrust else { throw AidenRemoteClientError.missingTrustConfiguration } endpoint = installation.endpoint self.credential = credential + let trustPolicy = try AidenServerTrustPolicy(pairingTrust: pairingTrust) session = Self.makePinnedSession( endpoint: installation.endpoint, fingerprint: installation.serverSpkiSha256, - trustPolicy: try AidenServerTrustPolicy(pairingTrust: pairingTrust), + trustPolicy: trustPolicy, + policy: .interactive, waitsForConnectivity: waitsForConnectivity, requestTimeout: requestTimeout ) + streamSession = Self.makePinnedSession( + endpoint: installation.endpoint, + fingerprint: installation.serverSpkiSha256, + trustPolicy: trustPolicy, + policy: .stream, + waitsForConnectivity: waitsForConnectivity, + requestTimeout: requestTimeout + ) + ownedSessions = [session, streamSession] } - init(endpoint: URL, credential: String?, session: URLSession) { + init(endpoint: URL, credential: String?, session: URLSession, streamSession: URLSession? = nil) { self.endpoint = endpoint self.credential = credential self.session = session + self.streamSession = streamSession ?? session + ownedSessions = [] + } + + private init(endpoint: URL, ownedSession: URLSession) { + self.endpoint = endpoint + credential = nil + session = ownedSession + streamSession = ownedSession + ownedSessions = [ownedSession] + } + + deinit { + // Let in-flight work finish, then release the sessions and their + // delegates. Without this every replaced client leaks both. + ownedSessions.forEach { $0.finishTasksAndInvalidate() } + } + + /// Timeouts per call type. The idle timeout doubles as stream liveness: + /// the server sends an SSE heartbeat comment every 15 s on both transcript + /// and progress streams, so a stream with no bytes for two heartbeats is + /// treated as dead and reconnects through the normal recovery path. + enum SessionPolicy: Equatable { + case interactive + case stream + + static let idleTimeout: TimeInterval = 30 + + /// Total time one task may take, including waiting for connectivity. + var resourceTimeout: TimeInterval { + switch self { + case .interactive: 5 * 60 + case .stream: 60 * 60 + } + } + + func configuration( + waitsForConnectivity: Bool, + requestTimeout: TimeInterval = SessionPolicy.idleTimeout + ) -> URLSessionConfiguration { + let configuration = URLSessionConfiguration.ephemeral + configuration.waitsForConnectivity = waitsForConnectivity + configuration.timeoutIntervalForRequest = requestTimeout + configuration.timeoutIntervalForResource = max(requestTimeout, resourceTimeout) + configuration.httpCookieAcceptPolicy = .never + configuration.httpShouldSetCookies = false + return configuration + } } static func pair( @@ -591,17 +656,20 @@ final class AidenRemoteClient: @unchecked Sendable { ) async throws -> AidenRemoteContractFixture.PairingExchange { let payload = try payload.validated(at: now) let bootstrap = payload.bootstrap - let session: URLSession + let client: AidenRemoteClient if let injectedSession { - session = injectedSession + client = AidenRemoteClient(endpoint: bootstrap.endpoint, credential: nil, session: injectedSession) } else { - session = makePinnedSession( + client = AidenRemoteClient( endpoint: bootstrap.endpoint, - fingerprint: bootstrap.serverSpkiSha256, - trustPolicy: try AidenServerTrustPolicy(pairingTrust: payload.trust) + ownedSession: makePinnedSession( + endpoint: bootstrap.endpoint, + fingerprint: bootstrap.serverSpkiSha256, + trustPolicy: try AidenServerTrustPolicy(pairingTrust: payload.trust), + policy: .interactive + ) ) } - let client = AidenRemoteClient(endpoint: bootstrap.endpoint, credential: nil, session: session) let request = PairingExchangeRequest( secret: bootstrap.secret, deviceName: deviceName, @@ -680,8 +748,9 @@ final class AidenRemoteClient: @unchecked Sendable { guard isCanonicalAidenEndpoint(endpoint) else { throw AidenRemoteClientError.invalidEndpoint } - let session = injectedSession ?? makeSealedBootstrapSession(endpoint: endpoint) - let client = AidenRemoteClient(endpoint: endpoint, credential: nil, session: session) + let client = injectedSession.map { + AidenRemoteClient(endpoint: endpoint, credential: nil, session: $0) + } ?? AidenRemoteClient(endpoint: endpoint, ownedSession: makeSealedBootstrapSession(endpoint: endpoint)) let sealed: AidenRemoteContractFixture.ManualPairingBootstrap = try await client.send( method: "POST", path: ["pairing", "manual-bootstrap"], @@ -1960,7 +2029,7 @@ final class AidenRemoteClient: @unchecked Sendable { authenticated: true ) request.setValue("text/event-stream", forHTTPHeaderField: "Accept") - let (bytes, response) = try await session.bytes(for: request) + let (bytes, response) = try await streamSession.bytes(for: request) guard let httpResponse = response as? HTTPURLResponse else { throw AidenRemoteClientError.invalidResponse } @@ -2038,8 +2107,9 @@ final class AidenRemoteClient: @unchecked Sendable { endpoint: URL, fingerprint: String, trustPolicy: AidenServerTrustPolicy, + policy: SessionPolicy, waitsForConnectivity: Bool = true, - requestTimeout: TimeInterval = 30 + requestTimeout: TimeInterval = SessionPolicy.idleTimeout ) -> URLSession { let delegate = AidenPinnedServerSessionDelegate( expectedHost: endpoint.host ?? "", @@ -2047,12 +2117,10 @@ final class AidenRemoteClient: @unchecked Sendable { expectedFingerprint: fingerprint, trustPolicy: trustPolicy ) - let configuration = URLSessionConfiguration.ephemeral - configuration.waitsForConnectivity = waitsForConnectivity - configuration.timeoutIntervalForRequest = requestTimeout - configuration.timeoutIntervalForResource = 60 * 60 - configuration.httpCookieAcceptPolicy = .never - configuration.httpShouldSetCookies = false + let configuration = policy.configuration( + waitsForConnectivity: waitsForConnectivity, + requestTimeout: requestTimeout + ) return URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) } From 690bd9e1e5c0f16e3a304100bfc311c27ccdc113 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 3 Oct 2026 15:57:02 -0400 Subject: [PATCH 06/10] perf(ios): check the active client cache before reading the Keychain (EXT-13) Co-Authored-By: Claude Opus 5.5 --- .../Remote/AidenRemoteCoordinator.swift | 22 +++++- .../AidenRemoteClientTests.swift | 75 ++++++++++++++++++- 2 files changed, 92 insertions(+), 5 deletions(-) diff --git a/ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift b/ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift index 2094ae18b7..a65a1795d9 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift @@ -843,6 +843,13 @@ final class AidenRemoteCoordinator { guard let installation = installationStore.activeInstallation else { throw AidenRemoteClientError.missingCredential } + // The cache key changes whenever the active installation, its device + // identity, its credential scope, or the activation generation does, + // so a hit never needs the Keychain read below. + if let cachedActiveClient, + cachedActiveClient.key == activeClientKey(for: installation, activationGeneration: activationGeneration) { + return cachedActiveClient.client + } guard let credential = try installationStore.credential(for: installation), !credential.isEmpty else { throw AidenRemoteClientError.missingCredential @@ -854,17 +861,24 @@ final class AidenRemoteCoordinator { ) } - private func client( + private func activeClientKey( for installation: AidenInstallation, - credential: String, activationGeneration: Int - ) throws -> AidenRemoteClient { - let key = ActiveClientKey( + ) -> ActiveClientKey { + ActiveClientKey( instanceId: installation.id, deviceId: installation.deviceId, credentialScope: installation.credentialScope, activationGeneration: activationGeneration ) + } + + private func client( + for installation: AidenInstallation, + credential: String, + activationGeneration: Int + ) throws -> AidenRemoteClient { + let key = activeClientKey(for: installation, activationGeneration: activationGeneration) if let cachedActiveClient, cachedActiveClient.key == key { return cachedActiveClient.client } diff --git a/ios/AidenOnTheGoTests/AidenRemoteClientTests.swift b/ios/AidenOnTheGoTests/AidenRemoteClientTests.swift index f8683750a5..91acef619d 100644 --- a/ios/AidenOnTheGoTests/AidenRemoteClientTests.swift +++ b/ios/AidenOnTheGoTests/AidenRemoteClientTests.swift @@ -3028,6 +3028,76 @@ final class AidenRemoteClientTests: XCTestCase { print("AIDEN_PHASE12_PHYSICAL checkpoint=repair-restarted") } + @MainActor + func testActiveClientIsReusedWithoutKeychainReadsUntilTheActiveInstallationChanges() throws { + let keychain = AidenRemoteMemoryKeychain() + let store = AidenInstallationStore(keychain: keychain) + let first = makeExchange( + instanceId: "instance-first", + deviceId: "device-first", + credential: String(repeating: "F", count: 43) + ) + let second = makeExchange( + instanceId: "instance-second", + deviceId: "device-second", + credential: String(repeating: "S", count: 43) + ) + _ = try store.savePairing(first, trust: makeSystemTrust(), name: "First Mac") + _ = try store.savePairing(second, trust: makeSystemTrust(), name: "Second Mac") + try store.setActive(second.instanceId) + let session = makeSession() + var builtCredentials: [String] = [] + let coordinator = AidenRemoteCoordinator( + installationStore: store, + clientFactory: { installation, credential in + builtCredentials.append(credential) + return AidenRemoteClient(endpoint: installation.endpoint, credential: credential, session: session) + } + ) + + let loadsBefore = keychain.scopedLoadCount + let client = try coordinator.remoteClient() + for _ in 0..<10 { + XCTAssertTrue(try coordinator.remoteClient() === client) + } + XCTAssertEqual(keychain.scopedLoadCount - loadsBefore, 1, "Cache hits must not read the Keychain.") + XCTAssertEqual(builtCredentials, [second.credential]) + + try store.setActive(first.instanceId) + let switched = try coordinator.remoteClient() + XCTAssertFalse(switched === client) + XCTAssertTrue(try coordinator.remoteClient() === switched) + XCTAssertEqual(builtCredentials, [second.credential, first.credential]) + XCTAssertEqual(keychain.scopedLoadCount - loadsBefore, 2) + } + + func testSessionPoliciesBoundInteractiveCallsAndKeepStreamsAliveOnHeartbeats() { + let serverHeartbeatInterval: TimeInterval = 15 + let interactive = AidenRemoteClient.SessionPolicy.interactive.configuration(waitsForConnectivity: true) + let stream = AidenRemoteClient.SessionPolicy.stream.configuration(waitsForConnectivity: true) + + // A request issued while offline must fail within minutes, not wait + // out an hour-long stream budget. + XCTAssertLessThanOrEqual(interactive.timeoutIntervalForResource, 5 * 60) + XCTAssertGreaterThanOrEqual(interactive.timeoutIntervalForResource, interactive.timeoutIntervalForRequest) + // A healthy stream survives long turns, and a silent one is declared + // dead only after missing at least two heartbeats. + XCTAssertGreaterThanOrEqual(stream.timeoutIntervalForResource, 30 * 60) + XCTAssertGreaterThanOrEqual(stream.timeoutIntervalForRequest, 2 * serverHeartbeatInterval) + XCTAssertLessThan(stream.timeoutIntervalForRequest, 3 * serverHeartbeatInterval) + for configuration in [interactive, stream] { + XCTAssertEqual(configuration.httpCookieAcceptPolicy, .never) + XCTAssertFalse(configuration.httpShouldSetCookies) + } + // Physical-device runs may lengthen the idle timeout; the resource + // budget never drops below it. + let slow = AidenRemoteClient.SessionPolicy.interactive.configuration( + waitsForConnectivity: false, + requestTimeout: 600 + ) + XCTAssertGreaterThanOrEqual(slow.timeoutIntervalForResource, 600) + } + @MainActor func testRePairingAtomicallyReplacesInstallationScopedCredential() throws { let keychain = AidenRemoteMemoryKeychain() @@ -4707,8 +4777,11 @@ private final class AidenRemoteMemoryKeychain: KeychainStoring { scoped[KeychainStore.scopedKey(key, scope: scope)] = value } + private(set) var scopedLoadCount = 0 + func load(_ key: KeychainStore.Key, scope: String) throws -> String? { - scoped[KeychainStore.scopedKey(key, scope: scope)] + scopedLoadCount += 1 + return scoped[KeychainStore.scopedKey(key, scope: scope)] } func delete(_ key: KeychainStore.Key, scope: String) throws { From 3512551551e3c0f9c6bd6d43d29f116b8287fb6e Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 3 Oct 2026 15:58:32 -0400 Subject: [PATCH 07/10] perf(ios): cap the thinking orb at 30 fps and hold decorative motion in Low Power Mode (EXT-18) Co-Authored-By: Claude Opus 5.5 --- ios/AidenOnTheGo/Config/AidenAppearance.swift | 15 +++++++++++++++ .../Features/Bots/AidenBotsHomeView.swift | 3 ++- .../Features/Remote/AidenChatFeature.swift | 3 ++- .../Shared/ThinkingOrbsKit/ThinkingOrb.swift | 7 +++++-- 4 files changed, 24 insertions(+), 4 deletions(-) diff --git a/ios/AidenOnTheGo/Config/AidenAppearance.swift b/ios/AidenOnTheGo/Config/AidenAppearance.swift index 666515badd..eaad63318a 100644 --- a/ios/AidenOnTheGo/Config/AidenAppearance.swift +++ b/ios/AidenOnTheGo/Config/AidenAppearance.swift @@ -453,6 +453,7 @@ private struct AidenPaletteEnvironmentKey: EnvironmentKey { } private struct AidenReduceMotionEnvironmentKey: EnvironmentKey { static let defaultValue = false } +private struct AidenLowPowerModeEnvironmentKey: EnvironmentKey { static let defaultValue = false } private struct AidenDiffMarkerEnvironmentKey: EnvironmentKey { static let defaultValue = AidenDiffMarkerPreference.symbols } private struct AidenSidebarTranslucencyEnvironmentKey: EnvironmentKey { static let defaultValue = true } private struct AidenCodeTypographyEnvironmentKey: EnvironmentKey { @@ -479,6 +480,13 @@ extension EnvironmentValues { set { self[AidenReduceMotionEnvironmentKey.self] = newValue } } + /// True while the system Low Power Mode is on. Decorative, continuously + /// redrawn animations (orbs, shimmers) hold still to save power. + var aidenLowPowerMode: Bool { + get { self[AidenLowPowerModeEnvironmentKey.self] } + set { self[AidenLowPowerModeEnvironmentKey.self] = newValue } + } + var aidenDiffMarkers: AidenDiffMarkerPreference { get { self[AidenDiffMarkerEnvironmentKey.self] } set { self[AidenDiffMarkerEnvironmentKey.self] = newValue } @@ -500,6 +508,7 @@ struct AidenAppearanceRoot: View { @Environment(\.colorScheme) private var colorScheme @Environment(\.colorSchemeContrast) private var colorSchemeContrast @Environment(\.accessibilityReduceMotion) private var systemReduceMotion + @State private var lowPowerMode = ProcessInfo.processInfo.isLowPowerModeEnabled @ViewBuilder let content: () -> Content var body: some View { @@ -515,6 +524,7 @@ struct AidenAppearanceRoot: View { content() .environment(\.aidenPalette, palette) .environment(\.aidenReduceMotion, appearance.resolvedReduceMotion(system: systemReduceMotion)) + .environment(\.aidenLowPowerMode, lowPowerMode) .environment(\.aidenDiffMarkers, appearance.diffMarkers) .environment(\.aidenSidebarTranslucent, appearance.translucentSidebar(for: effectiveScheme)) .environment(\.aidenCodeTypography, AidenCodeTypography(font: appearance.codeFont(for: effectiveScheme), size: appearance.codeFontSize)) @@ -522,6 +532,11 @@ struct AidenAppearanceRoot: View { .preferredColorScheme(appearance.mode.colorScheme) .tint(palette.accent) .background(palette.canvas.ignoresSafeArea()) + .task { + for await _ in NotificationCenter.default.notifications(named: .NSProcessInfoPowerStateDidChange) { + lowPowerMode = ProcessInfo.processInfo.isLowPowerModeEnabled + } + } } } diff --git a/ios/AidenOnTheGo/Features/Bots/AidenBotsHomeView.swift b/ios/AidenOnTheGo/Features/Bots/AidenBotsHomeView.swift index d5e06054de..62c286b608 100644 --- a/ios/AidenOnTheGo/Features/Bots/AidenBotsHomeView.swift +++ b/ios/AidenOnTheGo/Features/Bots/AidenBotsHomeView.swift @@ -237,6 +237,7 @@ private struct AidenBotHomeSkeletonView: View { struct AidenBotSkeletonBlock: View { @Environment(\.aidenPalette) private var palette + @Environment(\.aidenLowPowerMode) private var lowPowerMode let width: CGFloat? let height: CGFloat let radius: CGFloat @@ -247,7 +248,7 @@ struct AidenBotSkeletonBlock: View { RoundedRectangle(cornerRadius: radius, style: .continuous) .fill(palette.raised) .overlay { - if !reduceMotion { + if !reduceMotion && !lowPowerMode { TimelineView(.animation(minimumInterval: 1.0 / 30.0)) { timeline in let duration = 1.6 let elapsed = timeline.date.timeIntervalSinceReferenceDate diff --git a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift index 60adf170ba..b8c9506233 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift @@ -5219,11 +5219,12 @@ private struct AidenActivityStepLine: View { private struct AidenActivityShimmerModifier: ViewModifier { @Environment(\.aidenReduceMotion) private var reduceMotion + @Environment(\.aidenLowPowerMode) private var lowPowerMode let active: Bool @ViewBuilder func body(content: Content) -> some View { - if active && !reduceMotion { + if active && !reduceMotion && !lowPowerMode { content.overlay { GeometryReader { proxy in TimelineView(.animation(minimumInterval: 1 / 30)) { context in diff --git a/ios/AidenOnTheGo/Features/Shared/ThinkingOrbsKit/ThinkingOrb.swift b/ios/AidenOnTheGo/Features/Shared/ThinkingOrbsKit/ThinkingOrb.swift index cb2195bf11..31c8c8dd0b 100644 --- a/ios/AidenOnTheGo/Features/Shared/ThinkingOrbsKit/ThinkingOrb.swift +++ b/ios/AidenOnTheGo/Features/Shared/ThinkingOrbsKit/ThinkingOrb.swift @@ -23,6 +23,7 @@ public struct ThinkingOrb: View { @Environment(\.colorScheme) private var colorScheme @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.aidenLowPowerMode) private var lowPowerMode // ImageRenderer never advances a TimelineView, so snapshot.sh injects a // fixed instant here to capture a deterministic frame. @Environment(\.orbFrozenTime) private var frozenTime @@ -67,11 +68,13 @@ public struct ThinkingOrb: View { // directly, so applying the preset speed here would compare // two different instants and report a false mismatch. canvas(preset: preset, t: frozenTime) - } else if reduceMotion || paused { + } else if reduceMotion || paused || lowPowerMode { // one static, deterministic frame — same instant as the web canvas(preset: preset, t: OrbSpec.reducedMotionT * effSpeed) } else { - TimelineView(.animation(paused: paused)) { timeline in + // Capped at 30 fps: the orb is decorative, and ProMotion + // displays would otherwise redraw the Canvas at 120 Hz. + TimelineView(.animation(minimumInterval: 1.0 / 30.0, paused: paused)) { timeline in // One shared clock, so several orbs on screen stay in // phase exactly as they do on the web. let t = timeline.date.timeIntervalSinceReferenceDate * effSpeed From cb2f4554dc6bd6e356cda37fa7f2f392ca73068e Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 3 Oct 2026 16:00:58 -0400 Subject: [PATCH 08/10] perf(ios): refetch only when returning from the background (EXT-11) Transient inactive bounces (Control Center, app switcher, system prompts) no longer rerun the full reconnect or chat reload, or stop progress streams. A newer chat load epoch cancels an older in-flight load. Co-Authored-By: Claude Opus 5.5 --- ios/AidenOnTheGo.xcodeproj/project.pbxproj | 4 ++ ios/AidenOnTheGo/ContentView.swift | 11 +++-- .../Features/Remote/AidenChatFeature.swift | 26 +++++++---- .../Remote/AidenSceneRefreshGate.swift | 45 +++++++++++++++++++ .../AidenStreamingPerformanceTests.swift | 30 +++++++++++++ 5 files changed, 104 insertions(+), 12 deletions(-) create mode 100644 ios/AidenOnTheGo/Features/Remote/AidenSceneRefreshGate.swift diff --git a/ios/AidenOnTheGo.xcodeproj/project.pbxproj b/ios/AidenOnTheGo.xcodeproj/project.pbxproj index 538a534864..8e80e8c2df 100644 --- a/ios/AidenOnTheGo.xcodeproj/project.pbxproj +++ b/ios/AidenOnTheGo.xcodeproj/project.pbxproj @@ -21,6 +21,7 @@ A0D700000000000000000002 /* AidenSSEParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000012 /* AidenSSEParser.swift */; }; A0D700000000000000000003 /* AidenChatCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000013 /* AidenChatCache.swift */; }; A0D700000000000000000004 /* AidenChatFeature.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000014 /* AidenChatFeature.swift */; }; + A0F100000000000000000041 /* AidenSceneRefreshGate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0F100000000000000000040 /* AidenSceneRefreshGate.swift */; }; A0F100000000000000000031 /* AidenMarkdownContentCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0F100000000000000000030 /* AidenMarkdownContentCache.swift */; }; A0D700000000000000000005 /* AidenChatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0D700000000000000000015 /* AidenChatTests.swift */; }; A0F100000000000000000021 /* AidenStreamingPerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0F100000000000000000020 /* AidenStreamingPerformanceTests.swift */; }; @@ -147,6 +148,7 @@ A0D700000000000000000012 /* AidenSSEParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenSSEParser.swift; sourceTree = ""; }; A0D700000000000000000013 /* AidenChatCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatCache.swift; sourceTree = ""; }; A0F100000000000000000030 /* AidenMarkdownContentCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenMarkdownContentCache.swift; sourceTree = ""; }; + A0F100000000000000000040 /* AidenSceneRefreshGate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenSceneRefreshGate.swift; sourceTree = ""; }; A0D700000000000000000014 /* AidenChatFeature.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatFeature.swift; sourceTree = ""; }; A0F100000000000000000020 /* AidenStreamingPerformanceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenStreamingPerformanceTests.swift; sourceTree = ""; }; A0D700000000000000000015 /* AidenChatTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AidenChatTests.swift; sourceTree = ""; }; @@ -411,6 +413,7 @@ A0D600000000000000000015 /* AidenPairingView.swift */, A0D600000000000000000016 /* AidenWorkspaceShellView.swift */, A0D700000000000000000014 /* AidenChatFeature.swift */, + A0F100000000000000000040 /* AidenSceneRefreshGate.swift */, A0F100000000000000000030 /* AidenMarkdownContentCache.swift */, ); path = Remote; @@ -765,6 +768,7 @@ A0D700000000000000000002 /* AidenSSEParser.swift in Sources */, A0D700000000000000000003 /* AidenChatCache.swift in Sources */, A0D700000000000000000004 /* AidenChatFeature.swift in Sources */, + A0F100000000000000000041 /* AidenSceneRefreshGate.swift in Sources */, A0F100000000000000000031 /* AidenMarkdownContentCache.swift in Sources */, A0D800000000000000000001 /* AidenAppearance.swift in Sources */, A0D800000000000000000003 /* AidenVoiceInput.swift in Sources */, diff --git a/ios/AidenOnTheGo/ContentView.swift b/ios/AidenOnTheGo/ContentView.swift index 70a2b8d373..957768e39e 100644 --- a/ios/AidenOnTheGo/ContentView.swift +++ b/ios/AidenOnTheGo/ContentView.swift @@ -5,6 +5,7 @@ struct ContentView: View { @Environment(\.scenePhase) private var scenePhase @AppStorage("aiden.mobileOnboarding.v1.complete") private var hasCompletedMobileOnboarding = false @State private var navigationRequest: AidenNavigationRequest? + @State private var sceneRefreshGate = AidenSceneRefreshGate(refreshOnFirstActivation: true) var body: some View { Group { @@ -33,8 +34,8 @@ struct ContentView: View { Task { await open(request) } } .onChange(of: scenePhase) { _, phase in - switch phase { - case .active: + switch sceneRefreshGate.transition(to: phase) { + case .refresh: guard coordinator.connectionState != .needsPairing else { return } Task { await coordinator.connectActiveInstallation() @@ -47,9 +48,11 @@ struct ContentView: View { ) } } - case .background: + case .suspend: Task { await AidenRemoteLiveActivityManager.shared.markAllStale() } - default: + case .resume, .none: + // Returning from a transient `.inactive` (Control Center, + // app switcher, system prompts) keeps the live connection. break } } diff --git a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift index b8c9506233..0ccfd42cf1 100644 --- a/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift +++ b/ios/AidenOnTheGo/Features/Remote/AidenChatFeature.swift @@ -4084,6 +4084,8 @@ struct AidenChatDetailView: View { @Environment(\.aidenPalette) private var palette @Environment(\.scenePhase) private var scenePhase @State private var model: AidenChatViewModel + @State private var sceneRefreshGate = AidenSceneRefreshGate(refreshOnFirstActivation: false) + @State private var chatLoadEpoch = 0 @State private var composerHeight: CGFloat = 132 @State private var botToolsModel: AidenBotChatToolsModel? @State private var botSheet: AidenBotChatSheet? @@ -4184,11 +4186,10 @@ struct AidenChatDetailView: View { .navigationBarTitleDisplayMode(.inline) .toolbar { chatToolbar } .safeAreaInset(edge: .top, spacing: 0) { botIdentityInset } - .task(id: scenePhase) { - guard scenePhase == .active else { - model.stopProgressObservation() - return - } + .task(id: chatLoadEpoch) { + // Loads on appear and after each return from the background. A + // newer epoch cancels an older load still in flight. + guard scenePhase != .background else { return } await model.load(observeProgress: true) } .task(id: coordinator?.server?.serverTime) { @@ -4240,17 +4241,26 @@ struct AidenChatDetailView: View { model.setHapticsActive(true) model.setChatForegrounded(true) model.setSceneActive(scenePhase == .active) + if scenePhase == .background { _ = sceneRefreshGate.transition(to: .background) } } .onChange(of: model.readAloudCandidateID) { _, candidate in if let active = model.readAloud.activeMessageID, active != candidate { model.readAloud.stop() } } .onChange(of: scenePhase) { _, phase in model.setSceneActive(phase == .active) - if phase == .active { - model.startProgressObservation() - } else { + if phase != .active { model.readAloud.stop() + } + switch sceneRefreshGate.transition(to: phase) { + case .refresh: + chatLoadEpoch &+= 1 + case .resume: + model.startProgressObservation() + case .suspend: model.stopProgressObservation() + case .none: + // `.inactive` is transient; progress keeps streaming. + break } } .onDisappear { diff --git a/ios/AidenOnTheGo/Features/Remote/AidenSceneRefreshGate.swift b/ios/AidenOnTheGo/Features/Remote/AidenSceneRefreshGate.swift new file mode 100644 index 0000000000..a184c758e8 --- /dev/null +++ b/ios/AidenOnTheGo/Features/Remote/AidenSceneRefreshGate.swift @@ -0,0 +1,45 @@ +import SwiftUI + +/// Decides when a scene-phase change should refetch remote state. +/// +/// `.inactive` is transient and frequent: Control Center, Notification +/// Center, the app switcher, system alerts, and Face ID prompts all pass +/// through it while the app stays on screen and its streams stay open. +/// Refetching on every `.inactive` to `.active` bounce repeated the full +/// reconnect or chat reload for no new information. Only a return from +/// `.background`, where streams are suspended and state can go stale, +/// requires a refresh. +struct AidenSceneRefreshGate: Equatable { + enum Action: Equatable { + /// Refetch, then resume live observation. + case refresh + /// Resume live observation without refetching. + case resume + /// Suspend live observation; the next activation refreshes. + case suspend + /// Transient phase; leave everything running. + case none + } + + private(set) var needsRefresh: Bool + + /// `refreshOnFirstActivation` is false when the caller already loads on + /// appear, and true when the first `.active` transition performs the load. + init(refreshOnFirstActivation: Bool) { + needsRefresh = refreshOnFirstActivation + } + + mutating func transition(to phase: ScenePhase) -> Action { + switch phase { + case .background: + needsRefresh = true + return .suspend + case .active: + guard needsRefresh else { return .resume } + needsRefresh = false + return .refresh + default: + return .none + } + } +} diff --git a/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift b/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift index a51d2292b8..0f8f6401d4 100644 --- a/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift +++ b/ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift @@ -217,6 +217,36 @@ final class AidenStreamingPerformanceTests: XCTestCase { XCTAssertEqual(cache.parsedCharacterCount - parsedBefore, "Tail.\n".utf8.count) } + // MARK: - Scene refresh + + func testTransientInactiveBouncesNeverRefetchButBackgroundReturnsDo() { + var gate = AidenSceneRefreshGate(refreshOnFirstActivation: false) + // Control Center, the app switcher, and system prompts. + for _ in 0..<5 { + XCTAssertEqual(gate.transition(to: .inactive), .none) + XCTAssertEqual(gate.transition(to: .active), .resume) + } + XCTAssertEqual(gate.transition(to: .inactive), .none) + XCTAssertEqual(gate.transition(to: .background), .suspend) + XCTAssertEqual(gate.transition(to: .inactive), .none) + XCTAssertEqual(gate.transition(to: .active), .refresh) + XCTAssertEqual(gate.transition(to: .active), .resume, "One return refreshes once.") + + // Repeated background trips before activation still refresh once. + _ = gate.transition(to: .background) + _ = gate.transition(to: .background) + XCTAssertEqual(gate.transition(to: .active), .refresh) + XCTAssertEqual(gate.transition(to: .active), .resume) + } + + func testAGateThatOwnsTheInitialLoadRefreshesOnFirstActivation() { + var gate = AidenSceneRefreshGate(refreshOnFirstActivation: true) + XCTAssertEqual(gate.transition(to: .inactive), .none) + XCTAssertEqual(gate.transition(to: .active), .refresh) + XCTAssertEqual(gate.transition(to: .inactive), .none) + XCTAssertEqual(gate.transition(to: .active), .resume) + } + // MARK: - SSE line decoding private func decodeLines(_ text: String) async throws -> [String] { From a28a1f7c3a7921a956e2424a065a05bbf95c28b3 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sat, 3 Oct 2026 16:02:44 -0400 Subject: [PATCH 09/10] docs(memory): record the iOS streaming performance workstream Co-Authored-By: Claude Opus 5.5 --- .memory/perf-ios-streaming.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .memory/perf-ios-streaming.md diff --git a/.memory/perf-ios-streaming.md b/.memory/perf-ios-streaming.md new file mode 100644 index 0000000000..b264179e27 --- /dev/null +++ b/.memory/perf-ios-streaming.md @@ -0,0 +1,15 @@ +# iOS streaming performance (EXT-9..21) + +Branch `perf/ios-streaming`. iOS-only; no Remote protocol, fixture, or persisted-format change. Behavioral coverage lives in `ios/AidenOnTheGoTests/AidenStreamingPerformanceTests.swift` plus focused additions in `AidenChatTests` and `AidenRemoteClientTests`. + +- EXT-9: `AidenLatestValueThrottle` (LiveActivities/) coalesces Live Activity content to the newest value at most once per second. Status, approval, stale, finish, and end paths are urgent and bypass or cancel the pending write. +- EXT-10: `AidenMarkdownContentCache` (Features/Remote/) splits Markdown only at safe blank-line block boundaries and caches parsed settled chunks in a bounded LRU (512 entries / 400k UTF-8 bytes). Only the open tail is reparsed. Splitting is disabled for link/footnote definitions and blank-line-spanning HTML. Oracle: for every prefix of the fixtures, the chunked result equals `MarkdownContent(prefix)`. `AidenLiveResponseView` evaluates its projections once per render. +- EXT-12/17: the chat open takes a single progress snapshot that observation reuses. Reconciliation backoff uses equal jitter (cap 30 s). Android has the same backoff shape in `AidenChat.kt`, left to the Android workstream. +- EXT-19: `AidenSSELineDecoder` (in AidenSSEParser.swift) checks cancellation and validates UTF-8 once per line. LF/CRLF handling, blank-line delimiters, EOF discard, and the frame limit are unchanged. Do not use `bytes.lines`, because it drops blank lines. +- EXT-13: `activeClient()` returns the cached client before reading the Keychain. The key covers instance, device, credential scope, and activation generation. +- EXT-14/16: interactive calls use a 5-minute resource budget. SSE streams use a separate session (1 h resource, 30 s idle = two missed 15 s heartbeats). Clients `finishTasksAndInvalidate` the sessions they own in `deinit`; injected test sessions are never invalidated. +- EXT-11: `AidenSceneRefreshGate` refetches only on `.active` after `.background`. ContentView and the chat detail ignore transient `.inactive` bounces. The chat load is keyed by an epoch, so a newer load cancels an older one. No conditional fetch, because that needs a protocol change. +- EXT-18: ThinkingOrb is capped at 30 fps. The orb and the shimmers hold still under the `aidenLowPowerMode` environment, which `AidenAppearanceRoot` injects. +- Deferred EXT-15: `AidenChatCache.admittedChats` is the in-memory winner for failed disk writes and list merges. Bounding it needs a design for committed-only eviction plus disk fallback. Summary writes happen once per `saveChat` (on load or send, not per token), so a debounce would gain little. +- Skipped EXT-21: the settled-rows child's `ForEach` flattens into the parent `LazyVStack` (custom views and `EquatableView` are transparent to list flattening), so rows stay lazy. Not profiled in Instruments. +- EXT-20: no broad file split. Only the new types were extracted into their own files. From 3c2026e0141a4ded96af1688634954be48a3dad0 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Sun, 4 Oct 2026 03:45:39 -0400 Subject: [PATCH 10/10] fix(ios): register the new streaming sources on the reviewed iOS allowlists Co-Authored-By: Claude Opus 5.5 --- scripts/check-ios-shipping-target.test.mjs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/check-ios-shipping-target.test.mjs b/scripts/check-ios-shipping-target.test.mjs index 97142b7510..0e5c3988ae 100644 --- a/scripts/check-ios-shipping-target.test.mjs +++ b/scripts/check-ios-shipping-target.test.mjs @@ -67,9 +67,11 @@ const appSourcePaths = [ "AidenOnTheGo/Features/Chat/ComposerVoiceInputController.swift", "AidenOnTheGo/Features/Remote/AidenBotChatToolsView.swift", "AidenOnTheGo/Features/Remote/AidenChatFeature.swift", + "AidenOnTheGo/Features/Remote/AidenMarkdownContentCache.swift", "AidenOnTheGo/Features/Remote/AidenPairingView.swift", "AidenOnTheGo/Features/Remote/AidenProductShellView.swift", "AidenOnTheGo/Features/Remote/AidenRemoteCoordinator.swift", + "AidenOnTheGo/Features/Remote/AidenSceneRefreshGate.swift", "AidenOnTheGo/Features/Remote/AidenScheduledRunNotifier.swift", "AidenOnTheGo/Features/Remote/AidenScheduledTasksView.swift", "AidenOnTheGo/Features/Remote/AidenWorkspaceEnvironmentView.swift", @@ -87,6 +89,7 @@ const appSourcePaths = [ "AidenOnTheGo/Features/Shared/ThinkingOrbsKit/Web.swift", "AidenOnTheGo/LiveActivities/AgentRunActivityAttributes.swift", "AidenOnTheGo/LiveActivities/AidenDeepLink.swift", + "AidenOnTheGo/LiveActivities/AidenLatestValueThrottle.swift", "AidenOnTheGo/LiveActivities/AidenRemoteLiveActivityManager.swift", "AidenOnTheGo/Models/AidenBot.swift", "AidenOnTheGo/Models/AidenChat.swift", @@ -116,6 +119,7 @@ const testSources = [ "AidenRemoteClientTests.swift", "AidenRemotePhase0Tests.swift", "AidenScheduledTaskTests.swift", + "AidenStreamingPerformanceTests.swift", "AidenWorkspaceEnvironmentTests.swift", ];