Branchwell

Jotley / website · jotley.ai / scripts / video-refresh / JotleyVideoCaptureUITests.swift

Raw 19.5 KB on 2d09a211635f3fe134f5b72c9f84550adcafd8a3
1import XCTest
2import ObjectiveC
3#if DEBUG
4import FoundationModels
5#endif
6
7// Video capture take for the Jotley App Store / tutorial footage (copied into Jotley-iOSUITests by
8// record_ui.sh, removed again afterwards). One continuous take: open the untitled photo-walk note, choose a
9// template, Generate Summary at real speed with the on-device model, then ask two Ask AI questions.
10// Pauses are human-paced so the screen recording reads; nothing is simulated or sped up.
11// Prints "CAPTURE-MARK <name> <unix seconds>" so the recorder can cut the take into clips.
12final class JotleyVideoCaptureUITests: XCTestCase {
13 // Capture-only runner adjustment: native glass animations remain enabled, while
14 // XCTest does not wait 60 seconds for each continuously animated view to become idle.
15 // Explicit element and model-result waits below still govern every action.
16 private static let captureIdleWaits: Void = {
17 guard let cls = NSClassFromString("XCUIApplicationProcess") else { return }
18 let one = NSSelectorFromString("waitForQuiescenceIncludingAnimationsIdle:")
19 if let method = class_getInstanceMethod(cls, one) {
20 let block: @convention(block) (AnyObject, Bool) -> Void = { _, _ in }
21 method_setImplementation(method, imp_implementationWithBlock(block))
22 }
23 let two = NSSelectorFromString("waitForQuiescenceIncludingAnimationsIdle:isPreEvent:")
24 if let method = class_getInstanceMethod(cls, two) {
25 let block: @convention(block) (AnyObject, Bool, Bool) -> Void = { _, _, _ in }
26 method_setImplementation(method, imp_implementationWithBlock(block))
27 }
28 }()
29 override func setUpWithError() throws {
30 continueAfterFailure = false
31 _ = Self.captureIdleWaits
32 }
33
34 // xcodebuild does not forward the runner's stdout, so marks also go to the file record_ui.sh names
35 // (passed as TEST_RUNNER_CAPTURE_MARKS; simulator processes can write to the Mac's file system).
36 private func mark(_ name: String) {
37 let line = String(format: "CAPTURE-MARK %@ %.3f\n", name, Date().timeIntervalSince1970)
38 print(line, terminator: "")
39 guard let path = ProcessInfo.processInfo.environment["CAPTURE_MARKS"] else { return }
40 if let handle = FileHandle(forWritingAtPath: path) {
41 handle.seekToEndOfFile(); handle.write(Data(line.utf8)); try? handle.close()
42 } else { try? line.write(toFile: path, atomically: true, encoding: .utf8) }
43 }
44 private func pause(_ seconds: Double) { Thread.sleep(forTimeInterval: seconds) }
45
46 #if DEBUG
47 @MainActor func testCaptureSummaryAndAskAI() throws {
48 guard case .available = SystemLanguageModel.default.availability else {
49 throw XCTSkip("Apple model is not ready in this simulator")
50 }
51 let env = ProcessInfo.processInfo.environment
52 let template = env["CAPTURE_TEMPLATE"] ?? "personal-note"
53 XCUIDevice.shared.orientation = env["CAPTURE_ORIENTATION"] == "landscape" ? .landscapeLeft : .portrait
54 let app = XCUIApplication()
55 // Brand purple accent (the argument domain overrides whatever theme the simulator was left on).
56 app.launchArguments = ["-transcriptionLanguage", "en-US", "-selectedThemeColor", env["CAPTURE_THEME"] ?? "Purple"]
57 app.launchEnvironment["JOTLEY_TEST_ENGAGEMENT_COUNT"] = "0"
58 app.launchEnvironment["JOTLEY_SCREENSHOT_APPEARANCE"] = env["CAPTURE_APPEARANCE"] ?? "Dark"
59 // The same words the demo voice speaks in the live-transcription clip, so the clips follow on.
60 // Retired templates (Concise, Study) are only offered on notes already using them, so seed those.
61 let seedTemplate = ["Concise", "Study"].contains(template) ? #","template":"\#(template)""# : ""
62 app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = #"""
63 [{"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)}]
64 """#
65 // Optional seed file (CAPTURE_DATA_FILE, a JSON array of notes on the Mac's disk) replaces the default note.
66 if let path = env["CAPTURE_DATA_FILE"], !path.isEmpty, let seed = try? String(contentsOfFile: path, encoding: .utf8) {
67 app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = seed
68 }
69 app.launch()
70 // Since build 5f48c48 the app keeps a note selected, so iPhone opens straight onto the note; older builds
71 // (and a visible iPad sidebar) show the list row first. Same pacing either way, so the cut marks line up.
72 let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'notesListNoteRow-'")).firstMatch
73 let generate = app.buttons["noteDetailGenerateSummaryButton"]
74 let openBy = Date().addingTimeInterval(20)
75 while !row.exists && !generate.exists && Date() < openBy { pause(0.25) }
76 pause(2.0)
77 mark("list")
78 if row.exists && row.isHittable && !generate.exists { row.tap() }
79 XCTAssertTrue(generate.waitForExistence(timeout: 10))
80 pause(1.5)
81
82 // Summary: template, then Generate Summary at real speed.
83 mark("summary-start")
84 let templates = app.buttons["noteDetailTemplatesButton"]
85 templates.tap()
86 let choice = app.buttons["noteTemplate-\(template)"]
87 XCTAssertTrue(choice.waitForExistence(timeout: 5))
88 pause(1.4)
89 choice.tap()
90 pause(1.2)
91 mark("generate-tap")
92 generate.tap()
93 let title = app.staticTexts["noteDetailTitle"]
94 let titled = expectation(for: NSPredicate(format: "exists == true AND label != 'Untitled'"), evaluatedWith: title)
95 // 2.2 footer: Generate gives way to Cancel Generation, then to an enabled Ask AI once the summary is saved.
96 let finished = expectation(for: NSPredicate(format: "exists == true AND enabled == true"),
97 evaluatedWith: app.buttons["noteDetailSummaryAskAIButton"])
98 wait(for: [titled, finished], timeout: 180)
99 mark("summary-done")
100 XCTAssertFalse(app.alerts.firstMatch.exists, app.debugDescription)
101 pause(Double(env["CAPTURE_TOP_PAUSE"] ?? "") ?? 2.0) // the marketing film scrolls up straight away
102 // The summary follows the text as it streams in; scroll back up to the new title, like a person would.
103 let content = app.descendants(matching: .any).matching(identifier: "noteDetailSummaryContent").firstMatch
104 _ = content
105 for _ in 0..<3 { // a plain finger drag: long summaries render as several sections
106 app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.35))
107 .press(forDuration: 0.05, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.9)))
108 pause(0.5)
109 }
110 mark("summary-top")
111 pause(3.5)
112 let summaryShot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())
113 summaryShot.name = "capture-summary"; summaryShot.lifetime = .keepAlways; add(summaryShot)
114 mark("summary-end")
115
116 // Ask AI: two typed questions, answered by the on-device model.
117 let ask = app.buttons["noteDetailSummaryAskAIButton"]
118 XCTAssertTrue(ask.waitForExistence(timeout: 5))
119 pause(0.6)
120 mark("ask-start")
121 ask.tap()
122 // 2.2: the question box is a multiline UITextView (Send return key), so match it by identifier of any type.
123 let field = app.descendants(matching: .any).matching(identifier: "askAIQuestionField").firstMatch
124 XCTAssertTrue(field.waitForExistence(timeout: 10))
125 pause(1.5)
126 let copy = app.buttons["askAICopyConversationButton"]
127 let q = { (k: String) in env[k].flatMap { $0.isEmpty ? nil : $0 } }
128 let questions = [q("CAPTURE_Q1") ?? "What should I finish by Sunday?",
129 q("CAPTURE_Q2") ?? "What should I do on Saturday?"]
130 for (index, question) in questions.enumerated() {
131 field.tap()
132 pause(0.6)
133 field.typeText(question)
134 pause(0.9)
135 mark("ask-send-\(index + 1)")
136 // iPad's form sheet can expose more than one match; tap the one actually on screen.
137 let sends = app.buttons.matching(identifier: "askAISendButton").allElementsBoundByIndex
138 let send = sends.first { $0.isHittable && $0.isEnabled } ?? sends.first { $0.isHittable } ?? app.buttons["askAISendButton"]
139 send.tap()
140 if field.value as? String == question { pause(0.5); send.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap() }
141 // The conversation Copy button is enabled once the answer has finished.
142 pause(1.0)
143 let answered = expectation(for: NSPredicate(format: "enabled == YES"), evaluatedWith: copy)
144 wait(for: [answered], timeout: 120)
145 mark("ask-answer-\(index + 1)")
146 pause(3.5)
147 }
148 if app.keyboards.firstMatch.exists { app.swipeDown(velocity: .slow) }
149 pause(2.5)
150 let askShot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())
151 askShot.name = "capture-ask-ai"; askShot.lifetime = .keepAlways; add(askShot)
152 mark("ask-end")
153 pause(1.0)
154 guard env["CAPTURE_ORGANIZE"] != "0" else { return }
155
156 // Organize: tag the note, share it (More Export Options), then search for the tag (iPhone).
157 app.buttons["askAIDoneButton"].tap()
158 XCTAssertTrue(ask.waitForExistence(timeout: 5))
159 pause(1.5)
160 let chipsBefore = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'noteDetailTag-'")).count
161 mark("tag-start")
162 let addTag = app.buttons.matching(NSPredicate(format: "label == 'Add Tag'")).firstMatch
163 addTag.tap()
164 let tagField = app.textFields.matching(NSPredicate(format: "identifier == 'addTagTextField' OR identifier == 'Enter tag name' OR placeholderValue == 'Enter tag name'")).firstMatch
165 XCTAssertTrue(tagField.waitForExistence(timeout: 5))
166 pause(1.0)
167 tagField.tap(); pause(0.4)
168 // Completed summaries now add topic tags (often "photography"), so add one the model won't have chosen.
169 let tag = env["CAPTURE_TAG"].flatMap { $0.isEmpty ? nil : $0 } ?? "Side Project"
170 tagField.typeText(tag)
171 pause(1.0)
172 let save = app.buttons["addTagSaveButton"]
173 let confirm = save.exists ? save : app.buttons.matching(NSPredicate(format: "label == 'Add Tag'")).allElementsBoundByIndex
174 .last { $0.isHittable && $0.isEnabled }
175 XCTAssertNotNil(confirm); confirm?.tap()
176 pause(0.7)
177 if tagField.exists {
178 // Some iPad glass-button taps focus the sheet before activating it.
179 // Submit through the native text field if the sheet is still open.
180 tagField.typeText("\n")
181 pause(0.7)
182 }
183 let chips = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'noteDetailTag-'"))
184 let tagBy = Date().addingTimeInterval(5)
185 while chips.count <= chipsBefore && Date() < tagBy { pause(0.2) }
186 XCTAssertGreaterThan(chips.count, chipsBefore)
187 mark("tag-done")
188 pause(3.0)
189 mark("tag-end")
190
191 mark("share-start")
192 app.buttons["noteDetailShareButton"].tap()
193 let more = app.buttons["More Export Options"]
194 XCTAssertTrue(more.waitForExistence(timeout: 5))
195 pause(2.2)
196 more.tap()
197 // The submenu expands in place; its items may surface as buttons or menu items.
198 let summaryOnly = app.descendants(matching: .any).matching(NSPredicate(format: "label == 'Summary Only' OR identifier == 'exportSummaryButton'")).firstMatch
199 if !summaryOnly.waitForExistence(timeout: 5) { print(app.debugDescription) }
200 mark("export-options")
201 pause(3.5)
202 mark("share-end")
203 // Close the menu without exporting.
204 app.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.72)).tap() // empty area, clear of the toolbar
205 pause(1.2)
206
207 guard UIDevice.current.userInterfaceIdiom == .phone else { return }
208 let back = app.navigationBars.buttons["BackButton"].exists ? app.navigationBars.buttons["BackButton"]
209 : app.navigationBars.buttons.element(boundBy: 0)
210 if app.buttons["exportPlainTextButton"].exists { // menu still open: dismiss it first
211 app.coordinate(withNormalizedOffset: CGVector(dx: 0.3, dy: 0.72)).tap(); pause(0.8)
212 }
213 if back.isHittable { back.tap() } else { // edge swipe back, like a person would
214 app.coordinate(withNormalizedOffset: CGVector(dx: 0.01, dy: 0.5))
215 .press(forDuration: 0.05, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.85, dy: 0.5)))
216 }
217 let search = app.descendants(matching: .any)["notesListSearchField"].firstMatch
218 XCTAssertTrue(search.waitForExistence(timeout: 5))
219 pause(1.5)
220 mark("search-start")
221 search.tap(); pause(0.6)
222 search.typeText(env["CAPTURE_SEARCH"].flatMap { $0.isEmpty ? nil : $0 } ?? "Photo")
223 pause(3.5)
224 mark("search-end")
225 pause(0.5)
226 }
227
228 @MainActor func testCaptureRealLiveTranscription() throws {
229 let env = ProcessInfo.processInfo.environment
230 XCUIDevice.shared.orientation = env["CAPTURE_ORIENTATION"] == "landscape" ? .landscapeLeft : .portrait
231 let app = XCUIApplication()
232 app.launchArguments = ["-transcriptionLanguage", "en-US", "-selectedThemeColor", "Purple", "-jotleyWelcomeCompleted.v1", "YES"]
233 app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = "[]"
234 app.launchEnvironment["JOTLEY_SCREENSHOT_APPEARANCE"] = "Dark"
235 app.launchEnvironment["JOTLEY_TEST_ENGAGEMENT_COUNT"] = "0"
236 // Real microphone and Apple Speech. No simulated-speech or audio-level hooks.
237 app.launch()
238 let plus = app.buttons["notesListNewNoteButton"].firstMatch
239 XCTAssertTrue(plus.waitForExistence(timeout: 20)); mark("live-list"); pause(1)
240 plus.tap()
241 let pauseButton = app.buttons["transcriptionPauseButton"]
242 XCTAssertTrue(pauseButton.waitForExistence(timeout: 90))
243 mark("live-ready"); pause(27)
244 let words = app.staticTexts.matching(NSPredicate(format: "label CONTAINS[c] 'photography'")).firstMatch
245 XCTAssertTrue(words.waitForExistence(timeout: 15), "Real demo speech must produce a photography transcript")
246 mark("live-spoken")
247 pauseButton.tap(); mark("live-paused"); pause(1.6)
248 pauseButton.tap(); mark("live-resumed"); pause(1.4)
249 app.buttons["transcriptionStopButton"].tap()
250 XCTAssertTrue(app.staticTexts["noteDetailTitle"].waitForExistence(timeout: 10))
251 mark("live-stopped"); pause(2)
252 let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot())
253 shot.name = "Real-microphone-transcript"; shot.lifetime = .keepAlways; add(shot)
254 mark("live-end")
255 }
256
257 @MainActor func testCaptureRealSummaryStyles() throws {
258 XCUIDevice.shared.orientation = .portrait
259 let env = ProcessInfo.processInfo.environment
260 let app = XCUIApplication()
261 app.launchArguments = ["-transcriptionLanguage", env["CAPTURE_LANGUAGE"] ?? "en-US", "-selectedThemeColor", "Purple", "-jotleyWelcomeCompleted.v1", "YES"]
262 app.launchEnvironment["JOTLEY_SCREENSHOT_APPEARANCE"] = "Light"
263 app.launchEnvironment["JOTLEY_TEST_ENGAGEMENT_COUNT"] = "0"
264 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":""}]"#
265 if let path = env["CAPTURE_DATA_FILE"], !path.isEmpty {
266 app.launchEnvironment["JOTLEY_SCREENSHOT_DATA"] = try String(contentsOfFile: path, encoding: .utf8)
267 }
268 let dir = URL(fileURLWithPath: env["CAPTURE_STILLS_ROOT"]!)
269 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
270 func shot(_ name: String) throws {
271 pause(0.6)
272 try XCUIScreen.main.screenshot().pngRepresentation.write(to: dir.appendingPathComponent(name + ".png"))
273 }
274 func library() {
275 let settings = app.buttons["notesListSettingsButton"]
276 if settings.exists && settings.isHittable { return }
277 let back = app.buttons["BackButton"]
278 if back.exists && back.isHittable { back.tap() }
279 else {
280 let sidebar = app.navigationBars.buttons.matching(NSPredicate(format: "label CONTAINS[c] 'sidebar'")).firstMatch
281 XCTAssertTrue(sidebar.waitForExistence(timeout: 5)); sidebar.tap()
282 }
283 XCTAssertTrue(settings.waitForExistence(timeout: 5))
284 }
285 app.launch()
286 XCUIDevice.shared.orientation = .portrait
287 pause(1)
288 let generate = app.buttons["noteDetailGenerateSummaryButton"]
289 XCTAssertTrue(generate.waitForExistence(timeout: 20))
290 if env["CAPTURE_LANGUAGE"] == "fr-FR" { try shot("transcript-french") }
291 app.buttons["noteDetailTemplatesButton"].tap()
292 app.buttons["noteTemplate-personal-note"].tap()
293 generate.tap()
294 let ready = expectation(for: NSPredicate(format: "exists == true AND enabled == true"), evaluatedWith: app.buttons["noteDetailSummaryAskAIButton"])
295 wait(for: [ready], timeout: 180)
296 let title = app.staticTexts["noteDetailTitle"]
297 for _ in 0..<5 where !title.isHittable { app.swipeDown(); pause(0.4) }
298 try app.debugDescription.write(to: dir.appendingPathComponent("real-summary-accessibility.txt"), atomically: true, encoding: .utf8)
299 try shot("summary-purple")
300 if env["CAPTURE_LANGUAGE"] == "fr-FR" { try shot("summary-french"); return }
301 // Each still is a fresh real on-device result in the requested native theme.
302 // Relaunching avoids the platform's inaccessible nested settings menu.
303 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")] {
304 app.terminate()
305 app.launchArguments = ["-transcriptionLanguage", "en-US", "-selectedThemeColor", theme, "-jotleyWelcomeCompleted.v1", "YES"]
306 app.launchEnvironment["JOTLEY_SCREENSHOT_APPEARANCE"] = appearance
307 app.launch()
308 XCTAssertTrue(generate.waitForExistence(timeout: 20))
309 app.buttons["noteDetailTemplatesButton"].tap()
310 app.buttons["noteTemplate-personal-note"].tap()
311 generate.tap()
312 let generated = expectation(for: NSPredicate(format: "exists == true AND enabled == true"), evaluatedWith: app.buttons["noteDetailSummaryAskAIButton"])
313 wait(for: [generated], timeout: 180)
314 for _ in 0..<3 { app.swipeDown(); pause(0.3) }
315 try shot("summary-" + name)
316 }
317 library(); try shot("library")
318 app.buttons["notesListSettingsButton"].tap()
319 let language = app.descendants(matching: .any)["settingsLanguagePicker"].firstMatch
320 if language.exists { language.tap(); try shot("languages") }
321 }
322 #endif
323}