OpenTalon / app · opentalon.ai / native / ios / OpenTalonPhone.swift
| 1 | import CloudKit |
| 2 | import CompanionCore |
| 3 | import QuickLook |
| 4 | import SwiftUI |
| 5 | import UIKit |
| 6 | import UniformTypeIdentifiers |
| 7 | import UserNotifications |
| 8 | |
| 9 | private struct PhoneColorsKey: EnvironmentKey { |
| 10 | static let defaultValue = OpenTalonColors(theme: .light) |
| 11 | } |
| 12 | |
| 13 | extension EnvironmentValues { |
| 14 | var phoneColors: OpenTalonColors { |
| 15 | get { self[PhoneColorsKey.self] } |
| 16 | set { self[PhoneColorsKey.self] = newValue } |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | struct PhoneActionLabel: View { |
| 21 | @Environment(\.phoneColors) private var colors |
| 22 | let title: LocalizedStringKey |
| 23 | let systemImage: String |
| 24 | |
| 25 | var body: some View { |
| 26 | Label { |
| 27 | Text(title).foregroundStyle(colors.text) |
| 28 | } icon: { |
| 29 | Image(systemName: systemImage).foregroundStyle(colors.actionAccent) |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | struct PhoneActionButtonStyle: ButtonStyle { |
| 35 | @Environment(\.phoneColors) private var colors |
| 36 | @Environment(\.isEnabled) private var enabled |
| 37 | var horizontalPadding: CGFloat = 14 |
| 38 | var circular = false |
| 39 | var emphasized = false |
| 40 | |
| 41 | func makeBody(configuration: Configuration) -> some View { |
| 42 | let shape = Capsule() |
| 43 | let accent = configuration.role == .destructive ? colors.danger : colors.actionAccent |
| 44 | return configuration.label |
| 45 | .font(.callout.weight(.semibold)) |
| 46 | .foregroundStyle(configuration.role == .destructive ? colors.danger : colors.text) |
| 47 | .padding(.horizontal, circular ? 0 : horizontalPadding) |
| 48 | .padding(.vertical, circular ? 0 : 8) |
| 49 | .frame(width: circular ? 44 : nil, height: circular ? 44 : nil) |
| 50 | .frame(minWidth: 44, minHeight: 44) |
| 51 | .background { |
| 52 | shape.fill(configuration.isPressed ? colors.canvas : colors.card) |
| 53 | if emphasized { shape.fill(accent.opacity(configuration.isPressed ? 0.20 : 0.10)) } |
| 54 | } |
| 55 | .overlay { |
| 56 | shape.strokeBorder(emphasized ? accent.opacity(0.55) : colors.line) |
| 57 | .allowsHitTesting(false) |
| 58 | } |
| 59 | .contentShape(shape) |
| 60 | .opacity(enabled ? 1 : 0.48) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | struct PhoneActionToolbarItem<Content: View>: ToolbarContent { |
| 65 | let placement: ToolbarItemPlacement |
| 66 | @ViewBuilder let content: () -> Content |
| 67 | |
| 68 | var body: some ToolbarContent { |
| 69 | if #available(iOS 26.0, *) { |
| 70 | item.sharedBackgroundVisibility(.hidden) |
| 71 | } else { |
| 72 | item |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | private var item: some ToolbarContent { |
| 77 | ToolbarItem(placement: placement) { |
| 78 | content().buttonStyle(PhoneActionButtonStyle()) |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | extension View { |
| 84 | func phoneConfirmation(_ title: String, isPresented: Binding<Bool>, message: String, |
| 85 | confirm: String, cancel: String? = "Cancel", role: ButtonRole? = nil, |
| 86 | confirmID: String = "phoneConfirmAction", action: @escaping () -> Void) -> some View { |
| 87 | modifier(PhoneConfirmation(isPresented: isPresented, title: title, message: message, confirm: confirm, |
| 88 | cancel: cancel, role: role, confirmID: confirmID, action: action)) |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | private struct PhoneConfirmation: ViewModifier { |
| 93 | @Environment(\.phoneColors) private var colors |
| 94 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 95 | @AccessibilityFocusState private var titleFocused: Bool |
| 96 | @State private var coverPresented = false |
| 97 | @State private var visible = false |
| 98 | @State private var closing = false |
| 99 | |
| 100 | @Binding var isPresented: Bool |
| 101 | let title: String |
| 102 | let message: String |
| 103 | let confirm: String |
| 104 | let cancel: String? |
| 105 | let role: ButtonRole? |
| 106 | let confirmID: String |
| 107 | let action: () -> Void |
| 108 | |
| 109 | func body(content: Content) -> some View { |
| 110 | content |
| 111 | .fullScreenCover(isPresented: $coverPresented) { |
| 112 | dialog.presentationBackground(.clear) |
| 113 | } |
| 114 | .onChange(of: isPresented) { |
| 115 | setCoverPresented(isPresented) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | private var dialog: some View { |
| 120 | ZStack { |
| 121 | Color.black.opacity(visible ? 0.30 : 0) |
| 122 | .ignoresSafeArea() |
| 123 | .accessibilityHidden(true) |
| 124 | ViewThatFits(in: .vertical) { |
| 125 | panel.fixedSize(horizontal: false, vertical: true) |
| 126 | ScrollView { panel } |
| 127 | } |
| 128 | .frame(maxWidth: 370) |
| 129 | .padding(20) |
| 130 | .scaleEffect(visible || reduceMotion ? 1 : 0.96) |
| 131 | .opacity(visible ? 1 : 0) |
| 132 | .allowsHitTesting(visible && !closing) |
| 133 | } |
| 134 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 135 | .accessibilityAction(.escape) { close() } |
| 136 | .task { |
| 137 | await Task.yield() |
| 138 | guard !Task.isCancelled, !closing else { return } |
| 139 | withAnimation(.easeOut(duration: 0.18)) { visible = true } |
| 140 | titleFocused = true |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | private func setCoverPresented(_ presented: Bool) { |
| 145 | guard coverPresented != presented else { return } |
| 146 | var transaction = Transaction(animation: nil) |
| 147 | transaction.disablesAnimations = true |
| 148 | withTransaction(transaction) { |
| 149 | if !presented { visible = false } |
| 150 | coverPresented = presented |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | private func close(confirming: Bool = false) { |
| 155 | guard !closing else { return } |
| 156 | closing = true |
| 157 | withAnimation(.easeIn(duration: 0.14)) { |
| 158 | visible = false |
| 159 | } completion: { |
| 160 | setCoverPresented(false) |
| 161 | isPresented = false |
| 162 | closing = false |
| 163 | if confirming { action() } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | private var panel: some View { |
| 168 | VStack(alignment: .leading, spacing: 12) { |
| 169 | Text(title) |
| 170 | .font(.headline) |
| 171 | .foregroundStyle(colors.text) |
| 172 | .accessibilityAddTraits(.isHeader) |
| 173 | .accessibilityFocused($titleFocused) |
| 174 | Text(message) |
| 175 | .font(.subheadline) |
| 176 | .foregroundStyle(colors.muted) |
| 177 | ViewThatFits(in: .horizontal) { |
| 178 | HStack(spacing: 8) { buttons } |
| 179 | .fixedSize(horizontal: true, vertical: false) |
| 180 | VStack(alignment: .trailing, spacing: 8) { buttons } |
| 181 | } |
| 182 | .frame(maxWidth: .infinity, alignment: .trailing) |
| 183 | } |
| 184 | .padding(20) |
| 185 | .frame(maxWidth: .infinity, alignment: .leading) |
| 186 | .background(colors.canvas, in: RoundedRectangle(cornerRadius: 22)) |
| 187 | .overlay { RoundedRectangle(cornerRadius: 22).strokeBorder(colors.line).allowsHitTesting(false) } |
| 188 | .accessibilityElement(children: .contain) |
| 189 | } |
| 190 | |
| 191 | @ViewBuilder private var buttons: some View { |
| 192 | if let cancel { |
| 193 | Button(cancel, role: .cancel) { close() } |
| 194 | .keyboardShortcut(.cancelAction) |
| 195 | .buttonStyle(PhoneActionButtonStyle()) |
| 196 | } |
| 197 | Button(confirm, role: role) { close(confirming: true) } |
| 198 | .buttonStyle(PhoneActionButtonStyle(emphasized: cancel != nil)) |
| 199 | .accessibilityIdentifier(confirmID) |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | private struct PhoneListAppearance: ViewModifier { |
| 204 | @Environment(\.phoneColors) private var colors |
| 205 | var background: Color? = nil |
| 206 | |
| 207 | func body(content: Content) -> some View { |
| 208 | content.scrollContentBackground(.hidden).background(background ?? colors.canvas) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | @main |
| 213 | struct OpenTalonPhone: App { |
| 214 | @UIApplicationDelegateAdaptor(PhoneNotificationDelegate.self) private var notificationDelegate |
| 215 | @State private var workspace = PhoneWorkspace() |
| 216 | @Environment(\.scenePhase) private var phase |
| 217 | @AppStorage("appearanceTheme") private var theme = OpenTalonTheme.system |
| 218 | |
| 219 | var body: some Scene { |
| 220 | WindowGroup { |
| 221 | CompanionHome() |
| 222 | .environment(workspace) |
| 223 | .preferredColorScheme(theme.colorScheme) |
| 224 | .onReceive(NotificationCenter.default.publisher(for: .CKAccountChanged)) { _ in |
| 225 | workspace.accountDidChange() |
| 226 | } |
| 227 | .task(id: phase) { |
| 228 | guard phase == .active else { return } |
| 229 | while !Task.isCancelled { |
| 230 | await workspace.sync() |
| 231 | do { try await Task.sleep(for: .seconds(15)) } |
| 232 | catch { return } |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | private final class PhoneNotificationDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate { |
| 240 | func application(_ application: UIApplication, |
| 241 | didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { |
| 242 | UNUserNotificationCenter.current().delegate = self |
| 243 | return true |
| 244 | } |
| 245 | |
| 246 | nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, |
| 247 | willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { |
| 248 | [.banner, .list] |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | struct CompanionHome: View { |
| 253 | @State private var showAssistant = false |
| 254 | private enum Page { case today, projects, done, queue, settings } |
| 255 | |
| 256 | @Environment(PhoneWorkspace.self) private var workspace |
| 257 | @Environment(\.colorScheme) private var systemScheme |
| 258 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 259 | @AppStorage("appearanceTheme") private var theme = OpenTalonTheme.system |
| 260 | @State private var showAddTask = false |
| 261 | @AppStorage("OpenTalon.introductionCompleted") private var introductionCompleted = false |
| 262 | @AppStorage("OpenTalon.savedStarterIdea") private var starterIdea = "" |
| 263 | @AppStorage("OpenTalon.savedStarterIdeaAt") private var starterIdeaAt = 0.0 |
| 264 | @State private var showIntroduction = false |
| 265 | @State private var showStarterIdea = false |
| 266 | @State private var captureSeed = "" |
| 267 | @State private var openedTask: PhoneWorkspace.CapturedTask? |
| 268 | @State private var page = Page.today |
| 269 | |
| 270 | var body: some View { |
| 271 | let colors = OpenTalonColors(theme: theme, systemScheme: systemScheme) |
| 272 | TabView(selection: $page) { |
| 273 | NavigationStack { |
| 274 | if workspace.snapshot != nil { |
| 275 | TodayView() |
| 276 | .safeAreaInset(edge: .top, spacing: 0) { savedIdeaReady(colors: colors) } |
| 277 | .navigationTitle("Today") |
| 278 | .toolbar { controls } |
| 279 | } else { |
| 280 | syncUnavailable(colors: colors) |
| 281 | } |
| 282 | } |
| 283 | .tint(colors.text) |
| 284 | .safeAreaInset(edge: .bottom, spacing: 0) { taskToast } |
| 285 | .tabItem { tabLabel("Today", systemImage: "sun.max", destination: .today, colors: colors) } |
| 286 | .tag(Page.today) |
| 287 | |
| 288 | NavigationStack { |
| 289 | if workspace.snapshot == nil { |
| 290 | syncUnavailable(colors: colors) |
| 291 | } else { |
| 292 | ProjectsView() |
| 293 | .navigationTitle("Projects") |
| 294 | .toolbar { controls } |
| 295 | } |
| 296 | } |
| 297 | .tint(colors.text) |
| 298 | .safeAreaInset(edge: .bottom, spacing: 0) { taskToast } |
| 299 | .tabItem { tabLabel("Projects", systemImage: "square.grid.2x2", destination: .projects, colors: colors) } |
| 300 | .tag(Page.projects) |
| 301 | |
| 302 | NavigationStack { |
| 303 | PhoneDoneView() |
| 304 | .navigationTitle("Done") |
| 305 | .toolbar { controls } |
| 306 | } |
| 307 | .tint(colors.text) |
| 308 | .safeAreaInset(edge: .bottom, spacing: 0) { taskToast } |
| 309 | .tabItem { tabLabel("Done", systemImage: "checkmark.circle", destination: .done, colors: colors) } |
| 310 | .tag(Page.done) |
| 311 | |
| 312 | NavigationStack { |
| 313 | QueueView() |
| 314 | .navigationTitle("Queue") |
| 315 | .toolbar { controls } |
| 316 | } |
| 317 | .tint(colors.text) |
| 318 | .safeAreaInset(edge: .bottom, spacing: 0) { taskToast } |
| 319 | .tabItem { tabLabel("Queue", systemImage: "paperplane", destination: .queue, colors: colors) } |
| 320 | .tag(Page.queue) |
| 321 | .badge(workspace.pending.count) |
| 322 | |
| 323 | NavigationStack { |
| 324 | SyncSettingsView() |
| 325 | .navigationTitle("Settings") |
| 326 | } |
| 327 | .tint(colors.text) |
| 328 | .safeAreaInset(edge: .bottom, spacing: 0) { taskToast } |
| 329 | .tabItem { tabLabel("Settings", systemImage: "gearshape", destination: .settings, colors: colors) } |
| 330 | .tag(Page.settings) |
| 331 | } |
| 332 | .sheet(isPresented: $showAddTask) { |
| 333 | CaptureView(initialIdea: captureSeed) { |
| 334 | if !captureSeed.isEmpty && starterIdea == captureSeed { saveStarterIdea("") } |
| 335 | }.tint(colors.text) |
| 336 | } |
| 337 | .sheet(isPresented: $showStarterIdea) { StarterIdeaView(idea: starterIdea, save: saveStarterIdea) } |
| 338 | .fullScreenCover(isPresented: $showIntroduction) { |
| 339 | PhoneIntroduction { |
| 340 | introductionCompleted = true |
| 341 | showIntroduction = false |
| 342 | } |
| 343 | } |
| 344 | .task { |
| 345 | guard !introductionCompleted else { return } |
| 346 | if workspace.hasSavedWorkspace { introductionCompleted = true } |
| 347 | else { showIntroduction = true } |
| 348 | } |
| 349 | .sheet(isPresented: $showAssistant) { |
| 350 | if let snapshot = workspace.snapshot { |
| 351 | PhoneAssistantView(workspaceID: snapshot.workspaceID) |
| 352 | } |
| 353 | } |
| 354 | .sheet(item: $openedTask) { task in |
| 355 | NavigationStack { |
| 356 | CapturedTaskDetail(task: task) |
| 357 | .toolbar { |
| 358 | PhoneActionToolbarItem(placement: .topBarTrailing) { |
| 359 | Button("Close") { openedTask = nil } |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | .tint(colors.text) |
| 364 | } |
| 365 | .animation(reduceMotion ? nil : .easeInOut(duration: 0.18), value: workspace.capturedTask?.dismissed) |
| 366 | .animation(reduceMotion ? nil : .easeInOut(duration: 0.18), value: workspace.capturedTask?.id) |
| 367 | .animation(reduceMotion ? nil : .easeInOut(duration: 0.18), value: showAddTask) |
| 368 | .environment(\.phoneColors, colors) |
| 369 | .tint(colors.actionAccent) |
| 370 | } |
| 371 | |
| 372 | @ViewBuilder |
| 373 | private var taskToast: some View { |
| 374 | if let task = workspace.capturedTask, !task.dismissed, !showAddTask { |
| 375 | PhoneCreatedTaskToast(task: task) { openedTask = task } |
| 376 | .id(task.id) |
| 377 | .padding(.horizontal, 16) |
| 378 | .padding(.vertical, 10) |
| 379 | .frame(maxWidth: .infinity, alignment: .trailing) |
| 380 | .transition(reduceMotion ? .opacity : .move(edge: .bottom).combined(with: .opacity)) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | private func tabLabel(_ title: LocalizedStringKey, systemImage: String, destination: Page, |
| 385 | colors: OpenTalonColors) -> some View { |
| 386 | let neutral: Color = (theme.colorScheme ?? systemScheme) == .dark ? .white : .black |
| 387 | let color = page == destination ? colors.actionAccent : neutral |
| 388 | return Label { |
| 389 | Text(title) |
| 390 | } icon: { |
| 391 | if let symbol = UIImage(systemName: systemImage) { |
| 392 | Image(uiImage: symbol.withTintColor(UIColor(color), renderingMode: .alwaysOriginal)) |
| 393 | } else { |
| 394 | Image(systemName: systemImage) |
| 395 | } |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | private func syncUnavailable(colors: OpenTalonColors) -> some View { |
| 400 | ScrollView { |
| 401 | VStack(alignment: .leading, spacing: 24) { |
| 402 | Image("WelcomeIcon").resizable().frame(width: 64, height: 64) |
| 403 | .clipShape(RoundedRectangle(cornerRadius: 15)).accessibilityHidden(true) |
| 404 | VStack(alignment: .leading, spacing: 10) { |
| 405 | Text("Your Mac starts the workspace").font(.largeTitle.bold()) |
| 406 | Text("Organize tasks and projects on your Mac, then take them with you on iPhone and iPad. Your Mac also runs the work you send to an agent.") |
| 407 | .foregroundStyle(colors.muted) |
| 408 | } |
| 409 | VStack(alignment: .leading, spacing: 16) { |
| 410 | Label("Connect your Mac", systemImage: "desktopcomputer").font(.headline) |
| 411 | Text("Install OpenTalon on your Mac, use the same Apple Account with iCloud Drive on both devices, and keep the Mac app open.") |
| 412 | .foregroundStyle(colors.muted) |
| 413 | Link("Get the Mac app", destination: URL(string: "https://opentalon.ai/download")!) |
| 414 | .buttonStyle(PhoneActionButtonStyle(emphasized: true)) |
| 415 | .accessibilityIdentifier("welcomeMacDownload") |
| 416 | Text("Requires an Apple silicon Mac with macOS 14 or later.") |
| 417 | .font(.footnote).foregroundStyle(colors.muted) |
| 418 | Button("Setup guide") { showIntroduction = true } |
| 419 | .buttonStyle(PhoneActionButtonStyle()).accessibilityIdentifier("welcomeSetupGuide") |
| 420 | if let error = workspace.syncError, !workspace.syncing { |
| 421 | Label("iCloud needs attention", systemImage: "exclamationmark.icloud").font(.subheadline.bold()) |
| 422 | Text(error).font(.callout).foregroundStyle(colors.muted) |
| 423 | } else { |
| 424 | Label(workspace.syncing ? "Checking iCloud for your Mac…" : "Waiting for your Mac’s first sync", systemImage: "icloud") |
| 425 | .font(.footnote).foregroundStyle(colors.muted) |
| 426 | } |
| 427 | Button("Check Sync Settings") { page = .settings } |
| 428 | .buttonStyle(PhoneActionButtonStyle()) |
| 429 | } |
| 430 | .padding(20).frame(maxWidth: .infinity, alignment: .leading) |
| 431 | .background(colors.card, in: RoundedRectangle(cornerRadius: 24)) |
| 432 | VStack(alignment: .leading, spacing: 14) { |
| 433 | Label(starterIdea.isEmpty ? "Start with an idea" : "Your saved idea", systemImage: "square.and.pencil").font(.headline) |
| 434 | Text(starterIdea.isEmpty ? "Get a task out of your head while you set up your Mac." : starterIdea) |
| 435 | .foregroundStyle(starterIdea.isEmpty ? colors.muted : colors.text).lineLimit(6) |
| 436 | if !starterIdea.isEmpty, starterIdeaAt > 0 { |
| 437 | PhoneDateCaption("Last updated", date: Date(timeIntervalSinceReferenceDate: starterIdeaAt)) |
| 438 | } |
| 439 | Button(starterIdea.isEmpty ? "Save an idea" : "Edit idea") { showStarterIdea = true } |
| 440 | .buttonStyle(PhoneActionButtonStyle()).accessibilityIdentifier("welcomeSaveIdea") |
| 441 | Text("Saved on this device. Once your Mac connects, you can turn it into a task.") |
| 442 | .font(.footnote).foregroundStyle(colors.muted) |
| 443 | } |
| 444 | .padding(20).frame(maxWidth: .infinity, alignment: .leading) |
| 445 | .background(colors.card, in: RoundedRectangle(cornerRadius: 24)) |
| 446 | } |
| 447 | .padding(24).frame(maxWidth: 620, alignment: .leading).frame(maxWidth: .infinity) |
| 448 | } |
| 449 | .foregroundStyle(colors.text) |
| 450 | .background(colors.canvas.ignoresSafeArea()) |
| 451 | .navigationTitle("Get started") |
| 452 | .accessibilityIdentifier("welcomeWaitingForMac") |
| 453 | } |
| 454 | |
| 455 | @ViewBuilder private func savedIdeaReady(colors: OpenTalonColors) -> some View { |
| 456 | if !starterIdea.isEmpty { |
| 457 | HStack(alignment: .top, spacing: 12) { |
| 458 | Image(systemName: "square.and.pencil").foregroundStyle(colors.actionAccent) |
| 459 | VStack(alignment: .leading, spacing: 5) { |
| 460 | Text("Your saved idea is ready").font(.subheadline.bold()) |
| 461 | Text(starterIdea).font(.caption).foregroundStyle(colors.muted).lineLimit(2) |
| 462 | if starterIdeaAt > 0 { |
| 463 | PhoneDateCaption("Last updated", date: Date(timeIntervalSinceReferenceDate: starterIdeaAt)) |
| 464 | } |
| 465 | Button("Create task") { captureSeed = starterIdea; showAddTask = true } |
| 466 | .buttonStyle(PhoneActionButtonStyle()).accessibilityIdentifier("createTaskFromStarterIdea") |
| 467 | } |
| 468 | Spacer(minLength: 0) |
| 469 | Button("Edit") { showStarterIdea = true }.buttonStyle(PhoneActionButtonStyle()) |
| 470 | } |
| 471 | .padding(16).frame(maxWidth: 620, alignment: .leading) |
| 472 | .background(colors.card, in: RoundedRectangle(cornerRadius: 20)) |
| 473 | .padding(.horizontal, 16).padding(.vertical, 8) |
| 474 | .frame(maxWidth: .infinity).background(colors.canvas) |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | private func saveStarterIdea(_ idea: String) { |
| 479 | guard idea != starterIdea else { return } |
| 480 | starterIdeaAt = idea.isEmpty ? 0 : Date.now.timeIntervalSinceReferenceDate |
| 481 | starterIdea = idea |
| 482 | } |
| 483 | |
| 484 | @ToolbarContentBuilder |
| 485 | private var controls: some ToolbarContent { |
| 486 | PhoneActionToolbarItem(placement: .primaryAction) { |
| 487 | Button { showAssistant = true } label: { |
| 488 | PhoneActionLabel(title: "Ask OpenTalon", systemImage: "sparkles") |
| 489 | .labelStyle(.titleAndIcon) |
| 490 | } |
| 491 | .buttonStyle(PhoneActionButtonStyle()) |
| 492 | .accessibilityLabel("Ask OpenTalon") |
| 493 | .accessibilityIdentifier("askOpenTalon") |
| 494 | .disabled(workspace.snapshot == nil) |
| 495 | } |
| 496 | PhoneActionToolbarItem(placement: .primaryAction) { |
| 497 | Button { |
| 498 | captureSeed = "" |
| 499 | showAddTask = true |
| 500 | } label: { |
| 501 | Image(systemName: "plus") |
| 502 | .font(.system(size: 19, weight: .semibold)) |
| 503 | .foregroundStyle(OpenTalonColors(theme: theme, systemScheme: systemScheme).actionAccent) |
| 504 | } |
| 505 | .buttonStyle(PhoneActionButtonStyle(circular: true)) |
| 506 | .accessibilityLabel("New task") |
| 507 | .disabled(workspace.snapshot?.projects.isEmpty != false) |
| 508 | } |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | private struct PhoneIntroduction: View { |
| 513 | @Environment(\.phoneColors) private var colors |
| 514 | @State private var step = 0 |
| 515 | let finish: () -> Void |
| 516 | |
| 517 | var body: some View { |
| 518 | VStack(spacing: 0) { |
| 519 | HStack { |
| 520 | Text("OpenTalon").font(.headline) |
| 521 | Spacer() |
| 522 | Button("Not now", action: finish).accessibilityIdentifier("introSkip") |
| 523 | }.padding(20) |
| 524 | ScrollView { |
| 525 | VStack(alignment: .leading, spacing: 24) { |
| 526 | Image("WelcomeIcon").resizable().frame(width: 88, height: 88) |
| 527 | .clipShape(RoundedRectangle(cornerRadius: 21)).accessibilityHidden(true) |
| 528 | VStack(alignment: .leading, spacing: 12) { |
| 529 | Text(step == 0 ? "Your tasks. Your agents." : "Start with your Mac.") |
| 530 | .font(.largeTitle.bold()).accessibilityIdentifier("introHeading") |
| 531 | Text(step == 0 |
| 532 | ? "Plan your work on Mac. Manage tasks and follow your agents from iPhone and iPad." |
| 533 | : "Your Mac is the hub. This app connects to its workspace through your private iCloud account.") |
| 534 | .font(.title3).foregroundStyle(colors.muted) |
| 535 | } |
| 536 | if step == 0 { |
| 537 | Label("You’ll need OpenTalon on a Mac for synced boards and agent work.", systemImage: "desktopcomputer") |
| 538 | .font(.callout).foregroundStyle(colors.muted) |
| 539 | VStack(alignment: .leading, spacing: 22) { |
| 540 | feature("Organize your work", detail: "Keep tasks in project boards and move them from To do to Done.", symbol: "square.grid.2x2") |
| 541 | feature("Keep the plan close", detail: "Save a Markdown plan with a task, then preview or edit it.", symbol: "doc.text") |
| 542 | feature("Send work to an agent", detail: "Choose Claude, Codex, or Gemini on your Mac and follow the task’s progress from your phone.", symbol: "paperplane") |
| 543 | } |
| 544 | .padding(22).background(colors.card, in: RoundedRectangle(cornerRadius: 24)) |
| 545 | } else { |
| 546 | VStack(alignment: .leading, spacing: 24) { |
| 547 | setupStep("1", title: "Install OpenTalon for Mac", detail: "Get the free app on an Apple silicon Mac with macOS 14 or later, then open it.") |
| 548 | Link("Get the Mac app", destination: URL(string: "https://opentalon.ai/download")!) |
| 549 | .buttonStyle(PhoneActionButtonStyle(emphasized: true)).accessibilityIdentifier("introMacDownload") |
| 550 | setupStep("2", title: "Use the same Apple Account", detail: "Enable iCloud Drive on your Mac and this device, using the same Apple Account.") |
| 551 | setupStep("3", title: "Keep your Mac running", detail: "Keep OpenTalon open and your Mac awake for sync and agent work. On Mac, check Settings → iCloud sync.") |
| 552 | } |
| 553 | .padding(22).background(colors.card, in: RoundedRectangle(cornerRadius: 24)) |
| 554 | VStack(alignment: .leading, spacing: 8) { |
| 555 | Text("Not at your Mac yet?").font(.headline) |
| 556 | Text("Save an idea on this device now. When your Mac connects, turn it into a task.") |
| 557 | .foregroundStyle(colors.muted) |
| 558 | Text("Agents are optional. Connect Claude, Codex, or Gemini in the Mac app’s Settings when you’re ready.") |
| 559 | .font(.footnote).foregroundStyle(colors.muted) |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 | .padding(24).frame(maxWidth: 620, alignment: .leading).frame(maxWidth: .infinity) |
| 564 | } |
| 565 | HStack(spacing: 16) { |
| 566 | if step == 1 { Button("Back") { step = 0 }.accessibilityIdentifier("introBack") } |
| 567 | Text(step == 0 ? "1 of 2" : "2 of 2").font(.caption).foregroundStyle(colors.muted) |
| 568 | Spacer() |
| 569 | Button(step == 0 ? "Continue" : "Get started") { |
| 570 | if step == 0 { step = 1 } else { finish() } |
| 571 | } |
| 572 | .buttonStyle(PhoneActionButtonStyle(emphasized: true)) |
| 573 | .accessibilityIdentifier(step == 0 ? "introContinue" : "introFinish") |
| 574 | }.padding(20) |
| 575 | } |
| 576 | .buttonStyle(PhoneActionButtonStyle()) |
| 577 | .foregroundStyle(colors.text).tint(colors.actionAccent) |
| 578 | .background(colors.canvas.ignoresSafeArea()) |
| 579 | .interactiveDismissDisabled() |
| 580 | } |
| 581 | |
| 582 | private func feature(_ title: String, detail: String, symbol: String) -> some View { |
| 583 | HStack(alignment: .top, spacing: 14) { |
| 584 | Image(systemName: symbol).font(.title3).foregroundStyle(colors.actionAccent).frame(width: 24) |
| 585 | VStack(alignment: .leading, spacing: 5) { |
| 586 | Text(title).font(.headline) |
| 587 | Text(detail).foregroundStyle(colors.muted) |
| 588 | } |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | private func setupStep(_ number: String, title: String, detail: String) -> some View { |
| 593 | HStack(alignment: .top, spacing: 14) { |
| 594 | Text(number).font(.headline).foregroundStyle(colors.actionAccent) |
| 595 | .frame(width: 30, height: 30).background(colors.actionAccent.opacity(0.10), in: Circle()) |
| 596 | VStack(alignment: .leading, spacing: 6) { |
| 597 | Text(title).font(.headline) |
| 598 | Text(detail).foregroundStyle(colors.muted) |
| 599 | } |
| 600 | } |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | private struct StarterIdeaView: View { |
| 605 | @Environment(\.phoneColors) private var colors |
| 606 | @Environment(\.dismiss) private var dismiss |
| 607 | let savedIdea: String |
| 608 | let save: (String) -> Void |
| 609 | @State private var text: String |
| 610 | @State private var confirmDiscard = false |
| 611 | @FocusState private var focused: Bool |
| 612 | |
| 613 | init(idea: String, save: @escaping (String) -> Void) { |
| 614 | savedIdea = idea |
| 615 | self.save = save |
| 616 | _text = State(initialValue: idea) |
| 617 | } |
| 618 | |
| 619 | private var trimmed: String { text.trimmingCharacters(in: .whitespacesAndNewlines) } |
| 620 | private var tooLong: Bool { trimmed.utf16.count > SuggestedTaskDetails.captureLimit } |
| 621 | |
| 622 | var body: some View { |
| 623 | VStack(spacing: 0) { |
| 624 | HStack { |
| 625 | Text("Save an idea").font(.headline) |
| 626 | Spacer() |
| 627 | Button("Cancel") { dismiss() }.accessibilityIdentifier("starterIdeaCancel") |
| 628 | } |
| 629 | .padding(20).contentShape(Rectangle()).onTapGesture { focused = false } |
| 630 | ScrollView { |
| 631 | VStack(alignment: .leading, spacing: 20) { |
| 632 | Text("Write or dictate a task to come back to. It stays on this device until you choose to create a task in your Mac workspace.") |
| 633 | .foregroundStyle(colors.muted) |
| 634 | TextEditor(text: $text).focused($focused).scrollContentBackground(.hidden) |
| 635 | .padding(12).frame(height: 280) |
| 636 | .background(colors.card, in: RoundedRectangle(cornerRadius: 20)) |
| 637 | .accessibilityLabel("Your idea").accessibilityIdentifier("starterIdeaEditor") |
| 638 | if tooLong { Text("Keep your idea to 2,000 characters.").font(.footnote).foregroundStyle(colors.danger) } |
| 639 | HStack { |
| 640 | Spacer() |
| 641 | Button("Save idea") { save(trimmed); dismiss() } |
| 642 | .disabled(trimmed.isEmpty || tooLong).accessibilityIdentifier("starterIdeaSave") |
| 643 | } |
| 644 | if !savedIdea.isEmpty { |
| 645 | Button("Discard saved idea", role: .destructive) { confirmDiscard = true } |
| 646 | .accessibilityIdentifier("starterIdeaDiscard") |
| 647 | } |
| 648 | }.padding(20) |
| 649 | } |
| 650 | .scrollDismissesKeyboard(.interactively) |
| 651 | } |
| 652 | .buttonStyle(PhoneActionButtonStyle()).foregroundStyle(colors.text) |
| 653 | .background(colors.canvas.ignoresSafeArea()).tint(colors.actionAccent) |
| 654 | .phoneConfirmation("Discard this saved idea?", isPresented: $confirmDiscard, |
| 655 | message: "This removes the idea saved on this device.", confirm: "Discard idea", role: .destructive) { |
| 656 | save(""); dismiss() |
| 657 | } |
| 658 | .onAppear { focused = true } |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | private struct PhoneCreatedTaskToast: View { |
| 663 | @Environment(PhoneWorkspace.self) private var workspace |
| 664 | @Environment(\.phoneColors) private var colors |
| 665 | @GestureState private var drag = CGSize.zero |
| 666 | let task: PhoneWorkspace.CapturedTask |
| 667 | let open: () -> Void |
| 668 | |
| 669 | private var status: (title: String, symbol: String, color: Color) { |
| 670 | switch task.result { |
| 671 | case .queued: ("Task queued", "clock", colors.actionAccent) |
| 672 | case .saved: ("Task created", "checkmark.circle.fill", colors.actionAccent) |
| 673 | case .rejected: ("Task couldn’t sync", "exclamationmark.circle", colors.danger) |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | var body: some View { |
| 678 | HStack(spacing: 8) { |
| 679 | Image(systemName: status.symbol).foregroundStyle(status.color).accessibilityHidden(true) |
| 680 | VStack(alignment: .leading, spacing: 3) { |
| 681 | Text(status.title).font(.subheadline.weight(.semibold)) |
| 682 | Text(task.title).font(.caption).foregroundStyle(colors.muted).lineLimit(2) |
| 683 | } |
| 684 | .frame(maxWidth: .infinity, alignment: .leading) |
| 685 | Button("Open task", action: open) |
| 686 | .fixedSize(horizontal: true, vertical: false) |
| 687 | .buttonStyle(PhoneActionButtonStyle(horizontalPadding: 18)) |
| 688 | .accessibilityIdentifier("openCapturedTask") |
| 689 | Button { |
| 690 | workspace.dismissCapturedTask(task.id) |
| 691 | } label: { |
| 692 | Image(systemName: "xmark").font(.caption.weight(.semibold)) |
| 693 | } |
| 694 | .buttonStyle(PhoneActionButtonStyle(circular: true)) |
| 695 | .accessibilityLabel("Dismiss task notification") |
| 696 | } |
| 697 | .foregroundStyle(colors.text) |
| 698 | .padding(10) |
| 699 | .frame(maxWidth: 420) |
| 700 | .background(colors.card, in: .rect(cornerRadius: 17)) |
| 701 | .overlay { |
| 702 | RoundedRectangle(cornerRadius: 17).strokeBorder(colors.line).allowsHitTesting(false) |
| 703 | } |
| 704 | .shadow(color: .black.opacity(0.14), radius: 12, y: 4) |
| 705 | .offset(x: drag.width, y: drag.height) |
| 706 | .simultaneousGesture(DragGesture(minimumDistance: 12) |
| 707 | .updating($drag) { value, drag, _ in drag = value.translation } |
| 708 | .onEnded { value in |
| 709 | if abs(value.translation.width) > 64 || abs(value.translation.height) > 42 { |
| 710 | workspace.dismissCapturedTask(task.id) |
| 711 | } |
| 712 | }) |
| 713 | .accessibilityElement(children: .contain) |
| 714 | .accessibilityIdentifier("taskCreatedToast") |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | private struct CapturedTaskDetail: View { |
| 719 | @Environment(PhoneWorkspace.self) private var workspace |
| 720 | @Environment(\.phoneColors) private var colors |
| 721 | let task: PhoneWorkspace.CapturedTask |
| 722 | |
| 723 | var body: some View { |
| 724 | let current = workspace.capturedTask.flatMap { $0.id == task.id ? $0 : nil } ?? task |
| 725 | if case .saved(let id?) = current.result { |
| 726 | TaskView(taskID: id) |
| 727 | } else { |
| 728 | List { |
| 729 | Section { |
| 730 | Text(current.title).font(.title2.weight(.semibold)) |
| 731 | if let date = current.createdAt { PhoneDateCaption("Captured", date: date) } |
| 732 | LabeledContent("Project", value: current.project) |
| 733 | LabeledContent("Priority", value: current.priority.title) |
| 734 | LabeledContent("Issue type", value: (current.issueType ?? .issue).rawValue) |
| 735 | } |
| 736 | .listRowBackground(colors.card) |
| 737 | if !current.notes.isEmpty { |
| 738 | Section("Notes") { Text(current.notes).textSelection(.enabled) } |
| 739 | .listRowBackground(colors.card) |
| 740 | } |
| 741 | if let definition = current.definitionOfDone, !definition.isEmpty { |
| 742 | Section("Definition of done") { Text(definition).textSelection(.enabled) } |
| 743 | .listRowBackground(colors.card) |
| 744 | } |
| 745 | if let plan = current.planMarkdown, !plan.isEmpty { |
| 746 | Section("Plan") { MarkdownPlanPreview(plan) } |
| 747 | .listRowBackground(colors.card) |
| 748 | } |
| 749 | Section { |
| 750 | switch current.result { |
| 751 | case .queued: |
| 752 | Label("Waiting to sync with your Mac", systemImage: "clock") |
| 753 | .foregroundStyle(colors.muted) |
| 754 | case .saved: |
| 755 | Label("Synced. Find the task in Recent Tasks.", systemImage: "checkmark.circle") |
| 756 | .foregroundStyle(colors.muted) |
| 757 | case .rejected(let message): |
| 758 | Label(message, systemImage: "exclamationmark.circle") |
| 759 | .foregroundStyle(colors.danger) |
| 760 | } |
| 761 | } |
| 762 | .listRowBackground(colors.card) |
| 763 | } |
| 764 | .modifier(PhoneListAppearance()) |
| 765 | .navigationTitle("Task") |
| 766 | .navigationBarTitleDisplayMode(.inline) |
| 767 | } |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | private struct SyncSettingsView: View { |
| 772 | @Environment(PhoneWorkspace.self) private var workspace |
| 773 | @Environment(\.phoneColors) private var colors |
| 774 | @Environment(\.dynamicTypeSize) private var dynamicTypeSize |
| 775 | @Environment(\.colorScheme) private var colorScheme |
| 776 | @AppStorage("appearanceTheme") private var theme = OpenTalonTheme.system |
| 777 | @State private var showIntroduction = false |
| 778 | @AppStorage(PhoneWorkspace.pickupAlertsKey) private var pickupAlerts = false |
| 779 | @State private var notificationDenied = false |
| 780 | |
| 781 | private var settingsBackground: Color { |
| 782 | if theme == .light || (theme == .system && colorScheme == .light) { |
| 783 | return Color(red: 237.0 / 255, green: 240.0 / 255, blue: 243.0 / 255) |
| 784 | } |
| 785 | return colors.canvas |
| 786 | } |
| 787 | |
| 788 | var body: some View { |
| 789 | GeometryReader { geometry in |
| 790 | if geometry.size.width >= 640 && !dynamicTypeSize.isAccessibilitySize { |
| 791 | HStack(spacing: 20) { |
| 792 | Form { |
| 793 | syncSection |
| 794 | diagnosticsSection |
| 795 | trashSection |
| 796 | } |
| 797 | Form { |
| 798 | appearanceSection |
| 799 | helpSection |
| 800 | aboutSection |
| 801 | } |
| 802 | } |
| 803 | } else { |
| 804 | Form { |
| 805 | appearanceSection |
| 806 | syncSection |
| 807 | diagnosticsSection |
| 808 | trashSection |
| 809 | helpSection |
| 810 | aboutSection |
| 811 | } |
| 812 | } |
| 813 | } |
| 814 | .modifier(PhoneListAppearance(background: settingsBackground)) |
| 815 | } |
| 816 | |
| 817 | private var trashSection: some View { |
| 818 | Section { |
| 819 | NavigationLink { |
| 820 | PhoneTrashView() |
| 821 | } label: { |
| 822 | PhoneActionLabel(title: "Trash", systemImage: "trash") |
| 823 | } |
| 824 | } |
| 825 | .listRowBackground(colors.card) |
| 826 | } |
| 827 | |
| 828 | private var appearanceSection: some View { |
| 829 | Section("Appearance") { |
| 830 | ForEach([OpenTalonTheme.paper, .graphite, .light, .system]) { choice in |
| 831 | themeRow(choice) |
| 832 | } |
| 833 | } |
| 834 | .listRowBackground(colors.card) |
| 835 | } |
| 836 | |
| 837 | private func themeRow(_ choice: OpenTalonTheme) -> some View { |
| 838 | Button { |
| 839 | theme = choice |
| 840 | } label: { |
| 841 | HStack(spacing: 13) { |
| 842 | themePreview(choice) |
| 843 | .accessibilityHidden(true) |
| 844 | Text(choice.title) |
| 845 | .font(.body.weight(.medium)) |
| 846 | .foregroundStyle(colors.text) |
| 847 | Spacer(minLength: 8) |
| 848 | if theme == choice { |
| 849 | Image(systemName: "checkmark.circle.fill") |
| 850 | .foregroundStyle(colors.actionAccent) |
| 851 | .accessibilityHidden(true) |
| 852 | } |
| 853 | } |
| 854 | .frame(minHeight: 44) |
| 855 | .contentShape(Rectangle()) |
| 856 | } |
| 857 | .buttonStyle(.plain) |
| 858 | .accessibilityAddTraits(theme == choice ? .isSelected : []) |
| 859 | .accessibilityIdentifier("theme.\(choice.rawValue)") |
| 860 | } |
| 861 | |
| 862 | @ViewBuilder |
| 863 | private func themePreview(_ choice: OpenTalonTheme) -> some View { |
| 864 | if choice == .system { |
| 865 | Image(systemName: "circle.lefthalf.filled") |
| 866 | .foregroundStyle(colors.text) |
| 867 | .frame(width: 58, height: 35) |
| 868 | .background(colors.line.opacity(0.45), in: .rect(cornerRadius: 6)) |
| 869 | .overlay { RoundedRectangle(cornerRadius: 6).strokeBorder(colors.line) } |
| 870 | } else { |
| 871 | let swatch = OpenTalonColors(theme: choice) |
| 872 | VStack(alignment: .leading, spacing: 4) { |
| 873 | Capsule().fill(swatch.accent).frame(width: 19, height: 3) |
| 874 | RoundedRectangle(cornerRadius: 3) |
| 875 | .fill(swatch.card) |
| 876 | .overlay { RoundedRectangle(cornerRadius: 3).strokeBorder(swatch.line) } |
| 877 | } |
| 878 | .padding(6) |
| 879 | .frame(width: 58, height: 35) |
| 880 | .background(swatch.canvas, in: .rect(cornerRadius: 6)) |
| 881 | .overlay { RoundedRectangle(cornerRadius: 6).strokeBorder(swatch.line) } |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | private var syncSection: some View { |
| 886 | Section("iCloud Sync") { |
| 887 | LabeledContent("Apple Account", value: workspace.accountStatus) |
| 888 | LabeledContent("Mac workspace", value: workspaceStatus) |
| 889 | LabeledContent("Last check", value: timestamp(workspace.lastCheck)) |
| 890 | LabeledContent("Last iCloud response", value: timestamp(workspace.lastCloudContact)) |
| 891 | if let snapshot = workspace.snapshot { |
| 892 | LabeledContent("Mac snapshot", value: timestamp(snapshot.updatedAt)) |
| 893 | } |
| 894 | if let error = workspace.syncError { |
| 895 | Text(error).foregroundStyle(.secondary) |
| 896 | } else if workspace.remoteWorkspaceFound == false { |
| 897 | Text("iCloud has no workspace from your Mac yet. Open the Mac app and check Settings → iCloud sync.") |
| 898 | .foregroundStyle(.secondary) |
| 899 | } |
| 900 | Button { |
| 901 | Task { await workspace.sync() } |
| 902 | } label: { |
| 903 | if workspace.syncing { |
| 904 | ProgressView { |
| 905 | Text("Checking iCloud…").foregroundStyle(Color.primary) |
| 906 | } |
| 907 | } else { |
| 908 | settingsActionLabel("Check Now", systemImage: "arrow.clockwise") |
| 909 | } |
| 910 | } |
| 911 | .disabled(workspace.syncing) |
| 912 | Toggle("Agent pickup notifications", isOn: Binding(get: { pickupAlerts }, set: { enabled in |
| 913 | guard enabled else { |
| 914 | pickupAlerts = false |
| 915 | notificationDenied = false |
| 916 | return |
| 917 | } |
| 918 | Task { |
| 919 | pickupAlerts = (try? await UNUserNotificationCenter.current() |
| 920 | .requestAuthorization(options: [.alert])) == true |
| 921 | notificationDenied = !pickupAlerts |
| 922 | } |
| 923 | })) |
| 924 | .tint(colors.actionAccent) |
| 925 | .disabled(workspace.snapshot?.canUseAgents != true) |
| 926 | if notificationDenied { |
| 927 | Text("Allow notifications for OpenTalon in iOS Settings.") |
| 928 | .font(.footnote).foregroundStyle(colors.muted) |
| 929 | } |
| 930 | } |
| 931 | .listRowBackground(colors.card) |
| 932 | } |
| 933 | |
| 934 | private var diagnosticsSection: some View { |
| 935 | Section("Diagnostics") { |
| 936 | if let code = workspace.syncErrorCode { |
| 937 | LabeledContent("Error code", value: code) |
| 938 | .textSelection(.enabled) |
| 939 | } |
| 940 | ShareLink(item: diagnostics) { |
| 941 | settingsActionLabel("Share Sync Diagnostics", systemImage: "square.and.arrow.up") |
| 942 | } |
| 943 | } |
| 944 | .listRowBackground(colors.card) |
| 945 | } |
| 946 | |
| 947 | private var helpSection: some View { |
| 948 | Section("Help") { |
| 949 | Button { showIntroduction = true } label: { |
| 950 | settingsActionLabel("Getting started", systemImage: "hand.wave") |
| 951 | } |
| 952 | .accessibilityIdentifier("settingsGettingStarted") |
| 953 | .fullScreenCover(isPresented: $showIntroduction) { PhoneIntroduction { showIntroduction = false } } |
| 954 | Link(destination: OpenTalonCommunity.websiteHelp) { |
| 955 | settingsActionLabel("Setup and Troubleshooting", systemImage: "book") |
| 956 | } |
| 957 | } |
| 958 | .listRowBackground(colors.card) |
| 959 | } |
| 960 | |
| 961 | private func settingsActionLabel(_ title: LocalizedStringKey, systemImage: String) -> some View { |
| 962 | PhoneActionLabel(title: title, systemImage: systemImage) |
| 963 | } |
| 964 | |
| 965 | private var aboutSection: some View { |
| 966 | Section { |
| 967 | HStack(alignment: .center, spacing: 14) { |
| 968 | Image("OpenTalonBrand") |
| 969 | .resizable() |
| 970 | .scaledToFit() |
| 971 | .frame(width: 52, height: 52) |
| 972 | .clipShape(.rect(cornerRadius: 12)) |
| 973 | .shadow(color: colorScheme == .dark ? .white.opacity(0.14) : .black.opacity(0.12), |
| 974 | radius: 6, y: 2) |
| 975 | .accessibilityHidden(true) |
| 976 | VStack(alignment: .leading, spacing: 4) { |
| 977 | Text("OpenTalon").font(.headline).foregroundStyle(colors.text) |
| 978 | Text("A little room for the things you’re working on.") |
| 979 | .font(.subheadline).foregroundStyle(colors.muted) |
| 980 | } |
| 981 | } |
| 982 | .padding(.vertical, 6) |
| 983 | Text("Version \(appVersion) (\(appBuild))") |
| 984 | .foregroundStyle(colors.muted) |
| 985 | .accessibilityIdentifier("settingsAppVersion") |
| 986 | } header: { |
| 987 | Text("About").foregroundStyle(colors.muted) |
| 988 | } |
| 989 | .listRowBackground(colors.card) |
| 990 | } |
| 991 | |
| 992 | private var appVersion: String { |
| 993 | Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "—" |
| 994 | } |
| 995 | |
| 996 | private var appBuild: String { |
| 997 | Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "—" |
| 998 | } |
| 999 | |
| 1000 | private var workspaceStatus: String { |
| 1001 | switch workspace.remoteWorkspaceFound { |
| 1002 | case true?: "Found" |
| 1003 | case false?: workspace.snapshot == nil ? "Waiting for Mac" : "Showing saved copy" |
| 1004 | case nil: "Not checked" |
| 1005 | } |
| 1006 | } |
| 1007 | |
| 1008 | private var diagnostics: String { |
| 1009 | var lines = [ |
| 1010 | "OpenTalon \(appVersion) (\(appBuild))", |
| 1011 | "Apple Account: \(workspace.accountStatus)", |
| 1012 | "Mac workspace: \(workspaceStatus)", |
| 1013 | "Last check: \(timestamp(workspace.lastCheck))", |
| 1014 | "Last iCloud response: \(timestamp(workspace.lastCloudContact))", |
| 1015 | "Mac snapshot: \(timestamp(workspace.snapshot?.updatedAt))", |
| 1016 | "Queued changes: \(workspace.pending.count)" |
| 1017 | ] |
| 1018 | if let code = workspace.syncErrorCode { lines.append("Error code: \(code)") } |
| 1019 | return lines.joined(separator: "\n") |
| 1020 | } |
| 1021 | |
| 1022 | private func timestamp(_ date: Date?) -> String { |
| 1023 | date?.formatted(date: .abbreviated, time: .standard) ?? "—" |
| 1024 | } |
| 1025 | } |
| 1026 | |
| 1027 | private struct PhoneDoneView: View { |
| 1028 | @Environment(PhoneWorkspace.self) private var workspace |
| 1029 | @Environment(\.phoneColors) private var colors |
| 1030 | @State private var search = "" |
| 1031 | @AppStorage("done.workspaceOrder") private var order = DoneOrder.recent |
| 1032 | |
| 1033 | var body: some View { |
| 1034 | let query = search.trimmingCharacters(in: .whitespacesAndNewlines) |
| 1035 | let tasks = workspace.completedTasks(order: order).filter { item in |
| 1036 | guard !query.isEmpty else { return true } |
| 1037 | let task = item.task |
| 1038 | let reference = workspace.hasPendingProjectMove(for: task) ? "" : task.displayTaskID ?? "" |
| 1039 | return [workspace.displayedText(for: task, field: .title), reference, |
| 1040 | workspace.projectName(workspace.displayedProject(for: task)), |
| 1041 | workspace.displayedText(for: task, field: .notes)] |
| 1042 | .contains { $0.localizedStandardContains(query) } |
| 1043 | } |
| 1044 | |
| 1045 | List { |
| 1046 | if let message = workspace.syncError { |
| 1047 | syncIssue("Couldn’t sync with your Mac", message: message) |
| 1048 | } else if workspace.remoteWorkspaceFound == false { |
| 1049 | syncIssue("Waiting for your Mac", message: "Open OpenTalon on your Mac to sync completed tasks.") |
| 1050 | } |
| 1051 | |
| 1052 | if workspace.snapshot != nil { |
| 1053 | if tasks.isEmpty { |
| 1054 | if query.isEmpty { |
| 1055 | ContentUnavailableView("No completed tasks", systemImage: "checkmark.circle", |
| 1056 | description: Text("Completed tasks from all projects appear here.")) |
| 1057 | } else { |
| 1058 | ContentUnavailableView.search(text: query) |
| 1059 | } |
| 1060 | } else { |
| 1061 | ForEach(tasks) { item in |
| 1062 | NavigationLink(value: item.id) { |
| 1063 | TaskCardLabel(task: item.task, showProject: true, showStatus: false) |
| 1064 | } |
| 1065 | .accessibilityIdentifier("doneTask-\(item.id)") |
| 1066 | .listRowBackground(colors.card) |
| 1067 | } |
| 1068 | } |
| 1069 | } else if workspace.syncError == nil, workspace.remoteWorkspaceFound != false { |
| 1070 | ProgressView("Checking for completed tasks…") |
| 1071 | .listRowBackground(colors.card) |
| 1072 | } |
| 1073 | } |
| 1074 | .modifier(PhoneListAppearance()) |
| 1075 | .toolbar { |
| 1076 | PhoneActionToolbarItem(placement: .topBarTrailing) { |
| 1077 | PhoneDoneSortMenu(order: $order) |
| 1078 | } |
| 1079 | } |
| 1080 | .searchable(text: $search, prompt: "Search completed tasks") |
| 1081 | .refreshable { await workspace.sync() } |
| 1082 | .navigationDestination(for: String.self) { taskID in |
| 1083 | TaskView(taskID: taskID) |
| 1084 | } |
| 1085 | } |
| 1086 | |
| 1087 | private func syncIssue(_ title: LocalizedStringKey, message: String) -> some View { |
| 1088 | VStack(alignment: .leading, spacing: 8) { |
| 1089 | Label(title, systemImage: "icloud.slash").font(.subheadline.weight(.semibold)) |
| 1090 | Text(message).font(.footnote).foregroundStyle(colors.muted) |
| 1091 | Button("Retry Sync") { Task { await workspace.sync() } } |
| 1092 | .buttonStyle(PhoneActionButtonStyle()) |
| 1093 | .disabled(workspace.syncing) |
| 1094 | } |
| 1095 | .listRowBackground(colors.card) |
| 1096 | } |
| 1097 | } |
| 1098 | |
| 1099 | private struct PhoneSortIcon: View { |
| 1100 | var body: some View { |
| 1101 | Image(systemName: "arrow.up.arrow.down").frame(minWidth: 32, minHeight: 32) |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | private struct PhoneDoneSortMenu: View { |
| 1106 | @Binding var order: DoneOrder |
| 1107 | |
| 1108 | var body: some View { |
| 1109 | Menu { |
| 1110 | Picker("Sort completed tasks", selection: $order) { |
| 1111 | ForEach([DoneOrder.recent, .oldest]) { option in |
| 1112 | Text(option.title).tag(option) |
| 1113 | } |
| 1114 | } |
| 1115 | } label: { PhoneSortIcon() } |
| 1116 | .accessibilityLabel("Sort completed tasks") |
| 1117 | .accessibilityValue(order.title) |
| 1118 | .accessibilityIdentifier("doneSort") |
| 1119 | } |
| 1120 | } |
| 1121 | |
| 1122 | private struct PhoneTrashView: View { |
| 1123 | private struct EmptyPreview { |
| 1124 | let workspaceID: UUID |
| 1125 | let revision: Int |
| 1126 | let count: Int |
| 1127 | } |
| 1128 | |
| 1129 | @Environment(PhoneWorkspace.self) private var workspace |
| 1130 | @Environment(\.phoneColors) private var colors |
| 1131 | @State private var emptyPreview: EmptyPreview? |
| 1132 | @State private var showConfirmation = false |
| 1133 | @State private var error: String? |
| 1134 | |
| 1135 | private var emptyQueued: Bool { |
| 1136 | workspace.pending.contains { |
| 1137 | guard $0.workspaceID == workspace.snapshot?.workspaceID else { return false } |
| 1138 | if case .emptyTrash = $0.action { return true } |
| 1139 | return false |
| 1140 | } |
| 1141 | } |
| 1142 | |
| 1143 | var body: some View { |
| 1144 | let tasks = workspace.displayedTrash |
| 1145 | let archiveRemovals = workspace.pendingArchiveRemovals |
| 1146 | List { |
| 1147 | if let tasks { |
| 1148 | if tasks.isEmpty { |
| 1149 | ContentUnavailableView("Trash is empty", systemImage: "trash") |
| 1150 | } else { |
| 1151 | Section { |
| 1152 | Button(role: .destructive) { |
| 1153 | guard let snapshot = workspace.snapshot else { return } |
| 1154 | emptyPreview = EmptyPreview(workspaceID: snapshot.workspaceID, |
| 1155 | revision: snapshot.revision, count: tasks.count) |
| 1156 | showConfirmation = true |
| 1157 | } label: { |
| 1158 | Label("Empty Trash", systemImage: "trash") |
| 1159 | } |
| 1160 | .disabled(emptyQueued || tasks.contains { |
| 1161 | workspace.pendingTaskChange(for: $0.id) != nil || archiveRemovals[$0.id] != nil |
| 1162 | }) |
| 1163 | if emptyQueued { |
| 1164 | Label("Queued for Mac", systemImage: "clock").foregroundStyle(colors.muted) |
| 1165 | } |
| 1166 | } |
| 1167 | .listRowBackground(colors.card) |
| 1168 | Section { |
| 1169 | ForEach(tasks) { task in |
| 1170 | HStack { |
| 1171 | VStack(alignment: .leading, spacing: 4) { |
| 1172 | Text(task.title).font(.body.weight(.medium)) |
| 1173 | Text(workspace.projectName(task.projectID)) |
| 1174 | .font(.caption).foregroundStyle(colors.muted) |
| 1175 | if let deletedAt = task.deletedAt { |
| 1176 | PhoneDateCaption("Moved to Trash", date: deletedAt) |
| 1177 | } |
| 1178 | if let updatedAt = task.updatedAt, task.deletedAt != updatedAt { |
| 1179 | PhoneDateCaption("Last updated", date: updatedAt) |
| 1180 | } |
| 1181 | } |
| 1182 | Spacer() |
| 1183 | Button("Restore") { queue(.restoreTrashed(taskID: task.id, revision: task.revision)) } |
| 1184 | .buttonStyle(PhoneActionButtonStyle()) |
| 1185 | .disabled(emptyQueued || workspace.pendingTaskChange(for: task.id) != nil || |
| 1186 | archiveRemovals[task.id] != nil) |
| 1187 | } |
| 1188 | } |
| 1189 | } |
| 1190 | .listRowBackground(colors.card) |
| 1191 | } |
| 1192 | } else { |
| 1193 | ContentUnavailableView("Trash needs an update", systemImage: "trash", |
| 1194 | description: Text("Update OpenTalon on your Mac and sync to see Trash.")) |
| 1195 | } |
| 1196 | if let error { |
| 1197 | Text(error).font(.footnote).foregroundStyle(colors.danger) |
| 1198 | } |
| 1199 | } |
| 1200 | .modifier(PhoneListAppearance()) |
| 1201 | .navigationTitle("Trash") |
| 1202 | .refreshable { await workspace.sync() } |
| 1203 | .phoneConfirmation("Empty Trash?", isPresented: $showConfirmation, |
| 1204 | message: emptyTrashMessage, confirm: "Empty Trash", role: .destructive) { |
| 1205 | guard let preview = emptyPreview, preview.workspaceID == workspace.snapshot?.workspaceID else { return } |
| 1206 | queue(.emptyTrash(revision: preview.revision)) |
| 1207 | } |
| 1208 | } |
| 1209 | |
| 1210 | private var emptyTrashMessage: String { |
| 1211 | let count = emptyPreview?.count ?? 0 |
| 1212 | let tasks = count == 1 ? "one task" : "\(count) tasks" |
| 1213 | return "This permanently deletes \(tasks). This can’t be undone." |
| 1214 | } |
| 1215 | |
| 1216 | private func queue(_ action: PhoneRequest.Action) { |
| 1217 | do { |
| 1218 | try workspace.queue(action) |
| 1219 | error = nil |
| 1220 | } catch { |
| 1221 | self.error = error.localizedDescription |
| 1222 | } |
| 1223 | } |
| 1224 | } |
| 1225 | |
| 1226 | private struct PhoneArchiveView: View { |
| 1227 | private struct BulkPreview { |
| 1228 | let workspaceID: UUID |
| 1229 | let revision: Int |
| 1230 | let ids: [String] |
| 1231 | let permanently: Bool |
| 1232 | } |
| 1233 | |
| 1234 | @Environment(PhoneWorkspace.self) private var workspace |
| 1235 | @Environment(\.phoneColors) private var colors |
| 1236 | @State private var preview: BulkPreview? |
| 1237 | @State private var showConfirmation = false |
| 1238 | @State private var error: String? |
| 1239 | var projectID: String? = nil |
| 1240 | |
| 1241 | var body: some View { |
| 1242 | let snapshot = workspace.snapshot |
| 1243 | let permanently = preview?.permanently == true |
| 1244 | let removals = workspace.pendingArchiveRemovals |
| 1245 | let archived = workspace.visibleTasks.filter { |
| 1246 | workspace.isArchived($0) && (projectID == nil || workspace.displayedProject(for: $0) == projectID) |
| 1247 | } |
| 1248 | let tasks = archived.filter { removals[$0.id] == nil } |
| 1249 | .sorted { ($0.archivedAt ?? .distantPast) > ($1.archivedAt ?? .distantPast) } |
| 1250 | List { |
| 1251 | if let snapshot, snapshot.supportsBulkArchive, !tasks.isEmpty { |
| 1252 | Section { |
| 1253 | Button { |
| 1254 | prepare(tasks, in: snapshot, permanently: false) |
| 1255 | } label: { |
| 1256 | PhoneActionLabel(title: "Move All to Trash", systemImage: "trash") |
| 1257 | } |
| 1258 | Button("Delete All Permanently…", role: .destructive) { |
| 1259 | prepare(tasks, in: snapshot, permanently: true) |
| 1260 | } |
| 1261 | } |
| 1262 | .disabled(tasks.contains { workspace.pendingTaskChange(for: $0.id) != nil } || !removals.isEmpty) |
| 1263 | .listRowBackground(colors.card) |
| 1264 | } |
| 1265 | if archived.contains(where: { removals[$0.id] != nil }) { |
| 1266 | Label("Queued for Mac", systemImage: "clock") |
| 1267 | .foregroundStyle(colors.muted).listRowBackground(colors.card) |
| 1268 | } |
| 1269 | if tasks.isEmpty { |
| 1270 | ContentUnavailableView("Archive is empty", systemImage: "archivebox") |
| 1271 | } else { |
| 1272 | Section { |
| 1273 | ForEach(tasks) { TaskLink(task: $0, showProject: projectID == nil, archiveSwipe: true) } |
| 1274 | } |
| 1275 | } |
| 1276 | if let error { Text(error).font(.footnote).foregroundStyle(colors.danger) } |
| 1277 | } |
| 1278 | .modifier(PhoneListAppearance()) |
| 1279 | .navigationTitle("Archive") |
| 1280 | .refreshable { await workspace.sync() } |
| 1281 | .phoneConfirmation(permanently ? "Delete all archived tasks?" : "Move all archived tasks to Trash?", |
| 1282 | isPresented: $showConfirmation, message: archiveConfirmationMessage, |
| 1283 | confirm: permanently ? "Delete All Permanently" : "Move All to Trash", |
| 1284 | role: permanently ? .destructive : nil) { |
| 1285 | if let preview { apply(preview) } |
| 1286 | } |
| 1287 | } |
| 1288 | |
| 1289 | private var archiveConfirmationMessage: String { |
| 1290 | let count = preview?.ids.count ?? 0 |
| 1291 | if preview?.permanently == true { |
| 1292 | return "This permanently deletes \(count) archived items. This can’t be undone." |
| 1293 | } |
| 1294 | return "You can restore these \(count) archived items from Trash." |
| 1295 | } |
| 1296 | |
| 1297 | private func prepare(_ tasks: [PhoneTask], in snapshot: PhoneSnapshot, permanently: Bool) { |
| 1298 | preview = BulkPreview(workspaceID: snapshot.workspaceID, revision: snapshot.revision, |
| 1299 | ids: tasks.map(\.id), permanently: permanently) |
| 1300 | showConfirmation = true |
| 1301 | } |
| 1302 | |
| 1303 | private func apply(_ request: BulkPreview) { |
| 1304 | guard request.workspaceID == workspace.snapshot?.workspaceID else { return } |
| 1305 | do { |
| 1306 | try workspace.queue(.manageArchive(taskIDs: request.ids, revision: request.revision, |
| 1307 | permanently: request.permanently)) |
| 1308 | error = nil |
| 1309 | } catch { self.error = error.localizedDescription } |
| 1310 | } |
| 1311 | } |
| 1312 | |
| 1313 | private enum TodayCoordinateSpace: Hashable { |
| 1314 | case list |
| 1315 | } |
| 1316 | |
| 1317 | private struct TodayView: View { |
| 1318 | @Environment(PhoneWorkspace.self) private var workspace |
| 1319 | @Environment(\.phoneColors) private var colors |
| 1320 | @FocusState private var searchFocused: Bool |
| 1321 | @State private var searchFrame = CGRect.null |
| 1322 | @State private var search = "" |
| 1323 | |
| 1324 | @AppStorage("today.sort") private var sort = OpenTaskSort.newest |
| 1325 | @State private var priority: PhoneTask.Priority? |
| 1326 | |
| 1327 | var body: some View { |
| 1328 | let query = search.trimmingCharacters(in: .whitespacesAndNewlines) |
| 1329 | let projects = Dictionary(uniqueKeysWithValues: (workspace.snapshot?.projects ?? []).map { ($0.id, $0.name) }) |
| 1330 | let active = sort.ordered(workspace.visibleTasks.filter { |
| 1331 | !workspace.isArchived($0) && workspace.displayedStatus(for: $0) != .done && |
| 1332 | (priority == nil || workspace.displayedPriority(for: $0) == priority) && |
| 1333 | (query.isEmpty || [$0.title, workspace.hasPendingProjectMove(for: $0) ? "" : $0.displayTaskID ?? "", |
| 1334 | projects[workspace.displayedProject(for: $0)] ?? "", $0.notes] |
| 1335 | .contains { $0.localizedStandardContains(query) }) |
| 1336 | }, created: \.createdAt, priorityRank: { workspace.displayedPriority(for: $0).rank }, due: workspace.displayedDueDate) |
| 1337 | List { |
| 1338 | if let updated = workspace.snapshot?.updatedAt { |
| 1339 | Text("Mac snapshot \(updated.formatted(.relative(presentation: .named)))") |
| 1340 | .font(.footnote).foregroundStyle(.secondary) |
| 1341 | .listRowBackground(colors.card) |
| 1342 | } |
| 1343 | searchRow |
| 1344 | Section { |
| 1345 | NavigationLink { |
| 1346 | PhoneRecentTasks() |
| 1347 | } label: { |
| 1348 | PhoneActionLabel(title: "Recent Tasks", systemImage: "clock") |
| 1349 | } |
| 1350 | } |
| 1351 | .listRowBackground(colors.card) |
| 1352 | if let notice = workspace.pickupNotice { |
| 1353 | PhonePickupNotice(message: notice).listRowBackground(colors.card) |
| 1354 | } |
| 1355 | if let error = workspace.syncError { |
| 1356 | Text(error).font(.footnote).foregroundStyle(.secondary).listRowBackground(colors.card) |
| 1357 | } |
| 1358 | if active.isEmpty { |
| 1359 | if query.isEmpty && priority == nil { |
| 1360 | ContentUnavailableView("You’re caught up", systemImage: "checkmark.circle", |
| 1361 | description: Text("Open tasks appear here.")) |
| 1362 | } else { |
| 1363 | ContentUnavailableView("No matching tasks", systemImage: "magnifyingglass") |
| 1364 | } |
| 1365 | } |
| 1366 | if !active.isEmpty { |
| 1367 | Section { |
| 1368 | ForEach(active) { TaskLink(task: $0, showProject: true, showStatus: true) } |
| 1369 | } |
| 1370 | } |
| 1371 | Section { |
| 1372 | NavigationLink { |
| 1373 | PhoneArchiveView() |
| 1374 | } label: { |
| 1375 | PhoneActionLabel(title: "Archive", systemImage: "archivebox") |
| 1376 | } |
| 1377 | NavigationLink { |
| 1378 | PhoneTrashView() |
| 1379 | } label: { |
| 1380 | PhoneActionLabel(title: "Trash", systemImage: "trash") |
| 1381 | } |
| 1382 | } |
| 1383 | .listRowBackground(colors.card) |
| 1384 | } |
| 1385 | .modifier(PhoneListAppearance()) |
| 1386 | .toolbar { |
| 1387 | PhoneActionToolbarItem(placement: .topBarTrailing) { |
| 1388 | Menu { |
| 1389 | Picker("Sort tasks", selection: $sort) { |
| 1390 | ForEach(OpenTaskSort.allCases, id: \.self) { Text($0.rawValue).tag($0) } |
| 1391 | } |
| 1392 | Menu("Filter by priority") { |
| 1393 | Picker("Priority", selection: $priority) { |
| 1394 | Text("All priorities").tag(nil as PhoneTask.Priority?) |
| 1395 | ForEach(PhoneTask.Priority.allCases) { Text($0.title).tag(Optional($0)) } |
| 1396 | } |
| 1397 | } |
| 1398 | } label: { PhoneSortIcon() } |
| 1399 | .accessibilityLabel("Sort and filter tasks") |
| 1400 | .accessibilityValue("\(sort.rawValue), \(priority?.title ?? "All priorities")") |
| 1401 | .accessibilityIdentifier("todaySort") |
| 1402 | } |
| 1403 | } |
| 1404 | .refreshable { await workspace.sync() } |
| 1405 | .scrollDismissesKeyboard(.interactively) |
| 1406 | .contentShape(Rectangle()) |
| 1407 | .coordinateSpace(name: TodayCoordinateSpace.list) |
| 1408 | .simultaneousGesture( |
| 1409 | SpatialTapGesture(coordinateSpace: .named(TodayCoordinateSpace.list)).onEnded { tap in |
| 1410 | if !searchFrame.contains(tap.location) { searchFocused = false } |
| 1411 | }, |
| 1412 | including: searchFocused ? .all : .none |
| 1413 | ) |
| 1414 | } |
| 1415 | |
| 1416 | private var searchRow: some View { |
| 1417 | HStack(spacing: 10) { |
| 1418 | Image(systemName: "magnifyingglass") |
| 1419 | .foregroundStyle(colors.actionAccent) |
| 1420 | .accessibilityHidden(true) |
| 1421 | TextField("Search tasks", text: $search) |
| 1422 | .textInputAutocapitalization(.never) |
| 1423 | .autocorrectionDisabled() |
| 1424 | .focused($searchFocused) |
| 1425 | .submitLabel(.search) |
| 1426 | .onSubmit { searchFocused = false } |
| 1427 | if !search.isEmpty { |
| 1428 | Button { |
| 1429 | search = "" |
| 1430 | } label: { |
| 1431 | Image(systemName: "xmark.circle.fill").foregroundStyle(colors.muted) |
| 1432 | } |
| 1433 | .buttonStyle(.plain) |
| 1434 | .accessibilityLabel("Clear search") |
| 1435 | } |
| 1436 | } |
| 1437 | .onGeometryChange(for: CGRect.self) { geometry in |
| 1438 | geometry.frame(in: .named(TodayCoordinateSpace.list)) |
| 1439 | } action: { searchFrame = $0 } |
| 1440 | .listRowBackground(colors.card) |
| 1441 | } |
| 1442 | } |
| 1443 | |
| 1444 | private struct PhoneRecentTasks: View { |
| 1445 | @Environment(PhoneWorkspace.self) private var workspace |
| 1446 | @Environment(\.phoneColors) private var colors |
| 1447 | |
| 1448 | var body: some View { |
| 1449 | let recent = workspace.newestTasks(workspace.visibleTasks.filter { !workspace.isArchived($0) }) |
| 1450 | let pending = workspace.capturedTask.flatMap { task in |
| 1451 | if case .queued = task.result { return task } |
| 1452 | return nil |
| 1453 | } |
| 1454 | List { |
| 1455 | if let pending { |
| 1456 | NavigationLink { |
| 1457 | CapturedTaskDetail(task: pending) |
| 1458 | } label: { |
| 1459 | VStack(alignment: .leading, spacing: 6) { |
| 1460 | Text(pending.title).font(.body.weight(.semibold)) |
| 1461 | Label("Waiting to sync · \(pending.project)", systemImage: "clock") |
| 1462 | .font(.caption).foregroundStyle(colors.muted) |
| 1463 | } |
| 1464 | } |
| 1465 | .listRowBackground(colors.card) |
| 1466 | } |
| 1467 | if recent.isEmpty && pending == nil { |
| 1468 | ContentUnavailableView("No recent tasks", systemImage: "clock") |
| 1469 | .listRowBackground(colors.card) |
| 1470 | } else { |
| 1471 | ForEach(recent) { TaskLink(task: $0, showProject: true, showStatus: true) } |
| 1472 | } |
| 1473 | } |
| 1474 | .modifier(PhoneListAppearance()) |
| 1475 | .navigationTitle("Recent Tasks") |
| 1476 | .refreshable { await workspace.sync() } |
| 1477 | } |
| 1478 | } |
| 1479 | |
| 1480 | private struct ProjectsView: View { |
| 1481 | @Environment(PhoneWorkspace.self) private var workspace |
| 1482 | @Environment(\.phoneColors) private var colors |
| 1483 | @Environment(\.dynamicTypeSize) private var dynamicTypeSize |
| 1484 | @SceneStorage("projects.sidebarVisible") private var sidebarVisible = true |
| 1485 | @SceneStorage("projects.selection") private var selectedProjectID: String? |
| 1486 | |
| 1487 | var body: some View { |
| 1488 | let projects = workspace.snapshot?.projects ?? [] |
| 1489 | GeometryReader { geometry in |
| 1490 | if geometry.size.width >= 640, geometry.size.width > geometry.size.height, |
| 1491 | !dynamicTypeSize.isAccessibilitySize, let firstProject = projects.first { |
| 1492 | let selection = projects.first { $0.id == selectedProjectID } ?? firstProject |
| 1493 | wideProjects(projects, selection: selection, showsSidebarControl: geometry.size.width >= 1000) |
| 1494 | } else { |
| 1495 | projectList(projects) |
| 1496 | } |
| 1497 | } |
| 1498 | .background(colors.canvas.ignoresSafeArea()) |
| 1499 | } |
| 1500 | |
| 1501 | private func projectList(_ projects: [PhoneProject]) -> some View { |
| 1502 | List(projects) { project in |
| 1503 | NavigationLink { |
| 1504 | ProjectTasks(project: project) |
| 1505 | .navigationTitle(project.name) |
| 1506 | } label: { |
| 1507 | LabeledContent { |
| 1508 | Text("\(openCount(for: project)) open") |
| 1509 | } label: { |
| 1510 | projectTitle(project) |
| 1511 | } |
| 1512 | } |
| 1513 | .listRowBackground(colors.card) |
| 1514 | } |
| 1515 | .modifier(PhoneListAppearance()) |
| 1516 | .refreshable { await workspace.sync() } |
| 1517 | } |
| 1518 | |
| 1519 | private func wideProjects(_ projects: [PhoneProject], selection: PhoneProject, showsSidebarControl: Bool) -> some View { |
| 1520 | VStack(alignment: .leading, spacing: 0) { |
| 1521 | HStack(spacing: 14) { |
| 1522 | if showsSidebarControl { |
| 1523 | Button { |
| 1524 | withAnimation(.easeInOut(duration: 0.2)) { sidebarVisible.toggle() } |
| 1525 | } label: { |
| 1526 | PhoneActionLabel(title: sidebarVisible ? "Hide Projects" : "Show Projects", systemImage: "sidebar.left") |
| 1527 | } |
| 1528 | .buttonStyle(PhoneActionButtonStyle()) |
| 1529 | .accessibilityIdentifier("projectsSidebarToggle") |
| 1530 | Text(selection.name).font(.title2.bold()) |
| 1531 | .foregroundStyle(colors.text) |
| 1532 | .accessibilityAddTraits(.isHeader) |
| 1533 | } else { |
| 1534 | Menu { |
| 1535 | Picker("Project", selection: Binding( |
| 1536 | get: { selection.id }, set: { selectedProjectID = $0 } |
| 1537 | )) { |
| 1538 | ForEach(projects) { project in |
| 1539 | Text(project.name).tag(project.id) |
| 1540 | } |
| 1541 | } |
| 1542 | } label: { |
| 1543 | HStack(spacing: 7) { |
| 1544 | PhoneActionLabel(title: LocalizedStringKey(selection.name), systemImage: "folder") |
| 1545 | Image(systemName: "chevron.down").font(.caption.weight(.semibold)) |
| 1546 | .foregroundStyle(colors.muted) |
| 1547 | } |
| 1548 | } |
| 1549 | .buttonStyle(PhoneActionButtonStyle()) |
| 1550 | .accessibilityLabel("Project") |
| 1551 | .accessibilityValue(selection.name) |
| 1552 | .accessibilityIdentifier("boardProjectPicker") |
| 1553 | } |
| 1554 | } |
| 1555 | .padding(.horizontal, 20) |
| 1556 | .padding(.vertical, 10) |
| 1557 | HStack(spacing: 0) { |
| 1558 | if showsSidebarControl && sidebarVisible { |
| 1559 | ScrollView { |
| 1560 | LazyVStack(alignment: .leading, spacing: 5) { |
| 1561 | ForEach(projects) { project in |
| 1562 | let selected = project.id == selection.id |
| 1563 | Button { |
| 1564 | selectedProjectID = project.id |
| 1565 | } label: { |
| 1566 | HStack(spacing: 8) { |
| 1567 | Image(systemName: "folder") |
| 1568 | .foregroundStyle(selected ? colors.actionAccent : colors.muted) |
| 1569 | .accessibilityHidden(true) |
| 1570 | projectTitle(project) |
| 1571 | Spacer(minLength: 4) |
| 1572 | Text(openCount(for: project), format: .number) |
| 1573 | .font(.caption.monospacedDigit()) |
| 1574 | .foregroundStyle(colors.muted) |
| 1575 | .accessibilityLabel("\(openCount(for: project)) open") |
| 1576 | } |
| 1577 | .font(.callout.weight(selected ? .semibold : .regular)) |
| 1578 | .foregroundStyle(colors.text) |
| 1579 | .padding(.horizontal, 12).padding(.vertical, 4) |
| 1580 | .frame(minHeight: 44) |
| 1581 | .background(selected ? colors.actionAccent.opacity(0.10) : .clear, in: .rect(cornerRadius: 10)) |
| 1582 | .contentShape(Rectangle()) |
| 1583 | } |
| 1584 | .buttonStyle(.plain) |
| 1585 | .accessibilityAddTraits(selected ? .isSelected : []) |
| 1586 | } |
| 1587 | } |
| 1588 | .padding(8) |
| 1589 | } |
| 1590 | .frame(width: 225) |
| 1591 | .background(colors.card, in: .rect(cornerRadius: 16)) |
| 1592 | .padding(.leading, 20) |
| 1593 | .padding(.top, 8) |
| 1594 | .padding(.bottom, 16) |
| 1595 | .accessibilityIdentifier("projectsSidebar") |
| 1596 | } |
| 1597 | ProjectTasks(project: selection) |
| 1598 | .id(selection.id) |
| 1599 | } |
| 1600 | } |
| 1601 | } |
| 1602 | |
| 1603 | private func openCount(for project: PhoneProject) -> Int { |
| 1604 | workspace.visibleTasks.filter { |
| 1605 | !workspace.isArchived($0) && workspace.displayedProject(for: $0) == project.id && workspace.displayedStatus(for: $0) != .done |
| 1606 | }.count |
| 1607 | } |
| 1608 | |
| 1609 | private func projectTitle(_ project: PhoneProject) -> some View { |
| 1610 | VStack(alignment: .leading, spacing: 4) { |
| 1611 | Text(project.name).lineLimit(2) |
| 1612 | if let date = project.createdAt { PhoneDateCaption("Created", date: date) } |
| 1613 | } |
| 1614 | } |
| 1615 | } |
| 1616 | |
| 1617 | private struct ProjectTasks: View { |
| 1618 | private enum Sort: String, CaseIterable { |
| 1619 | case defaultOrder, urgency, newest |
| 1620 | |
| 1621 | var title: String { |
| 1622 | switch self { |
| 1623 | case .defaultOrder: "My order" |
| 1624 | case .urgency: "Urgency" |
| 1625 | case .newest: "Newest" |
| 1626 | } |
| 1627 | } |
| 1628 | } |
| 1629 | |
| 1630 | @Environment(PhoneWorkspace.self) private var workspace |
| 1631 | let project: PhoneProject |
| 1632 | |
| 1633 | @Environment(\.phoneColors) private var colors |
| 1634 | @Environment(\.dynamicTypeSize) private var dynamicTypeSize |
| 1635 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 1636 | @AppStorage("projects.taskSort") private var sort = Sort.defaultOrder |
| 1637 | @AppStorage("projects.doneOrder") private var doneOrder = DoneOrder.recent |
| 1638 | @State private var editMode: EditMode = .inactive |
| 1639 | @State private var highlightedLane: PhoneTask.Status? |
| 1640 | @State private var highlightedTaskID: String? |
| 1641 | @State private var taskToSend: BoardTaskDrag? |
| 1642 | @State private var moveError: String? |
| 1643 | |
| 1644 | private var statuses: [PhoneTask.Status] { |
| 1645 | PhoneTask.Status.allCases.filter { $0 != .sent || workspace.snapshot?.canUseAgents == true || workspace.visibleTasks.contains { $0.projectID == project.id && $0.status == .sent } } |
| 1646 | } |
| 1647 | |
| 1648 | private var canReorder: Bool { |
| 1649 | reorderable(.todo) || reorderable(.done) |
| 1650 | } |
| 1651 | |
| 1652 | private func reorderable(_ status: PhoneTask.Status) -> Bool { |
| 1653 | guard workspace.snapshot?.supportsTaskReordering == true else { return false } |
| 1654 | return status == .done ? doneOrder == .manual : sort == .defaultOrder |
| 1655 | } |
| 1656 | |
| 1657 | var body: some View { |
| 1658 | let snapshot = workspace.snapshot |
| 1659 | let projectTasks = workspace.visibleTasks.filter { workspace.displayedProject(for: $0) == project.id } |
| 1660 | let tasks = projectTasks.filter { !workspace.isArchived($0) } |
| 1661 | let archived = projectTasks.filter { workspace.isArchived($0) } |
| 1662 | GeometryReader { geometry in |
| 1663 | if geometry.size.width >= 640 && !dynamicTypeSize.isAccessibilitySize, let snapshot { |
| 1664 | board(snapshot: snapshot, tasks: tasks, archived: archived, width: geometry.size.width) |
| 1665 | } else { |
| 1666 | List { |
| 1667 | if canReorder { |
| 1668 | HStack { |
| 1669 | Spacer() |
| 1670 | Button(editMode.isEditing ? "Done" : "Reorder") { |
| 1671 | withAnimation(reduceMotion ? nil : .default) { |
| 1672 | editMode = editMode.isEditing ? .inactive : .active |
| 1673 | } |
| 1674 | } |
| 1675 | .buttonStyle(PhoneActionButtonStyle()) |
| 1676 | } |
| 1677 | .listRowBackground(colors.canvas) |
| 1678 | .listRowInsets(EdgeInsets()) |
| 1679 | } |
| 1680 | ForEach(statuses, id: \.self) { status in |
| 1681 | let items = items(for: status, in: tasks) |
| 1682 | if !items.isEmpty { |
| 1683 | Section { |
| 1684 | ForEach(items) { TaskLink(task: $0, showProject: false) } |
| 1685 | .onMove { indices, destination in |
| 1686 | reorderTasks(items, from: indices, to: destination, status: status) |
| 1687 | } |
| 1688 | .moveDisabled(!reorderable(status)) |
| 1689 | } header: { |
| 1690 | Text(status.rawValue) |
| 1691 | } |
| 1692 | } |
| 1693 | } |
| 1694 | if !archived.isEmpty { |
| 1695 | Section { archiveLink } |
| 1696 | .listRowBackground(colors.card) |
| 1697 | } |
| 1698 | if let moveError { |
| 1699 | Text(moveError).font(.footnote).foregroundStyle(colors.danger) |
| 1700 | } |
| 1701 | } |
| 1702 | .environment(\.editMode, $editMode) |
| 1703 | .overlay { |
| 1704 | if projectTasks.isEmpty { ContentUnavailableView("No tasks", systemImage: "checklist") } |
| 1705 | } |
| 1706 | } |
| 1707 | } |
| 1708 | .modifier(PhoneListAppearance()) |
| 1709 | .toolbar { |
| 1710 | PhoneActionToolbarItem(placement: .topBarTrailing) { sortMenu } |
| 1711 | } |
| 1712 | .onChange(of: canReorder) { |
| 1713 | if !canReorder { editMode = .inactive } |
| 1714 | } |
| 1715 | .refreshable { await workspace.sync() } |
| 1716 | .sheet(item: $taskToSend) { payload in |
| 1717 | if let snapshot, snapshot.workspaceID == payload.workspaceID, |
| 1718 | let task = snapshot.tasks.first(where: { $0.id == payload.taskID }) { |
| 1719 | PhoneAgentChooser(snapshot: snapshot, taskTitle: task.title) { agent, model, comment in |
| 1720 | try workspace.queueField(.status(.sent, agent: agent, model: model, dispatchComment: comment), |
| 1721 | for: task, in: snapshot.workspaceID) |
| 1722 | } |
| 1723 | } |
| 1724 | } |
| 1725 | } |
| 1726 | |
| 1727 | private var archiveLink: some View { |
| 1728 | NavigationLink { |
| 1729 | PhoneArchiveView(projectID: project.id) |
| 1730 | } label: { |
| 1731 | PhoneActionLabel(title: "Archive", systemImage: "archivebox") |
| 1732 | } |
| 1733 | } |
| 1734 | |
| 1735 | private var sortMenu: some View { |
| 1736 | Menu { |
| 1737 | Picker("Sort open tasks", selection: $sort) { |
| 1738 | ForEach(Sort.allCases, id: \.self) { Text($0.title).tag($0) } |
| 1739 | } |
| 1740 | Menu("Sort completed tasks") { |
| 1741 | Picker("Completed tasks", selection: $doneOrder) { |
| 1742 | ForEach(DoneOrder.allCases) { Text($0.title).tag($0) } |
| 1743 | } |
| 1744 | } |
| 1745 | } label: { PhoneSortIcon() } |
| 1746 | .accessibilityLabel("Sort project tasks") |
| 1747 | .accessibilityValue(sort.title) |
| 1748 | .accessibilityIdentifier("projectSort") |
| 1749 | } |
| 1750 | |
| 1751 | private func board(snapshot: PhoneSnapshot, tasks: [PhoneTask], archived: [PhoneTask], width: CGFloat) -> some View { |
| 1752 | let laneWidth = max(140, (width - 72) / 4) |
| 1753 | return VStack(alignment: .leading, spacing: 8) { |
| 1754 | HStack { |
| 1755 | if snapshot.supportsFieldEditing { |
| 1756 | PhoneActionLabel(title: canReorder ? "Touch and hold a card to reorder it or move it to another column." |
| 1757 | : "Touch and hold a card to move it to another column.", systemImage: "hand.draw") |
| 1758 | .font(.caption) |
| 1759 | } |
| 1760 | Spacer() |
| 1761 | if !archived.isEmpty { archiveLink.buttonStyle(PhoneActionButtonStyle()) } |
| 1762 | } |
| 1763 | .padding(.horizontal, 18) |
| 1764 | if let moveError { |
| 1765 | Text(moveError).font(.caption).foregroundStyle(colors.danger) |
| 1766 | .padding(.horizontal, 18) |
| 1767 | } |
| 1768 | ScrollView(.horizontal) { |
| 1769 | HStack(spacing: 12) { |
| 1770 | ForEach(statuses, id: \.self) { status in |
| 1771 | statusColumn(status, tasks: tasks, in: snapshot, laneWidth: laneWidth) |
| 1772 | .frame(width: laneWidth) |
| 1773 | .frame(maxHeight: .infinity, alignment: .top) |
| 1774 | } |
| 1775 | } |
| 1776 | .padding(.horizontal, 18) |
| 1777 | .padding(.bottom, 12) |
| 1778 | .frame(maxHeight: .infinity) |
| 1779 | } |
| 1780 | } |
| 1781 | .padding(.top, 8) |
| 1782 | } |
| 1783 | |
| 1784 | private func items(for status: PhoneTask.Status, in tasks: [PhoneTask]) -> [PhoneTask] { |
| 1785 | if status == .done { |
| 1786 | let completed = workspace.completedTasks(in: tasks, order: doneOrder).map(\.task) |
| 1787 | return doneOrder == .manual ? workspace.manualTaskOrder(completed, projectID: project.id, status: .done) : completed |
| 1788 | } |
| 1789 | let matching = tasks.filter { workspace.displayedStatus(for: $0) == status } |
| 1790 | if sort == .newest { return workspace.newestTasks(matching) } |
| 1791 | if sort == .urgency { return workspace.orderedTasks(matching, byPriority: true) } |
| 1792 | if reorderable(status) { return workspace.manualTaskOrder(matching, projectID: project.id, status: status) } |
| 1793 | return status == .todo ? workspace.orderedTasks(matching) : matching |
| 1794 | } |
| 1795 | |
| 1796 | private func reorderTasks(_ items: [PhoneTask], from indices: IndexSet, to destination: Int, |
| 1797 | status: PhoneTask.Status) { |
| 1798 | guard reorderable(status), items.count > 1, indices.count == 1, let index = indices.first else { return } |
| 1799 | let task = items[index] |
| 1800 | var reordered = items |
| 1801 | reordered.move(fromOffsets: indices, toOffset: destination) |
| 1802 | guard let position = reordered.firstIndex(where: { $0.id == task.id }), position != index else { return } |
| 1803 | let anchor = reordered[position == 0 ? 1 : position - 1] |
| 1804 | queueReorder(task.id, status: status, anchorID: anchor.id, before: position == 0) |
| 1805 | } |
| 1806 | |
| 1807 | private func queueReorder(_ id: String, status: PhoneTask.Status, anchorID: String, before: Bool) { |
| 1808 | guard reorderable(status), id != anchorID else { return } |
| 1809 | do { |
| 1810 | moveError = nil |
| 1811 | try withAnimation(reduceMotion ? nil : .snappy(duration: 0.30)) { |
| 1812 | try workspace.queue(.reorderTask(taskID: id, projectID: project.id, status: status, |
| 1813 | anchorID: anchorID, before: before)) |
| 1814 | } |
| 1815 | } catch { |
| 1816 | moveError = error.localizedDescription |
| 1817 | } |
| 1818 | } |
| 1819 | |
| 1820 | private func statusColumn(_ status: PhoneTask.Status, tasks: [PhoneTask], in snapshot: PhoneSnapshot, |
| 1821 | laneWidth: CGFloat) -> some View { |
| 1822 | let items = items(for: status, in: tasks) |
| 1823 | let targeted = highlightedLane == status |
| 1824 | return VStack(alignment: .leading, spacing: 8) { |
| 1825 | HStack(spacing: 8) { |
| 1826 | Text(status.rawValue).font(.subheadline.weight(.semibold)).accessibilityAddTraits(.isHeader) |
| 1827 | Text(items.count, format: .number).font(.caption.monospacedDigit()) |
| 1828 | .foregroundStyle(colors.muted) |
| 1829 | } |
| 1830 | .padding(.bottom, 4) |
| 1831 | ScrollView { |
| 1832 | LazyVStack(alignment: .leading, spacing: 8) { |
| 1833 | ForEach(items) { task in |
| 1834 | let card = boardCard(task) { |
| 1835 | TaskLink(task: task, showProject: false) |
| 1836 | .buttonStyle(.plain) |
| 1837 | .accessibilityIdentifier("boardCard-\(task.id)") |
| 1838 | } |
| 1839 | .overlay { |
| 1840 | if highlightedTaskID == task.id { |
| 1841 | RoundedRectangle(cornerRadius: 12).strokeBorder(colors.actionAccent) |
| 1842 | .allowsHitTesting(false) |
| 1843 | } |
| 1844 | } |
| 1845 | if snapshot.supportsFieldEditing, |
| 1846 | snapshot.supportsTaskOverrides || workspace.pendingTaskChange(for: task.id) == nil { |
| 1847 | let draggableCard = card |
| 1848 | .contentShape(.interaction, RoundedRectangle(cornerRadius: 12)) |
| 1849 | .draggable(BoardTaskDrag(workspaceID: snapshot.workspaceID, taskID: task.id)) { |
| 1850 | boardCard(task) { |
| 1851 | TaskCardLabel(task: task, showProject: false, showStatus: false) |
| 1852 | } |
| 1853 | .frame(width: laneWidth - 24) |
| 1854 | .foregroundStyle(colors.text) |
| 1855 | .environment(workspace) |
| 1856 | .environment(\.phoneColors, colors) |
| 1857 | .contentShape(.dragPreview, RoundedRectangle(cornerRadius: 12)) |
| 1858 | } |
| 1859 | if reorderable(status) { |
| 1860 | draggableCard |
| 1861 | .onDrop(of: [BoardTaskDrag.contentType], isTargeted: Binding( |
| 1862 | get: { highlightedTaskID == task.id }, |
| 1863 | set: { targeted in |
| 1864 | if targeted { highlightedTaskID = task.id } |
| 1865 | else if highlightedTaskID == task.id { highlightedTaskID = nil } |
| 1866 | } |
| 1867 | )) { providers in |
| 1868 | handleDrop(providers, to: status, anchorID: task.id) |
| 1869 | } |
| 1870 | .accessibilityHint("Touch and hold to reorder or move to another column") |
| 1871 | } else { |
| 1872 | draggableCard.accessibilityHint("Touch and hold to move to another column") |
| 1873 | } |
| 1874 | } else { |
| 1875 | card |
| 1876 | } |
| 1877 | } |
| 1878 | if items.isEmpty, snapshot.supportsFieldEditing { |
| 1879 | Text("Drop a task here").font(.caption) |
| 1880 | .foregroundStyle(targeted ? colors.actionAccent : colors.muted) |
| 1881 | .padding(.vertical, 12) |
| 1882 | } |
| 1883 | } |
| 1884 | } |
| 1885 | .frame(maxHeight: .infinity) |
| 1886 | } |
| 1887 | .padding(12) |
| 1888 | .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) |
| 1889 | .background(targeted ? colors.actionAccent.opacity(0.13) : colors.line.opacity(0.24), in: .rect(cornerRadius: 16)) |
| 1890 | .overlay { |
| 1891 | RoundedRectangle(cornerRadius: 16) |
| 1892 | .strokeBorder(targeted ? colors.actionAccent : .clear, lineWidth: 2) |
| 1893 | .allowsHitTesting(false) |
| 1894 | } |
| 1895 | .contentShape(.rect(cornerRadius: 16)) |
| 1896 | .accessibilityIdentifier("boardLane-\(status.rawValue)") |
| 1897 | .onDrop(of: [BoardTaskDrag.contentType], isTargeted: Binding( |
| 1898 | get: { highlightedLane == status }, |
| 1899 | set: { active in |
| 1900 | if active { highlightedLane = status } |
| 1901 | else if highlightedLane == status { highlightedLane = nil } |
| 1902 | } |
| 1903 | )) { providers in |
| 1904 | guard snapshot.supportsFieldEditing else { return false } |
| 1905 | return handleDrop(providers, to: status) |
| 1906 | } |
| 1907 | } |
| 1908 | |
| 1909 | private func boardCard<Content: View>(_ task: PhoneTask, @ViewBuilder content: () -> Content) -> some View { |
| 1910 | VStack(alignment: .leading, spacing: 6) { |
| 1911 | content() |
| 1912 | if workspace.displayedStatus(for: task) != task.status { |
| 1913 | Label("Queued for Mac", systemImage: "clock") |
| 1914 | .font(.caption) |
| 1915 | .foregroundStyle(colors.muted) |
| 1916 | } |
| 1917 | } |
| 1918 | .padding(10) |
| 1919 | .frame(maxWidth: .infinity, alignment: .leading) |
| 1920 | .background(colors.card, in: .rect(cornerRadius: 12)) |
| 1921 | } |
| 1922 | |
| 1923 | private func handleDrop(_ providers: [NSItemProvider], to status: PhoneTask.Status, |
| 1924 | anchorID: String? = nil) -> Bool { |
| 1925 | guard let provider = providers.first else { return false } |
| 1926 | // Update the board after the system drop callback returns. |
| 1927 | _ = provider.loadTransferable(type: BoardTaskDrag.self) { result in |
| 1928 | Task { @MainActor in |
| 1929 | switch result { |
| 1930 | case .success(let payload): move(payload, to: status, anchorID: anchorID) |
| 1931 | case .failure: moveError = "Couldn’t read the dropped task. Try again." |
| 1932 | } |
| 1933 | } |
| 1934 | } |
| 1935 | return true |
| 1936 | } |
| 1937 | |
| 1938 | private func move(_ payload: BoardTaskDrag, to status: PhoneTask.Status, anchorID: String?) { |
| 1939 | guard let snapshot = workspace.snapshot, snapshot.workspaceID == payload.workspaceID, |
| 1940 | snapshot.supportsFieldEditing, |
| 1941 | let task = snapshot.tasks.first(where: { |
| 1942 | $0.id == payload.taskID && !workspace.isArchived($0) && !workspace.isTrashed($0) && workspace.displayedProject(for: $0) == project.id |
| 1943 | }) else { return } |
| 1944 | if workspace.displayedStatus(for: task) == status { |
| 1945 | guard reorderable(status) else { return } |
| 1946 | let column = items(for: status, in: snapshot.tasks.filter { |
| 1947 | !workspace.isArchived($0) && !workspace.isTrashed($0) && workspace.displayedProject(for: $0) == project.id |
| 1948 | }) |
| 1949 | if let targetID = anchorID ?? column.last?.id, |
| 1950 | let source = column.firstIndex(where: { $0.id == task.id }), |
| 1951 | let target = column.firstIndex(where: { $0.id == targetID }) { |
| 1952 | queueReorder(task.id, status: status, anchorID: targetID, before: source > target) |
| 1953 | } |
| 1954 | return |
| 1955 | } |
| 1956 | guard snapshot.supportsTaskOverrides || workspace.pendingTaskChange(for: task.id) == nil else { |
| 1957 | moveError = "Wait for the current task change to sync with your Mac." |
| 1958 | return |
| 1959 | } |
| 1960 | guard status != .done || !task.assigned else { |
| 1961 | moveError = "This task is assigned to an agent." |
| 1962 | return |
| 1963 | } |
| 1964 | moveError = nil |
| 1965 | if status == .sent { |
| 1966 | guard snapshot.canUseAgents else { return } |
| 1967 | taskToSend = payload |
| 1968 | return |
| 1969 | } |
| 1970 | do { |
| 1971 | try withAnimation(reduceMotion ? nil : .snappy(duration: 0.30)) { |
| 1972 | try workspace.queueField(.status(status), for: task, in: snapshot.workspaceID) |
| 1973 | } |
| 1974 | } catch { |
| 1975 | moveError = error.localizedDescription |
| 1976 | } |
| 1977 | } |
| 1978 | |
| 1979 | } |
| 1980 | |
| 1981 | private extension PhoneAgent { |
| 1982 | var markAsset: String { |
| 1983 | switch self { |
| 1984 | case .claude: "ClaudeMark" |
| 1985 | case .codex: "OpenAIMark" |
| 1986 | case .gemini: "GeminiMark" |
| 1987 | } |
| 1988 | } |
| 1989 | } |
| 1990 | |
| 1991 | private struct PhoneAgentLabel: View { |
| 1992 | @Environment(\.phoneColors) private var colors |
| 1993 | @Environment(\.colorScheme) private var colorScheme |
| 1994 | let agent: PhoneAgent |
| 1995 | let title: String |
| 1996 | |
| 1997 | var body: some View { |
| 1998 | Label { |
| 1999 | Text(title).foregroundStyle(colors.text) |
| 2000 | } icon: { |
| 2001 | OpenTalonAgentMark( |
| 2002 | image: Image(agent.markAsset), |
| 2003 | agent: agent, |
| 2004 | darkSurface: colorScheme == .dark, |
| 2005 | size: 16 |
| 2006 | ) |
| 2007 | } |
| 2008 | } |
| 2009 | } |
| 2010 | |
| 2011 | private struct PhoneAgentChooser: View { |
| 2012 | @Environment(PhoneWorkspace.self) private var workspace |
| 2013 | @Environment(\.dismiss) private var dismiss |
| 2014 | @Environment(\.phoneColors) private var colors |
| 2015 | @State private var selectedAgent: PhoneAgent? |
| 2016 | @State private var selectedModel: String? |
| 2017 | @State private var comment = "" |
| 2018 | @State private var error: String? |
| 2019 | let snapshot: PhoneSnapshot |
| 2020 | let taskTitle: String |
| 2021 | let choose: (PhoneAgent, String?, String?) throws -> Void |
| 2022 | |
| 2023 | private var agents: [PhoneAgent] { |
| 2024 | let preferred = snapshot.agents.defaultAgent ?? .codex |
| 2025 | let available = snapshot.agents.availableAgents ?? [preferred] |
| 2026 | guard available.contains(preferred) else { return available } |
| 2027 | return [preferred] + available.filter { $0 != preferred } |
| 2028 | } |
| 2029 | |
| 2030 | private var agent: PhoneAgent? { |
| 2031 | selectedAgent.flatMap { agents.contains($0) ? $0 : nil } ?? agents.first |
| 2032 | } |
| 2033 | |
| 2034 | private var models: [AgentModelChoice] { |
| 2035 | (snapshot.agents.agentModels ?? []).filter { $0.agent == agent } |
| 2036 | } |
| 2037 | |
| 2038 | private var commentText: String { |
| 2039 | comment.trimmingCharacters(in: .whitespacesAndNewlines) |
| 2040 | } |
| 2041 | |
| 2042 | var body: some View { |
| 2043 | VStack(spacing: 0) { |
| 2044 | HStack(spacing: 8) { |
| 2045 | Button("Cancel") { dismiss() } |
| 2046 | Text("Send to agent") |
| 2047 | .font(.headline) |
| 2048 | .multilineTextAlignment(.center) |
| 2049 | .frame(maxWidth: .infinity) |
| 2050 | .accessibilityAddTraits(.isHeader) |
| 2051 | Button("Send", action: send) |
| 2052 | .disabled(agent == nil || workspace.snapshot?.canUseAgents != true || commentText.utf16.count > 10_000) |
| 2053 | .accessibilityIdentifier("confirmAgentSend") |
| 2054 | } |
| 2055 | .buttonStyle(PhoneActionButtonStyle()) |
| 2056 | .padding(.horizontal, 20) |
| 2057 | .padding(.vertical, 12) |
| 2058 | |
| 2059 | Form { |
| 2060 | Section { |
| 2061 | Text(taskTitle) |
| 2062 | .font(.headline) |
| 2063 | .accessibilityAddTraits(.isHeader) |
| 2064 | } footer: { |
| 2065 | Text("Your Mac will start the task after it syncs.") |
| 2066 | } |
| 2067 | .listRowBackground(colors.card) |
| 2068 | |
| 2069 | Section("Agent") { |
| 2070 | ForEach(agents) { option in |
| 2071 | Button { |
| 2072 | selectedAgent = option |
| 2073 | } label: { |
| 2074 | HStack { |
| 2075 | PhoneAgentLabel(agent: option, title: option.title) |
| 2076 | if option == agents.first { |
| 2077 | Text("Default") |
| 2078 | .font(.caption) |
| 2079 | .foregroundStyle(colors.muted) |
| 2080 | } |
| 2081 | Spacer() |
| 2082 | if option == agent { |
| 2083 | Image(systemName: "checkmark") |
| 2084 | .foregroundStyle(colors.actionAccent) |
| 2085 | .accessibilityHidden(true) |
| 2086 | } |
| 2087 | } |
| 2088 | .frame(minHeight: 32) |
| 2089 | .contentShape(Rectangle()) |
| 2090 | } |
| 2091 | .buttonStyle(.plain) |
| 2092 | .accessibilityAddTraits(option == agent ? .isSelected : []) |
| 2093 | .accessibilityIdentifier("sendAgent-\(option.rawValue)") |
| 2094 | } |
| 2095 | if agents.isEmpty { |
| 2096 | Text("Set up Claude, Codex, or Gemini on your Mac to send this task.") |
| 2097 | .foregroundStyle(colors.muted) |
| 2098 | } |
| 2099 | } |
| 2100 | .listRowBackground(colors.card) |
| 2101 | |
| 2102 | Section { |
| 2103 | Picker("Model", selection: $selectedModel) { |
| 2104 | Text(agent?.agentDefaultTitle(models: models) ?? "Agent default").tag(nil as String?) |
| 2105 | ForEach(models) { model in |
| 2106 | Text(model.title).tag(Optional(model.id)) |
| 2107 | } |
| 2108 | } |
| 2109 | .pickerStyle(.menu) |
| 2110 | .tint(colors.text) |
| 2111 | .accessibilityIdentifier("sendModelPicker") |
| 2112 | } |
| 2113 | .listRowBackground(colors.card) |
| 2114 | |
| 2115 | Section("Revision request (optional)") { |
| 2116 | if snapshot.supportsDispatchComments { |
| 2117 | TextField(TaskRevisionRequestCopy.field, text: $comment, |
| 2118 | prompt: Text(TaskRevisionRequestCopy.example), axis: .vertical) |
| 2119 | .lineLimit(4...8) |
| 2120 | .accessibilityIdentifier("sendComment") |
| 2121 | if commentText.utf16.count > 10_000 { |
| 2122 | Text("Revision requests can be up to 10,000 characters.") |
| 2123 | .font(.caption) |
| 2124 | .foregroundStyle(colors.danger) |
| 2125 | } |
| 2126 | } else { |
| 2127 | Text("Update OpenTalon on your Mac to include a revision request when you send.") |
| 2128 | .foregroundStyle(colors.muted) |
| 2129 | } |
| 2130 | } |
| 2131 | .listRowBackground(colors.card) |
| 2132 | if let error { |
| 2133 | Text(error).foregroundStyle(colors.danger).listRowBackground(colors.card) |
| 2134 | } |
| 2135 | } |
| 2136 | .foregroundStyle(colors.text) |
| 2137 | .modifier(PhoneListAppearance()) |
| 2138 | .onChange(of: agent) { selectedModel = nil } |
| 2139 | .onChange(of: models) { |
| 2140 | if !models.contains(where: { $0.id == selectedModel }) { selectedModel = nil } |
| 2141 | } |
| 2142 | } |
| 2143 | .background(colors.canvas) |
| 2144 | .presentationDetents([.large]) |
| 2145 | } |
| 2146 | |
| 2147 | private func send() { |
| 2148 | guard let agent, workspace.snapshot?.canUseAgents == true, commentText.utf16.count <= 10_000 else { return } |
| 2149 | let model = models.first(where: { $0.id == selectedModel })?.id |
| 2150 | do { |
| 2151 | try choose(agent, model, snapshot.supportsDispatchComments && !commentText.isEmpty ? commentText : nil) |
| 2152 | dismiss() |
| 2153 | } catch { |
| 2154 | self.error = error.localizedDescription |
| 2155 | } |
| 2156 | } |
| 2157 | } |
| 2158 | |
| 2159 | private struct BoardTaskDrag: Codable, Identifiable, Transferable { |
| 2160 | static let contentType = UTType(exportedAs: "com.protomota.opentalon.board-task") |
| 2161 | let workspaceID: UUID |
| 2162 | let taskID: String |
| 2163 | var id: String { taskID } |
| 2164 | |
| 2165 | static var transferRepresentation: some TransferRepresentation { |
| 2166 | CodableRepresentation(contentType: contentType) |
| 2167 | } |
| 2168 | } |
| 2169 | |
| 2170 | private struct TaskLink: View { |
| 2171 | @Environment(PhoneWorkspace.self) private var workspace |
| 2172 | @Environment(\.phoneColors) private var colors |
| 2173 | @State private var completionError: String? |
| 2174 | @State private var confirmCompletion = false |
| 2175 | let task: PhoneTask |
| 2176 | let showProject: Bool |
| 2177 | var showStatus = false |
| 2178 | var archiveSwipe = false |
| 2179 | |
| 2180 | var body: some View { |
| 2181 | NavigationLink { |
| 2182 | TaskView(taskID: task.id) |
| 2183 | } label: { |
| 2184 | TaskCardLabel(task: task, showProject: showProject, showStatus: showStatus) |
| 2185 | } |
| 2186 | .listRowBackground(colors.card) |
| 2187 | .swipeActions(edge: .trailing, allowsFullSwipe: true) { |
| 2188 | if !archiveSwipe, workspace.canMarkDone(task) { |
| 2189 | Button { |
| 2190 | if workspace.completionNeedsConfirmation(for: task) { confirmCompletion = true } |
| 2191 | else { markDone() } |
| 2192 | } label: { |
| 2193 | Label("Mark done", systemImage: "checkmark") |
| 2194 | } |
| 2195 | .tint(colors.actionAccent) |
| 2196 | } else if archiveSwipe, workspace.snapshot?.trashedTasks != nil, |
| 2197 | workspace.pendingTaskChange(for: task.id) == nil { |
| 2198 | Button(role: .destructive) { |
| 2199 | do { try workspace.queue(.removeArchived(taskID: task.id, revision: task.revision, permanently: false)) } |
| 2200 | catch { completionError = error.localizedDescription } |
| 2201 | } label: { |
| 2202 | Label("Move to Trash", systemImage: "trash") |
| 2203 | } |
| 2204 | } |
| 2205 | } |
| 2206 | .phoneConfirmation(archiveSwipe ? "Couldn’t move task to Trash" : "Couldn’t mark task done", isPresented: Binding( |
| 2207 | get: { completionError != nil }, |
| 2208 | set: { if !$0 { completionError = nil } } |
| 2209 | ), message: completionError ?? "", confirm: "OK", cancel: nil, action: {}) |
| 2210 | .phoneConfirmation("Mark this task done anyway?", isPresented: $confirmCompletion, |
| 2211 | message: "This stops any active agent run and moves the task to Done.", |
| 2212 | confirm: "Mark Done", action: markDone) |
| 2213 | } |
| 2214 | |
| 2215 | private func markDone() { |
| 2216 | do { try workspace.markDone(task) } |
| 2217 | catch { completionError = error.localizedDescription } |
| 2218 | } |
| 2219 | } |
| 2220 | |
| 2221 | private struct TaskCardLabel: View { |
| 2222 | @Environment(PhoneWorkspace.self) private var workspace |
| 2223 | @Environment(\.phoneColors) private var colors |
| 2224 | @Environment(\.colorScheme) private var scheme |
| 2225 | let task: PhoneTask |
| 2226 | let showProject: Bool |
| 2227 | let showStatus: Bool |
| 2228 | |
| 2229 | var body: some View { |
| 2230 | VStack(alignment: .leading, spacing: 6) { |
| 2231 | Text(workspace.displayedText(for: task, field: .title)).font(.body.weight(.semibold)) |
| 2232 | if workspace.hasPendingProjectMove(for: task) { |
| 2233 | Text("New task ID syncing…").font(.caption).foregroundStyle(colors.muted) |
| 2234 | } else if let taskKey = task.displayTaskID { |
| 2235 | Text(taskKey).font(.system(.subheadline, design: .monospaced).weight(.medium)) |
| 2236 | .foregroundStyle(colors.text) |
| 2237 | .accessibilityLabel("Task ID \(taskKey)") |
| 2238 | } |
| 2239 | ViewThatFits(in: .horizontal) { |
| 2240 | HStack(spacing: 8) { metadata } |
| 2241 | .fixedSize(horizontal: true, vertical: false) |
| 2242 | VStack(alignment: .leading, spacing: 4) { metadata } |
| 2243 | } |
| 2244 | .font(.subheadline.weight(.medium)) |
| 2245 | .foregroundStyle(colors.text) |
| 2246 | if showStatus { |
| 2247 | let status = workspace.displayedStatus(for: task) |
| 2248 | Label(status.mobileStage, systemImage: status.mobileStageIcon) |
| 2249 | .font(.caption.weight(.medium)) |
| 2250 | .foregroundStyle(colors.text) |
| 2251 | .padding(.horizontal, 8) |
| 2252 | .padding(.vertical, 4) |
| 2253 | .background(colors.actionAccent.opacity(0.10), in: Capsule()) |
| 2254 | .accessibilityIdentifier("taskStage-\(task.id)") |
| 2255 | } |
| 2256 | PhoneTaskDates(task: task) |
| 2257 | } |
| 2258 | .padding(.vertical, 3) |
| 2259 | .frame(maxWidth: .infinity, alignment: .leading) |
| 2260 | .contentShape(Rectangle()) |
| 2261 | } |
| 2262 | |
| 2263 | @ViewBuilder private var metadata: some View { |
| 2264 | if workspace.displayedIssueType(for: task) == .bug { IssueTypeBadge(.bug, tint: colors.actionAccent) } |
| 2265 | if showProject { Text(workspace.projectName(workspace.displayedProject(for: task))) } |
| 2266 | let priority = workspace.displayedPriority(for: task) |
| 2267 | if priority != .none { |
| 2268 | let tint = priorityTint(priority) |
| 2269 | Text(priority.title) |
| 2270 | .font(.subheadline.weight(priority == .urgent ? .bold : .semibold)) |
| 2271 | .padding(.horizontal, 8) |
| 2272 | .padding(.vertical, 3) |
| 2273 | .foregroundStyle(tint) |
| 2274 | .background(tint.opacity(0.11), in: Capsule()) |
| 2275 | } |
| 2276 | if let due = workspace.displayedDueDate(for: task) { Text("Due \(CalendarDay.label(due))") } |
| 2277 | } |
| 2278 | |
| 2279 | private func priorityTint(_ priority: PhoneTask.Priority) -> Color { |
| 2280 | switch priority { |
| 2281 | case .urgent: colors.danger |
| 2282 | case .high: scheme == .dark ? Color(red: 1, green: 0.72, blue: 0.44) |
| 2283 | : Color(red: 0.57, green: 0.28, blue: 0.04) |
| 2284 | case .medium: scheme == .dark ? Color(red: 0.92, green: 0.81, blue: 0.45) |
| 2285 | : Color(red: 0.43, green: 0.34, blue: 0.03) |
| 2286 | case .low: OpenTalonColors(theme: .system, systemScheme: scheme).actionAccent |
| 2287 | case .none: colors.muted |
| 2288 | } |
| 2289 | } |
| 2290 | } |
| 2291 | |
| 2292 | struct PhoneDateCaption: View { |
| 2293 | @Environment(\.phoneColors) private var colors |
| 2294 | let text: LocalizedStringKey |
| 2295 | |
| 2296 | init(_ label: LocalizedStringKey, date: Date) { |
| 2297 | text = "\(Text(label)) \(date.formatted(date: .abbreviated, time: .shortened))" |
| 2298 | } |
| 2299 | |
| 2300 | var body: some View { |
| 2301 | Text(text).font(.caption).foregroundStyle(colors.muted) |
| 2302 | .fixedSize(horizontal: false, vertical: true) |
| 2303 | } |
| 2304 | } |
| 2305 | |
| 2306 | private struct PhoneTaskDates: View { |
| 2307 | @Environment(PhoneWorkspace.self) private var workspace |
| 2308 | let task: PhoneTask |
| 2309 | |
| 2310 | var body: some View { |
| 2311 | if let date = workspace.lastUpdated(for: task) { |
| 2312 | PhoneDateCaption("Last updated", date: date) |
| 2313 | } else if let date = task.createdAt { |
| 2314 | PhoneDateCaption("Created", date: date) |
| 2315 | } |
| 2316 | if let completion = workspace.completion(for: task) { |
| 2317 | PhoneDateCaption(completion.pending ? "Completion queued" : "Completed", date: completion.date) |
| 2318 | } |
| 2319 | if let date = workspace.archivedDate(for: task) { |
| 2320 | PhoneDateCaption("Archived", date: date) |
| 2321 | } |
| 2322 | } |
| 2323 | } |
| 2324 | |
| 2325 | private extension PhoneTask.Status { |
| 2326 | var mobileStage: String { |
| 2327 | self == .sent ? "Sending to agent" : rawValue |
| 2328 | } |
| 2329 | |
| 2330 | var mobileStageIcon: String { |
| 2331 | switch self { |
| 2332 | case .todo: "circle" |
| 2333 | case .sent: "paperplane" |
| 2334 | case .working: "play.circle" |
| 2335 | case .done: "checkmark" |
| 2336 | } |
| 2337 | } |
| 2338 | } |
| 2339 | |
| 2340 | private struct PhonePickupNotice: View { |
| 2341 | @Environment(PhoneWorkspace.self) private var workspace |
| 2342 | @Environment(\.phoneColors) private var colors |
| 2343 | let message: String |
| 2344 | |
| 2345 | var body: some View { |
| 2346 | HStack(spacing: 10) { |
| 2347 | Image(systemName: "checkmark.icloud").foregroundStyle(colors.actionAccent).accessibilityHidden(true) |
| 2348 | Text(message).font(.callout.weight(.medium)) |
| 2349 | .accessibilityAddTraits(.updatesFrequently) |
| 2350 | Spacer() |
| 2351 | Button { workspace.dismissPickupNotice() } label: { |
| 2352 | Image(systemName: "xmark.circle.fill").foregroundStyle(colors.muted) |
| 2353 | } |
| 2354 | .buttonStyle(.plain) |
| 2355 | .accessibilityLabel("Dismiss pickup notice") |
| 2356 | } |
| 2357 | } |
| 2358 | } |
| 2359 | |
| 2360 | private func pickupCaption(macName: String?, date: Date) -> String { |
| 2361 | "Picked up by \(macName ?? "your Mac") · \(date.formatted(date: .abbreviated, time: .shortened))" |
| 2362 | } |
| 2363 | |
| 2364 | private struct NotesEdit: Identifiable { |
| 2365 | let task: PhoneTask |
| 2366 | let workspaceID: UUID |
| 2367 | let unsaved: PhoneWorkspace.UnsavedNotes? |
| 2368 | var id: String { task.id } |
| 2369 | } |
| 2370 | |
| 2371 | private struct DueDateEdit: Identifiable { |
| 2372 | let task: PhoneTask |
| 2373 | let workspaceID: UUID |
| 2374 | let currentDueDate: String? |
| 2375 | var id: String { task.id } |
| 2376 | } |
| 2377 | |
| 2378 | private struct TaskView: View { |
| 2379 | private struct PlanEdit: Identifiable { |
| 2380 | let id: String |
| 2381 | let workspaceID: UUID |
| 2382 | let markdown: String |
| 2383 | let reference: String |
| 2384 | let context: String |
| 2385 | } |
| 2386 | @State private var planEdit: PlanEdit? |
| 2387 | @State private var filePresentation = PhoneFilePresentation() |
| 2388 | @State private var showHistory = false |
| 2389 | @State private var showActivity = false |
| 2390 | @State private var showEarlierActivity = false |
| 2391 | @State private var linkedComment: PhoneComment? |
| 2392 | @State private var showFullLegacyNotes = false |
| 2393 | @Environment(\.dismiss) private var dismiss |
| 2394 | @State private var confirmTrash = false |
| 2395 | @State private var confirmArchive = false |
| 2396 | @State private var confirmArchiveDeletion = false |
| 2397 | @State private var confirmForceComplete = false |
| 2398 | @Environment(PhoneWorkspace.self) private var workspace |
| 2399 | @Environment(\.phoneColors) private var colors |
| 2400 | @Environment(\.scenePhase) private var phase |
| 2401 | @State private var showSend = false |
| 2402 | @State private var notesEdit: NotesEdit? |
| 2403 | @State private var dueDateEdit: DueDateEdit? |
| 2404 | @State private var showComment = false |
| 2405 | @State private var comment = "" |
| 2406 | @State private var commentWorkspaceID: UUID? |
| 2407 | @State private var commentSaved = false |
| 2408 | @State private var commentError: String? |
| 2409 | @State private var withdrawTarget: RevisionWithdrawTarget? |
| 2410 | @State private var confirmWithdraw = false |
| 2411 | @State private var withdrawError: String? |
| 2412 | @State private var copiedTaskReference: String? |
| 2413 | @State private var error: String? |
| 2414 | let taskID: String |
| 2415 | |
| 2416 | private var commentText: String { comment.trimmingCharacters(in: .whitespacesAndNewlines) } |
| 2417 | private var commentTooLong: Bool { commentText.utf16.count > 10_000 } |
| 2418 | |
| 2419 | var body: some View { |
| 2420 | if let snapshot = workspace.snapshot, |
| 2421 | let task = snapshot.tasks.first(where: { $0.id == taskID }) { |
| 2422 | List { |
| 2423 | Section { |
| 2424 | VStack(alignment: .leading, spacing: 4) { |
| 2425 | if workspace.hasPendingProjectMove(for: task) { |
| 2426 | Text("New task ID syncing…").font(.caption).foregroundStyle(colors.muted) |
| 2427 | } else if let reference = task.displayTaskID { |
| 2428 | taskReferenceHeader(reference) |
| 2429 | } else { |
| 2430 | Text("Task ID will appear after syncing with your Mac.") |
| 2431 | .font(.caption) |
| 2432 | .foregroundStyle(colors.muted) |
| 2433 | } |
| 2434 | Text(workspace.displayedText(for: task, field: .title)).font(.title2.weight(.semibold)) |
| 2435 | PhoneTaskDates(task: task) |
| 2436 | if workspace.displayedIssueType(for: task) == .bug { IssueTypeBadge(.bug, tint: colors.actionAccent) } |
| 2437 | quickActions(for: task, in: snapshot) |
| 2438 | if let pickup = task.agentPickup { |
| 2439 | Label(pickupCaption(macName: snapshot.macName, date: pickup.at), systemImage: "checkmark.icloud") |
| 2440 | .font(.caption).foregroundStyle(colors.muted) |
| 2441 | } |
| 2442 | if let dispatchError = task.agentDispatchError, workspace.displayedStatus(for: task) == .todo { |
| 2443 | VStack(alignment: .leading, spacing: 3) { |
| 2444 | Label("Agent didn’t start", systemImage: "exclamationmark.circle") |
| 2445 | .foregroundStyle(colors.danger) |
| 2446 | Text(dispatchError).foregroundStyle(colors.muted) |
| 2447 | } |
| 2448 | .font(.caption) |
| 2449 | } |
| 2450 | if let error { |
| 2451 | Text(error).font(.caption).foregroundStyle(colors.danger) |
| 2452 | } |
| 2453 | } |
| 2454 | properties(for: task, in: snapshot) |
| 2455 | } |
| 2456 | .listRowBackground(colors.card) |
| 2457 | notes(for: task, in: snapshot) |
| 2458 | if !workspace.displayedText(for: task, field: .definitionOfDone).isEmpty { |
| 2459 | Section("Definition of done") { Text(workspace.displayedText(for: task, field: .definitionOfDone)).textSelection(.enabled) } |
| 2460 | .listRowBackground(colors.card) |
| 2461 | } |
| 2462 | Section("Activity") { |
| 2463 | if let page = workspace.activityPage(for: taskID) { |
| 2464 | TaskActivitySummary(page: page, colors: colors) { showActivity = true } |
| 2465 | } else { |
| 2466 | let earlier = (workspace.snapshot?.commentsByTask?[taskID] ?? []).filter { !$0.isUserComment(hasSeparatedActivity: false) } |
| 2467 | if !earlier.isEmpty { |
| 2468 | Button { showEarlierActivity = true } label: { |
| 2469 | PhoneActionLabel(title: "View earlier activity", systemImage: "clock.arrow.circlepath") |
| 2470 | }.accessibilityIdentifier("earlierTaskActivity") |
| 2471 | } |
| 2472 | Text("Update OpenTalon on your Mac to link agent responses to your revision requests.").font(.caption).foregroundStyle(colors.muted) |
| 2473 | } |
| 2474 | }.listRowBackground(colors.card) |
| 2475 | Section("History") { |
| 2476 | Button { showHistory = true } label: { |
| 2477 | PhoneActionLabel(title: "View revision history", systemImage: "clock.arrow.circlepath") |
| 2478 | } |
| 2479 | .accessibilityIdentifier("taskHistory") |
| 2480 | .disabled(snapshot.historyByTask == nil) |
| 2481 | if snapshot.historyByTask == nil { Text("Update OpenTalon on your Mac to sync revision history.").font(.caption) } |
| 2482 | } |
| 2483 | Section("Plan") { |
| 2484 | Button { |
| 2485 | planEdit = PlanEdit(id: task.id, workspaceID: snapshot.workspaceID, |
| 2486 | markdown: workspace.displayedPlan(for: task), |
| 2487 | reference: task.displayTaskID ?? "Task", |
| 2488 | context: "\(task.title)\n\(task.notes)\nDefinition of done: \(task.definitionOfDone)") |
| 2489 | } label: { |
| 2490 | PhoneActionLabel(title: LocalizedStringKey(workspace.displayedPlan(for: task).isEmpty ? "Create plan" : TaskPlan.filename(reference: task.displayTaskID ?? "Task")), |
| 2491 | systemImage: "doc.text") |
| 2492 | } |
| 2493 | .accessibilityIdentifier("taskPlan") |
| 2494 | .disabled(!snapshot.supportsTaskPlans) |
| 2495 | if !workspace.displayedPlan(for: task).isEmpty { |
| 2496 | Text("Markdown document · Open to preview or edit") |
| 2497 | .font(.caption).foregroundStyle(colors.muted) |
| 2498 | } |
| 2499 | if workspace.hasPendingPlan(for: task.id) { |
| 2500 | Label("Plan saved locally. Queued for Mac.", systemImage: "clock") |
| 2501 | .font(.caption).foregroundStyle(colors.muted) |
| 2502 | } |
| 2503 | if workspace.planDraft(for: task.id) != nil { |
| 2504 | Text("An unsaved plan draft is available. Open the plan to review it.") |
| 2505 | .font(.caption).foregroundStyle(colors.muted) |
| 2506 | } |
| 2507 | if !snapshot.supportsTaskPlans { |
| 2508 | Text("Update OpenTalon on your Mac and sync to use plans.") |
| 2509 | .font(.caption).foregroundStyle(colors.muted) |
| 2510 | } |
| 2511 | } |
| 2512 | .listRowBackground(colors.card) |
| 2513 | PhoneTaskFiles(taskID: task.id, snapshot: snapshot, presentation: filePresentation) |
| 2514 | comments(for: task) |
| 2515 | if !workspace.isArchived(task) { |
| 2516 | Section { |
| 2517 | Button { confirmArchive = true } label: { |
| 2518 | PhoneActionLabel(title: "Archive task", systemImage: "archivebox") |
| 2519 | } |
| 2520 | .accessibilityIdentifier("taskArchive") |
| 2521 | Button { confirmTrash = true } label: { |
| 2522 | PhoneActionLabel(title: "Send to Trash", systemImage: "trash") |
| 2523 | } |
| 2524 | .accessibilityIdentifier("taskTrash") |
| 2525 | } footer: { |
| 2526 | Text(snapshot.supportsTaskOrganization |
| 2527 | ? "Archived tasks stay in Archive. Trashed tasks can be restored from Trash." |
| 2528 | : "Update OpenTalon on your Mac and sync to use these actions.") |
| 2529 | } |
| 2530 | .disabled(!snapshot.supportsTaskOrganization) |
| 2531 | .listRowBackground(colors.card) |
| 2532 | } else if snapshot.supportsTaskOrganization { |
| 2533 | Section { |
| 2534 | Button { organize(task, destination: .active) } label: { |
| 2535 | PhoneActionLabel(title: "Restore to To Do", systemImage: "arrow.uturn.backward") |
| 2536 | } |
| 2537 | .accessibilityIdentifier("taskRestoreArchive") |
| 2538 | } |
| 2539 | .disabled(workspace.pendingTaskChange(for: task.id) != nil) |
| 2540 | .listRowBackground(colors.card) |
| 2541 | } |
| 2542 | if task.archivedAt != nil, snapshot.trashedTasks != nil { |
| 2543 | Section { |
| 2544 | Button(role: .destructive) { |
| 2545 | queue(.removeArchived(taskID: task.id, revision: task.revision, permanently: false)) |
| 2546 | } label: { |
| 2547 | Label("Move to Trash", systemImage: "trash") |
| 2548 | } |
| 2549 | Button("Delete Permanently…", role: .destructive) { confirmArchiveDeletion = true } |
| 2550 | } |
| 2551 | .disabled(workspace.pendingTaskChange(for: task.id) != nil) |
| 2552 | .listRowBackground(colors.card) |
| 2553 | } |
| 2554 | } |
| 2555 | .modifier(PhoneListAppearance()) |
| 2556 | .onChange(of: snapshot.workspaceID, initial: true) { |
| 2557 | commentWorkspaceID = snapshot.workspaceID |
| 2558 | comment = workspace.commentDraft(for: taskID, in: snapshot.workspaceID) |
| 2559 | commentSaved = false |
| 2560 | commentError = nil |
| 2561 | } |
| 2562 | .onChange(of: phase) { |
| 2563 | if phase != .active { saveCommentDraft() } |
| 2564 | } |
| 2565 | .navigationTitle("Task") |
| 2566 | .navigationBarTitleDisplayMode(.inline) |
| 2567 | .modifier(PhoneFilePresenter(presentation: filePresentation, taskID: task.id, workspaceID: snapshot.workspaceID)) |
| 2568 | .phoneConfirmation("Archive this task?", isPresented: $confirmArchive, |
| 2569 | message: "You can restore it from Archive. Any active agent run will stop.", |
| 2570 | confirm: "Archive Task") { |
| 2571 | guard workspace.snapshot?.workspaceID == snapshot.workspaceID else { return } |
| 2572 | organize(task, destination: .archive) |
| 2573 | } |
| 2574 | .phoneConfirmation("Send this task to Trash?", isPresented: $confirmTrash, |
| 2575 | message: "You can restore it from Trash. Any active agent run will stop.", |
| 2576 | confirm: "Send to Trash") { |
| 2577 | guard workspace.snapshot?.workspaceID == snapshot.workspaceID else { return } |
| 2578 | organize(task, destination: .trash) |
| 2579 | } |
| 2580 | .phoneConfirmation("Delete this task permanently?", isPresented: $confirmArchiveDeletion, |
| 2581 | message: "“\(task.title)” and its revision requests will be permanently deleted. This can’t be undone.", |
| 2582 | confirm: "Delete Permanently", role: .destructive) { |
| 2583 | guard workspace.snapshot?.workspaceID == snapshot.workspaceID else { return } |
| 2584 | queue(.removeArchived(taskID: task.id, revision: task.revision, permanently: true)) |
| 2585 | } |
| 2586 | .phoneConfirmation("Withdraw this revision request?", isPresented: $confirmWithdraw, |
| 2587 | message: withdrawTarget?.message ?? "", confirm: "Withdraw", role: .destructive, |
| 2588 | confirmID: "confirmWithdrawRevision") { |
| 2589 | guard let withdrawTarget, workspace.snapshot?.workspaceID == snapshot.workspaceID else { return } |
| 2590 | withdraw(withdrawTarget, in: snapshot.workspaceID) |
| 2591 | } |
| 2592 | .phoneConfirmation("Mark this task done anyway?", isPresented: $confirmForceComplete, |
| 2593 | message: "This stops any active agent run and moves the task to Done.", |
| 2594 | confirm: "Mark Done") { |
| 2595 | guard workspace.snapshot?.workspaceID == snapshot.workspaceID else { return } |
| 2596 | markDone(task) |
| 2597 | } |
| 2598 | .sheet(item: $notesEdit) { edit in |
| 2599 | NotesEditor(edit: edit) |
| 2600 | } |
| 2601 | .sheet(isPresented: $showActivity) { |
| 2602 | TaskActivityView(page: workspace.activityPage(for: taskID), colors: colors, |
| 2603 | waitingForMac: workspace.isLoadingActivity(for: taskID)) { before in |
| 2604 | try workspace.loadActivity(for: taskID, before: before) |
| 2605 | } |
| 2606 | } |
| 2607 | .sheet(isPresented: $showEarlierActivity) { |
| 2608 | EarlierTaskActivityView(comments: (workspace.snapshot?.commentsByTask?[taskID] ?? []).filter { !$0.isUserComment(hasSeparatedActivity: false) }, colors: colors) |
| 2609 | } |
| 2610 | .sheet(item: $linkedComment) { entry in |
| 2611 | TaskActivityView(page: workspace.commentActivityPage(for: entry.id), colors: colors, |
| 2612 | waitingForMac: workspace.isLoadingCommentActivity(entry.id), commentID: entry.id) { before in |
| 2613 | try workspace.loadCommentActivity(taskID: taskID, commentID: entry.id, before: before) |
| 2614 | } |
| 2615 | } |
| 2616 | .sheet(isPresented: $showHistory) { |
| 2617 | if let task = workspace.snapshot?.tasks.first(where: { $0.id == taskID }) { |
| 2618 | TaskHistoryView(page: workspace.historyPage(for: taskID), colors: colors, waitingForMac: workspace.isLoadingHistory(for: taskID)) { before in |
| 2619 | try workspace.loadHistory(for: taskID, before: before) |
| 2620 | } restore: { entry in |
| 2621 | try workspace.restoreHistory(entry, for: task) |
| 2622 | return "Revision saved locally and queued for your Mac." |
| 2623 | } |
| 2624 | } |
| 2625 | } |
| 2626 | .sheet(item: $planEdit) { edit in |
| 2627 | PlanDocumentView(markdown: edit.markdown, draft: workspace.planDraft(for: edit.id), |
| 2628 | reference: edit.reference, context: edit.context, colors: colors) { markdown in |
| 2629 | try workspace.savePlan(markdown, expected: edit.markdown, for: edit.id, in: edit.workspaceID) |
| 2630 | } persistDraft: { markdown in |
| 2631 | do { try workspace.savePlanDraft(markdown, for: edit.id, in: edit.workspaceID) } |
| 2632 | catch { self.error = error.localizedDescription } |
| 2633 | } |
| 2634 | } |
| 2635 | .sheet(item: $dueDateEdit) { edit in |
| 2636 | DueDateEditor(edit: edit) |
| 2637 | } |
| 2638 | .sheet(isPresented: $showComment, onDismiss: saveCommentDraft) { |
| 2639 | commentEditor |
| 2640 | } |
| 2641 | .sheet(isPresented: $showSend) { |
| 2642 | PhoneAgentChooser(snapshot: snapshot, taskTitle: task.title) { agent, model, comment in |
| 2643 | if snapshot.supportsFieldEditing { |
| 2644 | try workspace.queueField(.status(.sent, agent: agent, model: model, dispatchComment: comment), |
| 2645 | for: task, in: snapshot.workspaceID) |
| 2646 | } else { |
| 2647 | try workspace.queue(.send(taskID: task.id, revision: task.revision, agent: agent)) |
| 2648 | } |
| 2649 | } |
| 2650 | } |
| 2651 | } else { |
| 2652 | ContentUnavailableView("Task unavailable", systemImage: "checklist") |
| 2653 | .frame(maxWidth: .infinity, maxHeight: .infinity) |
| 2654 | .background(colors.canvas.ignoresSafeArea()) |
| 2655 | } |
| 2656 | } |
| 2657 | |
| 2658 | @ViewBuilder |
| 2659 | private func quickActions(for task: PhoneTask, in snapshot: PhoneSnapshot) -> some View { |
| 2660 | let status = workspace.displayedStatus(for: task) |
| 2661 | let canChangeStatus = snapshot.supportsFieldEditing |
| 2662 | && (snapshot.supportsTaskOverrides || workspace.pendingTaskChange(for: task.id) == nil) |
| 2663 | let returningToTodo = status == .sent || status == .working |
| 2664 | if workspace.isArchived(task) || status == .done { |
| 2665 | if canChangeStatus, status == .done { |
| 2666 | returnToTodoButton(for: task, in: snapshot, reopening: true) |
| 2667 | .buttonStyle(PhoneActionButtonStyle()) |
| 2668 | .padding(.top, 8) |
| 2669 | } |
| 2670 | } else { |
| 2671 | ViewThatFits(in: .horizontal) { |
| 2672 | HStack(spacing: 6) { |
| 2673 | taskActionButtons(for: task, in: snapshot, returningToTodo: returningToTodo, |
| 2674 | canChangeStatus: canChangeStatus) |
| 2675 | } |
| 2676 | .fixedSize(horizontal: true, vertical: false) |
| 2677 | VStack(alignment: .leading, spacing: 6) { |
| 2678 | taskActionButtons(for: task, in: snapshot, returningToTodo: returningToTodo, |
| 2679 | canChangeStatus: canChangeStatus) |
| 2680 | } |
| 2681 | } |
| 2682 | .buttonStyle(PhoneActionButtonStyle(horizontalPadding: 9)) |
| 2683 | .padding(.top, 8) |
| 2684 | |
| 2685 | if status == .todo, canChangeStatus { |
| 2686 | Button { |
| 2687 | queueField(.status(.working), for: task, in: snapshot) |
| 2688 | } label: { |
| 2689 | quickActionLabel("In progress", systemImage: "play.circle") |
| 2690 | } |
| 2691 | .buttonStyle(PhoneActionButtonStyle(horizontalPadding: 9)) |
| 2692 | .accessibilityLabel("Mark in progress") |
| 2693 | .accessibilityIdentifier("taskQuickInProgress") |
| 2694 | } else if status == .working, workspace.canMarkDone(task), !task.assigned, snapshot.canUseAgents { |
| 2695 | sendToAgentButton |
| 2696 | .buttonStyle(PhoneActionButtonStyle(horizontalPadding: 9)) |
| 2697 | } |
| 2698 | } |
| 2699 | if let pending = workspace.pendingTaskChange(for: task.id) { |
| 2700 | VStack(alignment: .leading, spacing: 4) { |
| 2701 | Label("Queued for Mac", systemImage: "clock") |
| 2702 | .font(.callout) |
| 2703 | if let message = workspace.waitingMessage(for: pending) { |
| 2704 | Text(message).font(.caption) |
| 2705 | } |
| 2706 | } |
| 2707 | .foregroundStyle(colors.muted) |
| 2708 | .padding(.top, 8) |
| 2709 | } |
| 2710 | } |
| 2711 | |
| 2712 | private func organize(_ task: PhoneTask, destination: PhoneRequest.TaskDestination) { |
| 2713 | do { |
| 2714 | try workspace.queue(.organizeTask(taskID: task.id, destination: destination)) |
| 2715 | dismiss() |
| 2716 | } catch { |
| 2717 | self.error = error.localizedDescription |
| 2718 | } |
| 2719 | } |
| 2720 | |
| 2721 | @ViewBuilder |
| 2722 | private func taskActionButtons(for task: PhoneTask, in snapshot: PhoneSnapshot, |
| 2723 | returningToTodo: Bool, canChangeStatus: Bool) -> some View { |
| 2724 | if workspace.canMarkDone(task) { |
| 2725 | Button { |
| 2726 | if workspace.completionNeedsConfirmation(for: task) { confirmForceComplete = true } |
| 2727 | else { markDone(task) } |
| 2728 | } label: { |
| 2729 | quickActionLabel("Mark done", systemImage: "checkmark") |
| 2730 | } |
| 2731 | .accessibilityIdentifier("taskQuickDone") |
| 2732 | } |
| 2733 | |
| 2734 | if returningToTodo { |
| 2735 | if canChangeStatus { returnToTodoButton(for: task, in: snapshot, reopening: false) } |
| 2736 | } else if workspace.canMarkDone(task), snapshot.canUseAgents { |
| 2737 | sendToAgentButton |
| 2738 | } |
| 2739 | } |
| 2740 | |
| 2741 | private func returnToTodoButton(for task: PhoneTask, in snapshot: PhoneSnapshot, reopening: Bool) -> some View { |
| 2742 | Button { |
| 2743 | queueField(.status(.todo), for: task, in: snapshot) |
| 2744 | } label: { |
| 2745 | quickActionLabel(reopening ? "Reopen task" : "Back to To Do", systemImage: "arrow.uturn.backward") |
| 2746 | } |
| 2747 | .accessibilityIdentifier("taskQuickTodo") |
| 2748 | } |
| 2749 | |
| 2750 | private var sendToAgentButton: some View { |
| 2751 | Button { |
| 2752 | showSend = true |
| 2753 | } label: { |
| 2754 | quickActionLabel("Send to agent", systemImage: "paperplane") |
| 2755 | } |
| 2756 | .accessibilityHint("Opens agent, model, and revision request options") |
| 2757 | .accessibilityIdentifier("taskQuickSend") |
| 2758 | } |
| 2759 | |
| 2760 | private func markDone(_ task: PhoneTask) { |
| 2761 | do { try workspace.markDone(task); error = nil } |
| 2762 | catch { self.error = error.localizedDescription } |
| 2763 | } |
| 2764 | |
| 2765 | private func quickActionLabel(_ title: LocalizedStringKey, systemImage: String) -> some View { |
| 2766 | HStack(spacing: 5) { |
| 2767 | Image(systemName: systemImage) |
| 2768 | .foregroundStyle(colors.actionAccent) |
| 2769 | .accessibilityHidden(true) |
| 2770 | Text(title) |
| 2771 | } |
| 2772 | } |
| 2773 | |
| 2774 | private func taskReferenceHeader(_ reference: String) -> some View { |
| 2775 | let copied = copiedTaskReference == reference |
| 2776 | let idLabel = Text(reference) |
| 2777 | .font(.system(.caption, design: .monospaced).weight(.medium)) |
| 2778 | .foregroundStyle(colors.muted) |
| 2779 | .accessibilityLabel("Task ID \(reference)") |
| 2780 | let copyButton = Button { |
| 2781 | UIPasteboard.general.string = reference |
| 2782 | copiedTaskReference = reference |
| 2783 | } label: { |
| 2784 | HStack(spacing: 5) { |
| 2785 | Image(systemName: copied ? "checkmark" : "doc.on.doc") |
| 2786 | .foregroundStyle(colors.actionAccent) |
| 2787 | .accessibilityHidden(true) |
| 2788 | Text(copied ? "Copied" : "Copy task ID") |
| 2789 | .foregroundStyle(colors.text) |
| 2790 | } |
| 2791 | .font(.caption.weight(.semibold)) |
| 2792 | } |
| 2793 | .buttonStyle(PhoneActionButtonStyle()) |
| 2794 | .fixedSize() |
| 2795 | .accessibilityLabel("Copy task ID") |
| 2796 | .accessibilityValue(copied ? "Copied" : "") |
| 2797 | |
| 2798 | return ViewThatFits(in: .horizontal) { |
| 2799 | HStack(spacing: 8) { |
| 2800 | idLabel.fixedSize(horizontal: true, vertical: false) |
| 2801 | Spacer(minLength: 6) |
| 2802 | copyButton |
| 2803 | } |
| 2804 | VStack(alignment: .leading, spacing: 4) { |
| 2805 | idLabel |
| 2806 | copyButton |
| 2807 | } |
| 2808 | } |
| 2809 | } |
| 2810 | |
| 2811 | @ViewBuilder |
| 2812 | private func properties(for task: PhoneTask, in snapshot: PhoneSnapshot) -> some View { |
| 2813 | let status = workspace.displayedStatus(for: task) |
| 2814 | let projectID = workspace.displayedProject(for: task) |
| 2815 | let priority = workspace.displayedPriority(for: task) |
| 2816 | let due = workspace.displayedDueDate(for: task) |
| 2817 | let dueLabel = due.map(CalendarDay.label) ?? "No due date" |
| 2818 | if snapshot.supportsFieldEditing, |
| 2819 | snapshot.supportsTaskOverrides || workspace.pendingTaskChange(for: task.id) == nil { |
| 2820 | fieldMenu("Project", selected: projectID, choices: snapshot.projects.map(\.id), label: workspace.projectName) { |
| 2821 | queueField(.project($0), for: task, in: snapshot) |
| 2822 | } |
| 2823 | fieldMenu("Status", selected: status, |
| 2824 | choices: PhoneTask.Status.allCases.filter { |
| 2825 | ($0 != .sent || snapshot.canUseAgents) && (snapshot.supportsTaskOverrides || !task.assigned || $0 != .done || $0 == status) |
| 2826 | }, |
| 2827 | label: \.rawValue) { |
| 2828 | if $0 == .sent { showSend = true } |
| 2829 | else if $0 == .done, task.assigned || status == .sent { confirmForceComplete = true } |
| 2830 | else { queueField(.status($0), for: task, in: snapshot) } |
| 2831 | } |
| 2832 | if snapshot.supportsTaskTypes { |
| 2833 | fieldMenu("Issue type", selected: workspace.displayedIssueType(for: task), choices: IssueType.allCases, label: \.rawValue) { |
| 2834 | queueField(.issueType($0), for: task, in: snapshot) |
| 2835 | } |
| 2836 | } else { LabeledContent("Issue type", value: workspace.displayedIssueType(for: task).rawValue) } |
| 2837 | fieldMenu("Priority", selected: priority, choices: PhoneTask.Priority.allCases, label: \.title) { |
| 2838 | queueField(.priority($0), for: task, in: snapshot) |
| 2839 | } |
| 2840 | Button { |
| 2841 | dueDateEdit = DueDateEdit(task: task, workspaceID: snapshot.workspaceID, currentDueDate: due) |
| 2842 | } label: { |
| 2843 | fieldLabel("Due date", value: dueLabel, symbol: "calendar") |
| 2844 | } |
| 2845 | .accessibilityLabel("Due date") |
| 2846 | .accessibilityHint("Opens a calendar") |
| 2847 | .accessibilityValue(dueLabel) |
| 2848 | } else { |
| 2849 | LabeledContent("Project", value: workspace.projectName(projectID)) |
| 2850 | LabeledContent("Status", value: status.rawValue) |
| 2851 | LabeledContent("Priority", value: priority.title) |
| 2852 | LabeledContent("Issue type", value: workspace.displayedIssueType(for: task).rawValue) |
| 2853 | LabeledContent("Due date", value: dueLabel) |
| 2854 | if !snapshot.supportsFieldEditing { |
| 2855 | Text("Update OpenTalon on your Mac to edit ticket fields.") |
| 2856 | .font(.caption).foregroundStyle(colors.muted) |
| 2857 | } |
| 2858 | } |
| 2859 | } |
| 2860 | |
| 2861 | private func fieldMenu<Value: Hashable>(_ title: String, selected: Value, choices: [Value], |
| 2862 | label: @escaping (Value) -> String, |
| 2863 | change: @escaping (Value) -> Void) -> some View { |
| 2864 | HStack { |
| 2865 | Text(title) |
| 2866 | .layoutPriority(1) |
| 2867 | .accessibilityHidden(true) |
| 2868 | Spacer() |
| 2869 | Menu { |
| 2870 | Picker(title, selection: Binding(get: { selected }, set: { if $0 != selected { change($0) } })) { |
| 2871 | ForEach(choices, id: \.self) { choice in |
| 2872 | Text(label(choice)).tag(choice) |
| 2873 | } |
| 2874 | } |
| 2875 | } label: { |
| 2876 | fieldValue(label(selected), symbol: "chevron.up.chevron.down") |
| 2877 | .lineLimit(1) |
| 2878 | .frame(minHeight: 44, alignment: .trailing) |
| 2879 | } |
| 2880 | .buttonStyle(.borderless) |
| 2881 | .frame(maxWidth: 250, alignment: .trailing) |
| 2882 | .fixedSize(horizontal: true, vertical: false) |
| 2883 | .tint(colors.text) |
| 2884 | .accessibilityLabel(title) |
| 2885 | .accessibilityValue(label(selected)) |
| 2886 | } |
| 2887 | .foregroundStyle(colors.text) |
| 2888 | } |
| 2889 | |
| 2890 | private func fieldLabel(_ title: String, value: String, symbol: String) -> some View { |
| 2891 | HStack { |
| 2892 | Text(title) |
| 2893 | Spacer() |
| 2894 | fieldValue(value, symbol: symbol) |
| 2895 | } |
| 2896 | .foregroundStyle(colors.text) |
| 2897 | .contentShape(Rectangle()) |
| 2898 | } |
| 2899 | |
| 2900 | private func fieldValue(_ value: String, symbol: String) -> some View { |
| 2901 | HStack { |
| 2902 | Text(value) |
| 2903 | Image(systemName: symbol).font(.caption.weight(.semibold)) |
| 2904 | .foregroundStyle(symbol == "calendar" ? colors.actionAccent : colors.text) |
| 2905 | } |
| 2906 | } |
| 2907 | |
| 2908 | private func queueField(_ edit: PhoneTaskFieldEdit, for task: PhoneTask, in snapshot: PhoneSnapshot) { |
| 2909 | do { |
| 2910 | try workspace.queueField(edit, for: task, in: snapshot.workspaceID) |
| 2911 | error = nil |
| 2912 | } catch { |
| 2913 | self.error = error.localizedDescription |
| 2914 | } |
| 2915 | } |
| 2916 | |
| 2917 | private func notes(for task: PhoneTask, in snapshot: PhoneSnapshot) -> some View { |
| 2918 | let canEdit = snapshot.supportsNoteEditing |
| 2919 | let pending = workspace.pendingNotes(for: task.id) |
| 2920 | let text = pending ?? task.notes |
| 2921 | let hasCopiedPlan = !workspace.displayedPlan(for: task).isEmpty && text.contains("--- Plan:") && text.contains("--- End plan ---") |
| 2922 | return Section("Notes") { |
| 2923 | if canEdit, workspace.pendingTaskChange(for: task.id) == nil { |
| 2924 | Button { |
| 2925 | notesEdit = NotesEdit(task: task, workspaceID: snapshot.workspaceID, |
| 2926 | unsaved: workspace.unsavedNotes(for: task.id)) |
| 2927 | } label: { |
| 2928 | HStack(alignment: .top) { |
| 2929 | Text(text.isEmpty ? "Add notes" : text) |
| 2930 | .lineLimit(hasCopiedPlan && !showFullLegacyNotes ? 8 : nil) |
| 2931 | .foregroundStyle(text.isEmpty ? colors.muted : colors.text) |
| 2932 | .frame(maxWidth: .infinity, alignment: .leading) |
| 2933 | Image(systemName: "pencil") |
| 2934 | .foregroundStyle(colors.muted) |
| 2935 | } |
| 2936 | .contentShape(Rectangle()) |
| 2937 | } |
| 2938 | .buttonStyle(.plain) |
| 2939 | .accessibilityHint("Opens the notes editor") |
| 2940 | if workspace.unsavedNotes(for: task.id) != nil { |
| 2941 | Text("An unsaved edit is ready to review.").font(.caption).foregroundStyle(colors.danger) |
| 2942 | } |
| 2943 | } else { |
| 2944 | if !text.isEmpty { Text(text).lineLimit(hasCopiedPlan && !showFullLegacyNotes ? 8 : nil).textSelection(.enabled) } |
| 2945 | if !canEdit { |
| 2946 | Text("Update OpenTalon on your Mac to edit notes.") |
| 2947 | .font(.caption).foregroundStyle(colors.muted) |
| 2948 | } else if pending == nil { |
| 2949 | Text("Notes can be edited after the current change syncs.") |
| 2950 | .font(.caption).foregroundStyle(colors.muted) |
| 2951 | } |
| 2952 | } |
| 2953 | if hasCopiedPlan { |
| 2954 | Button(showFullLegacyNotes ? "Show less" : "Show full notes") { showFullLegacyNotes.toggle() } |
| 2955 | .font(.caption).foregroundStyle(colors.actionAccent) |
| 2956 | Text("Your plan is available as a Markdown document in Plan below.") |
| 2957 | .font(.caption).foregroundStyle(colors.muted) |
| 2958 | } |
| 2959 | } |
| 2960 | .listRowBackground(colors.card) |
| 2961 | } |
| 2962 | |
| 2963 | private func comments(for task: PhoneTask) -> some View { |
| 2964 | Section(TaskRevisionRequestCopy.heading) { |
| 2965 | if let commentsByTask = workspace.snapshot?.commentsByTask { |
| 2966 | let userComments = (commentsByTask[task.id] ?? []).filter { $0.isUserComment(hasSeparatedActivity: workspace.snapshot?.activityByTask != nil) } + workspace.acknowledgedLegacyComments(for: task.id) |
| 2967 | if userComments.isEmpty { Text("No revision requests yet.").font(.caption).foregroundStyle(colors.muted) } |
| 2968 | let savedIDs = Set((commentsByTask[task.id] ?? []).map(\.id)) |
| 2969 | ForEach(userComments) { entry in |
| 2970 | let withdrawing = workspace.isWithdrawing(entry.id) |
| 2971 | revisionRow(withdraw: savedIDs.contains(entry.id) && workspace.canWithdraw(entry) |
| 2972 | ? RevisionWithdrawTarget(id: entry.id, reachedAgent: entry.reachedAgent) : nil) { |
| 2973 | if !entry.text.isEmpty { Text(entry.text).textSelection(.enabled) } |
| 2974 | else { Label("Attachment on Mac", systemImage: "paperclip") } |
| 2975 | if withdrawing { |
| 2976 | withdrawingLabel |
| 2977 | } else if entry.wasActedOn && workspace.snapshot?.supportsCommentActivity == true { |
| 2978 | Button { linkedComment = entry } label: { |
| 2979 | Label("Acted on · View activity", systemImage: "checkmark.circle") |
| 2980 | .font(.caption.weight(.semibold)).foregroundStyle(colors.actionAccent) |
| 2981 | }.buttonStyle(.plain).accessibilityIdentifier("commentActivity-" + entry.id) |
| 2982 | } else { Text(commentStatus(entry)).font(.caption).foregroundStyle(colors.muted) } |
| 2983 | if let date = TaskCreationOrder.date(from: entry.createdAt) { |
| 2984 | PhoneDateCaption("Submitted", date: date) |
| 2985 | } |
| 2986 | if let date = entry.actedOnAt.flatMap(TaskCreationOrder.date(from:)) { |
| 2987 | PhoneDateCaption("Acted on", date: date) |
| 2988 | } |
| 2989 | } |
| 2990 | } |
| 2991 | ForEach(workspace.pending.filter { $0.taskID == task.id && !$0.changesTask }) { request in |
| 2992 | if case .comment(_, let text) = request.action, let id = request.revisionID { |
| 2993 | revisionRow(withdraw: workspace.canWithdraw(request) |
| 2994 | ? RevisionWithdrawTarget(id: id, reachedAgent: false) : nil) { |
| 2995 | Text(text) |
| 2996 | if workspace.isWithdrawing(id) { |
| 2997 | withdrawingLabel |
| 2998 | } else { |
| 2999 | Label("Waiting for Mac", systemImage: "clock") |
| 3000 | .font(.caption).foregroundStyle(.secondary) |
| 3001 | } |
| 3002 | PhoneDateCaption("Queued", date: request.createdAt) |
| 3003 | } |
| 3004 | } |
| 3005 | } |
| 3006 | if let withdrawError { |
| 3007 | Text(withdrawError).font(.caption).foregroundStyle(colors.danger) |
| 3008 | } |
| 3009 | Button { |
| 3010 | showComment = true |
| 3011 | } label: { |
| 3012 | PhoneActionLabel(title: commentText.isEmpty ? LocalizedStringKey(TaskRevisionRequestCopy.add) : "Continue revision request", systemImage: "plus") |
| 3013 | } |
| 3014 | if let commentError { |
| 3015 | Text(commentError).font(.caption).foregroundStyle(colors.danger) |
| 3016 | } else if commentSaved && commentText.isEmpty { |
| 3017 | savedCommentLabel("Saved").font(.caption) |
| 3018 | } |
| 3019 | } else { |
| 3020 | Text("Update OpenTalon on your Mac to sync revision requests here.") |
| 3021 | .foregroundStyle(.secondary) |
| 3022 | } |
| 3023 | } |
| 3024 | .listRowBackground(colors.card) |
| 3025 | } |
| 3026 | |
| 3027 | /// A revision request row. The trash button and the swipe action both ask before withdrawing. |
| 3028 | private func revisionRow<Details: View>(withdraw target: RevisionWithdrawTarget?, |
| 3029 | @ViewBuilder details: () -> Details) -> some View { |
| 3030 | // The icon sits on the first line of text at every text size. |
| 3031 | HStack(alignment: .firstTextBaseline, spacing: 4) { |
| 3032 | VStack(alignment: .leading, spacing: 4, content: details) |
| 3033 | .frame(maxWidth: .infinity, alignment: .leading) |
| 3034 | if let target { |
| 3035 | Button { confirmWithdrawal(of: target) } label: { |
| 3036 | Image(systemName: "trash") |
| 3037 | .foregroundStyle(colors.muted) |
| 3038 | .frame(minWidth: 44, minHeight: 44) |
| 3039 | .contentShape(.rect) |
| 3040 | } |
| 3041 | .buttonStyle(.borderless) |
| 3042 | .hoverEffect() |
| 3043 | // The touch target stays 44 points without making the row taller. |
| 3044 | .padding(.vertical, -11) |
| 3045 | .padding(.trailing, -10) |
| 3046 | .accessibilityLabel("Withdraw revision request") |
| 3047 | .accessibilityIdentifier("withdrawRevision-" + target.id) |
| 3048 | } |
| 3049 | } |
| 3050 | .swipeActions(edge: .trailing, allowsFullSwipe: false) { |
| 3051 | if let target { |
| 3052 | Button("Withdraw", systemImage: "trash") { confirmWithdrawal(of: target) } |
| 3053 | .tint(colors.danger) |
| 3054 | } |
| 3055 | } |
| 3056 | } |
| 3057 | |
| 3058 | private var withdrawingLabel: some View { |
| 3059 | Label("Withdrawing · Waiting for Mac", systemImage: "clock") |
| 3060 | .font(.caption).foregroundStyle(colors.muted) |
| 3061 | } |
| 3062 | |
| 3063 | private func confirmWithdrawal(of target: RevisionWithdrawTarget) { |
| 3064 | withdrawTarget = target |
| 3065 | confirmWithdraw = true |
| 3066 | } |
| 3067 | |
| 3068 | private func withdraw(_ target: RevisionWithdrawTarget, in workspaceID: UUID) { |
| 3069 | do { |
| 3070 | try workspace.withdrawRevision(target.id, for: taskID, in: workspaceID) |
| 3071 | withdrawError = nil |
| 3072 | } catch { |
| 3073 | withdrawError = "Couldn’t withdraw the revision request. \(error.localizedDescription)" |
| 3074 | } |
| 3075 | } |
| 3076 | |
| 3077 | private func commentStatus(_ comment: PhoneComment) -> String { |
| 3078 | let name = workspace.snapshot?.macName |
| 3079 | if let date = comment.pickedUpAt.flatMap(TaskCreationOrder.date(from:)) { |
| 3080 | return pickupCaption(macName: name, date: date) |
| 3081 | } |
| 3082 | switch comment.delivery { |
| 3083 | case "queued", "pending": return "Saved on \(name ?? "your Mac") · Waiting for agent" |
| 3084 | case "needs-review": return "Saved on \(name ?? "your Mac") · Agent delivery needs review" |
| 3085 | case "delivered": return "Delivered to agent" |
| 3086 | default: return "Saved on \(name ?? "your Mac")" |
| 3087 | } |
| 3088 | } |
| 3089 | |
| 3090 | private var commentEditor: some View { |
| 3091 | CommentEditor(text: $comment, canSend: !commentText.isEmpty && !commentTooLong, |
| 3092 | send: finishComment, cancel: { showComment = false }) { |
| 3093 | if commentTooLong { |
| 3094 | Text("Revision requests can be up to 10,000 characters.").foregroundStyle(colors.danger) |
| 3095 | } else if let commentError { |
| 3096 | Text(commentError).foregroundStyle(colors.danger) |
| 3097 | } else if !commentText.isEmpty, let commentWorkspaceID, |
| 3098 | workspace.commentDraft(for: taskID, in: commentWorkspaceID) == comment { |
| 3099 | savedCommentLabel("Draft saved") |
| 3100 | } |
| 3101 | } |
| 3102 | .task(id: comment) { |
| 3103 | do { try await Task.sleep(for: .milliseconds(450)) } |
| 3104 | catch { return } |
| 3105 | saveCommentDraft() |
| 3106 | } |
| 3107 | } |
| 3108 | |
| 3109 | private func savedCommentLabel(_ title: LocalizedStringKey) -> some View { |
| 3110 | Label { |
| 3111 | Text(title).foregroundStyle(colors.muted) |
| 3112 | } icon: { |
| 3113 | Image(systemName: "checkmark").foregroundStyle(colors.done) |
| 3114 | } |
| 3115 | } |
| 3116 | |
| 3117 | private func saveCommentDraft() { |
| 3118 | guard let commentWorkspaceID else { return } |
| 3119 | do { |
| 3120 | try workspace.saveCommentDraft(comment, for: taskID, in: commentWorkspaceID) |
| 3121 | } catch { |
| 3122 | commentError = "Couldn’t save the revision request draft. \(error.localizedDescription)" |
| 3123 | } |
| 3124 | } |
| 3125 | |
| 3126 | private func finishComment() { |
| 3127 | guard let commentWorkspaceID, workspace.snapshot?.workspaceID == commentWorkspaceID else { return } |
| 3128 | guard phase == .active, !commentText.isEmpty, !commentTooLong else { |
| 3129 | saveCommentDraft() |
| 3130 | return |
| 3131 | } |
| 3132 | do { |
| 3133 | try workspace.finishComment(commentText, for: taskID, in: commentWorkspaceID) |
| 3134 | comment = "" |
| 3135 | commentSaved = true |
| 3136 | commentError = nil |
| 3137 | showComment = false |
| 3138 | } catch { |
| 3139 | commentError = "Couldn’t send the revision request. \(error.localizedDescription)" |
| 3140 | } |
| 3141 | } |
| 3142 | |
| 3143 | private func queue(_ action: PhoneRequest.Action) { |
| 3144 | do { |
| 3145 | try workspace.queue(action) |
| 3146 | error = nil |
| 3147 | } |
| 3148 | catch { self.error = error.localizedDescription } |
| 3149 | } |
| 3150 | } |
| 3151 | |
| 3152 | private struct RevisionWithdrawTarget: Equatable { |
| 3153 | let id: String |
| 3154 | let reachedAgent: Bool |
| 3155 | |
| 3156 | var message: String { |
| 3157 | reachedAgent |
| 3158 | ? "The agent already has this request. Your Mac will tell it to skip the request. Work it already finished stays." |
| 3159 | : "It will be removed from this task and won’t be sent to an agent." |
| 3160 | } |
| 3161 | } |
| 3162 | |
| 3163 | private struct CommentEditor<Status: View>: View { |
| 3164 | @Environment(\.phoneColors) private var colors |
| 3165 | @FocusState private var editing: Bool |
| 3166 | @Binding var text: String |
| 3167 | let canSend: Bool |
| 3168 | let send: () -> Void |
| 3169 | let cancel: () -> Void |
| 3170 | @ViewBuilder let status: () -> Status |
| 3171 | |
| 3172 | var body: some View { |
| 3173 | VStack(spacing: 12) { |
| 3174 | HStack { |
| 3175 | Text(TaskRevisionRequestCopy.field) |
| 3176 | .font(.headline) |
| 3177 | .accessibilityAddTraits(.isHeader) |
| 3178 | Spacer(minLength: 12) |
| 3179 | editorButton("Cancel", action: cancel) |
| 3180 | } |
| 3181 | TextEditor(text: $text) |
| 3182 | .focused($editing) |
| 3183 | .scrollContentBackground(.hidden) |
| 3184 | .foregroundStyle(colors.text) |
| 3185 | .overlay(alignment: .topLeading) { |
| 3186 | if text.isEmpty { |
| 3187 | Text(TaskRevisionRequestCopy.example) |
| 3188 | .foregroundStyle(colors.muted) |
| 3189 | .padding(.leading, 5) |
| 3190 | .padding(.top, 8) |
| 3191 | .allowsHitTesting(false) |
| 3192 | .accessibilityHidden(true) |
| 3193 | } |
| 3194 | } |
| 3195 | .padding(8) |
| 3196 | .background(colors.card, in: .rect(cornerRadius: 12)) |
| 3197 | .frame(minHeight: 44) |
| 3198 | .accessibilityLabel(TaskRevisionRequestCopy.field) |
| 3199 | .accessibilityHint(TaskRevisionRequestCopy.example) |
| 3200 | HStack(spacing: 12) { |
| 3201 | status().font(.caption) |
| 3202 | Spacer(minLength: 0) |
| 3203 | Button(TaskRevisionRequestCopy.send, action: send) |
| 3204 | .buttonStyle(PhoneActionButtonStyle()) |
| 3205 | .disabled(!canSend) |
| 3206 | } |
| 3207 | } |
| 3208 | .padding(.horizontal, 20) |
| 3209 | .padding(.vertical, 12) |
| 3210 | .background(colors.canvas.ignoresSafeArea()) |
| 3211 | .presentationDetents([.large]) |
| 3212 | .task { editing = true } |
| 3213 | } |
| 3214 | |
| 3215 | private func editorButton(_ title: LocalizedStringKey, action: @escaping () -> Void) -> some View { |
| 3216 | Button(action: action) { |
| 3217 | Text(title).frame(minWidth: 56) |
| 3218 | } |
| 3219 | .buttonStyle(PhoneActionButtonStyle()) |
| 3220 | } |
| 3221 | } |
| 3222 | |
| 3223 | private struct NotesEditor: View { |
| 3224 | @Environment(PhoneWorkspace.self) private var workspace |
| 3225 | @Environment(\.phoneColors) private var colors |
| 3226 | @Environment(\.dismiss) private var dismiss |
| 3227 | @FocusState private var editing: Bool |
| 3228 | @State private var notes: String |
| 3229 | @State private var error: String? |
| 3230 | |
| 3231 | let task: PhoneTask |
| 3232 | let workspaceID: UUID |
| 3233 | let unsaved: PhoneWorkspace.UnsavedNotes? |
| 3234 | |
| 3235 | init(edit: NotesEdit) { |
| 3236 | task = edit.task |
| 3237 | workspaceID = edit.workspaceID |
| 3238 | unsaved = edit.unsaved |
| 3239 | _notes = State(initialValue: edit.unsaved?.text ?? edit.task.notes) |
| 3240 | } |
| 3241 | |
| 3242 | private var tooLong: Bool { notes.utf16.count > 100_000 } |
| 3243 | |
| 3244 | var body: some View { |
| 3245 | VStack(alignment: .leading, spacing: 12) { |
| 3246 | HStack { |
| 3247 | Text("Edit notes").font(.headline).accessibilityAddTraits(.isHeader) |
| 3248 | Spacer(minLength: 12) |
| 3249 | Button { dismiss() } label: { Text("Cancel").frame(minWidth: 56) } |
| 3250 | .buttonStyle(PhoneActionButtonStyle()) |
| 3251 | .keyboardShortcut(.cancelAction) |
| 3252 | } |
| 3253 | if let unsaved { |
| 3254 | Text(unsaved.message).font(.footnote).foregroundStyle(colors.danger) |
| 3255 | DisclosureGroup("Current notes on Mac") { |
| 3256 | Text(task.notes.isEmpty ? "No notes" : task.notes) |
| 3257 | .textSelection(.enabled) |
| 3258 | .frame(maxHeight: 120) |
| 3259 | } |
| 3260 | } |
| 3261 | TextEditor(text: $notes) |
| 3262 | .focused($editing) |
| 3263 | .scrollContentBackground(.hidden) |
| 3264 | .foregroundStyle(colors.text) |
| 3265 | .padding(8) |
| 3266 | .background(colors.card, in: .rect(cornerRadius: 12)) |
| 3267 | .frame(minHeight: 44) |
| 3268 | .accessibilityLabel("Task notes") |
| 3269 | HStack(spacing: 12) { |
| 3270 | if tooLong { |
| 3271 | Text("Notes can be up to 100,000 characters.") |
| 3272 | .font(.footnote).foregroundStyle(colors.danger) |
| 3273 | } else if let error { |
| 3274 | Text(error).font(.footnote).foregroundStyle(colors.danger) |
| 3275 | } |
| 3276 | Spacer(minLength: 0) |
| 3277 | Button(action: save) { Text("Save").frame(minWidth: 56) } |
| 3278 | .buttonStyle(PhoneActionButtonStyle()) |
| 3279 | .disabled(tooLong || notes == task.notes) |
| 3280 | } |
| 3281 | } |
| 3282 | .padding(.horizontal, 20) |
| 3283 | .padding(.vertical, 12) |
| 3284 | .background(colors.canvas.ignoresSafeArea()) |
| 3285 | .presentationDetents([.large]) |
| 3286 | .task { editing = true } |
| 3287 | .interactiveDismissDisabled(notes != (unsaved?.text ?? task.notes)) |
| 3288 | } |
| 3289 | |
| 3290 | private func save() { |
| 3291 | do { |
| 3292 | try workspace.queueNotes(notes, for: task, in: workspaceID) |
| 3293 | dismiss() |
| 3294 | } catch { |
| 3295 | self.error = error.localizedDescription |
| 3296 | } |
| 3297 | } |
| 3298 | } |
| 3299 | |
| 3300 | private struct DueDateEditor: View { |
| 3301 | @Environment(PhoneWorkspace.self) private var workspace |
| 3302 | @Environment(\.phoneColors) private var colors |
| 3303 | @Environment(\.dismiss) private var dismiss |
| 3304 | @State private var date: Date |
| 3305 | @State private var error: String? |
| 3306 | let edit: DueDateEdit |
| 3307 | |
| 3308 | init(edit: DueDateEdit) { |
| 3309 | self.edit = edit |
| 3310 | _date = State(initialValue: edit.currentDueDate.flatMap(CalendarDay.date) ?? .now) |
| 3311 | } |
| 3312 | |
| 3313 | var body: some View { |
| 3314 | NavigationStack { |
| 3315 | Form { |
| 3316 | DatePicker("Due date", selection: $date, displayedComponents: .date) |
| 3317 | .datePickerStyle(.graphical) |
| 3318 | .tint(colors.actionAccent) |
| 3319 | .listRowBackground(colors.card) |
| 3320 | if edit.currentDueDate != nil { |
| 3321 | Button { |
| 3322 | save(nil) |
| 3323 | } label: { |
| 3324 | PhoneActionLabel(title: "Clear due date", systemImage: "calendar.badge.minus") |
| 3325 | } |
| 3326 | .listRowBackground(colors.card) |
| 3327 | } |
| 3328 | if let error { |
| 3329 | Text(error).foregroundStyle(colors.danger).listRowBackground(colors.card) |
| 3330 | } |
| 3331 | } |
| 3332 | .modifier(PhoneListAppearance()) |
| 3333 | .navigationTitle("Due date") |
| 3334 | .navigationBarTitleDisplayMode(.inline) |
| 3335 | .toolbar { |
| 3336 | PhoneActionToolbarItem(placement: .cancellationAction) { |
| 3337 | Button("Cancel") { dismiss() } |
| 3338 | } |
| 3339 | PhoneActionToolbarItem(placement: .confirmationAction) { |
| 3340 | Button("Save") { save(CalendarDay.key(date)) } |
| 3341 | .disabled(CalendarDay.key(date) == edit.currentDueDate) |
| 3342 | } |
| 3343 | } |
| 3344 | } |
| 3345 | } |
| 3346 | |
| 3347 | private func save(_ day: String?) { |
| 3348 | do { |
| 3349 | try workspace.queueField(.dueDate(day), for: edit.task, in: edit.workspaceID) |
| 3350 | dismiss() |
| 3351 | } catch { |
| 3352 | self.error = error.localizedDescription |
| 3353 | } |
| 3354 | } |
| 3355 | } |
| 3356 | |
| 3357 | private struct QueueView: View { |
| 3358 | @Environment(PhoneWorkspace.self) private var workspace |
| 3359 | @Environment(\.phoneColors) private var colors |
| 3360 | |
| 3361 | var body: some View { |
| 3362 | let agentTasks = workspace.visibleTasks.filter { |
| 3363 | !workspace.isArchived($0) && workspace.pendingTaskChange(for: $0.id) == nil |
| 3364 | && ($0.status == .sent || ($0.status == .working && $0.assigned)) |
| 3365 | } |
| 3366 | List { |
| 3367 | if let notice = workspace.pickupNotice { |
| 3368 | PhonePickupNotice(message: notice).listRowBackground(colors.card) |
| 3369 | } |
| 3370 | if let rejection = workspace.lastRejection { |
| 3371 | Section("Couldn’t apply a change") { |
| 3372 | Text(rejection).font(.footnote) |
| 3373 | Button("Dismiss") { workspace.clearRejection() } |
| 3374 | } |
| 3375 | .listRowBackground(colors.card) |
| 3376 | } |
| 3377 | if workspace.pending.isEmpty && agentTasks.isEmpty { |
| 3378 | ContentUnavailableView("Queue is empty", systemImage: "clock", |
| 3379 | description: Text("Tasks and changes waiting for your\u{00A0}Mac.")) |
| 3380 | } |
| 3381 | if !workspace.pending.isEmpty { |
| 3382 | Section("Waiting for Mac") { |
| 3383 | ForEach(workspace.pending) { request in |
| 3384 | VStack(alignment: .leading, spacing: 5) { |
| 3385 | Text(workspace.title(for: request)).font(.body.weight(.medium)) |
| 3386 | Group { |
| 3387 | if let agent = requestedAgent(for: request) { |
| 3388 | PhoneAgentLabel(agent: agent, title: "Sending to \(agent.title)") |
| 3389 | } else { |
| 3390 | Text(kind(request)).foregroundStyle(.secondary) |
| 3391 | } |
| 3392 | } |
| 3393 | .font(.caption) |
| 3394 | PhoneDateCaption("Queued", date: request.createdAt) |
| 3395 | if let message = workspace.waitingMessage(for: request) { |
| 3396 | Text(message).font(.caption).foregroundStyle(.secondary) |
| 3397 | } |
| 3398 | } |
| 3399 | } |
| 3400 | } |
| 3401 | .listRowBackground(colors.card) |
| 3402 | } |
| 3403 | if !agentTasks.isEmpty { |
| 3404 | Section("Agent work") { |
| 3405 | ForEach(agentTasks) { task in |
| 3406 | TaskLink(task: task, showProject: true, showStatus: true) |
| 3407 | } |
| 3408 | } |
| 3409 | } |
| 3410 | if let error = workspace.syncError { |
| 3411 | Text(error).font(.footnote).foregroundStyle(.secondary).listRowBackground(colors.card) |
| 3412 | } |
| 3413 | } |
| 3414 | .modifier(PhoneListAppearance()) |
| 3415 | .refreshable { await workspace.sync() } |
| 3416 | } |
| 3417 | |
| 3418 | private func requestedAgent(for request: PhoneRequest) -> PhoneAgent? { |
| 3419 | switch request.action { |
| 3420 | case .send(_, _, let agent), .editField(_, _, .status(.sent, let agent, _, _)), |
| 3421 | .setField(_, _, .status(.sent, let agent, _, _)), |
| 3422 | .create(_, _, _, _, true, _, let agent, _, _, _, _, _): agent |
| 3423 | default: nil |
| 3424 | } |
| 3425 | } |
| 3426 | |
| 3427 | private func kind(_ request: PhoneRequest) -> String { |
| 3428 | switch request.action { |
| 3429 | case .createProject: "Create project" |
| 3430 | case .loadActivity, .loadCommentActivity: "Load task activity" |
| 3431 | case .loadHistory: "Load task history" |
| 3432 | case .restoreRevision: "Restore task revision" |
| 3433 | case .savePlan: "Save plan" |
| 3434 | case .attachFile: "Attach file" |
| 3435 | case .organizeTask(_, let destination): |
| 3436 | switch destination { |
| 3437 | case .archive: "Archive task" |
| 3438 | case .trash: "Send to Trash" |
| 3439 | case .active: "Restore task from Archive" |
| 3440 | } |
| 3441 | case .create(_, _, _, _, let send, _, _, _, _, _, _, _): send ? "New task for agent" : "New to-do" |
| 3442 | case .send: PhoneTask.Status.sent.mobileStage |
| 3443 | case .complete: "Mark done" |
| 3444 | case .forceComplete: "Mark done anyway" |
| 3445 | case .removeArchived(_, _, let permanently): permanently ? "Delete permanently" : "Move to Trash" |
| 3446 | case .restoreTrashed: "Restore task" |
| 3447 | case .emptyTrash: "Empty Trash" |
| 3448 | case .manageArchive(_, _, let permanently): permanently ? "Delete archived tasks" : "Move archived tasks to Trash" |
| 3449 | case .reorderTask: "Reorder task" |
| 3450 | case .comment: "Send revision request" |
| 3451 | case .withdrawComment: "Withdraw revision request" |
| 3452 | case .editNotes: "Edit notes" |
| 3453 | case .editField(_, _, .status(let status, _, _, _)), .setField(_, _, .status(let status, _, _, _)): status.mobileStage |
| 3454 | case .editField(_, _, let edit), .setField(_, _, let edit): edit.label |
| 3455 | } |
| 3456 | } |
| 3457 | } |
| 3458 | |
| 3459 | private struct PhoneTaskFiles: View { |
| 3460 | @Environment(PhoneWorkspace.self) private var workspace |
| 3461 | @Environment(\.phoneColors) private var colors |
| 3462 | let taskID: String |
| 3463 | let snapshot: PhoneSnapshot |
| 3464 | let presentation: PhoneFilePresentation |
| 3465 | |
| 3466 | var body: some View { |
| 3467 | Section("Files") { |
| 3468 | ForEach(snapshot.filesByTask?[taskID] ?? []) { file in |
| 3469 | Button { |
| 3470 | Task { await presentation.open(file, workspace: workspace, workspaceID: snapshot.workspaceID) } |
| 3471 | } label: { |
| 3472 | HStack(spacing: 12) { |
| 3473 | Image(systemName: presentation.opening == file.id ? "arrow.down.circle" : "doc") |
| 3474 | .foregroundStyle(colors.accent) |
| 3475 | VStack(alignment: .leading, spacing: 2) { |
| 3476 | Text(file.name).foregroundStyle(colors.text) |
| 3477 | Text(file.sizeLabel).font(.caption).foregroundStyle(colors.muted) |
| 3478 | } |
| 3479 | Spacer(minLength: 8) |
| 3480 | } |
| 3481 | .frame(minHeight: 44) |
| 3482 | .contentShape(Rectangle()) |
| 3483 | } |
| 3484 | .buttonStyle(.plain) |
| 3485 | .disabled(presentation.opening != nil) |
| 3486 | .accessibilityIdentifier("taskFile-\(file.name)") |
| 3487 | } |
| 3488 | ForEach(workspace.pendingFiles(for: taskID), id: \.id) { file in |
| 3489 | VStack(alignment: .leading, spacing: 3) { |
| 3490 | Label(file.name, systemImage: "clock") |
| 3491 | Text("Saved on this device. Waiting for Mac sync.").font(.caption).foregroundStyle(colors.muted) |
| 3492 | } |
| 3493 | } |
| 3494 | Button { presentation.chooseFile = true } label: { |
| 3495 | PhoneActionLabel(title: presentation.adding ? "Attaching…" : "Add file", systemImage: "paperclip") |
| 3496 | } |
| 3497 | .disabled(presentation.adding || snapshot.filesByTask == nil) |
| 3498 | .accessibilityIdentifier("addTaskFile") |
| 3499 | if snapshot.filesByTask == nil { |
| 3500 | Text("Update OpenTalon on your Mac and sync to use files.") |
| 3501 | .font(.caption).foregroundStyle(colors.muted) |
| 3502 | } |
| 3503 | if let error = presentation.error { Text(error).font(.caption).foregroundStyle(colors.muted) } |
| 3504 | } |
| 3505 | .listRowBackground(colors.card) |
| 3506 | } |
| 3507 | } |
| 3508 | |
| 3509 | @MainActor |
| 3510 | @Observable |
| 3511 | private final class PhoneFilePresentation { |
| 3512 | struct ShareFile: Identifiable { |
| 3513 | let url: URL |
| 3514 | var id: URL { url } |
| 3515 | } |
| 3516 | var chooseFile = false |
| 3517 | var previewURL: URL? |
| 3518 | var shareFile: ShareFile? |
| 3519 | private(set) var adding = false |
| 3520 | private(set) var opening: String? |
| 3521 | private(set) var error: String? |
| 3522 | |
| 3523 | func attach(_ result: Result<URL, Error>, workspace: PhoneWorkspace, taskID: String, workspaceID: UUID) async { |
| 3524 | adding = true |
| 3525 | error = nil |
| 3526 | defer { adding = false } |
| 3527 | do { |
| 3528 | let file = try await TaskFilePayload.importFile(result.get()) |
| 3529 | try workspace.attachFile(file, to: taskID, in: workspaceID) |
| 3530 | } catch { self.error = error.localizedDescription } |
| 3531 | } |
| 3532 | |
| 3533 | func open(_ file: TaskFile, workspace: PhoneWorkspace, workspaceID: UUID) async { |
| 3534 | opening = file.id |
| 3535 | error = nil |
| 3536 | defer { opening = nil } |
| 3537 | do { |
| 3538 | let url = try await workspace.openFile(file, in: workspaceID) |
| 3539 | if QLPreviewController.canPreview(url as NSURL) { previewURL = url } |
| 3540 | else { shareFile = ShareFile(url: url) } |
| 3541 | } catch { self.error = error.localizedDescription } |
| 3542 | } |
| 3543 | } |
| 3544 | |
| 3545 | private struct PhoneFilePresenter: ViewModifier { |
| 3546 | @Environment(PhoneWorkspace.self) private var workspace |
| 3547 | @Bindable var presentation: PhoneFilePresentation |
| 3548 | let taskID: String |
| 3549 | let workspaceID: UUID |
| 3550 | |
| 3551 | func body(content: Content) -> some View { |
| 3552 | content |
| 3553 | .fileImporter(isPresented: $presentation.chooseFile, allowedContentTypes: [.data]) { result in |
| 3554 | Task { await presentation.attach(result, workspace: workspace, taskID: taskID, workspaceID: workspaceID) } |
| 3555 | } |
| 3556 | .quickLookPreview($presentation.previewURL) |
| 3557 | .sheet(item: $presentation.shareFile) { file in |
| 3558 | VStack(alignment: .leading, spacing: 16) { |
| 3559 | Text(file.url.lastPathComponent).font(.headline) |
| 3560 | ShareLink(item: file.url) { |
| 3561 | Label("Share or save file", systemImage: "square.and.arrow.up") |
| 3562 | } |
| 3563 | } |
| 3564 | .padding(24) |
| 3565 | .presentationDetents([.medium]) |
| 3566 | } |
| 3567 | } |
| 3568 | } |
| 3569 | |
| 3570 | private struct CaptureView: View { |
| 3571 | private struct PreparedTask { |
| 3572 | let workspaceID: UUID |
| 3573 | let projectID: String |
| 3574 | let newProjectName: String? |
| 3575 | let title: String |
| 3576 | let notes: String |
| 3577 | let definitionOfDone: String |
| 3578 | let planMarkdown: String? |
| 3579 | let issueType: IssueType |
| 3580 | let priority: PhoneTask.Priority |
| 3581 | } |
| 3582 | |
| 3583 | @Environment(PhoneWorkspace.self) private var workspace |
| 3584 | @Environment(\.phoneColors) private var colors |
| 3585 | @Environment(\.dismiss) private var dismiss |
| 3586 | @FocusState private var ideaFocused: Bool |
| 3587 | @State private var idea = "" |
| 3588 | @State private var title = "" |
| 3589 | @State private var notes = "" |
| 3590 | @State private var definitionOfDone = "" |
| 3591 | @State private var includePlan = false |
| 3592 | @State private var project: String? |
| 3593 | @State private var priority: PhoneTask.Priority? |
| 3594 | @State private var issueType: IssueType? |
| 3595 | @State private var sendToAgent = false |
| 3596 | @State private var showSend = false |
| 3597 | @State private var dispatchQueued = false |
| 3598 | @State private var preparedTask: PreparedTask? |
| 3599 | @State private var draftRequest: Task<Void, Never>? |
| 3600 | @State private var saving = false |
| 3601 | @State private var error: String? |
| 3602 | private let onQueued: () -> Void |
| 3603 | |
| 3604 | init(initialIdea: String = "", onQueued: @escaping () -> Void = {}) { |
| 3605 | _idea = State(initialValue: initialIdea) |
| 3606 | self.onQueued = onQueued |
| 3607 | } |
| 3608 | |
| 3609 | private var trimmedIdea: String { idea.trimmingCharacters(in: .whitespacesAndNewlines) } |
| 3610 | private var editedTitle: String { title.trimmingCharacters(in: .whitespacesAndNewlines) } |
| 3611 | private var input: String { trimmedIdea.isEmpty ? editedTitle : trimmedIdea } |
| 3612 | private var tooLong: Bool { trimmedIdea.utf16.count > SuggestedTaskDetails.captureLimit } |
| 3613 | private var hasDetails: Bool { !editedTitle.isEmpty || !notes.isEmpty || !definitionOfDone.isEmpty } |
| 3614 | |
| 3615 | var body: some View { |
| 3616 | VStack(spacing: 0) { |
| 3617 | HStack(spacing: 8) { |
| 3618 | Button("Cancel") { dismiss() }.disabled(saving) |
| 3619 | Text("New task") |
| 3620 | .font(.headline) |
| 3621 | .frame(maxWidth: .infinity) |
| 3622 | .accessibilityAddTraits(.isHeader) |
| 3623 | Button(sendToAgent ? "Review send" : "Add", action: add) |
| 3624 | .disabled(input.isEmpty || tooLong || saving || draftRequest != nil |
| 3625 | || editedTitle.utf16.count > 500 || notes.utf8.count > 8000 |
| 3626 | || definitionOfDone.utf16.count > 10_000) |
| 3627 | } |
| 3628 | .buttonStyle(PhoneActionButtonStyle()) |
| 3629 | .padding(.horizontal, 20) |
| 3630 | .padding(.vertical, 12) |
| 3631 | |
| 3632 | Form { |
| 3633 | Section { |
| 3634 | TextField("Type or dictate a task", text: $idea, axis: .vertical) |
| 3635 | .lineLimit(2...5) |
| 3636 | .focused($ideaFocused) |
| 3637 | .accessibilityIdentifier("newTaskIdea") |
| 3638 | Picker("Project", selection: $project) { |
| 3639 | Text("Auto").tag(nil as String?) |
| 3640 | ForEach(workspace.snapshot?.projects ?? []) { Text($0.name).tag(Optional($0.id)) } |
| 3641 | } |
| 3642 | Picker("Priority", selection: $priority) { |
| 3643 | Text("Auto").tag(nil as PhoneTask.Priority?) |
| 3644 | ForEach(PhoneTask.Priority.allCases) { Text($0.title).tag(Optional($0)) } |
| 3645 | } |
| 3646 | Picker("Issue type", selection: Binding(get: { issueType ?? .inferred(from: idea) }, set: { issueType = $0 })) { |
| 3647 | ForEach(IssueType.allCases) { Label($0.rawValue, systemImage: $0.symbol).tag($0) } |
| 3648 | } |
| 3649 | .disabled(workspace.snapshot?.supportsTaskTypes != true) |
| 3650 | .accessibilityIdentifier("newTaskIssueType") |
| 3651 | Toggle("Include a plan", isOn: $includePlan) |
| 3652 | .tint(colors.actionAccent) |
| 3653 | .disabled(workspace.snapshot?.supportsTaskPlans != true) |
| 3654 | .accessibilityIdentifier("includeTaskPlan") |
| 3655 | } footer: { |
| 3656 | if tooLong { |
| 3657 | Text("Keep your task to 2,000 characters.").foregroundStyle(colors.danger) |
| 3658 | } |
| 3659 | } |
| 3660 | .listRowBackground(colors.card) |
| 3661 | |
| 3662 | Section { |
| 3663 | DisclosureGroup("More options") { |
| 3664 | TextField("Title (optional)", text: $title, axis: .vertical).lineLimit(1...3) |
| 3665 | TextField("Description and steps", text: $notes, axis: .vertical).lineLimit(2...6) |
| 3666 | TextField("Definition of done", text: $definitionOfDone, axis: .vertical).lineLimit(2...5) |
| 3667 | if TaskDrafting.unavailableReason == nil { |
| 3668 | Button(action: draftTicket) { |
| 3669 | if draftRequest != nil { |
| 3670 | ProgressView("Drafting on this device…") |
| 3671 | } else { |
| 3672 | PhoneActionLabel(title: "Draft with Apple Intelligence", systemImage: "sparkles") |
| 3673 | } |
| 3674 | } |
| 3675 | .buttonStyle(PhoneActionButtonStyle()) |
| 3676 | .disabled(trimmedIdea.isEmpty || tooLong || draftRequest != nil) |
| 3677 | } |
| 3678 | if workspace.snapshot?.canUseAgents == true { |
| 3679 | Toggle("Send to agent", isOn: $sendToAgent).tint(colors.actionAccent) |
| 3680 | } |
| 3681 | } |
| 3682 | } |
| 3683 | .listRowBackground(colors.card) |
| 3684 | |
| 3685 | if saving { ProgressView("Adding task…").listRowBackground(colors.card) } |
| 3686 | if let error { Text(error).foregroundStyle(colors.danger).listRowBackground(colors.card) } |
| 3687 | } |
| 3688 | .disabled(saving) |
| 3689 | .modifier(PhoneListAppearance()) |
| 3690 | .onAppear { ideaFocused = true } |
| 3691 | .onChange(of: idea) { _, value in |
| 3692 | if TaskPlan.requested(in: value), workspace.snapshot?.supportsTaskPlans == true { includePlan = true } |
| 3693 | } |
| 3694 | .onDisappear { draftRequest?.cancel() } |
| 3695 | .interactiveDismissDisabled(saving) |
| 3696 | .sheet(isPresented: $showSend, onDismiss: { |
| 3697 | preparedTask = nil |
| 3698 | if dispatchQueued { dismiss() } |
| 3699 | }) { |
| 3700 | if let snapshot = workspace.snapshot, let task = preparedTask { |
| 3701 | PhoneAgentChooser(snapshot: snapshot, taskTitle: task.title) { agent, model, comment in |
| 3702 | try queue(task, agent: agent, model: model, comment: comment) |
| 3703 | dispatchQueued = true |
| 3704 | } |
| 3705 | } |
| 3706 | } |
| 3707 | } |
| 3708 | .background(colors.canvas.ignoresSafeArea()) |
| 3709 | } |
| 3710 | |
| 3711 | private func draftTicket() { |
| 3712 | let idea = trimmedIdea |
| 3713 | ideaFocused = false |
| 3714 | error = nil |
| 3715 | draftRequest = Task { |
| 3716 | defer { draftRequest = nil } |
| 3717 | do { |
| 3718 | let draft = try await TaskDrafting.expand(idea) |
| 3719 | try Task.checkCancellation() |
| 3720 | guard trimmedIdea == idea else { return } |
| 3721 | if title.isEmpty { title = draft.title } |
| 3722 | if notes.isEmpty { notes = draft.notes } |
| 3723 | if definitionOfDone.isEmpty { definitionOfDone = draft.definitionOfDone } |
| 3724 | } catch is CancellationError { |
| 3725 | return |
| 3726 | } catch { |
| 3727 | self.error = error.localizedDescription |
| 3728 | } |
| 3729 | } |
| 3730 | } |
| 3731 | |
| 3732 | private func add() { |
| 3733 | guard let initialSnapshot = workspace.snapshot, !saving else { return } |
| 3734 | let idea = input |
| 3735 | let shouldDraft = !hasDetails && TaskDrafting.unavailableReason == nil |
| 3736 | saving = true |
| 3737 | ideaFocused = false |
| 3738 | error = nil |
| 3739 | Task { |
| 3740 | defer { saving = false } |
| 3741 | let suggestion = shouldDraft |
| 3742 | ? try? await TaskDrafting.expand(idea, projects: project == nil ? initialSnapshot.projects : nil) |
| 3743 | : nil |
| 3744 | let generated = suggestion.flatMap { $0.isUsableForCapture ? $0 : nil } |
| 3745 | let draft = generated ?? .fromIdea(idea) |
| 3746 | guard let snapshot = workspace.snapshot, snapshot.workspaceID == initialSnapshot.workspaceID, |
| 3747 | let firstProject = snapshot.projects.first else { |
| 3748 | error = "Your workspace changed. Please try again." |
| 3749 | return |
| 3750 | } |
| 3751 | let destination = project == nil |
| 3752 | ? TaskDrafting.captureDestination(in: idea, projects: snapshot.projects, suggestedName: generated?.projectName) |
| 3753 | : (projectID: project, newProjectName: nil) |
| 3754 | if snapshot.captureProjectID == nil, let newProject = destination.newProjectName, newProject != "Personal" { |
| 3755 | error = "Update OpenTalon on your Mac to create a new project." |
| 3756 | return |
| 3757 | } |
| 3758 | // Older Mac versions can still file tasks into an existing project. |
| 3759 | let newProject = snapshot.captureProjectID == nil ? nil : destination.newProjectName |
| 3760 | let projectID = destination.projectID ?? snapshot.captureProjectID ?? firstProject.id |
| 3761 | guard snapshot.projects.contains(where: { $0.id == projectID }) else { |
| 3762 | error = "Choose an available project." |
| 3763 | return |
| 3764 | } |
| 3765 | let type = issueType ?? IssueType.inferred(from: idea) |
| 3766 | guard type == .issue || snapshot.supportsTaskTypes else { |
| 3767 | error = "Update OpenTalon on your Mac to create Bug items."; return |
| 3768 | } |
| 3769 | let finalTitle = editedTitle.isEmpty ? draft.title : editedTitle |
| 3770 | let finalNotes = notes.isEmpty ? draft.notes : notes |
| 3771 | let finalDefinition = definitionOfDone.isEmpty ? draft.definitionOfDone : definitionOfDone |
| 3772 | let plan: String? |
| 3773 | if includePlan { |
| 3774 | guard snapshot.supportsTaskPlans else { error = "Update OpenTalon on your Mac to save a plan."; return } |
| 3775 | let context = "\(finalTitle)\n\(finalNotes)\nDefinition of done: \(finalDefinition)" |
| 3776 | if TaskDrafting.unavailableReason == nil { |
| 3777 | do { plan = try await TaskPlan.revise("", instruction: "Create a task plan with actionable steps and verification checks.", context: context) } |
| 3778 | catch { self.error = error.localizedDescription; return } |
| 3779 | } else { |
| 3780 | plan = TaskPlan.starter(title: finalTitle, notes: finalNotes, definitionOfDone: finalDefinition) |
| 3781 | } |
| 3782 | } else { plan = nil } |
| 3783 | let task = PreparedTask(workspaceID: snapshot.workspaceID, projectID: projectID, newProjectName: newProject, |
| 3784 | title: finalTitle, notes: finalNotes, definitionOfDone: finalDefinition, planMarkdown: plan, issueType: type, |
| 3785 | priority: priority ?? TaskDrafting.capturePriority(in: idea)) |
| 3786 | if sendToAgent { |
| 3787 | preparedTask = task |
| 3788 | showSend = true |
| 3789 | } else { |
| 3790 | do { |
| 3791 | try queue(task) |
| 3792 | dismiss() |
| 3793 | } catch { |
| 3794 | self.error = error.localizedDescription |
| 3795 | } |
| 3796 | } |
| 3797 | } |
| 3798 | } |
| 3799 | |
| 3800 | private func queue(_ task: PreparedTask, agent: PhoneAgent? = nil, model: String? = nil, comment: String? = nil) throws { |
| 3801 | guard workspace.snapshot?.workspaceID == task.workspaceID else { throw CompanionSyncError.missingWorkspace } |
| 3802 | try workspace.queue(.create( |
| 3803 | projectID: task.projectID, title: task.title, notes: task.notes, priority: task.priority, |
| 3804 | sendToAgent: agent != nil, definitionOfDone: task.definitionOfDone.isEmpty ? nil : task.definitionOfDone, |
| 3805 | agent: agent, model: model, dispatchComment: comment, newProjectName: task.newProjectName, |
| 3806 | planMarkdown: task.planMarkdown, issueType: task.issueType |
| 3807 | )) |
| 3808 | onQueued() |
| 3809 | } |
| 3810 | } |
| 3811 | |
| 3812 | private struct PhoneAssistantView: View { |
| 3813 | private struct Review: Identifiable { |
| 3814 | let id = UUID() |
| 3815 | let task: PhoneTask |
| 3816 | let operation: String |
| 3817 | } |
| 3818 | private struct ProposedPlan: Identifiable { |
| 3819 | let id = UUID() |
| 3820 | let task: PhoneTask |
| 3821 | let original: String |
| 3822 | let proposed: String |
| 3823 | } |
| 3824 | @Environment(PhoneWorkspace.self) private var workspace |
| 3825 | @Environment(\.phoneColors) private var colors |
| 3826 | @Environment(\.dismiss) private var dismiss |
| 3827 | @State private var history: PhoneAssistantHistory |
| 3828 | @State private var input = "" |
| 3829 | @State private var generation: Task<Void, Never>? |
| 3830 | @State private var error: String? |
| 3831 | @State private var results = [TaskAssistantCommand: String]() |
| 3832 | @State private var review: Review? |
| 3833 | @State private var proposedPlan: ProposedPlan? |
| 3834 | @State private var openedTask: String? |
| 3835 | @State private var deleteAll = false |
| 3836 | @State private var deleteCurrent = false |
| 3837 | @State private var showReviewConfirmation = false |
| 3838 | @FocusState private var inputFocused: Bool |
| 3839 | let workspaceID: UUID |
| 3840 | |
| 3841 | init(workspaceID: UUID) { |
| 3842 | self.workspaceID = workspaceID |
| 3843 | _history = State(initialValue: PhoneAssistantHistory(workspaceID: workspaceID)) |
| 3844 | } |
| 3845 | |
| 3846 | var body: some View { |
| 3847 | NavigationStack { |
| 3848 | VStack(spacing: 0) { |
| 3849 | header |
| 3850 | ScrollViewReader { scroll in |
| 3851 | ScrollView { |
| 3852 | LazyVStack(alignment: .leading, spacing: 14) { |
| 3853 | if (history.current?.messages ?? []).isEmpty { examples } |
| 3854 | ForEach(history.current?.messages ?? []) { message in |
| 3855 | messageRow(message).id(message.id) |
| 3856 | } |
| 3857 | if generation != nil { ProgressView("Working on this device…") } |
| 3858 | if let error = error ?? history.error { |
| 3859 | assistantNotice(error) |
| 3860 | } |
| 3861 | if let reason = TaskDrafting.unavailableReason { |
| 3862 | Text(reason).font(.footnote).foregroundStyle(colors.muted) |
| 3863 | } |
| 3864 | Text("Apple Intelligence runs on this device. Task changes sync through your existing Mac connection.") |
| 3865 | .font(.caption).foregroundStyle(colors.muted) |
| 3866 | } |
| 3867 | .padding(20) |
| 3868 | } |
| 3869 | .scrollDismissesKeyboard(.interactively) |
| 3870 | .simultaneousGesture(TapGesture().onEnded { inputFocused = false }) |
| 3871 | .onChange(of: history.current?.messages.count) { |
| 3872 | if let last = history.current?.messages.last { scroll.scrollTo(last.id, anchor: .bottom) } |
| 3873 | } |
| 3874 | } |
| 3875 | composer |
| 3876 | } |
| 3877 | .background(colors.canvas.ignoresSafeArea()) |
| 3878 | .foregroundStyle(colors.text) |
| 3879 | .navigationBarHidden(true) |
| 3880 | .navigationDestination(isPresented: Binding(get: { openedTask != nil }, set: { if !$0 { openedTask = nil } })) { |
| 3881 | if let openedTask { TaskView(taskID: openedTask).navigationBarHidden(false) } |
| 3882 | } |
| 3883 | } |
| 3884 | .buttonStyle(PhoneActionButtonStyle()) |
| 3885 | .phoneConfirmation("Delete all chats?", isPresented: $deleteAll, |
| 3886 | message: "This deletes your saved on-device chats. Your tasks and plans stay unchanged.", |
| 3887 | confirm: "Delete All Chats", role: .destructive) { |
| 3888 | do { try history.deleteAll() } catch { self.error = error.localizedDescription } |
| 3889 | } |
| 3890 | .phoneConfirmation("Delete this chat?", isPresented: $deleteCurrent, |
| 3891 | message: "Your tasks and plans stay unchanged.", confirm: "Delete Chat", role: .destructive) { |
| 3892 | if let id = history.current?.id { |
| 3893 | do { try history.deleteChat(id) } catch { self.error = error.localizedDescription } |
| 3894 | } |
| 3895 | } |
| 3896 | .phoneConfirmation(confirmationTitle, isPresented: $showReviewConfirmation, |
| 3897 | message: confirmationMessage, confirm: confirmationButton) { confirmReview() } |
| 3898 | .sheet(isPresented: Binding(get: { review?.operation == "send" }, set: { if !$0 { review = nil } })) { |
| 3899 | if let review, let snapshot = workspace.snapshot, snapshot.workspaceID == workspaceID { |
| 3900 | PhoneAgentChooser(snapshot: snapshot, taskTitle: review.task.title) { agent, model, comment in |
| 3901 | guard let current = workspace.snapshot?.tasks.first(where: { $0.id == review.task.id }) else { return } |
| 3902 | try workspace.queueField(.status(.sent, agent: agent, model: model, dispatchComment: comment), |
| 3903 | for: current, in: workspaceID) |
| 3904 | try history.append(.init(role: "action", text: "Send to agent queued for Mac.", taskID: current.id)) |
| 3905 | } |
| 3906 | } |
| 3907 | } |
| 3908 | .sheet(item: $proposedPlan) { proposal in |
| 3909 | PlanDocumentView(markdown: proposal.original, proposal: proposal.proposed, |
| 3910 | reference: proposal.task.displayTaskID ?? "Task", |
| 3911 | context: proposal.task.title + "\n" + proposal.task.notes, colors: colors) { markdown in |
| 3912 | try workspace.savePlan(markdown, expected: proposal.original, for: proposal.task.id, in: workspaceID) |
| 3913 | try history.append(.init(role: "action", text: "Plan saved locally and queued for Mac.", taskID: proposal.task.id)) |
| 3914 | } |
| 3915 | } |
| 3916 | .onDisappear { generation?.cancel() } |
| 3917 | } |
| 3918 | |
| 3919 | private var header: some View { |
| 3920 | HStack { |
| 3921 | VStack(alignment: .leading, spacing: 3) { |
| 3922 | Text("Ask OpenTalon").font(.headline) |
| 3923 | if let chat = history.current { |
| 3924 | Text(chat.title).font(.caption).foregroundStyle(colors.muted).lineLimit(1) |
| 3925 | if let date = chat.lastUpdated { PhoneDateCaption("Last updated", date: date) } |
| 3926 | } |
| 3927 | } |
| 3928 | Spacer() |
| 3929 | Menu { |
| 3930 | Button("New chat", systemImage: "plus") { do { try history.newChat() } catch { self.error = error.localizedDescription } } |
| 3931 | ForEach(history.chats) { chat in |
| 3932 | Button(chat.title) { do { try history.select(chat.id) } catch { self.error = error.localizedDescription } } |
| 3933 | } |
| 3934 | Divider() |
| 3935 | Button("Delete this chat", role: .destructive) { deleteCurrent = true }.disabled(history.current == nil) |
| 3936 | Button("Delete all chats", role: .destructive) { deleteAll = true } |
| 3937 | .disabled(history.chats.isEmpty && history.error == nil) |
| 3938 | } label: { Image(systemName: "clock.arrow.circlepath").foregroundStyle(colors.actionAccent) } |
| 3939 | .accessibilityLabel("Chat history") |
| 3940 | .disabled(generation != nil) |
| 3941 | Button("Close") { generation?.cancel(); dismiss() } |
| 3942 | } |
| 3943 | .padding(20) |
| 3944 | .contentShape(Rectangle()) |
| 3945 | .simultaneousGesture(TapGesture().onEnded { inputFocused = false }) |
| 3946 | } |
| 3947 | |
| 3948 | private func assistantNotice(_ message: String) -> some View { |
| 3949 | HStack(alignment: .top, spacing: 12) { |
| 3950 | Image(systemName: "exclamationmark.bubble").foregroundStyle(colors.actionAccent) |
| 3951 | VStack(alignment: .leading, spacing: 6) { |
| 3952 | Text("Request needs attention").font(.subheadline.bold()) |
| 3953 | Text(message).font(.footnote).foregroundStyle(colors.muted) |
| 3954 | if let request = history.current?.messages.last(where: { $0.role == "user" })?.text { |
| 3955 | Button("Edit request") { input = request; error = nil; inputFocused = true } |
| 3956 | } |
| 3957 | } |
| 3958 | Spacer(minLength: 0) |
| 3959 | Button("Dismiss") { error = nil }.disabled(error == nil) |
| 3960 | } |
| 3961 | .padding(14).frame(maxWidth: .infinity, alignment: .leading) |
| 3962 | .background(colors.card, in: RoundedRectangle(cornerRadius: 18)) |
| 3963 | } |
| 3964 | |
| 3965 | private var examples: some View { |
| 3966 | VStack(alignment: .leading, spacing: 12) { |
| 3967 | Text("Manage your tasks by chatting").font(.title3.bold()) |
| 3968 | Text("Find tasks, change priorities, move work between projects, or draft a plan.") |
| 3969 | .foregroundStyle(colors.muted) |
| 3970 | ForEach(["What are my urgent tasks?", "Create a task with a plan to review my weekly goals", "Which tasks are in progress?"], id: \.self) { example in |
| 3971 | Button(example) { input = example; send() } |
| 3972 | .disabled(TaskDrafting.unavailableReason != nil || generation != nil) |
| 3973 | } |
| 3974 | } |
| 3975 | } |
| 3976 | |
| 3977 | private func messageRow(_ message: PhoneAssistantHistory.Message) -> some View { |
| 3978 | VStack(alignment: .leading, spacing: 8) { |
| 3979 | Text(message.role == "user" ? "You" : message.role == "action" ? "App activity" : "OpenTalon") |
| 3980 | .font(.caption.weight(.semibold)).foregroundStyle(colors.muted) |
| 3981 | Text(message.text).textSelection(.enabled).accessibilityIdentifier("assistantMessage-" + message.role) |
| 3982 | if let date = message.savedAt { PhoneDateCaption("Saved", date: date) } |
| 3983 | if let taskID = message.taskID { |
| 3984 | HStack { |
| 3985 | Button("Open task") { openedTask = taskID } |
| 3986 | if message.planMarkdown != nil { |
| 3987 | Button("Review plan") { openProposal(message) } |
| 3988 | } |
| 3989 | } |
| 3990 | } |
| 3991 | } |
| 3992 | .padding(14).frame(maxWidth: .infinity, alignment: .leading) |
| 3993 | .background(colors.card, in: RoundedRectangle(cornerRadius: 18)) |
| 3994 | } |
| 3995 | |
| 3996 | private var composer: some View { |
| 3997 | HStack(alignment: .bottom, spacing: 12) { |
| 3998 | TextField("Ask about your tasks or tell me what to change", text: $input, axis: .vertical) |
| 3999 | .lineLimit(1...4).focused($inputFocused) |
| 4000 | .padding(12).background(colors.card, in: RoundedRectangle(cornerRadius: 14)) |
| 4001 | .accessibilityIdentifier("assistantInput") |
| 4002 | if generation != nil { |
| 4003 | Button("Stop") { generation?.cancel() } |
| 4004 | } else { |
| 4005 | Button("Send", action: send) |
| 4006 | .disabled(input.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !history.canWrite || |
| 4007 | TaskDrafting.unavailableReason != nil || input.utf16.count > 2_000) |
| 4008 | } |
| 4009 | } |
| 4010 | .padding(20) |
| 4011 | } |
| 4012 | |
| 4013 | private func send() { |
| 4014 | let message = input.trimmingCharacters(in: .whitespacesAndNewlines) |
| 4015 | guard generation == nil, !message.isEmpty, message.utf16.count <= 2_000, history.canWrite, |
| 4016 | workspace.snapshot?.workspaceID == workspaceID else { return } |
| 4017 | guard #available(iOS 26, *) else { return } |
| 4018 | error = nil; results = [:]; inputFocused = false |
| 4019 | do { try history.append(.init(role: "user", text: message)) } |
| 4020 | catch { self.error = error.localizedDescription; return } |
| 4021 | input = "" |
| 4022 | let recent = (history.current?.messages.dropLast().suffix(6) ?? []).map { "\($0.role): \($0.text)" }.joined(separator: "\n") |
| 4023 | generation = Task { |
| 4024 | defer { generation = nil } |
| 4025 | do { |
| 4026 | let response = try await OnDeviceTaskAssistant.respond(to: message, history: recent, search: search) { command in |
| 4027 | try await execute(command, requestedBy: message) |
| 4028 | } |
| 4029 | if history.current?.messages.last?.text != response { |
| 4030 | try history.append(.init(role: "assistant", text: response)) |
| 4031 | } |
| 4032 | } catch is CancellationError { |
| 4033 | try? history.append(.init(role: "assistant", text: "Stopped. Any changes already listed in App activity remain saved.")) |
| 4034 | } catch { |
| 4035 | self.error = error.localizedDescription |
| 4036 | try? history.append(.init(role: "assistant", text: "I couldn’t finish this reply. Check App activity for any changes already queued.")) |
| 4037 | } |
| 4038 | } |
| 4039 | } |
| 4040 | |
| 4041 | private func search(_ query: String) throws -> String { |
| 4042 | guard let snapshot = workspace.snapshot, snapshot.workspaceID == workspaceID else { throw CompanionSyncError.missingWorkspace } |
| 4043 | let query = TaskReference.normalized(in: query) ?? query.trimmingCharacters(in: .whitespacesAndNewlines) |
| 4044 | let words = query.split(whereSeparator: \.isWhitespace).map(String.init) |
| 4045 | .filter { !["task", "tasks", "my", "the", "all"].contains($0.lowercased()) } |
| 4046 | let matches = workspace.newestTasks(workspace.visibleTasks.filter { task in |
| 4047 | if query.isEmpty { return !workspace.isArchived(task) && workspace.displayedStatus(for: task) != .done } |
| 4048 | let fields = [task.id, task.taskKey ?? "", task.displayTaskID ?? "", workspace.displayedText(for: task, field: .title), |
| 4049 | workspace.projectName(workspace.displayedProject(for: task)), task.notes, |
| 4050 | workspace.displayedStatus(for: task).rawValue, workspace.displayedPriority(for: task).rawValue, |
| 4051 | workspace.displayedIssueType(for: task).rawValue, |
| 4052 | workspace.displayedPriority(for: task) == .urgent ? "critical" : ""] |
| 4053 | return words.allSatisfy { word in fields.contains { $0.localizedStandardContains(word) } } |
| 4054 | }) |
| 4055 | let tasks: [[String: Any]] = matches.prefix(8).map { task in |
| 4056 | ["id": task.id, "taskID": task.displayTaskID ?? "", "title": workspace.displayedText(for: task, field: .title), |
| 4057 | "projectID": workspace.displayedProject(for: task), |
| 4058 | "projectName": workspace.projectName(workspace.displayedProject(for: task)), |
| 4059 | "status": workspace.displayedStatus(for: task).rawValue, |
| 4060 | "priority": workspace.displayedPriority(for: task).rawValue, |
| 4061 | "issueType": workspace.displayedIssueType(for: task).rawValue, |
| 4062 | "dueDate": workspace.displayedDueDate(for: task) ?? "", "archived": workspace.isArchived(task), |
| 4063 | "notes": matches.count == 1 ? String(workspace.displayedText(for: task, field: .notes).prefix(800)) : "Search by task ID to read notes.", |
| 4064 | "planMarkdown": matches.count == 1 ? String(workspace.displayedPlan(for: task).prefix(2_000)) : "Search by task ID to read the plan.", |
| 4065 | "planCharacters": workspace.displayedPlan(for: task).utf16.count] |
| 4066 | } |
| 4067 | let data: [String: Any] = ["projects": snapshot.projects.prefix(20).map { ["id": $0.id, "name": $0.name] }, "tasks": tasks, |
| 4068 | "matchingCount": matches.count, "shownCount": tasks.count] |
| 4069 | return String(decoding: try JSONSerialization.data(withJSONObject: data), as: UTF8.self) |
| 4070 | } |
| 4071 | |
| 4072 | private func execute(_ command: TaskAssistantCommand, requestedBy message: String) async throws -> String { |
| 4073 | try Task.checkCancellation() |
| 4074 | guard let snapshot = workspace.snapshot, snapshot.workspaceID == workspaceID, snapshot.supportsTaskPlans else { |
| 4075 | throw AssistantError.message("Update OpenTalon on your Mac and sync before using assistant actions.") |
| 4076 | } |
| 4077 | if let previous = results[command] { return previous } |
| 4078 | guard results.count < 8, command.value.utf16.count <= 100_000, command.notes.utf16.count <= 100_000 else { |
| 4079 | throw AssistantError.message("Make fewer changes in one message, or shorten the text.") |
| 4080 | } |
| 4081 | let result: String |
| 4082 | if command.operation == "createProject" { |
| 4083 | let name = command.value.trimmingCharacters(in: .whitespacesAndNewlines) |
| 4084 | guard !name.isEmpty, name.utf16.count <= 100, message.localizedStandardContains(name) else { |
| 4085 | throw AssistantError.message("Ask the user for the new project's name.") |
| 4086 | } |
| 4087 | try workspace.queue(.createProject(name: name)) |
| 4088 | result = "Project \(name) queued for Mac." |
| 4089 | } else if command.operation == "create" { |
| 4090 | let title = command.value.trimmingCharacters(in: .whitespacesAndNewlines) |
| 4091 | guard !title.isEmpty, title.utf16.count <= 500, let first = snapshot.projects.first else { |
| 4092 | throw AssistantError.message("A task needs a title of no more than 500 characters and an available project.") |
| 4093 | } |
| 4094 | let projectID = command.projectID(in: snapshot.projects, requestedBy: message) |
| 4095 | let existing = snapshot.projects.first { $0.id == projectID } |
| 4096 | let personal = snapshot.projects.first { $0.name.caseInsensitiveCompare("Personal") == .orderedSame } |
| 4097 | let newProject: String? |
| 4098 | if existing == nil, !command.project.isEmpty { |
| 4099 | guard command.project.utf16.count <= 100, message.localizedStandardContains(command.project) else { |
| 4100 | throw AssistantError.message("Ask the user which project to use.") |
| 4101 | } |
| 4102 | newProject = command.project |
| 4103 | } else { newProject = existing == nil && personal == nil ? "Personal" : nil } |
| 4104 | guard IssueType.inferred(from: message) != .bug || snapshot.supportsTaskTypes else { |
| 4105 | throw AssistantError.message("Update OpenTalon on your Mac to create Bug items.") |
| 4106 | } |
| 4107 | let plan = TaskPlan.requested(in: message) && !command.planMarkdown.isEmpty ? command.planMarkdown : nil |
| 4108 | if let plan { try TaskPlan.validate(plan) } |
| 4109 | try workspace.queue(.create(projectID: existing?.id ?? personal?.id ?? first.id, title: title, |
| 4110 | notes: command.notes, priority: TaskDrafting.capturePriority(in: message), |
| 4111 | sendToAgent: false, newProjectName: newProject, planMarkdown: plan, |
| 4112 | issueType: IssueType.inferred(from: message))) |
| 4113 | result = "Task \(title) saved locally and queued for Mac. Its task ID will appear after the Mac accepts it." |
| 4114 | } else { |
| 4115 | guard let task = snapshot.tasks.first(where: { |
| 4116 | $0.id == command.taskID || $0.displayTaskID?.caseInsensitiveCompare(command.taskID) == .orderedSame |
| 4117 | }), !workspace.isTrashed(task) else { throw AssistantError.message("That task isn't available. Search again and use an exact task ID.") } |
| 4118 | switch command.operation { |
| 4119 | case "project": |
| 4120 | guard let project = snapshot.projects.first(where: { $0.id == command.value }) else { |
| 4121 | throw AssistantError.message("Choose an existing project returned by search.") |
| 4122 | } |
| 4123 | try workspace.queueField(.project(project.id), for: task, in: workspaceID) |
| 4124 | case "issueType": |
| 4125 | guard snapshot.supportsTaskTypes, let type = IssueType(rawValue: command.value) else { |
| 4126 | throw AssistantError.message("Choose Issue or Bug, and update OpenTalon on your Mac if needed.") |
| 4127 | } |
| 4128 | try workspace.queueField(.issueType(type), for: task, in: workspaceID) |
| 4129 | case "priority": |
| 4130 | guard let priority = PhoneTask.Priority(rawValue: command.value) else { throw AssistantError.message("Choose a valid priority.") } |
| 4131 | try workspace.queueField(.priority(priority), for: task, in: workspaceID) |
| 4132 | case "status": |
| 4133 | guard let status = PhoneTask.Status(rawValue: command.value), status != .sent else { |
| 4134 | throw AssistantError.message("Use To do, In progress or Done. Sending to an agent needs the send dialog.") |
| 4135 | } |
| 4136 | if status == .done, workspace.completionNeedsConfirmation(for: task) { |
| 4137 | review = Review(task: task, operation: "done") |
| 4138 | showReviewConfirmation = true |
| 4139 | result = "Waiting for the user's Mark Done confirmation." |
| 4140 | results[command] = result |
| 4141 | return result |
| 4142 | } |
| 4143 | try workspace.queueField(.status(status), for: task, in: workspaceID) |
| 4144 | case "dueDate": |
| 4145 | let date = command.value.isEmpty ? nil : command.value |
| 4146 | guard date == nil || date.flatMap(CalendarDay.date).map(CalendarDay.key) == date else { |
| 4147 | throw AssistantError.message("Choose a valid YYYY-MM-DD due date.") |
| 4148 | } |
| 4149 | try workspace.queueField(.dueDate(date), for: task, in: workspaceID) |
| 4150 | case "title": |
| 4151 | guard !command.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, command.value.utf16.count <= 500 else { |
| 4152 | throw AssistantError.message("Keep the task title between 1 and 500 characters.") |
| 4153 | } |
| 4154 | try workspace.queueField(.title(command.value), for: task, in: workspaceID) |
| 4155 | case "notes": try workspace.queueField(.notes(command.value), for: task, in: workspaceID) |
| 4156 | case "definitionOfDone": |
| 4157 | guard command.value.utf16.count <= 10_000 else { throw AssistantError.message("Keep the definition of done to 10,000 characters.") } |
| 4158 | try workspace.queueField(.definitionOfDone(command.value), for: task, in: workspaceID) |
| 4159 | case "plan": |
| 4160 | guard workspace.displayedPlan(for: task).utf16.count <= 2_000 else { |
| 4161 | throw AssistantError.message("This plan is too long to revise safely in chat. Open the task's Plan editor to revise the complete document.") |
| 4162 | } |
| 4163 | guard !command.planMarkdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { |
| 4164 | throw AssistantError.message("Provide the complete proposed Markdown plan.") |
| 4165 | } |
| 4166 | try TaskPlan.validate(command.planMarkdown) |
| 4167 | try history.append(.init(role: "plan", text: "A proposed plan is ready to review. The saved plan is unchanged.", |
| 4168 | taskID: task.id, planMarkdown: command.planMarkdown, |
| 4169 | expectedMarkdown: workspace.displayedPlan(for: task))) |
| 4170 | result = "Plan proposal ready. The user must open Review plan, apply the revision and Save." |
| 4171 | results[command] = result |
| 4172 | return result |
| 4173 | case "send", "archive", "trash": |
| 4174 | if command.operation == "send", workspace.snapshot?.canUseAgents != true { |
| 4175 | throw AssistantError.message("Connect MCP in Settings on your Mac to use agents.") |
| 4176 | } |
| 4177 | guard !showReviewConfirmation && review?.operation != "send" else { |
| 4178 | throw AssistantError.message("Finish the current review dialog before starting another.") |
| 4179 | } |
| 4180 | review = Review(task: task, operation: command.operation) |
| 4181 | showReviewConfirmation = command.operation != "send" |
| 4182 | result = "Waiting for the user to finish the \(command.operation) dialog. No action has been sent yet." |
| 4183 | results[command] = result |
| 4184 | return result |
| 4185 | default: throw AssistantError.message("That operation isn't supported.") |
| 4186 | } |
| 4187 | let detail = ["priority", "status", "dueDate", "title", "issueType"].contains(command.operation) && !command.value.isEmpty |
| 4188 | ? " → \(command.value)" : "" |
| 4189 | result = "\(task.displayTaskID ?? task.title): \(command.operation)\(detail) saved locally and queued for Mac." |
| 4190 | try history.append(.init(role: "action", text: result, taskID: task.id)) |
| 4191 | } |
| 4192 | if command.operation == "create" || command.operation == "createProject" { try history.append(.init(role: "action", text: result)) } |
| 4193 | results[command] = result |
| 4194 | return result |
| 4195 | } |
| 4196 | |
| 4197 | private func openProposal(_ message: PhoneAssistantHistory.Message) { |
| 4198 | guard let task = workspace.snapshot?.tasks.first(where: { $0.id == message.taskID }), |
| 4199 | let plan = message.planMarkdown, let original = message.expectedMarkdown else { return } |
| 4200 | guard workspace.displayedPlan(for: task) == original else { |
| 4201 | error = "The saved plan changed after this proposal. Ask for a fresh revision; this proposal remains in your chat." |
| 4202 | return |
| 4203 | } |
| 4204 | proposedPlan = ProposedPlan(task: task, original: original, proposed: plan) |
| 4205 | } |
| 4206 | |
| 4207 | private var confirmationTitle: String { |
| 4208 | review?.operation == "done" ? "Mark this task done anyway?" : review?.operation == "archive" ? "Archive this task?" : "Send this task to Trash?" |
| 4209 | } |
| 4210 | private var confirmationButton: String { |
| 4211 | review?.operation == "done" ? "Mark Done" : review?.operation == "archive" ? "Archive Task" : "Send to Trash" |
| 4212 | } |
| 4213 | private var confirmationMessage: String { |
| 4214 | guard let review else { return "" } |
| 4215 | return "\(review.task.title)\nAny active agent run will stop." |
| 4216 | } |
| 4217 | private func confirmReview() { |
| 4218 | guard let review, let snapshot = workspace.snapshot, snapshot.workspaceID == workspaceID, |
| 4219 | let task = snapshot.tasks.first(where: { $0.id == review.task.id }) else { return } |
| 4220 | do { |
| 4221 | if review.operation == "done" { try workspace.markDone(task) } |
| 4222 | else { try workspace.queue(.organizeTask(taskID: task.id, destination: review.operation == "archive" ? .archive : .trash)) } |
| 4223 | try history.append(.init(role: "action", text: "\(confirmationButton) confirmed and queued for Mac.", taskID: task.id)) |
| 4224 | } catch { self.error = error.localizedDescription } |
| 4225 | self.review = nil |
| 4226 | } |
| 4227 | |
| 4228 | private enum AssistantError: LocalizedError { |
| 4229 | case message(String) |
| 4230 | var errorDescription: String? { if case .message(let text) = self { text } else { "Try again." } } |
| 4231 | } |
| 4232 | } |