OpenTalon / app · opentalon.ai / native / ios / PhoneWorkspace.swift
| 1 | import CloudKit |
| 2 | import CompanionCore |
| 3 | import Foundation |
| 4 | import Observation |
| 5 | import UserNotifications |
| 6 | |
| 7 | @MainActor |
| 8 | @Observable |
| 9 | final class PhoneWorkspace { |
| 10 | static let pickupAlertsKey = "agentPickupAlerts" |
| 11 | struct UnsavedNotes: Codable { |
| 12 | let text: String |
| 13 | let message: String |
| 14 | } |
| 15 | |
| 16 | struct CapturedTask: Codable, Identifiable { |
| 17 | enum Result: Codable { |
| 18 | case queued |
| 19 | case saved(String?) |
| 20 | case rejected(String) |
| 21 | } |
| 22 | |
| 23 | let id: UUID |
| 24 | let title: String |
| 25 | let project: String |
| 26 | let notes: String |
| 27 | let definitionOfDone: String? |
| 28 | let priority: PhoneTask.Priority |
| 29 | let planMarkdown: String? |
| 30 | let issueType: IssueType? |
| 31 | let createdAt: Date? |
| 32 | var result: Result = .queued |
| 33 | var dismissed = false |
| 34 | } |
| 35 | |
| 36 | private enum QueueError: LocalizedError { |
| 37 | case changePending, agentDisconnected |
| 38 | |
| 39 | var errorDescription: String? { |
| 40 | switch self { |
| 41 | case .changePending: "Wait for the current task change to sync with your Mac." |
| 42 | case .agentDisconnected: "Connect MCP in Settings on your Mac to use agents." |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | enum PlanConflict: LocalizedError { |
| 48 | case changed |
| 49 | var errorDescription: String? { "The plan changed while you were editing. Your draft is preserved. Reopen it to review the saved version before applying your changes." } |
| 50 | } |
| 51 | |
| 52 | private struct LocalState: Codable { |
| 53 | var snapshot: PhoneSnapshot? |
| 54 | var pending: [PhoneRequest] = [] |
| 55 | var waiting: [UUID: String] = [:] |
| 56 | var rejected: String? |
| 57 | var commentDrafts: [String: String]? |
| 58 | var unsavedNotes: [String: UnsavedNotes]? |
| 59 | var planDrafts: [String: String]? |
| 60 | var historyPages: [String: TaskHistoryPage]? |
| 61 | var activityPages: [String: TaskActivityPage]? |
| 62 | var commentActivityPages: [String: TaskActivityPage]? |
| 63 | var acknowledgedUserComments: [String: [PhoneComment]]? |
| 64 | var capturedTask: CapturedTask? |
| 65 | /// Requests queued here that have never been offered to iCloud. |
| 66 | var unsent: Set<UUID>? |
| 67 | /// Revision requests the user withdrew that the Mac has not confirmed yet. |
| 68 | var withdrawing: Set<String>? |
| 69 | } |
| 70 | |
| 71 | private let directory = URL.applicationSupportDirectory.appending(path: "OpenTalonCompanion", directoryHint: .isDirectory) |
| 72 | @ObservationIgnored private let cloud: any CompanionTransport |
| 73 | private var state = LocalState() |
| 74 | private var account: String? |
| 75 | private var accountGeneration = 0 |
| 76 | private(set) var syncing = false |
| 77 | private(set) var syncError: String? |
| 78 | private(set) var syncErrorCode: String? |
| 79 | private(set) var accountStatus = "Not checked" |
| 80 | private(set) var remoteWorkspaceFound: Bool? |
| 81 | private(set) var lastCheck: Date? |
| 82 | private(set) var lastCloudContact: Date? |
| 83 | private(set) var pickupNotice: String? |
| 84 | let hasSavedWorkspace: Bool |
| 85 | |
| 86 | init() { |
| 87 | #if DEBUG && targetEnvironment(simulator) |
| 88 | if let path = ProcessInfo.processInfo.environment["OPENTALON_LOCAL_SYNC_DIRECTORY"], !path.isEmpty { |
| 89 | cloud = LocalCompanionTransport(directory: URL(fileURLWithPath: path, isDirectory: true)) |
| 90 | } else { |
| 91 | cloud = CompanionCloud() |
| 92 | } |
| 93 | #else |
| 94 | cloud = CompanionCloud() |
| 95 | #endif |
| 96 | let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [] |
| 97 | hasSavedWorkspace = files.filter { $0.lastPathComponent.hasPrefix("cloud-") && $0.pathExtension == "json" } |
| 98 | .contains { url in |
| 99 | guard let data = try? Data(contentsOf: url) else { return false } |
| 100 | return (try? JSONDecoder().decode(LocalState.self, from: data))?.snapshot != nil |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | var snapshot: PhoneSnapshot? { state.snapshot } |
| 105 | var pending: [PhoneRequest] { state.pending } |
| 106 | var lastRejection: String? { state.rejected } |
| 107 | var capturedTask: CapturedTask? { state.capturedTask } |
| 108 | |
| 109 | func dismissCapturedTask(_ id: UUID) { |
| 110 | guard state.capturedTask?.id == id else { return } |
| 111 | var updated = state |
| 112 | updated.capturedTask?.dismissed = true |
| 113 | try? save(updated) |
| 114 | } |
| 115 | |
| 116 | func accountDidChange() { |
| 117 | accountGeneration += 1 |
| 118 | account = nil |
| 119 | state = LocalState() |
| 120 | syncError = nil |
| 121 | syncErrorCode = nil |
| 122 | accountStatus = "Not checked" |
| 123 | remoteWorkspaceFound = nil |
| 124 | lastCheck = nil |
| 125 | lastCloudContact = nil |
| 126 | pickupNotice = nil |
| 127 | Task { await sync() } |
| 128 | } |
| 129 | |
| 130 | func queue(_ action: PhoneRequest.Action) throws { |
| 131 | guard let snapshot else { throw CompanionSyncError.missingWorkspace } |
| 132 | let request = PhoneRequest(workspaceID: snapshot.workspaceID, action: action) |
| 133 | try requireAgentConnection(for: action) |
| 134 | if case .savePlan(_, _, let markdown) = action { |
| 135 | guard snapshot.supportsTaskPlans else { throw CompanionSyncError.missingWorkspace } |
| 136 | try TaskPlan.validate(markdown) |
| 137 | try enqueue(request, in: state) |
| 138 | return |
| 139 | } |
| 140 | if case .organizeTask = action { |
| 141 | guard snapshot.supportsTaskOrganization else { throw CompanionSyncError.missingWorkspace } |
| 142 | guard !taskChanges(for: request.taskID ?? "").contains(where: { |
| 143 | if case .organizeTask = $0.action { return true } |
| 144 | return false |
| 145 | }) else { throw QueueError.changePending } |
| 146 | try enqueue(request, in: state) |
| 147 | return |
| 148 | } |
| 149 | if case .forceComplete = action { |
| 150 | try enqueue(request, in: state) |
| 151 | return |
| 152 | } |
| 153 | if request.changesTask, let taskID = request.taskID, pendingTaskChange(for: taskID) != nil { |
| 154 | throw QueueError.changePending |
| 155 | } |
| 156 | |
| 157 | try enqueue(request, in: state) |
| 158 | } |
| 159 | |
| 160 | func attachFile(_ file: TaskFilePayload, to taskID: String, in workspaceID: UUID) throws { |
| 161 | guard let snapshot, snapshot.workspaceID == workspaceID, |
| 162 | snapshot.tasks.contains(where: { $0.id == taskID }) else { throw CompanionSyncError.missingWorkspace } |
| 163 | guard snapshot.filesByTask != nil else { throw TaskFileError.updateMac } |
| 164 | let queuedBytes = state.pending.reduce(0) { total, request in |
| 165 | if case .attachFile(_, let file) = request.action { return total + file.bytes.count } |
| 166 | return total |
| 167 | } |
| 168 | guard queuedBytes + file.bytes.count <= 3 * TaskFilePayload.maxBytes else { throw TaskFileError.queueFull } |
| 169 | try queue(.attachFile(taskID: taskID, file: file)) |
| 170 | } |
| 171 | |
| 172 | func pendingFiles(for taskID: String) -> [(id: UUID, name: String)] { |
| 173 | pending.compactMap { request in |
| 174 | guard request.workspaceID == snapshot?.workspaceID, |
| 175 | case .attachFile(let id, let file) = request.action, id == taskID else { return nil } |
| 176 | return (request.id, file.name) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | func openFile(_ file: TaskFile, in workspaceID: UUID) async throws -> URL { |
| 181 | guard let account, snapshot?.workspaceID == workspaceID, |
| 182 | snapshot?.filesByTask?[file.taskId]?.contains(file) == true else { throw TaskFileError.unavailable } |
| 183 | let generation = accountGeneration |
| 184 | let folder = URL.cachesDirectory.appending(path: "TaskFiles/\(account)/\(workspaceID.uuidString)", directoryHint: .isDirectory) |
| 185 | let cached = try file.cachedURL(in: folder) |
| 186 | if let data = try? Data(contentsOf: cached), (try? file.verify(data)) != nil { return cached } |
| 187 | let bytes = try await cloud.getFile(file, workspaceID: workspaceID) |
| 188 | guard generation == accountGeneration, snapshot?.workspaceID == workspaceID else { throw TaskFileError.unavailable } |
| 189 | return try file.preview(bytes, in: folder) |
| 190 | } |
| 191 | |
| 192 | private func requireAgentConnection(for action: PhoneRequest.Action) throws { |
| 193 | let sends: Bool = switch action { |
| 194 | case .send, .create(_, _, _, _, true, _, _, _, _, _, _, _), |
| 195 | .editField(_, _, .status(.sent, _, _, _)), .setField(_, _, .status(.sent, _, _, _)): true |
| 196 | default: false |
| 197 | } |
| 198 | if sends && snapshot?.canUseAgents != true { |
| 199 | throw QueueError.agentDisconnected |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | func queueField(_ edit: PhoneTaskFieldEdit, for task: PhoneTask, in workspaceID: UUID) throws { |
| 204 | guard snapshot?.workspaceID == workspaceID, snapshot?.supportsFieldEditing == true else { |
| 205 | throw CompanionSyncError.missingWorkspace |
| 206 | } |
| 207 | if case .status(.sent, _, _, _) = edit, snapshot?.canUseAgents != true { throw QueueError.agentDisconnected } |
| 208 | if edit.field == .issueType, snapshot?.supportsTaskTypes != true { throw CompanionSyncError.missingWorkspace } |
| 209 | if snapshot?.supportsTaskOverrides == true { |
| 210 | let current = snapshot?.tasks.first(where: { $0.id == task.id }) ?? task |
| 211 | let expected: String? = switch edit.field { |
| 212 | case .project: displayedProject(for: current) |
| 213 | case .status: displayedStatus(for: current).rawValue |
| 214 | case .priority: displayedPriority(for: current).rawValue |
| 215 | case .issueType: displayedIssueType(for: current).rawValue |
| 216 | case .dueDate: displayedDueDate(for: current) |
| 217 | case .title: displayedText(for: current, field: .title) |
| 218 | case .notes: displayedText(for: current, field: .notes) |
| 219 | case .definitionOfDone: displayedText(for: current, field: .definitionOfDone) |
| 220 | } |
| 221 | guard expected != edit.value else { return } |
| 222 | try enqueue(PhoneRequest(workspaceID: workspaceID, |
| 223 | action: .setField(taskID: task.id, expected: expected, edit: edit)), in: state) |
| 224 | return |
| 225 | } |
| 226 | try queue(.editField(taskID: task.id, revision: task.revision, edit: edit)) |
| 227 | } |
| 228 | |
| 229 | func canMarkDone(_ task: PhoneTask) -> Bool { |
| 230 | guard !isArchived(task), !isTrashed(task), displayedStatus(for: task) != .done else { return false } |
| 231 | if snapshot?.supportsTaskOverrides == true { return true } |
| 232 | return task.isManualOpen && pendingTaskChange(for: task.id) == nil |
| 233 | } |
| 234 | |
| 235 | func completionNeedsConfirmation(for task: PhoneTask) -> Bool { |
| 236 | task.assigned || displayedStatus(for: task) == .sent |
| 237 | } |
| 238 | |
| 239 | func markDone(_ task: PhoneTask) throws { |
| 240 | guard let snapshot, canMarkDone(task) else { return } |
| 241 | if completionNeedsConfirmation(for: task) { |
| 242 | try queue(.forceComplete(taskID: task.id)) |
| 243 | } else if snapshot.supportsTaskOverrides { |
| 244 | try queueField(.status(.done), for: task, in: snapshot.workspaceID) |
| 245 | } else { |
| 246 | try queue(.complete(taskID: task.id, revision: task.revision)) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | func queueNotes(_ notes: String, for task: PhoneTask, in workspaceID: UUID) throws { |
| 251 | guard snapshot?.workspaceID == workspaceID, snapshot?.supportsNoteEditing == true else { |
| 252 | throw CompanionSyncError.missingWorkspace |
| 253 | } |
| 254 | guard pendingTaskChange(for: task.id) == nil else { throw QueueError.changePending } |
| 255 | var updated = state |
| 256 | updated.unsavedNotes?.removeValue(forKey: task.id) |
| 257 | let request = PhoneRequest(workspaceID: workspaceID, |
| 258 | action: .editNotes(taskID: task.id, revision: task.revision, notes: notes)) |
| 259 | try enqueue(request, in: updated) |
| 260 | } |
| 261 | |
| 262 | func unsavedNotes(for taskID: String) -> UnsavedNotes? { state.unsavedNotes?[taskID] } |
| 263 | |
| 264 | func commentDraft(for taskID: String, in workspaceID: UUID) -> String { |
| 265 | guard snapshot?.workspaceID == workspaceID else { return "" } |
| 266 | return state.commentDrafts?[taskID] ?? "" |
| 267 | } |
| 268 | |
| 269 | func saveCommentDraft(_ text: String, for taskID: String, in workspaceID: UUID) throws { |
| 270 | guard snapshot?.workspaceID == workspaceID else { return } |
| 271 | guard text != commentDraft(for: taskID, in: workspaceID) else { return } |
| 272 | var updated = state |
| 273 | var drafts = updated.commentDrafts ?? [:] |
| 274 | drafts[taskID] = text.isEmpty ? nil : text |
| 275 | updated.commentDrafts = drafts.isEmpty ? nil : drafts |
| 276 | try save(updated) |
| 277 | } |
| 278 | |
| 279 | func finishComment(_ text: String, for taskID: String, in workspaceID: UUID) throws { |
| 280 | guard snapshot?.workspaceID == workspaceID, snapshot?.commentsByTask != nil else { |
| 281 | throw CompanionSyncError.missingWorkspace |
| 282 | } |
| 283 | var updated = state |
| 284 | updated.commentDrafts?.removeValue(forKey: taskID) |
| 285 | let request = PhoneRequest(workspaceID: workspaceID, action: .comment(taskID: taskID, text: text)) |
| 286 | try enqueue(request, in: updated) |
| 287 | } |
| 288 | |
| 289 | func isWithdrawing(_ revisionID: String) -> Bool { state.withdrawing?.contains(revisionID) == true } |
| 290 | |
| 291 | /// A request queued on this phone can be withdrawn until the Mac has it. After that the Mac must support withdrawal. |
| 292 | func canWithdraw(_ request: PhoneRequest) -> Bool { |
| 293 | guard let id = request.revisionID, !isWithdrawing(id) else { return false } |
| 294 | return state.unsent?.contains(request.id) == true || snapshot?.supportsRevisionWithdrawal == true |
| 295 | } |
| 296 | |
| 297 | func canWithdraw(_ comment: PhoneComment) -> Bool { |
| 298 | guard let snapshot, !isWithdrawing(comment.id) else { return false } |
| 299 | return RevisionWithdrawal.isOffered(for: comment, in: snapshot) |
| 300 | } |
| 301 | |
| 302 | func withdrawRevision(_ revisionID: String, for taskID: String, in workspaceID: UUID) throws { |
| 303 | guard let snapshot, snapshot.workspaceID == workspaceID else { throw CompanionSyncError.missingWorkspace } |
| 304 | guard !isWithdrawing(revisionID) else { return } |
| 305 | var updated = state |
| 306 | switch try RevisionWithdrawal.plan(revisionID: revisionID, taskID: taskID, pending: state.pending, |
| 307 | unsent: state.unsent ?? [], snapshot: snapshot) { |
| 308 | case .discard(let requestID): |
| 309 | updated.pending.removeAll { $0.id == requestID } |
| 310 | updated.unsent?.remove(requestID) |
| 311 | updated.waiting.removeValue(forKey: requestID) |
| 312 | try save(updated) |
| 313 | case .request(let commentID): |
| 314 | updated.withdrawing = (updated.withdrawing ?? []).union([commentID]) |
| 315 | try enqueue(PhoneRequest(workspaceID: workspaceID, |
| 316 | action: .withdrawComment(taskID: taskID, commentID: commentID)), in: updated) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | private func enqueue(_ request: PhoneRequest, in state: LocalState) throws { |
| 321 | var updated = state |
| 322 | updated.pending.append(request) |
| 323 | updated.unsent = (updated.unsent ?? []).union([request.id]) |
| 324 | if case .create(let project, let title, let notes, let priority, _, let definition, _, _, _, let newProject, let plan, let type) = request.action { |
| 325 | updated.capturedTask = CapturedTask(id: request.id, title: title, project: newProject ?? projectName(project), |
| 326 | notes: notes, definitionOfDone: definition, priority: priority, planMarkdown: plan, issueType: type, |
| 327 | createdAt: request.createdAt) |
| 328 | } |
| 329 | try save(updated) |
| 330 | Task { await sync() } |
| 331 | } |
| 332 | |
| 333 | func sync() async { |
| 334 | guard !syncing else { return } |
| 335 | syncing = true |
| 336 | let generation = accountGeneration |
| 337 | var checkedAccount = false |
| 338 | defer { |
| 339 | syncing = false |
| 340 | if generation != accountGeneration { |
| 341 | Task { await sync() } |
| 342 | } else if !Task.isCancelled { |
| 343 | lastCheck = .now |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | do { |
| 348 | let currentAccount = try await cloud.accountKey() |
| 349 | guard generation == accountGeneration else { return } |
| 350 | checkedAccount = true |
| 351 | accountStatus = "Connected" |
| 352 | if account != currentAccount { |
| 353 | account = currentAccount |
| 354 | state = load(cacheURL(currentAccount)) ?? LocalState() |
| 355 | } |
| 356 | let incoming = try await cloud.snapshot(newerThan: state.snapshot) |
| 357 | guard generation == accountGeneration else { return } |
| 358 | lastCloudContact = .now |
| 359 | switch incoming { |
| 360 | case .missing: |
| 361 | remoteWorkspaceFound = false |
| 362 | case .unchanged: |
| 363 | remoteWorkspaceFound = true |
| 364 | case .updated(let incoming): |
| 365 | let previous = snapshot |
| 366 | remoteWorkspaceFound = true |
| 367 | var updated = state |
| 368 | if updated.snapshot?.workspaceID != incoming.workspaceID { |
| 369 | updated.commentDrafts = nil |
| 370 | updated.unsavedNotes = nil |
| 371 | updated.historyPages = nil |
| 372 | updated.activityPages = nil |
| 373 | updated.commentActivityPages = nil |
| 374 | updated.acknowledgedUserComments = nil |
| 375 | updated.withdrawing = nil |
| 376 | updated.capturedTask = nil |
| 377 | } |
| 378 | if updated.snapshot == nil, let legacy = load(directory.appending(path: "workspace.json")), |
| 379 | legacy.snapshot?.workspaceID == incoming.workspaceID { |
| 380 | updated.pending = legacy.pending.filter { $0.workspaceID == incoming.workspaceID } |
| 381 | } |
| 382 | for request in updated.pending where request.workspaceID != incoming.workspaceID { |
| 383 | updated.waiting[request.id] = "This change belongs to an earlier Mac workspace." |
| 384 | } |
| 385 | updated.snapshot = incoming |
| 386 | try save(updated) |
| 387 | await announcePickups(from: previous, to: incoming) |
| 388 | } |
| 389 | |
| 390 | guard let snapshot, remoteWorkspaceFound == true else { |
| 391 | syncError = nil |
| 392 | syncErrorCode = nil |
| 393 | return |
| 394 | } |
| 395 | for request in pending where request.workspaceID == snapshot.workspaceID { |
| 396 | guard generation == accountGeneration else { return } |
| 397 | // A request withdrawn while this pass was running must not be sent after all. |
| 398 | guard state.pending.contains(where: { $0.id == request.id }) else { continue } |
| 399 | if state.unsent?.contains(request.id) == true { |
| 400 | // Recorded before the first attempt: from here on the request may exist in iCloud. |
| 401 | var offered = state |
| 402 | offered.unsent?.remove(request.id) |
| 403 | try save(offered) |
| 404 | } |
| 405 | let receipt = try await cloud.submit(request) |
| 406 | guard generation == accountGeneration else { return } |
| 407 | guard let receipt else { continue } |
| 408 | var updated = state |
| 409 | if receipt.isSettled(at: snapshot.revision) { |
| 410 | if let page = receipt.activity, receipt.outcome == .applied, let commentID = page.commentID { |
| 411 | updated.commentActivityPages = updated.commentActivityPages ?? [:] |
| 412 | if case .loadCommentActivity(_, _, let before) = request.action, before != nil, |
| 413 | let cached = updated.commentActivityPages?[commentID] { |
| 414 | updated.commentActivityPages?[commentID] = cached.merging(page) |
| 415 | } else { updated.commentActivityPages?[commentID] = page } |
| 416 | } |
| 417 | if let page = receipt.activity, receipt.outcome == .applied, page.commentID == nil { |
| 418 | updated.activityPages = updated.activityPages ?? [:] |
| 419 | let cached = updated.activityPages?[page.taskID] |
| 420 | let base = updated.snapshot?.activityByTask?[page.taskID] |
| 421 | if case .loadActivity(_, let before) = request.action, before != nil { |
| 422 | let current: TaskActivityPage? = if let base { cached.map { base.keepingOlder(from: $0) } ?? base } else { cached } |
| 423 | updated.activityPages?[page.taskID] = current?.merging(page) ?? page |
| 424 | } else { updated.activityPages?[page.taskID] = cached.map { page.keepingOlder(from: $0) } ?? page } |
| 425 | } |
| 426 | if let page = receipt.history, receipt.outcome == .applied { |
| 427 | updated.historyPages = updated.historyPages ?? [:] |
| 428 | if let existing = updated.historyPages?[page.taskID] { |
| 429 | updated.historyPages?[page.taskID] = existing.merging(page) |
| 430 | } else { updated.historyPages?[page.taskID] = page } |
| 431 | } |
| 432 | if receipt.outcome == .applied, updated.snapshot?.activityByTask == nil, |
| 433 | case .comment(let taskID, let text) = request.action { |
| 434 | // Older Macs did not record authorship. Preserve only messages this phone explicitly sent. |
| 435 | updated.acknowledgedUserComments = updated.acknowledgedUserComments ?? [:] |
| 436 | var saved = updated.acknowledgedUserComments?[taskID] ?? [] |
| 437 | if !saved.contains(where: { $0.id == request.id.uuidString }) { |
| 438 | saved.append(PhoneComment(id: request.id.uuidString, text: text, |
| 439 | createdAt: request.createdAt.ISO8601Format(), delivery: "local", source: "user")) |
| 440 | } |
| 441 | updated.acknowledgedUserComments?[taskID] = saved |
| 442 | } |
| 443 | let withdrawing = updated.withdrawing ?? [] |
| 444 | updated.pending.removeAll { $0.id == receipt.requestID } |
| 445 | updated.waiting.removeValue(forKey: receipt.requestID) |
| 446 | updated.unsent?.remove(receipt.requestID) |
| 447 | let remaining = RevisionWithdrawal.stillWithdrawing(withdrawing, pending: updated.pending) |
| 448 | updated.withdrawing = remaining.isEmpty ? nil : remaining |
| 449 | if updated.capturedTask?.id == receipt.requestID { |
| 450 | if receipt.outcome == .applied { |
| 451 | // Older Macs only return a revision. A creation writes one task at that revision. |
| 452 | let matches = snapshot.tasks.filter { $0.revision == receipt.revision } |
| 453 | updated.capturedTask?.result = .saved(receipt.createdTaskID ?? (matches.count == 1 ? matches[0].id : nil)) |
| 454 | } else { |
| 455 | updated.capturedTask?.result = .rejected(receipt.message ?? "The Mac couldn’t create this task.") |
| 456 | } |
| 457 | } |
| 458 | if receipt.outcome == .rejected, !RevisionWithdrawal.hidesRejection(of: request, withdrawing: withdrawing) { |
| 459 | let message = receipt.message ?? "The Mac could not apply a queued change." |
| 460 | updated.rejected = message |
| 461 | if case .editNotes(let taskID, _, let notes) = request.action { |
| 462 | updated.unsavedNotes = updated.unsavedNotes ?? [:] |
| 463 | updated.unsavedNotes?[taskID] = UnsavedNotes(text: notes, message: message) |
| 464 | } |
| 465 | if case .savePlan(let taskID, _, let markdown) = request.action { |
| 466 | updated.planDrafts = updated.planDrafts ?? [:] |
| 467 | updated.planDrafts?[taskID] = markdown |
| 468 | } |
| 469 | } |
| 470 | try save(updated) |
| 471 | try? await cloud.retire(receipt.requestID) |
| 472 | } else if let message = receipt.message, updated.waiting[receipt.requestID] != message { |
| 473 | updated.waiting[receipt.requestID] = message |
| 474 | try save(updated) |
| 475 | } |
| 476 | } |
| 477 | if generation == accountGeneration { |
| 478 | syncError = nil |
| 479 | syncErrorCode = nil |
| 480 | } |
| 481 | } catch { |
| 482 | guard generation == accountGeneration, !Task.isCancelled else { return } |
| 483 | if !checkedAccount { |
| 484 | switch error as? CompanionCloudError { |
| 485 | case .noAccount: accountStatus = "Signed out" |
| 486 | case .accountRestricted: accountStatus = "Restricted" |
| 487 | default: accountStatus = "Unavailable" |
| 488 | } |
| 489 | } |
| 490 | let failure = error as NSError |
| 491 | syncErrorCode = "\(failure.domain) (\(failure.code))" |
| 492 | switch (error as? CKError)?.code { |
| 493 | case .badContainer, .missingEntitlement: |
| 494 | syncError = "This build couldn’t access the OpenTalon iCloud container." |
| 495 | case .notAuthenticated: |
| 496 | syncError = CompanionCloudError.noAccount.localizedDescription |
| 497 | case .networkUnavailable, .networkFailure: |
| 498 | syncError = "Check your internet connection and try again." |
| 499 | default: |
| 500 | syncError = error.localizedDescription |
| 501 | } |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | func waitingMessage(for request: PhoneRequest) -> String? { state.waiting[request.id] } |
| 506 | |
| 507 | private func announcePickups(from previous: PhoneSnapshot?, to incoming: PhoneSnapshot) async { |
| 508 | guard let previous, previous.workspaceID == incoming.workspaceID, previous.macName != nil else { return } |
| 509 | let previousPickups = Set(previous.tasks.compactMap { $0.agentPickup?.id }) |
| 510 | let starts = incoming.tasks.filter { task in |
| 511 | guard let pickup = task.agentPickup else { return false } |
| 512 | return !previousPickups.contains(pickup.id) |
| 513 | } |
| 514 | guard let first = starts.first, let pickup = first.agentPickup else { return } |
| 515 | let macName = incoming.macName ?? "your Mac" |
| 516 | let message = starts.count == 1 ? first.title : "\(starts.count) tasks" |
| 517 | pickupNotice = "Picked up by \(macName): \(message)" |
| 518 | guard UserDefaults.standard.bool(forKey: Self.pickupAlertsKey) else { return } |
| 519 | let content = UNMutableNotificationContent() |
| 520 | content.title = "Picked up by \(macName)" |
| 521 | content.body = message |
| 522 | try? await UNUserNotificationCenter.current().add( |
| 523 | UNNotificationRequest(identifier: "OpenTalon-Pickup-" + pickup.id, content: content, trigger: nil) |
| 524 | ) |
| 525 | } |
| 526 | |
| 527 | func dismissPickupNotice() { pickupNotice = nil } |
| 528 | |
| 529 | func pendingNotes(for taskID: String) -> String? { |
| 530 | taskChanges(for: taskID).reversed().compactMap { request -> String? in |
| 531 | if case .editNotes(_, _, let notes) = request.action { return notes } |
| 532 | if case .setField(_, _, .notes(let notes)) = request.action { return notes } |
| 533 | return nil |
| 534 | }.first |
| 535 | } |
| 536 | |
| 537 | func displayedText(for task: PhoneTask, field: PhoneTaskFieldEdit.Field) -> String { |
| 538 | if let edit = pendingField(for: task.id, field: field), let text = edit.value { return text } |
| 539 | switch field { |
| 540 | case .title: return task.title |
| 541 | case .notes: return pendingNotes(for: task.id) ?? task.notes |
| 542 | case .definitionOfDone: return task.definitionOfDone |
| 543 | default: return "" |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | func displayedIssueType(for task: PhoneTask) -> IssueType { |
| 548 | if case .issueType(let type) = pendingField(for: task.id, field: .issueType) { return type } |
| 549 | return task.kind |
| 550 | } |
| 551 | |
| 552 | func displayedPlan(for task: PhoneTask) -> String { |
| 553 | for request in taskChanges(for: task.id).reversed() { |
| 554 | if case .savePlan(_, _, let markdown) = request.action { return markdown } |
| 555 | if case .restoreRevision(_, let id, _) = request.action, |
| 556 | let entry = historyPage(for: task.id)?.entries.first(where: { $0.id == id }) { return entry.state.planMarkdown } |
| 557 | } |
| 558 | return task.planMarkdown ?? "" |
| 559 | } |
| 560 | |
| 561 | func planDraft(for taskID: String) -> String? { state.planDrafts?[taskID] } |
| 562 | |
| 563 | func hasPendingPlan(for taskID: String) -> Bool { |
| 564 | taskChanges(for: taskID).contains { if case .savePlan = $0.action { true } else { false } } |
| 565 | } |
| 566 | |
| 567 | func savePlanDraft(_ markdown: String?, for taskID: String, in workspaceID: UUID) throws { |
| 568 | guard snapshot?.workspaceID == workspaceID else { throw CompanionSyncError.missingWorkspace } |
| 569 | var updated = state |
| 570 | updated.planDrafts = updated.planDrafts ?? [:] |
| 571 | updated.planDrafts?[taskID] = markdown |
| 572 | try save(updated) |
| 573 | } |
| 574 | |
| 575 | func savePlan(_ markdown: String, expected: String, for taskID: String, in workspaceID: UUID) throws { |
| 576 | guard snapshot?.workspaceID == workspaceID, snapshot?.supportsTaskPlans == true else { |
| 577 | throw CompanionSyncError.missingWorkspace |
| 578 | } |
| 579 | try TaskPlan.validate(markdown) |
| 580 | guard let task = snapshot?.tasks.first(where: { $0.id == taskID }), displayedPlan(for: task) == expected else { |
| 581 | throw PlanConflict.changed |
| 582 | } |
| 583 | var updated = state |
| 584 | updated.planDrafts?.removeValue(forKey: taskID) |
| 585 | try enqueue(PhoneRequest(workspaceID: workspaceID, |
| 586 | action: .savePlan(taskID: taskID, expectedMarkdown: expected, markdown: markdown)), in: updated) |
| 587 | } |
| 588 | |
| 589 | private func pendingField(for taskID: String, field: PhoneTaskFieldEdit.Field) -> PhoneTaskFieldEdit? { |
| 590 | for request in taskChanges(for: taskID).reversed() { |
| 591 | switch request.action { |
| 592 | case .editField(_, _, let edit), .setField(_, _, let edit): |
| 593 | if edit.field == field { return edit } |
| 594 | case .restoreRevision(_, let id, _): |
| 595 | if let entry = historyPage(for: taskID)?.entries.first(where: { $0.id == id }) { return entry.state.edit(for: field) } |
| 596 | default: break |
| 597 | } |
| 598 | } |
| 599 | return nil |
| 600 | } |
| 601 | |
| 602 | func acknowledgedLegacyComments(for taskID: String) -> [PhoneComment] { |
| 603 | state.acknowledgedUserComments?[taskID] ?? [] |
| 604 | } |
| 605 | |
| 606 | func commentActivityPage(for commentID: String) -> TaskActivityPage? { state.commentActivityPages?[commentID] } |
| 607 | func isLoadingCommentActivity(_ commentID: String) -> Bool { |
| 608 | pending.contains { if case .loadCommentActivity(_, let id, _) = $0.action { return id == commentID }; return false } |
| 609 | } |
| 610 | func loadCommentActivity(taskID: String, commentID: String, before: Int?) throws { |
| 611 | guard snapshot?.supportsCommentActivity == true else { throw CompanionSyncError.missingWorkspace } |
| 612 | guard !pending.contains(where: { if case .loadCommentActivity(_, let id, let cursor) = $0.action { return id == commentID && cursor == before }; return false }) else { return } |
| 613 | try queue(.loadCommentActivity(taskID: taskID, commentID: commentID, beforeSequence: before)) |
| 614 | } |
| 615 | |
| 616 | func activityPage(for taskID: String) -> TaskActivityPage? { |
| 617 | let base = snapshot?.activityByTask?[taskID] |
| 618 | guard let cached = state.activityPages?[taskID] else { return base } |
| 619 | return base?.keepingOlder(from: cached) ?? cached |
| 620 | } |
| 621 | func isLoadingActivity(for taskID: String) -> Bool { |
| 622 | pending.contains { if case .loadActivity(let id, _) = $0.action { return id == taskID }; return false } |
| 623 | } |
| 624 | func loadActivity(for taskID: String, before: Int?) throws { |
| 625 | guard snapshot?.activityByTask != nil else { throw CompanionSyncError.missingWorkspace } |
| 626 | guard !pending.contains(where: { if case .loadActivity(let id, let cursor) = $0.action { return id == taskID && cursor == before }; return false }) else { return } |
| 627 | try queue(.loadActivity(taskID: taskID, beforeSequence: before)) |
| 628 | } |
| 629 | |
| 630 | func historyPage(for taskID: String) -> TaskHistoryPage? { |
| 631 | let base = snapshot?.historyByTask?[taskID] |
| 632 | guard let cached = state.historyPages?[taskID] else { return base } |
| 633 | if let newest = base?.entries.first?.version, let cachedNewest = cached.entries.first?.version, |
| 634 | newest > cachedNewest + 1 { return base } |
| 635 | return base?.merging(cached) ?? cached |
| 636 | } |
| 637 | |
| 638 | func isLoadingHistory(for taskID: String) -> Bool { |
| 639 | pending.contains { if case .loadHistory(let id, _) = $0.action { return id == taskID }; return false } |
| 640 | } |
| 641 | |
| 642 | func loadHistory(for taskID: String, before: Int?) throws { |
| 643 | guard let snapshot, snapshot.historyByTask != nil else { throw CompanionSyncError.missingWorkspace } |
| 644 | guard !pending.contains(where: { request in |
| 645 | if case .loadHistory(let id, let cursor) = request.action { return id == taskID && cursor == before } |
| 646 | return false |
| 647 | }) else { return } |
| 648 | try queue(.loadHistory(taskID: taskID, beforeVersion: before)) |
| 649 | } |
| 650 | |
| 651 | func restoreHistory(_ entry: TaskRevision, for task: PhoneTask) throws { |
| 652 | guard let snapshot, snapshot.historyByTask != nil else { throw CompanionSyncError.missingWorkspace } |
| 653 | try queue(.restoreRevision(taskID: task.id, historyID: entry.id, revision: task.revision)) |
| 654 | } |
| 655 | |
| 656 | func pendingTaskChange(for taskID: String) -> PhoneRequest? { |
| 657 | taskChanges(for: taskID).last |
| 658 | } |
| 659 | |
| 660 | private func taskChanges(for taskID: String) -> [PhoneRequest] { |
| 661 | pending.filter { |
| 662 | $0.workspaceID == snapshot?.workspaceID && $0.taskID == taskID && $0.changesTask |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | func lastUpdated(for task: PhoneTask) -> Date? { |
| 667 | let latestSaved = task.updatedAt ?? snapshot?.historyByTask?[task.id]?.entries |
| 668 | .first(where: { $0.action != "history_started" }) |
| 669 | .flatMap { TaskCreationOrder.date(from: $0.savedAt) } |
| 670 | let latestQueued = taskChanges(for: task.id).map(\.createdAt).max() |
| 671 | if let latestSaved, let latestQueued { return max(latestSaved, latestQueued) } |
| 672 | return latestSaved ?? latestQueued |
| 673 | } |
| 674 | |
| 675 | func completion(for task: PhoneTask) -> (date: Date, pending: Bool)? { |
| 676 | let displayed = pendingStatus(for: task) |
| 677 | guard displayed.status == .done, let date = displayed.completedAt ?? task.completedAt else { return nil } |
| 678 | return (date, displayed.completedAt != nil) |
| 679 | } |
| 680 | |
| 681 | func archivedDate(for task: PhoneTask) -> Date? { |
| 682 | guard isArchived(task) else { return nil } |
| 683 | if let request = taskChanges(for: task.id).last(where: { |
| 684 | if case .organizeTask(_, .archive) = $0.action { return true } |
| 685 | return false |
| 686 | }) { |
| 687 | return request.createdAt |
| 688 | } |
| 689 | return task.archivedAt |
| 690 | } |
| 691 | |
| 692 | func displayedStatus(for task: PhoneTask) -> PhoneTask.Status { |
| 693 | pendingStatus(for: task).status |
| 694 | } |
| 695 | |
| 696 | private func pendingStatus(for task: PhoneTask) -> (status: PhoneTask.Status, completedAt: Date?) { |
| 697 | var status = task.status |
| 698 | var completedAt: Date? |
| 699 | for request in taskChanges(for: task.id) { |
| 700 | let next: PhoneTask.Status? = switch request.action { |
| 701 | case .restoreRevision(_, let id, _): |
| 702 | historyPage(for: task.id)?.entries.first(where: { $0.id == id })?.state.restoredStatus |
| 703 | case .organizeTask(_, .active): .todo |
| 704 | case .complete, .forceComplete: .done |
| 705 | case .send: .sent |
| 706 | case .editField(_, _, .status(let status, _, _, _)), |
| 707 | .setField(_, _, .status(let status, _, _, _)): status |
| 708 | default: nil |
| 709 | } |
| 710 | guard let next, next != status else { continue } |
| 711 | status = next |
| 712 | completedAt = status == .done ? request.createdAt : nil |
| 713 | } |
| 714 | return (status, completedAt) |
| 715 | } |
| 716 | |
| 717 | func displayedPriority(for task: PhoneTask) -> PhoneTask.Priority { |
| 718 | if case .priority(let priority) = pendingField(for: task.id, field: .priority) { return priority } |
| 719 | return task.priority |
| 720 | } |
| 721 | |
| 722 | func displayedProject(for task: PhoneTask) -> String { |
| 723 | if case .project(let id) = pendingField(for: task.id, field: .project) { return id } |
| 724 | return task.projectID |
| 725 | } |
| 726 | |
| 727 | func hasPendingProjectMove(for task: PhoneTask) -> Bool { |
| 728 | pendingField(for: task.id, field: .project) != nil |
| 729 | } |
| 730 | |
| 731 | func isArchived(_ task: PhoneTask) -> Bool { |
| 732 | for request in taskChanges(for: task.id).reversed() { |
| 733 | if case .restoreRevision = request.action { return false } |
| 734 | if case .organizeTask(_, let destination) = request.action { |
| 735 | return destination == .archive || (destination == .trash && task.archivedAt != nil) |
| 736 | } |
| 737 | } |
| 738 | return task.archivedAt != nil |
| 739 | } |
| 740 | |
| 741 | func isTrashed(_ task: PhoneTask) -> Bool { pendingArchiveRemovals[task.id] != nil } |
| 742 | |
| 743 | var visibleTasks: [PhoneTask] { (snapshot?.tasks ?? []).filter { !isTrashed($0) } } |
| 744 | |
| 745 | struct CompletedTask: Identifiable { |
| 746 | let task: PhoneTask |
| 747 | let completedAt: Date? |
| 748 | var id: String { task.id } |
| 749 | var createdAt: Date? { task.createdAt } |
| 750 | } |
| 751 | |
| 752 | func completedTasks(in tasks: [PhoneTask]? = nil, order: DoneOrder) -> [CompletedTask] { |
| 753 | guard let snapshot else { return [] } |
| 754 | let trashedIDs = Set((snapshot.trashedTasks ?? []).map(\.id)) |
| 755 | let completed = (tasks ?? visibleTasks).compactMap { task -> CompletedTask? in |
| 756 | guard !trashedIDs.contains(task.id), !isArchived(task) else { return nil } |
| 757 | let pending = pendingStatus(for: task) |
| 758 | guard pending.status == .done else { return nil } |
| 759 | return CompletedTask(task: task, completedAt: pending.completedAt ?? task.completedAt) |
| 760 | } |
| 761 | return order.ordered(completed, completionDate: \.completedAt, creationDate: \.createdAt) |
| 762 | } |
| 763 | |
| 764 | var pendingArchiveRemovals: [String: Bool] { |
| 765 | var removals: [String: Bool] = [:] |
| 766 | for request in pending where request.workspaceID == snapshot?.workspaceID { |
| 767 | switch request.action { |
| 768 | case .organizeTask(let id, .trash): removals[id] = false |
| 769 | case .removeArchived(let id, _, let permanently): |
| 770 | removals[id] = permanently |
| 771 | case .manageArchive(let ids, _, let permanently): |
| 772 | for id in ids { removals[id] = permanently } |
| 773 | default: break |
| 774 | } |
| 775 | } |
| 776 | return removals |
| 777 | } |
| 778 | |
| 779 | var displayedTrash: [PhoneTrashedTask]? { |
| 780 | guard let snapshot, let savedTrash = snapshot.trashedTasks else { return nil } |
| 781 | var queuedTrashDates: [String: Date] = [:] |
| 782 | for request in pending where request.workspaceID == snapshot.workspaceID { |
| 783 | switch request.action { |
| 784 | case .organizeTask(let id, .trash), .removeArchived(let id, _, false): |
| 785 | queuedTrashDates[id] = request.createdAt |
| 786 | case .manageArchive(let ids, _, false): |
| 787 | for id in ids { queuedTrashDates[id] = request.createdAt } |
| 788 | default: break |
| 789 | } |
| 790 | } |
| 791 | let removals = pendingArchiveRemovals |
| 792 | let trashedIDs = Set(savedTrash.map(\.id)) |
| 793 | let queued = snapshot.tasks.filter { removals[$0.id] == false && !trashedIDs.contains($0.id) } |
| 794 | return queued.map { |
| 795 | PhoneTrashedTask(id: $0.id, projectID: displayedProject(for: $0), |
| 796 | title: displayedText(for: $0, field: .title), revision: $0.revision, |
| 797 | updatedAt: queuedTrashDates[$0.id] ?? lastUpdated(for: $0), |
| 798 | deletedAt: queuedTrashDates[$0.id]) |
| 799 | } + savedTrash |
| 800 | } |
| 801 | |
| 802 | func displayedDueDate(for task: PhoneTask) -> String? { |
| 803 | if case .dueDate(let date) = pendingField(for: task.id, field: .dueDate) { return date } |
| 804 | return task.dueDate |
| 805 | } |
| 806 | |
| 807 | func orderedTasks(_ tasks: [PhoneTask], byPriority: Bool = false) -> [PhoneTask] { |
| 808 | tasks.sorted { |
| 809 | let priority = displayedPriority(for: $0) |
| 810 | let otherPriority = displayedPriority(for: $1) |
| 811 | if byPriority && priority != otherPriority { return priority.rank < otherPriority.rank } |
| 812 | return TaskCreationOrder.precedes(urgent: priority == .urgent, createdAt: $0.createdAt, |
| 813 | otherUrgent: otherPriority == .urgent, otherCreatedAt: $1.createdAt) |
| 814 | ?? ($0.id < $1.id) |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | func newestTasks(_ tasks: [PhoneTask]) -> [PhoneTask] { |
| 819 | tasks.sorted { ($0.createdAt ?? .distantPast, $0.id) > ($1.createdAt ?? .distantPast, $1.id) } |
| 820 | } |
| 821 | |
| 822 | func manualTaskOrder(_ tasks: [PhoneTask], projectID: String, status: PhoneTask.Status) -> [PhoneTask] { |
| 823 | func position(_ task: PhoneTask) -> Int { |
| 824 | guard task.projectID == projectID, task.status == status else { return .max } |
| 825 | return task.position ?? .max |
| 826 | } |
| 827 | |
| 828 | var ordered = tasks.sorted { (position($0), $0.id) < (position($1), $1.id) } |
| 829 | for request in pending where request.workspaceID == snapshot?.workspaceID { |
| 830 | guard case .reorderTask(let id, let destination, let lane, let anchorID, let before) = request.action, |
| 831 | destination == projectID, lane == status, |
| 832 | let source = ordered.firstIndex(where: { $0.id == id }), |
| 833 | let target = ordered.firstIndex(where: { $0.id == anchorID }), source != target else { continue } |
| 834 | let item = ordered.remove(at: source) |
| 835 | let anchor = target - (source < target ? 1 : 0) |
| 836 | ordered.insert(item, at: anchor + (before ? 0 : 1)) |
| 837 | } |
| 838 | return ordered |
| 839 | } |
| 840 | |
| 841 | func title(for request: PhoneRequest) -> String { |
| 842 | switch request.action { |
| 843 | case .loadActivity, .loadCommentActivity: "Load task activity" |
| 844 | case .loadHistory: "Load task history" |
| 845 | case .restoreRevision: "Restore task revision" |
| 846 | case .createProject(let name): name |
| 847 | case .create(_, let title, _, _, _, _, _, _, _, _, _, _): title |
| 848 | case .emptyTrash: "Trash" |
| 849 | case .manageArchive: "Archive" |
| 850 | case .restoreTrashed(let id, _): snapshot?.trashedTasks?.first(where: { $0.id == id })?.title ?? "Task" |
| 851 | case .send(let id, _, _), .complete(let id, _), .comment(let id, _), .withdrawComment(let id, _), |
| 852 | .editNotes(let id, _, _), |
| 853 | .editField(let id, _, _), .setField(let id, _, _), .forceComplete(let id), .removeArchived(let id, _, _), |
| 854 | .reorderTask(let id, _, _, _, _), .organizeTask(let id, _), .savePlan(let id, _, _), .attachFile(let id, _): |
| 855 | snapshot?.tasks.first(where: { $0.id == id })?.title ?? "Task" |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | func clearRejection() { |
| 860 | var updated = state |
| 861 | updated.rejected = nil |
| 862 | try? save(updated) |
| 863 | } |
| 864 | |
| 865 | func projectName(_ id: String) -> String { |
| 866 | snapshot?.projects.first(where: { $0.id == id })?.name ?? "Project" |
| 867 | } |
| 868 | |
| 869 | private func cacheURL(_ account: String) -> URL { |
| 870 | directory.appending(path: "cloud-" + account + ".json") |
| 871 | } |
| 872 | |
| 873 | private func load(_ url: URL) -> LocalState? { |
| 874 | guard let data = try? Data(contentsOf: url) else { return nil } |
| 875 | return try? JSONDecoder().decode(LocalState.self, from: data) |
| 876 | } |
| 877 | |
| 878 | private func save(_ updated: LocalState) throws { |
| 879 | guard let account else { throw CompanionCloudError.accountUnavailable } |
| 880 | var directory = directory |
| 881 | try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) |
| 882 | var values = URLResourceValues() |
| 883 | values.isExcludedFromBackup = true |
| 884 | try directory.setResourceValues(values) |
| 885 | try JSONEncoder().encode(updated).write(to: cacheURL(account), options: [.atomic, .completeFileProtection]) |
| 886 | state = updated |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | typealias PhoneAssistantHistory = TaskAssistantHistory |