Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / WorkspaceTransferTests.swift
| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import Inkspring |
| 4 | |
| 5 | @Test func sqlitePreservesElectronFields() throws { |
| 6 | let directory = try temporaryWorkspace() |
| 7 | defer { try? FileManager.default.removeItem(at: directory) } |
| 8 | let url = directory.appending(path: "workspace.sqlite") |
| 9 | let project = WorkspaceRecord.new("project") |
| 10 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 11 | draft["title"] = "Test post" |
| 12 | draft.fields["futureField"] = ["content": "Keep this field"] |
| 13 | let database = try WorkspaceDatabase(url: url) |
| 14 | try database.transaction { |
| 15 | try database.put(project) |
| 16 | try database.put(draft) |
| 17 | } |
| 18 | let reopened = try WorkspaceDatabase(url: url) |
| 19 | let records = try reopened.records() |
| 20 | #expect(records.first?.id == draft.id) |
| 21 | #expect(records.first?.projectID == project.id) |
| 22 | #expect((records.first?.fields["futureField"] as? [String: String])?["content"] == "Keep this field") |
| 23 | #expect(throws: WorkspaceError.self) { |
| 24 | try database.transaction { |
| 25 | try database.put(WorkspaceRecord.new("idea", projectID: project.id)) |
| 26 | try database.put(WorkspaceRecord(kind: "newsletter", fields: draft.fields)) |
| 27 | } |
| 28 | } |
| 29 | #expect(try reopened.records().count == 2) |
| 30 | } |
| 31 | |
| 32 | @Test func zipPreservesMediaAndResetsRestoredSchedules() throws { |
| 33 | let directory = try temporaryWorkspace() |
| 34 | defer { try? FileManager.default.removeItem(at: directory) } |
| 35 | let images = directory.appending(path: "images") |
| 36 | try FileManager.default.createDirectory(at: images, withIntermediateDirectories: true) |
| 37 | let filename = "8ce78386-33d1-42d6-990d-ffbb1d3b50f2.png" |
| 38 | let png = try #require(Data(base64Encoded: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jR1sAAAAASUVORK5CYII=")) |
| 39 | try png.write(to: images.appending(path: filename)) |
| 40 | var project = WorkspaceRecord.new("project") |
| 41 | project["name"] = "Test project" |
| 42 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 43 | draft["title"] = "Image post" |
| 44 | draft["format"] = "image" |
| 45 | draft.fields["image"] = ["file": filename, "origin": "Attached"] |
| 46 | draft.fields["schedule"] = ["status": "queued", "slotAt": "2027-01-01T12:00:00.000Z"] |
| 47 | draft.fields["nested"] = ["access_token": "fixture-only", "label": "Kept"] |
| 48 | let videoURL = directory.appending(path: "unused.mp4") |
| 49 | let videoBytes = Data("unattached video fixture".utf8) |
| 50 | try videoBytes.write(to: videoURL) |
| 51 | let digest = try fileDigest(videoURL) |
| 52 | var video = WorkspaceRecord.new("local-video") |
| 53 | video["name"] = "Unused video" |
| 54 | video["path"] = videoURL.path |
| 55 | video["hash"] = digest.hash |
| 56 | video.fields["size"] = digest.size |
| 57 | let archive = directory.appending(path: "backup.zip") |
| 58 | try WorkspaceBackup.export(records: [draft, project, video], |
| 59 | preferences: ["provider": "openai", "autoPost": true, StudioTheme.preferenceKey: "graphite"], |
| 60 | directory: directory, to: archive) |
| 61 | let (backup, files) = try WorkspaceBackup.stage(archive, in: directory) |
| 62 | #expect(backup.preferences["provider"] as? String == "openai") |
| 63 | #expect(backup.preferences["autoPost"] == nil) |
| 64 | #expect(StudioTheme(preference: backup.preferences[StudioTheme.preferenceKey]) == .graphite) |
| 65 | let manifest = try JSONSerialization.jsonObject(with: Data(contentsOf: try #require(files["data.json"]))) as? [String: Any] |
| 66 | #expect((manifest?["preferences"] as? [String: Any])?[StudioTheme.preferenceKey] == nil) |
| 67 | let restored = backup.restored(try #require(backup.records.first { $0.id == draft.id })) |
| 68 | #expect(restored.scheduleStatus == "ready") |
| 69 | #expect(restored.schedule["originalSlotAt"] as? String == "2027-01-01T12:00:00.000Z") |
| 70 | #expect((restored.fields["nested"] as? [String: String]) == ["label": "Kept"]) |
| 71 | let entry = try #require(files["media/images/" + filename]) |
| 72 | #expect(try Data(contentsOf: entry) == png) |
| 73 | #expect(backup.records.contains { $0.id == video.id && $0.kind == "local-video" }) |
| 74 | let videoEntry = try #require(files["media/videos/" + video.id + ".mp4"]) |
| 75 | #expect(try Data(contentsOf: videoEntry) == videoBytes) |
| 76 | } |
| 77 | |
| 78 | @Test func zipRejectsUnrecognizedEntries() throws { |
| 79 | let directory = try temporaryWorkspace() |
| 80 | defer { try? FileManager.default.removeItem(at: directory) } |
| 81 | let input = directory.appending(path: "input") |
| 82 | try Data("content".utf8).write(to: input) |
| 83 | let archive = directory.appending(path: "backup.zip") |
| 84 | try ZipArchive.write(to: archive, files: [("../data.json", input, 7)]) |
| 85 | #expect(throws: WorkspaceError.self) { try WorkspaceBackup.stage(archive, in: directory) } |
| 86 | } |
| 87 | |
| 88 | @Test func electronZipInteroperability() throws { |
| 89 | let environment = ProcessInfo.processInfo.environment |
| 90 | guard let input = environment["INKSPRING_ELECTRON_FIXTURE"], |
| 91 | let output = environment["INKSPRING_SWIFT_FIXTURE"] else { return } |
| 92 | let directory = try temporaryWorkspace() |
| 93 | defer { try? FileManager.default.removeItem(at: directory) } |
| 94 | let (backup, files) = try WorkspaceBackup.stage(URL(fileURLWithPath: input), in: directory) |
| 95 | let draft = try #require(backup.records.first { $0.kind == "draft" }) |
| 96 | #expect(draft.title == "Electron parity draft") |
| 97 | #expect(backup.restored(draft).scheduleStatus == "ready") |
| 98 | let images = directory.appending(path: "images") |
| 99 | try FileManager.default.createDirectory(at: images, withIntermediateDirectories: true) |
| 100 | for item in backup.media where item.kind == "image" { |
| 101 | try FileManager.default.copyItem(at: try #require(files[item.entry]), |
| 102 | to: images.appending(path: try #require(item.file))) |
| 103 | } |
| 104 | try WorkspaceBackup.export(records: backup.records.reversed(), preferences: backup.preferences, |
| 105 | directory: directory, to: URL(fileURLWithPath: output)) |
| 106 | } |
| 107 | |
| 108 | private func temporaryWorkspace() throws -> URL { |
| 109 | let directory = FileManager.default.temporaryDirectory.appending(path: "inkspring-tests-" + UUID().uuidString) |
| 110 | try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) |
| 111 | return directory |
| 112 | } |
| 113 | |
| 114 | @Test func backupOnlyReportsUploadedWhenICloudConfirmsTheZIP() async throws { |
| 115 | #expect(ICloudBackup.uploadStatus(inDrive: false, available: true, ubiquitous: false, |
| 116 | uploaded: false, excluded: false, error: nil) == nil) |
| 117 | #expect(ICloudBackup.uploadStatus(inDrive: true, available: true, ubiquitous: false, |
| 118 | uploaded: true, excluded: false, error: nil) == .waiting) |
| 119 | #expect(ICloudBackup.uploadStatus(inDrive: true, available: true, ubiquitous: true, |
| 120 | uploaded: true, excluded: false, error: nil) == .uploaded) |
| 121 | #expect(ICloudBackup.uploadStatus(inDrive: true, available: true, ubiquitous: true, |
| 122 | uploaded: true, excluded: true, error: nil) == .excluded) |
| 123 | #expect(ICloudBackup.uploadStatus(inDrive: true, available: true, ubiquitous: true, |
| 124 | uploaded: false, excluded: false, error: "Quota reached") == .failed("Quota reached")) |
| 125 | #expect(ICloudBackup.uploadStatus(inDrive: true, available: false, ubiquitous: false, |
| 126 | uploaded: false, excluded: false, error: nil) == .unavailable) |
| 127 | let directory = try temporaryWorkspace() |
| 128 | defer { try? FileManager.default.removeItem(at: directory) } |
| 129 | let file = directory.appending(path: "local.zip") |
| 130 | try Data("fixture".utf8).write(to: file) |
| 131 | #expect(ICloudBackup.uploadStatus(of: file) == nil) |
| 132 | try await ICloudBackup.downloadIfNeeded(file) |
| 133 | #expect(try Data(contentsOf: file) == Data("fixture".utf8)) |
| 134 | } |
| 135 | |
| 136 | @Test(.enabled(if: ProcessInfo.processInfo.environment["INKSPRING_ICLOUD_QA_FOLDER"] != nil, |
| 137 | "Requires a disposable iCloud QA folder for the live upload and restore.")) |
| 138 | @MainActor func liveICloudBackupRoundTripsSyntheticWorkspace() async throws { |
| 139 | guard let folder = ProcessInfo.processInfo.environment["INKSPRING_ICLOUD_QA_FOLDER"] else { return } |
| 140 | let cloudFolder = URL(fileURLWithPath: folder, isDirectory: true) |
| 141 | #expect(cloudFolder.lastPathComponent.hasPrefix("Inkspring QA Backup.")) |
| 142 | guard cloudFolder.lastPathComponent.hasPrefix("Inkspring QA Backup.") else { |
| 143 | throw WorkspaceError("Use a disposable iCloud Drive folder for this test.") |
| 144 | } |
| 145 | let root = try temporaryWorkspace() |
| 146 | defer { try? FileManager.default.removeItem(at: root) } |
| 147 | let workspace = Workspace(directory: root.appending(path: "source")) |
| 148 | let source = try #require(workspace.directory) |
| 149 | let filename = "8ce78386-33d1-42d6-990d-ffbb1d3b50f2.png" |
| 150 | let bytes = Data("Synthetic Inkspring iCloud test attachment".utf8) |
| 151 | let images = source.appending(path: "images", directoryHint: .isDirectory) |
| 152 | try FileManager.default.createDirectory(at: images, withIntermediateDirectories: true) |
| 153 | try bytes.write(to: images.appending(path: filename)) |
| 154 | var draft = WorkspaceRecord.new("draft", projectID: workspace.projectID) |
| 155 | draft["title"] = "Synthetic iCloud backup test" |
| 156 | draft["content"] = "Restore verification for a disposable workspace." |
| 157 | draft["format"] = "image" |
| 158 | draft.fields["image"] = ["file": filename] |
| 159 | try workspace.save(draft) |
| 160 | try workspace.set(DailyBackup.folderKey, to: cloudFolder.path) |
| 161 | let archive = try #require(try DailyBackup.run(in: source, requested: true)) |
| 162 | print("Created the synthetic backup ZIP.") |
| 163 | let deadline = ContinuousClock.now + .seconds(90) |
| 164 | var lastError: String? |
| 165 | while true { |
| 166 | let file = URL(fileURLWithPath: archive.path) |
| 167 | let status = ICloudBackup.uploadStatus(of: file) |
| 168 | if status == .uploaded { break } |
| 169 | if case let .failed(message) = status { |
| 170 | if let metadata = try? file.resourceValues(forKeys: [.ubiquitousItemUploadingErrorKey]), |
| 171 | let error = metadata.ubiquitousItemUploadingError { |
| 172 | lastError = "\(error.domain) \(error.code): \(message)" |
| 173 | } else { |
| 174 | lastError = message |
| 175 | } |
| 176 | } |
| 177 | guard ContinuousClock.now < deadline else { |
| 178 | throw WorkspaceError(lastError ?? "iCloud did not confirm the synthetic ZIP upload.") |
| 179 | } |
| 180 | try await Task.sleep(for: .seconds(2)) |
| 181 | } |
| 182 | print("iCloud Drive confirmed the upload.") |
| 183 | |
| 184 | try FileManager.default.evictUbiquitousItem(at: archive) |
| 185 | let evicted = URL(fileURLWithPath: archive.path) |
| 186 | let status = try evicted.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey]).ubiquitousItemDownloadingStatus |
| 187 | #expect(status == .notDownloaded) |
| 188 | guard status == .notDownloaded else { throw WorkspaceError("The synthetic ZIP never became iCloud-only.") } |
| 189 | try await ICloudBackup.downloadIfNeeded(evicted) |
| 190 | print("Inkspring downloaded the iCloud-only ZIP.") |
| 191 | |
| 192 | let restored = Workspace(directory: root.appending(path: "restored")) |
| 193 | let (backup, files) = try WorkspaceBackup.stage(archive, in: #require(restored.directory)) |
| 194 | try restored.apply(backup, files: files) |
| 195 | let copy = try #require(restored.records.first { $0.id == draft.id }) |
| 196 | #expect(copy.body == draft.body) |
| 197 | #expect(try Data(contentsOf: #require(restored.mediaURL(copy))) == bytes) |
| 198 | #expect(restored.settings["autoPost"] as? Bool == false) |
| 199 | print("Restored the synthetic draft and verified its attachment bytes.") |
| 200 | } |
| 201 | |
| 202 | @Test @MainActor func workspaceFolderImportPreservesTheSourceAndPausesRestoredSchedules() throws { |
| 203 | let root = try temporaryWorkspace() |
| 204 | defer { try? FileManager.default.removeItem(at: root) } |
| 205 | let source = Workspace(directory: root.appending(path: "Source")) |
| 206 | let destination = Workspace(directory: root.appending(path: "Native")) |
| 207 | let sourceURL = try #require(source.directory) |
| 208 | let destinationURL = try #require(destination.directory) |
| 209 | let images = sourceURL.appending(path: "images") |
| 210 | try FileManager.default.createDirectory(at: images, withIntermediateDirectories: true) |
| 211 | let filename = "8ce78386-33d1-42d6-990d-ffbb1d3b50f2.png" |
| 212 | let image = Data("synthetic imported image".utf8) |
| 213 | try image.write(to: images.appending(path: filename)) |
| 214 | var draft = WorkspaceRecord.new("draft", projectID: source.projectID) |
| 215 | draft["title"] = "Source draft" |
| 216 | draft["content"] = "Import this draft and its attachment." |
| 217 | draft["format"] = "image" |
| 218 | draft.fields["image"] = ["file": filename] |
| 219 | draft.fields["schedule"] = ["status": "queued", "slotAt": "2027-01-01T12:00:00Z"] |
| 220 | try source.save(draft) |
| 221 | try source.set("provider", to: "gemini") |
| 222 | try source.set("mcpEnabled", to: true) |
| 223 | try source.set("autoPost", to: true) |
| 224 | let filesBefore = try Set(FileManager.default.contentsOfDirectory(atPath: sourceURL.path)) |
| 225 | #expect(throws: WorkspaceError.self) { try WorkspaceMigration.prepareImport(from: sourceURL, into: sourceURL) } |
| 226 | |
| 227 | let archive = try WorkspaceMigration.prepareImport(from: sourceURL, into: destinationURL) |
| 228 | let (backup, media) = try WorkspaceBackup.stage(archive, in: destinationURL) |
| 229 | let plan = try backup.restorePlan(over: destination.records) |
| 230 | #expect(!destination.records.contains { $0.id == draft.id }) |
| 231 | try destination.apply(backup, files: media, reviewedPlan: plan) |
| 232 | let imported = try #require(destination.records.first { $0.id == draft.id }) |
| 233 | #expect(imported.body == draft.body) |
| 234 | #expect(imported.scheduleStatus == "ready") |
| 235 | #expect(try Data(contentsOf: #require(destination.mediaURL(imported))) == image) |
| 236 | #expect(destination.settings["provider"] as? String == "gemini") |
| 237 | #expect(destination.settings["mcpEnabled"] as? Bool == false) |
| 238 | #expect(destination.settings["autoPost"] as? Bool == false) |
| 239 | |
| 240 | try source.reload() |
| 241 | #expect(source.records.first { $0.id == draft.id }?.scheduleStatus == "queued") |
| 242 | #expect(source.settings["mcpEnabled"] as? Bool == true) |
| 243 | #expect(source.settings["autoPost"] as? Bool == true) |
| 244 | #expect(try Set(FileManager.default.contentsOfDirectory(atPath: sourceURL.path)) == filesBefore) |
| 245 | } |
| 246 | |
| 247 | @Test @MainActor func videoAttachmentValidatesAndPreservesMediaMetadata() async throws { |
| 248 | guard let fixture = ProcessInfo.processInfo.environment["INKSPRING_VIDEO_FIXTURE"] else { return } |
| 249 | let directory = try temporaryWorkspace() |
| 250 | defer { try? FileManager.default.removeItem(at: directory) } |
| 251 | let workspace = Workspace(directory: directory.appending(path: "workspace")) |
| 252 | let invalid = directory.appending(path: "broken.mp4") |
| 253 | try Data("not a playable video".utf8).write(to: invalid) |
| 254 | await #expect(throws: WorkspaceError.self) { _ = try await workspace.attachVideo(invalid) } |
| 255 | #expect(!workspace.records.contains { $0.kind == "local-video" }) |
| 256 | |
| 257 | let source = URL(fileURLWithPath: fixture) |
| 258 | let media = try await workspace.attachVideo(source) |
| 259 | let record = try #require(workspace.records.first { $0.kind == "local-video" }) |
| 260 | #expect(media["id"] as? String == record.id) |
| 261 | #expect(record["type"] == "video/mp4") |
| 262 | #expect(record.fields["width"] as? Int == 640) |
| 263 | #expect(record.fields["height"] as? Int == 360) |
| 264 | #expect(record.fields["duration"] as? Double == 1) |
| 265 | let copy = URL(fileURLWithPath: record["path"]) |
| 266 | #expect(copy != source) |
| 267 | #expect(try fileDigest(copy) == fileDigest(source)) |
| 268 | let attachment = try await TikTokVideo.inspect(copy) |
| 269 | #expect(attachment.duration == 1) |
| 270 | #expect(attachment.hash == record["hash"]) |
| 271 | } |
| 272 | |
| 273 | @Test @MainActor func draftKeepsOnePreviewAttachmentWhenPublicationFormatChanges() throws { |
| 274 | let directory = try temporaryWorkspace() |
| 275 | defer { try? FileManager.default.removeItem(at: directory) } |
| 276 | let workspace = Workspace(directory: directory) |
| 277 | var project = WorkspaceRecord.new("project") |
| 278 | project["name"] = "Preview attachments" |
| 279 | project = try workspace.save(project) |
| 280 | let videoURL = directory.appending(path: "preview.mp4") |
| 281 | var video = WorkspaceRecord.new("local-video") |
| 282 | video["name"] = "Preview" |
| 283 | video["path"] = videoURL.path |
| 284 | video = try workspace.save(video) |
| 285 | let image = UUID().uuidString.lowercased() + ".png" |
| 286 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 287 | draft["title"] = "Media preview" |
| 288 | draft["platform"] = "reddit" |
| 289 | draft.fields["video"] = ["id": video.id] |
| 290 | draft.fields["image"] = ["file": image] |
| 291 | #expect(throws: WorkspaceError.self) { try workspace.save(draft) } |
| 292 | draft.setDraftMedia(["id": video.id], as: .video) |
| 293 | draft.fields["videoThumbnail"] = ["file": image] |
| 294 | draft.prepareDraftForSave() |
| 295 | draft = try workspace.save(draft) |
| 296 | |
| 297 | try workspace.reload() |
| 298 | let reopened = try #require(workspace.records.first { $0.id == draft.id }) |
| 299 | #expect(workspace.videoURL(reopened) == videoURL) |
| 300 | #expect(workspace.imageURL(reopened) == nil) |
| 301 | #expect(workspace.videoThumbnailURL(reopened)?.lastPathComponent == image) |
| 302 | draft["format"] = "video" |
| 303 | #expect(workspace.mediaURL(draft) == videoURL) |
| 304 | draft.setDraftMedia(["file": image], as: .image) |
| 305 | #expect(draft.fields["videoThumbnail"] == nil) |
| 306 | #expect(workspace.videoURL(draft) == nil) |
| 307 | #expect(workspace.imageURL(draft)?.lastPathComponent == image) |
| 308 | } |
| 309 | |
| 310 | @Test @MainActor func importedMediaInstructionsBecomeAReaderFacingDraftTitle() throws { |
| 311 | let directory = try temporaryWorkspace() |
| 312 | defer { try? FileManager.default.removeItem(at: directory) } |
| 313 | let workspace = Workspace(directory: directory) |
| 314 | var project = WorkspaceRecord.new("project") |
| 315 | project["name"] = "Demo" |
| 316 | project = try workspace.save(project) |
| 317 | |
| 318 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 319 | let file = "Jotley-Marketing-v12-MCP-portrait-social-1080x1920p30.mp4" |
| 320 | let headline = "Your meeting notes, now readable by Claude Code and Codex." |
| 321 | let attachment = ["id": "sample-video", "name": file] |
| 322 | draft["title"] = "Jotley MCP video, portrait (attach \(file))" |
| 323 | draft["content"] = "\(headline) Jotley transcribes on your device." |
| 324 | draft.fields["video"] = attachment |
| 325 | |
| 326 | #expect(draft.title == headline) |
| 327 | let saved = try workspace.save(draft) |
| 328 | #expect(saved["title"] == headline) |
| 329 | #expect(saved.fields["video"] as? [String: String] == attachment) |
| 330 | |
| 331 | var edited = saved |
| 332 | edited["title"] = "Read your meeting notes with an agent" |
| 333 | #expect(try workspace.save(edited)["title"] == edited["title"]) |
| 334 | } |
| 335 | |
| 336 | @Test @MainActor func webMVideoRemainsWebMThroughAttachmentAndRestore() async throws { |
| 337 | guard let fixture = ProcessInfo.processInfo.environment["INKSPRING_WEBM_FIXTURE"] else { return } |
| 338 | let directory = try temporaryWorkspace() |
| 339 | defer { try? FileManager.default.removeItem(at: directory) } |
| 340 | let source = URL(fileURLWithPath: fixture) |
| 341 | let workspace = Workspace(directory: directory.appending(path: "workspace")) |
| 342 | let truncated = directory.appending(path: "truncated.webm") |
| 343 | try Data(contentsOf: source).prefix(64).write(to: truncated) |
| 344 | await #expect(throws: WorkspaceError.self) { _ = try await workspace.attachVideo(truncated) } |
| 345 | #expect(!workspace.records.contains { $0.kind == "local-video" }) |
| 346 | |
| 347 | let media = try await workspace.attachVideo(source) |
| 348 | let record = try #require(workspace.records.first { $0.id == media["id"] as? String }) |
| 349 | #expect(record["type"] == "video/webm") |
| 350 | #expect(record.fields["width"] as? Int == 640) |
| 351 | #expect(record.fields["height"] as? Int == 360) |
| 352 | #expect(record.fields["duration"] as? Double == 1) |
| 353 | let video = try await TikTokVideo.inspect(URL(fileURLWithPath: record["path"])) |
| 354 | #expect(video.duration == 1) |
| 355 | #expect(video.hash == record["hash"]) |
| 356 | if let highRateFixture = ProcessInfo.processInfo.environment["INKSPRING_WEBM_60FPS_FIXTURE"] { |
| 357 | let highRateURL = URL(fileURLWithPath: highRateFixture) |
| 358 | #expect(try await VideoMetadata.inspect(highRateURL).frameRate == 60) |
| 359 | #expect(try await TikTokVideo.inspect(highRateURL).type == "video/webm") |
| 360 | } |
| 361 | let archive = directory.appending(path: "backup.zip") |
| 362 | try workspace.exportBackup(to: archive) |
| 363 | |
| 364 | let restored = Workspace(directory: directory.appending(path: "restored")) |
| 365 | let (backup, files) = try WorkspaceBackup.stage(archive, in: #require(restored.directory)) |
| 366 | try restored.apply(backup, files: files) |
| 367 | let restoredVideo = try #require(restored.records.first { $0.id == record.id }) |
| 368 | let restoredURL = URL(fileURLWithPath: restoredVideo["path"]) |
| 369 | #expect(restoredURL.pathExtension == "webm") |
| 370 | #expect(try fileDigest(restoredURL) == fileDigest(source)) |
| 371 | } |
| 372 | |
| 373 | @Test @MainActor func dailyBackupIsIdempotentAndRestoresIntoNewWorkspace() throws { |
| 374 | let directory = try temporaryWorkspace() |
| 375 | defer { try? FileManager.default.removeItem(at: directory) } |
| 376 | let source = Workspace(directory: directory.appending(path: "source")) |
| 377 | let sourceDirectory = try #require(source.directory) |
| 378 | let project = try #require(source.project) |
| 379 | let file = "8ce78386-33d1-42d6-990d-ffbb1d3b50f2.png" |
| 380 | let image = Data("synthetic attachment bytes".utf8) |
| 381 | let images = sourceDirectory.appending(path: "images") |
| 382 | try FileManager.default.createDirectory(at: images, withIntermediateDirectories: false) |
| 383 | try image.write(to: images.appending(path: file)) |
| 384 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 385 | draft["title"] = "Daily backup fixture" |
| 386 | draft["content"] = "Restore me" |
| 387 | draft["format"] = "image" |
| 388 | draft.fields["image"] = ["file": file, "origin": "Attached"] |
| 389 | draft.fields["schedule"] = ["status": "queued", "slotAt": "2027-01-01T12:00:00Z"] |
| 390 | try source.save(draft) |
| 391 | |
| 392 | let backups = directory.appending(path: "backups") |
| 393 | try FileManager.default.createDirectory(at: backups, withIntermediateDirectories: false) |
| 394 | try source.set(DailyBackup.folderKey, to: backups.path) |
| 395 | try source.set(DailyBackup.enabledKey, to: true) |
| 396 | let day = try #require(scheduleDate("2027-01-01T12:00:00Z")) |
| 397 | try DailyBackup.run(in: sourceDirectory, now: day) |
| 398 | try DailyBackup.run(in: sourceDirectory, now: day.addingTimeInterval(7200)) |
| 399 | let files = try FileManager.default.contentsOfDirectory(at: backups, includingPropertiesForKeys: nil) |
| 400 | #expect(files.count == 1) |
| 401 | let archive = try #require(files.first) |
| 402 | #expect(archive.pathExtension == "zip") |
| 403 | let attributes = try FileManager.default.attributesOfItem(atPath: archive.path) |
| 404 | #expect(attributes[.posixPermissions] as? Int == 0o600) |
| 405 | |
| 406 | let restored = Workspace(directory: directory.appending(path: "restored")) |
| 407 | let (backup, staged) = try WorkspaceBackup.stage(archive, in: try #require(restored.directory)) |
| 408 | try restored.apply(backup, files: staged) |
| 409 | try restored.apply(backup, files: staged) |
| 410 | let result = try #require(restored.records.first { $0.id == draft.id }) |
| 411 | #expect(result.body == "Restore me") |
| 412 | #expect(result.scheduleStatus == "ready") |
| 413 | #expect(try Data(contentsOf: #require(restored.mediaURL(result))) == image) |
| 414 | #expect(restored.settings[DailyBackup.enabledKey] == nil) |
| 415 | |
| 416 | try DailyBackup.run(in: sourceDirectory, now: day.addingTimeInterval(86_400)) |
| 417 | #expect(try FileManager.default.contentsOfDirectory(atPath: backups.path).count == 2) |
| 418 | } |
| 419 | |
| 420 | @Test @MainActor func backupRetriesAfterAnUnavailableFolderAndCanRunOnDemand() throws { |
| 421 | let directory = try temporaryWorkspace() |
| 422 | defer { try? FileManager.default.removeItem(at: directory) } |
| 423 | let workspace = Workspace(directory: directory.appending(path: "source")) |
| 424 | let source = try #require(workspace.directory) |
| 425 | let destination = directory.appending(path: "backups") |
| 426 | let start = try #require(scheduleDate("2027-01-01T12:00:00Z")) |
| 427 | try workspace.set(DailyBackup.folderKey, to: destination.path) |
| 428 | try workspace.set(DailyBackup.enabledKey, to: true) |
| 429 | |
| 430 | #expect(throws: (any Error).self) { try DailyBackup.run(in: source, now: start) } |
| 431 | try workspace.reload() |
| 432 | #expect(!(workspace.settings[DailyBackup.lastErrorKey] as? String ?? "").isEmpty) |
| 433 | try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: false) |
| 434 | #expect(try DailyBackup.run(in: source, now: start.addingTimeInterval(600)) == nil) |
| 435 | let retried = try #require(try DailyBackup.run(in: source, now: start.addingTimeInterval(7200))) |
| 436 | #expect(FileManager.default.fileExists(atPath: retried.path)) |
| 437 | try FileManager.default.removeItem(at: retried) |
| 438 | let replacement = try #require(try DailyBackup.run(in: source, now: start.addingTimeInterval(14_400))) |
| 439 | #expect(FileManager.default.fileExists(atPath: replacement.path)) |
| 440 | |
| 441 | try workspace.set(DailyBackup.enabledKey, to: false) |
| 442 | let requested = try #require(try DailyBackup.run(in: source, now: start.addingTimeInterval(14_401), requested: true)) |
| 443 | #expect(requested != replacement) |
| 444 | let (archive, _) = try WorkspaceBackup.stage(requested, in: source) |
| 445 | #expect(archive.records.count == workspace.records.count) |
| 446 | try workspace.reload() |
| 447 | #expect(workspace.settings[DailyBackup.lastErrorKey] as? String == "") |
| 448 | #expect(workspace.settings[DailyBackup.lastFileKey] as? String == requested.path) |
| 449 | #expect(workspace.settings[DailyBackup.enabledKey] as? Bool == false) |
| 450 | } |
| 451 | |
| 452 | @Test @MainActor func restoringAnOlderBackupKeepsPublishingHistoryAndSubstackLinks() throws { |
| 453 | let directory = try temporaryWorkspace() |
| 454 | defer { try? FileManager.default.removeItem(at: directory) } |
| 455 | let workspace = Workspace(directory: directory) |
| 456 | let project = try #require(workspace.project) |
| 457 | var draft = WorkspaceRecord.new("draft", projectID: project.id) |
| 458 | draft["title"] = "Published after the backup" |
| 459 | draft["content"] = "Published wording" |
| 460 | draft.fields["schedule"] = ["status": "posted", "url": "https://x.com/i/web/status/123"] |
| 461 | draft = try workspace.save(draft) |
| 462 | var receipt = WorkspaceRecord.new("publication", projectID: project.id) |
| 463 | receipt["draftId"] = draft.id |
| 464 | receipt["title"] = draft.title |
| 465 | receipt["status"] = "published" |
| 466 | receipt.fields["steps"] = [["id": "123", "url": "https://x.com/i/web/status/123"]] |
| 467 | receipt = try workspace.save(receipt) |
| 468 | var newsletter = WorkspaceRecord.new("newsletter", projectID: project.id) |
| 469 | newsletter["title"] = "Newsletter linked after the backup" |
| 470 | newsletter["state"] = "scheduled" |
| 471 | newsletter["remoteId"] = "321" |
| 472 | let otherConnection = try WorkspaceDatabase(url: directory.appending(path: "workspace.sqlite")) |
| 473 | try otherConnection.put(newsletter) |
| 474 | |
| 475 | var olderDraft = draft |
| 476 | olderDraft["content"] = "Earlier wording" |
| 477 | olderDraft.fields["schedule"] = ["status": "queued", "slotAt": "2027-01-01T12:00:00Z"] |
| 478 | var olderReceipt = receipt |
| 479 | olderReceipt["status"] = "uncertain" |
| 480 | olderReceipt.fields["steps"] = [] |
| 481 | var olderNewsletter = newsletter |
| 482 | olderNewsletter["remoteId"] = "" |
| 483 | olderNewsletter["state"] = "draft" |
| 484 | var ordinary = WorkspaceRecord.new("draft", projectID: project.id) |
| 485 | ordinary["title"] = "Editable draft" |
| 486 | ordinary["content"] = "Current text" |
| 487 | ordinary = try workspace.save(ordinary) |
| 488 | var olderOrdinary = ordinary |
| 489 | olderOrdinary["content"] = "Restored text" |
| 490 | let archive = directory.appending(path: "earlier.zip") |
| 491 | try WorkspaceBackup.export(records: [project, olderDraft, olderReceipt, olderNewsletter, olderOrdinary], |
| 492 | preferences: [:], directory: directory, to: archive) |
| 493 | let (backup, files) = try WorkspaceBackup.stage(archive, in: directory) |
| 494 | let reviewed = try backup.restorePlan(over: workspace.records) |
| 495 | #expect(reviewed.preservedIDs == [draft.id, receipt.id, newsletter.id]) |
| 496 | ordinary["content"] = "Changed after review" |
| 497 | ordinary = try workspace.save(ordinary) |
| 498 | #expect(throws: WorkspaceError.self) { try workspace.apply(backup, files: files, reviewedPlan: reviewed) } |
| 499 | #expect(workspace.drafts.first { $0.id == ordinary.id }?.body == "Changed after review") |
| 500 | let current = try backup.restorePlan(over: workspace.records) |
| 501 | try workspace.apply(backup, files: files, reviewedPlan: current) |
| 502 | #expect(workspace.drafts.first { $0.id == draft.id }?.body == "Published wording") |
| 503 | #expect(workspace.drafts.first { $0.id == draft.id }?.scheduleStatus == "posted") |
| 504 | #expect(workspace.records.first { $0.id == receipt.id }?["status"] == "published") |
| 505 | #expect(workspace.records.first { $0.id == newsletter.id }?["state"] == "scheduled") |
| 506 | #expect(workspace.records.first { $0.id == newsletter.id }?["remoteId"] == "321") |
| 507 | let restored = try #require(workspace.drafts.first { $0.id == ordinary.id }) |
| 508 | #expect(restored.body == "Restored text") |
| 509 | #expect(restored["updatedAt"] != ordinary["updatedAt"]) |
| 510 | try workspace.apply(backup, files: files) |
| 511 | #expect(workspace.drafts.first { $0.id == ordinary.id }?["updatedAt"] == restored["updatedAt"]) |
| 512 | #expect(workspace.settings["autoPost"] as? Bool == false) |
| 513 | } |
| 514 | |
| 515 | @Test @MainActor func manualBackupIncludesChangesFromAnotherWorkspaceConnection() throws { |
| 516 | let directory = try temporaryWorkspace() |
| 517 | defer { try? FileManager.default.removeItem(at: directory) } |
| 518 | let workspace = Workspace(directory: directory) |
| 519 | let other = Workspace(directory: directory) |
| 520 | var draft = WorkspaceRecord.new("draft", projectID: other.projectID) |
| 521 | draft["title"] = "New draft from another connection" |
| 522 | draft["content"] = "Saved just before export." |
| 523 | try other.save(draft) |
| 524 | #expect(!workspace.records.contains { $0.id == draft.id }) |
| 525 | let archive = directory.appending(path: "manual.zip") |
| 526 | try workspace.exportBackup(to: archive) |
| 527 | let (backup, _) = try WorkspaceBackup.stage(archive, in: directory) |
| 528 | #expect(backup.records.first { $0.id == draft.id }?.body == "Saved just before export.") |
| 529 | } |
| 530 | |
| 531 | @Test @MainActor func existingDailyBackupRestoresInAnIsolatedWorkspace() throws { |
| 532 | guard let path = ProcessInfo.processInfo.environment["INKSPRING_DAILY_BACKUP_CHECK"] else { return } |
| 533 | let directory = try temporaryWorkspace() |
| 534 | defer { try? FileManager.default.removeItem(at: directory) } |
| 535 | let workspace = Workspace(directory: directory) |
| 536 | let (backup, files) = try WorkspaceBackup.stage(URL(fileURLWithPath: path), in: directory) |
| 537 | try workspace.apply(backup, files: files) |
| 538 | let restored = Dictionary(uniqueKeysWithValues: workspace.records.map { ($0.id, $0) }) |
| 539 | #expect(backup.records.allSatisfy { row in restored[row.id]?.kind == row.kind && restored[row.id]?.body == row.body }) |
| 540 | #expect(workspace.settings["autoPost"] as? Bool == false) |
| 541 | #expect(workspace.settings["mcpEnabled"] as? Bool == false) |
| 542 | #expect(workspace.records.allSatisfy { !["queued", "posting", "due"].contains($0.scheduleStatus) }) |
| 543 | let images = directory.appending(path: "images") |
| 544 | let restoredImages = FileManager.default.fileExists(atPath: images.path) |
| 545 | ? try FileManager.default.contentsOfDirectory(at: images, includingPropertiesForKeys: nil) : [] |
| 546 | let imagesByHash = try Dictionary(grouping: restoredImages) { try fileDigest($0).hash } |
| 547 | for entry in backup.media { |
| 548 | let name = if entry.kind == "video" { |
| 549 | entry.id.flatMap { restored[$0]?["path"] } |
| 550 | } else { |
| 551 | imagesByHash[entry.sha256]?.first?.path |
| 552 | } |
| 553 | let file = URL(fileURLWithPath: try #require(name)) |
| 554 | #expect(try fileDigest(file) == (entry.sha256, entry.size)) |
| 555 | } |
| 556 | } |