Skip to content
Source
Sign inSign up
samwillis/jerry
Open History to see the last commit

AgentPrototypeChecks.swift

403 lines37.3 KB

1#if DEBUG
2import AppKit
3import SpriteKit
4import FoundationModels
5import ExpeditionCore
6import Network
7import CryptoKit
8import Security
9​
10@MainActor
11enum AgentPrototypeChecks {
12 private static var previewOverlay: OverlayController?
13 private static var previewController: AgentTaskController?
14 static func showJOLPreview() {
15 let controller = AgentTaskController(journalDirectory: nil); previewController = controller
16 controller.openSettings(section: "Jerry On Line")
17 }
18 static func showJournalPreview() async throws {
19 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("jerry-journal-preview-" + UUID().uuidString)
20 let journal = ExpeditionJournal(storageDirectory: folder)
21 journal.continueExpedition(prompt: "Write a greeting in TextEdit")
22 _ = journal.nameExpedition("The Curious Case of Five Little Letters")
23 journal.append(.request, "Open TextEdit and write hello.", details: "Request · 13:13\nProvider: preview fixture\n\nThis is a disposable visual sample.\nNo screen content was read.")
24 journal.append(.response, "I found TextEdit in Applications. Next, I’ll climb down to a fresh page and leave your greeting there.")
25 // A drawn fixture, never a capture of the user's screen.
26 let image = NSImage(size: .init(width: 640, height: 300))
27 image.lockFocus()
28 NSColor.white.setFill(); NSRect(x: 0, y: 0, width: 640, height: 300).fill()
29 NSColor(white: 0.94, alpha: 1).setFill(); NSRect(x: 0, y: 260, width: 640, height: 40).fill()
30 ("Untitled — TextEdit" as NSString).draw(at: .init(x: 240, y: 273), withAttributes: [.font: NSFont.systemFont(ofSize: 13), .foregroundColor: NSColor.darkGray])
31 ("hello" as NSString).draw(at: .init(x: 28, y: 206), withAttributes: [.font: NSFont.systemFont(ofSize: 22), .foregroundColor: NSColor.black])
32 let rig = ExplorerRig(); rig.handTargets = (.init(x: -18, y: 75), .init(x: 20, y: 78)); rig.seek(to: 1)
33 let scene = SKScene(size: .init(width: 180, height: 160)); scene.backgroundColor = .clear; scene.addChild(rig)
34 let view = SKView(frame: .init(x: 0, y: 0, width: 180, height: 160)); view.presentScene(scene)
35 if let texture = view.texture(from: rig) {
36 NSImage(cgImage: texture.cgImage(), size: texture.size()).draw(in: .init(x: 270, y: 65, width: 100, height: 145))
37 }
38 image.unlockFocus()
39 let jpeg = NSBitmapImageRep(data: image.tiffRepresentation!)!.representation(using: .jpeg, properties: [.compressionFactor: 0.85])!
40 try await journal.savePhoto(jpeg, caption: "A small greeting, safely on the page.")
41 journal.append(.response, "Five letters, one little expedition. I checked the page: “hello” is there in a new document. I’ve left it open for you.")
42 journal.append(.request, "Please keep this document open. Next, add a second line saying: Thanks, Jerry!\nThen check both lines before finishing.", details: "Tool request · inspect\n{\"action\": \"inspect\", \"targetID\": \"\"}\n\nTool response\nA disposable visual fixture with a deliberately longer line to check wrapping in the typed details insert, followed by another paragraph.\n\nNo real computer action was performed.")
43 journal.flush()
44 let controller = AgentTaskController(journalDirectory: folder)
45 previewController = controller; controller.showActivity()
46 if ProcessInfo.processInfo.arguments.contains("--compact") { controller.debugResizeJournal(width: 360, height: 420, sidebar: false) }
47 if ProcessInfo.processInfo.arguments.contains("--wide") { controller.debugResizeJournal(width: 900, height: 650, sidebar: true) }
48 }
49​
50 static func showLivePhotoPreview() async throws {
51 guard #available(macOS 27.0, *), CGPreflightScreenCaptureAccess() else { throw AgentConnectionError(message: "Existing Screen Recording access is required for the live photo fixture. No permission requested.") }
52 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("jerry-live-photo-" + UUID().uuidString)
53 let journal = ExpeditionJournal(storageDirectory: folder)
54 journal.continueExpedition(prompt: "Photograph Jerry at the fixture window")
55 _ = journal.nameExpedition("A Small Summit, A Grand Portrait")
56 let overlay = OverlayController(); previewOverlay = overlay
57 overlay.setIdleExploration(false); overlay.show(); overlay.beginAgent()
58 let computer = ExplorerComputer(); computer.start()
59 computer.photoStage = { overlay.setPhotoMoment($0) }; computer.photoSubject = { overlay.photoSubject }
60 computer.photograph = { data, caption in try await journal.savePhoto(data, caption: caption) }
61 try await Task.sleep(for: .milliseconds(500))
62 _ = try await computer.execute(action: "take_photo", targetID: "", text: "One for the journal — Jerry at the fixture window.", x: 0, y: 0, amount: 0)
63 journal.flush()
64 guard let photo = journal.entries.first(where: { $0.photo != nil }), let url = journal.photoURL(for: photo) else { throw AgentConnectionError(message: "The live photo fixture did not produce a photograph.") }
65 print("LIVE PHOTO", url.path); fflush(stdout)
66 let controller = AgentTaskController(journalDirectory: folder); previewController = controller; controller.showActivity()
67 }
68​
69 private static func checkJOL() async throws -> [(String, Bool)] {
70 var checks: [(String, Bool)] = []
71 let temporary = FileManager.default.temporaryDirectory.appendingPathComponent("Jerry-JOL-Checks-\(UUID())")
72 defer { try? FileManager.default.removeItem(at: temporary) }
73 let journals = temporary.appendingPathComponent("Expeditions")
74 let id = UUID(), row = UUID(), header = JournalRecord.Header(id: id, date: Date(), title: "The Paper Mountain")
75 let store = ExpeditionJournalStore(directory: journals) { _ in }
76 store.append(.init(event: .created, expedition: header), to: id)
77 let entry = ExpeditionJournal.Entry(id: row, date: Date(), kind: .response, text: "I reached the ridge.", details: "Private screen text", photo: UUID().uuidString + ".jpg")
78 store.append(.init(event: .entry, entry: entry), to: id)
79 store.append(.init(event: .detailsAppended, entryID: row, text: "More screen text"), to: id)
80 store.flush()
81 let sync = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Sync"), since: Date.distantPast, includeHistory: false, details: false, photos: false)
82 let batch = try await sync.nextBatches().first!
83 checks.append(("JOL reads committed journal records in order", batch.start == 1 && batch.records.count == 3 && batch.records.first?.event == .created))
84 checks.append(("JOL removes nested technical details and photograph references before upload", batch.records[1].entry?.details == "" && batch.records[1].entry?.photo == nil && batch.records[2].event == .redacted))
85 checks.append(("JOL retry preserves transport event IDs", try await sync.nextBatches().first?.records.map(\.id) == batch.records.map(\.id)))
86 try await sync.acknowledge(batch, cursor: 3)
87 let restored = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Sync"), since: .distantPast, includeHistory: false, details: false, photos: false)
88 checks.append(("JOL accepted cursor survives restarting without replay", try await restored.nextBatches().isEmpty))
89 let future = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Future"), since: Date().addingTimeInterval(10), includeHistory: false, details: false, photos: false)
90 checks.append(("JOL does not upload old journals without history opt-in", try await future.nextBatches().isEmpty))
91 await future.enableHistory()
92 checks.append(("JOL can add older expeditions on the same connection", try await future.nextBatches().first?.expeditionID == id))
93 await restored.enableDetails()
94 let details = try await restored.nextDetails()
95 checks.append(("JOL backfills only previously acknowledged details after opt-in",
96 details.first?.changes.map(\.sequence) == [2, 3] && details.first?.through == 3))
97 if let first = details.first { try await restored.acknowledgeDetails(first) }
98 let enriched = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Sync"),
99 since: .distantPast, includeHistory: false, details: false, photos: false, backfillDetails: true)
100 checks.append(("JOL preserves the details cursor across restart", try await enriched.nextDetails().isEmpty))
101 let file = journals.appendingPathComponent(id.uuidString).appendingPathComponent("journal.jsonl")
102 let handle = try FileHandle(forWritingTo: file); try handle.seekToEnd(); try handle.write(contentsOf: Data("{\"incomplete\":".utf8)); try handle.close()
103 checks.append(("JOL never uploads an uncommitted partial last line", try await restored.nextBatches().isEmpty))
104 try await restored.rememberCommand(id, status: "started")
105 let receipts = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Sync"), since: .distantPast, includeHistory: false, details: false, photos: false)
106 checks.append(("JOL persists accepted command IDs to prevent action replay", await receipts.priorCommand(id) == "started"))
107 checks.append(("JOL accepts an HTTPS origin", (try? JOLManifest.serverURL("https://jol.example.com/"))?.absoluteString == "https://jol.example.com"))
108 checks.append(("JOL rejects credentials, paths and insecure server addresses", ["http://jol.example.com", "https://a:b@jol.example.com", "https://jol.example.com/other", "https://jol.example.com?token=secret"].allSatisfy { (try? JOLManifest.serverURL($0)) == nil }))
109 let offline = JOLController(journalDirectory: nil)
110 checks.append(("JOL is disconnected and remote missions disabled by default", !offline.connected && !offline.remoteArmed))
111 return checks
112 }
113 private static func checkCredentialLabels() throws -> [(String, Bool)] {
114 // Exercise actual Keychain metadata with disposable, non-secret records.
115 // The production namespace and real account credentials are never used.
116 let service = "com.jerry.tests.credentials.\(UUID().uuidString)"
117 func query(_ account: String) -> [String: Any] {
118 [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account]
119 }
120 defer { for name in ["api-key", "chatgpt"] { SecItemDelete(query(name) as CFDictionary) } }
121 let account = AgentCredentials.Account(clientID: "test-client", subject: "test-subject", email: "test@example.invalid", accessToken: "not-a-real-token", refreshToken: "not-a-real-refresh-token", idToken: "", expiresAt: .distantFuture, scopes: [])
122 for (name, data) in [("api-key", Data("not-a-real-api-key".utf8)), ("chatgpt", try JSONEncoder().encode(account))] {
123 var item = query(name)
124 item[kSecValueData as String] = data; item[kSecAttrLabel as String] = "The Other Sock"
125 item[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
126 guard SecItemAdd(item as CFDictionary, nil) == errSecSuccess else { throw AgentConnectionError(message: "Could not create disposable Keychain check item.") }
127 }
128 func label(_ name: String) -> String? {
129 var q = query(name); q[kSecReturnAttributes as String] = true
130 q[kSecUseAuthenticationUI as String] = kSecUseAuthenticationUIFail
131 var item: CFTypeRef?
132 guard SecItemCopyMatching(q as CFDictionary, &item) == errSecSuccess else { return nil }
133 return (item as? [String: Any])?[kSecAttrLabel as String] as? String
134 }
135 let credentials = AgentCredentials(service: service)
136 let preserved = try credentials.apiKey() == "not-a-real-api-key" && credentials.account?.clientID == account.clientID
137 var checks = [("legacy Keychain labels become Jerry without changing saved API keys or ChatGPT accounts", preserved && label("api-key") == "Jerry — API key" && label("chatgpt") == "Jerry — ChatGPT")]
138 credentials.removeAPIKey(); try credentials.saveAPIKey("new-test-key")
139 checks.append(("new Keychain entries use Jerry labels", label("api-key") == "Jerry — API key"))
140 try credentials.saveAPIKey("updated-test-key")
141 checks.append(("updating a saved key preserves Jerry labels and the other connection", try credentials.apiKey() == "updated-test-key" && label("api-key") == "Jerry — API key" && credentials.account?.clientID == account.clientID))
142 return checks
143 }
144 private static func checkJournalPersistence() async throws -> [(String, Bool)] {
145 let root = FileManager.default.temporaryDirectory.appendingPathComponent("jerry-journal-check-\(UUID().uuidString)", isDirectory: true)
146 var journals: [ExpeditionJournal] = []
147 defer { journals.forEach { $0.flush() }; try? FileManager.default.removeItem(at: root) }
148 func journal(_ directory: URL) -> ExpeditionJournal {
149 let model = ExpeditionJournal(storageDirectory: directory); journals.append(model); return model
150 }
151 func appendBytes(_ data: Data, to url: URL) throws {
152 let file = try FileHandle(forWritingTo: url); defer { try? file.close() }
153 try file.seekToEnd(); try file.write(contentsOf: data); try file.synchronize()
154 }
155 let original = journal(root)
156 let first = original.continueExpedition(prompt: "Find a patterned sock")
157 let request = original.append(.request, "Find a patterned sock")
158 let response = original.append(.response, "")
159 var streamed = ""
160 for chunk in ["Hello", " 👩🏽‍🚀", " — café", "\nOne small discovery."] { streamed += chunk; original.update(response, text: streamed) }
161 let corrected = "A corrected note 👩🏽‍🚀\nThe sock has stripes."
162 original.update(response, text: corrected)
163 original.addDetails(response, "Tool metadata"); original.addDetails(response, "A later result")
164 original.status = "Inspecting the window…"; original.isRunning = true; original.flush()
165 let file = root.appendingPathComponent(first.uuidString).appendingPathComponent("journal.jsonl")
166 let lines = try Data(contentsOf: file).split(separator: 10)
167 let objects = try lines.map { try JSONSerialization.jsonObject(with: Data($0)) as! [String: Any] }
168 var checks = [("an expedition gets its own folder containing only a versioned JSONL journal", try FileManager.default.contentsOfDirectory(atPath: file.deletingLastPathComponent().path) == ["journal.jsonl"] && objects.allSatisfy { $0["version"] as? Int == 1 } && objects.contains { $0["event"] as? String == "textAppended" })]
169 checks.append(("new expeditions wait for an AI name instead of copying the prompt", original.selected?.title == "An untitled adventure"))
170 let rejectsCopiedPrompt = !original.nameExpedition("Find a patterned sock")
171 let named = original.nameExpedition("The Striped Sock Summit")
172 original.flush()
173 checks.append(("an AI expedition name persists and follow-up prompts do not rename it", named && rejectsCopiedPrompt && !original.nameExpedition("A second name") && journal(root).selected?.title == "The Striped Sock Summit"))
174 let restored = journal(root)
175 checks.append(("journal restart restores IDs, Unicode messages and expandable details", restored.activeID == first && restored.entries.first?.id == request && restored.entries.first { $0.id == response }?.text == corrected && restored.entries.first { $0.id == response }?.details == "Tool metadata\n\nA later result"))
176 checks.append(("a running expedition restores paused without restarting computer actions", !restored.isRunning && restored.selected?.status.contains("Paused after restarting") == true && restored.selected?.isFinished == false))
177 restored.flush()
178 let duplicate = lines.first { line in (try? JSONSerialization.jsonObject(with: Data(line)) as? [String: Any])?["event"] as? String == "textAppended" }!
179 try appendBytes(Data(duplicate) + Data([10]), to: file)
180 let deduplicated = journal(root)
181 checks.append(("retrying a previously appended event cannot duplicate streamed text", deduplicated.entries.first { $0.id == response }?.text == corrected))
182 try appendBytes(Data("{\"version\":1,\"event\":\"entry\"".utf8), to: file)
183 let recovered = journal(root)
184 checks.append(("a truncated final record preserves complete notes and reports recovery", recovered.entries.first { $0.id == response }?.text == corrected && recovered.storageIssue != nil))
185 recovered.append(.activity, "Recovered after an interrupted write"); recovered.flush()
186 let continued = journal(root)
187 checks.append(("new notes remain readable after an interrupted JSONL tail", continued.entries.contains { $0.text == "Recovered after an interrupted write" }))
188 continued.finishActive()
189 let second = continued.continueExpedition(prompt: "A second expedition")
190 continued.append(.request, "Keep this mission separate"); continued.finishActive()
191 let separate = journal(root)
192 checks.append(("finished expeditions restore separately with their completion state", separate.expeditions.count == 2 && separate.activeID == nil && separate.expeditions.allSatisfy(\.isFinished) && separate.exportText().contains("Keep this mission separate")))
193 separate.continueExpedition(prompt: "A follow-up direction", id: first)
194 separate.append(.request, "A follow-up direction"); separate.flush()
195 let resumed = journal(root)
196 checks.append(("an earlier expedition remains open and resumable after another restart", resumed.activeID == first && resumed.selectedID == first && resumed.entries.last?.text == "A follow-up direction" && resumed.expeditions.first { $0.id == second }?.isFinished == true))
197 // Photos share the expedition directory; old entries without photo metadata still decode.
198 let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 12, pixelsHigh: 8, bitsPerSample: 8, samplesPerPixel: 3, hasAlpha: false, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
199 bitmap.bitmapData?.initialize(repeating: 240, count: bitmap.bytesPerRow * bitmap.pixelsHigh)
200 let jpeg = bitmap.representation(using: .jpeg, properties: [:])!
201 try await resumed.savePhoto(jpeg, caption: "I found the result.")
202 resumed.flush()
203 let album = journal(root)
204 let photo = album.entries.first { $0.photo != nil }!
205 let photoURL = album.photoURL(for: photo)!
206 checks.append(("local photographs round-trip as assets beside their expedition notes", try Data(contentsOf: photoURL) == jpeg && NSImage(contentsOf: photoURL) != nil && photo.text == "I found the result." && album.exportText().contains(photo.photo!)))
207 var invalidPhoto = photo; invalidPhoto.photo = "../../outside.jpg"
208 checks.append(("journal photograph paths reject traversal", album.photoURL(for: invalidPhoto) == nil))
209 try FileManager.default.removeItem(at: photoURL)
210 checks.append(("a missing photograph preserves its caption and journal history", album.photoURL(for: photo) == nil && journal(root).entries.contains { $0.id == photo.id && $0.text == photo.text }))
211 let controller = AgentTaskController(journalDirectory: root)
212 checks.append(("the journal window restores an open expedition with Finish available and no running task", controller.debugCheckRestoredJournal(id: first, text: "A follow-up direction")))
213 resumed.append(.activity, "Saved automatically")
214 var automatic = false
215 for _ in 0..<20 {
216 try await Task.sleep(for: .milliseconds(100))
217 let snapshot = ExpeditionJournalStore(directory: root, report: { _ in }).restore()
218 automatic = snapshot.expeditions.contains { $0.entries.contains { $0.text == "Saved automatically" } }
219 if automatic { break }
220 }
221 checks.append(("batched journal records save automatically without an explicit flush", automatic))
222 let futureID = UUID(), futureFolder = root.appendingPathComponent(futureID.uuidString)
223 try FileManager.default.createDirectory(at: futureFolder, withIntermediateDirectories: true)
224 var future = JournalRecord(event: .created, expedition: .init(id: futureID, date: Date(), title: "Newer format")); future.version = 2
225 let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .millisecondsSince1970
226 let futureBytes = try encoder.encode(future) + Data([10])
227 let futureFile = futureFolder.appendingPathComponent("journal.jsonl"); try futureBytes.write(to: futureFile)
228 let unsupported = journal(root); unsupported.flush()
229 checks.append(("newer journal formats stay untouched and do not hide readable expeditions", try unsupported.expeditions.count == 2 && unsupported.storageIssue != nil && Data(contentsOf: futureFile) == futureBytes))
230 let asset = file.deletingLastPathComponent().appendingPathComponent("future-asset.txt")
231 try Data("Future asset fixture".utf8).write(to: asset)
232 let withAssets = journal(root)
233 checks.append(("unrelated future assets in an expedition folder are preserved", try withAssets.expeditions.count == 2 && String(contentsOf: asset, encoding: .utf8) == "Future asset fixture"))
234 let blocked = root.appendingPathComponent("blocked-storage")
235 let failed = journal(blocked) // Create the obstruction after a clean initial read.
236 try Data("obstruction".utf8).write(to: blocked)
237 failed.continueExpedition(prompt: "Survive a save failure"); failed.append(.request, "Keep this unsaved note"); failed.flush()
238 try await Task.sleep(for: .milliseconds(20))
239 checks.append(("save failures are visible while retaining the journal in memory", failed.saveFailed && failed.storageIssue != nil && failed.entries.first?.text == "Keep this unsaved note"))
240 try FileManager.default.removeItem(at: blocked)
241 failed.retrySaving(); failed.flush()
242 try await Task.sleep(for: .milliseconds(20))
243 let retried = journal(blocked)
244 checks.append(("retry saves retained records after a filesystem failure is fixed", !failed.saveFailed && failed.storageIssue == nil && retried.entries.first?.text == "Keep this unsaved note"))
245 return checks
246 }
247​
248 static func run() async -> Bool {
249 var passed = true
250 func check(_ condition: Bool, _ label: String) { print("AGENT \(condition ? "PASS" : "FAIL") \(label)"); fflush(stdout); passed = passed && condition }
251 let viewport = WorldRect(x: 0, y: 0, width: 1000, height: 800)
252 do {
253 for (name, result) in try await checkJOL() { check(result, name) }
254 for (name, result) in try await checkJournalPersistence() { check(result, name) }
255 for (name, result) in try checkCredentialLabels() { check(result, name) }
256 if #available(macOS 27.0, *) {
257 var calls = 0
258 let scripted = #"{"action":"inspect","targetID":"","text":"","x":0,"y":0,"amount":0}"#
259 let model = ExplorerLanguageModel(executorConfiguration: .init(model: "scripted", bearer: "", scriptedPlan: scripted, sessionID: UUID()))
260 let tool = ExplorerComputerTool { args in calls += 1; return Prompt("Computer tool received \(args.action). No input is injected by this test.") }
261 let session = LanguageModelSession(model: model, tools: [tool], instructions: "Test the native computer tool loop.")
262 var response = "", hasSnapshotResponse = false
263 for try await partial in session.streamResponse(to: "Inspect the active app.") {
264 response = partial.content
265 hasSnapshotResponse = hasSnapshotResponse || partial.transcriptEntries.contains { if case .response = $0 { return true }; return false }
266 }
267 check(hasSnapshotResponse, "stream snapshots expose response entries for the full journal")
268 check(calls == 1 && response.contains("Offline"), "Foundation Models invokes the computer tool and streams its final response")
269 let outputCount = session.transcript.filter { if case .toolOutput = $0 { return true }; return false }.count
270 check(outputCount == 1, "native computer tool output is included exactly once")
271 let continued = LanguageModelSession(model: model, tools: [tool], transcript: AgentTaskController.continuableTranscript(session.transcript))
272 for try await _ in continued.streamResponse(to: "Continue the same expedition with a second direction.") { }
273 let prompts = continued.transcript.compactMap { entry -> String? in
274 if case .prompt(let prompt) = entry { return prompt.segments.compactMap { if case .text(let text) = $0 { return text.content }; return nil }.joined() }
275 return nil
276 }
277 check(prompts.count == 2 && prompts.first?.contains("Inspect the active app.") == true && prompts.last?.contains("second direction") == true, "continuing a native model session retains the first request and the new direction")
278 let interrupted = Transcript(entries: session.transcript.filter { if case .toolOutput = $0 { return false }; return true })
279 let repaired = AgentTaskController.continuableTranscript(interrupted)
280 check(!repaired.contains { if case .toolCalls = $0 { return true }; return false }, "interrupted transcript repair removes tool calls without results before continuing")
281 let image = CGContext(data: nil, width: 2, height: 2, bitsPerComponent: 8, bytesPerRow: 8, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!.makeImage()!
282 var pictured = session.transcript
283 for index in pictured.indices {
284 if case .toolOutput(var output) = pictured[index] {
285 output.segments.append(.attachment(.init(content: .image(.init(image)))))
286 pictured[index] = .toolOutput(output)
287 }
288 }
289 func hasImages(_ transcript: Transcript) -> Bool {
290 transcript.contains { entry in
291 if case .toolOutput(let output) = entry { return output.segments.contains { if case .attachment = $0 { return true }; return false } }
292 return false
293 }
294 }
295 check(!hasImages(AgentTaskController.continuableTranscript(pictured, includeImages: false)), "continuation removes previous screen images when sharing is off")
296 check(hasImages(AgentTaskController.continuableTranscript(pictured, includeImages: true)), "continuation retains screen context only with image sharing enabled")
297 let definition = Transcript.ToolDefinition(tool: tool)
298 let schema = try JSONSerialization.jsonObject(with: JSONEncoder().encode(definition.parameters)) as? [String: Any]
299 check(schema?["type"] as? String == "object", "computer tool schemas encode to JSON Schema")
300 } else { check(false, "macOS 27 Foundation Models provider availability") }
301 let scene = ExplorerScene(size: .init(width: 1000, height: 800))
302 check(scene.children.filter { $0 is ExplorerRig }.count == 1, "the scene contains one explorer and no recruitment system")
303 scene.layout(in: .init(x: 0, y: 90, width: 1000, height: 710))
304 scene.updateTerrain(.init(windows: [], viewport: viewport))
305 scene.setAgentMode(true); scene.agentTarget = .init(x: 500, y: 1)
306 for frame in 0..<900 {
307 if frame == 600 {
308 scene.layout(in: .init(x: 0, y: 110, width: 1000, height: 690))
309 scene.updateTerrain(.init(windows: [], viewport: viewport))
310 }
311 scene.update(Double(frame) / 30)
312 }
313 check(scene.agentAtTarget, "the rendered hand reaches the Dock reveal edge after visible-frame changes")
314 scene.setAgentMode(false)
315 let spottingScene = ExplorerScene(size: .init(width: 1000, height: 800))
316 spottingScene.layout(in: .init(x: 0, y: 0, width: 1000, height: 800))
317 spottingScene.updateTerrain(.init(windows: [], viewport: viewport)); spottingScene.setIdleExploration(true)
318 let spottingRig = spottingScene.children.compactMap { $0 as? ExplorerRig }.first!
319 var tick = 0
320 while tick < 900 && !spottingRig.usingBinoculars { spottingScene.update(Double(tick) / 60); tick += 1 }
321 let sharedBinoculars = spottingRig.childNode(withName: "//binoculars")
322 check(spottingRig.usingBinoculars && sharedBinoculars?.isHidden == false, "idle sock spotting uses the explorer's head-mounted binoculars")
323 spottingScene.setAgentMode(true); spottingScene.agentReading = true; spottingScene.update(Double(tick + 1) / 60)
324 check(spottingRig.childNode(withName: "//binoculars") === sharedBinoculars && sharedBinoculars?.isHidden == false && spottingRig.clampedContacts == 0, "AI reading uses the same binoculars and reachable two-hand grip")
325 spottingScene.agentReading = false; spottingScene.update(Double(tick + 2) / 60)
326 check(sharedBinoculars?.isHidden == true, "finishing screen reading puts the binoculars away")
327 let keyboardFrame = CGRect(x: 100, y: 400, width: 600, height: 200)
328 let keyboard = ExplorerComputer.VisibleWindow(pid: 101, frame: keyboardFrame, alpha: 1)
329 check(ExplorerComputer.visibleWindow(keyboardFrame, pid: 101, in: [keyboard]), "a visible keyboard window matches its AX geometry")
330 check(!ExplorerComputer.visibleWindow(keyboardFrame, pid: 101, in: []), "remembered AX keyboard geometry is rejected when its window is hidden")
331 check(!ExplorerComputer.visibleWindow(keyboardFrame, pid: 102, in: [keyboard]), "another running keyboard process cannot borrow a visible window")
332 check(!ExplorerComputer.visibleWindow(keyboardFrame, pid: 101, in: [.init(pid: 101, frame: keyboardFrame, alpha: 0)]), "a transparent keyboard window is not visible")
333 check(!ExplorerComputer.visibleWindow(keyboardFrame.offsetBy(dx: 800, dy: 0), pid: 101, in: [keyboard]), "stale key-window positions do not match a moved keyboard")
334 let keyPoint = CGPoint(x: 300, y: 450)
335 let covering = ExplorerComputer.VisibleWindow(pid: 202, frame: keyboardFrame, alpha: 1)
336 check(!ExplorerComputer.windowIsFrontmost(at: keyPoint, pid: 101, ignoring: 303, in: [covering, keyboard]), "covered keyboard keys cannot receive physical presses")
337 check(ExplorerComputer.windowIsFrontmost(at: keyPoint, pid: 101, ignoring: 202, in: [covering, keyboard]), "only the explorer's own withdrawn overlay is ignored")
338 let suite = "JerryPermissionChecks." + UUID().uuidString
339 let permissionDefaults = UserDefaults(suiteName: suite)!
340 defer { permissionDefaults.removePersistentDomain(forName: suite) }
341 let denied = DesktopAccess.Snapshot(accessibility: false, screenRecording: false)
342 check(DesktopAccess.needed(for: denied, defaults: permissionDefaults).isEmpty, "a fresh install does not demand optional desktop permissions")
343 permissionDefaults.set(true, forKey: "exploreInsideWindows")
344 check(DesktopAccess.needed(for: denied, defaults: permissionDefaults) == [.screenRecording], "enabled internal ledges identify missing Screen Recording at startup")
345 permissionDefaults.set("configured-model", forKey: "agentModelID")
346 check(DesktopAccess.needed(for: denied, defaults: permissionDefaults) == [.accessibility, .screenRecording], "configured desktop tasks and terrain identify both missing grants")
347 check(DesktopAccess.needed(for: .init(accessibility: true, screenRecording: true), defaults: permissionDefaults).isEmpty, "valid macOS grants do not trigger startup repair")
348 permissionDefaults.removeObject(forKey: "agentModelID"); permissionDefaults.set(false, forKey: "exploreInsideWindows")
349 permissionDefaults.set(true, forKey: "desktopAccessibilityGranted")
350 check(DesktopAccess.needed(for: denied, defaults: permissionDefaults) == [.accessibility], "a lost previous Accessibility grant is detected after an app change")
351 let screen = CGRect(x: 0, y: 0, width: 1440, height: 900)
352 let helperSize = CGSize(width: 380, height: 510)
353 let settingsFrame = CGRect(x: 200, y: 80, width: 700, height: 760)
354 let right = DesktopAccess.setupFrame(size: helperSize, beside: settingsFrame, in: screen)
355 check(right != nil && !right!.intersects(settingsFrame) && screen.contains(right!), "access helper fits beside Settings without covering its controls")
356 let shifted = settingsFrame.offsetBy(dx: 400, dy: 0)
357 let left = DesktopAccess.setupFrame(size: helperSize, beside: shifted, in: screen)
358 check(left != nil && left!.maxX < shifted.minX, "access helper can use the left side without clamping onto Settings")
359 check(DesktopAccess.setupFrame(size: helperSize, beside: .init(x: 100, y: 40, width: 1240, height: 820), in: screen) == nil, "no side space leaves the helper in place instead of overlapping Settings")
360 let drag = JerryApplicationDragView()
361 let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() }
362 board.writeObjects([drag.applicationURL as NSURL])
363 let dragged = (board.readObjects(forClasses: [NSURL.self]) as? [URL])?.first
364 check(dragged == Bundle.main.bundleURL && dragged?.pathExtension == "app", "permission drag exports the exact running app as a file URL")
365 let history = ExpeditionJournal(storageDirectory: nil)
366 let first = history.continueExpedition(prompt: "First expedition")
367 history.append(.request, "First expedition")
368 let response = history.append(.response, "First reply")
369 history.isRunning = false
370 check(history.continueExpedition(prompt: "A follow-up") == first && history.expeditions.count == 1, "an expedition stays open between replies and follow-ups reuse it")
371 history.append(.request, "A follow-up")
372 history.prepareNew()
373 check(history.activeID == nil && history.selectedID == nil, "finishing or preparing a new expedition leaves no active conversation")
374 let second = history.continueExpedition(prompt: "Second expedition")
375 history.append(.request, "Second expedition"); history.select(first)
376 history.append(.activity, "Second expedition progress")
377 history.update(response, text: "Updated first reply")
378 check(history.entries.contains { $0.text == "Updated first reply" } && !history.entries.contains { $0.text == "Second expedition progress" }, "browsing an older expedition cannot redirect live progress or response updates")
379 check(history.expeditions.first { $0.id == second }?.entries.contains { $0.text == "Second expedition progress" } == true, "live entries remain attached to the active expedition")
380 check(history.continueExpedition(prompt: "Resume the first", id: first) == first && history.activeID == first && history.expeditions.count == 2, "a selected earlier expedition can be resumed without merging histories")
381 history.finishActive()
382 let third = history.continueExpedition(prompt: "Third expedition")
383 check(third != first && third != second && history.expeditions.count == 3 && history.exportText().contains("Second expedition"), "a prompt after finishing creates a new expedition and export retains all histories")
384 let journal = AgentTaskController(journalDirectory: nil)
385 for (name, passed) in journal.debugCheckSettings() { check(passed, name) }
386 check(await journal.debugCheckJournalFocus(), "showing and automatically focusing the journal cannot pause an expedition")
387 check(await journal.debugCheckTrafficLights(), "native traffic lights stay inside the paper margin after toolbar layout and resizing")
388 check(journal.debugCheckLogIsolation(), "late progress from a cancelled execution cannot create or change an expedition")
389 let journalChecks = journal.debugCheckJournal()
390 check(journalChecks.0, "streaming Unicode response updates preserve subsequent tool log entries")
391 check(journalChecks.1, "the journal preserves requests across tasks")
392 check(journalChecks.2, "human journal entries keep tool output and metadata inside details")
393 journal.closeAll()
394 let verifier = try AgentCredentials.randomToken()
395 let otherVerifier = try AgentCredentials.randomToken()
396 check(verifier.count == 43 && verifier != otherVerifier, "OAuth attempts use independent random PKCE values")
397 let challenge = Data(SHA256.hash(data: Data("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk".utf8))).base64URL
398 check(challenge == "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "PKCE matches the RFC S256 test vector")
399 } catch { check(false, "prototype round trip: \(error.localizedDescription)") }
400 return passed
401 }
403#endif