Jotley / app · jotley.ai / Jotley-iOSTests / Jotley_iOSTests.swift
| 1 | import CoreData |
| 2 | import Testing |
| 3 | import Foundation |
| 4 | import AVFoundation |
| 5 | import UIKit |
| 6 | import Speech |
| 7 | import FoundationModels |
| 8 | import XCTest |
| 9 | import UserNotifications |
| 10 | @testable import Jotley_iOS |
| 11 | |
| 12 | @Suite(.serialized) |
| 13 | struct Jotley_iOSTests { |
| 14 | init() { UserDefaults.standard.set(false, forKey: JotleySummaryNotifications.enabledKey) } |
| 15 | |
| 16 | @MainActor @Test func summaryNotificationsRespectConsentPrivacyAndDeduplication() async throws { |
| 17 | let suite = "JotleyNotificationTests-" + UUID().uuidString |
| 18 | let defaults = UserDefaults(suiteName: suite)! |
| 19 | defer { defaults.removePersistentDomain(forName: suite) } |
| 20 | var status: UNAuthorizationStatus = .notDetermined |
| 21 | var requests = 0 |
| 22 | var notifications: [UNNotificationRequest] = [] |
| 23 | let service = JotleySummaryNotifications(defaults: defaults, authorization: { status }, |
| 24 | requestAuthorization: { requests += 1; status = .authorized; return true }, |
| 25 | enqueue: { notifications.append($0) }, isActive: { true }) |
| 26 | #expect(service.isEnabled) |
| 27 | let note = UUID(), generation = UUID() |
| 28 | service.prepareForSummary(); service.prepareForSummary() |
| 29 | await service.summarySaved(noteID: note, generationID: generation) |
| 30 | await service.summarySaved(noteID: note, generationID: generation) |
| 31 | #expect(requests == 1 && notifications.count == 1) |
| 32 | let sent = try #require(notifications.first) |
| 33 | #expect(sent.content.title == "Summary ready") |
| 34 | #expect(sent.content.body == "Your summary is saved. Open Jotley to read it.") |
| 35 | #expect(sent.content.userInfo.count == 1 && sent.content.userInfo["noteID"] as? String == note.uuidString) |
| 36 | #expect(sent.trigger == nil) |
| 37 | #expect(service.openSummary(from: sent) && service.noteToOpen == note) |
| 38 | status = .denied |
| 39 | service.prepareForSummary() |
| 40 | await service.summarySaved(noteID: note) |
| 41 | #expect(requests == 1 && notifications.count == 1) |
| 42 | defaults.set(false, forKey: JotleySummaryNotifications.enabledKey) |
| 43 | status = .authorized |
| 44 | await service.summarySaved(noteID: note) |
| 45 | #expect(notifications.count == 1) |
| 46 | defaults.set(true, forKey: JotleySummaryNotifications.enabledKey) |
| 47 | await service.summarySaved(noteID: nil) |
| 48 | #expect(notifications.count == 1) |
| 49 | } |
| 50 | |
| 51 | #if DEBUG && targetEnvironment(simulator) |
| 52 | @MainActor @Test func shortNoteGetsSummaryTitleAndMiscWhenModelReturnsPlaceholders() async throws { |
| 53 | let store = try SharedPersistenceController(inMemory: true) |
| 54 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 55 | let manager = LiveTranscriptionManager(store: store) |
| 56 | let transcript = "The porch light flickers." |
| 57 | manager.simulatedSummaryGeneration = { _ in "## Summary\n" } |
| 58 | manager.simulatedTitleGeneration = { _ in throw LocalError.message("No title returned") } |
| 59 | manager.simulatedOrganization = { _, _ in LocalNoteOrganization(tags: [], folder: .unfiled) } |
| 60 | |
| 61 | let note = try manager.createNote(text: transcript, title: "Untitled Note") |
| 62 | manager.summarize(note, template: .auto) |
| 63 | for _ in 0..<200 { |
| 64 | if manager.summaryNoteID == nil { break } |
| 65 | try await Task.sleep(for: .milliseconds(10)) |
| 66 | } |
| 67 | #expect(manager.summaryNoteID == nil) |
| 68 | #expect(note.summary == transcript) |
| 69 | #expect(note.title == transcript) |
| 70 | #expect(note.folder?.name == "Misc") |
| 71 | #expect(note.tagNames.count == 3) |
| 72 | #expect(manager.errorMessage == nil) |
| 73 | |
| 74 | let second = try manager.createNote(text: "Replace the porch light.", title: "Untitled Note") |
| 75 | manager.simulatedTitleGeneration = { _ in |
| 76 | try store.saveNoteChanges(second, values: ["title": "My own title"]) |
| 77 | return "UNTITLED NOTE." |
| 78 | } |
| 79 | manager.summarize(second, template: .auto) |
| 80 | for _ in 0..<200 { |
| 81 | if manager.summaryNoteID == nil { break } |
| 82 | try await Task.sleep(for: .milliseconds(10)) |
| 83 | } |
| 84 | #expect(second.title == "My own title") |
| 85 | #expect(second.folder?.objectID == note.folder?.objectID) |
| 86 | } |
| 87 | |
| 88 | @MainActor @Test func successfulSummaryAddsThreeTagsAndPreservesManualTagsAndCancelledWork() async throws { |
| 89 | let store = try SharedPersistenceController(inMemory: true) |
| 90 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 91 | let suite = "JotleySummaryDelivery-" + UUID().uuidString |
| 92 | let defaults = UserDefaults(suiteName: suite)! |
| 93 | defer { defaults.removePersistentDomain(forName: suite) } |
| 94 | var sent: [UNNotificationRequest] = [] |
| 95 | let notifications = JotleySummaryNotifications(defaults: defaults, authorization: { .authorized }, |
| 96 | requestAuthorization: { true }, enqueue: { request in |
| 97 | let saved = try store.notes() |
| 98 | #expect(saved.contains { $0.text("summary") == "A completed design summary." }) |
| 99 | sent.append(request) |
| 100 | }, isActive: { true }) |
| 101 | let manager = LiveTranscriptionManager(store: store, summaryNotifications: notifications) |
| 102 | let note = try manager.createNote(text: String(repeating: "AI supports design and helps the team explore useful interface ideas. ", count: 5), title: "Design review") |
| 103 | let other = try manager.createNote(text: "Related work", title: "Related") |
| 104 | try store.saveNoteChanges(other, values: [:], replacingTags: ["AI", "Design"]) |
| 105 | store.organizeCompletedRecording(note, locale: Locale(identifier: "zxx")) |
| 106 | for _ in 0..<200 { |
| 107 | if note.folder != nil { break } |
| 108 | try await Task.sleep(for: .milliseconds(10)) |
| 109 | } |
| 110 | #expect(note.folder != nil) |
| 111 | #expect(note.tagNames.isEmpty) |
| 112 | #expect(!note.hasMeaningfulSummaryText) |
| 113 | try note.addTagByName("My own tag", in: store.context) |
| 114 | try store.save() |
| 115 | manager.simulatedSummaryGeneration = { _ in "A completed design summary." } |
| 116 | manager.simulatedOrganization = { _, library in |
| 117 | #expect(library.contains { $0.name == "AI" }) |
| 118 | return LocalNoteOrganization(tags: ["Artificial Intelligence", "AI Tools", "Design"], folder: .work) |
| 119 | } |
| 120 | manager.summarize(note, template: .auto) |
| 121 | for _ in 0..<100 { if manager.summaryNoteID == nil { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 122 | #expect(note.summary == "A completed design summary.") |
| 123 | #expect(note.tagNames.count == 4 && Set(["AI", "Design", "My-own-tag"]).isSubset(of: note.tagNames) && other.tagNames == ["AI", "Design"]) |
| 124 | #expect(note.folder != nil) |
| 125 | #expect(manager.errorMessage == nil && sent.count == 1) |
| 126 | try note.addTagByName("Follow-up", in: store.context) |
| 127 | #expect(throws: LocalError.self) { try note.addTagByName("Sixth tag", in: store.context) } |
| 128 | let savedTags = note.tagNames |
| 129 | manager.simulatedOrganization = { _, _ in |
| 130 | Issue.record("Regenerating a tagged summary should preserve the existing tags") |
| 131 | throw LocalError.message("Unexpected organization") |
| 132 | } |
| 133 | manager.summarize(note, template: .auto) |
| 134 | for _ in 0..<100 { if manager.summaryNoteID == nil { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 135 | #expect(note.tagNames == savedTags) |
| 136 | #expect(manager.errorMessage == nil && sent.count == 2) |
| 137 | manager.simulatedSummaryGeneration = { _ in |
| 138 | try await Task.sleep(for: .seconds(5)) |
| 139 | return "Cancelled replacement summary" |
| 140 | } |
| 141 | manager.simulatedOrganization = { _, _ in |
| 142 | try await Task.sleep(for: .seconds(5)) |
| 143 | return LocalNoteOrganization(tags: ["Wrong"], folder: .personal) |
| 144 | } |
| 145 | manager.summarize(note, template: .auto) |
| 146 | #expect(manager.summaryNoteID != nil) |
| 147 | manager.cancelProcessing() |
| 148 | for _ in 0..<100 { if manager.summaryNoteID == nil { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 149 | #expect(note.summary == "A completed design summary." && note.tagNames == savedTags && sent.count == 2) |
| 150 | manager.simulatedSummaryGeneration = { _ in throw LocalError.message("Injected summary failure") } |
| 151 | manager.summarize(note, template: .auto) |
| 152 | for _ in 0..<100 { if manager.summaryNoteID == nil { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 153 | #expect(sent.count == 2 && note.summary == "A completed design summary.") |
| 154 | manager.simulatedSummaryGeneration = { _ in "A completed design summary." } |
| 155 | manager.simulatedOrganization = { _, _ in LocalNoteOrganization(tags: [], folder: .unfiled) } |
| 156 | note.transcription = "one two three four five six seven eight nine ten" |
| 157 | manager.summarize(note, template: .auto) |
| 158 | for _ in 0..<100 { if manager.summaryNoteID == nil { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 159 | #expect(note.tagNames == savedTags && sent.count == 3) |
| 160 | note.transcription = "one two three four five six seven eight nine" |
| 161 | manager.summarize(note, template: .auto) |
| 162 | for _ in 0..<100 { if manager.summaryNoteID == nil { break }; try await Task.sleep(for: .milliseconds(10)) } |
| 163 | #expect(note.tagNames == savedTags && sent.count == 4) |
| 164 | } |
| 165 | #endif |
| 166 | |
| 167 | #if DEBUG && targetEnvironment(simulator) |
| 168 | @MainActor @Test func savedSummaryReachesSystemNotificationCenter() async throws { |
| 169 | let center = UNUserNotificationCenter.current() |
| 170 | let status = await center.notificationSettings().authorizationStatus |
| 171 | guard status == .authorized || status == .provisional else { |
| 172 | throw XCTSkip("Allow notifications in the Simulator before running the real OS delivery check") |
| 173 | } |
| 174 | let suite = "JotleyRealNotification-" + UUID().uuidString |
| 175 | let defaults = UserDefaults(suiteName: suite)! |
| 176 | defer { defaults.removePersistentDomain(forName: suite); JotleySummaryNotifications.shared.install() } |
| 177 | let service = JotleySummaryNotifications(defaults: defaults, center: center) |
| 178 | service.install() |
| 179 | let store = try SharedPersistenceController(inMemory: true) |
| 180 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 181 | let manager = LiveTranscriptionManager(store: store, summaryNotifications: service) |
| 182 | let note = try manager.createNote(text: "Maya will check the next build Friday.", title: "Notification test") |
| 183 | manager.simulatedSummaryGeneration = { _ in "Maya will check the next build Friday." } |
| 184 | manager.simulatedOrganization = { _, _ in LocalNoteOrganization(tags: ["Testing"], folder: .unfiled) } |
| 185 | manager.summarize(note, template: .auto) |
| 186 | for _ in 0..<200 { if manager.summaryNoteID == nil { break }; try await Task.sleep(for: .milliseconds(20)) } |
| 187 | #expect(note.summary == "Maya will check the next build Friday.") |
| 188 | #expect(manager.summaryNoteID == nil) |
| 189 | var matching: [UNNotification] = [] |
| 190 | for _ in 0..<50 { |
| 191 | matching = await center.deliveredNotifications().filter { $0.request.content.userInfo["noteID"] as? String == note.id?.uuidString } |
| 192 | if !matching.isEmpty { break } |
| 193 | try await Task.sleep(for: .milliseconds(100)) |
| 194 | } |
| 195 | defer { center.removeDeliveredNotifications(withIdentifiers: matching.map { $0.request.identifier }) } |
| 196 | #expect(matching.count == 1) |
| 197 | #expect(matching.first?.request.content.title == "Summary ready") |
| 198 | print("Verified real OS summary delivery:", matching.map { $0.request.identifier }) |
| 199 | } |
| 200 | #endif |
| 201 | |
| 202 | @MainActor @Test func streamingSummaryDoesNotCreateTemporaryMarkdownCards() throws { |
| 203 | let base = "## Summary\nA short overview.\n\n## Key Points\n- First point.\n" |
| 204 | let initial = StructuredSummary(ParsedNoteMarkdown.rendering(base, isStreaming: true)) |
| 205 | for tail in ["-", " -", "##", "## Action Items", "**Action", "**Action Items**", "1", "1.", |
| 206 | "- N", "- No", "- No decisions are", "- No decisions are mentioned.", "- None"] { |
| 207 | let parsed = ParsedNoteMarkdown.rendering(base + tail, isStreaming: true) |
| 208 | let result = StructuredSummary(parsed) |
| 209 | #expect(result.blocks.map(\.id) == initial.blocks.map(\.id)) |
| 210 | #expect(result.sections[0].paragraphs.isEmpty) |
| 211 | #expect(result.sections[0].items.count == 1) |
| 212 | } |
| 213 | let growing = "- A second point grows word by word." |
| 214 | for filler in ["- None", "- Nothing", "- N/A", "- No decisions are mentioned."] { |
| 215 | for length in 1...filler.count { |
| 216 | let result = StructuredSummary(ParsedNoteMarkdown.rendering(base + filler.prefix(length), isStreaming: true)) |
| 217 | #expect(result.sections[0].items.count == 1) |
| 218 | #expect(result.sections[0].paragraphs.isEmpty) |
| 219 | } |
| 220 | } |
| 221 | for length in 3...growing.count { |
| 222 | let result = StructuredSummary(ParsedNoteMarkdown.rendering(base + growing.prefix(length), isStreaming: true)) |
| 223 | #expect(result.sections[0].paragraphs.isEmpty) |
| 224 | #expect(result.sections[0].items.count == 2) |
| 225 | #expect(result.sections[0].items.last?.id == initial.sections[0].items[0].id + 1) |
| 226 | } |
| 227 | let complete = base + "## Action Items\n- Maya: Test the Mac layout." |
| 228 | let streamed = StructuredSummary(ParsedNoteMarkdown.rendering(complete, isStreaming: true)) |
| 229 | let saved = StructuredSummary(ParsedNoteMarkdown.rendering(complete)) |
| 230 | #expect(streamed.blocks.map(\.id) == saved.blocks.map(\.id)) |
| 231 | #expect(streamed.sections.map(\.title) == saved.sections.map(\.title)) |
| 232 | #expect(streamed.sections.last?.items.last?.fullText == "Maya: Test the Mac layout.") |
| 233 | // An overview classification change retains its source identity. |
| 234 | let lead = "## Launch\nA short lead-in.\n" |
| 235 | let before = StructuredSummary(ParsedNoteMarkdown.rendering(lead)) |
| 236 | let after = StructuredSummary(ParsedNoteMarkdown.rendering(lead + "## Decisions\n- Ship Friday.")) |
| 237 | #expect(before.blocks.first?.id == after.blocks.first?.id) |
| 238 | #expect(ParsedNoteMarkdown.rendering("## Action Items").lines[0].heading) |
| 239 | // A real point starting with No is delayed for one line, never dropped. |
| 240 | let deadline = base + "- No later than Friday." |
| 241 | #expect(StructuredSummary(ParsedNoteMarkdown.rendering(deadline)).sections[0].items.count == 2) |
| 242 | #expect(StructuredSummary(ParsedNoteMarkdown.rendering(deadline + "\n", isStreaming: true)).sections[0].items.count == 2) |
| 243 | } |
| 244 | |
| 245 | @MainActor @Test func summaryEditsPersistMarkdownWithoutChangingTranscriptAndRejectStaleDrafts() throws { |
| 246 | let store = try SharedPersistenceController(root: FileManager.default.temporaryDirectory.appendingPathComponent("JotleySummaryEditing-" + UUID().uuidString)) |
| 247 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 248 | let note = try #require(store.create(title: "Edited summary", text: "Original spoken words.") as? Note) |
| 249 | let original = "# Decisions\n- Original decision." |
| 250 | note.summary = original |
| 251 | note.setTranscriptUtterances([TranscriptUtterance(id: "original", text: "Original spoken words.", start: 4, end: 6)]) |
| 252 | try store.context.save() |
| 253 | let timing = note.value(forKey: "transcriptUtterancesJSON") as? String |
| 254 | let edited = "# Decisions\n- **Approved** decision.\n - Follow up Friday." |
| 255 | try note.saveEditedSummary(edited, original: original, in: store) |
| 256 | #expect(note.summary == edited) |
| 257 | #expect(note.transcription == "Original spoken words.") |
| 258 | #expect(note.value(forKey: "transcriptUtterancesJSON") as? String == timing) |
| 259 | #expect(throws: (any Error).self) { try note.saveEditedSummary("Stale edit", original: original, in: store) } |
| 260 | let id = note.objectID |
| 261 | store.context.reset() |
| 262 | let reloaded = try #require(store.context.existingObject(with: id) as? Note) |
| 263 | #expect(reloaded.summary == edited) |
| 264 | #expect(reloaded.transcription == "Original spoken words.") |
| 265 | #expect(reloaded.value(forKey: "transcriptUtterancesJSON") as? String == timing) |
| 266 | } |
| 267 | |
| 268 | @MainActor @Test func summaryMarkdownRendersListsAndPreservesInlineFormatting() throws { |
| 269 | let source = "# Decisions\n- **Keep** the transcript.\n - Nested task.\n* Another task.\n+ Last task.\n1. First step.\n2) Second step.\nA - dash in prose.\n\\- Escaped dash." |
| 270 | let parsed = ParsedNoteMarkdown.rendering(source) |
| 271 | #expect(parsed.lines[0].heading) |
| 272 | #expect(parsed.lines[1...4].allSatisfy { $0.marker == "•" }) |
| 273 | #expect(parsed.lines[1].text.runs.contains { $0.inlinePresentationIntent?.contains(.stronglyEmphasized) == true }) |
| 274 | #expect(String(parsed.lines[1].text.characters) == "Keep the transcript.") |
| 275 | #expect(parsed.lines[2].indentation == 2) |
| 276 | #expect(parsed.lines[5].marker == "1." && parsed.lines[6].marker == "2.") |
| 277 | #expect(parsed.lines[7].marker == nil && parsed.lines[8].marker == nil) |
| 278 | #expect(ParsedNoteMarkdown.rendering(source) === parsed) |
| 279 | } |
| 280 | |
| 281 | @Test func askAIConversationExportsEveryTurnInOrder() { |
| 282 | let messages = [LocalChatMessage(role: "user", content: "Who owns onboarding?"), |
| 283 | LocalChatMessage(role: "assistant", content: "- Maya finishes the onboarding screens.\n")] |
| 284 | let text = LocalNoteChat.conversationMarkdown(title: "Weekly Design Review", messages: messages) |
| 285 | #expect(text == "# Ask AI: Weekly Design Review\n\n**You**\n\nWho owns onboarding?\n\n**Jotley**\n\n- Maya finishes the onboarding screens.") |
| 286 | #expect(LocalNoteChat.conversationMarkdown(title: nil, messages: []) == "# Ask AI: Untitled") |
| 287 | } |
| 288 | |
| 289 | @MainActor @Test func structuredSummaryGroupsOverviewSectionsAndLabels() throws { |
| 290 | let source = "## Summary\nThe team agreed to ship Friday.\n\n## Key Points\n- **Launch date**: Friday at 10:00.\n - Room booked.\n- Keep the transcript simple.\n\n## Action Items\n- **Maya**: Finish onboarding.\n- Check https://example.com today.\n\n## Open Questions\n- Who owns widgets?" |
| 291 | let summary = StructuredSummary(ParsedNoteMarkdown.rendering(source)) |
| 292 | let overview = try #require(summary.overview) |
| 293 | #expect(String(overview.paragraphs[0].text.characters) == "The team agreed to ship Friday.") |
| 294 | #expect(summary.sections.map(\.title) == ["Key Points", "Action Items", "Open Questions"]) |
| 295 | #expect(summary.sections.map(\.style) == [.numbered, .checklist, .questions]) |
| 296 | let points = summary.sections[0].items |
| 297 | #expect(points[0].label.map { String($0.characters) } == "Launch date") |
| 298 | #expect(String(points[0].body.characters) == "Friday at 10:00.") |
| 299 | #expect(StructuredSummaryView.groups(points).map(\.count) == [2, 1]) |
| 300 | #expect(summary.sections[1].items[0].label.map { String($0.characters) } == "Maya") |
| 301 | #expect(summary.sections[1].items[1].label == nil) |
| 302 | let french = StructuredSummary(ParsedNoteMarkdown.rendering("## Résumé\nLancement vendredi.\n\n## Actions\n- Tester.")) |
| 303 | #expect(french.overview != nil && french.sections.count == 1) |
| 304 | let legacy = StructuredSummary(ParsedNoteMarkdown.rendering("The team reviewed the launch.\n**Key Points:**\n- Ship Friday.\n**Action Items**\n- **Maya**: Finish onboarding.\nA **bold** word in prose.")) |
| 305 | #expect(legacy.overview.map { String($0.paragraphs[0].text.characters) } == "The team reviewed the launch.") |
| 306 | #expect(legacy.sections.map(\.title) == ["Key Points", "Action Items"]) |
| 307 | #expect(legacy.sections[1].style == .checklist && legacy.sections[1].paragraphs.count == 1) |
| 308 | let filler = StructuredSummary(ParsedNoteMarkdown.rendering("## Summary\nA lecture.\n\n## Formulas\n- No formulas provided.\n\n## Examples\n- \n- None\n- Chunking 1-9-8-4.\n- No later than Friday.")) |
| 309 | #expect(filler.sections.map(\.title) == ["Examples"]) |
| 310 | #expect(filler.sections[0].items.map(\.fullText) == ["Chunking 1-9-8-4.", "No later than Friday."]) |
| 311 | let owner = StructuredSummary(ParsedNoteMarkdown.rendering("## Action Items\n- **Sam**: sends the list.")) |
| 312 | #expect(String(owner.sections[0].items[0].body.characters) == "Sends the list.") |
| 313 | let japanese = StructuredSummary(ParsedNoteMarkdown.rendering("**アクション項目**:\n- **美咲**:字幕を確認する。")) |
| 314 | let action = try #require(japanese.sections.first) |
| 315 | let task = try #require(action.items.first) |
| 316 | #expect(action.title == "アクション項目") |
| 317 | #expect(action.style == .checklist) |
| 318 | #expect(task.label.map { String($0.characters) } == "美咲") |
| 319 | #expect(String(task.body.characters) == "字幕を確認する。") |
| 320 | let time = StructuredSummary(ParsedNoteMarkdown.rendering("## Milestones\n- Launch Friday at 10:00.")) |
| 321 | #expect(time.sections[0].items[0].label == nil) |
| 322 | let casing = StructuredSummary(ParsedNoteMarkdown.rendering("## To-Dos\n- renew the registration.\n- iPad testing on Friday.")) |
| 323 | #expect(casing.sections[0].items.map { String($0.body.characters) } == ["Renew the registration.", "iPad testing on Friday."]) |
| 324 | let untitled = StructuredSummary(ParsedNoteMarkdown.rendering("# Decisions\n- Keep it.")) |
| 325 | #expect(untitled.overview == nil && untitled.sections.count == 1) |
| 326 | } |
| 327 | |
| 328 | @MainActor @Test func transcriptEditsPersistWithoutReplacingSummaryAndRejectStaleDrafts() throws { |
| 329 | let store = try SharedPersistenceController(root: FileManager.default.temporaryDirectory.appendingPathComponent("JotleyTranscriptEditing-" + UUID().uuidString)) |
| 330 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 331 | let note = try #require(store.create(title: "Edited note", text: "Original words.") as? Note) |
| 332 | note.summary = "Keep this summary." |
| 333 | note.sourceURL = "local://existing-mac-recording" |
| 334 | note.setTranscriptUtterances([TranscriptUtterance(id: "original", text: "Original words.", start: 4, end: 6)]) |
| 335 | try store.context.save() |
| 336 | let originalPayload = note.value(forKey: "transcriptUtterancesJSON") as? String |
| 337 | try note.saveEditedTranscript("Original words.", original: "Original words.", in: store) |
| 338 | #expect(note.value(forKey: "transcriptUtterancesJSON") as? String == originalPayload) |
| 339 | try note.saveEditedTranscript("Corrected words.\n\nSecond paragraph.", original: "Original words.", in: store) |
| 340 | #expect(note.transcriptUtterances.map(\.text) == ["Corrected words.", "Second paragraph."]) |
| 341 | #expect(note.transcriptUtterances.allSatisfy { $0.start == nil && $0.end == nil }) |
| 342 | #expect(note.summary == "Keep this summary.") |
| 343 | #expect(note.sourceURL == "local://existing-mac-recording") |
| 344 | #expect(throws: (any Error).self) { |
| 345 | try note.saveEditedTranscript("Stale changes.", original: "Original words.", in: store) |
| 346 | } |
| 347 | let id = note.objectID |
| 348 | store.context.reset() |
| 349 | let reloaded = try #require(store.context.existingObject(with: id) as? Note) |
| 350 | #expect(reloaded.transcription == "Corrected words.\n\nSecond paragraph.") |
| 351 | #expect(reloaded.transcriptUtterances.map(\.text) == ["Corrected words.", "Second paragraph."]) |
| 352 | #expect(reloaded.summary == "Keep this summary.") |
| 353 | #expect(reloaded.sourceURL == "local://existing-mac-recording") |
| 354 | } |
| 355 | @Test func widgetLinksAcceptTranscriptionAndInstalledWidgetAliases() throws { |
| 356 | let id = UUID() |
| 357 | #expect(MobileTranscriptionAction(url: try #require(URL(string: "jotley://startrecording"))) == .start) |
| 358 | #expect(MobileTranscriptionAction(url: try #require(URL(string: "jotley://stoprecording?id=\(id.uuidString)"))) == .stop(id)) |
| 359 | #expect(MobileTranscriptionAction(url: try #require(URL(string: "jotley://pauserecording?id=\(id.uuidString)"))) == .pause(id)) |
| 360 | #expect(MobileTranscriptionAction(url: try #require(URL(string: "jotley://starttranscription"))) == .start) |
| 361 | #expect(MobileTranscriptionAction(url: try #require(URL(string: "jotley://stoptranscription?id=\(id.uuidString)"))) == .stop(id)) |
| 362 | #expect(MobileTranscriptionAction(url: try #require(URL(string: "jotley://pausetranscription?id=\(id.uuidString)"))) == .pause(id)) |
| 363 | #expect(MobileTranscriptionAction(url: try #require(URL(string: "jotley://transcription?id=\(id.uuidString)"))) == .open(id)) |
| 364 | for invalid in ["https://startrecording", "jotley://stoprecording", "jotley://pauserecording?id=invalid", "jotley://recording?id=\(id.uuidString)&id=\(id.uuidString)", "jotley://other?id=\(id.uuidString)"] { |
| 365 | #expect(MobileTranscriptionAction(url: try #require(URL(string: invalid))) == nil) |
| 366 | } |
| 367 | } |
| 368 | @Test func askAISelectsEvidenceBeyondBeginningAndBoundsHistory() throws { |
| 369 | let source = String(repeating: "Routine introduction. ", count: 500) + " The launch owner is Mina; shipping is Friday." |
| 370 | let history = [LocalChatMessage(role: "assistant", content: String(repeating: "old answer ", count: 1000))] |
| 371 | let prompt = try LocalNoteChat.prompt(source: source, question: "Who is the launch owner?", history: history) |
| 372 | #expect(prompt.contains("launch owner is Mina")) |
| 373 | #expect(prompt.utf8.count < 4000) |
| 374 | #expect(prompt.contains("selected excerpts")) |
| 375 | #expect(throws: (any Error).self) { try LocalNoteChat.prompt(source: "", question: "Who?", history: []) } |
| 376 | #expect(throws: (any Error).self) { try LocalNoteChat.prompt(source: "A note", question: String(repeating: "x", count: 801), history: []) } |
| 377 | } |
| 378 | @MainActor @Test func askAIHistoryIsNoteScopedAndSurvivesReloadAndDeletion() throws { |
| 379 | let store = try SharedPersistenceController(inMemory: true) |
| 380 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 381 | let first = try store.create(title: "First", text: "Mina ships Friday") |
| 382 | let second = try store.create(title: "Second") |
| 383 | let firstID = try #require(first.localNoteID), secondID = try #require(second.localNoteID) |
| 384 | let question = LocalChatMessage(role: "user", content: "Who ships?") |
| 385 | let answer = LocalChatMessage(role: "assistant", content: "Mina.", timestamp: question.timestamp) |
| 386 | try store.saveChatMessage(question, noteID: firstID) |
| 387 | try store.saveChatMessage(answer, noteID: firstID) |
| 388 | let loaded = try store.chatMessages(noteID: firstID) |
| 389 | #expect(loaded.map(\.id) == [question.id, answer.id]) |
| 390 | #expect(loaded.map(\.content) == [question.content, answer.content]) |
| 391 | #expect(loaded.map(\.role) == ["user", "assistant"]) |
| 392 | #expect(abs((loaded.first?.timestamp ?? .distantPast).timeIntervalSince(question.timestamp)) < 0.000001) |
| 393 | #expect(try store.chatMessages(noteID: secondID).isEmpty) |
| 394 | store.context.reset() |
| 395 | let reloaded = try store.chatMessages(noteID: firstID) |
| 396 | #expect(reloaded.map(\.id) == [question.id, answer.id]) |
| 397 | #expect(reloaded.map(\.content) == [question.content, answer.content]) |
| 398 | try store.clearChat(noteID: secondID) |
| 399 | #expect(try store.chatMessages(noteID: firstID).count == 2) |
| 400 | let note = try #require(store.notes().first { $0.localNoteID == firstID }) |
| 401 | try store.deleteNote(note) |
| 402 | #expect(try store.chatMessages(noteID: firstID).isEmpty) |
| 403 | #expect(throws: (any Error).self) { try store.saveChatMessage(answer, noteID: firstID) } |
| 404 | } |
| 405 | @Test func microphoneKeepsListeningThroughSilenceWhileBuffersArrive() { |
| 406 | let progress = MicrophoneCaptureProgress(startedAt: 100) |
| 407 | // Ten seconds of microphone buffers (which may contain silence) still |
| 408 | // count as delivery. Silence must never trigger a disconnected-input alert. |
| 409 | for second in 100...110 { progress.received(frames: 48000, at: Double(second)) } |
| 410 | #expect(!progress.snapshot(at: 110).stalled) |
| 411 | #expect(progress.snapshot(at: 110).frames == 528000) |
| 412 | #expect(progress.snapshot(at: 113).stalled) |
| 413 | } |
| 414 | @Test func microphoneFailuresExplainRecoveryInsteadOfShowingOSStatusText() { |
| 415 | let message = LiveTranscriptionManager.microphoneErrorMessage(NSError(domain: NSOSStatusErrorDomain, code: -10851)) |
| 416 | #expect(message.contains("Settings → Apps → Jotley")) |
| 417 | #expect(message.contains("preserved")) |
| 418 | #expect(!message.contains("-10851")) |
| 419 | #expect(LiveTranscriptionManager.microphoneErrorMessage(LocalError.message("The microphone is muted.")) == "The microphone is muted.") |
| 420 | } |
| 421 | |
| 422 | |
| 423 | @Test func microphoneProgressDistinguishesSilenceFromMissingBuffers() { |
| 424 | let progress = MicrophoneCaptureProgress(startedAt: 100) |
| 425 | #expect(progress.snapshot(at: 102).frames == 0) |
| 426 | #expect(!progress.snapshot(at: 102).stalled) |
| 427 | #expect(progress.snapshot(at: 103).stalled) |
| 428 | // Zero-amplitude PCM still arrives as frames and must keep transcribing. |
| 429 | progress.received(frames: 48000, at: 103) |
| 430 | #expect(progress.snapshot(at: 105).frames == 48000) |
| 431 | #expect(!progress.snapshot(at: 105).stalled) |
| 432 | progress.received(frames: 0, at: 105) |
| 433 | #expect(progress.snapshot(at: 106).stalled) |
| 434 | progress.received(frames: 24000, at: 106) |
| 435 | #expect(progress.snapshot(at: 106).frames == 72000) |
| 436 | #expect(!progress.snapshot(at: 106).stalled) |
| 437 | } |
| 438 | @Test func languageChoicesRequireSpeechAndIntelligenceAndCollapseRegionalVariants() async throws { |
| 439 | let locales = ["en-US", "en-GB", "fr-FR", "fr-CA", "zh-CN", "zh-TW", "zh-HK", "ar-SA", "ru-RU", "hi-IN", "pl-PL"].map { Locale(identifier: $0) } |
| 440 | let choices = LocalSpeech.languages(speechLocales: locales, preferredLocale: Locale(identifier: "en-GB"), |
| 441 | supportsLocale: { $0.language.languageCode?.identifier != "fr" }) |
| 442 | #expect(Set(choices.map(\.id)) == ["en-GB", "zh-CN", "zh-TW"]) |
| 443 | #expect(LocalSpeech.selectedLanguage(locale: Locale(identifier: "en-AU"), in: choices)?.id == "en-GB") |
| 444 | #expect(LocalSpeech.selectedLanguage(locale: Locale(identifier: "ar-SA"), in: choices) == nil) |
| 445 | #expect(LocalSpeech.selectedLanguage(locale: Locale(identifier: "zh-HK"), in: choices)?.id == "zh-TW") |
| 446 | let all = await LocalSpeech.languages() |
| 447 | #expect(all.count <= 16) |
| 448 | #expect(Set(all.compactMap { LocalSpeech.languageKey(for: Locale(identifier: $0.id)) }).count == all.count) |
| 449 | for choice in all { #expect(SystemLanguageModel.default.supportsLocale(Locale(identifier: choice.id))) } |
| 450 | // Legacy choices must fail before asset reservation, installation or capture. |
| 451 | for id in ["ar-SA", "ru-RU", "hi-IN", "pl-PL"] { |
| 452 | let readiness = await LocalSpeech.readiness(locale: Locale(identifier: id)) |
| 453 | #expect(readiness.status == .unsupported && readiness.configuration == nil && !readiness.needsSetup) |
| 454 | await #expect(throws: (any Error).self) { try await LocalSpeech.configuration(locale: Locale(identifier: id)) } |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | @MainActor @Test func unsupportedSpeechStopsBeforeMicrophoneCaptureAndCreatesNoAudio() async throws { |
| 459 | let previous = UserDefaults.standard.string(forKey: "transcriptionLanguage") |
| 460 | UserDefaults.standard.set("zxx", forKey: "transcriptionLanguage") |
| 461 | defer { |
| 462 | if let previous { UserDefaults.standard.set(previous, forKey: "transcriptionLanguage") } |
| 463 | else { UserDefaults.standard.removeObject(forKey: "transcriptionLanguage") } |
| 464 | } |
| 465 | let store = try SharedPersistenceController(inMemory: true) |
| 466 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 467 | let service = LiveTranscriptionManager(store: store) |
| 468 | let note = try service.createNote(text: "Keep existing words") |
| 469 | note.summary = "Keep existing summary"; try store.save() |
| 470 | await service.startTranscription(note: note) |
| 471 | #expect(!service.isTranscribing && service.canStart && service.activeNoteID == nil) |
| 472 | #expect(service.transcriptionDuration == 0) |
| 473 | #expect(service.errorMessage?.contains("unavailable") == true) |
| 474 | #expect(note.sourceURL == nil && note.transcription == "Keep existing words") |
| 475 | #expect(note.summary == "Keep existing summary") |
| 476 | #expect(!FileManager.default.fileExists(atPath: store.root.appendingPathComponent("Recordings").path)) |
| 477 | let lease = try store.beginRecording(note); store.endRecording(lease: lease) |
| 478 | } |
| 479 | @MainActor @Test func upgradeDeletesLegacyAudioAndPreservesNotesAndUnrelatedFiles() throws { |
| 480 | let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| 481 | let store = try SharedPersistenceController(root: root) |
| 482 | defer { |
| 483 | for item in store.container.persistentStoreCoordinator.persistentStores { try? store.container.persistentStoreCoordinator.remove(item) } |
| 484 | try? FileManager.default.removeItem(at: root) |
| 485 | } |
| 486 | let note = try #require(store.create(title: "Keep this note", text: "Existing spoken words.") as? Note) |
| 487 | note.summary = "Existing summary." |
| 488 | note.sourceURL = "Recordings/legacy" |
| 489 | try store.save() |
| 490 | for name in ["Recordings", "DeletedRecordings"] { |
| 491 | let directory = root.appendingPathComponent(name).appendingPathComponent("legacy/take") |
| 492 | try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) |
| 493 | try Data([1, 2, 3]).write(to: directory.appendingPathComponent("audio.caf")) |
| 494 | } |
| 495 | let unrelated = root.appendingPathComponent("Keep.txt") |
| 496 | try Data("keep".utf8).write(to: unrelated) |
| 497 | let manager = LiveTranscriptionManager(store: store) |
| 498 | #expect(manager.errorMessage == nil) |
| 499 | for name in ["Recordings", "DeletedRecordings"] { |
| 500 | #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent(name).path)) |
| 501 | } |
| 502 | #expect(try Data(contentsOf: unrelated) == Data("keep".utf8)) |
| 503 | store.context.reset() |
| 504 | let reloaded = try #require(store.notes().first as? Note) |
| 505 | #expect(reloaded.title == "Keep this note") |
| 506 | #expect(reloaded.transcription == "Existing spoken words.") |
| 507 | #expect(reloaded.summary == "Existing summary.") |
| 508 | try LegacyAudioCleanup.remove(in: root) // Repeated launches are harmless. |
| 509 | } |
| 510 | @MainActor @Test func liveCheckpointPersistsVolatileRevisionsAndFinalWordsWithoutAudio() throws { |
| 511 | let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| 512 | let store = try SharedPersistenceController(root: root) |
| 513 | defer { |
| 514 | for item in store.container.persistentStoreCoordinator.persistentStores { try? store.container.persistentStoreCoordinator.remove(item) } |
| 515 | try? FileManager.default.removeItem(at: root) |
| 516 | } |
| 517 | let note = try #require(store.create(title: "Checkpoint", text: "Previous words") as? Note) |
| 518 | note.setTranscriptUtterances([TranscriptUtterance(text: "Previous words", start: 0, end: 100)]) |
| 519 | note.summary = "Previous summary" |
| 520 | let checkpoint = MobileTranscriptCheckpoint(baseText: note.transcription ?? "", baseUtterances: note.transcriptUtterances, offset: 100) |
| 521 | var value = LocalTranscript() |
| 522 | value.accept(text: "Mina ship", start: 0, end: 2, final: false) |
| 523 | _ = try checkpoint.save(value, to: note, in: store) |
| 524 | store.context.refresh(note, mergeChanges: false) |
| 525 | #expect(note.transcription == "Previous words Mina ship") |
| 526 | #expect(note.transcriptUtterances.last?.end == 102) |
| 527 | value.accept(text: "Mina ships Friday", start: 0, end: 3, final: false) |
| 528 | _ = try checkpoint.save(value, to: note, in: store) |
| 529 | #expect(note.transcription == "Previous words Mina ships Friday") |
| 530 | value.accept(text: "Mina ships Friday.", start: 0, end: 3, final: true) |
| 531 | _ = try checkpoint.save(value, to: note, in: store) |
| 532 | store.context.reset() |
| 533 | let reloaded = try #require(store.notes().first as? Note) |
| 534 | #expect(reloaded.transcription == "Previous words Mina ships Friday.") |
| 535 | #expect(reloaded.transcriptUtterances.map(\.text).joined(separator: " ") == "Previous words Mina ships Friday.") |
| 536 | #expect(reloaded.transcriptUtterances.last?.end == 103) |
| 537 | #expect(reloaded.summary == "Previous summary") |
| 538 | #expect(reloaded.sourceURL == nil) |
| 539 | #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("Recordings").path)) |
| 540 | } |
| 541 | @Test func encryptedStoreAllowsNoteCheckpointsAfterFirstUnlock() throws { |
| 542 | let description = try NoteSyncMode.localOnly.storeDescription(at: URL(fileURLWithPath: "/tmp/unused-check.sqlite"), inMemory: false) |
| 543 | #expect(description.options[NSPersistentStoreFileProtectionKey] as? String == FileProtectionType.completeUntilFirstUserAuthentication.rawValue) |
| 544 | } |
| 545 | |
| 546 | @MainActor @Test func unchangedSummaryRenderingReusesParsedMarkdownAndTracksEdits() throws { |
| 547 | let marker = UUID().uuidString |
| 548 | let content = "# " + marker + "\n" + (0..<1000).map { "- **Point \($0)**: recorded words with *emphasis* and [a link](https://example.com)." }.joined(separator: "\n") |
| 549 | let start = Date() |
| 550 | let parsed = ParsedNoteMarkdown.rendering(content) |
| 551 | let cold = Date().timeIntervalSince(start) |
| 552 | #expect(parsed.lines.count == 1001) |
| 553 | #expect(parsed.lines[0].heading) |
| 554 | #expect(String(parsed.lines[0].text.characters) == marker) |
| 555 | let warmStart = Date() |
| 556 | for _ in 0..<100 { #expect(ParsedNoteMarkdown.rendering(content) === parsed) } |
| 557 | print("Summary rendering: cold \(cold)s; 100 unchanged lookups \(Date().timeIntervalSince(warmStart))s") |
| 558 | let edited = ParsedNoteMarkdown.rendering("# Updated heading\n**Fresh words**") |
| 559 | #expect(edited !== parsed) |
| 560 | #expect(String(edited.lines[0].text.characters) == "Updated heading") |
| 561 | #expect(String(edited.lines[1].text.characters) == "Fresh words") |
| 562 | let fenced = ParsedNoteMarkdown.rendering("```markdown\n# Fenced heading\nBody\n```") |
| 563 | #expect(fenced.lines.count == 2 && fenced.lines[0].heading) |
| 564 | } |
| 565 | @Test func speechSetupSelection() async throws { |
| 566 | #expect(LocalSpeech.preferredIndex(statuses: [.supported, .installed]) == 1) |
| 567 | #expect(LocalSpeech.preferredIndex(statuses: [.supported, .downloading]) == 0) |
| 568 | #expect(LocalSpeech.preferredIndex(statuses: [.unsupported, .supported]) == 1) |
| 569 | #expect(LocalSpeech.preferredIndex(statuses: [.unsupported]) == 0) |
| 570 | #expect(LocalSpeech.preferredIndex(statuses: []) == nil) |
| 571 | let locale = Locale(identifier: "en_US") |
| 572 | #expect(LocalSpeech.exactLocale(Locale(identifier: "en-US"), in: [locale]) == locale) |
| 573 | #expect(LocalSpeech.exactLocale(Locale(identifier: "en-GB"), in: [locale]) == nil) |
| 574 | let module = DictationTranscriber(locale: locale, preset: .timeIndexedLongDictation) |
| 575 | let notReady = LocalSpeech.Readiness(configuration: .init(module: module, engine: .dictation, locale: locale), status: .unsupported) |
| 576 | #expect(notReady.needsSetup) |
| 577 | #expect(notReady.message.contains("Set Up On-Device Speech")) |
| 578 | let installed = LocalSpeech.Readiness(configuration: .init(module: module, engine: .dictation, locale: locale), status: .installed) |
| 579 | let selected = try LocalSpeech.configuration(from: installed) |
| 580 | #expect(selected.engine == .dictation && selected.locale == locale) |
| 581 | #expect((selected.module as? DictationTranscriber) === module) |
| 582 | do { |
| 583 | _ = try LocalSpeech.configuration(from: notReady) |
| 584 | Issue.record("An unready configuration must not be accepted for transcription") |
| 585 | } catch { #expect(error.localizedDescription.contains("Set Up On-Device Speech")) } |
| 586 | let ready = await LocalSpeech.readiness(locale: Locale(identifier: "zxx")) |
| 587 | #expect(ready.status == .unsupported) |
| 588 | #expect(!ready.needsSetup) |
| 589 | do { |
| 590 | try await LocalSpeech.setUp(locale: Locale(identifier: "zxx")) { _ in |
| 591 | Issue.record("Unsupported speech must not start setup or report download progress") |
| 592 | } |
| 593 | Issue.record("Unsupported speech setup must fail before installation") |
| 594 | } catch { |
| 595 | #expect(error.localizedDescription.contains("unavailable for the selected language")) |
| 596 | } |
| 597 | } |
| 598 | @MainActor @Test func transcriptDisplayTracksRevisionsAndIndependentContexts() throws { |
| 599 | let store = try SharedPersistenceController(inMemory: true) |
| 600 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 601 | let context = store.context |
| 602 | let note = try #require(store.create(title: "Generated display fixture") as? Note) |
| 603 | for revision in 0..<100 { |
| 604 | let text = "Revision \(revision) " + String(repeating: "你好📝", count: 128) |
| 605 | note.transcription = text |
| 606 | note.setTranscriptUtterances([TranscriptUtterance(id: "fixture", text: text, start: 12, end: 14, speaker: 3, confidence: 0.88)]) |
| 607 | let display = try #require(note.transcriptUtterances.first) |
| 608 | #expect(note.transcriptUtterances.count == 1) |
| 609 | #expect(display.text == text && display.start == 12 && display.end == 14) |
| 610 | #expect(display.speaker == 3 && display.confidence == 0.88) |
| 611 | } |
| 612 | try context.save() |
| 613 | let expected = note.transcriptUtterances |
| 614 | let otherContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) |
| 615 | otherContext.persistentStoreCoordinator = context.persistentStoreCoordinator |
| 616 | let other = try #require(otherContext.existingObject(with: note.objectID) as? Note) |
| 617 | other.transcription = "Unsaved text from another context." |
| 618 | other.setTranscriptUtterances([TranscriptUtterance(text: other.transcription!, start: 42, end: 44)]) |
| 619 | #expect(other.transcriptUtterances.first?.start == 42) |
| 620 | #expect(note.transcriptUtterances == expected) |
| 621 | note.transcription = "Fresh manual fallback." |
| 622 | note.setTranscriptUtterances([]) |
| 623 | #expect(note.transcriptUtterances.map(\.text) == ["Fresh manual fallback."]) |
| 624 | note.transcription = "Updated fallback after unreadable metadata." |
| 625 | note.setValue("{", forKey: "transcriptUtterancesJSON") |
| 626 | #expect(note.transcriptUtterances.map(\.text) == [note.transcription!]) |
| 627 | context.rollback() |
| 628 | #expect(note.transcriptUtterances == expected) |
| 629 | } |
| 630 | @Test func appleIntelligenceHardwareEligibilityDoesNotRejectPendingSetup() { |
| 631 | #expect(JotleyAppleIntelligenceEligibility.supports(availability: .available)) |
| 632 | #expect(JotleyAppleIntelligenceEligibility.supports(availability: .unavailable(.appleIntelligenceNotEnabled))) |
| 633 | #expect(JotleyAppleIntelligenceEligibility.supports(availability: .unavailable(.modelNotReady))) |
| 634 | #expect(!JotleyAppleIntelligenceEligibility.supports(availability: .unavailable(.deviceNotEligible))) |
| 635 | } |
| 636 | @Test func microphoneStereoMixPreservesSamples() throws { |
| 637 | let format = try #require(AVAudioFormat(standardFormatWithSampleRate: 48000, channels: 2)) |
| 638 | let buffer = try #require(AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 3)) |
| 639 | buffer.frameLength = 3 |
| 640 | let channels = try #require(buffer.floatChannelData) |
| 641 | for (index, value) in [Float(0.2), 0.4, -0.6].enumerated() { channels[0][index] = value } |
| 642 | for (index, value) in [Float(0.6), -0.4, -0.2].enumerated() { channels[1][index] = value } |
| 643 | let data = try LiveTranscriptionManager.monoPCM(buffer) |
| 644 | #expect(try LiveTranscriptionManager.monoPCM(AVReadOnlyAudioPCMBuffer(copying: buffer)) == data) |
| 645 | let actual = data.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) } |
| 646 | #expect(actual.count == 3) |
| 647 | #expect(abs(actual[0] - 0.4) < 0.00001) |
| 648 | #expect(abs(actual[1]) < 0.00001) |
| 649 | #expect(abs(actual[2] + 0.4) < 0.00001) |
| 650 | } |
| 651 | |
| 652 | |
| 653 | } |
| 654 | |
| 655 | extension Jotley_iOSTests { |
| 656 | |
| 657 | |
| 658 | @MainActor @Test func localExportsKeepOriginalFormatsAndIsolateTemporaryFiles() throws { |
| 659 | let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| 660 | let store = try SharedPersistenceController(root: root) |
| 661 | defer { |
| 662 | for item in store.container.persistentStoreCoordinator.persistentStores { try? store.container.persistentStoreCoordinator.remove(item) } |
| 663 | try? FileManager.default.removeItem(at: root) |
| 664 | } |
| 665 | let recorder = LiveTranscriptionManager(store: store) |
| 666 | let text = "Café 日本語 🎙️\nFinal words retained." |
| 667 | let note = try recorder.createNote(text: text, title: "Meeting/with:team") |
| 668 | note.summary = "Decision: local processing."; try store.save() |
| 669 | let full = LocalNoteExport.content(note: note, format: .markdown) |
| 670 | #expect(full.contains("## Summary\n\nDecision: local processing.") && full.contains("## Transcript\n\n" + text)) |
| 671 | #expect(LocalNoteExport.content(note: note, format: .plainText).contains("TRANSCRIPT\n----------\n" + text)) |
| 672 | #expect(!LocalNoteExport.content(note: note, format: .summary).contains(text)) |
| 673 | #expect(!LocalNoteExport.content(note: note, format: .transcript).contains("Decision: local processing.")) |
| 674 | let first = try LocalNoteExport.file(note: note, format: .markdown, temporaryRoot: root) |
| 675 | let second = try LocalNoteExport.file(note: note, format: .markdown, temporaryRoot: root) |
| 676 | #expect(first != second && first.lastPathComponent == "Meeting-with-team.md") |
| 677 | #expect(try String(contentsOf: first, encoding: .utf8) == full) |
| 678 | note.title = String(repeating: "👩🏽💻", count: 100); try store.save() |
| 679 | let longName = try LocalNoteExport.file(note: note, format: .transcript, temporaryRoot: root) |
| 680 | #expect(longName.lastPathComponent.utf8.count < 255) |
| 681 | let blocker = root.appendingPathComponent("not-a-folder") |
| 682 | try Data([1]).write(to: blocker) |
| 683 | #expect(throws: (any Error).self) { try LocalNoteExport.file(note: note, format: .markdown, temporaryRoot: blocker) } |
| 684 | #expect(note.transcription == text && note.summary == "Decision: local processing.") |
| 685 | #expect(try String(contentsOf: first, encoding: .utf8) == full) |
| 686 | let retained = root.appendingPathComponent("Saved Export.txt") |
| 687 | try full.write(to: retained, atomically: true, encoding: .utf8) |
| 688 | let unrelated = root.appendingPathComponent("JotleyExport-keep-this-folder") |
| 689 | try FileManager.default.createDirectory(at: unrelated, withIntermediateDirectories: true) |
| 690 | let link = root.appendingPathComponent("JotleyExport-\(UUID())") |
| 691 | try FileManager.default.createSymbolicLink(at: link, withDestinationURL: unrelated) |
| 692 | let ordinaryFile = root.appendingPathComponent("JotleyExport-\(UUID())") |
| 693 | try Data([1]).write(to: ordinaryFile) |
| 694 | try LocalNoteExport.cleanupStaleExports(temporaryRoot: root) |
| 695 | for file in [first, second, longName] { |
| 696 | #expect(!FileManager.default.fileExists(atPath: file.deletingLastPathComponent().path)) |
| 697 | } |
| 698 | #expect(try String(contentsOf: retained, encoding: .utf8) == full) |
| 699 | #expect(FileManager.default.fileExists(atPath: unrelated.path)) |
| 700 | #expect(try link.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true) |
| 701 | #expect(try Data(contentsOf: ordinaryFile) == Data([1])) |
| 702 | #expect(try store.notes().count == 1 && note.transcription == text) |
| 703 | try LocalNoteExport.cleanupStaleExports(temporaryRoot: root) // Relaunch cleanup is idempotent. |
| 704 | } |
| 705 | |
| 706 | |
| 707 | } |
| 708 | |
| 709 | |
| 710 | extension Jotley_iOSTests { |
| 711 | |
| 712 | } |
| 713 | |
| 714 | /// Actual model checks: never substitute fixtures for recognized/generated output. |
| 715 | /// These skip explicitly when Apple does not expose the required model in Simulator. |
| 716 | final class SimulatorModelAcceptanceTests: XCTestCase { |
| 717 | |
| 718 | @MainActor func testLiveSpeechRecognizesAudioSourceAndCheckpointsWithoutSavingAudio() async throws { |
| 719 | let locale = Locale(identifier: "en-US") |
| 720 | let ready = await LocalSpeech.readiness(locale: locale) |
| 721 | guard ready.status == .installed, let config = ready.configuration, |
| 722 | !(await config.module.availableCompatibleAudioFormats).isEmpty else { |
| 723 | throw XCTSkip("Apple exposes no usable on-device speech model here. Actual live recognition is unverified; checkpoint fixtures do not substitute for inference.") |
| 724 | } |
| 725 | let fixture = URL(fileURLWithPath: "/tmp/jotley-local-live-speech.aiff") |
| 726 | guard FileManager.default.fileExists(atPath: fixture.path) else { throw XCTSkip("Spoken-audio source fixture is unavailable") } |
| 727 | let store = try SharedPersistenceController(inMemory: true) |
| 728 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 729 | let note = try XCTUnwrap(store.create(title: "Live acceptance") as? Note) |
| 730 | let checkpoint = MobileTranscriptCheckpoint(baseText: "", baseUtterances: [], offset: 0) |
| 731 | let session = try await LiveSpeechSession.start(locale: locale) { value in |
| 732 | await MainActor.run { _ = try? checkpoint.save(value, to: note, in: store) } |
| 733 | } |
| 734 | let source = try AVAudioFile(forReading: fixture, commonFormat: .pcmFormatFloat32, interleaved: false) |
| 735 | let buffer = try XCTUnwrap(AVAudioPCMBuffer(pcmFormat: source.processingFormat, frameCapacity: 2400)) |
| 736 | while source.framePosition < source.length { |
| 737 | try source.read(into: buffer) |
| 738 | session.append(try LiveTranscriptionManager.monoPCM(buffer), sampleRate: source.processingFormat.sampleRate) |
| 739 | try await Task.sleep(for: .milliseconds(150)) |
| 740 | } |
| 741 | let result = try await session.finish() |
| 742 | _ = try checkpoint.save(result, to: note, in: store) |
| 743 | XCTAssertTrue(result.text.lowercased().contains("purple bicycle"), result.text) |
| 744 | XCTAssertTrue(note.transcription?.lowercased().contains("audio source") == true) |
| 745 | XCTAssertNil(note.sourceURL) |
| 746 | XCTAssertFalse(FileManager.default.fileExists(atPath: store.root.appendingPathComponent("Recordings").path)) |
| 747 | } |
| 748 | @MainActor func testSummaryAndAutomaticTitleUsingSimulatorAppleModel() async throws { |
| 749 | #if targetEnvironment(simulator) |
| 750 | let previousLanguage = UserDefaults.standard.string(forKey: "transcriptionLanguage") |
| 751 | UserDefaults.standard.set("en-US", forKey: "transcriptionLanguage") |
| 752 | defer { |
| 753 | if let previousLanguage { UserDefaults.standard.set(previousLanguage, forKey: "transcriptionLanguage") } |
| 754 | else { UserDefaults.standard.removeObject(forKey: "transcriptionLanguage") } |
| 755 | } |
| 756 | let locale = Locale(identifier: "en-US") |
| 757 | if let reason = LocalSummary.readiness(locale: locale) { |
| 758 | let diagnostics = XCTAttachment(string: reason) |
| 759 | diagnostics.name = "Actual simulator summary readiness"; diagnostics.lifetime = .keepAlways; add(diagnostics) |
| 760 | print("SIMULATOR_SUMMARY: \(reason)") |
| 761 | throw XCTSkip("Apple summary model unavailable in Simulator: \(reason)") |
| 762 | } |
| 763 | let store = try SharedPersistenceController(inMemory: true) |
| 764 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 765 | let recorder = LiveTranscriptionManager(store: store) |
| 766 | let note = try recorder.createNote(text: "We agreed to keep recordings offline. Maya will test the microphone and Sam will verify the summary templates.", title: "Untitled") |
| 767 | recorder.summarize(note, template: .auto) |
| 768 | for _ in 0..<1200 { |
| 769 | if recorder.summaryNoteID == nil { break } |
| 770 | try await Task.sleep(for: .milliseconds(50)) |
| 771 | } |
| 772 | if recorder.summaryNoteID != nil { recorder.cancelProcessing(); XCTFail("Summary did not finish within 60 seconds") } |
| 773 | XCTAssertNil(recorder.errorMessage) |
| 774 | XCTAssertTrue(Note.isMeaningfulSummaryText(note.summary)) |
| 775 | XCTAssertNotEqual(note.title, "Untitled") |
| 776 | XCTAssertEqual(note.summaryType, "default-summary") |
| 777 | XCTAssertEqual(note.tagNames.count, 3) |
| 778 | #else |
| 779 | throw XCTSkip("This acceptance check targets Simulator") |
| 780 | #endif |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | #if DEBUG && targetEnvironment(simulator) |
| 785 | private actor TranscriptionTestGate { |
| 786 | private var entered = false |
| 787 | private var releaseContinuation: CheckedContinuation<Void, Never>? |
| 788 | private var arrivalContinuations: [CheckedContinuation<Void, Never>] = [] |
| 789 | func hold() async { |
| 790 | entered = true |
| 791 | arrivalContinuations.forEach { $0.resume() }; arrivalContinuations.removeAll() |
| 792 | await withCheckedContinuation { releaseContinuation = $0 } |
| 793 | } |
| 794 | func waitUntilHeld() async { |
| 795 | if entered { return } |
| 796 | await withCheckedContinuation { arrivalContinuations.append($0) } |
| 797 | } |
| 798 | func release() { releaseContinuation?.resume(); releaseContinuation = nil } |
| 799 | } |
| 800 | |
| 801 | @MainActor private final class LifecycleTestSpeech: MobileSpeechSession { |
| 802 | var snapshot: (@Sendable (LocalTranscript) async -> Void)? |
| 803 | var final = LocalTranscript() |
| 804 | var finishGate: TranscriptionTestGate? |
| 805 | var finishError: Error? |
| 806 | var finishCount = 0 |
| 807 | var cancelCount = 0 |
| 808 | nonisolated func append(_ data: Data, sampleRate: Double) {} |
| 809 | @MainActor func finish() async throws -> LocalTranscript { |
| 810 | finishCount += 1 |
| 811 | if let finishGate { await finishGate.hold() } |
| 812 | if let finishError { throw finishError } |
| 813 | return final |
| 814 | } |
| 815 | @MainActor func cancel() async { cancelCount += 1 } |
| 816 | func publish(_ text: String, start: Double = 0, final: Bool = false) async { |
| 817 | var value = LocalTranscript() |
| 818 | value.accept(text: text, start: start, end: start + 1, final: final) |
| 819 | await snapshot?(value) |
| 820 | // Production intentionally coalesces live text/checkpoints to 4 Hz. |
| 821 | try? await Task.sleep(for: .milliseconds(275)) |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | extension Jotley_iOSTests { |
| 826 | @MainActor @Test func stoppingDrainsFinalWordsAndRejectsLateSnapshots() async throws { |
| 827 | let store = try SharedPersistenceController(inMemory: true) |
| 828 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 829 | let manager = LiveTranscriptionManager(store: store) |
| 830 | let note = try manager.createNote() |
| 831 | let session = LifecycleTestSpeech() |
| 832 | manager.simulatedSpeechStart = { snapshot in session.snapshot = snapshot; return session } |
| 833 | await manager.startTranscription(note: note) |
| 834 | await session.publish("Provisional words") |
| 835 | session.final.accept(text: "Final words before Stop.", start: 0, end: 1, final: true) |
| 836 | await manager.stopTranscription() |
| 837 | #expect(!manager.isTranscribing && !manager.busy && manager.activeNoteID == nil && manager.canStart) |
| 838 | #expect(session.finishCount == 1 && session.cancelCount == 0) |
| 839 | #expect(note.transcription == "Final words before Stop.") |
| 840 | #expect(manager.nextWaveformPeak() == 0) |
| 841 | await session.publish("Late words after Stop") |
| 842 | #expect(note.transcription == "Final words before Stop.") |
| 843 | #expect(manager.liveTranscript == "Final words before Stop.") |
| 844 | #expect(manager.liveUtterances.map(\.text) == ["Final words before Stop."]) |
| 845 | store.context.refresh(note, mergeChanges: false) |
| 846 | #expect(note.transcription == "Final words before Stop.") |
| 847 | } |
| 848 | |
| 849 | @MainActor @Test func simultaneousStopRequestsWaitForOneFinalization() async throws { |
| 850 | let store = try SharedPersistenceController(inMemory: true) |
| 851 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 852 | let manager = LiveTranscriptionManager(store: store) |
| 853 | let note = try manager.createNote() |
| 854 | let session = LifecycleTestSpeech(), gate = TranscriptionTestGate() |
| 855 | session.finishGate = gate |
| 856 | session.final.accept(text: "Saved once.", start: 0, end: 1, final: true) |
| 857 | manager.simulatedSpeechStart = { snapshot in session.snapshot = snapshot; return session } |
| 858 | await manager.startTranscription(note: note) |
| 859 | var firstFinished = false, secondRequested = false, secondFinished = false |
| 860 | let first = Task { await manager.stopTranscription(); firstFinished = true } |
| 861 | await gate.waitUntilHeld() |
| 862 | let second = Task { secondRequested = true; await manager.stopTranscription(); secondFinished = true } |
| 863 | while !secondRequested { await Task.yield() } |
| 864 | #expect(!firstFinished && !secondFinished && manager.busy && !manager.canStart) |
| 865 | await session.publish("Queued callback during finalization") |
| 866 | #expect(note.transcription != "Queued callback during finalization") |
| 867 | await gate.release() |
| 868 | await first.value; await second.value |
| 869 | #expect(firstFinished && secondFinished && session.finishCount == 1) |
| 870 | #expect(note.transcription == "Saved once." && manager.canStart) |
| 871 | } |
| 872 | |
| 873 | @MainActor @Test func closeDuringSpeechPreparationWaitsAndNeverOpensMicrophone() async throws { |
| 874 | let store = try SharedPersistenceController(inMemory: true) |
| 875 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 876 | let manager = LiveTranscriptionManager(store: store) |
| 877 | let note = try manager.createNote(text: "Existing words.") |
| 878 | let session = LifecycleTestSpeech(), gate = TranscriptionTestGate() |
| 879 | manager.simulatedSpeechStart = { snapshot in |
| 880 | session.snapshot = snapshot |
| 881 | await gate.hold() |
| 882 | return session |
| 883 | } |
| 884 | let start = Task { await manager.startTranscription(note: note) } |
| 885 | await gate.waitUntilHeld() |
| 886 | var closeRequested = false, closeFinished = false |
| 887 | let close = Task { closeRequested = true; await manager.stopTranscription(); closeFinished = true } |
| 888 | while !closeRequested { await Task.yield() } |
| 889 | #expect(!closeFinished && manager.busy) |
| 890 | await gate.release() |
| 891 | await start.value; await close.value |
| 892 | #expect(closeFinished && !manager.busy && !manager.isTranscribing && manager.activeNoteID == nil) |
| 893 | #expect(manager.transcriptionDuration == 0 && session.cancelCount == 1 && session.finishCount == 0) |
| 894 | #expect(note.transcription == "Existing words." && manager.errorMessage == nil && manager.canStart) |
| 895 | await session.publish("After cancelled preparation") |
| 896 | #expect(note.transcription == "Existing words.") |
| 897 | } |
| 898 | |
| 899 | @MainActor @Test func pausedStopAndContinuationFenceEarlierSession() async throws { |
| 900 | let store = try SharedPersistenceController(inMemory: true) |
| 901 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 902 | let manager = LiveTranscriptionManager(store: store) |
| 903 | let note = try manager.createNote() |
| 904 | let first = LifecycleTestSpeech(), second = LifecycleTestSpeech() |
| 905 | first.final.accept(text: "First session.", start: 0, end: 4, final: true) |
| 906 | second.final.accept(text: "Continued words.", start: 0, end: 3, final: true) |
| 907 | manager.simulatedSpeechStart = { snapshot in first.snapshot = snapshot; return first } |
| 908 | await manager.startTranscription(note: note) |
| 909 | manager.pauseTranscription() |
| 910 | #expect(manager.transcriptionState == .paused) |
| 911 | await manager.stopTranscription() |
| 912 | manager.simulatedSpeechStart = { snapshot in second.snapshot = snapshot; return second } |
| 913 | await manager.startTranscription(note: note) |
| 914 | await first.publish("Old session must not overwrite continuation") |
| 915 | #expect(note.transcription == "First session.") |
| 916 | await second.publish("New words", start: 0) |
| 917 | #expect(manager.liveUtterances.map(\.start) == [0, 4]) |
| 918 | manager.pauseTranscription(); await manager.resumeTranscription() |
| 919 | await manager.stopTranscription() |
| 920 | #expect(note.transcription == "First session. Continued words.") |
| 921 | // Saved cards use the existing Mac-style short-utterance coalescing. |
| 922 | #expect(note.transcriptUtterances.map(\.text).joined(separator: " ") == "First session. Continued words.") |
| 923 | #expect(note.transcriptUtterances.first?.start == 0) |
| 924 | #expect(note.transcriptUtterances.last?.end == 7) |
| 925 | await second.publish("Late continued words") |
| 926 | #expect(note.transcription == "First session. Continued words.") |
| 927 | } |
| 928 | |
| 929 | @MainActor @Test func closeDuringResumeWaitsForMicrophoneTransition() async throws { |
| 930 | let store = try SharedPersistenceController(inMemory: true) |
| 931 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 932 | let manager = LiveTranscriptionManager(store: store) |
| 933 | let note = try manager.createNote() |
| 934 | let session = LifecycleTestSpeech(), gate = TranscriptionTestGate() |
| 935 | session.final.accept(text: "Words before resuming.", start: 0, end: 1, final: true) |
| 936 | manager.simulatedSpeechStart = { snapshot in session.snapshot = snapshot; return session } |
| 937 | await manager.startTranscription(note: note) |
| 938 | manager.pauseTranscription() |
| 939 | manager.simulatedCaptureStart = { await gate.hold() } |
| 940 | let resume = Task { await manager.resumeTranscription() } |
| 941 | await gate.waitUntilHeld() |
| 942 | var closeRequested = false, closeFinished = false |
| 943 | let close = Task { closeRequested = true; await manager.stopTranscription(); closeFinished = true } |
| 944 | while !closeRequested { await Task.yield() } |
| 945 | #expect(manager.busy && !closeFinished) |
| 946 | await gate.release() |
| 947 | await resume.value; await close.value |
| 948 | #expect(closeFinished && manager.canStart && !manager.isTranscribing && manager.activeNoteID == nil) |
| 949 | #expect(note.transcription == "Words before resuming." && session.finishCount == 1) |
| 950 | await session.publish("Late words after interrupted Resume") |
| 951 | #expect(note.transcription == "Words before resuming.") |
| 952 | } |
| 953 | |
| 954 | @MainActor @Test func failedFinalizationStopsAndPreservesCheckpointedWords() async throws { |
| 955 | let store = try SharedPersistenceController(inMemory: true) |
| 956 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 957 | let manager = LiveTranscriptionManager(store: store) |
| 958 | let note = try manager.createNote() |
| 959 | let session = LifecycleTestSpeech() |
| 960 | session.finishError = LocalError.message("Test finalization failure") |
| 961 | manager.simulatedSpeechStart = { snapshot in session.snapshot = snapshot; return session } |
| 962 | await manager.startTranscription(note: note) |
| 963 | await session.publish("Keep the received words.") |
| 964 | await manager.stopTranscription() |
| 965 | #expect(!manager.isTranscribing && manager.activeNoteID == nil && manager.canStart) |
| 966 | #expect(manager.errorMessage?.contains("Test finalization failure") == true) |
| 967 | #expect(note.transcription == "Keep the received words.") |
| 968 | await session.publish("Must be rejected") |
| 969 | #expect(note.transcription == "Keep the received words.") |
| 970 | } |
| 971 | |
| 972 | @MainActor @Test func liveCardsKeepIdentityWhenTentativeWordsBecomeFinal() { |
| 973 | let checkpoint = MobileTranscriptCheckpoint(baseText: "", baseUtterances: [], offset: 12) |
| 974 | var value = LocalTranscript() |
| 975 | value.accept(text: "First card.", start: 0, end: 2, final: true) |
| 976 | value.accept(text: "Second…", start: 3, end: 4, final: false) |
| 977 | let initial = checkpoint.utterances(for: value) |
| 978 | value.accept(text: "Second card.", start: 3, end: 5, final: true) |
| 979 | let final = checkpoint.utterances(for: value) |
| 980 | #expect(initial.map(\.id) == final.map(\.id)) |
| 981 | #expect(final.map(\.start) == [12, 15] && final.map(\.end) == [14, 17]) |
| 982 | #expect(initial.last?.isInterim == true && final.last?.isInterim == false) |
| 983 | #expect(final.map(\.text) == ["First card.", "Second card."]) |
| 984 | } |
| 985 | |
| 986 | @MainActor @Test func newRecordingTimestampsSurviveSavingEditingAndReloading() throws { |
| 987 | let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| 988 | let store = try SharedPersistenceController(root: root) |
| 989 | defer { try? FileManager.default.removeItem(at: root) } |
| 990 | let note = try #require(store.create(title: "Timestamp verification") as? Note) |
| 991 | let checkpoint = MobileTranscriptCheckpoint(baseText: "", baseUtterances: [], offset: 0) |
| 992 | var result = LocalTranscript() |
| 993 | result.accept(text: "First spoken line.", start: 0.4, end: 2, final: true) |
| 994 | result.accept(text: "Second spoken line.", start: 7.3, end: 9, final: true) |
| 995 | try checkpoint.save(result, to: note, in: store) |
| 996 | |
| 997 | let id = note.objectID |
| 998 | store.context.reset() |
| 999 | let reloaded = try #require(store.context.existingObject(with: id) as? Note) |
| 1000 | #expect(reloaded.transcriptUtterances.map(\.timestampLabel) == ["00:00", "00:07"]) |
| 1001 | var draft = TranscriptEditDraft(text: reloaded.transcription ?? "", utterances: reloaded.storedTranscriptUtterances) |
| 1002 | #expect(draft.editorText == "[00:00]\nFirst spoken line.\n[00:07]\nSecond spoken line.") |
| 1003 | draft.editorText = draft.editorText.replacingOccurrences(of: "Second spoken", with: "Second edited") |
| 1004 | try reloaded.saveEditedTranscript(draft, in: store) |
| 1005 | |
| 1006 | store.context.reset() |
| 1007 | let edited = try #require(store.context.existingObject(with: id) as? Note) |
| 1008 | #expect(edited.transcriptUtterances.map(\.start) == [0.4, 7.3]) |
| 1009 | #expect(edited.transcriptUtterances.map(\.text) == ["First spoken line.", "Second edited line."]) |
| 1010 | } |
| 1011 | |
| 1012 | @Test func waveformRevealsQuietInputAndRetainsLoudInputHeadroom() { |
| 1013 | let samples: [Float] = [0, 0.005, 0.01, 0.03, 0.1, 0.3, 0.6, 0.9, 1] |
| 1014 | let levels = samples.map(LiveWaveformResponse.level) |
| 1015 | #expect(zip(levels, levels.dropFirst()).allSatisfy { $0 < $1 }) |
| 1016 | #expect(LiveWaveformResponse.level(for: 0.001) == LiveWaveformResponse.restingLevel) |
| 1017 | #expect(LiveWaveformResponse.level(for: 0.01) > 0.17) |
| 1018 | #expect(LiveWaveformResponse.level(for: 0.1) - LiveWaveformResponse.level(for: 0.01) > 0.3) |
| 1019 | #expect(LiveWaveformResponse.level(for: 0.9) < LiveWaveformResponse.level(for: 1)) |
| 1020 | #expect(LiveWaveformResponse.level(for: 1) < 0.93) |
| 1021 | #expect(LiveWaveformResponse.level(for: .nan) == 0.04) |
| 1022 | #expect(LiveWaveformResponse.level(for: -.infinity) == 0.04) |
| 1023 | #expect(LiveWaveformResponse.level(for: -1) == 0.04) |
| 1024 | } |
| 1025 | |
| 1026 | @Test func microphoneMeterPreservesPeaksWithinOneTapBuffer() { |
| 1027 | var samples = [Float](repeating: 0, count: 4_800) |
| 1028 | samples[799] = -0.02 |
| 1029 | samples[2_399] = 0.3 |
| 1030 | samples[4_799] = -0.06 |
| 1031 | let peaks = samples.withUnsafeBytes { |
| 1032 | LiveTranscriptionManager.waveformPeaks(in: Data($0), sampleRate: 48_000) |
| 1033 | } |
| 1034 | #expect(peaks == [0.02, 0.3, 0.06]) |
| 1035 | } |
| 1036 | } |
| 1037 | #endif |
| 1038 | |
| 1039 | |
| 1040 | private actor SummaryTestLog { |
| 1041 | var limits: [Int] = [] |
| 1042 | var snapshots: [String] = [] |
| 1043 | var progress: [LocalSummaryProgress] = [] |
| 1044 | var checkpoint: LocalSummaryCheckpoint? |
| 1045 | var sources: [String] = [] |
| 1046 | func save(_ value: LocalSummaryCheckpoint) { checkpoint = value } |
| 1047 | func visit(_ text: String) { sources.append(text) } |
| 1048 | func recordProgress(_ value: LocalSummaryProgress) { progress.append(value) } |
| 1049 | func record(limit: Int) { limits.append(limit) } |
| 1050 | func publish(_ text: String) { snapshots.append(text) } |
| 1051 | } |
| 1052 | |
| 1053 | extension Jotley_iOSTests { |
| 1054 | @Test func longSourceProducesOneFinalSummaryInsteadOfAppendingPartSummaries() async throws { |
| 1055 | let log = SummaryTestLog() |
| 1056 | let source = String(repeating: "Maya will review Friday. Sam owns testing. ", count: 180) |
| 1057 | let result = try await LocalSummary.run(source, template: .auto, infer: { _, _, limit, update in |
| 1058 | await log.record(limit: limit) |
| 1059 | if limit == 128 { |
| 1060 | await update("Internal extraction must stay hidden") |
| 1061 | return "Maya reviews Friday. Sam tests." |
| 1062 | } |
| 1063 | await update("One final summary") |
| 1064 | return "One final summary: Maya reviews Friday; Sam tests." |
| 1065 | }, progress: { await log.recordProgress($0) }, snapshot: { await log.publish($0) }) |
| 1066 | let progress = await log.progress |
| 1067 | #expect(progress.first == .preparing && progress.last == .writing) |
| 1068 | let count = LocalSummary.chunks(source).count |
| 1069 | #expect(progress.contains(.reading(completed: 0, total: count, pass: 0))) |
| 1070 | #expect(progress.contains(.reading(completed: count, total: count, pass: 0))) |
| 1071 | #expect(LocalSummaryProgress.reading(completed: 2, total: 4, pass: 0).fraction == 0.5) |
| 1072 | let limits = await log.limits, snapshots = await log.snapshots |
| 1073 | #expect(limits.filter { $0 == 512 }.count == 1) |
| 1074 | #expect(limits.filter { $0 == 128 }.count > 1) |
| 1075 | #expect(snapshots == ["One final summary"]) |
| 1076 | #expect(!result.contains("Part") && result == "One final summary: Maya reviews Friday; Sam tests.") |
| 1077 | } |
| 1078 | @Test func nonshrinkingSummaryReductionStopsWithoutRetryingForever() async { |
| 1079 | let log = SummaryTestLog() |
| 1080 | do { |
| 1081 | _ = try await LocalSummary.run(String(repeating: "Long source words. ", count: 250), template: .auto, |
| 1082 | infer: { text, _, limit, _ in await log.record(limit: limit); return text }, snapshot: { _ in }) |
| 1083 | Issue.record("A nonshrinking reduction must stop") |
| 1084 | } catch { #expect(error.localizedDescription.contains("Generation stopped")) } |
| 1085 | #expect(await log.limits.count == 2) |
| 1086 | } |
| 1087 | @Test func repetitionGuardKeepsOneCopyAndNormalRecurringWords() { |
| 1088 | let sentence = "Maya will review the final milestones with Sam on Friday." |
| 1089 | let repeated = "## Decisions\n\n" + Array(repeating: sentence, count: 3).joined(separator: "\n\n") |
| 1090 | #expect(LocalSummary.withoutRepeatingTail(repeated) == "## Decisions\n\n" + sentence) |
| 1091 | #expect(LocalSummary.withoutRepeatingTail("Maya reviews Friday. Sam reviews Monday. Maya and Sam review together.") == nil) |
| 1092 | #expect(LocalSummary.withoutRepeatingTail(String(repeating: "word ", count: 40)) == nil) |
| 1093 | } |
| 1094 | @Test func boundedSummaryStopsStalledWorkAndPropagatesCancellation() async { |
| 1095 | do { |
| 1096 | _ = try await LocalSummary.bounded({ try await Task.sleep(for: .seconds(60)); return "Must never finish" }, timeout: .milliseconds(25)) |
| 1097 | Issue.record("A stalled summary must time out") |
| 1098 | } catch { #expect(error.localizedDescription.contains("too long")) } |
| 1099 | let task = Task { try await LocalSummary.bounded { try await Task.sleep(for: .seconds(60)); return "Must not save" } } |
| 1100 | task.cancel() |
| 1101 | do { _ = try await task.value; Issue.record("Cancelled summaries must throw") } |
| 1102 | catch { #expect(error is CancellationError) } |
| 1103 | } |
| 1104 | @MainActor @Test func waveformAnimatesNativeLayersWithoutPublishingSwiftUIFrames() { |
| 1105 | let view = LiveWaveformLayerView(frame: CGRect(x: 0, y: 0, width: 400, height: 120)) |
| 1106 | view.update(levelProvider: { 0.3 }, listening: true, paused: false, color: .purple) |
| 1107 | view.layoutIfNeeded(); view.advanceWaveform() |
| 1108 | let layers = view.layer.sublayers ?? [] |
| 1109 | #expect(layers.count == 50) |
| 1110 | #expect(layers.allSatisfy { $0.animation(forKey: "liveLevel") is CABasicAnimation }) |
| 1111 | #expect((layers.last?.bounds.height ?? 0) > 6) |
| 1112 | view.update(levelProvider: { 0 }, listening: false, paused: false, color: .gray) |
| 1113 | view.layoutIfNeeded() |
| 1114 | #expect(layers.allSatisfy { $0.animationKeys()?.isEmpty != false }) |
| 1115 | #expect(layers.allSatisfy { abs($0.bounds.height - 4.8) < 0.01 }) |
| 1116 | } |
| 1117 | } |
| 1118 | |
| 1119 | #if DEBUG && targetEnvironment(simulator) |
| 1120 | extension Jotley_iOSTests { |
| 1121 | @MainActor @Test func summaryRunsOnceForRepeatedTapsAndReturnsToIdleAfterSaving() async throws { |
| 1122 | let store = try SharedPersistenceController(inMemory: true) |
| 1123 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 1124 | let manager = LiveTranscriptionManager(store: store) |
| 1125 | let note = try manager.createNote(text: "Maya reviews Friday.", title: "Meeting") |
| 1126 | var calls = 0 |
| 1127 | manager.simulatedSummaryGeneration = { update in |
| 1128 | calls += 1 |
| 1129 | await update("One summary in progress") |
| 1130 | try await Task.sleep(for: .milliseconds(50)) |
| 1131 | return "One completed summary." |
| 1132 | } |
| 1133 | manager.summarize(note, template: .auto) |
| 1134 | manager.summarize(note, template: .auto) |
| 1135 | try await Task.sleep(for: .milliseconds(200)) |
| 1136 | #expect(calls == 1 && note.summary == "One completed summary.") |
| 1137 | #expect(manager.summaryNoteID == nil && manager.summaryPreview.isEmpty && manager.canStart) |
| 1138 | try await Task.sleep(for: .milliseconds(100)) |
| 1139 | #expect(calls == 1) |
| 1140 | } |
| 1141 | } |
| 1142 | #endif |
| 1143 | |
| 1144 | extension SimulatorModelAcceptanceTests { |
| 1145 | @MainActor func testActualLongSourceSavesOneConsolidatedSummaryAndFinishes() async throws { |
| 1146 | let locale = Locale(identifier: "en-US") |
| 1147 | if let reason = LocalSummary.readiness(locale: locale) { throw XCTSkip(reason) } |
| 1148 | let paragraphs = (1...64).map { index in |
| 1149 | "Review \(index): Maya owns accessibility testing for the native notes app. Sam will check that transcripts remain on the device. The team agreed to review the completed checklist on Friday and keep all features free." |
| 1150 | }.joined(separator: "\n\n") |
| 1151 | XCTAssertGreaterThan(LocalSummary.chunks(paragraphs).count, 1) |
| 1152 | let log = SummaryTestLog() |
| 1153 | let began = Date() |
| 1154 | let result = try await LocalSummary.generate(paragraphs, template: .concise, locale: locale, |
| 1155 | progress: { await log.recordProgress($0) }, snapshot: { await log.publish($0) }) |
| 1156 | let progress = await log.progress, snapshots = await log.snapshots |
| 1157 | XCTAssertTrue(progress.contains(.preparing)) |
| 1158 | XCTAssertEqual(progress.last, .writing) |
| 1159 | XCTAssertFalse(snapshots.isEmpty) |
| 1160 | XCTAssertEqual(snapshots.last, result) |
| 1161 | XCTAssertTrue(result.localizedCaseInsensitiveContains("Maya")) |
| 1162 | let trace = XCTAttachment(string: "Model context: \(SystemLanguageModel.default.contextSize) tokens\nElapsed: \(Date().timeIntervalSince(began)) seconds\nProgress: \(progress)\nLive snapshots: \(snapshots.count)\nFirst live text: \(snapshots.first ?? "")") |
| 1163 | trace.name = "Actual Apple model preparation and live summary trace"; trace.lifetime = .keepAlways; add(trace) |
| 1164 | XCTAssertFalse(result.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) |
| 1165 | XCTAssertFalse(result.contains("## Part ")) |
| 1166 | XCTAssertNil(LocalSummary.withoutRepeatingTail(result)) |
| 1167 | let attachment = XCTAttachment(string: result) |
| 1168 | attachment.name = "Actual Apple model consolidated a long note once"; attachment.lifetime = .keepAlways; add(attachment) |
| 1169 | } |
| 1170 | } |
| 1171 | |
| 1172 | #if DEBUG && targetEnvironment(simulator) |
| 1173 | extension Jotley_iOSTests { |
| 1174 | @Test func tokenPackingKeepsEveryByteAndUsesLargerCompleteSections() async throws { |
| 1175 | let input = String(repeating: "Maya has café notes. 漢字🙂 ", count: 600) |
| 1176 | let parts = try await LocalSummary.packedSections(input, fits: { $0.utf8.count <= 9000 }) |
| 1177 | #expect(parts.joined() == input) |
| 1178 | #expect(parts.allSatisfy { $0.utf8.count <= 9000 }) |
| 1179 | #expect(parts.count < LocalSummary.chunks(input).count) |
| 1180 | let dense = try await LocalSummary.packedSections(input, fits: { $0.utf8.count <= 700 }) |
| 1181 | #expect(dense.joined() == input && dense.allSatisfy { $0.utf8.count <= 700 }) |
| 1182 | } |
| 1183 | @Test func summaryRecoverySkipsCompletedSectionsAndKeepsSourceOrder() async throws { |
| 1184 | let input = (1...8).map { "Section \($0). " + String(repeating: "Evidence words. ", count: 200) }.joined() |
| 1185 | let log = SummaryTestLog() |
| 1186 | let infer: LocalSummary.Inference = { source, _, limit, update in |
| 1187 | await log.visit(source) |
| 1188 | if limit == 128 { return "Reviewed: " + String(source.prefix(30)) } |
| 1189 | await update("Final summary") |
| 1190 | return "Final summary" |
| 1191 | } |
| 1192 | do { |
| 1193 | _ = try await LocalSummary.run(input, template: .auto, infer: infer, checkpoint: { state in |
| 1194 | await log.save(state) |
| 1195 | if state.facts.count == 2 { throw CancellationError() } |
| 1196 | }, snapshot: { _ in }) |
| 1197 | Issue.record("Expected a system interruption") |
| 1198 | } catch is CancellationError { } |
| 1199 | let saved = try #require(await log.checkpoint) |
| 1200 | #expect(saved.facts.count == 2) |
| 1201 | let encoded = try JSONEncoder().encode(saved) |
| 1202 | let restored = try JSONDecoder().decode(LocalSummaryCheckpoint.self, from: encoded) |
| 1203 | let result = try await LocalSummary.run(input, template: .auto, infer: infer, resuming: restored, |
| 1204 | checkpoint: { await log.save($0) }, snapshot: { _ in }) |
| 1205 | let visited = await log.sources |
| 1206 | #expect(Array(visited.dropLast()) == LocalSummary.chunks(input)) |
| 1207 | #expect(result == "Final summary") |
| 1208 | // Title recovery uses the finished result without running inference again. |
| 1209 | let completed = try #require(await log.checkpoint) |
| 1210 | _ = try await LocalSummary.run(input, template: .auto, infer: { _, _, _, _ in |
| 1211 | Issue.record("Completed summary must not be regenerated for title recovery"); return "Unexpected" |
| 1212 | }, resuming: completed, snapshot: { _ in }) |
| 1213 | } |
| 1214 | @MainActor @Test func leavingNoteDoesNotCancelSummaryAndExplicitCancelRemovesRecovery() async throws { |
| 1215 | let store = try SharedPersistenceController(inMemory: true) |
| 1216 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 1217 | let manager = LiveTranscriptionManager(store: store) |
| 1218 | let note = try manager.createNote(text: "Maya reviews Friday.", title: "Review") |
| 1219 | note.summary = "Original summary" |
| 1220 | manager.simulatedSummaryGeneration = { update in |
| 1221 | await update("New summary in progress") |
| 1222 | try await Task.sleep(for: .milliseconds(150)) |
| 1223 | return "Completed new summary" |
| 1224 | } |
| 1225 | manager.summarize(note, template: .auto) |
| 1226 | manager.saveEdits() // The exact app background lifecycle action. |
| 1227 | #expect(FileManager.default.fileExists(atPath: try #require(manager.summaryRecoveryURL).path)) |
| 1228 | try await Task.sleep(for: .milliseconds(300)) |
| 1229 | #expect(note.summary == "Completed new summary" && manager.summaryNoteID == nil) |
| 1230 | #expect(!FileManager.default.fileExists(atPath: try #require(manager.summaryRecoveryURL).path)) |
| 1231 | manager.simulatedSummaryGeneration = { _ in try await Task.sleep(for: .seconds(5)); return "Cancelled" } |
| 1232 | manager.summarize(note, template: .auto) |
| 1233 | manager.cancelProcessing() |
| 1234 | try await Task.sleep(for: .milliseconds(100)) |
| 1235 | #expect(note.summary == "Completed new summary" && manager.summaryNoteID == nil) |
| 1236 | #expect(!FileManager.default.fileExists(atPath: try #require(manager.summaryRecoveryURL).path)) |
| 1237 | } |
| 1238 | @MainActor @Test func pendingSummaryResumesFromDiskWithoutReplacingExistingNoteUntilComplete() async throws { |
| 1239 | let store = try SharedPersistenceController(inMemory: true) |
| 1240 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 1241 | let note = try #require(store.create(title: "Existing title", text: "Maya reviews Friday.") as? Note) |
| 1242 | note.summary = "Original summary" |
| 1243 | try store.save() |
| 1244 | var checkpoint = LocalSummaryCheckpoint(input: note.transcription ?? "", template: .auto) |
| 1245 | checkpoint.result = "Recovered completed summary" |
| 1246 | let job = MobileSummaryJob(noteID: try #require(note.id), templateKey: LocalSummaryTemplate.auto.key, |
| 1247 | localeIdentifier: "en-US", checkpoint: checkpoint) |
| 1248 | let url = store.root.appendingPathComponent("SummaryGeneration.json") |
| 1249 | try JSONEncoder().encode(job).write(to: url, options: .atomic) |
| 1250 | let manager = LiveTranscriptionManager(store: store) |
| 1251 | #expect(note.summary == "Original summary") |
| 1252 | manager.resumePendingSummary(applicationState: .active) |
| 1253 | try await Task.sleep(for: .milliseconds(250)) |
| 1254 | #expect(note.summary == "Recovered completed summary") |
| 1255 | #expect(note.title == "Existing title" && !FileManager.default.fileExists(atPath: url.path)) |
| 1256 | } |
| 1257 | } |
| 1258 | #endif |
| 1259 | |
| 1260 | #if DEBUG && targetEnvironment(simulator) |
| 1261 | extension Jotley_iOSTests { |
| 1262 | @MainActor @Test func systemExpirationKeepsRecoveryAndResumesInsteadOfCancellingTheJob() async throws { |
| 1263 | let store = try SharedPersistenceController(inMemory: true) |
| 1264 | defer { try? FileManager.default.removeItem(at: store.root) } |
| 1265 | let manager = LiveTranscriptionManager(store: store) |
| 1266 | let note = try manager.createNote(text: "Maya reviews Friday.", title: "Review") |
| 1267 | note.summary = "Original summary" |
| 1268 | var calls = 0 |
| 1269 | manager.simulatedSummaryGeneration = { update in |
| 1270 | calls += 1 |
| 1271 | if calls == 1 { try await Task.sleep(for: .seconds(5)) } |
| 1272 | try await Task.sleep(for: .milliseconds(100)) |
| 1273 | await update("Summary resumed") |
| 1274 | return "Summary resumed" |
| 1275 | } |
| 1276 | manager.summarize(note, template: .auto) |
| 1277 | try await Task.sleep(for: .milliseconds(20)) |
| 1278 | let url = try #require(manager.summaryRecoveryURL) |
| 1279 | // Simulator has no data-protection attribute. Verify the durable job, |
| 1280 | // not a filesystem-encryption property that requires physical hardware. |
| 1281 | let saved = try JSONDecoder().decode(MobileSummaryJob.self, from: Data(contentsOf: url)) |
| 1282 | #expect(saved.noteID == note.id && saved.checkpoint.input == note.transcription) |
| 1283 | manager.pauseSummaryForSystem() |
| 1284 | #expect(FileManager.default.fileExists(atPath: url.path) && note.summary == "Original summary") |
| 1285 | try await Task.sleep(for: .milliseconds(30)) |
| 1286 | manager.resumePendingSummary(applicationState: .active) |
| 1287 | try await Task.sleep(for: .milliseconds(250)) |
| 1288 | #expect(calls == 2 && note.summary == "Summary resumed" && manager.summaryNoteID == nil) |
| 1289 | #expect(!FileManager.default.fileExists(atPath: url.path)) |
| 1290 | } |
| 1291 | } |
| 1292 | #endif |