// SPDX-License-Identifier: GPL-3.0-or-later import XCTest import AppKit /// The interpreter is the tokenizer oracle. Optional private ROMs never enter Git. @MainActor final class BASICBridgeTests: XCTestCase { override func setUp() async throws { try await super.setUp() await MainActor.run { _ = NSApplication.shared } } private func command(_ body: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { await withCheckedContinuation { continuation in body { continuation.resume(returning: $0) } } } private func read(_ controller: VCCMachineController) async -> (String?, String?) { await withCheckedContinuation { continuation in controller.basicReadSource { source, snapshot in continuation.resume(returning: (source, snapshot.errorMessage)) } } } private func export(_ controller: VCCMachineController, source: String, name: String = "HELLO", cassette: Bool) async -> (Data?, VCCMachineSnapshot) { await withCheckedContinuation { continuation in controller.basicExportSource(source, name: name, cassette: cassette) { data, snapshot in continuation.resume(returning: (data, snapshot)) } } } private func assertExportPreservesSession(_ after: VCCMachineSnapshot, _ before: VCCMachineSnapshot, file: StaticString = #filePath, line: UInt = #line) { XCTAssertEqual(after.state, before.state, file: file, line: line) XCTAssertEqual(after.generation, before.generation, file: file, line: line) XCTAssertEqual(after.debuggerProgramRevision, before.debuggerProgramRevision, file: file, line: line) XCTAssertEqual(after.debuggerMappingFingerprint, before.debuggerMappingFingerprint, file: file, line: line) XCTAssertEqual(after.use6309, before.use6309, file: file, line: line) XCTAssertEqual(after.ramConfiguration, before.ramConfiguration, file: file, line: line) XCTAssertEqual(after.audioEnabled, before.audioEnabled, file: file, line: line) XCTAssertEqual(after.pasteRemaining, before.pasteRemaining, file: file, line: line) XCTAssertEqual(after.disks[0].name, before.disks[0].name, file: file, line: line) XCTAssertEqual(after.disks[0].mounted, before.disks[0].mounted, file: file, line: line) XCTAssertEqual(after.disks[0].dirty, before.disks[0].dirty, file: file, line: line) XCTAssertEqual(after.disks[0].writeProtected, before.disks[0].writeProtected, file: file, line: line) XCTAssertEqual(after.tapeMounted, before.tapeMounted, file: file, line: line) XCTAssertEqual(after.tapeDirty, before.tapeDirty, file: file, line: line) XCTAssertEqual(after.tapeMode, before.tapeMode, file: file, line: line) XCTAssertEqual(after.tapePosition, before.tapePosition, file: file, line: line) XCTAssertEqual(after.tapeLength, before.tapeLength, file: file, line: line) XCTAssertEqual(after.cartridgeKinds, before.cartridgeKinds, file: file, line: line) XCTAssertEqual(after.physicalSlot, before.physicalSlot, file: file, line: line) XCTAssertEqual(after.romSlot, before.romSlot, file: file, line: line) XCTAssertEqual(after.ioSlot, before.ioSlot, file: file, line: line) } private func memory(_ controller: VCCMachineController) async -> VCCDebuggerSnapshot { await withCheckedContinuation { continuation in controller.debuggerSnapshot(address: 0, followPC: false, memoryAddress: 0) { continuation.resume(returning: $0) } } } private func programBytes(_ controller: VCCMachineController) async throws -> Data { let capture = await memory(controller) let bytes = [UInt8](capture.logicalMemory) XCTAssertEqual(bytes.count, 65536) guard bytes.count == 65536 else { throw Failure.invalidMemory } let start = Int(bytes[0x19]) * 256 + Int(bytes[0x1a]) let end = Int(bytes[0x1b]) * 256 + Int(bytes[0x1c]) guard start >= 0x600, end >= start, end < 0x8000 else { throw Failure.invalidMemory } return Data(bytes[start.. String { await withCheckedContinuation { continuation in controller.copyScreenText { text, _ in continuation.resume(returning: text ?? "") } } } private func waitForScreen(_ text: String, controller: VCCMachineController, context: String = "") async throws { for _ in 0..<300 { if await screen(controller).contains(text) { return } try await Task.sleep(nanoseconds: 20_000_000) } let current = await screen(controller) XCTFail("\(context) BASIC screen did not contain \(text): \(current)") throw Failure.timeout } private func settle(_ controller: VCCMachineController, frames: UInt64 = 20) async throws { let before = await command(controller.snapshot) if before.state != .running { _ = await command(controller.resume) } for _ in 0..<300 { if await command(controller.snapshot).frames >= before.frames + frames { return } try await Task.sleep(nanoseconds: 20_000_000) } throw Failure.timeout } private func withBASIC(_ body: (VCCMachineController) async throws -> Void) async throws { let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() let roms = mac.appendingPathComponent("LocalResources/ROMs") let system = roms.appendingPathComponent("coco3.rom"), disk = roms.appendingPathComponent("disk11.rom") try XCTSkipUnless(FileManager.default.fileExists(atPath: system.path) && FileManager.default.fileExists(atPath: disk.path), "Stage the licensed local CoCo 3 and Disk BASIC ROMs for direct BASIC integration checks") let systemBytes = try Data(contentsOf: system), diskBytes = try Data(contentsOf: disk) let starter = mac.appendingPathComponent("Resources/StarterMedia") for use6309 in [false, true] { let controller = VCCMachineController() do { _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } _ = await command { controller.loadDiskROM(diskBytes, name: "Disk BASIC", completion: $0) } _ = await command { controller.configureCartridges([2, 0, 0, 0, 2], roms: Array(repeating: Data(), count: 5), names: Array(repeating: "", count: 5), multiPak: true, physicalSlot: 4, completion: $0) } let image = try Data(contentsOf: starter.appendingPathComponent("Hello World.dsk")) let cassette = try Data(contentsOf: starter.appendingPathComponent("Hello World.cas")) _ = await command { controller.mountDisk(image, drive: 0, name: "Preserved.dsk", readOnly: true, completion: $0) } _ = await command { controller.mountTape(cassette, wav: false, completion: $0) } let loaded = await command { controller.loadROM(systemBytes, use6309: use6309, completion: $0) } XCTAssertNil(loaded.errorMessage) _ = await command(controller.resume) try await waitForScreen("OK", controller: controller) try await settle(controller) try await body(controller) _ = await command(controller.shutdown) } catch { _ = await command(controller.shutdown) throw error } } } private func basicProfileStore(mac: URL, root: URL) throws -> StartupStore { let kit = StarterKit(directory: root.appendingPathComponent("Kit")) try FileManager.default.createDirectory(at: kit.directory, withIntermediateDirectories: true) for name in ["coco3.rom", "disk11.rom", "rgbdos.rom", "sdcdos.rom"] { let input = mac.appendingPathComponent("LocalResources/ROMs/" + name) try XCTSkipUnless(FileManager.default.fileExists(atPath: input.path), "Stage optional private ROM: " + name) try FileManager.default.copyItem(at: input, to: kit.directory.appendingPathComponent(name)) } for name in ["Hello World.dsk", "Hello World.cas", "Blank Disk.dsk", "Hello Hard Disk.dsk", "Blank OS9 Header.bin"] { try FileManager.default.copyItem(at: mac.appendingPathComponent("Resources/StarterMedia/" + name), to: kit.directory.appendingPathComponent(name)) } return StartupStore(directory: root.appendingPathComponent("Support"), kit: kit) } func testSharedMachineStatusReportsGuestAndRunBlockersWithoutChangingMedia() async throws { try await withBASIC { controller in let snapshot = await self.command(controller.assistantReadiness) XCTAssertEqual(snapshot.assistantEmptyBASIC, true) let status = MCPMachineStatus.result(snapshot, workspace: .cmoc(needsFloppy: true), buildBlockers: [], runBlockers: [], lastBuild: ["build_id": "last", "revision": 1, "status": "failed", "diagnostics": ["detail"]]) XCTAssertEqual(status["processor"] as? String, snapshot.use6309 ? "HD6309" : "MC6809") let build = try XCTUnwrap(status["build"] as? [String: Any]) XCTAssertEqual(build["available"] as? Bool, true) let last = try XCTUnwrap(build["last_build"] as? [String: Any]) XCTAssertEqual(last["build_id"] as? String, "last") XCTAssertEqual(last["status"] as? String, "failed") XCTAssertNil(last["diagnostics"]) let disks = try XCTUnwrap(status["floppy_drives"] as? [[String: Any]]) XCTAssertEqual(disks[0]["mounted"] as? Bool, true) XCTAssertEqual(disks[0]["write_protected"] as? Bool, true) XCTAssertNil(disks[0]["name"]) let run = try XCTUnwrap(status["run"] as? [String: Any]) let reasons = try XCTUnwrap(run["blockers"] as? [String]) XCTAssertTrue(reasons.contains { $0.contains("cassette") }) XCTAssertTrue(reasons.contains { $0.contains("drive 0") }) _ = await self.command(controller.discardTape) let observed = await self.command(controller.assistantReadiness) let assembly = MCPMachineStatus.result(observed, workspace: .assembly(needs6309: true), buildBlockers: [], runBlockers: []) let assemblyRun = try XCTUnwrap(assembly["run"] as? [String: Any]) XCTAssertEqual(assemblyRun["ready_for_native_run"] as? Bool, snapshot.use6309) XCTAssertEqual(observed.disks.first?.name, snapshot.disks.first?.name) XCTAssertEqual(observed.generation, snapshot.generation) XCTAssertEqual(observed.debuggerProgramRevision, snapshot.debuggerProgramRevision) let ordinary = MCPMachineStatus.result(observed, workspace: .cmoc(needsFloppy: false), buildBlockers: [], runBlockers: []) let ordinaryRun = try XCTUnwrap(ordinary["run"] as? [String: Any]) let ordinaryReasons = try XCTUnwrap(ordinaryRun["blockers"] as? [String]) XCTAssertFalse(ordinaryReasons.contains { $0.contains("drive 0") }) XCTAssertEqual(ordinary["basic_program_loaded"] as? Bool, false) let source = "10 PRINT \"KEEP MY PROGRAM\"" let loaded = await self.command { controller.basicLoadSource(source, run: false, completion: $0) } XCTAssertNil(loaded.errorMessage) let occupied = await self.command(controller.assistantReadiness) let blocked = MCPMachineStatus.result(occupied, workspace: .cmoc(needsFloppy: false), buildBlockers: [], runBlockers: []) XCTAssertEqual(blocked["basic_program_loaded"] as? Bool, true) let blockers = try XCTUnwrap((blocked["run"] as? [String: Any])?["blockers"] as? [String]) XCTAssertTrue(blockers.contains(MCPMachineStatus.occupiedBASICGuidance)) let denied = await self.command { controller.startReviewedC(Data(), disk: nil, name: "", stop: 0x2800, expected: occupied, completion: $0) } XCTAssertEqual(denied.errorMessage, "occupied_basic_program") let retained: String? = await withCheckedContinuation { done in controller.basicReadSource { text, _ in done.resume(returning: text) } } XCTAssertEqual(retained?.trimmingCharacters(in: .newlines), source) XCTAssertEqual(denied.debuggerProgramRevision, occupied.debuggerProgramRevision) XCTAssertEqual(denied.disks.first?.name, snapshot.disks.first?.name) } } func testReviewedBASICLoadRetriesOnlyPromptRefusalAndPreservesReviewAuthority() async throws { _ = NSApplication.shared let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() let roms = mac.appendingPathComponent("LocalResources/ROMs") for file in ["coco3.rom", "disk11.rom"] { try XCTSkipUnless(FileManager.default.fileExists(atPath: roms.appendingPathComponent(file).path), "Stage private BASIC ROMs") } let suite = "ReviewedBASICRetry-" + UUID().uuidString let root = FileManager.default.temporaryDirectory.appendingPathComponent(suite) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: root) } let controller = VCCMachineController() let machine = MachineModel(diskStore: .init(url: root.appendingPathComponent("drives.json")), controller: controller, displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("input.json"))) do { for _ in 0..<300 where machine.busy { try await Task.sleep(for: .milliseconds(20)) } for use6309 in [false, true] { try await MCPBASICRun.bootFixture(machine, romDirectory: roms, use6309: use6309) let emptySource = await machine.readBASICSource() let existing = try XCTUnwrap(emptySource) let initial = await machine.mcpMachineSnapshot() // Held Shift deterministically causes the exact read-only core // refusal. Release only when approval is checked after that // refused attempt and its retry wait, never before dispatch. controller.setKeyboardMask(CocoKeyboard.shift) var approvalChecks = 0 let loaded = await machine.loadBASICSource("10 GOTO 10\n", run: true, review: (initial, existing), reviewIsCurrent: { approvalChecks += 1 if approvalChecks == 2 { controller.setKeyboardMask(0) } return true }) XCTAssertGreaterThanOrEqual(approvalChecks, 2) let started = try XCTUnwrap(loaded, machine.fileError ?? "Reviewed retry failed") XCTAssertEqual(started.generation, initial.generation) XCTAssertEqual(started.debuggerProgramRevision, initial.debuggerProgramRevision + 1, "Only the successful queue transaction may install the program") try await settle(controller) let source = await machine.readBASICSource() let runningSource = try XCTUnwrap(source) let expected = await machine.mcpMachineSnapshot() let original = try await programBytes(controller) let replacement = "10 PRINT 99\n" var staleChecks = 0 let stale = await machine.loadBASICSource(replacement, run: true, review: (initial, runningSource), reviewIsCurrent: { staleChecks += 1; return true }) XCTAssertNil(stale); XCTAssertEqual(staleChecks, 1) XCTAssertEqual(machine.fileError, "The CoCo or its loaded program changed. Start a new reviewed run.") var sourceChecks = 0 let changedSource = await machine.loadBASICSource(replacement, run: true, review: (expected, runningSource + "20 REM NOT REVIEWED\n"), reviewIsCurrent: { sourceChecks += 1; return true }) XCTAssertNil(changedSource); XCTAssertEqual(sourceChecks, 1) XCTAssertEqual(machine.fileError, "The program in BASIC memory changed. Review it before continuing.") var revokedChecks = 0 let revoked = await machine.loadBASICSource(replacement, run: true, review: (expected, runningSource), reviewIsCurrent: { revokedChecks += 1; return revokedChecks == 1 }) XCTAssertNil(revoked); XCTAssertEqual(revokedChecks, 2) XCTAssertEqual(machine.fileError, "The approved revision or connection changed.") var cancelledChecks = 0 let cancelled = Task { @MainActor in await machine.loadBASICSource(replacement, run: true, review: (expected, runningSource), reviewIsCurrent: { cancelledChecks += 1 if cancelledChecks == 2 { withUnsafeCurrentTask { $0?.cancel() } } return true }) } let cancelledResult = await cancelled.value XCTAssertNil(cancelledResult); XCTAssertEqual(cancelledChecks, 2) XCTAssertEqual(machine.fileError, "The BASIC transfer was cancelled.") var boundedChecks = 0 let clock = ContinuousClock() let began = clock.now let bounded = await machine.loadBASICSource(replacement, run: true, review: (expected, runningSource), reviewIsCurrent: { boundedChecks += 1; return true }) XCTAssertNil(bounded); XCTAssertGreaterThan(boundedChecks, 2) XCTAssertLessThan(clock.now - began, .seconds(3), "An executing program must not cause unbounded retry") XCTAssertEqual(machine.fileError, "Wait at the BASIC OK prompt before loading or running from the editor; use BREAK to stop the current program first") controller.setKeyboardMask(CocoKeyboard.shift) let legacyBegan = clock.now let legacy = await machine.loadBASICSource(replacement, run: true, review: (expected, runningSource)) controller.setKeyboardMask(0) XCTAssertNil(legacy) XCTAssertLessThan(clock.now - legacyBegan, .seconds(1), "A review tuple without live approval must remain a single attempt") XCTAssertEqual(machine.fileError, "Wait at the BASIC OK prompt before loading or running from the editor; use BREAK to stop the current program first") var ordinaryChecks = 0 let ordinary = await machine.loadBASICSource(replacement, run: true, reviewIsCurrent: { ordinaryChecks += 1; return true }) XCTAssertNil(ordinary); XCTAssertEqual(ordinaryChecks, 0, "Ordinary loading remains a single unreviewed operation") let after = await machine.mcpMachineSnapshot() XCTAssertEqual(after.generation, expected.generation) XCTAssertEqual(after.debuggerProgramRevision, expected.debuggerProgramRevision) let preserved = try await programBytes(controller) XCTAssertEqual(preserved, original) XCTAssertEqual(after.disks.first?.name, expected.disks.first?.name) XCTAssertEqual(after.disks.first?.mounted, expected.disks.first?.mounted) } } catch { await withCheckedContinuation { done in machine.shutdown { done.resume() } } throw error } await withCheckedContinuation { done in machine.shutdown { done.resume() } } } func testReviewedBASICRunChecksRealMenuColorsPromptAndStaleSource() async throws { _ = NSApplication.shared // This fixture also runs alone in Apple's hostless XCTest runner. let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() let roms = mac.appendingPathComponent("LocalResources/ROMs") for file in ["coco3.rom", "disk11.rom"] { try XCTSkipUnless(FileManager.default.fileExists(atPath: roms.appendingPathComponent(file).path), "Stage private BASIC ROMs") } let suite = "MCPGuestTests-" + UUID().uuidString let dir = FileManager.default.temporaryDirectory.appendingPathComponent(suite) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: dir) } let controller = VCCMachineController() let machine = MachineModel(diskStore: .init(url: dir.appendingPathComponent("drives.json")), controller: controller, displayDefaults: defaults, inputStore: .init(url: dir.appendingPathComponent("input.json"))) do { for _ in 0..<300 where machine.busy { try await Task.sleep(for: .milliseconds(20)) } for use6309 in [false, true] { for composite in [false, true] { try await MCPBASICRun.bootFixture(machine, romDirectory: roms, use6309: use6309, composite: composite) let model = BASICDevelopmentModel(machine: machine, directory: dir.appendingPathComponent(UUID().uuidString)) model.source = model.source.replacingOccurrences(of: "Hello Cold Red Dot World!", with: "Bring a warm coat!") let guest = MCPBASICRun() await guest.start(model: model, bothChoices: true, isCurrent: { true }) let branches = try XCTUnwrap(guest.receipt?["branches"] as? [[String: Any]], guest.status) XCTAssertEqual(branches.compactMap { $0["key"] as? String }, ["2", "1"]) XCTAssertEqual(guest.receipt?["verified"] as? Bool, !composite) XCTAssertEqual(branches.compactMap { $0["color_matches"] as? Bool }, [!composite, true]) XCTAssertEqual(branches.compactMap { ($0["cell"] as? [String: Int])?["palette_value"] }, [37, 10]) XCTAssertEqual(branches.compactMap { $0["greeting"] as? String }, ["Bring a warm coat!", "Hello Nice Blue Dot World!"]) let runID = try XCTUnwrap(guest.runID) let observation = await guest.handle(tool: "read_screen_text", arguments: ["run_id": runID], model: model) XCTAssertNotNil(observation["result"]) model.source += "200 REM UNSAVED EDIT\n" let stale = await guest.handle(tool: "read_screen_text", arguments: ["run_id": runID], model: model) XCTAssertNotNil(stale["error"]) print("Reviewed BASIC guest", use6309 ? "HD6309" : "MC6809", composite ? "composite" : "RGB", branches.compactMap { $0["background_rgb"] }) } } try await MCPBASICRun.bootFixture(machine, romDirectory: roms) let ordinary = BASICDevelopmentModel(machine: machine, directory: dir.appendingPathComponent("Menu")) ordinary.source = """ 10 PRINT "PRESS ANY KEY" 20 FOR I=1 TO 10 30 K$=INKEY$:IF K$="" THEN 30 40 PRINT "GOT";I;" ";K$ 50 NEXT I 60 END """ let manual = MCPBASICRun() let enabled = await command { controller.setDriveWireEnabled(true, completion: $0) } XCTAssertTrue(enabled.driveWireEnabled) let armed = await command(controller.startMacShell) XCTAssertEqual(armed.macShellStatus, "ready") await manual.start(model: ordinary, bothChoices: false, isCurrent: { true }) XCTAssertNil(manual.runID) XCTAssertTrue(manual.status.contains("Disable DriveWire"), manual.status) _ = await command { controller.setDriveWireEnabled(false, completion: $0) } await manual.start(model: ordinary, bothChoices: false, isCurrent: { true }) let runID = try XCTUnwrap(manual.runID, manual.status) for _ in 0..<80 { let reply = await manual.handle(tool: "read_screen_text", arguments: ["run_id": runID], model: ordinary) let screen = (reply["result"] as? [String: Any])?["text"] as? String ?? "" if screen.contains("PRESS ANY KEY") { break } try await Task.sleep(for: .milliseconds(50)) } func send(_ keys: String, request: String) async -> [String: Any] { await manual.handle(tool: "send_keys", arguments: ["run_id": runID, "request_id": request, "keys": keys], model: ordinary) } let unsupported = await send("RUN\n", request: "command") XCTAssertEqual(unsupported["error"] as? String, "invalid_arguments") let first = await send("3", request: "one"), replay = await send("3", request: "one") XCTAssertNotNil(first["result"], String(describing: first)) XCTAssertTrue(NSDictionary(dictionary: first).isEqual(to: replay)) let conflict = await send("2", request: "one") XCTAssertEqual(conflict["error"] as? String, "request_conflict") func expectScreen(_ expected: String, direct: Bool = false) async throws { var text = "" for _ in 0..<100 { let reply = await manual.handle(tool: "read_screen_text", arguments: ["run_id": runID], model: ordinary) let result = reply["result"] as? [String: Any] text = result?["text"] as? String ?? String(describing: reply) if text.contains(expected), result?["paste_remaining"] as? Int == 0, result?["direct_prompt"] as? Bool == direct { return } try await Task.sleep(for: .milliseconds(40)) } XCTFail("Expected \(expected) in \(text)") } try await expectScreen("GOT 1") let network = await command { controller.setDriveWireEnabled(true, completion: $0) } XCTAssertFalse(network.driveWireEnabled) XCTAssertNotNil(network.errorMessage) for index in 2...10 { let key = index.isMultiple(of: 2) ? " " : "A" let response = await send(key, request: "key-\(index)") XCTAssertNotNil(response["result"], String(describing: response)) try await expectScreen("GOT \(index)", direct: index == 10) } let atPrompt = await send("N", request: "after-end") XCTAssertNotNil(atPrompt["error"]) let probe = await send("PRINT 7\n", request: "probe") XCTAssertNotNil(probe["result"], String(describing: probe)) try await expectScreen("PRINT 7", direct: true) manual.reset() let revoked = await send("1", request: "two") XCTAssertEqual(revoked["error"] as? String, "no_run") // The local-model trial edited the Earth assignment while leaving Mars intact. // A plausible replacement sentence in the source is insufficient to pass. try await MCPBASICRun.bootFixture(machine, romDirectory: roms) let wrong = BASICDevelopmentModel(machine: machine, directory: dir.appendingPathComponent("WrongBranch")) wrong.source = wrong.source.replacingOccurrences(of: "Hello Nice Blue Dot World!", with: "Bring a warm coat!") let rejected = MCPBASICRun() await rejected.start(model: wrong, bothChoices: true, isCurrent: { true }) XCTAssertNil(rejected.receipt) XCTAssertTrue(rejected.status.contains("Expected “Bring a warm coat!” for choice 2"), rejected.status) XCTAssertTrue(rejected.status.contains("Hello Cold Red Dot World!"), rejected.status) } catch { await withCheckedContinuation { c in machine.shutdown { c.resume() } } throw error } await withCheckedContinuation { c in machine.shutdown { c.resume() } } } func testPlanetEditorStartersAcceptKeyboardAndReturnToBASIC() async throws { let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() let tools = vccQualificationToolchain(mac.appendingPathComponent("LocalResources/ToolchainBundle")) try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/lwasm").path)) try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path)) let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) defer { try? FileManager.default.removeItem(at: root) } let project = try CMOCProject.create(at: root.appendingPathComponent("Project")) let service = CMOCBuildService(toolchain: tools, buildRoot: root.appendingPathComponent("Builds")) let c = try await service.build(project: project, overlays: [:]) let assembly = try await AssemblyBuildService(toolchain: tools).build(.single(source: AssemblyWorkspaceDocument.starterSource)) let cEntry = c.binaryData.suffix(2).reduce(UInt16(0)) { ($0 << 8) | UInt16($1) } try await withBASIC { controller in func type(_ text: String) async throws { let keys = try CocoPaste(text, mode: .text) let sent = await command { controller.pasteChords(keys.chords.map { NSNumber(value: $0) }, completion: $0) } XCTAssertNil(sent.errorMessage) for _ in 0..<300 { if await command(controller.snapshot).pasteRemaining == 0 { return } try await Task.sleep(nanoseconds: 20_000_000) } throw Failure.timeout } enum Language: CaseIterable { case basic, assembly, c } for language in Language.allCases { for (choice, greeting) in [("1", "Hello Nice Blue Dot World!"), ("2", "Hello Cold Red Dot World!")] { let launched: VCCMachineSnapshot switch language { case .assembly: let before = await command(controller.snapshot) launched = await command { controller.launchAssembly(assembly.binaryData, points: [], addresses: [], bytes: [], pauseAtEntry: false, requires6309: false, generation: before.generation, revision: before.debuggerProgramRevision, mapping: before.debuggerMappingFingerprint, completion: $0) } case .c: // C Development's Run arms the entry while loading, then releases it. let prepared = await command { controller.debuggerLoadBinary(c.binaryData, breakpoint: cEntry, completion: $0) } XCTAssertNil(prepared.errorMessage) _ = await command(controller.debuggerClearDevelopmentBreakpoints) launched = await command(controller.resume) case .basic: launched = await command { controller.basicLoadSource(BASICLanguage.sample, run: true, completion: $0) } } XCTAssertNil(launched.errorMessage) try await waitForScreen("What planet do you live on?\n1) Earth\n2) Mars", controller: controller) try await type("3" + choice) try await waitForScreen(greeting, controller: controller, context: "\(language) Direct Run") // Clearing the screen also prevents a previous run from satisfying the next check. try await type("CLS\nPRINT 7\n") try await waitForScreen("PRINT 7\n 7", controller: controller) try await settle(controller) } // A real EXEC inside a BASIC program must resume on the following line. if language != .basic { let entry = language == .c ? cEntry : assembly.entry let caller = String(format: "10 EXEC &H%04X\n20 PRINT \"BACK FROM EXEC\"\n", entry) let started = await command { controller.basicLoadSource(caller, run: true, completion: $0) } XCTAssertNil(started.errorMessage) try await waitForScreen("2) Mars", controller: controller) try await type("1") try await waitForScreen("Hello Nice Blue Dot World!\nBACK FROM EXEC", controller: controller) try await settle(controller) } } } } func testExportedBootDisksRunByDOSAndByTheirManualCommands() async throws { let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() let tools = vccQualificationToolchain(mac.appendingPathComponent("LocalResources/ToolchainBundle")) try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: tools.appendingPathComponent("bin/cmoc").path)) let service = AssemblyBuildService(toolchain: tools) let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: root) } let store = try basicProfileStore(mac: mac, root: root) let build = try await service.build(.single(source: " org $3f00\nstart lda #$8f\n sta $0400\nhold bra hold\n end start\n")) let machineDisk = try await service.diskImage(for: build, name: "ASMTEST", dosBoot: true) for binary in [false, true] { for shortcut in [false, true] { var profile = try store.systemProfile(.diskBasic) profile.sound = false profile.machine.use6309 = shortcut let request = try PreparedProfile.read(profile).request() let controller = VCCMachineController() do { let ready: Bool = await withCheckedContinuation { c in controller.applyProfile(request) { ok, _ in c.resume(returning: ok) } } XCTAssertTrue(ready) _ = await command(controller.resume) try await waitForScreen("OK", controller: controller) try await settle(controller) let image: Data if binary { image = machineDisk } else { let result = await export(controller, source: "10 PRINT \"BOOTED BASIC\"\n", name: "BASICTST", cassette: false) let plain = try XCTUnwrap(result.0) image = try await service.tools.bootableBASICDisk(plain, name: "BASICTST") let fat = 17 * 18 * 256 + 256 + 66 XCTAssertEqual(Array(plain[fat..= 0 { XCTFail("\(context): \(state.basicErrorCode) error on line \(state.basicErrorLine)") throw Failure.invalidMemory } if await screen(controller).contains(example.expectedOutput) { finished = true; break } try await Task.sleep(nanoseconds: 20_000_000) } if !finished { let output = await screen(controller) XCTFail("\(context): expected \(example.expectedOutput), received \(output)") throw Failure.timeout } // Ensure END has reached the direct prompt before replacing // the example, and catch errors that follow a printed result. try await settle(controller) let final = await command(controller.snapshot) XCTAssertEqual(final.basicErrorLine, -1, context) XCTAssertEqual(final.generation, baseline.generation, context) XCTAssertTrue(final.disks.allSatisfy { !$0.dirty && $0.writeEvents == 0 }, context) XCTAssertTrue(final.hardDisks.allSatisfy { !$0.dirty && $0.writeEvents == 0 }, context) XCTAssertEqual(final.sdcWriteCount, 0, context) XCTAssertFalse(final.tapeDirty, context) if example.dialect == "disk" || example.dialect == "rgbdos" { XCTAssertGreaterThan(final.disks.reduce(UInt64(0)) { $0 + $1.readEvents }, before.disks.reduce(UInt64(0)) { $0 + $1.readEvents }, context) } if example.dialect == "rgbdos" { XCTAssertGreaterThan(final.hardDisks.reduce(UInt64(0)) { $0 + $1.readEvents }, before.hardDisks.reduce(UInt64(0)) { $0 + $1.readEvents }, context) } if example.dialect == "sdcdos" { XCTAssertGreaterThan(final.sdcReadCount, before.sdcReadCount, context) } } _ = await command(controller.shutdown) } catch { _ = await command(controller.shutdown); throw error } } } } private func stagedArchive() throws -> ArchiveLibraryCatalog { let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent() let url = root.appendingPathComponent("media/knowledge-base/archive-library/ArchiveLibrary.sqlite") try XCTSkipUnless(FileManager.default.fileExists(atPath: url.path), "Stage the full Archive Library index") return ArchiveLibraryCatalog(url: url) } func testArchiveSearchWhileGuestRuns() async throws { try await withBASIC { controller in let catalog = try self.stagedArchive() let before = await self.command(controller.snapshot) var times: [Double] = [] for _ in 0..<3 { for query in ["OS-9 level II module directory", "JOYSTK", "TFM", "GIME", "WIDTH 80", "disk basic", "the"] { let start = DispatchTime.now().uptimeNanoseconds let hits = try await catalog.search(query: query, collection: nil, limit: 10, offset: 0) times.append(Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000) XCTAssertFalse(hits.isEmpty) if query.hasPrefix("OS-9") { XCTAssertTrue(hits.contains { $0.page == 79 && $0.document.memberPath == "Complete Rainbow Guide to OS-9 Level II.pdf" }) } } } let year = "Magazines/Rainbow, The/1983" let collections = try await catalog.collections() XCTAssertTrue(collections.contains(year)) let issues = try await catalog.browse(collection: year, limit: 50, offset: 0) XCTAssertTrue(issues.contains { $0.title.contains("November 1983") }) XCTAssertTrue(issues.allSatisfy { $0.title.contains("1983") }) let after = await self.command(controller.snapshot) XCTAssertGreaterThan(after.frames, before.frames) XCTAssertEqual(after.debuggerProgramRevision, before.debuggerProgramRevision) XCTAssertEqual(after.disks.map(\.name), before.disks.map(\.name)) let warm = times.dropFirst().sorted() print("Archive query milliseconds, guest \(after.use6309 ? "6309" : "6809"): first \(times[0]), warm median \(warm[9]), warm P95 \(warm[18])") } } func testReviewedArchiveBASICExamplesOnSharedPage() async throws { let catalog = try stagedArchive() let issue = "5f3398c7ad84af7f564d5e941014d2be36fd97ec5abc3176594fedb8e025936f" for title in ["Mini Data Base", "Pill"] { try await withBASIC { controller in let before = await self.command(controller.snapshot) let choices = try await catalog.examples(documentID: issue, page: 13) XCTAssertEqual(choices.map(\.title), ["Mini Data Base", "Pill"]) let unchanged = await self.command(controller.snapshot) XCTAssertEqual(unchanged.debuggerProgramRevision, before.debuggerProgramRevision) XCTAssertEqual(unchanged.state, before.state) XCTAssertEqual(unchanged.disks.map(\.name), before.disks.map(\.name)) let example = try XCTUnwrap(choices.first { $0.title == title }) let recovered = try await catalog.basicExample(sourceSHA256: example.sourceSHA256) XCTAssertEqual(recovered?.source, example.source) if example.title == "Mini Data Base" { // Stop once the form is drawn, before Disk BASIC opens the data file. let loaded = await self.command { controller.basicLoadSource(example.source, run: true, breakpoints: [130], completion: $0) } XCTAssertNil(loaded.errorMessage) _ = try await self.waitForBASICStop(controller, line: 130) let screen = await self.screen(controller) XCTAssertTrue(screen.contains("SURNAME")) } else { // PCLEAR relocates the program. Observe CURLIN in the Disk BASIC ROM // instead of attaching a breakpoint across the memory-map change. let loaded = await self.command { controller.basicLoadSource(example.source, run: true, completion: $0) } XCTAssertNil(loaded.errorMessage) var line = -1 for _ in 0..<250 { let ram = await self.memory(controller).logicalMemory line = Int(ram[0x68]) * 256 + Int(ram[0x69]) if line == 108 || line == 110 { break } try await Task.sleep(nanoseconds: 20_000_000) } XCTAssertTrue([108,110].contains(line), "Expected Pill's title-screen key loop, observed BASIC line \(line)") } } } } private func waitForBASICStop(_ controller: VCCMachineController, line: Int) async throws -> VCCMachineSnapshot { for _ in 0..<300 { let snapshot = await command(controller.snapshot) if snapshot.state == .paused && snapshot.basicStoppedLine == line { return snapshot } if let error = snapshot.errorMessage { XCTFail(error); throw Failure.timeout } try await Task.sleep(nanoseconds: 10_000_000) } let last = await command(controller.snapshot) XCTFail("No BASIC stop at \(line): \(last.basicDebugStatus), PC \(last.programCounter)") throw Failure.timeout } private func basicStep(_ controller: VCCMachineController, source: String, over: Bool = false) async throws -> VCCMachineSnapshot { let started = await command { controller.basicStep(source: source, over: over, completion: $0) } XCTAssertNil(started.errorMessage) for _ in 0..<400 { let state = await command(controller.snapshot) if state.state == .paused && !state.basicStepping { return state } try await Task.sleep(nanoseconds: 10_000_000) } XCTFail("BASIC step did not stop"); throw Failure.timeout } private func inspect(_ controller: VCCMachineController, source: String) async -> ([BASICVariable]?, VCCMachineSnapshot) { await withCheckedContinuation { continuation in controller.basicInspect(source: source) { rows, snapshot in continuation.resume(returning: (rows?.compactMap(BASICVariable.init), snapshot)) } } } private func stepOut(_ controller: VCCMachineController, source: String) async throws -> VCCMachineSnapshot { let started = await command { controller.basicStepOut(source: source, completion: $0) } XCTAssertNil(started.errorMessage) for _ in 0..<400 { let state = await command(controller.snapshot) if state.state == .paused && !state.basicStepping { return state } try await Task.sleep(nanoseconds: 10_000_000) } XCTFail("Step Out did not stop"); throw Failure.timeout } func testBASICStepOutNestedForFramesAndBreakpointPrecedence() async throws { try await withBASIC { controller in let source = "10 GOSUB 100:POKE &H4000,9:END\n100 FOR I=1 TO 2\n110 GOSUB 200\n120 NEXT I\n130 RETURN\n200 A=A+1\n210 RETURN\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [110,200], completion: $0) } let stopped = try await waitForBASICStop(controller, line: 110) XCTAssertTrue(stopped.basicCanStepOut, "GOSUB frame under a FOR frame") let stale = await command { controller.basicStepOut(source: source + "300 END\n", completion: $0) } XCTAssertNotNil(stale.errorMessage); XCTAssertEqual(stale.cycles, stopped.cycles) var result = try await stepOut(controller, source: source) XCTAssertEqual(result.basicStoppedLine, 200, "Explicit breakpoint wins inside nested call") _ = await command { controller.basicSetBreakpoints([], source: source, completion: $0) } result = try await stepOut(controller, source: source) XCTAssertEqual(result.basicStoppedLine, 120); XCTAssertTrue(result.basicCanStepOut) result = try await stepOut(controller, source: source) XCTAssertEqual(result.basicStoppedLine, 10); XCTAssertFalse(result.basicCanStepOut) assertToken(result, source: source, token: "POKE") let values = await inspect(controller, source: source) XCTAssertEqual(BASICWatch("A")?.value(in: values.0 ?? []), "2") let rejected = await command { controller.basicStepOut(source: source, completion: $0) } XCTAssertNotNil(rejected.errorMessage); XCTAssertEqual(rejected.cycles, result.cycles) } } func testBASICStepOutRecursionReturnsOneFrameAtATime() async throws { try await withBASIC { controller in let source = "10 N=3:GOSUB 100:END\n100 N=N-1\n110 IF N>0 THEN GOSUB 100\n120 N=N+1:RETURN\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [120], completion: $0) } _ = try await waitForBASICStop(controller, line: 120) _ = await command { controller.basicSetBreakpoints([], source: source, completion: $0) } for expected in [1,2,3] { let state = try await stepOut(controller, source: source) XCTAssertEqual(state.basicStoppedLine, expected == 3 ? 10 : 120) XCTAssertEqual(state.basicCanStepOut, expected != 3) let values = await inspect(controller, source: source) XCTAssertEqual(BASICWatch("N")?.value(in: values.0 ?? []), String(expected)) } } } func testBASICRuntimeErrorsCaptureActualROMCodeAndPreserveTraps() async throws { try await withBASIC { controller in for (statement, code) in [("A=1/0", "/0"), ("PRINT (", "SN"), ("READ A", "OD"), ("A=\"X\"", "TM"), ("OPEN \"I\",#1,\"MISSING\"", "NE")] { let source = "10 A=1\n20 " + statement + "\n30 END\n" let start = await command { controller.basicLoadSource(source, run: true, completion: $0) } XCTAssertNil(start.errorMessage) let failed = try await waitForBASICStop(controller, line: -1) XCTAssertEqual(failed.programCounter, 0xac7c) XCTAssertEqual(failed.basicErrorLine, 20); XCTAssertEqual(failed.basicErrorCode, code) XCTAssertFalse(failed.basicCanStepOut); XCTAssertFalse(failed.basicStepping) let text = await screen(controller) XCTAssertTrue(text.contains(code + " ERROR"), text) let continued = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNil(continued.errorMessage) try await settle(controller) } let source = "10 ON ERR GOTO 100\n20 A=1/0\n30 END\n100 A=42\n110 END\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [110], completion: $0) } let caught = try await waitForBASICStop(controller, line: 110) XCTAssertEqual(caught.basicErrorLine, -1); XCTAssertEqual(caught.basicErrorCode, "") let values = await inspect(controller, source: source) XCTAssertEqual(BASICWatch("A")?.value(in: values.0 ?? []), "42") } } func testBASICVariablesAndArraysMatchInterpreterWithoutMutation() async throws { try await withBASIC { controller in let source = "10 A=-1.5:ZERO=0:BIG=1E20:SMALL=1E-20\n20 NAME$=\"Mixed Case\":E$=\"\":B$=CHR$(0)+CHR$(255)\n30 DIM M(1,2),S$(2):M(0,1)=12:M(1,0)=21:M(1,2)=99:S$(2)=NAME$\n40 DEF FN F(X)=X+1\n50 A=A+1\n60 END\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10, 50], completion: $0) } _ = try await waitForBASICStop(controller, line: 10) let empty = await inspect(controller, source: source) XCTAssertNil(empty.1.errorMessage); XCTAssertEqual(empty.0, []) _ = await command { controller.basicContinue(source: source, completion: $0) } let stopped = try await waitForBASICStop(controller, line: 50) let before = await memory(controller) let inspected = await inspect(controller, source: source) XCTAssertNil(inspected.1.errorMessage) let values = try XCTUnwrap(inspected.0) func value(_ name: String) -> String? { BASICWatch(name)?.value(in: values) } XCTAssertEqual(value("A"), "-1.5"); XCTAssertEqual(value("ZERO"), "0") XCTAssertEqual(Double(try XCTUnwrap(value("BIG")))! / 1e20, 1, accuracy: 1e-9) XCTAssertEqual(Double(try XCTUnwrap(value("SMALL")))! / 1e-20, 1, accuracy: 1e-9) XCTAssertEqual(value("NAME$"), "\"Mixed Case\""); XCTAssertEqual(value("E$"), "\"\"") XCTAssertEqual(value("B$"), "\"\\x00\\xFF\"") XCTAssertEqual(value("M(0,1)"), "12"); XCTAssertEqual(value("M(1,0)"), "21") XCTAssertEqual(value("M(1,2)"), "99"); XCTAssertEqual(value("M(0,0)"), "0") XCTAssertEqual(value("S$(2)"), "\"Mixed Case\"") XCTAssertEqual(value("UNSET"), "Not assigned") XCTAssertEqual(value("Q(1)"), "Not dimensioned") XCTAssertEqual(value("M(2,0)"), "Subscript out of range") XCTAssertEqual(value("M(1)"), "Wrong number of subscripts") XCTAssertTrue(values.contains { $0.kind == "Function" && $0.value.contains("not evaluated") }) let array = try XCTUnwrap(values.first { $0.name == "M" && !$0.dimensions.isEmpty }) XCTAssertEqual(array.dimensions, [2, 3]); XCTAssertEqual(array.elementName(5), "M(1,2)") let after = await memory(controller) XCTAssertEqual(before.logicalMemory, after.logicalMemory) XCTAssertEqual(inspected.1.cycles, stopped.cycles) assertExportPreservesSession(inspected.1, stopped) let next = try await basicStep(controller, source: source) XCTAssertEqual(next.basicStoppedLine, 60) let changed = await inspect(controller, source: source) XCTAssertEqual(BASICWatch("A")?.value(in: changed.0 ?? []), "-0.5") _ = try await basicStep(controller, source: source) let ended = await inspect(controller, source: source) XCTAssertNil(ended.1.errorMessage, "Completed program retains inspectable values") } } func testBASICInspectionRejectsStaleRunningAndInvalidTables() async throws { try await withBASIC { controller in let source = "10 A=1\n20 INPUT B\n30 END\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [20], completion: $0) } let stopped = try await waitForBASICStop(controller, line: 20) let stale = await inspect(controller, source: "10 A=2\n20 INPUT B\n30 END\n") XCTAssertNil(stale.0); XCTAssertNotNil(stale.1.errorMessage); XCTAssertEqual(stale.1.cycles, stopped.cycles) let original = [UInt8]((await memory(controller)).logicalMemory) _ = await command { controller.debuggerWriteMemory(address: 0x1d, data: Data([0xff, 0xff]), completion: $0) } let invalid = await inspect(controller, source: source) XCTAssertNil(invalid.0); XCTAssertNotNil(invalid.1.errorMessage) _ = await command { controller.debuggerWriteMemory(address: 0x1d, data: Data(original[0x1d...0x1e]), completion: $0) } _ = await command { controller.basicContinue(source: source, completion: $0) } let running = await inspect(controller, source: source) XCTAssertNil(running.0); XCTAssertNotNil(running.1.errorMessage) _ = await command(controller.pause) let pausedMidStatement = await inspect(controller, source: source) XCTAssertNil(pausedMidStatement.0); XCTAssertNotNil(pausedMidStatement.1.errorMessage) } } private func assertToken(_ state: VCCMachineSnapshot, source: String, token: String, occurrence: Int = 0, file: StaticString = #filePath, line: UInt = #line) { let text = source as NSString var search = NSRange(location: 0, length: text.length), range = NSRange(location: NSNotFound, length: 0) for _ in 0...occurrence { range = text.range(of: token, options: [], range: search) guard range.location != NSNotFound else { XCTFail("Missing fixture token", file: file, line: line); return } search = NSRange(location: NSMaxRange(range), length: text.length - NSMaxRange(range)) } XCTAssertEqual(state.basicSourceOffset, range.location, file: file, line: line) XCTAssertGreaterThan(state.basicSourceLength, 0, file: file, line: line) } func testBASICStepColonStatementsAndForLoopWithExactSourceMapping() async throws { try await withBASIC { controller in let source = "30 POKE &H4001,I\r\n10 poke &H4000,1:POKE &H4000,2\r\n20 FOR I=1 TO 2\r\n40 NEXT I\r\n50 END\r\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } let initial = try await waitForBASICStop(controller, line: 10) assertToken(initial, source: source, token: "poke") var stopped = try await basicStep(controller, source: source) XCTAssertEqual(stopped.basicStoppedLine, 10) assertToken(stopped, source: source, token: "POKE &H4000,2") var bytes = [UInt8]((await memory(controller)).logicalMemory) XCTAssertEqual(bytes[0x4000], 1) stopped = try await basicStep(controller, source: source, over: true) XCTAssertEqual(stopped.basicStoppedLine, 20) assertToken(stopped, source: source, token: "FOR") for expected in [30, 40, 30, 40, 50] { stopped = try await basicStep(controller, source: source, over: true) XCTAssertEqual(stopped.basicStoppedLine, expected, "FOR frames must not be treated as GOSUB frames") } bytes = [UInt8]((await memory(controller)).logicalMemory) XCTAssertEqual(bytes[0x4000], 2); XCTAssertEqual(bytes[0x4001], 2) stopped = try await basicStep(controller, source: source) XCTAssertEqual(stopped.basicStoppedLine, -1) XCTAssertTrue(stopped.basicDebugStatus.contains("OK prompt")) XCTAssertEqual(stopped.generation, initial.generation) XCTAssertEqual(stopped.debuggerProgramRevision, initial.debuggerProgramRevision) } } func testBASICStepOverRecursiveAndOnGosub() async throws { try await withBASIC { controller in let source = "10 A=0:GOSUB 100:POKE &H4000,A\n20 ON 1 GOSUB 200:POKE &H4001,A\n30 END\n100 A=A+1\n110 IF A<3 THEN GOSUB 100\n120 RETURN\n200 A=A+10:RETURN\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } _ = try await waitForBASICStop(controller, line: 10) var stopped = try await basicStep(controller, source: source) assertToken(stopped, source: source, token: "GOSUB") stopped = try await basicStep(controller, source: source, over: true) XCTAssertEqual(stopped.basicStoppedLine, 10) assertToken(stopped, source: source, token: "POKE &H4000") stopped = try await basicStep(controller, source: source) XCTAssertEqual(stopped.basicStoppedLine, 20) stopped = try await basicStep(controller, source: source, over: true) XCTAssertEqual(stopped.basicStoppedLine, 20) assertToken(stopped, source: source, token: "POKE &H4001") _ = try await basicStep(controller, source: source) let bytes = [UInt8]((await memory(controller)).logicalMemory) XCTAssertEqual(bytes[0x4000], 3); XCTAssertEqual(bytes[0x4001], 13) } } func testBASICStepIntoAndExplicitBreakpointInterruptsStepOver() async throws { try await withBASIC { controller in let source = "10 GOSUB 100:END\n100 A=1\n110 GOSUB 200\n120 RETURN\n200 A=2\n210 RETURN\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10, 200], completion: $0) } _ = try await waitForBASICStop(controller, line: 10) var stopped = try await basicStep(controller, source: source) XCTAssertEqual(stopped.basicStoppedLine, 100) stopped = try await basicStep(controller, source: source) XCTAssertEqual(stopped.basicStoppedLine, 110) stopped = try await basicStep(controller, source: source, over: true) XCTAssertEqual(stopped.basicStoppedLine, 200, "Explicit breakpoints take precedence inside a stepped-over call") stopped = try await basicStep(controller, source: source) XCTAssertEqual(stopped.basicStoppedLine, 210) stopped = try await basicStep(controller, source: source, over: true) XCTAssertEqual(stopped.basicStoppedLine, 120) } } func testBASICStepRejectsStaleSourceAndCancelsInputWait() async throws { try await withBASIC { controller in let source = "10 INPUT A\n20 END\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } let stopped = try await waitForBASICStop(controller, line: 10) let rejected = await command { controller.basicStep(source: "10 END\n", over: false, completion: $0) } XCTAssertNotNil(rejected.errorMessage); XCTAssertEqual(rejected.cycles, stopped.cycles) let started = await command { controller.basicStep(source: source, over: false, completion: $0) } XCTAssertNil(started.errorMessage); XCTAssertTrue(started.basicStepping) try await Task.sleep(nanoseconds: 150_000_000) let paused = await command(controller.pause) XCTAssertFalse(paused.basicStepping); XCTAssertEqual(paused.state, .paused) XCTAssertEqual(paused.basicStoppedLine, -1); XCTAssertTrue(paused.basicDebugAttached) let invalidStep = await command { controller.basicStep(source: source, over: true, completion: $0) } XCTAssertNotNil(invalidStep.errorMessage) let resumed = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNil(resumed.errorMessage); XCTAssertEqual(resumed.state, .running) XCTAssertFalse(resumed.basicStepping) } } func testBASICStepOverHasExecutionBoundAndPreservesManualBreakpoints() async throws { try await withBASIC { controller in let source = "10 GOSUB 100:END\n100 A=A+1:GOTO 100\n" _ = await command { controller.debuggerSetBreakpoints([0xbfff], completion: $0) } _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } let before = try await waitForBASICStop(controller, line: 10) _ = await command { controller.basicStep(source: source, over: true, completion: $0) } var result = await command(controller.snapshot) for _ in 0..<1400 { result = await command(controller.snapshot) if result.state == .paused { break } try await Task.sleep(nanoseconds: 10_000_000) } XCTAssertEqual(result.state, .paused); XCTAssertFalse(result.basicStepping) XCTAssertTrue(result.basicDebugStatus.contains("10 emulated seconds")) XCTAssertGreaterThanOrEqual(result.frames - before.frames, 600) XCTAssertEqual(result.generation, before.generation) XCTAssertEqual(result.basicStoppedLine, -1) let manual = await memory(controller) XCTAssertEqual(manual.breakpoints, [NSNumber(value: 0xbfff)]) let resumed = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNil(resumed.errorMessage); XCTAssertEqual(resumed.state, .running) } } func testBASICStepIfElseAndRuntimeErrorFinishAtPrompt() async throws { try await withBASIC { controller in let source = "10 IF 0 THEN POKE &H4000,9 ELSE POKE &H4000,3\n20 A=1/0\n30 END\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } _ = try await waitForBASICStop(controller, line: 10) var stopped = try await basicStep(controller, source: source) XCTAssertEqual(stopped.basicStoppedLine, 10) assertToken(stopped, source: source, token: "POKE &H4000,3") stopped = try await basicStep(controller, source: source) XCTAssertEqual(stopped.basicStoppedLine, 20) let mem = await memory(controller) XCTAssertEqual([UInt8](mem.logicalMemory)[0x4000], 3) stopped = try await basicStep(controller, source: source) XCTAssertEqual(stopped.basicStoppedLine, -1) XCTAssertTrue(stopped.basicDebugStatus.contains("OK prompt")) let output = await screen(controller) XCTAssertTrue(output.contains("/0 ERROR IN 20")) } } func testBASICBreakpointsSurviveVideoPageSwitches() async throws { try await withBASIC { controller in let source = "10 WIDTH 40\n20 FOR I=1 TO 8:CLS:NEXT I\n30 PRINT \"READY\"\n40 END\n" let started = await command { controller.basicLoadSource(source, run: true, breakpoints: [30], completion: $0) } XCTAssertNil(started.errorMessage) let stopped = try await waitForBASICStop(controller, line: 30) XCTAssertTrue(stopped.basicDebugAttached) let before = await screen(controller) XCTAssertFalse(before.contains("READY")) let resumed = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNil(resumed.errorMessage) try await waitForScreen("READY", controller: controller) } } func testBASICStepStopsIfProgramModifiesItsOwnTokens() async throws { try await withBASIC { controller in let source = "10 POKE PEEK(25)*256+PEEK(26)+4,138\n20 END\n" _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } _ = try await waitForBASICStop(controller, line: 10) let stopped = try await basicStep(controller, source: source) XCTAssertFalse(stopped.basicDebugAttached); XCTAssertFalse(stopped.basicStepping) XCTAssertEqual(stopped.basicStoppedLine, -1); XCTAssertEqual(stopped.basicSourceOffset, -1) XCTAssertTrue(stopped.basicDebugStatus.contains("changed")) let rejected = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNotNil(rejected.errorMessage) } } /// Scanlines from the same 640x480 buffer passed to Metal. The stock BASIC /// text mode has sixteen 32-character rows in its 512x384 active picture. private func basicPixelRows(_ snapshot: VCCMachineSnapshot) throws -> [Data] { let capture = try ScreenCapture(pixels: snapshot.pixels, area: snapshot.activeVideoRect) let area = capture.area guard area.size == CGSize(width: 512, height: 384) else { XCTFail("Expected the stock BASIC active picture, got \(area)") throw Failure.invalidMemory } return (0..<16).map { row in var pixels = Data() let y = Int(area.minY) + row * 24 for scanline in y..<(y + 24) { let start = (scanline * 640 + Int(area.minX)) * 4 pixels.append(capture.pixels[start..<(start + 512 * 4)]) } return pixels } } func testBASICSamplePresentsCurrentPixelsAtEveryLine40Breakpoint() async throws { try await assertBASICSamplePixels(line: 40, nextStatement: "PRINT \"COUNT\"", countsShown: 0...4, frameInterval: 1) } func testBASICSamplePresentsCurrentPixelsAtEveryLine50Breakpoint() async throws { try await assertBASICSamplePixels(line: 50, nextStatement: "NEXT I", countsShown: 1...5, frameInterval: 6) } private func assertBASICSamplePixels(line: Int, nextStatement: String, countsShown: ClosedRange, frameInterval: Int) async throws { try await withBASIC { controller in let source = "10 CLS\n20 PRINT \"HELLO FROM VCC PLUS\"\n30 FOR I=1 TO 5\n40 PRINT \"COUNT\";I\n50 NEXT I\n60 END\n" let output = ["HELLO FROM VCC PLUS"] + (1...5).map { "COUNT \($0)" } let initial = await command(controller.snapshot) let configured = await command { controller.configureMachine(use6309: initial.use6309, ram: Int(initial.ramConfiguration), overclock: Int(initial.cpuOverclock), frameInterval: frameInterval, fastForward: initial.fastForward, completion: $0) } XCTAssertNil(configured.errorMessage) XCTAssertEqual(configured.generation, initial.generation) XCTAssertEqual(Int(configured.frameInterval), frameInterval) var previousRevision = configured.pixelRevision var stops: [VCCMachineSnapshot] = [] let started = await command { controller.basicLoadSource(source, run: true, breakpoints: [NSNumber(value: line)], completion: $0) } XCTAssertNil(started.errorMessage) for (i, count) in zip(1...5, countsShown) { let stop = try await waitForBASICStop(controller, line: line) let context = "\(stop.use6309 ? "6309" : "6809"), stopped before \(nextStatement) with I=\(i)" assertToken(stop, source: source, token: nextStatement) let values = await inspect(controller, source: source) XCTAssertNil(values.1.errorMessage, context) XCTAssertEqual(BASICWatch("I")?.value(in: values.0 ?? []), String(i), context) let text = await screen(controller) XCTAssertEqual(text.split(separator: "\n").map(String.init), Array(output.prefix(1 + count)), context) XCTAssertGreaterThan(stop.pixelRevision, previousRevision, context) let reread = await command(controller.snapshot) XCTAssertEqual(reread.pixelRevision, stop.pixelRevision, context) XCTAssertEqual(reread.cycles, stop.cycles, context) XCTAssertEqual(reread.frames, stop.frames, context) stops.append(stop) previousRevision = stop.pixelRevision let resumed = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNil(resumed.errorMessage, context) } // Let ordinary raster timing draw all five counts. Its distinct // glyph rows and a known empty row are the pixel references for // the earlier stops, independent of the paused presentation path. try await waitForScreen("OK", controller: controller) try await settle(controller) let finalText = await screen(controller) XCTAssertEqual(Array(finalText.split(separator: "\n").map(String.init).prefix(6)), output) let final = await command(controller.snapshot) let reference = try basicPixelRows(final) let blank = reference[15] XCTAssertEqual(Set(reference.prefix(6) + [blank]).count, 7, "The running raster must distinguish every expected text row and blank") for (stop, count) in zip(stops, countsShown) { XCTAssertEqual(stop.activeVideoRect, final.activeVideoRect) let rows = try basicPixelRows(stop) for row in rows.indices { let printed = row <= count let expected = printed ? reference[row] : blank XCTAssertTrue(rows[row] == expected, "\(stop.use6309 ? "6309" : "6809"), before \(nextStatement), \(count) counts printed, raster row \(row + 1) should show \(printed ? output[row] : "a blank line")") } } } } func testBASICBreakpointsStopBeforeLineAndContinueLoopWithoutReset() async throws { try await withBASIC { controller in let source = "10 POKE &H4000,1\n20 POKE &H4000,2\n30 GOTO 20\n" let before = await command(controller.snapshot) let started = await command { controller.basicLoadSource(source, run: true, breakpoints: [20], completion: $0) } XCTAssertNil(started.errorMessage) let stopped = try await waitForBASICStop(controller, line: 20) XCTAssertTrue(stopped.basicDebugAttached) XCTAssertEqual(stopped.generation, before.generation) XCTAssertEqual(stopped.disks[0].name, before.disks[0].name) XCTAssertEqual(stopped.tapeLength, before.tapeLength) let first = await memory(controller) XCTAssertEqual([UInt8](first.logicalMemory)[0x4000], 1, "Breakpoint precedes the line's side effects") XCTAssertFalse(first.breakpoints.contains(NSNumber(value: 0xadc6)), "BASIC hooks must not become manual CPU breakpoints") let resumed = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNil(resumed.errorMessage) let again = try await waitForBASICStop(controller, line: 20) XCTAssertGreaterThan(again.cycles, stopped.cycles) let second = await memory(controller) XCTAssertEqual([UInt8](second.logicalMemory)[0x4000], 2) XCTAssertEqual(again.debuggerProgramRevision, stopped.debuggerProgramRevision) let cleared = await command { controller.basicSetBreakpoints([], source: source, completion: $0) } XCTAssertNil(cleared.errorMessage) let continued = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNil(continued.errorMessage) try await settle(controller, frames: 5) let running = await command(controller.snapshot) XCTAssertEqual(running.state, .running) XCTAssertEqual(running.basicStoppedLine, -1) } } func testBASICContinuePreservesSubroutineStackVariablesAndManualBreakpoints() async throws { try await withBASIC { controller in let source = "10 A=1\n20 GOSUB 100\n30 POKE &H4000,A\n40 END\n100 A=A+1:POKE &H4001,A\n110 RETURN\n" _ = await command { controller.debuggerSetBreakpoints([0xbfff], completion: $0) } let loaded = await command { controller.basicLoadSource(source, run: true, breakpoints: [30, 100], completion: $0) } XCTAssertNil(loaded.errorMessage) _ = try await waitForBASICStop(controller, line: 100) let before = await memory(controller) XCTAssertTrue(before.breakpoints.contains(NSNumber(value: 0xbfff))) let continued = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNil(continued.errorMessage) _ = try await waitForBASICStop(controller, line: 30) let returned = await memory(controller) XCTAssertEqual([UInt8](returned.logicalMemory)[0x4001], 2, "Colon statement executes without a second line-entry stop") let resumed = await command { controller.basicContinue(source: source, completion: $0) } XCTAssertNil(resumed.errorMessage) try await settle(controller, frames: 5) let result = await memory(controller) XCTAssertEqual([UInt8](result.logicalMemory)[0x4000], 2, "Variables and the GOSUB return stack survive Continue") XCTAssertTrue(result.breakpoints.contains(NSNumber(value: 0xbfff))) // Explicitly redirecting the CPU must not retain a stale BASIC stop. _ = await command(controller.pause) _ = await command { controller.debuggerSetPC(0xa000, completion: $0) } let detached = await command(controller.snapshot) XCTAssertFalse(detached.basicDebugAttached) } } func testBASICDebugRejectsStaleSourceAndDetachesAfterMemoryEditOrReset() async throws { try await withBASIC { controller in let source = "10 POKE &H4000,1\n20 GOTO 10\n" let previous = try await programBytes(controller) let refused = await command { controller.basicLoadSource(source, run: true, breakpoints: [999], completion: $0) } XCTAssertNotNil(refused.errorMessage) let unchanged = try await programBytes(controller); XCTAssertEqual(unchanged, previous) _ = await command { controller.basicLoadSource(source, run: true, breakpoints: [10], completion: $0) } let stopped = try await waitForBASICStop(controller, line: 10) let rejected = await command { controller.basicContinue(source: "10 END\n", completion: $0) } XCTAssertNotNil(rejected.errorMessage) XCTAssertEqual(rejected.state, .paused); XCTAssertEqual(rejected.cycles, stopped.cycles) let capture = await memory(controller), bytes = [UInt8](capture.logicalMemory) let start = UInt16(bytes[0x19]) * 256 + UInt16(bytes[0x1a]) _ = await command { controller.debuggerWriteMemory(address: start + 4, data: Data([0x80]), completion: $0) } let edited = await command(controller.snapshot) XCTAssertFalse(edited.basicDebugAttached); XCTAssertEqual(edited.basicStoppedLine, -1) XCTAssertTrue(edited.basicDebugStatus.contains("changed")) _ = await command(controller.softReset) let reset = await command(controller.snapshot) XCTAssertFalse(reset.basicDebugAttached); XCTAssertEqual(reset.basicStoppedLine, -1) } } func testDirectLoadReadAndRunPreserveMachineAndMediaOnBothProcessors() async throws { try await withBASIC { controller in _ = await command(controller.pause) let before = await command(controller.snapshot) let loaded = await command { controller.basicLoadSource("10 PRINT 6*7\n20 END\n", run: false, completion: $0) } XCTAssertNil(loaded.errorMessage) XCTAssertEqual(loaded.state, .paused, "Loading while paused must not execute guest instructions") XCTAssertEqual(loaded.cycles, before.cycles) XCTAssertEqual(loaded.generation, before.generation) XCTAssertEqual(loaded.pasteRemaining, 0, "Direct BASIC loading must not enqueue keyboard input") let (source, error) = await read(controller) XCTAssertNil(error); XCTAssertTrue(source?.contains("10 PRINT 6*7") == true) XCTAssertTrue(source?.contains("20 END") == true) let running = await command { controller.basicLoadSource("10 PRINT 6*7\n20 END\n", run: true, completion: $0) } XCTAssertNil(running.errorMessage); XCTAssertEqual(running.state, .running) XCTAssertEqual(running.pasteRemaining, 0) try await waitForScreen("42", controller: controller) try await settle(controller) let after = await command(controller.snapshot) XCTAssertEqual(after.generation, before.generation) XCTAssertEqual(after.use6309, before.use6309) XCTAssertEqual(after.ramConfiguration, before.ramConfiguration) XCTAssertEqual(after.audioEnabled, before.audioEnabled) XCTAssertTrue(after.disks[0].mounted); XCTAssertFalse(after.disks[0].dirty) XCTAssertEqual(after.disks[0].name, "Preserved.dsk") XCTAssertTrue(after.disks[0].writeProtected) XCTAssertTrue(after.tapeMounted); XCTAssertFalse(after.tapeDirty) XCTAssertEqual(after.tapeMode, before.tapeMode) } } func testRejectedSourceLeavesThePreviousProgramIntactOnBothProcessors() async throws { try await withBASIC { controller in let loaded = await command { controller.basicLoadSource("10 PRINT 42\n", run: false, completion: $0) } XCTAssertNil(loaded.errorMessage) let original = try await programBytes(controller) let oversized = (1...500).map { "\($0) REM " + String(repeating: "X", count: 120) }.joined(separator: "\n") for source in ["PRINT 42\n", "64000 PRINT 42\n", "10 PRINT \u{0000}\n", oversized] { let failed = await command { controller.basicLoadSource(source, run: false, completion: $0) } XCTAssertNotNil(failed.errorMessage) XCTAssertEqual(failed.generation, loaded.generation) let preserved = try await programBytes(controller) XCTAssertEqual(preserved, original, "Validation must precede RAM replacement") } } } func testDirectTokenizationMatchesActualROMEntryOnBothProcessors() async throws { try await withBASIC { controller in // This source is intentionally entered through the original ROM first. // No handcrafted token table supplies the expected output. let source = """ 10 REM PRINT "KEEP":DATA 20 DATA "PRINT:REM",12:PRINT "A:B"; 30 ? LEFT$("ABC",1):IF 1 THEN 50 ELSE 40 40 'PRINT SIN(1) 50 HSCREEN 0:DIR """ + "\n" let paste = try CocoPaste(source, mode: .newBASIC) let started = await command { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) } XCTAssertNil(started.errorMessage) var finished = false for _ in 0..<2500 { if await command(controller.snapshot).pasteRemaining == 0 { finished = true; break } try await Task.sleep(nanoseconds: 20_000_000) } XCTAssertTrue(finished) try await settle(controller) let expected = try await programBytes(controller) XCTAssertGreaterThan(expected.count, 20) let loaded = await command { controller.basicLoadSource(source, run: false, completion: $0) } XCTAssertNil(loaded.errorMessage) let installed = try await programBytes(controller) XCTAssertEqual(installed, expected) let (roundTrip, error) = await read(controller) XCTAssertNil(error) let second = await command { controller.basicLoadSource(roundTrip ?? "", run: false, completion: $0) } XCTAssertNil(second.errorMessage) let reloaded = try await programBytes(controller) XCTAssertEqual(reloaded, expected, "Read-back must remain a lossless source representation") } } func testExecutingAndInputProgramsCannotBeReplacedOnBothProcessors() async throws { try await withBASIC { controller in for source in ["10 GOTO 10\n", "10 INPUT \"VALUE\";A\n20 GOTO 10\n"] { let started = await command { controller.basicLoadSource(source, run: true, completion: $0) } XCTAssertNil(started.errorMessage) try await settle(controller) let original = try await programBytes(controller) let refused = await command { controller.basicLoadSource("10 PRINT 99\n", run: false, completion: $0) } XCTAssertNotNil(refused.errorMessage, "Running BASIC and INPUT are not the direct-mode prompt") let after = try await programBytes(controller) XCTAssertEqual(after, original) XCTAssertEqual(refused.generation, started.generation) _ = await command(controller.softReset) _ = await command(controller.resume) try await settle(controller, frames: 60) } } } func testDiskAndCassetteExportPreservePausedAndRunningSessionsOnBothProcessors() async throws { try await withBASIC { controller in _ = await command(controller.pause) let loaded = await command { controller.basicLoadSource("10 GOTO 10\n", run: false, completion: $0) } XCTAssertNil(loaded.errorMessage) let original = await memory(controller) let source = "10 PRINT \"EXPORTED, NOT LOADED\"\n20 END\n" var payloads: [Bool: Data] = [:] for cassette in [false, true] { let (bytes, after) = await export(controller, source: source, name: "hello", cassette: cassette) XCTAssertNil(after.errorMessage) let payload = try XCTUnwrap(bytes) if cassette { XCTAssertGreaterThan(payload.count, 256) } else { XCTAssertEqual(payload.count, 35 * 18 * 256) } payloads[cassette] = payload assertExportPreservesSession(after, loaded) XCTAssertEqual(after.cycles, loaded.cycles) let afterMemory = await memory(controller) XCTAssertEqual(afterMemory.logicalMemory, original.logicalMemory) XCTAssertEqual(afterMemory.registers, original.registers) } let running = await command { controller.basicLoadSource("10 GOTO 10\n", run: true, completion: $0) } XCTAssertNil(running.errorMessage) try await settle(controller) let originalProgram = try await programBytes(controller) for cassette in [false, true] { let before = await command(controller.snapshot) let (bytes, after) = await export(controller, source: source, cassette: cassette) XCTAssertNil(after.errorMessage) XCTAssertEqual(bytes, payloads[cassette], "Export bytes are independent of the running program and filename case") assertExportPreservesSession(after, before) let afterProgram = try await programBytes(controller) XCTAssertEqual(afterProgram, originalProgram) } } } func testInvalidExportLeavesProgramAndMountedMediaUntouchedOnBothProcessors() async throws { try await withBASIC { controller in _ = await command(controller.pause) let before = await command { controller.basicLoadSource("10 PRINT 42\n", run: false, completion: $0) } XCTAssertNil(before.errorMessage) let original = await memory(controller) for cassette in [false, true] { let cases = [("PRINT 42\n", "HELLO"), ("10 PRINT 42\n", ""), ("10 PRINT 42\n", "../BAD"), ("10 PRINT 42\n", "TOOLONG99"), ("10 PRINT 42\n", "BAD.BAS"), ("10 PRINT 42\n", "HÉLLO")] for (source, name) in cases { let (bytes, failed) = await export(controller, source: source, name: name, cassette: cassette) XCTAssertNil(bytes) XCTAssertNotNil(failed.errorMessage) assertExportPreservesSession(failed, before) XCTAssertEqual(failed.cycles, before.cycles) } } let after = await memory(controller) XCTAssertEqual(after.logicalMemory, original.logicalMemory) XCTAssertEqual(after.registers, original.registers) } } func testUnsupportedMachineDoesNotAcceptDirectBASICMemoryWrites() async throws { let controller = VCCMachineController() let empty = await command { controller.basicLoadSource("10 PRINT 42\n", run: true, completion: $0) } XCTAssertNotNil(empty.errorMessage) let loaded = await command(controller.loadDiagnostic) let before = await memory(controller) let rejected = await command { controller.basicLoadSource("10 PRINT 42\n", run: true, completion: $0) } XCTAssertNotNil(rejected.errorMessage) XCTAssertEqual(rejected.generation, loaded.generation) XCTAssertEqual(rejected.state, loaded.state) let after = await memory(controller) XCTAssertEqual(after.logicalMemory, before.logicalMemory) let (source, error) = await read(controller) XCTAssertNil(source); XCTAssertNotNil(error) for cassette in [false, true] { let (bytes, refused) = await export(controller, source: "10 PRINT 42\n", cassette: cassette) XCTAssertNil(bytes); XCTAssertNotNil(refused.errorMessage) assertExportPreservesSession(refused, rejected) } // A valid CPU ROM is not necessarily a recognized BASIC interpreter. var synthetic = Data(repeating: 0x12, count: 32768) synthetic[0] = 0x20; synthetic[1] = 0xfe synthetic[32766] = 0x80; synthetic[32767] = 0 let otherROM = await command { controller.loadROM(synthetic, use6309: false, completion: $0) } XCTAssertNil(otherROM.errorMessage) let customBefore = await memory(controller) let customRejected = await command { controller.basicLoadSource("10 PRINT 42\n", run: true, completion: $0) } XCTAssertNotNil(customRejected.errorMessage) let customAfter = await memory(controller) XCTAssertEqual(customAfter.logicalMemory, customBefore.logicalMemory) XCTAssertEqual(customRejected.generation, otherROM.generation) let (customSource, customError) = await read(controller) XCTAssertNil(customSource); XCTAssertNotNil(customError) _ = await command(controller.shutdown) } }