Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / WorkSourceSettings.swift
| 1 | import AppKit |
| 2 | import SwiftUI |
| 3 | |
| 4 | struct WorkSourceSettings: View { |
| 5 | let workspace: Workspace |
| 6 | @State private var projectID = "" |
| 7 | @State private var scanning = false |
| 8 | @State private var found: WorkContext.Result? |
| 9 | @State private var selected: Set<Int> = [] |
| 10 | |
| 11 | private var schedule: [String: Any] { workspace.workSourceSchedule(projectID) } |
| 12 | private var enabled: Bool { schedule["enabled"] as? Bool == true && schedule["nativeApproved"] as? Bool == true } |
| 13 | private var hours: Int { schedule["hours"] as? Int ?? 24 } |
| 14 | |
| 15 | var body: some View { |
| 16 | GroupBox("Idea source schedule") { |
| 17 | VStack(alignment: .leading, spacing: 12) { |
| 18 | StudioLabeledChoice(title: "Project", selection: $projectID, |
| 19 | options: [""] + workspace.projects.map(\.id), |
| 20 | label: { id in workspace.projects.first(where: { $0.id == id })?.title ?? "Choose a project" }) |
| 21 | Group { |
| 22 | folder("Project folder", key: "codeFolder") |
| 23 | folder("Obsidian notes folder", key: "notesFolder") |
| 24 | StudioLabeledChoice(title: "Refresh frequency", selection: Binding(get: { hours }, set: { |
| 25 | configure(hours: $0, enabled: enabled) |
| 26 | }), options: [1, 6, 24], label: { $0 == 24 ? "Every day" : $0 == 1 ? "Every hour" : "Every 6 hours" }) |
| 27 | Toggle("Refresh idea sources automatically", isOn: Binding(get: { enabled }, set: { |
| 28 | configure(hours: hours, enabled: $0) |
| 29 | })) |
| 30 | .disabled(!["codeFolder", "notesFolder"].contains { !(schedule[$0] as? String ?? "").isEmpty }) |
| 31 | } |
| 32 | .disabled(projectID.isEmpty) |
| 33 | Text("Automatic refresh saves recent work and notes from your chosen folders as project references. Your writing model can use those references when generating ideas.") |
| 34 | .font(.caption).foregroundStyle(.secondary) |
| 35 | if enabled, let count = schedule["lastCount"] as? Int, |
| 36 | let value = schedule["lastAttemptAt"] as? String, let date = scheduleDate(value) { |
| 37 | Text("Last refresh \(date.formatted(date: .abbreviated, time: .shortened)) · \(count) new references") |
| 38 | .font(.caption).foregroundStyle(.secondary) |
| 39 | } |
| 40 | if enabled { availability(schedule["unavailable"] as? [String] ?? []) } |
| 41 | Divider() |
| 42 | Button(scanning ? "Finding recent work…" : "Review recent work manually…", |
| 43 | systemImage: "folder", action: scan) |
| 44 | .disabled(projectID.isEmpty || scanning) |
| 45 | if let found { |
| 46 | availability(found.unavailable) |
| 47 | if found.items.isEmpty { Text("No work found in the last two days.").foregroundStyle(.secondary) } |
| 48 | ForEach(found.items.indices, id: \.self) { index in |
| 49 | review(index, item: found.items[index]) |
| 50 | } |
| 51 | if !found.items.isEmpty { |
| 52 | Button("Save selected references", action: save) |
| 53 | .disabled(projectID.isEmpty || selected.isEmpty || scanning) |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | .padding(5) |
| 58 | .frame(maxWidth: .infinity, alignment: .leading) |
| 59 | } |
| 60 | .onAppear { |
| 61 | if projectID.isEmpty { projectID = workspace.projectID } |
| 62 | } |
| 63 | .onChange(of: projectID) { _, _ in found = nil; selected.removeAll() } |
| 64 | } |
| 65 | |
| 66 | private func folder(_ title: String, key: String) -> some View { |
| 67 | let path = schedule[key] as? String ?? "" |
| 68 | return HStack { |
| 69 | VStack(alignment: .leading) { |
| 70 | Text(title) |
| 71 | Text(path.isEmpty ? "Choose a folder" : path) |
| 72 | .font(.caption).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle) |
| 73 | } |
| 74 | Spacer() |
| 75 | Button(path.isEmpty ? "Choose…" : "Change…") { |
| 76 | guard let url = chooseFolder("Choose " + title.lowercased()) else { return } |
| 77 | update([key: url.resolvingSymlinksInPath().path, "enabled": false]) |
| 78 | } |
| 79 | if !path.isEmpty { Button("Remove") { update([key: "", "enabled": false]) } } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | @ViewBuilder private func availability(_ sources: [String]) -> some View { |
| 84 | if !sources.isEmpty { |
| 85 | Text("Couldn’t read " + sources.joined(separator: ", ") + ".") |
| 86 | .font(.caption).foregroundStyle(.secondary) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | private func review(_ index: Int, item: WorkReference) -> some View { |
| 91 | DisclosureGroup { |
| 92 | Toggle("Use this reference", isOn: Binding(get: { selected.contains(index) }, set: { |
| 93 | if $0 { selected.insert(index) } else { selected.remove(index) } |
| 94 | })) |
| 95 | .disabled(selected.count >= 20 && !selected.contains(index)) |
| 96 | TextField("Summary", text: Binding(get: { found?.items[index].text ?? "" }, set: { |
| 97 | found?.items[index].text = String($0.prefix(2000)) |
| 98 | }), axis: .vertical) |
| 99 | .lineLimit(3...6) |
| 100 | .studioInput() |
| 101 | } label: { |
| 102 | VStack(alignment: .leading) { |
| 103 | Text(item.title).lineLimit(1) |
| 104 | Group { |
| 105 | switch item.origin { |
| 106 | case .claude: StudioAgentLabel(agent: .claude, title: "Claude recap") |
| 107 | case .codex: StudioAgentLabel(agent: .codex, title: "Codex recap") |
| 108 | default: Text(item.origin.rawValue) |
| 109 | } |
| 110 | } |
| 111 | .font(.caption).foregroundStyle(.secondary) |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | private func configure(hours: Int, enabled: Bool) { |
| 117 | update(["hours": hours, "enabled": enabled, "nativeApproved": enabled]) |
| 118 | if enabled { Task { await workspace.refreshScheduledWork() } } |
| 119 | } |
| 120 | |
| 121 | private func update(_ fields: [String: Any]) { |
| 122 | workspace.perform { try workspace.updateWorkSourceSchedule(projectID, fields: fields) } |
| 123 | } |
| 124 | |
| 125 | private func scan() { |
| 126 | guard let folder = chooseFolder("Choose a project folder to find recent work") else { return } |
| 127 | let project = projectID |
| 128 | scanning = true |
| 129 | Task { |
| 130 | let result = await Task.detached(priority: .utility) { WorkContext().collect(code: folder, notes: nil) }.value |
| 131 | scanning = false |
| 132 | guard project == projectID else { return } |
| 133 | found = result |
| 134 | selected.removeAll() |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | private func save() { |
| 139 | guard let found else { return } |
| 140 | let items = selected.sorted().map { found.items[$0] } |
| 141 | workspace.perform { |
| 142 | let count = try workspace.saveWorkReferences(items, projectID: projectID) |
| 143 | selected.removeAll() |
| 144 | workspace.notice = count == 0 ? "These references are already saved." : "Saved \(count) project references." |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | private func chooseFolder(_ title: String) -> URL? { |
| 149 | let panel = NSOpenPanel() |
| 150 | panel.title = title |
| 151 | panel.canChooseDirectories = true |
| 152 | panel.canChooseFiles = false |
| 153 | return panel.runModal() == .OK ? panel.url : nil |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | extension Workspace { |
| 158 | func workSourceSchedule(_ projectID: String) -> [String: Any] { |
| 159 | (settings["workSourceSchedules"] as? [String: [String: Any]])?[projectID] ?? [:] |
| 160 | } |
| 161 | |
| 162 | func updateWorkSourceSchedule(_ projectID: String, fields: [String: Any], reset: Bool = true) throws { |
| 163 | try withChanges { |
| 164 | guard projects.contains(where: { $0.id == projectID }) else { throw WorkspaceError("Choose an existing project.") } |
| 165 | var all = settings["workSourceSchedules"] as? [String: [String: Any]] ?? [:] |
| 166 | var next = all[projectID] ?? [:] |
| 167 | if reset { |
| 168 | for key in ["lastAttemptAt", "lastCount", "unavailable"] { next.removeValue(forKey: key) } |
| 169 | } |
| 170 | next.merge(fields) { _, value in value } |
| 171 | all[projectID] = next |
| 172 | try set("workSourceSchedules", to: all) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | func saveWorkReferences(_ items: [WorkReference], projectID: String) throws -> Int { |
| 177 | guard (1...20).contains(items.count) else { throw WorkspaceError("Choose up to 20 references.") } |
| 178 | return try withChanges { |
| 179 | guard projects.contains(where: { $0.id == projectID }) else { throw WorkspaceError("Choose an existing project.") } |
| 180 | var known = Set(records.filter { $0.kind == "source" && $0.projectID == projectID }.map { [$0["title"], $0["text"]] }) |
| 181 | var count = 0 |
| 182 | for item in items { |
| 183 | let text = item.text.trimmingCharacters(in: .whitespacesAndNewlines) |
| 184 | guard !text.isEmpty, text.count <= 2000, !item.title.isEmpty else { |
| 185 | throw WorkspaceError("Enter a title and a summary for each selected reference.") |
| 186 | } |
| 187 | guard known.insert([item.title, text]).inserted else { continue } |
| 188 | var source = WorkspaceRecord.new("source", projectID: projectID) |
| 189 | source["title"] = item.title |
| 190 | source["text"] = text |
| 191 | source["origin"] = item.origin.rawValue |
| 192 | source["postedAt"] = workspaceTimestamp(item.at) |
| 193 | _ = try save(source) |
| 194 | count += 1 |
| 195 | } |
| 196 | return count |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | func refreshScheduledWork() async { |
| 201 | guard !refreshingWorkSources else { return } |
| 202 | refreshingWorkSources = true |
| 203 | defer { refreshingWorkSources = false } |
| 204 | for id in projects.map(\.id) where !Task.isCancelled { |
| 205 | let config = workSourceSchedule(id) |
| 206 | guard config["enabled"] as? Bool == true, config["nativeApproved"] as? Bool == true else { continue } |
| 207 | let hours = config["hours"] as? Int ?? 24 |
| 208 | let interval = [1, 6, 24].contains(hours) ? hours : 24 |
| 209 | let last = (config["lastAttemptAt"] as? String).flatMap(scheduleDate) ?? .distantPast |
| 210 | guard Date.now.timeIntervalSince(last) >= Double(interval * 3600) else { continue } |
| 211 | let code = (config["codeFolder"] as? String).flatMap { $0.hasPrefix("/") ? URL(fileURLWithPath: $0) : nil } |
| 212 | let notes = (config["notesFolder"] as? String).flatMap { $0.hasPrefix("/") ? URL(fileURLWithPath: $0) : nil } |
| 213 | guard code != nil || notes != nil else { continue } |
| 214 | let attempt = WorkspaceRecord.timestamp |
| 215 | do { |
| 216 | try updateWorkSourceSchedule(id, fields: ["lastAttemptAt": attempt], reset: false) |
| 217 | let result = await Task.detached(priority: .utility) { WorkContext().collect(code: code, notes: notes, limit: 20) }.value |
| 218 | guard !Task.isCancelled else { return } |
| 219 | let saved = try withChanges { |
| 220 | let latest = workSourceSchedule(id) |
| 221 | guard latest["enabled"] as? Bool == true, latest["lastAttemptAt"] as? String == attempt else { return false } |
| 222 | let count = result.items.isEmpty ? 0 : try saveWorkReferences(result.items.reversed(), projectID: id) |
| 223 | try updateWorkSourceSchedule(id, fields: ["lastCount": count, "unavailable": result.unavailable], reset: false) |
| 224 | return true |
| 225 | } |
| 226 | if saved { await refillIdeaQueueIfNeeded(projectID: id) } |
| 227 | } catch { |
| 228 | notice = "Idea sources couldn’t refresh: " + error.localizedDescription |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | } |