Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / Workspace.swift

Raw 75.1 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import AppKit
2import Foundation
3import InkspringSchedule
4import UniformTypeIdentifiers
5
6@MainActor @Observable
7final class Workspace {
8 private(set) var records: [WorkspaceRecord] = []
9 private(set) var trashedRecords: [WorkspaceRecord] = []
10 private(set) var settings: [String: Any] = [:]
11 private(set) var directory: URL?
12 private(set) var startupError: String?
13 let socialAccounts = ManagedSocialAccounts()
14 @ObservationIgnored lazy var substackSession = SubstackSession()
15 @ObservationIgnored var substackReviews: [String: UUID] = [:]
16 var substackBusy = false
17 var companionBusy = false
18 var companionLastSync: Date?
19 var companionError: String?
20 var companionTransfer: CompanionTransfer?
21 var companionLibraryBusy = false
22 var companionLibraryTextCleanupPending = false
23 var companionLibraryError: String?
24 var projectID = ""
25 var error: String?
26 var notice: String?
27 var postResultNotice: PostResultNotice?
28 var scheduleReminderDraftID: String?
29 var backupRegistrationError: String?
30 var importingWorkspaceFolder = false
31 var restoringBackup = false
32 var runningDuePosts = false
33 var runningDraftRevisions = false
34 @ObservationIgnored var activeRevision: (itemID: String, ids: Set<String>, task: Task<Void, Error>)?
35 var runningMobileXGeneration = false
36 var refreshingReplies = false
37 var refreshingAnalytics: Set<SocialPlatform> = []
38 private var lastIdeaQueueAttempt: [String: Date] = [:]
39 var refreshingWorkSources = false
40 private(set) var verifiedAgentConnection: AgentConnectionCheck.Result?
41 private(set) var database: WorkspaceDatabase?
42 private var lastDataVersion: Int32?
43
44 init(directory override: URL? = nil) {
45 do {
46 let directory = try override ?? DailyBackup.directory()
47 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
48 attributes: [.posixPermissions: 0o700])
49 let database = try WorkspaceDatabase(url: directory.appending(path: "workspace.sqlite"))
50 self.directory = directory
51 self.database = database
52 try seed(database)
53 try reload()
54 projectID = (settings["selectedProjectID"] as? String).flatMap { id in
55 projects.first { $0.id == id }?.id
56 } ?? projects.first?.id ?? ""
57 } catch {
58 startupError = error.localizedDescription
59 }
60 }
61
62 var projects: [WorkspaceRecord] { records.filter { $0.kind == "project" } }
63 var project: WorkspaceRecord? { projects.first { $0.id == projectID } }
64 var drafts: [WorkspaceRecord] { items("draft") }
65 var workspaceDrafts: [WorkspaceRecord] {
66 records.filter { $0.projectID == projectID && ($0.kind == "draft" || $0.isLongForm) && !$0.isPublishedContent }
67 }
68 var ideas: [WorkspaceRecord] { items("idea") }
69 var sources: [WorkspaceRecord] { items("source") }
70 var agentAccessEnabled: Bool { settings["mcpEnabled"] as? Bool == true }
71 var agentConnectionVerified: Bool { agentAccessEnabled && verifiedAgentConnection != nil }
72 var agentConnected: Bool {
73 agentConnectionVerified && StudioChatAgent.writingAgent(settings: settings).executable != nil
74 }
75 var writingToolsAvailable: Bool { StudioWritingConnection(settings: settings) == .api || agentConnected }
76
77 func verifyAgentConnection() async throws -> AgentConnectionCheck.Result {
78 guard agentAccessEnabled, let directory else {
79 throw WorkspaceError("Turn on agent access before testing the connection.")
80 }
81 let command = Bundle.main.executableURL?.path ?? CommandLine.arguments[0]
82 let path = directory.path
83 do {
84 let result = try await Task.detached(priority: .userInitiated) {
85 try AgentConnectionCheck.run(command: command, workspaceOverride: path)
86 }.value
87 try Task.checkCancellation()
88 guard agentAccessEnabled else { throw CancellationError() }
89 verifiedAgentConnection = result
90 return result
91 } catch {
92 if !Task.isCancelled { verifiedAgentConnection = nil }
93 throw error
94 }
95 }
96
97 func items(_ kind: String) -> [WorkspaceRecord] {
98 records.filter { $0.kind == kind && $0.projectID == projectID }
99 }
100
101 func selectProject(_ id: String) {
102 projectID = id
103 perform { try set("selectedProjectID", to: id) }
104 }
105
106 func showPostResult(_ result: WorkspaceRecord) {
107 guard let result = PostResultNotice(result) else { return }
108 notice = nil
109 postResultNotice = result
110 }
111
112 func reload() throws {
113 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
114 let version = try database.dataVersion()
115 let records = try database.records().compactMap { stored -> WorkspaceRecord? in
116 // Keep retired writing in the database and full backups.
117 guard stored.kind != "article" || stored["platform"] != "linkedin" || stored.isLinkedInWritingArticle else { return nil }
118 guard stored.kind == "draft", !stored["linkedinArticleID"].isEmpty else { return stored }
119 var post = stored
120 post.fields["linkedinArticleID"] = nil
121 if ["queued", "due"].contains(post.scheduleStatus) {
122 var schedule = post.schedule
123 schedule["status"] = "ready"
124 schedule["slotAt"] = ""
125 post.fields["schedule"] = schedule
126 }
127 return post
128 }
129 let settings = try database.settings()
130 func inTrash(_ record: WorkspaceRecord) -> Bool {
131 !record["trashedAt"].isEmpty || record.kind == "idea" && record["status"] == "skipped"
132 }
133 self.records = records.filter { !inTrash($0) }
134 trashedRecords = records.filter(inTrash)
135 self.settings = settings
136 if !agentAccessEnabled { verifiedAgentConnection = nil }
137 lastDataVersion = version
138 }
139
140 func refreshAfterExternalWrite() {
141 guard let database, let version = try? database.dataVersion(), version != lastDataVersion else { return }
142 perform { try reload() }
143 }
144
145 func set(_ key: String, to value: Any) throws {
146 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
147 try database.set(key, to: value)
148 settings[key] = value
149 if !agentAccessEnabled { verifiedAgentConnection = nil }
150 }
151
152 @discardableResult
153 func save(_ original: WorkspaceRecord) throws -> WorkspaceRecord {
154 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
155 return try database.transaction {
156 try reload()
157 return try saveCurrent(original, to: database)
158 }
159 }
160
161 private func saveCurrent(_ original: WorkspaceRecord, to database: WorkspaceDatabase,
162 scheduling: Bool = false) throws -> WorkspaceRecord {
163 var record = original
164 guard !trashedRecords.contains(where: { $0.id == record.id }) else {
165 throw WorkspaceError("This item is in Trash. Restore it before editing.")
166 }
167 guard !(settings["libraryDeletedIDs"] as? [String] ?? []).contains(record.id) else {
168 throw WorkspaceError("This item was permanently deleted. Create a new draft or idea instead.")
169 }
170 if record.kind == "draft" {
171 record["title"] = record.draftTitle
172 record.fields["linkedinArticleID"] = nil
173 if record["platform"] != "x" { record.fields["xArticleID"] = nil }
174 }
175 if ["script", "article"].contains(record.kind) {
176 if record.kind == "script" { record["platform"] = "youtube" }
177 if record.kind == "article", !record.isLinkedInWritingArticle {
178 guard record["platform"] == "x" || record["platform"].isEmpty else {
179 throw WorkspaceError("Choose X for an article draft.")
180 }
181 record["platform"] = "x"
182 }
183 record["state"] = "draft"
184 for key in ["schedule", "remoteId", "publication", "editUrl", "sendEmail", "audience"] { record.fields[key] = nil }
185 }
186 if record.kind == "newsletter" {
187 if record.fields["audience"] == nil || record.fields["audience"] as? String == "" { record["audience"] = "everyone" }
188 if record.fields["sendEmail"] == nil { record.fields["sendEmail"] = false }
189 }
190 if let plan = record.fields["planMarkdown"] as? String { try ContentPlan.validate(plan) }
191 try validate(record)
192 let current = records.first { $0.id == record.id }
193 if current?.fields["mobileGenerationPending"] as? Bool == true, record.body != current?.body {
194 record.fields["mobileGenerationPending"] = nil
195 record.fields["generationError"] = nil
196 }
197 if record.kind == "draft", record.fields["image"] != nil, record.fields["video"] != nil {
198 guard let current, !scheduling,
199 ["image", "video"].allSatisfy({ (record.fields[$0] as? NSDictionary) == (current.fields[$0] as? NSDictionary) }) else {
200 throw WorkspaceError("Choose one attachment to keep in Writing Studio before saving.")
201 }
202 }
203 if let current, !record.isLongForm {
204 guard current["updatedAt"] == record["updatedAt"] else {
205 throw WorkspaceError("This item changed in another window or agent. Reopen the latest version before saving.")
206 }
207 if ["draft", "idea"].contains(record.kind) {
208 record.fields["reviewComments"] = current.fields["reviewComments"]
209 }
210 }
211 if record.isLongForm {
212 if let current, !["draft", "synced"].contains(current["state"]) {
213 throw WorkspaceError("Check this newsletter in Substack before editing.")
214 }
215 if let current {
216 record.fields["reviewComments"] = current.fields["reviewComments"]
217 let applied = current.appliedRevisionCommentIDs + record.appliedRevisionCommentIDs
218 record.fields["appliedRevisionCommentIDs"] = Array(NSOrderedSet(array: applied))
219 }
220 let revision = record.fields["revision"] as? Int ?? 0
221 guard revision == (current?.fields["revision"] as? Int ?? 0) else {
222 throw WorkspaceError("Reopen the latest version of this newsletter before saving.")
223 }
224 if let current {
225 guard current["updatedAt"] == record["updatedAt"] else {
226 throw WorkspaceError("Reopen the latest version of this newsletter before saving.")
227 }
228 for key in record.kind == "newsletter" ? ["remoteId", "publication", "editUrl", "syncedRevision", "remoteFingerprint", "embeddedCoverURL", "error"] : [] {
229 record.fields[key] = current.fields[key]
230 }
231 }
232 record.fields["state"] = current?["state"] ?? "draft"
233 record.fields["revision"] = revision + 1
234 }
235 if let current, record.kind == "draft" {
236 guard !["posting", "posted"].contains(current.scheduleStatus) else {
237 throw WorkspaceError("This post is already publishing or published. Create a new draft to revise it.")
238 }
239 let keys = ["title", "content", "format", "platform", "xArticleID", "tiktokCoverTime"]
240 let oldContent = keys.map { current[$0] }
241 let newContent = keys.map { record[$0] }
242 let oldMedia = ["image", "video", "videoThumbnail", "linkedinDestination"].map { current.fields[$0] as? NSDictionary }
243 let newMedia = ["image", "video", "videoThumbnail", "linkedinDestination"].map { record.fields[$0] as? NSDictionary }
244 if !scheduling, ["queued", "due"].contains(current.scheduleStatus),
245 oldContent != newContent || oldMedia != newMedia {
246 record.fields["schedule"] = ["status": "ready", "slotAt": "",
247 "error": "This post changed. Review it and choose a new posting time."]
248 }
249 }
250 record.markUpdated(after: current?["updatedAt"])
251 record = try database.put(record)
252 try reload()
253 return record
254 }
255
256 func withChanges<T>(_ changes: () throws -> T) throws -> T {
257 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
258 do {
259 return try database.transaction {
260 try reload()
261 return try changes()
262 }
263 } catch {
264 try? reload()
265 throw error
266 }
267 }
268
269 func revisionHistory(for record: WorkspaceRecord) throws -> [ContentRevision] {
270 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
271 return try database.revisionHistory(recordID: record.id)
272 }
273
274 func retainRevision(_ revision: ContentRevision, recordID: String) throws {
275 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
276 try database.storeRevision(revision, recordID: recordID)
277 }
278
279 func restoreRevision(_ revision: ContentRevision, to expected: WorkspaceRecord) throws -> WorkspaceRecord {
280 try withChanges {
281 guard var current = records.first(where: { $0.id == expected.id && $0.kind == expected.kind }),
282 current["updatedAt"] == expected["updatedAt"],
283 ["draft", "newsletter", "script", "article"].contains(current.kind),
284 !["posting", "posted", "uncertain"].contains(current.scheduleStatus),
285 current.kind != "newsletter" || ["draft", "synced"].contains(current["state"]) else {
286 throw WorkspaceError("This item changed. Reopen the latest version before restoring.")
287 }
288 current["title"] = revision.title
289 current[current.isLongForm ? "body" : "content"] = revision.text
290 if let format = revision.format { current["format"] = format }
291 if let subtitle = revision.subtitle { current["subtitle"] = subtitle }
292 return try save(current)
293 }
294 }
295
296 func updateFromAgent<T>(_ changes: () throws -> T) throws -> T {
297 try withChanges {
298 guard settings["mcpEnabled"] as? Bool == true else {
299 throw WorkspaceError("Turn on agent access in Inkspring Settings.")
300 }
301 return try changes()
302 }
303 }
304
305 func perform(_ action: () throws -> Void) {
306 do { try action() } catch { self.error = error.localizedDescription }
307 }
308
309 func mediaURL(_ record: WorkspaceRecord) -> URL? {
310 if record.kind == "draft", record["format"] == "video" { return videoURL(record) }
311 return imageURL(record) ?? videoURL(record)
312 }
313
314 func imageURL(_ record: WorkspaceRecord) -> URL? {
315 storedImageURL(record.fields["image"] ?? record.fields["coverImage"])
316 }
317
318 func videoThumbnailURL(_ record: WorkspaceRecord) -> URL? {
319 guard record["platform"] != "x", record.fields["video"] is [String: Any] else { return nil }
320 return storedImageURL(record.fields["videoThumbnail"])
321 }
322
323 private func storedImageURL(_ value: Any?) -> URL? {
324 if let image = value as? [String: Any],
325 let file = image["file"] as? String,
326 file.range(of: #"^[a-f0-9-]{36}\.(png|jpe?g|webp)$"#, options: .regularExpression) != nil {
327 return directory?.appending(path: "images").appending(path: file)
328 }
329 return nil
330 }
331
332 func videoURL(_ record: WorkspaceRecord) -> URL? {
333 if let video = record.fields["video"] as? [String: Any], let id = video["id"] as? String,
334 let path = records.first(where: { $0.kind == "local-video" && $0.id == id })?["path"],
335 !path.isEmpty {
336 return URL(fileURLWithPath: path)
337 }
338 return nil
339 }
340
341 func attachImage(_ source: URL) throws -> [String: String] {
342 let attributes = try source.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey, .isSymbolicLinkKey])
343 guard attributes.isRegularFile == true, attributes.isSymbolicLink != true,
344 (1...30_000_000).contains(attributes.fileSize ?? 0),
345 let image = NSImage(contentsOf: source), image.isValid, let directory else {
346 throw WorkspaceError("Choose a valid local image of up to 30 MB.")
347 }
348 let fileExtension = source.pathExtension.lowercased()
349 guard ["png", "jpeg", "jpg", "webp"].contains(fileExtension) else {
350 throw WorkspaceError("Choose a PNG, JPEG or WebP image.")
351 }
352 let images = directory.appending(path: "images", directoryHint: .isDirectory)
353 try FileManager.default.createDirectory(at: images, withIntermediateDirectories: true,
354 attributes: [.posixPermissions: 0o700])
355 let name = UUID().uuidString.lowercased() + "." + fileExtension
356 try FileManager.default.copyItem(at: source, to: images.appending(path: name))
357 return ["file": name, "origin": "Attached"]
358 }
359
360 func addComment(to record: WorkspaceRecord, text: String, revisionRequestID: String? = nil,
361 writingSelection: CompanionLibrary.WritingSelection? = nil, fromCompanion: Bool = false) throws {
362 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
363 try withChanges {
364 guard var current = records.first(where: { $0.id == record.id && $0.kind == record.kind }) else {
365 throw WorkspaceError("This item is no longer available.")
366 }
367 if let revisionRequestID,
368 (withdrawnRevisionIDs(for: record.id).contains(revisionRequestID) ||
369 current.comments.contains(where: { $0["revisionRequestID"] as? String == revisionRequestID })) { return }
370 guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
371 text.utf16.count <= 4000, current.comments.count < 100 else {
372 throw WorkspaceError("Enter a revision request of up to 4,000 characters. Each item can hold 100 requests.")
373 }
374 var comment = ["text": text, "at": WorkspaceRecord.timestamp]
375 if ["draft", "idea"].contains(current.kind) || current.isLongForm { comment["revisionRequestID"] = revisionRequestID }
376 if fromCompanion { comment["source"] = "companion" }
377 comment["writingProvider"] = writingSelection?.provider
378 comment["writingModel"] = writingSelection?.model
379 current.fields["writingRequestError"] = nil
380 current.fields["reviewComments"] = current.comments + [comment]
381 try database.put(current)
382 try reload()
383 }
384 }
385
386 func trashLibraryItem(_ input: WorkspaceRecord) throws {
387 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
388 let lease = try claimPublication()
389 defer { withExtendedLifetime(lease) {} }
390 try withChanges {
391 guard var record = records.first(where: { $0.id == input.id && $0.kind == input.kind }),
392 record["updatedAt"] == input["updatedAt"], ["draft", "idea"].contains(record.kind) else {
393 throw WorkspaceError("This item changed. Refresh it before deleting.")
394 }
395 guard !["posting", "posted", "uncertain"].contains(record.scheduleStatus),
396 !records.contains(where: { ["publication", "reply-inbox"].contains($0.kind) && $0["draftId"] == record.id }) else {
397 throw WorkspaceError("This post has publishing history and cannot be deleted here.")
398 }
399 record["trashedAt"] = WorkspaceRecord.timestamp
400 if record.kind == "idea", record["status"] == "draft" {
401 record["status"] = "skipped"
402 record["skippedAt"] = WorkspaceRecord.timestamp
403 }
404 if record.kind == "draft" { record.fields["schedule"] = [:] as [String: Any] }
405 record.markUpdated()
406 try database.put(record)
407 try reload()
408 }
409 }
410
411 func restoreLibraryItem(_ input: WorkspaceRecord) throws {
412 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
413 try withChanges {
414 guard var record = trashedRecords.first(where: { $0.id == input.id && $0.kind == input.kind }),
415 record["updatedAt"] == input["updatedAt"] else {
416 throw WorkspaceError("This item changed. Refresh Trash and try again.")
417 }
418 record["trashedAt"] = ""
419 if record.kind == "idea", record["status"] == "skipped" { record["status"] = "draft"; record["skippedAt"] = "" }
420 record.markUpdated()
421 try database.put(record)
422 try reload()
423 }
424 }
425
426 func deleteLibraryItem(_ input: WorkspaceRecord) throws {
427 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
428 try withChanges {
429 guard let record = trashedRecords.first(where: { $0.id == input.id && $0.kind == input.kind }),
430 record["updatedAt"] == input["updatedAt"] else {
431 throw WorkspaceError("Only items already in Trash can be permanently deleted.")
432 }
433 // Keep linked drafts and media; permanent deletion removes only the item and its links.
434 for var draft in records + trashedRecords where record.kind == "idea" && draft.kind == "draft" && draft["ideaId"] == record.id {
435 draft["ideaId"] = ""
436 draft.markUpdated()
437 try database.put(draft)
438 }
439 for var idea in records + trashedRecords where record.kind == "draft" && idea.kind == "idea" {
440 let versions = idea.fields["versions"] as? [String: String] ?? [:]
441 guard versions.values.contains(record.id) else { continue }
442 let remaining = versions.filter { $0.value != record.id }
443 idea.fields["versions"] = remaining
444 if remaining.isEmpty { idea["status"] = "draft"; idea["pickedAt"] = "" }
445 idea.markUpdated()
446 try database.put(idea)
447 }
448 for consent in records where consent.kind == "tiktok-consent" && consent["draftId"] == record.id {
449 try database.remove(consent.id, kind: consent.kind)
450 }
451 try database.remove(record.id, kind: record.kind)
452 var deletedIDs = settings["libraryDeletedIDs"] as? [String] ?? []
453 if !deletedIDs.contains(record.id) { deletedIDs.append(record.id) }
454 try database.set("libraryDeletedIDs", to: deletedIDs)
455 try reload()
456 }
457 }
458
459 func updatePostText(_ input: WorkspaceRecord, title: String, text: String, format: String? = nil,
460 xArticleID: String? = nil) throws {
461 try withChanges {
462 guard var record = records.first(where: { $0.kind == input.kind && $0.id == input.id }),
463 record["updatedAt"] == input["updatedAt"] else {
464 throw WorkspaceError("This item changed. Reopen the latest version before editing.")
465 }
466 switch record.kind {
467 case "idea":
468 let angle = text.trimmingCharacters(in: .whitespacesAndNewlines)
469 guard record["status"] == "draft", (1...2000).contains(angle.utf16.count) else {
470 throw WorkspaceError("Enter up to 2,000 characters for an open idea.")
471 }
472 record["topic"] = title.trimmingCharacters(in: .whitespacesAndNewlines)
473 record["previousText"] = record.body
474 record["text"] = angle
475 record["revisedAt"] = WorkspaceRecord.timestamp
476 record["notesReply"] = ""
477 case "draft":
478 record["title"] = title.trimmingCharacters(in: .whitespacesAndNewlines)
479 record["content"] = text
480 if let format, record["platform"] == "x", XPostStyle(rawValue: format) != nil {
481 record["format"] = format
482 }
483 if let xArticleID, record["platform"] == "x" {
484 record["xArticleID"] = xArticleID
485 }
486 default:
487 throw WorkspaceError("Choose an idea or post to edit.")
488 }
489 try save(record)
490 }
491 }
492
493 private func validate(_ record: WorkspaceRecord) throws {
494 let title = switch record.kind {
495 case "project": record["name"]
496 case "local-video": record["name"]
497 case "idea": record["topic"]
498 default: record["title"]
499 }
500 guard !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
501 throw WorkspaceError("Enter a title before saving.")
502 }
503 if !["project", "local-video"].contains(record.kind), !projects.contains(where: { $0.id == record.projectID }) {
504 throw WorkspaceError("Choose an existing project.")
505 }
506 if record.kind == "source", !record["url"].isEmpty {
507 guard let components = URLComponents(string: record["url"]), components.scheme == "https",
508 components.host != nil, components.user == nil, components.password == nil else {
509 throw WorkspaceError("Enter an HTTPS source link.")
510 }
511 }
512 if record.kind == "draft" {
513 guard record["title"].utf16.count <= 200, record["content"].utf16.count <= 40_000 else {
514 throw WorkspaceError("Use up to 200 characters for the title and 40,000 for the draft.")
515 }
516 if !record["xArticleID"].isEmpty,
517 records.first(where: { $0.id == record.id })?["xArticleID"] != record["xArticleID"] {
518 guard record["platform"] == "x",
519 records.contains(where: {
520 $0.isXArticle && $0.projectID == record.projectID && $0.id == record["xArticleID"]
521 }) else {
522 throw WorkspaceError("Choose an X article from this project.")
523 }
524 }
525 if record["format"] == "reply" {
526 let reply = record.fields["replyTo"] as? [String: String]
527 let url = reply?["url"] ?? ""
528 let text = (reply?["text"] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
529 guard record["platform"] == "x", !url.isEmpty || !text.isEmpty else {
530 throw WorkspaceError("Enter the X post you are replying to.")
531 }
532 guard url.isEmpty || url.range(of: #"^https://(?:www\.|mobile\.)?(?:x|twitter)\.com/(?:[A-Za-z0-9_]{1,15}|i(?:/web)?)/status(?:es)?/[0-9]{1,25}(?:[/?#]|$)"#,
533 options: .regularExpression) != nil else {
534 throw WorkspaceError("Enter a valid X post link.")
535 }
536 }
537 }
538 if record.isLongForm {
539 guard record["title"].utf16.count <= 300 else {
540 throw WorkspaceError("Shorten the title to 300 characters or less.")
541 }
542 guard record["subtitle"].utf16.count <= 1_000 else {
543 throw WorkspaceError("Shorten the subtitle to 1,000 characters or less.")
544 }
545 guard record["body"].utf16.count <= 200_000 else {
546 throw WorkspaceError("Shorten the newsletter to 200,000 characters or less.")
547 }
548 guard !record["body"].contains("\0") else {
549 throw WorkspaceError("Remove the invalid control character from the newsletter text.")
550 }
551 if ["script", "article"].contains(record.kind) { return }
552 guard ["everyone", "only_paid", "founding"].contains(record["audience"]) else {
553 throw WorkspaceError("Choose an audience in Newsletter settings.")
554 }
555 guard record.fields["sendEmail"] is Bool else {
556 throw WorkspaceError("Check the Email subscribers setting in Newsletter settings.")
557 }
558 }
559 if record.kind == "idea", record["text"].trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
560 throw WorkspaceError("Enter the idea before saving.")
561 }
562 }
563
564 private func seed(_ database: WorkspaceDatabase) throws {
565 guard try database.settings()["initialized"] == nil, try database.records().isEmpty else { return }
566 var project = WorkspaceRecord.new("project")
567 project["name"] = "The independent studio"
568 project["description"] = "A one-person lab making useful, private desktop software. Small tools that give people room to do their own work."
569 project["audience"] = "Independent makers, curious people, and founders who care about owning their tools."
570 project["voice"] = "Plainspoken, specific, a little opinionated. First person singular. No marketing jargon."
571 project.fields["sample"] = true
572 var draft = WorkspaceRecord.new("draft", projectID: project.id)
573 draft["title"] = "Tools you can keep"
574 draft["content"] = "I like software that leaves me with a folder I can open.\n\nNotes, drafts, projects. Still there when the Wi-Fi drops. Still mine if the company disappears.\n\nThat feels like a reasonable starting point for a tool."
575 draft.fields["sample"] = true
576 var source = WorkspaceRecord.new("source", projectID: project.id)
577 source["title"] = "Show the unfinished thing"
578 source["text"] = "Sample research note: a small detail from the making of a tool can be more interesting than a polished launch announcement. Show a real decision, the constraint, and what changed."
579 source["origin"] = "Sample note"
580 source.fields["sample"] = true
581 try database.transaction {
582 try database.put(project)
583 try database.put(draft)
584 try database.put(source)
585 try database.set("initialized", to: true)
586 }
587 }
588}
589
590extension Workspace {
591 func exportBackup() {
592 let panel = NSSavePanel()
593 panel.allowedContentTypes = [.zip]
594 panel.nameFieldStringValue = "Inkspring-backup-\(Date.now.formatted(.iso8601.year().month().day().dateSeparator(.dash))).zip"
595 guard panel.runModal() == .OK, let url = panel.url else { return }
596 perform {
597 try exportBackup(to: url)
598 notice = "Backup ZIP saved"
599 }
600 }
601
602 func exportBackup(to url: URL) throws {
603 guard let database, let directory else { throw WorkspaceError("The workspace is unavailable.") }
604 let snapshot = try database.snapshot()
605 try WorkspaceBackup.export(records: snapshot.records, preferences: snapshot.settings, directory: directory, to: url)
606 }
607
608 func restoreBackup() async {
609 guard !restoringBackup, !importingWorkspaceFolder else { return }
610 let panel = NSOpenPanel()
611 panel.allowedContentTypes = [.zip, .json]
612 guard panel.runModal() == .OK, let url = panel.url else { return }
613 restoringBackup = true
614 let accessed = url.startAccessingSecurityScopedResource()
615 defer {
616 if accessed { url.stopAccessingSecurityScopedResource() }
617 restoringBackup = false
618 }
619 do {
620 try await ICloudBackup.downloadIfNeeded(url)
621 try reviewRestore(url)
622 } catch {
623 self.error = error.localizedDescription
624 }
625 }
626
627 func importWorkspaceFolder() async {
628 guard let directory, !importingWorkspaceFolder, !restoringBackup else { return }
629 let panel = NSOpenPanel()
630 panel.title = "Choose an Inkspring workspace folder"
631 panel.canChooseDirectories = true
632 panel.canChooseFiles = false
633 if let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
634 panel.directoryURL = support
635 }
636 guard panel.runModal() == .OK, let source = panel.url else { return }
637 importingWorkspaceFolder = true
638 defer { importingWorkspaceFolder = false }
639 do {
640 let archive = try await Task.detached(priority: .utility) {
641 try WorkspaceMigration.prepareImport(from: source, into: directory)
642 }.value
643 defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }
644 try reviewRestore(archive, importingFolder: true)
645 } catch {
646 self.error = error.localizedDescription
647 }
648 }
649
650 private func reviewRestore(_ url: URL, importingFolder: Bool = false) throws {
651 guard let directory else { throw WorkspaceError("The workspace is unavailable.") }
652 let (backup, files) = try WorkspaceBackup.stage(url, in: directory)
653 defer {
654 if let staging = backup.stagingDirectory { try? FileManager.default.removeItem(at: staging) }
655 }
656 try reload()
657 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
658 let plan = try backup.restorePlan(over: database.records())
659 let added = backup.records.count - plan.preservedIDs.count - plan.replacements.count
660 let alert = NSAlert()
661 alert.messageText = importingFolder ? "Import this workspace?" : "Restore this backup?"
662 alert.informativeText = "Add \(added) records and restore \(backup.media.count) media files. Replace \(plan.replacements.count) matching records. Restored posts will need a new schedule."
663 if !plan.preservedIDs.isEmpty {
664 alert.informativeText += "\n\nKeep \(plan.preservedIDs.count) matching records with publishing history or Substack links."
665 }
666 if importingFolder {
667 alert.informativeText += "\n\nThe source workspace stays unchanged. Reconnect social accounts in this app after importing."
668 } else if backup.isLegacy {
669 alert.informativeText += "\n\nOlder JSON backups contain text only. Reattach media after restoring."
670 }
671 alert.addButton(withTitle: "Cancel")
672 alert.addButton(withTitle: importingFolder ? "Import workspace" : "Restore backup")
673 guard alert.runModal() == .alertSecondButtonReturn else { return }
674 try apply(backup, files: files, reviewedPlan: plan)
675 notice = importingFolder ? "Workspace imported" : "Workspace restored"
676 }
677
678 func apply(_ backup: WorkspaceBackup, files: [String: URL], reviewedPlan: WorkspaceBackup.RestorePlan? = nil) throws {
679 guard let directory, let database else { throw WorkspaceError("The workspace is unavailable.") }
680 let lease = try claimPublication()
681 defer { withExtendedLifetime(lease) {} }
682 let initialPlan = try backup.restorePlan(over: database.records())
683 guard reviewedPlan == nil || reviewedPlan == initialPlan else {
684 throw WorkspaceError("The workspace changed after review. Review the restore again.")
685 }
686 let manager = FileManager.default
687 var created: [URL] = []
688 var images: [String: String] = [:]
689 var videos: [String: (WorkspaceBackup.Media, URL)] = [:]
690 do {
691 for item in backup.media {
692 guard let input = files[item.entry], try fileDigest(input) == (item.sha256, item.size) else {
693 throw WorkspaceError("A staged backup file is missing or changed.")
694 }
695 let fileExtension = URL(fileURLWithPath: item.entry).pathExtension
696 let imageID = UUID(uuidString: uuidText(from: item.sha256))!.uuidString.lowercased()
697 let name = (item.kind == "image" ? imageID : item.sha256) + "." + fileExtension
698 let folder = directory.appending(path: item.kind == "image" ? "images" : "videos", directoryHint: .isDirectory)
699 try manager.createDirectory(at: folder, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
700 let target = folder.appending(path: name)
701 if manager.fileExists(atPath: target.path) {
702 let attributes = try target.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
703 guard attributes.isRegularFile == true, attributes.isSymbolicLink != true,
704 try fileDigest(target) == (item.sha256, item.size) else {
705 throw WorkspaceError("A restored file conflicts with an existing attachment.")
706 }
707 } else {
708 let temporary = folder.appending(path: ".restore-\(UUID().uuidString)")
709 defer { try? manager.removeItem(at: temporary) }
710 try manager.copyItem(at: input, to: temporary)
711 try manager.linkItem(at: temporary, to: target)
712 created.append(target)
713 }
714 if let original = item.file { images[original] = name }
715 if let id = item.id { videos[id] = (item, target) }
716 }
717 try database.transaction {
718 let current = try database.records()
719 let plan = try backup.restorePlan(over: current)
720 guard reviewedPlan == nil || reviewedPlan == plan else {
721 throw WorkspaceError("The workspace changed after review. Review the restore again.")
722 }
723 let local = Dictionary(uniqueKeysWithValues: current.map { ($0.id, $0) })
724 let rows = backup.records.filter { $0.kind == "project" } + backup.records.filter { $0.kind != "project" }
725 for input in rows where !plan.preservedIDs.contains(input.id) {
726 var row = backup.restored(input)
727 for key in ["image", "coverImage", "videoThumbnail"] {
728 if var image = row.fields[key] as? [String: Any],
729 let name = image["file"] as? String, let replacement = images[name] {
730 image["file"] = replacement
731 row.fields[key] = image
732 }
733 }
734 if row.kind == "local-video", let (item, target) = videos[row.id] {
735 row["path"] = target.path
736 row["hash"] = item.sha256
737 row.fields["size"] = item.size
738 row.fields["mtime"] = try target.resourceValues(forKeys: [.contentModificationDateKey])
739 .contentModificationDate.map { $0.timeIntervalSince1970 * 1000 }
740 }
741 if let previous = local[row.id] {
742 row.fields["updatedAt"] = previous.fields["updatedAt"]
743 if NSDictionary(dictionary: row.fields).isEqual(to: previous.fields) { continue }
744 row.markUpdated(after: previous["updatedAt"])
745 }
746 try database.put(row)
747 }
748 for (key, value) in backup.preferences { try database.set(key, to: value) }
749 for key in ["autoPost", "ideaQueueAutomatic", "mcpEnabled", "mcpAllowPosting"] {
750 try database.set(key, to: false)
751 }
752 try database.set("replyMonitoringX", to: ["enabled": false])
753 try database.set("analyticsAutomatic", to: [String: Bool]())
754 if var schedules = try database.settings()["workSourceSchedules"] as? [String: [String: Any]] {
755 for key in schedules.keys { schedules[key]?["enabled"] = false }
756 try database.set("workSourceSchedules", to: schedules)
757 }
758 try database.set("backupRestoredAt", to: WorkspaceRecord.timestamp)
759 }
760 } catch {
761 for file in created { try? manager.removeItem(at: file) }
762 throw error
763 }
764 try reload()
765 if let first = backup.records.last(where: { $0.kind == "project" }) { selectProject(first.id) }
766 }
767
768 private func uuidText(from digest: String) -> String {
769 let hex = Array(digest.prefix(32))
770 return [0..<8, 8..<12, 12..<16, 16..<20, 20..<32].map { String(hex[$0]) }.joined(separator: "-")
771 }
772}
773
774extension Workspace {
775 func writeGeneratedImage(_ data: Data, fileExtension: String) throws -> String {
776 guard let directory, ["png", "jpeg", "jpg", "webp"].contains(fileExtension) else {
777 throw WorkspaceError("The generated image format is unsupported.")
778 }
779 let images = directory.appending(path: "images", directoryHint: .isDirectory)
780 try FileManager.default.createDirectory(at: images, withIntermediateDirectories: true,
781 attributes: [.posixPermissions: 0o700])
782 let file = UUID().uuidString.lowercased() + "." + fileExtension
783 try data.write(to: images.appending(path: file), options: .atomic)
784 return file
785 }
786}
787
788extension Workspace {
789 func chooseDailyBackupFolder(startingAt: URL? = nil) {
790 guard let database else { return }
791 let panel = NSOpenPanel()
792 panel.title = "Choose a folder for daily Inkspring backups"
793 panel.canChooseDirectories = true
794 panel.canChooseFiles = false
795 panel.canCreateDirectories = true
796 panel.directoryURL = startingAt
797 guard panel.runModal() == .OK, let url = panel.url else { return }
798 perform {
799 try DailyBackup.chooseFolder(url, database: database)
800 try reload()
801 }
802 Task { await checkDailyBackup() }
803 }
804
805 func setDailyBackupEnabled(_ enabled: Bool) {
806 perform {
807 try set(DailyBackup.enabledKey, to: enabled)
808 guard !DailyBackup.usesTestWorkspace else { return }
809 let service = DailyBackup.service
810 if enabled && [.notRegistered, .notFound].contains(service.status) {
811 try service.register()
812 try set(DailyBackup.registrationKey, to: DailyBackup.registrationVersion() ?? "")
813 } else if !enabled && [.enabled, .requiresApproval].contains(service.status) {
814 try service.unregister()
815 }
816 backupRegistrationError = nil
817 }
818 if enabled { Task { await checkDailyBackup() } }
819 }
820
821 func refreshDailyBackupRegistration() async {
822 guard settings[DailyBackup.enabledKey] as? Bool == true, let directory else { return }
823 do {
824 if try await DailyBackup.refreshRegistration(in: directory) { try reload() }
825 backupRegistrationError = nil
826 } catch {
827 backupRegistrationError = error.localizedDescription
828 }
829 }
830
831 func checkDailyBackup(requested: Bool = false) async {
832 guard requested || settings[DailyBackup.enabledKey] as? Bool == true, let directory else { return }
833 let backup = Task.detached(priority: .utility) { try DailyBackup.run(in: directory, requested: requested) }
834 do {
835 if try await backup.value != nil, requested { notice = "Backup ZIP saved" }
836 } catch {
837 if requested { self.error = error.localizedDescription }
838 }
839 // The background helper may have updated these settings in another process.
840 if let current = try? database?.settings() { settings = current }
841 }
842}
843
844extension Workspace {
845 func beginPublication(_ plan: SocialPublishPlan, automatic: Bool, fromAgent: Bool) throws -> WorkspaceRecord {
846 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
847 return try database.transaction {
848 try reload()
849 guard let draft = records.first(where: { $0.id == plan.draftID && $0.kind == "draft" }),
850 draft["updatedAt"] == plan.revision, !["posting", "posted"].contains(draft.scheduleStatus) else {
851 throw WorkspaceError("This draft changed or already went out. Review it again.")
852 }
853 if fromAgent, settings["mcpEnabled"] as? Bool != true || settings["mcpAllowPosting"] as? Bool != true {
854 throw WorkspaceError("Immediate agent posting is off in Inkspring Settings.")
855 }
856 if automatic, settings["autoPost"] as? Bool != true || draft.scheduleStatus != "queued" {
857 throw WorkspaceError("Automatic posting is paused or this post was unscheduled.")
858 }
859 let receipts = records.filter { $0.kind == "publication" && $0["draftId"] == draft.id }
860 guard !receipts.contains(where: { ["publishing", "published", "uncertain"].contains($0["status"]) }) else {
861 throw WorkspaceError("This post already went out or has an unresolved publishing attempt. Check the account before retrying.")
862 }
863 if let partial = receipts.first(where: { $0["status"] == "partial" }), partial["fingerprint"] != plan.fingerprint {
864 throw WorkspaceError("Part of this thread already went out. Restore the reviewed text before resuming.")
865 }
866 var receipt = receipts.first { $0["fingerprint"] == plan.fingerprint && ["failed", "partial"].contains($0["status"]) }
867 ?? .new("publication", projectID: draft.projectID)
868 receipt["draftId"] = draft.id
869 receipt["platform"] = plan.platform.rawValue
870 receipt["title"] = plan.title
871 receipt["accountId"] = plan.accountID
872 receipt["accountName"] = plan.accountName
873 receipt["fingerprint"] = plan.fingerprint
874 if let destination = plan.linkedInDestination { receipt.fields["linkedinDestination"] = destination.fields }
875 receipt["replyToId"] = plan.replyID ?? ""
876 receipt["status"] = "publishing"
877 receipt["error"] = ""
878 if receipt.fields["steps"] == nil { receipt.fields["steps"] = [[String: Any]]() }
879 try database.put(receipt)
880 var locked = draft
881 var schedule = locked.schedule
882 if !automatic { schedule["slotAt"] = nil }
883 schedule["status"] = "posting"
884 locked.fields["schedule"] = schedule
885 try database.put(locked)
886 try reload()
887 return receipt
888 }
889 }
890
891 func saveNewsletterEditor(_ edited: WorkspaceRecord, basedOn base: WorkspaceRecord) throws -> WorkspaceRecord {
892 try withChanges {
893 guard var current = records.first(where: { $0.isLongForm && $0.kind == edited.kind && $0.id == edited.id }) else {
894 guard (base.fields["revision"] as? Int ?? 0) == 0 else {
895 throw WorkspaceError("This newsletter is no longer available.")
896 }
897 return try save(edited)
898 }
899 guard let body = NewsletterMerge.merge(base: base.body, mac: edited.body, mobile: current.body) else {
900 throw WorkspaceError("Both versions changed the same part of this newsletter. Your edits are still open here.")
901 }
902 current["body"] = body
903 for key in ["title", "subtitle", "audience"] where base[key] != edited[key] {
904 current[key] = edited[key]
905 }
906 for key in ["sendEmail", "coverImage"] {
907 if (base.fields[key] as? NSObject) != (edited.fields[key] as? NSObject) {
908 current.fields[key] = edited.fields[key]
909 }
910 }
911 return try save(current)
912 }
913 }
914
915 func patchNewsletter(_ expected: WorkspaceRecord, _ changes: [String: Any]) throws -> WorkspaceRecord {
916 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
917 return try withChanges {
918 guard var item = records.first(where: { $0.kind == "newsletter" && $0.id == expected.id }),
919 item.fields["revision"] as? Int == expected.fields["revision"] as? Int,
920 item["updatedAt"] == expected["updatedAt"], item["state"] == expected["state"] else {
921 throw WorkspaceError("The newsletter changed. Open the latest version and check Substack.")
922 }
923 item.fields.merge(changes) { _, replacement in replacement }
924 item.markUpdated(after: expected["updatedAt"])
925 try database.put(item)
926 try reload()
927 return item
928 }
929 }
930
931 func recoverInterruptedNewsletters() {
932 guard records.contains(where: { $0.kind == "newsletter" && ["syncing", "releasing"].contains($0["state"]) }),
933 let lease = try? claimPublication() else { return }
934 defer { withExtendedLifetime(lease) {} }
935 perform {
936 try reload()
937 for item in records where item.kind == "newsletter" && ["syncing", "releasing"].contains(item["state"]) {
938 _ = try patchNewsletter(item, [
939 "state": "uncertain",
940 "error": "Inkspring closed before Substack confirmed the result. Check Substack before trying again."
941 ])
942 }
943 }
944 }
945
946 func claimPublication() throws -> PublicationLease {
947 guard let directory else { throw WorkspaceError("The workspace is unavailable.") }
948 return try PublicationLease(directory: directory)
949 }
950
951 func allowPublicationRetry(_ id: String) throws {
952 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
953 let lease = try claimPublication()
954 defer { withExtendedLifetime(lease) {} }
955 try database.transaction {
956 try reload()
957 guard var receipt = records.first(where: { $0.kind == "publication" && $0.id == id }),
958 ["publishing", "uncertain"].contains(receipt["status"]) else {
959 throw WorkspaceError("Wait for the active publishing attempt to finish.")
960 }
961 let steps = receipt.fields["steps"] as? [[String: Any]] ?? []
962 if receipt["contentKind"] == "article", !steps.isEmpty {
963 throw WorkspaceError("X already confirmed this article’s post ID. Open the published article instead of retrying.")
964 }
965 receipt["status"] = steps.isEmpty ? "failed" : "partial"
966 receipt["error"] = "The author checked the platform and allowed another attempt."
967 try updatePublication(receipt)
968 }
969 }
970
971 func recoverInterruptedPublications() {
972 guard let database, records.contains(where: {
973 $0.kind == "publication" && $0["status"] == "publishing" || $0.kind == "draft" && $0.scheduleStatus == "posting"
974 }), let lease = try? claimPublication() else { return }
975 defer { withExtendedLifetime(lease) {} }
976 perform {
977 try withChanges {
978 let message = "Publishing was interrupted. Check the connected account before retrying."
979 var receipts = records.filter { $0.kind == "publication" }
980 for index in receipts.indices where receipts[index]["status"] == "publishing" {
981 receipts[index]["status"] = "uncertain"
982 receipts[index]["error"] = message
983 receipts[index].markUpdated()
984 try database.put(receipts[index])
985 if receipts[index]["contentKind"] == "article",
986 var article = records.first(where: { $0.kind == "article" && $0.id == receipts[index]["draftId"] }) {
987 article["state"] = "uncertain"
988 article["articlePublicationStatus"] = "uncertain"
989 article["articlePublicationError"] = message
990 try database.put(article)
991 }
992 }
993 let receiptsByDraft = Dictionary(grouping: receipts, by: { $0["draftId"] })
994 for draft in records where draft.kind == "draft" && draft.scheduleStatus == "posting" {
995 let attempts = receiptsByDraft[draft.id] ?? []
996 if let receipt = attempts.first(where: { $0["status"] == "published" })
997 ?? attempts.first(where: { $0["status"] == "uncertain" })
998 ?? attempts.first(where: { ["failed", "partial"].contains($0["status"]) }) {
999 try database.put(draftAfterPublication(draft, receipt: receipt))
1000 } else {
1001 var receipt = WorkspaceRecord.new("publication", projectID: draft.projectID)
1002 receipt["title"] = draft.title
1003 receipt["draftId"] = draft.id
1004 receipt["platform"] = draft["platform"]
1005 receipt["status"] = "uncertain"
1006 receipt["error"] = message
1007 try database.put(receipt)
1008 try database.put(draftAfterPublication(draft, receipt: receipt))
1009 }
1010 }
1011 try reload()
1012 }
1013 }
1014 }
1015
1016 func updatePublication(_ receipt: WorkspaceRecord) throws {
1017 if receipt["contentKind"] == "article" { try updateXArticlePublication(receipt); return }
1018 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1019 try database.transaction {
1020 try reload()
1021 var receipt = receipt
1022 receipt.markUpdated()
1023 try database.put(receipt)
1024 if receipt["status"] != "publishing",
1025 let draft = records.first(where: { $0.id == receipt["draftId"] && $0.kind == "draft" }),
1026 draft.scheduleStatus != "posted" || receipt["status"] == "published" {
1027 try database.put(draftAfterPublication(draft, receipt: receipt))
1028 }
1029 try reload()
1030 }
1031 }
1032
1033 func savePublishedPostLink(_ input: WorkspaceRecord, address: String) throws {
1034 guard let url = CompanionPublication.postURL(address.trimmingCharacters(in: .whitespacesAndNewlines)) else {
1035 throw WorkspaceError("Enter a valid HTTPS link to the published post.")
1036 }
1037 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1038 try withChanges {
1039 guard var draft = records.first(where: { $0.id == input.id && $0.kind == "draft" }),
1040 draft.scheduleStatus == "posted", draft["updatedAt"] == input["updatedAt"] else {
1041 throw WorkspaceError("This published post changed. Open it again before adding its link.")
1042 }
1043 var schedule = draft.schedule
1044 schedule["url"] = url.absoluteString
1045 draft.fields["schedule"] = schedule
1046 draft.markUpdated()
1047 try database.put(draft)
1048 try reload()
1049 }
1050 }
1051
1052 private func draftAfterPublication(_ input: WorkspaceRecord, receipt: WorkspaceRecord) -> WorkspaceRecord {
1053 var draft = input
1054 var schedule = draft.schedule
1055 if receipt["status"] == "published" {
1056 schedule["status"] = "posted"
1057 if !receipt["publishedAt"].isEmpty { schedule["postedAt"] = receipt["publishedAt"] }
1058 let steps = receipt.fields["steps"] as? [[String: Any]] ?? []
1059 if let address = steps.compactMap({ $0["url"] as? String }).first(where: { !$0.isEmpty }) {
1060 schedule["url"] = address
1061 }
1062 schedule["error"] = ""
1063 } else {
1064 schedule["status"] = "failed"
1065 schedule["error"] = receipt["error"]
1066 }
1067 draft.fields["schedule"] = schedule
1068 draft.markUpdated()
1069 return draft
1070 }
1071}
1072
1073extension Workspace {
1074 struct IdeaReturnPlan: Equatable {
1075 let ideaID: String
1076 let ideaTitle: String
1077 let ideaRevision: String
1078 }
1079
1080 func reviewIdeaReturn(for draft: WorkspaceRecord) throws -> IdeaReturnPlan {
1081 try reload()
1082 guard let latest = records.first(where: { $0.id == draft.id && $0.kind == "draft" }),
1083 latest["updatedAt"] == draft["updatedAt"] else {
1084 throw WorkspaceError("This draft changed. Open it again before returning the idea.")
1085 }
1086 let ideaID = latest["ideaId"].isEmpty ? records.first {
1087 $0.kind == "idea" && $0.projectID == latest.projectID &&
1088 ($0.fields["versions"] as? [String: String])?.values.contains(latest.id) == true
1089 }?.id ?? "" : latest["ideaId"]
1090 return try ideaReturnPlan(ideaID: ideaID)
1091 }
1092
1093 func returnToIdeas(_ reviewed: IdeaReturnPlan) throws {
1094 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1095 let lease = try claimPublication()
1096 defer { withExtendedLifetime(lease) {} }
1097 try withChanges {
1098 guard try ideaReturnPlan(ideaID: reviewed.ideaID) == reviewed,
1099 var idea = records.first(where: { $0.id == reviewed.ideaID && $0.kind == "idea" }) else {
1100 throw WorkspaceError("The idea or its drafts changed. Review them before returning the idea.")
1101 }
1102 idea["status"] = "draft"
1103 _ = try saveCurrent(idea, to: database)
1104 }
1105 }
1106
1107 private func ideaReturnPlan(ideaID: String) throws -> IdeaReturnPlan {
1108 guard !ideaID.isEmpty, let idea = records.first(where: { $0.id == ideaID && $0.kind == "idea" }),
1109 idea["status"] == "picked" else {
1110 throw WorkspaceError("This post does not belong to a picked idea.")
1111 }
1112 return IdeaReturnPlan(ideaID: idea.id, ideaTitle: idea.title, ideaRevision: idea["updatedAt"])
1113 }
1114
1115 func quoteComposerURL(for draft: WorkspaceRecord) -> URL? {
1116 guard draft.kind == "draft", draft["platform"] == "x", !["posting", "posted"].contains(draft.scheduleStatus),
1117 let idea = records.first(where: { $0.kind == "idea" && $0.id == draft["ideaId"] && $0.projectID == draft.projectID }),
1118 let source = XQuoteComposer.source(in: idea) else { return nil }
1119 let opening = ["followup", "thread"].contains(draft["format"]) ? XThreadText.posts(in: draft.body).first ?? "" : draft.body
1120 return XQuoteComposer.url(text: opening, quoting: source)
1121 }
1122
1123 func prepareManualQuote(_ draft: WorkspaceRecord) throws -> URL {
1124 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1125 let lease = try claimPublication()
1126 defer { withExtendedLifetime(lease) {} }
1127 return try withChanges {
1128 guard var latest = records.first(where: { $0.kind == "draft" && $0.id == draft.id }),
1129 latest["updatedAt"] == draft["updatedAt"], let url = quoteComposerURL(for: latest),
1130 !records.contains(where: { $0.kind == "publication" && $0["draftId"] == draft.id }) else {
1131 throw WorkspaceError("Review the latest draft and its publishing history before opening X.")
1132 }
1133 if latest.scheduleStatus != "manual" || latest.fields["manualQuote"] as? Bool != true ||
1134 !(latest.schedule["slotAt"] as? String ?? "").isEmpty {
1135 var schedule = latest.schedule
1136 schedule["status"] = "manual"
1137 schedule["slotAt"] = ""
1138 schedule["error"] = ""
1139 latest.fields["schedule"] = schedule
1140 latest.fields["manualQuote"] = true
1141 _ = try saveCurrent(latest, to: database)
1142 }
1143 return url
1144 }
1145 }
1146
1147 @discardableResult
1148 func scheduleDraft(_ input: WorkspaceRecord, at time: Date, tiktok plan: SocialPublishPlan? = nil,
1149 linkedin selected: LinkedInDestination? = nil,
1150 linkedInAccount override: ManagedSocialAccount? = nil,
1151 customTime: Bool = false) throws -> WorkspaceRecord {
1152 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1153 return try database.transaction {
1154 try reload()
1155 guard var draft = records.first(where: { $0.kind == "draft" && $0.id == input.id }),
1156 input["updatedAt"] == draft["updatedAt"], !["posting", "posted"].contains(draft.scheduleStatus),
1157 !draft.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
1158 throw WorkspaceError("Reopen the latest draft and add its post text before scheduling.")
1159 }
1160 guard draft.fields["manualQuote"] as? Bool != true else {
1161 throw WorkspaceError("Open this quote draft in X to publish it.")
1162 }
1163 guard !records.contains(where: {
1164 $0.kind == "publication" && $0["draftId"] == draft.id && ["published", "publishing", "uncertain"].contains($0["status"])
1165 }) else {
1166 throw WorkspaceError("Check this post in Publishing history before scheduling it again.")
1167 }
1168 _ = try PostVideo.forDraft(draft, in: records)
1169 var personalURN: String?
1170 if draft["platform"] == "x" {
1171 let posts = ["followup", "thread"].contains(draft["format"]) ? XThreadText.posts(in: draft.body) : [draft.body]
1172 let links = try XPostArticleLinks(draft: draft, posts: posts, records: records)
1173 let pending = Set(links.articles.filter { $0["state"] != "published" }.map(\.id))
1174 guard customTime || pending.isEmpty else {
1175 throw WorkspaceError("Use Publish together on X to send the draft article and its post.")
1176 }
1177 _ = try links.resolve(posts, pending: pending)
1178 }
1179 if draft["platform"] == "linkedin" {
1180 guard let account = try override ?? socialAccounts.savedAccount(.linkedin) else {
1181 throw WorkspaceError("Connect LinkedIn and choose a destination before scheduling.")
1182 }
1183 let destination = try LinkedInPages.schedulingDestination(for: draft, account: account, selected: selected)
1184 draft.fields["linkedinDestination"] = destination.fields
1185 personalURN = LinkedInDestination.personal(account).urn
1186 }
1187 guard time >= Date.now.addingTimeInterval(PostScheduling.leadTime) else {
1188 throw WorkspaceError("Choose a posting time at least two minutes from now.")
1189 }
1190 guard PostScheduling.isFree(time, for: draft, in: records, linkedInPersonalURN: personalURN, customTime: customTime) else {
1191 throw WorkspaceError(customTime ? "This destination already has a post at that minute. Choose another time."
1192 : "Choose another open posting time for this platform.")
1193 }
1194 var schedule = draft.schedule
1195 let slot = workspaceTimestamp(time)
1196 schedule["slotAt"] = slot
1197 schedule["companionRevision"] = UUID().uuidString
1198 schedule["status"] = "queued"
1199 schedule["error"] = ""
1200 schedule["pickedAt"] = schedule["pickedAt"] ?? WorkspaceRecord.timestamp
1201 if draft["platform"] == "tiktok" {
1202 guard let plan, let options = plan.tiktok, options.consent, plan.revision == draft["updatedAt"],
1203 plan.draftID == draft.id, plan.platform == .tiktok else {
1204 throw WorkspaceError("Review TikTok’s privacy, caption and consent before scheduling.")
1205 }
1206 draft["content"] = options.caption
1207 if draft["format"] == "image", !options.title.isEmpty { draft["title"] = options.title }
1208 draft.markUpdated()
1209 draft.fields["schedule"] = schedule
1210 var consent = WorkspaceRecord.new("tiktok-consent", projectID: draft.projectID)
1211 consent["id"] = "tiktok-consent:" + draft.id
1212 consent["draftId"] = draft.id
1213 consent["accountId"] = plan.accountID
1214 consent["slotAt"] = slot
1215 consent["draftRevision"] = draft["updatedAt"]
1216 consent["imageURL"] = plan.publicImage?.absoluteString ?? ""
1217 consent.fields["options"] = try JSONSerialization.jsonObject(with: JSONEncoder().encode(options))
1218 try database.put(draft)
1219 try database.put(consent)
1220 try reload()
1221 return draft
1222 }
1223 draft.fields["schedule"] = schedule
1224 return try saveCurrent(draft, to: database, scheduling: true)
1225 }
1226 }
1227}
1228
1229extension Workspace {
1230 func savePersonalProfile(_ profile: [String: Any], replacing expected: [String: Any], suggestionID: String? = nil) throws {
1231 try withChanges {
1232 let active = settings["personalProfile"] as? [String: Any] ?? [:]
1233 guard NSDictionary(dictionary: active).isEqual(to: expected) else {
1234 throw WorkspaceError("The saved profile changed. Reload it before applying your edits.")
1235 }
1236 let normalized = try PersonalProfile.normalized(profile)
1237 if let suggestionID {
1238 try reviewSuggestion(suggestionID, accept: true, reviewedProfile: normalized)
1239 } else {
1240 try set("personalProfile", to: normalized)
1241 }
1242 }
1243 }
1244
1245 func suggestProfile(_ patch: [String: Any]) throws -> WorkspaceRecord {
1246 guard !patch.isEmpty else { throw WorkspaceError("Include a profile field to suggest.") }
1247 let existing = settings["personalProfile"] as? [String: Any] ?? [:]
1248 let profile = try PersonalProfile.normalized(existing.merging(patch) { _, value in value })
1249 var item = WorkspaceRecord.new("personal-inbox")
1250 item["kind"] = "profile"
1251 item["origin"] = "Connected agent"
1252 item.fields["profile"] = profile
1253 return try saveSuggestion(item)
1254 }
1255
1256 func suggestContext(projectID: String, title: String, summary: String, origin: String,
1257 noteIDs: [String]? = nil) throws -> WorkspaceRecord {
1258 guard projects.contains(where: { $0.id == projectID }),
1259 (1...200).contains(title.utf16.count), (1...5000).contains(summary.utf16.count),
1260 !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
1261 !summary.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, origin.utf16.count <= 100 else {
1262 throw WorkspaceError("Choose a project and enter a short title and public-safe summary.")
1263 }
1264 var item = WorkspaceRecord.new("personal-inbox", projectID: projectID)
1265 item["kind"] = "context"
1266 item["title"] = title
1267 item["summary"] = summary
1268 item["origin"] = origin.isEmpty ? "Connected agent" : origin
1269 item.fields["noteIds"] = noteIDs
1270 return try saveSuggestion(item)
1271 }
1272
1273 private func saveSuggestion(_ input: WorkspaceRecord) throws -> WorkspaceRecord {
1274 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1275 return try withChanges {
1276 guard records.filter({ $0.kind == "personal-inbox" && $0["status"] == "pending" }).count < 40 else {
1277 throw WorkspaceError("Review the pending suggestions in Settings before adding more.")
1278 }
1279 var item = input
1280 item["status"] = "pending"
1281 try database.put(item)
1282 try reload()
1283 return item
1284 }
1285 }
1286
1287 func reviewSuggestion(_ id: String, accept: Bool, reviewedProfile: [String: Any]? = nil) throws {
1288 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1289 try withChanges {
1290 guard var item = records.first(where: { $0.kind == "personal-inbox" && $0.id == id && $0["status"] == "pending" }) else {
1291 throw WorkspaceError("This suggestion was already reviewed.")
1292 }
1293 if accept {
1294 if item["kind"] == "profile", let profile = reviewedProfile ?? item.fields["profile"] as? [String: Any] {
1295 try set("personalProfile", to: PersonalProfile.normalized(profile))
1296 } else if item["kind"] == "context" {
1297 var source = WorkspaceRecord.new("source", projectID: item.projectID)
1298 source["title"] = item["title"]
1299 source["text"] = item["summary"]
1300 source["origin"] = item["origin"]
1301 try save(source)
1302 } else {
1303 throw WorkspaceError("This suggestion is invalid.")
1304 }
1305 }
1306 item["status"] = accept ? "accepted" : "dismissed"
1307 item["updatedAt"] = WorkspaceRecord.timestamp
1308 try database.put(item)
1309 try reload()
1310 }
1311 }
1312}
1313
1314extension Workspace {
1315 func saveResearchReference(_ fields: [String: Any], projectID: String) throws -> WorkspaceRecord {
1316 try withChanges {
1317 let link = fields["url"] as? String ?? ""
1318 if !link.isEmpty, let existing = records.first(where: { $0.kind == "source" && $0.projectID == projectID && $0["url"] == link }) {
1319 return existing
1320 }
1321 var source = WorkspaceRecord.new("source", projectID: projectID)
1322 for key in ["title", "text", "url", "author", "origin", "likes", "reposts", "replies", "views", "followers", "postedAt", "sourceType"] {
1323 source.fields[key] = fields[key]
1324 }
1325 source["title"] = String(source["title"].prefix(150))
1326 return try save(source)
1327 }
1328 }
1329
1330 func dismissResearch(_ itemID: String, from feedID: String) throws {
1331 try withChanges {
1332 guard var feed = records.first(where: { $0.kind == "discovery" && $0.id == feedID }),
1333 let items = feed.fields["items"] as? [[String: Any]],
1334 items.contains(where: { $0["id"] as? String == itemID }) else {
1335 throw WorkspaceError("This research item is no longer available.")
1336 }
1337 var feedback = records.first { $0.kind == "research-feedback" && $0.id == feedID + ":feedback" }
1338 ?? WorkspaceRecord.new("research-feedback", projectID: feed.projectID)
1339 feedback["id"] = feedID + ":feedback"
1340 feedback["title"] = "Dismissed research"
1341 let dismissed = feedback.fields["dismissed"] as? [String] ?? []
1342 feedback.fields["dismissed"] = Array((dismissed.filter { $0 != itemID } + [itemID]).suffix(300))
1343 try save(feedback)
1344 if feed["title"].isEmpty { feed["title"] = platformName(feed["platform"]) }
1345 feed.fields["items"] = items.filter { $0["id"] as? String != itemID }
1346 try save(feed)
1347 }
1348 }
1349}
1350
1351extension Workspace {
1352 func refillIdeaQueueIfNeeded(projectID requestedProject: String? = nil) async {
1353 let id = requestedProject ?? projectID
1354 guard settings["ideaQueueAutomatic"] as? Bool == true,
1355 let project = projects.first(where: { $0.id == id }),
1356 project.fields["sample"] as? Bool != true else { return }
1357 let now = Date.now
1358 let target = IdeaQueuePlan.target(settings["ideaQueueTarget"])
1359 guard records.filter({ $0.isPendingPostIdea && $0.projectID == id }).count < target,
1360 now.timeIntervalSince(lastIdeaQueueAttempt[project.id] ?? .distantPast) > 3600 else { return }
1361 lastIdeaQueueAttempt[project.id] = now
1362 do {
1363 _ = try await ResearchDiscovery(studio: ContentStudio(workspace: self))
1364 .refreshIdeas(projectID: project.id, withResearch: true, automatic: true)
1365 } catch {
1366 notice = "Idea refill paused: " + error.localizedDescription
1367 }
1368 }
1369}
1370
1371extension Workspace {
1372 @discardableResult
1373 func saveReplyPage(_ rows: [WorkspaceRecord], session: String, state: [String: Any]) throws -> Int {
1374 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1375 return try withChanges {
1376 var count = 0
1377 for row in rows {
1378 var next = row
1379 let old = records.first { $0.kind == "reply-inbox" && $0.id == row.id }
1380 next["status"] = old?["status"] ?? "unread"
1381 next["draftId"] = old?["draftId"] ?? ""
1382 if old == nil { count += 1 }
1383 try database.put(next)
1384 }
1385 var states = settings["replyInboxSync"] as? [String: [String: Any]] ?? [:]
1386 states[session] = state
1387 try database.set("replyInboxSync", to: states)
1388 try reload()
1389 return count
1390 }
1391 }
1392
1393 func markReply(_ id: String, status: String) throws {
1394 guard let database, ["unread", "read", "archived"].contains(status) else {
1395 throw WorkspaceError("Choose a reply status.")
1396 }
1397 try withChanges {
1398 guard var row = records.first(where: { $0.kind == "reply-inbox" && $0.id == id }) else {
1399 throw WorkspaceError("This reply no longer exists.")
1400 }
1401 row["status"] = status
1402 try database.put(row)
1403 try reload()
1404 }
1405 }
1406
1407 func ignoreReplies(_ ids: Set<String>) throws {
1408 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1409 try withChanges {
1410 for var row in records where row.kind == "reply-inbox" && ids.contains(row.id) && row["status"] != "archived" {
1411 row["status"] = "archived"
1412 try database.put(row)
1413 }
1414 try reload()
1415 }
1416 }
1417
1418 func makeReplyDraft(_ id: String, projectID: String) throws -> WorkspaceRecord {
1419 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1420 return try withChanges {
1421 guard var row = records.first(where: { $0.kind == "reply-inbox" && $0.id == id }) else {
1422 throw WorkspaceError("This reply no longer exists.")
1423 }
1424 if let prior = records.first(where: { $0.kind == "draft" && $0.id == row["draftId"] }) { return prior }
1425 var draft = WorkspaceRecord.new("draft", projectID: projectID)
1426 draft["title"] = "Reply to " + String(row.title.prefix(150))
1427 draft["format"] = "reply"
1428 draft.fields["replyTo"] = ["text": row.body, "url": row["url"], "author": String(row["author"].prefix(100))]
1429 if let parent = row.fields["parent"] as? [String: Any], let text = parent["text"] as? String {
1430 draft["brief"] = "Conversation context for this reply: " + String(text.prefix(4500))
1431 }
1432 let saved = try save(draft)
1433 row["draftId"] = saved.id
1434 row["status"] = "drafted"
1435 try database.put(row)
1436 try reload()
1437 return saved
1438 }
1439 }
1440}
1441
1442extension Workspace {
1443 func saveAnalyticsRows(_ rows: [WorkspaceRecord]) throws {
1444 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1445 try withChanges {
1446 for row in rows {
1447 guard ["analytics-day", "analytics-post", "analytics-state"].contains(row.kind) else {
1448 throw WorkspaceError("Invalid analytics record.")
1449 }
1450 try database.put(row)
1451 }
1452 try reload()
1453 }
1454 }
1455}
1456
1457extension Workspace {
1458 func saveR2Media(_ media: R2Client.Media, config: R2Configuration) throws {
1459 guard let database else { throw WorkspaceError("The workspace is unavailable.") }
1460 try withChanges {
1461 let existing = records.first {
1462 $0.kind == "r2-object" && $0["accountId"] == config.accountId && $0["bucket"] == config.bucket
1463 && $0["jurisdiction"] == config.jurisdiction && $0["key"] == media.key
1464 }
1465 var record = existing ?? WorkspaceRecord.new("r2-object")
1466 record["accountId"] = config.accountId
1467 record["bucket"] = config.bucket
1468 record["jurisdiction"] = config.jurisdiction
1469 record["key"] = media.key
1470 record["type"] = media.type
1471 record["name"] = media.name
1472 record["uploadedAt"] = WorkspaceRecord.timestamp
1473 record.fields["size"] = media.size
1474 try database.put(record)
1475 try reload()
1476 }
1477 }
1478}