OpenTalon / app · opentalon.ai / native / Sources / OpenTalon / PhoneCompanion.swift
| 1 | import CompanionCore |
| 2 | import Foundation |
| 3 | import Observation |
| 4 | import SwiftUI |
| 5 | |
| 6 | @MainActor |
| 7 | @Observable |
| 8 | final class PhoneCompanion { |
| 9 | private struct Identity: Codable { |
| 10 | var workspaceID = UUID() |
| 11 | var account: String? |
| 12 | } |
| 13 | |
| 14 | private struct TicketSnapshot: Decodable { |
| 15 | let workspace: Workspace |
| 16 | let defaultAgent: PhoneAgent |
| 17 | let availableAgents: [PhoneAgent] |
| 18 | let agentConnectionReady: Bool |
| 19 | let agentModels: [AgentModelChoice] |
| 20 | let commentsByTask: [String: [PhoneComment]] |
| 21 | let filesByTask: [String: [TaskFile]]? |
| 22 | let historyByTask: [String: TaskHistoryPage] |
| 23 | let activityByTask: [String: TaskActivityPage] |
| 24 | } |
| 25 | |
| 26 | private struct MutationRevision: Decodable { |
| 27 | struct TaskIdentity: Decodable { let id: String } |
| 28 | let revision: Int |
| 29 | let task: TaskIdentity? |
| 30 | } |
| 31 | |
| 32 | @ObservationIgnored private let file: URL |
| 33 | @ObservationIgnored private let cloud: any CompanionTransport |
| 34 | @ObservationIgnored private var polling: Task<Void, Never>? |
| 35 | @ObservationIgnored private var uploadedFiles: [String: String] = [:] |
| 36 | private var identity: Identity |
| 37 | private(set) var lastSync: Date? |
| 38 | private(set) var error: String? |
| 39 | private(set) var syncing = false |
| 40 | |
| 41 | init(profile: URL, isolated: Bool) { |
| 42 | #if DEBUG |
| 43 | if isolated, let path = ProcessInfo.processInfo.environment["OPENTALON_LOCAL_SYNC_DIRECTORY"], !path.isEmpty { |
| 44 | cloud = LocalCompanionTransport(directory: URL(fileURLWithPath: path, isDirectory: true)) |
| 45 | } else { |
| 46 | cloud = CompanionCloud() |
| 47 | } |
| 48 | #else |
| 49 | cloud = CompanionCloud() |
| 50 | #endif |
| 51 | // Read the old workspace ID so queued requests retain their original identity. |
| 52 | file = profile.appendingPathComponent("phone-cloud.json") |
| 53 | let legacy = profile.appendingPathComponent("phone-companion.json") |
| 54 | identity = [file, legacy].compactMap { url in |
| 55 | guard let data = try? Data(contentsOf: url) else { return nil } |
| 56 | return try? JSONDecoder().decode(Identity.self, from: data) |
| 57 | }.first ?? Identity() |
| 58 | } |
| 59 | |
| 60 | var usesLocalTransport: Bool { |
| 61 | #if DEBUG |
| 62 | return cloud is LocalCompanionTransport |
| 63 | #else |
| 64 | return false |
| 65 | #endif |
| 66 | } |
| 67 | |
| 68 | func start(service: Service) { |
| 69 | guard polling == nil else { return } |
| 70 | polling = Task { [weak self, weak service] in |
| 71 | while let self, let service, !Task.isCancelled { |
| 72 | await sync(service: service) |
| 73 | do { try await Task.sleep(for: .seconds(15)) } |
| 74 | catch { return } |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | func sync(service: Service) async { |
| 80 | guard service.ready, !syncing else { return } |
| 81 | syncing = true |
| 82 | defer { syncing = false } |
| 83 | do { |
| 84 | let account = try await cloud.accountKey() |
| 85 | if let original = identity.account, original != account { |
| 86 | throw CompanionCloudError.accountChanged |
| 87 | } |
| 88 | if identity.account == nil { |
| 89 | var updated = identity |
| 90 | updated.account = account |
| 91 | try JSONEncoder().encode(updated).write(to: file, options: .atomic) |
| 92 | identity = updated |
| 93 | } |
| 94 | try await cloud.prepare(account: account) |
| 95 | let snapshot: TicketSnapshot = try await service.call("native_phone_snapshot") |
| 96 | try await cloud.publish(projection(snapshot)) |
| 97 | let requests = try await cloud.pendingRequests(for: identity.workspaceID) |
| 98 | for request in PhoneRequest.applicationOrder(requests) { |
| 99 | let receipt = try await apply(request, service: service) |
| 100 | try await cloud.acknowledge(receipt) |
| 101 | } |
| 102 | if !requests.isEmpty { |
| 103 | let updated: TicketSnapshot = try await service.call("native_phone_snapshot") |
| 104 | try await cloud.publish(projection(updated)) |
| 105 | try await syncFiles(updated, service: service) |
| 106 | } else { |
| 107 | try await syncFiles(snapshot, service: service) |
| 108 | } |
| 109 | lastSync = .now |
| 110 | error = nil |
| 111 | } catch { |
| 112 | self.error = error.localizedDescription |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | private func syncFiles(_ snapshot: TicketSnapshot, service: Service) async throws { |
| 117 | for file in (snapshot.filesByTask ?? [:]).values.joined() { |
| 118 | guard uploadedFiles[file.id] != file.sha256 else { continue } |
| 119 | struct Contents: Decodable { let base64: Data } |
| 120 | let contents: Contents = try await service.call("read_task_file", ["taskId": file.taskId, "fileId": file.id]) |
| 121 | try await cloud.putFile(file, data: contents.base64, workspaceID: identity.workspaceID) |
| 122 | uploadedFiles[file.id] = file.sha256 |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | private func projection(_ snapshot: TicketSnapshot) -> PhoneSnapshot { |
| 127 | let workspace = snapshot.workspace |
| 128 | let projects = workspace.boards.map { |
| 129 | PhoneProject(id: $0.id, name: $0.name, createdAt: $0.createdAt.flatMap(TaskCreationOrder.date(from:))) |
| 130 | } |
| 131 | let pickups = Dictionary(uniqueKeysWithValues: workspace.agentRuns.compactMap { run in |
| 132 | run.pickedUpAt.flatMap(TaskCreationOrder.date(from:)).map { (run.id, PhoneAgentPickup(id: run.id, at: $0)) } |
| 133 | }) |
| 134 | let latestRuns = Dictionary(workspace.agentRuns.map { ($0.taskId, $0) }, uniquingKeysWith: { latest, _ in latest }) |
| 135 | let tasks = workspace.tasks.compactMap { item -> PhoneTask? in |
| 136 | guard !item.deleted, let status = PhoneTask.Status(rawValue: item.status.rawValue), |
| 137 | let priority = PhoneTask.Priority(rawValue: item.priority.rawValue) else { return nil } |
| 138 | let error: String? = if status == .todo, let run = latestRuns[item.id], |
| 139 | run.pickedUpAt == nil, ["failed", "interrupted"].contains(run.state) { |
| 140 | run.summary |
| 141 | } else { nil } |
| 142 | return PhoneTask( |
| 143 | id: item.id, projectID: item.boardId, title: item.title, |
| 144 | notes: item.notes, definitionOfDone: item.definitionOfDone, |
| 145 | status: status, priority: priority, dueDate: item.dueDate, revision: item.revision, |
| 146 | assigned: workspace.agentAssignments[item.id] != nil, |
| 147 | taskKey: item.taskKey, createdAt: item.creationDate, |
| 148 | archivedAt: item.archivedAt.flatMap(TaskCreationOrder.date(from:)), |
| 149 | agentPickup: workspace.agentAssignments[item.id].flatMap { pickups[$0] }, |
| 150 | agentDispatchError: error, position: item.position, planMarkdown: item.planMarkdown, issueType: item.kind, |
| 151 | completedAt: item.completionDate, updatedAt: TaskCreationOrder.date(from: item.updatedAt) |
| 152 | ) |
| 153 | } |
| 154 | return PhoneSnapshot(workspaceID: identity.workspaceID, revision: workspace.revision, |
| 155 | projects: projects, tasks: tasks, defaultAgent: snapshot.defaultAgent, |
| 156 | commentsByTask: snapshot.commentsByTask, supportsNoteEditing: true, |
| 157 | supportsFieldEditing: true, includesCardMetadata: true, |
| 158 | availableAgents: snapshot.availableAgents, agentModels: snapshot.agentModels, |
| 159 | supportsDispatchComments: true, |
| 160 | trashedTasks: workspace.tasks.filter(\.deleted) |
| 161 | .sorted { ($0.deletedAt ?? "") > ($1.deletedAt ?? "") } |
| 162 | .map { PhoneTrashedTask(id: $0.id, projectID: $0.boardId, |
| 163 | title: $0.title, revision: $0.revision, |
| 164 | updatedAt: TaskCreationOrder.date(from: $0.updatedAt), |
| 165 | deletedAt: $0.deletedAt.flatMap(TaskCreationOrder.date(from:))) }, |
| 166 | captureProjectID: workspace.selectedBoard, macName: Host.current().localizedName ?? "Mac", |
| 167 | supportsTaskOverrides: true, supportsBulkArchive: true, supportsTaskReordering: true, |
| 168 | supportsTaskOrganization: true, supportsTaskPlans: true, supportsTaskTypes: true, historyByTask: snapshot.historyByTask, activityByTask: snapshot.activityByTask, supportsCommentActivity: true, |
| 169 | includesCompletionDates: true, agentConnectionReady: snapshot.agentConnectionReady, |
| 170 | includesTaskUpdateDates: true, filesByTask: snapshot.filesByTask, |
| 171 | supportsRevisionWithdrawal: true) |
| 172 | } |
| 173 | |
| 174 | private func apply(_ request: PhoneRequest, service: Service) async throws -> PhoneReceipt { |
| 175 | let action: String |
| 176 | var input: [String: Any] = ["requestKey": "phone:" + request.id.uuidString] |
| 177 | switch request.action { |
| 178 | case .attachFile(let id, let file): |
| 179 | action = "attach_task_file" |
| 180 | input["taskId"] = id |
| 181 | input["name"] = file.name |
| 182 | input["contentType"] = file.contentType |
| 183 | input["base64"] = file.bytes.base64EncodedString() |
| 184 | case .loadCommentActivity(let id, let commentID, let before): |
| 185 | var fields: [String: Any] = ["taskId": id, "commentId": commentID, "limit": 20] |
| 186 | fields["beforeSequence"] = before |
| 187 | do { |
| 188 | let page: TaskActivityPage = try await service.call("list_task_activity", fields) |
| 189 | return PhoneReceipt(requestID: request.id, outcome: .applied, revision: page.revision, activity: page) |
| 190 | } catch let failure as ServiceFailure where failure.code == "NOT_FOUND" { |
| 191 | return PhoneReceipt(requestID: request.id, outcome: .rejected, message: failure.message) |
| 192 | } |
| 193 | case .loadActivity(let id, let before): |
| 194 | var fields: [String: Any] = ["taskId": id, "limit": 20] |
| 195 | fields["beforeSequence"] = before |
| 196 | do { |
| 197 | let page: TaskActivityPage = try await service.call("list_task_activity", fields) |
| 198 | return PhoneReceipt(requestID: request.id, outcome: .applied, revision: page.revision, activity: page) |
| 199 | } catch let failure as ServiceFailure where failure.code == "NOT_FOUND" { |
| 200 | return PhoneReceipt(requestID: request.id, outcome: .rejected, message: failure.message) |
| 201 | } |
| 202 | case .loadHistory(let id, let before): |
| 203 | var fields: [String: Any] = ["id": id, "limit": 20] |
| 204 | fields["beforeVersion"] = before |
| 205 | do { |
| 206 | let page: TaskHistoryPage = try await service.call("get_task_history", fields) |
| 207 | return PhoneReceipt(requestID: request.id, outcome: .applied, revision: page.revision, history: page) |
| 208 | } catch let failure as ServiceFailure where failure.code == "NOT_FOUND" { |
| 209 | return PhoneReceipt(requestID: request.id, outcome: .rejected, message: failure.message) |
| 210 | } |
| 211 | case .restoreRevision(let id, let historyID, let revision): |
| 212 | action = "restore_task_revision" |
| 213 | input["id"] = id |
| 214 | input["historyID"] = historyID |
| 215 | input["expectedRevision"] = revision |
| 216 | case .createProject(let name): |
| 217 | action = "create_board" |
| 218 | input["name"] = name |
| 219 | case .savePlan(let id, let expected, let markdown): |
| 220 | action = "set_task_plan" |
| 221 | input["id"] = id |
| 222 | input["expectedMarkdown"] = expected |
| 223 | input["markdown"] = markdown |
| 224 | case .organizeTask(let id, let destination): |
| 225 | action = "companion_organize_task" |
| 226 | input["id"] = id |
| 227 | input["destination"] = destination.rawValue |
| 228 | case .create(let project, let title, let notes, let priority, let send, let definitionOfDone, let agent, let model, |
| 229 | let dispatchComment, let newProjectName, let planMarkdown, let issueType): |
| 230 | action = newProjectName == nil ? "create_task" : "capture_task" |
| 231 | input["boardId"] = project |
| 232 | input["newProjectName"] = newProjectName |
| 233 | input["title"] = title |
| 234 | input["notes"] = notes |
| 235 | input["planMarkdown"] = planMarkdown |
| 236 | input["issueType"] = issueType?.rawValue |
| 237 | input["definitionOfDone"] = definitionOfDone |
| 238 | input["priority"] = priority.rawValue |
| 239 | input["status"] = send ? WorkStatus.sent.rawValue : WorkStatus.todo.rawValue |
| 240 | input["agent"] = agent?.rawValue |
| 241 | input["model"] = model |
| 242 | input["dispatchComment"] = dispatchComment |
| 243 | case .comment(let id, let text): |
| 244 | action = "add_user_comment" |
| 245 | input["taskId"] = id |
| 246 | input["text"] = text |
| 247 | // The phone's own request ID names the saved request, so the phone can withdraw it later. |
| 248 | input["clientId"] = request.revisionID |
| 249 | let connection: Connection = try await service.call("connection_status") |
| 250 | input["notifyAgent"] = connection.enabled && connection.running |
| 251 | case .withdrawComment(let id, let commentID): |
| 252 | action = "withdraw_revision_request" |
| 253 | input["taskId"] = id |
| 254 | input["id"] = commentID |
| 255 | case .editNotes(let id, let revision, let notes): |
| 256 | action = "update_task" |
| 257 | input["id"] = id |
| 258 | input["expectedRevision"] = revision |
| 259 | input["notes"] = notes |
| 260 | case .removeArchived(let id, let revision, let permanently): |
| 261 | action = permanently ? "companion_delete_archived_task" : "trash_task" |
| 262 | input["id"] = id |
| 263 | input["expectedRevision"] = revision |
| 264 | case .restoreTrashed(let id, let revision): |
| 265 | action = "restore_task" |
| 266 | input["id"] = id |
| 267 | input["expectedRevision"] = revision |
| 268 | case .emptyTrash(let revision): |
| 269 | action = "companion_empty_trash" |
| 270 | input["expectedRevision"] = revision |
| 271 | case .manageArchive(let ids, let revision, let permanently): |
| 272 | action = "manage_archived_tasks" |
| 273 | input["taskIds"] = ids |
| 274 | input["expectedRevision"] = revision |
| 275 | input["permanently"] = permanently |
| 276 | case .forceComplete(let id): |
| 277 | action = "force_complete_task" |
| 278 | input["id"] = id |
| 279 | case .reorderTask(let id, let projectID, let status, let anchorID, let before): |
| 280 | action = "companion_reorder_task" |
| 281 | input["id"] = id |
| 282 | input["boardId"] = projectID |
| 283 | input["status"] = status.rawValue |
| 284 | input["anchorId"] = anchorID |
| 285 | input["before"] = before |
| 286 | case .setField(let id, let expected, let edit): |
| 287 | action = "companion_set_task_field" |
| 288 | input["id"] = id |
| 289 | input["field"] = edit.field.rawValue |
| 290 | input["value"] = edit.value.map { $0 as Any } ?? NSNull() |
| 291 | input["expectedValue"] = expected.map { $0 as Any } ?? NSNull() |
| 292 | if case .status(_, let agent, let model, let comment) = edit { |
| 293 | input["agent"] = agent?.rawValue |
| 294 | input["model"] = model |
| 295 | input["dispatchComment"] = comment |
| 296 | } |
| 297 | case .editField(let id, let revision, let edit): |
| 298 | input["id"] = id |
| 299 | input["expectedRevision"] = revision |
| 300 | switch edit { |
| 301 | case .project(let projectID): |
| 302 | action = "move_task" |
| 303 | input["boardId"] = projectID |
| 304 | case .status(let status, let agent, let model, let dispatchComment): |
| 305 | action = "move_task" |
| 306 | input["status"] = status.rawValue |
| 307 | input["agent"] = agent?.rawValue |
| 308 | input["model"] = model |
| 309 | input["dispatchComment"] = dispatchComment |
| 310 | case .priority(let priority): |
| 311 | action = "update_task" |
| 312 | input["priority"] = priority.rawValue |
| 313 | case .dueDate(let date): |
| 314 | action = "update_task" |
| 315 | input["dueDate"] = date.map { $0 as Any } ?? NSNull() |
| 316 | case .title, .notes, .definitionOfDone, .issueType: |
| 317 | action = "update_task" |
| 318 | input[edit.field.rawValue] = edit.value |
| 319 | } |
| 320 | case .send(let id, let revision, _), .complete(let id, let revision): |
| 321 | let current: Workspace = try await service.call("snapshot") |
| 322 | // A different revision may be a replay after a successful commit. Let the store |
| 323 | // check the original request key before it checks the expected revision. |
| 324 | if let task = current.tasks.first(where: { $0.id == id && $0.revision == revision }), |
| 325 | task.deleted || current.agentAssignments[id] != nil || ![.todo, .working].contains(task.status) { |
| 326 | return PhoneReceipt(requestID: request.id, outcome: .rejected, message: "This task is no longer open for manual changes.") |
| 327 | } |
| 328 | action = "move_task" |
| 329 | input["id"] = id |
| 330 | input["expectedRevision"] = revision |
| 331 | if case .send(_, _, let agent) = request.action { |
| 332 | input["status"] = WorkStatus.sent.rawValue |
| 333 | input["agent"] = agent?.rawValue |
| 334 | } |
| 335 | else { input["status"] = WorkStatus.done.rawValue } |
| 336 | } |
| 337 | |
| 338 | do { |
| 339 | let result: MutationRevision = try await service.call(action, input) |
| 340 | let createdTaskID: String? |
| 341 | if case .create = request.action { createdTaskID = result.task?.id } |
| 342 | else { createdTaskID = nil } |
| 343 | return PhoneReceipt(requestID: request.id, outcome: .applied, revision: result.revision, |
| 344 | createdTaskID: createdTaskID) |
| 345 | } catch let failure as ServiceFailure { |
| 346 | switch failure.code { |
| 347 | case "AGENT_SETUP_REQUIRED", "AGENT_NOT_INSTALLED", "MCP_DISABLED": |
| 348 | return PhoneReceipt(requestID: request.id, outcome: .waiting, message: failure.message) |
| 349 | case "CONFLICT", "NOT_FOUND", "IN_TRASH", "INVALID_ARGUMENT", "INVALID_STATE", "EMPTY_COMMENT", "WITHDRAWN", |
| 350 | "AGENT_ALREADY_RUNNING", "COMPLETION_PROOF_REQUIRED": |
| 351 | return PhoneReceipt(requestID: request.id, outcome: .rejected, message: failure.message) |
| 352 | default: |
| 353 | throw failure |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | struct PhoneCompanionSettings: View { |
| 360 | @Environment(WorkspaceModel.self) private var model |
| 361 | @Environment(\.palette) private var palette |
| 362 | |
| 363 | var body: some View { |
| 364 | VStack(alignment: .leading, spacing: 8) { |
| 365 | Text("iCloud sync").font(.system(size: 16, weight: .semibold)) |
| 366 | Text("OpenTalon syncs projects and tasks automatically with your iPhone using the same Apple Account.") |
| 367 | .font(.system(size: 12)).foregroundStyle(palette.muted) |
| 368 | if let error = model.phoneCompanion.error { |
| 369 | Text(error).font(.caption).foregroundStyle(palette.muted) |
| 370 | } |
| 371 | if let lastSync = model.phoneCompanion.lastSync { |
| 372 | Label("Last synced \(lastSync.formatted(date: .omitted, time: .shortened))", systemImage: "checkmark.icloud") |
| 373 | .font(.caption).foregroundStyle(palette.muted) |
| 374 | } |
| 375 | Button(model.phoneCompanion.syncing ? "Checking iCloud…" : "Check Now", systemImage: "arrow.clockwise") { |
| 376 | Task { await model.phoneCompanion.sync(service: model.service) } |
| 377 | } |
| 378 | .disabled(model.phoneCompanion.syncing || !model.service.ready || model.isolatedProfile) |
| 379 | } |
| 380 | .frame(maxWidth: .infinity, alignment: .leading) |
| 381 | } |
| 382 | } |