Branchwell

Jotley / app · jotley.ai / Tests / jotleyTests / ContinuationResumerTests.swift

1import XCTest
2import AVFoundation
3import CoreData
4import CloudKit
5import Speech
6import NaturalLanguage
7@testable import jotley
8
9final class LocalCoreTests: XCTestCase {
10 func testAutomaticOrganizationDefaultsOnWithIndependentOptOuts() throws {
11 let suite = "JotleyOrganizationTests.\(UUID())"
12 let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
13 defer { defaults.removePersistentDomain(forName: suite) }
14 XCTAssertTrue(LocalNoteOrganizationSettings.autoTags(in: defaults))
15 XCTAssertTrue(LocalNoteOrganizationSettings.autoFolders(in: defaults))
16 defaults.set(false, forKey: LocalNoteOrganizationSettings.autoTagsKey)
17 XCTAssertFalse(LocalNoteOrganizationSettings.autoTags(in: defaults))
18 XCTAssertTrue(LocalNoteOrganizationSettings.autoFolders(in: defaults))
19 defaults.set(true, forKey: LocalNoteOrganizationSettings.autoTagsKey)
20 defaults.set(false, forKey: LocalNoteOrganizationSettings.autoFoldersKey)
21 XCTAssertTrue(LocalNoteOrganizationSettings.autoTags(in: defaults))
22 XCTAssertFalse(LocalNoteOrganizationSettings.autoFolders(in: defaults))
23 }
24
25 @MainActor func testAutomaticFilingCreatesOnlyNeededFoldersAndPreservesAssignments() throws {
26 let store = try SharedPersistenceController(inMemory: true)
27 defer { try? FileManager.default.removeItem(at: store.root) }
28 let request = NSFetchRequest<NSManagedObject>(entityName: "Folder")
29 let first = try store.create(title: "Team planning")
30 let second = try store.create(title: "Project update")
31 let third = try store.create(title: "Miscellaneous")
32 try store.saveNoteChanges(first, values: ["summary": "Plan the next launch."], replacingTags: ["Planning"], autoFolder: .work)
33 let work = try XCTUnwrap(first.value(forKey: "folder") as? NSManagedObject)
34 XCTAssertEqual(work.text("name"), "Work")
35 XCTAssertEqual(first.text("summary"), "Plan the next launch.")
36 work.setValue("WORK", forKey: "name")
37 try store.saveNoteChanges(second, values: [:], replacingTags: nil, autoFolder: .work)
38 XCTAssertEqual((second.value(forKey: "folder") as? NSManagedObject)?.objectID, work.objectID)
39 try store.saveNoteChanges(second, values: [:], replacingTags: nil, autoFolder: .study)
40 XCTAssertEqual((second.value(forKey: "folder") as? NSManagedObject)?.objectID, work.objectID)
41 try store.saveNoteChanges(third, values: [:], replacingTags: nil, autoFolder: .unfiled)
42 XCTAssertNil(third.value(forKey: "folder"))
43 XCTAssertEqual(try store.context.count(for: request), 1)
44 }
45
46 func testCompletedTagsFillThreeDistinctSlotsEvenForShortNotes() {
47 let library = [LocalTagCandidate(name: "AI", usageCount: 40), LocalTagCandidate(name: "Design", usageCount: 20)]
48 let nine = "one two three four five six seven eight nine"
49 let ten = nine + " ten"
50 XCTAssertEqual(LocalNoteTags.completedNames(["AI"], transcript: nine, summary: "AI", library: library).count, 3)
51 let short = LocalNoteTags.completedNames(nil, transcript: ten, summary: "AI helps design.", library: library)
52 XCTAssertEqual(short.count, 3)
53 XCTAssertEqual(Array(short.prefix(2)), ["AI", "Design"])
54 let long = String(repeating: "AI helps design teams plan research projects and meetings every week. ", count: 40)
55 let modelTags = LocalNoteTags.completedNames(["Artificial Intelligence", "Design", "Research", "Planning", "Meetings", "Overflow"], transcript: long, summary: "", library: library)
56 XCTAssertEqual(modelTags, ["AI", "Design", "Research"])
57 for proposed: [String]? in [nil, [], ["###", " "]] {
58 let fallback = LocalNoteTags.completedNames(proposed, transcript: long, summary: "AI helps design.", library: library)
59 XCTAssertEqual(Array(fallback.prefix(2)), ["AI", "Design"])
60 XCTAssertEqual(Set(fallback.map(LocalNoteTags.key)).count, 3)
61 XCTAssertEqual(LocalNoteTags.completedNames(proposed, transcript: ten, summary: "", library: []).count, 3)
62 }
63 XCTAssertEqual(LocalNoteTags.completedNames(nil, transcript: "", summary: "", library: library), [])
64 }
65
66 @MainActor func testAutoFilingReusesNamedProjectsAndReservesMiscAtTheCap() throws {
67 let store = try SharedPersistenceController(inMemory: true)
68 defer { try? FileManager.default.removeItem(at: store.root) }
69 let first = try store.create(title: "Jotley review", text: "The Jotley project is ready.")
70 try store.saveNoteChanges(first, values: [:], replacingTags: nil, autoFolder: .work,
71 projectName: "Jotley", filingSource: "The Jotley project is ready.")
72 let project = try XCTUnwrap(first.value(forKey: "folder") as? NSManagedObject)
73 XCTAssertEqual(project.text("name"), "Jotley")
74 let second = try store.create(title: "Second review", text: "Testing the JOTLEY release.")
75 try store.saveNoteChanges(second, values: [:], replacingTags: nil, autoFolder: .work,
76 filingSource: "Testing the JOTLEY release.")
77 XCTAssertEqual((second.value(forKey: "folder") as? NSManagedObject)?.objectID, project.objectID)
78
79 for index in 1...8 {
80 let folder = NSEntityDescription.insertNewObject(forEntityName: "Folder", into: store.context)
81 folder.setValue(UUID(), forKey: "id")
82 folder.setValue("Manual \(index)", forKey: "name")
83 }
84 try store.save()
85 let third = try store.create(title: "Another project", text: "OpenTalon project kickoff.")
86 try store.saveNoteChanges(third, values: [:], replacingTags: nil, autoFolder: .work,
87 projectName: "OpenTalon", filingSource: "OpenTalon project kickoff.")
88 XCTAssertEqual((third.value(forKey: "folder") as? NSManagedObject)?.text("name"), "Misc")
89 let fourth = try store.create(title: "Course", text: "Lecture notes")
90 try store.saveNoteChanges(fourth, values: [:], replacingTags: nil, autoFolder: .study,
91 projectName: "Invented project", filingSource: "Lecture notes")
92 XCTAssertEqual((fourth.value(forKey: "folder") as? NSManagedObject)?.objectID,
93 (third.value(forKey: "folder") as? NSManagedObject)?.objectID)
94 XCTAssertEqual(try store.context.count(for: NSFetchRequest<NSManagedObject>(entityName: "Folder")), 10)
95 }
96
97 func testAutoTagsReuseBucketsAndLimitDistinctTopics() {
98 let library = [LocalTagCandidate(name: "AI", usageCount: 40), LocalTagCandidate(name: "Design", usageCount: 20), LocalTagCandidate(name: "Project-Planning", usageCount: 5)]
99 XCTAssertEqual(LocalNoteTags.resolvedNames(["artificial intelligence", "AI Tools", "ai", "Design", "Project Planning", "Research", "Work", "Extra"], library: library),
100 ["AI", "Design", "Project-Planning", "Research", "Work"])
101 XCTAssertEqual(LocalNoteTags.resolvedNames(["###", " ", "A sentence with far too many words for a topic", "design"], library: library), ["Design"])
102 let many = (0..<500).map { LocalTagCandidate(name: "Topic-\($0)", usageCount: 500 - $0) }
103 + [LocalTagCandidate(name: "Gardening", usageCount: 1)]
104 let candidates = LocalNoteTags.candidates(for: "Gardening plans", library: many, byteLimit: 400)
105 XCTAssertEqual(candidates.first, "Gardening")
106 XCTAssertLessThanOrEqual(candidates.reduce(0) { $0 + $1.utf8.count + 4 }, 400)
107 XCTAssertEqual(Set(candidates.map(LocalNoteTags.key)).count, candidates.count)
108 }
109
110 @MainActor func testSummaryTagsReplaceRelationshipsReuseEntitiesAndKeepOtherNotes() throws {
111 let store = try SharedPersistenceController(inMemory: true)
112 defer { try? FileManager.default.removeItem(at: store.root) }
113 let note = try store.create(title: "Summary", text: "AI and design")
114 let other = try store.create(title: "Other", text: "AI")
115 try store.saveNoteChanges(other, values: [:], replacingTags: ["AI", "Design"])
116 try store.saveNoteChanges(note, values: [:], replacingTags: ["Outdated", "Temporary"])
117 let before = (other.value(forKey: "tags") as? Set<NSManagedObject>) ?? []
118 let ai = try XCTUnwrap(before.first { $0.text("name") == "AI" })
119 try store.saveNoteChanges(note, values: ["summary": "Final summary"], replacingTags: ["Artificial Intelligence", "AI Tools", "Design", "Research", "Planning", "Meetings", "Overflow"])
120 let tags = (note.value(forKey: "tags") as? Set<NSManagedObject>) ?? []
121 XCTAssertEqual(tags.count, 5)
122 XCTAssertTrue(tags.contains(ai))
123 XCTAssertFalse(tags.contains { ["Outdated", "Temporary", "Overflow"].contains($0.text("name")) })
124 XCTAssertEqual((other.value(forKey: "tags") as? Set<NSManagedObject>), before)
125 XCTAssertEqual(try store.tagLibrary().filter { LocalNoteTags.key($0.name) == "ai" }.count, 1)
126 // A tagging failure supplies nil and preserves the old relationships.
127 try store.saveNoteChanges(note, values: ["summary": "Another summary"], replacingTags: nil)
128 XCTAssertEqual((note.value(forKey: "tags") as? Set<NSManagedObject>), tags)
129 try store.saveNoteChanges(note, values: [:], replacingTags: [])
130 XCTAssertEqual((note.value(forKey: "tags") as? NSSet)?.count, 0)
131 XCTAssertEqual((other.value(forKey: "tags") as? Set<NSManagedObject>), before)
132 }
133
134 @MainActor func testRejectedSummaryRestoresTagsWithoutLeavingNewEntities() throws {
135 let seed = try SharedPersistenceController(inMemory: true)
136 defer { try? FileManager.default.removeItem(at: seed.root) }
137 let model = try XCTUnwrap(seed.container.managedObjectModel.copy() as? NSManagedObjectModel)
138 model.entitiesByName["Note"]?.managedObjectClassName = NSStringFromClass(GeneratedContentRefusedNote.self)
139 let store = try SharedPersistenceController(inMemory: true, model: model)
140 defer { try? FileManager.default.removeItem(at: store.root) }
141 let note = try store.create(title: "Keep tags", text: "Original")
142 try store.saveNoteChanges(note, values: ["summary": "Original summary"], replacingTags: ["Existing"])
143 let other = try store.create(title: "Other")
144 other.setValue("Unrelated unsaved edit", forKey: "title")
145 XCTAssertThrowsError(try store.saveNoteChanges(note, values: ["summary": "Rejected output"], replacingTags: ["New tag"]))
146 XCTAssertEqual(note.text("summary"), "Original summary")
147 XCTAssertEqual((note.value(forKey: "tags") as? Set<NSManagedObject>)?.map { $0.text("name") }, ["Existing"])
148 XCTAssertEqual(try store.tagLibrary().map(\.name), ["Existing"])
149 XCTAssertEqual(other.text("title"), "Unrelated unsaved edit")
150 }
151
152 @MainActor func testInstalledTagModelReusesExistingBroadBuckets() async throws {
153 guard ProcessInfo.processInfo.environment["JOTLEY_RUN_TAG_TESTS"] == "1" else { throw XCTSkip("Installed Apple tag model test is opt-in") }
154 let locale = Locale(identifier: "en-US")
155 if let reason = LocalSummary.readiness(locale: locale) { throw XCTSkip(reason) }
156 let library = [LocalTagCandidate(name: "AI", usageCount: 50), LocalTagCandidate(name: "Design", usageCount: 20), LocalTagCandidate(name: "Gardening", usageCount: 5)]
157 let source = String(repeating: "The design team adopted artificial intelligence tools. Designers use generative AI to explore interface layouts and prototype product ideas. ", count: 3)
158 let tags = try await LocalNoteTags.generate(from: source, library: library, locale: locale)
159 XCTAssertTrue(tags.contains("AI"), tags.description)
160 XCTAssertTrue(tags.contains("Design"), tags.description)
161 XCTAssertFalse(tags.contains("Gardening"), tags.description)
162 XCTAssertLessThanOrEqual(tags.count, 3)
163 XCTAssertEqual(Set(tags.map(LocalNoteTags.key)).count, tags.count)
164 let store = try SharedPersistenceController(inMemory: true)
165 defer { try? FileManager.default.removeItem(at: store.root) }
166 let note = try store.create(title: "Ten old tags", text: source)
167 var oldTags: [NSManagedObject] = []
168 for index in 1...10 {
169 let tag = NSEntityDescription.insertNewObject(forEntityName: "Tag", into: store.context)
170 tag.setValue(UUID(), forKey: "id"); tag.setValue("Outdated-\(index)", forKey: "name")
171 oldTags.append(tag)
172 }
173 note.setValue(NSSet(array: oldTags), forKey: "tags")
174 try store.save()
175 XCTAssertEqual((note.value(forKey: "tags") as? NSSet)?.count, 10)
176 try store.saveNoteChanges(note, values: ["summary": source], replacingTags: tags)
177 store.context.refresh(note, mergeChanges: false)
178 let saved = (note.value(forKey: "tags") as? Set<NSManagedObject>) ?? []
179 XCTAssertEqual(Set(saved.map { $0.text("name") }), Set(tags))
180 XCTAssertFalse(saved.contains { $0.text("name").hasPrefix("Outdated-") })
181 let cancelled = Task { try await LocalNoteTags.generate(from: "AI", library: library, locale: locale) }
182 cancelled.cancel()
183 do { _ = try await cancelled.value; XCTFail("Cancelled tagging must not finish") } catch is CancellationError { }
184 print("Verified installed Apple model tags:", tags)
185 }
186
187 @MainActor func testChatHistoryRoundTrip() throws {
188 let store = try SharedPersistenceController(inMemory: true)
189 defer { try? FileManager.default.removeItem(at: store.root) }
190 let note = try store.create(title: "Chat", text: "Mina ships Friday")
191 let id = try XCTUnwrap(note.localNoteID)
192 let question = LocalChatMessage(role: "user", content: "Who ships?")
193 let answer = LocalChatMessage(role: "assistant", content: "Mina.")
194 try store.saveChatMessage(question, noteID: id)
195 try store.saveChatMessage(answer, noteID: id)
196 XCTAssertEqual(try store.chatMessages(noteID: id).map(\.id), [question.id, answer.id])
197 store.context.reset()
198 XCTAssertEqual(try store.chatMessages(noteID: id).map(\.id), [question.id, answer.id])
199 let saved = try XCTUnwrap(store.notes().first)
200 try store.deleteNote(saved)
201 XCTAssertEqual(try store.chatMessages(noteID: id).map(\.id), [question.id, answer.id])
202 try store.restoreNote(saved)
203 XCTAssertEqual(try store.notes().first?.localNoteID, id)
204 XCTAssertThrowsError(try store.permanentlyDeleteNotes([saved]))
205 try store.deleteNote(saved)
206 try store.permanentlyDeleteNotes([saved])
207 XCTAssertTrue(try store.chatMessages(noteID: id).isEmpty)
208 }
209
210 func testInstalledAskAIAnswersFromNoteAndCancelsWithoutCloudFallback() async throws {
211 guard ProcessInfo.processInfo.environment["JOTLEY_RUN_CHAT_TESTS"] == "1" else { throw XCTSkip("Installed Apple model test is opt-in") }
212 let locale = Locale(identifier: "en-US")
213 if let reason = LocalSummary.readiness(locale: locale) { throw XCTSkip(reason) }
214 let answer = try await LocalNoteChat.answer(source: "Mina is responsible for the launch. The team ships Friday.",
215 question: "Who is responsible for launch?", history: [], locale: locale) { _ in }
216 XCTAssertTrue(answer.localizedCaseInsensitiveContains("Mina"), answer)
217 let cancelled = Task {
218 try await LocalNoteChat.answer(source: "Mina ships Friday.", question: "When?", history: [], locale: locale) { _ in }
219 }
220 cancelled.cancel()
221 do { _ = try await cancelled.value; XCTFail("Cancelled answers must not finish") }
222 catch is CancellationError { }
223 }
224
225 func testOriginalAndMigrationTemplateKeysRemainUsableOffline() {
226 let originals = ["default-summary", "lecture", "meetings/general", "meetings/1-1",
227 "meetings/all-hands", "meetings/brainstorming", "meetings/networking",
228 "meetings/project-kickoff", "meetings/sprint-planning", "meetings/stand-up",
229 "meetings/weekly-project-status"]
230 for key in originals {
231 let template = LocalSummaryTemplate.resolve(key)
232 XCTAssertEqual(template.key, key, "An original note must retain its template")
233 XCTAssertFalse(template.prompt.isEmpty)
234 }
235 XCTAssertEqual(LocalSummaryTemplate.resolve(nil), .auto)
236 XCTAssertEqual(LocalSummaryTemplate.resolve("Meeting"), .meeting)
237 XCTAssertEqual(LocalSummaryTemplate.resolve("Concise"), .concise)
238 XCTAssertEqual(LocalSummaryTemplate.resolve("Study"), .study)
239 XCTAssertNotEqual(LocalSummaryTemplate.auto.prompt, LocalSummaryTemplate.concise.prompt)
240 XCTAssertFalse(LocalSummaryTemplate.allCases.contains { $0.key == "youtube" })
241 }
242
243 @MainActor func testActiveRecordingCannotBeDeletedOrReleasedByAnotherOwner() throws {
244 let root = try temporaryDirectory()
245 let store = try SharedPersistenceController(root: root)
246 defer {
247 for item in store.container.persistentStoreCoordinator.persistentStores { try? store.container.persistentStoreCoordinator.remove(item) }
248 try? FileManager.default.removeItem(at: root)
249 }
250 let note = NSEntityDescription.insertNewObject(forEntityName: "Note", into: store.context)
251 let id = UUID(); note.setValue(id, forKey: "id"); note.setValue("Active", forKey: "title")
252 let lease = try store.beginRecording(note)
253 XCTAssertFalse(note.objectID.isTemporaryID)
254 try store.save()
255 let other = try store.create(title: "Other")
256 XCTAssertThrowsError(try store.deleteNote(note))
257 XCTAssertThrowsError(try store.beginRecording(other))
258 store.endRecording(lease: UUID())
259 XCTAssertThrowsError(try store.deleteNote(note))
260 XCTAssertEqual(try store.notes().count, 2)
261 XCTAssertFalse(note.isDeleted)
262 // Unrelated notes remain deletable while the recording is protected.
263 try store.deleteNote(other)
264 store.endRecording(lease: lease)
265 let next = try store.create(title: "Next")
266 let nextLease = try store.beginRecording(next)
267 store.endRecording(lease: lease) // A stale owner cannot release the next session.
268 XCTAssertThrowsError(try store.deleteNote(next))
269 try store.deleteNote(note)
270 store.endRecording(lease: nextLease)
271 try store.deleteNote(next)
272 XCTAssertThrowsError(try store.beginRecording(next))
273 XCTAssertTrue(try store.notes().isEmpty)
274 }
275 func testCloudSyncDefaultsOnWithConfiguredIdentifierAndHonorsOptOut() throws {
276 let suite = "JotleySyncTests-\(UUID())"
277 let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
278 defer { defaults.removePersistentDomain(forName: suite) }
279 let info = [NoteSyncMode.containerInfoKey: "iCloud.org.example.JotleyTests"]
280 XCTAssertEqual(NoteSyncMode.application(info: info, defaults: defaults), .privateICloud(containerIdentifier: "iCloud.org.example.JotleyTests"))
281 XCTAssertNil(defaults.object(forKey: NoteSyncMode.preferenceKey))
282 defaults.set(true, forKey: NoteSyncMode.preferenceKey)
283 XCTAssertEqual(NoteSyncMode.application(info: [:], defaults: defaults), .localOnly)
284 XCTAssertEqual(NoteSyncMode.application(info: [NoteSyncMode.containerInfoKey: "https://example.com"], defaults: defaults), .localOnly)
285 XCTAssertEqual(NoteSyncMode.application(info: info, defaults: defaults), .privateICloud(containerIdentifier: "iCloud.org.example.JotleyTests"))
286 defaults.set(false, forKey: NoteSyncMode.preferenceKey)
287 XCTAssertEqual(NoteSyncMode.application(info: info, defaults: defaults), .localOnly)
288 let reopened = try XCTUnwrap(UserDefaults(suiteName: suite))
289 XCTAssertEqual(NoteSyncMode.application(info: info, defaults: reopened), .localOnly)
290 defaults.removeObject(forKey: NoteSyncMode.preferenceKey)
291 XCTAssertEqual(NoteSyncMode.application(info: info, defaults: defaults), .privateICloud(containerIdentifier: "iCloud.org.example.JotleyTests"))
292 }
293 @MainActor
294 func testCloudSyncConfigurationIsPrivateAndCannotMirrorPreviewStores() throws {
295 let mode = NoteSyncMode.privateICloud(containerIdentifier: "iCloud.org.example.JotleyTests")
296 let url = URL(fileURLWithPath: "/tmp/JotleySyncConfiguration.sqlite")
297 let description = try mode.storeDescription(at: url, inMemory: false)
298 XCTAssertEqual(description.cloudKitContainerOptions?.containerIdentifier, "iCloud.org.example.JotleyTests")
299 XCTAssertEqual(description.cloudKitContainerOptions?.databaseScope, .private)
300 XCTAssertEqual(description.options[NSPersistentHistoryTrackingKey] as? NSNumber, true)
301 XCTAssertEqual(description.options[NSPersistentStoreRemoteChangeNotificationPostOptionKey] as? NSNumber, true)
302 XCTAssertNil(try NoteSyncMode.localOnly.storeDescription(at: url, inMemory: false).cloudKitContainerOptions)
303 XCTAssertThrowsError(try NoteSyncMode.privateICloud(containerIdentifier: "invalid").storeDescription(at: url, inMemory: false))
304 let root = try temporaryDirectory()
305 defer { try? FileManager.default.removeItem(at: root) }
306 let preview = try SharedPersistenceController(root: root, inMemory: true, syncMode: mode)
307 XCTAssertTrue(preview.ready)
308 XCTAssertEqual(preview.syncMode, .localOnly)
309 XCTAssertFalse(preview.container is NSPersistentCloudKitContainer)
310 XCTAssertNil(preview.container.persistentStoreDescriptions.first?.cloudKitContainerOptions)
311 _ = try preview.create(title: "Preview only")
312 XCTAssertEqual(try preview.notes().count, 1)
313 }
314 func temporaryDirectory() throws -> URL {
315 let url = FileManager.default.temporaryDirectory.appendingPathComponent("JotleyTests-\(UUID())")
316 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
317 return url
318 }
319 func testTentativeAndFinalSpeechDoNotDuplicate() {
320 var transcript = LocalTranscript()
321 transcript.accept(text: "hello", start: 0, end: 1, final: false)
322 transcript.accept(text: "hello world", start: 0, end: 2, final: false)
323 XCTAssertEqual(transcript.displayText, "hello world")
324 XCTAssertEqual(transcript.text, "")
325 transcript.accept(text: "hello world", start: 0, end: 2, final: true)
326 transcript.accept(text: "hello world!", start: 0, end: 2, final: true)
327 XCTAssertEqual(transcript.text, "hello world!")
328 XCTAssertEqual(transcript.utterances.count, 1)
329 XCTAssertEqual(transcript.tentative, "")
330 }
331 func testLongUnicodeTranscriptChunksWithoutDroppingText() {
332 let text = String(repeating: "日本語の会議。 Action: call Sam.\n", count: 2000)
333 let chunks = LocalSummary.chunks(text)
334 XCTAssertEqual(chunks.joined(), text)
335 XCTAssertTrue(chunks.allSatisfy { $0.utf8.count <= 2400 })
336 XCTAssertGreaterThan(chunks.count, 2)
337 }
338 @MainActor
339 func testIsolatedStorePersistsAcrossRelaunchAndUsesVersionSixModel() throws {
340 let root = try temporaryDirectory()
341 defer { try? FileManager.default.removeItem(at: root) }
342 let first = try SharedPersistenceController(root: root)
343 XCTAssertTrue(first.ready)
344 XCTAssertTrue(first.container.managedObjectModel.entitiesByName["Folder"] != nil)
345 XCTAssertTrue(first.container.managedObjectModel.entitiesByName["Note"]?.attributesByName["transcriptUtterancesJSON"] != nil)
346 let note = try first.create(title: "Retain", text: "Existing content")
347 let id = note.localNoteID
348 for store in first.container.persistentStoreCoordinator.persistentStores {
349 try first.container.persistentStoreCoordinator.remove(store)
350 }
351 let second = try SharedPersistenceController(root: root)
352 let saved = try XCTUnwrap(second.notes().first)
353 XCTAssertEqual(saved.localNoteID, id)
354 XCTAssertEqual(saved.text("transcription"), "Existing content")
355 XCTAssertNil(second.container.persistentStoreDescriptions.first?.cloudKitContainerOptions)
356 XCTAssertTrue(second.container.persistentStoreDescriptions.first!.url!.path.hasPrefix(root.path))
357 }
358 @MainActor
359 func testCorruptStorePreservedOnLoadFailure() throws {
360 let root = try temporaryDirectory()
361 defer { try? FileManager.default.removeItem(at: root) }
362 let url = root.appendingPathComponent("JotleyNotes.sqlite")
363 let original = Data("not a database".utf8)
364 try original.write(to: url)
365 let store = try SharedPersistenceController(root: root)
366 XCTAssertFalse(store.ready)
367 XCTAssertNotNil(store.errorMessage)
368 XCTAssertThrowsError(try store.create(title: "Must fail"))
369 XCTAssertEqual(try Data(contentsOf: url), original)
370 }
371 @MainActor
372 func testBackgroundNoteChangesMergeAndDeletionCannotBeOverwritten() async throws {
373 let root = try temporaryDirectory()
374 defer { try? FileManager.default.removeItem(at: root) }
375 let store = try SharedPersistenceController(root: root)
376 let note = try store.create(title: "Existing", text: "Original transcript")
377 let objectID = note.objectID
378 let background = store.container.newBackgroundContext()
379 try await background.perform {
380 let imported = try background.existingObject(with: objectID)
381 imported.setValue("Imported transcript", forKey: "transcription")
382 imported.setValue("Imported summary", forKey: "summary")
383 let folder = NSEntityDescription.insertNewObject(forEntityName: "Folder", into: background)
384 folder.setValue(UUID(), forKey: "id"); folder.setValue("Imported folder", forKey: "name")
385 imported.setValue(folder, forKey: "folder")
386 try background.save()
387 }
388 for _ in 0..<200 {
389 if note.text("transcription") == "Imported transcript" { break }
390 try await Task.sleep(for: .milliseconds(10))
391 }
392 XCTAssertEqual(note.text("transcription"), "Imported transcript")
393 XCTAssertEqual(note.text("summary"), "Imported summary")
394 XCTAssertEqual((note.value(forKey: "folder") as? NSManagedObject)?.text("name"), "Imported folder")
395 // Preserve a local edit to a different field while another import arrives.
396 note.setValue("Pending local title", forKey: "title")
397 try await background.perform {
398 let imported = try background.existingObject(with: objectID)
399 imported.setValue("Second imported summary", forKey: "summary")
400 try background.save()
401 }
402 for _ in 0..<200 {
403 if note.text("summary") == "Second imported summary" { break }
404 try await Task.sleep(for: .milliseconds(10))
405 }
406 XCTAssertEqual(note.text("summary"), "Second imported summary")
407 XCTAssertEqual(note.text("title"), "Pending local title")
408 try store.save()
409 // A new import context reads the current row after the local title commit.
410 let deletionContext = store.container.newBackgroundContext()
411 try await deletionContext.perform {
412 deletionContext.delete(try deletionContext.existingObject(with: objectID)); try deletionContext.save()
413 }
414 for _ in 0..<200 {
415 if note.isDeleted || note.managedObjectContext == nil { break }
416 try await Task.sleep(for: .milliseconds(10))
417 }
418 XCTAssertTrue(note.isDeleted || note.managedObjectContext == nil)
419 XCTAssertThrowsError(try store.saveNoteChanges(note, values: ["transcription": "Late generated words"]))
420 XCTAssertTrue(try store.notes().isEmpty)
421 let reopened = try SharedPersistenceController(root: root)
422 XCTAssertTrue(try reopened.notes().isEmpty)
423 }
424}
425
426private actor LiveResultProbe {
427 var snapshotCount = 0
428 var text = ""
429 func accept(_ value: LocalTranscript) { snapshotCount += 1; text = value.displayText }
430 func count() -> Int { snapshotCount }
431}
432
433extension LocalCoreTests {
434 func testUnsupportedLanguageRemainsUnavailableWithoutModelInstallation() async {
435 do {
436 _ = try await LocalSpeech.configuration(locale: Locale(identifier: "zxx"))
437 XCTFail("A language with no linguistic content must not select a speech model")
438 } catch {
439 XCTAssertTrue(error.localizedDescription.contains("unavailable for the selected language"))
440 }
441 }
442
443 func testSpeechSelectionDistinguishesMissingAssetsFromUnsupportedLanguage() {
444 XCTAssertEqual(LocalSpeech.preferredIndex(statuses: [.supported, .installed]), 1)
445 XCTAssertEqual(LocalSpeech.preferredIndex(statuses: [.installed, .installed]), 0)
446 XCTAssertEqual(LocalSpeech.preferredIndex(statuses: [.supported, .supported]), 0)
447 XCTAssertEqual(LocalSpeech.preferredIndex(statuses: [.unsupported, .downloading]), 1)
448 XCTAssertEqual(LocalSpeech.preferredIndex(statuses: [.unsupported, .unsupported]), 0)
449 XCTAssertNil(LocalSpeech.preferredIndex(statuses: []))
450 let locale = Locale(identifier: "en_US")
451 XCTAssertEqual(LocalSpeech.exactLocale(Locale(identifier: "en-US"), in: [locale]), locale)
452 XCTAssertNil(LocalSpeech.exactLocale(Locale(identifier: "en-GB"), in: [locale]))
453 let module = DictationTranscriber(locale: locale, preset: .timeIndexedLongDictation)
454 let pending = LocalSpeech.Readiness(configuration: .init(module: module, engine: .dictation, locale: locale), status: .unsupported)
455 XCTAssertTrue(pending.needsSetup, "An unready supported-locale module must remain available for explicit setup")
456 XCTAssertTrue(pending.message.contains("Set Up On-Device Speech"))
457 XCTAssertThrowsError(try LocalSpeech.configuration(from: pending))
458 let installed = LocalSpeech.Readiness(configuration: .init(module: module, engine: .dictation, locale: locale), status: .installed)
459 let selected = try? LocalSpeech.configuration(from: installed)
460 XCTAssertEqual(selected?.engine, .dictation)
461 XCTAssertEqual(selected?.locale, locale)
462 XCTAssertTrue((selected?.module as? DictationTranscriber) === module,
463 "Recording must use the same installed configuration Settings selected")
464 }
465
466 func testExplicitSetupReusesInstalledAppleSpeech() async throws {
467 guard ProcessInfo.processInfo.environment["JOTLEY_RUN_MODEL_TESTS"] == "1" else {
468 throw XCTSkip("Opt in to exercise this host's installed speech assets.")
469 }
470 let locale = Locale(identifier: "en-US")
471 // Require the asset first so this integration test cannot initiate a download.
472 let before = try await LocalSpeech.configuration(locale: locale)
473 try await LocalSpeech.setUp(locale: locale) { _ in }
474 let after = try await LocalSpeech.configuration(locale: locale)
475 XCTAssertEqual(before.engine, after.engine)
476 XCTAssertEqual(before.locale, after.locale)
477 let ready = await LocalSpeech.readiness(locale: locale)
478 XCTAssertFalse(ready.needsSetup)
479 XCTAssertEqual(ready.configuration?.engine, after.engine)
480 XCTAssertEqual(ready.configuration?.locale, after.locale)
481 }
482
483
484
485 /// Opt-in integration check against this Mac's installed Apple speech assets.
486 /// Feed audio progressively and require visible speech before ending the stream.
487 func testInstalledModelTranscribesLiveInputBeforeStopAndKeepsFinalWords() async throws {
488 guard ProcessInfo.processInfo.environment["JOTLEY_RUN_MODEL_TESTS"] == "1" else {
489 throw XCTSkip("Enable explicitly with a locally generated speech fixture and installed Apple assets.")
490 }
491 let fixture = ProcessInfo.processInfo.environment["JOTLEY_MODEL_AUDIO_FIXTURE"] ?? "/tmp/jotley-local-live-speech.aiff"
492 let audio = try AVAudioFile(forReading: URL(fileURLWithPath: fixture), commonFormat: .pcmFormatFloat32, interleaved: false)
493 let probe = LiveResultProbe()
494 let session = try await LiveSpeechSession.start(locale: Locale(identifier: "en-US")) { await probe.accept($0) }
495 guard let buffer = AVAudioPCMBuffer(pcmFormat: audio.processingFormat, frameCapacity: 2048) else { return XCTFail("Audio buffer unavailable") }
496 while audio.framePosition < audio.length {
497 try audio.read(into: buffer)
498 guard let channels = buffer.floatChannelData else { return XCTFail("Audio samples unavailable") }
499 var samples = [Float](repeating: 0, count: Int(buffer.frameLength))
500 for i in samples.indices {
501 for channel in 0..<Int(buffer.format.channelCount) { samples[i] += channels[channel][i] / Float(buffer.format.channelCount) }
502 }
503 session.append(samples.withUnsafeBufferPointer { Data(buffer: $0) }, sampleRate: buffer.format.sampleRate)
504 try await Task.sleep(for: .milliseconds(35))
505 }
506 for _ in 0..<100 {
507 if await probe.count() > 0 { break }
508 try await Task.sleep(for: .milliseconds(100))
509 }
510 let countBeforeStop = await probe.count()
511 XCTAssertGreaterThan(countBeforeStop, 0, "Speech must arrive while the input stream is still open")
512 let result = try await session.finish()
513 XCTAssertTrue(result.text.lowercased().contains("audio source"), result.text)
514 XCTAssertTrue(result.text.lowercased().contains("purple bicycle"), "Stop must retain the final spoken words: \(result.text)")
515 let entries = result.utterances.filter { !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
516 XCTAssertGreaterThanOrEqual(entries.count, 2)
517 XCTAssertTrue(entries.allSatisfy { $0.start.isFinite && $0.start >= 0 && $0.end.isFinite && $0.end > $0.start })
518 XCTAssertGreaterThan(entries.last?.start ?? 0, entries.first?.start ?? 0)
519 let document = TranscriptUtterance.formattedTranscriptText(entries.map {
520 TranscriptUtterance(text: $0.text, start: $0.start, end: $0.end)
521 })
522 print("Speech timestamp proof:\n\(document)")
523 }
524}
525
526@objc(JotleyDeletionRefusedNote)
527private final class DeletionRefusedNote: NSManagedObject {
528 override func validateForDelete() throws {
529 throw NSError(domain: "JotleyDeletionTests", code: 1)
530 }
531}
532
533extension LocalCoreTests {
534 @MainActor func testDeletedNoteStaysDeletedAndUnrelatedEditsPersist() throws {
535 let root = try temporaryDirectory()
536 let store = try SharedPersistenceController(root: root)
537 defer {
538 for item in store.container.persistentStoreCoordinator.persistentStores { try? store.container.persistentStoreCoordinator.remove(item) }
539 try? FileManager.default.removeItem(at: root)
540 }
541 let target = try store.create(title: "Delete")
542 let keep = try store.create(title: "Keep", text: "Original")
543 keep.setValue("Edited content", forKey: "transcription")
544 try store.deleteNote(target)
545 XCTAssertEqual(try store.notes().count, 1)
546 XCTAssertEqual(keep.text("transcription"), "Edited content")
547 for item in store.container.persistentStoreCoordinator.persistentStores { try store.container.persistentStoreCoordinator.remove(item) }
548 let reopened = try SharedPersistenceController(root: root)
549 defer { for item in reopened.container.persistentStoreCoordinator.persistentStores { try? reopened.container.persistentStoreCoordinator.remove(item) } }
550 XCTAssertEqual(try reopened.notes().map { $0.text("title") }, ["Keep"])
551 }
552 @MainActor func testFailedDeletionCommitRestoresNote() throws {
553 let root = try temporaryDirectory()
554 let model = NSManagedObjectModel()
555 let entity = NSEntityDescription(); entity.name = "Note"
556 entity.managedObjectClassName = NSStringFromClass(DeletionRefusedNote.self)
557 entity.properties = [("id", NSAttributeType.UUIDAttributeType), ("timestamp", .dateAttributeType), ("trashedAt", .dateAttributeType),
558 ("title", .stringAttributeType), ("transcription", .stringAttributeType), ("noteType", .stringAttributeType)].map { name, type in
559 let attribute = NSAttributeDescription(); attribute.name = name; attribute.attributeType = type; attribute.isOptional = true; return attribute
560 }
561 model.entities = [entity]
562 let store = try SharedPersistenceController(root: root, model: model)
563 defer {
564 for item in store.container.persistentStoreCoordinator.persistentStores { try? store.container.persistentStoreCoordinator.remove(item) }
565 try? FileManager.default.removeItem(at: root)
566 }
567 let note = try store.create(title: "Keep after failure", text: "Final transcript")
568 try store.deleteNote(note)
569 XCTAssertThrowsError(try store.permanentlyDeleteNotes([note]))
570 XCTAssertTrue(SharedPersistenceController.trashedNotesPredicate.evaluate(with: note))
571 try store.restoreNote(note)
572 XCTAssertEqual(try store.notes().count, 1)
573 XCTAssertEqual(note.text("transcription"), "Final transcript")
574 }
575}
576
577
578@objc(JotleyGeneratedContentRefusedNote)
579private final class GeneratedContentRefusedNote: NSManagedObject {
580 override func validateForUpdate() throws {
581 if value(forKey: "summary") as? String == "Rejected output" {
582 throw NSError(domain: "JotleyGeneratedContentTests", code: 1)
583 }
584 try super.validateForUpdate()
585 }
586}
587
588@objc(JotleyCreationRefusedNote)
589private final class CreationRefusedNote: NSManagedObject {
590 override func validateForInsert() throws {
591 if value(forKey: "title") as? String == "Rejected note" {
592 throw NSError(domain: "JotleyCreationTests", code: 1)
593 }
594 try super.validateForInsert()
595 }
596}
597
598extension LocalCoreTests {
599 @MainActor func testFailedCreationRemovesOnlyInsertedNoteAndKeepsPendingEdits() throws {
600 let root = try temporaryDirectory()
601 let model = NSManagedObjectModel()
602 let entity = NSEntityDescription(); entity.name = "Note"
603 entity.managedObjectClassName = NSStringFromClass(CreationRefusedNote.self)
604 entity.properties = [("id", NSAttributeType.UUIDAttributeType), ("timestamp", .dateAttributeType), ("trashedAt", .dateAttributeType),
605 ("title", .stringAttributeType), ("transcription", .stringAttributeType), ("noteType", .stringAttributeType)].map { name, type in
606 let attribute = NSAttributeDescription(); attribute.name = name; attribute.attributeType = type; attribute.isOptional = true; return attribute
607 }
608 model.entities = [entity]
609 let store = try SharedPersistenceController(root: root, model: model)
610 defer {
611 for item in store.container.persistentStoreCoordinator.persistentStores { try? store.container.persistentStoreCoordinator.remove(item) }
612 try? FileManager.default.removeItem(at: root)
613 }
614 let keep = try store.create(title: "Existing", text: "Keep existing content")
615 keep.setValue("Pending local edit", forKey: "title")
616 XCTAssertThrowsError(try store.create(title: "Rejected note", text: "Should never persist", noteType: "voice"))
617 XCTAssertEqual(try store.notes().count, 1)
618 XCTAssertEqual(keep.text("title"), "Pending local edit")
619 XCTAssertEqual(keep.text("transcription"), "Keep existing content")
620 try store.save()
621 let imported = try store.create(title: "Accepted note", text: "Complete text", noteType: "voice")
622 XCTAssertEqual(imported.text("noteType"), "voice")
623 let reopened = try SharedPersistenceController(root: root, model: model)
624 let notes = try reopened.notes()
625 XCTAssertEqual(notes.count, 2)
626 XCTAssertTrue(notes.contains { $0.text("title") == "Pending local edit" })
627 XCTAssertTrue(notes.contains { $0.text("title") == "Accepted note" && $0.text("noteType") == "voice" })
628 XCTAssertFalse(notes.contains { $0.text("title") == "Rejected note" })
629 }
630}
631
632extension LocalCoreTests {
633 func testLargeCombiningSequenceStillRespectsSummaryByteLimit() {
634 let text = "Start " + "a" + String(repeating: "\u{0301}", count: 4000) + " 👩🏽‍💻 End"
635 let parts = LocalSummary.chunks(text)
636 XCTAssertEqual(parts.joined(), text)
637 XCTAssertTrue(parts.allSatisfy { $0.utf8.count <= 2400 })
638 XCTAssertGreaterThan(parts.count, 3)
639 }
640 @MainActor func testRejectedGeneratedContentRestoresAllFieldsAndPreservesOtherEdits() throws {
641 let root = try temporaryDirectory()
642 defer { try? FileManager.default.removeItem(at: root) }
643 let model = NSManagedObjectModel()
644 let entity = NSEntityDescription(); entity.name = "Note"
645 entity.managedObjectClassName = NSStringFromClass(GeneratedContentRefusedNote.self)
646 entity.properties = [("id", NSAttributeType.UUIDAttributeType), ("timestamp", .dateAttributeType), ("trashedAt", .dateAttributeType),
647 ("title", .stringAttributeType), ("transcription", .stringAttributeType), ("noteType", .stringAttributeType),
648 ("summary", .stringAttributeType), ("summaryType", .stringAttributeType)].map { name, type in
649 let attribute = NSAttributeDescription(); attribute.name = name; attribute.attributeType = type; attribute.isOptional = true; return attribute
650 }
651 model.entities = [entity]
652 let store = try SharedPersistenceController(root: root, model: model)
653 let note = try store.create(title: "Generated content", text: "Original transcript")
654 try store.saveNoteChanges(note, values: ["summary": "Original summary"])
655 let other = try store.create(title: "Other note")
656 other.setValue("Edited title", forKey: "title")
657 XCTAssertThrowsError(try store.saveNoteChanges(note, values: ["summary": "Rejected output", "summaryType": "Meeting", "transcription": "Replacement transcript"]))
658 XCTAssertEqual(note.text("summary"), "Original summary")
659 XCTAssertEqual(note.text("transcription"), "Original transcript")
660 XCTAssertNil(note.value(forKey: "summaryType"))
661 XCTAssertEqual(other.text("title"), "Edited title")
662 XCTAssertThrowsError(try store.saveNoteChanges(note, values: ["unknownField": "Must not mutate"]))
663 try store.save()
664 for persistent in store.container.persistentStoreCoordinator.persistentStores { try store.container.persistentStoreCoordinator.remove(persistent) }
665 let reopened = try SharedPersistenceController(root: root, model: model)
666 defer { for persistent in reopened.container.persistentStoreCoordinator.persistentStores { try? reopened.container.persistentStoreCoordinator.remove(persistent) } }
667 let notes = try reopened.notes()
668 XCTAssertTrue(notes.contains { $0.text("title") == "Edited title" })
669 let original = try XCTUnwrap(notes.first { $0.text("title") == "Generated content" })
670 XCTAssertEqual(original.text("summary"), "Original summary")
671 XCTAssertNil(original.value(forKey: "summaryType"))
672 }
673 func testCancelledSummaryStopsBeforeCheckingAssetsOrProducingSnapshots() async throws {
674 let probe = SummaryProbe()
675 let task = Task {
676 withUnsafeCurrentTask { $0?.cancel() }
677 return try await LocalSummary.generate("Retain this note", template: .concise, locale: Locale(identifier: "en-US")) { await probe.accept($0) }
678 }
679 do { _ = try await task.value; XCTFail("Cancelled summary should not start") }
680 catch is CancellationError { }
681 let count = await probe.count()
682 XCTAssertEqual(count, 0)
683 }
684 func testInstalledSummaryModelCancelsDuringStreamingAndCanGenerateAgain() async throws {
685 guard ProcessInfo.processInfo.environment["JOTLEY_RUN_MODEL_TESTS"] == "1" else { throw XCTSkip("Installed-model integration is opt-in") }
686 let locale = Locale(identifier: "en-US")
687 if let reason = LocalSummary.readiness(locale: locale) { throw XCTSkip(reason) }
688 let probe = SummaryProbe()
689 let source = String(repeating: "Meeting decision: Keep notes and microphone recordings offline. Sam will test crash recovery. Nina will review the interface. No dates were agreed.\n", count: 60)
690 let generation = Task {
691 try await LocalSummary.generate(source, template: .meeting, locale: locale) { await probe.accept($0) }
692 }
693 var began = false
694 for _ in 0..<300 {
695 if await probe.hasGeneratedBody() { began = true; break }
696 try await Task.sleep(for: .milliseconds(100))
697 }
698 generation.cancel()
699 do { _ = try await generation.value; XCTFail("Cancellation during streaming must not return generated content") }
700 catch is CancellationError { }
701 XCTAssertTrue(began, "Installed model must generate body text before cancellation")
702 let countAtCancellation = await probe.count()
703 try await Task.sleep(for: .milliseconds(200))
704 let countAfterCancellation = await probe.count()
705 XCTAssertEqual(countAfterCancellation, countAtCancellation)
706 let restarted = SummaryProbe()
707 let result = try await LocalSummary.generate("Meeting decision: Keep all notes offline. Sam owns crash recovery testing.", template: .auto, locale: locale) { await restarted.accept($0) }
708 XCTAssertFalse(result.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
709 let last = await restarted.last()
710 XCTAssertEqual(last, result, "Streaming publishes complete snapshots, not repeated deltas")
711 }
712}
713
714private actor SummaryProbe {
715 private var snapshots: [String] = []
716 func accept(_ text: String) { snapshots.append(text) }
717 func count() -> Int { snapshots.count }
718 func last() -> String? { snapshots.last }
719 func hasGeneratedBody() -> Bool {
720 guard let text = snapshots.last else { return false }
721 return text.replacingOccurrences(of: "## Part 1\n", with: "").trimmingCharacters(in: .whitespacesAndNewlines).count >= 32
722 }
723}
724
725
726
727extension LocalCoreTests {
728 func testMalformedLivePCMReportsFailure() async throws {
729 guard ProcessInfo.processInfo.environment["JOTLEY_RUN_MODEL_TESTS"] == "1" else { throw XCTSkip("Installed-model integration is opt-in") }
730 let session = try await LiveSpeechSession.start(locale: Locale(identifier: "en-US"), snapshot: { _ in })
731 session.append(Data([1, 2, 3]), sampleRate: 16000)
732 do { _ = try await session.finish(); XCTFail("Partial PCM sample must fail safely") }
733 catch { XCTAssertTrue(error.localizedDescription.contains("incomplete PCM sample"), error.localizedDescription) }
734 }
735
736 func testLegacyAudioCleanupRemovesOnlyAudioDirectories() throws {
737 let root = try temporaryDirectory()
738 defer { try? FileManager.default.removeItem(at: root) }
739 for name in ["Recordings/note/segment", "DeletedRecordings/note"] {
740 let directory = root.appendingPathComponent(name)
741 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
742 try Data([0, 1]).write(to: directory.appendingPathComponent("audio.float32"))
743 }
744 let unrelated = root.appendingPathComponent("JotleyNotes.sqlite")
745 try Data("keep".utf8).write(to: unrelated)
746 try LegacyAudioCleanup.remove(in: root)
747 XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("Recordings").path))
748 XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("DeletedRecordings").path))
749 XCTAssertEqual(try Data(contentsOf: unrelated), Data("keep".utf8))
750 try LegacyAudioCleanup.remove(in: root) // Repeated launches are harmless.
751 }
752}
753
754extension LocalCoreTests {
755 func testConciseOverviewMovesDetailsBelowTheParagraphWithoutLosingFacts() {
756 let input = """
757 ## Summary
758 The team planned the launch.
759 They agreed to test first.
760
761 - **AI in finance:** Brex tested agent policies.
762 The proxy audits traffic.
763
764 A separate paragraph explains the security work.
765
766 ## Key Points
767 - Keep the existing findings.
768
769 ## Action Items
770 - **Maya:** Review on Friday at 10:00.
771 """
772 let output = LocalSummary.conciseOverview(input)
773 XCTAssertTrue(output.hasPrefix("## Summary\nThe team planned the launch. They agreed to test first.\n\n## Key Points\n"), output)
774 XCTAssertEqual(output.components(separatedBy: "## Key Points").count, 2)
775 for fact in ["**AI in finance:** Brex tested agent policies.", "The proxy audits traffic.", "A separate paragraph explains the security work.", "Keep the existing findings.", "**Maya:** Review on Friday at 10:00."] {
776 XCTAssertTrue(output.contains(fact), output)
777 }
778 XCTAssertEqual(LocalSummary.conciseOverview(output), output, "Formatting must be stable when a checkpoint is resumed")
779 }
780
781 func testConciseOverviewBoundsLongAndUnspacedTextWithoutDiscardingDetails() {
782 for paragraph in [String(repeating: "This is a complete sentence with useful context. ", count: 80),
783 String(repeating: "a long run-on phrase without punctuation ", count: 80),
784 String(repeating: "非常に長い説明文", count: 400)] {
785 let output = LocalSummary.conciseOverview("## Summary\n" + paragraph + "\n\n## Decisions\n- Approved Friday.")
786 let overview = output.components(separatedBy: "\n\n")[0].components(separatedBy: "\n").dropFirst().joined()
787 XCTAssertLessThanOrEqual(overview.count, LocalSummary.overviewCharacterLimit)
788 XCTAssertLessThanOrEqual(overview.split(whereSeparator: \.isWhitespace).count, LocalSummary.overviewWordLimit)
789 XCTAssertTrue(output.contains("## Decisions\n- Approved Friday."))
790 XCTAssertTrue(output.contains("## Key Points"), "Overflow belongs outside Summary")
791 }
792 }
793
794 func testDevelopedOverviewParagraphIsNotReducedToASentenceOrThreeSentenceCap() {
795 let paragraph = "The team reviewed the launch plan and the feedback collected during the first round of testing. They agreed that the welcome screens need clearer labels so new users can start a transcription without hesitation. Accessibility work remains a priority, especially readable controls and sufficient contrast in dark appearance. Testing will cover both compact phone layouts and larger split views before the launch decision is made. Maya will lead the review on Friday, with Alex checking accessibility and Sam sharing the checklist beforehand. The group will use that review to resolve remaining questions and confirm whether the release is ready."
796 let input = "## Summary\n" + paragraph + "\n\n## Action Items\n- **Alex:** Finish accessibility checks."
797 XCTAssertGreaterThan(paragraph.split(whereSeparator: \.isWhitespace).count, 80)
798 XCTAssertEqual(LocalSummary.conciseOverview(input), input, "A substantive six-sentence paragraph should stay intact")
799 }
800
801 func testAllTemplatesBoundStreamedFinalAndRecoveredSummaryOverviews() async throws {
802 let raw = "## Summary\n" + String(repeating: "The project has a useful finding. ", count: 30) + "\n\n- **Sam:** Test by Thursday.\n\n## Decisions\n- Launch Friday."
803 let expected = LocalSummary.conciseOverview(raw)
804 for template in LocalSummaryTemplate.allCases {
805 let probe = SummaryProbe()
806 let output = try await LocalSummary.run("Complete transcript", template: template, infer: { _, _, _, update in
807 await update(raw)
808 return raw
809 }, partition: { [$0] }) { await probe.accept($0) }
810 XCTAssertEqual(output, expected, template.title)
811 let last = await probe.last()
812 XCTAssertEqual(last, expected, "Streamed and saved summaries must use the same overview policy")
813 var checkpoint = LocalSummaryCheckpoint(input: "Complete transcript", template: template)
814 checkpoint.result = raw
815 let recovered = try await LocalSummary.run("Complete transcript", template: template, infer: { _, _, _, _ in
816 XCTFail("A completed checkpoint must not rerun the model"); return ""
817 }, resuming: checkpoint) { _ in }
818 XCTAssertEqual(recovered, expected)
819 }
820 }
821}
822
823extension LocalCoreTests {
824 func testInstalledModelKeepsLongOverviewShortAndDetailsSeparate() async throws {
825 guard ProcessInfo.processInfo.environment["JOTLEY_RUN_MODEL_TESTS"] == "1" else { throw XCTSkip("Installed-model integration is opt-in") }
826 let locale = Locale(identifier: "en-US")
827 if let reason = LocalSummary.readiness(locale: locale) { throw XCTSkip(reason) }
828 let source = String(repeating: "Maya leads the launch review on Friday. Alex finishes accessibility checks by Thursday. Sam shares the launch checklist and gathers feedback. We agreed to test both compact and larger layouts. The main risk is unreadable controls in dark appearance. The project remains free and keeps notes private.\n", count: 12)
829 let output = try await LocalSummary.generate(source, template: .meeting, locale: locale) { _ in }
830 let blocks = output.components(separatedBy: "\n\n")
831 let overview = try XCTUnwrap(blocks.first)
832 XCTAssertTrue(overview.hasPrefix("## Summary\n"), output)
833 let paragraph = overview.components(separatedBy: "\n").dropFirst().joined()
834 XCTAssertLessThanOrEqual(paragraph.split(whereSeparator: \.isWhitespace).count, LocalSummary.overviewWordLimit)
835 XCTAssertLessThanOrEqual(paragraph.count, LocalSummary.overviewCharacterLimit)
836 let sentences = NLTokenizer(unit: .sentence)
837 sentences.string = paragraph
838 var sentenceCount = 0
839 sentences.enumerateTokens(in: paragraph.startIndex..<paragraph.endIndex) { _, _ in sentenceCount += 1; return true }
840 XCTAssertGreaterThanOrEqual(sentenceCount, 3, "An information-rich transcript needs a developed overview paragraph")
841 XCTAssertFalse(paragraph.hasPrefix("- "))
842 XCTAssertTrue(output.contains("\n## "), "Details must remain in sections below the short overview")
843 }
844}
845
846extension LocalCoreTests {
847 @MainActor func testFreshLibrarySeedsDefaultFoldersOnlyOnceInItsOwnModel() throws {
848 let root = try temporaryDirectory()
849 defer { try? FileManager.default.removeItem(at: root) }
850 let first = try SharedPersistenceController(root: root)
851 let request = NSFetchRequest<NSManagedObject>(entityName: "Folder")
852 let folders = try first.context.fetch(request)
853 XCTAssertEqual(Set(folders.map { $0.text("name") }), Set(["Personal", "Study", "Work"]))
854 XCTAssertEqual(Set(folders.compactMap { $0.value(forKey: "id") as? UUID }).count, 3)
855 for folder in folders { XCTAssertNotNil(folder.value(forKey: "createdAt")) }
856 let reopened = try SharedPersistenceController(root: root)
857 XCTAssertEqual(try reopened.context.count(for: request), 3)
858 for store in first.container.persistentStoreCoordinator.persistentStores { try first.container.persistentStoreCoordinator.remove(store) }
859 for store in reopened.container.persistentStoreCoordinator.persistentStores { try reopened.container.persistentStoreCoordinator.remove(store) }
860 }
861}