Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / RevisionComments.swift
| 1 | import Foundation |
| 2 | import OSLog |
| 3 | import InkspringSchedule |
| 4 | |
| 5 | extension WorkspaceRecord { |
| 6 | var acceptsRevisionComments: Bool { |
| 7 | (kind == "idea" && self["status"] == "draft" && !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) || |
| 8 | (kind == "draft" && (scheduleStatus.isEmpty || scheduleStatus == "ready") |
| 9 | && !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) || |
| 10 | (isLongForm && ["draft", "synced"].contains(self["state"])) |
| 11 | } |
| 12 | |
| 13 | var appliedRevisionCommentIDs: [String] { |
| 14 | fields["appliedRevisionCommentIDs"] as? [String] ?? [] |
| 15 | } |
| 16 | |
| 17 | var revisionRequests: [CompanionLibrary.RevisionRequest] { |
| 18 | let applied = Set(appliedRevisionCommentIDs) |
| 19 | let acceptsRequests = acceptsRevisionComments |
| 20 | return comments.enumerated().compactMap { index, row in |
| 21 | guard let text = row["text"] as? String else { return nil } |
| 22 | let id = row["revisionRequestID"] as? String |
| 23 | let state: CompanionLibrary.RevisionRequest.State |
| 24 | if let id { |
| 25 | state = applied.contains(id) ? .actedOn : acceptsRequests ? .pending : .waitingForEditable |
| 26 | } else { state = .savedNote } |
| 27 | return .init(id: id ?? "legacy-\(index)", text: text, date: row["at"] as? String, state: state) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | var pendingRevisionComments: [(id: String, text: String, writing: CompanionLibrary.WritingSelection?, fromCompanion: Bool)] { |
| 32 | let applied = Set(appliedRevisionCommentIDs) |
| 33 | return comments.compactMap { comment in |
| 34 | guard let id = comment["revisionRequestID"] as? String, !applied.contains(id), |
| 35 | let text = comment["text"] as? String else { return nil } |
| 36 | let writing = (comment["writingProvider"] as? String).map { |
| 37 | CompanionLibrary.WritingSelection(provider: $0, model: comment["writingModel"] as? String) |
| 38 | } |
| 39 | return (id, text, writing, comment["source"] as? String == "companion" || writing != nil) |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | extension Workspace { |
| 45 | func withdrawnRevisionIDs(for itemID: String) -> Set<String> { |
| 46 | Set((settings["companionRevisionWithdrawals"] as? [String: [String]])?[itemID] ?? []) |
| 47 | } |
| 48 | |
| 49 | // Called inside the same database transaction as the companion change receipt. |
| 50 | func withdrawRevision(_ target: UUID, itemID: String) throws -> String? { |
| 51 | let id = target.uuidString.lowercased() |
| 52 | let record = (records + trashedRecords).first { $0.id == itemID } |
| 53 | if record?.appliedRevisionCommentIDs.contains(id) == true { |
| 54 | return "Already applied on your Mac. Your revision history is available." |
| 55 | } |
| 56 | var withdrawals = settings["companionRevisionWithdrawals"] as? [String: [String]] ?? [:] |
| 57 | if !(withdrawals[itemID] ?? []).contains(id) { |
| 58 | withdrawals[itemID, default: []].append(id) |
| 59 | try set("companionRevisionWithdrawals", to: withdrawals) |
| 60 | } |
| 61 | if var record, record.comments.contains(where: { $0["revisionRequestID"] as? String == id }) { |
| 62 | record.fields["reviewComments"] = record.comments.filter { $0["revisionRequestID"] as? String != id } |
| 63 | if record.pendingRevisionComments.isEmpty { record.fields["writingRequestError"] = nil } |
| 64 | try database?.put(record) |
| 65 | try reload() |
| 66 | } |
| 67 | if let activeRevision, activeRevision.itemID == itemID, activeRevision.ids.contains(id) { |
| 68 | activeRevision.task.cancel() |
| 69 | } |
| 70 | return nil |
| 71 | } |
| 72 | |
| 73 | func runDraftRevisionComments(model: ContentStudio.Model? = nil) async { |
| 74 | guard !runningDraftRevisions else { return } |
| 75 | runningDraftRevisions = true |
| 76 | defer { runningDraftRevisions = false } |
| 77 | do { try reload() } |
| 78 | catch { return } |
| 79 | let draftIDs = records.filter { $0.acceptsRevisionComments && !$0.pendingRevisionComments.isEmpty }.map(\.id) |
| 80 | for id in draftIDs { |
| 81 | while !Task.isCancelled { |
| 82 | refreshAfterExternalWrite() |
| 83 | guard let draft = records.first(where: { $0.id == id && $0.acceptsRevisionComments }) else { break } |
| 84 | let appliedMobileIDs = settings["companionLibraryApplied"] as? [String] ?? [] |
| 85 | let pending = draft.pendingRevisionComments.filter { request in |
| 86 | if agentConnected || (agentAccessEnabled && model != nil) { return true } |
| 87 | return writingToolsAvailable && !request.fromCompanion && !appliedMobileIDs.contains(request.id) |
| 88 | } |
| 89 | let selection = pending.first?.writing |
| 90 | var requestIDs: [String] = [] |
| 91 | var notes = "" |
| 92 | for request in pending { |
| 93 | guard request.writing == selection else { break } |
| 94 | let next = notes.isEmpty ? request.text : notes + "\n\n" + request.text |
| 95 | guard next.utf16.count <= 4_000 else { break } |
| 96 | notes = next |
| 97 | requestIDs.append(request.id) |
| 98 | } |
| 99 | guard !requestIDs.isEmpty else { break } |
| 100 | do { |
| 101 | let writer = try model ?? selection.map { try companionWritingModel($0) } |
| 102 | let task = Task { |
| 103 | _ = try await ContentStudio(workspace: self, model: writer) |
| 104 | .rewrite(draft, notes: notes, revisionCommentIDs: requestIDs) |
| 105 | } |
| 106 | activeRevision = (id, Set(requestIDs), task) |
| 107 | defer { activeRevision = nil } |
| 108 | try await withTaskCancellationHandler { try await task.value } onCancel: { task.cancel() } |
| 109 | } catch is CancellationError { |
| 110 | if Task.isCancelled { return } |
| 111 | if !withdrawnRevisionIDs(for: id).isDisjoint(with: requestIDs) { continue } |
| 112 | return |
| 113 | } catch { |
| 114 | try? withChanges { |
| 115 | guard var current = records.first(where: { $0.id == id }), !current.pendingRevisionComments.isEmpty else { return } |
| 116 | current["writingRequestError"] = selection == nil |
| 117 | ? "Your Mac couldn’t finish these revision requests. The draft and requests are saved and will be checked again." |
| 118 | : error.localizedDescription |
| 119 | try database?.put(current) |
| 120 | try reload() |
| 121 | } |
| 122 | Logger(subsystem: "com.protomota.inkspring.native", category: "RevisionComments") |
| 123 | .error("Could not apply a queued draft revision. It will be checked again.") |
| 124 | break |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | } |