Sync source edition with VCC Plus 3.7.0 build 63

This commit is contained in:
Brian Holman committed 2026-11-14 01:43:46 -07:00
1 parent c652a5276d
commit b2ecec4d87
86 files changed
+10519 -472

No files matched your search

@@ -3,6 +3,7 @@ import CryptoKit
import Foundation
import PDFKit
import SQLite3
import SwiftUI
import XCTest
@MainActor
@@ -40,6 +41,33 @@ final class ArchiveReaderTests: XCTestCase {
private struct ReaderTimeout: Error {}
func testSavedPDFPageAndZoomResumeButExplicitLocationWins() async throws {
let pdf = PDFDocument()
for color in [NSColor.white, .gray] {
let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in color.setFill(); rect.fill(); return true }
pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: pdf.pageCount)
}
let bytes = try XCTUnwrap(pdf.dataRepresentation())
let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
let item = ArchiveDocument(id: digest, title: "Resume", collection: "Books",
sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Resume.pdf")!, memberPath: nil,
pageCount: 2, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Resume.pdf")!, deliveryBytes: Int64(bytes.count))
try bytes.write(to: directory.appendingPathComponent(digest + ".pdf"))
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
store.setReading(LibraryReadingPosition(documentID: digest, page: 2, offset: 0.7, zoom: 1.75, autoScales: false), for: "archive:" + digest)
let resumed = ArchiveReaderModel(remembersPage: true, cache: cache, continuity: store)
defer { resumed.reset() }
resumed.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300)
resumed.open(item, page: resumed.savedPage(for: digest), resumePosition: true)
try await waitFor { resumed.progress == nil }
XCTAssertNil(resumed.error)
XCTAssertEqual(resumed.page, 2)
XCTAssertEqual(resumed.view.scaleFactor, 1.75, accuracy: 0.01)
resumed.open(item, page: 1)
XCTAssertEqual(resumed.page, 1)
XCTAssertTrue(resumed.view.currentPage === resumed.document?.page(at: 0))
}
func testSelectingPDFPagesReusesTheVerifiedDocumentAndOpensTheCitedPage() async throws {
let pdf = PDFDocument()
for color in [NSColor.white, .gray] {
@@ -75,6 +103,36 @@ final class ArchiveReaderTests: XCTestCase {
XCTAssertTrue(model.view.currentPage === rendered.page(at: 0))
}
func testExplicitSamePageDuringPDFResumeDiscardsSavedZoomAndOffset() async throws {
let pdf = PDFDocument()
let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in NSColor.white.setFill(); rect.fill(); return true }
pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: 0)
let bytes = try XCTUnwrap(pdf.dataRepresentation())
let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
let item = ArchiveDocument(id: digest, title: "Same page", collection: "Books",
sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Same.pdf")!, memberPath: nil,
pageCount: 1, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Same.pdf")!, deliveryBytes: Int64(bytes.count))
try bytes.write(to: directory.appendingPathComponent(digest + ".pdf"))
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
store.setReading(LibraryReadingPosition(documentID: digest, page: 1, offset: 0.7, horizontalOffset: 0.6, zoom: 9, autoScales: false), for: "archive:" + digest)
let model = ArchiveReaderModel(remembersPage: true, cache: cache, continuity: store)
defer { model.reset() }
model.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300)
model.open(item, page: 1, resumePosition: true)
XCTAssertNotNil(model.progress)
// Both calls occur before the load task gets its first execution turn:
// same bytes and same page, but the second action is an explicit link.
model.open(item, page: 1, resumePosition: false)
try await waitFor { model.progress == nil }
XCTAssertNil(model.error)
XCTAssertEqual(model.page, 1)
XCTAssertTrue(model.view.autoScales, "An explicit target must not inherit the pending resume's manual zoom")
XCTAssertNotEqual(model.view.scaleFactor, 9)
let position = try XCTUnwrap(store.reading(for: "archive:" + digest))
XCTAssertNotEqual(position.offset, 0.7, "An explicit target must not restore the old within-page offset")
XCTAssertNotEqual(position.horizontalOffset, 0.6)
}
func testSelectingTextThenCachedImageReplacesThePreview() async throws {
let model = ArchiveReaderModel(remembersPage: false, cache: cache)
defer { model.reset() }
@@ -108,6 +166,49 @@ final class ArchiveReaderTests: XCTestCase {
XCTAssertNil(model.referenceID)
}
func testExplicitTextNavigationOverridesInFlightAndVisibleResume() async throws {
_ = NSApplication.shared
let bytes = Data((0..<250).map { "Line \($0): Archive reading position fixture." }.joined(separator: "\n").utf8)
let item = record("Resume.txt", format: "text", bytes: bytes)
try bytes.write(to: directory.appendingPathComponent(item.id + ".txt"))
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
store.setReading(LibraryReadingPosition(documentID: item.id, offset: 0.65), for: "archive:" + item.id)
let model = ArchiveReaderModel(remembersPage: true, cache: cache, continuity: store)
defer { model.reset() }
model.open(item, page: 1, resumePosition: true)
model.open(item, page: 1, resumePosition: false)
try await waitFor { model.progress == nil }
XCTAssertNil(model.error)
XCTAssertEqual(model.inlinePosition?.offset, 0, "Explicit intent must replace the in-flight resume's saved inline position")
model.updateInlinePosition(offset: 0.65)
let host = NSHostingView(rootView: ArchiveReaderPane(record: item, hit: nil, reader: model,
requestedPage: 1, catalog: ArchiveLibraryCatalog(url: nil), resumesPosition: true))
host.frame = NSRect(x: 0, y: 0, width: 700, height: 500)
func textView(_ root: NSView) -> NSTextView? {
if let text = root as? NSTextView, text.accessibilityIdentifier() == "archive-inline-text" { return text }
return root.subviews.lazy.compactMap { textView($0) }.first
}
host.layoutSubtreeIfNeeded()
try await waitFor {
host.layoutSubtreeIfNeeded()
return textView(host)?.enclosingScrollView?.contentView.bounds.minY ?? 0 > 100
}
let resumedText = try XCTUnwrap(textView(host))
let revision = model.inlineNavigationRevision
model.open(item, page: 1, resumePosition: true)
XCTAssertEqual(model.inlineNavigationRevision, revision)
XCTAssertGreaterThan(resumedText.enclosingScrollView?.contentView.bounds.minY ?? 0, 100)
model.open(item, page: 1, resumePosition: false)
try await waitFor {
host.layoutSubtreeIfNeeded()
guard let current = textView(host), current !== resumedText else { return false }
return (current.enclosingScrollView?.contentView.bounds.minY ?? 1) == 0
}
XCTAssertEqual(model.inlinePosition?.offset, 0)
withExtendedLifetime(host) {}
}
func testTextReaderPreservesLegacyEncodingsAndRemovesFloppyPadding() throws {
let url = directory.appendingPathComponent("Letter.txt")
let accented = "Café\n£5"
@@ -164,6 +164,22 @@ final class BASICReferenceTests: XCTestCase {
XCTAssertFalse(content.allowsExternalReference(URL(fileURLWithPath: "/tmp/private.txt")))
}
func testOverlayContractIsDiscoverableAndReadableThroughTheBundledMCPIndex() async throws {
try requireFullManualEdition()
let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent()
let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app")))
let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil))
let index = MCPHelpIndex(root: root)
let hits = try await index.search("overlayGroups")
let hit = try XCTUnwrap(hits.first { $0.id.hasSuffix("#verified-physical-code-overlays") })
let read = try await index.read(hit.id)
let topic = try XCTUnwrap(read)
for field in ["banked_debug_manifest_versions", "verified_code_overlays", "overlayGroups", "residency_fingerprint"] {
XCTAssertTrue(topic.text.contains(field), field)
}
XCTAssertLessThanOrEqual(topic.text.utf8.count, 12 * 1024, "The complete contract must fit a read_topic response")
}
func testOriginalToolReferencesAreReadableThroughTheNativeMCPIndex() async throws {
try requireFullManualEdition()
let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent()
+284 -29
View File
@@ -2,51 +2,306 @@
import XCTest
final class CMOCSourceMapTests: XCTestCase {
/// Explicit opt-in diagnostic for any retained custom project's immutable
/// build result. No project Makefile is executed and no emulator is loaded.
func testExplicitlySuppliedBankedBuildEvidence() throws {
private enum RetainedEvidenceFailure: Error { case missingCompilationRoot, ambiguousCompilationRoot }
/// Test harness recovery only. Ordinary CMOC markers survive optimized builds
/// even when optional VCCDBG1 type records are absent. Never infer from a Mac
/// username, output directory name or current project location.
private func retainedCompilationDirectory(files: [String: Data], entrySource: String) throws -> URL {
let pattern = try NSRegularExpression(pattern: #"\* (?:Line (.+):([0-9]+)(?::.*)?|FUNCTION .+: defined at (.+):([0-9]+))$"#)
var roots = Set<String>()
func consider(_ path: String) {
guard path.hasPrefix("/"), path.hasSuffix("/" + entrySource) else { return }
roots.insert(URL(fileURLWithPath: String(path.dropLast(entrySource.count))).standardizedFileURL.path)
}
for (name, data) in files where ["s", "lst"].contains((name as NSString).pathExtension.lowercased()) {
guard let text = String(data: data, encoding: .utf8) else { continue }
for row in text.components(separatedBy: .newlines) {
if let marker = row.range(of: "* VCCDBG1 "),
let record = try? JSONSerialization.jsonObject(with: Data(row[marker.upperBound...].utf8)) as? [String: Any],
let location = record["location"] as? String, let colon = location.lastIndex(of: ":") {
consider(String(location[..<colon]))
}
let ns = row as NSString
if let match = pattern.firstMatch(in: row, range: NSRange(location: 0, length: ns.length)) {
let index = match.range(at: 1).location == NSNotFound ? 3 : 1
consider(ns.substring(with: match.range(at: index)))
}
}
}
guard !roots.isEmpty else { throw RetainedEvidenceFailure.missingCompilationRoot }
guard roots.count == 1, let root = roots.first else { throw RetainedEvidenceFailure.ambiguousCompilationRoot }
return URL(fileURLWithPath: root, isDirectory: true)
}
private func explicitlySuppliedBankedArtifact() throws -> CMOCBuildArtifact {
guard let path = ProcessInfo.processInfo.environment["VCC_TEST_BANKED_ARTIFACT"] else {
throw XCTSkip("Supply a retained banked artifact directory for project qualification.")
}
let directory = URL(fileURLWithPath: path).resolvingSymlinksInPath()
if let expected = ProcessInfo.processInfo.environment["VCC_TEST_BANKED_ARTIFACT_ID"] {
XCTAssertEqual(directory.lastPathComponent, expected, "Qualification must read the explicitly selected artifact")
}
let project = try CMOCProject.open(at: directory)
let files = try CMOCProject.files(in: directory)
let sources = files.filter { CMOCProject.isSource($0.key) && String(data: $0.value, encoding: .utf8) != nil && !$0.value.contains(0) }
let settings = project.configuration
let entry = try XCTUnwrap(sources[settings.entrySource])
let binaryPath = try XCTUnwrap(settings.binary)
let binary = try XCTUnwrap(files[binaryPath])
// Compiler source markers retain the original isolated working folder.
// Recover it from a full, retained metadata record rather than assuming
// it is the current output folder or a historical machine path.
var compilationDirectory: URL?
for (name, data) in sources where name.hasSuffix(".s") {
guard let text = String(data: data, encoding: .utf8) else { continue }
for row in text.components(separatedBy: .newlines) {
guard let marker = row.range(of: "* VCCDBG1 "),
let record = try? JSONSerialization.jsonObject(with: Data(row[marker.upperBound...].utf8)) as? [String: Any],
let location = record["location"] as? String, let colon = location.lastIndex(of: ":") else { continue }
let sourcePath = String(location[..<colon])
if sourcePath.hasPrefix("/"), sourcePath.hasSuffix("/" + settings.entrySource) {
compilationDirectory = URL(fileURLWithPath: String(sourcePath.dropLast(settings.entrySource.count)))
break
}
}
if compilationDirectory != nil { break }
}
let artifact = CMOCBuildArtifact(id: UUID(), directory: directory, source: String(decoding: entry, as: UTF8.self),
let binaryPath = try XCTUnwrap(settings.binary), binary = try XCTUnwrap(files[binaryPath])
let manifestPath = try XCTUnwrap(settings.debugManifest), manifest = try XCTUnwrap(files[manifestPath])
print("Retained qualification identity: artifact=\(directory.lastPathComponent), manifest_sha256=\(CMOCSourceMap.sha256(manifest)), binary_sha256=\(CMOCSourceMap.sha256(binary)).")
return CMOCBuildArtifact(id: UUID(), directory: directory, source: String(decoding: entry, as: UTF8.self),
sourceData: entry, sourceSHA256: CMOCProject.sha256(entry), binaryData: binary, buildLog: "",
sources: sources, compilationDirectory: try XCTUnwrap(compilationDirectory), entrySourcePath: settings.entrySource,
binaryRelativePath: binaryPath, diskRelativePath: settings.diskImage, outputPaths: files.keys.sorted(),
debugManifestRelativePath: settings.debugManifest)
sources: sources, compilationDirectory: try retainedCompilationDirectory(files: files, entrySource: settings.entrySource),
entrySourcePath: settings.entrySource, binaryRelativePath: binaryPath, diskRelativePath: settings.diskImage,
outputPaths: files.keys.sorted(), debugManifestRelativePath: settings.debugManifest)
}
/// Explicit opt-in typed Debug qualification remains strict: a verified
/// executable does not substitute for real compiler type/function metadata.
func testExplicitlySuppliedBankedBuildEvidence() throws {
let artifact = try explicitlySuppliedBankedArtifact()
let map = try CMOCProjectSourceMap.parse(artifact: artifact)
XCTAssertNotNil(map.bankedLayout)
XCTAssertFalse(map.instructions.isEmpty)
XCTAssertNotNil(map.bankedLayout); XCTAssertFalse(map.instructions.isEmpty)
let metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map)
XCTAssertFalse(metadata.functions.isEmpty)
print("Verified retained banked artifact: \(map.bankedLayout?.modules.count ?? 0) modules, \(map.instructions.count) instructions, \(metadata.functions.count) functions, \(metadata.variables.count) variables.")
}
/// Release builds may deliberately omit type records. This separate opt-in
/// still requires complete executable/source mapping and reports typed limits.
func testExplicitlySuppliedBankedExecutableEvidence() throws {
let artifact = try explicitlySuppliedBankedArtifact()
let map = try CMOCProjectSourceMap.parse(artifact: artifact)
XCTAssertNotNil(map.bankedLayout); XCTAssertFalse(map.instructions.isEmpty)
XCTAssertFalse(map.executableSymbols.isEmpty)
let metadata: CMOCVariableDebug?, reason: String?
do { metadata = try CMOCVariableDebug.parse(artifact: artifact, verifiedMap: map); reason = nil }
catch { metadata = nil; reason = error.localizedDescription }
let fields = CMOCPublicDebugEvidence.fields(map: map, metadata: metadata, variableError: reason, sharedPaths: Set(artifact.sources.keys))
XCTAssertEqual(fields["source_map"] as? String, "verified")
if metadata == nil {
XCTAssertEqual(fields["status"] as? String, "source_only")
XCTAssertEqual(fields["variables"] as? String, "unavailable")
XCTAssertFalse(try XCTUnwrap(fields["reason"] as? String).isEmpty)
} else { XCTAssertEqual(fields["status"] as? String, "verified") }
print("Verified retained executable: \(map.bankedLayout?.modules.count ?? 0) modules, \(map.instructions.count) instructions, \(map.executableSymbols.count) executable symbols; typed metadata: \(reason ?? "verified").")
}
func testRetainedCompilationRootUsesOrdinaryMarkersWithoutInventingTypeMetadata() throws {
let root = "/private/tmp/authored build/project"
let function = Data("* FUNCTION main(): defined at \(root)/src/main.c:7\n".utf8)
XCTAssertEqual(try retainedCompilationDirectory(files: ["obj/main.s": function], entrySource: "src/main.c").path, root)
let listing = Data("(obj/main.s):00018 * Line \(root)/src/main.c:8: inline assembly\n".utf8)
XCTAssertEqual(try retainedCompilationDirectory(files: ["obj/main.lst": listing], entrySource: "src/main.c").path, root)
let metadata = Data("* VCCDBG1 {\"location\":\"\(root)/src/main.c:9\"}\n".utf8)
XCTAssertEqual(try retainedCompilationDirectory(files: ["obj/main.s": metadata], entrySource: "src/main.c").path, root)
XCTAssertThrowsError(try retainedCompilationDirectory(files: ["obj/other.s": function], entrySource: "other.c"))
let conflicting = function + Data("* Line /private/tmp/different/src/main.c:4\n".utf8)
XCTAssertThrowsError(try retainedCompilationDirectory(files: ["obj/main.s": conflicting], entrySource: "src/main.c"))
}
func testExplicitPhysicalOverlaysRequireExclusiveOwnersAndResidentCodeProof() throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCOverlay-" + UUID().uuidString).resolvingSymlinksInPath()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
let source = Data("void a(void) {}\nvoid b(void) {}\n".utf8)
let packed = binary([(0x0e00, [0x12])], entry: 0x0e00)
let names = ["a1", "a2", "b1", "b2"]
let opcodes: [UInt8] = [0x12, 0x39, 0x13, 0x3a]
let objectBytes = object(zip(names, opcodes).map { Section(name: $0.0, bytes: [$0.1]) })
let listing = Data(names.enumerated().flatMap { index, name in
[row("SECTION \(name)"), row("* Line main.c:\(index < 2 ? 1 : 2)"), row("NOP", offset: 0, bytes: [opcodes[index]]), row("ENDSECTION")]
}.joined(separator: "\n").utf8)
let placements = names.enumerated().map { index, name in "Section: \(name) (main.o) load at \(index % 2 == 0 ? "4000" : "5000"), length 0001" }
let map = Data((placements + ["Section: dataA (runtime.o) load at 6000, length 0001", "Section: dataB (runtime.o) load at 6000, length 0001", "Section: bssA (runtime.o) load at 6100, length 0001", "Section: bssB (runtime.o) load at 6100, length 0001", "Section: resident (runtime.o) load at 7000, length 0001"]).joined(separator: "\n").utf8)
var files = ["game.bin": packed, "game.map": map, "main.o": objectBytes, "main.lst": listing,
"a1.raw": Data([opcodes[0]]), "a2.raw": Data([opcodes[1]]), "b1.raw": Data([opcodes[2]]), "b2.raw": Data([opcodes[3]]),
"dataA.raw": Data([0x42]), "dataB.raw": Data([0x99]), "resident.raw": Data([0x39])]
var modules: [[String: Any]] = names.enumerated().map { index, name in
["id": name, "sections": [name], "codeSections": [name],
"image": ["path": name + ".raw", "logicalAddress": index % 2 == 0 ? 0x4000 : 0x5000],
"pages": [["logicalPage": 2, "physicalPage": 30]],
"overlay": ["group": "stages", "owner": index < 2 ? "A" : "B"]]
}
for owner in ["A", "B"] {
modules.append(["id": "data" + owner, "sections": ["data" + owner], "codeSections": [],
"image": ["path": "data" + owner + ".raw", "logicalAddress": 0x6000],
"pages": [["logicalPage": 3, "physicalPage": 31]], "overlay": ["group": "stages", "owner": owner]])
modules.append(["id": "bss" + owner, "sections": ["bss" + owner], "codeSections": [],
"pages": [["logicalPage": 3, "physicalPage": 31]], "overlay": ["group": "stages", "owner": owner]])
}
modules.append(["id": "resident", "sections": ["resident"], "codeSections": ["resident"],
"image": ["path": "resident.raw", "logicalAddress": 0x7000], "pages": [["logicalPage": 3, "physicalPage": 31]]])
func manifest(_ edit: (inout [String: Any]) -> Void = { _ in }) throws -> Data {
var value: [String: Any] = ["version": 2, "entryPoint": 0x0e00,
"binary": ["path": "game.bin", "sha256": CMOCSourceMap.sha256(packed)],
"linkMap": ["path": "game.map", "sha256": CMOCSourceMap.sha256(map)],
"sources": ["main.c": CMOCSourceMap.sha256(source)],
"artifacts": files.filter { $0.key != "game.bin" && $0.key != "game.map" }.mapValues(CMOCSourceMap.sha256),
"overlayGroups": [["id": "stages", "owners": ["A", "B"]]], "modules": modules]
edit(&value); return try JSONSerialization.data(withJSONObject: value)
}
func layout(_ edit: (inout [String: Any]) -> Void = { _ in }) throws -> CMOCBankedDebugLayout {
for (name, bytes) in files { try bytes.write(to: directory.appendingPathComponent(name)) }
return try CMOCBankedDebugLayout.parse(data: manifest(edit), directory: directory, sources: ["main.c": source], binary: packed,
binaryPath: "game.bin", allowedOutputs: Array(files.keys))
}
let verified = try layout()
XCTAssertTrue(verified.permitsPhysicalOverlap(between: "a1", and: "b1"))
XCTAssertFalse(verified.permitsPhysicalOverlap(between: "a1", and: "a2"))
let mapping = try CMOCProjectSourceMap.parse(sources: ["main.c": source], compilationDirectory: directory,
units: [.init(sourcePath: "main.c", sourceName: "main.c", objectName: "main.o", listing: listing, object: objectBytes)],
linkMap: map, binary: packed, bankedLayout: verified)
XCTAssertEqual(mapping.instructions.count, 4, "Distinct exclusive owners may occupy the same physical instruction identity")
XCTAssertEqual(mapping.projected(physicalPages: [2: 30, 3: 31]).activeModuleIDs, ["resident"], "Pages alone never identify an overlay owner")
var memory = Data(repeating: 0, count: 65536), available = Data(repeating: 1, count: 65536)
memory[0x4000] = opcodes[0]; memory[0x5000] = opcodes[1]; memory[0x7000] = 0x39
func selected() -> CMOCProjectSourceMap { mapping.projected(physicalPages: [2: 30, 3: 31], memory: memory, available: available) }
XCTAssertEqual(selected().activeModuleIDs, ["a1", "a2", "dataA", "bssA", "resident"])
XCTAssertEqual(selected().instructions.map(\.moduleID), ["a1", "a2"])
let typed = CMOCVariableDebug(functions: [
.init(name: "stage", sourcePath: "main.c", entry: 0x4000, body: 0x4000, end: 0x4001, frame: false, moduleID: "a1"),
.init(name: "stage", sourcePath: "main.c", entry: 0x4000, body: 0x4000, end: 0x4001, frame: false, moduleID: "b1")], variables: [
.init(name: "stateA", sourcePath: "main.c", line: 1, type: .integer, address: 0x6100, offset: nil, scope: nil, isStatic: false, moduleID: "bssA"),
.init(name: "stateB", sourcePath: "main.c", line: 2, type: .integer, address: 0x6100, offset: nil, scope: nil, isStatic: false, moduleID: "bssB"),
.init(name: "wrongScope", sourcePath: "main.c", line: 1, type: .integer, address: 0x6000, offset: nil, scope: 0x4000..<0x4001, isStatic: true, moduleID: "dataA", scopeModuleID: "b1")], sourceMap: mapping)
func typedSelection() -> CMOCVariableDebug { typed.projected(physicalPages: [2: 30, 3: 31], memory: memory, available: available) }
XCTAssertTrue(typed.projected(physicalPages: [2: 30, 3: 31]).variables.isEmpty)
XCTAssertEqual(typedSelection().variables.map(\.name), ["stateA"], "BSS inherits only its uniquely proven owner; lexical owner must also match")
XCTAssertEqual(typedSelection().entryFunction(named: "stage")?.moduleID, "a1")
memory[0x5000] = opcodes[3]
XCTAssertEqual(selected().activeModuleIDs, ["resident"], "A half-loaded owner must not establish residency")
XCTAssertTrue(typedSelection().functions.isEmpty); XCTAssertTrue(typedSelection().variables.isEmpty)
memory[0x4000] = opcodes[2]
XCTAssertEqual(selected().activeModuleIDs, ["b1", "b2", "dataB", "bssB", "resident"])
XCTAssertEqual(typedSelection().variables.map(\.name), ["stateB"])
XCTAssertEqual(typedSelection().entryFunction(named: "stage")?.moduleID, "b1")
available[0x5000] = 0
XCTAssertEqual(selected().activeModuleIDs, ["resident"], "Unavailable executable bytes never establish residency")
XCTAssertThrowsError(try layout { $0["version"] = 1 })
XCTAssertThrowsError(try layout { $0.removeValue(forKey: "overlayGroups") })
XCTAssertThrowsError(try layout { value in
var changed = modules; changed[2]["overlay"] = ["group": "stages", "owner": "A"]; value["modules"] = changed
}, "Same-owner physical overlap remains invalid")
XCTAssertThrowsError(try layout { value in
var changed = modules; changed[2].removeValue(forKey: "overlay"); value["modules"] = changed
}, "Ordinary resident code cannot share overlay storage")
XCTAssertThrowsError(try layout { value in
value["overlayGroups"] = [["id": "stages", "owners": ["A", "B", "unused"]]]
})
XCTAssertThrowsError(try layout { value in
var changed = modules; changed[5]["overlay"] = ["group": "stages", "owner": "C"]
value["modules"] = changed; value["overlayGroups"] = [["id": "stages", "owners": ["A", "B", "C"]]]
}, "A data/BSS-only owner has no immutable executable residency proof")
XCTAssertThrowsError(try layout { value in
value["overlayGroups"] = [["id": "stages", "owners": ["A", "A"]]]
})
XCTAssertThrowsError(try layout { value in
var changed = modules; changed[2]["overlay"] = ["group": "other", "owner": "C"]
value["modules"] = changed
value["overlayGroups"] = [["id": "stages", "owners": ["A", "B"]], ["id": "other", "owners": ["C", "D"]]]
}, "Different overlay groups may coexist and cannot share physical storage") {
XCTAssertTrue($0.localizedDescription.contains("module images overlap physical RAM"))
}
XCTAssertThrowsError(try layout { value in
var changed = modules; changed[0]["overlay"] = ["group": "stages", "owner": "unknown"]; value["modules"] = changed
})
XCTAssertThrowsError(try layout { value in
value["overlayGroups"] = [["id": "stages", "owners": ["A", "B"]], ["id": "stages", "owners": ["C", "D"]]]
})
XCTAssertThrowsError(try layout { value in
value["overlayGroups"] = [["id": String(repeating: "x", count: 129), "owners": ["A", "B"]]]
})
XCTAssertThrowsError(try layout { value in
value["overlayGroups"] = (0..<65).map { ["id": "g\($0)", "owners": ["A", "B"]] }
})
XCTAssertThrowsError(try layout { value in
value["overlayGroups"] = [["id": "stages", "owners": (0..<257).map { "o\($0)" }]]
})
XCTAssertThrowsError(try layout { value in
// Even null metadata cannot silently downgrade to version 1.
value["version"] = 1; value["overlayGroups"] = NSNull()
})
let catalog = CMOCPublicDebugEvidence.fields(map: mapping, metadata: nil, variableError: nil, sharedPaths: ["main.c"])
XCTAssertEqual(catalog["supported_manifest_versions"] as? [Int], [1, 2])
XCTAssertEqual(catalog["module_catalog_scope"] as? String, "verified_static_declarations_not_residency")
XCTAssertEqual((catalog["overlay_groups"] as? [[String: Any]])?.first?["owners"] as? [String], ["A", "B"])
XCTAssertNil(catalog["active_overlay_owners"], "Build declarations never assert runtime residency")
files["b1.raw"] = files["a1.raw"]; files["b2.raw"] = files["a2.raw"]
let ambiguousLayout = try layout()
let ambiguous = CMOCProjectSourceMap(entryPoint: mapping.entryPoint, binarySHA256: mapping.binarySHA256, sourceHashes: mapping.sourceHashes,
instructions: mapping.instructions, objectHashes: mapping.objectHashes, listingHashes: mapping.listingHashes,
linkMapSHA256: mapping.linkMapSHA256, bankedLayout: ambiguousLayout)
memory[0x4000] = opcodes[0]; memory[0x5000] = opcodes[1]; available[0x5000] = 1
XCTAssertEqual(ambiguous.projected(physicalPages: [2: 30, 3: 31], memory: memory, available: available).activeModuleIDs, ["resident"],
"Identical code signatures must not guess an owner or expose its BSS")
}
func testGeneratedAssemblyEvidenceUsesTypedBudgetsAndExactIdentity() throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCEvidence-" + UUID().uuidString).resolvingSymlinksInPath()
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
let source = Data("void main(void) {}\n".utf8)
let packed = binary([(0x0e00, [0x12])], entry: 0x0e00)
let map = Data("Section: code (main.o) load at 4000, length 0001\n".utf8)
let raw = Data([0x39])
for (name, data) in ["game.bin": packed, "game.map": map, "code.raw": raw] {
try data.write(to: directory.appendingPathComponent(name))
}
var artifacts = ["code.raw": CMOCSourceMap.sha256(raw)]
func parse(outputs: [String]? = nil) throws -> CMOCBankedDebugLayout {
let value: [String: Any] = ["version": 1, "entryPoint": 0x0e00,
"binary": ["path": "game.bin", "sha256": CMOCSourceMap.sha256(packed)],
"linkMap": ["path": "game.map", "sha256": CMOCSourceMap.sha256(map)],
"sources": ["main.c": CMOCSourceMap.sha256(source)], "artifacts": artifacts,
"modules": [["id": "code", "sections": ["code"], "codeSections": ["code"],
"image": ["path": "code.raw", "logicalAddress": 0x4000],
"pages": [["logicalPage": 2, "physicalPage": 30]]]]]
return try CMOCBankedDebugLayout.parse(data: JSONSerialization.data(withJSONObject: value),
directory: directory, sources: ["main.c": source], binary: packed, binaryPath: "game.bin",
allowedOutputs: outputs ?? (["game.bin", "game.map"] + Array(artifacts.keys)))
}
// A compiler can emit large type records/data while retaining small code.
let assembly = Data(repeating: 0x3b, count: 9 * 1024 * 1024 + 17)
let path = "generated.s", file = directory.appendingPathComponent(path)
try assembly.write(to: file); artifacts[path] = CMOCSourceMap.sha256(assembly)
let verified = try parse()
XCTAssertEqual(verified.artifactHashes[path], CMOCSourceMap.sha256(assembly))
XCTAssertEqual(verified.modules.first?.physicalAddress(0x4000), 30 * 8192)
XCTAssertNoThrow(try CMOCSourceMap.validateEvidenceSize(assembly.count, path: path))
XCTAssertThrowsError(try parse(outputs: ["game.bin", "game.map", "code.raw"]))
try Data(repeating: 0x21, count: assembly.count).write(to: file)
XCTAssertThrowsError(try parse()) { XCTAssertTrue($0.localizedDescription.contains("generated.s SHA-256")) }
try FileManager.default.removeItem(at: file)
try FileManager.default.createSymbolicLink(at: file, withDestinationURL: directory.appendingPathComponent("code.raw"))
XCTAssertThrowsError(try parse()) { XCTAssertTrue($0.localizedDescription.contains("generated.s must not traverse symbolic links")) }
try FileManager.default.removeItem(at: file)
artifacts.removeValue(forKey: path)
for (name, size, limit) in [("oversized.s", 32 * 1024 * 1024 + 1, 32 * 1024 * 1024),
("oversized.lst", 8 * 1024 * 1024 + 1, 8 * 1024 * 1024)] {
let bytes = Data(repeating: 0x3b, count: size)
try bytes.write(to: directory.appendingPathComponent(name)); artifacts[name] = CMOCSourceMap.sha256(bytes)
XCTAssertThrowsError(try parse()) {
let message = $0.localizedDescription
XCTAssertTrue(message.contains(name)); XCTAssertTrue(message.contains("\(size) bytes"))
XCTAssertTrue(message.contains("\(limit) bytes"))
}
XCTAssertThrowsError(try CMOCSourceMap.validateEvidenceSize(size, path: name))
artifacts.removeValue(forKey: name)
try FileManager.default.removeItem(at: directory.appendingPathComponent(name))
}
let chunk = Data(repeating: 0x3b, count: 27 * 1024 * 1024)
let hash = CMOCSourceMap.sha256(chunk)
for index in 0..<5 {
let name = "part\(index).s"
try chunk.write(to: directory.appendingPathComponent(name)); artifacts[name] = hash
}
XCTAssertThrowsError(try parse()) {
XCTAssertTrue($0.localizedDescription.contains("aggregate limit is 134217728 bytes"))
}
}
// Small LWOBJ16 records are constructed here to exercise relocation failures
// independently of a compiler installation or personal ROM files.
private struct Section {
@@ -354,6 +354,60 @@ final class CartridgePersistenceTests: XCTestCase {
XCTAssertFalse(model.disks[0].dirty); XCTAssertTrue(model.diskConnected)
}
}
@MainActor func testMediaCommandsRecheckActiveTransferWithoutChangingDisksOnBothCPUs() async throws {
// The native controls remain available during guest I/O. Their safety
// must come from the worker's current state, not a stale UI snapshot.
for use6309 in [false, true] {
let controller = VCCMachineController()
func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
await withCheckedContinuation { c in action { c.resume(returning: $0) } }
}
let original = Data(repeating: 0, count: 161280)
_ = await step { controller.loadDiskROM(Data(repeating: 0, count: 8192), name: "Original ROM", completion: $0) }
_ = await step { controller.mountDisk(original, drive: 0, name: "Original.dsk", readOnly: false, completion: $0) }
var system = Data(repeating: 0, count: 32768)
// Begin a write, then leave its sector data transfer incomplete.
let code: [UInt8] = [0x86,0x29,0xb7,0xff,0x40,0x86,1,0xb7,0xff,0x4a,0x86,0xa0,0xb7,0xff,0x48,0x20,0xfe]
system.replaceSubrange(0..<code.count, with: code); system[32766] = 0x80
_ = await step { controller.loadROM(system, use6309: use6309, completion: $0) }
_ = await step(controller.resume)
var snapshot = await step(controller.snapshot)
for _ in 0..<100 where !snapshot.diskBusy {
try await Task.sleep(nanoseconds: 1_000_000)
snapshot = await step(controller.snapshot)
}
XCTAssertTrue(snapshot.diskBusy, "CPU \(use6309 ? "6309" : "6809") must reach a real transfer")
_ = await step(controller.pause)
let operations: [(@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void] = [
controller.pauseForDiskChange,
{ controller.mountDisk(Data(repeating: 0xe5, count: 161280), drive: 0, name: "Replacement.dsk", readOnly: false, completion: $0) },
{ controller.createDisk(inDrive: 0, format: .standard, completion: $0) },
{ controller.ejectDisk(inDrive: 0, discard: false, completion: $0) },
{ controller.setDiskWriteProtected(true, drive: 0, completion: $0) },
{ controller.loadDiskROM(Data(repeating: 0x12, count: 8192), name: "Replacement ROM", completion: $0) },
controller.disableDisks,
]
for operation in operations {
snapshot = await step(operation)
XCTAssertNotNil(snapshot.errorMessage)
XCTAssertTrue(snapshot.diskBusy)
XCTAssertTrue(snapshot.disks[0].mounted)
XCTAssertEqual(snapshot.disks[0].name, "Original.dsk")
XCTAssertFalse(snapshot.disks[0].writeProtected)
XCTAssertEqual(snapshot.diskROMName, "Original ROM")
}
_ = await step(controller.reset)
let (bytes, _, exported): (Data?, UInt64, VCCMachineSnapshot) = await withCheckedContinuation { done in
controller.exportDisk(inDrive: 0) { done.resume(returning: ($0, $1, $2)) }
}
XCTAssertNil(exported.errorMessage)
XCTAssertEqual(bytes, original, "Rejected actions must retain the original bytes")
snapshot = await step { controller.ejectDisk(inDrive: 0, discard: false, completion: $0) }
XCTAssertNil(snapshot.errorMessage)
XCTAssertFalse(snapshot.disks[0].mounted, "Ejection works once the controller is idle")
_ = await step(controller.shutdown)
}
}
@MainActor func testBridgeRejectsInvalidAndBusyLayoutsWithoutReplacingSlots() async throws {
let controller = VCCMachineController()
func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
@@ -0,0 +1,779 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import AVFoundation
import AppKit
final class CoCoCaptureTests: XCTestCase {
private final class HeldPullController: VCCMachineController, @unchecked Sendable {
private let lock = NSLock()
private var reply: (() -> Void)?
private var holdNextPull = true
private var finals = 0
var heldReply: (() -> Void)? { lock.withLock { reply } }
var finalPulls: Int { lock.withLock { finals } }
override func takeVideoCapture(finish: Bool, replyQueue: DispatchQueue, completion: @escaping ([VCCVideoPacket], String?) -> Void) {
if finish { lock.withLock { finals += 1 } }
super.takeVideoCapture(finish: finish, replyQueue: replyQueue) { [self] packets, error in
let held = lock.withLock {
if !finish && holdNextPull {
holdNextPull = false; reply = { completion(packets, error) }; return true
}
return false
}
if !held { completion(packets, error) }
}
}
func releasePull() { let value = lock.withLock { let value = reply; reply = nil; return value }; value?() }
}
private final class InvalidCapturePacket: VCCVideoPacket {
private let original: VCCVideoPacket
init(_ original: VCCVideoPacket) { self.original = original; super.init() }
override var pixels: Data { Data() }
override var samples: Data { original.samples }
override var activeArea: CGRect { original.activeArea }
override var sampleOffset: UInt64 { original.sampleOffset }
}
private final class FailingPullController: VCCMachineController, @unchecked Sendable {
private let lock = NSLock()
private var failPull = false
private var invalidPull = false
private var finals = 0
var finalPulls: Int { lock.withLock { finals } }
var failNextPull: Bool { get { lock.withLock { failPull } } set { lock.withLock { failPull = newValue } } }
var invalidateNextPull: Bool { get { lock.withLock { invalidPull } } set { lock.withLock { invalidPull = newValue } } }
override func takeVideoCapture(finish: Bool, replyQueue: DispatchQueue, completion: @escaping ([VCCVideoPacket], String?) -> Void) {
if finish { lock.withLock { finals += 1 } }
super.takeVideoCapture(finish: finish, replyQueue: replyQueue) { [self] packets, error in
let fail = lock.withLock { let fail = !finish && failPull; if fail { failPull = false }; return fail }
if fail {
completion(packets, "Authored capture-consumer interruption")
} else {
let invalid = lock.withLock { let invalid = !finish && invalidPull && !packets.isEmpty; if invalid { invalidPull = false }; return invalid }
if invalid { completion([InvalidCapturePacket(packets[0])] + Array(packets.dropFirst()), error) }
else { completion(packets, error) }
}
}
}
}
/// Deliberately occupies the UI executor longer than the bridge's eight
/// packets can buffer. This is test-only starvation, never a product wait.
private func holdMainActor() { Thread.sleep(forTimeInterval: 0.8) }
private final class BookmarkGate: @unchecked Sendable {
private let lock = NSLock()
private let release = DispatchSemaphore(value: 0)
private var began = false
let blocked: URL
let fails: Bool
init(blocked: URL, fails: Bool = false) { self.blocked = blocked; self.fails = fails }
var started: Bool { lock.withLock { began } }
func unblock() { release.signal() }
func prepare(_ url: URL) throws -> Data {
XCTAssertFalse(Thread.isMainThread, "Bookmark creation must not occupy the UI thread")
if url == blocked {
lock.withLock { began = true }
guard release.wait(timeout: .now() + 5) == .success else { throw CoCoRecordingError.message("The authored bookmark gate timed out") }
if fails { throw CocoaError(.fileReadNoSuchFile) }
}
return try url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
}
}
/// Each lifecycle case owns its controller, defaults and media directory.
/// Feedback is injected by the caller; these tests never play host cues.
@MainActor private func guest(controller: VCCMachineController = VCCMachineController(), use6309: Bool = false) async throws -> (URL, UserDefaults, MachineModel) {
let root = try folder(), suite = "CoCoCaptureLifecycle-" + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
addTeardownBlock { defaults.removePersistentDomain(forName: suite) }
// Never ask the native test runner to bookmark the person's Desktop.
// Seed the owned location before preferences initialize, on both hosts.
defaults.set(try root.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil), forKey: "capture.folder.shared")
let model = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller,
displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json")), restoreMediaOnLaunch: false)
addTeardownBlock { await withCheckedContinuation { c in controller.shutdown { _ in c.resume() } } }
await withCheckedContinuation { c in controller.loadDiagnostic(use6309: use6309) { _ in c.resume() } }
await withCheckedContinuation { c in controller.resume { _ in c.resume() } }
for _ in 0..<200 where model.pixels == nil { model.poll(); try await Task.sleep(for: .milliseconds(10)) }
_ = try XCTUnwrap(model.pixels, "The owned authored diagnostic must publish a frame")
return (root, defaults, model)
}
private func folder() throws -> URL {
let url = FileManager.default.temporaryDirectory.appendingPathComponent("CoCoCapture-" + UUID().uuidString)
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
addTeardownBlock { try? FileManager.default.removeItem(at: url) }
return url
}
private func picture() -> Data {
var data = Data(count: 640 * 480 * 4)
data.withUnsafeMutableBytes { raw in
let p = raw.bindMemory(to: UInt8.self)
for y in 0..<480 { for x in 0..<640 {
let n = (y * 640 + x) * 4
// Green outside the crop, red above blue inside: catches both
// unwanted border content and an upside-down encoded picture.
if x < 64 || x >= 576 || y < 48 || y >= 432 { p[n+1] = 255 }
else if y < 240 { p[n+2] = 255 } else { p[n] = 255 }
} }
}
return data
}
func testQuickSaveCollisionIsAtomicAndRetainsOriginal() throws {
let dir = try folder()
let first = dir.appendingPathComponent("Example.png")
try Data([1,2,3]).write(to: first)
let temporary = dir.appendingPathComponent("temporary")
try Data([4,5,6]).write(to: temporary)
let second = try CoCoCaptureFiles.promote(temporary, folder: dir, name: "Example", extension: "png")
XCTAssertEqual(second.lastPathComponent, "Example-1.png")
XCTAssertEqual(try Data(contentsOf: first), Data([1,2,3]))
XCTAssertEqual(try Data(contentsOf: second), Data([4,5,6]))
let capture = try ScreenCapture(pixels: picture(), area: CGRect(x: 64, y: 48, width: 512, height: 384))
let png = try CoCoCaptureFiles.save(capture, folder: dir)
let image = try XCTUnwrap(NSImage(contentsOf: png))
XCTAssertEqual(image.size, NSSize(width: 512, height: 384))
}
func testNativeMovieCompletesMP4WithGuestOnlyCropAndStereo() async throws {
let dir = try folder(), movie = dir.appendingPathComponent("Working.mov"), final = dir.appendingPathComponent("Final.mp4")
let encoder = try CoCoVideoEncoder(workingURL: movie)
let bytes = picture()
for n in 0..<60 {
var samples = Data(count: 735 * 8)
samples.withUnsafeMutableBytes { raw in
let values = raw.bindMemory(to: Float.self)
for i in 0..<735 { values[2*i] = Float(sin(Double(n*735+i)*2 * .pi * 440 / 44100)) * 0.2; values[2*i+1] = -values[2*i] }
}
encoder.append([CoCoVideoFrame(pixels: bytes, area: CGRect(x: 64, y: 48, width: 512, height: 384), audio: samples, sampleOffset: Int64(n*735))])
try await Task.sleep(for: .milliseconds(17))
}
let working: URL = try await withCheckedThrowingContinuation { c in encoder.finish { c.resume(with: $0) } }
try await CoCoVideoEncoder.exportMP4(from: working, to: final)
let asset = AVURLAsset(url: final)
let duration = try await asset.load(.duration).seconds
XCTAssertEqual(duration, 1, accuracy: 0.03)
let video = try await asset.loadTracks(withMediaType: .video), audio = try await asset.loadTracks(withMediaType: .audio)
XCTAssertEqual(video.count, 1); XCTAssertEqual(audio.count, 1)
let dimensions = try await video[0].load(.naturalSize)
XCTAssertEqual(dimensions, CGSize(width: 1280, height: 960))
let generator = AVAssetImageGenerator(asset: asset)
let frame = try await generator.image(at: .zero).image
var rgba = Data(count: 1280 * 960 * 4)
rgba.withUnsafeMutableBytes { p in
let context = CGContext(data: p.baseAddress, width: 1280, height: 960, bitsPerComponent: 8,
bytesPerRow: 1280 * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
context.draw(frame, in: CGRect(x: 0, y: 0, width: 1280, height: 960))
}
let top = (240 * 1280 + 640) * 4, bottom = (720 * 1280 + 640) * 4
XCTAssertGreaterThan(rgba[top], 200); XCTAssertLessThan(rgba[top+1], 40); XCTAssertLessThan(rgba[top+2], 40)
XCTAssertGreaterThan(rgba[bottom+2], 200); XCTAssertLessThan(rgba[bottom+1], 40); XCTAssertLessThan(rgba[bottom], 40)
// Passthrough refuses overwrite, leaving an already delivered movie intact.
let hash = try Data(contentsOf: final)
do { try await CoCoVideoEncoder.exportMP4(from: working, to: final); XCTFail("Must not overwrite") } catch { }
XCTAssertEqual(try Data(contentsOf: final), hash)
}
@MainActor func testBridgeCaptureBothProcessorsDoesNotAdvancePausedGuest() async throws {
for hd in [false, true] {
let controller = VCCMachineController()
func command(_ op: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
await withCheckedContinuation { c in op { c.resume(returning: $0) } }
}
func packets(_ finish: Bool) async -> ([VCCVideoPacket], String?) {
await withCheckedContinuation { c in controller.takeVideoCapture(finish: finish) { c.resume(returning: ($0,$1)) } }
}
_ = await command { controller.loadDiagnostic(use6309: hd, completion: $0) }
_ = await command(controller.resume)
var available = await command(controller.snapshot)
for _ in 0..<50 where available.presentedFrame == 0 {
try await Task.sleep(for: .milliseconds(10))
available = await command(controller.snapshot)
}
XCTAssertGreaterThan(available.presentedFrame, 0)
let before = await command(controller.pause)
let started = await command(controller.beginVideoCapture)
XCTAssertNil(started.errorMessage)
try await Task.sleep(for: .milliseconds(65))
let capture = await packets(true)
XCTAssertNil(capture.1); XCTAssertFalse(capture.0.isEmpty)
for p in capture.0 {
XCTAssertEqual(p.pixels.count, 640 * 480 * 4)
XCTAssertTrue(p.samples.allSatisfy { $0 == 0 })
XCTAssertGreaterThan(p.activeArea.width, 0)
}
let after = await command(controller.snapshot)
XCTAssertEqual(after.generation, before.generation)
XCTAssertEqual(after.cycles, before.cycles)
XCTAssertEqual(after.presentedFrame, before.presentedFrame)
XCTAssertEqual(after.audioStarts, before.audioStarts)
XCTAssertEqual(after.use6309, hd)
_ = await command(controller.shutdown)
}
}
@MainActor func testStopWaitsForAnInFlightDrainedPacketBeforeFinalizing() async throws {
let root = try folder(), controller = HeldPullController()
let suite = "CoCoCaptureStop-" + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
defaults.set(try root.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil), forKey: "capture.folder.recordings")
let model = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller,
displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json")), restoreMediaOnLaunch: false)
func command(_ op: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async {
_ = await withCheckedContinuation { c in op { c.resume(returning: $0) } }
}
await command { controller.loadDiagnostic(use6309: false, completion: $0) }
await command(controller.resume)
// This fixture owns its guest setup. An asynchronous remembered-media
// restore must not race that load or supply the frame incidentally.
for _ in 0..<100 where model.pixels == nil {
model.poll(); try await Task.sleep(for: .milliseconds(10))
}
guard model.pixels != nil else {
await withCheckedContinuation { c in model.shutdown { c.resume() } }
XCTFail("The authored diagnostic guest did not produce its first frame")
return
}
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
capture.startRecording()
capture.startRecording() // Repeated Start while starting cannot add another cue.
for _ in 0..<100 where controller.heldReply == nil { try await Task.sleep(for: .milliseconds(5)) }
XCTAssertNotNil(controller.heldReply)
XCTAssertEqual(cues, [.recordingStarted])
let stopping = Task { await capture.stopRecording() }
try await Task.sleep(for: .milliseconds(30))
XCTAssertEqual(capture.state, .finishing)
XCTAssertEqual(controller.finalPulls, 0, "Stop must not overtake the pull that already owns drained samples")
await capture.stopRecording()
XCTAssertEqual(capture.state, .finishing, "Duplicate Stop must leave the first finalization in control")
XCTAssertEqual(controller.finalPulls, 0)
controller.releasePull()
await stopping.value
XCTAssertEqual(controller.finalPulls, 1)
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error)
let saved = capture.saved
XCTAssertTrue(capture.recoveries.isEmpty)
XCTAssertEqual(cues, [.recordingStarted], "Stop/finalization must not replay the start cue")
await withCheckedContinuation { c in model.shutdown { c.resume() } }
let movie = try XCTUnwrap(saved)
XCTAssertTrue(FileManager.default.fileExists(atPath: movie.path))
}
@MainActor func testFailedQuickSaveRetainsImageAndRejectsReplacementUntilExplicitDiscard() async throws {
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
let blocked = root.appendingPathComponent("Not a folder")
let original = Data("existing user file".utf8)
try original.write(to: blocked)
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
// A regular file is a deterministic inaccessible-directory fixture,
// independent of the account's administrator/write permissions.
try await capture.preferences.setFolder(blocked)
capture.captureNow()
for _ in 0..<200 where capture.saving { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertFalse(capture.saving); XCTAssertNotNil(capture.error)
XCTAssertTrue(capture.hasPendingImage); XCTAssertNil(capture.saved)
XCTAssertEqual(cues, [.screenshot])
try await capture.preferences.setFolder(root)
capture.captureNow(); capture.delay(5)
XCTAssertTrue(capture.hasPendingImage); XCTAssertNil(capture.countdown)
XCTAssertEqual(cues, [.screenshot], "A failed image cannot be silently replaced or cue again")
XCTAssertEqual(try Data(contentsOf: blocked), original)
capture.discardImage()
XCTAssertFalse(capture.hasPendingImage); XCTAssertNil(capture.error)
capture.captureNow()
for _ in 0..<200 where capture.saving { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertNotNil(capture.saved); XCTAssertFalse(capture.hasPendingImage)
XCTAssertEqual(cues, [.screenshot, .screenshot])
XCTAssertEqual(try Data(contentsOf: blocked), original)
}
@MainActor func testFastForwardStartRefusesWithoutChangingMachineOrCreatingRecovery() async throws {
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
await withCheckedContinuation { c in
controller.configureMachine(use6309: false, ram: model.settings.ram, overclock: 1, frameInterval: 1, fastForward: true) { _ in c.resume() }
}
for _ in 0..<200 where !model.settings.fastForward { model.poll(); try await Task.sleep(for: .milliseconds(5)) }
XCTAssertTrue(model.settings.fastForward)
let before = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
try await capture.preferences.setFolder(root)
capture.startRecording(); capture.startRecording()
XCTAssertEqual(capture.state, .idle)
XCTAssertTrue(capture.error?.contains("fast-forward") == true)
XCTAssertTrue(capture.recoveries.isEmpty); XCTAssertTrue(cues.isEmpty)
let after = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
XCTAssertTrue(after.fastForward); XCTAssertEqual(after.generation, before.generation)
XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("CaptureRecovery.json").path))
}
@MainActor func testTenSecondCaptureExpiresWhilePausedWithoutAdvancingGuest() async throws {
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
let before = await withCheckedContinuation { c in controller.pause { c.resume(returning: $0) } }
model.poll()
try await Task.sleep(for: .milliseconds(20))
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
try await capture.preferences.setFolder(root)
capture.preferences.setTimerSeconds(10)
capture.capture()
XCTAssertEqual(capture.countdown, 10); XCTAssertTrue(cues.isEmpty)
for _ in 0..<1_200 where capture.countdown != nil || capture.saving { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertNil(capture.countdown); XCTAssertFalse(capture.saving)
XCTAssertEqual(cues, [.screenshot]); XCTAssertNil(capture.error)
let image = try XCTUnwrap(NSImage(contentsOf: try XCTUnwrap(capture.saved)))
XCTAssertEqual(image.size, NSSize(width: model.activeVideoRect.width, height: model.activeVideoRect.height))
let after = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
XCTAssertEqual(after.generation, before.generation)
XCTAssertEqual(after.cycles, before.cycles)
XCTAssertEqual(after.presentedFrame, before.presentedFrame)
XCTAssertEqual(after.audioStarts, before.audioStarts)
}
@MainActor func testResetsCancelScreenshotTimersButContinueTheSameRecording() async throws {
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
model.captures = capture
try await capture.preferences.setFolder(root)
capture.startRecording()
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertEqual(capture.state, .recording)
let record = try XCTUnwrap(capture.recoveries.first)
for cold in [false, true] {
capture.delay(10)
XCTAssertEqual(capture.countdown, 10)
if cold { model.reset() } else { model.softReset() }
XCTAssertNil(capture.countdown)
for _ in 0..<200 where model.busy { try await Task.sleep(for: .milliseconds(5)) }
XCTAssertFalse(model.busy)
XCTAssertEqual(capture.state, .recording)
XCTAssertEqual(capture.recoveries.map(\.id), [record.id])
try await Task.sleep(for: .milliseconds(80))
}
XCTAssertEqual(cues, [.recordingStarted], "A reset neither restarts recording nor takes a delayed screenshot")
await capture.stopRecording()
XCTAssertNil(capture.error); XCTAssertEqual(capture.state, .idle)
let asset = AVURLAsset(url: try XCTUnwrap(capture.saved))
let duration = try await asset.load(.duration).seconds
XCTAssertGreaterThan(duration, 0.12)
XCTAssertTrue(capture.recoveries.isEmpty)
}
@MainActor func testCaptureInterruptionRetainsOwnedMovieAndRecoveryAcrossRelaunch() async throws {
let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller)
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
try await capture.preferences.setFolder(root)
capture.startRecording()
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertEqual(capture.state, .recording)
let record = try XCTUnwrap(capture.recoveries.first)
let unrelated = record.directory.appendingPathComponent("User note.txt"), original = Data("preserve".utf8)
try original.write(to: unrelated)
try await Task.sleep(for: .milliseconds(250))
controller.failNextPull = true
for _ in 0..<300 where capture.state != .idle { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.saved)
XCTAssertEqual(capture.error, "Authored capture-consumer interruption")
XCTAssertEqual(capture.recoveries.map(\.id), [record.id])
XCTAssertTrue(FileManager.default.fileExists(atPath: record.working.path))
XCTAssertGreaterThan(try Data(contentsOf: record.working).count, 0)
XCTAssertEqual(cues, [.recordingStarted])
let reopened = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
XCTAssertEqual(reopened.recoveries.map(\.id), [record.id])
let recoveredFolder = root.appendingPathComponent("Recovered", isDirectory: true)
try FileManager.default.createDirectory(at: recoveredFolder, withIntermediateDirectories: true)
try await reopened.preferences.setFolder(recoveredFolder)
reopened.recover(record)
for _ in 0..<400 where reopened.state != .idle { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertNil(reopened.error); XCTAssertTrue(reopened.recoveries.isEmpty)
let final = try XCTUnwrap(reopened.saved)
XCTAssertEqual(final.deletingLastPathComponent().standardizedFileURL, recoveredFolder.standardizedFileURL)
let duration = try await AVURLAsset(url: final).load(.duration).seconds
XCTAssertGreaterThan(duration, 0.2, "Recovery must deliver preceding recorded content")
XCTAssertEqual(try Data(contentsOf: unrelated), original, "Completion cleans only its working movie, never unexpected files")
XCTAssertFalse(FileManager.default.fileExists(atPath: record.working.path))
XCTAssertEqual(cues, [.recordingStarted], "Recovery must not emit a new recording-start cue")
}
@MainActor func testRecordingTransportSurvivesAnOccupiedMainActorOnBothProcessors() async throws {
for hd in [false, true] {
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller, use6309: hd)
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
capture.startRecording()
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertEqual(capture.state, .recording)
let before = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
holdMainActor()
let after = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } }
// Allow any delayed failure notification to run before assertions;
// merely observing the old published Recording state proves little.
try await Task.sleep(for: .milliseconds(100))
XCTAssertEqual(capture.state, .recording); XCTAssertNil(capture.error)
XCTAssertEqual(after.generation, before.generation)
XCTAssertEqual(after.audioStarts, before.audioStarts)
XCTAssertGreaterThan(after.cycles, before.cycles)
XCTAssertGreaterThan(after.presentedFrame, before.presentedFrame)
XCTAssertEqual(after.use6309, hd)
await capture.stopRecording()
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error)
XCTAssertTrue(capture.recoveries.isEmpty)
let asset = AVURLAsset(url: try XCTUnwrap(capture.saved))
let duration = try await asset.load(.duration).seconds
XCTAssertGreaterThan(duration, 0.75, "The movie must span the occupied UI interval")
XCTAssertEqual(cues, [.recordingStarted])
await withCheckedContinuation { c in model.shutdown { c.resume() } }
}
}
@MainActor func testCaptureFailureQuiescesAndFinalizesWhileMainActorIsOccupied() async throws {
let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller)
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { _ in })
capture.startRecording()
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertEqual(capture.state, .recording)
let record = try XCTUnwrap(capture.recoveries.first)
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .milliseconds(200)) { controller.failNextPull = true }
holdMainActor()
XCTAssertEqual(controller.finalPulls, 1, "Failure must stop the source without waiting for the UI notification")
for _ in 0..<300 where capture.state != .idle { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.saved)
XCTAssertEqual(capture.error, "Authored capture-consumer interruption")
XCTAssertEqual(capture.recoveries.map(\.id), [record.id])
let duration = try await AVURLAsset(url: record.working).load(.duration).seconds
XCTAssertGreaterThan(duration, 0.1)
XCTAssertEqual(controller.finalPulls, 1, "The later UI stop shares the same backend finalization")
}
@MainActor func testEncoderFailureQuiescesSourceBeforeItsMainActorNotification() async throws {
let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller)
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { _ in })
capture.startRecording()
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertEqual(capture.state, .recording)
let record = try XCTUnwrap(capture.recoveries.first)
// A malformed authored transport frame exercises the real encoder's
// validation/failure callback; no guest memory or registers are changed.
DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .milliseconds(200)) { controller.invalidateNextPull = true }
holdMainActor()
XCTAssertEqual(controller.finalPulls, 1)
// User Stop can arrive before the queued UI failure notification. Both
// paths must share the already-started backend finalization.
await capture.stopRecording()
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.saved)
XCTAssertTrue(capture.error?.contains("ordering") == true)
XCTAssertEqual(capture.recoveries.map(\.id), [record.id])
XCTAssertEqual(controller.finalPulls, 1)
let duration = try await AVURLAsset(url: record.working).load(.duration).seconds
XCTAssertGreaterThan(duration, 0.1)
}
@MainActor func testImmediateFailureDoesNotLatchRecordingOrStopItsSuccessor() async throws {
let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller)
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
for _ in 0..<4 {
controller.failNextPull = true
capture.startRecording()
for _ in 0..<300 where capture.state != .idle { try await Task.sleep(for: .milliseconds(5)) }
XCTAssertEqual(capture.state, .idle, "An immediate background failure must not leave a stale Recording state")
XCTAssertEqual(capture.error, "Authored capture-consumer interruption")
}
let retained = capture.recoveries.map(\.id), oldCues = cues.count
XCTAssertEqual(retained.count, 4)
capture.startRecording()
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
try await Task.sleep(for: .milliseconds(150))
XCTAssertEqual(capture.state, .recording); XCTAssertNil(capture.error)
XCTAssertEqual(cues.count, oldCues + 1)
await capture.stopRecording()
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error)
XCTAssertNotNil(capture.saved)
XCTAssertEqual(capture.recoveries.map(\.id), retained)
}
@MainActor func testCaptureStartOwnsFreshErrorStateAndBridgeRefusalNeverCuesOnBothProcessors() async throws {
for hd in [false, true] {
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller, use6309: hd)
let rejected = await withCheckedContinuation { c in
controller.configureMachine(use6309: hd, ram: 99, overclock: 1, frameInterval: 1, fastForward: false) { c.resume(returning: $0) }
}
XCTAssertNotNil(rejected.errorMessage)
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
capture.startRecording()
for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertEqual(capture.state, .recording); XCTAssertNil(capture.error)
try await Task.sleep(for: .milliseconds(100))
await capture.stopRecording()
XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error)
XCTAssertNotNil(capture.saved); XCTAssertTrue(capture.recoveries.isEmpty)
XCTAssertEqual(cues, [.recordingStarted])
// The model deliberately retains its last normal-speed snapshot;
// the owner queue independently refuses the actual fast-forward run.
_ = await withCheckedContinuation { c in
controller.configureMachine(use6309: hd, ram: model.settings.ram, overclock: 1, frameInterval: 1, fastForward: true) { c.resume(returning: $0) }
}
XCTAssertFalse(model.settings.fastForward)
capture.startRecording()
for _ in 0..<200 where capture.state != .idle { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertEqual(capture.state, .idle)
XCTAssertTrue(capture.error?.contains("fast-forward") == true)
XCTAssertEqual(cues, [.recordingStarted], "A refused bridge start must not emit a success cue")
_ = await withCheckedContinuation { c in
controller.configureMachine(use6309: hd, ram: model.settings.ram, overclock: 1, frameInterval: 1, fastForward: false) { c.resume(returning: $0) }
}
let probe = await withCheckedContinuation { c in controller.beginVideoCapture(replyQueue: .global(qos: .userInitiated)) { c.resume(returning: $0) } }
XCTAssertNil(probe.errorMessage, "The rejected start must not leave an unowned capture producer active")
let stopped: String? = await withCheckedContinuation { c in controller.takeVideoCapture(finish: true, replyQueue: .global(qos: .userInitiated)) { _, error in c.resume(returning: error) } }
XCTAssertNil(stopped)
await withCheckedContinuation { c in model.shutdown { c.resume() } }
}
}
@MainActor func testNewerRecoveryManifestIsPreservedAndBlocksAnotherWriter() async throws {
let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller)
let manifest = root.appendingPathComponent("CaptureRecovery.json")
let original = Data(#"{"version":2,"recordings":[],"futureMetadata":"preserve exactly"}"#.utf8)
try original.write(to: manifest)
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
try await capture.preferences.setFolder(root)
XCTAssertNotNil(capture.error)
capture.startRecording()
XCTAssertEqual(capture.state, .idle); XCTAssertTrue(capture.recoveries.isEmpty)
XCTAssertTrue(capture.error?.contains("preserved recording recovery") == true)
XCTAssertTrue(cues.isEmpty)
XCTAssertEqual(try Data(contentsOf: manifest), original)
let contents = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
XCTAssertFalse(contents.contains { $0.lastPathComponent.hasPrefix(".vcc-recording-") })
}
@MainActor func testSharedDestinationDefaultsTimerAndAudioPersistWithoutMovingFiles() async throws {
let root = try folder(), suite = "CoCoCapturePreferences-" + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let first = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
XCTAssertEqual(first.destination, .desktop)
XCTAssertEqual(first.folder, root)
XCTAssertEqual(first.screenshots, first.recordings)
XCTAssertEqual(first.timerSeconds, 0); XCTAssertTrue(first.includeVideoAudio)
XCTAssertNil(defaults.data(forKey: "capture.folder.shared"), "A logical default must not create a security bookmark before the user chooses a folder")
let custom = root.appendingPathComponent("My Captures", isDirectory: true)
try FileManager.default.createDirectory(at: custom, withIntermediateDirectories: true)
let original = custom.appendingPathComponent("Existing.txt")
try Data("keep me".utf8).write(to: original)
try await first.setFolder(custom); first.setTimerSeconds(10); first.includeVideoAudio = false
let chosenBookmark = try XCTUnwrap(defaults.data(forKey: "capture.folder.shared"))
let reopened = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
XCTAssertEqual(reopened.folder.standardizedFileURL, custom.standardizedFileURL)
XCTAssertEqual(reopened.screenshots, reopened.recordings)
XCTAssertEqual(reopened.destination, .other)
XCTAssertEqual(reopened.timerSeconds, 10); XCTAssertFalse(reopened.includeVideoAudio)
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), chosenBookmark, "Reopening preferences preserves an explicit selected-folder grant")
reopened.setTimerSeconds(3)
XCTAssertEqual(reopened.timerSeconds, 10, "Only None, 5 and 10 are valid timer choices")
reopened.setDestination(.documents)
XCTAssertEqual(reopened.folder, root.appendingPathComponent("Documents", isDirectory: true))
XCTAssertEqual(try Data(contentsOf: original), Data("keep me".utf8))
reopened.setDestination(.desktop)
XCTAssertEqual(reopened.folder, root)
defaults.set(999, forKey: "capture.timer.seconds")
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).timerSeconds, 0)
}
@MainActor func testLegacyCaptureFoldersMigrateWithExplicitScreenshotChoiceFirst() throws {
let root = try folder(), screenshot = root.appendingPathComponent("Pictures"), video = root.appendingPathComponent("Movies")
for path in [screenshot, video] { try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true) }
for screenshotChosen in [false, true] {
let suite = "CoCoCaptureMigration-" + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let videoBookmark = try video.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
defaults.set(videoBookmark, forKey: "capture.folder.recordings")
if screenshotChosen {
defaults.set(try screenshot.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil), forKey: "capture.folder.screenshots")
}
let migrated = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
let expected = screenshotChosen ? screenshot : video
XCTAssertEqual(migrated.folder.standardizedFileURL, expected.standardizedFileURL)
XCTAssertEqual(migrated.screenshots, migrated.recordings)
XCTAssertEqual(defaults.data(forKey: "capture.folder.recordings"), videoBookmark)
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"),
defaults.data(forKey: screenshotChosen ? "capture.folder.screenshots" : "capture.folder.recordings"),
"Migration reuses the existing security bookmark bytes instead of requesting a new grant")
let reopened = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
XCTAssertEqual(reopened.folder.standardizedFileURL, expected.standardizedFileURL)
}
}
@MainActor func testBuiltInDestinationsPersistWithoutBookmarkOrDirectoryWorkAndOverrideOther() async throws {
let root = try folder(), custom = root.appendingPathComponent("Chosen Other", isDirectory: true)
try FileManager.default.createDirectory(at: custom, withIntermediateDirectories: true)
let suite = "CoCoLogicalDestination-" + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
try await preferences.setFolder(custom)
let bookmark = try XCTUnwrap(defaults.data(forKey: "capture.folder.shared"))
let documents = root.appendingPathComponent("Documents", isDirectory: true)
XCTAssertFalse(FileManager.default.fileExists(atPath: documents.path))
preferences.setDestination(.documents)
XCTAssertEqual(preferences.destination, .documents); XCTAssertEqual(preferences.folder, documents)
XCTAssertEqual(defaults.string(forKey: "capture.destination"), "documents")
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), bookmark, "Keep the previous explicit grant for in-flight writers")
XCTAssertFalse(FileManager.default.fileExists(atPath: documents.path), "Selecting a logical folder must not create it on the UI thread")
let reopened = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { _ in
XCTFail("Logical destination restore must not make a bookmark"); return Data()
})
XCTAssertEqual(reopened.destination, .documents); XCTAssertEqual(reopened.folder, documents)
reopened.setDestination(.desktop)
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).folder, root)
XCTAssertEqual(defaults.string(forKey: "capture.destination"), "desktop")
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), bookmark)
XCTAssertFalse(FileManager.default.fileExists(atPath: documents.path))
}
@MainActor func testLateOtherGrantCannotReplaceNewerBuiltInOrOtherChoice() async throws {
for newerOther in [false, true] {
let root = try folder(), first = root.appendingPathComponent("First"), second = root.appendingPathComponent("Second")
for url in [first, second] { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) }
let suite = "CoCoDestinationOrder-" + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let gate = BookmarkGate(blocked: first)
let preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { try gate.prepare($0) })
let stale = Task { try await preferences.setFolder(first) }
for _ in 0..<200 where !gate.started { try await Task.sleep(for: .milliseconds(5)) }
XCTAssertTrue(gate.started); XCTAssertTrue(preferences.preparingDestination)
if newerOther { try await preferences.setFolder(second) } else { preferences.setDestination(.documents) }
gate.unblock()
do { try await stale.value; XCTFail("A superseded grant must not become the selected folder") }
catch is CancellationError { }
let expected = newerOther ? second : root.appendingPathComponent("Documents", isDirectory: true)
XCTAssertEqual(preferences.folder, expected); XCTAssertFalse(preferences.preparingDestination)
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).folder.standardizedFileURL, expected.standardizedFileURL)
}
}
@MainActor func testLateOtherFailureIsCancellationAndLegacyFallbackStillMigrates() async throws {
let root = try folder(), first = root.appendingPathComponent("First"), legacy = root.appendingPathComponent("Legacy")
for url in [first, legacy] { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) }
let suite = "CoCoDestinationFailure-" + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let legacyBookmark = try legacy.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
defaults.set(Data("invalid shared bookmark".utf8), forKey: "capture.folder.shared")
defaults.set(legacyBookmark, forKey: "capture.folder.recordings")
let gate = BookmarkGate(blocked: first, fails: true)
let preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { try gate.prepare($0) })
XCTAssertEqual(preferences.folder.standardizedFileURL, legacy.standardizedFileURL)
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), legacyBookmark)
let stale = Task { try await preferences.setFolder(first) }
for _ in 0..<200 where !gate.started { try await Task.sleep(for: .milliseconds(5)) }
XCTAssertTrue(gate.started)
preferences.setDestination(.desktop); gate.unblock()
do { try await stale.value; XCTFail("A superseded failed grant must be ignored") }
catch is CancellationError { }
XCTAssertEqual(preferences.folder, root); XCTAssertFalse(preferences.preparingDestination)
XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), legacyBookmark)
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).destination, .desktop)
let later = root.appendingPathComponent("Later Other")
try FileManager.default.createDirectory(at: later, withIntermediateDirectories: true)
let nextGate = BookmarkGate(blocked: first, fails: true)
let next = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { try nextGate.prepare($0) })
let superseded = Task { try await next.setFolder(first) }
for _ in 0..<200 where !nextGate.started { try await Task.sleep(for: .milliseconds(5)) }
XCTAssertTrue(nextGate.started)
try await next.setFolder(later); nextGate.unblock()
do { try await superseded.value; XCTFail("An old failure must not replace a newer accepted Other folder") }
catch is CancellationError { }
XCTAssertEqual(next.folder, later); XCTAssertFalse(next.preparingDestination)
XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).folder.standardizedFileURL, later.standardizedFileURL)
}
@MainActor func testTimerSelectionCancellationAndRealCaptureEmitOnlyActualCaptureCues() async throws {
let root = try folder(), suite = "CoCoCaptureCues-" + UUID().uuidString
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let controller = VCCMachineController()
let model = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller,
displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json")), restoreMediaOnLaunch: false)
var cues: [CoCoCaptureFeedback.Cue] = []
let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) })
try await capture.preferences.setFolder(root)
capture.captureNow(); capture.startRecording()
XCTAssertTrue(cues.isEmpty, "A missing framebuffer cannot emit a success cue")
XCTAssertEqual(capture.state, .idle)
await withCheckedContinuation { c in controller.loadDiagnostic(use6309: false) { _ in c.resume() } }
await withCheckedContinuation { c in controller.resume { _ in c.resume() } }
for _ in 0..<100 where model.pixels == nil { model.poll(); try await Task.sleep(for: .milliseconds(10)) }
guard model.pixels != nil else {
await withCheckedContinuation { c in model.shutdown { c.resume() } }
return XCTFail("The diagnostic guest did not provide a picture")
}
capture.preferences.setTimerSeconds(10); capture.preferences.includeVideoAudio = false
XCTAssertNil(capture.countdown); XCTAssertNil(capture.saved); XCTAssertTrue(cues.isEmpty)
capture.capture()
XCTAssertEqual(capture.countdown, 10); XCTAssertTrue(cues.isEmpty)
capture.cancelCountdown()
try await Task.sleep(for: .milliseconds(50))
XCTAssertNil(capture.countdown); XCTAssertNil(capture.saved); XCTAssertTrue(cues.isEmpty)
capture.preferences.setTimerSeconds(0); capture.capture(); capture.capture()
XCTAssertEqual(cues, [.screenshot], "A duplicate click during saving must not capture or cue twice")
for _ in 0..<100 where capture.saving { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertNotNil(capture.saved); XCTAssertFalse(capture.hasPendingImage)
capture.preferences.setTimerSeconds(5); capture.capture()
XCTAssertEqual(capture.countdown, 5); XCTAssertEqual(cues.count, 1)
for _ in 0..<650 where capture.countdown != nil || capture.saving { try await Task.sleep(for: .milliseconds(10)) }
XCTAssertNil(capture.countdown); XCTAssertFalse(capture.saving)
XCTAssertEqual(cues, [.screenshot, .screenshot], "Only timer expiry emits the delayed capture cue")
let pngs = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil).filter { $0.pathExtension == "png" }
XCTAssertEqual(pngs.count, 2)
await withCheckedContinuation { c in model.shutdown { c.resume() } }
}
func testSilentVideoDecodesToSilenceWithUnchangedPictureAndTimeline() async throws {
let root = try folder(), movie = root.appendingPathComponent("Silent.mov"), final = root.appendingPathComponent("Silent.mp4")
let encoder = try CoCoVideoEncoder(workingURL: movie), bytes = picture()
var source = Data(count: 735 * 8)
source.withUnsafeMutableBytes { raw in
let floats = raw.bindMemory(to: Float.self)
for i in 0..<735 { floats[2*i] = 0.25; floats[2*i+1] = -0.25 }
}
let live = CoCoCaptureCoordinator.videoFrame(pixels: bytes, area: CGRect(x: 64, y: 48, width: 512, height: 384), audio: source, sampleOffset: 735, includeAudio: true)
XCTAssertEqual(live.audio, source)
for n in 0..<60 {
let silent = CoCoCaptureCoordinator.videoFrame(pixels: bytes, area: live.area, audio: source, sampleOffset: Int64(n*735), includeAudio: false)
XCTAssertEqual(silent.pixels, bytes); XCTAssertEqual(silent.area, live.area)
XCTAssertEqual(silent.sampleOffset, Int64(n*735)); XCTAssertEqual(silent.audio.count, source.count)
XCTAssertTrue(silent.audio.allSatisfy { $0 == 0 })
encoder.append([silent]); try await Task.sleep(for: .milliseconds(17))
}
let working: URL = try await withCheckedThrowingContinuation { c in encoder.finish { c.resume(with: $0) } }
try await CoCoVideoEncoder.exportMP4(from: working, to: final)
let asset = AVURLAsset(url: final)
let duration = try await asset.load(.duration).seconds
XCTAssertEqual(duration, 1, accuracy: 0.03)
let audio = try await asset.loadTracks(withMediaType: .audio), video = try await asset.loadTracks(withMediaType: .video)
XCTAssertEqual(video.count, 1)
let track = try XCTUnwrap(audio.first)
let reader = try AVAssetReader(asset: asset)
let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM,
AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false])
reader.add(output); XCTAssertTrue(reader.startReading())
var peak: Float = 0, count = 0
while let sample = output.copyNextSampleBuffer() {
let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample))
var data = Data(count: CMBlockBufferGetDataLength(buffer))
let result = data.withUnsafeMutableBytes { CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!) }
XCTAssertEqual(result, noErr)
data.withUnsafeBytes { raw in
for value in raw.bindMemory(to: Float.self) { peak = max(peak, abs(value)); count += 1 }
}
}
XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(count, 0)
XCTAssertLessThan(peak, 0.00001, "The delivered MP4 must decode to silence, despite nonzero source PCM")
}
}
@@ -0,0 +1,110 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import AVFoundation
import Foundation
import XCTest
final class CoCoVideoBudgetTests: XCTestCase {
private func directory() throws -> URL {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CoCoVideoBudget-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false)
addTeardownBlock { try? FileManager.default.removeItem(at: root) }
return root
}
private func frames(count: Int, audioFrames: Int = 735) -> [CoCoVideoFrame] {
let pixels = Data(repeating: 0x40, count: 640 * 480 * 4)
return (0..<count).map { n in
CoCoVideoFrame(pixels: pixels, area: CGRect(x:64,y:48,width:512,height:384),
audio: Data(count: audioFrames * 8), sampleOffset: Int64(n * audioFrames))
}
}
func testOversizedIngressFailsOnceAndEveryFinishCallbackCompletesOnce() async throws {
let root = try directory()
let encoder = try CoCoVideoEncoder(workingURL: root.appendingPathComponent("Working.mov"))
let failure = expectation(description: "bounded ingress reports one failure")
failure.assertForOverFulfill = true
encoder.failure = { message in
XCTAssertTrue(message.localizedCaseInsensitiveContains("bounded"))
failure.fulfill()
}
// A valid three-second stereo batch exceeds the recorder's public
// two-second retention contract before it reaches the encoder queue.
let oversized = frames(count: 1, audioFrames: 3 * 44_100)
for _ in 0..<100 { encoder.append(oversized) }
let first = expectation(description: "first finish returns failure")
let second = expectation(description: "repeat finish returns failure")
first.assertForOverFulfill = true; second.assertForOverFulfill = true
encoder.finish { result in
if case .success = result { XCTFail("Over-budget input must not claim a completed movie") }
XCTAssertTrue(encoder.writerIsTerminal, "Failure completion must await AVFoundation writer closure")
first.fulfill()
}
encoder.finish { result in
if case .success = result { XCTFail("Repeated Stop must not manufacture a successful movie") }
XCTAssertTrue(encoder.writerIsTerminal, "Duplicate Stop must share the same writer-closure barrier")
second.fulfill()
}
await fulfillment(of: [failure, first, second], timeout: 8)
}
func testRapidValidFrameProducerIsRejectedWithoutUnboundedQueueing() async throws {
let root = try directory()
let encoder = try CoCoVideoEncoder(workingURL: root.appendingPathComponent("Working.mov"))
let failure = expectation(description: "unpaced producer reaches bounded ingress")
failure.assertForOverFulfill = true
encoder.failure = { message in
XCTAssertTrue(message.localizedCaseInsensitiveContains("bounded"))
failure.fulfill()
}
// This is deliberately not real-time pacing: a producer must not hide
// thousands of otherwise valid frames inside pending dispatch blocks.
let pixels = Data(repeating:0x60,count:640 * 480 * 4)
let audio = Data(count:735 * 8)
for n in 0..<2_000 {
encoder.append([CoCoVideoFrame(pixels:pixels,area:CGRect(x:64,y:48,width:512,height:384),audio:audio,sampleOffset:Int64(n * 735))])
}
let stopped = expectation(description: "stop finishes after input rejection")
stopped.assertForOverFulfill = true
encoder.finish { result in
if case .success = result { XCTFail("Dropped over-budget input cannot be reported as a complete recording") }
stopped.fulfill()
}
await fulfillment(of:[failure,stopped],timeout:8)
}
func testOrderingFailureRetainsPrecedingMovieBytesAndNeverClaimsSuccessfulCompletion() async throws {
let root = try directory(), working = root.appendingPathComponent("Working.mov")
let neighbor = root.appendingPathComponent("Existing.mp4"), original = Data("unrelated original".utf8)
try original.write(to: neighbor)
let encoder = try CoCoVideoEncoder(workingURL: working)
let failure = expectation(description: "ordering failure is reported once")
failure.assertForOverFulfill = true
encoder.failure = { message in
XCTAssertTrue(message.contains("ordering"))
failure.fulfill()
}
// First establish a real encoded movie, rather than asserting that an
// empty writer created a pathname. The next packet violates ordering.
for frame in frames(count: 20) {
encoder.append([frame])
try await Task.sleep(for: .milliseconds(17))
}
var invalid = frames(count: 1)[0]
invalid.sampleOffset = -1
encoder.append([invalid])
await fulfillment(of: [failure], timeout: 5)
let stopped: Result<URL, Error> = await withCheckedContinuation { c in encoder.finish { c.resume(returning: $0) } }
if case .success = stopped { XCTFail("Writer failure must not be advertised as a completed movie") }
XCTAssertTrue(encoder.writerIsTerminal)
let drained: Result<Void, Error> = await withCheckedContinuation { c in encoder.whenDrained { c.resume(returning: $0) } }
if case .success = drained { XCTFail("Failed input cannot be acknowledged as a successful drain") }
// The failure notification can precede AVFoundation's closure, but the
// finish callback cannot. No polling/retry is permitted after finish.
let duration = try await AVURLAsset(url: working).load(.duration).seconds
XCTAssertGreaterThan(duration, 0.2, "A failed writer retains its preceding playable content")
XCTAssertGreaterThan(try Data(contentsOf: working).count, 0)
XCTAssertEqual(try Data(contentsOf: neighbor), original)
let contents = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
XCTAssertEqual(Set(contents.map(\.lastPathComponent)), ["Working.mov", "Existing.mp4"])
}
}
@@ -1,13 +1,66 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import ImageIO
import UniformTypeIdentifiers
final class CompanionLibraryTests: XCTestCase {
private static func release(_ id: String, media: String = "disk") -> SoftwareLibraryRelease {
.init(id: id, titleID: "title", name: id, category: "Disks/Games", mediaType: media,
func testColdServiceReadinessCanOutlastOldSixSecondLimitWithoutDelayingReadyService() async throws {
var uptime: TimeInterval = 100, attempts = 0, pauses = 0
try await CompanionTransport.waitForService(now: { uptime }, sleep: { delay in
pauses += 1; uptime += delay
}, probe: { remaining in
attempts += 1
XCTAssertGreaterThan(remaining, 0); XCTAssertLessThanOrEqual(remaining, 45)
if uptime < 123 { throw CompanionTransport.Failure.unavailable }
})
XCTAssertGreaterThan(uptime - 100, 22.9)
XCTAssertGreaterThan(attempts, 60); XCTAssertEqual(pauses, attempts - 1)
pauses = 0; attempts = 0
try await CompanionTransport.waitForService(now: { uptime }, sleep: { _ in pauses += 1 }, probe: { _ in attempts += 1 })
XCTAssertEqual(attempts, 1); XCTAssertEqual(pauses, 0)
}
func testColdServiceReadinessHasBoundedDeadlineAndKeepsRealErrors() async throws {
var uptime: TimeInterval = 0, pauses = 0
do {
try await CompanionTransport.waitForService(timeout: 0.25, now: { uptime }, sleep: { delay in
pauses += 1; uptime += delay
}, probe: { _ in throw CompanionTransport.Failure.unavailable })
XCTFail("A service that never starts must time out")
} catch CompanionTransport.Failure.startupTimedOut { }
XCTAssertEqual(uptime, 0.25, accuracy: 0.00001); XCTAssertEqual(pauses, 3)
for failure in [CompanionTransport.Failure.untrustedPeer, .unsafeEndpoint, .unsupportedVersion, .timedOut, .remote("Denied")] {
pauses = 0
do {
try await CompanionTransport.waitForService(sleep: { _ in pauses += 1 }, probe: { _ in throw failure })
XCTFail("A real companion error must not be retried")
} catch { XCTAssertEqual(error.localizedDescription, failure.localizedDescription) }
XCTAssertEqual(pauses, 0)
}
}
func testColdServiceReadinessCancelsDuringStartupWait() async throws {
let waiting = expectation(description: "Startup is waiting for its missing listener")
let task = Task {
try await CompanionTransport.waitForService(sleep: { _ in
waiting.fulfill()
try await Task.sleep(for: .seconds(60))
}, probe: { _ in throw CompanionTransport.Failure.unavailable })
}
await fulfillment(of: [waiting], timeout: 2)
task.cancel()
do { try await task.value; XCTFail("Cancellation must end startup polling") }
catch is CancellationError { }
}
private static func release(_ id: String, media: String = "disk", owned: Bool = false) -> SoftwareLibraryRelease {
var metadata: [String: LibraryJSON] = ["title": .string("Authored Example"), "optional": .null, "enabled": .bool(false), "count": .number(2)]
if owned { metadata["owned_game"] = .object([:]) }
return .init(id: id, titleID: "title", name: id, category: "Disks/Games", mediaType: media,
contentRole: "software", sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Example.zip")!,
modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil,
packageSHA256: String(repeating: "a", count: 64), byteSize: 256, languageStatus: "unknown",
metadata: .object(["title": .string("Authored Example"), "optional": .null, "enabled": .bool(false), "count": .number(2)]),
metadata: .object(metadata),
setup: .init(status: "manual-setup", command: nil, instructions: "Follow the authored instructions.",
configuration: .object([:]), selectedMembers: .array([]), reasons: [], validation: .object([:])),
assets: [], downloadURLs: [])
@@ -44,6 +97,61 @@ final class CompanionLibraryTests: XCTestCase {
XCTAssertNil(state.saveError)
XCTAssertFalse(FileManager.default.fileExists(atPath: state.directory.appendingPathComponent("Unused.json").path))
}
@MainActor
func testBothAppsSharePersistedFavoritesAndEditionChoicesWithoutASecondStateFile() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CompanionChoices-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let catalog = SoftwareLibraryCatalog(titles: [.init(id: "title", name: "Authored Example", identityStatus: "reviewed",
releases: [Self.release("disk"), Self.release("second-disk")])], metadata: [:])
let host = SoftwareLibraryModel(state: .init(directory: root))
await host.load(from: root.appendingPathComponent("authored.sqlite"), catalogLoader: { _ in catalog })
host.state.toggleFavorite("title")
host.state.selectRelease("second-disk", for: "title")
await host.state.flush()
let service = AuthorityLibrary(authority: .init(model: host))
let client = SoftwareLibraryModel(companion: service) { _ in XCTFail("Changing choices must not insert media.") }
await client.load()
XCTAssertTrue(client.state.isFavorite("title"), "A companion opening after a VCC Plus change reads the same choices.")
XCTAssertEqual(client.state.preferredReleaseID(for: "title"), "second-disk")
client.state.toggleFavorite("title")
client.state.selectRelease("disk", for: "title")
await client.state.flush()
XCTAssertNil(client.state.saveError)
XCTAssertFalse(host.state.isFavorite("title"))
XCTAssertEqual(host.state.preferredReleaseID(for: "title"), "disk")
// Reopening the authoritative state proves the response was persisted,
// rather than copied only between the two current in-memory models.
let persisted = SoftwareLibraryState(directory: root)
XCTAssertNil(persisted.saveError)
XCTAssertFalse(persisted.isFavorite("title"))
XCTAssertEqual(persisted.preferredReleaseID(for: "title"), "disk")
XCTAssertFalse(FileManager.default.fileExists(atPath: client.state.directory.appendingPathComponent("Unused.json").path))
let reopened = SoftwareLibraryModel(companion: service) { _ in XCTFail("Reopening must not insert media.") }
await reopened.load()
XCTAssertFalse(reopened.state.isFavorite("title"))
XCTAssertEqual(reopened.state.preferredReleaseID(for: "title"), "disk")
await reopened.shutdown(); await client.shutdown(); await host.shutdown()
}
@MainActor
func testUnavailableCompanionCanBeRetriedWithoutCreatingLocalLibraryState() async throws {
let service = RecoveringLibrary(catalog: Self.catalog)
let model = SoftwareLibraryModel(companion: service) { _ in XCTFail("A failed or retried browse must not insert media.") }
await model.load()
XCTAssertNotNil(model.error)
XCTAssertNil(model.catalog)
XCTAssertFalse(model.loading)
await service.reconnect()
await model.load()
XCTAssertNil(model.error)
XCTAssertEqual(model.catalog?.releases.map(\.id), ["disk"])
XCTAssertFalse(model.loading)
XCTAssertFalse(FileManager.default.fileExists(atPath: model.state.directory.appendingPathComponent("Unused.json").path))
await model.shutdown()
}
@MainActor
func testClearingFiltersAndChangingEditionCannotExposeTapeOrCartridge() async throws {
let service = FakeLibrary(catalog: Self.catalog)
@@ -68,6 +176,301 @@ final class CompanionLibraryTests: XCTestCase {
}
}
func testPersonalCapabilityIsExplicitAndOlderRequestsDecodeWithoutIt() throws {
let current = CompanionLibraryRequest(operation: .snapshot)
XCTAssertEqual(current.personalTitlesVersion, 1)
let old = try JSONDecoder().decode(CompanionLibraryRequest.self, from: Data("{\"operation\":\"snapshot\",\"requestID\":\"00000000-0000-0000-0000-000000000001\"}".utf8))
XCTAssertNil(old.personalTitlesVersion)
XCTAssertNil(old.ownedTitlesVersion)
let entry = PersonalSoftwareEntry(id: UUID(), title: "Private disk", files: [
.init(path: "game.dsk", kind: "disk", byteSize: 256, sha256: String(repeating: "a", count: 64))])
let release = entry.release(in: URL(fileURLWithPath: "/unused/PersonalLibrary/" + entry.id.uuidString.lowercased()))
let catalog = SoftwareLibraryCatalog(titles: Self.catalog.titles + [
.init(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [release])], metadata: [:])
XCTAssertEqual(catalog.companionDisks(includingOwnedTitles: true).releases.map(\.id), ["disk"])
XCTAssertEqual(Set(catalog.companionDisksOnly.releases.map(\.id)), Set(["disk", entry.releaseID]))
let mixed = SoftwareLibraryCatalog(titles: [.init(id: "title", name: "Mixed editions", identityStatus: "reviewed",
releases: [Self.release("disk"), Self.release("owned", owned: true), Self.release("cart", media: "cartridge")])], metadata: [:])
XCTAssertEqual(mixed.companionDisks(includingOwnedTitles: false, includingPersonalTitles: true).releases.map(\.id), ["disk"])
XCTAssertEqual(mixed.companionDisks(includingOwnedTitles: true).releases.map(\.id), ["disk", "owned"])
}
@MainActor
func testAuthoritySharesCurrentPersonalDiskChoicesAndIndependentWritableCopies() async throws {
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionPersonal-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
let source = root.appendingPathComponent("GAME.dsk")
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
let original = try Data(contentsOf: fixture)
try original.write(to: source)
let manual = root.appendingPathComponent("README.txt"), instructions = Data("Private local instructions".utf8)
try instructions.write(to: manual)
let draft = try await model.personalStore.inspect([source, manual])
let entry = try await model.personalStore.save(draft)
await model.load(from: root.appendingPathComponent("authored.sqlite"), catalogLoader: { _ in Self.catalog })
let authority = CompanionLibraryAuthority(model: model)
let initial = try await authority.handle(.init(operation: .snapshot))
let snapshot = try XCTUnwrap(initial.snapshot)
XCTAssertEqual(Set(snapshot.catalog.releases.map(\.id)), Set(["disk", entry.releaseID]))
XCTAssertEqual(snapshot.installations.map(\.releaseID), [entry.releaseID])
XCTAssertTrue(snapshot.catalog.releases.first(where: { $0.id == entry.releaseID })!.downloadURLs.isEmpty)
let favorite = try await authority.handle(.init(operation: .setFavorite, titleID: entry.titleID, enabled: true))
XCTAssertTrue(favorite.snapshot!.favorites.contains(entry.titleID))
let preferred = try await authority.handle(.init(operation: .setPreferredRelease, releaseID: entry.releaseID, titleID: entry.titleID))
XCTAssertEqual(preferred.snapshot!.preferredReleaseIDs[entry.titleID], entry.releaseID)
for operation in [CompanionLibraryRequest.Operation.install, .installStatus] {
let status = try await authority.handle(.init(operation: operation, releaseID: entry.releaseID))
XCTAssertFalse(status.isInstalling); XCTAssertEqual(status.receipt?.releaseID, entry.releaseID)
}
let directory = model.personalDirectory(entry), working = directory.appendingPathComponent("Working/GAME.dsk")
var saved = original; saved[0] ^= 1; try saved.write(to: working)
let members = try await authority.handle(.init(operation: .diskMembers, releaseID: entry.releaseID))
XCTAssertEqual(members.disks?.map(\.path), ["GAME.dsk"])
let export = try await authority.handle(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk"))
let copy = try XCTUnwrap(export.exportedDiskURL)
XCTAssertNotEqual(copy, working); XCTAssertEqual(try Data(contentsOf: copy), saved)
try Data([1, 2, 3]).write(to: copy)
let second = try await authority.handle(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk"))
XCTAssertNotEqual(second.exportedDiskURL, copy)
XCTAssertEqual(try Data(contentsOf: working), saved)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.dsk")), original)
XCTAssertEqual(try Data(contentsOf: source), original)
let asset = try XCTUnwrap(snapshot.catalog.releases.first(where: { $0.id == entry.releaseID })?.primaryManualAsset)
let response = try await authority.handle(.init(operation: .manual, assetID: asset.id))
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(response.assetFileURL)), instructions)
let localManual = try XCTUnwrap(response.assetFileURL)
try FileManager.default.removeItem(at: localManual)
try FileManager.default.createSymbolicLink(at: localManual, withDestinationURL: manual)
await assertFailure(authority, .init(operation: .manual, assetID: asset.id))
await assertFailure(authority, .init(operation: .removeInstallation, releaseID: entry.releaseID))
XCTAssertTrue(FileManager.default.fileExists(atPath: working.path))
await model.shutdown()
}
@MainActor
func testAuthorityRefusesHiddenUnknownNondiskAndUnnegotiatedPersonalIDs() async throws {
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionHidden-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
let draft = try await model.personalStore.inspect([fixture])
let visible = try await model.personalStore.save(draft)
let duplicate = try await model.personalStore.inspect([fixture])
var hidden = try await model.personalStore.save(duplicate, allowDuplicate: true)
hidden.hidden = true; try await model.personalStore.update(hidden)
let cart = root.appendingPathComponent("CART.ccc"); try Data([0x39]).write(to: cart)
let cartDraft = try await model.personalStore.inspect([cart])
let nondisk = try await model.personalStore.save(cartDraft)
var unsupported: [PersonalSoftwareEntry] = []
for ext in ["dmk", "jvc", "vdk"] {
let file = root.appendingPathComponent("Unsupported." + ext)
try FileManager.default.copyItem(at: fixture, to: file)
let draft = try await model.personalStore.inspect([file])
unsupported.append(try await model.personalStore.save(draft))
}
await model.load(from: fixture, catalogLoader: { _ in Self.catalog })
let authority = CompanionLibraryAuthority(model: model)
let current = try await authority.handle(.init(operation: .snapshot))
XCTAssertEqual(Set(current.snapshot!.catalog.releases.map(\.id)), Set(["disk", visible.releaseID]))
for version in [nil, 2] as [Int?] {
let response = try await authority.handle(.init(operation: .snapshot, personalTitlesVersion: version))
XCTAssertEqual(response.snapshot?.catalog.releases.map(\.id), ["disk"])
XCTAssertTrue(response.snapshot!.installations.isEmpty)
await assertFailure(authority, .init(operation: .diskMembers, releaseID: visible.releaseID, personalTitlesVersion: version))
await assertFailure(authority, .init(operation: .setFavorite, titleID: visible.titleID, enabled: true, personalTitlesVersion: version))
}
for entry in [hidden, nondisk] + unsupported {
await assertFailure(authority, .init(operation: .diskMembers, releaseID: entry.releaseID))
await assertFailure(authority, .init(operation: .setFavorite, titleID: entry.titleID, enabled: true))
}
await assertFailure(authority, .init(operation: .diskMembers, releaseID: "personal:unknown:edition"))
await assertFailure(authority, .init(operation: .setPreferredRelease, releaseID: visible.releaseID, titleID: hidden.titleID))
await assertFailure(authority, .init(operation: .exportDisk, releaseID: visible.releaseID, memberPath: "../DECB.dsk"))
await assertFailure(authority, .init(operation: .exportDisk, releaseID: visible.releaseID, memberPath: "missing.dsk"))
var removed = visible; removed.hidden = true; try await model.personalStore.update(removed)
await assertFailure(authority, .init(operation: .diskMembers, releaseID: visible.releaseID))
await model.shutdown()
}
@MainActor
func testAuthorityRefusesPersonalWorkingAndMemberSymlinks() async throws {
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionLinks-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
let source = root.appendingPathComponent("Set/sub"), fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true)
try FileManager.default.copyItem(at: fixture, to: source.appendingPathComponent("GAME.dsk"))
let draft = try await model.personalStore.inspect([source.deletingLastPathComponent()])
let entry = try await model.personalStore.save(draft)
await model.load(from: fixture, catalogLoader: { _ in Self.catalog })
let authority = CompanionLibraryAuthority(model: model), directory = model.personalDirectory(entry)
let working = directory.appendingPathComponent("Working"), member = working.appendingPathComponent("sub/GAME.dsk")
let original = try Data(contentsOf: fixture)
try FileManager.default.removeItem(at: member)
try FileManager.default.createSymbolicLink(at: member, withDestinationURL: fixture)
await assertFailure(authority, .init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "sub/GAME.dsk"))
try FileManager.default.removeItem(at: working.appendingPathComponent("sub"))
try FileManager.default.createSymbolicLink(at: working.appendingPathComponent("sub"), withDestinationURL: source)
await assertFailure(authority, .init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "sub/GAME.dsk"))
try FileManager.default.moveItem(at: working, to: directory.appendingPathComponent("RetainedWorking"))
try FileManager.default.createSymbolicLink(at: working, withDestinationURL: directory.appendingPathComponent("RetainedWorking"))
await assertFailure(authority, .init(operation: .diskMembers, releaseID: entry.releaseID))
XCTAssertEqual(try Data(contentsOf: fixture), original)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/sub/GAME.dsk")), original)
await model.shutdown()
}
@MainActor
func testCompanionModelPlaysPersonalDiskThroughActualAuthority() async throws {
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionClient-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let host = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
let source = root.appendingPathComponent("PRIVATE.dsk"), original = try Data(contentsOf: fixture)
try original.write(to: source)
let draft = try await host.personalStore.inspect([source])
let entry = try await host.personalStore.save(draft)
await host.load(from: fixture, catalogLoader: { _ in Self.catalog })
let directory = host.personalDirectory(entry), working = directory.appendingPathComponent("Working/PRIVATE.dsk")
var workingBytes = original; workingBytes[0] ^= 1
try workingBytes.write(to: working)
let service = AuthorityLibrary(authority: .init(model: host))
var inserted: [URL] = []
var insertedBytes: [Data] = []
let client = SoftwareLibraryModel(companion: service) { url in
inserted.append(url)
insertedBytes.append(try Data(contentsOf: url))
// Real DriveWire writes must affect only its separate handoff image.
try Data([0x42, 0x43]).write(to: url)
}
await client.load()
XCTAssertNil(client.error)
let release = try XCTUnwrap(client.catalog?.releases.first(where: { $0.id == entry.releaseID }))
XCTAssertTrue(release.isPersonal)
XCTAssertNotNil(client.state.installedReleases[entry.releaseID])
client.play(release)
for _ in 0..<100 where client.installingReleaseID != nil { try await Task.sleep(nanoseconds: 20_000_000) }
XCTAssertNil(client.installingReleaseID, "The local companion operation must complete without downloading or launching the emulator.")
XCTAssertNil(client.installationErrors[entry.releaseID]); XCTAssertNil(client.launchError)
XCTAssertEqual(inserted.count, 1)
XCTAssertEqual(insertedBytes, [workingBytes])
let copy = try XCTUnwrap(inserted.first)
XCTAssertNotEqual(copy, working)
XCTAssertTrue(copy.path.hasPrefix(host.state.directory.appendingPathComponent("CompanionDisks").path + "/"))
XCTAssertEqual(try Data(contentsOf: copy), Data([0x42, 0x43]))
XCTAssertEqual(try Data(contentsOf: working), workingBytes)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/PRIVATE.dsk")), original)
XCTAssertEqual(try Data(contentsOf: source), original)
let requests = await service.requests
XCTAssertEqual(requests.map(\.operation), [.snapshot, .install, .diskMembers, .exportDisk])
XCTAssertTrue(requests.allSatisfy { $0.personalTitlesVersion == 1 })
await client.shutdown(); await host.shutdown()
}
@MainActor
func testSelectedPersonalCoverAndRemovalReachCompanionWithoutChangingDiskBytes() async throws {
let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionCover-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let host = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
let source = root.appendingPathComponent("GAME.dsk"), original = try Data(contentsOf: fixture)
try original.write(to: source)
let context = try XCTUnwrap(CGContext(data: nil, width: 24, height: 36, bitsPerComponent: 8,
bytesPerRow: 24 * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
context.setFillColor(CGColor(gray: 0.3, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: 24, height: 36))
let imageBytes = NSMutableData()
let encoder = try XCTUnwrap(CGImageDestinationCreateWithData(imageBytes, UTType.png.identifier as CFString, 1, nil))
CGImageDestinationAddImage(encoder, try XCTUnwrap(context.makeImage()), nil)
XCTAssertTrue(CGImageDestinationFinalize(encoder))
let authored = imageBytes as Data, imported = root.appendingPathComponent("Imported.png")
try authored.write(to: imported)
var draft = try await host.personalStore.inspect([source, imported]); draft.entry.category = "Games"
let entry = try await host.personalStore.save(draft, coverPNG: authored)
let directory = host.personalDirectory(entry), working = directory.appendingPathComponent("Working/GAME.dsk")
var saved = original; saved[0] ^= 1; try saved.write(to: working)
await host.load(from: fixture, catalogLoader: { _ in Self.catalog })
let authority = CompanionLibraryAuthority(model: host), service = AuthorityLibrary(authority: authority)
let client = SoftwareLibraryModel(companion: service) { _ in XCTFail("Artwork browsing must not insert media.") }
await client.load()
let release = try XCTUnwrap(client.catalog?.releases.first { $0.id == entry.releaseID })
let asset = try XCTUnwrap(release.assets.first { $0.kind == "cover" })
XCTAssertEqual(release.assets.filter { $0.kind == "cover" }.count, 1)
XCTAssertEqual(asset.name, "Personal Cover Image")
XCTAssertTrue(asset.id.contains(":asset:PersonalCovers/"))
XCTAssertTrue(SoftwareLibraryArtworkCache.canDisplay(asset))
let local = try XCTUnwrap(asset.thumbnailURL), retainedCover = try Data(contentsOf: local)
let thumbnail = try await service.libraryRequest(.init(operation: .thumbnail, assetID: asset.id))
let decoded = try XCTUnwrap(SoftwareLibraryArtworkCache.image(from: XCTUnwrap(thumbnail.assetData)))
XCTAssertEqual(decoded.width, 24); XCTAssertEqual(decoded.height, 36)
// Even an otherwise selected local asset must retain its recorded hash.
var changed = retainedCover; changed[changed.count - 1] ^= 1; try changed.write(to: local)
await assertFailure(authority, .init(operation: .thumbnail, assetID: asset.id))
try retainedCover.write(to: local)
let oldClient = try await service.libraryRequest(.init(operation: .snapshot, personalTitlesVersion: nil))
XCTAssertFalse(oldClient.snapshot!.catalog.titles.contains { $0.id == entry.titleID })
let beforeRemoval = try await service.libraryRequest(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk"))
let beforeCopy = try XCTUnwrap(beforeRemoval.exportedDiskURL)
XCTAssertEqual(try Data(contentsOf: beforeCopy), saved)
host.query.scope = .personal; host.selection = entry.titleID
host.selectPersonalCover(.categoryIcon, for: entry)
for _ in 0..<100 where host.personalSaving { try await Task.sleep(nanoseconds: 20_000_000) }
XCTAssertFalse(host.personalSaving); XCTAssertNil(host.personalError)
let reopened = SoftwareLibraryModel(companion: service) { _ in XCTFail("Removing artwork must not insert media.") }
await reopened.load()
let withoutCover = try XCTUnwrap(reopened.catalog?.releases.first { $0.id == entry.releaseID })
XCTAssertTrue(withoutCover.assets.filter { $0.thumbnailURL != nil }.isEmpty,
"Removal must suppress the imported image as well, leaving the category illustration.")
XCTAssertEqual(SoftwareLibraryCategoryStyle.symbol(for: LibraryBrowseQuery.type(of: withoutCover)), "gamecontroller")
XCTAssertEqual(withoutCover.packageSHA256, release.packageSHA256)
await assertFailure(authority, .init(operation: .thumbnail, assetID: asset.id))
let afterRemoval = try await service.libraryRequest(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk"))
let afterCopy = try XCTUnwrap(afterRemoval.exportedDiskURL)
XCTAssertNotEqual(beforeCopy, afterCopy)
XCTAssertEqual(try Data(contentsOf: afterCopy), saved)
XCTAssertEqual(try Data(contentsOf: beforeCopy), saved)
XCTAssertEqual(try Data(contentsOf: working), saved)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.dsk")), original)
XCTAssertEqual(try Data(contentsOf: source), original)
XCTAssertEqual(try Data(contentsOf: local), retainedCover)
XCTAssertEqual(try Data(contentsOf: imported), authored)
await client.shutdown(); await reopened.shutdown(); await host.shutdown()
}
@MainActor
private func assertFailure(_ authority: CompanionLibraryAuthority, _ request: CompanionLibraryRequest,
file: StaticString = #filePath, line: UInt = #line) async {
do { _ = try await authority.handle(request); XCTFail("Expected refusal for \(request.operation)", file: file, line: line) }
catch { }
}
private actor AuthorityLibrary: CompanionLibraryAccess {
let authority: CompanionLibraryAuthority
private(set) var requests: [CompanionLibraryRequest] = []
init(authority: CompanionLibraryAuthority) { self.authority = authority }
func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse {
requests.append(request)
return try await authority.handle(request)
}
}
private actor RecoveringLibrary: CompanionLibraryAccess {
let catalog: SoftwareLibraryCatalog
private var connected = false
init(catalog: SoftwareLibraryCatalog) { self.catalog = catalog }
func reconnect() { connected = true }
func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse {
guard connected else { throw CompanionTransport.Failure.unavailable }
guard request.operation == .snapshot else { throw CompanionLibraryFailure(message: "Unexpected mutation in reconnect fixture.") }
return .init(snapshot: .init(catalog: catalog, favorites: [], preferredReleaseIDs: [:], installations: []))
}
}
private actor FakeLibrary: CompanionLibraryAccess {
let catalog: SoftwareLibraryCatalog
var favorites = Set<String>()
@@ -2,6 +2,64 @@
import XCTest
final class DebuggerMMUBridgeTests: XCTestCase {
@MainActor func testOverlayBridgeQualifiesOwnerAndRequiresFreshResidencyForSourceStep() async {
for enhanced in [false, true] {
let controller = VCCMachineController()
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
_ = await command { controller.configureMachine(use6309: enhanced, ram: 1, overclock: 1, frameInterval: 1, fastForward: false, completion: $0) }
_ = await command { controller.loadDiagnostic(use6309: enhanced, completion: $0) }
// Initial authored code setup. Guest-driven replacement itself is
// covered by the core and disposable-worker loader fixtures.
let a = Data([0x12, 0x86, 0x11, 0x39]), b = Data([0x12, 0x86, 0x22, 0x39])
_ = await command { controller.debuggerWriteMemory(address: 0x4000, data: a, completion: $0) }
_ = await command { controller.debuggerSetPC(0x4000, completion: $0) }
_ = await command { controller.debuggerSetBreakpoints([0x4567], completion: $0) }
let initial = await capture(controller, includePhysical: false)
let physical = Int(initial.mmu.effective[2].sourceAddress / 8192)
let modules: [[String: Any]] = [("a", a), ("b", b)].map { name, bytes in
["id": name, "pages": [["logicalPage": 2, "physicalPage": physical]],
"addresses": [0x4000], "bytes": [bytes], "breakpoints": [],
"overlay_group": "stage", "overlay_owner": name]
}
let armed = await command { controller.debuggerArmBankedDevelopmentBreakpoints([], modules: modules, completion: $0) }
XCTAssertNil(armed.errorMessage); XCTAssertTrue(armed.debuggerDevelopmentAttached)
XCTAssertNotEqual(armed.debuggerResidencyFingerprint, 0)
var malformed = modules
malformed[0].removeValue(forKey: "overlay_owner")
let invalid = await command { controller.debuggerArmBankedDevelopmentBreakpoints([], modules: malformed, completion: $0) }
XCTAssertNotNil(invalid.errorMessage)
XCTAssertEqual(invalid.debuggerResidencyFingerprint, armed.debuggerResidencyFingerprint)
for key in ["overlay_group", "overlay_owner"] {
var definitions = modules; definitions[0][key] = "a\0truncated"
let rejectedDefinitions = definitions
let rejected = await command { controller.debuggerArmBankedDevelopmentBreakpoints([], modules: rejectedDefinitions, completion: $0) }
XCTAssertNotNil(rejected.errorMessage)
XCTAssertEqual(rejected.debuggerResidencyFingerprint, armed.debuggerResidencyFingerprint)
}
func step(_ fingerprint: UInt64) async -> VCCMachineSnapshot {
await command {
controller.debuggerStepBankedSource(mode: 0, addresses: [0x4000,0x4001,0x4000,0x4001], locations: [1,2,3,4],
bytes: [Data([0x12]),Data([0x86,0x11]),Data([0x12]),Data([0x86,0x22])],
moduleIdentifiers: ["a","a","b","b"], generation: armed.generation,
programRevision: armed.debuggerProgramRevision, mappingFingerprint: armed.debuggerMappingFingerprint,
residencyFingerprint: fingerprint, programCounter: 0x4000, completion: $0)
}
}
let stale = await step(armed.debuggerResidencyFingerprint &+ 1)
XCTAssertNotNil(stale.errorMessage); XCTAssertEqual(stale.cycles, armed.cycles)
let started = await step(armed.debuggerResidencyFingerprint)
XCTAssertNil(started.errorMessage)
var stopped = started
for _ in 0..<100 where stopped.state == .running {
try? await Task.sleep(for: .milliseconds(5)); stopped = await command(controller.snapshot)
}
XCTAssertEqual(stopped.state, .paused); XCTAssertEqual(stopped.programCounter, 0x4001)
XCTAssertEqual(stopped.debuggerResidencyFingerprint, armed.debuggerResidencyFingerprint)
let final = await capture(controller, includePhysical: false)
XCTAssertEqual(final.breakpoints.map(\.uint16Value), [0x4567])
_ = await command(controller.shutdown)
}
}
@MainActor func testBankedGuardBridgeFreezesModulesAndPreservesManualPoints() async {
let controller = VCCMachineController()
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
@@ -41,7 +99,8 @@ final class DebuggerMMUBridgeTests: XCTestCase {
controller.debuggerStepBankedSource(mode: 0, addresses: [0x4000,0x4001], locations: [1,2],
bytes: [Data([0x12]),Data([0x20,0xfe])], moduleIdentifiers: ["resident","resident"],
generation: armed.generation, programRevision: armed.debuggerProgramRevision,
mappingFingerprint: armed.debuggerMappingFingerprint &+ 1, programCounter: 0x4000, completion: $0)
mappingFingerprint: armed.debuggerMappingFingerprint &+ 1,
residencyFingerprint: armed.debuggerResidencyFingerprint, programCounter: 0x4000, completion: $0)
}
XCTAssertNotNil(stale.errorMessage); XCTAssertEqual(stale.state, .paused)
let cleared = await command(controller.debuggerClearDevelopmentBreakpoints)
+149 -1
View File
@@ -1,7 +1,155 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import AppKit
final class InputTests: XCTestCase {
private func inputStore() throws -> InputSettingsStore {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("InputSelection-" + UUID().uuidString)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
addTeardownBlock { try? FileManager.default.removeItem(at: directory) }
return InputSettingsStore(url: directory.appendingPathComponent("input.json"))
}
func testSoleControllerPolicyPreservesOtherSourcesAndRememberedAssignments() {
for source in JoystickSource.allCases {
var settings = InputSettings(); settings.right.source = source
settings.right.interface = .tandy; settings.right.rightStick = true
settings.right.fire1 = 4; settings.right.fire2 = 8; settings.right.deadZone = 0.3
settings.left.source = .controller; settings.left.device = "disconnected-remembered"
XCTAssertEqual(settings.assigningSoleController([]), settings)
XCTAssertEqual(settings.assigningSoleController(["first", "second"]), settings)
let selected = settings.assigningSoleController(["sole"])
var expected = settings
if source == .controller { expected.right.device = "sole" }
XCTAssertEqual(selected, expected)
var remembered = settings; remembered.right.device = "previous-controller"
XCTAssertEqual(remembered.assigningSoleController(["sole"]), remembered)
}
}
@MainActor func testSelectingControllerWithSoleCachedDevicePersistsOnceAndReopens() throws {
_ = NSApplication.shared
let store = try inputStore()
var settings = InputSettings(); settings.right.source = .keyboard
settings.right.interface = .tandy; settings.right.rightStick = true
settings.right.fire1 = 4; settings.right.fire2 = 1; settings.right.deadZone = 0.25
try store.save(settings)
let device = ControllerReading(id: "gc:authored:0", name: "Authored controller", rx: 1, ry: -1, buttons: 8)
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [device] }, automaticallyPoll: false)
hub.poll()
XCTAssertEqual(hub.epoch, 0)
hub.settings.right.source = .controller
settings.right.source = .controller; settings.right.device = device.id
XCTAssertEqual(hub.settings, settings)
XCTAssertEqual(hub.epoch, 1, "One effective settings edit must release and persist once")
XCTAssertEqual(try store.load(), settings)
XCTAssertFalse(try store.loadState().automaticRightController)
hub.poll()
XCTAssertEqual(hub.preview[0], JoystickSample(x: 16383, y: 0, buttons: 1))
let stamp = Date(timeIntervalSince1970: 1234)
try FileManager.default.setAttributes([.modificationDate: stamp], ofItemAtPath: store.url.path)
for _ in 0..<8 { hub.poll() }
XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: store.url.path)[.modificationDate] as? Date, stamp)
let reopened = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [device] }, automaticallyPoll: false)
reopened.poll()
XCTAssertEqual(reopened.settings, settings); XCTAssertEqual(reopened.epoch, 0)
XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: store.url.path)[.modificationDate] as? Date, stamp)
}
@MainActor func testUnassignedControllerAdoptsLateDeviceButNeverStealsDisconnectedAssignment() throws {
_ = NSApplication.shared
let store = try inputStore()
var settings = InputSettings(); settings.right.source = .controller
try store.save(settings)
var observed: [ControllerReading] = []
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false)
hub.poll(); XCTAssertEqual(hub.settings, settings); XCTAssertEqual(hub.epoch, 0)
observed = [ControllerReading(id: "hid:authored:one", name: "First"), ControllerReading(id: "gc:authored:two", name: "Second")]
hub.poll(); XCTAssertEqual(hub.settings.right.device, ""); XCTAssertEqual(hub.epoch, 0)
observed.removeLast(); hub.poll()
XCTAssertEqual(hub.settings.right.device, "hid:authored:one"); XCTAssertEqual(hub.epoch, 1)
observed = [ControllerReading(id: "gc:authored:two", name: "Other", x: 1, buttons: 3)]
hub.poll()
XCTAssertEqual(hub.settings.right.device, "hid:authored:one")
XCTAssertEqual(hub.preview[0], JoystickSample()); XCTAssertEqual(hub.epoch, 1)
XCTAssertEqual(try store.load(), hub.settings)
}
@MainActor func testFreshMouseFallbackSurvivesStoreRecreationThenAdoptsSoleController() throws {
_ = NSApplication.shared
let immediateStore = try inputStore()
let immediate = InputHub(controller: VCCMachineController(), store: immediateStore,
controllerReadings: { [ControllerReading(id: "connected-at-launch", name: "Sole")] }, automaticallyPoll: false)
immediate.poll()
XCTAssertEqual(immediate.settings.right.source, .controller)
XCTAssertEqual(immediate.settings.right.device, "connected-at-launch")
XCTAssertEqual(immediate.settings.left.source, .none)
XCTAssertEqual(try immediateStore.load(), immediate.settings)
let store = try inputStore()
var observed: [ControllerReading] = []
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false)
XCTAssertEqual(hub.settings, .freshDefaults)
hub.poll(); XCTAssertEqual(hub.settings.right.source, .mouse); XCTAssertEqual(hub.settings.left.source, .none)
observed = [ControllerReading(id: "one", name: "First"), ControllerReading(id: "two", name: "Second")]
hub.poll(); XCTAssertEqual(hub.settings.right.source, .mouse)
hub.settings.keyboard = .compact
XCTAssertTrue(try store.loadState().automaticRightController)
let reopened = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false)
observed.removeLast(); reopened.poll()
XCTAssertEqual(reopened.settings.right.source, .controller); XCTAssertEqual(reopened.settings.right.device, "one")
XCTAssertEqual(reopened.settings.keyboard, .compact); XCTAssertEqual(reopened.settings.left.source, .none)
XCTAssertFalse(try store.loadState().automaticRightController)
}
@MainActor func testLegacyExplicitSourcesAndPersonalProfileOverrideFreshAutomaticDefault() throws {
_ = NSApplication.shared
let sole = ControllerReading(id: "one", name: "Sole")
for source in [JoystickSource.none, .keyboard, .mouse] {
let store = try inputStore()
var settings = InputSettings(); settings.right.source = source
// Exact previous-format document has no automatic-default marker.
try JSONEncoder().encode(settings).write(to: store.url)
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [sole] }, automaticallyPoll: false)
hub.poll(); XCTAssertEqual(hub.settings, settings); XCTAssertEqual(hub.epoch, 0)
}
let store = try inputStore()
var observed: [ControllerReading] = []
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false)
hub.applyProfileSettings(.freshDefaults)
XCTAssertFalse(try store.loadState().automaticRightController, "An explicit profile's Mouse source is authoritative even when it matches the fresh fallback")
observed = [sole]; hub.poll(); XCTAssertEqual(hub.settings.right.source, .mouse)
hub.restoreDefaultSettings(); hub.poll()
XCTAssertEqual(hub.settings.right.source, .controller); XCTAssertEqual(hub.settings.right.device, sole.id)
XCTAssertEqual(hub.settings.left.source, .none)
hub.settings.right = PortSettings(source: .mouse)
hub.poll()
XCTAssertEqual(hub.settings.right.source, .mouse)
XCTAssertFalse(try store.loadState().automaticRightController, "An explicit right-port edit must end fresh automatic discovery")
}
@MainActor func testLibraryHintsPreserveUnchangedFreshRightPolicyAcrossReload() throws {
_ = NSApplication.shared
let store = try inputStore()
let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [] }, automaticallyPoll: false)
var librarySettings = hub.settings
librarySettings.left.source = .keyboard
hub.applyLibrarySettings(librarySettings)
XCTAssertEqual(try store.load(), librarySettings)
XCTAssertTrue(try store.loadState().automaticRightController)
let reopened = InputHub(controller: VCCMachineController(), store: store,
controllerReadings: { [ControllerReading(id: "late", name: "Sole")] }, automaticallyPoll: false)
reopened.poll()
XCTAssertEqual(reopened.settings.right.source, .controller)
XCTAssertEqual(reopened.settings.right.device, "late")
XCTAssertEqual(reopened.settings.left, librarySettings.left)
XCTAssertFalse(try store.loadState().automaticRightController)
// A library action must not re-enable discovery after an explicit
// personal profile selected Mouse, even if all its values match.
reopened.applyProfileSettings(.freshDefaults)
reopened.applyLibrarySettings(.freshDefaults)
reopened.poll()
XCTAssertEqual(reopened.settings.right.source, .mouse)
XCTAssertFalse(try store.loadState().automaticRightController)
}
func testKeyboardModesAndReservedNavigation() {
var keyboard = CocoKeyboard()
keyboard.mode = .coco
@@ -194,7 +342,7 @@ final class InputTests: XCTestCase {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
defer { try? FileManager.default.removeItem(at: directory) }
let store = InputSettingsStore(url: directory.appendingPathComponent("input.json"))
XCTAssertEqual(try store.load(), InputSettings())
XCTAssertEqual(try store.load(), .freshDefaults)
var settings = InputSettings(); settings.keyboard = .compact
settings.right.source = .controller; settings.right.device = "authored controller"
settings.right.interface = .tandy; settings.left.source = .keyboard; settings.left.keys = .wasd
@@ -0,0 +1,324 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import AppKit
import CryptoKit
import Foundation
import PDFKit
import WebKit
import XCTest
import SQLite3
@MainActor
final class LibraryContinuityTests: XCTestCase {
private var directory: URL!
override func setUpWithError() throws {
directory = FileManager.default.temporaryDirectory.appendingPathComponent("LibraryContinuity-" + UUID().uuidString)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)
}
override func tearDownWithError() throws { try FileManager.default.removeItem(at: directory) }
func testBrowseReadingAndIndependentBookmarksRoundTripAcrossRelaunch() async throws {
let store = LibraryContinuityStore(directory: directory)
var browse = LibraryBrowseState()
browse.scope = "Games"; browse.query = "adventure"; browse.selectedID = "personal:one"
browse.filters = ["format":"disk", "sort":"name"]; browse.topVisibleID = "personal:two"
store.setBrowse(browse, for: "software-main")
let first = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/chapter.html", anchor: "alpha", offset: 0.25)
let second = LibraryReadingPosition(documentID: "book-two", relativePath: "book-two/chapter.html", anchor: "beta", offset: 0.5)
let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "Book One", sectionTitle: "Alpha", position: first))
store.setReading(second, for: "manual-last")
store.renameBookmark(mark.id, label: "My reference")
await store.flush()
let restored = LibraryContinuityStore(directory: directory)
XCTAssertEqual(restored.browse(for: "software-main"), browse)
XCTAssertEqual(restored.reading(for: "manual-last"), second)
XCTAssertEqual(restored.bookmarks.first?.position, first)
XCTAssertEqual(restored.bookmarks.first?.displayName, "My reference")
}
func testDuplicateBookmarkPreservesOriginalLabelAndPosition() async throws {
let store = LibraryContinuityStore(directory: directory)
let position = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/a.html", anchor: "section", offset: 0.2)
let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "One", sectionTitle: "Section", position: position))
store.renameBookmark(mark.id, label: "Keep this")
var moved = position; moved.offset = 0.8
let again = store.addBookmark(bookID: "book-one", bookTitle: "One", sectionTitle: "New heading", position: moved)
XCTAssertEqual(again?.id, mark.id)
XCTAssertEqual(store.bookmarks.count, 1)
XCTAssertEqual(store.bookmarks.first?.position.offset, 0.2)
XCTAssertEqual(store.bookmarks.first?.label, "Keep this")
store.removeBookmark(mark.id)
await store.flush()
XCTAssertTrue(LibraryContinuityStore(directory: directory).bookmarks.isEmpty)
}
func testNewerOrUnreadableStateIsNeverOverwritten() async throws {
let file = directory.appendingPathComponent("LibraryContinuity.json")
for bytes in [Data("{\"version\":999,\"browse\":{},\"reading\":{},\"bookmarks\":[]}".utf8), Data("invalid json".utf8)] {
try bytes.write(to: file, options: .atomic)
let store = LibraryContinuityStore(directory: directory)
XCTAssertNotNil(store.saveError)
store.setBrowse(LibraryBrowseState(), for: "archive-main")
await store.flush()
XCTAssertEqual(try Data(contentsOf: file), bytes)
}
}
func testInvalidPositionsCannotEscapeContentRootOrPersistNonfiniteValues() async throws {
let store = LibraryContinuityStore(directory: directory)
store.setReading(LibraryReadingPosition(documentID: "one", relativePath: "../private.html"), for: "bad-path")
store.setReading(LibraryReadingPosition(documentID: "one", offset: .nan), for: "bad-offset")
var browse = LibraryBrowseState(); browse.pageOffset = -1
store.setBrowse(browse, for: "bad-browse")
await store.flush()
XCTAssertNil(store.reading(for: "bad-path")); XCTAssertNil(store.reading(for: "bad-offset"))
XCTAssertNil(store.browse(for: "bad-browse"))
}
func testManualScrollBookmarkAndResumeUseStableSectionInSeparateReader() async throws {
_ = NSApplication.shared
let contentRoot = directory.appendingPathComponent("Manuals")
let book = contentRoot.appendingPathComponent("book-one")
try FileManager.default.createDirectory(at: book, withIntermediateDirectories: true)
let page = book.appendingPathComponent("chapter.html")
try """
<!doctype html><html><head><title>One</title></head><body>
<nav class="crumb"><a href="../index.html">Library</a><a href="template.html">Book One</a></nav>
<article><h1>Chapter</h1><section id="alpha" style="height:1400px"><h2>Alpha</h2></section>
<section id="beta" style="height:1400px"><h2>Beta</h2></section></article>
</body></html>
""".write(to: page, atomically: true, encoding: .utf8)
try "<html><body>Home</body></html>".write(to: contentRoot.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
let reader = ManualReader(content: ManualLibraryContent(root: contentRoot), continuity: store)
reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
reader.webView.loadFileURL(page, allowingReadAccessTo: contentRoot)
try await waitFor { reader.currentPosition?.relativePath == "book-one/chapter.html" }
_ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100);window.vccLibraryCheckpoint();")
try await waitFor { reader.currentPosition?.anchor == "beta" }
reader.bookmarkCurrentLocation()
try await waitFor { store.bookmarks.count == 1 }
XCTAssertEqual(store.bookmarks.first?.sectionTitle, "Beta")
await store.flush()
let restoredStore = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
let reopened = ManualReader(content: ManualLibraryContent(root: contentRoot), continuity: restoredStore)
reopened.webView.frame = reader.webView.frame
reopened.resume()
try await waitFor { reopened.currentPosition?.anchor == "beta" }
XCTAssertGreaterThan(reopened.currentPosition?.offset ?? 0, 0)
XCTAssertEqual(reopened.currentBookTitle, "Book One")
XCTAssertEqual(restoredStore.bookmarks.count, 1)
}
func testImmediateBookmarkSamplesFreshScrollAndIgnoresSupersedingNavigation() async throws {
_ = NSApplication.shared
let root = directory.appendingPathComponent("Manuals")
let book = root.appendingPathComponent("book-one")
try FileManager.default.createDirectory(at: book, withIntermediateDirectories: true)
let page = book.appendingPathComponent("chapter.html")
try """
<!doctype html><html><head><title>One</title></head><body>
<article><h1>Chapter</h1><section id="alpha" style="height:1400px"><h2>Alpha</h2></section>
<section id="beta" style="height:1400px"><h2>Beta</h2></section></article>
</body></html>
""".write(to: page, atomically: true, encoding: .utf8)
try "<html><body>Home</body></html>".write(to: root.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State"))
let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store)
reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
reader.webView.loadFileURL(page, allowingReadAccessTo: root)
try await waitFor { reader.currentPosition != nil }
XCTAssertNotEqual(reader.currentPosition?.anchor, "beta")
// Deliberately do not call the checkpoint or wait for its one-second
// scroll timer before performing the user's bookmark action.
_ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100)")
reader.bookmarkCurrentLocation()
try await waitFor { store.bookmarks.count == 1 }
XCTAssertEqual(store.bookmarks[0].position.anchor, "beta")
XCTAssertEqual(store.bookmarks[0].sectionTitle, "Beta")
XCTAssertGreaterThan(store.bookmarks[0].position.offset, 0)
store.removeBookmark(store.bookmarks[0].id)
reader.bookmarkCurrentLocation()
reader.showHome()
try await waitFor { reader.currentPosition?.relativePath == "index.html" }
XCTAssertTrue(store.bookmarks.isEmpty, "A checkpoint from a superseded page must not create a bookmark")
}
func testArchiveDeepLinkFindsExactDocumentOutsideFirstBrowseBatch() async throws {
let database = directory.appendingPathComponent("Archive.sqlite")
var handle: OpaquePointer?
XCTAssertEqual(sqlite3_open(database.path, &handle), SQLITE_OK)
defer { sqlite3_close(handle) }
var sql = """
PRAGMA application_id=0x56434341; PRAGMA user_version=2;
CREATE TABLE document(id INTEGER PRIMARY KEY,sha256 TEXT,title TEXT,collection TEXT,format TEXT,source_url TEXT,page_count INTEGER,issue_year TEXT);
"""
for n in 0..<72 {
let digest = String(format: "%064x", n+1)
sql += "INSERT INTO document VALUES(\(n+1),'\(digest)','Title \(String(format: "%03d", n))','Books','text','https://colorcomputerarchive.com/repo/Documents/Books/\(n).txt',1,NULL);"
}
XCTAssertEqual(sqlite3_exec(handle, sql, nil, nil, nil), SQLITE_OK)
let catalog = ArchiveLibraryCatalog(url: database)
let digest = String(format: "%064x", 61)
let exact = try await catalog.document(id: digest)
XCTAssertEqual(exact?.title, "Title 060")
let offset = try await catalog.browseOffset(documentID: digest, collection: "Books", batchSize: 35)
XCTAssertEqual(offset, 35)
let rows = try await catalog.browse(collection: "Books", limit: 35, offset: offset ?? 0)
XCTAssertTrue(rows.contains { $0.id == digest })
let malformed = try await catalog.document(id: "not-a-content-identity")
XCTAssertNil(malformed)
}
func testTwoBookReadingPositionsAndBookmarksSurviveReaderAndStoreRecreation() async throws {
_ = NSApplication.shared
let root = try makeTwoBookManuals()
let state = directory.appendingPathComponent("State")
let store = LibraryContinuityStore(directory: state)
let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store)
reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
for book in ["book-one", "book-two"] {
reader.webView.loadFileURL(root.appendingPathComponent(book + "/chapter.html"), allowingReadAccessTo: root)
try await waitFor { reader.currentBookID == book }
_ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100);window.vccLibraryCheckpoint();")
try await waitFor { reader.currentPosition?.anchor == "beta" }
reader.bookmarkCurrentLocation()
try await waitFor { store.bookmarks.contains { $0.bookID == book } }
}
let originalBookmarks = store.bookmarks
func assertSavedBookmarks(_ actual: [ManualBookmark], file: StaticString = #filePath, line: UInt = #line) {
// Successful navigation may update location validation metadata;
// the user's saved identity, label and position must stay fixed.
XCTAssertEqual(actual.map(\.id), originalBookmarks.map(\.id), file: file, line: line)
XCTAssertEqual(actual.map(\.position), originalBookmarks.map(\.position), file: file, line: line)
XCTAssertEqual(actual.map(\.displayName), originalBookmarks.map(\.displayName), file: file, line: line)
}
let firstPosition = try XCTUnwrap(store.reading(for: "manual-book:book-one"))
let secondPosition = try XCTUnwrap(store.reading(for: "manual-book:book-two"))
XCTAssertNotEqual(firstPosition.relativePath, secondPosition.relativePath)
await store.flush()
let recreatedStore = LibraryContinuityStore(directory: state)
let reopened = ManualReader(content: ManualLibraryContent(root: root), continuity: recreatedStore)
reopened.webView.frame = reader.webView.frame
reopened.resume()
try await waitFor { reopened.currentBookID == "book-two" && reopened.currentPosition?.anchor == "beta" }
XCTAssertEqual(recreatedStore.reading(for: "manual-book:book-one"), firstPosition)
assertSavedBookmarks(recreatedStore.bookmarks)
// An explicit bookmark in another book wins over the last-active book.
reopened.openBookmark(try XCTUnwrap(originalBookmarks.first { $0.bookID == "book-one" }))
try await waitFor { reopened.currentBookID == "book-one" && reopened.currentPosition?.anchor == "beta" }
_ = try await reopened.webView.evaluateJavaScript("window.scrollTo(0,0);window.vccLibraryCheckpoint();")
try await waitFor { reopened.currentPosition?.anchor == nil }
assertSavedBookmarks(recreatedStore.bookmarks)
XCTAssertEqual(recreatedStore.reading(for: "manual-book:book-two"), secondPosition)
reopened.showHome()
try await waitFor { reopened.currentPosition?.relativePath == "index.html" }
reopened.resume()
XCTAssertEqual(reopened.currentPosition?.relativePath, "index.html", "Explicit Library Home must not be replaced by automatic resume")
await recreatedStore.flush()
assertSavedBookmarks(LibraryContinuityStore(directory: state).bookmarks)
}
func testUpdatedManualMissingSectionAndPagePreserveBookmarksWithoutOpeningOtherContent() async throws {
_ = NSApplication.shared
let root = try makeTwoBookManuals()
let state = directory.appendingPathComponent("State")
let store = LibraryContinuityStore(directory: state)
let position = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/chapter.html", anchor: "removed-section", offset: 0.7)
let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "Book One", sectionTitle: "Removed section", position: position))
store.renameBookmark(mark.id, label: "Keep my reference")
let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store)
reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600)
reader.openBookmark(mark)
try await waitFor { reader.error?.contains("Location changed") == true }
XCTAssertEqual(reader.webView.url?.lastPathComponent, "chapter.html")
let fallbackScroll = try await reader.webView.evaluateJavaScript("window.scrollY") as? Double
XCTAssertEqual(fallbackScroll, 0)
XCTAssertFalse(reader.bookmarkAvailable(try XCTUnwrap(store.bookmarks.first)))
await store.flush()
let preserved = try XCTUnwrap(LibraryContinuityStore(directory: state).bookmarks.first)
XCTAssertEqual(preserved.id, mark.id)
XCTAssertEqual(preserved.position, position)
XCTAssertEqual(preserved.displayName, "Keep my reference")
XCTAssertEqual(preserved.locationChanged, true)
reader.showHome()
try await waitFor { reader.currentPosition?.relativePath == "index.html" }
try FileManager.default.removeItem(at: root.appendingPathComponent("book-one/chapter.html"))
reader.openBookmark(preserved)
XCTAssertTrue(reader.error?.contains("page is no longer") == true)
XCTAssertEqual(reader.currentPosition?.relativePath, "index.html")
XCTAssertEqual(store.bookmarks.first?.position, position)
XCTAssertEqual(store.bookmarks.count, 1)
}
func testLegacyArchivePageMigratesToPersistentStateIndependentOfAssetCache() async throws {
let pdf = PDFDocument()
for color in [NSColor.white, .gray] {
let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in color.setFill(); rect.fill(); return true }
pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: pdf.pageCount)
}
let bytes = try XCTUnwrap(pdf.dataRepresentation())
let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()
let key = "archive-library.page." + digest
let original = UserDefaults.standard.object(forKey: key)
defer {
if let original { UserDefaults.standard.set(original, forKey: key) }
else { UserDefaults.standard.removeObject(forKey: key) }
}
UserDefaults.standard.set(2, forKey: key)
let cached = directory.appendingPathComponent(digest + ".pdf")
try bytes.write(to: cached)
let state = directory.appendingPathComponent("State")
let store = LibraryContinuityStore(directory: state)
let reader = ArchiveReaderModel(remembersPage: true, cache: ArchiveAssetCache(directory: directory), continuity: store)
defer { reader.reset() }
reader.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300)
let item = ArchiveDocument(id: digest, title: "Migration fixture", collection: "Books",
sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Migration.pdf")!, memberPath: nil,
pageCount: 2, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Migration.pdf")!, deliveryBytes: Int64(bytes.count))
reader.open(item, page: reader.savedPage(for: digest), resumePosition: true)
try await waitFor { reader.progress == nil }
XCTAssertNil(reader.error)
XCTAssertEqual(reader.page, 2)
reader.reset()
await store.flush()
// Clearing an asset cache or moving away from old preferences must not
// clear the user's newly migrated reading position.
try FileManager.default.removeItem(at: cached)
UserDefaults.standard.removeObject(forKey: key)
let recreated = LibraryContinuityStore(directory: state)
let reopened = ArchiveReaderModel(remembersPage: true, cache: ArchiveAssetCache(directory: directory), continuity: recreated)
defer { reopened.reset() }
XCTAssertEqual(reopened.savedPage(for: digest), 2)
XCTAssertEqual(recreated.reading(for: "archive:" + digest)?.documentID, digest)
XCTAssertFalse(FileManager.default.fileExists(atPath: cached.path))
}
private func makeTwoBookManuals() throws -> URL {
let root = directory.appendingPathComponent("Manuals")
for book in ["book-one", "book-two"] {
let folder = root.appendingPathComponent(book)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
try """
<!doctype html><html><head><title>\(book)</title></head><body>
<nav class="crumb"><a href="../index.html">Library</a><a href="template.html">\(book)</a></nav>
<article><h1>Chapter</h1><section id="alpha" style="height:1400px"><h2>Alpha</h2></section>
<section id="beta" style="height:1400px"><h2>Beta</h2></section></article></body></html>
""".write(to: folder.appendingPathComponent("chapter.html"), atomically: true, encoding: .utf8)
}
try "<html><body>Library Home</body></html>".write(to: root.appendingPathComponent("index.html"), atomically: true, encoding: .utf8)
return root
}
private func waitFor(_ condition: () -> Bool) async throws {
let deadline = ContinuousClock.now + .seconds(8)
while !condition() {
guard ContinuousClock.now < deadline else { XCTFail("Reader did not reach its expected state"); throw CocoaError(.fileReadUnknown) }
try await Task.sleep(for: .milliseconds(25))
}
}
}
@@ -156,11 +156,14 @@ final class MCPCallContextAccessTests: XCTestCase {
do {
try await host.exportCallContextRegression(model, at: grantFile, helperURL: worker, roms: roms)
let grant = try readGrant(grantFile)
XCTAssertEqual(grant["toolset"] as? Int, 11)
XCTAssertEqual(grant["toolset"] as? Int, 12)
XCTAssertEqual(grant["playtestVideo"] as? Bool, true)
XCTAssertEqual(grant["playtestCallContext"] as? Bool, true)
let capabilities = try await result("get_capabilities", grant: grant)
XCTAssertTrue((capabilities["tools"] as? [String])?.contains("get_call_context") == true)
XCTAssertEqual(capabilities["call_context"] as? Bool, true)
XCTAssertEqual(capabilities["banked_debug_manifest_versions"] as? [Int], [1, 2])
XCTAssertEqual(capabilities["verified_code_overlays"] as? Bool, true)
XCTAssertTrue((capabilities["build_actions"] as? [String])?.contains("disk") == true)
XCTAssertTrue((capabilities["configurations"] as? [String])?.contains("Debug") == true)
let scope: [String: Any] = ["project_id": try XCTUnwrap(capabilities["project_id"] as? String),
@@ -176,6 +179,12 @@ final class MCPCallContextAccessTests: XCTestCase {
XCTAssertEqual(running["run_id"] as? String, run)
let snapshot = try await result("get_debug_snapshot", ["run_id": run], grant: grant)
let snapshotID = try XCTUnwrap(snapshot["snapshot_id"] as? String)
XCTAssertEqual(snapshot["residency_fingerprint"] as? String, "0", "Ordinary flat runs retain their existing identity")
let range = try XCTUnwrap((snapshot["memory_ranges"] as? [[String: Int]])?.first)
let memoryArguments: [String: Any] = ["run_id": run, "snapshot_id": snapshotID,
"address": try XCTUnwrap(range["address"]), "count": min(8, try XCTUnwrap(range["count"]))]
let frozenRead = try await result("read_debug_memory", memoryArguments, grant: grant)
XCTAssertFalse((frozenRead["bytes"] as? [Int] ?? []).isEmpty)
let arguments: [String: Any] = ["run_id": run, "snapshot_id": snapshotID]
let context = try await result("get_call_context", arguments, grant: grant)
XCTAssertEqual(context["run_id"] as? String, run)
@@ -203,6 +212,8 @@ final class MCPCallContextAccessTests: XCTestCase {
let repeated = try await result("get_call_context", arguments, grant: grant)
XCTAssertEqual(repeated as NSDictionary, context as NSDictionary,
"Repeated context reads preserve clock, registers, mapping and snapshot identity.")
let memoryRead = try await result("read_debug_memory", memoryArguments, grant: grant)
XCTAssertEqual(memoryRead as NSDictionary, frozenRead as NSDictionary)
}
for invalid in [arguments.merging(["run_id": "ordinary-shared-run"]) { _, new in new },
arguments.merging(["snapshot_id": "stale-snapshot"]) { _, new in new },
@@ -213,11 +224,78 @@ final class MCPCallContextAccessTests: XCTestCase {
_ = try await result("playtest_debug", ["run_id": run, "request_id": UUID().uuidString, "action": "step"], grant: grant)
let staleAfterStep = try await request("get_call_context", arguments, grant: grant)
XCTAssertNotNil(staleAfterStep["error"])
let staleMemory = try await request("read_debug_memory", memoryArguments, grant: grant)
XCTAssertNotNil(staleMemory["error"])
let newer = try await result("get_debug_snapshot", ["run_id": run], grant: grant)
let newerArguments: [String: Any] = ["run_id": run, "snapshot_id": try XCTUnwrap(newer["snapshot_id"] as? String)]
_ = try await build(scope, grant: grant)
let latestArtifact = try await build(scope, grant: grant)
let staleAfterBuild = try await request("get_call_context", newerArguments, grant: grant)
XCTAssertNotNil(staleAfterBuild["error"])
// Exercise the real stdio public schema and authenticated app host,
// not a fixture host returning a manufactured MP4 response.
let helper = Bundle(for: Self.self).bundleURL.deletingLastPathComponent().appendingPathComponent("vcc-mcp")
let clientSource = resources.deletingLastPathComponent().appendingPathComponent("Tools/MCP/test-helper.py")
var selection = scope; selection["artifact_id"] = try XCTUnwrap(latestArtifact["artifact_id"] as? String)
let selectionJSON = String(decoding: try JSONSerialization.data(withJSONObject: selection), as: UTF8.self)
let movie = root.appendingPathComponent("PublicVideo.mp4")
let script = """
import base64,hashlib,importlib.util,json,pathlib,sys,time,uuid
spec=importlib.util.spec_from_file_location('mcp_fixture',sys.argv[1])
fixture=importlib.util.module_from_spec(spec);spec.loader.exec_module(fixture)
selection=json.loads(sys.argv[4])
with fixture.Client(sys.argv[2],sys.argv[3]) as client:
client.handshake('2025-06-18')
def call(name,**args):
result=client.call(name,**args)['result']
assert not result.get('isError'), result
return result['structuredContent']
run=call('start_playtest',**selection,request_id=str(uuid.uuid4()))['run_id']
scope={k:selection[k] for k in ('project_id','revision')}
deadline=time.monotonic()+60
while True:
ready=call('get_run',**scope)
if ready['status']!='starting':
assert ready['status']=='ready', ready
break
assert time.monotonic()<deadline
time.sleep(.025)
started=call('start_playtest_video',run_id=run,request_id='begin-public-video',include_audio=False,max_fields=60)
advanced=call('playtest_input',run_id=run,request_id='public-video-input',steps=[{'keys':[],'fields':30}])
stopped=call('stop_playtest_video',run_id=run,request_id='end-public-video')
clip=stopped['video']; assert clip['completed'] and clip['fields_recorded']==30, clip
assert stopped['field_clock']==advanced['field_clock']
data=bytearray();offset=0
while True:
page=call('read_playtest_video',run_id=run,clip_id=clip['clip_id'],offset=offset,limit=65536)
data.extend(base64.b64decode(page['video_chunk_base64'],validate=True));offset=page['next_offset']
if page['eof']:break
assert len(data)==clip['byte_count'] and hashlib.sha256(data).hexdigest()==clip['sha256']
assert data[4:8]==b'ftyp'
pathlib.Path(sys.argv[5]).write_bytes(data)
retained=call('stop_playtest',run_id=run,request_id='public-video-cleanup')
assert retained['disk_retained']
print(json.dumps({'bytes':len(data),'sha256':clip['sha256'],'fields':clip['fields_recorded']}))
"""
let publicOutput = try await Task.detached {
let process = Process(), pipe = Pipe()
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
process.arguments = ["python3", "-c", script, clientSource.path, helper.path, grantFile.path, selectionJSON, movie.path]
process.standardOutput = pipe; process.standardError = pipe
let deadline = DispatchWorkItem { if process.isRunning { process.terminate() } }
DispatchQueue.global().asyncAfter(deadline: .now() + 90, execute: deadline)
defer { deadline.cancel() }
try process.run()
let output = try pipe.fileHandleForReading.readToEnd() ?? Data()
process.waitUntilExit()
guard process.terminationStatus == 0 else {
throw NSError(domain: "MCPPublicVideo", code: Int(process.terminationStatus),
userInfo: [NSLocalizedDescriptionKey: String(decoding: output, as: UTF8.self)])
}
return output
}.value
let publicVideo = try XCTUnwrap(JSONSerialization.jsonObject(with: publicOutput) as? [String: Any])
XCTAssertEqual(publicVideo["fields"] as? Int, 30)
XCTAssertEqual(publicVideo["sha256"] as? String, CMOCProject.sha256(try Data(contentsOf: movie)))
await host.revoke().value
XCTAssertFalse(FileManager.default.fileExists(atPath: grantFile.path))
// A fresh endpoint lets us check the revoked token itself, rather
@@ -292,7 +370,7 @@ final class MCPCallContextAccessTests: XCTestCase {
}.value
let observed = try XCTUnwrap(JSONSerialization.jsonObject(with: output) as? [String: Any])
let names = try XCTUnwrap(observed["tools"] as? [String])
XCTAssertEqual(names.count, 32)
XCTAssertEqual(names.count, 35)
XCTAssertTrue(names.contains("list_playtest_media")); XCTAssertTrue(names.contains("exchange_playtest_media"))
XCTAssertEqual(Set(names), Set(try XCTUnwrap(observed["host_tools"] as? [String])))
XCTAssertEqual(observed["media"] as? Bool, true)
@@ -391,11 +469,12 @@ final class MCPCallContextAccessTests: XCTestCase {
do {
try await host.exportCallContextRegression(model, at: grantFile, helperURL: worker, roms: roms)
let grant = try readGrant(grantFile)
XCTAssertEqual(grant["toolset"] as? Int, 11)
XCTAssertEqual(grant["toolset"] as? Int, 12)
XCTAssertEqual(grant["playtestVideo"] as? Bool, true)
XCTAssertEqual(grant["playtestMedia"] as? Bool, true)
let capabilities = try await result("get_capabilities", grant: grant)
XCTAssertEqual(capabilities["playtest_media_exchange"] as? Bool, true)
XCTAssertEqual((capabilities["tools"] as? [String])?.count, 32)
XCTAssertEqual((capabilities["tools"] as? [String])?.count, 35)
let scope: [String: Any] = ["project_id": try XCTUnwrap(capabilities["project_id"] as? String),
"revision": try XCTUnwrap(capabilities["revision"] as? Int)]
let artifact = try await build(scope, grant: grant)
@@ -183,6 +183,7 @@ extension MCPDebuggerInspectionTests {
("pc", 0x3101), ("registers", ["PC": 0x3100, "S": 0x7002, "U": 0x7100]),
("processor", "HD6309"), ("execution_mode", "native"), ("md_register", 1),
("mapping_fingerprint", "mapping-2"), ("program_revision", 2), ("physical_pages", ["3": 57]),
("residency_fingerprint", "changed-owner"),
("logical_memory", Data(repeating: 1, count: 65536).base64EncodedString()),
("available", Data(repeating: 0, count: 65536).base64EncodedString())] {
var changed = base; changed[key] = value
+426 -1
View File
@@ -1,8 +1,225 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import AVFoundation
import Darwin
@MainActor
final class MCPPlaytestTests: XCTestCase {
func testMissingOrChangedVideoDoesNotPreventGuestDiskRetention() async throws {
let (helper, system, diskROM) = try inputs()
for mediaEnabled in [false, true] {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCVideoDiskSafety-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let original = disk(), artifact = UUID().uuidString
let baseHash = CMOCProject.sha256(original)
let provenance = MCPPlaytestDiskStore.Provenance(projectKey: CMOCProject.sha256(Data("video-disk-safety".utf8)),
artifactID: artifact, artifactDiskSHA256: baseHash, mediaKey: mediaEnabled ? "primary" : nil,
mediaBaseSHA256: mediaEnabled ? baseHash : nil)
let media: [MCPPlaytestMedium]? = mediaEnabled ? [MCPPlaytestMedium(id: MCPPlaytestMedium.identifier(artifactID: artifact, key: "primary"),
name: "HOME.dsk", key: "primary", baseSHA256: baseHash, data: original, provenance: provenance)] : nil
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: original,
bootCommands: "10 PRINT 37\nSAVE\"TEST\"\n", projectID: "video-disk-safety", revision: 1,
artifactID: artifact, helperURL: helper, retentionDirectory: root, diskProvenance: provenance, media: media,
videoArtifactWillVerify: { clip in
// Fail exactly at first host registration, after the real
// worker finalized its MP4 and before the host reads it.
if mediaEnabled { try Data([0,1,2,3]).write(to: clip, options: .atomic) }
else { try FileManager.default.removeItem(at: clip) }
})
defer { test.invalidate() }
let savedHash = try XCTUnwrap(test.startReceipt["disk_sha256"] as? String)
XCTAssertNotEqual(savedHash, CMOCProject.sha256(original), "An ordinary guest SAVE must change the retained disk")
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin", "include_audio": false, "max_fields": 120])
let input = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "fields", "steps": [["keys": [], "fields": 3]]])
let video = try XCTUnwrap(input["video_recording"] as? [String: Any])
let id = try XCTUnwrap(video["clip_id"] as? String)
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
XCTAssertNotNil(stopped["video_retention_error"], "A separate artifact failure must remain visible")
let retained = try XCTUnwrap(test.retainedDiskURL)
XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: retained)), savedHash)
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id]) }
}
}
private func videoBytes(_ test: MCPPlaytest, metadata: [String: Any]) async throws -> Data {
let id = try XCTUnwrap(metadata["clip_id"] as? String)
let size = try XCTUnwrap(metadata["byte_count"] as? Int)
XCTAssertGreaterThan(size, 0); XCTAssertLessThanOrEqual(size, 64 * 1024 * 1024)
var data = Data(), offset = 0
while offset < size {
let arguments: [String: Any] = ["run_id": test.runID, "clip_id": id, "offset": offset, "limit": 4096]
let chunk = try await test.reply("read_playtest_video", arguments: arguments)
XCTAssertEqual(chunk["clip_id"] as? String, id)
XCTAssertEqual(chunk["offset"] as? Int, offset)
XCTAssertEqual(chunk["byte_count"] as? Int, size)
XCTAssertEqual(chunk["mime_type"] as? String, "video/mp4")
XCTAssertEqual(chunk["sha256"] as? String, metadata["sha256"] as? String)
let bytes = try XCTUnwrap((chunk["video_chunk_base64"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertFalse(bytes.isEmpty); XCTAssertLessThanOrEqual(bytes.count, 4096)
guard !bytes.isEmpty else { throw ProfileFailure.message("Empty video chunk before EOF") }
data.append(bytes); offset += bytes.count
XCTAssertEqual(chunk["next_offset"] as? Int, offset)
XCTAssertEqual(chunk["eof"] as? Bool, offset == size)
let retry = try await test.reply("read_playtest_video", arguments: arguments)
XCTAssertEqual(retry["video_chunk_base64"] as? String, chunk["video_chunk_base64"] as? String)
}
XCTAssertEqual(data.count, size); XCTAssertEqual(CMOCProject.sha256(data), metadata["sha256"] as? String)
let eof = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id, "offset": size])
XCTAssertEqual(eof["eof"] as? Bool, true); XCTAssertEqual(eof["video_chunk_base64"] as? String, "")
return data
}
private func decodedVideoAudio(_ url: URL) async throws -> (Float, Float, Int) {
let asset = AVURLAsset(url: url)
let tracks = try await asset.loadTracks(withMediaType: .audio)
let track = try XCTUnwrap(tracks.first)
let reader = try AVAssetReader(asset: asset)
let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM,
AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false])
reader.add(output); XCTAssertTrue(reader.startReading())
var minimum: Float = 1, maximum: Float = -1, count = 0
while let sample = output.copyNextSampleBuffer() {
let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample))
var data = Data(count: CMBlockBufferGetDataLength(buffer))
XCTAssertEqual(data.withUnsafeMutableBytes {
CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!)
}, noErr)
data.withUnsafeBytes { raw in
for value in raw.bindMemory(to: Float.self) { minimum = min(minimum, value); maximum = max(maximum, value); count += 1 }
}
}
XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(count, 0)
return (minimum, maximum, count)
}
func testOwnedVideoRecordsActualFieldsAudioChoiceAndRetryIdentityOnBothProcessors() async throws {
let (helper, system, diskROM) = try inputs()
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOwnedVideo-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: folder) }
for cpu in ["6809", "6309"] {
let root = folder.appendingPathComponent(cpu)
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(),
bootCommands: "10 CLS 3:PRINT \"VIDEO\"\n20 SOUND 80,255:GOTO20\nRUN\n",
projectID: "video-fixture", revision: 1, artifactID: UUID().uuidString, cpu: cpu,
helperURL: helper, retentionDirectory: root)
do {
let before = try await test.capture()
for value: Any in [0, 3601, true, 1.5] {
await expectDiskFailure {
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "invalid", "max_fields": value])
}
}
for value: Any in [1, "yes"] {
await expectDiskFailure {
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "invalid-audio", "include_audio": value])
}
}
await expectDiskFailure { _ = try await test.reply("start_playtest_video", arguments: ["run_id": "foreign", "request_id": "foreign"]) }
let afterInvalid = try await test.capture()
XCTAssertEqual(afterInvalid["field_clock"] as? Int, before["field_clock"] as? Int)
for includeAudio in [true, false] {
let key = includeAudio ? "audio" : "silent"
let starting = try await test.capture()
let startArgs: [String: Any] = ["run_id": test.runID, "request_id": "begin-" + key,
"include_audio": includeAudio, "max_fields": 120]
let started = try await test.reply("start_playtest_video", arguments: startArgs)
XCTAssertEqual(started["field_clock"] as? Int, starting["field_clock"] as? Int, "Starting video must not execute the guest")
let startRetry = try await test.reply("start_playtest_video", arguments: startArgs)
XCTAssertEqual(startRetry as NSDictionary, started as NSDictionary)
await expectDiskFailure {
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-" + key, "include_audio": !includeAudio, "max_fields": 120])
}
await expectDiskFailure {
_ = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart-" + key])
}
let inputArgs: [String: Any] = ["run_id": test.runID, "request_id": "fields-" + key,
"steps": [["keys": ["space"], "fields": 30], ["keys": [], "fields": 30]]]
let input = try await test.reply("playtest_input", arguments: inputArgs)
assertProcessor(input, cpu: cpu)
let trace = try XCTUnwrap(input["input_trace"] as? [[String: Any]])
XCTAssertEqual(trace.count, 2); XCTAssertEqual(trace[0]["fields_advanced"] as? Int, 30)
XCTAssertEqual((trace[0]["input"] as? [String: Any])?["neutral"] as? Bool, false)
XCTAssertEqual((trace[1]["input"] as? [String: Any])?["neutral"] as? Bool, true)
let inputRetry = try await test.reply("playtest_input", arguments: inputArgs)
XCTAssertEqual(inputRetry["field_clock"] as? Int, input["field_clock"] as? Int)
let stopArgs: [String: Any] = ["run_id": test.runID, "request_id": "end-" + key]
let stopped = try await test.reply("stop_playtest_video", arguments: stopArgs)
let stopRetry = try await test.reply("stop_playtest_video", arguments: stopArgs)
XCTAssertEqual(stopRetry as NSDictionary, stopped as NSDictionary)
XCTAssertEqual(stopped["field_clock"] as? Int, input["field_clock"] as? Int, "Stopping video must not execute the guest")
let video = try XCTUnwrap(stopped["video"] as? [String: Any])
XCTAssertEqual(video["include_audio"] as? Bool, includeAudio)
XCTAssertEqual(video["fields_recorded"] as? Int, 60)
XCTAssertEqual(video["truncated"] as? Bool, false)
XCTAssertEqual((video["field_end"] as? Int ?? -1) - (video["field_start"] as? Int ?? -1), 60)
let movie = root.appendingPathComponent(key + ".mp4")
try await videoBytes(test, metadata: video).write(to: movie)
let asset = AVURLAsset(url: movie)
let duration = try await asset.load(.duration).seconds
XCTAssertEqual(duration, 1, accuracy: 0.05)
let tracks = try await asset.loadTracks(withMediaType: .video)
XCTAssertEqual(tracks.count, 1)
let dimensions = try await XCTUnwrap(tracks.first).load(.naturalSize)
XCTAssertEqual(dimensions, CGSize(width: 1280, height: 960))
let generator = AVAssetImageGenerator(asset: asset)
let frame = try await generator.image(at: .zero).image
XCTAssertEqual(frame.width, 1280); XCTAssertEqual(frame.height, 960)
let samples = try await decodedVideoAudio(movie)
if includeAudio { XCTAssertGreaterThan(samples.1 - samples.0, 0.01, "A real guest SOUND program must reach the delivered MP4") }
else { XCTAssertLessThan(max(abs(samples.0), abs(samples.1)), 0.00001, "Silent video must exclude guest audio and all UI cues") }
if !includeAudio {
let id = try XCTUnwrap(video["clip_id"] as? String)
let retained = root.appendingPathComponent("Videos/\(test.runID)/\(id)/Clip.mp4")
try FileManager.default.removeItem(at: retained)
XCTAssertEqual(mkfifo(retained.path, 0o600), 0)
let began = ContinuousClock.now
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id]) }
XCTAssertLessThan(began.duration(to: .now), .seconds(2), "A replaced FIFO must not block the ownership lease before validation")
}
let clipID = try XCTUnwrap(video["clip_id"] as? String)
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": clipID, "offset": -1]) }
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": UUID().uuidString]) }
await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": "foreign", "clip_id": clipID]) }
}
let retained = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "retain"])
XCTAssertEqual(retained["disk_retained"] as? Bool, true)
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), disk())
} catch { await test.invalidate().value; throw error }
await test.invalidate().value
}
}
func testVideoFieldBoundAndRunStopRetainCompletedClipsWithoutMoreExecution() async throws {
let (helper, system, diskROM) = try inputs()
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCVideoBounds-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(),
bootCommands: "10 CLS:PRINT \"BOUNDED VIDEO\"\n20 GOTO20\nRUN\n", projectID: "video-bound", revision: 1,
artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: root)
do {
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-limit", "max_fields": 2])
let input = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "cross-limit", "steps": [["keys": [], "fields": 5]]])
let limited = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "end-limit"])
let video = try XCTUnwrap(limited["video"] as? [String: Any])
XCTAssertEqual(video["fields_recorded"] as? Int, 2); XCTAssertEqual(video["truncated"] as? Bool, true)
XCTAssertEqual(video["reason"] as? String, "field_limit"); XCTAssertEqual(video["completed"] as? Bool, true)
XCTAssertEqual(limited["field_clock"] as? Int, input["field_clock"] as? Int)
_ = try await videoBytes(test, metadata: video)
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-cleanup", "include_audio": false])
let last = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "cleanup-fields", "steps": [["keys": [], "fields": 3]]])
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "retain-with-video"])
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
XCTAssertEqual(stopped["field_clock"] as? Int, last["field_clock"] as? Int)
let finalVideo = try XCTUnwrap(stopped["video"] as? [String: Any])
XCTAssertEqual(finalVideo["fields_recorded"] as? Int, 3)
XCTAssertEqual(finalVideo["reason"] as? String, "run_stopped"); XCTAssertEqual(finalVideo["truncated"] as? Bool, false)
_ = try await videoBytes(test, metadata: finalVideo)
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), disk())
} catch { await test.invalidate().value; throw error }
await test.invalidate().value
}
func testPhysicalKeysCoverGameplayWithoutHostLayoutOrArbitraryText() {
XCTAssertEqual(MCPPlaytest.chord("left"), UInt64(1) << 29)
XCTAssertEqual(MCPPlaytest.chord("right"), UInt64(1) << 30)
@@ -551,7 +768,11 @@ final class MCPPlaytestTests: XCTestCase {
projectID: "request-limit-fixture", revision: 1, artifactID: UUID().uuidString,
helperURL: helper, retentionDirectory: folder)
defer { test.invalidate() }
for index in 0..<MCPPlaytest.mutationRequestLimit {
_ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "video-before-limit", "include_audio": false])
_ = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "video-fields", "steps": [["keys": [], "fields": 2]]])
let budget = try await test.capture()
let remaining = try XCTUnwrap(budget["remaining_mutation_requests"] as? Int)
for index in 0..<remaining {
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause-\(index)", "action": "pause"])
}
let before = try await test.capture()
@@ -560,6 +781,18 @@ final class MCPPlaytestTests: XCTestCase {
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "exhausted", "action": "step"])
XCTFail("Exhausted execution ledger accepted another mutation")
} catch { XCTAssertTrue(error.localizedDescription.contains("playtest_request_limit")) }
let finishedVideo = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "finish-video-after-limit"])
let clip = try XCTUnwrap(finishedVideo["video"] as? [String: Any])
XCTAssertEqual(clip["fields_recorded"] as? Int, 2)
_ = try await videoBytes(test, metadata: clip)
for index in 0..<32 {
do {
_ = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "extra-video-stop-\(index)"])
XCTFail("A cleanup exemption must not retain unlimited distinct stop receipts")
} catch { XCTAssertTrue(error.localizedDescription.contains("request_conflict")) }
}
let sameVideoStop = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "finish-video-after-limit"])
XCTAssertEqual(sameVideoStop as NSDictionary, finishedVideo as NSDictionary)
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
XCTAssertEqual(stopped["stop_retention_exempt"] as? Bool, true)
@@ -886,6 +1119,198 @@ final class MCPPlaytestTests: XCTestCase {
if let disk = test.retainedDiskURL { try FileManager.default.removeItem(at:disk.deletingLastPathComponent()) }
}
private enum PhysicalOverlayLoad { case complete, partial, corrupted }
/// Authored LOADM guest: real 6809 instructions copy two immutable code
/// pieces into the same physical RAM. The ROM pair still comes from the
/// selected build resources through inputs(); these bytes are not firmware.
private func physicalOverlayFixture(_ mode: PhysicalOverlayLoad) throws -> (disk: Data, modules: [[String: Any]], a: Data, b: Data) {
let a = Data([0x12, 0x86, 0x11, 0xb7, 0x50, 0x00, 0x7e, 0x11, 0x00])
let b = mode == .complete
? Data([0x12, 0x86, 0x22, 0xb7, 0x50, 0x00, 0x7e, 0x12, 0x00])
: Data([0x12, 0x86, 0x22, 0xb7, 0x50, 0x00, 0x20, 0xf8])
let witnessA = Data([0x12, 0x86, 0xa1, 0x39]), witnessB = Data([0x12, 0x86, 0xb2, 0x39])
func raw(_ code: Data, _ witness: Data) -> Data {
code + Data(repeating: 0x12, count: 0x20 - code.count) + witness
}
let rawA = raw(a, witnessA), rawB = raw(b, witnessB)
func loader(_ source: UInt16, count: Int, corruptWitness: Bool = false) -> Data {
// LDX #$4000; LDY #source; LDB #count;
// copy: LDA ,Y+; STA ,X+; DECB; BNE copy.
var code = Data([0x8e, 0x40, 0, 0x10, 0x8e, UInt8(source >> 8), UInt8(source & 255),
0xc6, UInt8(count), 0xa6, 0xa0, 0xa7, 0x80, 0x5a, 0x26, 0xf9])
if corruptWitness { code.append(contentsOf: [0x86, 0xc3, 0xb7, 0x40, 0x22]) } // Guest LDA/STA.
code.append(contentsOf: [0x7e, 0x40, 0])
return code
}
let loadA = loader(0x2000, count: rawA.count)
let loadB = loader(0x2100, count: mode == .partial ? b.count : rawB.count, corruptWitness: mode == .corrupted)
let blocks: [(UInt16, Data)] = [(0x1000, loadA), (0x1100, loadB), (0x1200, loadA), (0x2000, rawA), (0x2100, rawB)]
var binary = Data()
for (address, bytes) in blocks {
binary.append(contentsOf: [0, UInt8(bytes.count >> 8), UInt8(bytes.count & 255), UInt8(address >> 8), UInt8(address & 255)])
binary.append(bytes)
}
binary.append(contentsOf: [255, 0, 0, 0x10, 0])
guard binary.count < 256 else { throw ProfileFailure.message("The authored overlay fixture must fit one DECB sector.") }
var image = disk()
image.replaceSubrange(0..<binary.count, with: binary)
image[(17 * 18 + 1) * 256] = 0xc1
var entry = Data(repeating: 0, count: 32)
entry.replaceSubrange(0..<11, with: Data("PROBE BIN".utf8))
entry[11] = 2; entry[15] = UInt8(binary.count)
let directory = (17 * 18 + 2) * 256
image.replaceSubrange(directory..<(directory + 32), with: entry)
func guardBytes(_ address: Int, _ bytes: Data) -> [String: Any] {
["address": address, "bytes_base64": bytes.base64EncodedString()]
}
func piece(_ id: String, owner: String, address: Int, bytes: Data) -> [String: Any] {
["id": id, "overlay_group": "stage-code", "overlay_owner": owner,
"pages": [["logical_page": 2, "physical_page": 58]], "guards": [guardBytes(address, bytes)]]
}
let modules = [
piece("a-entry", owner: "A", address: 0x4000, bytes: a),
piece("a-witness", owner: "A", address: 0x4020, bytes: witnessA),
piece("b-entry", owner: "B", address: 0x4000, bytes: b),
piece("b-witness", owner: "B", address: 0x4020, bytes: witnessB),
["id": "loader", "pages": [["logical_page": 0, "physical_page": 56]],
"guards": [guardBytes(0x1000, loadA), guardBytes(0x1100, loadB), guardBytes(0x1200, loadA)]]
]
return (image, modules, a, b)
}
func testPhysicalCodeOverlayWorkerFollowsActualGuestCopiesAndRetainsDiskOnBothProcessors() async throws {
let (helper, system, diskROM) = try inputs()
let fixture = try physicalOverlayFixture(.complete)
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPhysicalOverlay-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
for cpu in ["6809", "6309"] {
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: fixture.disk,
// Buffer disk operations in one BASIC command before SAVE runs,
// so subsequent pasted characters cannot arrive during disk I/O.
bootCommands: "10 PRINT 7\nSAVE\"MARKER\":LOADM\"PROBE\":EXEC\n", projectID: "physical-overlay-worker",
revision: 1, artifactID: UUID().uuidString, modules: fixture.modules, stopAt: 0x4000,
stopModule: "a-entry", cpu: cpu, helperURL: helper, retentionDirectory: root.appendingPathComponent(cpu))
defer { test.invalidate() }
if test.startReceipt["state"] as? String != "paused" {
let screen = try await test.capture()
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "failed-start-cleanup"])
XCTFail("Overlay guest did not reach A: \(screen["screen_text"] ?? "no screen text"); PC \(screen["pc"] ?? "unknown")")
return
}
XCTAssertEqual(test.startReceipt["ram_kb"] as? Int, 512)
assertProcessor(test.startReceipt, cpu: cpu)
XCTAssertNotEqual(test.startReceipt["disk_sha256"] as? String, CMOCProject.sha256(fixture.disk), "SAVE must actually modify the disposable guest disk")
func captured(_ expected: Data, witness: UInt8) async throws -> [String: Any] {
let capture = try await test.debugCapture()
assertProcessor(capture, cpu: cpu)
XCTAssertEqual(capture["pc"] as? Int, 0x4000)
XCTAssertEqual(capture["attached"] as? Bool, true)
XCTAssertEqual((capture["physical_pages"] as? [String: Int])?["2"], 58)
let memory = try XCTUnwrap((capture["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertEqual(Data(memory[0x4000..<(0x4000 + expected.count)]), expected)
XCTAssertEqual(memory[0x4022], witness)
XCTAssertNotEqual(capture["residency_fingerprint"] as? String, "0")
return capture
}
let first = try await captured(fixture.a, witness: 0xa1)
let firstResidency = try XCTUnwrap(first["residency_fingerprint"] as? String)
func stop(_ module: String, request: String) async throws {
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": request,
"action": "stop_at", "address": 0x4000, "module_id": module, "selection": "function_entry:" + module])
let receipt = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": request + "-advance",
"steps": [["keys": [], "fields": 2]]])
XCTAssertEqual(receipt["state"] as? String, "paused")
}
// The entry opcode, logical address and physical page are identical.
// Asking for B must run past A and let the guest loader install B.
try await stop("b-entry", request: "owner-b")
let second = try await captured(fixture.b, witness: 0xb2)
XCTAssertNotEqual(second["residency_fingerprint"] as? String, firstResidency)
XCTAssertEqual(second["mapping_fingerprint"] as? String, first["mapping_fingerprint"] as? String)
XCTAssertEqual(second["program_revision"] as? Int, first["program_revision"] as? Int)
let secondMemory = try XCTUnwrap((second["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertEqual(secondMemory[0x5000], 0x11, "A executed its own guest STA before loading B")
try await stop("a-entry", request: "owner-a-again")
let third = try await captured(fixture.a, witness: 0xa1)
XCTAssertEqual(third["residency_fingerprint"] as? String, firstResidency)
let thirdMemory = try XCTUnwrap((third["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertEqual(thirdMemory[0x5000], 0x22, "B executed its own guest STA before restoring A")
let restarted = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart"])
XCTAssertEqual(restarted["boot"] as? Int, 2)
XCTAssertEqual(restarted["disk_sha256"] as? String, test.startReceipt["disk_sha256"] as? String)
XCTAssertEqual(restarted["disk_original_sha256"] as? String, CMOCProject.sha256(fixture.disk))
_ = try await captured(fixture.a, witness: 0xa1)
let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
XCTAssertEqual(stopped["disk_retained"] as? Bool, true)
let saved = try XCTUnwrap(test.retainedDiskURL)
XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: saved)), restarted["disk_sha256"] as? String)
}
}
func testPhysicalCodeOverlayWorkerRejectsPartialAndCorruptedOwnerWitnessesOnBothProcessors() async throws {
let (helper, system, diskROM) = try inputs()
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPhysicalOverlayPartial-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
for cpu in ["6809", "6309"] {
for (name, mode, witness) in [("partial", PhysicalOverlayLoad.partial, UInt8(0xa1)), ("corrupted", .corrupted, UInt8(0xc3))] {
let fixture = try physicalOverlayFixture(mode)
let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: fixture.disk,
bootCommands: "LOADM\"PROBE\":EXEC\n", projectID: "physical-overlay-invalid-worker", revision: 1,
artifactID: UUID().uuidString, modules: fixture.modules, stopAt: 0x4000, stopModule: "a-entry",
cpu: cpu, helperURL: helper, retentionDirectory: root.appendingPathComponent(cpu + "-" + name))
defer { test.invalidate() }
let valid = try await test.debugCapture()
XCTAssertEqual(valid["attached"] as? Bool, true)
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "want-b",
"action": "stop_at", "address": 0x4000, "module_id": "b-entry", "selection": "function_entry:b-entry"])
let advanced = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "load-invalid",
"steps": [["keys": [], "fields": 2]]])
XCTAssertEqual(advanced["state"] as? String, "running", "An invalid owner must not qualify B's stop")
_ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause", "action": "pause"])
let invalid = try await test.debugCapture()
assertProcessor(invalid, cpu: cpu)
XCTAssertEqual(invalid["attached"] as? Bool, false)
XCTAssertEqual(invalid["mapping_fingerprint"] as? String, valid["mapping_fingerprint"] as? String)
XCTAssertNotEqual(invalid["residency_fingerprint"] as? String, valid["residency_fingerprint"] as? String)
let pc = try XCTUnwrap(invalid["pc"] as? Int)
XCTAssertTrue((0x4000..<0x4008).contains(pc), "Pause observes the actual guest loop, not a manufactured PC")
let memory = try XCTUnwrap((invalid["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) })
XCTAssertEqual(Data(memory[0x4000..<(0x4000 + fixture.b.count)]), fixture.b, "B's entry alone is insufficient proof")
XCTAssertEqual(memory[0x4022], witness, "The guest partial copy/corruption must remain visible in the full capture")
XCTAssertEqual(memory[0x5000], 0x22)
_ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"])
}
}
}
func testPhysicalOverlayWireRejectsEmbeddedNULIdentityBeforeGuestExecution() async throws {
let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent()
let helper = ProcessInfo.processInfo.environment["VCC_TEST_PLAYTEST_HELPER"].map { URL(fileURLWithPath: $0) }
?? products.appendingPathComponent("vcc-playtest")
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: helper.path), "Requires the built, isolated vcc-playtest helper.")
let fixture = try physicalOverlayFixture(.complete)
let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOverlayWire-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
for field in ["overlay_group", "overlay_owner"] {
var modules = fixture.modules
modules[0][field] = "a\0alias"
do {
// These deliberately unusable ROM bytes must never execute.
// This is a wire validation check, not a firmware/CPU pass.
let run = try await MCPPlaytest.start(systemROM: Data(repeating: 0, count: 32768),
diskROM: Data(repeating: 0, count: 8192), disk: fixture.disk, bootCommands: "\n",
projectID: "overlay-wire-invalid", revision: 1, artifactID: UUID().uuidString,
modules: modules, stopAt: 0x4000, stopModule: "a-entry", cpu: "6809", helperURL: helper,
retentionDirectory: root.appendingPathComponent(field))
await run.invalidate().value
XCTFail("An embedded NUL in \(field) crossed the worker boundary")
} catch {
XCTAssertTrue(error.localizedDescription.contains("invalid_overlay_identity"), error.localizedDescription)
}
}
}
func testFlatOwnedStopUsesVerifiedBytesAndActualRuntimeMapping() async throws {
let (helper, system, diskROM) = try inputs()
// Guest instructions assign42 to a global, then loop at a verified stop.
@@ -93,6 +93,68 @@ final class SoftwareLibraryBrowseTests: XCTestCase {
XCTAssertEqual(LibraryBrowseQuery.type(of: cartridge, related: [disk, music]), "Other", "Conflicting editions do not establish a type")
XCTAssertEqual(LibraryBrowseQuery.type(of: release("demo", category: "Disks/Games/Sierra Games/Demos")), "Games")
}
func testUnifiedPersonalGamesAreFirstAndAvailableToLocalDiskCompanion() {
var entry = PersonalSoftwareEntry(id: UUID(), title: "Private Game", files: [
.init(path: "PRIVATE.DSK", kind: "disk", byteSize: 4, sha256: String(repeating: "a", count: 64))
])
entry.category = "Games"
let privateRelease = entry.release(in: directory)
let privateTitle = SoftwareLibraryTitle(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [privateRelease])
let publicGame = title("public-game", name: "Public Game", [release("public-edition", category: "Disks/Games")])
let titles = [privateTitle, publicGame]
XCTAssertEqual(LibraryBrowseQuery(scope: .all, softwareType: "Games").apply(to: titles, favorites: [entry.titleID], installed: [entry.releaseID]).map(\.id), [entry.titleID, publicGame.id])
XCTAssertEqual(LibraryBrowseQuery(scope: .all, category: "Games").apply(to: [privateTitle], favorites: [], installed: []).count, 1)
for scope in [LibraryBrowseQuery.Scope.started, .showcase, .installed] {
XCTAssertTrue(LibraryBrowseQuery(scope: scope).apply(to: [privateTitle], favorites: [entry.titleID], installed: [entry.releaseID]).isEmpty)
}
XCTAssertEqual(LibraryBrowseQuery(scope: .personal).apply(to: titles, favorites: [], installed: []).map(\.id), [entry.titleID])
XCTAssertEqual(LibraryBrowseQuery(scope: .favorites).apply(to: titles, favorites: [entry.titleID], installed: []).map(\.id), [entry.titleID])
XCTAssertEqual(LibraryBrowseQuery(scope: .search, text: "Private Game").apply(to: titles, favorites: [], installed: []).map(\.id), [entry.titleID])
let companion = SoftwareLibraryCatalog(titles: titles, metadata: [:]).companionDisksOnly
XCTAssertEqual(companion.titles.map(\.id), [privateTitle.id, publicGame.id], "The user's local companion can browse their own disks")
}
func testPersonalGroupIsAlphabeticalBeforeCatalogWithoutMergingSameNames() {
func personal(_ name: String, bytes: Int64) -> SoftwareLibraryTitle {
var entry = PersonalSoftwareEntry(id: UUID(), title: name, files: [.init(path: "GAME.dsk", kind: "disk", byteSize: bytes, sha256: String(repeating: "a", count: 64))])
entry.category = "Games"
return .init(id: entry.titleID, name: name, identityStatus: "personal", releases: [entry.release(in: directory)])
}
let privateA = personal("A Game", bytes: 10000), privateZ = personal("Z Game", bytes: 1)
let publicA = title("public-a", name: "A Game", [release("a", bytes: 10)])
let publicB = title("public-b", name: "B Game", [release("b", bytes: 50)])
for sort in LibraryBrowseQuery.Sort.allCases {
let rows = LibraryBrowseQuery(scope: .all, softwareType: "Games", sort: sort).apply(to: [publicA, privateZ, publicB, privateA], favorites: [], installed: [])
XCTAssertEqual(Array(rows.prefix(2)).map(\.id), [privateA.id, privateZ.id])
XCTAssertTrue(rows[0].isPersonal); XCTAssertFalse(rows[2].isPersonal)
XCTAssertEqual(rows.count, 4, "Personal and catalog editions with the same name stay distinct")
XCTAssertEqual(Array(rows.suffix(2)).map(\.id), sort == .size ? [publicB.id, publicA.id] : [publicA.id, publicB.id])
}
XCTAssertTrue(LibraryBrowseQuery(scope: .all, softwareType: "Music").apply(to: [privateA], favorites: [], installed: []).isEmpty)
}
@MainActor
func testHeaderSearchEscapesEveryPriorScopeAndFacetsAndResumes() async throws {
let support = directory.appendingPathComponent("GlobalSearch")
let continuity = LibraryContinuityStore(directory: support)
let model = SoftwareLibraryModel(state: .init(directory: support), continuity: continuity)
model.restoreBrowseContext()
for scope in LibraryBrowseQuery.Scope.allCases where scope != .search {
model.query = .init(scope: scope, category: "Disks", softwareType: "Music", media: "cassette", evidence: "checked", sort: .modified)
model.setSearchText("Popstar")
XCTAssertEqual(model.query, .init(scope: .search, text: "Popstar", sort: .modified))
}
model.query.media = "disk"; model.setSearchText("Popstar Game")
XCTAssertEqual(model.query.media, "disk", "Explicit filters within Search Results survive further typing")
model.saveBrowseContext(); await continuity.flush()
let resumed = SoftwareLibraryModel(state: .init(directory: support), continuity: LibraryContinuityStore(directory: support))
await resumed.load(from: try database()); try await settle(resumed)
XCTAssertEqual(resumed.query.scope, .search); XCTAssertEqual(resumed.query.text, "Popstar Game")
XCTAssertEqual(resumed.query.media, "disk")
model.setSearchText("")
XCTAssertEqual(model.query.scope, .all); XCTAssertEqual(model.query.text, "")
await model.shutdown(); await resumed.shutdown()
}
func testAdvancedFacetsMatchTheSameEditionAndKeepUnknownEvidenceHonest() {
let disk = release("disk", environment: "os9", processor: "6309", hardware: ["speech-sound": "optional"], videoModes: ["SG-12"])
let tape = release("tape", media: "cassette", environment: "basic", processor: "either", hardware: ["joystick": "unspecified"], videoModes: ["6847T1"])
@@ -221,6 +283,87 @@ final class SoftwareLibraryBrowseTests: XCTestCase {
await state.flush()
}
@MainActor
func testColdResumeRetainsSelectionWhileCatalogRecoveryIsDelayed() async throws {
let support = directory.appendingPathComponent("DelayedResume")
let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support)
let query = LibraryBrowseQuery(scope: .all)
let encoded = String(decoding: try JSONEncoder().encode(query), as: UTF8.self)
continuity.setBrowse(.init(scope: "all", filters: ["browse-query": encoded, "layout": "Table"], selectedID: "other"), for: "software-main")
await continuity.flush()
let restored = LibraryContinuityStore(directory: support)
let model = SoftwareLibraryModel(state: state, continuity: restored), url = try database()
let loading = Task { await model.load(from: url, catalogLoader: { url in
try await Task.sleep(nanoseconds: 350_000_000)
return try await SoftwareLibraryCatalog.load(from: url)
}) }
for _ in 0..<100 where !model.loading { try await Task.sleep(nanoseconds: 1_000_000) }
try await Task.sleep(nanoseconds: 180_000_000) // exceeds the empty-result filter debounce
XCTAssertTrue(model.loading)
XCTAssertEqual(model.selection, "other")
XCTAssertEqual(restored.browse(for: "software-main")?.selectedID, "other", "An empty interim result must not overwrite resume state")
await loading.value; try await settle(model)
XCTAssertEqual(model.selection, "other"); XCTAssertEqual(model.layout, "Table")
XCTAssertEqual(model.selectedRow?.name, "Other Game")
await model.shutdown()
}
@MainActor
func testFailedCatalogReadKeepsPublicResumePendingForRetry() async throws {
let support = directory.appendingPathComponent("FailedResume")
let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support)
let encoded = String(decoding: try JSONEncoder().encode(LibraryBrowseQuery(scope: .all)), as: UTF8.self)
continuity.setBrowse(.init(scope: "all", filters: ["browse-query": encoded], selectedID: "other"), for: "software-main")
let model = SoftwareLibraryModel(state: state, continuity: continuity), url = try database()
await model.load(from: url, catalogLoader: { _ in throw CocoaError(.fileReadNoPermission) })
try await settle(model)
XCTAssertNotNil(model.error); XCTAssertNil(model.catalog)
XCTAssertEqual(model.selection, "other")
XCTAssertEqual(continuity.browse(for: "software-main")?.selectedID, "other")
await model.load(from: url); try await settle(model)
XCTAssertNil(model.error); XCTAssertEqual(model.selection, "other")
XCTAssertEqual(model.selectedRow?.name, "Other Game")
await model.shutdown()
}
@MainActor
func testPrivateScopeRemainsUsableWhenPublicCatalogCannotLoad() async throws {
let support = directory.appendingPathComponent("PrivateWithoutCatalog")
let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support)
let encoded = String(decoding: try JSONEncoder().encode(LibraryBrowseQuery(scope: .personal)), as: UTF8.self)
continuity.setBrowse(.init(scope: "personal", filters: ["browse-query": encoded], selectedID: "personal:missing"), for: "software-main")
let model = SoftwareLibraryModel(state: state, continuity: continuity)
let source = directory.appendingPathComponent("LOCAL.ccc"); try Data([0x12,0x39]).write(to: source)
let draft = try await model.personalStore.inspect([source]), entry = try await model.personalStore.save(draft)
await model.load(from: directory.appendingPathComponent("Unavailable.sqlite"), catalogLoader: { _ in throw CocoaError(.fileReadNoSuchFile) })
try await settle(model)
XCTAssertNil(model.catalog); XCTAssertNotNil(model.error)
XCTAssertEqual(model.query.scope, .personal); XCTAssertEqual(model.selectedRow?.id, entry.titleID)
await model.shutdown()
}
@MainActor
func testPersonalSaveDuringColdCatalogLoadWinsOverResumedPublicScope() async throws {
let support = directory.appendingPathComponent("PersonalDuringLoad")
let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support)
let encoded = String(decoding: try JSONEncoder().encode(LibraryBrowseQuery(scope: .all)), as: UTF8.self)
continuity.setBrowse(.init(scope: "all", filters: ["browse-query": encoded], selectedID: "other"), for: "software-main")
let model = SoftwareLibraryModel(state: state, continuity: continuity), url = try database()
let source = directory.appendingPathComponent("AUTHORED.ccc")
try Data([0x12,0x39]).write(to: source)
let draft = try await model.personalStore.inspect([source]), entry = try await model.personalStore.save(draft)
let loading = Task { await model.load(from: url, catalogLoader: { url in
try await Task.sleep(nanoseconds: 500_000_000)
return try await SoftwareLibraryCatalog.load(from: url)
}) }
for _ in 0..<100 where !model.loading { try await Task.sleep(nanoseconds: 1_000_000) }
try await Task.sleep(nanoseconds: 150_000_000)
model.editPersonal(entry); model.savePersonal(entry, allowDuplicate: false)
for _ in 0..<100 where model.personalSaving { try await Task.sleep(nanoseconds: 5_000_000) }
XCTAssertEqual(model.query.scope, .personal); XCTAssertEqual(model.selection, entry.titleID)
await loading.value; try await settle(model)
XCTAssertEqual(model.query.scope, .personal); XCTAssertEqual(model.selection, entry.titleID)
XCTAssertEqual(model.selectedRow?.id, entry.titleID)
await model.shutdown()
XCTAssertEqual(continuity.browse(for: "software-main")?.selectedID, entry.titleID)
}
@MainActor
func testRapidQueriesAndFavoriteChangesPublishLatestResults() async throws {
let state = SoftwareLibraryState(directory: directory.appendingPathComponent("Personal"))
let model = SoftwareLibraryModel(state: state)
@@ -40,6 +40,20 @@ final class SoftwareLibraryLaunchPlanTests: XCTestCase {
XCTAssertFalse(automatic(release(media: "hard-disk", profile: "hard-drive-basic", paths: [("hardDisk0", "GAME.vhd")], command: "DOS\r")))
XCTAssertFalse(automatic(release(paths: [("disk0", "GAME.vhd")], command: "DOS\r")))
}
func testUnconfiguredPersonalROMImportOffersRealCartridgeSetup() async throws {
let selected = root.appendingPathComponent("AUTHORED.ROM"), bytes = Data([0x12,0x39])
try bytes.write(to: selected)
let store = PersonalSoftwareLibraryStore(root: root.appendingPathComponent("PersonalLibrary"))
let draft = try await store.inspect([selected]), entry = try await store.save(draft)
XCTAssertFalse(entry.configured)
let imported = await store.directory(for: entry.id)
let plan = try SoftwareLibraryLaunchPlan.prepare(release: entry.release(in: imported), receipt: entry.receipt(in: imported))
XCTAssertEqual(plan.profile, .romCartridge)
XCTAssertEqual(plan.cartridgeURL?.lastPathComponent, "AUTHORED.ROM")
XCTAssertTrue(plan.commands.isEmpty)
XCTAssertEqual(try Data(contentsOf: selected), bytes)
try plan.validateMedia()
}
func testCartridgeAutostartsWithoutTypingAndHonorsItsStartupSlot() throws {
try file("GAME.ccc")
let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(media: "cartridge", profile: "rom-cartridge", paths: [("cartridge", "GAME.ccc")], extra: ["cartridge_slot": .number(2)]), receipt: receipt(["GAME.ccc"]))
@@ -186,4 +200,53 @@ final class SoftwareLibraryLaunchPlanTests: XCTestCase {
XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands(command), command)
}
}
func testBasicProgramLoadThenRunUsesSeparateKeyboardLines() throws {
for sequence in ["LOAD \"POPSTAR\"\nRUN", "load \"POPSTAR\"\r\nrun", "LOAD\"POPSTAR\"\\rRUN\\r"] {
let commands = try XCTUnwrap(SoftwareLibraryLaunchPlan.decodeCommands(sequence))
XCTAssertEqual(commands.count, 2)
XCTAssertEqual(commands[0].uppercased().replacingOccurrences(of: " ", with: ""), "LOAD\"POPSTAR\"")
XCTAssertEqual(commands[1].uppercased(), "RUN")
}
try file("POPSTAR.DSK")
let item = release(paths: [("disk0", "POPSTAR.DSK")], command: "LOAD \"POPSTAR\"\nRUN", status: "manual-setup")
XCTAssertTrue(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: item))
let plan = try SoftwareLibraryLaunchPlan.prepare(release: item, receipt: receipt(["POPSTAR.DSK"]))
XCTAssertTrue(plan.automaticallyStarts)
XCTAssertEqual(plan.commands, ["LOAD \"POPSTAR\"", "RUN"])
XCTAssertEqual(plan.floppyURLs[0]?.lastPathComponent, "POPSTAR.DSK")
XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands("LOAD \"POPSTAR\":RUN"), "BASIC discards the rest of the LOAD command line")
XCTAssertEqual(SoftwareLibraryLaunchPlan.decodeCommands("LOAD \"POPSTAR\""), ["LOAD \"POPSTAR\""])
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release(paths: [("disk0", "POPSTAR.DSK")], command: "LOAD \"POPSTAR\"")))
XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands("LOAD \"POPSTAR\"\nRUN\nDIR"), "No later commands may be typed into a started guest program")
}
@MainActor
func testReviewedPersonalDiskOffersPlayWithoutLoadingCommands() throws {
try file("GAME.DSK")
var entry = PersonalSoftwareEntry(id: UUID(), title: "Reviewed personal disk", files: [
.init(path: "GAME.DSK", kind: "disk", byteSize: 3, sha256: sha, role: "disk0")
])
entry.configured = true
let item = entry.release(in: root)
XCTAssertTrue(SoftwareLibraryLaunchPlan.hasPlayAction(for: item))
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: item))
let plan = try SoftwareLibraryLaunchPlan.prepare(release: item, receipt: entry.receipt(in: root))
XCTAssertTrue(plan.offersPlay); XCTAssertFalse(plan.automaticallyStarts)
XCTAssertTrue(plan.commands.isEmpty); XCTAssertNotNil(plan.floppyURLs[0])
let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State")))
XCTAssertEqual(model.launchLabel(item, installed: true), "Play…")
XCTAssertEqual(model.launchSymbol(item), "play.fill")
entry.command = "LOAD \"GAME\""
let loadOnly = try SoftwareLibraryLaunchPlan.prepare(release: entry.release(in: root), receipt: entry.receipt(in: root))
XCTAssertTrue(loadOnly.offersPlay); XCTAssertFalse(loadOnly.automaticallyStarts)
XCTAssertEqual(loadOnly.commands, ["LOAD \"GAME\""])
entry.command = "SYSTEM \"curl example.invalid\""
let unsupported = try SoftwareLibraryLaunchPlan.prepare(release: entry.release(in: root), receipt: entry.receipt(in: root))
XCTAssertTrue(unsupported.offersPlay); XCTAssertTrue(unsupported.commands.isEmpty)
entry.configured = false
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: entry.release(in: root)))
entry.configured = true; entry.files[0].role = ""
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: entry.release(in: root)))
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: release(paths: [("disk0", "GAME.DSK")])), "Public catalog labels retain their existing behavior")
}
}
@@ -36,21 +36,21 @@ final class SoftwareLibraryMachineLaunchTests: XCTestCase {
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") throws -> SoftwareLibraryLaunchPlan {
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 = cartridge ? "Fixture.ccc" : "Fixture.dsk"
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(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")])])]
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(cartridge ? "cartridge" : "disk0")])]), reasons: [], validation: .object([:]))
let release = SoftwareLibraryRelease(id: "fixture", titleID: "fixture", name: "Fixture", category: cartridge ? "Cartridges" : "Disks/Games", mediaType: 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: [])
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)
}
@@ -114,6 +114,56 @@ final class SoftwareLibraryMachineLaunchTests: XCTestCase {
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
@@ -18,6 +18,25 @@ final class SoftwareLibraryManualTests: XCTestCase {
asset.manualURL = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Manuals/Games/Manual.pdf")
return (asset, bytes)
}
func testImportedUppercaseTextManualUsesTextReaderWithoutNetwork() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("PersonalManual-" + UUID().uuidString)
defer { try? FileManager.default.removeItem(at: root) }
let source = root.appendingPathComponent("Selected")
try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true)
let text = Data("Authored local loading instructions\n".utf8)
try text.write(to: source.appendingPathComponent("README.TXT"))
try Data([0x12,0x39]).write(to: source.appendingPathComponent("GAME.ccc"))
let store = PersonalSoftwareLibraryStore(root: root.appendingPathComponent("PersonalLibrary"))
let draft = try await store.inspect([source]), entry = try await store.save(draft)
let imported = await store.directory(for: entry.id)
let manual = try XCTUnwrap(entry.release(in: imported).primaryManualAsset)
let model = SoftwareLibraryManualModel(); model.open(manual, directory: root.appendingPathComponent("UnusedCache"))
for _ in 0..<100 where model.loading { try await Task.sleep(nanoseconds: 10_000_000) }
XCTAssertEqual(model.text, String(decoding: text, as: UTF8.self))
XCTAssertNil(model.document); XCTAssertNil(model.error)
XCTAssertEqual(try Data(contentsOf: source.appendingPathComponent("README.TXT")), text)
model.cancel()
}
func testPlainTextDecodingPreservesInstructionsAndRejectsBinaryData() throws {
XCTAssertEqual(try SoftwareLibraryManualModel.decodeText(Data("Z = start\r\nX = kick\u{1A}".utf8)), "Z = start\nX = kick")
XCTAssertEqual(try SoftwareLibraryManualModel.decodeText(Data([0x63, 0x61, 0x66, 0xe9])), "café")
@@ -0,0 +1,380 @@
// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import CryptoKit
import ImageIO
import UniformTypeIdentifiers
final class SoftwareLibraryPersonalTests: XCTestCase {
private var root: URL!
override func setUpWithError() throws {
root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("PersonalLibraryTests-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
}
override func tearDownWithError() throws { if let root { try? FileManager.default.removeItem(at: root) } }
private func service() -> PersonalSoftwareLibraryStore { .init(root: root.appendingPathComponent("PersonalLibrary")) }
private func cartridge(_ name: String = "GAME.ccc") throws -> URL {
let source = root.appendingPathComponent(name)
try Data([0x39,0x12,0x12,0x12]).write(to: source)
return source
}
private func png(width: Int = 96, height: Int = 128, gray: CGFloat = 0.25) throws -> Data {
let context = try XCTUnwrap(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8,
bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
context.setFillColor(CGColor(gray: gray, alpha: 1))
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
let data = NSMutableData()
let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil))
CGImageDestinationAddImage(destination, try XCTUnwrap(context.makeImage()), nil)
XCTAssertTrue(CGImageDestinationFinalize(destination))
return data as Data
}
func testSingleFloppyDefaultsToFD0WithoutEnablingAutomation() async throws {
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
let source = root.appendingPathComponent("GAME.dsk")
let bytes = try Data(contentsOf: fixture); try bytes.write(to: source)
let readme = root.appendingPathComponent("README.txt"); try Data("Instructions".utf8).write(to: readme)
let store = service(), draft = try await store.inspect([source, readme])
XCTAssertEqual(draft.entry.files.first(where: { $0.kind == "disk" })?.role, "disk0")
XCTAssertFalse(draft.entry.configured); XCTAssertTrue(draft.entry.command.isEmpty)
let entry = try await store.save(draft), directory = await store.directory(for: entry.id)
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: entry.release(in: directory)))
let recovered = try await store.entries()
XCTAssertEqual(recovered.first?.files.first(where: { $0.kind == "disk" })?.role, "disk0")
XCTAssertEqual(try Data(contentsOf: source), bytes)
}
func testMultipleFloppiesKeepExplicitRolesAndSavedChoicesAreNotReset() async throws {
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
let first = root.appendingPathComponent("FIRST.dsk"), second = root.appendingPathComponent("SECOND.dsk")
let bytes = try Data(contentsOf: fixture); try bytes.write(to: first); try bytes.write(to: second)
let store = service(), multiple = try await store.inspect([first, second])
XCTAssertTrue(multiple.entry.files.allSatisfy { $0.role.isEmpty }, "Do not infer a boot disk from filename order")
await store.cancel(multiple.id)
let single = try await store.inspect([first]); var entry = try await store.save(single)
entry.files[0].role = "disk2"; try await store.update(entry)
let saved = try await store.entries()
XCTAssertEqual(saved.first?.files[0].role, "disk2", "Defaulting applies to new imports, not saved user choices")
XCTAssertEqual(try Data(contentsOf: second), bytes)
}
func testImportPreservesOriginalsAndWorkingSavesAndNeverPublishes() async throws {
let source = try cartridge(), bytes = try Data(contentsOf: source), store = service()
let draft = try await store.inspect([source])
XCTAssertEqual(draft.entry.profile, "rom-cartridge")
XCTAssertFalse(draft.entry.configured)
let entry = try await store.save(draft)
let directory = await store.directory(for: entry.id)
let working = directory.appendingPathComponent("Working/GAME.ccc")
XCTAssertEqual(try Data(contentsOf: working), bytes)
let saved = Data([0x10,0x20,0x30]); try saved.write(to: working)
XCTAssertEqual(try Data(contentsOf: source), bytes)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc")), bytes)
let restored = try await service().entries()
XCTAssertEqual(restored.map(\.id), [entry.id])
XCTAssertEqual(try Data(contentsOf: working), saved)
let release = entry.release(in: directory)
XCTAssertTrue(release.isPersonal); XCTAssertFalse(release.isArchive)
XCTAssertTrue(release.downloadURLs.isEmpty)
XCTAssertTrue(release.sourceURL.isFileURL)
let catalog = SoftwareLibraryCatalog(titles: [.init(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [release])], metadata: [:])
XCTAssertTrue(catalog.companionDisksOnly.titles.isEmpty)
XCTAssertEqual(LibraryBrowseQuery(scope: .all).apply(to: catalog.titles, favorites: [], installed: []).map(\.id), [entry.titleID])
XCTAssertEqual(LibraryBrowseQuery(scope: .personal).apply(to: catalog.titles, favorites: [], installed: []).count,1)
XCTAssertEqual(LibraryBrowseQuery(scope: .favorites).apply(to: catalog.titles, favorites: [entry.titleID], installed: []).count,1)
}
func testDuplicateRequiresExplicitSeparateCopyAndHiddenEntryStaysHidden() async throws {
let source = try cartridge(), store = service()
let initial = try await store.inspect([source])
let first = try await store.save(initial)
let duplicate = try await store.inspect([source])
do { _ = try await store.save(duplicate); XCTFail("Expected duplicate review") }
catch PersonalSoftwareLibraryStore.Failure.duplicate(let id) { XCTAssertEqual(id, first.id) }
let second = try await store.save(duplicate, allowDuplicate: true)
XCTAssertNotEqual(first.id, second.id)
var removed = first; removed.hidden = true
try await store.update(removed)
let visible = try await service().entries()
XCTAssertEqual(visible.map(\.id), [second.id])
let retained = await store.directory(for: first.id)
XCTAssertTrue(FileManager.default.fileExists(atPath: retained.appendingPathComponent("Working/GAME.ccc").path))
}
func testPersonalCategoryDefaultsAndNormalizesWithoutReplacingWorkingFiles() async throws {
let source = try cartridge(), store = service()
var draft = try await store.inspect([source])
XCTAssertEqual(draft.entry.category, "Other")
draft.entry.category = "A custom category"
var entry = try await store.save(draft)
XCTAssertEqual(entry.category, "Other")
let directory = await store.directory(for: entry.id)
let working = directory.appendingPathComponent("Working/GAME.ccc")
let bytes = Data([0x39, 0x20, 0x30]); try bytes.write(to: working)
entry.category = "Games"; try await store.update(entry)
var recovered = try await store.entries()
XCTAssertEqual(recovered.first?.category, "Games")
for category in PersonalSoftwareEntry.standardCategories {
entry.category = category
let release = entry.release(in: directory)
XCTAssertEqual(LibraryBrowseQuery.type(of: release), category, "Each dropdown choice must use its actual category illustration")
}
// Simulate a free-form category saved by the previous development UI.
entry.category = "An old custom category"
try JSONEncoder().encode(entry).write(to: directory.appendingPathComponent("Entry.json"), options: .atomic)
recovered = try await store.entries()
XCTAssertEqual(recovered.first?.category, "Other")
XCTAssertEqual(try Data(contentsOf: working), bytes)
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
}
func testSavedReviewedBasicCommandsOfferAutomaticLaunchWithoutTouchingMedia() async throws {
let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk")
let source = root.appendingPathComponent("POPSTAR.DSK")
let bytes = try Data(contentsOf: fixture)
try bytes.write(to: source)
let store = service(), draft = try await store.inspect([source])
var entry = try await store.save(draft)
entry.configured = true; entry.video = "rgb"; entry.ramKiB = 512
entry.files[0].role = "disk0"
entry.command = "LOAD \"POPSTAR\"\nRUN"
try await store.update(entry)
let recovered = try await store.entries()
let saved = try XCTUnwrap(recovered.first)
let directory = await store.directory(for: saved.id)
let release = saved.release(in: directory)
XCTAssertTrue(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release))
let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: saved.receipt(in: directory))
XCTAssertTrue(plan.automaticallyStarts)
XCTAssertEqual(plan.commands, ["LOAD \"POPSTAR\"", "RUN"])
XCTAssertEqual(plan.floppyURLs[0], directory.appendingPathComponent("Working/POPSTAR.DSK"))
XCTAssertEqual(plan.ramKiB, 512)
XCTAssertEqual(try Data(contentsOf: source), bytes)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/POPSTAR.DSK")), bytes)
var manual = saved; manual.configured = false
XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: manual.release(in: directory)))
}
func testCancelAndSymlinkFailurePreserveSelectedFiles() async throws {
let source = try cartridge(), store = service()
let draft = try await store.inspect([source])
await store.cancel(draft.id)
let entries = try await store.entries(); XCTAssertTrue(entries.isEmpty)
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
let folder = root.appendingPathComponent("Set")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
try FileManager.default.createSymbolicLink(at: folder.appendingPathComponent("GAME.ccc"), withDestinationURL: source)
do { _ = try await store.inspect([folder]); XCTFail("Symbolic links must not be followed") } catch { }
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
do { _ = try await store.inspect([root]); XCTFail("A source folder must not recursively include its own import destination.") } catch { }
}
func testMultiFileSetMetadataEditsAndInvalidRecipePreserveMedia() async throws {
let folder = root.appendingPathComponent("Owned Software")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
try Data([0x39]).write(to: folder.appendingPathComponent("GAME.ccc"))
try Data("Private instructions".utf8).write(to: folder.appendingPathComponent("README.txt"))
let store = service(); let draft = try await store.inspect([folder])
XCTAssertEqual(draft.entry.files.map(\.path), ["GAME.ccc", "README.txt"], "Selected-folder aliases must not become member prefixes.")
var entry = try await store.save(draft)
let directory = await store.directory(for: entry.id)
let original = try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc"))
entry.title = "My purchased game"; entry.author = "Original author"
try await store.update(entry)
let recovered = try await service().entries()
XCTAssertEqual(recovered.first?.title, entry.title)
XCTAssertEqual(recovered.first?.files.count,2)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/README.txt")), Data("Private instructions".utf8))
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc")), original)
entry.command = "hello\u{1B}"
do { try await store.update(entry); XCTFail("Control injection must fail") } catch { }
XCTAssertEqual(try Data(contentsOf: folder.appendingPathComponent("README.txt")), Data("Private instructions".utf8))
let release = recovered[0].release(in: directory)
let manual = try XCTUnwrap(release.primaryManualAsset)
try SoftwareLibraryLocalAsset.validate(manual, url: manual.manualURL!, maximumBytes: 1024*1024)
try Data("changed".utf8).write(to: manual.manualURL!)
XCTAssertThrowsError(try SoftwareLibraryLocalAsset.validate(manual,url:manual.manualURL!,maximumBytes:1024*1024))
}
func testZIPKeepsOriginalPackageAndCompleteWorkingTree() async throws {
let archive = root.appendingPathComponent("Authored Software.zip")
let bytes = Data(base64Encoded: "UEsDBBQAAAAAAAAAIVyFZweNAQAAAAEAAAANAAAAR2FtZS9HQU1FLmNjYzlQSwMEFAAAAAAAAAAhXFokposcAAAAHAAAAA8AAABHYW1lL1JFQURNRS50eHRBdXRob3JlZCBsb2NhbCBpbnN0cnVjdGlvbnMKUEsBAhQDFAAAAAAAAAAhXIVnB40BAAAAAQAAAA0AAAAAAAAAAAAAAKSBAAAAAEdhbWUvR0FNRS5jY2NQSwECFAMUAAAAAAAAACFcWiSmixwAAAAcAAAADwAAAAAAAAAAAAAApIEsAAAAR2FtZS9SRUFETUUudHh0UEsFBgAAAAACAAIAeAAAAHUAAAAAAA==")!
try bytes.write(to: archive)
let store = service()
let owned = try await store.inspect([archive])
let entry = try await store.save(owned)
let directory = await store.directory(for: entry.id)
XCTAssertEqual(entry.files.map(\.path), ["Game/GAME.ccc", "Game/README.txt"])
XCTAssertEqual(try Data(contentsOf: archive),bytes)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Package.zip")),bytes)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/Game/README.txt")),Data("Authored local instructions\n".utf8))
}
func testReviewedZIPRejectsChangedValidBytesAndPreservesExistingLibrary() async throws {
let source = root.appendingPathComponent("Authored.zip")
let original = Data(base64Encoded: "UEsDBBQAAAAAAAAAIVyFZweNAQAAAAEAAAANAAAAR2FtZS9HQU1FLmNjYzlQSwMEFAAAAAAAAAAhXFokposcAAAAHAAAAA8AAABHYW1lL1JFQURNRS50eHRBdXRob3JlZCBsb2NhbCBpbnN0cnVjdGlvbnMKUEsBAhQDFAAAAAAAAAAhXIVnB40BAAAAAQAAAA0AAAAAAAAAAAAAAKSBAAAAAEdhbWUvR0FNRS5jY2NQSwECFAMUAAAAAAAAACFcWiSmixwAAAAcAAAADwAAAAAAAAAAAAAApIEsAAAAR2FtZS9SRUFETUUudHh0UEsFBgAAAAACAAIAeAAAAHUAAAAAAA==")!
try original.write(to: source)
let store = service(), reviewedHash = SHA256.hash(data: original).map { String(format: "%02x", $0) }.joined()
let draft = try await store.inspect([source]), entry = try await store.save(draft)
let retained = await store.directory(for: entry.id)
// Rename ZIP member directories in both local/central headers. Sizes and
// file CRCs remain valid: rejection must bind bytes, not just ZIP validity.
var changed = original, offset = 0
while let range = changed.range(of: Data("Game/".utf8), in: offset..<changed.count) {
changed.replaceSubrange(range, with: Data("Play/".utf8)); offset = range.upperBound
}
XCTAssertEqual(changed.count, original.count); XCTAssertNotEqual(changed, original)
try changed.write(to: source)
let extracted = root.appendingPathComponent("ChangedIsValid")
let paths = try VCCLibraryArchive.extractZIP(at: source, toNewDirectory: extracted, maximumExpandedBytes: 1024*1024, maximumEntries: 10, shouldCancel: { false })
XCTAssertEqual(paths, ["Play/GAME.ccc", "Play/README.txt"])
let attempted = root.appendingPathComponent("Unpublished.zip")
XCTAssertThrowsError(try PersonalSoftwareLibraryStore.copyReviewedPackage(from: source, to: attempted,
byteSize: Int64(original.count), sha256: reviewedHash))
XCTAssertFalse(FileManager.default.fileExists(atPath: attempted.path))
XCTAssertEqual(try Data(contentsOf: source), changed, "Failed import must not modify the selected source")
XCTAssertEqual(try Data(contentsOf: retained.appendingPathComponent("Original/Package.zip")), original)
XCTAssertEqual(try Data(contentsOf: retained.appendingPathComponent("Working/Game/GAME.ccc")), Data([0x39]))
let existing = try await store.entries(); XCTAssertEqual(existing.map(\.id), [entry.id])
}
func testPersonalCoverSelectionReplacementRemovalAndReloadPreserveMedia() async throws {
let source = try cartridge(), store = service(), firstPNG = try png(), secondPNG = try png(gray: 0.75)
let first = root.appendingPathComponent("A.png"), second = root.appendingPathComponent("B.png")
try firstPNG.write(to: first); try secondPNG.write(to: second)
let manual = root.appendingPathComponent("README.txt")
try Data("Retained manual".utf8).write(to: manual)
var draft = try await store.inspect([source, first, second, manual])
XCTAssertNil(draft.entry.cover)
XCTAssertEqual(draft.entry.selectedCoverFile?.path, "A.png")
let initialPreview = try await store.previewCover(draft.entry, draftID: draft.id)
XCTAssertEqual(initialPreview, try PersonalCoverImage.prepare(firstPNG))
draft.entry.cover = .imported("B.png")
let selectedPreview = try await store.previewCover(draft.entry, draftID: draft.id)
XCTAssertEqual(selectedPreview, try PersonalCoverImage.prepare(secondPNG))
var entry = try await store.save(draft)
let identity = entry.packageSHA256, files = entry.files.map(\.path)
let directory = await store.directory(for: entry.id), working = directory.appendingPathComponent("Working/GAME.ccc")
let savedProgram = Data([0x39, 0x20]); try savedProgram.write(to: working)
let release = entry.release(in: directory)
XCTAssertEqual(release.assets.filter { $0.kind == "cover" }.map(\.name), ["B.png"])
XCTAssertEqual(release.assets.filter(\.isManual).map(\.name), ["README.txt"])
let replacement = try png(width: 1800, height: 1000)
try await store.update(entry, coverPNG: replacement)
var reloaded = try await store.entries(); entry = try XCTUnwrap(reloaded.first)
guard case .custom(let custom) = entry.cover else { return XCTFail("Replacement cover must use a separate local asset.") }
XCTAssertTrue(custom.path.hasPrefix("PersonalCovers/"))
let customURL = directory.appendingPathComponent("Assets").appendingPathComponent(custom.path)
let customBytes = try Data(contentsOf: customURL)
XCTAssertEqual(Int64(customBytes.count), custom.byteSize)
XCTAssertEqual(custom.sha256, SHA256.hash(data: customBytes).map { String(format: "%02x", $0) }.joined())
let image = try XCTUnwrap(SoftwareLibraryArtworkCache.image(from: customBytes))
XCTAssertEqual(image.width, 640); XCTAssertLessThanOrEqual(image.height, 640)
let customAsset = try XCTUnwrap(entry.release(in: directory).assets.first { $0.kind == "cover" })
XCTAssertEqual(customAsset.name, "Personal Cover Image")
try SoftwareLibraryLocalAsset.validate(customAsset, url: customURL, maximumBytes: 2 * 1024 * 1024)
let customPreview = try await store.previewCover(entry)
XCTAssertEqual(customPreview, try PersonalCoverImage.prepare(customBytes))
try await store.update(entry, coverPNG: secondPNG)
reloaded = try await store.entries(); entry = try XCTUnwrap(reloaded.first)
XCTAssertNotEqual(entry.selectedCoverFile?.path, custom.path)
XCTAssertTrue(FileManager.default.fileExists(atPath: customURL.path), "Prior cover assets remain recoverable.")
entry.cover = .categoryIcon
try await store.update(entry)
reloaded = try await store.entries(); entry = try XCTUnwrap(reloaded.first)
XCTAssertEqual(entry.cover, .categoryIcon)
let removedPreview = try await store.previewCover(entry)
XCTAssertNil(removedPreview)
XCTAssertTrue(entry.release(in: directory).assets.filter { $0.kind == "cover" }.isEmpty)
XCTAssertEqual(entry.release(in: directory).assets.filter(\.isManual).map(\.name), ["README.txt"])
entry.cover = .imported("A.png"); try await store.update(entry)
reloaded = try await store.entries(); entry = try XCTUnwrap(reloaded.first)
XCTAssertEqual(entry.cover, .imported("A.png"))
XCTAssertEqual(entry.packageSHA256, identity); XCTAssertEqual(entry.files.map(\.path), files)
XCTAssertEqual(entry.receipt(in: directory).relativeFiles, files)
XCTAssertEqual(try Data(contentsOf: working), savedProgram)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc")), Data([0x39,0x12,0x12,0x12]))
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/A.png")), firstPNG)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/A.png")), firstPNG)
XCTAssertEqual(try Data(contentsOf: first), firstPNG)
XCTAssertTrue(FileManager.default.fileExists(atPath: customURL.path))
}
func testPersonalCoverPendingSaveCancelAndLegacyEntryCompatibility() async throws {
let source = try cartridge(), store = service(), image = try png()
let art = root.appendingPathComponent("cover.png"); try image.write(to: art)
let draft = try await store.inspect([source, art])
let pending = try PersonalCoverImage.prepare(art)
await store.cancel(draft.id)
let cancelled = try await store.entries(); XCTAssertTrue(cancelled.isEmpty)
do { _ = try await store.save(draft, coverPNG: pending); XCTFail("A canceled cover edit must not persist.") } catch { }
XCTAssertEqual(try Data(contentsOf: art), image)
let newDraft = try await store.inspect([source, art])
let entry = try await store.save(newDraft, coverPNG: pending)
guard case .custom = entry.cover else { return XCTFail("New imports can save their chosen local cover atomically.") }
let directory = await store.directory(for: entry.id)
XCTAssertEqual(entry.packageSHA256, newDraft.entry.packageSHA256)
XCTAssertEqual(entry.files.map(\.path), newDraft.entry.files.map(\.path))
// An actual pre-cover JSON record omits the optional key entirely.
var json = try XCTUnwrap(JSONSerialization.jsonObject(with: JSONEncoder().encode(entry)) as? [String: Any])
json.removeValue(forKey: "cover")
try JSONSerialization.data(withJSONObject: json).write(to: directory.appendingPathComponent("Entry.json"), options: .atomic)
let restored = try await store.entries(), legacy = try XCTUnwrap(restored.first)
XCTAssertNil(legacy.cover)
XCTAssertEqual(legacy.release(in: directory).assets.filter { $0.kind == "cover" }.map(\.name), ["cover.png"])
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/cover.png")), image)
}
func testCoverInputsRejectCorruptOversizedAndUnsafeFiles() throws {
let valid = try png(), selected = root.appendingPathComponent("selected.png")
try valid.write(to: selected)
XCTAssertThrowsError(try PersonalCoverImage.prepare(Data()))
XCTAssertThrowsError(try PersonalCoverImage.prepare(Data("invalid image".utf8)))
XCTAssertThrowsError(try PersonalCoverImage.prepare(Data(repeating: 0, count: 8 * 1024 * 1024 + 1)))
XCTAssertThrowsError(try PersonalCoverImage.prepare(png(width: 16_385, height: 1)))
XCTAssertThrowsError(try PersonalCoverImage.prepare(URL(string: "https://example.com/cover.png")!))
let link = root.appendingPathComponent("link.png")
try FileManager.default.createSymbolicLink(at: link, withDestinationURL: selected)
XCTAssertThrowsError(try PersonalCoverImage.prepare(link))
XCTAssertThrowsError(try PersonalCoverImage.prepare(root))
XCTAssertEqual(try Data(contentsOf: selected), valid)
}
func testCoverInvalidDescriptorsSymlinksAndStaleEditsPreserveSavedEntry() async throws {
let source = try cartridge(), store = service(), image = try png()
let draft = try await store.inspect([source]), entry = try await store.save(draft)
let directory = await store.directory(for: entry.id), record = directory.appendingPathComponent("Entry.json")
let before = try Data(contentsOf: record)
do { try await store.update(entry, coverPNG: Data("corrupt".utf8)); XCTFail("Invalid replacement must be refused.") } catch { }
var invalid = entry; invalid.cover = .imported("GAME.ccc")
do { try await store.update(invalid); XCTFail("Media cannot be selected as an imported cover.") } catch { }
for path in ["../outside.png", "PersonalCovers/../outside.png", "/outside.png", "PersonalCovers/not-a-uuid.png"] {
invalid.cover = .custom(.init(path: path, sha256: String(repeating: "a", count: 64), byteSize: 10))
do { try await store.update(invalid); XCTFail("Unsafe cover path must be refused: " + path) } catch { }
}
let assets = directory.appendingPathComponent("Assets"), outside = root.appendingPathComponent("Outside")
try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)
try FileManager.default.createSymbolicLink(at: assets.appendingPathComponent("PersonalCovers"), withDestinationURL: outside)
do { try await store.update(entry, coverPNG: image); XCTFail("The cover destination must not follow links.") } catch { }
XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: outside.path).isEmpty)
XCTAssertEqual(try Data(contentsOf: record), before)
try FileManager.default.removeItem(at: assets.appendingPathComponent("PersonalCovers"))
var external = entry; external.title = "Changed in another editor"
try await store.update(external)
let changed = try Data(contentsOf: record)
do { try await store.update(entry, coverPNG: image); XCTFail("An older cover editor must not overwrite newer metadata.") } catch { }
var staleRemoval = entry; staleRemoval.cover = .categoryIcon
do { try await store.update(staleRemoval); XCTFail("Stale cover removal must be refused.") } catch { }
XCTAssertEqual(try Data(contentsOf: record), changed)
XCTAssertFalse(FileManager.default.fileExists(atPath: assets.appendingPathComponent("PersonalCovers").path))
let recovered = try await store.entries(), current = try XCTUnwrap(recovered.first)
try await store.update(current, coverPNG: image)
let withCover = try await store.entries(), selected = try XCTUnwrap(withCover.first)
let cover = try XCTUnwrap(selected.selectedCoverFile), coverURL = assets.appendingPathComponent(cover.path)
let retained = try Data(contentsOf: coverURL), savedRecord = try Data(contentsOf: record)
try FileManager.default.removeItem(at: coverURL)
try FileManager.default.createSymbolicLink(at: coverURL, withDestinationURL: source)
do { _ = try await store.previewCover(selected); XCTFail("Preview must refuse a linked asset.") } catch { }
do { try await store.update(selected); XCTFail("Saving a linked selected asset must be refused.") } catch { }
XCTAssertEqual(try Data(contentsOf: record), savedRecord)
try FileManager.default.removeItem(at: coverURL); try retained.write(to: coverURL)
XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/GAME.ccc")), Data([0x39,0x12,0x12,0x12]))
XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12]))
}
func testRelatedReferenceValidationAndPrivateCompanionBoundary() throws {
let id = String(repeating: "a",count:64)
let good = LibraryJSON.object(["id": .string("guide"), "title": .string("Example guide"), "document_id": .string(id), "sha256": .string(id), "role": .string("Hints"), "spoiler": .bool(true)])
XCTAssertEqual(try SoftwareLibraryRelatedReference.parse(good).documentID,id)
var bad = good.object; bad["page"] = .number(0)
XCTAssertThrowsError(try SoftwareLibraryRelatedReference.parse(.object(bad)))
bad = good.object; bad["sha256"] = .string(String(repeating:"b",count:64))
XCTAssertThrowsError(try SoftwareLibraryRelatedReference.parse(.object(bad)))
}
}
+34 -2
View File
@@ -312,7 +312,8 @@ extension StartupTests {
custom.media.cartridges!.physicalSlot=2
try profileStore.save(custom)
for launch in 0..<2 {
let model = MachineModel(diskStore:f.disks,displayDefaults:defaults,inputStore:inputStore,startupStore:f.startup)
let model = MachineModel(diskStore:f.disks,displayDefaults:defaults,inputStore:inputStore,startupStore:f.startup,
inputControllerReadings: { [] })
try await waitForStartup(model)
if launch == 0 {
await model.loadProfile(custom);XCTAssertNil(model.profileError);XCTAssertTrue(model.settings.use6309)
@@ -321,7 +322,7 @@ extension StartupTests {
XCTAssertNil(model.profileError);XCTAssertNil(model.fileError)
XCTAssertEqual(model.settings,MachineSettings());XCTAssertEqual(model.state,.running)
XCTAssertEqual(model.videoOutput,.composite);XCTAssertTrue(model.audioEnabled);XCTAssertEqual(model.volume,0.5)
XCTAssertEqual(model.input.settings,InputSettings());XCTAssertFalse(model.tapeFast)
XCTAssertEqual(model.input.settings,.freshDefaults);XCTAssertFalse(model.tapeFast)
XCTAssertEqual(model.cartridgeAssignments,expected.media.cartridges)
XCTAssertTrue(model.disks[0].mounted);XCTAssertFalse(model.disks[0].writeProtected);XCTAssertFalse(model.diskTemporary[0])
XCTAssertTrue(model.disks.dropFirst().allSatisfy { !$0.mounted });XCTAssertFalse(model.hardDiskConnected)
@@ -333,6 +334,37 @@ extension StartupTests {
await withCheckedContinuation { done in model.shutdown { done.resume() } }
}
}
@MainActor func testBuiltInProfilePreservesInputButPersonalProfileAndExplicitResetApplyTheirChoices() async throws {
let f = try Fixture(); defer { f.remove() }
let suite = "VCCInputProfile-" + UUID().uuidString, defaults = UserDefaults(suiteName: suite)!
defer { defaults.removePersistentDomain(forName: suite) }
let inputStore = InputSettingsStore(url: f.support.appendingPathComponent("Input.json"))
var configured = InputSettings()
configured.right.source = .controller; configured.right.device = "remembered-disconnected"
configured.right.rightStick = true; configured.right.fire1 = 4; configured.right.fire2 = 8
configured.right.deadZone = 0.3; configured.right.interface = .tandy
configured.left.source = .keyboard
try inputStore.save(configured)
let controller = VCCMachineController()
let model = MachineModel(diskStore: f.disks, controller: controller, displayDefaults: defaults, inputStore: inputStore,
startupStore: f.startup, inputControllerReadings: { [] }, restoreMediaOnLaunch: false)
let loaded = await model.loadSystemProfile(.diskBasic)
XCTAssertTrue(loaded); XCTAssertEqual(model.input.settings, configured)
XCTAssertEqual(try inputStore.load(), configured)
let snapshot = await withCheckedContinuation { done in controller.snapshot { done.resume(returning: $0) } }
XCTAssertEqual(Int(snapshot.joystickInputs[0].mode), configured.right.interface.rawValue,
"Preserving settings must also restore their interface to the newly loaded guest")
var personal = try f.startup.appDefaults()
personal.name = "Explicit personal input"; personal.input.right.source = .mouse
personal.input.left.source = .keyboard; personal.sound = false
await model.loadProfile(personal)
XCTAssertNil(model.profileError); XCTAssertEqual(model.input.settings, personal.input)
XCTAssertFalse(try inputStore.loadState().automaticRightController)
let reset = await model.restoreAppDefaults()
XCTAssertTrue(reset); XCTAssertEqual(model.input.settings, .freshDefaults)
XCTAssertTrue(try inputStore.loadState().automaticRightController)
await withCheckedContinuation { done in model.shutdown { done.resume() } }
}
@MainActor func testDefaultRestoreRefusesUnsavedDiskAndRecording() async throws {
let f = try Fixture(); defer { f.remove() }
let suite = "VCCDefaultGuards-" + UUID().uuidString, defaults = UserDefaults(suiteName:suite)!