Branchwell

OpenTalon / app · opentalon.ai / native / Sources / OpenTalon / Sheets.swift

Raw 25.4 KB on d752fc53b5caa0d12214a7b5a145b0c32ef811f0
1import AppKit
2import CompanionCore
3import SwiftUI
4
5struct SheetContent: View {
6 @Environment(WorkspaceModel.self) private var model
7 @Environment(\.palette) private var palette
8
9 var body: some View {
10 Group {
11 switch model.sheet {
12 case .settings: SettingsView()
13 case .connectionIntroduction: ConnectionIntroduction()
14 case .connectionSetup:
15 VStack(alignment: .leading, spacing: 0) {
16 SheetTitle(title: "Connect an agent").padding(24)
17 Divider()
18 ThemedScrollView(track: palette.panel) {
19 ConnectionSetup(showsTitle: false).padding(24)
20 }
21 }
22 .frame(width: 610, height: model.canUseAgents ? 535 : 250)
23 .toggleStyle(GlassToggleStyle())
24 case .agentChat: AgentChatView()
25 case .project(let board): ProjectEditor(board: board)
26 case .projectFolder(let board): ProjectFolderEditor(board: board)
27 case .task(let status): NewTaskView(status: status, board: model.board?.id ?? model.selectedBoard)
28 case .send: SendView()
29 case .icon(let board): IconPicker(board: board)
30 case .preview(let preview): PreviewView(preview: preview)
31 case nil: EmptyView()
32 }
33 }
34 .id(model.sheet?.id)
35 .foregroundStyle(palette.text)
36 .tint(palette.accent)
37 .buttonStyle(GlassActionStyle())
38 .background(palette.panel)
39 }
40}
41
42struct SheetTitle: View {
43 @Environment(WorkspaceModel.self) private var model
44 @Environment(\.palette) private var palette
45 let title: String
46 var close: (() -> Void)?
47 var body: some View {
48 HStack {
49 Text(title).font(palette.display(27)).accessibilityAddTraits(.isHeader)
50 Spacer()
51 IconButton(symbol: "xmark", label: "Close \(title)") {
52 if let close { close() }
53 else { model.sheet = nil }
54 }
55 }
56 }
57}
58
59private struct ProjectEditor: View {
60 @Environment(WorkspaceModel.self) private var model
61 @Environment(\.palette) private var palette
62 @State private var name: String
63 @State private var busy = false
64 @State private var error: String?
65 @FocusState private var focus: Bool
66 let board: Board?
67
68 init(board: Board?) {
69 self.board = board
70 _name = State(initialValue: board?.name ?? "")
71 }
72
73 var body: some View {
74 VStack(alignment: .leading, spacing: 15) {
75 SheetTitle(title: board == nil ? "New project" : "Rename project")
76 Text(board == nil ? "Give your next project a little space." : "Choose a new name for this project.")
77 .foregroundStyle(palette.muted)
78 TextField("Project name", text: $name)
79 .textFieldStyle(.plain)
80 .padding(.horizontal, 11)
81 .frame(height: 35)
82 .surface(9)
83 .focused($focus)
84 if let error { Text(error).font(.caption).foregroundStyle(palette.danger) }
85 HStack {
86 Spacer()
87 Button("Cancel") { model.sheet = nil }.keyboardShortcut(.cancelAction)
88 Button(board == nil ? "Create project" : "Save", action: save)
89 .glassPrimary()
90 .keyboardShortcut(.defaultAction)
91 .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
92 }
93 }
94 .disabled(busy)
95 .padding(24)
96 .frame(width: 410)
97 .onAppear { focus = true }
98 }
99
100 private func save() {
101 busy = true
102 Task {
103 defer { busy = false }
104 do {
105 if let board {
106 try await model.mutate("rename_board", ["id": board.id, "expectedRevision": board.revision, "name": name])
107 } else {
108 let result: BoardResponse = try await model.write("create_board", ["name": name])
109 model.navigate(.board(result.board.id))
110 }
111 model.sheet = nil
112 } catch let failure { error = failure.localizedDescription }
113 }
114 }
115}
116
117private struct NewTaskView: View {
118 @Environment(WorkspaceModel.self) private var model
119 @Environment(\.palette) private var palette
120 @State private var idea = ""
121 @State private var notes = ""
122 @State private var definitionOfDone = ""
123 @State private var includePlan = false
124 @State private var issueType: IssueType?
125 @State private var detailsExpanded = false
126 @State private var draftRequest: Task<Void, Never>?
127 @State private var draftError: String?
128 @State private var board: String
129 @State private var priority = Priority.none
130 @State private var busy = false
131 @State private var error: String?
132 @FocusState private var focus: Bool
133 let status: WorkStatus
134
135 init(status: WorkStatus, board: String?) {
136 self.status = status
137 _board = State(initialValue: board ?? "")
138 }
139
140 private var taskTitle: String {
141 idea.components(separatedBy: .newlines)
142 .map { $0.trimmingCharacters(in: .whitespaces) }
143 .filter { !$0.isEmpty }
144 .joined(separator: " ")
145 }
146
147 private var canSave: Bool { !board.isEmpty && !taskTitle.isEmpty && taskTitle.utf16.count <= 500 }
148
149 var body: some View {
150 VStack(alignment: .leading, spacing: 20) {
151 VStack(alignment: .leading, spacing: 10) {
152 SheetTitle(title: "New task")
153 HStack(spacing: 8) {
154 Text("Status").foregroundStyle(palette.muted)
155 Text(status.rawValue).fontWeight(.semibold)
156 }
157 .font(.system(size: 13))
158 .accessibilityElement(children: .ignore)
159 .accessibilityLabel("Status")
160 .accessibilityValue(status.rawValue)
161 }
162
163 VStack(alignment: .leading, spacing: 7) {
164 HStack {
165 Text("Task description").font(.system(size: 12, weight: .semibold))
166 Spacer()
167 if draftRequest != nil {
168 ProgressView().controlSize(.small)
169 .accessibilityLabel("Drafting task details")
170 }
171 Button(action: draftDetails) {
172 Label(draftRequest == nil ? "Draft with AI" : "Drafting…", systemImage: "sparkles")
173 }
174 .buttonStyle(GlassActionStyle())
175 .disabled(!canSave || draftRequest != nil || (!notes.isEmpty && !definitionOfDone.isEmpty))
176 .help("Draft empty detail fields on this Mac with Apple Intelligence")
177 }
178 TextField("What needs doing?", text: $idea, axis: .vertical)
179 .textFieldStyle(.plain)
180 .font(.system(size: 16))
181 .lineLimit(2...3)
182 .padding(.horizontal, 13)
183 .padding(.vertical, 12)
184 .surface(10)
185 .overlay {
186 RoundedRectangle(cornerRadius: 10)
187 .strokeBorder(palette.accent.opacity(focus ? 0.75 : 0), lineWidth: 1.5)
188 .allowsHitTesting(false)
189 }
190 .accessibilityLabel("Task description")
191 .focused($focus)
192 .disabled(draftRequest != nil)
193 if taskTitle.utf16.count > 500 {
194 Text("Keep the description to 500 characters. You can add more context in Task details.")
195 .font(.caption).foregroundStyle(palette.danger)
196 }
197 if let draftError { Text(draftError).font(.caption).foregroundStyle(palette.danger) }
198 }
199
200 HStack(spacing: 10) {
201 BoardDropdown(selection: $board, title: "Project", symbol: "folder",
202 choices: model.boards.map(\.id), label: model.projectName)
203 BoardDropdown(selection: $priority, title: "Priority", symbol: "flag",
204 choices: Priority.allCases, label: \.label)
205 }
206
207 BoardDropdown(selection: Binding(get: { issueType ?? .inferred(from: idea) }, set: { issueType = $0 }),
208 title: "Issue type", symbol: (issueType ?? .inferred(from: idea)).symbol,
209 choices: IssueType.allCases, label: \.rawValue)
210
211 DisclosureGroup("Task details", isExpanded: $detailsExpanded) {
212 VStack(alignment: .leading, spacing: 10) {
213 detailField("Description and steps", text: $notes, height: 92)
214 detailField("Definition of done", text: $definitionOfDone, height: 62)
215 Toggle("Include a plan", isOn: $includePlan).tint(palette.actionAccent)
216 }
217 .padding(.top, 10)
218 .disabled(draftRequest != nil)
219 }
220 .font(.system(size: 12, weight: .semibold))
221
222 if let error { Text(error).font(.caption).foregroundStyle(palette.danger) }
223 Rectangle().fill(palette.line).frame(height: 1)
224 HStack(spacing: 10) {
225 Spacer()
226 Button("Cancel") { model.sheet = nil }
227 .keyboardShortcut(.cancelAction)
228 Button(status == .sent ? "Create and send" : "Create task", action: save)
229 .glassPrimary()
230 .keyboardShortcut(.return, modifiers: .command)
231 .disabled(!canSave || draftRequest != nil)
232 }
233 }
234 .disabled(busy)
235 .padding(27)
236 .frame(width: 492)
237 .onAppear { focus = true }
238 .onDisappear { draftRequest?.cancel() }
239 }
240
241 private func detailField(_ title: String, text: Binding<String>, height: CGFloat) -> some View {
242 VStack(alignment: .leading, spacing: 5) {
243 Text(title).font(.system(size: 11, weight: .medium)).foregroundStyle(palette.muted)
244 TextEditor(text: text)
245 .font(.system(size: 13))
246 .scrollContentBackground(.hidden)
247 .padding(7)
248 .frame(height: height)
249 .surface(8)
250 .accessibilityLabel(title)
251 }
252 }
253
254 private func draftDetails() {
255 guard draftRequest == nil, canSave else { return }
256 let request = idea
257 draftError = nil
258 draftRequest = Task {
259 defer { draftRequest = nil }
260 do {
261 let draft = try await TaskDrafting.expand(request)
262 try Task.checkCancellation()
263 if notes.isEmpty { notes = draft.notes }
264 if definitionOfDone.isEmpty { definitionOfDone = draft.definitionOfDone }
265 detailsExpanded = true
266 } catch is CancellationError {
267 return
268 } catch {
269 draftError = error.localizedDescription
270 detailsExpanded = true
271 }
272 }
273 }
274
275 private func save() {
276 guard canSave, !busy, draftRequest == nil else { return }
277 busy = true
278 Task {
279 defer { busy = false }
280 do {
281 let plan: String?
282 if includePlan || TaskPlan.requested(in: idea) {
283 if TaskDrafting.unavailableReason == nil {
284 plan = try await TaskPlan.revise("", instruction: "Draft a Markdown plan with actionable steps and verification checks.",
285 context: "\(taskTitle)\n\(notes)\nDefinition of done: \(definitionOfDone)")
286 } else {
287 plan = TaskPlan.starter(title: taskTitle, notes: notes, definitionOfDone: definitionOfDone)
288 }
289 } else { plan = nil }
290 try await model.createItem(title: taskTitle, notes: notes, definitionOfDone: definitionOfDone,
291 project: board, status: status, priority: priority, planMarkdown: plan, issueType: issueType ?? .inferred(from: idea))
292 if model.pendingSend == nil { model.sheet = nil }
293 } catch let failure { error = failure.localizedDescription }
294 }
295 }
296}
297
298private struct IconPicker: View {
299 @Environment(WorkspaceModel.self) private var model
300 @Environment(\.palette) private var palette
301 @State private var selected: String?
302 @State private var busy = false
303 @State private var error: String?
304 let board: Board
305
306 init(board: Board) {
307 self.board = board
308 _selected = State(initialValue: board.icon)
309 }
310
311 var body: some View {
312 VStack(alignment: .leading, spacing: 16) {
313 SheetTitle(title: "Change project icon")
314 Text(board.name).foregroundStyle(palette.muted)
315 LazyVGrid(columns: Array(repeating: GridItem(.fixed(36), spacing: 6), count: 10), spacing: 6) {
316 choice(nil)
317 ForEach(BoardIcons.entries.map(\.0), id: \.self) { choice($0) }
318 }
319 if let error { Text(error).font(.caption).foregroundStyle(palette.danger) }
320 HStack {
321 Spacer()
322 Button("Cancel") { model.sheet = nil }.keyboardShortcut(.cancelAction)
323 Button("Save icon", action: save).glassPrimary().keyboardShortcut(.defaultAction).disabled(selected == board.icon)
324 }
325 }
326 .disabled(busy)
327 .padding(23)
328 .frame(width: 465)
329 }
330
331 private func choice(_ key: String?) -> some View {
332 Button { selected = key } label: {
333 ProjectIcon(key: key, size: 14)
334 .frame(width: 36, height: 33)
335 .surface(6, fill: selected == key ? palette.active : palette.card)
336 }
337 .buttonStyle(.plain)
338 .help(key ?? "Default project icon")
339 .accessibilityLabel(key ?? "Default project icon")
340 .accessibilityAddTraits(selected == key ? .isSelected : [])
341 }
342
343 private func save() {
344 busy = true
345 Task {
346 defer { busy = false }
347 do {
348 try await model.mutate("set_board_icon", [
349 "id": board.id, "expectedRevision": board.revision,
350 "icon": selected.map { $0 as Any } ?? NSNull()
351 ])
352 model.sheet = nil
353 } catch let failure { error = failure.localizedDescription }
354 }
355 }
356}
357
358private struct RestoreResponse: Decodable { let safetyBackup: String? }
359
360private struct PreviewView: View {
361 @Environment(WorkspaceModel.self) private var model
362 @Environment(\.palette) private var palette
363 @State private var busy = false
364 @State private var error: String?
365 @State private var requestKey = UUID().uuidString
366 let preview: Preview
367
368 var body: some View {
369 VStack(alignment: .leading, spacing: 15) {
370 SheetTitle(title: preview.title, close: cancel)
371 Text(preview.detail).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true)
372 if !preview.summary.taskNames.isEmpty {
373 let names = preview.summary.taskNames
374 Text(names.prefix(4).joined(separator: " · ") + (names.count > 4 ? " and \(names.count - 4) more" : ""))
375 .font(.caption).textSelection(.enabled).lineLimit(3)
376 }
377 if let path = preview.summary.path, !path.contains("/.native-import-") {
378 Text(path).font(.caption).textSelection(.enabled)
379 }
380 if let error { Text(error).foregroundStyle(palette.danger).font(.caption) }
381 HStack {
382 Spacer()
383 Button("Cancel", action: cancel).keyboardShortcut(.cancelAction)
384 Button(preview.restoring ? "Restore workspace" : "Delete permanently", role: .destructive, action: confirm)
385 }
386 }
387 .disabled(busy)
388 .padding(24)
389 .frame(width: 475)
390 }
391
392 private func cancel() {
393 model.sheet = preview.restoring ? .settings : nil
394 if preview.restoring {
395 model.perform { let _: EmptyResponse = try await model.service.call("native_cancel_restore") }
396 }
397 }
398
399 private func confirm() {
400 busy = true
401 Task {
402 defer { busy = false }
403 do {
404 let result: RestoreResponse = try await model.write("confirm_destructive_action",
405 ["token": preview.token, "requestKey": requestKey])
406 model.sheet = nil
407 model.undoTrash = nil
408 if preview.restoring {
409 model.navigate(.dashboard)
410 model.banner = result.safetyBackup == nil ? "Workspace restored" : "Workspace restored. A safety backup was saved."
411 } else { model.banner = "Tasks permanently deleted" }
412 } catch let failure { error = failure.localizedDescription }
413 }
414 }
415}
416
417private struct SendView: View {
418 private struct AgentOptions: Decodable {
419 let defaultAgent: PhoneAgent
420 let availableAgents: [PhoneAgent]
421 let agentModels: [AgentModelChoice]
422 let needsSetup: Bool
423 let workingFolder: String
424 }
425
426 @Environment(WorkspaceModel.self) private var model
427 @Environment(\.palette) private var palette
428 @State private var options: AgentOptions?
429 @State private var agent: PhoneAgent?
430 @State private var selectedModel: String?
431 @State private var dispatchComment = ""
432 @State private var showSetup = false
433 @State private var busy = false
434 @State private var error: String?
435
436 private var models: [AgentModelChoice] {
437 options?.agentModels.filter { $0.agent == agent } ?? []
438 }
439
440 private var agentDefaultTitle: String {
441 agent?.agentDefaultTitle(models: models) ?? "Agent default"
442 }
443
444 var body: some View {
445 VStack(alignment: .leading, spacing: 16) {
446 SheetTitle(title: "Send to agent", close: cancel)
447 Text(model.pendingSend?.title ?? "New task").fontWeight(.semibold)
448 if let folder = options?.workingFolder, !folder.isEmpty {
449 Label(folder, systemImage: "folder").font(.caption).foregroundStyle(palette.muted)
450 .textSelection(.enabled).lineLimit(2)
451 }
452 if let options, !options.availableAgents.isEmpty {
453 if options.availableAgents.count > 1 {
454 BoardDropdown(selection: $agent, title: "Agent", symbol: "terminal",
455 choices: options.availableAgents.map(Optional.some), compact: true,
456 agentBrand: { Agent(rawValue: $0?.rawValue ?? "") ?? .claude },
457 label: { $0?.title ?? "Default" })
458 } else if let agent, let brand = Agent(rawValue: agent.rawValue) {
459 AgentBrandLabel(agent: brand)
460 }
461 if !models.isEmpty {
462 BoardDropdown(selection: $selectedModel, title: "Model", symbol: "cpu",
463 choices: [nil] + models.map { Optional($0.id) }, compact: true,
464 label: { id in models.first(where: { $0.id == id })?.title ?? agentDefaultTitle })
465 }
466 } else if options == nil && error == nil {
467 ProgressView().controlSize(.small)
468 }
469 Text("Revision request (optional)").font(.caption).foregroundStyle(palette.muted)
470 TextField(TaskRevisionRequestCopy.field, text: $dispatchComment,
471 prompt: Text(TaskRevisionRequestCopy.example), axis: .vertical)
472 .textFieldStyle(.plain).lineLimit(2...4).padding(12).surface(10)
473 .accessibilityIdentifier("agentDispatchComment")
474 DisclosureGroup("Agent setup", isExpanded: $showSetup) {
475 AgentControls(settingUpSend: true)
476 .padding(.top, 8)
477 Button("Refresh agents", action: { Task { await load() } })
478 }
479 if let error { Text(error).foregroundStyle(palette.danger).font(.caption) }
480 HStack {
481 Spacer()
482 Button("Cancel", action: cancel).keyboardShortcut(.cancelAction)
483 Button("Send to agent", action: send).glassPrimary()
484 .disabled(!model.canUseAgents || options == nil || dispatchComment.utf16.count > 10_000)
485 }
486 }
487 .disabled(busy)
488 .padding(24)
489 .frame(width: 530)
490 .task { await load() }
491 .onChange(of: agent) { selectedModel = nil }
492 .onChange(of: model.connectionSignal) { Task { await load() } }
493 .onChange(of: model.workspace?.revision) { _, _ in Task { await load() } }
494 }
495
496 private func cancel() {
497 model.pendingSend = nil
498 model.sheet = nil
499 }
500
501 private func send() {
502 busy = true
503 Task {
504 defer { busy = false }
505 do {
506 try await model.finishSend(agent: agent, model: models.first(where: { $0.id == selectedModel })?.id,
507 comment: dispatchComment)
508 } catch let failure {
509 error = failure.localizedDescription
510 if let serviceFailure = failure as? ServiceFailure,
511 ["AGENT_SETUP_REQUIRED", "AGENT_NOT_INSTALLED", "MCP_DISABLED"].contains(serviceFailure.code) {
512 showSetup = true
513 }
514 }
515 }
516 }
517
518 private func load() async {
519 do {
520 let fields = model.pendingSend?.input ?? [:]
521 let taskID = fields["id"] as? String
522 let boardID = fields["boardId"] as? String ?? model.tasks.first(where: { $0.id == taskID })?.boardId
523 let input: [String: Any] = boardID.map { ["boardId": $0] } ?? [:]
524 let loaded: AgentOptions = try await model.service.call("native_agent_options", input)
525 options = loaded
526 if let selectedModel, !loaded.agentModels.contains(where: { $0.agent == agent && $0.id == selectedModel }) {
527 self.selectedModel = nil
528 }
529 if !loaded.availableAgents.contains(where: { $0 == agent }) {
530 agent = loaded.availableAgents.first(where: { $0 == loaded.defaultAgent }) ?? loaded.availableAgents.first
531 }
532 if loaded.needsSetup { showSetup = true }
533 error = nil
534 } catch let failure {
535 error = failure.localizedDescription
536 }
537 }
538}
539
540struct AboutView: View {
541 @Environment(\.palette) private var palette
542
543 var body: some View {
544 ThemedScrollView {
545 VStack(alignment: .leading, spacing: 24) {
546 masthead
547 VStack(alignment: .leading, spacing: 16) {
548 Divider()
549 siteLinks
550 }
551 }
552 .frame(maxWidth: 980)
553 .padding(.horizontal, 36)
554 .padding(.vertical, 28)
555 .frame(maxWidth: .infinity, alignment: .topLeading)
556 }
557 }
558
559 private var masthead: some View {
560 let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "—"
561 let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "—"
562
563 return VStack(alignment: .leading, spacing: 18) {
564 HStack(spacing: 24) {
565 Image(nsImage: NSApp.applicationIconImage)
566 .resizable().scaledToFit()
567 .frame(width: 100, height: 88)
568 .shadow(color: .black.opacity(palette.dark ? 0 : 0.18), radius: 8, y: 4)
569 .accessibilityHidden(true)
570 VStack(alignment: .leading, spacing: 5) {
571 Text("OpenTalon")
572 .font(.system(size: 48, weight: .semibold, design: .serif))
573 .accessibilityAddTraits(.isHeader)
574 Text("A little room for the things you’re working on.")
575 .font(.system(size: 15))
576 .foregroundStyle(palette.muted)
577 }
578 }
579 Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 6) {
580 GridRow {
581 Text("Version")
582 Text(version).foregroundStyle(palette.muted)
583 }
584 GridRow {
585 Text("Build")
586 Text(build).foregroundStyle(palette.muted)
587 }
588 }
589 .font(.system(size: 12, weight: .medium))
590 }
591 .frame(maxWidth: .infinity, alignment: .leading)
592 .padding(25)
593 .surface(22, fill: palette.panel)
594 }
595
596 private var siteLinks: some View {
597 HStack(spacing: 16) {
598 Link(destination: OpenTalonCommunity.websiteHelp) { Label("Setup and Troubleshooting", systemImage: "book") }
599 Link(destination: OpenTalonCommunity.website) { Label("OpenTalon website", systemImage: "globe") }
600 Link(destination: URL(string: "https://github.com/projectatomai/opentalon")!) {
601 Label("View source on GitHub", systemImage: "chevron.left.forwardslash.chevron.right")
602 }
603 }
604 .fixedSize(horizontal: true, vertical: false)
605 }
606
607}
608
609struct WebLink: View {
610 let title: String
611 let url: String
612 let symbol: String
613
614 var body: some View {
615 if let destination = URL(string: url) {
616 Link(destination: destination) { Label(title, systemImage: symbol) }.font(.system(size: 12))
617 }
618 }
619}