Repository navigation
fix(mobile): keep agent widgets updated in the background #14861
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
jakeleventhal
wants to merge
8
commits into
pingdotgg:main
from
jakeleventhal:t3code/agent-widget-background-refresh-v2
+6,416
−917
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
29f92f9
fix(mobile): keep agent widgets updated in the background
jakeleventhal 7f2a6bd
fix(mobile): preserve widget replay and current Effect checks
jakeleventhal 00d18ca
fix(relay): use the current activity projection type
jakeleventhal 735f034
Merge remote-tracking branch 'github/main' into pr-14861
maria-rcks 8728c9a
fix(mobile): keep widget placeholders and stale-only summaries accurate
maria-rcks d9a61d7
fix(server): publish a waiting child's parent once at startup
maria-rcks 03b4a5a
fix: snoozed awareness rows and superseded widget reads
maria-rcks 01691ee
Merge remote-tracking branch 'github/main' into pr-14861
maria-rcks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
92 changes: 92 additions & 0 deletions
92
apps/mobile/modules/t3-native-controls/ios/AgentWidgetCredential.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| import Foundation | ||
| import Security | ||
| import CryptoKit | ||
|
|
||
| // Both targets already belong to this app group, which is also a Keychain | ||
| // access group. Keep the bearer credential out of preferences and backups. | ||
| enum AgentWidgetCredential { | ||
| private static func query(account: String) -> [String: Any]? { | ||
| guard let group = Bundle.main.object(forInfoDictionaryKey: "ExpoWidgetsAppGroupIdentifier") as? String else { return nil } | ||
| return [ | ||
| kSecClass as String: kSecClassGenericPassword, | ||
| kSecAttrService as String: "t3-agent-widget", | ||
| kSecAttrAccount as String: account, | ||
| kSecAttrAccessGroup as String: group, | ||
| ] | ||
| } | ||
|
|
||
| static func read(account: String = "read-capability") -> String? { | ||
| guard var query = query(account: account) else { return nil } | ||
| query[kSecReturnData as String] = true | ||
| query[kSecMatchLimit as String] = kSecMatchLimitOne | ||
| var result: CFTypeRef? | ||
| guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, | ||
| let data = result as? Data else { return nil } | ||
| return String(data: data, encoding: .utf8) | ||
| } | ||
|
|
||
| static func store(_ token: String, account: String = "read-capability") -> Bool { | ||
| guard var query = query(account: account) else { return false } | ||
| query[kSecValueData as String] = Data(token.utf8) | ||
| query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly | ||
| var status = SecItemAdd(query as CFDictionary, nil) | ||
| if status == errSecDuplicateItem, let base = self.query(account: account) { | ||
| status = SecItemUpdate(base as CFDictionary, [ | ||
| kSecValueData as String: Data(token.utf8), | ||
| kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, | ||
| ] as CFDictionary) | ||
| } | ||
| return status == errSecSuccess | ||
| } | ||
|
|
||
| static func remove(account: String = "read-capability") { | ||
| guard let query = query(account: account) else { return } | ||
| SecItemDelete(query as CFDictionary) | ||
| } | ||
|
|
||
| static func preserveRevocation(_ request: URLRequest) -> Bool { | ||
| guard let revocation = Revocation(request: request), | ||
| let data = try? JSONEncoder().encode(revocation), | ||
| let value = String(data: data, encoding: .utf8) else { return false } | ||
| return store(value, account: revocation.account) | ||
| } | ||
|
|
||
| static func pendingRevocations() -> [Revocation] { | ||
| guard var query = query(account: "") else { return [] } | ||
| query.removeValue(forKey: kSecAttrAccount as String) | ||
| query[kSecReturnAttributes as String] = true | ||
| query[kSecReturnData as String] = true | ||
| query[kSecMatchLimit as String] = kSecMatchLimitAll | ||
| var result: CFTypeRef? | ||
| guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, | ||
| let items = result as? [[String: Any]] else { return [] } | ||
| return items.compactMap { item in | ||
| guard (item[kSecAttrAccount as String] as? String)?.hasPrefix("revoke-") == true, | ||
| let data = item[kSecValueData as String] as? Data else { return nil } | ||
| return try? JSONDecoder().decode(Revocation.self, from: data) | ||
| } | ||
| } | ||
|
|
||
| struct Revocation: Codable { | ||
| let url: URL | ||
| let token: String | ||
|
|
||
| init?(request: URLRequest) { | ||
| guard let url = request.url, let header = request.value(forHTTPHeaderField: "Authorization"), | ||
| header.hasPrefix("Bearer ") else { return nil } | ||
| self.url = url | ||
| self.token = String(header.dropFirst(7)) | ||
| } | ||
|
|
||
| var account: String { | ||
| "revoke-" + SHA256.hash(data: Data((url.absoluteString + "\n" + token).utf8)).map { String(format: "%02x", $0) }.joined() | ||
| } | ||
|
|
||
| var request: URLRequest { | ||
| var request = URLRequest(url: url, timeoutInterval: 10) | ||
| request.httpMethod = "DELETE" | ||
| request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") | ||
| return request | ||
| } | ||
| } | ||
| } |
61 changes: 61 additions & 0 deletions
61
apps/mobile/modules/t3-native-controls/ios/AgentWidgetStorage.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import Foundation | ||
| import Darwin | ||
|
|
||
| enum AgentWidgetStorage { | ||
| static let timelineKey = "__expo_widgets_AgentActivity_timeline" | ||
| static let generationKey = "t3_agent_widget_generation" | ||
|
|
||
| static func withLock<T>(_ body: (UserDefaults) -> T) -> T? { | ||
| guard let group = Bundle.main.object(forInfoDictionaryKey: "ExpoWidgetsAppGroupIdentifier") as? String, | ||
| let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group), | ||
| let defaults = UserDefaults(suiteName: group) else { return nil } | ||
| return withLock(at: directory.appendingPathComponent("agent-widget.lock"), defaults: defaults, body) | ||
| } | ||
|
|
||
| // App and extension must synchronize preferences inside the same OS lock. | ||
| static func withLock<T>(at url: URL, defaults: UserDefaults, _ body: (UserDefaults) -> T) -> T? { | ||
| let fd = open(url.path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR) | ||
| guard fd >= 0 else { return nil } | ||
| defer { close(fd) } | ||
| guard flock(fd, LOCK_EX) == 0 else { return nil } | ||
| defer { flock(fd, LOCK_UN) } | ||
| defaults.synchronize() | ||
| defer { defaults.synchronize() } | ||
| return body(defaults) | ||
| } | ||
|
|
||
| static func generation(in defaults: UserDefaults) -> String { | ||
| if let generation = defaults.string(forKey: generationKey) { return generation } | ||
| let generation = UUID().uuidString | ||
| defaults.set(generation, forKey: generationKey) | ||
| return generation | ||
| } | ||
|
|
||
| static func owns(_ props: [String: Any]?, in defaults: UserDefaults) -> Bool { | ||
| guard let owner = props?[generationKey] as? String else { return false } | ||
| return owner == defaults.string(forKey: generationKey) | ||
| } | ||
|
|
||
| @discardableResult | ||
| static func commit(_ entries: [[String: Any]], generation: String, in defaults: UserDefaults) -> Bool { | ||
| guard defaults.string(forKey: generationKey) == generation else { return false } | ||
| defaults.set(entries.map { entry in | ||
| var entry = entry | ||
| var props = (entry["props"] as? [String: Any] ?? [:]).filter { !($0.value is NSNull) } | ||
| props[generationKey] = generation | ||
| entry["props"] = props | ||
| return entry | ||
| }, forKey: timelineKey) | ||
| return true | ||
| } | ||
|
|
||
| static func retryRevocations() { | ||
| let pending = withLock { _ in AgentWidgetCredential.pendingRevocations() } ?? [] | ||
| for revocation in pending { | ||
| URLSession.shared.dataTask(with: revocation.request) { _, response, error in | ||
| guard error == nil, (response as? HTTPURLResponse)?.statusCode == 200 else { return } | ||
| _ = withLock { _ in AgentWidgetCredential.remove(account: revocation.account) } | ||
| }.resume() | ||
| } | ||
| } | ||
| } |
75 changes: 75 additions & 0 deletions
75
apps/mobile/modules/t3-native-controls/ios/T3AgentWidgetConfiguration.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import Foundation | ||
| import Security | ||
| import WidgetKit | ||
|
|
||
| // Shared with the WidgetKit extension, which runs independently of React Native. | ||
| enum T3AgentWidgetConfiguration { | ||
| static func token(identity: String) -> String? { | ||
| let token = AgentWidgetStorage.withLock { defaults -> String? in | ||
| if defaults.string(forKey: "t3_agent_widget_identity") == identity, | ||
| let token = AgentWidgetCredential.read(), | ||
| !AgentWidgetCredential.pendingRevocations().contains(where: { $0.token == token }) { return token } | ||
| _ = clearStoredState(in: defaults) | ||
| // If Keychain cannot preserve revocation, keep the disabled credential for retry. | ||
| guard AgentWidgetCredential.read() == nil else { return nil } | ||
| var bytes = [UInt8](repeating: 0, count: 32) | ||
| guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { return nil } | ||
| let token = bytes.map { String(format: "%02x", $0) }.joined() | ||
| guard AgentWidgetCredential.store(token) else { return nil } | ||
| defaults.set(identity, forKey: "t3_agent_widget_identity") | ||
| return token | ||
| }.flatMap { $0 } | ||
| AgentWidgetStorage.retryRevocations() | ||
| return token | ||
| } | ||
|
|
||
| static func configure(url: String, token: String) { | ||
| _ = AgentWidgetStorage.withLock { defaults in | ||
| guard defaults.string(forKey: "t3_agent_widget_identity") != nil, | ||
| AgentWidgetCredential.read() == token else { return } | ||
| defaults.set(url, forKey: "t3_agent_widget_url") | ||
| } | ||
| AgentWidgetStorage.retryRevocations() | ||
| WidgetCenter.shared.reloadTimelines(ofKind: "AgentActivity") | ||
| } | ||
|
|
||
| static func observe(props: String, timeline: String) -> Bool { | ||
| guard let data = timeline.data(using: .utf8), | ||
| let entries = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { return false } | ||
| let stored = AgentWidgetStorage.withLock { defaults in | ||
| defaults.set(props, forKey: "t3_agent_widget_local_observation") | ||
| return AgentWidgetStorage.commit(entries, generation: AgentWidgetStorage.generation(in: defaults), in: defaults) | ||
| } ?? false | ||
| AgentWidgetStorage.retryRevocations() | ||
| if stored { WidgetCenter.shared.reloadTimelines(ofKind: "AgentActivity") } | ||
| return stored | ||
| } | ||
|
|
||
| static func clear() { | ||
| _ = AgentWidgetStorage.withLock { defaults in clearStoredState(in: defaults) } | ||
| WidgetCenter.shared.reloadTimelines(ofKind: "AgentActivity") | ||
| AgentWidgetStorage.retryRevocations() | ||
| } | ||
|
|
||
| @discardableResult | ||
| static func clearStoredState(in defaults: UserDefaults, storeRevocation: (URLRequest) -> Bool = AgentWidgetCredential.preserveRevocation) -> URLRequest? { | ||
| let url = defaults.string(forKey: "t3_agent_widget_url").flatMap(URL.init(string:)) | ||
| // Revoke the pre-Keychain development credential when upgrading this branch. | ||
| let token = AgentWidgetCredential.read() ?? defaults.string(forKey: "t3_agent_widget_token") | ||
| defaults.set(UUID().uuidString, forKey: AgentWidgetStorage.generationKey) | ||
| for key in ["t3_agent_widget_identity", "t3_agent_widget_local_observation", AgentWidgetStorage.timelineKey] { | ||
| defaults.removeObject(forKey: key) | ||
| } | ||
| var request: URLRequest? | ||
| if let url, let token { | ||
| var revoke = URLRequest(url: url, timeoutInterval: 10) | ||
| revoke.httpMethod = "DELETE" | ||
| revoke.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") | ||
| guard storeRevocation(revoke) else { return nil } | ||
| request = revoke | ||
| } | ||
| AgentWidgetCredential.remove() | ||
|
jakeleventhal marked this conversation as resolved.
Resolved
|
||
| for key in ["t3_agent_widget_token", "t3_agent_widget_url"] { defaults.removeObject(forKey: key) } | ||
| return request | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.