OpenTalon / app / native / Sources / OpenTalon / WorkspaceModel.swift
| 1 | import AppKit |
| 2 | import CompanionCore |
| 3 | import Observation |
| 4 | import SwiftUI |
| 5 | |
| 6 | enum WorkspaceSheet: Identifiable { |
| 7 | case settings, connectionIntroduction, connectionSetup, agentChat, project(Board?), projectFolder(Board), task(WorkStatus), send, icon(Board), preview(Preview) |
| 8 | var id: String { |
| 9 | switch self { |
| 10 | case .settings: "settings" |
| 11 | case .connectionIntroduction: "connection-introduction" |
| 12 | case .connectionSetup: "connection-setup" |
| 13 | case .agentChat: "agent-chat" |
| 14 | case .project: "project" |
| 15 | case .projectFolder: "project-folder" |
| 16 | case .task: "task" |
| 17 | case .send: "send" |
| 18 | case .icon: "icon" |
| 19 | case .preview: "preview" |
| 20 | } |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | struct ViewOptions: Codable { |
| 25 | var priority: Priority? |
| 26 | var sort: String = BoardSort.manual.rawValue |
| 27 | var doneOrder: DoneOrder? |
| 28 | } |
| 29 | |
| 30 | struct Notice: Identifiable { |
| 31 | var id = UUID() |
| 32 | var title: String |
| 33 | var message: String |
| 34 | } |
| 35 | |
| 36 | @MainActor |
| 37 | @Observable |
| 38 | final class WorkspaceModel { |
| 39 | @ObservationIgnored let service = Service() |
| 40 | @ObservationIgnored let profile: URL |
| 41 | @ObservationIgnored let phoneCompanion: PhoneCompanion |
| 42 | let agentChat: AgentChat |
| 43 | let taskAssistant: MacTaskAssistant |
| 44 | @ObservationIgnored var appearanceChanged: ((Theme) -> Void)? |
| 45 | @ObservationIgnored private var refreshTask: Task<Void, Never>? |
| 46 | @ObservationIgnored private let defaults: UserDefaults? |
| 47 | var workspace: Workspace? |
| 48 | var page: WorkspacePage = .dashboard |
| 49 | var showsSidebar = true |
| 50 | var sheet: WorkspaceSheet? |
| 51 | var selection: String? |
| 52 | var search = "" |
| 53 | var searchSignal = 0 |
| 54 | var notice: Notice? |
| 55 | var startupError: String? |
| 56 | var workspaceLocked = false |
| 57 | @ObservationIgnored var retryWorkspace: (() -> Void)? |
| 58 | var banner: String? |
| 59 | var createdTask: WorkItem? |
| 60 | var isQuickAdding = false |
| 61 | var isWorkspaceWindowKey = false |
| 62 | var draftDirty = false |
| 63 | var pendingSend: (name: String, input: [String: Any], title: String)? |
| 64 | var options: [String: ViewOptions] = [:] |
| 65 | var undoTrash: WorkItem? |
| 66 | var connectionSignal = 0 |
| 67 | var backupSignal = 0 |
| 68 | var isolatedProfile: Bool { defaults == nil } |
| 69 | |
| 70 | init(profile: URL, useDefaults: Bool) { |
| 71 | self.profile = profile |
| 72 | agentChat = AgentChat(profile: profile) |
| 73 | taskAssistant = MacTaskAssistant(profile: profile) |
| 74 | phoneCompanion = PhoneCompanion(profile: profile, isolated: !useDefaults) |
| 75 | defaults = useDefaults ? .standard : nil |
| 76 | if let data = defaults?.data(forKey: "BoardOptions"), |
| 77 | let saved = try? JSONDecoder().decode([String: ViewOptions].self, from: data) { |
| 78 | options = saved |
| 79 | } |
| 80 | service.onReady = { [weak self] in |
| 81 | guard let self else { return } |
| 82 | self.scheduleRefresh() |
| 83 | if useDefaults || self.phoneCompanion.usesLocalTransport { self.phoneCompanion.start(service: self.service) } |
| 84 | } |
| 85 | service.onChange = { [weak self] in self?.scheduleRefresh() } |
| 86 | service.onBackupChange = { [weak self] in self?.backupSignal += 1 } |
| 87 | service.onChatActivity = { [weak self] name, title in self?.agentChat.record(name, title: title) } |
| 88 | service.onFailure = { [weak self] error in |
| 89 | if self?.startupError == nil { self?.startupError = error.message } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | func offerConnectionIntroduction() { |
| 94 | guard let defaults, !defaults.bool(forKey: "HasSeenConnectionIntroduction") else { return } |
| 95 | defaults.set(true, forKey: "HasSeenConnectionIntroduction") |
| 96 | sheet = .connectionIntroduction |
| 97 | } |
| 98 | |
| 99 | var boards: [Board] { workspace?.boards ?? [] } |
| 100 | var canUseAgents: Bool { workspace?.agentConnectionReady == true } |
| 101 | var editableStatuses: [WorkStatus] { WorkStatus.allCases.filter { $0 != .sent || canUseAgents } } |
| 102 | |
| 103 | func requireAgentConnection() throws { |
| 104 | guard canUseAgents else { |
| 105 | throw ServiceFailure(code: "MCP_DISABLED", message: "Connect MCP in Settings on your Mac to use agents.") |
| 106 | } |
| 107 | } |
| 108 | var tasks: [WorkItem] { workspace?.tasks ?? [] } |
| 109 | var board: Board? { |
| 110 | guard case .board(let id) = page else { return nil } |
| 111 | return boards.first { $0.id == id } |
| 112 | } |
| 113 | var selected: WorkItem? { |
| 114 | tasks.first { $0.id == selection && !$0.deleted } |
| 115 | } |
| 116 | var selectedBoard: String? { workspace?.selectedBoard ?? boards.first?.id } |
| 117 | var sort: BoardSort { |
| 118 | get { BoardSort(rawValue: options[page.storageKey]?.sort ?? "") ?? .manual } |
| 119 | set { updateOptions { $0.sort = newValue.rawValue } } |
| 120 | } |
| 121 | var doneOrder: DoneOrder { |
| 122 | get { options[page.storageKey]?.doneOrder ?? .recent } |
| 123 | set { updateOptions { $0.doneOrder = newValue } } |
| 124 | } |
| 125 | var priority: Priority? { |
| 126 | get { options[page.storageKey]?.priority } |
| 127 | set { updateOptions { $0.priority = newValue } } |
| 128 | } |
| 129 | |
| 130 | private func updateOptions(_ change: (inout ViewOptions) -> Void) { |
| 131 | change(&options[page.storageKey, default: ViewOptions()]) |
| 132 | defaults?.set(try? JSONEncoder().encode(options), forKey: "BoardOptions") |
| 133 | } |
| 134 | |
| 135 | func scheduleRefresh() { |
| 136 | guard refreshTask == nil else { return } |
| 137 | refreshTask = Task { [weak self] in |
| 138 | try? await Task.sleep(for: .milliseconds(55)) |
| 139 | guard let self else { return } |
| 140 | refreshTask = nil |
| 141 | do { try await refresh() } |
| 142 | catch { if workspace == nil { startupError = error.localizedDescription } } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | func refresh() async throws { |
| 147 | let previousTheme = workspace?.theme |
| 148 | workspace = try await service.call("snapshot") |
| 149 | if !canUseAgents { |
| 150 | if case .agentChat = sheet { sheet = nil } |
| 151 | if case .send = sheet { sheet = nil; pendingSend = nil } |
| 152 | } |
| 153 | if let theme = workspace?.theme, theme != previousTheme { appearanceChanged?(theme) } |
| 154 | if case .board(let id) = page, !boards.contains(where: { $0.id == id }) { |
| 155 | page = .dashboard |
| 156 | } |
| 157 | if selection != nil && selected == nil { selection = nil } |
| 158 | } |
| 159 | |
| 160 | func write<Response: Decodable>(_ action: String, _ input: [String: Any]) async throws -> Response { |
| 161 | var fields = input |
| 162 | if fields["requestKey"] == nil { fields["requestKey"] = "mac:" + UUID().uuidString } |
| 163 | let result: Response = try await service.call(action, fields) |
| 164 | try await refresh() |
| 165 | return result |
| 166 | } |
| 167 | |
| 168 | func mutate(_ action: String, _ input: [String: Any]) async throws { |
| 169 | if action == "create_task" { |
| 170 | _ = try await saveNewTask(input) |
| 171 | } else { |
| 172 | let _: EmptyResponse = try await write(action, input) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | func saveNewTask(_ input: [String: Any], newProjectName: String? = nil) async throws -> WorkItem { |
| 177 | var fields = input |
| 178 | if fields["requestKey"] == nil { fields["requestKey"] = "mac:" + UUID().uuidString } |
| 179 | fields["newProjectName"] = newProjectName |
| 180 | let result: ItemResponse = try await service.call(newProjectName == nil ? "create_task" : "capture_task", fields) |
| 181 | scheduleRefresh() |
| 182 | createdTask = result.task |
| 183 | return result.task |
| 184 | } |
| 185 | |
| 186 | func openCreatedTask(_ id: String) { |
| 187 | guard canLeave() else { return } |
| 188 | perform { |
| 189 | try await self.refresh() |
| 190 | guard self.canLeave() else { return } |
| 191 | if self.createdTask?.id == id { self.createdTask = nil } |
| 192 | guard let item = self.tasks.first(where: { $0.id == id && !$0.deleted }) else { |
| 193 | self.banner = "This task is no longer available." |
| 194 | return |
| 195 | } |
| 196 | self.navigate(.board(item.boardId)) |
| 197 | self.select(item) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | func perform(_ operation: @escaping @MainActor () async throws -> Void) { |
| 202 | Task { |
| 203 | do { try await operation() } |
| 204 | catch { show(error) } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | func show(_ error: Error) { |
| 209 | notice = Notice(title: "OpenTalon", message: error.localizedDescription) |
| 210 | } |
| 211 | |
| 212 | func canLeave() -> Bool { |
| 213 | guard draftDirty else { |
| 214 | return true |
| 215 | } |
| 216 | banner = "Save or discard your task changes before leaving." |
| 217 | return false |
| 218 | } |
| 219 | |
| 220 | func navigate(_ destination: WorkspacePage) { |
| 221 | guard canLeave() else { return } |
| 222 | page = destination |
| 223 | selection = nil |
| 224 | search = "" |
| 225 | banner = nil |
| 226 | if case .board(let id) = destination, id != selectedBoard { |
| 227 | perform { try await self.preferences(["selectedBoard": id]) } |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | func preferences(_ fields: [String: Any]) async throws { |
| 232 | guard let revision = workspace?.preferencesRevision else { return } |
| 233 | var input = fields |
| 234 | input["expectedRevision"] = revision |
| 235 | try await mutate("set_preferences", input) |
| 236 | } |
| 237 | |
| 238 | func select(_ item: WorkItem) { |
| 239 | guard selection == item.id || canLeave() else { return } |
| 240 | selection = item.id |
| 241 | banner = nil |
| 242 | } |
| 243 | |
| 244 | func findTasks() { |
| 245 | if page == .dashboard || page == .about || page == .assistant { navigate(.all) } |
| 246 | searchSignal += 1 |
| 247 | } |
| 248 | |
| 249 | func newTask(_ status: WorkStatus = .todo) { |
| 250 | guard canLeave(), workspace != nil, status != .sent || canUseAgents else { return } |
| 251 | sheet = .task(status) |
| 252 | } |
| 253 | |
| 254 | func projectName(_ id: String) -> String { |
| 255 | boards.first { $0.id == id }?.name ?? "Project" |
| 256 | } |
| 257 | |
| 258 | func column(_ status: WorkStatus, filtered: Bool = true, sorting: BoardSort? = nil) -> [WorkItem] { |
| 259 | let boardId = board?.id |
| 260 | let base = tasks.filter { |
| 261 | !$0.deleted && $0.archivedAt == nil && $0.status == status && (boardId == nil || $0.boardId == boardId) |
| 262 | } |
| 263 | if status == .done, sorting == nil, doneOrder != .manual { |
| 264 | return doneOrder.ordered(base.filter { !filtered || matches($0) }, |
| 265 | completionDate: \.completionDate, creationDate: \.creationDate) |
| 266 | } |
| 267 | let selectedSort = sorting ?? (status == .done ? .manual : sort) |
| 268 | if selectedSort == .newest { |
| 269 | return newestFirst(base.filter { !filtered || matches($0) }) |
| 270 | } |
| 271 | if status == .todo && sorting == nil { |
| 272 | let visible = base.filter { !filtered || matches($0) } |
| 273 | let dated = visible.map { (item: $0, date: $0.creationDate) } |
| 274 | let newestFirst = dated.sorted { first, second in |
| 275 | let order = TaskCreationOrder.precedes(urgent: first.item.priority == .urgent, createdAt: first.date, |
| 276 | otherUrgent: second.item.priority == .urgent, otherCreatedAt: second.date) |
| 277 | return order ?? (first.item.id < second.item.id) |
| 278 | } |
| 279 | return newestFirst.map(\.item) |
| 280 | } |
| 281 | let boardOrder = base.sorted { |
| 282 | ($0.position, $0.id) < ($1.position, $1.id) |
| 283 | } |
| 284 | let ordered = page == .all ? orderAcrossProjects(boardOrder) : boardOrder |
| 285 | return ordered.enumerated() |
| 286 | .filter { !filtered || matches($0.element) } |
| 287 | .sorted { |
| 288 | let first = selectedSort.rank($0.element.priority) |
| 289 | let second = selectedSort.rank($1.element.priority) |
| 290 | return selectedSort != .manual && first != second ? first < second : $0.offset < $1.offset |
| 291 | } |
| 292 | .map(\.element) |
| 293 | } |
| 294 | |
| 295 | var recentTasks: [WorkItem] { |
| 296 | newestFirst(tasks.filter { !$0.deleted && $0.archivedAt == nil && matches($0, filterPriority: false) }) |
| 297 | } |
| 298 | |
| 299 | private func newestFirst(_ tasks: [WorkItem]) -> [WorkItem] { |
| 300 | tasks.map { (task: $0, date: $0.creationDate ?? .distantPast) } |
| 301 | .sorted { ($0.date, $0.task.id) > ($1.date, $1.task.id) } |
| 302 | .map(\.task) |
| 303 | } |
| 304 | |
| 305 | private func orderAcrossProjects(_ column: [WorkItem]) -> [WorkItem] { |
| 306 | let byId = Dictionary(uniqueKeysWithValues: column.map { ($0.id, $0) }) |
| 307 | let queues = Dictionary(grouping: column, by: \.boardId) |
| 308 | var placed: Set<String> = [] |
| 309 | var slots = (workspace?.allTasksOrder ?? []).compactMap { id -> String? in |
| 310 | guard let item = byId[id], placed.insert(id).inserted else { return nil } |
| 311 | return item.boardId |
| 312 | } |
| 313 | for board in boards { |
| 314 | slots.append(contentsOf: (queues[board.id] ?? []).filter { !placed.contains($0.id) }.map(\.boardId)) |
| 315 | } |
| 316 | var offsets: [String: Int] = [:] |
| 317 | return slots.compactMap { id in |
| 318 | let index = offsets[id, default: 0] |
| 319 | offsets[id] = index + 1 |
| 320 | return queues[id]?[index] |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | func matches(_ item: WorkItem, filterPriority: Bool = true) -> Bool { |
| 325 | let query = search.trimmingCharacters(in: .whitespacesAndNewlines) |
| 326 | return (!filterPriority || priority == nil || item.priority == priority) && |
| 327 | (query.isEmpty || item.reference.localizedCaseInsensitiveContains(query) || |
| 328 | item.kind.rawValue.localizedCaseInsensitiveContains(query) || |
| 329 | item.title.localizedCaseInsensitiveContains(query) || item.notes.localizedCaseInsensitiveContains(query)) |
| 330 | } |
| 331 | |
| 332 | func createItem(title: String, notes: String, definitionOfDone: String, project: String, |
| 333 | status: WorkStatus, priority: Priority, planMarkdown: String? = nil, issueType: IssueType = .issue) async throws { |
| 334 | var fields: [String: Any] = [ |
| 335 | "boardId": project, "title": title, "notes": notes, "definitionOfDone": definitionOfDone, |
| 336 | "status": status.rawValue, "priority": priority.rawValue, "issueType": issueType.rawValue |
| 337 | ] |
| 338 | fields["planMarkdown"] = planMarkdown |
| 339 | try await sendable("create_task", fields, title: title, choosingModel: status == .sent) |
| 340 | } |
| 341 | |
| 342 | func move(_ item: WorkItem, to status: WorkStatus, board boardId: String? = nil, |
| 343 | anchor: String? = nil, before: Bool = true) { |
| 344 | guard canLeave(), anchor != item.id else { return } |
| 345 | perform { |
| 346 | var fields = item.write |
| 347 | fields["status"] = status.rawValue |
| 348 | fields["boardId"] = boardId ?? item.boardId |
| 349 | if let anchor { fields[before ? "beforeId" : "afterId"] = anchor } |
| 350 | try await self.sendable("move_task", fields, title: item.title, choosingModel: status == .sent && item.status != .sent) |
| 351 | if let boardId, case .board = self.page, self.board?.id != boardId, self.pendingSend == nil { |
| 352 | self.navigate(.board(boardId)) |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | func drop(_ id: String, in status: WorkStatus, anchor: String?, before: Bool) -> Bool { |
| 358 | guard status != .sent || canUseAgents, canLeave(), id != anchor, let item = tasks.first(where: { $0.id == id && !$0.deleted }), |
| 359 | let workspace else { return false } |
| 360 | if status == .todo { |
| 361 | guard item.status != .todo else { return false } |
| 362 | move(item, to: status) |
| 363 | return true |
| 364 | } |
| 365 | if status == .done, doneOrder != .manual { |
| 366 | guard item.status != .done else { return false } |
| 367 | move(item, to: .done) |
| 368 | return true |
| 369 | } |
| 370 | let selectedSort = status == .done ? .manual : sort |
| 371 | let sorted = selectedSort != .manual && item.status == status |
| 372 | let all = page == .all |
| 373 | guard all || sorted else { |
| 374 | move(item, to: status, anchor: selectedSort == .manual ? anchor : nil, before: before) |
| 375 | return true |
| 376 | } |
| 377 | let key = page.storageKey |
| 378 | let useAnchor = sorted || selectedSort == .manual ? anchor : nil |
| 379 | var ids = column(status, filtered: false, sorting: sorted ? selectedSort : .manual).map(\.id).filter { $0 != id } |
| 380 | let index = useAnchor.flatMap { ids.firstIndex(of: $0) }.map { $0 + (before ? 0 : 1) } ?? ids.endIndex |
| 381 | ids.insert(id, at: index) |
| 382 | var fields: [String: Any] = ["status": status.rawValue, "expectedRevision": workspace.revision, "taskIds": ids] |
| 383 | if !all { fields["boardId"] = item.boardId } |
| 384 | if all && status == .sent && item.status != .sent { |
| 385 | stageSend("reorder_all_tasks", fields, title: item.title) |
| 386 | return true |
| 387 | } |
| 388 | perform { |
| 389 | do { |
| 390 | try await self.mutate(all ? "reorder_all_tasks" : "reorder_tasks", fields) |
| 391 | if sorted { |
| 392 | self.options[key, default: ViewOptions()].sort = BoardSort.manual.rawValue |
| 393 | self.defaults?.set(try? JSONEncoder().encode(self.options), forKey: "BoardOptions") |
| 394 | self.banner = "Manual order saved" |
| 395 | } |
| 396 | } catch let failure as ServiceFailure where self.isSetup(failure) { |
| 397 | var move = item.write |
| 398 | move["status"] = status.rawValue |
| 399 | move["boardId"] = item.boardId |
| 400 | self.stageSend("move_task", move, title: item.title) |
| 401 | } |
| 402 | } |
| 403 | return true |
| 404 | } |
| 405 | |
| 406 | private func isSetup(_ error: ServiceFailure) -> Bool { |
| 407 | ["AGENT_SETUP_REQUIRED", "AGENT_NOT_INSTALLED", "MCP_DISABLED"].contains(error.code) |
| 408 | } |
| 409 | |
| 410 | private func stageSend(_ name: String, _ fields: [String: Any], title: String) { |
| 411 | guard canUseAgents else { return } |
| 412 | var fields = fields |
| 413 | if fields["requestKey"] == nil { fields["requestKey"] = "mac:" + UUID().uuidString } |
| 414 | pendingSend = (name, fields, title) |
| 415 | sheet = .send |
| 416 | } |
| 417 | |
| 418 | private func sendable(_ name: String, _ fields: [String: Any], title: String, choosingModel: Bool) async throws { |
| 419 | if choosingModel { |
| 420 | try requireAgentConnection() |
| 421 | stageSend(name, fields, title: title) |
| 422 | return |
| 423 | } |
| 424 | var fields = fields |
| 425 | fields["requestKey"] = "mac:" + UUID().uuidString |
| 426 | do { try await mutate(name, fields) } |
| 427 | catch let failure as ServiceFailure where isSetup(failure) { stageSend(name, fields, title: title) } |
| 428 | } |
| 429 | |
| 430 | func finishSend(agent: PhoneAgent?, model: String?, comment: String = "") async throws { |
| 431 | try requireAgentConnection() |
| 432 | guard let intent = pendingSend else { return } |
| 433 | var input = intent.input |
| 434 | input["agent"] = agent?.rawValue |
| 435 | input["model"] = model |
| 436 | let comment = comment.trimmingCharacters(in: .whitespacesAndNewlines) |
| 437 | if !comment.isEmpty { input["dispatchComment"] = comment } |
| 438 | if let id = input["id"] as? String { |
| 439 | let current: ItemResponse = try await service.call("get_task", ["id": id]) |
| 440 | guard !current.task.deleted else { |
| 441 | throw ServiceFailure(code: "NOT_FOUND", message: "This task is in Trash.") |
| 442 | } |
| 443 | input["expectedRevision"] = current.task.revision |
| 444 | } |
| 445 | try await mutate(intent.name, input) |
| 446 | pendingSend = nil |
| 447 | sheet = nil |
| 448 | } |
| 449 | |
| 450 | func trash(_ item: WorkItem) { |
| 451 | guard canLeave() else { return } |
| 452 | perform { |
| 453 | let result: ItemResponse = try await self.write("trash_task", item.write) |
| 454 | self.undoTrash = result.task |
| 455 | self.banner = "Task moved to Trash" |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | func restore(_ item: WorkItem) { |
| 460 | perform { |
| 461 | try await self.mutate("restore_task", item.write) |
| 462 | self.undoTrash = nil |
| 463 | self.banner = "Task restored" |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | func preview(_ action: String, path: String? = nil, taskIds: [String]? = nil) async throws { |
| 468 | var input: [String: Any] = ["action": action] |
| 469 | input["path"] = path |
| 470 | input["taskIds"] = taskIds |
| 471 | let result: Preview = try await service.call("preview_destructive_action", input) |
| 472 | sheet = .preview(result) |
| 473 | } |
| 474 | } |