// SPDX-License-Identifier: GPL-3.0-or-later import XCTest import CryptoKit /// Authored catalog/media fixtures. Optional ROM/toolchain checks use private /// local inputs and ordinary keyboard commands, never injected guest results. final class SoftwareLibraryCuratedLaunchTests: XCTestCase { private struct Fixture { let folder: URL let defaults: UserDefaults let suite = "CuratedLibrary-" + UUID().uuidString init() throws { folder = FileManager.default.temporaryDirectory.appendingPathComponent("CuratedLibrary-" + 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(realROMs: Bool = false, cpu: Bool = false) throws -> ConfigurationProfile { var profile = ConfigurationProfile(name: "Before curated Play") profile.sound = false; profile.machine.use6309 = cpu let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() if realROMs { profile.systemROM = mac.appendingPathComponent("LocalResources/ROMs/coco3.rom") profile.media.rom = mac.appendingPathComponent("LocalResources/ROMs/disk11.rom") try XCTSkipUnless(FileManager.default.fileExists(atPath: profile.systemROM!.path) && FileManager.default.fileExists(atPath: profile.media.rom!.path), "Stage optional licensed CoCo ROMs") } else { 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!) } var cartridges = CartridgeAssignments(); cartridges.multiPak = true; cartridges.mpiConfigured = true cartridges.physicalSlot = 4; cartridges.slots[4].kind = .floppy profile.media.cartridges = cartridges return profile } func release(ram: Int = 512, cpu: Bool = false, owned: Bool = true, approved: Bool = true, bytes: Data = Data(repeating: 0, count: 161280), change: ((inout [String: Any]) -> Void)? = nil) throws -> (SoftwareLibraryRelease, SoftwareLibraryInstallationReceipt) { let installation = folder.appendingPathComponent(UUID().uuidString) let working = installation.appendingPathComponent("Working") let originals = installation.appendingPathComponent("Original/Files") try FileManager.default.createDirectory(at: working, withIntermediateDirectories: true) try FileManager.default.createDirectory(at: originals, withIntermediateDirectories: true) try bytes.write(to: working.appendingPathComponent("FIXTURE.DSK")) try bytes.write(to: originals.appendingPathComponent("FIXTURE.DSK")) let diskSHA = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() let packageSHA = String(repeating: "a", count: 64) let configuration: [String: LibraryJSON] = ["profile": .string("disk-basic"), "processor": .string(cpu ? "6309" : "6809"), "ram_kib": .number(Double(ram)), "controller_slot": .number(4), "video": .string("rgb")] func hosted(_ prefix: String, _ name: String) -> [String: Any] { ["url": "https://vccplus.brianholman.com/dl/software/CoCoLibrary/" + prefix + "/Fixture/1/" + name, "sha256": packageSHA, "byte_size": 123] } var record: [String: Any] = [ "schema_version": 1, "id": "vccplus.fixture", "release_id": "fixture-v1", "publication_status": approved ? "approved" : "pending-review", "getting_started": true, "category_featured": true, "browse_categories": ["Games"], "primary_browse_category": "Games", "provenance": ["kind": "project-owned", "collection": "vccplus-exclusive", "author": "Fixture Author", "license": "CC0 authored fixture", "project_url": "https://example.invalid/fixture"], "disk_package": hosted("Exclusives", "Fixture.zip"), "disk": ["path": "FIXTURE.DSK", "sha256": diskSHA, "byte_size": bytes.count], "setup": ["configuration": ["profile": "disk-basic", "processor": cpu ? "6309" : "6809", "ram_kib": ram], "selected_members": [["path": "FIXTURE.DSK", "target": "disk0"]], "command": "DOS\r", "validation": ["scope": "runtime-verified", "disk_sha256": diskSHA]], "first_play": ["mode": "cold-restart-dos"], "links": ["manual_online": "https://vccplus.brianholman.com/games/fixture/", "manual_pdf": hosted("Documents/Manuals/Exclusives", "Manual.pdf"), "source_repository": "https://example.invalid/fixture/source"], "source": ["package": hosted("Sources/Exclusives", "Source.zip"), "project_directory": "Fixture", "configuration_file": "Fixture/vccplus-project.json", "entry_source": "main.c", "license_files": ["LICENSE"]] ] change?(&record) let metadata: LibraryJSON = owned ? try JSONDecoder().decode(LibraryJSON.self, from: JSONSerialization.data(withJSONObject: ["owned_game": record])) : .object([:]) let setup = SoftwareLibrarySetup(status: "spot-checked", command: owned ? "DOS\r" : nil, instructions: "Authored fixture", configuration: .object(configuration), selectedMembers: .array([.object(["path": .string("FIXTURE.DSK"), "target": .string("disk0")])]), reasons: [], validation: .object([:])) let release = SoftwareLibraryRelease(id: "fixture-v1", titleID: "vccplus.fixture", name: "Fixture", category: "Disks/Games", mediaType: "disk", contentRole: "software", sourceURL: URL(string: "https://example.invalid/fixture")!, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: packageSHA, byteSize: 123, languageStatus: "english", metadata: metadata, setup: setup, assets: [], downloadURLs: []) return (release, .init(releaseID: release.id, packageSHA256: packageSHA, installedAt: Date(), workingDirectory: working, relativeFiles: ["FIXTURE.DSK"])) } } @MainActor private func command(_ body: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { await withCheckedContinuation { done in body { done.resume(returning: $0) } } } @MainActor private func settle(_ model: MachineModel) async throws { for _ in 0..<1000 { if !model.busy && !model.diskSaving { return } try await Task.sleep(nanoseconds: 10_000_000) } throw ProfileFailure.message("Authored curated-launch fixture did not settle") } @MainActor private func screen(_ controller: VCCMachineController) async -> String { await withCheckedContinuation { done in controller.copyScreenText { text, _ in done.resume(returning: text ?? "") } } } @MainActor private func waitForScreen(_ text: String, controller: VCCMachineController) async throws { for _ in 0..<1000 { if await screen(controller).contains(text) { return } try await Task.sleep(nanoseconds: 20_000_000) } throw ProfileFailure.message("Expected authored screen marker \(text): " + (await screen(controller))) } @MainActor private func withMachine(_ fixture: Fixture, profile: ConfigurationProfile, body: (MachineModel, VCCMachineController) async throws -> Void) async throws { let controller = VCCMachineController() let model = MachineModel(diskStore: .init(url: fixture.folder.appendingPathComponent("Disks-" + UUID().uuidString + ".json")), controller: controller, displayDefaults: fixture.defaults, inputStore: .init(url: fixture.folder.appendingPathComponent("Input-" + UUID().uuidString + ".json"))) do { try await settle(model); await model.loadProfile(profile); XCTAssertNil(model.profileError) model.resume(); try await settle(model) try await body(model, controller) } catch { await withCheckedContinuation { done in model.shutdown { done.resume() } }; throw error } await withCheckedContinuation { done in model.shutdown { done.resume() } } } func testVettedShortcutRequiresMatchingApprovedMetadataAndActualDiskRecipe() throws { let fixture = try Fixture(); defer { fixture.cleanup() } let (release, receipt) = try fixture.release() let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt) XCTAssertTrue(plan.usesCuratedStartup); XCTAssertEqual(plan.commands, ["DOS"]) try plan.validateMedia() let (pending, pendingReceipt) = try fixture.release(approved: false) XCTAssertFalse(try SoftwareLibraryLaunchPlan.prepare(release: pending, receipt: pendingReceipt).usesCuratedStartup) for mismatch in ["release_id", "id"] { let (changed, changedReceipt) = try fixture.release { $0[mismatch] = "vccplus.different" } XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: changed, receipt: changedReceipt)) } let (unverified, unverifiedReceipt) = try fixture.release { record in var setup = record["setup"] as! [String: Any] var evidence = setup["validation"] as! [String: Any]; evidence["scope"] = "fixture-only" setup["validation"] = evidence; record["setup"] = setup } XCTAssertThrowsError(try SoftwareLibraryLaunchPlan.prepare(release: unverified, receipt: unverifiedReceipt)) } func testWorkingSavesAreKeptButChangedOriginalCannotUseCuratedStartup() throws { let fixture = try Fixture(); defer { fixture.cleanup() } let (release, receipt) = try fixture.release() let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt) let working = receipt.workingDirectory.appendingPathComponent("FIXTURE.DSK") var saved = try Data(contentsOf: working); saved[100] = 42; try saved.write(to: working) try plan.validateMedia() XCTAssertEqual(try Data(contentsOf: working), saved, "Validating startup must not reset saved scores") let original = receipt.workingDirectory.deletingLastPathComponent().appendingPathComponent("Original/Files/FIXTURE.DSK") try saved.write(to: original) XCTAssertThrowsError(try plan.validateMedia()) XCTAssertEqual(try Data(contentsOf: working), saved) } @MainActor func testExplicit128And512KBReachPreparedAndActualMachineOnBothCPUs() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } for cpu in [false, true] { for ram in [128, 512] { try await withMachine(fixture, profile: fixture.initialProfile(cpu: cpu)) { model, controller in let (release, receipt) = try fixture.release(ram: ram, cpu: cpu, owned: false) let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt) let prepared = try await model.prepareLibraryLaunch(plan) XCTAssertEqual(plan.ramKiB, ram) XCTAssertEqual(prepared.profile.machine.ram, ram == 128 ? 0 : 1) _ = try await model.launchLibrary(prepared) let actual = await command(controller.snapshot) XCTAssertEqual(actual.ramConfiguration, ram == 128 ? 0 : 1) XCTAssertEqual(actual.use6309, cpu); XCTAssertTrue(actual.disks[0].mounted) } } } } @MainActor func testUnsavedDiskBlocksCuratedLaunchWithoutDiscardingIt() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture, profile: fixture.initialProfile()) { model, controller in model.createDisk(1); try await settle(model) let (release, receipt) = try fixture.release() let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt) let prepared = try await model.prepareLibraryLaunch(plan) let before = await command(controller.snapshot); XCTAssertTrue(before.disks[1].dirty) do { _ = try await model.launchLibrary(prepared); XCTFail("Unsaved media must block curated startup") } catch { } let after = await command(controller.snapshot) XCTAssertEqual(after.generation, before.generation); XCTAssertTrue(after.disks[1].dirty) } } @MainActor func testRealPromptAndOccupiedBASICRequireDifferentRestartReview() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture, profile: fixture.initialProfile(realROMs: true)) { _, controller in try await waitForScreen("OK", controller: controller) var ready = await command(controller.assistantReadiness) for _ in 0..<100 where ready.assistantDirectPrompt?.boolValue != true { try await Task.sleep(nanoseconds: 20_000_000); ready = await command(controller.assistantReadiness) } XCTAssertEqual(ready.assistantEmptyBASIC?.boolValue, true) XCTAssertFalse(SoftwareLibraryModel.needsCuratedRestartReview(ready)) XCTAssertTrue(SoftwareLibraryModel.needsCuratedRestartReview(ready, hasRAMDisk: true)) let paste = try CocoPaste("10 PRINT \"KEEP THIS PROGRAM\"\n", mode: .text) let queued = await command { controller.pasteChords(paste.chords.map { NSNumber(value: $0) }, completion: $0) } XCTAssertNil(queued.errorMessage) var occupied = await command(controller.assistantReadiness) for _ in 0..<500 where occupied.assistantEmptyBASIC?.boolValue != false || occupied.pasteRemaining > 0 { try await Task.sleep(nanoseconds: 20_000_000); occupied = await command(controller.assistantReadiness) } XCTAssertEqual(occupied.assistantEmptyBASIC?.boolValue, false) XCTAssertTrue(SoftwareLibraryModel.needsCuratedRestartReview(occupied)) let preserved: String? = await withCheckedContinuation { done in controller.basicReadSource { source, _ in done.resume(returning: source) } } XCTAssertTrue(preserved?.contains("KEEP THIS PROGRAM") == true) } try await withMachine(fixture, profile: fixture.initialProfile()) { _, controller in let unknown = await command(controller.assistantReadiness) XCTAssertNil(unknown.assistantEmptyBASIC) XCTAssertTrue(SoftwareLibraryModel.needsCuratedRestartReview(unknown)) } } @MainActor func testRealDOSStartupLoadsAuthoredHelloDiskOnBothCPUs() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } 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), "Stage optional bundled tools") _ = try fixture.initialProfile(realROMs: true) let template = mac.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("examples/cmoc/HelloDisk") let project = try CMOCProject.createHelloDisk(at: fixture.folder.appendingPathComponent("Hello Disk"), templateDirectory: template) let build = try await CMOCBuildService(toolchain: tools, buildRoot: fixture.folder.appendingPathComponent("Builds")) .build(project: project, overlays: [:], action: .disk) let disk = try Data(contentsOf: XCTUnwrap(build.diskURL)) for cpu in [false, true] { try await withMachine(fixture, profile: fixture.initialProfile(realROMs: true, cpu: cpu)) { model, controller in let (release, receipt) = try fixture.release(ram: 512, cpu: cpu, bytes: disk) let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt) XCTAssertTrue(plan.usesCuratedStartup) let prepared = try await model.prepareLibraryLaunch(plan) let before = await command(controller.snapshot) let launched = try await model.launchLibrary(prepared) XCTAssertNil(launched.message) try await waitForScreen("GENERATED WORD COUNT: 5", controller: controller) let output = await screen(controller) XCTAssertTrue(output.contains("DISK RESULT: 0"), output) let after = await command(controller.snapshot) XCTAssertNotEqual(after.generation, before.generation) XCTAssertEqual(after.use6309, cpu); XCTAssertEqual(after.ramConfiguration, 1) XCTAssertEqual(after.pasteRemaining, 0); XCTAssertFalse(after.debuggerDevelopmentAttached) } } } }