Files
openchamber/packages/mobile/ios/App/OpenChamberNotificationService/NotificationService.swift
T
Bohdan Triapitsyn 85400459e9 perf: overhaul session loading, caching, and runtime isolation (#2360)
Improve OpenChamber responsiveness under large session workloads while fixing
cache, synchronization, and persistence correctness across runtimes, projects,
directories, and worktrees.

- prioritize selected and visible sessions during bootstrap and defer
  non-critical enrichment work
- reduce redundant message loading, event processing, store publication, and
  hidden sidebar work
- prevent stale session and message requests from overwriting newer
  authoritative state
- preserve existing data when authoritative fetches fail instead of treating
  failures as successful empty responses
- scope session materialization, messages, drafts, queues, todos, pins,
  permissions, folders, tabs, Git state, and pull request data by runtime and
  directory identity
- harden runtime switching, reconnect, cleanup, mutation reconciliation, and
  persisted-state ordering
- preserve live subagent Task linkage when metadata arrives after an older
  message request or while streaming parts are suspended
- coalesce overlapping tail refreshes without losing newer refresh demand
- improve cold-session loading by moving deferrable work out of the critical
  bootstrap path
- isolate URL authentication, mobile credentials, native secrets, and other
  runtime-owned state across endpoint changes
- bound long-lived caches and remove avoidable allocations from event and
  rendering hot paths
- limit virtualization to archive collections where it improves rendering
  without disrupting active sidebar layout
- stabilize session folders, pin ordering, expanded state, and persisted
  sidebar behavior
- open skill files through the same secure editor and outside-workspace grant
  flow used by file navigation, including worktree sessions
- expand regression coverage for stale completions, runtime collisions,
  reconnect behavior, persistence races, authoritative empty results, and
  subagent refresh ordering
- document the updated synchronization, cache ownership, performance, and
  runtime-isolation invariants
2026-07-21 20:52:20 +03:00

83 lines
3.4 KiB
Swift

import UserNotifications
import WidgetKit
/// Runs on every incoming push that carries `mutable-content: 1` — even when the app is closed
/// — and refreshes the widgets' shared snapshot so the home/lock-screen attention count and
/// unread dot stay current without the app having to foreground. It makes NO network calls:
/// it reads the count the server already put in `aps.badge` and the `sessionId` from the push,
/// updates the App Group snapshot the app wrote, and reloads the widget timelines. The app
/// still overwrites the snapshot with the authoritative full list on its next foreground.
class NotificationService: UNNotificationServiceExtension {
private static let appGroup = "group.com.openchamber.app"
private static let snapshotKey = "widgetSnapshot"
private var contentHandler: ((UNNotificationContent) -> Void)?
private var bestAttempt: UNMutableNotificationContent?
override func didReceive(
_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
) {
self.contentHandler = contentHandler
self.bestAttempt = request.content.mutableCopy() as? UNMutableNotificationContent
refreshWidgetSnapshot(from: request)
// Deliver the notification unchanged (we only used the push to refresh widgets).
contentHandler(bestAttempt ?? request.content)
}
override func serviceExtensionTimeWillExpire() {
if let handler = contentHandler {
handler(bestAttempt ?? UNNotificationContent())
}
}
private func refreshWidgetSnapshot(from request: UNNotificationRequest) {
guard let defaults = UserDefaults(suiteName: Self.appGroup) else { return }
var snapshot: [String: Any] = [
"runtimeKey": request.content.userInfo["runtimeKey"] as? String ?? "",
"attentionCount": 0,
"recentSessions": [],
]
if let json = defaults.string(forKey: Self.snapshotKey),
let data = json.data(using: .utf8),
let stored = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
snapshot = stored
}
if let pushRuntimeKey = request.content.userInfo["runtimeKey"] as? String,
!pushRuntimeKey.isEmpty,
snapshot["runtimeKey"] as? String != pushRuntimeKey {
snapshot = [
"runtimeKey": pushRuntimeKey,
"attentionCount": 0,
"recentSessions": [],
]
}
// Attention count: authoritative server value carried in aps.badge.
if let badge = request.content.badge as? Int {
snapshot["attentionCount"] = badge
}
// Mark the pushed session unread in the existing recent list (best-effort; the full
// list/titles only refresh when the app next foregrounds).
if let sessionId = request.content.userInfo["sessionId"] as? String,
var sessions = snapshot["recentSessions"] as? [[String: Any]] {
for index in sessions.indices where sessions[index]["id"] as? String == sessionId {
sessions[index]["unread"] = true
}
snapshot["recentSessions"] = sessions
}
if let data = try? JSONSerialization.data(withJSONObject: snapshot),
let json = String(data: data, encoding: .utf8) {
defaults.set(json, forKey: Self.snapshotKey)
}
WidgetCenter.shared.reloadAllTimelines()
}
}