// SPDX-License-Identifier: GPL-3.0-or-later import XCTest import CryptoKit import AppKit final class SoftwareLibraryMachineLaunchTests: XCTestCase { override func setUp() async throws { try await super.setUp() // InputHub reads the host application's activation state. Initialize // AppKit explicitly so this class also runs without earlier suites. await MainActor.run { _ = NSApplication.shared } } private struct Fixture { let folder: URL, defaults: UserDefaults, suite: String init() throws { folder = FileManager.default.temporaryDirectory.appendingPathComponent("LibraryMachine-" + UUID().uuidString) suite = "LibraryMachine-" + UUID().uuidString; defaults = UserDefaults(suiteName: suite)! try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) } func cleanup() { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: folder) } func initialProfile() throws -> ConfigurationProfile { var profile = ConfigurationProfile(name: "Before Library") profile.sound = false; profile.volume = 0.23 var rom = Data(repeating: 0x12, count: 32768) rom[0] = 0x20; rom[1] = 0xfe; rom[32766] = 0x80; rom[32767] = 0 profile.systemROM = folder.appendingPathComponent("System.rom"); try rom.write(to: profile.systemROM!) profile.media.rom = folder.appendingPathComponent("Disk.rom") try Data(repeating: 0, count: 8192).write(to: profile.media.rom!) let disk = folder.appendingPathComponent("Previous.dsk") try Data(repeating: 0, count: 161280).write(to: disk) profile.media.drives[0] = .init(url: disk, writeProtected: true) var cartridges = CartridgeAssignments(); cartridges.multiPak = true; cartridges.mpiConfigured = true cartridges.physicalSlot = 4; cartridges.slots[4].kind = .floppy profile.media.cartridges = cartridges profile.input.right.source = .controller; profile.input.right.device = "remembered-controller" return profile } func plan(cartridge: Bool = true, command: String? = nil, keyboardControls: Bool = false, cartridgeDevice: String = "rom", hardDrive: Bool = false) throws -> SoftwareLibraryLaunchPlan { let working = folder.appendingPathComponent(UUID().uuidString).appendingPathComponent("Working") try FileManager.default.createDirectory(at: working, withIntermediateDirectories: true) let filename = hardDrive ? "Fixture.vhd" : cartridge ? "Fixture.ccc" : "Fixture.dsk" var bytes = Data(repeating: cartridge ? 0x12 : 0, count: cartridge ? 8192 : 161280) if cartridge { bytes[0] = 0x20; bytes[1] = 0xfe } try bytes.write(to: working.appendingPathComponent(filename)) let sha = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() var configuration: [String: LibraryJSON] = ["profile": .string(hardDrive ? "hard-drive-basic" : cartridge ? "rom-cartridge" : "disk-basic"), "processor": .string("6809"), "ram_kib": .number(2048), "video": .string("composite"), "controller_slot": .number(4), "controls": .object(["right": .object(["suggested_input": .string("keyboard-joystick")])])] if keyboardControls { configuration["controls"] = .object(["keyboard": .string("Arrow keys, Z, X and C")]) } if cartridge { configuration["launch_method"] = .string("cartridge-autostart"); configuration["cartridge_device"] = .string(cartridgeDevice) } let setup = SoftwareLibrarySetup(status: command == nil && !cartridge ? "manual-setup" : "inferred-ready", command: command, instructions: "Authored launch fixture", configuration: .object(configuration), selectedMembers: .array([.object(["path": .string(filename), "target": .string(hardDrive ? "hard0" : cartridge ? "cartridge" : "disk0")])]), reasons: [], validation: .object([:])) let release = SoftwareLibraryRelease(id: "fixture", titleID: "fixture", name: "Fixture", category: cartridge ? "Cartridges" : "Disks/Games", mediaType: hardDrive ? "hard-disk" : cartridge ? "cartridge" : "disk", contentRole: "software", sourceURL: URL(string: "https://example.invalid/" + filename)!, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: sha, byteSize: Int64(bytes.count), languageStatus: "english", metadata: .object(["title": .string("Authored Launch")]), setup: setup, assets: [], downloadURLs: []) let receipt = SoftwareLibraryInstallationReceipt(releaseID: release.id, packageSHA256: sha, installedAt: Date(), workingDirectory: working, relativeFiles: [filename]) return try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt) } } @MainActor private func step(_ body: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { await withCheckedContinuation { continuation in body { continuation.resume(returning: $0) } } } @MainActor private func settle(_ model: MachineModel) async throws { for _ in 0..<500 { if !model.busy && !model.diskSaving { return } try await Task.sleep(nanoseconds: 10_000_000) } throw ProfileFailure.message("Library machine test did not settle") } @MainActor private func withMachine(_ fixture: Fixture, _ body: (MachineModel, VCCMachineController, ConfigurationProfile) async throws -> Void) async throws { let controller = VCCMachineController() let model = MachineModel(diskStore: .init(url: fixture.folder.appendingPathComponent("Disks.json")), controller: controller, displayDefaults: fixture.defaults, inputStore: .init(url: fixture.folder.appendingPathComponent("Input.json"))) do { try await settle(model) let initial = try fixture.initialProfile() await model.loadProfile(initial); XCTAssertNil(model.profileError) model.resume(); try await settle(model) try await body(model, controller, initial) } catch { await withCheckedContinuation { done in model.shutdown { done.resume() } }; throw error } await withCheckedContinuation { done in model.shutdown { done.resume() } } } @MainActor func testLibraryReturnRestoresBuiltInNitrOS9NetworkingDefault() async throws { let startup = try StartupTests.Fixture(); defer { startup.remove() } let fixture = try Fixture(); defer { fixture.cleanup() } let model = MachineModel(diskStore: startup.disks, displayDefaults: fixture.defaults, inputStore: .init(url: fixture.folder.appendingPathComponent("Input.json")), startupStore: startup.startup) do { try await settle(model) let selected = await model.loadSystemProfile(.nitros9) XCTAssertTrue(selected); XCTAssertTrue(model.driveWireEnabled) let prepared = try await model.prepareLibraryLaunch(fixture.plan()) let previous = try XCTUnwrap(prepared.previousSetup) let launched = try await model.launchLibrary(prepared) XCTAssertNil(launched.message); XCTAssertFalse(model.driveWireEnabled, "A Library launch uses its own default") try await model.returnLibrarySetup(previous) XCTAssertTrue(model.driveWireEnabled, "Return preserves the originating built-in preset") XCTAssertEqual(try startup.startup.read()?.builtInNitros9, true) } catch { await withCheckedContinuation { done in model.shutdown { done.resume() } }; throw error } await withCheckedContinuation { done in model.shutdown { done.resume() } } } @MainActor func testMissingFirmwarePreflightLeavesRunningMachineUntouched() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, controller, initial in let plan = try fixture.plan() let before = await step(controller.snapshot) try FileManager.default.removeItem(at: initial.systemROM!) do { _ = try await model.prepareLibraryLaunch(plan); XCTFail("Missing firmware must not prepare") } catch { } let after = await step(controller.snapshot) XCTAssertEqual(after.generation, before.generation); XCTAssertEqual(after.state, .running) XCTAssertEqual(model.profileName, initial.name); XCTAssertTrue(after.disks[0].mounted) } } @MainActor func testHardDriveLibraryRejectsUnrecognizedDiskROMWithoutChangingMachine() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, controller, initial in let before = await step(controller.snapshot) do { _ = try await model.prepareLibraryLaunch(fixture.plan(cartridge: false, hardDrive: true)) XCTFail("An arbitrary Disk BASIC ROM cannot stand in for RGB-DOS") } catch { XCTAssertTrue(error.localizedDescription.contains("rgbdos.rom")) } let after = await step(controller.snapshot) XCTAssertEqual(after.generation, before.generation) XCTAssertEqual(after.state, .running) XCTAssertEqual(model.diskAssignments.rom, initial.media.rom) XCTAssertEqual(model.profileName, initial.name) } } @MainActor func testHardDriveLibraryUsesSuppliedRGBDOSAndRecognizedCachedFallback() async throws { let startup = try StartupTests.Fixture(); defer { startup.remove() } let fixture = try Fixture(); defer { fixture.cleanup() } let rgbdos = Data(repeating: 0x39, count: 8192) try rgbdos.write(to: startup.kit.directory.appendingPathComponent("rgbdos.rom")) let model = MachineModel(diskStore: startup.disks, displayDefaults: fixture.defaults, inputStore: .init(url: fixture.folder.appendingPathComponent("Input.json")), startupStore: startup.startup) do { try await settle(model) let initial = try fixture.initialProfile() await model.loadProfile(initial); XCTAssertNil(model.profileError) let plan = try fixture.plan(cartridge: false, hardDrive: true) let prepared = try await model.prepareLibraryLaunch(plan) let rom = try XCTUnwrap(prepared.profile.media.rom) XCTAssertNotEqual(rom, initial.media.rom) XCTAssertEqual(try Data(contentsOf: rom), rgbdos) XCTAssertEqual(prepared.profile.media.hardDisks?.drives[0]?.url, plan.hardDiskURLs[0]) XCTAssertEqual(prepared.profile.media.cartridges?.slots[4].kind, .floppy) XCTAssertEqual(prepared.profile.media.cartridges?.slots[1].kind, .hardDisk) // Known starter firmware remains a valid fallback after bundle moves. let loaded = await model.loadSystemProfile(.hardDriveBasic) XCTAssertTrue(loaded) XCTAssertEqual(model.usageProfile, .hardDriveBasic) try FileManager.default.removeItem(at: startup.kit.directory.appendingPathComponent("rgbdos.rom")) let cached = try await model.prepareLibraryLaunch(plan) XCTAssertEqual(cached.profile.media.rom, rom) XCTAssertEqual(try Data(contentsOf: XCTUnwrap(cached.profile.media.rom)), rgbdos) } catch { await withCheckedContinuation { done in model.shutdown { done.resume() } }; throw error } await withCheckedContinuation { done in model.shutdown { done.resume() } } } @MainActor func testPreviewDoesNotChangeSessionAndStaleConfigurationCannotLaunch() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, controller, _ in let before = await step(controller.snapshot) let prepared = try await model.prepareLibraryLaunch(fixture.plan()) let preview = await step(controller.snapshot) XCTAssertEqual(preview.generation, before.generation); XCTAssertEqual(preview.state, .running) XCTAssertEqual(preview.audioStarts, before.audioStarts); XCTAssertTrue(preview.disks[0].mounted) model.volume = 0.71 do { _ = try await model.launchLibrary(prepared); XCTFail("Changed setup requires another preview") } catch { } let after = await step(controller.snapshot) XCTAssertEqual(after.generation, before.generation); XCTAssertEqual(after.state, .running) } } @MainActor func testUnsavedMediaBlocksLaunchAndRetainsDirtyDisk() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, controller, _ in model.createDisk(1); try await settle(model) let prepared = try await model.prepareLibraryLaunch(fixture.plan()) let before = await step(controller.snapshot); XCTAssertTrue(before.disks[1].dirty) XCTAssertNil(prepared.previousSetup, "Unbacked media cannot be recreated by a return-to-setup profile") do { _ = try await model.launchLibrary(prepared); XCTFail("Dirty unbacked media must block replacement") } catch { } let after = await step(controller.snapshot) XCTAssertEqual(after.generation, before.generation); XCTAssertTrue(after.disks[1].dirty) XCTAssertTrue(after.disks[0].mounted); XCTAssertEqual(after.state, .paused) } } @MainActor func testCartridgeLaunchClearsDebuggerAndReturnRestoresConfiguration() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, controller, initial in _ = await step(controller.pause) _ = await step { controller.debuggerConfigureBreakpoints([0x2000], disabled: [0x2002], completion: $0) } let binary = Data([0, 0, 2, 0x20, 0, 0x20, 0xfe, 0xff, 0, 0, 0x20, 0]) let attached = await step { controller.debuggerLoadBinary(binary, breakpoints: [0x2000], completion: $0) } XCTAssertNil(attached.errorMessage) XCTAssertTrue(attached.debuggerDevelopmentAttached) let plan = try fixture.plan() let prepared = try await model.prepareLibraryLaunch(plan) let previous = try XCTUnwrap(prepared.previousSetup) let result = try await model.launchLibrary(prepared) XCTAssertNil(result.message) let running = await step(controller.snapshot) XCTAssertNotEqual(running.generation, attached.generation); XCTAssertEqual(running.state, .running) XCTAssertFalse(running.debuggerDevelopmentAttached) let debugger: VCCDebuggerSnapshot = await withCheckedContinuation { done in controller.debuggerSnapshot(address: 0x8000, followPC: false, memoryAddress: 0) { done.resume(returning: $0) } } XCTAssertTrue(debugger.breakpoints.isEmpty); XCTAssertTrue(debugger.disabledBreakpoints.isEmpty) XCTAssertEqual(model.cartridgeAssignments.slots[4].url, plan.cartridgeURL) XCTAssertEqual(model.settings.ram, 2); XCTAssertEqual(model.volume, initial.volume) XCTAssertFalse(model.audioEnabled); XCTAssertEqual(model.input.settings.right, initial.input.right, "Preserve the user's physical controller assignment") try await model.returnLibrarySetup(previous) let restored = await step(controller.snapshot) XCTAssertEqual(restored.state, .running); XCTAssertTrue(restored.disks[0].mounted) XCTAssertEqual(model.diskAssignments.drives[0]?.url, initial.media.drives[0]?.url) XCTAssertEqual(model.settings, initial.machine) } } @MainActor func testOrchestraCartridgeUsesNativeSoundDevice() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, controller, _ in let plan = try fixture.plan(cartridgeDevice: "orchestra90") let prepared = try await model.prepareLibraryLaunch(plan) XCTAssertEqual(prepared.profile.media.cartridges?.slots[4].kind, .orchestra90) let result = try await model.launchLibrary(prepared) XCTAssertNil(result.message) XCTAssertEqual(model.cartridgeAssignments.slots[4].kind, .orchestra90) XCTAssertEqual(model.cartridgeAssignments.slots[4].url, plan.cartridgeURL) let running = await step(controller.snapshot) XCTAssertEqual(running.state, .running) XCTAssertEqual(running.cartridgeKinds[4].intValue, model.cartridgeAssignments.slots[4].kind.rawValue) } } @MainActor func testNativeKeyboardGameReleasesOnlyKeyboardJoystickPort() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, _, initial in var changed = initial changed.input.right.source = .keyboard changed.input.left.source = .controller; changed.input.left.device = "physical-left" await model.loadProfile(changed); model.resume(); try await settle(model) let prepared = try await model.prepareLibraryLaunch(fixture.plan(keyboardControls: true)) XCTAssertEqual(prepared.profile.input.right.source, .none) XCTAssertEqual(prepared.profile.input.left, changed.input.left) XCTAssertEqual(model.input.settings.right.source, .keyboard, "Preview must not change current input") } } @MainActor func testManualDiskLaunchMountsWithoutInjectingCommands() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, controller, _ in var configuredInput = model.input.settings configuredInput.right = PortSettings(source: .controller, interface: .tandy, device: "remembered-disconnected") configuredInput.left = PortSettings(source: .mouse, interface: .cocoMax) model.input.applyProfileSettings(configuredInput) let inputEpoch = model.input.epoch let plan = try fixture.plan(cartridge: false) XCTAssertTrue(plan.commands.isEmpty); XCTAssertFalse(plan.automaticallyStarts) let prepared = try await model.prepareLibraryLaunch(plan) let result = try await model.launchLibrary(prepared) XCTAssertNil(result.message) let running = await step(controller.snapshot) XCTAssertEqual(running.state, .running); XCTAssertTrue(running.disks[0].mounted) XCTAssertEqual(running.pasteRemaining, 0) XCTAssertEqual(Int(running.joystickInputs[0].mode), configuredInput.right.interface.rawValue) XCTAssertEqual(Int(running.joystickInputs[1].mode), configuredInput.left.interface.rawValue) XCTAssertEqual(model.input.settings, configuredInput) XCTAssertEqual(model.input.epoch, inputEpoch) XCTAssertEqual(model.diskAssignments.drives[0]?.url, plan.floppyURLs[0]) } } @MainActor func testCancelDuringPromptWaitLeavesAppliedSetupPausedWithMedia() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, controller, _ in let plan = try fixture.plan(cartridge: false, command: "RUN\"HELLO\"\r") let prepared = try await model.prepareLibraryLaunch(plan) let before = await step(controller.snapshot) let launch = Task { @MainActor in try await model.launchLibrary(prepared) } var applied = false for _ in 0..<500 { let current = await step(controller.snapshot) if current.generation != before.generation { applied = true; break } try await Task.sleep(nanoseconds: 10_000_000) } XCTAssertTrue(applied); launch.cancel() let result = try await launch.value XCTAssertNotNil(result.message) let paused = await step(controller.snapshot) XCTAssertEqual(paused.state, .paused); XCTAssertEqual(paused.pasteRemaining, 0) XCTAssertTrue(paused.disks[0].mounted) XCTAssertEqual(model.diskAssignments.drives[0]?.url, plan.floppyURLs[0]) } } /// Explicit local review only: proprietary ROMs and Archive software never enter Git. /// The marker JSON supplies {"repository": "/.../VCCPlus", "output": "/tmp/..."}. @MainActor func testOptInRealCatalogCartridgeDiskCassetteAndSDC() async throws { let marker = URL(fileURLWithPath: "/tmp/vcc-library-real-launch-config.json") try XCTSkipUnless(FileManager.default.fileExists(atPath: marker.path), "Opt-in real-media launch review is not enabled") let config = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: marker)) as? [String: String]) let repo = URL(fileURLWithPath: try XCTUnwrap(config["repository"])) let output = URL(fileURLWithPath: try XCTUnwrap(config["output"])) try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) let media = repo.appendingPathComponent("media/software-library-full") let catalog = try await SoftwareLibraryCatalog.load(from: media.appendingPathComponent("prepared/app-catalog.sqlite")) let roms = repo.appendingPathComponent("platforms/macos/LocalResources/ROMs") let cases = [("MegaBug", "3b56eeffbf4f2131ba8b0c9a248ecec8"), ("BedlamDisk", "0d0cf0cd41681695d541afdbaba15096"), ("BedlamCassette", "4ae2f5e30faa14f8d30abd7efb711b90"), ("DoubleDragon", "6062d9b73d08579671fe0d489c53fdd0")] for (label, id) in cases { let fixture = try Fixture(); defer { fixture.cleanup() } let release = try XCTUnwrap(catalog.releases.first { $0.id == id }) let installRoot = fixture.folder.appendingPathComponent("Library") let packages = installRoot.appendingPathComponent("Packages") try FileManager.default.createDirectory(at: packages, withIntermediateDirectories: true) let cached = media.appendingPathComponent("cache").appendingPathComponent(release.packageSHA256 + "." + release.sourceURL.pathExtension) try FileManager.default.copyItem(at: cached, to: packages.appendingPathComponent(release.packageSHA256 + ".package")) // The normal installer verifies the cached SHA-256 and size before extracting. let installer = SoftwareLibraryInstaller(root: installRoot) let receipt = try await installer.install(release) let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt) let controller = VCCMachineController() let model = MachineModel(diskStore: .init(url: fixture.folder.appendingPathComponent("Disks.json")), controller: controller, displayDefaults: fixture.defaults, inputStore: .init(url: fixture.folder.appendingPathComponent("Input.json")), startupStore: .init(directory: fixture.folder.appendingPathComponent("Support"), kit: StarterKit(directory: roms))) do { try await settle(model) var initial = try fixture.initialProfile() initial.systemROM = roms.appendingPathComponent("coco3.rom") initial.media.rom = roms.appendingPathComponent("disk11.rom") await model.loadProfile(initial); XCTAssertNil(model.profileError) let prepared = try await model.prepareLibraryLaunch(plan) let result = try await model.launchLibrary(prepared) XCTAssertNil(result.message, "\(label): \(result.message ?? "")") // Observe the actual program, not merely an accepted loading command. // Double Dragon reads all nine images at the normal emulation rate. let deadline = Date().addingTimeInterval(label == "DoubleDragon" ? 420 : 60) var arrived = false var snapshot = await step(controller.snapshot) var screen = "" while Date() < deadline { let text: String? = await withCheckedContinuation { done in controller.inspectScreenText { value, _ in done.resume(returning: value) } } snapshot = await step(controller.snapshot) screen = text ?? "[graphics]" if label.hasPrefix("Bedlam") { arrived = screen.contains("AWAKENED") || screen.contains("WHERE AM I") } else if label == "DoubleDragon" { arrived = text == nil && snapshot.sdcReadCount > 1000 } else { arrived = text == nil } if arrived || snapshot.state != .running || snapshot.errorMessage != nil { break } try await Task.sleep(nanoseconds: 250_000_000) } XCTAssertTrue(arrived, "\(label) did not reach its program screen: \(screen)") // Allow the first graphics screen to draw completely before capture. if arrived && !label.hasPrefix("Bedlam") { let firstFrame = snapshot.frames for _ in 0..<100 { snapshot = await step(controller.snapshot) if snapshot.frames >= firstFrame + 120 { break } try await Task.sleep(nanoseconds: 50_000_000) } } XCTAssertFalse(snapshot.fastForward, "Validate the normal-speed launch path") XCTAssertEqual(snapshot.ramConfiguration, 2) let afterProbe = await step(controller.snapshot) XCTAssertEqual(afterProbe.state, snapshot.state, "Read-only screen inspection preserves state") XCTAssertEqual(afterProbe.generation, snapshot.generation) XCTAssertNil(afterProbe.errorMessage, "Graphics is not a machine failure") XCTAssertEqual(snapshot.state, .running, label) XCTAssertNil(snapshot.errorMessage, label) XCTAssertEqual(snapshot.pasteRemaining, 0, label) if label == "BedlamDisk" { XCTAssertGreaterThan(snapshot.disks[0].readEvents, 0) } if label == "BedlamCassette" { XCTAssertGreaterThan(snapshot.tapeReadEvents, 0) } if label == "DoubleDragon" { XCTAssertGreaterThan(snapshot.sdcReadCount, 20); XCTAssertNil(snapshot.sdcError) } let image = try ScreenCapture(pixels: snapshot.pixels, area: snapshot.activeVideoRect).png() try image.write(to: output.appendingPathComponent(label + ".png")) let report = "\(label)\nstate=\(snapshot.state.rawValue), PC=\(snapshot.programCounter), frames=\(snapshot.frames), tapeReads=\(snapshot.tapeReadEvents), floppyReads=\(snapshot.disks[0].readEvents), sdcReads=\(snapshot.sdcReadCount)\n\(screen)\n" try report.write(to: output.appendingPathComponent(label + ".txt"), atomically: true, encoding: .utf8) } catch { await withCheckedContinuation { done in model.shutdown { done.resume() } }; throw error } await withCheckedContinuation { done in model.shutdown { done.resume() } } } } }