Open History to see the last commit
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 bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 12, pixelsHigh: 8, bitsPerSample: 8, samplesPerPixel: 3, hasAlpha: false, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
78 bitmap.bitmapData?.initialize(repeating: 240, count: bitmap.bytesPerRow * bitmap.pixelsHigh)
79 let photograph = bitmap.representation(using: .jpeg, properties: [:])!
80 let filename = try await store.savePhoto(photograph, to: id)
81 let entry = ExpeditionJournal.Entry(id: row, date: Date(), kind: .response, text: "I reached the ridge.", details: "Private screen text", photo: filename)
82 store.append(.init(event: .entry, entry: entry), to: id)
83 store.append(.init(event: .detailsAppended, entryID: row, text: "More screen text"), to: id)
84 store.flush()
85 let sync = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Sync"), since: Date.distantPast, includeHistory: false, details: false, photos: false)
86 let batch = try await sync.nextBatches().first!
87 checks.append(("JOL reads committed journal records in order", batch.start == 1 && batch.records.count == 3 && batch.records.first?.event == .created))
88 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))
89 checks.append(("JOL retry preserves transport event IDs", try await sync.nextBatches().first?.records.map(\.id) == batch.records.map(\.id)))
90 try await sync.acknowledge(batch, cursor: 3)
91 let restored = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Sync"), since: .distantPast, includeHistory: false, details: false, photos: false)
92 checks.append(("JOL accepted cursor survives restarting without replay", try await restored.nextBatches().isEmpty))
93 checks.append(("JOL keeps saved photographs local until explicitly shared", try await restored.nextPhotos().isEmpty))
94 await restored.enablePhotos()
95 let photos = try await restored.nextPhotos()
96 checks.append(("JOL finds an existing photograph and the acknowledged entry it belongs to",
97 photos.count == 1 && photos.first?.entryID == row && photos.first?.data == photograph))
98 if let photo = photos.first { try await restored.acknowledgePhoto(photo) }
99 let future = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Future"), since: Date().addingTimeInterval(10), includeHistory: false, details: false, photos: false)
100 checks.append(("JOL does not upload old journals without history opt-in", try await future.nextBatches().isEmpty))
101 await future.enableHistory()
102 checks.append(("JOL can add older expeditions on the same connection", try await future.nextBatches().first?.expeditionID == id))
103 await restored.enableDetails()
104 let details = try await restored.nextDetails()
105 checks.append(("JOL backfills only previously acknowledged details after opt-in",
106 details.first?.changes.map(\.sequence) == [2, 3] && details.first?.through == 3))
107 if let first = details.first { try await restored.acknowledgeDetails(first) }
108 let enriched = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Sync"),
109 since: .distantPast, includeHistory: false, details: false, photos: false, backfillDetails: true, backfillPhotos: true)
110 checks.append(("JOL preserves the details cursor across restart", try await enriched.nextDetails().isEmpty))
111 checks.append(("JOL does not re-upload an acknowledged photograph after restart", try await enriched.nextPhotos().isEmpty))
112 let file = journals.appendingPathComponent(id.uuidString).appendingPathComponent("journal.jsonl")
113 let handle = try FileHandle(forWritingTo: file); try handle.seekToEnd(); try handle.write(contentsOf: Data("{\"incomplete\":".utf8)); try handle.close()
114 checks.append(("JOL never uploads an uncommitted partial last line", try await restored.nextBatches().isEmpty))
115 try await restored.rememberCommand(id, status: "started")
116 let receipts = try JOLSyncStore(journals: journals, directory: temporary.appendingPathComponent("Sync"), since: .distantPast, includeHistory: false, details: false, photos: false)
117 checks.append(("JOL persists accepted command IDs to prevent action replay", await receipts.priorCommand(id) == "started"))
118 checks.append(("JOL accepts an HTTPS origin", (try? JOLManifest.serverURL("https://jol.example.com/"))?.absoluteString == "https://jol.example.com"))
119 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 }))
120 let offline = JOLController(journalDirectory: nil)
121 checks.append(("JOL is disconnected and remote missions disabled by default", !offline.connected && !offline.remoteArmed))
122 return checks
123 }
124 private static func checkCredentialLabels() throws -> [(String, Bool)] {
125 // Exercise actual Keychain metadata with disposable, non-secret records.
126 // The production namespace and real account credentials are never used.
127 let service = "com.jerry.tests.credentials.\(UUID().uuidString)"
128 func query(_ account: String) -> [String: Any] {
129 [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account]
130 }
131 defer { for name in ["api-key", "chatgpt"] { SecItemDelete(query(name) as CFDictionary) } }
132 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: [])
133 for (name, data) in [("api-key", Data("not-a-real-api-key".utf8)), ("chatgpt", try JSONEncoder().encode(account))] {
134 var item = query(name)
135 item[kSecValueData as String] = data; item[kSecAttrLabel as String] = "The Other Sock"
136 item[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
137 guard SecItemAdd(item as CFDictionary, nil) == errSecSuccess else { throw AgentConnectionError(message: "Could not create disposable Keychain check item.") }
138 }
139 func label(_ name: String) -> String? {
140 var q = query(name); q[kSecReturnAttributes as String] = true
141 q[kSecUseAuthenticationUI as String] = kSecUseAuthenticationUIFail
142 var item: CFTypeRef?
143 guard SecItemCopyMatching(q as CFDictionary, &item) == errSecSuccess else { return nil }
144 return (item as? [String: Any])?[kSecAttrLabel as String] as? String
145 }
146 let credentials = AgentCredentials(service: service)
147 let preserved = try credentials.apiKey() == "not-a-real-api-key" && credentials.account?.clientID == account.clientID
148 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")]
149 credentials.removeAPIKey(); try credentials.saveAPIKey("new-test-key")
150 checks.append(("new Keychain entries use Jerry labels", label("api-key") == "Jerry — API key"))
151 try credentials.saveAPIKey("updated-test-key")
152 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))
153 return checks
154 }
155 private static func checkJournalPersistence() async throws -> [(String, Bool)] {
156 let root = FileManager.default.temporaryDirectory.appendingPathComponent("jerry-journal-check-\(UUID().uuidString)", isDirectory: true)
157 var journals: [ExpeditionJournal] = []
158 defer { journals.forEach { $0.flush() }; try? FileManager.default.removeItem(at: root) }
159 func journal(_ directory: URL) -> ExpeditionJournal {
160 let model = ExpeditionJournal(storageDirectory: directory); journals.append(model); return model
161 }
162 func appendBytes(_ data: Data, to url: URL) throws {
163 let file = try FileHandle(forWritingTo: url); defer { try? file.close() }
164 try file.seekToEnd(); try file.write(contentsOf: data); try file.synchronize()
165 }
166 let original = journal(root)
167 let first = original.continueExpedition(prompt: "Find a patterned sock")
168 let request = original.append(.request, "Find a patterned sock")
169 let response = original.append(.response, "")
170 var streamed = ""
171 for chunk in ["Hello", " 👩🏽🚀", " — café", "\nOne small discovery."] { streamed += chunk; original.update(response, text: streamed) }
172 let corrected = "A corrected note 👩🏽🚀\nThe sock has stripes."
173 original.update(response, text: corrected)
174 original.addDetails(response, "Tool metadata"); original.addDetails(response, "A later result")
175 original.status = "Inspecting the window…"; original.isRunning = true; original.flush()
176 let file = root.appendingPathComponent(first.uuidString).appendingPathComponent("journal.jsonl")
177 let lines = try Data(contentsOf: file).split(separator: 10)
178 let objects = try lines.map { try JSONSerialization.jsonObject(with: Data($0)) as! [String: Any] }
179 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" })]
180 checks.append(("new expeditions wait for an AI name instead of copying the prompt", original.selected?.title == "An untitled adventure"))
181 let rejectsCopiedPrompt = !original.nameExpedition("Find a patterned sock")
182 let named = original.nameExpedition("The Striped Sock Summit")
183 original.flush()
184 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"))
185 let restored = journal(root)
186 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"))
187 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))
188 restored.flush()
189 let duplicate = lines.first { line in (try? JSONSerialization.jsonObject(with: Data(line)) as? [String: Any])?["event"] as? String == "textAppended" }!
190 try appendBytes(Data(duplicate) + Data([10]), to: file)
191 let deduplicated = journal(root)
192 checks.append(("retrying a previously appended event cannot duplicate streamed text", deduplicated.entries.first { $0.id == response }?.text == corrected))
193 try appendBytes(Data("{\"version\":1,\"event\":\"entry\"".utf8), to: file)
194 let recovered = journal(root)
195 checks.append(("a truncated final record preserves complete notes and reports recovery", recovered.entries.first { $0.id == response }?.text == corrected && recovered.storageIssue != nil))
196 recovered.append(.activity, "Recovered after an interrupted write"); recovered.flush()
197 let continued = journal(root)
198 checks.append(("new notes remain readable after an interrupted JSONL tail", continued.entries.contains { $0.text == "Recovered after an interrupted write" }))
199 continued.finishActive()
200 let second = continued.continueExpedition(prompt: "A second expedition")
201 continued.append(.request, "Keep this mission separate"); continued.finishActive()
202 let separate = journal(root)
203 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")))
204 separate.continueExpedition(prompt: "A follow-up direction", id: first)
205 separate.append(.request, "A follow-up direction"); separate.flush()
206 let resumed = journal(root)
207 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))
208 // Photos share the expedition directory; old entries without photo metadata still decode.
209 let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 12, pixelsHigh: 8, bitsPerSample: 8, samplesPerPixel: 3, hasAlpha: false, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
210 bitmap.bitmapData?.initialize(repeating: 240, count: bitmap.bytesPerRow * bitmap.pixelsHigh)
211 let jpeg = bitmap.representation(using: .jpeg, properties: [:])!
212 try await resumed.savePhoto(jpeg, caption: "I found the result.")
213 resumed.flush()
214 let album = journal(root)
215 let photo = album.entries.first { $0.photo != nil }!
216 let photoURL = album.photoURL(for: photo)!
217 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!)))
218 var invalidPhoto = photo; invalidPhoto.photo = "../../outside.jpg"
219 checks.append(("journal photograph paths reject traversal", album.photoURL(for: invalidPhoto) == nil))
220 try FileManager.default.removeItem(at: photoURL)
221 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 }))
222 let controller = AgentTaskController(journalDirectory: root)
223 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")))
224 resumed.append(.activity, "Saved automatically")
225 var automatic = false
226 for _ in 0..<20 {
227 try await Task.sleep(for: .milliseconds(100))
228 let snapshot = ExpeditionJournalStore(directory: root, report: { _ in }).restore()
229 automatic = snapshot.expeditions.contains { $0.entries.contains { $0.text == "Saved automatically" } }
230 if automatic { break }
231 }
232 checks.append(("batched journal records save automatically without an explicit flush", automatic))
233 let futureID = UUID(), futureFolder = root.appendingPathComponent(futureID.uuidString)
234 try FileManager.default.createDirectory(at: futureFolder, withIntermediateDirectories: true)
235 var future = JournalRecord(event: .created, expedition: .init(id: futureID, date: Date(), title: "Newer format")); future.version = 2
236 let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .millisecondsSince1970
237 let futureBytes = try encoder.encode(future) + Data([10])
238 let futureFile = futureFolder.appendingPathComponent("journal.jsonl"); try futureBytes.write(to: futureFile)
239 let unsupported = journal(root); unsupported.flush()
240 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))
241 let asset = file.deletingLastPathComponent().appendingPathComponent("future-asset.txt")
242 try Data("Future asset fixture".utf8).write(to: asset)
243 let withAssets = journal(root)
244 checks.append(("unrelated future assets in an expedition folder are preserved", try withAssets.expeditions.count == 2 && String(contentsOf: asset, encoding: .utf8) == "Future asset fixture"))
245 let blocked = root.appendingPathComponent("blocked-storage")
246 let failed = journal(blocked) // Create the obstruction after a clean initial read.
247 try Data("obstruction".utf8).write(to: blocked)
248 failed.continueExpedition(prompt: "Survive a save failure"); failed.append(.request, "Keep this unsaved note"); failed.flush()
249 try await Task.sleep(for: .milliseconds(20))
250 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"))
251 try FileManager.default.removeItem(at: blocked)
252 failed.retrySaving(); failed.flush()
253 try await Task.sleep(for: .milliseconds(20))
254 let retried = journal(blocked)
255 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"))
256 return checks
257 }
258
259 static func run() async -> Bool {
260 var passed = true
261 func check(_ condition: Bool, _ label: String) { print("AGENT \(condition ? "PASS" : "FAIL") \(label)"); fflush(stdout); passed = passed && condition }
262 let viewport = WorldRect(x: 0, y: 0, width: 1000, height: 800)
263 do {
264 for (name, result) in try await checkJOL() { check(result, name) }
265 for (name, result) in try await checkJournalPersistence() { check(result, name) }
266 for (name, result) in try checkCredentialLabels() { check(result, name) }
267 if #available(macOS 27.0, *) {
268 var calls = 0
269 let scripted = #"{"action":"inspect","targetID":"","text":"","x":0,"y":0,"amount":0}"#
270 let model = ExplorerLanguageModel(executorConfiguration: .init(model: "scripted", bearer: "", scriptedPlan: scripted, sessionID: UUID()))
271 let tool = ExplorerComputerTool { args in calls += 1; return Prompt("Computer tool received \(args.action). No input is injected by this test.") }
272 let session = LanguageModelSession(model: model, tools: [tool], instructions: "Test the native computer tool loop.")
273 var response = "", hasSnapshotResponse = false
274 for try await partial in session.streamResponse(to: "Inspect the active app.") {
275 response = partial.content
276 hasSnapshotResponse = hasSnapshotResponse || partial.transcriptEntries.contains { if case .response = $0 { return true }; return false }
277 }
278 check(hasSnapshotResponse, "stream snapshots expose response entries for the full journal")
279 check(calls == 1 && response.contains("Offline"), "Foundation Models invokes the computer tool and streams its final response")
280 let outputCount = session.transcript.filter { if case .toolOutput = $0 { return true }; return false }.count
281 check(outputCount == 1, "native computer tool output is included exactly once")
282 let continued = LanguageModelSession(model: model, tools: [tool], transcript: AgentTaskController.continuableTranscript(session.transcript))
283 for try await _ in continued.streamResponse(to: "Continue the same expedition with a second direction.") { }
284 let prompts = continued.transcript.compactMap { entry -> String? in
285 if case .prompt(let prompt) = entry { return prompt.segments.compactMap { if case .text(let text) = $0 { return text.content }; return nil }.joined() }
286 return nil
287 }
288 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")
289 let interrupted = Transcript(entries: session.transcript.filter { if case .toolOutput = $0 { return false }; return true })
290 let repaired = AgentTaskController.continuableTranscript(interrupted)
291 check(!repaired.contains { if case .toolCalls = $0 { return true }; return false }, "interrupted transcript repair removes tool calls without results before continuing")
292 let image = CGContext(data: nil, width: 2, height: 2, bitsPerComponent: 8, bytesPerRow: 8, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!.makeImage()!
293 var pictured = session.transcript
294 for index in pictured.indices {
295 if case .toolOutput(var output) = pictured[index] {
296 output.segments.append(.attachment(.init(content: .image(.init(image)))))
297 pictured[index] = .toolOutput(output)
298 }
299 }
300 func hasImages(_ transcript: Transcript) -> Bool {
301 transcript.contains { entry in
302 if case .toolOutput(let output) = entry { return output.segments.contains { if case .attachment = $0 { return true }; return false } }
303 return false
304 }
305 }
306 check(!hasImages(AgentTaskController.continuableTranscript(pictured, includeImages: false)), "continuation removes previous screen images when sharing is off")
307 check(hasImages(AgentTaskController.continuableTranscript(pictured, includeImages: true)), "continuation retains screen context only with image sharing enabled")
308 let definition = Transcript.ToolDefinition(tool: tool)
309 let schema = try JSONSerialization.jsonObject(with: JSONEncoder().encode(definition.parameters)) as? [String: Any]
310 check(schema?["type"] as? String == "object", "computer tool schemas encode to JSON Schema")
311 } else { check(false, "macOS 27 Foundation Models provider availability") }
312 let scene = ExplorerScene(size: .init(width: 1000, height: 800))
313 check(scene.children.filter { $0 is ExplorerRig }.count == 1, "the scene contains one explorer and no recruitment system")
314 scene.layout(in: .init(x: 0, y: 90, width: 1000, height: 710))
315 scene.updateTerrain(.init(windows: [], viewport: viewport))
316 scene.setAgentMode(true); scene.agentTarget = .init(x: 500, y: 1)
317 for frame in 0..<900 {
318 if frame == 600 {
319 scene.layout(in: .init(x: 0, y: 110, width: 1000, height: 690))
320 scene.updateTerrain(.init(windows: [], viewport: viewport))
321 }
322 scene.update(Double(frame) / 30)
323 }
324 check(scene.agentAtTarget, "the rendered hand reaches the Dock reveal edge after visible-frame changes")
325 scene.setAgentMode(false)
326 let spottingScene = ExplorerScene(size: .init(width: 1000, height: 800))
327 spottingScene.layout(in: .init(x: 0, y: 0, width: 1000, height: 800))
328 spottingScene.updateTerrain(.init(windows: [], viewport: viewport)); spottingScene.setIdleExploration(true)
329 let spottingRig = spottingScene.children.compactMap { $0 as? ExplorerRig }.first!
330 var tick = 0
331 while tick < 900 && !spottingRig.usingBinoculars { spottingScene.update(Double(tick) / 60); tick += 1 }
332 let sharedBinoculars = spottingRig.childNode(withName: "//binoculars")
333 check(spottingRig.usingBinoculars && sharedBinoculars?.isHidden == false, "idle sock spotting uses the explorer's head-mounted binoculars")
334 spottingScene.setAgentMode(true); spottingScene.agentReading = true; spottingScene.update(Double(tick + 1) / 60)
335 check(spottingRig.childNode(withName: "//binoculars") === sharedBinoculars && sharedBinoculars?.isHidden == false && spottingRig.clampedContacts == 0, "AI reading uses the same binoculars and reachable two-hand grip")
336 spottingScene.agentReading = false; spottingScene.update(Double(tick + 2) / 60)
337 check(sharedBinoculars?.isHidden == true, "finishing screen reading puts the binoculars away")
338 let keyboardFrame = CGRect(x: 100, y: 400, width: 600, height: 200)
339 let keyboard = ExplorerComputer.VisibleWindow(pid: 101, frame: keyboardFrame, alpha: 1)
340 check(ExplorerComputer.visibleWindow(keyboardFrame, pid: 101, in: [keyboard]), "a visible keyboard window matches its AX geometry")
341 check(!ExplorerComputer.visibleWindow(keyboardFrame, pid: 101, in: []), "remembered AX keyboard geometry is rejected when its window is hidden")
342 check(!ExplorerComputer.visibleWindow(keyboardFrame, pid: 102, in: [keyboard]), "another running keyboard process cannot borrow a visible window")
343 check(!ExplorerComputer.visibleWindow(keyboardFrame, pid: 101, in: [.init(pid: 101, frame: keyboardFrame, alpha: 0)]), "a transparent keyboard window is not visible")
344 check(!ExplorerComputer.visibleWindow(keyboardFrame.offsetBy(dx: 800, dy: 0), pid: 101, in: [keyboard]), "stale key-window positions do not match a moved keyboard")
345 let keyPoint = CGPoint(x: 300, y: 450)
346 let covering = ExplorerComputer.VisibleWindow(pid: 202, frame: keyboardFrame, alpha: 1)
347 check(!ExplorerComputer.windowIsFrontmost(at: keyPoint, pid: 101, ignoring: 303, in: [covering, keyboard]), "covered keyboard keys cannot receive physical presses")
348 check(ExplorerComputer.windowIsFrontmost(at: keyPoint, pid: 101, ignoring: 202, in: [covering, keyboard]), "only the explorer's own withdrawn overlay is ignored")
349 let suite = "JerryPermissionChecks." + UUID().uuidString
350 let permissionDefaults = UserDefaults(suiteName: suite)!
351 defer { permissionDefaults.removePersistentDomain(forName: suite) }
352 let denied = DesktopAccess.Snapshot(accessibility: false, screenRecording: false)
353 check(DesktopAccess.needed(for: denied, defaults: permissionDefaults).isEmpty, "a fresh install does not demand optional desktop permissions")
354 permissionDefaults.set(true, forKey: "exploreInsideWindows")
355 check(DesktopAccess.needed(for: denied, defaults: permissionDefaults) == [.screenRecording], "enabled internal ledges identify missing Screen Recording at startup")
356 permissionDefaults.set("configured-model", forKey: "agentModelID")
357 check(DesktopAccess.needed(for: denied, defaults: permissionDefaults) == [.accessibility, .screenRecording], "configured desktop tasks and terrain identify both missing grants")
358 check(DesktopAccess.needed(for: .init(accessibility: true, screenRecording: true), defaults: permissionDefaults).isEmpty, "valid macOS grants do not trigger startup repair")
359 permissionDefaults.removeObject(forKey: "agentModelID"); permissionDefaults.set(false, forKey: "exploreInsideWindows")
360 permissionDefaults.set(true, forKey: "desktopAccessibilityGranted")
361 check(DesktopAccess.needed(for: denied, defaults: permissionDefaults) == [.accessibility], "a lost previous Accessibility grant is detected after an app change")
362 let screen = CGRect(x: 0, y: 0, width: 1440, height: 900)
363 let helperSize = CGSize(width: 380, height: 510)
364 let settingsFrame = CGRect(x: 200, y: 80, width: 700, height: 760)
365 let right = DesktopAccess.setupFrame(size: helperSize, beside: settingsFrame, in: screen)
366 check(right != nil && !right!.intersects(settingsFrame) && screen.contains(right!), "access helper fits beside Settings without covering its controls")
367 let shifted = settingsFrame.offsetBy(dx: 400, dy: 0)
368 let left = DesktopAccess.setupFrame(size: helperSize, beside: shifted, in: screen)
369 check(left != nil && left!.maxX < shifted.minX, "access helper can use the left side without clamping onto Settings")
370 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")
371 let drag = JerryApplicationDragView()
372 let board = NSPasteboard.withUniqueName(); defer { board.releaseGlobally() }
373 board.writeObjects([drag.applicationURL as NSURL])
374 let dragged = (board.readObjects(forClasses: [NSURL.self]) as? [URL])?.first
375 check(dragged == Bundle.main.bundleURL && dragged?.pathExtension == "app", "permission drag exports the exact running app as a file URL")
376 let history = ExpeditionJournal(storageDirectory: nil)
377 let first = history.continueExpedition(prompt: "First expedition")
378 history.append(.request, "First expedition")
379 let response = history.append(.response, "First reply")
380 history.isRunning = false
381 check(history.continueExpedition(prompt: "A follow-up") == first && history.expeditions.count == 1, "an expedition stays open between replies and follow-ups reuse it")
382 history.append(.request, "A follow-up")
383 history.prepareNew()
384 check(history.activeID == nil && history.selectedID == nil, "finishing or preparing a new expedition leaves no active conversation")
385 let second = history.continueExpedition(prompt: "Second expedition")
386 history.append(.request, "Second expedition"); history.select(first)
387 history.append(.activity, "Second expedition progress")
388 history.update(response, text: "Updated first reply")
389 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")
390 check(history.expeditions.first { $0.id == second }?.entries.contains { $0.text == "Second expedition progress" } == true, "live entries remain attached to the active expedition")
391 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")
392 history.finishActive()
393 let third = history.continueExpedition(prompt: "Third expedition")
394 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")
395 let journal = AgentTaskController(journalDirectory: nil)
396 for (name, passed) in journal.debugCheckSettings() { check(passed, name) }
397 check(await journal.debugCheckJournalFocus(), "showing and automatically focusing the journal cannot pause an expedition")
398 check(await journal.debugCheckTrafficLights(), "native traffic lights stay inside the paper margin after toolbar layout and resizing")
399 check(journal.debugCheckLogIsolation(), "late progress from a cancelled execution cannot create or change an expedition")
400 let journalChecks = journal.debugCheckJournal()
401 check(journalChecks.0, "streaming Unicode response updates preserve subsequent tool log entries")
402 check(journalChecks.1, "the journal preserves requests across tasks")
403 check(journalChecks.2, "human journal entries keep tool output and metadata inside details")
404 journal.closeAll()
405 let verifier = try AgentCredentials.randomToken()
406 let otherVerifier = try AgentCredentials.randomToken()
407 check(verifier.count == 43 && verifier != otherVerifier, "OAuth attempts use independent random PKCE values")
408 let challenge = Data(SHA256.hash(data: Data("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk".utf8))).base64URL
409 check(challenge == "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "PKCE matches the RFC S256 test vector")
410 } catch { check(false, "prototype round trip: \(error.localizedDescription)") }
411 return passed
412 }
413}
414#endif