498e6b8064
Android UI Tests / ui-tests (pull_request) Has been cancelled
Users with multiple residences can now pick which one a given home- screen widget shows tasks for. Pinning two widgets — one per house — lets each surface tasks for only that residence; users who keep the configuration untouched continue to see all residences (the previous default), so single-home users see no behavioural change. Implementation (iOS only — Android Glance follow-up is scoped in the issue): * `ConfigurationAppIntent` (HoneyDue widget extension) gains an optional `@Parameter` of type `WidgetResidenceEntity`. `AppIntents` renders it as a residence picker in the widget edit sheet. * `WidgetResidenceEntity` + `WidgetResidenceEntityQuery` resolve the user's residences from a new `widget_residences.json` sidecar in the App Group container (avoids a network call at config time). * `WidgetDataManager.saveResidences(from:)` writes that sidecar from the main app whenever `DataManagerObservable.myResidences` updates. Logout clears it along with the rest of the widget cache. * `WidgetDataManager.WidgetTask` + the widget extension's `CacheManager.CustomTask` both gain an optional `residence_id` field. Optional so older app builds that wrote pre-#6 widget cache continue to decode — those tasks pass through the filter for unscoped widgets and are hidden from scoped ones (safer than guessing). * `CacheManager.getUpcomingTasks(forResidenceId:)` and the pure helper `WidgetDataManager.filterTasks(_:forResidenceId:)` apply the filter. `Provider.timeline` / `snapshot` read `configuration.residence?.intId` and pass it through. Tests: new `WidgetResidenceFilterTests` (HoneyDueTests target, 5 cases) cover nil-passthrough, matching-id, no-match, missing-residence on a task, and order preservation. All five green. No Android changes in this commit — Glance widgets need a separate configuration activity and an actionStartActivity wiring that's non-trivial; tracking as a follow-up in the same issue. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
377 lines
13 KiB
Swift
377 lines
13 KiB
Swift
//
|
|
// AppIntent.swift
|
|
// honeyDue
|
|
//
|
|
// Created by Trey Tartt on 11/5/25.
|
|
//
|
|
|
|
import WidgetKit
|
|
import AppIntents
|
|
import Foundation
|
|
|
|
// MARK: - Widget Configuration Intent
|
|
|
|
/// Per-instance widget configuration. The `residence` parameter (added
|
|
/// for gitea#6) lets users with multiple residences pick which one a
|
|
/// given widget tile shows tasks for. When unset the widget continues
|
|
/// to display tasks across every residence — that's the single-home
|
|
/// default and matches pre-#6 behaviour for users who only have one
|
|
/// property.
|
|
struct ConfigurationAppIntent: WidgetConfigurationIntent {
|
|
static var title: LocalizedStringResource { "honeyDue Configuration" }
|
|
static var description: IntentDescription {
|
|
IntentDescription("Pick which residence this widget shows tasks for.")
|
|
}
|
|
|
|
@Parameter(title: "Residence")
|
|
var residence: WidgetResidenceEntity?
|
|
}
|
|
|
|
// MARK: - Residence Entity (configuration picker)
|
|
|
|
/// `AppEntity` exposing the user's residences to the widget's
|
|
/// configuration sheet. Reads from the `widget_residences.json`
|
|
/// sidecar that the main app writes via
|
|
/// `WidgetDataManager.saveResidences(...)`.
|
|
struct WidgetResidenceEntity: AppEntity, Identifiable, Hashable {
|
|
/// Backing residence id (matches `Residence.id` on the server). Stored
|
|
/// as `String` because `AppEntity.id` requires `Hashable`-conformance
|
|
/// for stable widget reconfiguration — Apple's docs recommend a stable
|
|
/// string identifier over `Int` so the widget timeline survives
|
|
/// device-id changes.
|
|
var id: String
|
|
|
|
var name: String
|
|
|
|
/// Convenience integer form for `CacheManager.getUpcomingTasks`.
|
|
var intId: Int? { Int(id) }
|
|
|
|
static var typeDisplayRepresentation: TypeDisplayRepresentation {
|
|
TypeDisplayRepresentation(name: "Residence")
|
|
}
|
|
|
|
var displayRepresentation: DisplayRepresentation {
|
|
DisplayRepresentation(title: "\(name)")
|
|
}
|
|
|
|
static var defaultQuery = WidgetResidenceEntityQuery()
|
|
}
|
|
|
|
/// Provides the residence choices the configuration sheet displays. The
|
|
/// list is sourced from the App-Group-shared `widget_residences.json`
|
|
/// the main app maintains; on a brand-new install (or signed-out state)
|
|
/// the sheet falls back to showing only the "All residences" implicit
|
|
/// option exposed by the optional parameter.
|
|
struct WidgetResidenceEntityQuery: EntityQuery {
|
|
/// Look up specific residences by id (used when the system needs to
|
|
/// re-resolve a saved configuration after the user reopens the
|
|
/// widget edit sheet).
|
|
func entities(for identifiers: [WidgetResidenceEntity.ID]) async throws -> [WidgetResidenceEntity] {
|
|
let known = loadAll()
|
|
return identifiers.compactMap { id in known.first(where: { $0.id == id }) }
|
|
}
|
|
|
|
/// Populate the picker. Sorted alphabetically so the list is stable
|
|
/// across refreshes — `WidgetDataManager.saveResidences` writes in
|
|
/// the order the API returned, which can shuffle on server-side
|
|
/// re-sorts.
|
|
func suggestedEntities() async throws -> [WidgetResidenceEntity] {
|
|
loadAll().sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
|
|
}
|
|
|
|
private func loadAll() -> [WidgetResidenceEntity] {
|
|
let raw = CacheManager.getResidences()
|
|
return raw.map { WidgetResidenceEntity(id: String($0.id), name: $0.name) }
|
|
}
|
|
}
|
|
|
|
// MARK: - Complete Task Intent
|
|
/// Marks a task as completed from the widget by calling the API directly
|
|
struct CompleteTaskIntent: AppIntent {
|
|
static var title: LocalizedStringResource { "Complete Task" }
|
|
static var description: IntentDescription { "Mark a task as completed" }
|
|
|
|
@Parameter(title: "Task ID")
|
|
var taskId: Int
|
|
|
|
@Parameter(title: "Task Title")
|
|
var taskTitle: String
|
|
|
|
init() {
|
|
self.taskId = 0
|
|
self.taskTitle = ""
|
|
}
|
|
|
|
init(taskId: Int, taskTitle: String) {
|
|
self.taskId = taskId
|
|
self.taskTitle = taskTitle
|
|
}
|
|
|
|
func perform() async throws -> some IntentResult {
|
|
print("CompleteTaskIntent: Starting completion for task \(taskId)")
|
|
|
|
// Check auth BEFORE marking pending — if auth fails the task should remain visible
|
|
guard let token = WidgetActionManager.shared.getAuthToken() else {
|
|
print("CompleteTaskIntent: No auth token available")
|
|
WidgetCenter.shared.reloadTimelines(ofKind: "honeyDue")
|
|
return .result()
|
|
}
|
|
|
|
guard let baseURL = WidgetActionManager.shared.getAPIBaseURL() else {
|
|
print("CompleteTaskIntent: No API base URL available")
|
|
WidgetCenter.shared.reloadTimelines(ofKind: "honeyDue")
|
|
return .result()
|
|
}
|
|
|
|
// Mark task as pending completion (optimistic UI) only after auth is confirmed
|
|
WidgetActionManager.shared.markTaskPendingCompletion(taskId: taskId)
|
|
|
|
// Reload widget immediately to update task list and stats
|
|
WidgetCenter.shared.reloadTimelines(ofKind: "honeyDue")
|
|
|
|
// Make API call to complete the task
|
|
let success = await WidgetAPIClient.quickCompleteTask(
|
|
taskId: taskId,
|
|
token: token,
|
|
baseURL: baseURL
|
|
)
|
|
|
|
if success {
|
|
print("CompleteTaskIntent: Task \(taskId) completed successfully")
|
|
// Mark tasks as dirty so main app refreshes on next launch
|
|
WidgetActionManager.shared.markTasksDirty()
|
|
} else {
|
|
print("CompleteTaskIntent: Failed to complete task \(taskId)")
|
|
// Task will remain hidden until it times out or app refreshes
|
|
}
|
|
|
|
// Reload widget
|
|
WidgetCenter.shared.reloadTimelines(ofKind: "honeyDue")
|
|
|
|
return .result()
|
|
}
|
|
}
|
|
|
|
// MARK: - Widget API Client
|
|
/// Lightweight API client for widget network calls
|
|
enum WidgetAPIClient {
|
|
/// Complete a task via the quick-complete endpoint
|
|
/// Returns true on success, false on failure
|
|
static func quickCompleteTask(taskId: Int, token: String, baseURL: String) async -> Bool {
|
|
let urlString = "\(baseURL)/tasks/\(taskId)/quick-complete/"
|
|
|
|
guard let url = URL(string: urlString) else {
|
|
print("WidgetAPIClient: Invalid URL: \(urlString)")
|
|
return false
|
|
}
|
|
|
|
var request = URLRequest(url: url)
|
|
request.httpMethod = "POST"
|
|
request.setValue("Token \(token)", forHTTPHeaderField: "Authorization")
|
|
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
request.timeoutInterval = 10 // Short timeout for widget
|
|
|
|
do {
|
|
let (_, response) = try await URLSession.shared.data(for: request)
|
|
|
|
if let httpResponse = response as? HTTPURLResponse {
|
|
let isSuccess = httpResponse.statusCode == 200
|
|
print("WidgetAPIClient: quick-complete response: \(httpResponse.statusCode)")
|
|
return isSuccess
|
|
}
|
|
return false
|
|
} catch {
|
|
print("WidgetAPIClient: Error completing task: \(error.localizedDescription)")
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Open Task Intent
|
|
/// Opens a specific task in the main app
|
|
struct OpenTaskIntent: AppIntent {
|
|
static var title: LocalizedStringResource { "Open Task" }
|
|
static var description: IntentDescription { "Open task details in the app" }
|
|
|
|
@Parameter(title: "Task ID")
|
|
var taskId: Int
|
|
|
|
init() {
|
|
self.taskId = 0
|
|
}
|
|
|
|
init(taskId: Int) {
|
|
self.taskId = taskId
|
|
}
|
|
|
|
static var openAppWhenRun: Bool { true }
|
|
|
|
func perform() async throws -> some IntentResult {
|
|
// The app will handle deep linking via URL scheme
|
|
return .result()
|
|
}
|
|
}
|
|
|
|
// MARK: - Widget Action Manager
|
|
/// Manages shared data between the main app and widget extension via App Group
|
|
final class WidgetActionManager {
|
|
static let shared = WidgetActionManager()
|
|
|
|
private let appGroupIdentifier: String = {
|
|
Bundle.main.infoDictionary?["AppGroupIdentifier"] as? String ?? "group.com.myhoneydue.honeyDue.dev"
|
|
}()
|
|
private let pendingTasksFileName = "widget_pending_tasks.json"
|
|
private let tokenKey = "widget_auth_token"
|
|
private let dirtyFlagKey = "widget_tasks_dirty"
|
|
private let apiBaseURLKey = "widget_api_base_url"
|
|
private let limitationsEnabledKey = "widget_limitations_enabled"
|
|
private let isPremiumKey = "widget_is_premium"
|
|
|
|
private var sharedDefaults: UserDefaults? {
|
|
UserDefaults(suiteName: appGroupIdentifier)
|
|
}
|
|
|
|
private init() {}
|
|
|
|
// MARK: - Shared Container Access
|
|
|
|
private var sharedContainerURL: URL? {
|
|
FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)
|
|
}
|
|
|
|
private var pendingTasksFileURL: URL? {
|
|
sharedContainerURL?.appendingPathComponent(pendingTasksFileName)
|
|
}
|
|
|
|
// MARK: - Auth Token Access
|
|
|
|
/// Get auth token from shared App Group (set by main app)
|
|
func getAuthToken() -> String? {
|
|
return sharedDefaults?.string(forKey: tokenKey)
|
|
}
|
|
|
|
/// Get API base URL from shared App Group (set by main app)
|
|
func getAPIBaseURL() -> String? {
|
|
return sharedDefaults?.string(forKey: apiBaseURLKey)
|
|
}
|
|
|
|
// MARK: - Dirty Flag
|
|
|
|
/// Mark tasks as dirty (needs refresh from server)
|
|
func markTasksDirty() {
|
|
sharedDefaults?.set(true, forKey: dirtyFlagKey)
|
|
sharedDefaults?.synchronize()
|
|
print("WidgetActionManager: Marked tasks as dirty")
|
|
}
|
|
|
|
// MARK: - Subscription Status
|
|
|
|
/// Check if limitations are enabled (from backend)
|
|
func areLimitationsEnabled() -> Bool {
|
|
return sharedDefaults?.bool(forKey: limitationsEnabledKey) ?? false
|
|
}
|
|
|
|
/// Check if user has premium subscription
|
|
func isPremium() -> Bool {
|
|
return sharedDefaults?.bool(forKey: isPremiumKey) ?? false
|
|
}
|
|
|
|
/// Check if widget should show interactive features
|
|
/// Returns true if: limitations disabled OR user is premium
|
|
func shouldShowInteractiveWidget() -> Bool {
|
|
let limitationsEnabled = areLimitationsEnabled()
|
|
let premium = isPremium()
|
|
// Interactive if limitations are off, or if user is premium
|
|
return !limitationsEnabled || premium
|
|
}
|
|
|
|
// MARK: - Pending Task State Management
|
|
|
|
/// Tracks which tasks have pending completion (not yet synced with server)
|
|
struct PendingTaskState: Codable {
|
|
let taskId: Int
|
|
let timestamp: Date
|
|
}
|
|
|
|
/// Mark a task as pending completion (optimistic UI update - hides from widget)
|
|
func markTaskPendingCompletion(taskId: Int) {
|
|
var pendingTasks = loadPendingTaskStates()
|
|
|
|
// Remove any existing state for this task
|
|
pendingTasks.removeAll { $0.taskId == taskId }
|
|
|
|
// Add new pending state
|
|
pendingTasks.append(PendingTaskState(
|
|
taskId: taskId,
|
|
timestamp: Date()
|
|
))
|
|
|
|
savePendingTaskStates(pendingTasks)
|
|
}
|
|
|
|
/// Load pending task states
|
|
func loadPendingTaskStates() -> [PendingTaskState] {
|
|
guard let fileURL = pendingTasksFileURL,
|
|
FileManager.default.fileExists(atPath: fileURL.path) else {
|
|
return []
|
|
}
|
|
|
|
do {
|
|
let data = try Data(contentsOf: fileURL)
|
|
let states = try JSONDecoder().decode([PendingTaskState].self, from: data)
|
|
|
|
// Filter out stale states (older than 5 minutes)
|
|
let freshStates = states.filter { state in
|
|
Date().timeIntervalSince(state.timestamp) < 300 // 5 minutes
|
|
}
|
|
|
|
if freshStates.count != states.count {
|
|
savePendingTaskStates(freshStates)
|
|
}
|
|
|
|
return freshStates
|
|
} catch {
|
|
return []
|
|
}
|
|
}
|
|
|
|
/// Save pending task states
|
|
private func savePendingTaskStates(_ states: [PendingTaskState]) {
|
|
guard let fileURL = pendingTasksFileURL else { return }
|
|
|
|
do {
|
|
let data = try JSONEncoder().encode(states)
|
|
try data.write(to: fileURL, options: .atomic)
|
|
} catch {
|
|
print("WidgetActionManager: Error saving pending task states - \(error)")
|
|
}
|
|
}
|
|
|
|
/// Clear pending state for a task (called after synced with server)
|
|
func clearPendingState(forTaskId taskId: Int) {
|
|
var pendingTasks = loadPendingTaskStates()
|
|
pendingTasks.removeAll { $0.taskId == taskId }
|
|
savePendingTaskStates(pendingTasks)
|
|
|
|
// Also reload widget
|
|
WidgetCenter.shared.reloadTimelines(ofKind: "honeyDue")
|
|
}
|
|
|
|
/// Clear all pending states
|
|
func clearAllPendingStates() {
|
|
guard let fileURL = pendingTasksFileURL else { return }
|
|
|
|
do {
|
|
try FileManager.default.removeItem(at: fileURL)
|
|
} catch {
|
|
// File might not exist
|
|
}
|
|
}
|
|
|
|
/// Check if a task is pending completion
|
|
func isTaskPendingCompletion(taskId: Int) -> Bool {
|
|
let states = loadPendingTaskStates()
|
|
return states.contains { $0.taskId == taskId }
|
|
}
|
|
}
|