Branchwell

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

Raw 16.3 KB on d82caf36fa99426fea138f030e7704d2b3cf17b3
1import AppKit
2import CompanionCore
3import SwiftUI
4import UniformTypeIdentifiers
5
6struct SettingsView: View {
7 @Environment(WorkspaceModel.self) private var model
8 @Environment(\.palette) private var palette
9 @State private var busy = false
10 @State private var error: String?
11 @State private var note: String?
12 @State private var pendingTheme: Theme?
13 @State private var themeError: String?
14 @State private var editingModels = false
15
16 var body: some View {
17 VStack(alignment: .leading, spacing: 0) {
18 SheetTitle(title: "Settings").padding(.horizontal, 24).padding(.vertical, 17)
19 Divider()
20 ThemedScrollView(track: palette.panel) {
21 VStack(alignment: .leading, spacing: 24) {
22 appearance
23 Divider()
24 HStack {
25 section("Task agent", "Choose who picks up tasks you move to Sent to agent.")
26 Spacer()
27 Button("Agent connection guide", systemImage: "book") {
28 model.sheet = .connectionIntroduction
29 }
30 }
31 AgentControls()
32 Button("Manage models…", systemImage: "slider.horizontal.3") { editingModels = true }
33 Divider()
34 backupSection
35 DailyBackupView()
36 Divider()
37 PhoneCompanionSettings()
38 Divider()
39 ConnectionSetup()
40 Divider()
41 section("Help", "Guides for Mac, iPhone, and iPad.")
42 WebLink(title: "Setup and Troubleshooting", url: OpenTalonCommunity.websiteHelp.absoluteString,
43 symbol: "book")
44 }
45 .padding(24)
46 }
47 }
48 .frame(width: 690, height: 640)
49 .toggleStyle(GlassToggleStyle())
50 .disabled(busy)
51 .sheet(isPresented: $editingModels) { AgentModelCatalogEditor() }
52 }
53
54 private var appearance: some View {
55 VStack(alignment: .leading, spacing: 11) {
56 section("Make yourself at home", "Choose the canvas you like working in.")
57 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: 3), spacing: 0) {
58 themeChoice(.graphite, "Quiet focus. A darker canvas.")
59 themeChoice(.paper, "A softer place to get things done.")
60 themeChoice(.light, "Crisp, clear, and familiar.")
61 }
62 Toggle("Follow macOS light/dark appearance", isOn: Binding(
63 get: { (pendingTheme ?? model.workspace?.theme) == .system },
64 set: { useTheme($0 ? .system : .light) }
65 ))
66 if let themeError { Text(themeError).font(.caption).foregroundStyle(palette.danger) }
67 }
68 .transaction { $0.animation = nil }
69 }
70
71 private func themeChoice(_ theme: Theme, _ description: String) -> some View {
72 let swatch = Palette(theme: theme)
73 let active = (pendingTheme ?? model.workspace?.theme) == theme
74 return Button { useTheme(theme) } label: {
75 VStack(alignment: .leading, spacing: 8) {
76 HStack(spacing: 6) {
77 VStack(alignment: .leading, spacing: 5) {
78 Capsule().fill(swatch.accent).frame(width: 16, height: 2)
79 Capsule().fill(swatch.muted).frame(width: 13, height: 2)
80 Capsule().fill(swatch.muted).frame(width: 9, height: 2)
81 }
82 .frame(width: 37, height: 50)
83 .background(swatch.sidebar)
84 ForEach(0..<3) { column in
85 VStack(spacing: 3) {
86 ForEach(0..<(column == 0 ? 3 : 2), id: \.self) { _ in
87 RoundedRectangle(cornerRadius: 2).fill(swatch.card).frame(height: 6)
88 }
89 Spacer(minLength: 0)
90 }
91 .padding(3)
92 .frame(maxWidth: .infinity)
93 .background(swatch.well, in: .rect(cornerRadius: 4))
94 }
95 }
96 .padding(.trailing, 6)
97 .frame(height: 50)
98 .background(swatch.canvas)
99 .clipShape(.rect(cornerRadius: 5))
100 HStack {
101 Text(theme.title).fontWeight(.semibold)
102 Spacer()
103 Image(systemName: "checkmark.circle.fill")
104 .foregroundStyle(palette.accent)
105 .frame(width: 16)
106 .opacity(active ? 1 : 0)
107 .accessibilityHidden(true)
108 }
109 Text(description).font(.caption2).foregroundStyle(palette.muted)
110 }
111 .padding(9)
112 .frame(maxWidth: .infinity, alignment: .leading)
113 .surface(8, fill: active ? palette.active : palette.card)
114 }
115 .buttonStyle(.plain)
116 .accessibilityLabel(theme.title)
117 .accessibilityAddTraits(active ? .isSelected : [])
118 }
119
120 private var backupSection: some View {
121 VStack(alignment: .leading, spacing: 10) {
122 section("Your data & backups", "Export everything to one readable JSON file. Keep a copy outside this Mac.")
123 HStack {
124 Button("Show data folder", systemImage: "folder") { NSWorkspace.shared.open(model.profile) }
125 Button("Export Backup…", systemImage: "square.and.arrow.up", action: exportBackup)
126 Button("Import / Restore…", systemImage: "square.and.arrow.down", action: importBackup)
127 }
128 if legacyWorkspaceAvailable {
129 Button("Copy from the Electron app…", action: copyElectron)
130 }
131 Text("Backups include projects, tasks, Trash, appearance, revision requests, screenshots, and agent history. Restore saves a safety backup and never dispatches restored work.")
132 .font(.caption).foregroundStyle(palette.muted)
133 if let note { Text(note).font(.caption).textSelection(.enabled) }
134 if let error { Text(error).font(.caption).foregroundStyle(palette.danger) }
135 }
136 }
137
138 private func section(_ title: String, _ description: String) -> some View {
139 VStack(alignment: .leading, spacing: 5) {
140 Text(title).font(.system(size: 16, weight: .semibold)).accessibilityAddTraits(.isHeader)
141 Text(description).font(.system(size: 12)).foregroundStyle(palette.muted)
142 }
143 }
144
145 private func run(_ operation: @escaping @MainActor () async throws -> Void) {
146 busy = true
147 error = nil
148 note = nil
149 Task {
150 defer { busy = false }
151 do { try await operation() }
152 catch let failure { error = failure.localizedDescription }
153 }
154 }
155
156 private func useTheme(_ theme: Theme) {
157 guard pendingTheme == nil, model.workspace?.theme != theme else { return }
158 pendingTheme = theme
159 themeError = nil
160 Task {
161 defer { pendingTheme = nil }
162 do { try await model.preferences(["theme": theme.rawValue]) }
163 catch { themeError = error.localizedDescription }
164 }
165 }
166
167 private func exportBackup() {
168 run {
169 let panel = NSSavePanel()
170 panel.title = "Export OpenTalon Backup"
171 panel.nameFieldStringValue = "OpenTalon-\(CalendarDay.today).json"
172 panel.allowedContentTypes = [.json]
173 guard await panel.begin() == .OK, let url = panel.url else { return }
174 let result: PathResponse = try await model.write("create_backup", ["destination": url.path, "format": "json"])
175 note = "Backup saved: \(result.path)"
176 }
177 }
178
179 private func importBackup() {
180 guard model.canLeave() else { error = "Save or discard your task changes before restoring."; return }
181 run {
182 let panel = NSOpenPanel()
183 panel.title = "Import / Restore OpenTalon Backup"
184 panel.allowedContentTypes = [.json] + ["opentalon", "sqlite"].compactMap { UTType(filenameExtension: $0) }
185 guard await panel.begin() == .OK, let url = panel.url else { return }
186 try await model.preview("restore_backup", path: url.path)
187 }
188 }
189
190 private var legacyWorkspaceAvailable: Bool {
191 let url = model.profile.deletingLastPathComponent().appendingPathComponent("OpenTalon Prototype/opentalon.sqlite")
192 guard let file = try? FileHandle(forReadingFrom: url) else { return false }
193 defer { try? file.close() }
194 return (try? file.read(upToCount: 16)) == Data("SQLite format 3\0".utf8)
195 }
196
197 private func copyElectron() {
198 guard model.canLeave() else { error = "Save or discard your task changes before importing."; return }
199 run {
200 let preview: Preview = try await model.service.call("native_preview_electron")
201 model.sheet = .preview(preview)
202 }
203 }
204}
205
206struct RuntimeState: Decodable { let installed: Bool }
207
208struct AgentControls: View {
209 @Environment(WorkspaceModel.self) private var model
210 @Environment(\.palette) private var palette
211 @State private var settings: AgentSettings?
212 @State private var runtimes: [String: RuntimeState] = [:]
213 @State private var connection: Connection?
214 @State private var error: String?
215 @State private var busy = false
216 var settingUpSend = false
217
218 private var onlyAvailableAgent: Agent? {
219 let available = Agent.allCases.filter { runtimes[$0.rawValue]?.installed == true }
220 return available.count == 1 ? available.first : nil
221 }
222
223 var body: some View {
224 VStack(alignment: .leading, spacing: 10) {
225 if let settings {
226 Group {
227 if settingUpSend, let onlyAvailableAgent {
228 AgentBrandLabel(agent: onlyAvailableAgent)
229 } else {
230 HStack(spacing: 10) {
231 Text("Default agent").foregroundStyle(palette.muted).accessibilityHidden(true)
232 BoardDropdown(selection: Binding(get: { settings.defaultAgent }, set: { agent in
233 var updated = settings
234 updated.defaultAgent = agent
235 save(updated)
236 }), title: "Default agent", symbol: "terminal", choices: Agent.allCases,
237 compact: true, agentBrand: { $0 }, label: \.title)
238 .frame(width: 185)
239 }
240 if runtimes[settings.defaultAgent.rawValue]?.installed == false {
241 if let guide = URL(string: settings.defaultAgent.guide) {
242 Link(destination: guide) {
243 AgentBrandLabel(agent: settings.defaultAgent, title: "Install \(settings.defaultAgent.title)")
244 }
245 }
246 }
247 if settings.defaultAgent == .gemini {
248 Text("Gemini runs through Google’s Antigravity CLI (agy) with your Google sign-in. Agent default uses an available model from your Google account. Until Google confirms your models, it uses Gemini 3.8 Flash. Choose a specific model to always use it.")
249 .font(.caption).foregroundStyle(palette.muted)
250 .fixedSize(horizontal: false, vertical: true)
251 }
252 }
253 HStack(spacing: 10) {
254 Text("Permissions").foregroundStyle(palette.muted).accessibilityHidden(true)
255 BoardDropdown(selection: Binding(get: { settings.permissionMode }, set: { mode in
256 var updated = settings
257 updated.permissionMode = mode
258 save(updated)
259 }), title: "Permissions", symbol: "lock.shield", choices: AgentPermission.allCases,
260 compact: true, label: \.title)
261 .frame(width: 185)
262 }
263 Text(settings.permissionMode.detail)
264 .font(.caption).foregroundStyle(palette.muted)
265 HStack {
266 Label(settings.workingFolder.isEmpty ? "No working folder selected" : settings.workingFolder,
267 systemImage: "folder")
268 .font(.caption).foregroundStyle(palette.muted).lineLimit(2)
269 Spacer(minLength: 4)
270 Button("Choose OpenTalon folder…", systemImage: "folder") { chooseFolder(settings) }
271 if !settings.workingFolder.isEmpty {
272 Button("Clear") {
273 var updated = settings
274 updated.workingFolder = ""
275 save(updated)
276 }
277 }
278 }
279 Text("Projects use this global folder unless you choose a project’s own Agent folder from its project menu. This also applies to requests from iPhone and iPad. New Codex chats reuse the project for that folder. Choose dedicated folders to keep agent files together and reduce folder-access prompts.")
280 .font(.caption).foregroundStyle(palette.muted)
281 }
282 .disabled(!model.canUseAgents)
283 if let connection {
284 Toggle("Enable local agent connection", isOn: Binding(
285 get: { connection.enabled },
286 set: { enabled in
287 run {
288 self.connection = try await model.service.call("set_connection", ["enabled": enabled])
289 model.connectionSignal += 1
290 }
291 }
292 ))
293 if !connection.error.isEmpty { Text(connection.error).font(.caption).foregroundStyle(palette.danger) }
294 }
295 } else {
296 ProgressView().controlSize(.small)
297 }
298 if let error { Text(error).font(.caption).foregroundStyle(palette.danger) }
299 }
300 .disabled(busy)
301 .task(id: model.connectionSignal) { await load() }
302 .onChange(of: model.workspace?.revision) { _, _ in
303 Task { if !busy { await load() } }
304 }
305 }
306
307 private func load() async {
308 do {
309 settings = try await model.service.call("get_agent_settings")
310 runtimes = try await model.service.call("agent_runtime_status")
311 connection = try await model.service.call("connection_status")
312 } catch { self.error = error.localizedDescription }
313 }
314
315 private func save(_ settings: AgentSettings) {
316 run { try await write(settings) }
317 }
318
319 private func write(_ settings: AgentSettings) async throws {
320 try await model.mutate("set_agent_settings", [
321 "defaultAgent": settings.defaultAgent.rawValue, "workingFolder": settings.workingFolder,
322 "permissionMode": settings.permissionMode.rawValue
323 ])
324 self.settings = settings
325 }
326
327 private func chooseFolder(_ settings: AgentSettings) {
328 run {
329 guard let url = await chooseDirectory("Choose your global OpenTalon working folder", prompt: "Use this folder") else { return }
330 var updated = settings
331 updated.workingFolder = url.path
332 try await write(updated)
333 }
334 }
335
336 private func run(_ operation: @escaping @MainActor () async throws -> Void) {
337 busy = true
338 error = nil
339 Task {
340 defer { busy = false }
341 do { try await operation() }
342 catch let failure { error = failure.localizedDescription }
343 }
344 }
345}
346
347@MainActor
348func chooseDirectory(_ title: String, prompt: String) async -> URL? {
349 let panel = NSOpenPanel()
350 panel.title = title
351 panel.prompt = prompt
352 panel.canChooseFiles = false
353 panel.canChooseDirectories = true
354 panel.canCreateDirectories = true
355 return await panel.begin() == .OK ? panel.url : nil
356}