import XCTest import ObjectiveC #if DEBUG import FoundationModels #endif // Video capture take for the Jotley App Store / tutorial footage (copied into Jotley-iOSUITests by // record_ui.sh, removed again afterwards). One continuous take: open the untitled photo-walk note, choose a // template, Generate Summary at real speed with the on-device model, then ask two Ask AI questions. // Pauses are human-paced so the screen recording reads; nothing is simulated or sped up. // Prints "CAPTURE-MARK " so the recorder can cut the take into clips. final class JotleyVideoCaptureUITests: XCTestCase { // Capture-only runner adjustment: native glass animations remain enabled, while // XCTest does not wait 60 seconds for each continuously animated view to become idle. // Explicit element and model-result waits below still govern every action. private static let captureIdleWaits: Void = { guard let cls = NSClassFromString("XCUIApplicationProcess") else { return } let one = NSSelectorFromString("waitForQuiescenceIncludingAnimationsIdle:") if let method = class_getInstanceMethod(cls, one) { let block: @convention(block) (AnyObject, Bool) -> Void = { _, _ in } method_setImplementation(method, imp_implementationWithBlock(block)) } let two = NSSelectorFromString("waitForQuiescenceIncludingAnimationsIdle:isPreEvent:") if let method = class_getInstanceMethod(cls, two) { let block: @convention(block) (AnyObject, Bool, Bool) -> Void = { _, _, _ in } method_setImplementation(method, imp_implementationWithBlock(block)) } }() override func setUpWithError() throws { continueAfterFailure = false _ = Self.captureIdleWaits } // xcodebuild does not forward the runner's stdout, so marks also go to the file record_ui.sh names // (passed as TEST_RUNNER_CAPTURE_MARKS; simulator processes can write to the Mac's file system). private func mark(_ name: String) { let line = String(format: "CAPTURE-MARK %@ %.3f\n", name, Date().timeIntervalSince1970) print(line, terminator: "") guard let path = ProcessInfo.processInfo.environment["CAPTURE_MARKS"] else { return } if let handle = FileHandle(forWritingAtPath: path) { handle.seekToEndOfFile(); handle.write(Data(line.utf8)); try? handle.close() } else { try? line.write(toFile: path, atomically: true, encoding: .utf8) } } private func pause(_ seconds: Double) { Thread.sleep(forTimeInterval: seconds) } #if DEBUG @MainActor func testCaptureSummaryAndAskAI() throws { guard case .available = SystemLanguageModel.default.availability else { throw XCTSkip("Apple model is not ready in this simulator") } let env = ProcessInfo.processInfo.environment let template = env["CAPTURE_TEMPLATE"] ?? "personal-note" XCUIDevice.shared.orientation = env["CAPTURE_ORIENTATION"] == "landscape" ? .landscapeLeft : .portrait let app = XCUIApplication() // Brand purple accent (the argument domain overrides whatever theme the simulator was left on). app.launchArguments = ["-transcriptionLanguage", "en-US", "-selectedThemeColor", env["CAPTURE_THEME"] ?? "Purple"] app.launchEnvironment["JOTLEY_TEST_ENGAGEMENT_COUNT"] = "0" app.launchEnvironment["JOTLEY_SCREENSHOT_APPEARANCE"] = env["CAPTURE_APPEARANCE"] ?? "Dark" // The same words the demo voice speaks in the live-transcription clip, so the clips follow on. // Retired templates (Concise, Study) are only offered on notes already using them, so seed those. let seedTemplate = ["Concise", "Study"].contains(template) ? #","template":"\#(template)""# : "" app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = #""" [{"title":"Untitled","folder":"Personal","tags":[],"transcript":"I want to make a weekend photography guide. On Saturday, I'll test three easy photo walks around town. I'll pick ten favorite images and write a short tip for each one. By Sunday evening, I'll share a first draft with two friends and ask which tips were most useful.","summary":""\#(seedTemplate)}] """# // Optional seed file (CAPTURE_DATA_FILE, a JSON array of notes on the Mac's disk) replaces the default note. if let path = env["CAPTURE_DATA_FILE"], !path.isEmpty, let seed = try? String(contentsOfFile: path, encoding: .utf8) { app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = seed } app.launch() // Since build 5f48c48 the app keeps a note selected, so iPhone opens straight onto the note; older builds // (and a visible iPad sidebar) show the list row first. Same pacing either way, so the cut marks line up. let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'notesListNoteRow-'")).firstMatch let generate = app.buttons["noteDetailGenerateSummaryButton"] let openBy = Date().addingTimeInterval(20) while !row.exists && !generate.exists && Date() < openBy { pause(0.25) } pause(2.0) mark("list") if row.exists && row.isHittable && !generate.exists { row.tap() } XCTAssertTrue(generate.waitForExistence(timeout: 10)) pause(1.5) // Summary: template, then Generate Summary at real speed. mark("summary-start") let templates = app.buttons["noteDetailTemplatesButton"] templates.tap() let choice = app.buttons["noteTemplate-\(template)"] XCTAssertTrue(choice.waitForExistence(timeout: 5)) pause(1.4) choice.tap() pause(1.2) mark("generate-tap") generate.tap() let title = app.staticTexts["noteDetailTitle"] let titled = expectation(for: NSPredicate(format: "exists == true AND label != 'Untitled'"), evaluatedWith: title) // 2.2 footer: Generate gives way to Cancel Generation, then to an enabled Ask AI once the summary is saved. let finished = expectation(for: NSPredicate(format: "exists == true AND enabled == true"), evaluatedWith: app.buttons["noteDetailSummaryAskAIButton"]) wait(for: [titled, finished], timeout: 180) mark("summary-done") XCTAssertFalse(app.alerts.firstMatch.exists, app.debugDescription) pause(Double(env["CAPTURE_TOP_PAUSE"] ?? "") ?? 2.0) // the marketing film scrolls up straight away // The summary follows the text as it streams in; scroll back up to the new title, like a person would. let content = app.descendants(matching: .any).matching(identifier: "noteDetailSummaryContent").firstMatch _ = content for _ in 0..<3 { // a plain finger drag: long summaries render as several sections app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.35)) .press(forDuration: 0.05, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.9))) pause(0.5) } mark("summary-top") pause(3.5) let summaryShot = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) summaryShot.name = "capture-summary"; summaryShot.lifetime = .keepAlways; add(summaryShot) mark("summary-end") // Ask AI: two typed questions, answered by the on-device model. let ask = app.buttons["noteDetailSummaryAskAIButton"] XCTAssertTrue(ask.waitForExistence(timeout: 5)) pause(0.6) mark("ask-start") ask.tap() // 2.2: the question box is a multiline UITextView (Send return key), so match it by identifier of any type. let field = app.descendants(matching: .any).matching(identifier: "askAIQuestionField").firstMatch XCTAssertTrue(field.waitForExistence(timeout: 10)) pause(1.5) let copy = app.buttons["askAICopyConversationButton"] let q = { (k: String) in env[k].flatMap { $0.isEmpty ? nil : $0 } } let questions = [q("CAPTURE_Q1") ?? "What should I finish by Sunday?", q("CAPTURE_Q2") ?? "What should I do on Saturday?"] for (index, question) in questions.enumerated() { field.tap() pause(0.6) field.typeText(question) pause(0.9) mark("ask-send-\(index + 1)") // iPad's form sheet can expose more than one match; tap the one actually on screen. let sends = app.buttons.matching(identifier: "askAISendButton").allElementsBoundByIndex let send = sends.first { $0.isHittable && $0.isEnabled } ?? sends.first { $0.isHittable } ?? app.buttons["askAISendButton"] send.tap() if field.value as? String == question { pause(0.5); send.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap() } // The conversation Copy button is enabled once the answer has finished. pause(1.0) let answered = expectation(for: NSPredicate(format: "enabled == YES"), evaluatedWith: copy) wait(for: [answered], timeout: 120) mark("ask-answer-\(index + 1)") pause(3.5) } if app.keyboards.firstMatch.exists { app.swipeDown(velocity: .slow) } pause(2.5) let askShot = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) askShot.name = "capture-ask-ai"; askShot.lifetime = .keepAlways; add(askShot) mark("ask-end") pause(1.0) guard env["CAPTURE_ORGANIZE"] != "0" else { return } // Organize: tag the note, share it (More Export Options), then search for the tag (iPhone). app.buttons["askAIDoneButton"].tap() XCTAssertTrue(ask.waitForExistence(timeout: 5)) pause(1.5) let chipsBefore = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'noteDetailTag-'")).count mark("tag-start") let addTag = app.buttons.matching(NSPredicate(format: "label == 'Add Tag'")).firstMatch addTag.tap() let tagField = app.textFields.matching(NSPredicate(format: "identifier == 'addTagTextField' OR identifier == 'Enter tag name' OR placeholderValue == 'Enter tag name'")).firstMatch XCTAssertTrue(tagField.waitForExistence(timeout: 5)) pause(1.0) tagField.tap(); pause(0.4) // Completed summaries now add topic tags (often "photography"), so add one the model won't have chosen. let tag = env["CAPTURE_TAG"].flatMap { $0.isEmpty ? nil : $0 } ?? "Side Project" tagField.typeText(tag) pause(1.0) let save = app.buttons["addTagSaveButton"] let confirm = save.exists ? save : app.buttons.matching(NSPredicate(format: "label == 'Add Tag'")).allElementsBoundByIndex .last { $0.isHittable && $0.isEnabled } XCTAssertNotNil(confirm); confirm?.tap() pause(0.7) if tagField.exists { // Some iPad glass-button taps focus the sheet before activating it. // Submit through the native text field if the sheet is still open. tagField.typeText("\n") pause(0.7) } let chips = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'noteDetailTag-'")) let tagBy = Date().addingTimeInterval(5) while chips.count <= chipsBefore && Date() < tagBy { pause(0.2) } XCTAssertGreaterThan(chips.count, chipsBefore) mark("tag-done") pause(3.0) mark("tag-end") mark("share-start") app.buttons["noteDetailShareButton"].tap() let more = app.buttons["More Export Options"] XCTAssertTrue(more.waitForExistence(timeout: 5)) pause(2.2) more.tap() // The submenu expands in place; its items may surface as buttons or menu items. let summaryOnly = app.descendants(matching: .any).matching(NSPredicate(format: "label == 'Summary Only' OR identifier == 'exportSummaryButton'")).firstMatch if !summaryOnly.waitForExistence(timeout: 5) { print(app.debugDescription) } mark("export-options") pause(3.5) mark("share-end") // Close the menu without exporting. app.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.72)).tap() // empty area, clear of the toolbar pause(1.2) guard UIDevice.current.userInterfaceIdiom == .phone else { return } let back = app.navigationBars.buttons["BackButton"].exists ? app.navigationBars.buttons["BackButton"] : app.navigationBars.buttons.element(boundBy: 0) if app.buttons["exportPlainTextButton"].exists { // menu still open: dismiss it first app.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.72)).tap(); pause(0.8) } if back.isHittable { back.tap() } else { // edge swipe back, like a person would app.coordinate(withNormalizedOffset: CGVector(dx: 0.01, dy: 0.5)) .press(forDuration: 0.05, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.85, dy: 0.5))) } let search = app.descendants(matching: .any)["notesListSearchField"].firstMatch XCTAssertTrue(search.waitForExistence(timeout: 5)) pause(1.5) mark("search-start") search.tap(); pause(0.6) search.typeText(env["CAPTURE_SEARCH"].flatMap { $0.isEmpty ? nil : $0 } ?? "Photo") pause(3.5) mark("search-end") pause(0.5) } @MainActor func testCaptureRealLiveTranscription() throws { let env = ProcessInfo.processInfo.environment XCUIDevice.shared.orientation = env["CAPTURE_ORIENTATION"] == "landscape" ? .landscapeLeft : .portrait let app = XCUIApplication() app.launchArguments = ["-transcriptionLanguage", "en-US", "-selectedThemeColor", "Purple", "-jotleyWelcomeCompleted.v1", "YES"] app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = "[]" app.launchEnvironment["JOTLEY_SCREENSHOT_APPEARANCE"] = "Dark" app.launchEnvironment["JOTLEY_TEST_ENGAGEMENT_COUNT"] = "0" // Real microphone and Apple Speech. No simulated-speech or audio-level hooks. app.launch() let plus = app.buttons["notesListNewNoteButton"].firstMatch XCTAssertTrue(plus.waitForExistence(timeout: 20)); mark("live-list"); pause(1) plus.tap() let pauseButton = app.buttons["transcriptionPauseButton"] XCTAssertTrue(pauseButton.waitForExistence(timeout: 90)) mark("live-ready"); pause(27) let words = app.staticTexts.matching(NSPredicate(format: "label CONTAINS[c] 'photography'")).firstMatch XCTAssertTrue(words.waitForExistence(timeout: 15), "Real demo speech must produce a photography transcript") mark("live-spoken") pauseButton.tap(); mark("live-paused"); pause(1.6) pauseButton.tap(); mark("live-resumed"); pause(1.4) app.buttons["transcriptionStopButton"].tap() XCTAssertTrue(app.staticTexts["noteDetailTitle"].waitForExistence(timeout: 10)) mark("live-stopped"); pause(2) let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) shot.name = "Real-microphone-transcript"; shot.lifetime = .keepAlways; add(shot) mark("live-end") } @MainActor func testCaptureRealSummaryStyles() throws { XCUIDevice.shared.orientation = .portrait let env = ProcessInfo.processInfo.environment let app = XCUIApplication() app.launchArguments = ["-transcriptionLanguage", env["CAPTURE_LANGUAGE"] ?? "en-US", "-selectedThemeColor", "Purple", "-jotleyWelcomeCompleted.v1", "YES"] app.launchEnvironment["JOTLEY_SCREENSHOT_APPEARANCE"] = "Light" app.launchEnvironment["JOTLEY_TEST_ENGAGEMENT_COUNT"] = "0" app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = #"[{"title":"Untitled","folder":"Personal","tags":[],"transcript":"I want to make a weekend photography guide. On Saturday, I'll test three easy photo walks around town. I'll pick ten favorite images and write a short tip for each one. By Sunday evening, I'll share a first draft with two friends and ask which tips were most useful.","summary":""}]"# if let path = env["CAPTURE_DATA_FILE"], !path.isEmpty { app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = try String(contentsOfFile: path, encoding: .utf8) } let dir = URL(fileURLWithPath: env["CAPTURE_STILLS_ROOT"]!) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) func shot(_ name: String) throws { pause(0.6) try XCUIScreen.main.screenshot().pngRepresentation.write(to: dir.appendingPathComponent(name + ".png")) } func library() { let settings = app.buttons["notesListSettingsButton"] if settings.exists && settings.isHittable { return } let back = app.buttons["BackButton"] if back.exists && back.isHittable { back.tap() } else { let sidebar = app.navigationBars.buttons.matching(NSPredicate(format: "label CONTAINS[c] 'sidebar'")).firstMatch XCTAssertTrue(sidebar.waitForExistence(timeout: 5)); sidebar.tap() } XCTAssertTrue(settings.waitForExistence(timeout: 5)) } app.launch() XCUIDevice.shared.orientation = .portrait pause(1) let generate = app.buttons["noteDetailGenerateSummaryButton"] XCTAssertTrue(generate.waitForExistence(timeout: 20)) if env["CAPTURE_LANGUAGE"] == "fr-FR" { try shot("transcript-french") } app.buttons["noteDetailTemplatesButton"].tap() app.buttons["noteTemplate-personal-note"].tap() generate.tap() let ready = expectation(for: NSPredicate(format: "exists == true AND enabled == true"), evaluatedWith: app.buttons["noteDetailSummaryAskAIButton"]) wait(for: [ready], timeout: 180) let title = app.staticTexts["noteDetailTitle"] for _ in 0..<5 where !title.isHittable { app.swipeDown(); pause(0.4) } try app.debugDescription.write(to: dir.appendingPathComponent("real-summary-accessibility.txt"), atomically: true, encoding: .utf8) try shot("summary-purple") if env["CAPTURE_LANGUAGE"] == "fr-FR" { try shot("summary-french"); return } // Each still is a fresh real on-device result in the requested native theme. // Relaunching avoids the platform's inaccessible nested settings menu. for (theme, appearance, name) in [("Orange","Light","orange"),("Magenta","Light","magenta"),("Yellow","Light","yellow"),("Light Blue","Light","blue"),("Neutral","Light","neutral"),("Purple","Dark","dark"),("Purple","Light","purple")] { app.terminate() app.launchArguments = ["-transcriptionLanguage", "en-US", "-selectedThemeColor", theme, "-jotleyWelcomeCompleted.v1", "YES"] app.launchEnvironment["JOTLEY_SCREENSHOT_APPEARANCE"] = appearance app.launch() XCTAssertTrue(generate.waitForExistence(timeout: 20)) app.buttons["noteDetailTemplatesButton"].tap() app.buttons["noteTemplate-personal-note"].tap() generate.tap() let generated = expectation(for: NSPredicate(format: "exists == true AND enabled == true"), evaluatedWith: app.buttons["noteDetailSummaryAskAIButton"]) wait(for: [generated], timeout: 180) for _ in 0..<3 { app.swipeDown(); pause(0.3) } try shot("summary-" + name) } library(); try shot("library") app.buttons["notesListSettingsButton"].tap() let language = app.descendants(matching: .any)["settingsLanguagePicker"].firstMatch if language.exists { language.tap(); try shot("languages") } } #endif }