Branchwell

Jotley / app · jotley.ai / JotleyUITests-macOS / JotleyUITests_macOS.swift

1#if JOTLEY_MAC_ROUTING_HARNESS
2import Foundation
3import CoreData
4import Darwin
5import SwiftUI
6import AppKit
7import UserNotifications
8import AVFoundation
9import CoreText
10import Vision
11@testable import Jotley
12
13@MainActor private final class SummaryObserverState: ObservableObject {
14 @Published var summary = ""
15 @Published var error: String?
16 @Published var generating = false
17 @Published var inlineEdit = 0
18 @Published var rawMarkdown = false
19}
20
21private struct SummaryObserverView: View {
22 let note: Note
23 @ObservedObject var state: SummaryObserverState
24 @FocusState private var summaryFocused: Bool
25 @FocusState private var transcriptFocused: Bool
26 @State private var transcript = ""
27 @StateObject private var stream = StreamingSummaryViewModel()
28 var body: some View {
29 ScrollView {
30 DetailTabPanel(note: note, selectedTab: .constant(DetailTab.summary.rawValue),
31 isGeneratingSummary: $state.generating, summaryGenerationError: $state.error,
32 editableSummary: $state.summary, isSummaryEditorFocused: $summaryFocused,
33 summaryInlineEditRequestCounter: $state.inlineEdit, editableTranscript: $transcript,
34 isTranscriptEditorFocused: $transcriptFocused,
35 showRawMarkdown: $state.rawMarkdown, streamingSummaryViewModel: stream)
36 }
37 }
38}
39
40@MainActor private final class RecordingLayoutDelegate: NSObject, NSApplicationDelegate {
41 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
42}
43
44@objc(JotleyRoutingRefusedNote)
45private final class RoutingRefusedNote: Note {
46 static var rejectsNewNotes = true
47 override func validateForInsert() throws {
48 if Self.rejectsNewNotes, title == "Untitled Note" { throw LocalError.message("Injected note creation failure.") }
49 try super.validateForInsert()
50 }
51 override func validateForUpdate() throws {
52 // Refuse a mistaken recording update before hardware access. Its changed
53 // fields remain observable, so the baseline routing bug still fails.
54 if title == "Keep selected note", noteType != "local" || sourceURL != nil {
55 throw LocalError.message("The prior selected note cannot become the new recording.")
56 }
57 try super.validateForUpdate()
58 }
59}
60
61private struct MacTranscriptionPreviewRoot: View {
62 @ObservedObject var model: NotesListViewModel
63 @State private var speechCount = 30
64 var body: some View {
65 HStack(spacing: 0) {
66 VStack(alignment: .leading, spacing: 16) {
67 Text("Notes").font(.title.bold())
68 Button("Active transcript") { model.jumpToActiveRecordingNote() }
69 Button("Browse another note") {
70 if let other = try? model.viewContext.fetch(Note.fetchRequest()).first(where: { $0 != model.newNoteBeingRecorded }) {
71 model.toggleSelection(for: other)
72 }
73 }
74 Button("Append speech") {
75 speechCount += 1
76 var speech = LocalTranscript()
77 for index in 1...speechCount {
78 speech.accept(text: "Segment \(index). This synthetic passage checks that you can read earlier text without incoming words pulling your scroll position away.", start: Double(index * 15), end: Double(index * 15 + 8), final: true)
79 }
80 model.recorder.publishSimulatedLiveTranscript(speech)
81 }
82 Spacer()
83 }.padding(20).frame(width: 200)
84 Divider()
85 if let id = model.selectedNoteIDs.first,
86 let note = try? model.viewContext.existingObject(with: id) as? Note {
87 NoteDetailPlaceholderView(note: note, selectedTab: $model.selectedDetailTab, viewModel: model)
88 .id(note.objectID)
89 .environmentObject(model.persistenceController)
90 .environment(\.managedObjectContext, model.viewContext)
91 }
92 }.frame(width: 1000, height: 760)
93 .foregroundStyle(Color.themeTextPrimary).background(Color.themeBackground)
94 }
95}
96
97/// Compile this existing source against the built app with the harness flag to
98/// exercise its actual view model without adding a second implementation.
99@main private struct MacRoutingHarness {
100 @MainActor static func main() {
101 UserDefaults.standard.set(false, forKey: JotleySummaryNotifications.enabledKey)
102 if CommandLine.arguments.contains("--layout-preview") {
103 previewRecordingControls()
104 return
105 }
106 if CommandLine.arguments.contains("--detail-fixes-preview") {
107 previewCompletedTranscript()
108 return
109 }
110 if CommandLine.arguments.contains("--summary-progress-preview") {
111 previewSummaryProgress()
112 return
113 }
114 if let index = CommandLine.arguments.firstIndex(of: "--settings-about-snapshot"),
115 CommandLine.arguments.indices.contains(index + 1) {
116 snapshotSettingsAbout(to: CommandLine.arguments[index + 1])
117 return
118 }
119 Task { @MainActor in
120 await runChecks()
121 exit(0)
122 }
123 NSApplication.shared.run()
124 }
125 @MainActor private static func runChecks() async {
126 do {
127 if CommandLine.arguments.contains("--summary-footer-proof") {
128 try await verifySummaryFooter()
129 return
130 }
131 try await verifyLanguageChoices()
132 if CommandLine.arguments.contains("--languages-only") { return }
133 if CommandLine.arguments.contains("--summary-editor-only") {
134 let store = try SharedPersistenceController(inMemory: true)
135 let note = try store.create(title: "Summary editor fixture", text: "Sample note.") as! Note
136 try await verifySummaryPresentation(note: note)
137 } else if CommandLine.arguments.contains("--note-menu-only") {
138 guard let base = LocalAppModel.shared.store else { throw LocalError.message("Navigation store unavailable") }
139 let store = try SharedPersistenceController(inMemory: true, model: base.container.managedObjectModel)
140 let note = try store.create(title: "Navigation fixture", text: "Keep both editors available.") as! Note
141 note.summary = "## Summary\nA short overview.\n\n## Key Points\n- Keep both editors available."
142 let model = NotesListViewModel(viewContext: store.context, recorder: ProcessTapRecorder(), persistenceController: store)
143 try await verifyNoteMenus(note: note, store: store, model: model)
144 } else if CommandLine.arguments.contains("--compact-only") {
145 guard let store = LocalAppModel.shared.store else { throw LocalError.message("Preview store unavailable") }
146 try await verifyCompactTranscription(store: store)
147 } else if CommandLine.arguments.contains("--transcript-scroll-only") {
148 guard let store = LocalAppModel.shared.store else { throw LocalError.message("Preview store unavailable") }
149 try await verifyNewTranscriptScroll(store: store)
150 } else if CommandLine.arguments.contains("--transcript-editor-only") {
151 guard let base = LocalAppModel.shared.store else { throw LocalError.message("Preview store unavailable") }
152 let store = try SharedPersistenceController(inMemory: true, model: base.container.managedObjectModel)
153 let note = try store.create(title: "Inline edit fixture", text: "Original Mac words.") as! Note
154 let model = NotesListViewModel(viewContext: store.context, recorder: ProcessTapRecorder(), persistenceController: store)
155 try await verifyTranscriptEditing(note: note, store: store, viewModel: model)
156 } else if CommandLine.arguments.contains("--summary-scroll-only") {
157 guard let store = LocalAppModel.shared.store,
158 let note = try store.create(title: "Summary scroll fixture", text: "Maya reviews Friday.") as? Note else { throw LocalError.message("Summary scroll store unavailable") }
159 defer { try? store.deleteNote(note) }
160 let model = NotesListViewModel(viewContext: store.context, recorder: LocalAppModel.shared.recorder, persistenceController: store)
161 try await verifySummaryFollowAndCancel(note: note, store: store, viewModel: model)
162 } else { try await verifyRouting() }
163 }
164 catch { fputs("FAIL: \(error.localizedDescription)\n", stderr); exit(1) }
165 }
166 @MainActor private static func verifyLanguageChoices() async throws {
167 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) }
168 let choices = LocalSpeech.languages(speechLocales: locales, preferredLocale: Locale(identifier: "en-GB"),
169 supportsLocale: { $0.language.languageCode?.identifier != "fr" })
170 guard Set(choices.map(\.id)) == ["en-GB", "zh-CN", "zh-TW"],
171 LocalSpeech.selectedLanguage(locale: Locale(identifier: "en-AU"), in: choices)?.id == "en-GB",
172 LocalSpeech.selectedLanguage(locale: Locale(identifier: "zh-HK"), in: choices)?.id == "zh-TW",
173 LocalSpeech.selectedLanguage(locale: Locale(identifier: "ar-SA"), in: choices) == nil else {
174 throw LocalError.message("Language intersection, regional deduplication or legacy selection failed")
175 }
176 let actual = await LocalSpeech.languages()
177 guard !actual.isEmpty, actual.count <= 16,
178 Set(actual.compactMap { LocalSpeech.languageKey(for: Locale(identifier: $0.id)) }).count == actual.count,
179 actual.allSatisfy({ LocalSpeech.supportsIntelligence(locale: Locale(identifier: $0.id)) }) else {
180 throw LocalError.message("The runtime picker offered an unsupported or duplicate language")
181 }
182 for id in ["ar-SA", "ru-RU", "hi-IN", "pl-PL"] {
183 let ready = await LocalSpeech.readiness(locale: Locale(identifier: id))
184 guard ready.status == .unsupported, ready.configuration == nil, !ready.needsSetup else {
185 throw LocalError.message("A legacy unsupported language reached speech setup")
186 }
187 do { _ = try await LocalSpeech.configuration(locale: Locale(identifier: id)) }
188 catch { continue }
189 throw LocalError.message("A legacy unsupported language reached capture configuration")
190 }
191 print("PASS: speech/Intelligence intersection, regional deduplication, Chinese scripts, legacy language rejection; runtime choices (\(actual.count)): \(actual.map { "\($0.name) [\($0.id)]" }.joined(separator: ", ")).")
192 }
193 @MainActor private static func verifyRouting() async throws {
194 let watchdog = Task.detached {
195 try? await Task.sleep(for: .seconds(ProcessInfo.processInfo.environment["JOTLEY_RUN_TITLE_TESTS"] == "1" ? 90 : 20))
196 if !Task.isCancelled { fputs("Routing test timed out.\n", stderr); _exit(2) }
197 }
198 defer { watchdog.cancel() }
199 guard JotleyUpdates.allowsUpdate(recording: false, recorderBusy: false, processing: false),
200 !JotleyUpdates.allowsUpdate(recording: true, recorderBusy: false, processing: false),
201 !JotleyUpdates.allowsUpdate(recording: false, recorderBusy: true, processing: false),
202 !JotleyUpdates.allowsUpdate(recording: false, recorderBusy: false, processing: true),
203 !JotleyUpdates.shared.isEnabled else { throw LocalError.message("Sparkle must wait for idle capture and stay disabled in the isolated test app.") }
204 print("PASS: Sparkle waits for recording/finalization/processing and stays disabled in local test variants.")
205 var microphoneRequests = 0
206 for status: AVAuthorizationStatus in [.authorized, .denied, .restricted] {
207 let allowed = await ProcessTapRecorder.authorizeMicrophone(status: status) {
208 microphoneRequests += 1
209 return true
210 }
211 guard allowed == (status == .authorized), microphoneRequests == 0 else {
212 throw LocalError.message("Determined microphone permissions were requested again.")
213 }
214 }
215 for grant in [true, false] {
216 let allowed = await ProcessTapRecorder.authorizeMicrophone(status: .notDetermined) {
217 microphoneRequests += 1
218 return grant
219 }
220 guard allowed == grant else { throw LocalError.message("Microphone consent was ignored.") }
221 }
222 guard microphoneRequests == 2 else { throw LocalError.message("Microphone prompt count is incorrect.") }
223 print("PASS: microphone permissions consult macOS and request consent only for undetermined access.")
224 guard let modelURL = Bundle.main.url(forResource: "JotleyNotes", withExtension: "momd"),
225 let bundledModel = NSManagedObjectModel(contentsOf: modelURL),
226 let model = bundledModel.copy() as? NSManagedObjectModel,
227 let entity = model.entitiesByName["Note"] else { throw LocalError.message("Test model missing.") }
228 let starterRoot = FileManager.default.temporaryDirectory.appendingPathComponent("JotleyStarterFolders-\(UUID())")
229 defer { try? FileManager.default.removeItem(at: starterRoot) }
230 let fresh = try SharedPersistenceController(root: starterRoot)
231 let request = Folder.fetchRequest()
232 guard Set(try fresh.context.fetch(request).compactMap(\.name)) == ["Personal", "Study", "Work"],
233 let personal = Folder.find(named: "Personal", in: fresh.context),
234 let study = Folder.find(named: "Study", in: fresh.context) else { throw LocalError.message("New libraries need three starter folders.") }
235 personal.name = "Life"; fresh.context.delete(study); try fresh.save()
236 let reopened = try SharedPersistenceController(root: starterRoot)
237 guard Set(try reopened.context.fetch(Folder.fetchRequest()).compactMap(\.name)) == ["Life", "Work"] else { throw LocalError.message("Starter folders were recreated after a rename or deletion.") }
238 print("PASS: new libraries start with Personal, Study and Work; renamed/deleted folders stay changed after reopening.")
239 entity.managedObjectClassName = NSStringFromClass(RoutingRefusedNote.self)
240 let root = FileManager.default.temporaryDirectory.appendingPathComponent("JotleyMacRouting-\(UUID())")
241 let store = try SharedPersistenceController(root: root, model: model)
242 defer {
243 for item in store.container.persistentStoreCoordinator.persistentStores { try? store.container.persistentStoreCoordinator.remove(item) }
244 try? FileManager.default.removeItem(at: root)
245 }
246 guard let note = try store.create(title: "Keep selected note", text: "Earlier recorded words.") as? Note else {
247 throw LocalError.message("Test note missing.")
248 }
249 let recorder = ProcessTapRecorder()
250 let viewModel = NotesListViewModel(viewContext: store.context, recorder: recorder, persistenceController: store)
251 viewModel.ensureSelection(in: [note])
252 viewModel.toggleSelection(for: note, isCommandKeyPressed: true)
253 guard viewModel.selectedNoteIDs == [note.objectID] else { throw LocalError.message("Command-click cleared the last selected note.") }
254 let staleID = NSManagedObjectID()
255 viewModel.selectedNoteIDs = [staleID]
256 viewModel.ensureSelection(in: [note])
257 guard viewModel.selectedNoteIDs == [note.objectID] else { throw LocalError.message("Missing selection did not recover the first note.") }
258 viewModel.ensureSelection(in: [])
259 guard viewModel.selectedNoteIDs.isEmpty else { throw LocalError.message("Empty library retained a stale selection.") }
260 viewModel.ensureSelection(in: [note])
261 print("PASS: the first available note is selected; the last selection cannot be toggled off, stale IDs recover and empty libraries clear safely.")
262 viewModel.createBlankNote()
263 viewModel.showSyncError = false
264 await viewModel.startNewNote()
265 guard viewModel.showSyncError, viewModel.selectedNoteIDs == [note.objectID],
266 note.title == "Keep selected note", note.transcription == "Earlier recorded words.",
267 note.noteType == "local", note.sourceURL == nil,
268 !recorder.isRecording, !recorder.isBusy, viewModel.newNoteBeingRecorded == nil,
269 try store.notes().count == 1,
270 !FileManager.default.fileExists(atPath: root.appendingPathComponent("Recordings").path) else {
271 throw LocalError.message("Failed new-note creation changed or recorded the previous selection.")
272 }
273 let lease = try store.beginRecording(note); store.endRecording(lease: lease)
274 print("PASS: failed new-note creation leaves the previous selection, transcript, metadata and recording state intact.")
275 // Ordinary creation must still select a fresh note without changing the
276 // prior note; this check does not request microphone access.
277 RoutingRefusedNote.rejectsNewNotes = false
278 viewModel.showSyncError = false
279 viewModel.createBlankNote(text: "Fresh note content.", title: "New selected note")
280 let notes = try store.notes()
281 guard notes.count == 2, let created = notes.first(where: { $0.objectID != note.objectID }) as? Note,
282 viewModel.selectedNoteIDs == [created.objectID], created.noteType == "local", created.sourceURL == nil,
283 created.title == "New selected note", created.transcription == "Fresh note content.",
284 note.noteType == "local", note.sourceURL == nil, note.transcription == "Earlier recorded words.",
285 !viewModel.showSyncError,
286 !recorder.isRecording, !recorder.isBusy, viewModel.newNoteBeingRecorded == nil,
287 !FileManager.default.fileExists(atPath: root.appendingPathComponent("Recordings").path) else {
288 throw LocalError.message("Successful creation did not select a fresh note or preserve the previous note.")
289 }
290 let nextLease = try store.beginRecording(created); store.endRecording(lease: nextLease)
291 print("PASS: successful creation selects a fresh note and preserves prior content.")
292 try await verifyTranscriptEditing(note: created, store: store, viewModel: viewModel)
293 try verifyLegacyAudioCleanup()
294 try await verifySummaryObserverLifetime(note: created)
295 try verifyTranscriptRevisions(note: created)
296 try await verifySummaryPresentation(note: created)
297 try verifySummaryStyleRendering()
298 try await verifyMacAskPresentation(note: created, store: store)
299 try verifySearchEditingAlignment()
300 try verifyGeneratedTitlePersistence(note: created, store: store)
301 try await verifyAutomaticTags(note: created, store: store, viewModel: viewModel)
302 try await verifyPlusStartsCaptureImmediately(store: store)
303 try await verifyRecordingControlLayout()
304 try await verifyCompactTranscription(store: store)
305 try await verifyNewTranscriptScroll(store: store)
306 if ProcessInfo.processInfo.environment["JOTLEY_RUN_TITLE_TESTS"] == "1" {
307 try await verifyOnDeviceTitle(note: created, viewModel: viewModel)
308 }
309 }
310 @MainActor private static func verifyPlusStartsCaptureImmediately(store: SharedPersistenceController) async throws {
311 _ = NSApplication.shared
312 let recorder = ProcessTapRecorder()
313 var calls: [UUID] = []
314 recorder.simulatedStart = { _, id, _ in
315 calls.append(id)
316 try await Task.sleep(for: .milliseconds(150))
317 throw LocalError.message("Injected capture-start rejection; no microphone was accessed.")
318 }
319 defer { recorder.simulatedStart = nil }
320 let before = try store.notes().map(\.objectID)
321 let viewModel = NotesListViewModel(viewContext: store.context, recorder: recorder, persistenceController: store)
322 let start = Task { await viewModel.startNewNote() }
323 for _ in 0..<30 { if !calls.isEmpty { break }; try await Task.sleep(for: .milliseconds(10)) }
324 guard calls.count == 1, viewModel.newNoteBeingRecorded != nil else { throw LocalError.message("New transcription must immediately start capture without a modal.") }
325 await viewModel.startNewNote()
326 await start.value
327 let created = try store.notes().filter { !before.contains($0.objectID) }
328 guard calls.count == 1, created.count == 1, created.first?.localNoteID == calls.first,
329 !recorder.starting, !recorder.isRecording, viewModel.newNoteBeingRecorded == nil else {
330 throw LocalError.message("Repeated + taps created duplicate notes or left capture busy after failure.")
331 }
332 guard let newNote = created.first else { throw LocalError.message("New transcription note is missing.") }
333 defer { try? store.deleteNote(newNote) }
334 // The failure path must release its note lease, allowing a retry.
335 let lease = try store.beginRecording(newNote); store.endRecording(lease: lease)
336 print("PASS: Mac new-transcription route starts capture on a fresh note immediately, blocks duplicate starts and releases a failed start.")
337 }
338 @MainActor private static func verifyAutomaticTags(note: Note, store: SharedPersistenceController, viewModel: NotesListViewModel) async throws {
339 let suite = "JotleyMacSummaryDelivery-" + UUID().uuidString
340 let defaults = UserDefaults(suiteName: suite)!
341 defer { defaults.removePersistentDomain(forName: suite) }
342 var delivered = 0
343 let notifications = JotleySummaryNotifications(defaults: defaults, authorization: { .authorized },
344 requestAuthorization: { true }, enqueue: { request in
345 guard note.summary == "Finished design summary.", request.content.userInfo["noteID"] as? String == note.id?.uuidString else {
346 throw LocalError.message("A notification was sent before its summary was saved.")
347 }
348 delivered += 1
349 }, isActive: { true })
350 let viewModel = NotesListViewModel(viewContext: store.context, recorder: ProcessTapRecorder(), persistenceController: store, summaryNotifications: notifications)
351 let other = try store.create(title: "Other tag bucket", text: "Related note")
352 try store.saveNoteChanges(other, values: [:], replacingTags: ["AI", "Design"])
353 try store.saveNoteChanges(note, values: [:], replacingTags: ["My own tag"])
354 note.summary = nil
355 note.title = "Design review"
356 note.transcription = String(repeating: "AI supports design and helps the team explore useful interface ideas. ", count: 5)
357 viewModel.simulatedSummaryGeneration = { _ in "Finished design summary." }
358 viewModel.simulatedOrganization = { _, _ in
359 LocalNoteOrganization(tags: ["Artificial Intelligence", "AI Tools", "Design"], folder: .work)
360 }
361 defer { viewModel.simulatedSummaryGeneration = nil; viewModel.simulatedOrganization = nil; try? store.deleteNote(other) }
362 await viewModel.generateSummary(note: note, templateKey: "Concise")
363 guard note.summary == "Finished design summary.", note.tagNames.count == 4,
364 Set(["AI", "Design", "My-own-tag"]).isSubset(of: note.tagNames), delivered == 1,
365 (other.value(forKey: "tags") as? NSSet)?.count == 2 else {
366 throw LocalError.message("Mac summary must preserve manual tags and reuse existing library buckets.")
367 }
368 viewModel.simulatedOrganization = { _, _ in throw LocalError.message("Injected tagging failure") }
369 await viewModel.generateSummary(note: note, templateKey: "Concise")
370 guard note.tagNames.count == 4, note.summary == "Finished design summary.", delivered == 2, !viewModel.showSyncError else {
371 throw LocalError.message("Regenerating a summary must preserve its tags.")
372 }
373 viewModel.simulatedSummaryGeneration = { _ in throw LocalError.message("Injected summary failure") }
374 await viewModel.generateSummary(note: note, templateKey: "Concise")
375 guard delivered == 2, note.summary == "Finished design summary.", viewModel.showSyncError else { throw LocalError.message("Failed summaries must not notify.") }
376 viewModel.showSyncError = false
377 print("PASS: Mac summaries preserve manual tags and deliver local notifications only after saved results, including silent fallback tags and genuine summary failures.")
378 }
379 @MainActor private static func verifySummaryFollowAndCancel(note: Note, store: SharedPersistenceController, viewModel: NotesListViewModel) async throws {
380 let previousSummary = (1...30).map { "## Saved section \($0)\nPreviously saved summary text that remains safe when generation is cancelled.\n" }.joined(separator: "\n")
381 note.summary = previousSummary
382 try store.save()
383 viewModel.simulatedSummaryGeneration = { _ in
384 try await Task.sleep(for: .seconds(60))
385 return "Cancelled test must never save"
386 }
387 let host = NSHostingView(rootView: NoteDetailPlaceholderView(note: note, selectedTab: .constant(DetailTab.summary.rawValue), viewModel: viewModel)
388 .environment(\.managedObjectContext, store.context).environmentObject(store))
389 let window = NSWindow(contentRect: NSRect(x: 100, y: 100, width: 700, height: 500), styleMask: [.borderless], backing: .buffered, defer: false)
390 window.isReleasedWhenClosed = false; window.contentView = host; window.orderFrontRegardless()
391 defer { window.close() }
392 func scrollViews(_ view: NSView) -> [NSScrollView] {
393 (view as? NSScrollView).map { [$0] } ?? view.subviews.flatMap(scrollViews)
394 }
395 try await Task.sleep(for: .milliseconds(400))
396 host.layoutSubtreeIfNeeded()
397 guard let initialScroll = scrollViews(host).max(by: { ($0.documentView?.bounds.height ?? 0) < ($1.documentView?.bounds.height ?? 0) }),
398 let initialDocument = initialScroll.documentView else { throw LocalError.message("Saved summary scroll fixture unavailable.") }
399 let bottomY = initialDocument.isFlipped ? initialDocument.bounds.maxY - initialScroll.contentView.bounds.height : initialDocument.bounds.minY
400 initialScroll.contentView.scroll(to: NSPoint(x: 0, y: bottomY))
401 initialScroll.reflectScrolledClipView(initialScroll.contentView)
402 let generation = Task { await viewModel.generateSummary(note: note, templateKey: "Concise") }
403 await Task.yield()
404 defer { generation.cancel(); viewModel.simulatedSummaryGeneration = nil }
405 for count in [12, 36] {
406 viewModel.streamingSummaryViewModel.summary = (1...count).map {
407 "## Summary update \($0)\nMaya will review milestones Friday. Sam will test the next steps and share feedback with the team.\n"
408 }.joined(separator: "\n")
409 viewModel.objectWillChange.send()
410 try await Task.sleep(for: .milliseconds(600))
411 host.layoutSubtreeIfNeeded()
412 guard let scroll = scrollViews(host).filter({ ($0.documentView?.bounds.height ?? 0) > $0.contentView.bounds.height + 100 }).max(by: { ($0.documentView?.bounds.height ?? 0) < ($1.documentView?.bounds.height ?? 0) }),
413 let document = scroll.documentView else { throw LocalError.message("Mac summary scroll fixture did not overflow.") }
414 let visible = scroll.documentVisibleRect
415 let distance = document.isFlipped ? visible.minY - document.bounds.minY : document.bounds.maxY - visible.maxY
416 guard distance < 30 else { throw LocalError.message("Mac summary must open and stay at the top while streaming: \(distance) points away.") }
417 if let bitmap = host.bitmapImageRepForCachingDisplay(in: host.bounds) {
418 host.cacheDisplay(in: host.bounds, to: bitmap)
419 try bitmap.representation(using: .png, properties: [:])?.write(to: FileManager.default.temporaryDirectory.appendingPathComponent("jotley-summary-mac-preview.png"))
420 }
421 guard let bitmap = host.bitmapImageRepForCachingDisplay(in: host.bounds) else { throw LocalError.message("Mac summary snapshot unavailable") }
422 host.cacheDisplay(in: host.bounds, to: bitmap)
423 var purplePixels = 0
424 for y in (bitmap.pixelsHigh - 65)..<bitmap.pixelsHigh {
425 for x in 0..<bitmap.pixelsWide {
426 if let color = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.deviceRGB),
427 color.blueComponent > color.greenComponent + 0.2,
428 color.redComponent > color.greenComponent + 0.1 { purplePixels += 1 }
429 }
430 }
431 guard purplePixels > 300 else { throw LocalError.message("Cancel Generation is not visibly styled in the pinned footer.") }
432 }
433 if let bitmap = host.bitmapImageRepForCachingDisplay(in: host.bounds) {
434 host.cacheDisplay(in: host.bounds, to: bitmap)
435 try bitmap.representation(using: .png, properties: [:])?.write(to: FileManager.default.temporaryDirectory.appendingPathComponent("jotley-summary-mac-preview.png"))
436 }
437 window.makeKeyAndOrderFront(nil)
438 guard let escape = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,
439 windowNumber: window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53) else { throw LocalError.message("Cancel key event unavailable") }
440 if !window.performKeyEquivalent(with: escape) { window.sendEvent(escape) }
441 try await Task.sleep(for: .milliseconds(300))
442 guard !viewModel.isGeneratingSummary, note.summary == previousSummary else { throw LocalError.message("Pinned Cancel Generation did not cancel/preserve the saved summary.") }
443 await generation.value
444 print("PASS: real Mac summary generation returns a scrolled summary to the top, stays there while streaming and keeps a visible Cancel Generation footer; Escape cancels the actual task and preserves saved content.")
445 }
446
447 @MainActor private static func verifyTranscriptEditing(note: Note, store: SharedPersistenceController, viewModel: NotesListViewModel) async throws {
448 let theme = ThemeManager.shared
449 let priorAppearance = theme.currentAppearanceMode
450 let priorColor = theme.currentThemeColor
451 let screenshot = ProcessInfo.processInfo.environment["JOTLEY_TRANSCRIPT_EDITOR_SCREENSHOT"]
452 if screenshot != nil {
453 theme.setAppearanceMode(.dark)
454 theme.setThemeColor(.magenta)
455 }
456 defer {
457 theme.setAppearanceMode(priorAppearance)
458 theme.setThemeColor(priorColor)
459 }
460 note.transcription = "Original Mac words. Another paragraph."
461 note.summary = "Preserved summary."
462 note.sourceURL = "local://preserved-recording"
463 note.setTranscriptUtterances([
464 TranscriptUtterance(text: "Original Mac words.", start: 1.2, end: 3),
465 TranscriptUtterance(text: "Another paragraph.", start: 7.4, end: 9)
466 ])
467 try store.context.save()
468 let host = NSHostingView(rootView: NoteDetailPlaceholderView(note: note,
469 selectedTab: .constant(DetailTab.transcript.rawValue), viewModel: viewModel, isEditingTranscript: true)
470 .environment(\.managedObjectContext, store.context).environmentObject(store)
471 .preferredColorScheme(theme.effectiveColorScheme))
472 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 760, height: 560), styleMask: [.borderless], backing: .buffered, defer: false)
473 window.isReleasedWhenClosed = false; window.contentView = host; window.orderFrontRegardless()
474 defer { window.close() }
475 try await Task.sleep(for: .milliseconds(250))
476 func textViews(_ view: NSView) -> [NSTextView] {
477 (view as? NSTextView).map { [$0] } ?? view.subviews.flatMap(textViews)
478 }
479 let editors = textViews(host).filter(\.isEditable)
480 guard editors.count == 1, let editor = editors.first,
481 editor.string == "[00:01]\nOriginal Mac words.\n[00:07]\nAnother paragraph." else {
482 throw LocalError.message("Mac transcript must open in one editable field with its saved timestamps.")
483 }
484 if let screenshot,
485 let bitmap = host.bitmapImageRepForCachingDisplay(in: host.bounds) {
486 host.cacheDisplay(in: host.bounds, to: bitmap)
487 try bitmap.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: screenshot))
488 }
489 editor.selectAll(nil)
490 editor.insertText("[00:01]\nCorrected Mac words.\n[00:07]\nAnother paragraph.", replacementRange: editor.selectedRange())
491 try await Task.sleep(for: .milliseconds(2300))
492 guard window.attachedSheet == nil, note.transcription == "Corrected Mac words.\n\nAnother paragraph." else {
493 throw LocalError.message("Transcript edits must autosave inline without opening a sheet.")
494 }
495 let addition = " Saved before closing the app."
496 editor.insertText(addition, replacementRange: NSRange(location: (editor.string as NSString).length, length: 0))
497 NotificationCenter.default.post(name: Notification.Name("JotleyForceAllEditorsSave"), object: nil)
498 try await Task.sleep(for: .milliseconds(150))
499 guard note.transcription?.hasSuffix(addition) == true else { throw LocalError.message("Inline transcript did not flush its latest draft before quitting.") }
500 window.makeKeyAndOrderFront(nil)
501 guard let key = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: .command, timestamp: ProcessInfo.processInfo.systemUptime,
502 windowNumber: window.windowNumber, context: nil, characters: "\r", charactersIgnoringModifiers: "\r", isARepeat: false, keyCode: 36),
503 window.performKeyEquivalent(with: key) else {
504 throw LocalError.message("Mac inline transcript Done keyboard action was inaccessible.")
505 }
506 try await Task.sleep(for: .milliseconds(150))
507 guard !textViews(host).contains(where: { $0.isEditable }),
508 note.transcription == "Corrected Mac words.\n\nAnother paragraph." + addition,
509 note.transcriptUtterances.map(\.text) == ["Corrected Mac words.", "Another paragraph." + addition],
510 note.transcriptUtterances.map(\.start) == [1.2, 7.4],
511 note.summary == "Preserved summary.", note.sourceURL == "local://preserved-recording" else {
512 throw LocalError.message("Mac editor failed to persist corrected words or preserve existing content.")
513 }
514 do {
515 try note.saveEditedTranscript("Stale draft", original: "Original Mac words.", in: store)
516 throw LocalError.message("Mac accepted a stale transcript draft.")
517 } catch let error as LocalError {
518 guard error.localizedDescription.contains("changed while") else { throw error }
519 }
520 print("PASS: the real Mac note edits its transcript inline, autosaves paragraphs, exits with Command-Return, preserves summary/audio metadata and rejects stale drafts.")
521 }
522 @MainActor private static func verifyNoteMenus(note: Note, store: SharedPersistenceController, model: NotesListViewModel) async throws {
523 let window = NSWindow(contentRect: NSRect(x: 100, y: 100, width: 400, height: 600),
524 styleMask: [.titled], backing: .buffered, defer: false)
525 window.isReleasedWhenClosed = false
526 defer { window.close() }
527 for tab in [DetailTab.summary, .transcript] {
528 let parent = NoteDetailPlaceholderView(note: note, selectedTab: .constant(tab.rawValue), viewModel: model)
529 let menu = NoteDetailPlaceholderView.CustomMoreMenu(parent: parent, viewModel: model, note: note, isPresented: .constant(true))
530 let host = NSHostingView(rootView: menu.environmentObject(store).environment(\.managedObjectContext, store.context))
531 window.contentView = host; window.makeKeyAndOrderFront(nil)
532 try await Task.sleep(for: .milliseconds(300))
533 let renderer = ImageRenderer(content: menu.environmentObject(store).frame(width: 260).padding(20).background(Color.themeBackground))
534 renderer.scale = 2
535 guard let image = renderer.cgImage else { throw LocalError.message("Mac More menu did not render.") }
536 let request = VNRecognizeTextRequest()
537 request.recognitionLevel = .accurate
538 try VNImageRequestHandler(cgImage: image).perform([request])
539 let actual = (request.results ?? []).compactMap { $0.topCandidates(1).first?.string }.joined(separator: "\n")
540 for required in ["Edit Transcript", "Edit Summary", "Summary Style", "Template"] {
541 guard actual.contains(required) else {
542 throw LocalError.message("Mac \(tab) menu is missing \(required): \(actual)")
543 }
544 }
545 }
546 print("PASS: the actual Mac More menu offers both editors, summary style and template on either tab.")
547 }
548
549 @MainActor private static func verifyMacAskPresentation(note: Note, store: SharedPersistenceController) async throws {
550 let original = ThemeManager.shared.currentAppearanceMode
551 defer { ThemeManager.shared.setAppearanceMode(original) }
552 note.title = "Release planning"
553 note.transcription = "Mina owns the release checklist. The team will test recording and review the new widgets."
554 let output = FileManager.default.temporaryDirectory.appendingPathComponent("Jotley-Ask-Proof", isDirectory: true)
555 try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
556 var images: [Data] = []
557 for mode in [AppearanceMode.dark, .light] {
558 ThemeManager.shared.setAppearanceMode(mode)
559 let content = LocalMacAskNoteView(note: note).environmentObject(store)
560 let host = NSHostingView(rootView: content)
561 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 580, height: 650),
562 styleMask: [.borderless], backing: .buffered, defer: false)
563 window.isReleasedWhenClosed = false
564 window.contentView = host; window.orderFrontRegardless()
565 defer { window.close() }
566 try await Task.sleep(for: .milliseconds(250))
567 host.layoutSubtreeIfNeeded()
568 guard host.fittingSize.width >= 580, host.fittingSize.height >= 650 else {
569 throw LocalError.message("Mac Ask AI did not mount at its intended readable size.")
570 }
571 // Offscreen snapshots composite transparent glass against the window
572 // appearance. Its reflective rim stays bright even in Dark Mode.
573 let renderer = ImageRenderer(content: content.frame(width: 580, height: 650).background(Color.themeBackground))
574 renderer.proposedSize = ProposedViewSize(width: 580, height: 650)
575 guard let rendered = renderer.cgImage else { throw LocalError.message("Mac Ask AI snapshot failed.") }
576 let bitmap = NSBitmapImageRep(cgImage: rendered)
577 // Native glass is composited by WindowServer and has no reliable
578 // offscreen backdrop pixel. Check the resolved label contrast here;
579 // verify the actual material in the live Light/Dark sheet captures.
580 guard let foreground = NSColor(Color.themeTextPrimary).usingColorSpace(.deviceRGB) else {
581 throw LocalError.message("Mac Ask AI text color did not resolve.")
582 }
583 let brightness = (foreground.redComponent + foreground.greenComponent + foreground.blueComponent) / 3
584 guard mode == .dark ? brightness > 0.8 : brightness < 0.3 else {
585 throw LocalError.message("Mac Ask AI text does not follow its light/dark appearance.")
586 }
587 guard let png = bitmap.representation(using: .png, properties: [:]), !png.isEmpty else {
588 throw LocalError.message("Mac Ask AI screen did not render.")
589 }
590 images.append(png)
591 let file = output.appendingPathComponent("Mac-Ask-AI-\(mode == .dark ? "dark" : "light").png")
592 try png.write(to: file)
593 print("JOTLEY_MAC_ASK_SCREENSHOT \(file.path)")
594 }
595 guard images[0] != images[1] else { throw LocalError.message("Mac Ask AI did not update its appearance.") }
596 print("PASS: actual Mac Ask AI screen mounts at 580×650 and renders distinct light/dark appearances.")
597 }
598 @MainActor private static func verifySummaryStyleRendering() throws {
599 let suite = "JotleySummaryStyle-" + UUID().uuidString
600 let defaults = UserDefaults(suiteName: suite)!
601 let theme = ThemeManager.shared
602 let previousMode = theme.currentAppearanceMode
603 let previousColor = theme.currentThemeColor
604 defer {
605 defaults.removePersistentDomain(forName: suite)
606 theme.setAppearanceMode(previousMode); theme.setThemeColor(previousColor)
607 }
608 let output = FileManager.default.temporaryDirectory.appendingPathComponent("Jotley-Summary-Style-Proof")
609 try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
610 let source = "## Summary\nA clear plan for Friday.\n\n## Next Steps\n- **Maya:** Review the launch."
611 theme.setThemeColor(.purple)
612 for mode in [AppearanceMode.light, .dark] {
613 theme.setAppearanceMode(mode)
614 for style in SummaryDisplayStyle.allCases {
615 defaults.set(style.rawValue, forKey: SummaryDisplayStyle.preferenceKey)
616 let content = StructuredSummaryView(content: source).defaultAppStorage(defaults)
617 .frame(width: 520).padding(24).background(Color.themeBackground)
618 let renderer = ImageRenderer(content: content)
619 guard let image = renderer.cgImage else { throw LocalError.message("Summary style did not render.") }
620 let bitmap = NSBitmapImageRep(cgImage: image)
621 var accentPixels = 0
622 for y in 0..<bitmap.pixelsHigh { for x in 0..<bitmap.pixelsWide {
623 guard let pixel = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.deviceRGB) else { continue }
624 if pixel.redComponent > pixel.greenComponent + 0.08,
625 pixel.blueComponent > pixel.greenComponent + 0.08 { accentPixels += 1 }
626 } }
627 guard style == .standard ? accentPixels == 0 : accentPixels > 100 else {
628 throw LocalError.message("Summary appearance preference was not reflected in the rendered content: \(style.title), \(accentPixels).")
629 }
630 if let png = bitmap.representation(using: .png, properties: [:]) {
631 try png.write(to: output.appendingPathComponent("Mac-\(style.rawValue)-\(mode.rawValue).png"))
632 }
633 }
634 }
635 print("PASS: actual shared Mac summaries honor the saved Cards/Standard Text preference in light and dark; Standard Text contains neutral text without colored cards.")
636 }
637
638 @MainActor private static func verifyGeneratedTitlePersistence(note: Note, store: SharedPersistenceController) throws {
639 for title in [nil, "", "Untitled", "Untitled Note"] as [String?] {
640 note.title = title
641 try store.saveNoteChanges(note, values: note.generatedSummaryValues("Saved summary", template: "Meeting", generatedTitle: "Planning the Free Jotley Release"))
642 store.context.refresh(note, mergeChanges: false)
643 guard note.title == "Planning the Free Jotley Release", note.summary == "Saved summary", note.summaryType == "Meeting" else {
644 throw LocalError.message("An untitled note did not persist its generated title with its summary.")
645 }
646 }
647 note.title = "Untitled Note"
648 guard note.shouldReplaceTitleFromGeneratedSummary() else { throw LocalError.message("Untitled fixture rejected generation.") }
649 // A user can name the note while the model is still generating.
650 note.title = "My own title"
651 try store.saveNoteChanges(note, values: note.generatedSummaryValues("New summary", template: "Study", generatedTitle: "Model title"))
652 store.context.refresh(note, mergeChanges: false)
653 guard note.title == "My own title", note.summary == "New summary" else { throw LocalError.message("Title generation overwrote a user's concurrent edit.") }
654 note.title = "Untitled Note"
655 try store.saveNoteChanges(note, values: note.generatedSummaryValues("Summary survives title failure", template: "Concise", generatedTitle: nil))
656 store.context.refresh(note, mergeChanges: false)
657 guard note.title == "Untitled Note", note.summary == "Summary survives title failure" else {
658 throw LocalError.message("A failed title discarded the successful summary.")
659 }
660 print("PASS: generated titles persist with summaries; user edits win; title failure retains the summary.")
661 }
662 @MainActor private static func verifyOnDeviceTitle(note: Note, viewModel: NotesListViewModel) async throws {
663 note.title = "Untitled Note"
664 note.transcription = "The team agreed to keep Jotley's existing interface and release version two as a free app. Recording and summaries will use installed Apple models. Optional iCloud sync will share notes between devices."
665 note.summary = nil
666 await viewModel.generateSummary(note: note, templateKey: "Concise")
667 guard let title = note.title, !title.isEmpty, title != "Untitled Note", note.hasMeaningfulSummaryText,
668 !viewModel.isGeneratingSummary, !viewModel.showSyncError else {
669 throw LocalError.message("The actual on-device summary flow did not save both summary and title: \(viewModel.syncErrorMessage)")
670 }
671 let generatedTitle = title
672 var progress: [LocalSummaryProgress] = [], snapshots: [String] = []
673 let progressObserver = viewModel.streamingSummaryViewModel.$progress.sink { progress.append($0) }
674 let streamObserver = viewModel.streamingSummaryViewModel.$summary.sink { if !$0.isEmpty { snapshots.append($0) } }
675 defer { progressObserver.cancel(); streamObserver.cancel() }
676 note.transcription = Array(repeating: note.transcription ?? "", count: 64).joined(separator: "\n\n")
677 let began = Date()
678 await viewModel.generateSummary(note: note, templateKey: "Meeting")
679 guard note.title == generatedTitle, note.summaryType == LocalSummaryTemplate.meeting.key, !viewModel.showSyncError else {
680 throw LocalError.message("Template regeneration changed an already named note or failed.")
681 }
682 guard progress.contains(.preparing),
683 progress.contains(.writing), snapshots.count > 1, !viewModel.isGeneratingSummary else {
684 throw LocalError.message("Mac long-note generation did not report preparation and live text before finishing.")
685 }
686 print("PASS: installed Apple model generated summary/title and regenerated a long transcript in \(Date().timeIntervalSince(began)) seconds with \(snapshots.count) live snapshots; preparation progress was reported and the title was preserved.")
687 }
688 @MainActor private static func verifyNewTranscriptScroll(store baseStore: SharedPersistenceController) async throws {
689 let store = try SharedPersistenceController(inMemory: true, model: baseStore.container.managedObjectModel)
690 defer { try? FileManager.default.removeItem(at: store.root) }
691 let recorder = ProcessTapRecorder()
692 recorder.simulatedStart = { _, _, _ in recorder.beginSimulatedLiveTranscription(LocalTranscript()) }
693 let model = NotesListViewModel(viewContext: store.context, recorder: recorder, persistenceController: store)
694 await model.startNewNote()
695 guard let note = model.newNoteBeingRecorded else { throw LocalError.message("New transcript fixture did not start.") }
696 defer { recorder.simulatedStart = nil; try? store.deleteNote(note) }
697 let host = NSHostingView(rootView: MacTranscriptionPreviewRoot(model: model))
698 let window = NSWindow(contentRect: NSRect(x: 100, y: 100, width: 1000, height: 760), styleMask: [.borderless], backing: .buffered, defer: false)
699 window.isReleasedWhenClosed = false; window.contentView = host; window.orderFrontRegardless()
700 defer { window.close() }
701 func scrollViews(_ view: NSView) -> [NSScrollView] {
702 (view as? NSScrollView).map { [$0] } ?? view.subviews.flatMap(scrollViews)
703 }
704 func transcriptScroll() throws -> NSScrollView {
705 host.layoutSubtreeIfNeeded()
706 guard let scroll = scrollViews(host).first(where: { $0.bounds.height > 300 }) else {
707 throw LocalError.message("New transcript scroll view unavailable.")
708 }
709 return scroll
710 }
711 for text in ["", "The first words should stay beside the note header."] {
712 if !text.isEmpty {
713 var speech = LocalTranscript()
714 speech.accept(text: text, start: 0, end: 8, final: true)
715 recorder.publishSimulatedLiveTranscript(speech)
716 }
717 try await Task.sleep(for: .milliseconds(500))
718 let scroll = try transcriptScroll()
719 guard let document = scroll.documentView else { throw LocalError.message("Missing transcript document.") }
720 let visible = scroll.documentVisibleRect
721 let fromTop = document.isFlipped ? visible.minY - document.bounds.minY : document.bounds.maxY - visible.maxY
722 guard abs(fromTop) < 2 else {
723 throw LocalError.message("A new or short transcript must stay at the top; shifted \(fromTop) points for '\(text)'.")
724 }
725 }
726 var longSpeech = LocalTranscript()
727 for index in 1...40 {
728 longSpeech.accept(text: "Segment \(index). A longer transcript should keep following incoming speech after it fills the available space, with enough clearance for the recording controls.", start: Double(index * 15), end: Double(index * 15 + 8), final: true)
729 }
730 recorder.publishSimulatedLiveTranscript(longSpeech)
731 try await Task.sleep(for: .milliseconds(700))
732 let scroll = try transcriptScroll()
733 guard let document = scroll.documentView, document.bounds.height > scroll.bounds.height + 100 else {
734 throw LocalError.message("Long transcript fixture did not overflow.")
735 }
736 let visible = scroll.documentVisibleRect
737 let fromBottom = document.isFlipped ? document.bounds.maxY - visible.maxY : visible.minY - document.bounds.minY
738 guard abs(fromBottom) < 30 else { throw LocalError.message("Long live transcript stopped following: \(fromBottom) points from bottom.") }
739 await model.stopRecording()
740 print("PASS: new and short Mac transcriptions stay at the top; a long transcript follows incoming speech once it fills the view.")
741 }
742
743 @MainActor private static func verifyCompactTranscription(store: SharedPersistenceController) async throws {
744 let recorder = ProcessTapRecorder()
745 var speech = LocalTranscript()
746 speech.accept(text: "Keep live transcription running while browsing other notes.", start: 0, end: 8, final: true)
747 recorder.simulatedStart = { _, _, _ in recorder.beginSimulatedLiveTranscription(speech) }
748 let model = NotesListViewModel(viewContext: store.context, recorder: recorder, persistenceController: store)
749 await model.startNewNote()
750 guard recorder.isRecording, let note = model.newNoteBeingRecorded else { throw LocalError.message("Capture did not start immediately.") }
751 if CommandLine.arguments.contains("--compact-only") {
752 let host = NSHostingView(rootView: MacTranscriptionPreviewRoot(model: model))
753 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 760),
754 styleMask: [.borderless], backing: .buffered, defer: false)
755 window.isReleasedWhenClosed = false; window.contentView = host; window.orderFrontRegardless()
756 defer { window.close() }
757 try await Task.sleep(for: .milliseconds(250))
758 host.layoutSubtreeIfNeeded()
759 func scrollViews(in view: NSView) -> [NSScrollView] {
760 (view as? NSScrollView).map { [$0] } ?? view.subviews.flatMap { scrollViews(in: $0) }
761 }
762 guard let scroll = scrollViews(in: host).first(where: { $0.bounds.height > 300 }) else {
763 throw LocalError.message("The actual transcript scroll view is missing.")
764 }
765 let frame = scroll.convert(scroll.bounds, to: host)
766 let bottomGap = host.isFlipped ? host.bounds.maxY - frame.maxY : frame.minY - host.bounds.minY
767 guard abs(bottomGap) < 2 else { throw LocalError.message("Scrollbar stops above the window bottom: \(bottomGap) points.") }
768 print("PASS: actual transcript scroll view reaches the window bottom under the floating capsule.")
769 }
770 let other = try store.create(title: "Browse while transcribing", text: "Keep this note unchanged.") as! Note
771 other.summary = "Existing summary"; try store.save()
772 defer { recorder.simulatedStart = nil; try? store.deleteNote(note); try? store.deleteNote(other) }
773 model.toggleSelection(for: other)
774 var updated = speech
775 updated.accept(text: "These words belong only to the active transcription.", start: 10, end: 18, final: true)
776 recorder.publishSimulatedLiveTranscript(updated)
777 guard recorder.isRecording, model.selectedNoteIDs == [other.objectID],
778 note.transcription == updated.text, other.transcription == "Keep this note unchanged." else {
779 throw LocalError.message("Browsing interrupted capture or sent speech to the wrong note.")
780 }
781 await model.resumeTranscription()
782 guard model.isTranscriptionPaused, model.selectedNoteIDs == [other.objectID] else { throw LocalError.message("Pause changed the selected note.") }
783 await model.resumeTranscription()
784 guard !model.isTranscriptionPaused else { throw LocalError.message("Continue did not resume capture.") }
785 await model.stopRecording()
786 guard !recorder.isRecording, model.newNoteBeingRecorded == nil,
787 model.selectedNoteIDs == [other.objectID], model.selectedDetailTab == DetailTab.summary.rawValue,
788 note.transcription == updated.text else { throw LocalError.message("Stop failed to save or displaced the browsed note.") }
789 let saved = note.transcription
790 recorder.publishSimulatedLiveTranscript(speech)
791 guard note.transcription == saved else { throw LocalError.message("Stopped transcript still accepts live words.") }
792 recorder.simulatedStart = { _, _, _ in recorder.beginSimulatedLiveTranscription(speech) }
793 await model.resumeTranscriptionOnNote(note: note)
794 model.jumpToActiveRecordingNote()
795 guard model.selectedNoteIDs == [note.objectID], model.selectedDetailTab == DetailTab.transcript.rawValue else { throw LocalError.message("Return to active transcript failed.") }
796 await model.stopRecording()
797 guard note.transcription == [updated.text, speech.text].joined(separator: " ") else { throw LocalError.message("Continuing replaced the saved transcript.") }
798 var follow = MacTranscriptFollowState()
799 guard follow.shouldFollow else { throw LocalError.message("Live transcript must initially follow.") }
800 follow.bottomChanged(false)
801 follow.scrollPhaseChanged(isUserScrolling: false)
802 guard follow.shouldFollow else { throw LocalError.message("Layout/programmatic phases disabled initial following.") }
803 follow.scrollPhaseChanged(isUserScrolling: true)
804 follow.bottomChanged(false)
805 guard !follow.shouldFollow else { throw LocalError.message("Follow interrupted an active user scroll.") }
806 follow.scrollPhaseChanged(isUserScrolling: false)
807 guard !follow.shouldFollow else { throw LocalError.message("Follow resumed while reading earlier text.") }
808 follow.bottomChanged(true)
809 guard follow.shouldFollow else { throw LocalError.message("Returning to bottom did not restore following.") }
810 follow.scrollPhaseChanged(isUserScrolling: true); follow.bottomChanged(true)
811 guard !follow.shouldFollow else { throw LocalError.message("Dragging at the bottom must still suspend following.") }
812 follow.scrollPhaseChanged(isUserScrolling: false)
813 guard follow.shouldFollow else { throw LocalError.message("Finishing a scroll at bottom must resume following.") }
814 print("PASS: compact Mac controls allow browsing during capture; speech stays on its note; pause/continue/stop save correctly without changing the browsed note; manual scrolling suspends following until the bottom.")
815 }
816 @MainActor private static func verifyRecordingControlLayout() async throws {
817 let original = ThemeManager.shared.currentAppearanceMode
818 defer { ThemeManager.shared.setAppearanceMode(original) }
819 for mode in [AppearanceMode.dark, .light] {
820 ThemeManager.shared.setAppearanceMode(mode)
821 var sizes: [NSSize] = []
822 for timer in ["0m 28s", "180m 00s"] {
823 let host = NSHostingView(rootView: MacTranscriptionControls(timerText: timer, isPaused: timer == "180m 00s", onPause: {}, onStop: {}))
824 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 90),
825 styleMask: [.borderless], backing: .buffered, defer: false)
826 window.isReleasedWhenClosed = false; window.contentView = host; window.orderFrontRegardless()
827 try await Task.sleep(for: .milliseconds(100))
828 sizes.append(host.fittingSize)
829 window.close()
830 }
831 guard sizes[0].height == 52, sizes[1].height == 52, sizes[0].width >= 200 && sizes[0].width < 400, sizes[1].width >= sizes[0].width else {
832 throw LocalError.message("Recording controls compressed Stop or failed to grow for a longer timer: \(sizes)")
833 }
834 }
835 print("PASS: actual recording controls retain 52-point height and fit long timers in light and dark mode.")
836 }
837 @MainActor private static func previewRecordingControls() {
838 let app = NSApplication.shared
839 app.setActivationPolicy(.regular)
840 let delegate = RecordingLayoutDelegate(); app.delegate = delegate
841 ThemeManager.shared.setAppearanceMode(.dark)
842 app.appearance = NSAppearance(named: .darkAqua)
843 let store = LocalAppModel.shared.store!
844 let recorder = ProcessTapRecorder()
845 var speech = LocalTranscript()
846 for index in 1...30 {
847 speech.accept(text: "Segment \(index). This synthetic passage checks that you can read earlier text without incoming words pulling your scroll position away.", start: Double(index * 15), end: Double(index * 15 + 8), final: true)
848 }
849 recorder.simulatedStart = { _, _, _ in recorder.beginSimulatedLiveTranscription(speech) }
850 let model = NotesListViewModel(viewContext: store.context, recorder: recorder, persistenceController: store)
851 _ = try! store.create(title: "Another note", text: "You can browse this note while transcription continues.")
852 let host = NSHostingView(rootView: MacTranscriptionPreviewRoot(model: model))
853 let window = NSWindow(contentRect: NSRect(x: 200, y: 100, width: 840, height: 760),
854 styleMask: [.titled, .closable], backing: .buffered, defer: false)
855 window.title = "Jotley Transcription Preview"; window.isReleasedWhenClosed = false
856 window.contentView = host; window.makeKeyAndOrderFront(nil)
857 app.activate(ignoringOtherApps: true)
858 Task { await model.startNewNote() }
859 withExtendedLifetime(delegate) { app.run() }
860 }
861 @MainActor private static func verifySummaryFooter() async throws {
862 let store = try SharedPersistenceController(inMemory: true)
863 let note = try store.create(title: "Untitled Note",
864 text: "Maya will test the microphone by Friday. Sam will verify the summary templates before launch.") as! Note
865 let model = NotesListViewModel(viewContext: store.context, recorder: ProcessTapRecorder(), persistenceController: store)
866 ThemeManager.shared.setAppearanceMode(.light)
867 ThemeManager.shared.currentThemeColor = .magenta
868 UserDefaults.standard.set(true, forKey: LocalNoteOrganizationSettings.autoTagsKey)
869 UserDefaults.standard.set(true, forKey: "showTags")
870 let host = NSHostingView(rootView: NoteDetailPlaceholderView(note: note,
871 selectedTab: Binding(get: { model.selectedDetailTab }, set: { model.selectedDetailTab = $0 }), viewModel: model)
872 .environmentObject(store).environment(\.managedObjectContext, store.context).environment(\.colorScheme, .light))
873 host.frame = CGRect(x: 0, y: 0, width: 820, height: 640)
874 let window = NSWindow(contentRect: host.frame, styleMask: [.titled], backing: .buffered, defer: false)
875 window.appearance = NSAppearance(named: .aqua)
876 window.contentView = host
877 func capture(_ label: String) async throws {
878 try await Task.sleep(for: .milliseconds(300))
879 host.layoutSubtreeIfNeeded()
880 guard let bitmap = host.bitmapImageRepForCachingDisplay(in: host.bounds) else {
881 throw LocalError.message("Cannot capture Mac summary footer.")
882 }
883 host.cacheDisplay(in: host.bounds, to: bitmap)
884 guard let png = bitmap.representation(using: .png, properties: [:]) else {
885 throw LocalError.message("Cannot encode Mac summary footer.")
886 }
887 print("MAC_PROOF_\(label)=\(png.base64EncodedString())")
888 }
889 model.selectedDetailTab = DetailTab.transcript.rawValue
890 try await capture("BEFORE")
891 let locale = Locale(identifier: UserDefaults.standard.string(forKey: "transcriptionLanguage") ?? "en-US")
892 if let reason = LocalSummary.readiness(locale: locale) {
893 print("Mac Apple model unavailable: \(reason)")
894 model.simulatedSummaryGeneration = { _ in "Maya tests the microphone by Friday. Sam verifies the summary templates before launch." }
895 model.simulatedOrganization = { _, _ in LocalNoteOrganization(tags: ["Microphone", "Templates", "Launch"], folder: .work) }
896 }
897 await model.generateSummary(note: note, templateKey: LocalSummaryTemplate.auto.key)
898 guard note.hasMeaningfulSummaryText, note.title != "Untitled Note", note.tagNames.count == 3 else {
899 throw LocalError.message("Mac title, summary, and three tags must be saved together.")
900 }
901 model.selectedDetailTab = DetailTab.summary.rawValue
902 try await capture("AFTER")
903 print("PASS: Mac saved its title, summary and three tags together.")
904 }
905
906 @MainActor private static func previewCompletedTranscript() {
907 let app = NSApplication.shared
908 app.setActivationPolicy(.regular)
909 let delegate = RecordingLayoutDelegate(); app.delegate = delegate
910 ThemeManager.shared.setAppearanceMode(.dark)
911 ThemeManager.shared.currentThemeColor = .magenta
912 app.appearance = NSAppearance(named: .darkAqua)
913 let store = LocalAppModel.shared.store!
914 let utterances: [TranscriptUtterance] = (1...30).map { index in
915 let text = index == 30
916 ? "Final passage: these completed words must remain fully readable above the footer gradient and Continue Transcription button."
917 : "Passage \(index). Review the complete transcript at your own pace, then ask questions about the note or export its summary."
918 return TranscriptUtterance(text: text, start: Double(index * 10), end: Double(index * 10 + 7))
919 }
920 let note = try! store.create(title: "Completed transcript layout", text: utterances.map(\.text).joined(separator: "\n\n")) as! Note
921 note.setTranscriptUtterances(utterances)
922 note.summary = "## Summary\n\n- Review the completed transcript.\n- Export a summary as PDF."
923 // Historical metadata must not revive the retired saved-audio action.
924 note.sourceURL = "Recordings/legacy-preview.m4a"
925 try! store.save()
926 defer { try? store.deleteNote(note) }
927 let model = NotesListViewModel(viewContext: store.context, recorder: ProcessTapRecorder(), persistenceController: store)
928 model.selectedNoteIDs = [note.objectID]; model.selectedDetailTab = DetailTab.transcript.rawValue
929 let host = NSHostingView(rootView: NoteDetailPlaceholderView(note: note, selectedTab: Binding(get: { model.selectedDetailTab }, set: { model.selectedDetailTab = $0 }), viewModel: model)
930 .environmentObject(store).environment(\.managedObjectContext, store.context))
931 let window = NSWindow(contentRect: NSRect(x: 200, y: 100, width: 760, height: 700), styleMask: [.titled, .closable], backing: .buffered, defer: false)
932 window.title = "Jotley Detail Fixes Preview"; window.isReleasedWhenClosed = false
933 window.contentView = host; window.makeKeyAndOrderFront(nil)
934 app.activate(ignoringOtherApps: true)
935 withExtendedLifetime(delegate) { app.run() }
936 }
937
938 @MainActor private static func previewSummaryProgress() {
939 let app = NSApplication.shared
940 app.setActivationPolicy(.regular)
941 let delegate = RecordingLayoutDelegate(); app.delegate = delegate
942 ThemeManager.shared.setAppearanceMode(.dark)
943 ThemeManager.shared.currentThemeColor = .purple
944 app.appearance = NSAppearance(named: .darkAqua)
945 let store = LocalAppModel.shared.store!
946 let note = try! store.create(title: "Weekly project review", text: "The team will review the design on Friday and prepare the next release together.") as! Note
947 let model = NotesListViewModel(viewContext: store.context, recorder: ProcessTapRecorder(), persistenceController: store)
948 model.selectedNoteIDs = [note.objectID]; model.selectedDetailTab = DetailTab.summary.rawValue
949 model.simulatedSummaryGeneration = { _ in try await Task.sleep(for: .seconds(3600)); return "Unused preview result" }
950 let host = NSHostingView(rootView: NoteDetailPlaceholderView(note: note, selectedTab: Binding(get: { model.selectedDetailTab }, set: { model.selectedDetailTab = $0 }), viewModel: model)
951 .environmentObject(store).environment(\.managedObjectContext, store.context))
952 let window = NSWindow(contentRect: NSRect(x: 200, y: 100, width: 760, height: 680), styleMask: [.titled, .closable], backing: .buffered, defer: false)
953 window.title = "Jotley Summary Progress Preview"; window.isReleasedWhenClosed = false
954 window.contentView = host; window.makeKeyAndOrderFront(nil)
955 app.activate(ignoringOtherApps: true)
956 Task {
957 let generation = Task { await model.generateSummary(note: note, templateKey: "Concise") }
958 for _ in 0..<100 { if model.isGeneratingSummary { break }; try? await Task.sleep(for: .milliseconds(10)) }
959 model.streamingSummaryViewModel.progress = .writing
960 await generation.value
961 }
962 withExtendedLifetime(delegate) { app.run() }
963 }
964 /// Renders the real Settings view offscreen (works while the Mac is locked) and saves the
965 /// General and About sections to its container's temporary folder. Launch with JOTLEY_SCREENSHOT_DATA and JOTLEY_SCREENSHOT_SETTINGS=general.
966 @MainActor private static func snapshotSettingsAbout(to path: String) {
967 let app = NSApplication.shared
968 app.setActivationPolicy(.accessory)
969 ThemeManager.shared.setAppearanceMode(.light)
970 app.appearance = NSAppearance(named: .aqua)
971 guard let base = LocalAppModel.shared.store,
972 let store = try? SharedPersistenceController(inMemory: true, model: base.container.managedObjectModel) else {
973 fputs("FAIL: settings store unavailable\n", stderr); exit(1)
974 }
975 let size = NSSize(width: 1160, height: 780)
976 let window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.titled], backing: .buffered, defer: false)
977 let host = NSHostingView(rootView: SettingsView().environmentObject(store)
978 .environment(\.managedObjectContext, store.context))
979 window.contentView = host
980 window.orderBack(nil)
981 Task { @MainActor in
982 try? await Task.sleep(for: .seconds(3))
983 host.layoutSubtreeIfNeeded()
984 guard let bitmap = host.bitmapImageRepForCachingDisplay(in: host.bounds) else { exit(1) }
985 host.cacheDisplay(in: host.bounds, to: bitmap)
986 // The sandboxed harness can only write inside its container; print where the file landed.
987 let output = FileManager.default.temporaryDirectory.appending(path: URL(fileURLWithPath: path).lastPathComponent)
988 do { try bitmap.representation(using: .png, properties: [:])?.write(to: output) }
989 catch { fputs("FAIL: \(error.localizedDescription)\n", stderr); exit(1) }
990 print("PASS: wrote \(output.path)")
991 exit(0)
992 }
993 app.run()
994 }
995 @MainActor private static func verifyTranscriptRevisions(note: Note) throws {
996 guard let context = note.managedObjectContext else { throw LocalError.message("Missing fixture context.") }
997 for revision in 0..<100 {
998 let text = "Revision \(revision) " + String(repeating: "你好📝", count: 128)
999 note.transcription = text
1000 note.setTranscriptUtterances([TranscriptUtterance(id: "fixture", text: text, start: 12, end: 14, speaker: 3, confidence: 0.88)])
1001 let display = note.transcriptUtterances
1002 guard display.count == 1, display[0].text == text, display[0].start == 12,
1003 display[0].end == 14, display[0].speaker == 3, display[0].confidence == 0.88 else {
1004 throw LocalError.message("A transcript revision returned stale text or timing metadata.")
1005 }
1006 }
1007 try context.save()
1008 let expected = note.transcriptUtterances
1009 let otherContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
1010 otherContext.persistentStoreCoordinator = context.persistentStoreCoordinator
1011 guard let other = try otherContext.existingObject(with: note.objectID) as? Note else {
1012 throw LocalError.message("Second-context fixture missing.")
1013 }
1014 other.transcription = "Unsaved text from another context."
1015 other.setTranscriptUtterances([TranscriptUtterance(text: other.transcription!, start: 42, end: 44)])
1016 guard other.transcriptUtterances.first?.start == 42, note.transcriptUtterances == expected else {
1017 throw LocalError.message("A different context replaced this note's display data.")
1018 }
1019 note.transcription = "Fresh manual fallback."
1020 note.setTranscriptUtterances([])
1021 guard note.transcriptUtterances.map(\.text) == ["Fresh manual fallback."] else {
1022 throw LocalError.message("Clearing structured transcript left stale display text.")
1023 }
1024 note.transcription = "Updated fallback after unreadable metadata."
1025 note.setValue("{", forKey: "transcriptUtterancesJSON")
1026 guard note.transcriptUtterances.map(\.text) == [note.transcription!] else {
1027 throw LocalError.message("Unreadable metadata reused an obsolete display revision.")
1028 }
1029 context.rollback()
1030 guard note.transcriptUtterances == expected else { throw LocalError.message("Rollback did not restore displayed transcript metadata.") }
1031 print("PASS: repeated Unicode transcript revisions, independent contexts, clearing, unreadable metadata and rollback display current content.")
1032 }
1033 @MainActor private static func verifySummaryObserverLifetime(note: Note) async throws {
1034 _ = NSApplication.shared
1035 let state = SummaryObserverState()
1036 let host = NSHostingView(rootView: AnyView(SummaryObserverView(note: note, state: state)))
1037 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 700, height: 500),
1038 styleMask: [.borderless], backing: .buffered, defer: false)
1039 window.isReleasedWhenClosed = false; window.contentView = host
1040 window.orderFrontRegardless()
1041 defer { window.close() }
1042 try await Task.sleep(for: .milliseconds(350))
1043 NotificationCenter.default.post(name: Notification.Name("SummaryGenerationComplete"), object: nil,
1044 userInfo: ["noteID": note.objectID, "summary": "Mounted summary result."])
1045 try await Task.sleep(for: .milliseconds(100))
1046 state.generating = true
1047 try await Task.sleep(for: .milliseconds(450))
1048 guard state.generating else {
1049 throw LocalError.message("An earlier completion reset a newer summary generation.")
1050 }
1051 guard state.summary == "Mounted summary result." else {
1052 throw LocalError.message("The mounted summary observer fixture did not receive completion.")
1053 }
1054 host.rootView = AnyView(EmptyView())
1055 try await Task.sleep(for: .milliseconds(350))
1056 NotificationCenter.default.post(name: Notification.Name("SummaryGenerationComplete"), object: nil,
1057 userInfo: ["noteID": note.objectID, "summary": "Retired summary result."])
1058 try await Task.sleep(for: .milliseconds(450))
1059 guard state.summary == "Mounted summary result." else {
1060 throw LocalError.message("A retired Mac summary view still receives completion notifications.")
1061 }
1062 print("PASS: summary completion preserves a newer generation and retired views release subscriptions.")
1063 }
1064 @MainActor private static func verifySummaryPresentation(note: Note) async throws {
1065 let fenced = "```markdown\n# Meeting Notes\n\n**Decision:** Keep the original app.\n- Record live audio.\n```"
1066 let expected = "# Meeting Notes\n\n**Decision:** Keep the original app.\n- Record live audio."
1067 guard LocalSummary.markdownForDisplay(fenced) == expected,
1068 LocalSummary.markdownForDisplay("```md\n# Streaming") == "# Streaming",
1069 LocalSummary.markdownForDisplay("# Notes\n```swift\nlet x = 1\n```") == "# Notes\n```swift\nlet x = 1\n```" else {
1070 throw LocalError.message("Summary normalization lost formatting or intentional code.")
1071 }
1072 let state = SummaryObserverState(); state.summary = fenced
1073 let host = NSHostingView(rootView: AnyView(SummaryObserverView(note: note, state: state)))
1074 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 700, height: 500),
1075 styleMask: [.titled], backing: .buffered, defer: false)
1076 // A titled window can become key, so text focus behaves as it does in the app.
1077 window.isReleasedWhenClosed = false; window.contentView = host; window.makeKeyAndOrderFront(nil)
1078 defer { window.close() }
1079 func textViews(_ view: NSView) -> [NSTextView] {
1080 (view as? NSTextView).map { [$0] } ?? view.subviews.flatMap(textViews)
1081 }
1082 try await Task.sleep(for: .milliseconds(350))
1083 // The structured view renders SwiftUI text, so check the sections it draws
1084 // and that no Markdown editor or raw syntax is shown.
1085 let structured = StructuredSummary(ParsedNoteMarkdown.rendering(fenced))
1086 let item = structured.sections.first?.items.first
1087 guard !textViews(host).contains(where: { $0.isEditable }),
1088 structured.sections.map(\.title) == ["Meeting Notes"],
1089 structured.sections.first?.paragraphs.map({ String($0.text.characters) }) == ["Decision: Keep the original app."],
1090 item.map({ String($0.body.characters) }) == "Record live audio." else {
1091 throw LocalError.message("Fenced summary displayed as code instead of formatted text.")
1092 }
1093 state.summary = "## Summary\nKeep the original app.\n\n## Key Points\n- Record live audio."
1094 try await Task.sleep(for: .milliseconds(200))
1095 state.inlineEdit = 1
1096 try await Task.sleep(for: .milliseconds(350))
1097 guard state.inlineEdit == 0, state.rawMarkdown else {
1098 throw LocalError.message("Explicit summary editing was not consumed.")
1099 }
1100 // Edit the Markdown the way a person types it, then leave the editor.
1101 guard let editor = textViews(host).first(where: { $0.isEditable }),
1102 editor.string.contains("- Record live audio.") else {
1103 throw LocalError.message("The summary editor did not show the Markdown.")
1104 }
1105 window.makeFirstResponder(editor)
1106 let end = NSRange(location: (editor.string as NSString).length, length: 0)
1107 let addition = "\n\n## Action Items\n- **Maya**: Share the edited summary."
1108 if editor.shouldChangeText(in: end, replacementString: addition) {
1109 editor.textStorage?.replaceCharacters(in: end, with: addition)
1110 editor.didChangeText()
1111 }
1112 try await Task.sleep(for: .milliseconds(350))
1113 try await Task.sleep(for: .milliseconds(350))
1114 let edited = StructuredSummary(ParsedNoteMarkdown.rendering(state.summary))
1115 let editedItem = edited.sections.last?.items.first
1116 let editedLabel = editedItem?.label.map { String($0.characters) }
1117 let editedBody = editedItem.map { String($0.body.characters) }
1118 guard edited.sections.last?.title == "Action Items",
1119 editedLabel == "Maya", editedBody == "Share the edited summary." else {
1120 throw LocalError.message("Typed summary Markdown was not saved as structured sections: label=\(editedLabel ?? "nil") body=\(editedBody ?? "nil") sections=\(edited.sections.map(\.title))")
1121 }
1122 print("PASS: Markdown typed into the Mac summary editor is saved and parses into structured sections.")
1123 let longLine = "- Keep decisions and action items in the project notes so people can find them after the review."
1124 let longAddition = "\n" + Array(repeating: longLine, count: 30).joined(separator: "\n") + "\n"
1125 let insertion = NSRange(location: editor.string.utf16.count, length: 0)
1126 editor.insertText(longAddition, replacementRange: insertion)
1127 try await Task.sleep(for: .milliseconds(350))
1128 func verifyEditorFits() throws -> CGFloat {
1129 host.layoutSubtreeIfNeeded()
1130 guard let manager = editor.layoutManager, let container = editor.textContainer else {
1131 throw LocalError.message("Missing summary editor text layout.")
1132 }
1133 manager.ensureLayout(for: container)
1134 let contentHeight = max(manager.usedRect(for: container).maxY, manager.extraLineFragmentRect.maxY)
1135 guard abs(container.containerSize.width - editor.bounds.width) < 1,
1136 abs(ceil(contentHeight) - editor.bounds.height) < 1 else {
1137 throw LocalError.message("Summary editor bounds \(editor.bounds.size) do not fit the text layout \(container.containerSize.width) × \(contentHeight).")
1138 }
1139 return editor.bounds.height
1140 }
1141 guard state.summary.hasSuffix(longAddition) else {
1142 throw LocalError.message("The long paste did not reach the summary binding.")
1143 }
1144 let wideHeight = try verifyEditorFits()
1145 window.setContentSize(NSSize(width: 450, height: 500))
1146 try await Task.sleep(for: .milliseconds(350))
1147 editor.setSelectedRange(NSRange(location: editor.string.utf16.count - longLine.utf16.count - 1,
1148 length: longLine.utf16.count))
1149 let narrowHeight = try verifyEditorFits()
1150 guard narrowHeight > wideHeight, editor.selectedRange().length == longLine.utf16.count else {
1151 throw LocalError.message("The summary did not reflow or retain the last-line selection.")
1152 }
1153 print("PASS: The Mac summary editor grows for pasted text and fits selected lines after narrowing the window.")
1154 state.summary = fenced
1155 try await Task.sleep(for: .milliseconds(200))
1156 state.generating = true
1157 try await Task.sleep(for: .milliseconds(350))
1158 state.summary = fenced; state.generating = false
1159 try await Task.sleep(for: .milliseconds(350))
1160 guard !state.rawMarkdown, !textViews(host).contains(where: { $0.isEditable }) else {
1161 throw LocalError.message("Template regeneration reopened the Markdown editor.")
1162 }
1163 host.rootView = AnyView(EmptyView())
1164 try await Task.sleep(for: .milliseconds(100))
1165 host.rootView = AnyView(SummaryObserverView(note: note, state: state))
1166 try await Task.sleep(for: .milliseconds(350))
1167 guard !state.rawMarkdown, !textViews(host).contains(where: { $0.isEditable }) else {
1168 throw LocalError.message("Remounting the summary replayed an old edit request.")
1169 }
1170 let originalAppearance = ThemeManager.shared.currentAppearanceMode
1171 defer { ThemeManager.shared.setAppearanceMode(originalAppearance) }
1172 for mode in [AppearanceMode.dark, .light, .dark, .light, .dark, .light] {
1173 ThemeManager.shared.setAppearanceMode(mode)
1174 try await Task.sleep(for: .milliseconds(200))
1175 guard host.fittingSize.height > 60, !textViews(host).contains(where: { $0.isEditable }) else {
1176 throw LocalError.message("Rendered summary disappeared during theme switching.")
1177 }
1178 // The structured view reads these colors on every render.
1179 guard let rgb = NSColor(Color.themeTextPrimary).usingColorSpace(.deviceRGB) else {
1180 throw LocalError.message("Summary text color missing.")
1181 }
1182 let expected: CGFloat = mode == .dark ? 0.85 : 0.1
1183 guard abs(rgb.redComponent - expected) < 0.04,
1184 abs(rgb.greenComponent - expected) < 0.04,
1185 abs(rgb.blueComponent - expected) < 0.04 else {
1186 throw LocalError.message("Summary retained stale color after switching to \(mode.rawValue): \(rgb).")
1187 }
1188 }
1189 print("PASS: six repeated light/dark switches keep the summary rendered with current text colors and never reopen the editor.")
1190 print("PASS: fenced summaries render as formatted text; regeneration and remounting never replay Markdown editing.")
1191 }
1192 @MainActor private static func verifySearchEditingAlignment() throws {
1193 let field = ThemedNSTextField(frame: NSRect(x: 0, y: 0, width: 250, height: 36))
1194 field.cell = ThemedTextFieldCell(textCell: "")
1195 field.isEditable = true; field.isSelectable = true; field.isBordered = false
1196 field.font = .systemFont(ofSize: 14); field.maxDisplayLines = 1; field.configureLineWrapping()
1197 let window = NSWindow(contentRect: field.frame, styleMask: [.borderless], backing: .buffered, defer: false)
1198 window.isReleasedWhenClosed = false; window.contentView = field
1199 defer { window.close() }
1200 window.makeFirstResponder(field)
1201 guard let editor = field.currentEditor() as? NSTextView,
1202 let cell = field.cell as? ThemedTextFieldCell else { throw LocalError.message("Search field editor missing.") }
1203 let drawn = cell.drawingRect(forBounds: field.bounds)
1204 let edited = field.convert(editor.bounds, from: editor)
1205 guard abs(drawn.midY - field.bounds.midY) <= 1,
1206 abs(edited.midY - field.bounds.midY) <= 2 else {
1207 throw LocalError.message("Search drawing/editor are not vertically centered: \(drawn), \(edited).")
1208 }
1209 print("PASS: search text and its active AppKit field editor are centered in the 36-point control.")
1210 }
1211
1212
1213 @MainActor private static func verifyLegacyAudioCleanup() throws {
1214 let app = LocalAppModel.shared
1215 guard Bundle.main.bundleIdentifier == "com.protomota.jotley.mac-routing-tests",
1216 let store = app.store, store.ready,
1217 store.root.path.contains("/com.protomota.jotley.mac-routing-tests/") else {
1218 throw LocalError.message("Audio cleanup checks require the separate test sandbox.")
1219 }
1220 guard try store.notes().isEmpty else { throw LocalError.message("Preserve unexpected test sandbox notes.") }
1221 defer {
1222 for item in store.container.persistentStoreCoordinator.persistentStores { try? store.container.persistentStoreCoordinator.remove(item) }
1223 try? FileManager.default.removeItem(at: store.root)
1224 }
1225 let kept = try store.create(title: "Keep cleanup title", text: "Keep cleanup words.")
1226 guard let id = kept.localNoteID else { throw LocalError.message("Cleanup fixture has no ID.") }
1227 for name in ["Recordings/\(id.uuidString)/segment", "DeletedRecordings/\(id.uuidString)"] {
1228 let directory = store.root.appendingPathComponent(name)
1229 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
1230 try Data(repeating: 0, count: 64000).write(to: directory.appendingPathComponent("audio.float32"))
1231 }
1232 try LegacyAudioCleanup.remove(in: store.root); try LegacyAudioCleanup.remove(in: store.root)
1233 guard try store.notes().count == 1, kept.text("title") == "Keep cleanup title",
1234 kept.text("transcription") == "Keep cleanup words.",
1235 !FileManager.default.fileExists(atPath: store.root.appendingPathComponent("Recordings").path),
1236 !FileManager.default.fileExists(atPath: store.root.appendingPathComponent("DeletedRecordings").path) else {
1237 throw LocalError.message("Legacy Mac audio cleanup kept audio or changed note content.")
1238 }
1239 print("PASS: audio saved by earlier Mac versions is removed while notes and transcripts are kept.")
1240 }
1241}
1242#else
1243import XCTest
1244
1245final class JotleyLocalUITests: XCTestCase {
1246 @MainActor func testNotesTrash() {
1247 continueAfterFailure = false
1248 let app = XCUIApplication()
1249 app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = #"[{"title":"Friday launch plan","folder":"Work","tags":["Launch"],"transcript":"Confirm Friday’s launch checklist.","summary":"The checklist is ready."}]"#
1250 app.launchArguments = ["-AppleLanguages", "(en)", "-jotleyWelcomeCompleted.v1", "YES", "-selectedAppearanceMode", "Light"]
1251 app.launch()
1252 let trash = app.buttons["notesTrashLink"]
1253 if !trash.waitForExistence(timeout: 3) { app.typeKey("0", modifierFlags: [.command, .option]) }
1254 XCTAssertTrue(trash.waitForExistence(timeout: 10))
1255 let window = app.windows.firstMatch
1256 capture(window, named: "mac-trash-01-notes-list")
1257 let title = app.staticTexts["noteDetailTitle"]
1258 XCTAssertTrue(title.waitForExistence(timeout: 5))
1259 app.buttons["noteDetailMoreMenuButton"].click()
1260 app.buttons["noteDetailMoveToTrash"].click()
1261 XCTAssertTrue(title.waitForNonExistence(timeout: 5))
1262 trash.click()
1263 let done = app.buttons["notesTrashDone"]
1264 XCTAssertTrue(done.waitForExistence(timeout: 5))
1265 capture(window, named: "mac-trash-02-management")
1266 app.buttons["notesEmptyTrash"].click()
1267 let empty = app.buttons.matching(identifier: "Empty Trash").firstMatch
1268 XCTAssertTrue(empty.waitForExistence(timeout: 5))
1269 empty.click()
1270 XCTAssertTrue(app.staticTexts["Trash Is Empty"].waitForExistence(timeout: 5))
1271 }
1272
1273 @MainActor func testSettingsHaveNoSupportOrFeedbackLinks() {
1274 continueAfterFailure = false
1275 let app = XCUIApplication()
1276 app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = #"[{"title":"Launch planning","folder":"Work","tags":[],"transcript":"Review the next steps.","summary":"Share the launch plan."}]"#
1277 app.launchArguments = ["-AppleLanguages", "(en)", "-jotleyWelcomeCompleted.v1", "YES", "-selectedAppearanceMode", "Dark"]
1278 app.launch()
1279 let settings = app.buttons["notesListSettingsButton"]
1280 if !settings.waitForExistence(timeout: 3) { app.typeKey("0", modifierFlags: [.command, .option]) }
1281 XCTAssertTrue(settings.waitForExistence(timeout: 10))
1282 settings.click()
1283 let mcp = app.buttons["settingsMCPSection"]
1284 XCTAssertTrue(mcp.waitForExistence(timeout: 10))
1285 for id in ["settingsAppHelp", "settingsSupportReminderCard", "settingsSupportJotleyCard", "settingsAtomProduct"] {
1286 XCTAssertFalse(app.descendants(matching: .any)[id].exists, id)
1287 }
1288 mcp.click()
1289 XCTAssertFalse(app.buttons["settingsAppHelp"].exists)
1290 XCTAssertFalse(app.menuItems["Send Feedback…"].exists)
1291 capture(app.windows.firstMatch, named: "mac-settings-no-support-links")
1292 }
1293
1294 @MainActor func testLocalizedStorefrontCaptures() throws {
1295 guard let fixture = ProcessInfo.processInfo.environment["JOTLEY_STORE_SCREENSHOT_FIXTURE"] else {
1296 throw XCTSkip("Run scripts/capture-app-store.py to supply localized fixtures.")
1297 }
1298 struct CaptureLocale: Decodable {
1299 let notes: String
1300 let region: String
1301 let transcriptLabel: String
1302 let foldersLabel: String
1303 }
1304 let locales = try JSONDecoder().decode([String: CaptureLocale].self, from: Data(fixture.utf8))
1305 continueAfterFailure = false
1306 let app = XCUIApplication()
1307 for (locale, sample) in locales.sorted(by: { $0.key < $1.key }) {
1308 app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = sample.notes
1309 app.launchArguments = [
1310 "-AppleLanguages", "(\(locale))", "-AppleLocale", sample.region,
1311 "-jotleyWelcomeCompleted.v1", "YES", "-selectedThemeColor", "Purple",
1312 "-selectedAppearanceMode", "Light", "-jotleyCompletedLocalSummaries", "0",
1313 "-AppleWindowTabbingMode", "manual"
1314 ]
1315 app.launch()
1316 let window = app.windows.firstMatch
1317 if !window.waitForExistence(timeout: 2) {
1318 app.typeKey("0", modifierFlags: [.command, .option])
1319 }
1320 XCTAssertTrue(window.waitForExistence(timeout: 10), locale)
1321 XCTAssertEqual(window.frame.width, 1080, accuracy: 2, locale)
1322 XCTAssertEqual(window.frame.height, 720, accuracy: 2, locale)
1323 let transcript = app.buttons["noteDetailTranscriptTab"]
1324 XCTAssertTrue(transcript.waitForExistence(timeout: 10), locale)
1325 XCTAssertEqual(transcript.label, sample.transcriptLabel, locale)
1326 XCTAssertTrue(app.staticTexts["noteDetailTitle"].exists, locale)
1327 let folders = app.buttons.matching(NSPredicate(format: "label == %@", sample.foldersLabel)).firstMatch
1328 let manage = app.buttons["notesListManageFoldersButton"]
1329 if manage.exists {
1330 folders.click()
1331 XCTAssertTrue(manage.waitForNonExistence(timeout: 5), locale)
1332 }
1333 capture(window, named: "\(locale)-01-summary")
1334
1335 transcript.click()
1336 XCTAssertTrue(app.staticTexts["00:00"].waitForExistence(timeout: 5), locale)
1337 capture(window, named: "\(locale)-02-transcript")
1338
1339 app.buttons["noteDetailSummaryTab"].click()
1340 if !manage.exists { folders.click() }
1341 XCTAssertTrue(manage.waitForExistence(timeout: 5), locale)
1342 capture(window, named: "\(locale)-03-folders")
1343 app.terminate()
1344 }
1345 }
1346
1347 private func capture(_ window: XCUIElement, named name: String) {
1348 let attachment = XCTAttachment(screenshot: window.screenshot())
1349 attachment.name = "JotleyStore-\(name)"
1350 attachment.lifetime = .keepAlways
1351 add(attachment)
1352 }
1353
1354 func testOriginalInterfaceCreatesAndPersistsLocalNoteWithoutAccount() {
1355 let app = XCUIApplication()
1356 app.launch()
1357 XCTAssertTrue(app.textFields["notesListSearchField"].waitForExistence(timeout: 15))
1358 let filter = app.buttons["notesListTagFilterButton"]
1359 XCTAssertEqual(filter.frame.width, 36, accuracy: 1)
1360 // SwiftUI/macOS accessibility height includes toolbar/container extents.
1361 // Compare visible heights in the app; the square filter width is reliable.
1362 XCTAssertTrue(app.toolbars.buttons["Hide Sidebar"].exists)
1363 XCTAssertFalse(app.buttons["Sign in"].exists)
1364 let count = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "notesListNoteRow-")).count
1365 app.menuBars.menuBarItems["File"].click()
1366 app.menuItems["New Note"].click()
1367 XCTAssertTrue(app.buttons["notesListNoteRow-\(count)"].waitForExistence(timeout: 5), "New Note must create an additional note")
1368 let title = app.textFields["noteDetailTitle"]
1369 XCTAssertTrue(title.waitForExistence(timeout: 5))
1370 let name = "Local UI check " + UUID().uuidString
1371 title.click()
1372 title.typeKey("a", modifierFlags: .command)
1373 title.typeText(name)
1374 title.typeKey(.return, modifierFlags: [])
1375 title.typeKey(.tab, modifierFlags: [])
1376 XCTAssertTrue(app.buttons["notesListNoteRow-0"].exists)
1377 app.terminate()
1378 app.launch()
1379 let search = app.textFields["notesListSearchField"]
1380 XCTAssertTrue(search.waitForExistence(timeout: 15))
1381 search.click(); search.typeText(name)
1382 XCTAssertTrue(app.buttons["notesListNoteRow-0"].waitForExistence(timeout: 5))
1383 XCTAssertFalse(app.buttons["Sign in"].exists)
1384 }
1385}
1386#endif