interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Sources / UITest.swift

883 lines · 73436 bytes Raw Blame History
1import AppKit
2
3/// `Hop --uitest --no-global-hotkey`: presses real keys in the real panel and checks where they land.
4/// No agent is started: requests are recorded instead. Prints one line per check.
5@MainActor
6enum UITest {
7 static var active = false
8
9
10 /// Production model routes, run without an app delegate, windows, cursor events or real providers.
11 static func flowChecks(_ m: AppModel) async -> Int32 {
12 var failures = 0
13 var sent: [String] = []
14 m.agentDryRun = { sent.append($0) }
15 m.dictation.testMode = true
16 func report(_ name: String, _ ok: Bool, _ detail: String = "") {
17 print("\(ok ? "PASS" : "FAIL") \(name)\(detail.isEmpty ? "" : ": " + detail)")
18 if !ok { failures += 1 }
19 }
20 // Exercise the production entry points with a recording agent, never a real provider.
21 m.tab = .agent; m.agentRunning = true
22 let idea = " A flowing idea 🧠\nwith original spacing "
23 m.query = idea; m.submit(alt: false)
24 report("Enter parks an exact idea while the agent keeps running",
25 m.query.isEmpty && m.agentRunning && sent.isEmpty && m.parkingLot.ideas.last?.text == idea)
26 m.query = "draft during an active run"; m.fixIt()
27 report("An explicit send while busy keeps the draft and explains it was not sent",
28 m.query == "draft during an active run" && sent.isEmpty && m.agentLog.last?.text == "Still working. Your draft has not been sent.")
29 let saved = m.parkingLot.ideas
30 let reopened = ParkingLot(file: HopConfig.dir.appendingPathComponent("parking-lot/ideas.json"))
31 report("The parking lot survives a fresh reader", reopened.ideas == saved)
32 m.agentRunning = false
33 m.tab = .find; m.query = "send from another screen"; m.fixIt()
34 report("An explicit send outside Agent is not captured by Flow",
35 sent == ["send from another screen"] && m.parkingLot.ideas == saved)
36 m.tab = .agent; m.query = "explicit send in Agent"; m.fixIt()
37 report("Shift Enter explicitly sends while Flow is always on",
38 sent.last == "explicit send in Agent" && sent.count == 2 && m.parkingLot.ideas == saved)
39 m.query = "another idea after returning to Agent"; m.submit(alt: false)
40 report("Enter keeps parking after an explicit send", sent.count == 2 && m.parkingLot.ideas.last?.text == "another idea after returning to Agent")
41 do {
42 let defaults = try JSONDecoder().decode(HopConfig.self, from: Data("{}".utf8))
43 var advanced = defaults; advanced.reviewParkedIdeasBeforeSorting = true
44 let restored = try JSONDecoder().decode(HopConfig.self, from: JSONEncoder().encode(advanced))
45 report("Sorting is one action by default; detailed preview is an opt-in setting",
46 !defaults.reviewParkedIdeasBeforeSorting && restored.reviewParkedIdeasBeforeSorting)
47 } catch { report("Advanced setting round trip", false, error.localizedDescription) }
48 m.query = "my unfinished next idea"
49 m.sortParkedIdeas()
50 let actualRequest = sent.last ?? ""
51 report("Sorting preserves Flow and the draft, with a simple conversation line",
52 m.query == "my unfinished next idea" && actualRequest.contains(idea)
53 && m.agentLog.last?.text == "Sort my parked ideas by feasibility and importance."
54 && AppModel.history(m.agentLog).last?.text == actualRequest)
55 m.strongerLeft = true; m.runStronger()
56 report("A stronger sorting request retains the original ideas", sent.last == actualRequest)
57 m.query = ""; m.dictation.isHopFront = { true }; m.dictation.settings.speakReplies = true
58 let beforeVoice = sent.count
59 m.dictation.deliver("spoken idea")
60 report("Dictated Flow ideas are parked without arming a spoken answer",
61 m.parkingLot.ideas.last?.text == "spoken idea" && !m.dictation.speakNextReply && sent.count == beforeVoice)
62 m.query = " unfinished typed idea "
63 m.dictation.deliverCommandToAgent("spoken command idea")
64 report("A spoken command in Agent Flow preserves the typed draft and parks both",
65 m.parkingLot.ideas.last?.text == " unfinished typed idea \nspoken command idea"
66 && m.query.isEmpty && !m.dictation.speakNextReply && sent.count == beforeVoice)
67 m.agentRunning = true; m.query = "typed while working"
68 m.dictation.deliverCommandToAgent("spoken while working")
69 report("Spoken Flow capture keeps both ideas while the current agent continues",
70 m.parkingLot.ideas.last?.text == "typed while working\nspoken while working"
71 && m.query.isEmpty && m.agentRunning && sent.count == beforeVoice)
72 m.agentRunning = false
73 m.dictation.settings.speakReplies = false
74 m.dictation.isHopFront = { false }
75 m.query = "another unfinished idea"
76 m.dictation.deliverCommandToAgent("command from another app")
77 report("An external spoken command sends only the command and saves the existing draft",
78 sent.last == "command from another app" && m.parkingLot.ideas.last?.text == "another unfinished idea")
79 let beforeBusyVoice = sent.count
80 m.agentRunning = true; m.query = "busy typed draft"
81 m.dictation.deliverCommandToAgent("busy spoken command")
82 report("An external spoken command while busy preserves both inputs without sending",
83 m.query == "busy typed draft\nbusy spoken command" && sent.count == beforeBusyVoice
84 && m.agentLog.last?.text == "Still working. Your draft has not been sent.")
85 m.agentRunning = false
86 m.dictation.isHopFront = { true }
87 // Exercise Sort ideas through AppModel -> Pick -> Fusion, with real loopback models.
88 // File-capable stand-ins leave a marker if any proposal/probe/fallback launches them.
89 let recording = m.agentDryRun
90 m.agentDryRun = nil; m.learnFromAgent = false
91 let marker = HopConfig.dir.appendingPathComponent("sorting-must-not-run-tools")
92 var prompts = 0
93 m.confirmAgentRun = { _ in prompts += 1; return false }
94 func waitForReply() async {
95 for _ in 0..<150 {
96 if !m.agentRunning { return }
97 try? await Task.sleep(nanoseconds: 100_000_000)
98 }
99 m.stopAgent()
100 }
101 if let own = PickChecks.stub(says: "First assessment", reports: nil),
102 let next = PickChecks.stub(says: "Stronger assessment", reports: nil),
103 let p1 = await own.start(), let p2 = await next.start() {
104 var cfg = HopConfig(); cfg.cortex.enabled = false
105 var first = PickChecks.ownModel(p1); first.tier = 1
106 var second = PickChecks.ownModel(p2); second.name = "Second assessment model"; second.tier = 4
107 cfg.models = [first, second]; cfg.fusionSeats = []; cfg.agentCommand = []
108 cfg.agentWorkingDirectory = HopConfig.dir.path
109 cfg.agentEngines = [PickChecks.tool("Must never run", "echo ran >> \(Shell.quote(marker.path)); echo unsafe", tier: 4, family: "other", cost: 1)]
110 m.config = cfg
111 _ = m.parkingLot.capture("Design a website, implement it, run commands and deploy it. These are parked ideas to assess.")
112 let originals = m.parkingLot.ideas
113 m.query = "draft that sorting must preserve"
114 m.sortParkedIdeas(); await waitForReply()
115 let answered = m.agentLog.contains { $0.role == "assistant" && $0.text.contains("assessment") }
116 report("Sort ideas reaches a chat model without a tool permission prompt or command",
117 !m.agentRunning && answered && prompts == 0 && !FileManager.default.fileExists(atPath: marker.path)
118 && m.query == "draft that sorting must preserve" && m.parkingLot.ideas == originals)
119 m.strongerLeft = true; m.runStronger(); await waitForReply()
120 report("Stronger keeps sorting restricted to chat models",
121 !m.agentRunning && prompts == 0 && !FileManager.default.fileExists(atPath: marker.path)
122 && m.query == "draft that sorting must preserve" && m.parkingLot.ideas == originals)
123 own.stop(); next.stop()
124 // With no chat seat, fail safely even though a coding tool is installed.
125 cfg.models = []; m.config = cfg; m.newAgent(); m.query = "draft without a chat model"
126 _ = m.parkingLot.capture("A new idea after the first assessment, to avoid replaying a cached result.")
127 let laterOriginals = m.parkingLot.ideas
128 m.sortParkedIdeas(); await waitForReply()
129 report("Sorting without a chat model keeps ideas and never falls back to a coding tool",
130 !m.agentRunning && prompts == 0 && !FileManager.default.fileExists(atPath: marker.path)
131 && m.parkingLot.ideas == laterOriginals && m.query == "draft without a chat model"
132 && !m.agentLog.contains { $0.role == "assistant" })
133 } else { report("Real sorting route fixtures", false) }
134 m.agentDryRun = recording
135 report("Upgrading tool consent requires a new yes before execution", await PickChecks.consentUpgradeCheck())
136
137 let savedBeforeFailure = m.parkingLot.ideas
138 let sentBeforeFailure = sent.count
139 // A write failure after loading must leave both the draft and the saved notebook intact.
140 let folder = HopConfig.dir.appendingPathComponent("parking-lot")
141 let backup = HopConfig.dir.appendingPathComponent("parking-lot-test-backup")
142 do {
143 try FileManager.default.moveItem(at: folder, to: backup)
144 try Data().write(to: folder)
145 m.query = "keep this unsaved idea"; m.submit(alt: false)
146 report("A failed save keeps the draft and original ideas",
147 m.query == "keep this unsaved idea" && m.parkingLot.ideas == savedBeforeFailure && m.parkingLot.problem != nil && sent.count == sentBeforeFailure)
148 m.dictation.deliverCommandToAgent("unsaved spoken idea")
149 report("A spoken Flow idea survives a failed save alongside the typed draft",
150 m.query == "keep this unsaved idea\nunsaved spoken idea" && m.parkingLot.ideas == savedBeforeFailure && sent.count == sentBeforeFailure)
151 m.dictation.isHopFront = { false }
152 m.query = "unsaved external draft"
153 m.dictation.deliverCommandToAgent("unsent external command")
154 report("An external command waits if its existing draft cannot be saved",
155 m.query == "unsaved external draft\nunsent external command" && m.parkingLot.ideas == savedBeforeFailure && sent.count == sentBeforeFailure)
156 } catch { report("Write-failure fixture", false, error.localizedDescription) }
157 print(failures == 0 ? "ALL FLOW CHECKS PASS" : "\(failures) FLOW CHECKS FAILED")
158 return failures == 0 ? 0 : 1
159 }
160
161 /// Which of the configured agents are on this Mac, worked out WITHOUT Hop's own lookup script: each tool is
162 /// looked for as a file, in the login shell's PATH and the usual install folders. The tests compare Hop's
163 /// answer with this one instead of trusting it.
164 nonisolated static func agentsOnDisk(_ cfg: HopConfig) -> [String] {
165 let p = Process(), out = Pipe()
166 p.executableURL = URL(fileURLWithPath: "/bin/zsh"); p.arguments = ["-lc", "printf '\\nHOP-PATH=%s\\n' \"$PATH\""]
167 p.standardOutput = out; p.standardError = FileHandle.nullDevice
168 try? p.run()
169 let text = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
170 p.waitUntilExit()
171 let path = text.split(separator: "\n").last { $0.hasPrefix("HOP-PATH=") }.map { String($0.dropFirst(9)) } ?? ""
172 let dirs = path.split(separator: ":").map(String.init) + CommandRun.extraPath
173 func onDisk(_ tool: String) -> Bool {
174 guard !tool.isEmpty else { return false }
175 if tool.contains("/") { return FileManager.default.isExecutableFile(atPath: tool) }
176 return dirs.contains { FileManager.default.isExecutableFile(atPath: $0 + "/" + tool) }
177 }
178 let listed = cfg.agentEngines.filter { onDisk($0.tool) }.map(\.name)
179 if !listed.isEmpty { return listed }
180 return onDisk(cfg.agentCommand.first ?? "") ? [AppModel.legacyEngineName] : []
181 }
182
183 /// nil when the tests may run: HOP_CONFIG_DIR is set and lies under the system's temporary folders.
184 /// Otherwise the reason, and nothing is started (no settings are read or written).
185 nonisolated static func refusal() -> String? {
186 let how = "Run it like this: HOP_CONFIG_DIR=$(mktemp -d) Hop --uitest --uitest-voice --no-global-hotkey" // also: --uitest-box, --uitest-launch
187 let dir = ProcessInfo.processInfo.environment["HOP_CONFIG_DIR"] ?? ""
188 guard !dir.isEmpty else { return "Hop's UI tests change settings, so they do not run on your real ones. HOP_CONFIG_DIR is not set. " + how }
189 let path = URL(fileURLWithPath: dir).resolvingSymlinksInPath().standardizedFileURL.path
190 let roots = [NSTemporaryDirectory(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders"]
191 .map { URL(fileURLWithPath: $0).resolvingSymlinksInPath().standardizedFileURL.path }
192 guard roots.contains(where: { path.hasPrefix($0.hasSuffix("/") ? $0 : $0 + "/") }) else {
193 return "Hop's UI tests change settings, so they run only on a throwaway folder. HOP_CONFIG_DIR (\(path)) is not under the system's temporary folder. " + how
194 }
195 return nil
196 }
197
198 static func run(_ app: AppDelegate) {
199 active = true
200 Task { @MainActor in
201 var failures = 0
202 var sent: [String] = []
203 let m = app.model!
204 m.agentDryRun = { sent.append($0) }
205 m.dictation.testMode = true
206 @MainActor func report(_ name: String, _ ok: Bool, _ detail: String = "") {
207 print("\(ok ? "PASS" : "FAIL") \(name)\(detail.isEmpty ? "" : ": \(detail)")")
208 if !ok { failures += 1 }
209 }
210 @MainActor func pause(_ s: Double) async { try? await Task.sleep(nanoseconds: UInt64(s * 1_000_000_000)) }
211 @MainActor func key(_ code: UInt16, _ chars: String, _ mods: NSEvent.ModifierFlags = []) async {
212 for type in [NSEvent.EventType.keyDown, .keyUp] {
213 if let e = NSEvent.keyEvent(with: type, location: .zero, modifierFlags: mods,
214 timestamp: ProcessInfo.processInfo.systemUptime,
215 windowNumber: app.panel.windowNumber, context: nil, characters: chars,
216 charactersIgnoringModifiers: chars, isARepeat: false, keyCode: code) {
217 NSApp.sendEvent(e)
218 }
219 }
220 await pause(0.3)
221 }
222 let left = String(UnicodeScalar(NSLeftArrowFunctionKey)!), right = String(UnicodeScalar(NSRightArrowFunctionKey)!)
223 let arrow: NSEvent.ModifierFlags = [.function, .numericPad]
224
225
226 @MainActor func voiceCheck() async {
227 if !m.dictation.settings.enabled { // a fresh install: nothing may be loaded until the user turns dictation on
228 await pause(2.0)
229 report("With dictation off, no speech model is loaded", !m.dictation.modelReady && !m.dictation.engine.ready, "model loaded=\(m.dictation.engine.ready)")
230 m.dictation.begin(.hold); await pause(0.3)
231 report("With dictation off, the key does nothing", m.dictation.phase == .idle)
232 m.dictation.settings.enabled = true // what the "Turn on dictation" button does (test mode: not saved)
233 }
234 // Dictation into Hop's own box: a spoken sentence (made with the Mac's voice) goes through the live path.
235 let clip = NSTemporaryDirectory() + "hop-uitest-\(ProcessInfo.processInfo.processIdentifier).wav"
236 let sayIt = Process(); sayIt.executableURL = URL(fileURLWithPath: "/usr/bin/say")
237 sayIt.arguments = ["-o", clip, "--data-format=LEI16@16000", "Um, move the meeting to Friday at ten."]
238 try? sayIt.run(); sayIt.waitUntilExit()
239 m.dictation.isHopFront = { true }
240 m.agentUnseen = false; m.query = ""; m.tab = .clipboard
241 var waited = 0.0
242 while !m.dictation.modelReady && waited < 60 { await pause(0.5); waited += 0.5 }
243 m.dictation.begin(.hold, source: .file(URL(fileURLWithPath: clip)))
244 await pause(1.0)
245 m.dictation.end()
246 waited = 0
247 while m.dictation.phase != .idle && waited < 10 { await pause(0.25); waited += 0.25 }
248 let got = m.query.lowercased()
249 report("Dictation lands in Hop's box, tidied", got.contains("friday") && got.contains("meeting") && !got.hasPrefix("um"), "“\(m.query)” after \(waited)s")
250 try? FileManager.default.removeItem(atPath: clip)
251 m.query = ""
252 }
253 if CommandLine.arguments.contains("--uitest-agent") { // one real request through the app's own agent path; no window
254 m.learnFromAgent = false
255 // A search that finds nothing is not a request: plain Enter must not reach the agent unless switched on.
256 let wasOn = m.config.enterSendsToAgent
257 m.clipboard.showTestItems([])
258 m.config.enterSendsToAgent = false
259 m.tab = .clipboard; m.query = "quarterly budget draft"; m.submit(alt: false)
260 let quiet = sent.isEmpty && m.tab == .clipboard
261 m.config.enterSendsToAgent = true
262 m.tab = .clipboard; m.query = "quarterly budget draft"; m.submit(alt: false)
263 report("Plain Enter on a search with no match starts no agent; with enterSendsToAgent on it does", quiet && sent == ["quarterly budget draft"],
264 "off: sent \(quiet ? 0 : 1); on: sent \(sent.count)")
265 m.config.enterSendsToAgent = wasOn; sent = []; m.query = ""
266 // Enter on the agent line waits for the other machines too: a text that is a file's name there must
267 // not go to an agent. The machine here has a name that cannot exist, so nothing is reached.
268 let machinesWere = m.config.machines
269 m.config.machines = [Machine(name: "Far", ssh: "hop-uitest-no-such-host.invalid", roots: [])]
270 let far = "zq7 tidy the far shelf"
271 m.tab = .all; m.query = far
272 var farWait = 0.0
273 while m.settledQuery != far && farWait < 3 { await pause(0.02); farWait += 0.02 }
274 let stillLooking = m.remotePending, topLine = m.smartRows.first?.id ?? "none"
275 m.submit(alt: false)
276 let held = sent.isEmpty && m.sendWhenSettled == far
277 farWait = 0
278 while m.remotePending && farWait < 20 { await pause(0.1); farWait += 0.1 }
279 await pause(0.3)
280 report("Enter on the agent line waits until the other machines have searched too, then sends once",
281 stillLooking && topLine == "agent" && held && sent == [far] && m.sendWhenSettled == nil,
282 "this Mac done and another machine still looking at the Enter: \(stillLooking); top line: \(topLine); held: \(held); sent after \(String(format: "%.1f", farWait)) s: \(sent)")
283 m.config.machines = machinesWere; sent = []; m.query = ""; m.tab = .clipboard
284 m.agentDryRun = nil
285 var asked: [String] = [], answer = false
286 m.confirmAgentRun = { asked.append($0); return answer }
287 let ask = "Reply with exactly one word: ready. Do not use any tools."
288 @MainActor func settle(_ limit: Double) async -> Double { // until the run is over, or the limit
289 var w = 0.5
290 await pause(0.5)
291 while m.agentRunning && w < limit { await pause(0.5); w += 0.5 }
292 return w
293 }
294 // What Hop found is compared with a separate look at the disk, and with what the caller says to expect
295 // (HOP_UITEST_EXPECT_ENGINE: an agent's name that must be among them, or "none"). Hop's own lookup is
296 // never taken as the truth.
297 let cfgNow = m.config
298 let onDisk = await Task.detached { UITest.agentsOnDisk(cfgNow) }.value
299 let found = await AppModel.detectEngines(cfgNow).map(\.name)
300 let told = ProcessInfo.processInfo.environment["HOP_UITEST_EXPECT_ENGINE"]
301 report("The agents Hop found are the ones on this Mac (checked separately, file by file)",
302 found == onDisk && (told == nil || (told == "none" ? found.isEmpty : found.contains(told ?? ""))),
303 "Hop found: \(found.isEmpty ? "none" : found.joined(separator: ", ")); on disk: \(onDisk.isEmpty ? "none" : onDisk.joined(separator: ", ")); expected: \(told ?? "what is on disk")")
304 // Stronger through the Agent screen's own path, from the first answer to the end of a failed and of a stopped
305 // stronger try. A stub server on this Mac and two stand-in tools; nobody real is asked.
306 let strongerRow = "A stronger try that fails, and one that is stopped, puts the earlier answer back without its own half answer (the Agent screen's own path)"
307 if let server = PickChecks.stub(reports: nil), let port = await server.start() {
308 let was = m.config
309 // Settings of its own for who answers: nothing of the settings under test decides it (no seats of
310 // their own, no switch that keeps own models out, no machines, no knowledge base).
311 var alone = HopConfig()
312 alone.models = [PickChecks.ownModel(port)]
313 alone.agentEngines = [PickChecks.tool("Half", "echo half of an answer; exit 1", tier: 4, family: "a", cost: 1)]
314 alone.fusionSeats = []; alone.preferOwnModel = nil; alone.machines = []
315 alone.agentWorkingDirectory = NSTemporaryDirectory()
316 alone.agentConfirmed = true; alone.agentConsentVersion = HopConfig.currentAgentConsentVersion
317 m.config = alone
318 let question = "hello there friend"
319 m.newAgent(); m.query = question; m.tab = .agent; m.runAgent()
320 _ = await settle(30)
321 let firstAnswer = m.agentLog.last(where: { $0.role == "assistant" })?.text ?? "", offered = m.strongerLeft
322 m.runStronger()
323 _ = await settle(30)
324 let afterFailed = AppModel.history(m.agentLog).map(\.text), offeredAgain = m.strongerLeft
325 m.config.agentEngines = [PickChecks.tool("Slow", "echo half of another; sleep 60", tier: 4, family: "b", cost: 1)]
326 m.runStronger()
327 var waited = 0.0
328 while !m.agentLog.contains(where: { $0.text.contains("half of another") }) && waited < 20 { await pause(0.2); waited += 0.2 }
329 let halfShown = m.agentLog.contains { $0.role == "assistant" && $0.text.contains("half of another") }
330 m.stopAgent()
331 await pause(1.0)
332 let afterStopped = AppModel.history(m.agentLog).map(\.text)
333 report(strongerRow,
334 firstAnswer == "ready" && offered && afterFailed == [question, "ready"] && offeredAgain
335 && halfShown && afterStopped == [question, "ready"] && m.strongerLeft && !m.agentRunning,
336 "first answer “\(firstAnswer)”, Stronger offered \(offered); after a try that failed the next mind would be told: \(afterFailed.joined(separator: " / ")); the stopped try's half answer was on screen: \(halfShown); after the stop: \(afterStopped.joined(separator: " / "))")
337 m.newAgent(); m.config = was; server.stop()
338 await pause(CommandRun.graceToEnd + 1) // the stopped stand-in is gone before anything real is started
339 } else {
340 report(strongerRow, false, "could not start a stub server on this Mac's loopback address")
341 }
342 // Nobody who could take a message (no tool found, no model server answering): Hop says so and runs nothing.
343 let seatsNow = await Fusion.seats(cfgNow, installed: await AppModel.detectEngines(cfgNow))
344 if !seatsNow.contains(where: \.ready) {
345 m.query = ask; m.tab = .agent; m.runAgent()
346 let w = await settle(30)
347 let note = m.agentLog.last(where: { $0.role == "note" })?.text ?? ""
348 report("With nobody ready to take a message, Hop says so and runs nothing",
349 (note.contains("no mind to hand this to") || note.contains("No mind is ready")) && !m.agentRunning && asked.isEmpty && !m.agentLog.contains { $0.role == "assistant" }, "“\(note)” after \(w)s")
350 exit(failures == 0 ? 0 : 1)
351 }
352 if !m.config.agentConfirmed, !onDisk.isEmpty { // fresh settings: before the first tool runs Hop asks, and "Cancel" runs nothing
353 let change = "Delete the file hop-uitest-no-such-file.txt in this folder."
354 m.query = change; m.tab = .agent; m.runAgent()
355 let w = await settle(90)
356 report("Before the first agent tool runs Hop asks, and Cancel runs nothing and gives the request back",
357 asked.count == 1 && !m.agentRunning && !m.config.agentConfirmed && !HopConfig.load().agentConfirmed && m.query == change
358 && !m.agentLog.contains { $0.role == "assistant" },
359 "asked about \(asked.first ?? "-") after \(w)s; running=\(m.agentRunning); request back in the box=\(m.query == change)")
360 m.query = ""; m.newAgent()
361 }
362 answer = true
363 m.query = ask
364 m.tab = .agent; m.runAgent()
365 let w = await settle(180)
366 let reply = m.agentLog.last(where: { $0.role == "assistant" })
367 let said = reply?.text ?? "", under = reply?.meta ?? ""
368 let wanted = ProcessInfo.processInfo.environment["HOP_UITEST_EXPECT_OUTPUT"] ?? "ready" // what the answer must hold
369 report("A real request is answered by a mind Hop picked, and the line under it says who", said.lowercased().contains(wanted.lowercased()) && under.contains("answered by"),
370 "“\(said.prefix(40))” · \(under) · after \(w)s; agents found: \(found.joined(separator: ", "))")
371 // A settings file Hop could not read is never saved over, so there a yes lasts for this run only.
372 let unreadable = SettingsFile.isBroken(HopConfig.url)
373 if !onDisk.isEmpty { // two requests that need a tool: the yes is asked for the first and not again for the second
374 let before = asked.count, was = m.config.agentConfirmed
375 m.newAgent()
376 m.query = "Run this command and tell me what it printed: echo hop-uitest-one"; m.tab = .agent; m.runAgent()
377 let w1 = await settle(300)
378 let first = m.agentLog.last(where: { $0.role == "assistant" })?.text ?? ""
379 let afterFirst = asked.count - before
380 m.query = "Run this command and tell me what it printed: echo hop-uitest-two"; m.tab = .agent; m.runAgent()
381 let w2 = await settle(300)
382 let replies = m.agentLog.filter { $0.role == "assistant" }.count
383 report(unreadable ? "A yes to agent tools is asked once and kept for this run; a settings file Hop could not read is still not saved over"
384 : "A yes to agent tools is asked once, saved, and not asked again for the next tool request",
385 afterFirst == (was ? 0 : 1) && asked.count - before == afterFirst && m.config.agentConfirmed && HopConfig.load().agentConfirmed == !unreadable
386 && !first.isEmpty && replies == 2,
387 "asked \(afterFirst) time(s) for the first tool request (\(w1)s) and \(asked.count - before - afterFirst) for the second (\(w2)s); saved in the config: \(HopConfig.load().agentConfirmed); replies: \(replies)")
388 }
389 exit(failures == 0 ? 0 : 1)
390 }
391 @MainActor func shot(_ name: String) { // HOP_UITEST_SHOTS=<folder>: pictures of Hop's own window, for a look at the result
392 // The window's frame is in the picture too, so anything macOS draws round Hop's own shape shows.
393 guard let dir = ProcessInfo.processInfo.environment["HOP_UITEST_SHOTS"], let v = app.panel.contentView?.superview ?? app.panel.contentView,
394 let rep = v.bitmapImageRepForCachingDisplay(in: v.bounds) else { return }
395 v.cacheDisplay(in: v.bounds, to: rep)
396 try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: dir).appendingPathComponent(name + ".png"))
397 }
398 @MainActor func views<T: NSView>(_ kind: T.Type, in v: NSView?) -> [T] {
399 guard let v, !v.isHidden else { return [] }
400 return (v as? T).map { [$0] } ?? [] + v.subviews.flatMap { views(kind, in: $0) }
401 }
402 /// A real click in Hop's window. `r` is where a view said it was drawn, in the window's own coordinates
403 /// (top left origin), so the click lands only if that view is really there.
404 @MainActor func click(_ r: CGRect) async {
405 guard let v = app.panel.contentView else { return }
406 // The first click on a window that does not have the keyboard only gives it the keyboard.
407 if !app.panel.isKeyWindow { app.panel.makeKeyAndOrderFront(nil); await pause(0.3) }
408 let p = v.convert(NSPoint(x: r.midX, y: v.isFlipped ? r.midY : v.bounds.height - r.midY), to: nil)
409 for (type, pressure) in [(NSEvent.EventType.leftMouseDown, Float(1)), (.leftMouseUp, Float(0))] {
410 if let e = NSEvent.mouseEvent(with: type, location: p, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,
411 windowNumber: app.panel.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: pressure) {
412 NSApp.sendEvent(e)
413 }
414 }
415 await pause(0.9)
416 // A made-up click comes with no real pointer behind it, and macOS may take the keyboard from the panel.
417 if !app.panel.isKeyWindow { app.panel.makeKeyAndOrderFront(nil); await pause(0.3) }
418 }
419 // A conversation is drawn newest on top, and digging into it holds still. Made-up messages on the Agent
420 // screen; no agent is asked anything.
421 @MainActor func transcriptCheck() async {
422 func top(_ msg: ChatMessage) -> CGFloat { TranscriptProbe.tops[msg.id] ?? .nan }
423 let first = ChatMessage(role: "user", text: "First made-up message"), second = ChatMessage(role: "assistant", text: "Second made-up message")
424 m.query = ""; m.tab = .agent; m.agentLog = [first, second]; await pause(0.8)
425 report("The second message is drawn above the first", top(second) < top(first) && TranscriptProbe.shownTop == second.id,
426 "second at \(top(second)), first at \(top(first))")
427 let third = ChatMessage(role: "user", text: "Third made-up message")
428 m.agentLog.append(third); await pause(0.8)
429 report("A new message takes the top and pushes the others down", top(third) < top(second) && top(second) < top(first) && TranscriptProbe.shownTop == third.id,
430 "third at \(top(third)), second at \(top(second)), first at \(top(first))")
431 shot("5-chat-newest-on-top")
432 // A long conversation: scroll down into it, then a message arrives.
433 let long = (1...40).map { ChatMessage(role: $0 % 2 == 0 ? "assistant" : "user", text: "Made-up message \($0). " + String(repeating: "More words to fill the line. ", count: $0 % 4)) }
434 m.agentLog = long; await pause(1.0)
435 let scrolls = views(NSScrollView.self, in: app.panel.contentView).filter { ($0.documentView?.frame.height ?? 0) > $0.contentView.bounds.height + 300 }
436 guard let scroll = scrolls.first else {
437 report("Scrolling down and then receiving a message keeps your place", false, "no scrolling page with the conversation was found (\(scrolls.count))")
438 m.agentLog = []; return
439 }
440 func scrollTo(_ y: CGFloat) async { scroll.contentView.scroll(to: NSPoint(x: 0, y: y)); scroll.reflectScrolledClipView(scroll.contentView); await pause(0.8) }
441 func page() -> CGFloat { scroll.contentView.bounds.origin.y }
442 let quietTop = !TranscriptProbe.digging && TranscriptProbe.latestButton == nil
443 guard let newest = long.last else { return }
444 let newestTop = top(newest) // on top now; a message that arrives later must push it down
445 await scrollTo(500)
446 let old = long[20], oldTop = top(old), offset = page()
447 let arrived = ChatMessage(role: "assistant", text: "A message that arrives while you are reading older ones. " + String(repeating: "It is a long one. ", count: 30))
448 m.agentLog.append(arrived); await pause(0.8)
449 let button = TranscriptProbe.latestButton
450 report("Scrolling down and then receiving a message keeps your place, and a button offers the new one",
451 quietTop && TranscriptProbe.digging && TranscriptProbe.waiting == 1 && TranscriptProbe.shownTop == newest.id
452 && top(old) == oldTop && page() == offset && offset >= 500 && button != nil,
453 "at the top no button: \(quietTop); digging=\(TranscriptProbe.digging) waiting=\(TranscriptProbe.waiting); button drawn: \(button != nil); an older message at \(oldTop) then \(top(old)); page at \(offset) then \(page())")
454 shot("6-digging-a-new-message-waits")
455 if let button { await click(button) } // a real click where the button was drawn
456 report("Clicking that button goes to the top, with the new message on top and the others pushed down",
457 !TranscriptProbe.digging && TranscriptProbe.waiting == 0 && TranscriptProbe.shownTop == arrived.id && TranscriptProbe.latestButton == nil
458 && page() <= SpiritOrder.topSlack && top(arrived) == newestTop && top(newest) > newestTop,
459 "digging=\(TranscriptProbe.digging) waiting=\(TranscriptProbe.waiting); button still drawn: \(TranscriptProbe.latestButton != nil); page at \(page()); the new message is at \(top(arrived)); the one before it moved down from \(newestTop) to \(top(newest))")
460 // What Ask does on Enter: your message and an empty answer are added in one step.
461 await scrollTo(500)
462 let diggingAgain = TranscriptProbe.digging
463 let mine = ChatMessage(role: "user", text: "A made-up message you send while reading older ones"), reply = ChatMessage(role: "assistant", text: "")
464 m.agentLog.append(contentsOf: [mine, reply]); await pause(0.9)
465 report("Sending a message yourself brings you back to the top, even with the empty answer added after it",
466 diggingAgain && !TranscriptProbe.digging && TranscriptProbe.shownTop == reply.id && page() <= SpiritOrder.topSlack && top(reply) < top(mine),
467 "was digging: \(diggingAgain); digging now: \(TranscriptProbe.digging); page at \(page()); the answer at \(top(reply)), your message at \(top(mine))")
468 await scrollTo(500)
469 let pageBefore = page()
470 m.agentLog.append(ChatMessage(role: "assistant", text: "Another message that only arrives")); await pause(0.8)
471 report("A message that only arrives does not move you (the control for the row above)", TranscriptProbe.digging && TranscriptProbe.waiting == 1 && page() == pageBefore,
472 "digging=\(TranscriptProbe.digging) waiting=\(TranscriptProbe.waiting); page at \(pageBefore) then \(page())")
473 // A long answer that is still being written: further down inside it the text stays live, and a "busy"
474 // note put in before it (as Ask does) does not take its place. Below it, among older messages, it waits.
475 await scrollTo(0)
476 let tall = ChatMessage(role: "assistant", text: (1...70).map { "Line \($0) of a long made-up answer." }.joined(separator: "\n"))
477 func growTall(_ more: String) { if let i = m.agentLog.firstIndex(where: { $0.id == tall.id }) { m.agentLog[i].text += more } }
478 m.agentLog = Array(long.prefix(32)) + [tall]; await pause(1.0) // enough older messages to get wholly below the answer
479 await scrollTo(300)
480 let inside = TranscriptProbe.digging && TranscriptProbe.shownTop == tall.id
481 growTall("\nGROWN ONCE"); await pause(0.6)
482 let grew = TranscriptProbe.shownTopText.hasSuffix("GROWN ONCE")
483 if let i = m.agentLog.firstIndex(where: { $0.id == tall.id }) { m.agentLog.insert(ChatMessage(role: "note", text: "A made-up busy note"), at: i) }
484 await pause(0.6)
485 let noteWaits = TranscriptProbe.shownTop == tall.id && TranscriptProbe.waiting == 1 && page() == 300
486 report("Reading further down a long answer that is still being written: it keeps growing, and a note put in before it waits",
487 inside && grew && noteWaits, "inside the newest: \(inside); text grew on screen: \(grew); the note waits and the answer stays on show: \(noteWaits); page at \(page()); text held: \(TranscriptProbe.frozen)")
488 await scrollTo((scroll.documentView?.frame.height ?? 0) - scroll.contentView.bounds.height) // the very bottom: the oldest messages
489 let deep = page(), below = TranscriptProbe.frozen, oldest = long[0], oldestTop = top(oldest)
490 growTall("\nGROWN TWICE\nAND MORE\nAND MORE"); await pause(0.6)
491 report("Wholly below an answer that is still being written, among older messages, nothing moves: its new text waits",
492 below && deep > 300 && page() == deep && top(oldest) == oldestTop && TranscriptProbe.shownTop == tall.id && TranscriptProbe.shownTopText.hasSuffix("GROWN ONCE"),
493 "below the answer: \(below); page at \(deep) then \(page()); the oldest message at \(oldestTop) then \(top(oldest)); the text on show ends “\(TranscriptProbe.shownTopText.suffix(10))”")
494 await scrollTo(0)
495 report("Back at the top the whole answer is there", !TranscriptProbe.digging && TranscriptProbe.shownTop == tall.id && TranscriptProbe.shownTopText.hasSuffix("AND MORE"),
496 "digging=\(TranscriptProbe.digging); the text on show ends “\(TranscriptProbe.shownTopText.suffix(10))”")
497 m.agentLog = []; m.query = ""; m.tab = .all
498 }
499 // Ask and Agent are one conversation. What a run says is shown here without a model: the lines are made up
500 // and handed to the same two functions the real run calls (`take`, `finished`).
501 @MainActor func oneConversationCheck() async {
502 m.newAgent(); m.query = ""; m.tab = .agent
503 m.agentLog = [ChatMessage(role: "user", text: "A made-up question")]
504 m.take(.progress("A made-up line saying who answers")); m.take(.answer("A made-up")); m.take(.answer(" answer"))
505 func shape() -> String { m.agentLog.map { "\($0.role):\($0.text)" }.joined(separator: " | ") }
506 report("The answer is one message that grows, with the line about who answers before it",
507 m.agentLog.map(\.role) == ["user", "note", "assistant"] && m.agentLog.last?.text == "A made-up answer", shape())
508 m.take(.problem("A made-up problem"))
509 report("A line that arrives while the answer is being written goes in before it: the answer stays the newest",
510 m.agentLog.map(\.role) == ["user", "note", "note", "assistant"], shape())
511 m.take(.restart); m.take(.answer("A better made-up answer"))
512 report("After a restart line, the answer that follows takes the place of the first one",
513 m.agentLog.filter { $0.role == "assistant" }.map(\.text) == ["A better made-up answer"], shape())
514 m.agentRunning = true
515 m.finished(PickOutcome(ok: true, by: "A made-up mind", meta: "✓ a made-up line under the answer", acted: false, strongerLeft: true))
516 await pause(0.6)
517 report("When the run ends the answer gets its line underneath, Hop is no longer busy, and a stronger mind is noted as left to try",
518 !m.agentRunning && !m.busy && m.strongerLeft && m.agentLog.last?.meta == "✓ a made-up line under the answer", "running=\(m.agentRunning) busy=\(m.busy) stronger left=\(m.strongerLeft)")
519 shot("6-one-conversation")
520 m.agentDryRun = { sent.append($0) }; sent = []
521 m.runStronger()
522 report("Stronger takes the old answer away and hands the same message over again (recorded here, not run)",
523 sent == ["A made-up question"] && m.agentLog.last?.role == "user" && !m.strongerLeft, "sent=\(sent); \(shape())")
524 m.agentLog = [ChatMessage(role: "user", text: "▸ one"), ChatMessage(role: "note", text: "a note"),
525 ChatMessage(role: "assistant", text: ""), ChatMessage(role: "assistant", text: "two")]
526 report("What goes along as the conversation so far is what was said and answered, whatever it starts with: no notes, no empty answers",
527 AppModel.history(m.agentLog).map(\.text) == ["▸ one", "two"], AppModel.history(m.agentLog).map(\.text).joined(separator: " | "))
528 report("No screen is named Ask", !m.tabs.contains { $0.rawValue == "Ask" }, m.tabs.map(\.rawValue).joined(separator: ", "))
529 m.agentLog = []; m.strongerLeft = false; m.query = ""; m.tab = .all
530 }
531 // The one box: what typing puts first, and where Enter sends it. Nothing is opened, pasted or sent:
532 // apps and questions are recorded instead, the copied items are made up.
533 @MainActor func boxCheck() async {
534 var opened: [String] = []
535 sent = []
536 m.launchDryRun = { opened.append($0) }
537 let enterWas = m.config.enterSendsToAgent
538 m.config.enterSendsToAgent = false
539 m.clipboard.showTestItems(["hop box alpha note", "hop box beta note", "hop box gamma note"])
540 func kind(_ r: SmartRow?) -> String {
541 guard let r else { return "nothing" }
542 switch r.kind {
543 case .app(let a, _): return "app " + a.name
544 case .file(let h): return "file " + h.path
545 case .clip(let c): return "clip " + (c.text ?? "")
546 case .url(let u): return "open " + u
547 case .screen(let t): return "screen " + t.rawValue
548 case .command(let c): return "command " + c.rawValue
549 case .account(let e): return "account " + e.account
550 case .agent: return "agent"
551 }
552 }
553 // The moment is made up too: Hop was opened from an app called Editor.
554 func from(_ id: String, _ name: String) { m.context = HopContext(frontID: id, frontName: name, frontPath: "/Applications/\(name).app"); m.refreshSmart() }
555 m.tab = .all; m.query = ""; from("com.example.editor", "Editor"); await pause(0.4)
556 let copied = m.smartRows.filter { kind($0).hasPrefix("clip ") }.count
557 report("With nothing typed the box already offers what you just copied, first", kind(m.smartRows.first) == "clip hop box alpha note" && copied == 3,
558 "first: \(kind(m.smartRows.first)); copied items listed: \(copied) of 3; rows=\(m.rowCount)")
559 let homeLists = views(NSTableView.self, in: app.panel.contentView).count
560 report("With nothing typed there is no list: at most \(AppModel.homeOffers) offers, and the first is the highlighted one",
561 homeLists == 0 && m.rowCount == min(m.smartRows.count, AppModel.homeOffers) && m.rowCount <= AppModel.homeOffers && m.selection == 0,
562 "lists on screen: \(homeLists); offers on show: \(m.rowCount) of \(m.smartRows.count) guesses")
563 // The offers are really drawn: one card each, the first highlighted, and a click on the second highlights it.
564 let shownIDs = m.smartRows.prefix(m.rowCount).map(\.id)
565 let drawn = shownIDs.filter { HomeProbe.cards[$0].map { $0.width > 40 && $0.height > 20 } ?? false }.count
566 let firstLit = HomeProbe.highlighted == shownIDs.first
567 shot("1-opened-nothing-typed")
568 if shownIDs.count > 1, let second = HomeProbe.cards[shownIDs[1]] { await click(second) }
569 let typing = app.panel.firstResponder is NSTextView // the text box's editor
570 report("Each offer is drawn as a card, the first is highlighted, and clicking another highlights that one and leaves the box ready to type in",
571 drawn == shownIDs.count && drawn == m.rowCount && HomeProbe.cards.count == drawn && firstLit && shownIDs.count > 1 && m.selection == 1 && HomeProbe.highlighted == shownIDs[1] && typing,
572 "cards drawn: \(drawn) of \(shownIDs.count); first highlighted: \(firstLit); after a click on the second: highlighted card \(m.selection + 1); typing goes to the box: \(typing) (\(type(of: app.panel.firstResponder as Any)))")
573 m.selection = 0
574 m.query = "message to delete"; await pause(0.3)
575 await key(0, "a", .command); await key(51, "\u{7f}")
576 report("⌘A then Delete empties the text bar", m.query.isEmpty, "query=\"\(m.query)\" key window=\(app.panel.isKeyWindow) first responder=\(type(of: app.panel.firstResponder as Any))")
577 m.query = "textedit"; await pause(0.6)
578 report("Typing an app's name puts the app first", kind(m.smartRows.first) == "app TextEdit", kind(m.smartRows.first))
579 let typedLists = views(NSTableView.self, in: app.panel.contentView).count
580 report("Typing brings the list", typedLists == 1 && m.rowCount == m.smartRows.count, "lists on screen: \(typedLists); lines: \(m.rowCount)")
581 shot("2-typed-app-name")
582 await key(36, "\r")
583 report("Enter opens it, and the box is ready for the next thing", opened == ["/System/Applications/TextEdit.app"] && m.query.isEmpty && m.tab == .all, "opened=\(opened)")
584 m.query = "textedit"; await pause(0.6)
585 let lifted = m.smartRows.first.map { $0.score } ?? 0
586 await key(36, "\r"); await pause(0.3) // opened from Editor a second time: now it is a habit
587 let habit = m.smartRows.first
588 report("An app you keep opening from the same app is offered first, before you type",
589 kind(habit) == "app TextEdit" && habit?.why == "You often open this from Editor" && m.query.isEmpty, "first: \(kind(habit)) (\(habit?.why ?? "-"))")
590 shot("3-learned-habit")
591 from("com.example.other", "Other"); await pause(0.2)
592 report("Opened from a different app, that habit does not push it to the top", kind(m.smartRows.first) == "clip hop box alpha note", kind(m.smartRows.first))
593 m.clipboard.showTestItems(["https://example.com/docs", "hop box alpha note", "hop box beta note", "hop box gamma note"]); await pause(0.4)
594 report("A web address you just copied is offered to open, then to paste",
595 m.smartRows.prefix(2).map(kind) == ["open https://example.com/docs", "clip https://example.com/docs"],
596 m.smartRows.prefix(2).map(kind).joined(separator: " | "))
597 await key(36, "\r")
598 report("Enter opens that address", opened.last == "https://example.com/docs", "opened=\(opened.last ?? "-")")
599 from("com.apple.Safari", "Safari"); await pause(0.2)
600 report("In a browser, pasting the address comes before opening it", m.smartRows.prefix(2).map(kind) == ["clip https://example.com/docs", "open https://example.com/docs"],
601 m.smartRows.prefix(2).map(kind).joined(separator: " | "))
602 m.clipboard.showTestItems(["hop box alpha note", "hop box beta note", "hop box gamma note"])
603 from("com.example.editor", "Editor")
604 m.query = "example.com/docs"; await pause(0.6)
605 report("Typing a web address offers to open it", m.smartRows.contains { kind($0) == "open https://example.com/docs" }, m.smartRows.map(kind).prefix(3).joined(separator: " | "))
606 m.query = "calcu"; await pause(0.6)
607 report("Part of a name is enough", kind(m.smartRows.first) == "app Calculator", kind(m.smartRows.first))
608 m.query = "clacul"; await pause(0.6)
609 report("A swapped letter still finds the app", m.smartRows.contains { kind($0) == "app Calculator" }, kind(m.smartRows.first))
610 let plain = AppCatalog.match("textedit", apps: m.appCatalog.apps).first?.score ?? 0
611 report("An app you opened ranks higher the next time", lifted > plain + 40, "after one open \(lifted), never opened \(plain + 40)")
612 m.query = "beta note"; await pause(0.6)
613 report("Something you copied shows up in the same list", m.smartRows.contains { kind($0) == "clip hop box beta note" }, m.smartRows.map(kind).prefix(4).joined(separator: " | "))
614 m.query = "accounts"; await pause(0.6)
615 report("A screen's name offers that screen", kind(m.smartRows.first) == "screen Accounts", kind(m.smartRows.first))
616 await key(36, "\r")
617 report("Enter shows it, with no screen shortcut needed", m.tab == .accounts && m.query.isEmpty, m.tab.rawValue)
618 // The Agent screen's menu for how much of the agent's work is shown: one run, looked at on three levels.
619 do {
620 let before = (m.agentLog, m.agentDetail, m.tab)
621 m.agentLog = [ChatMessage(role: "user", text: "what is in the notes folder?")] + [
622 #"{"type":"assistant","message":{"content":[{"type":"text","text":"I will look."},{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"ls -la ~/notes | head -3"}}]}}"#,
623 #"{"type":"user","message":{"content":[{"tool_use_id":"t1","type":"tool_result","content":"total 16\nideas.md\ntodo.md","is_error":false}]}}"#,
624 #"{"type":"assistant","message":{"content":[{"type":"text","text":"Two files: ideas.md and todo.md."}]}}"#,
625 ].flatMap(AgentEvents.messages)
626 m.tab = .agent; m.agentDetail = .commands; await pause(0.5); shot("5-agent-commands")
627 let kept = HopConfig.read(HopConfig.url).config.agentDetail
628 let commands = m.agentDetail.shown(m.agentLog).map(\.text)
629 m.agentDetail = .output; await pause(0.4); shot("6-agent-output")
630 let output = m.agentDetail.shown(m.agentLog).count
631 m.agentDetail = .answers; await pause(0.4); shot("7-agent-answers")
632 let answers = m.agentDetail.shown(m.agentLog).count
633 report("The Agent screen shows as much of the agent's work as you choose, and keeps the choice in the settings",
634 kept == "commands" && commands.contains("▸ Bash\nls -la ~/notes | head -3") && output == 5 && answers == 3
635 && HopConfig.read(HopConfig.url).config.agentDetail == "answers",
636 "settings said \(kept) then \(HopConfig.read(HopConfig.url).config.agentDetail); messages shown: commands \(commands.count), output \(output), answers \(answers)")
637 (m.agentLog, m.agentDetail, m.tab) = before
638 }
639 let q = "what is the tallest mountain in Japan?"
640 m.tab = .all; m.query = q; await pause(0.6)
641 report("A question puts the agent first", kind(m.smartRows.first) == "agent", kind(m.smartRows.first))
642 shot("4-typed-question")
643 await key(36, "\r")
644 report("Enter sends the question to the agent and shows the conversation", sent == [q] && m.tab == .agent, "agent=\(sent) tab=\(m.tab.rawValue)")
645 let job = "zq7 make the dock smaller"
646 sent = []
647 m.tab = .all; m.query = job; await pause(1.0)
648 report("A sentence that matches nothing offers one agent line, not an Ask line and an Agent line",
649 m.smartRows.map(kind) == ["agent"], m.smartRows.map(kind).joined(separator: " | "))
650 await key(36, "\r")
651 report("Enter sends it to that same agent", sent == [job] && m.tab == .agent, "agent=\(sent) tab=\(m.tab.rawValue)")
652 // Enter pressed the moment the text is in the box, before this Mac has searched its files for it: the
653 // Enter is kept and carried out when the search is done, once.
654 sent = []
655 m.tab = .all; m.query = job + " please"; m.submit(alt: false)
656 let atOnce = sent.count
657 await pause(1.2)
658 report("Enter pressed before the file search is done is not lost, and sends once", atOnce == 0 && sent == [job + " please"] && m.sendWhenSettled == nil,
659 "sent at once=\(atOnce) after the search=\(sent)")
660 m.tab = .all; m.query = "zq7 make the dock"; m.submit(alt: false); m.query = "zq7 make the dock bigger"; await pause(1.2)
661 report("…and typing on after that Enter sends nothing", sent == [job + " please"] && m.sendWhenSettled == nil, "agent=\(sent)")
662 m.tab = .all; m.query = "zq7 make the dock wider"; m.submit(alt: false)
663 let wasHeld = m.sendWhenSettled != nil
664 m.tab = .find; await pause(1.2); m.tab = .all; await pause(0.6)
665 report("…nor does leaving the box and coming back to the same text", wasHeld && sent == [job + " please"] && m.sendWhenSettled == nil, "held=\(wasHeld) agent=\(sent)")
666 m.tab = .all; m.query = "zq7 make the dock taller"; m.submit(alt: false); m.newAgent(); await pause(1.2)
667 report("…nor does starting a new conversation", sent == [job + " please"] && m.sendWhenSettled == nil, "agent=\(sent)")
668 // Below other lines the agent line is a choice the user makes: Down to it, then Enter (README, Keys).
669 sent = []
670 m.tab = .all; m.query = "textedit"; await pause(1.0)
671 let agentAt = m.smartRows.firstIndex { kind($0) == "agent" } ?? -1
672 for _ in 0..<max(0, agentAt) { await key(125, String(UnicodeScalar(NSDownArrowFunctionKey)!), arrow) }
673 let onAgent = kind(m.smartRows.indices.contains(m.selection) ? m.smartRows[m.selection] : nil), openedBefore = opened.count
674 m.query = "textedit"; let keptAfterWriteBack = m.selection // what the text field does on Enter: same text, no change
675 await key(36, "\r")
676 report("Moving to the agent line and pressing Enter sends it to the agent, and opens nothing",
677 agentAt > 0 && onAgent == "agent" && keptAfterWriteBack == agentAt && sent == ["textedit"] && opened.count == openedBefore,
678 "agent line at \(agentAt); highlighted=\(onAgent) after the same text is written back: line \(keptAfterWriteBack); agent=\(sent) opened=\(opened.count - openedBefore)")
679 m.config.enterSendsToAgent = true
680 m.tab = .all; m.query = job; await pause(1.0)
681 report("enterSendsToAgent changes nothing in the one box: the same one line", m.smartRows.map(kind) == ["agent"], m.smartRows.map(kind).joined(separator: " | "))
682 m.tab = .all; m.query = "textedit"; await pause(0.6)
683 await key(36, "\r", .shift)
684 report("⇧Enter still sends anything to the agent", sent.last == "textedit" && sent.count == 2 && m.tab == .agent, "agent=\(sent)")
685 m.config.enterSendsToAgent = enterWas; sent = []
686 // Nothing typed and nothing copied: every guess is an app, so a wrong Enter would be recorded as an opening.
687 m.clipboard.showTestItems([])
688 m.tab = .all; m.query = ""; from("com.example.editor", "Editor"); await pause(0.4)
689 let guesses = m.smartRows.count
690 for _ in 0..<5 { await key(125, String(UnicodeScalar(NSDownArrowFunctionKey)!), arrow) }
691 let lowest = m.selection
692 let before = opened.count
693 m.selection = AppModel.homeOffers // a guess that is not on show
694 await key(36, "\r")
695 if guesses > AppModel.homeOffers {
696 report("With nothing typed, the keys reach only the offers on show: Enter on a guess that is not shown opens nothing",
697 lowest == AppModel.homeOffers - 1 && opened.count == before && m.query.isEmpty,
698 "\(guesses) guesses, \(AppModel.homeOffers) on show; Down five times stops at offer \(lowest + 1); opened \(opened.count - before)")
699 } else {
700 print("SKIP With nothing typed, the keys reach only the offers on show: this Mac gave only \(guesses) guesses, so none is hidden")
701 }
702 m.launchDryRun = nil; m.query = ""; m.tab = .all
703 }
704 if CommandLine.arguments.contains("--uitest-box") {
705 app.showPanel(); await pause(0.9)
706 await boxCheck(); await transcriptCheck(); await oneConversationCheck(); exit(failures == 0 ? 0 : 1)
707 }
708 if CommandLine.arguments.contains("--uitest-launch") { // really opens TextEdit through the box, then closes it again if it was closed before
709 let id = "com.apple.TextEdit"
710 func running() -> [NSRunningApplication] { NSRunningApplication.runningApplications(withBundleIdentifier: id).filter { !$0.isTerminated } }
711 let wasOpen = !running().isEmpty
712 app.showPanel(); await pause(0.9)
713 m.tab = .all; m.query = "textedit"; await pause(0.6)
714 await key(36, "\r")
715 var w = 0.0
716 while running().isEmpty && w < 8 { await pause(0.25); w += 0.25 }
717 report("Typing an app's name and pressing Enter really opens the app", !running().isEmpty && !app.panel.isVisible,
718 "TextEdit running=\(!running().isEmpty) after \(w)s (was open before: \(wasOpen)); Hop hidden=\(!app.panel.isVisible)")
719 if !wasOpen { running().forEach { $0.terminate() } }
720 exit(failures == 0 ? 0 : 1)
721 }
722 if CommandLine.arguments.contains("--uitest-voice") { // no window shown, nothing typed anywhere
723 await voiceCheck(); exit(failures == 0 ? 0 : 1)
724 }
725 if CommandLine.arguments.contains("--uitest-learn") {
726 // Learning from corrections, end to end in a real app: a throwaway TextEdit document gets a dictation
727 // through the paste path, the test edits the text the way a user would (through accessibility), and Hop
728 // must learn the respelled name and nothing from a reworded word. Refuses if TextEdit is already open.
729 let id = "com.apple.TextEdit"
730 func running() -> [NSRunningApplication] { NSRunningApplication.runningApplications(withBundleIdentifier: id).filter { !$0.isTerminated } }
731 guard running().isEmpty else { print("NOT_RUN --uitest-learn: TextEdit is open; the test only uses a TextEdit it starts itself"); exit(3) }
732 let doc = URL(fileURLWithPath: NSTemporaryDirectory() + "hop-learn-\(ProcessInfo.processInfo.processIdentifier).txt")
733 try? "Notes: ".write(to: doc, atomically: true, encoding: .utf8)
734 func quitTextEdit() async {
735 for a in running() { a.terminate() }
736 var w = 0.0; while !running().isEmpty && w < 5 { await pause(0.25); w += 0.25 }
737 for a in running() { a.forceTerminate() } // only the TextEdit this test started
738 try? FileManager.default.removeItem(at: doc) // exit() below skips any defer
739 }
740 guard let te = NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) else { print("NOT_RUN no TextEdit"); exit(3) }
741 // macOS lets only the active app hand the front to another one, as when Hop opens an app from its box.
742 app.showPanel(); await pause(0.9)
743 let cfg = NSWorkspace.OpenConfiguration(); cfg.activates = true
744 let opened = try? await NSWorkspace.shared.open([doc], withApplicationAt: te, configuration: cfg)
745 // macOS 14 and later activate cooperatively: the active app (Hop, with its panel up) hands the front over.
746 if let opened { NSApp.yieldActivation(to: opened); opened.activate() }
747 await pause(0.5)
748 app.hidePanel()
749 var field: AXUIElement?
750 var w = 0.0
751 while w < 25 { // a cold TextEdit after a long idle can take more than 10 s
752 if NSWorkspace.shared.frontmostApplication?.bundleIdentifier == id, let f = FixLearner.focusedField(),
753 FixLearner.value(f)?.hasPrefix("Notes:") == true { field = f; break }
754 // macOS may keep a newly opened app behind the one in front when nobody has touched the Mac for a
755 // while; the paste permission lets Hop bring the throwaway TextEdit forward itself.
756 if NSWorkspace.shared.frontmostApplication?.bundleIdentifier != id, let te = running().first {
757 AXUIElementSetAttributeValue(AXUIElementCreateApplication(te.processIdentifier), kAXFrontmostAttribute as CFString, kCFBooleanTrue)
758 if Int(w * 4) % 8 == 0 { app.showPanel(); NSApp.yieldActivation(to: te); te.activate(); app.hidePanel() } // every 2 s
759 }
760 await pause(0.25); w += 0.25
761 }
762 guard let field else {
763 let f = FixLearner.focusedField()
764 let windows: Int = running().first.map { te in
765 var v: CFTypeRef?
766 AXUIElementCopyAttributeValue(AXUIElementCreateApplication(te.processIdentifier), kAXWindowsAttribute as CFString, &v)
767 return (v as? [AXUIElement])?.count ?? -1
768 } ?? -2
769 report("TextEdit opened a throwaway document with its text readable", false,
770 "after \(w)s: front=\(NSWorkspace.shared.frontmostApplication?.bundleIdentifier ?? "-") TextEdit running=\(running().count) windows=\(windows) opened=\(opened != nil) trusted=\(AXIsProcessTrusted()) field=\(f != nil) text=\(f.flatMap(FixLearner.value).map { String($0.prefix(20)) } ?? "-")")
771 await quitTextEdit(); exit(1)
772 }
773 func caretToEnd() {
774 var r = CFRange(location: (FixLearner.value(field) ?? "").utf16.count, length: 0)
775 if let v = AXValueCreate(.cfRange, &r) { AXUIElementSetAttributeValue(field, kAXSelectedTextRangeAttribute as CFString, v) }
776 }
777 func userEdits(_ from: String, _ to: String) { // what a user's own correction does to the field
778 let now = FixLearner.value(field) ?? ""
779 AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, now.replacingOccurrences(of: from, with: to) as CFString)
780 caretToEnd()
781 }
782 let d = m.dictation
783 d.isHopFront = { false }; d.learnInTest = true; d.fixWindow = 3
784 d.settings.learnFromFixes = true; d.settings.fixes = []; d.settings.words = []; d.settings.learned = []; d.settings.learning = []
785 caretToEnd()
786 d.deliverForTest("I published it on Zendoto with my notes.")
787 await pause(2.0)
788 let typed = FixLearner.value(field) ?? ""
789 report("A dictation is typed into the app in front", typed.contains("Zendoto with my notes."), "field: “\(typed)”")
790 userEdits("Zendoto", "Zenodo")
791 await pause(3.5)
792 let learned = d.settings.learned.map { "\($0.heard)>\($0.write)" }
793 report("Respelling a new name Hop typed teaches it at once", learned == ["Zendoto>Zenodo"] && Cleanup.apply("upload to zendoto", d.settings) == "Upload to Zenodo",
794 "learned=\(learned) next time “\(Cleanup.apply("upload to zendoto", d.settings))”")
795 d.deliverForTest("We met at the cafe.")
796 await pause(2.0)
797 userEdits("We met at", "We spoke at")
798 await pause(3.5)
799 report("Changing a word for a different word is not learned", d.settings.learned.count == 1 && d.settings.learning.isEmpty,
800 "learned=\(d.settings.learned.count) waiting=\(d.settings.learning.count)")
801 if let first = d.settings.learned.first { d.undoLearned(first) }
802 report("Undo takes the learned fix back out", d.settings.fixes.isEmpty && Cleanup.apply("upload to zendoto", d.settings) == "Upload to zendoto",
803 "fixes=\(d.settings.fixes.count) rejected=\(d.settings.rejected)")
804 await quitTextEdit()
805 report("The throwaway TextEdit is closed again", running().isEmpty, "running=\(running().count)")
806 exit(failures == 0 ? 0 : 1)
807 }
808 if CommandLine.arguments.contains("--uitest-arrows") { // 3-second check, made-up items, nothing pasted
809 m.clipboard.showTestItems((1...6).map { "test clip \($0)" })
810 app.showPanel(); await pause(0.9)
811 let d = String(UnicodeScalar(NSDownArrowFunctionKey)!), u = String(UnicodeScalar(NSUpArrowFunctionKey)!)
812 let fn: NSEvent.ModifierFlags = [.function, .numericPad]
813 await key(125, d, fn); let a = m.selection
814 await key(125, d, fn); let b = m.selection
815 await key(126, u, fn)
816 report("Down / Up arrows move through Clipboard items", a == 1 && b == 2 && m.selection == 1,
817 "rows=\(m.rowCount) key window=\(app.panel.isKeyWindow) first responder=\(type(of: app.panel.firstResponder as Any)) down=\(a),\(b) up=\(m.selection)")
818 exit(failures == 0 ? 0 : 1)
819 }
820 m.tab = .agent
821 app.showPanel()
822 await pause(1.2)
823 report("Opens on the one box", m.tab == .all, "tab=\(m.tab.rawValue), key window=\(app.panel.isKeyWindow)")
824 await key(48, "\t"); report("Tab goes to the next screen", m.tab == .clipboard, m.tab.rawValue)
825 await key(48, "\u{19}", .shift); report("Shift-Tab goes back", m.tab == .all, m.tab.rawValue)
826 await key(124, right, arrow); report("Right arrow in an empty box goes on", m.tab == .clipboard, m.tab.rawValue)
827 await key(123, left, arrow); report("Left arrow in an empty box goes back", m.tab == .all, m.tab.rawValue)
828 m.query = "abc"; await pause(0.2)
829 await key(123, left, arrow); report("Arrows still edit text once you type", m.tab == .all, m.tab.rawValue)
830 m.query = ""; await pause(0.2)
831 await key(20, "3", .command); report("⌘3 jumps straight to the agent", m.tab == .agent, m.tab.rawValue)
832
833 let down = String(UnicodeScalar(NSDownArrowFunctionKey)!), up = String(UnicodeScalar(NSUpArrowFunctionKey)!)
834 m.tab = .find; m.query = "textedit"; await pause(1.0)
835 let findRows = m.rowCount
836 await key(125, down, arrow); let f1 = m.selection
837 await key(126, up, arrow)
838 report("Down / Up arrows move through Find results", findRows < 2 || (f1 == 1 && m.selection == 0), "rows=\(findRows) after down=\(f1) after up=\(m.selection)")
839 m.clipboard.showTestItems((1...6).map { "test clip \($0)" })
840 m.query = ""; m.tab = .clipboard; await pause(0.8)
841 let clipRows = m.rowCount
842 await key(125, down, arrow); let c1 = m.selection
843 await key(125, down, arrow); let c2 = m.selection
844 await key(126, up, arrow)
845 report("Down / Up arrows move through Clipboard items", clipRows >= 3 && c1 == 1 && c2 == 2 && m.selection == 1,
846 "rows=\(clipRows) (lock=\(m.clipboard.lockReason ?? "none")) down=\(c1),\(c2) up=\(m.selection)")
847 m.selection = 0
848
849 let ask = "zq7 make the dock smaller"
850 let enterWas = m.config.enterSendsToAgent
851 m.config.enterSendsToAgent = false
852 m.tab = .clipboard; m.query = ask; await pause(0.4)
853 await key(36, "\r")
854 report("By default, typing a sentence + Enter starts no agent", sent.isEmpty && m.tab == .clipboard, "sent=\(sent)")
855 m.config.enterSendsToAgent = true // the rest checks the opt-in behaviour
856 m.tab = .clipboard; m.query = ask; await pause(0.4)
857 await key(36, "\r")
858 report("With enterSendsToAgent on, typing a problem + Enter sends it to the agent", sent.last == ask && m.tab == .agent, "sent=\(sent)")
859 m.tab = .clipboard; m.query = "zq7zq7"; await pause(0.4)
860 let before = sent.count
861 await key(36, "\r")
862 report("One stray word + Enter does not start an agent", sent.count == before, "sent=\(sent.count - before)")
863 m.query = ""; m.tab = .find; m.query = "textedit"; await pause(0.8)
864 await key(36, "\r", .shift)
865 report("⇧Enter sends anything to the agent", sent.last == "textedit" && m.tab == .agent, "sent=\(sent.last ?? "-")")
866 m.config.enterSendsToAgent = enterWas // back to what the settings say
867
868 m.query = ""; m.tab = .factory
869 app.hidePanel(); await pause(0.3); app.showPanel(); await pause(0.5)
870 report("Reopening lands on the one box again", m.tab == .all, m.tab.rawValue)
871 app.hidePanel(); m.agentUnseen = true; await pause(0.3); app.showPanel(); await pause(0.5)
872 report("Reopening after the agent finished shows its answer", m.tab == .agent && !m.agentUnseen, m.tab.rawValue)
873
874 await boxCheck()
875 await transcriptCheck()
876 await oneConversationCheck()
877 await voiceCheck()
878
879 print(failures == 0 ? "ALL PASS" : "\(failures) FAILED")
880 exit(failures == 0 ? 0 : 1)
881 }
882 }
883}