Files
VCCPlusOSS/platforms/macos/UITests/InteractionTests.swift
T

5115 lines
328 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-or-later
import XCTest
import AppKit
import CryptoKit
import AVFoundation
// Run using the VCCUITests scheme: its separate app identity and mandatory
// authored fixture keep personal ROMs, media, profiles and sessions untouched.
@MainActor
final class InteractionTests: XCTestCase {
private var app: XCUIApplication!
private var archiveCache: URL?
private var diskEditorFixtureFolder: URL?
private var projectSetupFixtureFolder: URL?
private var audioGameFixtureFolder: URL?
private var captureFixtureFolder: URL?
private var coverFixtureFolder: URL?
private var continuityFixtureFolder: URL?
private var originalClipboard: [NSPasteboardItem]?
private var main: XCUIElement { app.windows["VCC UI Tests"] }
private var display: XCUIElement { main.descendants(matching: .any)["coco-display"].firstMatch }
private func requireFullManualEdition() throws {
struct Manifest: Decodable {
let schemaVersion: Int
let profile: String
let manuals: String
}
// XCUITest bundles can be nested inside the runner app. Find only the
// sibling build product, never an installed app or a source-tree marker.
var directory = Bundle(for: Self.self).bundleURL
for _ in 0..<7 {
let builtApp = directory.appendingPathComponent("VCC Plus OSS.app")
if FileManager.default.fileExists(atPath: builtApp.path) {
let manifest = builtApp.appendingPathComponent("Contents/Resources/BuildContent.json")
let value = try JSONDecoder().decode(Manifest.self, from: Data(contentsOf: manifest))
guard value.schemaVersion == 1,
(value.profile == "normal" && value.manuals == "full") ||
(value.profile == "source" && value.manuals == "lookup") else {
throw CocoaError(.fileReadCorruptFile)
}
if value.manuals == "lookup" {
throw XCTSkip("This content profile includes lookup; this workflow qualifies the full manuals.")
}
return
}
directory.deleteLastPathComponent()
}
// Explicit test-runner configuration is a fallback for runners whose
// bundled-app location is unavailable. Unknown/missing values fail.
switch ProcessInfo.processInfo.environment["VCC_BUILD_CONTENT_PROFILE"] {
case "normal": return
case "source": throw XCTSkip("The explicit source profile omits this full-manual workflow.")
default: throw CocoaError(.fileReadNoSuchFile)
}
}
override func setUpWithError() throws {
continueAfterFailure = false
app = XCUIApplication(bundleIdentifier: "com.brianholman.vccplus.oss.mac.uitesting")
if ["testManualLibraryPageFindAndKeywordSearch", "testBASICWorkspaceManualLibrarySignalWorkflow",
"testSystemHelpOpensManualIndexFromAnOpenChapter"].contains(where: { name.contains($0) }) {
try requireFullManualEdition()
}
// A different chat may have a consent dialog in the installed app.
// Never dismiss another app's prompts through XCTest's default monitor.
addUIInterruptionMonitor(withDescription: "Keep unrelated app dialogs untouched") { [weak self] element in
guard let self, let app = self.app else { return false }
do {
// Read immutable public snapshots once. A closing popover can
// vanish between live window/frame queries in this callback.
let interruption = try element.snapshot()
let frame = interruption.frame
let finite = [frame.minX, frame.minY, frame.width, frame.height].allSatisfy { $0.isFinite }
&& frame.width > 0 && frame.height > 0
var pending = [try app.snapshot()]
while let owned = pending.popLast() {
// AppKit exposes native alerts, sheets and the Caps Lock
// indicator as non-window containers. Require the same
// immutable identity inside this app's own snapshot;
// geometry alone must not accept another app's dialog.
let containers: [XCUIElement.ElementType] = [.window, .dialog, .sheet, .alert]
if finite, containers.contains(interruption.elementType),
owned.elementType == interruption.elementType,
owned.frame == frame,
owned.identifier == interruption.identifier,
owned.label == interruption.label {
// Leave owned modal interaction to the test's explicit
// control. Do not dismiss or claim to handle it here.
return false
}
pending.append(contentsOf: owned.children)
}
} catch {
// An unresolvable live interruption remains a failure below.
// Only a fresh absence check can establish that it vanished.
}
if !element.exists { return false }
let detail = XCTAttachment(string: "Interruption:\n" + element.debugDescription
+ "\n\nIsolated application:\n" + app.debugDescription)
detail.name = "Unowned interruption and isolated-app hierarchy"
detail.lifetime = .keepAlways
self.add(detail)
let screen = XCTAttachment(screenshot: XCUIScreen.main.screenshot())
screen.name = "Whole desktop at unowned interruption"
screen.lifetime = .keepAlways
self.add(screen)
XCTFail("An unexpected window interrupted the isolated test; leave it for its owner.")
return true
}
app.launchArguments = ["-ApplePersistenceIgnoreState", "YES", "-NSQuitAlwaysKeepsWindows", "NO"]
if name.contains("testArchiveLibraryAndManualsResumeAcrossProcessRelaunch") {
try requireFullManualEdition()
let token = UUID().uuidString
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityRelaunch-" + token)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
try token.write(to: folder.appendingPathComponent("fixture-owner"), atomically: true, encoding: .utf8)
continuityFixtureFolder = folder
app.launchEnvironment["VCC_CONTINUITY_TEST_ROOT"] = folder.path
}
if name.contains("testPersonalLibraryCover") {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCoverUI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
coverFixtureFolder = folder
app.launchEnvironment["VCC_COVER_DRAG_TRACE"] = folder.appendingPathComponent("drag-trace.txt").path
app.launchEnvironment["VCC_COVER_DRAG_SOURCE"] = folder.appendingPathComponent("Blue Cover.png").path
}
if name.contains("testCoCoCapture") {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCaptureUI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
captureFixtureFolder = folder; app.launchEnvironment["VCC_CAPTURE_TEST_DIRECTORY"] = folder.path
}
if name.contains("CompactOS9") { app.launchArguments.append("--disk-editor-compact-fixture") }
if name.contains("testDiskImageEditor") {
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let format = name.contains("OS9") ? "OS9" : "DECB"
let fixture = mac.appendingPathComponent("Tests/Fixtures/DiskEditor/" + format + ".dsk")
_ = try Data(contentsOf: fixture) // A missing authored fixture is a failure, not a compatibility skip.
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCDiskEditorUI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
diskEditorFixtureFolder = folder
app.launchEnvironment["VCC_DISK_EDITOR_PROMISE_TRACE"] = folder.appendingPathComponent("promise-trace.txt").path
if name.contains("HardDisk") {
let combined = folder.appendingPathComponent("combined-fixture.vhd")
let decb = try Data(contentsOf: mac.appendingPathComponent("Tests/Fixtures/DiskEditor/DECB.dsk"))
var bytes = try Data(contentsOf: fixture)
bytes.append(decb); bytes.append(decb); bytes.append(Data(repeating: 0xA5, count: 512))
try bytes.write(to: combined)
app.launchEnvironment["VCC_DISK_EDITOR_TEST_IMAGE"] = combined.path
app.launchEnvironment["VCC_DISK_EDITOR_TEST_HARD"] = "1"
} else if name.contains("Supplementary") {
let extended = folder.appendingPathComponent("extended-fixture.dsk")
var bytes = try Data(contentsOf: fixture)
bytes.append(Data(repeating: 0xA5, count: 161280))
try bytes.write(to: extended)
app.launchEnvironment["VCC_DISK_EDITOR_TEST_IMAGE"] = extended.path
} else {
app.launchEnvironment["VCC_DISK_EDITOR_TEST_IMAGE"] = fixture.path
}
app.launchEnvironment["VCC_DISK_EDITOR_TEST_RECEIPT"] = folder.appendingPathComponent("fixture.json").path
}
if name.contains("testArchiveLibrary") {
let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
.deletingLastPathComponent().deletingLastPathComponent()
let store = repo.appendingPathComponent("media/knowledge-base")
// Match normal packaging: prefer the prepared local index and avoid
// touching the optional external research volume during UI setup.
let localIndex = repo.appendingPathComponent("media/app-inputs/archive-library/ArchiveLibrary.sqlite")
let index = FileManager.default.fileExists(atPath: localIndex.path) ? localIndex :
store.appendingPathComponent("archive-library/ArchiveLibrary.sqlite")
try XCTSkipUnless(FileManager.default.fileExists(atPath: index.path), "Stage the local Archive Library index.")
let cache = FileManager.default.temporaryDirectory.appendingPathComponent("VCCArchiveReader-" + UUID().uuidString)
try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: false)
archiveCache = cache
func seed(_ relative: String, as filename: String) throws {
// Stage optional retained originals before launching XCTest when
// the research store is on a removable volume. File access in
// setUp must not wait indefinitely on an unseen system prompt.
let staged = repo.appendingPathComponent(".build/archive-ui-fixtures").appendingPathComponent(relative)
let original = FileManager.default.fileExists(atPath: staged.path) ? staged :
store.appendingPathComponent("originals/archive-documents").appendingPathComponent(relative)
try XCTSkipUnless(FileManager.default.fileExists(atPath: original.path), "Stage the Archive fixture " + relative)
let data = try Data(contentsOf: original)
XCTAssertEqual(SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(),
(filename as NSString).deletingPathExtension, "Retained fixture must match the indexed original")
try data.write(to: cache.appendingPathComponent(filename), options: .atomic)
}
if name.contains("testArchiveLibraryAndManualsResumeAcrossProcessRelaunch") {
try seed("Magazines/MOTD/MOTD 1986 04.pdf", as: "917d4da1916fd14cd89f20da6fea5474e807a16e723f05055231992e430e6d33.pdf")
try seed("Walkthroughs/Sierra Games/King's Quest I Map (Sierra).png",
as: "1ed75351da8136ed8c2eafb6c3b93d92af411bbdb8f616ced57282d155d1a5f5.png")
app.launchArguments += ["-archive-library.collection", "Walkthroughs/Sierra Games"]
} else if name.contains("testArchiveLibraryRelatedReferenceFromSoftware") {
try seed("Walkthroughs/Raaka-Tu Walkthrough (Tandy).txt", as: "e55b30ce36985c0ff35ade23152828e090014bae1b8ddcadd50b02b90f72c7dc.txt")
} else if name.contains("testArchiveLibraryBrowsesTextAndImageInline") {
try seed("Walkthroughs/Sierra Games/AGI Quest I Walkthrough (Juha Terho).txt",
as: "563a8fe2ba0e251227fb05c1ac6a4bfe965bc3e124bb91547f8bae493adab68a.txt")
try seed("Walkthroughs/Sierra Games/King's Quest I Map (Sierra).png",
as: "1ed75351da8136ed8c2eafb6c3b93d92af411bbdb8f616ced57282d155d1a5f5.png")
app.launchArguments += ["-archive-library.collection", "Walkthroughs/Sierra Games"]
} else {
try seed("Magazines/MOTD/MOTD 1986 04.pdf", as: "917d4da1916fd14cd89f20da6fea5474e807a16e723f05055231992e430e6d33.pdf")
}
app.launchEnvironment["VCC_ARCHIVE_TEST_CACHE"] = cache.path
app.launchArguments += ["-archive-library.scope", "NO", "-archive-library.browse-offset", "0"]
}
if name.contains("testFirstUseProfileGuides") { app.launchArguments.append("--first-guide-fixture") }
if name.contains("testMacShellGuestPermission") { app.launchArguments.append("--shell-permission-fixture") }
if name.contains("testPrinterOutput") { app.launchArguments.append("--printer-fixture") }
if name.contains("testSDC") { app.launchArguments.append("--sdc-fixture") }
if name.contains("SoftwareLibraryFilters") { app.launchArguments += ["-VCCUITestAppearance", "light"] }
if name.contains("SoftwareLibraryInstall") { app.launchArguments.append("--library-install-fixture") }
if name.contains("SoftwareLibraryPlay") { app.launchArguments.append("--library-play-fixture") }
if name.contains("testBASICWorkspace") {
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let system = mac.appendingPathComponent("LocalResources/ROMs/coco3.rom")
let disk = mac.appendingPathComponent("LocalResources/ROMs/disk11.rom")
try XCTSkipUnless(FileManager.default.fileExists(atPath: system.path) && FileManager.default.fileExists(atPath: disk.path), "Local BASIC ROMs required")
app.launchEnvironment["VCC_BASIC_SYSTEM_ROM"] = system.path
app.launchEnvironment["VCC_BASIC_DISK_ROM"] = disk.path
}
if name.contains("testAudioGameCartridgePlayback") {
guard let disk = ProcessInfo.processInfo.environment["VCC_AUDIO_GAME_DISK"] else { throw XCTSkip("Supply a private DOS-boot disk through VCC_AUDIO_GAME_DISK") }
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let roms = mac.appendingPathComponent("LocalResources/ROMs")
for file in ["coco3.rom", "disk11.rom", "pic-7040-510.bin", "sp0256-al2.bin", "orch90.rom"] {
try XCTSkipUnless(FileManager.default.fileExists(atPath: roms.appendingPathComponent(file).path), "Supply the local audio-validation ROMs")
}
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCAudioGameUI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
audioGameFixtureFolder = folder
app.launchArguments += ["--audio-game-listening", roms.path, disk]
app.launchEnvironment["VCC_AUDIO_GAME_RECEIPT"] = folder.appendingPathComponent("audio.json").path
}
app.launch()
if name.contains("testAudioGameCartridgePlayback") {
app.activate()
// A manual quit can retain a closed single-window scene. Reopen
// it through the same public Window command available to users.
menu("Window", "VCC UI Tests")
}
XCTAssertTrue(main.waitForExistence(timeout: 15))
XCTAssertTrue(main.buttons["execution"].waitForExistence(timeout: 10))
let expectsAuthoredFD0 = !name.contains("testSDC") && !name.contains("testFirstUseProfileGuides") && !name.contains("testAudioGameCartridgePlayback")
// Startup can briefly run its starter media before the asynchronous
// authored fixture replaces it. Wait for the required fixture identity
// as well as running state, within the existing readiness deadline.
let ready = NSPredicate { _, _ in
self.main.buttons["execution"].label == "Pause" && self.session().count == 5 &&
(!expectsAuthoredFD0 || self.main.links["FD0 Authored FD0.dsk"].exists)
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 15), .completed)
if !name.contains("testSDC") && !name.contains("testFirstUseProfileGuides") && !name.contains("testAudioGameCartridgePlayback") { XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists) }
}
override func tearDownWithError() throws {
if let saved = originalClipboard {
NSPasteboard.general.clearContents()
if !saved.isEmpty { XCTAssertTrue(NSPasteboard.general.writeObjects(saved), "Restore the original clipboard items") }
}
defer {
if let archiveCache { try? FileManager.default.removeItem(at: archiveCache) }
if let diskEditorFixtureFolder { try? FileManager.default.removeItem(at: diskEditorFixtureFolder) }
if let projectSetupFixtureFolder { try? FileManager.default.removeItem(at: projectSetupFixtureFolder) }
if let audioGameFixtureFolder { try? FileManager.default.removeItem(at: audioGameFixtureFolder) }
if let captureFixtureFolder { try? FileManager.default.removeItem(at: captureFixtureFolder) }
if let coverFixtureFolder { try? FileManager.default.removeItem(at: coverFixtureFolder) }
if let continuityFixtureFolder {
let suite = continuityFixtureFolder.lastPathComponent
UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite)
try? FileManager.default.removeItem(at: continuityFixtureFolder)
}
}
if let app, app.state != .notRunning {
if (testRun?.failureCount ?? 0) > 0 {
let tree = XCTAttachment(string: app.debugDescription)
tree.name = "UI hierarchy"; tree.lifetime = .keepAlways; add(tree)
}
let shot = XCTAttachment(screenshot: app.screenshot())
shot.name = name; shot.lifetime = .keepAlways; add(shot)
app.terminate()
}
}
private func session() -> [UInt64] {
(display.value as? String ?? "").split(separator: ",").compactMap { UInt64($0) }
}
// A menu that survived only because UI/emulation polling stopped is a failure.
private func liveHold(_ element: XCUIElement, seconds: Double = 2) {
let before = session(); XCTAssertEqual(before.count, 5)
let end = Date().addingTimeInterval(seconds)
repeat {
XCTAssertTrue(element.exists && element.isHittable, "Control vanished during live refresh")
Thread.sleep(forTimeInterval: 0.2)
} while Date() < end
let after = session(); XCTAssertEqual(after.count, 5)
guard before.count == 5, after.count == 5 else { return }
XCTAssertEqual(after[0], before[0], "UI interaction reset the machine")
XCTAssertGreaterThan(after[1], before[1], "Frames must continue while the control is open")
XCTAssertEqual(after[2], before[2], "UI interaction restarted audio")
}
func testAudioGameCartridgePlayback() throws {
let receipt = try XCTUnwrap(audioGameFixtureFolder).appendingPathComponent("audio.json")
let ready = NSPredicate { _, _ in FileManager.default.fileExists(atPath: receipt.path) }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 90), .completed)
let data = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: receipt)) as? [String: Any])
func count(_ name: String) throws -> UInt64 { try XCTUnwrap(data[name] as? NSNumber).uint64Value }
XCTAssertEqual(data["audio_enabled"] as? Bool, true)
XCTAssertGreaterThan(try XCTUnwrap(data["volume"] as? Double), 0)
XCTAssertGreaterThan(try count("frames_after"), try count("frames_before"))
XCTAssertGreaterThan(try count("consumed_after"), try count("consumed_before"))
XCTAssertGreaterThan(try count("starts_before"), 0)
XCTAssertEqual(try count("starts_after"), try count("starts_before"))
XCTAssertEqual(try count("signal_after"), try count("signal_before"), "Actual output stays silent without muting or restarting the audio engine")
XCTAssertEqual(try count("tape_position"), 0)
let record = XCTAttachment(data: try Data(contentsOf: receipt), uniformTypeIdentifier: "public.json")
record.name = "Native idle audio counters"; record.lifetime = .keepAlways; add(record)
app.activate()
let shot = XCTAttachment(screenshot: main.screenshot())
shot.name = "Game title with Speech-Sound and Orchestra-90"; shot.lifetime = .keepAlways; add(shot)
}
func testArchiveLibraryKeyboardAndClipboard() throws {
// Restore even rich, multi-item pasteboards on failure. Resolve promised data
// before copying anything, and keep the user's original contents out of logs.
originalClipboard = try (NSPasteboard.general.pasteboardItems ?? []).map { item in
let saved = NSPasteboardItem()
for type in item.types {
guard let data = item.data(forType: type), saved.setData(data, forType: type) else {
throw XCTSkip("The current clipboard contains a representation that cannot be preserved.")
}
}
return saved
}
let before = session()
menu("Help", "Archive Library…")
let window = app.windows["Archive Library"]
let search = window.textFields["archive-search"]
XCTAssertTrue(search.waitForExistence(timeout: 10))
app.typeKey("f", modifierFlags: [.command, .shift])
app.typeText("MOTD strip buffer")
XCTAssertEqual(search.value as? String, "MOTD strip buffer")
let first = window.outlines["archive-results-list"].descendants(matching: .outlineRow)
.containing(.staticText, identifier: "PDF page 4").firstMatch
XCTAssertTrue(first.waitForExistence(timeout: 5))
XCTAssertFalse(window.textFields["archive-pdf-find"].exists, "Typing a query alone should not open a scan")
func layout(_ listID: String) -> [String: CGRect] {
// AXOutline can describe its entire row content. Its scroll view is
// the visible viewport the user expects to stay put during searches.
let collections = window.scrollViews.containing(.outline, identifier: "Archive collections").firstMatch
let list = window.scrollViews.containing(.outline, identifier: listID).firstMatch
XCTAssertTrue(collections.exists && list.exists, "Both Archive viewports must be exposed")
return ["window": window.frame, "search": search.frame, "collections": collections.frame, "list": list.frame]
}
let originalLayout = layout("archive-results-list")
func checkLayout(_ listID: String, state: String) {
for (name, frame) in layout(listID) {
guard let original = originalLayout[name] else { return XCTFail("Missing baseline for " + name) }
XCTAssertEqual(frame.minX, original.minX, accuracy: 2, "\(state): \(name) left")
XCTAssertEqual(frame.minY, original.minY, accuracy: 2, "\(state): \(name) top")
XCTAssertEqual(frame.maxX, original.maxX, accuracy: 2, "\(state): \(name) right")
XCTAssertEqual(frame.maxY, original.maxY, accuracy: 2, "\(state): \(name) bottom")
}
}
func expectPDFPage(_ number: Int) {
let page = window.textFields["PDF page number"]
let selected = NSPredicate { _, _ in page.exists && page.value as? String == String(number) }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: selected, object: nil)], timeout: 10), .completed,
"Selecting the result must open PDF page \(number) without another action")
}
// Raise this actual reader window and click the visible row's center.
// Native outline rows can omit an AX hit point on this SDK.
window.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.015)).click()
first.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).click()
expectPDFPage(4)
XCTAssertTrue(window.buttons["Copy Snippet"].waitForExistence(timeout: 5))
let pdfShot = XCTAttachment(screenshot: window.screenshot())
pdfShot.name = "Archive Library — cited PDF page and reviewed snippet"; pdfShot.lifetime = .keepAlways; add(pdfShot)
app.typeKey(.downArrow, modifierFlags: [])
expectPDFPage(12)
app.typeKey(.upArrow, modifierFlags: [])
expectPDFPage(4)
let find = window.textFields["archive-pdf-find"]
XCTAssertTrue(find.exists)
window.buttons["archive-copy-citation"].click()
let expectedCitation = "MOTD 1986 04 · PDF page 4 · Color Computer Archive · https://colorcomputerarchive.com/repo/Documents/Magazines/MOTD/MOTD%201986%2004.pdf#page=4"
XCTAssertTrue(NSPasteboard.general.string(forType: .string) == expectedCitation, "Copy the cited upstream page exactly")
window.buttons["Copy Snippet"].click()
let expectedSource = "C$CR set $0D\nC$LF set $0A\nC$BS set $08\nC$ASCC set 'C\nC$ASCL set 'L\nC$ASCB set 'B\nC$ASCD set 'D\n"
XCTAssertTrue(NSPasteboard.general.string(forType: .string) == expectedSource, "Preserve reviewed source and its trailing newline")
let sourceShot = XCTAttachment(screenshot: window.screenshot())
sourceShot.name = "Archive Library — reviewed source copied"; sourceShot.lifetime = .keepAlways; add(sourceShot)
app.typeKey("f", modifierFlags: .command)
app.typeText("unfindabletext")
XCTAssertEqual(find.value as? String, "unfindabletext")
app.typeKey(.return, modifierFlags: [])
XCTAssertTrue(window.staticTexts["No matching text in the PDF’s text layer."].waitForExistence(timeout: 5))
app.typeKey("f", modifierFlags: [.command, .shift])
app.typeKey("a", modifierFlags: .command)
app.typeText("nxqmissingarchiveword")
XCTAssertTrue(window.staticTexts["No matching pages"].waitForExistence(timeout: 5))
checkLayout("archive-results-list", state: "No matches")
app.typeKey("a", modifierFlags: .command)
app.typeKey(.delete, modifierFlags: [])
XCTAssertEqual(search.value as? String, "")
XCTAssertTrue(window.descendants(matching: .any)["archive-browse-list"].firstMatch.waitForExistence(timeout: 3))
checkLayout("archive-browse-list", state: "Back to browse")
let after = session()
XCTAssertEqual(after.count, 5)
XCTAssertEqual(after[0], before[0], "Archive keyboard use must preserve the machine session")
XCTAssertGreaterThan(after[1], before[1], "The guest must continue advancing")
XCTAssertEqual(after[3], before[3], "Archive search and navigation must not type into the guest")
}
func testArchiveLibraryBrowsesTextAndImageInline() {
menu("Help", "Archive Library…")
let window = app.windows["Archive Library"]
func captureReader(_ name: String) {
let shot = XCTAttachment(screenshot: window.screenshot())
shot.name = name
shot.lifetime = .keepAlways
add(shot)
}
let browse = window.descendants(matching: .any)["archive-browse-list"].firstMatch
let walkthrough = browse.staticTexts["AGI Quest I Walkthrough (Juha Terho)"]
XCTAssertTrue(walkthrough.waitForExistence(timeout: 10))
walkthrough.click()
let text = window.textViews["archive-inline-text"]
XCTAssertTrue(text.waitForExistence(timeout: 5))
XCTAssertTrue((text.value as? String)?.contains("You start off on the beach with a rope") == true)
captureReader("Archive Library walkthrough text")
if window.buttons["Browse"].exists { window.buttons["Browse"].click() }
let map = browse.staticTexts["King's Quest I Map (Sierra)"]
XCTAssertTrue(map.exists)
map.click()
XCTAssertTrue(window.images["archive-inline-image"].waitForExistence(timeout: 5))
XCTAssertFalse(text.exists)
XCTAssertTrue(window.buttons["archive-copy-citation"].exists)
captureReader("Archive Library Sierra map")
let fit = window.buttons["Fit Image"]
XCTAssertFalse(fit.isEnabled)
window.buttons["Zoom in"].click()
XCTAssertTrue(fit.isEnabled)
XCTAssertTrue(window.buttons["Zoom out"].isEnabled)
fit.click()
XCTAssertFalse(window.buttons["Zoom out"].isEnabled)
func resize(toWidth width: CGFloat) {
let change = width - window.frame.width
guard abs(change) > 2 else { return }
let corner = window.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(CGVector(dx: change, dy: 0)))
}
let originalWidth = window.frame.width
defer { resize(toWidth: originalWidth) }
resize(toWidth: 730)
XCTAssertLessThan(window.frame.width, 790, "The Archive window must enter the compact layout")
let image = window.images["archive-inline-image"]
XCTAssertTrue(image.waitForExistence(timeout: 5))
let back = window.buttons["Browse"]
XCTAssertTrue(back.isHittable)
captureReader("Archive Library compact map")
back.click()
XCTAssertTrue(map.waitForExistence(timeout: 3))
XCTAssertFalse(image.exists)
map.click()
XCTAssertTrue(image.waitForExistence(timeout: 5), "Clicking the selected map again must reopen it in compact view")
XCTAssertTrue(back.isHittable)
}
func testTalkingLanderTemplateChoiceOpensNewProjectPanel() {
menu("Develop", "C Development…")
let editor = app.windows["C Development"]
XCTAssertTrue(editor.waitForExistence(timeout: 10))
editor.buttons["New"].click()
let lander = app.buttons["Talking Planet Lander"].firstMatch
XCTAssertTrue(lander.waitForExistence(timeout: 5))
let shot = XCTAttachment(screenshot: app.screenshot())
shot.name = "C project templates"
shot.lifetime = .keepAlways
add(shot)
clickOwnedAlert(message: "Choose a C project template", button: "Talking Planet Lander",
action: "Talking Planet Lander", additionalButtons: ["Hello Disk", "Hello World"])
XCTAssertTrue(app.buttons["Create Project"].firstMatch.waitForExistence(timeout: 5))
app.typeKey(.escape, modifierFlags: [])
XCTAssertTrue(editor.buttons["New"].isEnabled)
}
func testCWorkspaceAndAssistantDocumentation() throws {
let parent = FileManager.default.temporaryDirectory.appendingPathComponent("VCCManualC-" + UUID().uuidString)
let folder = parent.appendingPathComponent("Workbench")
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
defer {
app.terminate()
try? FileManager.default.removeItem(at: parent)
}
let source = "#include <coco.h>\n\nint main(void)\n{\n puts(\"HELLO FROM THE COCO WORKBENCH\");\n return 0;\n}\n"
let makefile = "CMOC ?= cmoc\n\nall: main.bin\n\nmain.bin: main.c\n\t\"$(CMOC)\" --coco --intermediate -O0 -fno-omit-frame-pointer --org=2800 -o $@ $<\n"
try Data(source.utf8).write(to: folder.appendingPathComponent("main.c"))
try Data(makefile.utf8).write(to: folder.appendingPathComponent("Makefile"))
let before = session()
menu("Develop", "C Development…")
let workspace = app.windows["C Development"]
XCTAssertTrue(workspace.waitForExistence(timeout: 5))
workspace.buttons["Open"].click()
let open = app.buttons["Open"].firstMatch
XCTAssertTrue(open.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift])
let path = app.textFields["PathTextField"].firstMatch
XCTAssertTrue(path.waitForExistence(timeout: 5))
path.click(); app.typeKey("a", modifierFlags: .command); path.typeText(folder.path)
app.typeKey(.return, modifierFlags: [])
diskEditorWait("The authored C project folder must be ready to open") { open.isEnabled }
open.click()
let assistant = workspace.buttons["Assistant…"]
diskEditorWait("Opening an ordinary project must enable its Assistant control") { assistant.exists && assistant.isEnabled }
XCTAssertTrue(workspace.textViews.firstMatch.waitForExistence(timeout: 5))
let workspaceShot = XCTAttachment(screenshot: workspace.screenshot())
workspaceShot.name = "C Development — current project workspace"; workspaceShot.lifetime = .keepAlways; add(workspaceShot)
assistant.click()
let access = app.dialogs["C Project Assistant Access"]
XCTAssertTrue(access.waitForExistence(timeout: 5))
XCTAssertTrue(access.checkBoxes["Allow Disposable Playtests"].exists)
XCTAssertTrue(access.checkBoxes["Use Project Makefile"].exists)
XCTAssertTrue(access.buttons["Save Private Connection…"].exists)
let accessShot = XCTAttachment(screenshot: access.screenshot())
accessShot.name = "C Development — native Assistant permission choices"; accessShot.lifetime = .keepAlways; add(accessShot)
access.buttons[XCUIIdentifierCloseWindow].click()
XCTAssertEqual(session()[0], before[0], "Reading workspace and consent controls must not restart the CoCo")
XCTAssertEqual(try String(contentsOf: folder.appendingPathComponent("main.c"), encoding: .utf8), source)
XCTAssertFalse(FileManager.default.fileExists(atPath: folder.appendingPathComponent("main.bin").path), "Opening and inspecting consent must not execute Make")
}
func testProjectSetupPromptCopiesEditsAndResetWithoutChangingAccess() throws {
// Use the isolated app's authored default draft and a native read-only
// export. Never register a connection in the user's ChatGPT settings.
originalClipboard = try (NSPasteboard.general.pasteboardItems ?? []).map { item in
let saved = NSPasteboardItem()
for type in item.types {
guard let data = item.data(forType: type), saved.setData(data, forType: type) else {
throw XCTSkip("The current clipboard contains a representation that cannot be preserved.")
}
}
return saved
}
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCProjectSetupUI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
projectSetupFixtureFolder = folder
let grant = folder.appendingPathComponent("Authored Read Only Connection.json")
let before = session()
menu("Develop", "Connect to ChatGPT…")
let access = app.dialogs["Connect to ChatGPT or Another Assistant"]
XCTAssertTrue(access.waitForExistence(timeout: 5))
let export = access.buttons["mcp.access.grant"]
XCTAssertTrue(export.waitForExistence(timeout: 5))
XCTAssertEqual(export.label, "Save Read-Only Connection…")
export.click()
diskEditorSavePanel(to: grant)
let grantBytes = try Data(contentsOf: grant)
let exported = try XCTUnwrap(JSONSerialization.jsonObject(with: grantBytes) as? [String: Any])
let token = try XCTUnwrap(exported["token"] as? String)
XCTAssertEqual(exported["canPropose"] as? Bool, false)
let copy = access.buttons["mcp.projectSetup.copy"]
let edit = access.buttons["mcp.projectSetup.edit"]
diskEditorWait("The bundled project starter must load into the connection interface") {
copy.exists && copy.isEnabled && edit.exists && edit.isEnabled
}
// At compact width the existing first-prompt and new setup controls must
// remain reachable in the native scrolling access panel.
let corner = access.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(CGVector(dx: 380 - access.frame.width, dy: 430 - access.frame.height)))
XCTAssertLessThan(access.frame.width, 425, "Actually enter the compact connection layout")
if !copy.isHittable { access.scrollViews.firstMatch.swipeUp() }
XCTAssertTrue(copy.isHittable && edit.isHittable)
liveHold(copy, seconds: 1)
let compactShot = XCTAttachment(screenshot: access.screenshot())
compactShot.name = "Project setup — compact connection controls"; compactShot.lifetime = .keepAlways; add(compactShot)
copy.click()
let starterCopy = try XCTUnwrap(NSPasteboard.general.string(forType: .string))
XCTAssertTrue(starterCopy.contains(grant.path), "Copy the current exported connection path")
XCTAssertTrue(starterCopy.contains("/Contents/Helpers/vcc-mcp"), "Use the running app's helper")
XCTAssertTrue(starterCopy.contains("identify my shared BASIC draft"), "Keep the existing first read-only request for this connection")
XCTAssertFalse(starterCopy.contains(token), "Connection secrets must never reach the clipboard")
edit.click()
let instructions = app.textViews["mcp.projectSetup.instructions"].firstMatch
let editorCopy = app.buttons["mcp.projectSetup.editorCopy"].firstMatch
XCTAssertTrue(instructions.waitForExistence(timeout: 5))
let starterText = try XCTUnwrap(instructions.value as? String)
XCTAssertFalse(starterText.isEmpty)
XCTAssertTrue(starterCopy.hasPrefix(starterText.trimmingCharacters(in: .whitespacesAndNewlines)))
let custom = "Build an original keyboard game for a 128 KB CoCo 3.\nUse the installed BASIC manual first."
instructions.click(); app.typeKey("a", modifierFlags: .command)
NSPasteboard.general.clearContents(); NSPasteboard.general.setString(custom, forType: .string)
instructions.typeKey("v", modifierFlags: .command)
diskEditorWait("The native prompt editor must retain the user's instructions") { instructions.value as? String == custom }
app.buttons["Done"].firstMatch.click()
diskEditorWait("Closing the editor must restore the connection panel") { !editorCopy.exists && edit.isHittable }
copy.click()
let editedCopy = try XCTUnwrap(NSPasteboard.general.string(forType: .string))
XCTAssertTrue(editedCopy.hasPrefix(custom))
XCTAssertTrue(editedCopy.contains(grant.path))
XCTAssertFalse(editedCopy.contains(token))
edit.click()
XCTAssertTrue(instructions.waitForExistence(timeout: 5))
XCTAssertEqual(instructions.value as? String, custom, "Reopening the sheet must preserve edits")
XCTAssertTrue(editorCopy.isHittable)
editorCopy.click()
XCTAssertEqual(NSPasteboard.general.string(forType: .string), editedCopy, "Both copy buttons use the same edited prompt and current connection")
let editorShot = XCTAttachment(screenshot: access.screenshot())
editorShot.name = "Project setup — editable starter and copy controls"; editorShot.lifetime = .keepAlways; add(editorShot)
app.buttons["mcp.projectSetup.reset"].firstMatch.click()
XCTAssertEqual(instructions.value as? String, starterText, "Reset restores the bundled starter only on explicit request")
editorCopy.click()
XCTAssertEqual(NSPasteboard.general.string(forType: .string), starterCopy)
app.buttons["Done"].firstMatch.click()
XCTAssertEqual(try Data(contentsOf: grant), grantBytes, "Copy, edit and reset must not change the connection's permissions or contents")
let after = session()
XCTAssertEqual(after[0], before[0], "Project setup controls must preserve the running machine")
XCTAssertGreaterThan(after[1], before[1], "The guest continues while the editor is open")
XCTAssertEqual(after[2], before[2], "Project setup must not restart audio")
XCTAssertEqual(after[3], before[3], "Typing the prompt must not type into the guest")
let revoke = access.buttons["mcp.access.revoke"]
if !revoke.isHittable { access.scrollViews.firstMatch.swipeUp() }
revoke.click()
diskEditorWait("Revoke the isolated test's connection before cleanup") { !FileManager.default.fileExists(atPath: grant.path) }
}
private func menu(_ title: String, _ item: String) {
app.menuBars.menuBarItems[title].click()
app.menuBars.menuBarItems[title].menus.menuItems[item].firstMatch.click()
}
private func expand(_ triangle: XCUIElement) {
XCTAssertTrue(triangle.waitForExistence(timeout: 3))
// A native disclosure's AX bounds can include its full header width.
// On this SDK its reported bounds also begin 22.5 points before
// the visible arrow. Target that arrow, not empty header space.
if (triangle.value as? NSNumber)?.intValue != 1 {
triangle.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0.5))
.withOffset(CGVector(dx: 28, dy: 0)).click()
}
}
private func videoMenu() -> XCUIElement {
main.menuButtons["Settings"].click()
main.menuButtons["Settings"].descendants(matching: .menuItem)["Video Signal"].hover()
let rgb = main.menuButtons["Settings"].descendants(matching: .menuItem)["RGB Monitor"]
XCTAssertTrue(rgb.waitForExistence(timeout: 3)); return rgb
}
private func pasteBASICSource(_ source: String, into editor: XCUIElement) {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(source, forType: .string)
editor.typeKey("v", modifierFlags: .command)
}
private func preserveClipboard() throws {
guard originalClipboard == nil else { return }
originalClipboard = try (NSPasteboard.general.pasteboardItems ?? []).map { item in
let saved = NSPasteboardItem()
for type in item.types {
guard let data = item.data(forType: type), saved.setData(data, forType: type) else {
throw XCTSkip("The current clipboard contains a representation that cannot be preserved.")
}
}
return saved
}
}
private var operatorAssistanceEnabled: Bool {
ProcessInfo.processInfo.environment["VCC_UI_OPERATOR_ASSISTANCE"] == "1"
}
private func waitForOperator(kind: String, request: [String: Any], until observed: @escaping () -> Bool) {
guard operatorAssistanceEnabled else {
XCTFail("Operator assistance must be explicitly enabled in the UI test runner"); return
}
let bundle = "com.brianholman.vccplus.oss.mac.uitesting"
let running = NSRunningApplication.runningApplications(withBundleIdentifier: bundle)
guard running.count == 1, let owner = running.first, owner.processIdentifier > 0,
owner.isActive, app.state == .runningForeground else {
XCTFail("Exactly one isolated test app must own the foreground before requesting assistance"); return
}
var marker = request
marker["id"] = UUID().uuidString
marker["test"] = name
marker["bundleIdentifier"] = bundle
marker["pid"] = Int(owner.processIdentifier)
marker["kind"] = kind
marker["mode"] = "operator-assisted"
marker["event"] = "request"
func emit(_ prefix: String, _ value: [String: Any]) -> String? {
guard let bytes = try? JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]),
let json = String(data: bytes, encoding: .utf8) else {
XCTFail("The operator request must be valid structured JSON"); return nil
}
// FileHandle writes directly to stdout, avoiding buffered markers
// while an external operator observes this bounded XCTest wait.
FileHandle.standardOutput.write(Data(("\n" + prefix + " " + json + "\n").utf8))
return json
}
guard let requested = emit("VCC_UI_OPERATOR_REQUEST", marker) else { return }
let started = Date()
let condition = NSPredicate { _, _ in observed() }
let result = XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: condition, object: nil)], timeout: 90)
marker["event"] = "resolved"
marker["status"] = result == .completed ? "completed" : (result == .timedOut ? "timed_out" : "failed")
marker["waiterResult"] = result.rawValue
marker["elapsedSeconds"] = Date().timeIntervalSince(started)
let resolved = emit("VCC_UI_OPERATOR_RESOLVED", marker) ?? "Resolution could not be encoded."
let receipt = XCTAttachment(string: requested + "\n" + resolved)
receipt.name = "Operator-assisted native UI action"; receipt.lifetime = .keepAlways; add(receipt)
XCTAssertEqual(result, .completed, "The requested native UI outcome must be observed within 90 seconds")
}
private func clickOwnedAlert(message: String, button title: String, action: String, additionalButtons: [String] = []) {
// Deterministic confirmations always retain their exact native controls.
// Some OS/XCTest combinations misidentify background windows as blocking
// an alert. Explicit qualification mode allows an operator to perform
// that same UI action; it never changes app state through a test hook.
let expectedButtons = ["Cancel", action] + additionalButtons
guard Set(expectedButtons).count == expectedButtons.count, expectedButtons.contains(title) else {
XCTFail("The requested button must belong to a unique exact set of expected alert choices"); return
}
func expectedAlert() -> XCUIElement? {
let messagePredicate = NSPredicate(format: "value == %@ OR label == %@", message, message)
return (app.dialogs.allElementsBoundByIndex + app.alerts.allElementsBoundByIndex).first {
candidate in candidate.staticTexts.matching(messagePredicate).count == 1 &&
candidate.buttons.count == expectedButtons.count &&
expectedButtons.allSatisfy { candidate.buttons.matching(identifier: $0).count == 1 }
}
}
let present = NSPredicate { _, _ in expectedAlert() != nil }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: present, object: nil)], timeout: 8), .completed,
"Expected the isolated app's exact confirmation: " + message)
guard let alert = expectedAlert() else { return }
let button = alert.buttons[title]
XCTAssertEqual(alert.buttons.matching(identifier: title).count, 1)
let buttonsEnabled = expectedButtons.allSatisfy { alert.buttons[$0].isEnabled }
XCTAssertTrue(buttonsEnabled, "Every exact confirmation choice must be enabled")
let frame = button.frame, alertFrame = alert.frame
let frames = expectedButtons.map { alert.buttons[$0].frame }
let finite = ([alertFrame] + frames).allSatisfy {
[$0.minX, $0.minY, $0.width, $0.height].allSatisfy { $0.isFinite } && $0.width > 0 && $0.height > 0
}
let contained = frames.allSatisfy { alertFrame.contains($0) }
XCTAssertTrue(finite && contained && frame.width > 0 && frame.height > 0 && alertFrame.contains(frame),
"The exact confirmation button must have a finite frame inside its owned alert")
guard buttonsEnabled, finite, contained, frame.width > 0, frame.height > 0, alertFrame.contains(frame) else { return }
if operatorAssistanceEnabled {
waitForOperator(kind: "alert", request: ["message": message, "button": title, "action": action, "expectedButtons": expectedButtons]) {
expectedAlert() == nil
}
} else {
button.click()
}
let dismissed = NSPredicate { _, _ in expectedAlert() == nil }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: dismissed, object: nil)], timeout: 5), .completed,
"The exact requested confirmation must close after choosing " + title)
}
private func waitForCoCoScreenText(_ expected: String, timeout: TimeInterval = 5) {
let deadline = Date().addingTimeInterval(timeout)
var text = ""
repeat {
let before = NSPasteboard.general.changeCount
menu("Edit", "Copy CoCo Screen Text")
let copied = NSPredicate { _, _ in
NSPasteboard.general.changeCount != before && NSPasteboard.general.string(forType: .string) != nil
}
let remaining = max(0.1, deadline.timeIntervalSinceNow)
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: copied, object: nil)], timeout: min(2, remaining)), .completed,
"Copy CoCo Screen Text must finish before inspecting its new snapshot")
text = NSPasteboard.general.string(forType: .string) ?? ""
if text.contains(expected) { return }
} while Date() < deadline
let observation = XCTAttachment(string: text)
observation.name = "Last copied authored guest screen"; observation.lifetime = .keepAlways; add(observation)
XCTAssertTrue(text.contains(expected), "Fresh guest screen must contain: " + expected)
}
private func chooseBASICEarth(greeting: String) {
// This workflow covers ordinary field-timed emulated keyboard paste,
// rather than XCTest's very short physical key pulse. Dedicated host
// typing/focus tests continue to exercise keyDown/keyUp separately.
waitForCoCoScreenText("What planet do you live on?")
NSPasteboard.general.clearContents()
XCTAssertTrue(NSPasteboard.general.setString("1", forType: .string))
menu("Edit", "Paste Text into CoCo")
waitForCoCoScreenText(greeting)
}
func testEditorFindAndReplaceAndWindowShortcutRouting() {
menu("Develop", "BASIC Development…")
let basic = app.windows["BASIC Development"]
let editor = basic.textViews["basic.source-text"]
XCTAssertTrue(editor.waitForExistence(timeout: 5))
editor.click(); app.typeKey("a", modifierFlags: .command)
editor.typeText("10 PRINT \"EARTH earth\"")
app.typeKey("f", modifierFlags: [.command, .option])
let query = basic.textFields["source.find.query"]
XCTAssertTrue(query.waitForExistence(timeout: 3))
app.typeText("earth")
XCTAssertTrue(basic.staticTexts["2 matches"].waitForExistence(timeout: 3))
app.typeKey("g", modifierFlags: .command)
app.typeKey("g", modifierFlags: [.command, .shift])
basic.textFields["source.find.replacement"].click(); app.typeText("Mars")
basic.buttons["Replace All in File"].click()
XCTAssertEqual(editor.value as? String, "10 PRINT \"Mars Mars\"")
app.typeKey("z", modifierFlags: .command)
XCTAssertEqual(editor.value as? String, "10 PRINT \"EARTH earth\"")
let beforeEscape = "Source frame: \(editor.frame)\nFind field frame: \(query.frame)\n" + app.debugDescription
app.typeKey(.escape, modifierFlags: [])
if query.exists {
let focus = XCTAttachment(string: "Before Escape (including focused AX element):\n" + beforeEscape + "\nAfter Escape:\n" + app.debugDescription)
focus.name = "Find Escape responder diagnosis"; focus.lifetime = .keepAlways; add(focus)
let image = XCTAttachment(screenshot: basic.screenshot())
image.name = "BASIC Find after Escape"; image.lifetime = .keepAlways; add(image)
}
XCTAssertFalse(query.exists)
menu("Develop", "C Development…")
let c = app.windows["C Development"]
XCTAssertTrue(c.waitForExistence(timeout: 4))
app.typeKey("f", modifierFlags: [.command, .shift])
XCTAssertTrue(c.textFields["cmoc.search.query"].waitForExistence(timeout: 3))
app.typeKey("f", modifierFlags: .command)
XCTAssertTrue(c.textFields["source.find.query"].waitForExistence(timeout: 3))
c.buttons["Done"].click()
menu("Develop", "Assembly Development…")
let assembly = app.windows["Assembly Development"]
XCTAssertTrue(assembly.waitForExistence(timeout: 4))
assembly.buttons["source.find.open"].click()
let asmQuery = assembly.textFields["source.find.query"]
XCTAssertTrue(asmQuery.waitForExistence(timeout: 3))
app.typeText("planet")
app.typeKey(.return, modifierFlags: [])
app.typeKey(.return, modifierFlags: .shift)
app.typeKey(.escape, modifierFlags: [])
XCTAssertFalse(asmQuery.exists)
// AppKit owns the visible native completion popup. Prepared candidates
// alone do not prove that a popup is open or that it consumes Escape.
let asmSource = assembly.textViews["assembly-source"]
app.typeKey("a", modifierFlags: .command); app.typeText(" LD")
assembly.buttons["source.find.open"].click()
XCTAssertTrue(asmQuery.waitForExistence(timeout: 3))
asmSource.click(); app.typeKey(.rightArrow, modifierFlags: .command)
assembly.buttons["assembly-complete"].click()
let completions = app.descendants(matching: .any).matching(NSPredicate(format:
"label == %@ OR value == %@", "word completion suggestions", "word completion suggestions")).firstMatch
XCTAssertTrue(completions.waitForExistence(timeout: 3), "Open the actual native completion list")
app.typeKey(.escape, modifierFlags: [])
XCTAssertTrue(completions.waitForNonExistence(timeout: 3))
XCTAssertTrue(asmQuery.exists, "The completion popup consumes the first Escape")
XCTAssertEqual(asmSource.value as? String, " LD")
app.typeKey(.escape, modifierFlags: [])
XCTAssertFalse(asmQuery.exists, "The next Escape closes Find from the source editor")
XCTAssertEqual(asmSource.value as? String, " LD")
}
func testAssemblyWorkspaceDirectRunStepAndReferenceExample() {
menu("Develop", "Assembly Development…")
let workspace = app.windows["Assembly Development"]
XCTAssertTrue(workspace.waitForExistence(timeout: 5))
let editor = workspace.textViews["assembly-source"]
let original = editor.value as? String
XCTAssertTrue(original?.contains("What planet do you live on?") == true)
workspace.buttons["assembly-debug-entry"].click()
clickOwnedAlert(message: "Load this assembly program into the CoCo?", button: "Debug from Entry", action: "Debug from Entry")
let execution = workspace.staticTexts["assembly-execution"]
func waitForPC(_ pc: String) {
let matches = NSPredicate { _, _ in (execution.value as? String ?? execution.label).contains("PC $" + pc) }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: matches, object: nil)], timeout: 8), .completed)
}
waitForPC("3F00")
workspace.buttons["assembly-step"].click()
waitForPC("3F02")
workspace.buttons["assembly-step"].click()
waitForPC("F643") // Stepping into the ROM routine that sets WIDTH 40.
let stopped = XCTAttachment(screenshot: workspace.screenshot())
stopped.name = "Assembly Development"; stopped.lifetime = .keepAlways; add(stopped)
workspace.buttons["assembly-run"].click()
let running = NSPredicate { _, _ in self.main.buttons["execution"].label == "Pause" && self.main.isHittable }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: running, object: nil)], timeout: 8), .completed)
let beforeInput = session()
XCTAssertEqual(beforeInput.count, 5)
app.typeText("1")
let acceptedKey = NSPredicate { _, _ in
let current = self.session()
return beforeInput.count == 5 && current.count == 5 && current[3] > beforeInput[3]
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: acceptedKey, object: nil)], timeout: 5), .completed)
menu("Develop", "Assembly Quick Reference…")
let reference = app.windows["Assembly Quick Reference"]
XCTAssertTrue(reference.waitForExistence(timeout: 5))
let example = reference.buttons["Open Example"]
XCTAssertTrue(example.waitForExistence(timeout: 5))
let ref = XCTAttachment(screenshot: reference.screenshot())
ref.name = "Assembly Quick Reference"; ref.lifetime = .keepAlways; add(ref)
example.click()
XCTAssertTrue(editor.waitForExistence(timeout: 4))
XCTAssertTrue((editor.value as? String)?.contains("org") == true)
XCTAssertTrue(main.buttons["execution"].label == "Pause", "Opening a lesson must preserve the running session")
let exampleSource = editor.value as? String
let resizeSession = session()
XCTAssertEqual(resizeSession.count, 5)
// Placement can restore this window at its minimum size. Establish a
// roomy baseline before testing a real shrink, using straight edges
// inside the owned window rather than its transparent rounded corner.
func resizeWorkspace(to size: CGSize) -> Bool {
for horizontal in [true, false] {
let frame = workspace.frame
guard [frame.minX, frame.minY, frame.width, frame.height].allSatisfy({ $0.isFinite }),
frame.width > 0, frame.height > 0 else {
XCTFail("Assembly workspace must have a finite, nonempty frame")
return false
}
let edge = workspace.coordinate(withNormalizedOffset: horizontal
? CGVector(dx: 1, dy: 0.5) : CGVector(dx: 0.5, dy: 1))
.withOffset(horizontal ? CGVector(dx: -2, dy: 0) : CGVector(dx: 0, dy: -2))
let point = edge.screenPoint
guard point.x.isFinite, point.y.isFinite, frame.contains(point) else {
XCTFail("Resize must begin on an edge inside the owned Assembly workspace")
return false
}
let delta = horizontal ? CGVector(dx: size.width - frame.width, dy: 0)
: CGVector(dx: 0, dy: size.height - frame.height)
edge.click(forDuration: 0.2, thenDragTo: edge.withOffset(delta))
}
return true
}
guard resizeWorkspace(to: CGSize(width: 1040, height: 760)) else { return }
XCTAssertGreaterThan(workspace.frame.width, 1000, "Establish room to test compact resizing")
XCTAssertGreaterThan(workspace.frame.height, 720)
let beforeResize = workspace.frame
guard resizeWorkspace(to: CGSize(width: 800, height: 600)) else { return }
let compactFrame = workspace.frame
let resizeEvidence = XCTAttachment(string: "Roomy workspace: \(beforeResize)\nCompact workspace: \(compactFrame)")
resizeEvidence.name = "Assembly workspace actual resize geometry"
resizeEvidence.lifetime = .keepAlways; add(resizeEvidence)
XCTAssertLessThan(compactFrame.width, beforeResize.width - 100, "The compact workspace must materially shrink")
XCTAssertLessThan(compactFrame.height, beforeResize.height, "The native resize must also reduce window height")
XCTAssertTrue(editor.isHittable)
XCTAssertTrue(workspace.buttons["assembly-debug-entry"].isHittable)
XCTAssertTrue(workspace.frame.contains(editor.frame))
XCTAssertTrue(workspace.frame.contains(workspace.buttons["assembly-debug-entry"].frame))
XCTAssertEqual(editor.value as? String, exampleSource)
let resizedSession = session()
XCTAssertEqual(resizedSession.count, 5)
guard resizeSession.count == 5, resizedSession.count == 5 else { return }
XCTAssertEqual(resizedSession[0], resizeSession[0], "Resizing must preserve the machine")
XCTAssertEqual(resizedSession[2], resizeSession[2], "Resizing must not restart audio")
XCTAssertTrue(main.buttons["execution"].label == "Pause", "Resizing must leave the guest running")
}
func testBASICWorkspaceFindReplaceLeavesGuestAloneUntilRun() throws {
try preserveClipboard()
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
let editor = window.textViews["basic.source-text"]
XCTAssertTrue(editor.waitForExistence(timeout: 4))
func waitForRun() {
let started = NSPredicate { _, _ in
(window.staticTexts["basic.status"].value as? String ?? "").contains("started")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: started, object: nil)], timeout: 8), .completed)
}
window.buttons["basic.run"].click()
waitForRun()
window.buttons["basic.show-machine"].click()
chooseBASICEarth(greeting: "Hello Nice Blue Dot World!")
menu("Develop", "BASIC Development…")
app.typeKey("f", modifierFlags: [.command, .option])
let query = window.textFields["source.find.query"]
XCTAssertTrue(query.waitForExistence(timeout: 3))
query.click(); app.typeText("Nice Blue Dot")
window.textFields["source.find.replacement"].click(); app.typeText("Little Blue")
window.buttons["Replace"].click()
XCTAssertTrue((editor.value as? String ?? "").contains("Hello Little Blue World!"))
waitForCoCoScreenText("Hello Nice Blue Dot World!")
window.buttons["basic.run"].click()
let confirmation = app.buttons["Replace and Run"].firstMatch
if confirmation.waitForExistence(timeout: 1) {
clickOwnedAlert(message: "Replace the BASIC program in the CoCo?", button: "Replace and Run", action: "Replace and Run")
}
waitForRun()
window.buttons["basic.show-machine"].click()
chooseBASICEarth(greeting: "Hello Little Blue World!")
}
func testBASICWorkspaceBreakpointsContinueAndSourceMismatch() {
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let editor = window.textViews["basic.source-text"]
let source = "10 A=1\n20 A=A+1\n30 PRINT A\n40 GOTO 20\n"
editor.click(); editor.typeKey("a", modifierFlags: .command)
pasteBASICSource(source, into: editor)
editor.typeKey(.upArrow, modifierFlags: .command)
editor.typeKey(.downArrow, modifierFlags: [])
window.buttons["basic.toggle-breakpoint"].click()
// The visible gutter must hit the same numbered row as the accessible
// toolbar action. Remove and restore line 20 through actual mouse clicks.
let gutter = editor.coordinate(withNormalizedOffset: .zero).withOffset(CGVector(dx: -15, dy: 40))
gutter.click()
XCTAssertFalse(window.staticTexts["1 breakpoint"].exists)
gutter.click()
XCTAssertTrue(window.staticTexts["1 breakpoint"].exists)
XCTAssertFalse(window.buttons["basic.continue"].isEnabled)
let before = session()
window.buttons["basic.run"].click()
let status = window.staticTexts["basic.debug-status"]
let paused = NSPredicate { _, _ in
(status.value as? String ?? status.label).contains("Paused at BASIC line 20") && window.buttons["basic.continue"].isEnabled
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: paused, object: nil)], timeout: 8), .completed)
XCTAssertEqual(editor.value as? String, source)
let capture = XCTAttachment(screenshot: window.screenshot())
capture.name = "BASIC breakpoint before line 20"; capture.lifetime = .keepAlways; add(capture)
window.buttons["basic.continue"].click()
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: paused, object: nil)], timeout: 8), .completed)
XCTAssertEqual(session()[0], before[0])
editor.click(); editor.typeKey(.downArrow, modifierFlags: .command); editor.typeText("50 END")
XCTAssertFalse(window.buttons["basic.continue"].isEnabled)
XCTAssertTrue((status.value as? String ?? status.label).contains("Source changed"))
window.menuButtons["basic.editing-actions"].click()
app.menuItems["Clear All Breakpoints"].firstMatch.click()
XCTAssertEqual(editor.value as? String, source + "50 END")
}
func testManualLibraryPageFindAndKeywordSearch() throws {
menu("Help", "Manual Library…")
let reader = app.windows["Manual Library"]
XCTAssertTrue(reader.waitForExistence(timeout: 8))
for title in ["Open the first book", "Start reading"] {
let link = reader.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch
XCTAssertTrue(link.waitForExistence(timeout: 8), title)
link.click()
}
reader.typeKey("f", modifierFlags: .command)
let field = reader.textFields["manual.find.field"].firstMatch
XCTAssertTrue(field.waitForExistence(timeout: 5))
app.typeText("CoCo")
let status = reader.staticTexts["manual.find.status"].firstMatch
func showsMatch(_ number: Int) -> XCTWaiter.Result {
let match = NSPredicate { _, _ in
let text = status.exists ? ((status.value as? String) ?? status.label) : ""
return text.hasPrefix("\(number) of ")
}
return XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: match, object: nil)], timeout: 5)
}
XCTAssertEqual(showsMatch(1), .completed)
app.typeKey("g", modifierFlags: .command)
XCTAssertEqual(showsMatch(2), .completed)
app.typeKey("g", modifierFlags: [.command, .shift])
XCTAssertEqual(showsMatch(1), .completed)
let findShot = XCTAttachment(screenshot: reader.screenshot())
findShot.name = "Find on current manual page"
findShot.lifetime = .keepAlways
add(findShot)
app.typeKey(.escape, modifierFlags: [])
XCTAssertTrue(field.waitForNonExistence(timeout: 4))
reader.buttons["manual.ask"].click()
let query = reader.searchFields["Search text"].firstMatch
XCTAssertTrue(query.waitForExistence(timeout: 8))
app.typeText("PRINT@")
let command = reader.links.matching(NSPredicate(format: "label == %@ OR title == %@", "PRINT@", "PRINT@")).firstMatch
XCTAssertTrue(command.waitForExistence(timeout: 8))
let shot = XCTAttachment(screenshot: reader.screenshot())
shot.name = "Whole-library keyword search"; shot.lifetime = .keepAlways; add(shot)
command.click()
XCTAssertTrue(query.waitForNonExistence(timeout: 6))
reader.buttons["manual.back"].click()
XCTAssertTrue(command.waitForExistence(timeout: 8))
XCTAssertTrue(reader.buttons["manual.back"].isEnabled)
}
func testBASICWorkspaceManualLibrarySignalWorkflow() throws {
menu("Develop", "BASIC Development…")
let primary = app.windows["BASIC Development"]
let primaryEditor = primary.textViews["basic.source-text"]
XCTAssertTrue(primaryEditor.waitForExistence(timeout: 5))
let original = try XCTUnwrap(primaryEditor.value as? String)
let initialSession = session()
menu("Help", "Manual Library…")
let reader = app.windows["Manual Library"]
XCTAssertTrue(reader.waitForExistence(timeout: 5))
func link(_ title: String) -> XCUIElement {
reader.links.matching(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch
}
func follow(_ title: String) {
let item = link(title)
XCTAssertTrue(item.waitForExistence(timeout: 8), "Missing manual link: " + title)
for _ in 0..<8 where !item.isHittable {
reader.webViews.firstMatch.scroll(byDeltaX: 0, deltaY: -360)
}
item.click()
}
follow("Open the first book")
follow("Catch the computer in the act")
follow("SIGNAL.bas")
let example = app.windows["BASIC Example"]
let editor = example.textViews["basic.source-text"]
XCTAssertTrue(editor.waitForExistence(timeout: 5))
let listing = try XCTUnwrap(editor.value as? String)
XCTAssertTrue(listing.contains("30 PRINT \"BLINK\";I"))
XCTAssertEqual(primaryEditor.value as? String, original)
XCTAssertEqual(session()[0], initialSession[0])
XCTAssertEqual(session()[2], initialSession[2])
editor.click()
editor.typeKey(.upArrow, modifierFlags: .command)
editor.typeKey(.downArrow, modifierFlags: [])
editor.typeKey(.downArrow, modifierFlags: [])
example.buttons["basic.toggle-breakpoint"].click()
example.buttons["basic.run"].click()
let step = example.buttons["basic.step-into"]
let status = example.staticTexts["basic.debug-status"]
func waitForLine(_ line: Int) {
let paused = NSPredicate { _, _ in
step.isEnabled && (status.value as? String ?? status.label).contains("BASIC line \(line)")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: paused, object: nil)], timeout: 8), .completed)
}
waitForLine(30)
example.radioButtons["Watches"].firstMatch.click()
let entry = example.textFields["basic.watch-entry"]
entry.click(); entry.typeText("I"); example.buttons["basic.add-watch"].click()
func waitForI(_ value: String) {
let watch = example.staticTexts["basic.watch-value.I"]
let updated = NSPredicate { _, _ in watch.exists && (watch.value as? String ?? watch.label) == value }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: updated, object: nil)], timeout: 5), .completed)
}
waitForI("1")
step.click()
waitForLine(40)
waitForI("1")
let stopped = session()
example.buttons["basic.show-machine"].click()
XCTAssertTrue(display.waitForExistence(timeout: 5))
menu("Help", "Manual Library…")
XCTAssertTrue(link("SIGNAL.bas").waitForExistence(timeout: 5), "Returning to the manual should retain chapter 6")
XCTAssertEqual(session(), stopped, "Changing windows must preserve the debugger stop")
let shot = XCTAttachment(screenshot: reader.screenshot())
shot.name = "Manual Library chapter 6"; shot.lifetime = .keepAlways; add(shot)
follow("SIGNAL.bas")
XCTAssertEqual(editor.value as? String, listing)
XCTAssertTrue(step.isEnabled)
example.buttons["basic.continue"].click()
waitForLine(30)
waitForI("2")
XCTAssertEqual(primaryEditor.value as? String, original)
}
func testBASICWorkspaceQuickReferenceAndIndependentExample() {
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let editor = window.textViews["basic.source-text"]
let source = "10 A=42\n20 PRINT A\n30 END\n"
editor.click(); editor.typeKey("a", modifierFlags: .command); pasteBASICSource(source, into: editor)
editor.typeKey(.upArrow, modifierFlags: .command); editor.typeKey(.downArrow, modifierFlags: [])
window.buttons["basic.toggle-breakpoint"].click(); window.buttons["basic.run"].click()
let stopped = NSPredicate { _, _ in window.buttons["basic.step-into"].isEnabled }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: stopped, object: nil)], timeout: 8), .completed)
let before = session()
window.buttons["basic.reference.context"].click()
let reference = app.windows["BASIC Quick Reference"]
XCTAssertTrue(reference.waitForExistence(timeout: 5))
let title = reference.staticTexts["basic.reference.title"]
XCTAssertEqual(title.value as? String ?? title.label, "PRINT")
let search = reference.textFields["basic.reference.search"]
search.click(); search.typeText("zzznomatch")
XCTAssertTrue(reference.staticTexts["No matching commands"].exists)
search.typeKey("a", modifierFlags: .command); search.typeText("SDC-DOS")
XCTAssertTrue(reference.descendants(matching: .any)["basic.reference.topic.SDC.DRIVE"].firstMatch.exists)
search.typeKey("a", modifierFlags: .command); search.typeText("PRINT")
reference.descendants(matching: .any)["basic.reference.topic.PRINT"].firstMatch.click()
let exampleButton = reference.buttons["basic.reference.example"]
for _ in 0..<5 where !exampleButton.isHittable {
reference.scrollViews["basic.reference.detail"].scroll(byDeltaX: 0, deltaY: -160)
}
XCTAssertTrue(exampleButton.isHittable)
let referenceShot = XCTAttachment(screenshot: reference.screenshot())
referenceShot.name = "BASIC Quick Reference"; referenceShot.lifetime = .keepAlways; add(referenceShot)
exampleButton.click()
let exampleWindow = app.windows["BASIC Example"]
XCTAssertTrue(exampleWindow.waitForExistence(timeout: 5))
let exampleEditor = exampleWindow.textViews["basic.source-text"]
XCTAssertTrue((exampleEditor.value as? String ?? "").contains("HELLO, COCO"))
XCTAssertEqual(editor.value as? String, source)
XCTAssertEqual(session(), before, "Opening and reading help must preserve the stopped CoCo")
XCTAssertTrue(window.buttons["basic.continue"].isEnabled)
XCTAssertFalse(exampleWindow.buttons["basic.continue"].isEnabled)
exampleEditor.click(); exampleEditor.typeKey(.downArrow, modifierFlags: .command)
exampleEditor.typeText("50 REM PERSONAL EXAMPLE")
XCTAssertEqual(editor.value as? String, source)
XCTAssertTrue(window.buttons["basic.continue"].isEnabled)
let exampleShot = XCTAttachment(screenshot: exampleWindow.screenshot())
exampleShot.name = "Independent BASIC example"; exampleShot.lifetime = .keepAlways; add(exampleShot)
// Close and reopen the example; the original source and its debugger
// stay intact while the example keeps its independent edit/recovery.
exampleWindow.buttons[XCUIIdentifierCloseWindow].click()
exampleButton.click()
XCTAssertTrue(exampleWindow.waitForExistence(timeout: 5))
XCTAssertTrue((exampleWindow.textViews["basic.source-text"].value as? String ?? "").contains("PERSONAL EXAMPLE"))
XCTAssertEqual(editor.value as? String, source)
// Bring the original forward; clicking an obscured control would hit
// the example window at the same screen coordinates.
exampleWindow.buttons[XCUIIdentifierCloseWindow].click()
reference.buttons[XCUIIdentifierCloseWindow].click()
window.buttons["basic.continue"].click()
let finished = NSPredicate { _, _ in !window.buttons["basic.step-into"].isEnabled }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: finished, object: nil)], timeout: 8), .completed)
menu("Develop", "BASIC Quick Reference…")
exampleButton.click()
XCTAssertTrue(exampleWindow.waitForExistence(timeout: 5))
exampleWindow.buttons["basic.run"].click()
clickOwnedAlert(message: "Replace the BASIC program in the CoCo?", button: "Cancel", action: "Replace and Run")
XCTAssertEqual(editor.value as? String, source)
exampleWindow.buttons["basic.run"].click()
clickOwnedAlert(message: "Replace the BASIC program in the CoCo?", button: "Replace and Run", action: "Replace and Run")
let handedOff = NSPredicate { _, _ in
let status = exampleWindow.staticTexts["basic.status"]
return (status.value as? String ?? status.label).contains("started")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: handedOff, object: nil)], timeout: 8), .completed)
XCTAssertFalse(window.buttons["basic.continue"].isEnabled)
XCTAssertEqual(editor.value as? String, source)
XCTAssertEqual(session()[0], before[0], "Running an example must not reset the machine")
// The reference remains usable at its compact supported size.
// Run may leave the existing example behind the CoCo window. Use the
// public window command before closing, rather than a background-only
// title-bar accessibility child that macOS may omit.
XCTAssertTrue(exampleWindow.exists, "The existing example remains available after Run")
menu("Window", "BASIC Example")
app.typeKey("w", modifierFlags: .command)
XCTAssertTrue(exampleWindow.waitForNonExistence(timeout: 5), "Close the exact example before resizing its reference")
let corner = reference.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -2, dy: -2))
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(CGVector(dx: 800 - reference.frame.width, dy: 600 - reference.frame.height)))
XCTAssertTrue(search.isHittable)
XCTAssertTrue(reference.frame.contains(search.frame))
let compact = XCTAttachment(screenshot: reference.screenshot())
compact.name = "Compact BASIC Quick Reference"; compact.lifetime = .keepAlways; add(compact)
}
func testBASICWorkspaceStepOutAndRuntimeErrorNavigation() {
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
// Placement is restored across launches; establish a generous initial size
// so the regression always exercises a real shrink, even on repeated runs.
let initialCorner = window.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -2, dy: -2))
initialCorner.click(forDuration: 0.2, thenDragTo: initialCorner.withOffset(CGVector(dx: 1050 - window.frame.width, dy: 782 - window.frame.height)))
let editor = window.textViews["basic.source-text"]
let source = "10 GOSUB 100\n20 A=1/0\n30 END\n100 A=42\n110 RETURN\n"
editor.click(); editor.typeKey("a", modifierFlags: .command); pasteBASICSource(source, into: editor)
editor.typeKey(.upArrow, modifierFlags: .command)
for _ in 0..<3 { editor.typeKey(.downArrow, modifierFlags: []) }
window.buttons["basic.toggle-breakpoint"].click(); window.buttons["basic.run"].click()
let stepOut = window.buttons["basic.step-out"], status = window.staticTexts["basic.debug-status"]
func waitStopped(_ line: Int) {
let predicate = NSPredicate { _, _ in
window.buttons["basic.step-into"].isEnabled && (status.value as? String ?? status.label).contains("Paused at BASIC line \(line)")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: 8), .completed)
}
waitStopped(100); XCTAssertTrue(stepOut.isEnabled)
stepOut.click(); waitStopped(20); XCTAssertFalse(stepOut.isEnabled)
let caller = XCTAttachment(screenshot: window.screenshot())
caller.name = "BASIC returned to caller"; caller.lifetime = .keepAlways; add(caller)
window.buttons["basic.continue"].click()
let error = window.staticTexts["basic.runtime-error"]
XCTAssertTrue(error.waitForExistence(timeout: 8))
XCTAssertTrue((error.value as? String ?? error.label).contains("/0"))
XCTAssertFalse(window.buttons["basic.step-into"].isEnabled)
window.buttons["basic.show-runtime-error"].click()
editor.typeKey("c", modifierFlags: .command)
XCTAssertEqual(NSPasteboard.general.string(forType: .string), "20 A=1/0")
XCTAssertEqual(editor.value as? String, source)
let originalFrame = window.frame
let corner = window.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -2, dy: -2))
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(CGVector(dx: -190, dy: -150)))
XCTAssertLessThan(window.frame.width, originalFrame.width - 50, "The window must actually shrink")
XCTAssertTrue(window.buttons["basic.show-runtime-error"].isHittable)
XCTAssertTrue(window.buttons["basic.continue"].isHittable)
XCTAssertTrue(editor.isHittable)
let header = window.buttons["basic.show-machine"]
let footer = window.staticTexts["basic.preset-support"]
XCTAssertTrue(header.isHittable)
XCTAssertTrue(window.frame.contains(header.frame), "The header must remain inside the smaller window")
XCTAssertTrue(window.frame.contains(footer.frame), "The complete preset guidance must remain inside the smaller window")
let failure = XCTAttachment(screenshot: window.screenshot())
failure.name = "BASIC runtime error source navigation"; failure.lifetime = .keepAlways; add(failure)
window.buttons["basic.continue"].click()
Thread.sleep(forTimeInterval: 0.3)
// Correct the selected statement and run again; old diagnostics must disappear.
pasteBASICSource("20 A=2", into: editor)
XCTAssertFalse(error.exists)
window.buttons["basic.run"].click(); waitStopped(100)
XCTAssertFalse(error.exists)
}
func testBASICWorkspaceVariablesWatchesAndArrayInspection() {
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let editor = window.textViews["basic.source-text"]
let source = "10 A=1:NAME$=\"Mixed Case\":DIM M(1,2):M(1,2)=42\n20 A=A+1\n30 END\n"
editor.click(); editor.typeKey("a", modifierFlags: .command); pasteBASICSource(source, into: editor)
editor.typeKey(.upArrow, modifierFlags: .command); editor.typeKey(.downArrow, modifierFlags: [])
window.buttons["basic.toggle-breakpoint"].click(); window.buttons["basic.run"].click()
let step = window.buttons["basic.step-into"]
func waitValue(_ id: String, _ value: String) {
let element = window.staticTexts[id]
let predicate = NSPredicate { _, _ in element.exists && (element.value as? String ?? element.label) == value }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: 8), .completed)
}
waitValue("basic.variable-value.A", "1")
waitValue("basic.variable-value.NA$", "\"Mixed Case\"")
let array = window.descendants(matching: .any)["basic.array.M"].firstMatch
XCTAssertTrue(array.exists)
let inspector = window.scrollViews["basic.inspector-values"]
// The compact inspector initially clips this row. Settle its actual
// location before pressing it; a synthesized auto-scroll is not a press.
for _ in 0..<4 {
if inspector.frame.contains(array.frame) && array.isHittable { break }
inspector.scroll(byDeltaX: 0, deltaY: -35)
}
XCTAssertTrue(inspector.frame.contains(array.frame) && array.isHittable,
"The collapsed array button must be fully visible before clicking")
array.click()
let expanded = NSPredicate { _, _ in (array.value as? String) == "Expanded" }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: expanded, object: nil)], timeout: 3), .completed,
"Clicking M must expand its actual array rows")
let cell = window.staticTexts["basic.variable-value.M(1,2)"]
for _ in 0..<4 {
if cell.exists && cell.isHittable { break }
inspector.scroll(byDeltaX: 0, deltaY: -50)
}
let inspection = XCTAttachment(string: "Array expansion: \(array.value as? String ?? "unavailable")\n" + inspector.debugDescription)
inspection.name = "BASIC expanded-array accessibility"; inspection.lifetime = .keepAlways; add(inspection)
XCTAssertTrue(cell.exists && cell.isHittable, "Expanded M(1,2) must be visible in the bounded inspector scroll")
waitValue("basic.variable-value.M(1,2)", "42")
let variables = XCTAttachment(screenshot: window.screenshot())
variables.name = "BASIC variables and expanded array"; variables.lifetime = .keepAlways; add(variables)
window.radioButtons["Watches"].firstMatch.click()
let entry = window.textFields["basic.watch-entry"]
for name in ["A", "NAME$", "M(1,2)", "UNSET"] {
entry.click(); entry.typeText(name); window.buttons["basic.add-watch"].click()
}
waitValue("basic.watch-value.M(1,2)", "42")
waitValue("basic.watch-value.UN", "Not assigned")
XCTAssertTrue(step.isEnabled); step.click()
waitValue("basic.watch-value.A", "2")
XCTAssertEqual(editor.value as? String, source)
let watches = XCTAttachment(screenshot: window.screenshot())
watches.name = "BASIC watches after stepping"; watches.lifetime = .keepAlways; add(watches)
window.buttons["basic.continue"].click()
waitValue("basic.watch-value.A", "Waiting for a BASIC stop")
XCTAssertFalse(window.staticTexts["basic.variable-value.A"].exists)
}
func testBASICWorkspaceStatementSteppingAndInputWait() {
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let editor = window.textViews["basic.source-text"]
let source = "10 A=0:GOSUB 100:PRINT A\n20 END\n100 A=A+1\n110 RETURN\n"
editor.click(); editor.typeKey("a", modifierFlags: .command); pasteBASICSource(source, into: editor)
editor.typeKey(.upArrow, modifierFlags: .command)
window.buttons["basic.toggle-breakpoint"].click()
window.buttons["basic.run"].click()
let step = window.buttons["basic.step-into"], over = window.buttons["basic.step-over"]
let status = window.staticTexts["basic.debug-status"]
func waitStopped(_ line: Int) {
let predicate = NSPredicate { _, _ in
step.isEnabled && (status.value as? String ?? status.label).contains("Paused at BASIC line \(line)")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: 8), .completed)
}
waitStopped(10)
step.click(); waitStopped(10) // GOSUB, after assignment
over.click(); waitStopped(10) // PRINT, after RETURN
XCTAssertEqual(editor.value as? String, source)
let capture = XCTAttachment(screenshot: window.screenshot())
capture.name = "BASIC statement after Step Over"; capture.lifetime = .keepAlways; add(capture)
step.click(); waitStopped(20)
step.click()
let finished = NSPredicate { _, _ in (status.value as? String ?? status.label).contains("OK prompt") }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: finished, object: nil)], timeout: 8), .completed)
XCTAssertFalse(step.isEnabled)
window.buttons["basic.continue"].click()
// Continue lets the ROM settle into its keyboard prompt before replacing the program.
Thread.sleep(forTimeInterval: 0.3)
editor.click(); editor.typeKey("a", modifierFlags: .command)
pasteBASICSource("10 INPUT A\n20 END\n", into: editor)
window.buttons["basic.run"].click(); waitStopped(10)
step.click()
let pause = window.buttons["basic.pause-step"]
XCTAssertTrue(pause.waitForExistence(timeout: 5))
XCTAssertFalse(over.isEnabled)
pause.click()
let canceled = NSPredicate { _, _ in
window.buttons["basic.continue"].isEnabled && (status.value as? String ?? status.label).contains("step paused")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: canceled, object: nil)], timeout: 5), .completed)
XCTAssertFalse(step.isEnabled)
XCTAssertEqual(editor.value as? String, "10 INPUT A\n20 END\n")
}
func testBASICWorkspaceInlineCompletionAndAutomaticNumbers() {
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let editor = window.textViews["basic.source-text"]
editor.click(); editor.typeKey("a", modifierFlags: .command)
editor.typeText("10 PRI")
XCTAssertEqual(editor.value as? String, "10 PRI", "Preview must not be document content")
let shot = XCTAttachment(screenshot: window.screenshot())
shot.name = "BASIC inline keyword preview"; shot.lifetime = .keepAlways; add(shot)
editor.typeKey(.tab, modifierFlags: [])
XCTAssertEqual(editor.value as? String, "10 PRINT")
editor.typeKey("z", modifierFlags: .command)
XCTAssertEqual(editor.value as? String, "10 PRI")
editor.typeKey(.escape, modifierFlags: [])
editor.typeKey(.tab, modifierFlags: [])
XCTAssertFalse((editor.value as? String ?? "").contains("PRINT"))
editor.typeKey("a", modifierFlags: .command); editor.typeText("100 PRINT \"Hello from BASIC\"")
editor.typeKey(.return, modifierFlags: [])
XCTAssertEqual(editor.value as? String, "100 PRINT \"Hello from BASIC\"\n110 ")
editor.typeText("END"); editor.typeKey(.return, modifierFlags: [])
XCTAssertEqual(editor.value as? String, "100 PRINT \"Hello from BASIC\"\n110 END\n120 ")
editor.typeKey("z", modifierFlags: .command)
XCTAssertEqual(editor.value as? String, "100 PRINT \"Hello from BASIC\"\n110 END")
editor.typeKey("a", modifierFlags: .command)
pasteBASICSource("10 PRINT 1\n20 END\n", into: editor)
XCTAssertEqual(editor.value as? String, "10 PRINT 1\n20 END\n")
}
func testBASICWorkspaceRenumberNavigationAndDiagnostics() {
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let editor = window.textViews["basic.source-text"]
let original = "10 PRINT \"GOTO 20\"\n20 IF A=1 THEN 40 ELSE 30\n30 GOTO 10\n40 END\n"
let expected = "100 PRINT \"GOTO 20\"\n110 IF A=1 THEN 130 ELSE 120\n120 GOTO 100\n130 END\n"
let before = session()
editor.click(); editor.typeKey("a", modifierFlags: .command); pasteBASICSource(original, into: editor)
window.menuButtons["basic.editing-actions"].click(); app.menuItems["Renumber…"].firstMatch.click()
let start = window.sheets.textFields["basic.renumber-start"]
XCTAssertTrue(start.waitForExistence(timeout: 5))
start.click(); start.typeKey("a", modifierFlags: .command); start.typeText("100")
window.sheets.buttons["basic.editing-confirm"].click()
let changed = NSPredicate { _, _ in editor.value as? String == expected }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: changed, object: nil)], timeout: 5), .completed)
editor.typeKey("z", modifierFlags: .command)
XCTAssertEqual(editor.value as? String, original)
editor.typeKey("z", modifierFlags: [.command, .shift])
XCTAssertEqual(editor.value as? String, expected)
window.menuButtons["basic.editing-actions"].click(); app.menuItems["Go to Line…"].firstMatch.click()
let line = window.sheets.textFields["basic.go-line-number"]
XCTAssertTrue(line.waitForExistence(timeout: 5))
line.click(); line.typeKey("a", modifierFlags: .command); line.typeText("130")
window.sheets.buttons["basic.editing-confirm"].click()
editor.typeKey("c", modifierFlags: .command)
XCTAssertEqual(NSPasteboard.general.string(forType: .string), "130 END")
editor.typeKey("a", modifierFlags: .command); pasteBASICSource("10 PRINT 1\n10 END\n", into: editor)
window.menuButtons["basic.editing-actions"].click(); app.menuItems["Check Source"].firstMatch.click()
let issue = window.buttons.containing(NSPredicate(format: "identifier BEGINSWITH %@", "basic.diagnostic.")).firstMatch
XCTAssertTrue(issue.waitForExistence(timeout: 5)); issue.click()
editor.typeKey("c", modifierFlags: .command)
XCTAssertFalse((NSPasteboard.general.string(forType: .string) ?? "").isEmpty)
XCTAssertEqual(editor.value as? String, "10 PRINT 1\n10 END\n")
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
let shot = XCTAttachment(screenshot: window.screenshot())
shot.name = "BASIC source diagnostics"; shot.lifetime = .keepAlways; add(shot)
}
func testDevelopmentDiskExportCommandsStayVisibleWithDOS() {
for basic in [true, false] {
let title = basic ? "BASIC Development" : "Assembly Development"
menu("Develop", title + "…")
let window = app.windows[title]
window.menuButtons[basic ? "basic.file-actions" : "assembly-export"].click()
app.menuItems[basic ? "Export Disk…" : "Export Disk Image…"].firstMatch.click()
let sheet = window.sheets.firstMatch
let field = sheet.textFields[basic ? "basic.export-name" : "assembly-disk-name"]
field.click(); field.typeKey("a", modifierFlags: .command); field.typeText("mydemo")
let checkbox = sheet.checkBoxes[basic ? "basic.export-dos" : "assembly-export-dos"]
let commands = sheet.staticTexts[basic ? "basic.export-commands" : "assembly-export-commands"]
let manual = basic ? "LOAD\"MYDEMO\"" : "LOADM\"MYDEMO\":EXEC"
for (index, checked) in [false, true, false].enumerated() {
if index > 0 { checkbox.click() }
let text = commands.value as? String ?? commands.label
XCTAssertTrue(text.contains(manual), text)
if basic { XCTAssertTrue(text.contains("RUN")) }
XCTAssertEqual(text.contains("type DOS"), checked)
}
sheet.buttons["Cancel"].click()
}
}
func testBASICWorkspaceExportsDiskAndCassette() throws {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCC-BASIC-Export-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: folder) }
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let before = session()
let original = window.textViews["basic.source-text"].value as? String
for (title, ext) in [("Export Disk…", "dsk"), ("Export Cassette…", "cas")] {
window.menuButtons["basic.file-actions"].click()
app.menuItems[title].firstMatch.click()
let field = window.sheets.textFields["basic.export-name"]
XCTAssertTrue(field.waitForExistence(timeout: 5))
field.click(); field.typeKey("a", modifierFlags: .command); field.typeText("BAD/NAME")
XCTAssertFalse(window.sheets.buttons["basic.export-location"].isEnabled)
field.typeKey("a", modifierFlags: .command); field.typeText("HELLO")
XCTAssertTrue(window.sheets.buttons["basic.export-location"].isEnabled)
if ext == "dsk" {
let shot = XCTAttachment(screenshot: window.screenshot())
shot.name = "BASIC disk export options"; shot.lifetime = .keepAlways; add(shot)
}
window.sheets.buttons["basic.export-location"].click()
let target = folder.appendingPathComponent("HELLO." + ext)
diskEditorSavePanel(to: target, diagnostics: {
let status = window.staticTexts["basic.status"]
return "BASIC export status: " + (status.value as? String ?? status.label) + "\n" + window.debugDescription
})
let data = try Data(contentsOf: target)
if ext == "dsk" { XCTAssertEqual(data.count, 35 * 18 * 256) }
else { XCTAssertEqual(data.prefix(16), Data(repeating: 0x55, count: 16)) }
XCTAssertEqual(window.textViews["basic.source-text"].value as? String, original)
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
}
func testBASICWorkspaceDirectTransferCompletionAndReadback() throws {
try preserveClipboard()
menu("Develop", "BASIC Development…")
let window = app.windows["BASIC Development"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let editor = window.textViews["basic.source-text"]
XCTAssertTrue(editor.waitForExistence(timeout: 5))
let before = session()
window.buttons["basic.load"].click()
let loaded = NSPredicate { _, _ in
(window.staticTexts["basic.status"].value as? String ?? "").contains("Loaded directly")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: loaded, object: nil)], timeout: 8), .completed)
window.buttons["basic.run"].click()
let started = NSPredicate { _, _ in
(window.staticTexts["basic.status"].value as? String ?? "").contains("started")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: started, object: nil)], timeout: 8), .completed)
XCTAssertEqual(session().first, before.first)
window.buttons["basic.show-machine"].click()
chooseBASICEarth(greeting: "Hello Nice Blue Dot World!")
menu("Develop", "BASIC Development…")
editor.click(); editor.typeKey("a", modifierFlags: .command); editor.typeText("10 PRI")
window.buttons["basic.complete"].click()
if !(editor.value as? String ?? "").contains("PRINT") { editor.typeKey(.return, modifierFlags: []) }
XCTAssertTrue((editor.value as? String ?? "").contains("PRINT"))
editor.typeKey("z", modifierFlags: .command)
XCTAssertEqual(editor.value as? String, "10 PRI")
editor.typeKey("a", modifierFlags: .command)
pasteBASICSource("10 PRINT \"DIRECT BASIC\"\n20 END\n", into: editor)
window.buttons["basic.run"].click()
let replace = app.buttons["Replace and Run"].firstMatch
if replace.waitForExistence(timeout: 1) {
clickOwnedAlert(message: "Replace the BASIC program in the CoCo?", button: "Replace and Run", action: "Replace and Run")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: started, object: nil)], timeout: 8), .completed)
// Reading a changed draft must offer save/discard, then retrieve the guest program.
window.buttons["basic.read"].click()
let discard = app.dialogs.buttons["Discard Changes"].firstMatch
XCTAssertTrue(discard.waitForExistence(timeout: 2), "Reading the changed draft must offer save, cancel and discard")
clickOwnedAlert(message: "Save changes to Untitled BASIC?", button: "Discard Changes", action: "Discard Changes", additionalButtons: ["Save"])
let read = NSPredicate { _, _ in
(window.staticTexts["basic.status"].value as? String ?? "").contains("Read from CoCo memory")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: read, object: nil)], timeout: 8), .completed)
XCTAssertTrue((editor.value as? String ?? "").contains("DIRECT BASIC"))
XCTAssertEqual(session().first, before.first)
let capture = XCTAttachment(screenshot: window.screenshot())
capture.name = "BASIC workspace direct readback"; capture.lifetime = .keepAlways; add(capture)
window.buttons["basic.show-machine"].click()
waitForCoCoScreenText("DIRECT BASIC")
menu("Develop", "BASIC Development…")
menu("Window", "BASIC Development")
app.typeKey("w", modifierFlags: .command)
XCTAssertTrue(window.waitForNonExistence(timeout: 5), "Close the existing BASIC workspace before checking recovery")
menu("Develop", "BASIC Development…")
XCTAssertTrue((app.windows["BASIC Development"].textViews["basic.source-text"].value as? String ?? "").contains("DIRECT BASIC"))
}
func testSDCControlsStayOpenAndPreserveSession() {
menu("Cartridge", "Cartridges…")
let window = app.windows["Cartridges"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
window.buttons["Show CoCo SDC settings for slot 4"].click()
window.scrollViews.firstMatch.swipeUp()
let protection = window.checkBoxes["sdc-protected-4"]
XCTAssertTrue(protection.waitForExistence(timeout: 3))
XCTAssertEqual((protection.value as? NSNumber)?.intValue, 1)
let mounted = window.staticTexts.containing(NSPredicate(format: "value CONTAINS %@", "ONE.DSK")).firstMatch
for _ in 0..<4 where !mounted.exists { window.scrollViews.firstMatch.swipeUp() }
XCTAssertTrue(mounted.exists)
for _ in 0..<4 where !protection.isHittable { window.scrollViews.firstMatch.swipeDown() }
liveHold(protection)
let beforePicker = session()
window.buttons["Choose SD card folder for slot 4"].click()
let panel = app.windows["Choose SD Card Folder"]
XCTAssertTrue(panel.waitForExistence(timeout: 5))
panel.buttons["Cancel"].click()
XCTAssertTrue(protection.waitForExistence(timeout: 5))
XCTAssertEqual(session().first, beforePicker.first, "Cancelling a picker must not restart the CoCo")
// Media pickers pause first, matching existing disk-change semantics.
window.buttons["Run"].click()
liveHold(protection)
window.buttons[XCUIIdentifierCloseWindow].click()
let before = session()
menu("Display", "Interactive System")
let cart = main.buttons["system-sdc(4)"]
XCTAssertTrue(cart.waitForExistence(timeout: 3))
XCTAssertFalse(main.buttons["system-floppy(0)"].exists)
let originalCartFrame = cart.frame
let originalDisplayFrame = display.frame
let sceneShot = XCTAttachment(screenshot: main.screenshot())
sceneShot.name = "CoCo SDC System view"; sceneShot.lifetime = .keepAlways; add(sceneShot)
cart.click()
XCTAssertTrue(app.staticTexts["system-sdc-transfers"].waitForExistence(timeout: 3))
liveHold(app.buttons["Choose SD Card Folder…"])
let controlsShot = XCTAttachment(screenshot: app.popovers.firstMatch.screenshot())
controlsShot.name = "CoCo SDC controls"; controlsShot.lifetime = .keepAlways; add(controlsShot)
XCTAssertTrue(app.buttons["Choose SD Card Folder…"].exists)
main.buttons["expand-monitor"].click()
XCTAssertFalse(cart.exists)
main.buttons["expand-monitor"].click()
XCTAssertTrue(cart.exists)
XCTAssertEqual(cart.frame, originalCartFrame)
XCTAssertEqual(display.frame, originalDisplayFrame)
cart.click()
XCTAssertTrue(app.buttons["Choose SD Card Folder…"].waitForExistence(timeout: 3))
menu("Display", "Conventional Display")
let after = session()
XCTAssertEqual(after.first, before.first)
menu("Cartridge", "Cartridges…")
XCTAssertTrue(window.waitForExistence(timeout: 3))
XCTAssertTrue(window.staticTexts.matching(NSPredicate(format: "value == %@", "CoCo SDC")).firstMatch.exists)
}
func testSystemHelpOpensManualIndexFromAnOpenChapter() {
menu("Display", "Interactive System")
let before = session()
let help = main.buttons["system-manuals"]
XCTAssertTrue(help.isHittable)
XCTAssertGreaterThan(help.frame.minY, main.buttons["system-selector"].frame.maxY)
let shot = XCTAttachment(screenshot: main.screenshot())
shot.name = "System with Help button"; shot.lifetime = .keepAlways; add(shot)
help.click()
let reader = app.windows["Manual Library"]
let firstBook = reader.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", "Open the first book", "Open the first book")).firstMatch
XCTAssertTrue(firstBook.waitForExistence(timeout: 8))
firstBook.click()
XCTAssertTrue(firstBook.waitForNonExistence(timeout: 5))
menu("File", "Show Emulator")
help.click()
XCTAssertTrue(firstBook.waitForExistence(timeout: 8))
XCTAssertEqual(app.windows.matching(identifier: "Manual Library").count, 1)
XCTAssertEqual(session()[0], before[0])
XCTAssertEqual(session()[2], before[2])
}
func testSDCSoftwareLibraryShelfWithoutTower() {
menu("Display", "Interactive System")
let before = session()
let shelf = main.buttons["system-library"]
XCTAssertTrue(shelf.isHittable)
XCTAssertFalse(main.buttons["system-floppy(0)"].exists)
XCTAssertFalse(shelf.frame.intersects(display.frame))
XCTAssertTrue(main.frame.contains(shelf.frame))
let help = main.buttons["system-manuals"]
XCTAssertTrue(help.isHittable)
XCTAssertTrue(main.frame.contains(help.frame))
let originalHelp = help.frame
let original = shelf.frame
let shot = XCTAttachment(screenshot: main.screenshot())
shot.name = "System shelf — CoCo SDC without tower"; shot.lifetime = .keepAlways; add(shot)
shelf.click()
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
library.buttons[XCUIIdentifierCloseWindow].click()
main.buttons["expand-monitor"].click()
XCTAssertFalse(shelf.exists)
XCTAssertFalse(help.exists)
main.buttons["expand-monitor"].click()
XCTAssertEqual(shelf.frame, original)
XCTAssertEqual(help.frame, originalHelp)
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
}
func testShowEmulatorReopensExistingSession() {
let before = session()
let originalFrame = main.frame
menu("Help", "Keyboard & Shortcuts…")
let help = app.windows["Keyboard & Shortcuts"]
XCTAssertTrue(help.waitForExistence(timeout: 5))
XCTAssertTrue(help.staticTexts["Show Emulator — reopen or bring it forward"].exists)
for useShortcut in [false, true] {
main.buttons[XCUIIdentifierCloseWindow].click()
XCTAssertTrue(main.waitForNonExistence(timeout: 3))
XCTAssertTrue(help.exists, "Closing the emulator must leave other windows open")
if useShortcut { app.typeKey("1", modifierFlags: [.command]) }
else { menu("File", "Show Emulator") }
XCTAssertTrue(main.waitForExistence(timeout: 5))
let ready = NSPredicate { _, _ in self.session().count == 5 }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 5), .completed)
XCTAssertEqual(main.frame, originalFrame)
XCTAssertEqual(session()[0], before[0], "Show Emulator must reopen the existing machine")
XCTAssertEqual(session()[2], before[2], "Show Emulator must not restart audio")
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let keys = session()[3]
app.typeText("a")
let typed = NSPredicate { _, _ in self.session()[3] > keys }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: typed, object: nil)], timeout: 3), .completed)
}
app.typeKey("1", modifierFlags: [.command])
XCTAssertEqual(app.windows.matching(identifier: "VCC UI Tests").count, 1)
XCTAssertEqual(session()[0], before[0])
XCTAssertGreaterThan(session()[1], before[1])
}
func testSoftwareLibrarySystemShelfPreservesSession() throws {
menu("Display", "Interactive System")
let before = session()
let shelf = main.buttons["system-library"]
XCTAssertTrue(shelf.isHittable)
XCTAssertEqual(shelf.label, "Software Library")
let original = shelf.frame
let screen = display.frame
XCTAssertFalse(original.intersects(screen))
XCTAssertLessThan(original.maxY, main.buttons["system-slot(4)"].frame.minY)
liveHold(shelf, seconds: 0.5)
let shot = XCTAttachment(screenshot: main.screenshot())
shot.name = "System — wooden Software Library shelf"; shot.lifetime = .keepAlways; add(shot)
shelf.click()
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
library.buttons[XCUIIdentifierCloseWindow].click()
for _ in 0..<3 {
main.buttons["expand-monitor"].click()
XCTAssertFalse(shelf.exists)
main.buttons["expand-monitor"].click()
XCTAssertEqual(shelf.frame, original)
XCTAssertEqual(display.frame, screen)
}
main.checkBoxes["show-clickable-areas"].click()
XCTAssertTrue(shelf.isHittable, "Hiding outlines must not disable the shelf")
// The existing keyboard command opens the same window without a pointer.
app.typeKey("l", modifierFlags: [.command, .shift])
XCTAssertTrue(library.waitForExistence(timeout: 5))
library.buttons[XCUIIdentifierCloseWindow].click()
let corner = main.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(CGVector(dx: -120, dy: -80)))
XCTAssertNotEqual(shelf.frame.width, original.width)
XCTAssertTrue(shelf.isHittable)
XCTAssertFalse(shelf.frame.intersects(display.frame))
main.buttons["expand-monitor"].click()
main.buttons["expand-monitor"].click()
shelf.click()
XCTAssertTrue(library.waitForExistence(timeout: 5))
library.buttons[XCUIIdentifierCloseWindow].click()
display.click()
let keys = session()[3]
app.typeText("a")
let received = NSPredicate { _, _ in self.session()[3] > keys }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: received, object: nil)], timeout: 3), .completed)
let after = session()
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2])
XCTAssertGreaterThan(after[1], before[1])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let compact = XCTAttachment(screenshot: main.screenshot())
compact.name = "System shelf — compact window"; compact.lifetime = .keepAlways; add(compact)
}
func testPrinterOutputSystemPlacementAndIndicators() {
menu("Display", "Interactive System")
let before = session()
let printer = main.buttons["system-printer"]
XCTAssertTrue(printer.isHittable)
let original = printer.frame
let screen = display.frame
XCTAssertFalse(original.intersects(main.buttons["system-cassette"].frame))
XCTAssertFalse(original.intersects(screen))
XCTAssertTrue((printer.value as? String ?? "").contains("Capture stopped · 0 bytes"))
main.checkBoxes["show-clickable-areas"].click()
printer.click()
let window = app.windows["Printer Output"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
window.buttons["printer-capture"].click()
let received = NSPredicate { _, _ in
(printer.value as? String ?? "").contains("Capturing") &&
(window.textViews["printer-text"].value as? String ?? "").contains("HELLO FROM PRINTER")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: received, object: nil)], timeout: 10), .completed)
window.buttons[XCUIIdentifierCloseWindow].click()
for _ in 0..<3 {
main.buttons["expand-monitor"].click()
XCTAssertFalse(printer.exists)
main.buttons["expand-monitor"].click()
XCTAssertEqual(printer.frame, original)
XCTAssertEqual(display.frame, screen)
}
XCTAssertTrue((printer.value as? String ?? "").contains("Not saved"))
printer.click()
XCTAssertEqual(window.buttons["printer-capture"].label, "Stop Capture")
window.buttons["printer-capture"].click()
liveHold(window.buttons["printer-capture"], seconds: 0.5)
XCTAssertTrue((printer.value as? String ?? "").contains("Capture stopped"))
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertGreaterThan(session()[1], before[1])
}
func testPrinterOutputCaptureExportPrintAndClearPreserveSession() throws {
let before = session()
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCC-Printer-UI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: folder) }
menu("Media", "Printer Output…")
let window = app.windows["Printer Output"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let capture = window.buttons["printer-capture"]
XCTAssertEqual(capture.label, "Start Capture")
capture.click()
let text = window.textViews["printer-text"]
let received = NSPredicate { _, _ in (text.value as? String ?? "").contains("HELLO FROM PRINTER") }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: received, object: nil)], timeout: 10), .completed)
liveHold(capture, seconds: 1)
window.buttons[XCUIIdentifierCloseWindow].click()
menu("Media", "Printer Output…")
XCTAssertEqual(capture.label, "Stop Capture", "Closing must not stop collection")
capture.click()
XCTAssertEqual(capture.label, "Start Capture")
let stopped = text.value as? String ?? ""
XCTAssertTrue(stopped.contains("HELLO FROM PRINTER"))
window.buttons["Copy"].click()
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in
NSPasteboard.general.string(forType: .string) == stopped
}, object: nil)], timeout: 5), .completed)
func save(_ filename: String) {
let button = app.buttons["Save"].firstMatch
XCTAssertTrue(button.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift])
let path = app.textFields["PathTextField"].firstMatch
XCTAssertTrue(path.waitForExistence(timeout: 5))
path.click(); app.typeKey("a", modifierFlags: .command); path.typeText(folder.path + "/"); app.typeKey(.return, modifierFlags: [])
let name = app.textFields["saveAsNameTextField"].firstMatch
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "hittable == true AND enabled == true"), object: name)], timeout: 5), .completed)
name.click(); app.typeKey("a", modifierFlags: .command); name.typeText(filename)
button.click()
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in FileManager.default.fileExists(atPath: folder.appendingPathComponent(filename).path) }, object: nil)], timeout: 5), .completed)
}
window.buttons["printer-save-text"].click()
let cancel = app.buttons["Cancel"].firstMatch
XCTAssertTrue(cancel.waitForExistence(timeout: 5)); cancel.click()
XCTAssertTrue((window.staticTexts["printer-output-status"].value as? String ?? "").contains("Not saved"))
window.buttons["printer-save-text"].click(); save("printer.txt")
XCTAssertEqual(try String(contentsOf: folder.appendingPathComponent("printer.txt"), encoding: .utf8), stopped)
window.buttons["printer-save-raw"].click(); save("printer.bin")
let raw = try Data(contentsOf: folder.appendingPathComponent("printer.bin"))
XCTAssertTrue(raw.contains(13)); XCTAssertFalse(raw.contains(10))
XCTAssertEqual(String(decoding: raw, as: UTF8.self).replacingOccurrences(of: "\r", with: "\n"), stopped)
window.buttons["printer-print"].click()
let printPanels = window.sheets.matching(identifier: "PDPrintPanel")
let printPanel = printPanels.firstMatch
XCTAssertTrue(printPanel.waitForExistence(timeout: 10))
XCTAssertEqual(printPanels.count, 1, "Cancel only this isolated Printer Output window's print sheet")
let printCancels = printPanel.buttons.matching(identifier: "PDCancel")
XCTAssertEqual(printCancels.count, 1)
XCTAssertEqual(printPanel.buttons.matching(identifier: "PDPrint").count, 1, "The real native print controls must be present")
let printCancel = printCancels.firstMatch
XCTAssertTrue(printCancel.isEnabled)
let panelFrame = printPanel.frame, cancelFrame = printCancel.frame
let finitePrintFrames = [panelFrame, cancelFrame].allSatisfy {
[$0.minX, $0.minY, $0.width, $0.height].allSatisfy { $0.isFinite } && $0.width > 0 && $0.height > 0
}
XCTAssertTrue(finitePrintFrames && panelFrame.contains(cancelFrame), "Cancel must have a finite frame inside its owned print sheet")
guard printPanels.count == 1, printCancels.count == 1, printCancel.isEnabled,
finitePrintFrames, panelFrame.contains(cancelFrame) else { return }
if operatorAssistanceEnabled {
waitForOperator(kind: "print-panel-cancel", request: ["windowIdentifier": "printer", "windowTitle": "Printer Output",
"sheetIdentifier": "PDPrintPanel", "buttonIdentifier": "PDCancel", "button": "Cancel"]) {
!printPanel.exists
}
} else {
printCancel.click()
}
XCTAssertTrue(printPanel.waitForNonExistence(timeout: 5), "The actual Print sheet must close before testing Clear")
window.buttons["printer-clear"].click()
clickOwnedAlert(message: "Clear printer output?", button: "Cancel", action: "Clear Output")
XCTAssertEqual(text.value as? String, stopped)
window.buttons["printer-clear"].click()
clickOwnedAlert(message: "Clear printer output?", button: "Clear Output", action: "Clear Output")
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in
(text.value as? String ?? "") == ""
}, object: nil)], timeout: 5), .completed)
XCTAssertEqual(capture.label, "Start Capture")
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertGreaterThan(session()[1], before[1])
}
func testSecondaryDeviceAndDriveMenusStayOpen() {
menu("Cartridge", "Cartridges…")
let cartridges = app.windows["Cartridges"]
XCTAssertTrue(cartridges.waitForExistence(timeout: 5))
cartridges.menuButtons["cartridge-device-1"].click()
liveHold(app.menuItems["Use Orchestra-90 in slot 1"].firstMatch)
app.typeKey(.escape, modifierFlags: [])
XCTAssertTrue(cartridges.descendants(matching: .any)["cartridge-live-routing"].firstMatch.exists)
menu("Media", "Floppy Disks…")
let disks = app.windows["Floppy Disks"]
disks.menuButtons["floppy-actions-0"].click()
liveHold(app.menuItems["Save disk from drive 0 as"].firstMatch)
app.typeKey(.escape, modifierFlags: [])
expand(disks.disclosureTriangles["floppy-options-0"])
let protection = disks.checkBoxes["Write protect drive 0"]
XCTAssertEqual((protection.value as? NSNumber)?.intValue, 1)
liveHold(protection)
}
func testVCCPlusIdentityAndCredits() throws {
let running = try XCTUnwrap(NSRunningApplication.runningApplications(withBundleIdentifier: "com.brianholman.vccplus.oss.mac.uitesting").first)
let bundle = try XCTUnwrap(running.bundleURL.flatMap(Bundle.init(url:)))
XCTAssertEqual(bundle.object(forInfoDictionaryKey: "CFBundleName") as? String, "VCC Plus OSS")
XCTAssertEqual(bundle.bundleURL.lastPathComponent, "VCC Plus OSS.app")
XCTAssertNotNil(bundle.url(forResource: "AppIcon", withExtension: "icns"))
menu("Help", "About VCC Plus OSS")
let about = app.windows["About VCC Plus OSS"]
XCTAssertTrue(about.waitForExistence(timeout: 5))
XCTAssertTrue(about.staticTexts["VCC Plus OSS"].isHittable)
XCTAssertTrue(about.staticTexts["Designed by Brian Holman"].isHittable)
XCTAssertTrue(about.staticTexts["Sponsored by Dezota LLC"].isHittable)
let icon = about.images["about-app-icon"]
let founder = about.images["about-founder"]
let sponsor = about.descendants(matching: .any)["about-sponsor"].firstMatch
XCTAssertTrue(icon.isHittable); XCTAssertTrue(founder.isHittable); XCTAssertTrue(sponsor.isHittable)
XCTAssertLessThan(icon.frame.maxY, founder.frame.minY)
XCTAssertLessThan(founder.frame.maxX, sponsor.frame.minX)
XCTAssertEqual(founder.frame.midY, sponsor.frame.midY, accuracy: 3)
XCTAssertEqual(icon.frame.minX, founder.frame.minX, accuracy: 3)
let shot = XCTAttachment(screenshot: about.screenshot())
shot.name = "VCC Plus About"; shot.lifetime = .keepAlways; add(shot)
about.buttons["about-windows-credits"].click()
XCTAssertTrue(about.staticTexts["Original Windows VCC"].isHittable)
about.buttons["about-licenses"].click()
XCTAssertTrue(app.windows["Licenses & Notices"].staticTexts["VCC Plus Notices"].waitForExistence(timeout: 5))
}
func testSecondaryHelpNavigationAndHardDiskCreation() {
let before = session()
menu("Help", "About VCC Plus OSS")
let about = app.windows["About VCC Plus OSS"]
XCTAssertTrue(about.waitForExistence(timeout: 5))
about.buttons["about-windows-credits"].click()
XCTAssertTrue(about.staticTexts["Original Windows VCC"].isHittable)
about.buttons["about-mac-credits"].click()
XCTAssertTrue(about.staticTexts["Designed by Brian Holman"].isHittable)
about.buttons["about-licenses"].click()
let licenses = app.windows["Licenses & Notices"]
XCTAssertTrue(licenses.waitForExistence(timeout: 5))
for name in ["GPL", "ThirdPartyNotices", "WindowsAbout", "Overview"] {
let item = licenses.descendants(matching: .any)["license-document-" + name].firstMatch
XCTAssertTrue(item.exists); item.click()
}
menu("Help", "Keyboard & Shortcuts…")
let help = app.windows["Keyboard & Shortcuts"]
let search = help.textFields["keyboard-help-search"]
XCTAssertTrue(search.waitForExistence(timeout: 5)); search.click(); app.typeText("Debugger")
liveHold(search, seconds: 1)
XCTAssertTrue(help.staticTexts["Step one instruction while paused"].exists)
XCTAssertFalse(help.staticTexts["Configuration Profiles"].exists)
app.typeKey("a", modifierFlags: .command); app.typeText("no-such-topic")
XCTAssertTrue(help.staticTexts["No matching shortcuts or topics"].exists)
app.typeKey("a", modifierFlags: .command); app.typeKey(.delete, modifierFlags: [])
menu("Media", "Virtual Hard Disks…")
let disks = app.windows["Virtual Hard Disks"]
XCTAssertTrue(disks.waitForExistence(timeout: 5))
disks.menuButtons["hard-disk-actions-0"].click()
app.menuItems["New hard disk 0"].firstMatch.click()
let size = app.textFields["new-hard-disk-size"]
XCTAssertTrue(size.waitForExistence(timeout: 5)); size.click()
app.typeKey("a", modifierFlags: .command); app.typeText("0")
XCTAssertFalse(app.buttons["create-hard-disk-confirm"].isEnabled)
app.typeKey("a", modifierFlags: .command); app.typeText("1024")
XCTAssertTrue(app.buttons["create-hard-disk-confirm"].isEnabled)
app.buttons["Cancel"].firstMatch.click()
XCTAssertTrue(disks.staticTexts["Authored HD0.vhd"].exists)
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
disks.buttons["New hard disk 1"].click()
XCTAssertTrue(size.waitForExistence(timeout: 5)); size.click()
app.typeKey("a", modifierFlags: .command); app.typeText("1024")
app.buttons["create-hard-disk-confirm"].click()
XCTAssertTrue(disks.staticTexts["Untitled.vhd"].waitForExistence(timeout: 5))
XCTAssertTrue(disks.staticTexts["Authored HD0.vhd"].exists)
XCTAssertEqual(session()[0], before[0], "Creating HD1 must not replace the machine or HD0")
}
func testNativeDebuggerSteppingBreakpointsMemoryAndFocus() {
let before = session()
menu("Debug", "Show Debugger")
let window = app.windows["Debugger"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let run = window.buttons["debugger-run"]
liveHold(run, seconds: 1)
run.click()
func expectPC(_ value: String) {
let item = window.staticTexts["debugger-pc"]
let check = XCTNSPredicateExpectation(predicate: NSPredicate(format: "label == %@ OR value == %@", value, value), object: item)
XCTAssertEqual(XCTWaiter.wait(for: [check], timeout: 5), .completed)
}
func enter(_ identifier: String, _ text: String) {
let field = window.textFields[identifier]
XCTAssertTrue(field.waitForExistence(timeout: 3)); field.click()
app.typeKey("a", modifierFlags: .command); app.typeText(text)
}
let step = window.buttons["debugger-step"]
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "enabled == true"), object: step)], timeout: 5), .completed)
enter("debugger-pc-entry", "8000")
window.buttons["debugger-set-pc"].click(); expectPC("$8000")
step.click(); expectPC("$8003")
enter("debugger-memory-address", "4000"); window.buttons["debugger-memory-go"].click()
enter("debugger-edit-address", "4000"); enter("debugger-edit-byte", "2A")
window.buttons["debugger-write-memory"].click()
let byte = window.buttons["Memory 4000, 2A"]
XCTAssertTrue(byte.waitForExistence(timeout: 5))
enter("debugger-breakpoint-address", "8000")
window.buttons["debugger-add-breakpoint"].click()
XCTAssertTrue(window.buttons["Remove All"].waitForExistence(timeout: 5))
run.click(); expectPC("$8000")
XCTAssertTrue(step.isEnabled)
let shot = XCTAttachment(screenshot: window.screenshot()); shot.name = "Native debugger baseline"; shot.lifetime = .keepAlways; add(shot)
window.buttons["Remove All"].click()
run.click()
let field = window.textFields["debugger-address"]
enter("debugger-address", "123")
Thread.sleep(forTimeInterval: 1)
app.typeText("4")
XCTAssertEqual(field.value as? String, "1234", "Live refresh must retain typing focus and draft")
let corner = window.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(CGVector(dx: -80, dy: -60)))
XCTAssertTrue(run.isHittable); XCTAssertTrue(window.buttons["debugger-go"].isHittable)
app.typeKey("w", modifierFlags: .command)
XCTAssertFalse(window.exists)
XCTAssertEqual(session()[0], before[0])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
menu("Debug", "Show Debugger")
XCTAssertTrue(window.waitForExistence(timeout: 5)); liveHold(window.buttons["debugger-run"], seconds: 1)
}
func testBASICWorkspaceGraphicsPreviewOfHiddenPage() throws {
let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
let example = try String(contentsOf: root.appendingPathComponent("platforms/macos/Tests/Fixtures/two-page-pmode.bas"), encoding: .utf8)
menu("Develop", "BASIC Development…")
let basic = app.windows["BASIC Development"]
let editor = basic.textViews["basic.source-text"]
editor.click(); editor.typeKey("a", modifierFlags: .command)
pasteBASICSource(example, into: editor)
editor.typeKey(.upArrow, modifierFlags: .command)
for _ in 0..<4 { editor.typeKey(.downArrow, modifierFlags: []) }
basic.buttons["basic.toggle-breakpoint"].click()
basic.buttons["basic.run"].click()
let stopped = NSPredicate { _, _ in
let status = basic.staticTexts["basic.debug-status"]
return (status.value as? String ?? status.label).contains("Paused at BASIC line 50")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: stopped, object: nil)], timeout: 10), .completed)
menu("Debug", "Show Debugger")
let debugger = app.windows["Debugger"]
debugger.radioButtons["Graphics Preview"].click()
let reveal = debugger.buttons["graphics-reveal"]
XCTAssertTrue(reveal.waitForExistence(timeout: 5))
debugger.radioButtons["At Address"].click()
func enter(_ identifier: String, _ value: String) {
let field = debugger.textFields[identifier]
field.click(); app.typeKey("a", modifierFlags: .command); app.typeText(value)
}
enter("graphics-address", "1A00"); debugger.buttons["graphics-go"].click()
debugger.popUpButtons["graphics-zoom"].click(); app.menuItems["3×"].firstMatch.click()
let raster = debugger.descendants(matching: .any)["graphics-raster"].firstMatch
raster.coordinate(withNormalizedOffset: CGVector(dx: 81.5 / 128, dy: 32.5 / 96)).click()
XCTAssertEqual(debugger.textFields["graphics-x"].value as? String, "81")
XCTAssertEqual(debugger.textFields["graphics-y"].value as? String, "32")
enter("graphics-x", "81"); enter("graphics-y", "32")
debugger.buttons["graphics-inspect"].click()
XCTAssertTrue(debugger.staticTexts["$1E14"].firstMatch.waitForExistence(timeout: 4))
XCTAssertTrue(debugger.staticTexts["$AA"].firstMatch.exists)
let shot = XCTAttachment(screenshot: debugger.screenshot())
shot.name = "Two-page PMODE hidden drawing"; shot.lifetime = .keepAlways; add(shot)
reveal.click()
XCTAssertTrue(debugger.buttons["Memory 1E14, AA"].waitForExistence(timeout: 5))
}
func testMemoryToolsAndTraceExportPreserveSession() throws {
let before = session()
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCC-Debugger-UI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: folder) }
menu("Debug", "Show Debugger")
let window = app.windows["Debugger"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
window.radioButtons["Memory Tools"].click()
window.popUpButtons["memory-tools-space"].click()
app.menuItems["Mapped CPU"].firstMatch.click()
func enter(_ id: String, _ value: String) {
let field = window.textFields[id]
field.click(); app.typeKey("a", modifierFlags: .command); app.typeText(value)
}
func save(_ filename: String) {
let save = app.buttons["Save"].firstMatch
XCTAssertTrue(save.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift])
let path = app.textFields["PathTextField"].firstMatch
XCTAssertTrue(path.waitForExistence(timeout: 5))
path.click(); app.typeKey("a", modifierFlags: .command); path.typeText(folder.path + "/"); app.typeKey(.return, modifierFlags: [])
let name = app.textFields["saveAsNameTextField"].firstMatch
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "hittable == true AND enabled == true"), object: name)], timeout: 5), .completed)
name.click(); app.typeKey("a", modifierFlags: .command); name.typeText(filename)
save.click()
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in FileManager.default.fileExists(atPath: folder.appendingPathComponent(filename).path) }, object: nil)], timeout: 5), .completed)
}
enter("memory-tools-start", "8000"); enter("memory-tools-end", "8004")
window.buttons["memory-tools-decode"].click()
XCTAssertTrue(window.descendants(matching: .any)["memory-tools-row-0"].firstMatch.waitForExistence(timeout: 5))
window.buttons["memory-tools-export"].click(); save("memory.raw")
XCTAssertEqual(try Data(contentsOf: folder.appendingPathComponent("memory.raw")), Data([0x7c,0x40,0x00,0x20,0xfb]))
let memoryShot = XCTAttachment(screenshot: window.screenshot()); memoryShot.name = "Native memory tools"; memoryShot.lifetime = .keepAlways; add(memoryShot)
enter("memory-tools-start", "FF00"); enter("memory-tools-end", "FFFF")
window.buttons["memory-tools-export"].click()
XCTAssertTrue(window.staticTexts["memory-tools-error"].waitForExistence(timeout: 5))
XCTAssertFalse(app.buttons["Save"].firstMatch.exists)
window.radioButtons["Trace"].click()
enter("trace-limit", "6"); enter("trace-start-addresses", "8000")
window.buttons["trace-start"].click()
let first = window.buttons["trace-row-0"]
XCTAssertTrue(first.waitForExistence(timeout: 5))
first.click(); window.buttons["trace-mark-a"].click()
window.buttons["trace-row-1"].click(); window.buttons["trace-mark-b"].click()
XCTAssertTrue(window.staticTexts["trace-difference"].exists)
window.buttons["trace-export"].click(); save("trace.csv")
let csv = try String(contentsOf: folder.appendingPathComponent("trace.csv"), encoding: .utf8)
XCTAssertTrue(csv.contains("INC")); XCTAssertTrue(csv.contains("BRA"))
let traceShot = XCTAttachment(screenshot: window.screenshot()); traceShot.name = "Native execution trace"; traceShot.lifetime = .keepAlways; add(traceShot)
window.radioButtons["Inspector"].click()
window.radioButtons["Trace"].click()
XCTAssertEqual(window.textFields["trace-limit"].value as? String, "6", "Workspace switching retains trace settings")
XCTAssertTrue(window.staticTexts["trace-difference"].exists)
let after = session()
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertGreaterThan(after[1], before[1])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
func testSourceListingsAndDisabledBreakpoints() throws {
let before = session()
menu("Debug", "Show Debugger")
let window = app.windows["Debugger"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
window.radioButtons["Source"].click()
XCTAssertGreaterThan(window.buttons["debugger-run"].frame.minY, window.frame.minY + 24,
"Source must not push execution controls into the title bar")
let open = window.buttons["debugger-source-open"]
open.click()
let cancel = app.buttons["Cancel"].firstMatch
XCTAssertTrue(cancel.waitForExistence(timeout: 5)); cancel.click()
XCTAssertEqual(session()[0], before[0]); XCTAssertGreaterThan(session()[1], before[1])
open.click()
XCTAssertTrue(cancel.waitForExistence(timeout: 5))
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
app.typeKey("g", modifierFlags: [.command, .shift])
app.typeText(mac.appendingPathComponent("Tests/Fixtures/debugger-source.lst").path)
app.typeKey(.return, modifierFlags: [])
let choose = app.buttons["Open"].firstMatch
XCTAssertTrue(choose.waitForExistence(timeout: 5)); choose.click()
let sourceBP = window.buttons["debugger-source-breakpoint-5"]
XCTAssertTrue(sourceBP.waitForExistence(timeout: 5))
XCTAssertEqual(session()[2], before[2], "Import does not restart audio")
window.buttons["debugger-run"].click()
let pc = window.textFields["debugger-pc-entry"]
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "enabled == true"), object: pc)], timeout: 5), .completed)
pc.click(); app.typeKey("a", modifierFlags: .command); app.typeText("8000")
window.buttons["debugger-set-pc"].click()
sourceBP.click()
let enabled = window.checkBoxes["debugger-breakpoint-enabled-8003"]
XCTAssertTrue(enabled.waitForExistence(timeout: 5)); enabled.click()
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "value == 0"), object: enabled)], timeout: 5), .completed)
window.buttons["debugger-run"].click()
liveHold(open, seconds: 1)
window.buttons["debugger-run"].click()
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "enabled == true"), object: pc)], timeout: 5), .completed)
enabled.click()
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "value == 1"), object: enabled)], timeout: 5), .completed)
window.buttons["debugger-run"].click()
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "enabled == true"), object: pc)], timeout: 5), .completed)
let location = window.staticTexts["debugger-source-location"]
XCTAssertTrue(location.waitForExistence(timeout: 5))
XCTAssertTrue(((location.value as? String) ?? location.label).contains(":6"))
let search = window.textFields["debugger-source-search"]
search.click(); app.typeText("loo"); Thread.sleep(forTimeInterval: 1); app.typeText("p")
XCTAssertEqual(search.value as? String, "loop")
window.buttons["debugger-source-find"].click()
window.checkBoxes["debugger-source-follow"].click()
let shot = XCTAttachment(screenshot: window.screenshot()); shot.name = "Native source debugger"; shot.lifetime = .keepAlways; add(shot)
window.buttons["debugger-source-close"].click()
XCTAssertTrue(enabled.exists, "Unloading a listing preserves shared breakpoints")
window.radioButtons["Disassembly"].click()
XCTAssertTrue(window.buttons["debugger-breakpoint-8003"].waitForExistence(timeout: 5))
XCTAssertEqual(session()[0], before[0]) // Explicit Pause/Continue legitimately restarts host audio.
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
func testMMUAndPhysicalMemoryInspectionPreservesExecution() {
let before = session()
menu("Debug", "Show Debugger")
let window = app.windows["Debugger"]
XCTAssertTrue(window.waitForExistence(timeout: 5))
let mmu = window.radioButtons["MMU"]
XCTAssertTrue(mmu.waitForExistence(timeout: 5)); mmu.click()
let backing = window.descendants(matching: .any)["debugger-mmu-ram-4"].firstMatch
XCTAssertTrue(backing.waitForExistence(timeout: 5)); liveHold(backing, seconds: 1)
let source = window.staticTexts["debugger-mmu-source-4"]
XCTAssertTrue(source.exists)
XCTAssertTrue(((source.value as? String) ?? source.label).contains("System ROM"))
window.staticTexts["debugger-state"].hover()
Thread.sleep(forTimeInterval: 0.5)
let mmuShot = XCTAttachment(screenshot: window.screenshot())
mmuShot.name = "Native MMU monitor"; mmuShot.lifetime = .keepAlways; add(mmuShot)
backing.click()
let readonly = window.staticTexts["debugger-physical-read-only"]
XCTAssertTrue(readonly.waitForExistence(timeout: 5))
XCTAssertFalse(window.buttons["debugger-write-memory"].exists)
let address = window.textFields["debugger-memory-address"]
XCTAssertEqual(address.value as? String, "078000")
func enter(_ value: String) {
address.click(); app.typeKey("a", modifierFlags: .command); app.typeText(value)
window.buttons["debugger-memory-go"].click()
}
enter("07FFF0")
let next = window.buttons["debugger-memory-next"]
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "enabled == false"), object: next)], timeout: 5), .completed)
XCTAssertTrue(readonly.exists)
enter("080000")
XCTAssertTrue(window.staticTexts["debugger-error"].waitForExistence(timeout: 5))
enter("010000")
address.click(); app.typeKey("a", modifierFlags: .command); app.typeText("012")
Thread.sleep(forTimeInterval: 1); app.typeText("3")
XCTAssertEqual(address.value as? String, "0123", "Live inspection preserves the physical-address draft and focus")
enter("010000")
let physicalShot = XCTAttachment(screenshot: window.screenshot())
physicalShot.name = "Native physical RAM"; physicalShot.lifetime = .keepAlways; add(physicalShot)
let space = window.popUpButtons["debugger-memory-space"]
space.click(); app.menuItems["Mapped CPU"].firstMatch.click()
XCTAssertTrue(window.buttons["debugger-write-memory"].waitForExistence(timeout: 5))
XCTAssertFalse(window.buttons["debugger-write-memory"].isEnabled, "Running machine remains protected from RAM edits")
let after = session()
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2])
XCTAssertGreaterThan(after[1], before[1])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
app.typeKey("w", modifierFlags: .command)
XCTAssertFalse(window.exists)
}
func testNativeFocusWindowPlacementAndAccessibleAlternatives() {
let before = session()
app.typeKey("u", modifierFlags: [.command, .option])
app.typeKey(.space, modifierFlags: [])
let profiles = app.windows["Configuration Profiles"]
XCTAssertTrue(profiles.waitForExistence(timeout: 5), "Keyboard command must focus an operable native control")
app.typeKey("w", modifierFlags: .command)
app.typeKey("k", modifierFlags: [.command, .option])
let keys = session()[3]
app.typeText("a")
XCTAssertGreaterThan(session()[3], keys, "Focus command must return typing to the guest")
app.typeKey("u", modifierFlags: [.command, .option])
app.typeKey(.space, modifierFlags: [])
XCTAssertTrue(profiles.waitForExistence(timeout: 5), "Repeated native focus must work")
app.typeKey("w", modifierFlags: .command)
menu("Media", "Cassette…")
let tape = app.windows["Cassette"]
XCTAssertTrue(tape.waitForExistence(timeout: 5))
let corner = tape.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(CGVector(dx: 90, dy: 70)))
let saved = tape.frame
app.typeKey("w", modifierFlags: .command)
menu("Media", "Cassette…")
XCTAssertTrue(tape.waitForExistence(timeout: 5))
XCTAssertEqual(tape.frame.width, saved.width, accuracy: 2)
XCTAssertEqual(tape.frame.height, saved.height, accuracy: 2)
XCTAssertEqual(tape.frame.minX, saved.minX, accuracy: 2)
XCTAssertEqual(tape.frame.minY, saved.minY, accuracy: 2)
app.typeKey("w", modifierFlags: .command)
menu("Display", "Interactive System")
main.buttons["Devices"].click()
XCTAssertTrue(app.popovers.firstMatch.waitForExistence(timeout: 5))
XCTAssertTrue(app.popovers.descendants(matching: .any).matching(NSPredicate(format: "label BEGINSWITH %@", "Monitor video signal")).firstMatch.exists)
XCTAssertTrue(app.popovers.descendants(matching: .any).matching(NSPredicate(format: "label BEGINSWITH %@", "Floppy FD0")).firstMatch.exists)
app.typeKey(.escape, modifierFlags: [])
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
func testSpeechSoundROMPickersAndSystemArtwork() throws {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("Authored SSC " + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: folder) }
let pic = folder.appendingPathComponent("PIC.bin"), speech = folder.appendingPathComponent("Speech.bin")
var firmware = Data(repeating: 0, count: 4096)
firmware[0] = 0xb3; firmware[1] = 0xe0; firmware[2] = 0xfd; firmware[4094] = 0xf0
try firmware.write(to: pic); try Data(repeating: 0, count: 2048).write(to: speech)
menu("Display", "Interactive System"); menu("Cartridge", "Cartridges…")
let cartridges = app.windows["Cartridges"]
XCTAssertTrue(cartridges.waitForExistence(timeout: 5))
cartridges.menuButtons["cartridge-device-1"].click()
app.menuItems["Use Speech/Sound in slot 1"].firstMatch.click()
clickOwnedAlert(message: "Change slot 1 and restart?", button: "Change and Restart", action: "Change and Restart")
let inactive = cartridges.staticTexts["Inactive — choose both ROMs to enable speech and music."]
XCTAssertTrue(inactive.waitForExistence(timeout: 5))
cartridges.buttons["Show Speech/Sound ROMs for slot 1"].click()
cartridges.buttons["Choose PIC firmware for slot 1"].click()
let cancel = app.buttons["Cancel"].firstMatch
XCTAssertTrue(cancel.waitForExistence(timeout: 5)); cancel.click()
XCTAssertTrue(inactive.exists)
for (button, file, _) in [("Choose PIC firmware for slot 1",pic,"PIC firmware: PIC.bin"),("Choose speech ROM for slot 1",speech,"Speech ROM: Speech.bin")] {
cartridges.buttons[button].click()
XCTAssertTrue(cancel.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command,.shift]); app.typeText(file.path); app.typeKey(.return, modifierFlags: [])
let open = app.buttons["Open"].firstMatch
XCTAssertTrue(open.waitForExistence(timeout: 5)); open.click()
XCTAssertTrue(cartridges.staticTexts[file.lastPathComponent].waitForExistence(timeout: 5))
}
XCTAssertFalse(inactive.exists)
let controls = XCTAttachment(screenshot: cartridges.screenshot())
controls.name = "Speech-Sound controls"; controls.lifetime = .keepAlways; add(controls)
app.typeKey("w", modifierFlags: .command)
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let system = XCTAttachment(screenshot: main.screenshot())
system.name = "Speech-Sound System view"; system.lifetime = .keepAlways; add(system)
main.buttons["Devices"].click()
XCTAssertTrue(app.descendants(matching: .disclosureTriangle).matching(NSPredicate(format: "label CONTAINS %@", "Speech/Sound")).firstMatch.waitForExistence(timeout: 5))
}
func testOrchestraSelectionOptionalROMAndSystemArtwork() throws {
let file = FileManager.default.temporaryDirectory.appendingPathComponent("Authored Orchestra \(UUID().uuidString).rom")
try Data(repeating: 0x12, count: 8192).write(to: file)
defer { try? FileManager.default.removeItem(at: file) }
menu("Display", "Interactive System")
menu("Cartridge", "Cartridges…")
let cartridges = app.windows["Cartridges"]
XCTAssertTrue(cartridges.waitForExistence(timeout: 5))
cartridges.menuButtons["cartridge-device-1"].click()
app.menuItems["Use Orchestra-90 in slot 1"].firstMatch.click()
clickOwnedAlert(message: "Change slot 1 and restart?", button: "Change and Restart", action: "Change and Restart")
XCTAssertTrue(cartridges.staticTexts["Stereo sound only · No program ROM"].waitForExistence(timeout: 5))
XCTAssertTrue(main.buttons["Devices"].exists)
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
cartridges.buttons["Choose Orchestra-90 ROM for slot 1"].click()
let cancel = app.buttons["Cancel"].firstMatch
XCTAssertTrue(cancel.waitForExistence(timeout: 5)); cancel.click()
XCTAssertTrue(cartridges.staticTexts["Stereo sound only · No program ROM"].exists)
cartridges.buttons["Choose Orchestra-90 ROM for slot 1"].click()
XCTAssertTrue(cancel.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(file.path); app.typeKey(.return, modifierFlags: [])
let open = app.buttons["Open"].firstMatch
XCTAssertTrue(open.waitForExistence(timeout: 5)); open.click()
XCTAssertTrue(cartridges.staticTexts[file.lastPathComponent].waitForExistence(timeout: 5))
let controls = XCTAttachment(screenshot: cartridges.screenshot())
controls.name = "Orchestra-90 controls"; controls.lifetime = .keepAlways; add(controls)
expand(cartridges.disclosureTriangles.matching(NSPredicate(format: "label CONTAINS %@", "Details for slot 1")).firstMatch)
cartridges.buttons["Remove Orchestra-90 ROM from slot 1"].click()
clickOwnedAlert(message: "Remove the Orchestra-90 ROM and restart?", button: "Remove ROM and Restart", action: "Remove ROM and Restart")
XCTAssertTrue(cartridges.staticTexts["Stereo sound only · No program ROM"].waitForExistence(timeout: 5))
XCTAssertTrue(cartridges.exists)
menu("Window", "Cartridges")
app.typeKey("w", modifierFlags: .command)
XCTAssertTrue(cartridges.waitForNonExistence(timeout: 5), "Close the exact cartridge controls before checking System artwork")
let system = XCTAttachment(screenshot: main.screenshot())
system.name = "Orchestra-90 System view"; system.lifetime = .keepAlways; add(system)
main.buttons["Devices"].click()
XCTAssertTrue(app.descendants(matching: .disclosureTriangle).matching(NSPredicate(format: "label CONTAINS %@", "Orchestra-90")).firstMatch.waitForExistence(timeout: 5))
}
func testRamDiskSelectionAndRemovalUseNativeControlsWithoutInventedArtwork() {
menu("Display", "Interactive System")
menu("Cartridge", "Cartridges…")
let cartridges = app.windows["Cartridges"]
XCTAssertTrue(cartridges.waitForExistence(timeout: 5))
cartridges.menuButtons["cartridge-device-1"].click()
app.menuItems["Use RAM disk in slot 1"].firstMatch.click()
clickOwnedAlert(message: "Change slot 1 and restart?", button: "Change and Restart", action: "Change and Restart")
let installed = cartridges.staticTexts["RAM disk (512 KB)"].firstMatch
XCTAssertTrue(installed.waitForExistence(timeout: 5))
XCTAssertTrue(main.staticTexts["Custom configuration"].exists)
XCTAssertFalse(main.buttons["Devices"].exists)
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let installedShot = XCTAttachment(screenshot: cartridges.screenshot())
installedShot.name = "RAM disk controls"; installedShot.lifetime = .keepAlways; add(installedShot)
cartridges.menuButtons["cartridge-device-1"].click()
app.menuItems["Remove cartridge from slot 1"].firstMatch.click()
let change = app.dialogs.buttons["Change and Restart"].firstMatch
XCTAssertTrue(change.waitForExistence(timeout: 5))
XCTAssertTrue(app.dialogs.staticTexts.matching(NSPredicate(format: "value CONTAINS %@", "RAM disk data is volatile")).firstMatch.exists)
clickOwnedAlert(message: "Change slot 1 and restart?", button: "Cancel", action: "Change and Restart")
XCTAssertTrue(installed.exists)
cartridges.menuButtons["cartridge-device-1"].click()
app.menuItems["Remove cartridge from slot 1"].firstMatch.click()
clickOwnedAlert(message: "Change slot 1 and restart?", button: "Change and Restart", action: "Change and Restart")
XCTAssertTrue(main.buttons["Devices"].waitForExistence(timeout: 5))
XCTAssertFalse(installed.exists)
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let shot = XCTAttachment(screenshot: cartridges.screenshot())
shot.name = "Native cartridge controls"; shot.lifetime = .keepAlways; add(shot)
}
// Examine the composited live Metal surface, not just the viewport formula.
// The authored diagnostic fills its 640 × 384 active raster with color bars.
private func assertPictureAspect(scaling: String = "Sharp — Fit Window") throws {
let bitmap = try XCTUnwrap(NSBitmapImageRep(data: display.screenshot().pngRepresentation))
func bright(_ x: Int, _ y: Int) -> Bool {
var pixel = [Int](repeating: 0, count: 5)
bitmap.getPixel(&pixel, atX: x, y: y)
return pixel.prefix(3).max()! > 150
}
let xs = (0..<bitmap.pixelsWide).filter { bright($0, bitmap.pixelsHigh / 2) }
let ys = (0..<bitmap.pixelsHigh).filter { bright(bitmap.pixelsWide / 2, $0) }
let width = try XCTUnwrap(xs.last) - XCTUnwrap(xs.first) + 1
let height = try XCTUnwrap(ys.last) - XCTUnwrap(ys.first) + 1
XCTAssertEqual(Double(width), Double(height) * 640 / 384, accuracy: 3,
"Resized on-screen Metal picture must preserve the diagnostic raster's aspect")
// Aspect alone also passes for a tiny picture centered in a huge
// viewport. Measure actual composited coverage and placement as well.
// Calculate expectations independently of the app's VideoGeometry.
let backing = Double(bitmap.pixelsWide) / display.frame.width
let inset = 4 * backing
let fit = min((Double(bitmap.pixelsWide) - 2 * inset) / 640,
(Double(bitmap.pixelsHigh) - 2 * inset) / 384)
let integer = scaling == "Integer Pixels" && fit >= 1
let scale = integer ? floor(fit) : fit
XCTAssertEqual(Double(width), 640 * scale, accuracy: 3,
"Fit modes must fill the available monitor aperture; integer mode uses the largest whole multiple")
XCTAssertEqual(Double(height), 384 * scale, accuracy: 3)
XCTAssertEqual(Double(try XCTUnwrap(xs.first)) + Double(width) / 2,
Double(bitmap.pixelsWide) / 2, accuracy: 2, "Picture must remain horizontally centered")
XCTAssertEqual(Double(try XCTUnwrap(ys.first)) + Double(height) / 2,
Double(bitmap.pixelsHigh) / 2, accuracy: 2, "Picture must remain vertically centered")
}
func testActualPictureAspectAcrossResizeAndPresentations() throws {
let before = session()
try assertPictureAspect() // Fresh app defaults must fit, not use integer scaling.
for mode in ["Conventional Display", "Interactive System", "Expand Monitor"] {
menu("Display", mode)
for scaling in ["Sharp — Fit Window", "Smooth — Fit Window", "Integer Pixels"] {
menu("Display", scaling)
for paused in [false, true] {
if paused { main.buttons["execution"].click() }
let desired = paused ? "Run" : "Pause"
let ready = NSPredicate { _, _ in self.main.buttons["execution"].label == desired }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 5), .completed)
let resizeBaseline = session()
let corner = main.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
let delta = CGVector(dx: paused ? -100 : 100, dy: paused ? 70 : -70)
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(delta))
try assertPictureAspect(scaling: scaling)
XCTAssertEqual(session()[2], resizeBaseline[2], "Resizing must not restart audio")
if paused { XCTAssertEqual(session()[1], resizeBaseline[1], "Resizing must not advance a paused guest") }
if paused { main.buttons["execution"].click() }
}
}
}
XCTAssertEqual(session()[0], before[0])
}
func testToolbarAndMenuBarStayOpenDuringRefresh() {
for mode in ["Conventional Display", "Interactive System"] {
menu("Display", mode)
let rgb = videoMenu(); liveHold(rgb)
rgb.click()
liveHold(display, seconds: 0.5)
XCTAssertEqual(session()[4], 0, "Toolbar selection must reach the running machine")
_ = videoMenu()
main.menuButtons["Settings"].descendants(matching: .menuItem)["Composite TV"].click()
main.menuButtons["Restart"].click()
liveHold(main.menuButtons["Restart"].descendants(matching: .menuItem)["Soft Reset — Retain RAM"])
app.typeKey(.escape, modifierFlags: [])
main.menuButtons["Media"].click()
liveHold(main.menuButtons["Media"].descendants(matching: .menuItem)["Cassette…"])
app.typeKey(.escape, modifierFlags: [])
}
app.menuBars.menuBarItems["View"].click()
liveHold(app.menuBars.menuBarItems["View"].menus.menuItems["Enter Full Screen"])
app.typeKey(.escape, modifierFlags: [])
}
func testSystemPopoversAndExpandReturnPreserveSession() throws {
menu("Display", "Interactive System")
let before = session()
for label in ["Color Computer 3", "Cassette", "Multi-Pak slot 4", "Joystick ports"] {
let button = main.buttons[label]
XCTAssertTrue(button.exists)
button.click()
let popover = app.popovers.firstMatch
XCTAssertTrue(popover.waitForExistence(timeout: 3))
XCTAssertTrue(popover.staticTexts[label].exists, "Popover must belong to the selected device")
let deviceFrame = button.frame, panelFrame = popover.frame
let gapX = max(0, max(deviceFrame.minX - panelFrame.maxX, panelFrame.minX - deviceFrame.maxX))
let gapY = max(0, max(deviceFrame.minY - panelFrame.maxY, panelFrame.minY - deviceFrame.maxY))
XCTAssertLessThanOrEqual(hypot(gapX, gapY), 24, "Popover must anchor to its device, not the entire stage")
// A popover is an accessibility container, not a clickable control.
// Its container hit test can fail over the Metal/SwiftUI scene even
// while its native buttons remain visible and operable.
liveHold(popover.buttons.firstMatch)
if label == "Color Computer 3" {
let shot = XCTAttachment(screenshot: app.screenshot())
shot.name = "Device popover anchor"; shot.lifetime = .keepAlways; add(shot)
}
// The tall slot popover can cover the header at smaller window sizes.
// Dismiss from the empty bottom-left window margin instead.
main.coordinate(withNormalizedOffset: CGVector(dx: 0.01, dy: 0.98)).click()
XCTAssertTrue(popover.waitForNonExistence(timeout: 3))
}
main.buttons["Devices"].click()
let devices = app.popovers.firstMatch
liveHold(devices.disclosureTriangles.firstMatch)
// The Devices list can cover the old fixed bottom-left point. Measure
// a title-bar point that is inside this window and outside the list.
let windowFrame = main.frame, devicesFrame = devices.frame
let finiteFrames = [windowFrame, devicesFrame].allSatisfy {
[$0.minX, $0.minY, $0.width, $0.height].allSatisfy { $0.isFinite } && $0.width > 0 && $0.height > 0
}
let titleBarPoints = [CGPoint(x: windowFrame.maxX - 20, y: windowFrame.minY + 16),
CGPoint(x: windowFrame.minX + 100, y: windowFrame.minY + 16)]
guard finiteFrames, let outside = titleBarPoints.first(where: {
$0.x.isFinite && $0.y.isFinite && windowFrame.contains($0) && !devicesFrame.insetBy(dx: -8, dy: -8).contains($0)
}) else {
XCTFail("Devices dismissal must use a measured owned-window point outside its popover"); return
}
main.coordinate(withNormalizedOffset: .zero)
.withOffset(CGVector(dx: outside.x - windowFrame.minX, dy: outside.y - windowFrame.minY)).click()
XCTAssertTrue(devices.waitForNonExistence(timeout: 3))
display.click()
let original = display.frame
for _ in 0..<3 {
main.buttons["expand-monitor"].click()
XCTAssertGreaterThan(display.frame.width, original.width)
liveHold(display, seconds: 0.5)
try assertPictureAspect()
let keys = session()[3]
app.typeText("a") // No refocus click: expanding must restore keyboard input.
let received = NSPredicate { _, _ in
let state = self.session(); return state.count == 5 && state[3] > keys
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: received, object: nil)], timeout: 3), .completed, "Expanded monitor must retain keyboard focus")
main.buttons["expand-monitor"].click()
XCTAssertEqual(display.frame.width, original.width, accuracy: 1)
XCTAssertEqual(display.frame.minX, original.minX, accuracy: 1)
XCTAssertEqual(display.frame.minY, original.minY, accuracy: 1)
}
let windowBeforeResize = main.frame
let corner = main.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
// Resize inward when already large: growing a height-limited stage
// against the desktop edge can leave the monitor scale unchanged.
let resizeDelta = CGVector(dx: windowBeforeResize.width > 1100 ? -100 : 100,
dy: windowBeforeResize.height > 750 ? -80 : 80)
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(resizeDelta))
let resized = display.frame
XCTAssertNotEqual(resized.width, original.width, "Window drag must actually resize the stage")
main.buttons["expand-monitor"].click()
main.buttons["expand-monitor"].click()
XCTAssertEqual(display.frame.width, resized.width, accuracy: 1)
XCTAssertEqual(session()[0], before[0])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
XCTAssertTrue(main.links["Tape Authored tape.cas"].exists)
}
func testClickableAreasAndMonitorSignalPreserveSession() {
menu("Display", "Interactive System")
let before = session()
let guide = main.checkBoxes["show-clickable-areas"]
XCTAssertEqual((guide.value as? NSNumber)?.intValue, 1)
guide.click()
XCTAssertEqual((guide.value as? NSNumber)?.intValue, 0)
guide.click()
XCTAssertEqual((guide.value as? NSNumber)?.intValue, 1)
main.buttons["Floppy FD0"].hover()
let shot = XCTAttachment(screenshot: app.screenshot())
shot.name = "Clickable areas and inset drive outline"; shot.lifetime = .keepAlways; add(shot)
for label in ["Multi-Pak slot 4", "Multi-Pak slot 3", "Multi-Pak slot 2", "Multi-Pak slot 1"] {
// The right side of each enlarged socket shelf must select its own
// slot, including when the cartridge artwork obscures other slots.
let slot = main.buttons[label]
let slotFrame = slot.frame
slot.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).click()
let popover = app.popovers.firstMatch
let opened = popover.waitForExistence(timeout: 3)
let exactTitle = NSPredicate(format: "value == %@ OR label == %@", label, label)
let matchesSlot = opened && popover.staticTexts.matching(exactTitle).firstMatch.exists
func attachSlotPopover(_ reason: String) {
let detail = XCTAttachment(string: "\(reason)\nRequested slot: \(label)\nButton frame before right-shelf click: \(slotFrame)\nClick offset: (0.9, 0.5)\n" + (popover.exists ? popover.debugDescription : "No popover exists.\n" + main.debugDescription))
detail.name = "Multi-Pak slot popover diagnosis"; detail.lifetime = .keepAlways; add(detail)
let image = XCTAttachment(screenshot: popover.exists ? popover.screenshot() : main.screenshot())
image.name = "Actual popover after " + label; image.lifetime = .keepAlways; add(image)
}
if !matchesSlot { attachSlotPopover("Right-shelf click did not show the exact requested slot") }
XCTAssertTrue(opened)
XCTAssertTrue(matchesSlot)
// A fixed point in the main header can lie inside the slot popover
// when its native anchor places it above that header. Select an
// actual window-title-bar point outside the current popover bounds.
let windowFrame = main.frame, popoverFrame = popover.frame
let titleBarPoints = [CGPoint(x: windowFrame.maxX - 20, y: windowFrame.minY + 16),
CGPoint(x: windowFrame.minX + 100, y: windowFrame.minY + 16)]
guard let outside = titleBarPoints.first(where: {
$0.x.isFinite && $0.y.isFinite && windowFrame.contains($0) && !popoverFrame.insetBy(dx: -8, dy: -8).contains($0)
}) else {
attachSlotPopover("No verified title-bar dismissal point is outside the current popover")
XCTFail("An outside-click dismissal must use an actual point outside the popover"); return
}
main.coordinate(withNormalizedOffset: .zero)
.withOffset(CGVector(dx: outside.x - windowFrame.minX, dy: outside.y - windowFrame.minY)).click()
let dismissed = popover.waitForNonExistence(timeout: 3)
if !dismissed { attachSlotPopover("The slot popover remained after the outside click") }
XCTAssertTrue(dismissed)
}
for expanded in [false, true] {
if expanded { main.buttons["expand-monitor"].click() }
let bezel = main.buttons["Monitor video signal"]
XCTAssertGreaterThan(bezel.frame.minY, display.frame.maxY)
bezel.coordinate(withNormalizedOffset: CGVector(dx: 0.85, dy: 0.5)).click()
let popover = app.popovers.firstMatch
XCTAssertTrue(popover.waitForExistence(timeout: 3))
let picker = popover.descendants(matching: .any)["monitor-video-signal"].firstMatch
picker.click()
let rgb = popover.descendants(matching: .menuItem)["RGB Monitor"]
liveHold(rgb); rgb.click()
liveHold(picker, seconds: 0.5)
XCTAssertEqual(session()[4], 0)
main.coordinate(withNormalizedOffset: CGVector(dx: 0.55, dy: 0.07)).click()
XCTAssertTrue(popover.waitForNonExistence(timeout: 3))
menu("Display", "Composite TV — Alternate Colors")
bezel.click()
XCTAssertTrue(popover.waitForExistence(timeout: 3))
XCTAssertEqual(picker.value as? String, "Composite TV — Alternate Colors")
main.coordinate(withNormalizedOffset: CGVector(dx: 0.55, dy: 0.07)).click()
XCTAssertTrue(popover.waitForNonExistence(timeout: 3))
}
main.buttons["expand-monitor"].click()
XCTAssertEqual(session()[0], before[0])
XCTAssertEqual(session()[2], before[2])
guide.click()
XCTAssertEqual((guide.value as? NSNumber)?.intValue, 0)
}
func testMacShellGuestPermissionCanBeDenied() {
menu("Machine", "Machine Settings…")
let settings = app.windows["Machine Settings"]
settings.scrollViews.firstMatch.scroll(byDeltaX: 0, deltaY: -600)
settings.checkBoxes["machine-drivewire-networking"].click()
let deny = app.buttons["Deny"].firstMatch
XCTAssertTrue(deny.waitForExistence(timeout: 8))
XCTAssertTrue(app.buttons["Allow"].exists)
let screenshot = XCTAttachment(screenshot: settings.screenshot())
screenshot.name = "Mac shell access request"
screenshot.lifetime = .keepAlways
add(screenshot)
deny.click()
XCTAssertTrue(settings.buttons["Start Mac Shell Session"].waitForExistence(timeout: 5))
settings.buttons["Start Mac Shell Session"].click()
let stop = settings.buttons["Stop Mac Shell Session"]
XCTAssertTrue(stop.waitForExistence(timeout: 5))
stop.click()
XCTAssertTrue(settings.buttons["Start Mac Shell Session"].waitForExistence(timeout: 5))
}
func testDriveWireSettingsAndGuestHelp() {
menu("Machine", "Machine Settings…")
let settings = app.windows["Machine Settings"]
XCTAssertTrue(settings.waitForExistence(timeout: 5))
let scroll = settings.scrollViews.firstMatch
scroll.scroll(byDeltaX: 0, deltaY: -380)
let toggle = settings.checkBoxes["machine-drivewire-networking"]
XCTAssertEqual((toggle.value as? NSNumber)?.intValue, 0)
toggle.click()
XCTAssertEqual((toggle.value as? NSNumber)?.intValue, 1)
let help = settings.disclosureTriangles["Connect from NitrOS-9"].firstMatch
expand(help)
let commands = settings.staticTexts["drivewire-guest-commands"]
XCTAssertTrue(commands.waitForExistence(timeout: 3))
XCTAssertTrue((commands.value as? String)?.contains("telnet HOST PORT") == true)
let screenshot = XCTAttachment(screenshot: settings.screenshot())
screenshot.name = "DriveWire networking and guest commands"
screenshot.lifetime = .keepAlways
add(screenshot)
toggle.click()
XCTAssertEqual((toggle.value as? NSNumber)?.intValue, 0)
}
func testMachineSettingsPickersAndDraftSurviveRefresh() {
menu("Machine", "Machine Settings…")
let settings = app.windows["Machine Settings"]
XCTAssertTrue(settings.waitForExistence(timeout: 3))
let memory = settings.descendants(matching: .any)["machine-memory"].firstMatch
memory.click(); liveHold(app.menuItems["2 MB"].firstMatch)
app.menuItems["2 MB"].firstMatch.click()
liveHold(memory)
XCTAssertEqual(memory.value as? String, "2 MB")
XCTAssertTrue(settings.buttons["Apply and Restart…"].isEnabled)
let before = session()
let processor = settings.popUpButtons["machine-processor"]
processor.click(); app.menuItems["Hitachi 6309"].firstMatch.click()
XCTAssertEqual(processor.value as? String, "Hitachi 6309")
for capacity in ["128 KB", "512 KB", "2 MB", "8 MB"] {
memory.click(); app.menuItems[capacity].firstMatch.click()
XCTAssertEqual(memory.value as? String, capacity)
}
settings.buttons["Revert"].click()
XCTAssertEqual(memory.value as? String, "512 KB")
XCTAssertEqual(processor.value as? String, "Motorola 6809")
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
}
func testSystemProfilesAreReadOnlyAndCopyWithoutRestarting() {
menu("Machine", "Configuration Profiles…")
let profiles = app.windows["Configuration Profiles"]
let before = session()
let hard = profiles.descendants(matching:.any)["system-hardDriveBasic"].firstMatch
XCTAssertTrue(hard.waitForExistence(timeout:5)); hard.click()
XCTAssertFalse(profiles.menuButtons["profile-actions"].exists)
let copy = profiles.buttons["copy-system-profile"]
profiles.scrollViews.element(boundBy: 1).scroll(byDeltaX: 0, deltaY: -280)
liveHold(copy)
let screenshot = XCTAttachment(screenshot: profiles.screenshot())
screenshot.name = "System Profiles - Hard Drive BASIC"; screenshot.lifetime = .keepAlways; add(screenshot)
copy.click()
let field = app.textFields["profile-name"]
XCTAssertTrue(field.waitForExistence(timeout:3))
app.typeKey("a", modifierFlags:.command);app.typeText("My hard drive")
clickOwnedAlert(message: "Save System Setup as My Profile", button: "Save", action: "Save")
let editable = profiles.menuButtons["profile-actions"]
let enabled = NSPredicate { _, _ in editable.isEnabled }
XCTAssertEqual(XCTWaiter.wait(for:[XCTNSPredicateExpectation(predicate:enabled,object:nil)],timeout:15),.completed)
XCTAssertEqual(session()[0],before[0],"Copying a system profile must not restart the session")
XCTAssertTrue(profiles.staticTexts["My hard drive"].firstMatch.exists)
editable.click(); liveHold(app.menuItems["Rename…"].firstMatch)
app.typeKey(.escape, modifierFlags: [])
profiles.descendants(matching:.any)["system-diskBasic"].firstMatch.click()
let fresh=profiles.buttons["fresh-system-media"]
profiles.scrollViews.element(boundBy: 1).scroll(byDeltaX: 0, deltaY: -280)
fresh.click()
XCTAssertTrue(field.waitForExistence(timeout:3))
app.typeKey("a", modifierFlags:.command);app.typeText("Fresh disk setup")
clickOwnedAlert(message: "Name Setup with Fresh Starter Media", button: "Save", action: "Save")
XCTAssertEqual(XCTWaiter.wait(for:[XCTNSPredicateExpectation(predicate:enabled,object:nil)],timeout:15),.completed)
XCTAssertTrue(profiles.staticTexts["Fresh disk setup"].firstMatch.exists)
XCTAssertEqual(session()[0],before[0])
XCTAssertEqual(session()[2],before[2],"Copying profiles must not restart audio")
}
func testCocoSDCSystemProfileMountsStarterAndProvidesGuide() {
menu("Machine", "Configuration Profiles…")
let profiles = app.windows["Configuration Profiles"]
let profile = profiles.descendants(matching: .any)["system-cocoSDC"].firstMatch
XCTAssertTrue(profile.waitForExistence(timeout: 5)); profile.click()
XCTAssertFalse(profiles.menuButtons["profile-actions"].exists)
XCTAssertTrue(profiles.staticTexts["HELLO.DSK · mounted at startup"].exists)
let shot = XCTAttachment(screenshot: profiles.screenshot())
shot.name = "CoCo SDC system profile"; shot.lifetime = .keepAlways; add(shot)
profiles.buttons["Load…"].click()
clickOwnedAlert(message: "Load “CoCo SDC”?", button: "Load Profile", action: "Load Profile")
let ready = NSPredicate { _, _ in self.main.buttons["execution"].label == "Pause" && profiles.buttons["Load…"].isEnabled }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 20), .completed)
XCTAssertTrue(profiles.exists, "A successful load keeps the existing Profiles window available")
menu("Window", "Configuration Profiles")
app.typeKey("w", modifierFlags: .command)
XCTAssertTrue(profiles.waitForNonExistence(timeout: 5), "Close the existing Profiles window after the successful load")
main.buttons["Using the CoCo"].click()
let guide = app.popovers.firstMatch
XCTAssertTrue(guide.staticTexts["CoCo SDC"].waitForExistence(timeout: 3))
XCTAssertTrue(guide.staticTexts["DIR 0\nLOAD \"HELLO:0\"\nRUN"].exists)
liveHold(guide.staticTexts["CoCo SDC"])
let helpShot = XCTAttachment(screenshot: guide.screenshot())
helpShot.name = "CoCo SDC starter guide"; helpShot.lifetime = .keepAlways; add(helpShot)
app.typeKey(.escape, modifierFlags: [])
menu("Display", "Interactive System")
main.buttons["system-sdc(4)"].click()
XCTAssertTrue(app.staticTexts["SDC0: /HELLO.DSK"].waitForExistence(timeout: 3))
XCTAssertTrue(app.staticTexts["Writable SD card — changes save directly"].exists)
XCTAssertTrue(app.buttons["Show SD Card Folder in Finder"].exists)
}
func testFirstUseProfileGuides() {
let popover = app.popovers.firstMatch
XCTAssertTrue(popover.staticTexts["Disk BASIC"].waitForExistence(timeout: 5))
liveHold(popover)
app.typeKey(.escape, modifierFlags: [])
for (identifier, title, firstVisit) in [
("system-hardDriveBasic", "Hard Drive BASIC", true),
("system-diskBasic", "Disk BASIC", false),
("system-hardDriveBasic", "Hard Drive BASIC", false)
] {
menu("Machine", "Configuration Profiles…")
let profiles = app.windows["Configuration Profiles"]
profiles.descendants(matching: .any)[identifier].firstMatch.click()
profiles.buttons["Load…"].click()
clickOwnedAlert(message: "Load “\(title)”?", button: "Load Profile", action: "Load Profile")
let ready = NSPredicate { _, _ in self.main.buttons["execution"].label == "Pause" && profiles.buttons["Load…"].isEnabled }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 20), .completed)
if firstVisit {
XCTAssertTrue(popover.staticTexts[title].waitForExistence(timeout: 5))
liveHold(popover)
let shot = XCTAttachment(screenshot: main.screenshot())
shot.name = "First-use Hard Drive BASIC guide"; shot.lifetime = .keepAlways; add(shot)
app.typeKey(.escape, modifierFlags: [])
} else {
XCTAssertFalse(popover.waitForExistence(timeout: 1))
}
// A first-use guide intentionally brings the CoCo forward. The
// Profiles window remains open; bring that exact window forward
// through its native command before closing it.
XCTAssertTrue(profiles.exists, "The first-use guide must not close the existing Profiles window")
menu("Window", "Configuration Profiles")
app.typeKey("w", modifierFlags: .command)
XCTAssertTrue(profiles.waitForNonExistence(timeout: 5), "Close the existing Profiles window between guide checks")
}
// The information button remains available after automatic introductions.
main.buttons["Using the CoCo"].click()
XCTAssertTrue(popover.staticTexts["Hard Drive BASIC"].waitForExistence(timeout: 3))
liveHold(popover)
}
func testUsageHelpTracksSystemProfileAndSurvivesRefresh() {
for (identifier, title, command) in [
("system-diskBasic", "Disk BASIC", "DIR 0"),
("system-hardDriveBasic", "Hard Drive BASIC", "DRIVE OFF\nDIR 0")
] {
menu("Machine", "Configuration Profiles…")
let profiles = app.windows["Configuration Profiles"]
profiles.descendants(matching: .any)[identifier].firstMatch.click()
profiles.buttons["Load…"].click()
clickOwnedAlert(message: "Load “\(title)”?", button: "Load Profile", action: "Load Profile")
let ready = NSPredicate { _, _ in self.main.buttons["execution"].label == "Pause" && profiles.buttons["Load…"].isEnabled }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 20), .completed)
XCTAssertTrue(profiles.exists, "The loaded Profiles window remains available")
menu("Window", "Configuration Profiles")
app.typeKey("w", modifierFlags: .command)
XCTAssertTrue(profiles.waitForNonExistence(timeout: 5), "Close the loaded Profiles window before opening setup help")
main.buttons["Using the CoCo"].click()
let popover = app.popovers.firstMatch
XCTAssertTrue(popover.staticTexts[title].waitForExistence(timeout: 3))
XCTAssertTrue(popover.staticTexts[command].firstMatch.exists)
liveHold(popover.staticTexts[title])
let shot = XCTAttachment(screenshot: popover.screenshot())
shot.name = "Using your CoCo - " + title; shot.lifetime = .keepAlways; add(shot)
app.typeKey(.escape, modifierFlags: [])
}
}
func testProfileNameKeepsTextAndFocusDuringRefresh() {
menu("Machine", "Configuration Profiles…")
let profiles = app.windows["Configuration Profiles"]
let cancelledName = profiles.staticTexts.matching(NSPredicate(format: "value == %@ OR label == %@", "Refresh test", "Refresh test")).firstMatch
XCTAssertFalse(cancelledName.exists, "The authored fixture must not already contain the proposed personal profile")
profiles.buttons["Save Current As…"].click()
let field = app.textFields["profile-name"]
XCTAssertTrue(field.waitForExistence(timeout: 3))
app.typeText("Refresh") // The native name prompt assigns initial text focus.
liveHold(field)
app.typeText(" test") // Do not refocus the field after the refresh hold.
XCTAssertEqual(field.value as? String, "Refresh test")
clickOwnedAlert(message: "Save Current Setup as Profile", button: "Cancel", action: "Save")
XCTAssertTrue(profiles.buttons["Save Current As…"].isEnabled)
XCTAssertFalse(cancelledName.exists, "Cancel must not add the named personal profile to My Profiles")
}
func testCassetteSliderAndRecordingMenuDuringRefresh() {
menu("Media", "Cassette…")
let cassette = app.windows["Cassette"]
let slider = cassette.sliders["Volume"]
XCTAssertTrue(slider.waitForExistence(timeout: 3))
let transportShot = XCTAttachment(screenshot: cassette.screenshot())
transportShot.name = "Cassette — current transport"; transportShot.lifetime = .keepAlways; add(transportShot)
// The app-sound row is below the transport in this compact window.
// Existence in the accessibility tree does not imply a visible control.
cassette.scrollViews.firstMatch.scroll(byDeltaX: 0, deltaY: -220)
XCTAssertTrue(slider.isHittable)
slider.adjust(toNormalizedSliderPosition: 0.25)
liveHold(slider)
XCTAssertEqual(slider.normalizedSliderPosition, 0.25, accuracy: 0.06)
slider.adjust(toNormalizedSliderPosition: 0.7)
liveHold(slider)
XCTAssertEqual(slider.normalizedSliderPosition, 0.7, accuracy: 0.06)
cassette.menuButtons["New Recording"].click()
liveHold(app.menuItems["CAS"].firstMatch)
app.typeKey(.escape, modifierFlags: [])
XCTAssertTrue(app.menuItems["CAS"].firstMatch.waitForNonExistence(timeout: 3))
let shot = XCTAttachment(screenshot: cassette.screenshot())
shot.name = "Cassette — current transport and app sound controls"; shot.lifetime = .keepAlways; add(shot)
}
func testCreateDMKAndVDKFromFloppyWindow() {
menu("Media", "Floppy Disks…")
let disks = app.windows["Floppy Disks"]
XCTAssertTrue(disks.waitForExistence(timeout: 5))
for (drive, option, filename) in [(1, "DMK Track Image", "Untitled.dmk"), (2, "VDK Disk Image", "Untitled.vdk")] {
disks.menuButtons["floppy-new-\(drive)"].click()
let item = app.menuItems[option].firstMatch
XCTAssertTrue(item.waitForExistence(timeout: 3))
if drive == 1 { liveHold(item, seconds: 1) }
item.click()
XCTAssertTrue(disks.staticTexts[filename].waitForExistence(timeout: 5))
}
XCTAssertTrue(disks.staticTexts["Authored FD0.dsk"].exists)
}
func testFilePickerCancelKeepsMountedDiskAndSession() {
menu("Media", "Floppy Disks…")
let disks = app.windows["Floppy Disks"]
XCTAssertTrue(disks.waitForExistence(timeout: 5))
disks.buttons["Insert disk in drive 0"].click()
let cancel = app.buttons["Cancel"].firstMatch
XCTAssertTrue(cancel.waitForExistence(timeout: 5))
// Disk dialogs intentionally freeze the controller; cancellation must
// preserve the mounted image and paused session, not resume implicitly.
let paused = session()
Thread.sleep(forTimeInterval: 2)
XCTAssertTrue(cancel.isHittable)
XCTAssertEqual(session(), paused)
cancel.click()
XCTAssertTrue(disks.staticTexts["Authored FD0.dsk"].exists)
expand(disks.disclosureTriangles["floppy-options-0"])
XCTAssertEqual((disks.checkBoxes["Write protect drive 0"].value as? NSNumber)?.intValue, 1)
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
private var diskEditorWindow: XCUIElement {
app.windows["Disk Image Editor"]
}
private func diskEditorWait(_ message: String, timeout: TimeInterval = 8, _ condition: @escaping () -> Bool) {
let predicate = NSPredicate { _, _ in condition() }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: timeout),
.completed, message)
}
private func diskEditorFixture() throws -> (folder: URL, image: URL, original: Data) {
let folder = try XCTUnwrap(diskEditorFixtureFolder)
let receipt = folder.appendingPathComponent("fixture.json")
diskEditorWait("The isolated fixture must identify its actual mounted copy") {
FileManager.default.fileExists(atPath: receipt.path)
}
let record = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: receipt)) as? [String: Any])
let image = URL(fileURLWithPath: try XCTUnwrap(record["mounted_image"] as? String))
return (folder, image, try Data(contentsOf: image))
}
private func openDiskEditor() -> XCUIElement {
menu("Media", "Floppy Disks…")
let disks = app.windows["Floppy Disks"]
let edit = disks.buttons["floppy-edit-0"]
XCTAssertTrue(edit.waitForExistence(timeout: 5))
XCTAssertTrue(edit.isEnabled)
let shot = XCTAttachment(screenshot: disks.screenshot())
shot.name = "Floppy Disks — mounted drive Edit action"; shot.lifetime = .keepAlways; add(shot)
edit.click()
let editor = diskEditorWindow
XCTAssertTrue(editor.waitForExistence(timeout: 8))
XCTAssertTrue(editor.descendants(matching: .any)["disk-editor-files"].firstMatch.waitForExistence(timeout: 8))
XCTAssertTrue(editor.staticTexts["README.TXT"].firstMatch.waitForExistence(timeout: 8))
diskEditorWait("Disk editing must pause and lock the personal machine") {
self.main.buttons["execution"].label == "Run" && !self.main.buttons["execution"].isEnabled
}
XCTAssertFalse(main.menuButtons["Restart"].isEnabled, "A restart cannot invalidate an open edit transaction")
let space = editor.descendants(matching: .any)["disk-editor-space"].firstMatch
XCTAssertTrue(space.exists, "Show allocation information from the actual filesystem")
let spaceText = space.value as? String ?? space.label
XCTAssertTrue(spaceText.contains("Total") && spaceText.contains("Used") && spaceText.contains("Free"), spaceText)
return editor
}
private func diskEditorSelect(_ name: String, in editor: XCUIElement) {
let entry = editor.staticTexts[name].firstMatch
XCTAssertTrue(entry.waitForExistence(timeout: 5), "Missing disk entry " + name)
entry.click()
}
private func diskEditorSavePanel(to destination: URL, diagnostics: (() -> String)? = nil) {
// A sheet blocks only its owner; another document's Save command can
// remain enabled. Select the native file picker's exact control.
let save = app.buttons["OKButton"].firstMatch
XCTAssertTrue(save.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift])
let path = app.textFields["PathTextField"].firstMatch
XCTAssertTrue(path.waitForExistence(timeout: 5))
path.click(); app.typeKey("a", modifierFlags: .command)
path.typeText(destination.deletingLastPathComponent().path + "/")
app.typeKey(.return, modifierFlags: [])
diskEditorWait("The selected export folder must finish navigating") { !path.exists }
let name = app.textFields["saveAsNameTextField"].firstMatch
diskEditorWait("The export filename field must be ready") { name.exists && name.isHittable && name.isEnabled }
name.click(); app.typeKey("a", modifierFlags: .command); name.typeText(destination.lastPathComponent)
XCTAssertEqual(name.value as? String, destination.lastPathComponent, "Use the exact requested export filename")
let chosenName = name.value as? String ?? "unavailable"
save.click()
let saved = NSPredicate { _, _ in FileManager.default.fileExists(atPath: destination.path) }
let result = XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: saved, object: nil)], timeout: 8)
if result != .completed {
let detail = XCTAttachment(string: "Expected export: \(destination.path)\nChosen filename: \(chosenName)\n" + (diagnostics?() ?? app.debugDescription))
detail.name = "Export destination and status"; detail.lifetime = .keepAlways; add(detail)
}
XCTAssertEqual(result, .completed, "The exported file must exist at the exact selected location: " + destination.path)
}
private func diskEditorExport(_ name: String, from editor: XCUIElement, to destination: URL) {
diskEditorSelect(name, in: editor)
let export = editor.buttons["disk-editor-export"]
diskEditorWait("Selecting a file must enable export") { export.isEnabled }
export.click()
diskEditorSavePanel(to: destination)
}
private func diskEditorImport(_ source: URL, into editor: XCUIElement, decb: Bool) {
editor.buttons["disk-editor-import"].click()
let open = app.buttons["Open"].firstMatch
XCTAssertTrue(open.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift])
let path = app.textFields["PathTextField"].firstMatch
XCTAssertTrue(path.waitForExistence(timeout: 5))
path.click(); app.typeKey("a", modifierFlags: .command); path.typeText(source.path)
app.typeKey(.return, modifierFlags: [])
diskEditorWait("The selected host file must be importable") { open.exists && open.isEnabled }
open.click()
let confirm = app.buttons["disk-editor-import-confirm"].firstMatch
XCTAssertTrue(confirm.waitForExistence(timeout: 5))
if decb {
let type = app.popUpButtons["disk-editor-import-type"].firstMatch
let encoding = app.popUpButtons["disk-editor-import-encoding"].firstMatch
XCTAssertTrue(type.exists && encoding.exists)
type.click(); app.menuItems["Text"].firstMatch.click()
encoding.click(); app.menuItems["ASCII"].firstMatch.click()
}
confirm.click()
XCTAssertTrue(editor.staticTexts[source.lastPathComponent].firstMatch.waitForExistence(timeout: 8))
}
private func diskEditorName(_ name: String) {
let field = app.textFields["disk-editor-name"].firstMatch
XCTAssertTrue(field.waitForExistence(timeout: 5))
field.click(); app.typeKey("a", modifierFlags: .command); field.typeText(name)
app.buttons["disk-editor-name-confirm"].firstMatch.click()
}
private func closeDiskEditorDiscardingChanges(_ editor: XCUIElement) {
editor.buttons["disk-editor-close"].click()
let discard = app.buttons["Discard Changes"].firstMatch
XCTAssertTrue(discard.waitForExistence(timeout: 5), "Private unsaved edits require a discard confirmation")
discard.click()
diskEditorWait("Closing must retire the editor and release its lease") { !editor.exists }
diskEditorWait("Cancel must return control without automatically resuming") {
self.main.buttons["execution"].label == "Run" && self.main.buttons["execution"].isEnabled
}
}
func testDiskImageEditorFinderOpenRoutesMountedSafely() throws {
let fixture = try diskEditorFixture()
let unmounted = fixture.folder.appendingPathComponent("Finder Copy.dsk")
try fixture.original.write(to: unmounted)
let bundle = try XCTUnwrap(NSRunningApplication.runningApplications(
withBundleIdentifier: "com.brianholman.vccplus.oss.mac.uitesting").first?.bundleURL)
func finderOpen(_ url: URL) {
// Target only the isolated test app, regardless of the user's
// normal Finder association for disk images.
let configuration = NSWorkspace.OpenConfiguration()
configuration.activates = true
NSWorkspace.shared.open([url], withApplicationAt: bundle, configuration: configuration)
}
let before = session()
finderOpen(unmounted)
let action = app.popUpButtons["diskOpenAction"].firstMatch
let drive = app.popUpButtons["diskOpenDrive"].firstMatch
let execution = app.popUpButtons["diskOpenExecution"].firstMatch
let reset = app.popUpButtons["diskOpenReset"].firstMatch
XCTAssertTrue(action.waitForExistence(timeout: 8))
app.activate()
XCTAssertEqual(action.value as? String, "Edit Disk Image")
XCTAssertFalse(drive.isEnabled)
XCTAssertFalse(execution.isEnabled)
XCTAssertFalse(reset.isEnabled)
action.click(); app.menuItems["Insert into Floppy Drive"].firstMatch.click()
XCTAssertTrue(drive.isEnabled && execution.isEnabled && reset.isEnabled)
XCTAssertEqual(execution.value as? String, "Keep current state")
XCTAssertEqual(reset.value as? String, "No Reset")
reset.click(); app.menuItems["Soft Reset"].firstMatch.click()
XCTAssertEqual(reset.value as? String, "Soft Reset")
reset.click(); app.menuItems["Cold Restart"].firstMatch.click()
XCTAssertEqual(reset.value as? String, "Cold Restart")
let chooser = main.sheets.containing(.popUpButton, identifier: "diskOpenAction").firstMatch
let choiceShot = XCTAttachment(screenshot: chooser.screenshot()); choiceShot.name = "Finder disk action chooser"; choiceShot.lifetime = .keepAlways; add(choiceShot)
drive.click(); app.menuItems["FD1"].firstMatch.click()
execution.click(); app.menuItems["Pause"].firstMatch.click()
app.buttons["Cancel"].firstMatch.click()
diskEditorWait("Cancelling Finder's insertion choices must leave the CoCo running") {
!action.exists && self.main.buttons["execution"].label == "Pause"
}
XCTAssertEqual(session()[0], before[0])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
finderOpen(unmounted)
XCTAssertTrue(action.waitForExistence(timeout: 8))
XCTAssertEqual(action.value as? String, "Edit Disk Image")
app.buttons["Open"].firstMatch.click()
let independent = diskEditorWindow
XCTAssertTrue(independent.waitForExistence(timeout: 8))
XCTAssertTrue(independent.staticTexts["README.TXT"].firstMatch.waitForExistence(timeout: 8))
XCTAssertTrue(independent.staticTexts["Unmounted image · CoCo unchanged"].exists)
XCTAssertTrue(main.buttons["execution"].isEnabled)
liveHold(independent.buttons["disk-editor-close"], seconds: 1)
independent.buttons["disk-editor-close"].click()
diskEditorWait("An unchanged unmounted image should close without stopping the machine") { !independent.exists }
XCTAssertEqual(try Data(contentsOf: unmounted), fixture.original)
finderOpen(fixture.image)
XCTAssertTrue(action.waitForExistence(timeout: 8))
app.buttons["Open"].firstMatch.click()
let mounted = diskEditorWindow
XCTAssertTrue(mounted.waitForExistence(timeout: 8))
diskEditorWait("Finder editing a mounted path must acquire the same paused lease as its Edit button") {
self.main.buttons["execution"].label == "Run" && !self.main.buttons["execution"].isEnabled
}
XCTAssertTrue(mounted.staticTexts["FD0 · CoCo paused and locked"].exists)
XCTAssertFalse(main.menuButtons["Restart"].isEnabled)
mounted.buttons["disk-editor-close"].click()
diskEditorWait("Closing the unchanged mounted image must release the edit lock") {
!mounted.exists && self.main.buttons["execution"].isEnabled
}
XCTAssertEqual(main.buttons["execution"].label, "Run")
XCTAssertEqual(session()[0], before[0])
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
}
func testDiskImageEditorSupplementaryTracksPreserved() throws {
let fixture = try diskEditorFixture()
let suffix = Data(fixture.original.dropFirst(161280))
XCTAssertEqual(suffix.count, 161280)
let host = fixture.folder.appendingPathComponent("EXTRA.TXT")
try Data("NORMAL DISK BASIC FILE\r".utf8).write(to: host)
let editor = openDiskEditor()
XCTAssertTrue(editor.staticTexts["disk-editor-preserved-data"].firstMatch.exists)
diskEditorImport(host, into: editor, decb: true)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
editor.buttons["disk-editor-apply"].click()
let apply = app.buttons["Restart and Apply"].firstMatch
XCTAssertTrue(apply.waitForExistence(timeout: 5)); apply.click()
diskEditorWait("Applying an extended image must finish", timeout: 15) { !editor.exists }
let saved = try Data(contentsOf: fixture.image)
XCTAssertEqual(saved.count, fixture.original.count)
XCTAssertEqual(Data(saved.dropFirst(161280)), suffix)
XCTAssertNotEqual(Data(saved.prefix(161280)), Data(fixture.original.prefix(161280)))
let reopened = openDiskEditor()
XCTAssertTrue(reopened.staticTexts["EXTRA.TXT"].firstMatch.waitForExistence(timeout: 5))
XCTAssertTrue(reopened.staticTexts["disk-editor-preserved-data"].firstMatch.exists)
reopened.buttons["disk-editor-close"].click()
diskEditorWait("Reopened extended image closes cleanly") { !reopened.exists }
}
func testDiskImageEditorCompactOS9WindowRetainsControls() throws {
_ = try diskEditorFixture()
let editor = openDiskEditor()
// The isolated fixture creates a real native window at its minimum
// size. This verifies compact layout, not synthetic resize gestures.
diskEditorWait("The editor must actually open at its compact size") {
editor.frame.width > 0 && editor.frame.height > 0 &&
editor.frame.width <= 800 && editor.frame.height <= 530
}
for control in [editor.buttons["disk-editor-import"], editor.buttons["disk-editor-save-copy"],
editor.buttons["disk-editor-close"], editor.descendants(matching: .any)["disk-editor-space"].firstMatch] {
XCTAssertTrue(control.isHittable)
XCTAssertTrue(editor.frame.insetBy(dx: -1, dy: -1).contains(control.frame), "Compact controls must remain inside the window")
}
let shot = XCTAttachment(screenshot: editor.screenshot()); shot.name = "Disk Image Editor — compact"; shot.lifetime = .keepAlways; add(shot)
editor.buttons["disk-editor-close"].click()
diskEditorWait("Closing a compact editor releases its lease") { !editor.exists && self.main.buttons["execution"].isEnabled }
}
func testDiskImageEditorDECBRoundTripAndCancel() throws {
let fixture = try diskEditorFixture()
let before = session()
let expectedReadme = Data("VCC Plus authored Disk Image Editor fixture.\rDECB and OS-9 round trips preserve exact file bytes.\r".utf8)
let hostBytes = Data("HOST COPY\r".utf8)
let host = fixture.folder.appendingPathComponent("INPUT.TXT")
try hostBytes.write(to: host)
let editor = openDiskEditor()
let locked = session()
XCTAssertEqual(locked[0], before[0], "Opening the editor must not reset the machine")
Thread.sleep(forTimeInterval: 1)
XCTAssertEqual(session()[1], locked[1], "The paused guest must not advance while editing")
XCTAssertFalse(editor.buttons["disk-editor-new-folder"].isEnabled, "DECB has no directories")
let decbShot = XCTAttachment(screenshot: editor.screenshot()); decbShot.name = "Disk Image Editor — DECB"; decbShot.lifetime = .keepAlways; add(decbShot)
let readme = fixture.folder.appendingPathComponent("readme-export.txt")
diskEditorExport("README.TXT", from: editor, to: readme)
XCTAssertEqual(try Data(contentsOf: readme), expectedReadme)
let space = editor.descendants(matching: .any)["disk-editor-space"].firstMatch
let initialSpace = space.value as? String ?? space.label
diskEditorImport(host, into: editor, decb: true)
diskEditorWait("Allocating a DECB granule must update used/free allocation") {
(space.value as? String ?? space.label) != initialSpace
}
diskEditorSelect("INPUT.TXT", in: editor)
editor.buttons["disk-editor-rename"].click(); diskEditorName("RENAMED.TXT")
XCTAssertTrue(editor.staticTexts["RENAMED.TXT"].firstMatch.waitForExistence(timeout: 5))
let exported = fixture.folder.appendingPathComponent("roundtrip.txt")
diskEditorExport("RENAMED.TXT", from: editor, to: exported)
XCTAssertEqual(try Data(contentsOf: exported), hostBytes)
diskEditorSelect("RENAMED.TXT", in: editor)
editor.buttons["disk-editor-delete"].click()
let delete = app.buttons["action-button-1"].firstMatch
XCTAssertTrue(delete.waitForExistence(timeout: 5)); delete.click()
diskEditorWait("Delete must remove the selected entry") { !editor.staticTexts["RENAMED.TXT"].firstMatch.exists }
app.typeKey("z", modifierFlags: .command)
XCTAssertTrue(editor.staticTexts["RENAMED.TXT"].firstMatch.waitForExistence(timeout: 5))
app.typeKey("z", modifierFlags: [.command, .shift])
diskEditorWait("Redo must repeat the private deletion") { !editor.staticTexts["RENAMED.TXT"].firstMatch.exists }
editor.buttons["disk-editor-undo"].click()
XCTAssertTrue(editor.staticTexts["RENAMED.TXT"].firstMatch.waitForExistence(timeout: 5))
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original, "Edits must remain in a private working image")
closeDiskEditorDiscardingChanges(editor)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original, "Cancel must preserve every mounted source byte")
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[1], locked[1])
// A fresh transaction must also prove the Apply button is wired to the
// real disk/restart path, and that cancelling its warning changes nothing.
let applyHost = fixture.folder.appendingPathComponent("APPLY.TXT")
try hostBytes.write(to: applyHost)
let applying = openDiskEditor()
diskEditorImport(applyHost, into: applying, decb: true)
applying.buttons["disk-editor-apply"].click()
let restart = app.buttons["Restart and Apply"].firstMatch
XCTAssertTrue(restart.waitForExistence(timeout: 5))
app.buttons["Cancel"].firstMatch.click()
XCTAssertTrue(applying.exists)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
XCTAssertEqual(session()[0], before[0])
applying.buttons["disk-editor-apply"].click()
XCTAssertTrue(restart.waitForExistence(timeout: 5)); restart.click()
diskEditorWait("A confirmed Apply must finish and close the editor", timeout: 15) { !applying.exists }
diskEditorWait("Confirmed filesystem replacement must cold-restart the guest") { self.session()[0] > before[0] }
XCTAssertNotEqual(try Data(contentsOf: fixture.image), fixture.original)
let reopened = openDiskEditor()
XCTAssertTrue(reopened.staticTexts["APPLY.TXT"].firstMatch.waitForExistence(timeout: 5))
let appliedExport = fixture.folder.appendingPathComponent("applied.txt")
diskEditorExport("APPLY.TXT", from: reopened, to: appliedExport)
XCTAssertEqual(try Data(contentsOf: appliedExport), hostBytes)
reopened.buttons["disk-editor-close"].click()
diskEditorWait("An unchanged editor closes without a discard prompt") { !reopened.exists }
}
func testDiskImageEditorOS9InternalDragPreservesEntries() throws {
let fixture = try diskEditorFixture()
let before = session()
let editor = openDiskEditor()
editor.buttons["disk-editor-new-folder"].click(); diskEditorName("DOCS")
let folder = editor.staticTexts["DOCS"].firstMatch
XCTAssertTrue(folder.waitForExistence(timeout: 5))
diskEditorSelect("README.TXT", in: editor)
let source = editor.staticTexts["README.TXT"].firstMatch
let space = editor.descendants(matching: .any)["disk-editor-space"].firstMatch
let allocation = space.value as? String ?? space.label
// Exercise NSTableView's real drag initiation/file-promise path. Keep
// the entire gesture within this authored image's native file table.
let table = editor.descendants(matching: .any)["disk-editor-files"].firstMatch
let initialTrace = XCTAttachment(string: (table.value as? String) ?? table.debugDescription)
initialTrace.name = "OS-9 drag trace before gesture"; initialTrace.lifetime = .keepAlways; add(initialTrace)
let start = source.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.5))
let destination = table.coordinate(withNormalizedOffset: CGVector(dx: 0.85, dy: 0))
.withOffset(CGVector(dx: 0, dy: folder.frame.midY - table.frame.minY))
start.click(forDuration: 0.5, thenDragTo: destination, withVelocity: .slow, thenHoldForDuration: 1)
let trace = XCTAttachment(string: (table.value as? String) ?? table.debugDescription)
trace.name = "OS-9 drag trace after gesture"; trace.lifetime = .keepAlways; add(trace)
XCTAssertNotEqual(app.state, .notRunning, "Starting a disk-file drag after creating an OS-9 folder must not crash")
XCTAssertTrue(editor.exists)
diskEditorWait("Dropping onto an OS-9 folder must move the selected file out of the current directory") { !source.exists && folder.exists }
XCTAssertEqual(space.value as? String ?? space.label, allocation, "Moving into the existing folder must not allocate another copy of the file")
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
folder.doubleClick()
XCTAssertTrue(source.waitForExistence(timeout: 5), "The original file must now be in DOCS")
let exported = fixture.folder.appendingPathComponent("drag-moved.txt")
diskEditorExport("README.TXT", from: editor, to: exported)
XCTAssertEqual(try Data(contentsOf: exported), Data("VCC Plus authored Disk Image Editor fixture.\rDECB and OS-9 round trips preserve exact file bytes.\r".utf8))
editor.buttons["disk-editor-up"].click()
diskEditorWait("The moved file must remain absent from the source directory") { !source.exists && folder.exists }
editor.buttons["disk-editor-undo"].click()
XCTAssertTrue(source.waitForExistence(timeout: 5))
XCTAssertTrue(folder.exists)
diskEditorSelect("README.TXT", in: editor)
let shot = XCTAttachment(screenshot: editor.screenshot())
shot.name = "Disk Image Editor — OS-9 Move To and restored file"; shot.lifetime = .keepAlways; add(shot)
closeDiskEditorDiscardingChanges(editor)
XCTAssertEqual(session()[0], before[0], "Discarding the private folder must not restart the CoCo")
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
}
func testDiskImageEditorDECBInternalDragKeepsImageUnchanged() throws {
let fixture = try diskEditorFixture()
let before = session()
let editor = openDiskEditor()
diskEditorSelect("README.TXT", in: editor)
let source = editor.staticTexts["README.TXT"].firstMatch
let start = source.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
// A short horizontal drag stays in the Name column of the same row.
// It initiates a file promise without exporting to Finder or the Mac.
start.click(forDuration: 0.3, thenDragTo: start.withOffset(CGVector(dx: 100, dy: 0)), withVelocity: .slow, thenHoldForDuration: 0.5)
let table = editor.descendants(matching: .any)["disk-editor-files"].firstMatch
let trace = (table.value as? String) ?? table.debugDescription
let traceAttachment = XCTAttachment(string: trace)
traceAttachment.name = "DECB actual mouse drag callbacks"; traceAttachment.lifetime = .keepAlways; add(traceAttachment)
XCTAssertTrue(trace.contains("writer row="), "The real mouse gesture must invoke the file-promise writer")
XCTAssertTrue(trace.contains("begin rows="), "Survival only counts after a native dragging session actually begins")
XCTAssertNotEqual(app.state, .notRunning, "The DECB file-promise path must also survive a real drag")
XCTAssertTrue(editor.exists && source.exists)
XCTAssertFalse(editor.buttons["disk-editor-apply"].isEnabled, "A rejected internal drag must not create an image edit")
let shot = XCTAttachment(screenshot: editor.screenshot())
shot.name = "Disk Image Editor — DECB current move controls"; shot.lifetime = .keepAlways; add(shot)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
editor.buttons["disk-editor-close"].click()
diskEditorWait("An unchanged image must close and release its edit lease") {
!editor.exists && self.main.buttons["execution"].isEnabled
}
XCTAssertEqual(session()[0], before[0])
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
}
func testDiskImageEditorOS9ExportsFilePromiseToFinder() throws {
try diskEditorFilePromiseToFinder(twoFiles: false)
}
func testDiskImageEditorOS9ExportsTwoFilePromisesToFinder() throws {
try diskEditorFilePromiseToFinder(twoFiles: true)
}
private func diskEditorFilePromiseToFinder(twoFiles: Bool) throws {
try XCTSkipUnless((NSScreen.screens.map { $0.visibleFrame.width }.max() ?? 0) >= 2200,
"The isolated Finder drag check needs room for two separate windows.")
let fixture = try diskEditorFixture()
let folder = fixture.folder.appendingPathComponent("VCC Finder Drop " + String(UUID().uuidString.prefix(8)))
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false)
let editor = openDiskEditor()
let secondBytes = Data("SECOND AUTHORED FINDER PROMISE\r".utf8)
if twoFiles {
let second = fixture.folder.appendingPathComponent("SECOND.TXT")
try secondBytes.write(to: second)
diskEditorImport(second, into: editor, decb: false)
}
// Keep only the test editor in front of the destination. These are all
// windows of the isolated app, never the installed user's VCC session.
menu("Window", "Floppy Disks")
app.windows["Floppy Disks"].buttons[XCUIIdentifierCloseWindow].click()
menu("Window", "VCC UI Tests")
app.typeKey("m", modifierFlags: .command)
func place(_ window: XCUIElement, x: CGFloat, y: CGFloat) {
let frame = window.frame
let title = window.coordinate(withNormalizedOffset: CGVector(dx: 0.65, dy: 0)).withOffset(CGVector(dx: 0, dy: 14))
title.click(forDuration: 0.2, thenDragTo: title.withOffset(CGVector(dx: x - frame.minX, dy: y - frame.minY)))
}
place(editor, x: 30, y: 70)
let finder = XCUIApplication(bundleIdentifier: "com.apple.finder")
finder.activate()
let previousWindows = finder.windows.count
finder.typeKey("n", modifierFlags: .command)
diskEditorWait("Finder must create a separate test-owned window") { finder.windows.count > previousWindows }
finder.typeKey("g", modifierFlags: [.command, .shift])
let go = finder.sheets.firstMatch
XCTAssertTrue(go.waitForExistence(timeout: 5))
let field = go.comboBoxes.firstMatch.exists ? go.comboBoxes.firstMatch : go.textFields.firstMatch
XCTAssertTrue(field.waitForExistence(timeout: 5))
field.click(); finder.typeKey("a", modifierFlags: .command); field.typeText(folder.path)
finder.typeKey(.return, modifierFlags: [])
let destinationWindow = finder.windows[folder.lastPathComponent]
XCTAssertTrue(destinationWindow.waitForExistence(timeout: 8))
let finderTitle = folder.lastPathComponent
addTeardownBlock {
await MainActor.run {
// XCTest runs this even when a fatal assertion bypasses Swift
// defer. Never terminate Finder or close another folder.
let owned = XCUIApplication(bundleIdentifier: "com.apple.finder").windows[finderTitle]
if owned.exists { owned.buttons[XCUIIdentifierCloseWindow].click() }
}
}
place(destinationWindow, x: editor.frame.maxX + 30, y: 70)
XCTAssertGreaterThanOrEqual(destinationWindow.frame.minX, editor.frame.maxX, "Keep the real drop destination outside the source window")
app.activate()
let file = editor.staticTexts["README.TXT"].firstMatch
XCTAssertTrue(file.waitForExistence(timeout: 5))
file.click()
if twoFiles { XCUIElement.perform(withKeyModifiers: .command) { editor.staticTexts["SECOND.TXT"].firstMatch.click() } }
let start = file.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.5))
// The center-right of our empty Finder content is clear of its toolbar
// and sidebar, independently of the user's preferred Finder view mode.
let target = destinationWindow.coordinate(withNormalizedOffset: CGVector(dx: 0.75, dy: 0.65))
start.click(forDuration: 0.5, thenDragTo: target, withVelocity: .slow, thenHoldForDuration: 1)
let table = editor.descendants(matching: .any)["disk-editor-files"].firstMatch
var trace = (table.value as? String) ?? table.debugDescription
let receipt = XCTAttachment(string: trace)
receipt.name = "Finder actual file-promise callbacks"; receipt.lifetime = .keepAlways; add(receipt)
let exported = folder.appendingPathComponent("README.TXT")
let arrived = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in
FileManager.default.fileExists(atPath: exported.path) &&
(!twoFiles || FileManager.default.fileExists(atPath: folder.appendingPathComponent("SECOND.TXT").path))
}, object: nil)
let delivery = XCTWaiter.wait(for: [arrived], timeout: 15)
let ended = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in
((table.value as? String) ?? "").contains("ended operation=")
}, object: nil)
_ = XCTWaiter.wait(for: [ended], timeout: 5)
trace = (table.value as? String) ?? table.debugDescription
let finishedReceipt = XCTAttachment(string: trace)
finishedReceipt.name = "Finder completed file-promise callbacks"; finishedReceipt.lifetime = .keepAlways; add(finishedReceipt)
let exportedBytes = try? Data(contentsOf: exported)
let exportedSecond = try? Data(contentsOf: folder.appendingPathComponent("SECOND.TXT"))
let phases = (try? String(contentsOf: fixture.folder.appendingPathComponent("promise-trace.txt"), encoding: .utf8)) ?? "No promise delegate phase recorded"
let phaseReceipt = XCTAttachment(string: phases)
phaseReceipt.name = "Finder promise fulfillment phases"; phaseReceipt.lifetime = .keepAlways; add(phaseReceipt)
let sourceUnchanged = try Data(contentsOf: fixture.image) == fixture.original
let entryRemains = file.exists
let expectedImageEdits = editor.buttons["disk-editor-apply"].isEnabled == twoFiles
let shot = XCTAttachment(screenshot: destinationWindow.screenshot())
shot.name = "Finder — received authored disk file"; shot.lifetime = .keepAlways; add(shot)
destinationWindow.buttons[XCUIIdentifierCloseWindow].click()
app.activate()
// Close the front editor before restoring the minimized machine; the
// latter can otherwise physically cover the editor's footer controls.
editor.buttons["disk-editor-close"].click()
if twoFiles {
let discard = app.buttons["Discard Changes"].firstMatch
XCTAssertTrue(discard.waitForExistence(timeout: 5)); discard.click()
}
diskEditorWait("Closing after export must release the editor") { !editor.exists }
menu("Window", "VCC UI Tests")
XCTAssertTrue(main.buttons["execution"].isEnabled, "Completed Finder exports must release the media-command guard")
XCTAssertEqual(delivery, .completed, "Finder must receive and write the actual promised file")
XCTAssertEqual(exportedBytes, Data("VCC Plus authored Disk Image Editor fixture.\rDECB and OS-9 round trips preserve exact file bytes.\r".utf8))
XCTAssertTrue(trace.contains("writer row=") && trace.contains("begin rows="))
XCTAssertTrue(trace.contains("ended operation=1"), "Exporting to Finder must finish as a copy")
if twoFiles { XCTAssertEqual(exportedSecond, secondBytes) }
XCTAssertTrue(entryRemains && expectedImageEdits && sourceUnchanged)
}
func testDiskImageEditorOS9MoveToChooserAndCollision() throws {
let fixture = try diskEditorFixture()
let editor = openDiskEditor()
editor.buttons["disk-editor-new-folder"].click(); diskEditorName("DOCS")
XCTAssertTrue(editor.staticTexts["DOCS"].firstMatch.waitForExistence(timeout: 5))
func chooseDocs(fromContextMenu: Bool = false) -> XCUIElement {
diskEditorSelect("README.TXT", in: editor)
if fromContextMenu {
editor.staticTexts["README.TXT"].firstMatch.rightClick()
let move = app.menuItems["Move To…"].firstMatch
XCTAssertTrue(move.waitForExistence(timeout: 5)); move.click()
} else { editor.buttons["disk-editor-move"].click() }
let sheet = app.sheets.firstMatch
let confirm = sheet.buttons["disk-editor-move-confirm"]
XCTAssertTrue(confirm.waitForExistence(timeout: 5))
XCTAssertFalse(confirm.isEnabled, "Moving to the current folder must be unavailable")
let folder = sheet.staticTexts["DOCS"].firstMatch
XCTAssertTrue(folder.waitForExistence(timeout: 5)); folder.click()
diskEditorWait("A selected folder must be keyboard-openable") { sheet.buttons["disk-editor-move-open"].isEnabled }
app.typeKey(.downArrow, modifierFlags: .command)
diskEditorWait("Opening DOCS must enable moving here") { confirm.isEnabled && sheet.buttons["disk-editor-move-up"].isEnabled }
return sheet
}
let canceled = chooseDocs(fromContextMenu: true)
let shot = XCTAttachment(screenshot: editor.screenshot())
shot.name = "Disk Image Editor — OS-9 Move To folder chooser"; shot.lifetime = .keepAlways; add(shot)
canceled.buttons["disk-editor-move-cancel"].click()
XCTAssertTrue(editor.staticTexts["README.TXT"].firstMatch.exists)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
let chosen = chooseDocs()
chosen.buttons["disk-editor-move-confirm"].click()
diskEditorWait("Move Here must dismiss the chooser and remove the source entry") {
!chosen.exists && !editor.staticTexts["README.TXT"].firstMatch.exists
}
// A second distinct file with the same basename must not overwrite the
// moved original. A failed move must not add an Undo transaction.
let host = fixture.folder.appendingPathComponent("README.TXT")
let replacement = Data("KEEP THIS ROOT FILE\r".utf8)
try replacement.write(to: host)
diskEditorImport(host, into: editor, decb: false)
let conflict = chooseDocs()
conflict.buttons["disk-editor-move-confirm"].click()
XCTAssertTrue(conflict.descendants(matching: .any)["disk-editor-move-error"].firstMatch.waitForExistence(timeout: 5))
conflict.buttons["disk-editor-move-cancel"].click()
let rootExport = fixture.folder.appendingPathComponent("collision-root.txt")
diskEditorExport("README.TXT", from: editor, to: rootExport)
XCTAssertEqual(try Data(contentsOf: rootExport), replacement)
editor.staticTexts["DOCS"].firstMatch.doubleClick()
XCTAssertTrue(editor.staticTexts["README.TXT"].firstMatch.waitForExistence(timeout: 5))
let originalExport = fixture.folder.appendingPathComponent("collision-original.txt")
diskEditorExport("README.TXT", from: editor, to: originalExport)
XCTAssertEqual(try Data(contentsOf: originalExport), Data("VCC Plus authored Disk Image Editor fixture.\rDECB and OS-9 round trips preserve exact file bytes.\r".utf8))
editor.buttons["disk-editor-up"].click()
XCTAssertTrue(editor.staticTexts["README.TXT"].firstMatch.waitForExistence(timeout: 5))
editor.buttons["disk-editor-undo"].click()
diskEditorWait("Undo must remove only the later import, since collision made no change") { !editor.staticTexts["README.TXT"].firstMatch.exists }
editor.buttons["disk-editor-undo"].click()
XCTAssertTrue(editor.staticTexts["README.TXT"].firstMatch.waitForExistence(timeout: 5), "One Undo must restore the whole successful move")
editor.buttons["disk-editor-redo"].click()
diskEditorWait("Redo must repeat the move as one operation") { !editor.staticTexts["README.TXT"].firstMatch.exists }
closeDiskEditorDiscardingChanges(editor)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
}
func testDiskImageEditorOS9InformationPermissionsAndOwnership() throws {
let fixture = try diskEditorFixture()
let before = session()
let editor = openDiskEditor()
let permissionIDs = ["owner-read", "owner-write", "owner-execute", "public-read", "public-write", "public-execute", "single-access"]
let save = app.buttons["disk-editor-info-save"].firstMatch
let cancel = app.buttons["disk-editor-info-cancel"].firstMatch
let user = app.textFields["disk-editor-info-owner-user"].firstMatch
let group = app.textFields["disk-editor-info-owner-group"].firstMatch
func checkbox(_ id: String) -> XCUIElement { app.checkBoxes["disk-editor-info-" + id].firstMatch }
func openInformation() {
diskEditorSelect("README.TXT", in: editor)
editor.buttons["disk-editor-info"].click()
XCTAssertTrue(save.waitForExistence(timeout: 5))
XCTAssertEqual(app.sheets.count, 1, "File details, access and ownership belong in one modal")
}
func replace(_ field: XCUIElement, with value: String) {
field.click(); app.typeKey("a", modifierFlags: .command); field.typeText(value)
// Commit the numeric field through ordinary focus traversal before
// clicking another control; dismiss this field's macOS completion.
app.typeKey(.tab, modifierFlags: [])
}
func closeInformation() {
cancel.click()
diskEditorWait("Closing File Information must return to the disk editor") { !save.exists }
}
let space = editor.descendants(matching: .any)["disk-editor-space"].firstMatch
let allocation = space.value as? String ?? space.label
let originalExport = fixture.folder.appendingPathComponent("info-original.txt")
diskEditorExport("README.TXT", from: editor, to: originalExport)
let originalFile = try Data(contentsOf: originalExport)
openInformation()
XCTAssertFalse(save.isEnabled, "Unchanged information must not create an edit")
let originalUser = try XCTUnwrap(user.value as? String)
let originalGroup = try XCTUnwrap(group.value as? String)
let originalPermissions = permissionIDs.map { (checkbox($0).value as? NSNumber)?.intValue ?? -1 }
XCTAssertFalse(originalPermissions.contains(-1))
let entryType = app.descendants(matching: .any)["disk-editor-info-directory"].firstMatch
XCTAssertEqual(entryType.value as? String ?? entryType.label, "File")
checkbox("owner-write").click()
closeInformation()
XCTAssertFalse(editor.buttons["disk-editor-apply"].isEnabled, "Cancel must leave the working image unchanged")
openInformation()
XCTAssertEqual(permissionIDs.map { (checkbox($0).value as? NSNumber)?.intValue ?? -1 }, originalPermissions)
replace(group, with: "256")
XCTAssertTrue(app.descendants(matching: .any)["disk-editor-info-validation"].firstMatch.exists)
XCTAssertFalse(save.isEnabled)
replace(group, with: "12")
replace(user, with: "-1")
XCTAssertFalse(save.isEnabled)
replace(user, with: "34")
for id in ["owner-write", "public-execute", "single-access"] { checkbox(id).click() }
let editedPermissions = permissionIDs.map { (checkbox($0).value as? NSNumber)?.intValue ?? -1 }
let combinedOwner = app.descendants(matching: .any)["disk-editor-info-owner-id"].firstMatch
let combinedText = combinedOwner.value as? String ?? combinedOwner.label
XCTAssertEqual(combinedText.filter(\.isNumber), "3106")
XCTAssertTrue(save.isEnabled)
let sheetShot = XCTAttachment(screenshot: editor.screenshot())
sheetShot.name = "Disk Image Editor — OS-9 File Information"; sheetShot.lifetime = .keepAlways; add(sheetShot)
save.click()
diskEditorWait("Saving information must change the private disk entry and close its modal") {
!save.exists && editor.staticTexts["12.34"].firstMatch.exists
}
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
XCTAssertEqual(space.value as? String ?? space.label, allocation, "Attribute edits must not allocate file data")
let editedExport = fixture.folder.appendingPathComponent("info-edited.txt")
diskEditorExport("README.TXT", from: editor, to: editedExport)
XCTAssertEqual(try Data(contentsOf: editedExport), originalFile)
editor.buttons["disk-editor-undo"].click()
openInformation()
XCTAssertEqual(user.value as? String, originalUser)
XCTAssertEqual(group.value as? String, originalGroup)
XCTAssertEqual(permissionIDs.map { (checkbox($0).value as? NSNumber)?.intValue ?? -1 }, originalPermissions)
closeInformation()
editor.buttons["disk-editor-redo"].click()
openInformation()
XCTAssertEqual(user.value as? String, "34")
XCTAssertEqual(group.value as? String, "12")
XCTAssertEqual(permissionIDs.map { (checkbox($0).value as? NSNumber)?.intValue ?? -1 }, editedPermissions)
closeInformation()
editor.buttons["disk-editor-apply"].click()
let apply = app.buttons["Restart and Apply"].firstMatch
XCTAssertTrue(apply.waitForExistence(timeout: 5)); apply.click()
diskEditorWait("Applying OS-9 information must close the editor", timeout: 15) { !editor.exists }
diskEditorWait("Applying disk metadata must cold-restart after confirmation") { self.session()[0] > before[0] }
XCTAssertNotEqual(try Data(contentsOf: fixture.image), fixture.original)
let reopened = openDiskEditor()
openInformation()
XCTAssertEqual(user.value as? String, "34")
XCTAssertEqual(group.value as? String, "12")
XCTAssertEqual(permissionIDs.map { (checkbox($0).value as? NSNumber)?.intValue ?? -1 }, editedPermissions)
closeInformation()
let appliedExport = fixture.folder.appendingPathComponent("info-applied.txt")
diskEditorExport("README.TXT", from: reopened, to: appliedExport)
XCTAssertEqual(try Data(contentsOf: appliedExport), originalFile)
XCTAssertEqual(space.value as? String ?? space.label, allocation)
reopened.buttons["disk-editor-close"].click()
diskEditorWait("The saved OS-9 image closes without another edit prompt") { !reopened.exists }
}
func testDiskImageEditorHardDiskOS9AndHDBVolumeApply() throws {
let fixture = try diskEditorFixture()
let before = session()
menu("Media", "Virtual Hard Disks…")
let disks = app.windows["Virtual Hard Disks"]
XCTAssertTrue(disks.waitForExistence(timeout: 5))
let shot = XCTAttachment(screenshot: disks.screenshot())
shot.name = "Hard disks — HD0 and HD1 Edit"; shot.lifetime = .keepAlways; add(shot)
let edit = disks.buttons["hard-disk-edit-0"]
XCTAssertTrue(edit.waitForExistence(timeout: 5)); XCTAssertTrue(edit.isEnabled); edit.click()
let editor = diskEditorWindow
XCTAssertTrue(editor.waitForExistence(timeout: 8))
XCTAssertTrue(editor.staticTexts["README.TXT"].firstMatch.waitForExistence(timeout: 8))
XCTAssertTrue(editor.buttons["disk-editor-apply"].label.contains("HD0"))
XCTAssertFalse(main.buttons["execution"].isEnabled)
XCTAssertFalse(disks.buttons["hard-disk-edit-1"].isEnabled)
editor.buttons["disk-editor-new-folder"].click(); diskEditorName("DOCS")
XCTAssertTrue(editor.staticTexts["DOCS"].firstMatch.waitForExistence(timeout: 5))
let volume = editor.popUpButtons["disk-editor-volume"]
XCTAssertTrue(volume.exists); volume.click()
app.menuItems["HDB-DOS disk 1"].firstMatch.click()
diskEditorWait("HDB-DOS must show Disk BASIC actions") { !editor.buttons["disk-editor-new-folder"].isEnabled }
diskEditorSelect("README.TXT", in: editor)
editor.buttons["disk-editor-rename"].click(); diskEditorName("HD1.TXT")
XCTAssertTrue(editor.staticTexts["HD1.TXT"].firstMatch.waitForExistence(timeout: 5))
let exported = fixture.folder.appendingPathComponent("HDB-export.txt")
diskEditorExport("HD1.TXT", from: editor, to: exported)
XCTAssertFalse(try Data(contentsOf: exported).isEmpty)
let volumesShot = XCTAttachment(screenshot: editor.screenshot())
volumesShot.name = "Hard disk editor — numbered volume"; volumesShot.lifetime = .keepAlways; add(volumesShot)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
editor.buttons["disk-editor-apply"].click()
XCTAssertTrue(app.buttons["Restart and Apply"].firstMatch.waitForExistence(timeout: 5))
app.buttons["Cancel"].firstMatch.click()
XCTAssertTrue(editor.exists); XCTAssertEqual(session()[0], before[0])
editor.buttons["disk-editor-apply"].click()
let apply = app.buttons["Restart and Apply"].firstMatch
XCTAssertTrue(apply.waitForExistence(timeout: 5)); apply.click()
diskEditorWait("Hard disk Apply closes after a confirmed restart", timeout: 15) { !editor.exists }
XCTAssertGreaterThan(session()[0], before[0])
let applied = try Data(contentsOf: fixture.image)
XCTAssertEqual(applied.count, fixture.original.count)
XCTAssertEqual(applied.suffix(512), fixture.original.suffix(512))
XCTAssertEqual(applied[161280..<(161280 * 2)], fixture.original[161280..<(161280 * 2)], "Other numbered disk remains unchanged")
disks.buttons["hard-disk-edit-0"].click()
XCTAssertTrue(editor.staticTexts["DOCS"].firstMatch.waitForExistence(timeout: 8))
editor.popUpButtons["disk-editor-volume"].click(); app.menuItems["HDB-DOS disk 1"].firstMatch.click()
XCTAssertTrue(editor.staticTexts["HD1.TXT"].firstMatch.waitForExistence(timeout: 5))
editor.buttons["disk-editor-close"].click()
diskEditorWait("Saved hard disk closes without discard") { !editor.exists }
disks.buttons["hard-disk-edit-1"].click()
XCTAssertTrue(editor.waitForExistence(timeout: 8))
XCTAssertTrue(editor.buttons["disk-editor-apply"].label.contains("HD1"))
XCTAssertFalse(editor.staticTexts["DOCS"].firstMatch.exists)
editor.buttons["disk-editor-close"].click()
diskEditorWait("HD1 closes without changing its independent image") { !editor.exists }
}
func testDiskImageEditorOS9FoldersUndoAndApplyConfirmation() throws {
let fixture = try diskEditorFixture()
let before = session()
let hostBytes = Data("HOST COPY\r".utf8)
let host = fixture.folder.appendingPathComponent("INPUT.TXT")
try hostBytes.write(to: host)
let editor = openDiskEditor()
XCTAssertTrue(editor.buttons["disk-editor-new-folder"].isEnabled)
let os9Shot = XCTAttachment(screenshot: editor.screenshot()); os9Shot.name = "Disk Image Editor — OS-9"; os9Shot.lifetime = .keepAlways; add(os9Shot)
editor.buttons["disk-editor-new-folder"].click(); diskEditorName("DOCS")
XCTAssertTrue(editor.staticTexts["DOCS"].firstMatch.waitForExistence(timeout: 5))
editor.buttons["disk-editor-undo"].click()
diskEditorWait("Undo must remove only the new OS-9 directory") { !editor.staticTexts["DOCS"].firstMatch.exists }
editor.buttons["disk-editor-redo"].click()
let directory = editor.staticTexts["DOCS"].firstMatch
XCTAssertTrue(directory.waitForExistence(timeout: 5)); directory.doubleClick()
diskEditorWait("Double-clicking an OS-9 folder must navigate into it") { !editor.staticTexts["README.TXT"].firstMatch.exists }
diskEditorImport(host, into: editor, decb: false)
let exported = fixture.folder.appendingPathComponent("os9-import.txt")
diskEditorExport("INPUT.TXT", from: editor, to: exported)
XCTAssertEqual(try Data(contentsOf: exported), hostBytes)
editor.buttons["disk-editor-up"].click()
XCTAssertTrue(editor.staticTexts["README.TXT"].firstMatch.waitForExistence(timeout: 5))
XCTAssertTrue(editor.staticTexts["DOCS"].firstMatch.exists)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
editor.buttons["disk-editor-apply"].click()
XCTAssertTrue(app.buttons["Restart and Apply"].firstMatch.waitForExistence(timeout: 5))
app.buttons["Cancel"].firstMatch.click()
XCTAssertTrue(editor.exists, "Cancelling Apply must preserve the editor and its working changes")
XCTAssertFalse(main.buttons["execution"].isEnabled)
XCTAssertEqual(try Data(contentsOf: fixture.image), fixture.original)
XCTAssertEqual(session()[0], before[0], "Cancelling OS-9 Apply must not restart the CoCo")
editor.buttons["disk-editor-apply"].click()
let apply = app.buttons["Restart and Apply"].firstMatch
XCTAssertTrue(apply.waitForExistence(timeout: 5)); apply.click()
diskEditorWait("Confirmed OS-9 Apply must close the editor", timeout: 15) { !editor.exists }
diskEditorWait("OS-9 Apply must cold-restart after confirmation") { self.session()[0] > before[0] }
XCTAssertNotEqual(try Data(contentsOf: fixture.image), fixture.original)
let reopened = openDiskEditor()
let savedFolder = reopened.staticTexts["DOCS"].firstMatch
XCTAssertTrue(savedFolder.waitForExistence(timeout: 5)); savedFolder.doubleClick()
XCTAssertTrue(reopened.staticTexts["INPUT.TXT"].firstMatch.waitForExistence(timeout: 5))
reopened.buttons["disk-editor-close"].click()
diskEditorWait("Reopened OS-9 image closes without discarding saved files") { !reopened.exists }
}
func testKeyboardAndJoystickPickersDuringRefresh() {
menu("Input", "Keyboard and Joysticks…")
let input = app.windows["Keyboard and Joysticks"]
XCTAssertTrue(input.waitForExistence(timeout: 5))
expand(input.disclosureTriangles.matching(NSPredicate(format: "label CONTAINS %@", "Controller Test")).firstMatch)
let preview = input.staticTexts["controller-preview-ui-fixture"]
XCTAssertTrue(preview.exists)
let reading = preview.value as? String
XCTAssertNotNil(reading)
input.descendants(matching: .any)["input-keyboard"].firstMatch.click()
liveHold(app.menuItems["Compact"].firstMatch)
XCTAssertNotEqual(preview.value as? String, reading, "Controller preview must update while choosing a keyboard mode")
app.menuItems["Compact"].firstMatch.click()
XCTAssertEqual(input.descendants(matching: .any)["input-keyboard"].firstMatch.value as? String, "Compact")
input.descendants(matching: .any)["input-source-0"].firstMatch.click()
liveHold(app.menuItems["Keyboard"].firstMatch)
app.menuItems["Keyboard"].firstMatch.click()
XCTAssertEqual(input.descendants(matching: .any)["input-source-0"].firstMatch.value as? String, "Keyboard")
}
}
extension InteractionTests {
func testDisplayAppearanceAndScreenshotPreserveSession() throws {
let before = session()
menu("Display", "Display Settings…")
let settings = app.windows["Display Settings"]
let scaling = settings.popUpButtons["display-scaling"]
XCTAssertTrue(scaling.waitForExistence(timeout: 5))
scaling.click()
liveHold(app.menuItems["Sharp — Fit Window"].firstMatch, seconds: 1)
app.menuItems["Sharp — Fit Window"].firstMatch.click()
settings.checkBoxes["display-scanlines"].click()
XCTAssertEqual(scaling.value as? String, "Sharp — Fit Window")
XCTAssertEqual(settings.checkBoxes["display-scanlines"].value as? Int, 1)
settings.buttons["Reset Display Appearance"].click()
XCTAssertEqual(scaling.value as? String, "Smooth — Fit Window")
XCTAssertEqual(settings.checkBoxes["display-scanlines"].value as? Int, 0)
settings.buttons["Save CoCo Screen…"].click()
let cancel = app.buttons["Cancel"].firstMatch
XCTAssertTrue(cancel.waitForExistence(timeout: 5)); cancel.click()
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertGreaterThan(session()[1], before[1])
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCC-Screenshot-UI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: folder) }
settings.buttons["Save CoCo Screen…"].click()
XCTAssertTrue(cancel.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift])
app.typeText(folder.path + "/")
app.typeKey(.return, modifierFlags: [])
let save = app.buttons["Save"].firstMatch
XCTAssertTrue(save.waitForExistence(timeout: 5)); save.click()
var output: URL?
let saved = NSPredicate { _, _ in
output = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil))?.first { $0.pathExtension == "png" }
return output != nil
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: saved, object: nil)], timeout: 10), .completed)
XCTAssertEqual(try Data(contentsOf: XCTUnwrap(output)).prefix(8), Data([137,80,78,71,13,10,26,10]))
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let shot = XCTAttachment(screenshot: settings.screenshot())
shot.name = "Display Settings"; shot.lifetime = .keepAlways; add(shot)
}
}
extension InteractionTests {
func testSoftwareLibraryDocumentationCapture() throws {
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
if library.descendants(matching: .any)["library-catalog-empty"].firstMatch.exists {
throw XCTSkip("Stage the prepared local catalog for the documentation capture.")
}
library.buttons["library-scope-showcase"].click()
let cover = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "library-title-")).firstMatch
XCTAssertTrue(cover.waitForExistence(timeout: 15))
cover.click()
let settled = NSPredicate { _, _ in
!library.progressIndicators.allElementsBoundByIndex.contains(where: { $0.isHittable })
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: settled, object: nil)], timeout: 25), .completed,
"Capture settled cover art or its honest fallback, rather than loading spinners")
let shot = XCTAttachment(screenshot: library.screenshot())
shot.name = "Software Library — settled documentation view"; shot.lifetime = .keepAlways; add(shot)
}
func testSoftwareLibraryBrowsingPreservesRunningSession() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
let search = library.descendants(matching: .any)["library-search"].firstMatch
XCTAssertTrue(search.waitForExistence(timeout: 15))
if library.descendants(matching: .any)["library-catalog-empty"].firstMatch.exists {
throw XCTSkip("A full local catalog is required for the Archive browsing integration check.")
}
library.buttons["library-scope-showcase"].click()
let firstCover = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "library-title-")).firstMatch
XCTAssertTrue(firstCover.waitForExistence(timeout: 15))
let covers = XCTAttachment(screenshot: library.screenshot())
covers.name = "Software Library — Cover Collection"; covers.lifetime = .keepAlways; add(covers)
library.buttons["library-scope-all"].click()
library.radioButtons["Shelf"].click()
search.click()
app.typeText("Aerial Attack")
let aerial = library.buttons["library-title-c431ec3a140ac5715db5e93f141d13d4"]
XCTAssertTrue(aerial.waitForExistence(timeout: 10)); aerial.click()
let instructions = library.descendants(matching: .any)["library-loading-instructions"].firstMatch
XCTAssertTrue(instructions.waitForExistence(timeout: 5))
let command = library.descendants(matching: .any)["library-loading-command"].firstMatch
let hasCassetteCommand = NSPredicate { _, _ in
((command.value as? String ?? "") + command.label).contains("CLOADM")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: hasCassetteCommand, object: nil)], timeout: 5), .completed)
let compatibility = library.descendants(matching: .any)["library-compatibility-notes"].firstMatch
XCTAssertTrue(compatibility.exists, "Video caveats remain separate from loading instructions")
XCTAssertTrue(((compatibility.value as? String ?? "") + compatibility.label).contains("SG-24"))
let favorite = library.buttons["library-favorite"]
XCTAssertTrue(favorite.exists)
if favorite.label == "Remove Favorite" { favorite.click() }
favorite.click()
XCTAssertEqual(favorite.label, "Remove Favorite")
search.click(); app.typeKey("a", modifierFlags: .command); app.typeKey(.delete, modifierFlags: [])
library.buttons["library-scope-favorites"].click()
XCTAssertTrue(aerial.waitForExistence(timeout: 5))
library.radioButtons["Table"].click()
XCTAssertTrue(library.outlines["Software titles"].waitForExistence(timeout: 5))
library.radioButtons["Shelf"].click()
XCTAssertTrue(aerial.waitForExistence(timeout: 5))
let cartridges = library.buttons["library-category-Cartridges"]
XCTAssertTrue(cartridges.waitForExistence(timeout: 5)); cartridges.click()
search.click(); app.typeText("Mega-Bug")
let megaBug = library.buttons["library-title-0e1c55f0a29a52d91d28903454654bd7"]
XCTAssertTrue(megaBug.waitForExistence(timeout: 5))
liveHold(search, seconds: 1)
XCTAssertEqual(search.value as? String, "Mega-Bug", "Search text and focus survive emulator refresh")
megaBug.click()
XCTAssertTrue(library.descendants(matching: .any)["library-detail-title"].firstMatch.exists)
library.buttons["library-scope-all"].click()
library.buttons["library-filters"].click()
library.popUpButtons["library-filter-type"].click()
app.menuItems["Games"].firstMatch.click()
app.typeKey(.escape, modifierFlags: [])
search.click(); app.typeKey("a", modifierFlags: .command); app.typeText("Bedlam")
let bedlam = library.buttons["library-title-2a384f275ebcae78dca310d3312e9cdf"]
XCTAssertTrue(bedlam.waitForExistence(timeout: 5)); bedlam.click()
let editions = library.popUpButtons["library-release-picker"]
XCTAssertTrue(editions.waitForExistence(timeout: 5))
editions.click()
app.menuItems["library-release-4ae2f5e30faa14f8d30abd7efb711b90"].firstMatch.click()
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: hasCassetteCommand, object: nil)], timeout: 5), .completed)
editions.click()
app.menuItems["library-release-0d0cf0cd41681695d541afdbaba15096"].firstMatch.click()
let hasDiskCommand = NSPredicate { _, _ in
((command.value as? String ?? "") + command.label).contains("LOADM\"BEDLAM\":EXEC")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: hasDiskCommand, object: nil)], timeout: 5), .completed)
liveHold(editions, seconds: 1)
XCTAssertTrue(library.buttons["library-play"].exists)
XCTAssertTrue(library.buttons["library-install"].exists, "Installation is available without starting the guest software")
let shot = XCTAttachment(screenshot: library.screenshot())
shot.name = "Software Library — formats and loading guidance"; shot.lifetime = .keepAlways; add(shot)
let originalFrame = library.frame
let corner = library.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
let delta = CGVector(dx: originalFrame.width > 950 ? -100 : 80,
dy: originalFrame.height > 650 ? -80 : 60)
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(delta))
XCTAssertNotEqual(library.frame.width, originalFrame.width, "The native Library window must actually resize")
for control in [search, library.buttons["library-scope-all"], library.radioButtons["Shelf"], library.radioButtons["Table"]] {
XCTAssertTrue(control.isHittable)
XCTAssertTrue(library.frame.insetBy(dx: -1, dy: -1).contains(control.frame), "Library navigation must remain inside the resized window")
}
let compact = XCTAttachment(screenshot: library.screenshot())
compact.name = "Software Library — compact window"; compact.lifetime = .keepAlways; add(compact)
library.buttons[XCUIIdentifierCloseWindow].click()
menu("Media", "Software Library…")
XCTAssertTrue(library.waitForExistence(timeout: 5))
search.click(); app.typeKey("a", modifierFlags: .command); app.typeKey(.delete, modifierFlags: [])
library.buttons["library-scope-favorites"].click()
XCTAssertTrue(aerial.waitForExistence(timeout: 5), "Favorites survive closing and reopening Library")
library.buttons[XCUIIdentifierCloseWindow].click()
let after = session()
XCTAssertEqual(after[0], before[0], "Browsing must not restart the CoCo")
XCTAssertEqual(after[2], before[2], "Browsing must not restart audio")
XCTAssertGreaterThan(after[1], before[1], "Emulation continues while browsing")
XCTAssertEqual(after[3], before[3], "Library search keystrokes must not reach the CoCo")
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
XCTAssertEqual(main.buttons["execution"].label, "Pause")
}
}
extension InteractionTests {
func testSoftwareLibraryFiltersRemainOpenDuringEmulation() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
let search = library.descendants(matching: .any)["library-search"].firstMatch
XCTAssertTrue(search.waitForExistence(timeout: 15))
let firstCover = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "library-title-")).firstMatch
XCTAssertTrue(firstCover.waitForExistence(timeout: 15))
library.buttons["library-scope-all"].click()
library.buttons["library-filters"].click()
let format = app.popUpButtons["library-filter-media"].firstMatch
XCTAssertTrue(format.waitForExistence(timeout: 5))
format.click()
app.menuItems["Cartridge"].firstMatch.click()
liveHold(format, seconds: 1)
XCTAssertEqual(format.value as? String, "Cartridge")
let shot = XCTAttachment(screenshot: library.screenshot())
shot.name = "Software Library — light appearance and format filter"; shot.lifetime = .keepAlways; add(shot)
app.typeKey(.escape, modifierFlags: [])
XCTAssertTrue(library.buttons["Clear filters"].exists,
"The live format choice remains active before entering a global search")
search.click(); app.typeText("Mega-Bug")
let cartridge = library.buttons["library-title-0e1c55f0a29a52d91d28903454654bd7"]
XCTAssertTrue(cartridge.waitForExistence(timeout: 5))
let result = library.descendants(matching: .any)["library-result-count"].firstMatch
let oneResult = NSPredicate { _, _ in
(result.value as? String ?? result.label).hasPrefix("1 title")
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: oneResult, object: nil)], timeout: 5), .completed)
cartridge.click()
XCTAssertFalse(library.buttons["Clear filters"].exists,
"Entering a global search clears the preceding collection's narrower filters")
let heading = library.descendants(matching: .any)["library-heading"].firstMatch
XCTAssertTrue((heading.value as? String ?? heading.label).contains("Search Results"))
let after = session()
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertEqual(after[3], before[3])
XCTAssertGreaterThan(after[1], before[1])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
}
extension InteractionTests {
func testSoftwareLibraryPublishedGamesAcceptance() throws {
let environment = ProcessInfo.processInfo.environment
try XCTSkipUnless(environment["VCC_RUN_PUBLISHED_LIBRARY_UI"] == "1",
"Explicitly opt into verified published-game downloads and supplied local BASIC firmware")
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let localROMs = mac.appendingPathComponent("LocalResources/ROMs")
let system = URL(fileURLWithPath: environment["VCC_BASIC_SYSTEM_ROM"] ?? localROMs.appendingPathComponent("coco3.rom").path)
let disk = URL(fileURLWithPath: environment["VCC_BASIC_DISK_ROM"] ?? localROMs.appendingPathComponent("disk11.rom").path)
try XCTSkipUnless(FileManager.default.fileExists(atPath: system.path) && FileManager.default.fileExists(atPath: disk.path),
"Supply the local system and Disk BASIC ROMs for the isolated actual-game launch")
app.terminate()
app.launchArguments.removeAll { ["--library-exclusive-fixture", "--library-install-fixture", "--library-play-fixture"].contains($0) }
app.launchEnvironment["VCC_BASIC_SYSTEM_ROM"] = system.path
app.launchEnvironment["VCC_BASIC_DISK_ROM"] = disk.path
app.launch()
XCTAssertTrue(main.waitForExistence(timeout: 15))
let parent = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPublishedLibraryUI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: false)
defer { app.terminate(); try? FileManager.default.removeItem(at: parent) }
func wait(_ message: String, timeout: TimeInterval = 30, _ condition: @escaping () -> Bool) {
let predicate = NSPredicate { _, _ in condition() }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: timeout), .completed, message)
}
wait("The supplied real BASIC firmware must reach the running isolated machine") {
self.session().count == 5 && self.main.buttons["execution"].label == "Pause"
}
let beforeBrowsing = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 15))
app.activate()
let overviewSize = library.frame.size
let corner = library.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(CGVector(dx: 1300 - overviewSize.width, dy: 820 - overviewSize.height)))
wait("The handbook overview must give all three cards room", timeout: 10) { library.frame.width > 1250 && library.frame.height > 780 }
let bone = library.buttons["library-title-vccplus.bone-quest"]
let capital = library.buttons["library-title-vccplus.capital-quest"]
let quad = library.buttons["library-title-vccplus.quadrapassel"]
XCTAssertTrue(bone.waitForExistence(timeout: 20))
XCTAssertTrue(capital.waitForExistence(timeout: 20))
XCTAssertTrue(quad.waitForExistence(timeout: 10))
XCTAssertFalse(library.buttons["library-title-6062d9b73d08579671fe0d489c53fdd0"].exists,
"Double Dragon remains in the regular catalog, outside Getting Started")
capital.click()
let editionPicker = library.popUpButtons["library-release-picker"]
XCTAssertTrue(editionPicker.waitForExistence(timeout: 10))
XCTAssertTrue((editionPicker.value as? String ?? "").contains("2026-11-12"),
"A fresh Library must select the new Capital Quest edition and show its date")
wait("Getting Started artwork must finish loading before its manual capture") { library.progressIndicators.count == 0 }
XCTAssertTrue([bone, capital, quad].allSatisfy { $0.isHittable && library.frame.contains($0.frame) },
"All three Getting Started cards must be visible in the handbook overview")
library.textFields["library-search"].hover()
let startedShot = XCTAttachment(screenshot: library.screenshot())
startedShot.name = "Book 4 — Getting Started with published VCC Plus-exclusive games"; startedShot.lifetime = .keepAlways; add(startedShot)
// These editorial categories and stable IDs come from verified catalog data.
library.buttons["library-type-Educational"].click()
XCTAssertTrue(capital.waitForExistence(timeout: 10))
XCTAssertTrue(bone.waitForExistence(timeout: 10))
wait("Quadrapassel is not an educational title", timeout: 10) { !quad.exists }
library.buttons["library-type-Games"].click()
XCTAssertTrue(bone.waitForExistence(timeout: 10))
XCTAssertTrue(capital.waitForExistence(timeout: 10)); XCTAssertTrue(quad.waitForExistence(timeout: 10))
library.buttons["library-scope-getting-started"].click()
func detailButton(_ id: String, towardTop: Bool) -> XCUIElement {
app.activate()
let button = library.buttons[id]
XCTAssertTrue(button.waitForExistence(timeout: 10))
let detail = library.scrollViews.containing(.button, identifier: id).firstMatch
func comfortablyVisible() -> Bool {
button.isHittable && button.frame.minY > library.frame.minY + 110
&& button.frame.maxY < library.frame.maxY - 80
}
for _ in 0..<10 where !comfortablyVisible() { detail.scroll(byDeltaX: 0, deltaY: towardTop ? 250 : -250) }
wait("The actual Library action must be fully inside the visible detail pane: " + id, timeout: 10) { comfortablyVisible() }
return button
}
func capture(_ window: XCUIElement, name: String, hover _: XCUIElement) {
if window.identifier == "machine" { menu("Window", "VCC UI Tests") }
let image = XCTAttachment(screenshot: window.screenshot())
image.name = name; image.lifetime = .keepAlways; add(image)
}
func saveSource(to destination: URL) {
detailButton("library-open-source", towardTop: false).click()
let download = app.buttons["Download Source"].firstMatch
XCTAssertTrue(download.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift])
let path = app.textFields["PathTextField"].firstMatch
XCTAssertTrue(path.waitForExistence(timeout: 5))
path.click(); app.typeKey("a", modifierFlags: .command); path.typeText(destination.deletingLastPathComponent().path + "/")
app.typeKey(.return, modifierFlags: [])
let name = app.textFields["saveAsNameTextField"].firstMatch
wait("The new personal source folder must be editable", timeout: 10) { name.exists && name.isEnabled && name.isHittable }
name.click(); app.typeKey("a", modifierFlags: .command); name.typeText(destination.lastPathComponent)
download.click()
}
let games: [(id: String, label: String, wrapper: String, disk: String)] = [
("vccplus.bone-quest", "Bone Quest", "BoneQuest", "BONEQ.DSK"),
("vccplus.capital-quest", "Capital Quest", "CapitalQuest", "CAPITAL.DSK"),
("vccplus.quadrapassel", "Quadrapassel", "Quadrapassel", "QUADPSL05.DSK")
]
// Resume the independent Play phase without repeating completed source/manual checks.
if environment["VCC_PUBLISHED_PLAY_ONLY"] != "1" {
for game in games {
library.buttons["library-title-" + game.id].click()
XCTAssertTrue(library.descendants(matching: .any)["library-exclusive"].firstMatch.waitForExistence(timeout: 10))
XCTAssertFalse(library.links["View on Color Computer Archive"].exists)
capture(library, name: "Book 4 — " + game.label + " owned-title provenance and manual action", hover: library.textFields["library-search"])
detailButton("library-read-manual", towardTop: true).click()
let reader = app.windows["Software Manual"]
XCTAssertTrue(reader.waitForExistence(timeout: 10))
XCTAssertTrue(reader.buttons["manual-fit"].waitForExistence(timeout: 90), "The real hosted PDF must download, verify and render: " + game.label)
capture(reader, name: "Book 4 — " + game.label + " published PDF in native reader", hover: reader.staticTexts.firstMatch)
reader.buttons[XCUIIdentifierCloseWindow].click()
_ = detailButton("library-open-source", towardTop: false)
XCTAssertTrue(library.descendants(matching: .any)["library-online-manual"].firstMatch.exists)
capture(library, name: "Book 4 — " + game.label + " source and online manual controls", hover: library.textFields["library-search"])
let destination = parent.appendingPathComponent(game.wrapper + " Personal Source")
saveSource(to: destination)
let workspace = app.windows["C Development"]
XCTAssertTrue(workspace.waitForExistence(timeout: 90), "The verified source starter must open: " + game.label)
let editor = workspace.textViews["cmoc.source"]
XCTAssertTrue(editor.waitForExistence(timeout: 10))
let project = destination.appendingPathComponent(game.wrapper)
wait("The known source entry must be opened from the personal import", timeout: 60) {
FileManager.default.fileExists(atPath: project.appendingPathComponent("vccplus-project.json").path)
&& workspace.staticTexts[game.wrapper].firstMatch.exists && !(editor.value as? String ?? "").isEmpty
}
XCTAssertFalse(workspace.buttons["cmoc.launch"].isEnabled, "Opening source must not compile or inherit a runnable build")
let build = workspace.descendants(matching: .any)["cmoc.status.build"].firstMatch
XCTAssertTrue((build.label + (build.value as? String ?? "")).localizedCaseInsensitiveContains("not built"),
"Opening source must report its unbuilt state")
XCTAssertEqual(workspace.popUpButtons["Configuration, Build configuration"].value as? String, "Release",
"The published starter's Release configuration must be selected: " + game.label)
let configuration = try JSONSerialization.jsonObject(with: Data(contentsOf: project.appendingPathComponent("vccplus-project.json"))) as? [String: Any]
let entry = try XCTUnwrap(configuration?["entrySource"] as? String)
XCTAssertEqual(editor.value as? String, try String(contentsOf: project.appendingPathComponent(entry), encoding: .utf8))
for key in ["binary", "diskImage"] {
if let relative = configuration?[key] as? String {
XCTAssertFalse(FileManager.default.fileExists(atPath: project.appendingPathComponent(relative).path),
"The clean source starter must not acquire build products just from Open Source")
}
}
capture(workspace, name: "Book 4 — " + game.label + " editable personal source without building", hover: workspace.staticTexts["CMOC · Project workspace"].firstMatch)
menu("Media", "Software Library…")
XCTAssertTrue(library.waitForExistence(timeout: 5))
}
}
let afterBrowsing = session()
XCTAssertEqual(afterBrowsing[0], beforeBrowsing[0], "Reading manuals/importing source must not reset the CoCo")
XCTAssertEqual(afterBrowsing[2], beforeBrowsing[2], "Source import must not restart audio")
XCTAssertEqual(afterBrowsing[3], beforeBrowsing[3], "Save-panel typing must not reach the guest")
func play(_ game: (id: String, label: String, wrapper: String, disk: String), reviewExpected: Bool, cached: Bool) {
menu("Media", "Software Library…")
XCTAssertTrue(library.waitForExistence(timeout: 5))
library.buttons["library-scope-getting-started"].click()
library.buttons["library-title-" + game.id].click()
let initial = session()
XCTAssertEqual(initial.count, 5)
detailButton("library-play", towardTop: true).click()
let restart = app.buttons["Restart & Play"].firstMatch
if reviewExpected {
XCTAssertTrue(restart.waitForExistence(timeout: 90), "An occupied guest requires our state-preserving restart review")
XCTAssertFalse(app.buttons["library-confirm-play"].exists, "Curated Play has no redundant generic setup chooser")
restart.click()
}
wait("Curated Play must cold-restart and mount its declared disk: " + game.label, timeout: 90) {
let live = self.session()
return live.count == 5 && live[0] != initial[0]
&& self.main.buttons["execution"].label == "Pause"
&& self.main.links["FD0 " + game.disk].exists
}
XCTAssertFalse(restart.exists)
XCTAssertFalse(app.buttons["library-confirm-play"].exists)
XCTAssertFalse(library.descendants(matching: .any)["library-launch-error"].firstMatch.exists)
let running = session()
wait("The launched game must continue through disk loading and title drawing", timeout: 35) {
let live = self.session(); return live.count == 5 && live[1] > running[1] + 1200
}
capture(main, name: game.label + (cached ? " cached Play" : " first curated Play") + " — actual Metal guest image",
hover: main.staticTexts["VCC UI Tests"].firstMatch)
}
for (index, game) in games.enumerated() {
play(game, reviewExpected: index != 0, cached: false)
play(game, reviewExpected: true, cached: true)
}
}
func testSoftwareLibraryExclusiveSourceImportAndReview() throws {
// Relaunch only the isolated app with a fully intercepted authored title.
// No real game, personal project, production download or Play is used.
app.terminate()
app.launchArguments.append("--library-exclusive-fixture")
app.launch()
XCTAssertTrue(main.waitForExistence(timeout: 15))
XCTAssertTrue(main.buttons["execution"].waitForExistence(timeout: 10))
diskEditorWait("The isolated machine must be running before the Library check") { self.session().count == 5 && self.main.buttons["execution"].label == "Pause" }
let parent = FileManager.default.temporaryDirectory.appendingPathComponent("VCCExclusiveUI-" + UUID().uuidString)
try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: false)
defer { app.terminate(); try? FileManager.default.removeItem(at: parent) }
let destination = parent.appendingPathComponent("My Orbit Source")
let secondDestination = parent.appendingPathComponent("Another Orbit Source")
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
let title = library.buttons["library-title-vccplus.fixture-orbit"]
for category in ["Educational", "Games"] {
let categoryButton = library.buttons["library-type-" + category]
XCTAssertTrue(categoryButton.waitForExistence(timeout: 5)); categoryButton.click()
XCTAssertTrue(title.waitForExistence(timeout: 5), "One title must appear in both browse categories")
XCTAssertEqual(library.buttons.matching(identifier: "library-title-vccplus.fixture-orbit").count, 1)
}
title.click()
XCTAssertTrue(library.descendants(matching: .any)["library-exclusive"].firstMatch.waitForExistence(timeout: 5))
XCTAssertTrue(library.staticTexts["By Fixture Author"].exists)
XCTAssertFalse(library.links["View on Color Computer Archive"].exists)
XCTAssertTrue(library.buttons["library-read-manual"].exists)
library.textFields["library-search"].hover()
let shot = XCTAttachment(screenshot: library.screenshot())
shot.name = "Project-owned Library title — provenance and native manual"; shot.lifetime = .keepAlways; add(shot)
let install = library.buttons["library-install"]
let installDetail = library.scrollViews.containing(.button, identifier: "library-install").firstMatch
for _ in 0..<5 where !install.isHittable { installDetail.scroll(byDeltaX: 0, deltaY: -200) }
diskEditorWait("The owned ZIP must be eligible for Install Only") { install.exists && install.isEnabled && install.isHittable }
install.click()
XCTAssertTrue(library.buttons["library-reveal-install"].waitForExistence(timeout: 15),
"Install uses the verified ZIP delivery descriptor even though provenance points to a project webpage")
XCTAssertFalse(app.buttons["library-confirm-play"].exists)
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists, "Install Only keeps the current guest disk")
for _ in 0..<5 where !library.buttons["library-read-manual"].isHittable { library.scrollViews.containing(.button, identifier: "library-read-manual").firstMatch.scroll(byDeltaX: 0, deltaY: 200) }
library.buttons["library-read-manual"].click()
let reader = app.windows["Software Manual"]
XCTAssertTrue(reader.waitForExistence(timeout: 5))
XCTAssertTrue(reader.buttons["manual-fit"].waitForExistence(timeout: 10), "The exact authored PDF must open from the isolated cache offline")
reader.buttons[XCUIIdentifierCloseWindow].click()
let source = library.buttons["library-open-source"]
let detail = library.scrollViews.containing(.button, identifier: "library-open-source").firstMatch
for _ in 0..<8 where !source.isHittable { detail.scroll(byDeltaX: 0, deltaY: -300) }
XCTAssertTrue(source.isHittable)
XCTAssertTrue(library.descendants(matching: .any)["library-online-manual"].firstMatch.exists, "The online edition remains a distinct link")
func downloadSource(to location: URL) {
source.click()
let download = app.buttons["Download Source"].firstMatch
XCTAssertTrue(download.waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift])
let path = app.textFields["PathTextField"].firstMatch
XCTAssertTrue(path.waitForExistence(timeout: 5))
path.click(); app.typeKey("a", modifierFlags: .command); path.typeText(location.deletingLastPathComponent().path + "/")
app.typeKey(.return, modifierFlags: [])
let name = app.textFields["saveAsNameTextField"].firstMatch
diskEditorWait("The new source folder name must be editable") { name.exists && name.isHittable && name.isEnabled }
name.click(); app.typeKey("a", modifierFlags: .command); name.typeText(location.lastPathComponent)
download.click()
}
downloadSource(to: destination)
let workspace = app.windows["C Development"]
XCTAssertTrue(workspace.waitForExistence(timeout: 15))
let editor = workspace.textViews["cmoc.source"]
XCTAssertTrue(editor.waitForExistence(timeout: 5))
diskEditorWait("The known C entry source must open without a build") { (editor.value as? String ?? "").contains("fixture_orbit") }
XCTAssertEqual(workspace.popUpButtons["Configuration, Build configuration"].value as? String, "Release",
"A published source starter's declared configuration must take precedence over the workspace default")
let project = destination.appendingPathComponent("FixtureOrbit")
XCTAssertTrue(FileManager.default.fileExists(atPath: project.appendingPathComponent("vccplus-project.json").path))
XCTAssertFalse(FileManager.default.fileExists(atPath: project.appendingPathComponent("MAKE_WAS_RUN").path))
workspace.staticTexts["FixtureOrbit"].firstMatch.hover()
let imported = XCTAttachment(screenshot: workspace.screenshot())
imported.name = "Verified source copy opened without executing Make"; imported.lifetime = .keepAlways; add(imported)
editor.click(); app.typeKey("a", modifierFlags: .command); editor.typeText("int unsaved_local;\n")
let dirty = editor.value as? String
menu("Media", "Software Library…")
XCTAssertTrue(library.waitForExistence(timeout: 5))
for _ in 0..<8 where !source.isHittable { detail.scroll(byDeltaX: 0, deltaY: -300) }
downloadSource(to: secondDestination)
let cancelReview = app.buttons["Cancel"].firstMatch
XCTAssertTrue(app.staticTexts["Save changes to this project?"].firstMatch.waitForExistence(timeout: 15))
XCTAssertTrue(cancelReview.exists); cancelReview.click()
menu("Develop", "C Development…")
XCTAssertEqual(editor.value as? String, dirty, "Cancel keeps the existing unsaved project")
XCTAssertEqual(try String(contentsOf: project.appendingPathComponent("main.c"), encoding: .utf8).contains("fixture_orbit"), true,
"The dirty editor must not overwrite its saved project")
let secondProject = secondDestination.appendingPathComponent("FixtureOrbit")
XCTAssertTrue(FileManager.default.fileExists(atPath: secondProject.appendingPathComponent("main.c").path), "Canceling the workspace switch retains the downloaded personal folder")
XCTAssertFalse(FileManager.default.fileExists(atPath: secondProject.appendingPathComponent("MAKE_WAS_RUN").path))
let after = session()
XCTAssertEqual(after[0], before[0], "Source import must not reset the running CoCo")
XCTAssertEqual(after[2], before[2], "Source import must not restart audio")
XCTAssertEqual(after[3], before[3], "Source-project typing must not reach the guest")
XCTAssertGreaterThan(after[1], before[1])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
func testSoftwareLibraryInstallRetryCancelAndRemovePreserveSession() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
library.buttons["library-scope-all"].click()
let fixture = library.buttons["library-title-authored-library-title"]
XCTAssertTrue(fixture.waitForExistence(timeout: 10)); fixture.click()
let install = library.buttons["library-install"]
XCTAssertTrue(install.waitForExistence(timeout: 5)); install.click()
let retry = library.buttons["library-retry-install"]
XCTAssertTrue(retry.waitForExistence(timeout: 10), "The authored first request deliberately returns HTTP 503")
XCTAssertFalse(library.buttons["library-reveal-install"].exists, "Failed downloads must not create installations")
retry.click()
let cancel = library.buttons["library-cancel-install"]
XCTAssertTrue(cancel.waitForExistence(timeout: 5))
liveHold(cancel, seconds: 0.5)
cancel.click()
XCTAssertTrue(install.waitForExistence(timeout: 10), "Canceled partial downloads return to an explicit Install Only action")
XCTAssertFalse(library.buttons["library-reveal-install"].exists)
install.click()
let reveal = library.buttons["library-reveal-install"]
XCTAssertTrue(reveal.waitForExistence(timeout: 15), "The third request returns the complete authored cartridge")
library.buttons["library-scope-installed"].click()
XCTAssertTrue(fixture.waitForExistence(timeout: 5)); fixture.click()
XCTAssertTrue(reveal.exists)
XCTAssertTrue(library.buttons["library-play"].exists, "Install Only leaves starting the software as a separate action")
let shot = XCTAttachment(screenshot: library.screenshot())
shot.name = "Software Library — authored installed cartridge"; shot.lifetime = .keepAlways; add(shot)
library.buttons[XCUIIdentifierCloseWindow].click()
menu("Media", "Software Library…")
XCTAssertTrue(library.waitForExistence(timeout: 5))
library.buttons["library-scope-installed"].click()
XCTAssertTrue(fixture.waitForExistence(timeout: 5)); fixture.click()
let remove = library.buttons["library-remove-install"]
XCTAssertTrue(remove.waitForExistence(timeout: 5)); remove.click()
let cancelRemoval = app.buttons["Cancel"].firstMatch
XCTAssertTrue(cancelRemoval.waitForExistence(timeout: 5)); cancelRemoval.click()
XCTAssertTrue(reveal.exists, "Canceling removal must preserve the installation")
remove.click()
let confirmRemoval = app.buttons["Remove from Library"].firstMatch
XCTAssertTrue(confirmRemoval.waitForExistence(timeout: 5)); confirmRemoval.click()
let removed = NSPredicate { _, _ in !fixture.exists && !reveal.exists }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: removed, object: nil)], timeout: 5), .completed)
let after = session()
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertEqual(after[3], before[3])
XCTAssertGreaterThan(after[1], before[1])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
XCTAssertEqual(main.buttons["execution"].label, "Pause")
}
}
extension InteractionTests {
func testSoftwareLibraryPlayConfirmationAndReturn() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
library.buttons["library-scope-all"].click()
let cartridge = library.buttons["library-title-authored-library-cartridge"]
XCTAssertTrue(cartridge.waitForExistence(timeout: 10)); cartridge.click()
let play = library.buttons["library-play"]
XCTAssertTrue(play.waitForExistence(timeout: 5)); play.click()
let confirm = app.buttons["library-confirm-play"].firstMatch
XCTAssertTrue(confirm.waitForExistence(timeout: 15))
let canceled = session()
XCTAssertEqual(canceled[0], before[0]); XCTAssertEqual(canceled[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let preview = XCTAttachment(screenshot: library.screenshot())
preview.name = "Software Library — recommended setup preview"; preview.lifetime = .keepAlways; add(preview)
app.buttons["library-cancel-play"].firstMatch.click()
XCTAssertTrue(library.buttons["library-reveal-install"].waitForExistence(timeout: 5), "Canceling startup keeps the downloaded copy")
XCTAssertEqual(session()[0], before[0], "Canceling the preview must not restart the CoCo")
play.click(); XCTAssertTrue(confirm.waitForExistence(timeout: 10)); confirm.click()
let started = NSPredicate { _, _ in
let current = self.session()
return current.count == 5 && current[0] != before[0] && self.main.buttons["execution"].label == "Pause"
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: started, object: nil)], timeout: 15), .completed)
XCTAssertFalse(main.links["FD0 Authored FD0.dsk"].exists, "The cartridge setup replaces the old floppy layout")
let beforeKey = session()
app.typeText("z")
let deliveredKey = NSPredicate { _, _ in
let current = self.session()
return current.count == 5 && current[3] > beforeKey[3]
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: deliveredKey, object: nil)], timeout: 5), .completed, "Play must focus the live CoCo without another click")
let afterLaunch = session()
menu("Media", "Software Library…") // Play deliberately brought the CoCo forward.
let returnSetup = library.buttons["library-return-setup"]
XCTAssertTrue(returnSetup.waitForExistence(timeout: 5)); returnSetup.click()
let confirmReturn = app.buttons["library-confirm-return"].firstMatch
XCTAssertTrue(confirmReturn.waitForExistence(timeout: 5)); confirmReturn.click()
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].waitForExistence(timeout: 15))
let restored = NSPredicate { _, _ in
let current = self.session()
return current.count == 5 && current[0] != afterLaunch[0] && self.main.buttons["execution"].label == "Pause"
}
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: restored, object: nil)], timeout: 10), .completed)
}
func testSoftwareLibraryPlayManualAndMissingMember() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
library.buttons["library-scope-all"].click()
let missing = library.buttons["library-title-authored-library-missing-member"]
XCTAssertTrue(missing.waitForExistence(timeout: 10)); missing.click()
library.buttons["library-play"].click()
let failure = library.descendants(matching: .any)["library-launch-error"].firstMatch
XCTAssertTrue(failure.waitForExistence(timeout: 15), "A missing selected member must fail preflight")
XCTAssertEqual(session()[0], before[0])
XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let manual = library.buttons["library-title-authored-library-manual-disk"]
XCTAssertTrue(manual.waitForExistence(timeout: 5)); manual.click()
library.buttons["library-play"].click()
let confirm = app.buttons["library-confirm-play"].firstMatch
XCTAssertTrue(confirm.waitForExistence(timeout: 15))
XCTAssertEqual(confirm.label, "Set Up", "A recipe without a loading command must not promise automatic Play")
confirm.click()
XCTAssertTrue(main.links["FD0 Authored Manual Disk.dsk"].waitForExistence(timeout: 15))
let ready = NSPredicate { _, _ in self.main.buttons["execution"].label == "Pause" && self.session()[0] != before[0] }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 10), .completed)
XCTAssertEqual(session()[3], before[3], "Manual setup must not inject guessed loading commands")
menu("Media", "Software Library…")
let shot = XCTAttachment(screenshot: library.screenshot())
shot.name = "Software Library — manual loading guidance"; shot.lifetime = .keepAlways; add(shot)
}
}
extension InteractionTests {
func testSoftwareLibraryEmptySearchNavigationKeepsWindowAnchored() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
let search = library.descendants(matching: .any)["library-search"].firstMatch
let covers = library.buttons["library-scope-showcase"]
// This workflow exercises the cover collection; Getting Started is the
// intentional first-launch default and need not contain Predator.
covers.click()
let firstCover = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "library-title-")).firstMatch
XCTAssertTrue(firstCover.waitForExistence(timeout: 15))
let searchY = search.frame.minY - library.frame.minY
let coversY = covers.frame.minY - library.frame.minY
let result = library.descendants(matching: .any)["library-result-count"].firstMatch
func waitForCount(_ text: String) {
let predicate = NSPredicate { _, _ in (result.value as? String ?? result.label) == text }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: 8), .completed)
}
func anchored() {
XCTAssertEqual(search.frame.minY - library.frame.minY, searchY, accuracy: 2, "Empty results must not vertically center the whole Library")
XCTAssertEqual(covers.frame.minY - library.frame.minY, coversY, accuracy: 2)
for control in [search, covers, library.radioButtons["Shelf"], library.radioButtons["Table"]] {
XCTAssertTrue(control.isHittable)
XCTAssertTrue(library.frame.insetBy(dx: -1, dy: -1).contains(control.frame))
}
}
search.click(); app.typeText("Pred")
waitForCount("1 title"); anchored()
for _ in 0..<3 {
library.buttons["library-type-Educational"].click()
waitForCount("0 titles"); anchored()
XCTAssertTrue(library.staticTexts["No matching titles"].exists)
XCTAssertFalse(library.buttons["library-play"].exists, "No stale selected title should remain actionable")
covers.click(); waitForCount("1 title"); anchored()
XCTAssertEqual(search.value as? String, "Pred")
XCTAssertEqual(library.descendants(matching: .any)["library-heading"].firstMatch.value as? String, "Cover Collection")
}
library.buttons["library-type-Educational"].click(); waitForCount("0 titles")
let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Empty search remains anchored"; shot.lifetime = .keepAlways; add(shot)
let oldFrame = library.frame
let corner = library.coordinate(withNormalizedOffset: CGVector(dx: 1, dy: 1)).withOffset(CGVector(dx: -3, dy: -3))
corner.click(forDuration: 0.2, thenDragTo: corner.withOffset(CGVector(dx: oldFrame.width > 1050 ? -100 : 100, dy: oldFrame.height > 700 ? -80 : 80)))
XCTAssertNotEqual(library.frame.size, oldFrame.size)
anchored()
library.radioButtons["Table"].click(); anchored()
library.buttons["library-empty-clear-search"].click()
XCTAssertEqual(search.value as? String, "")
XCTAssertTrue(library.outlines["Software titles"].waitForExistence(timeout: 8))
XCTAssertEqual(library.descendants(matching: .any)["library-heading"].firstMatch.value as? String, "Education")
anchored()
library.radioButtons["Shelf"].click()
XCTAssertTrue(firstCover.waitForExistence(timeout: 8)); anchored()
let after = session()
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertEqual(after[3], before[3])
XCTAssertGreaterThan(after[1], before[1])
}
func testSoftwareLibraryDoubleDragonReadmeAndScreenshot() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
// Double Dragon belongs to the Archive catalog, outside Getting Started.
library.buttons["library-scope-all"].click()
let search = library.descendants(matching: .any)["library-search"].firstMatch
search.click(); app.typeText("Double Dragon")
let title = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'library-title-' AND label CONTAINS 'Double Dragon'")).firstMatch
XCTAssertTrue(title.waitForExistence(timeout: 10)); title.click()
let art = library.descendants(matching: .any).matching(NSPredicate(format: "label == 'Artwork: Double Dragon — Title Screen'")).firstMatch
XCTAssertTrue(art.exists)
let loaded = NSPredicate { _, _ in title.value as? String == "Loaded" }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: loaded, object: nil)], timeout: 45), .completed)
let controls = library.staticTexts["library-controls-keyboard"]
XCTAssertTrue(controls.exists)
XCTAssertTrue((controls.value as? String ?? controls.label).contains("Z: start/punch"))
let shot = XCTAttachment(screenshot: library.screenshot())
shot.name = "Double Dragon screenshot and instructions"; shot.lifetime = .keepAlways; add(shot)
let read = library.buttons["library-read-manual"]
XCTAssertEqual(read.label, "Read Instructions"); read.click()
let reader = app.windows["Software Manual"]
let text = reader.textViews["Readme and instructions"]
XCTAssertTrue(text.waitForExistence(timeout: 30))
XCTAssertTrue((text.value as? String ?? "").contains("start with Z."))
reader.buttons["manual-text-find"].click()
let capture = XCTAttachment(screenshot: reader.screenshot())
capture.name = "Double Dragon original text readme"; capture.lifetime = .keepAlways; add(capture)
reader.buttons[XCUIIdentifierCloseWindow].click(); read.click()
XCTAssertTrue(text.waitForExistence(timeout: 5))
let after = session()
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertEqual(after[3], before[3])
XCTAssertGreaterThan(after[1], before[1])
}
func testSoftwareLibraryHostedCoversAndManualReader() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
// Color File II is an Archive title, outside the Getting Started default.
library.buttons["library-scope-all"].click()
let search = library.descendants(matching: .any)["library-search"].firstMatch
search.click(); app.typeText("Color File II")
let title = library.buttons["library-title-fe6c3480e9010d9f11ac8faab3ea3c31"]
XCTAssertTrue(title.waitForExistence(timeout: 10)); title.click()
let read = library.buttons["library-read-manual"]
XCTAssertTrue(read.waitForExistence(timeout: 10)); read.click()
let reader = app.windows["Software Manual"]
XCTAssertTrue(reader.waitForExistence(timeout: 10))
XCTAssertTrue(reader.buttons["manual-fit"].waitForExistence(timeout: 60))
reader.buttons["Next page"].click()
let page = reader.textFields["Page number"]
XCTAssertEqual(page.value as? String, "2")
reader.buttons["Previous page"].click()
XCTAssertEqual(page.value as? String, "1")
reader.buttons["Zoom in"].click(); reader.buttons["manual-fit"].click()
reader.buttons["Show page thumbnails"].click()
let capture = XCTAttachment(screenshot: reader.screenshot())
capture.name = "Native manual reader — Color File II"; capture.lifetime = .keepAlways; add(capture)
reader.buttons["Next page"].click()
reader.buttons[XCUIIdentifierCloseWindow].click()
read.click()
XCTAssertTrue(reader.buttons["manual-fit"].waitForExistence(timeout: 10))
XCTAssertEqual(reader.textFields["Page number"].value as? String, "2")
let after = session()
XCTAssertEqual(after[0],before[0]); XCTAssertEqual(after[2],before[2]); XCTAssertEqual(after[3],before[3])
XCTAssertGreaterThan(after[1],before[1])
}
func testSoftwareLibraryAdvancedFiltersAndVideoBadge() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
library.buttons["library-scope-all"].click()
library.buttons["library-filters"].click()
let filterPopover = app.popovers.containing(.popUpButton, identifier: "library-filter-environment").firstMatch
XCTAssertTrue(filterPopover.waitForExistence(timeout: 5))
func pick(_ id: String, _ value: String) {
let picker = app.popUpButtons[id].firstMatch
XCTAssertTrue(picker.waitForExistence(timeout: 5)); picker.click()
app.menuItems[value].firstMatch.click()
}
pick("library-filter-environment", "Disk BASIC")
let advanced = app.disclosureTriangles["Advanced Filters"].firstMatch
expand(advanced)
let processor = app.popUpButtons["library-filter-processor"].firstMatch
liveHold(processor)
pick("library-filter-processor", "Requires Hitachi 6309")
pick("library-filter-hardware", "Joystick")
pick("library-filter-hardware-use", "Requirement unspecified")
pick("library-filter-display", "Semigraphics-12")
let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Advanced Library filters"; shot.lifetime = .keepAlways; add(shot)
app.typeKey(.escape, modifierFlags: [])
XCTAssertTrue(filterPopover.waitForNonExistence(timeout: 5), "Escape must dismiss the owned filters before clearing them")
let summary = library.descendants(matching: .any)["library-active-filters"].firstMatch
XCTAssertTrue((summary.value as? String ?? summary.label).contains("Requires Hitachi 6309"))
XCTAssertTrue((summary.value as? String ?? summary.label).contains("Semigraphics-12"))
library.buttons["Clear filters"].click()
XCTAssertFalse(summary.exists)
let search = library.descendants(matching: .any)["library-search"].firstMatch
search.click(); app.typeText("Color File II")
// Search also matches publisher/category/edition metadata; select the
// intended title, not whichever other matching title sorts first.
let colorFile = library.buttons["library-title-fe6c3480e9010d9f11ac8faab3ea3c31"]
XCTAssertTrue(colorFile.waitForExistence(timeout: 10)); colorFile.click()
XCTAssertTrue(library.staticTexts["library-video-badge-6847T1"].waitForExistence(timeout: 5))
let badgeShot = XCTAttachment(screenshot: library.screenshot())
badgeShot.name = "Color File II badge and validation"; badgeShot.lifetime = .keepAlways; add(badgeShot)
XCTAssertFalse(library.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", "6847T1 has not been verified")).firstMatch.exists)
let after = session()
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertEqual(after[3], before[3])
XCTAssertGreaterThan(after[1], before[1])
}
func testSoftwareLibraryFilterCombinationsAndEmptyCollectionsRecover() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 10))
library.buttons["library-scope-showcase"].click()
let firstCover = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "library-title-")).firstMatch
XCTAssertTrue(firstCover.waitForExistence(timeout: 15))
let search = library.descendants(matching: .any)["library-search"].firstMatch
let searchY = search.frame.minY - library.frame.minY
search.click(); app.typeText("Pred")
library.buttons["library-filters"].click()
func pick(_ id: String, _ value: String) {
let picker = app.popUpButtons[id].firstMatch
XCTAssertTrue(picker.waitForExistence(timeout: 5)); picker.click()
app.menuItems[value].firstMatch.click()
}
pick("library-filter-media", "Cartridge")
pick("library-filter-system", "CoCo 1/2")
pick("library-filter-sort", "Last Modified")
app.typeKey(.escape, modifierFlags: [])
XCTAssertTrue(library.staticTexts["No matching titles"].waitForExistence(timeout: 8))
XCTAssertEqual(search.frame.minY - library.frame.minY, searchY, accuracy: 2)
let summary = library.descendants(matching: .any)["library-active-filters"].firstMatch
XCTAssertTrue((summary.value as? String ?? summary.label).contains("Cartridge")); XCTAssertTrue((summary.value as? String ?? summary.label).contains("CoCo 1/2"))
library.buttons["Clear filters"].click()
XCTAssertEqual(search.value as? String, "Pred")
XCTAssertTrue(firstCover.waitForExistence(timeout: 8))
for scope in ["favorites", "installed"] {
library.buttons["library-scope-" + scope].click()
XCTAssertTrue(library.staticTexts["No matching titles"].waitForExistence(timeout: 8))
XCTAssertEqual(search.frame.minY - library.frame.minY, searchY, accuracy: 2)
library.buttons["library-empty-clear-search"].click()
XCTAssertTrue(library.staticTexts[scope == "favorites" ? "Keep your favorites close" : "Your software will live here"].waitForExistence(timeout: 8))
XCTAssertEqual(search.frame.minY - library.frame.minY, searchY, accuracy: 2)
search.click(); app.typeText("Pred")
}
let heading = library.descendants(matching: .any)["library-heading"].firstMatch
XCTAssertTrue((heading.value as? String ?? heading.label).contains("Search Results"),
"Typing in the header starts a global search even from an empty collection")
XCTAssertTrue(firstCover.waitForExistence(timeout: 8))
// A global search has results, so its earlier empty-state action is no
// longer a valid click target. Explicitly return to an empty collection
// before exercising that action and its query reset.
library.buttons["library-scope-installed"].click()
XCTAssertTrue(library.staticTexts["No matching titles"].waitForExistence(timeout: 8))
let browse = library.buttons["Browse All Titles"]
XCTAssertTrue(browse.waitForExistence(timeout: 8)); XCTAssertTrue(browse.isHittable)
browse.click()
XCTAssertEqual(search.value as? String, "")
XCTAssertTrue(firstCover.waitForExistence(timeout: 8))
library.buttons["library-category-Cartridges"].click()
search.click(); app.typeText("Pred")
XCTAssertTrue(firstCover.waitForExistence(timeout: 8))
firstCover.click()
XCTAssertTrue(library.buttons["library-play"].waitForExistence(timeout: 5))
let after = session()
XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertEqual(after[3], before[3])
}
}
extension InteractionTests {
func testCoCoCaptureHeaderScreenshotTimerAndMovie() async throws {
let before = session()
let root = try XCTUnwrap(captureFixtureFolder)
let documents = root.appendingPathComponent("Documents", isDirectory: true)
func files(_ dir: URL, _ ext: String) -> [URL] {
((try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []).filter { $0.pathExtension == ext && !$0.lastPathComponent.hasPrefix(".") }
}
func waitFor(_ predicate: @escaping () -> Bool, seconds: TimeInterval = 12) {
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in predicate() }, object: nil)], timeout: seconds), .completed)
}
let camera = main.buttons["capture-now"], record = main.buttons["capture-record"]
let options = main.menuButtons["capture-options"]
func choose(_ label: String) {
options.click()
let item = app.menuItems[label].firstMatch
XCTAssertTrue(item.waitForExistence(timeout: 3)); item.click()
}
XCTAssertTrue(camera.waitForExistence(timeout: 5)); XCTAssertTrue(record.exists)
camera.click(); waitFor { files(root,"png").count == 1 }
let png = try XCTUnwrap(files(root,"png").first)
let picture = try XCTUnwrap(NSImage(contentsOf: png))
XCTAssertLessThanOrEqual(picture.size.width, 640); XCTAssertLessThanOrEqual(picture.size.height, 480)
XCTAssertGreaterThan(picture.size.width, 200)
choose("10 Seconds")
let cancel = main.buttons["capture-countdown-cancel"]
XCTAssertFalse(cancel.exists, "Changing the timer must not start a capture")
XCTAssertEqual(files(root,"png").count, 1)
camera.click(); XCTAssertTrue(cancel.waitForExistence(timeout: 3)); cancel.click()
XCTAssertFalse(cancel.exists); XCTAssertEqual(files(root,"png").count, 1)
choose("5 Seconds")
XCTAssertFalse(cancel.exists, "Only the camera performs a capture")
camera.click(); XCTAssertTrue(cancel.waitForExistence(timeout: 3))
waitFor({ files(root,"png").count == 2 }, seconds: 10)
choose("None")
choose("Documents")
// The chooser changes the one shared destination only on confirmation.
choose("Other Location…")
let chooser = app.windows["Save Screenshots and Videos To"]
XCTAssertTrue(chooser.waitForExistence(timeout: 4))
chooser.buttons["Cancel"].click()
camera.click(); waitFor { files(documents,"png").count == 1 }
XCTAssertEqual(files(root,"png").count, 2)
choose("Include CoCo Audio in Video")
record.click()
waitFor { record.label == "Stop Recording" }
// Take another image while video is active. Its shutter is host-only.
camera.click(); waitFor { files(documents,"png").count == 2 }
choose("Include CoCo Audio in Video") // Changes the next recording only.
let deadline = Date().addingTimeInterval(1.2)
waitFor { Date() >= deadline }
record.click()
waitFor({ files(documents,"mp4").count == 1 }, seconds: 20)
let movie = try XCTUnwrap(files(documents,"mp4").first)
XCTAssertGreaterThan(try movie.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0, 1000)
let asset = AVURLAsset(url: movie)
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 peak: Float = 0, samples = 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) { peak = max(peak, abs(value)); samples += 1 }
}
}
XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(samples, 0)
XCTAssertLessThan(peak, 0.00001, "Local start/shutter cues must not leak into the silent video")
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertGreaterThan(session()[1], before[1])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
let shot = XCTAttachment(screenshot: main.screenshot()); shot.name = "Shared capture controls"; shot.lifetime = .keepAlways; add(shot)
}
}
extension InteractionTests {
func testArchiveLibraryAndManualsResumeAcrossProcessRelaunch() throws {
let fixture = try XCTUnwrap(continuityFixtureFolder)
let stateFile = fixture.appendingPathComponent("LibraryContinuity.json")
func state() -> [String: Any] {
guard let data = try? Data(contentsOf: stateFile),
let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [:] }
return object
}
func waitUntil(_ description: String, _ condition: @escaping () -> Bool) {
let predicate = NSPredicate { _, _ in condition() }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: 12), .completed, description)
}
func reading(_ key: String) -> [String: Any] { (state()["reading"] as? [String: [String: Any]])?[key] ?? [:] }
func bookmarks() -> [[String: Any]] { state()["bookmarks"] as? [[String: Any]] ?? [] }
func capture(_ window: XCUIElement, _ title: String) {
let image = XCTAttachment(screenshot: window.screenshot()); image.name = title; image.lifetime = .keepAlways; add(image)
}
func relaunch() {
app.activate()
app.typeKey("q", modifierFlags: .command)
waitUntil("The first isolated process must quit before launching its successor") { self.app.state == .notRunning }
app.launch()
XCTAssertTrue(main.waitForExistence(timeout: 15))
waitUntil("The successor process must finish its authored machine startup") {
self.main.buttons["execution"].label == "Pause" && self.main.links["FD0 Authored FD0.dsk"].exists
}
}
menu("Media", "Software Library…")
let software = app.windows["Software Library"]
XCTAssertTrue(software.buttons["library-scope-all"].waitForExistence(timeout: 10))
software.buttons["library-scope-all"].click()
let softwareSearch = software.descendants(matching: .any)["library-search"].firstMatch
softwareSearch.click(); app.typeText("Raaka-Tu")
let game = software.buttons["library-title-486dda54b9351ac926c382f70f328aa5"]
XCTAssertTrue(game.waitForExistence(timeout: 10)); game.click()
waitUntil("Software title and search must reach the continuity file") {
let browse = (state()["browse"] as? [String: [String: Any]])?["software-main"]
return browse?["selectedID"] as? String == "486dda54b9351ac926c382f70f328aa5"
}
menu("Help", "Archive Library…")
let archive = app.windows["Archive Library"]
let map = archive.descendants(matching: .any)["archive-browse-list"].firstMatch.staticTexts["King's Quest I Map (Sierra)"]
XCTAssertTrue(map.waitForExistence(timeout: 10)); map.click()
XCTAssertTrue(archive.images["archive-inline-image"].waitForExistence(timeout: 10))
archive.buttons["Zoom in"].click()
let mapID = "1ed75351da8136ed8c2eafb6c3b93d92af411bbdb8f616ced57282d155d1a5f5"
waitUntil("Archive image zoom must be checkpointed") { (reading("archive:" + mapID)["zoom"] as? Double ?? 0) > 1 }
let mapZoom = try XCTUnwrap(reading("archive:" + mapID)["zoom"] as? Double)
capture(archive, "Archive map before process relaunch")
menu("Help", "Manual Library…")
let manual = app.windows["Manual Library"]
func follow(_ title: String) {
let link = manual.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch
XCTAssertTrue(link.waitForExistence(timeout: 10), title); link.click()
}
let firstBook = "meet-your-color-computer", secondBook = "back-at-the-coco"
func readAndBookmark(_ book: String) {
let chapter = book + (book == firstBook ? "/meet-the-machine.html" : "/familiar-hardware.html")
waitUntil("The selected chapter must finish loading") {
reading("manual-last")["relativePath"] as? String == chapter && manual.buttons["manual.bookmark-location"].isEnabled
}
manual.webViews.firstMatch.scroll(byDeltaX: 0, deltaY: -600)
waitUntil("Scrolling must record a reading position") {
let position = reading("manual-book:" + book)
return (position["offset"] as? Double ?? 0) > 0.001 || position["anchor"] as? String != nil
}
let bookmark = manual.buttons["manual.bookmark-location"]
XCTAssertTrue(bookmark.isEnabled); bookmark.click()
waitUntil("A bookmark in each book must be saved") { bookmarks().contains { $0["bookID"] as? String == book } }
}
follow("Open the first book"); follow("Start reading"); readAndBookmark(firstBook)
manual.buttons["manual.home"].click()
follow("Open Back at the CoCo"); follow("Start reading"); readAndBookmark(secondBook)
let firstPosition = reading("manual-book:" + firstBook), secondPosition = reading("manual-book:" + secondBook)
let firstMark = try XCTUnwrap(bookmarks().first { $0["bookID"] as? String == firstBook }?["id"] as? String)
let secondMark = try XCTUnwrap(bookmarks().first { $0["bookID"] as? String == secondBook }?["id"] as? String)
XCTAssertEqual(bookmarks().count, 2)
capture(manual, "Second manual before process relaunch")
relaunch()
menu("Media", "Software Library…")
XCTAssertTrue(game.waitForExistence(timeout: 10))
XCTAssertEqual(softwareSearch.value as? String, "Raaka-Tu")
XCTAssertTrue(software.links["library-reference-02587e81cceaec9ac0c11fe9"].waitForExistence(timeout: 10), "The selected software detail must resume")
capture(software, "Software selection and search after process relaunch")
menu("Help", "Archive Library…")
XCTAssertTrue(archive.images["archive-inline-image"].waitForExistence(timeout: 10), "The selected browse image must resume")
XCTAssertTrue(archive.buttons["Fit Image"].isEnabled, "The image must retain its zoom")
XCTAssertEqual(reading("archive:" + mapID)["zoom"] as? Double, mapZoom)
let archiveSearch = archive.textFields["archive-search"]
archiveSearch.click(); app.typeText("MOTD strip buffer")
let result = archive.outlines["archive-results-list"].descendants(matching: .outlineRow).containing(.staticText, identifier: "PDF page 12").firstMatch
XCTAssertTrue(result.waitForExistence(timeout: 10)); result.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).click()
let pdfPage = archive.textFields["PDF page number"]
waitUntil("The selected search result must show its cited page") { pdfPage.value as? String == "12" }
capture(archive, "Archive search before second process relaunch")
menu("Help", "Manual Library…")
waitUntil("The last active manual must resume") { reading("manual-last")["documentID"] as? String == secondBook && manual.buttons["manual.bookmark-location"].isEnabled }
XCTAssertEqual(reading("manual-last")["relativePath"] as? String, secondPosition["relativePath"] as? String)
XCTAssertEqual(reading("manual-last")["anchor"] as? String, secondPosition["anchor"] as? String)
manual.buttons["manual.bookmarks"].click()
manual.radioButtons["All Books"].click()
let firstEntry = manual.buttons["manual.bookmark-open-" + firstMark]
let secondEntry = manual.buttons["manual.bookmark-open-" + secondMark]
XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertTrue(secondEntry.exists)
capture(manual, "Two-book bookmarks after process relaunch")
// This journey verifies native scope actions and persistence. Focused
// keyboard/VoiceOver operation is qualified separately; clicking a Mac
// radio button alone does not establish keyboard focus for arrow keys.
manual.radioButtons["This Book"].click()
waitUntil("This Book must show only the active book's bookmark") { !firstEntry.exists && secondEntry.exists }
manual.radioButtons["All Books"].click()
waitUntil("All Books must show both saved bookmarks") { firstEntry.exists && secondEntry.exists }
firstEntry.click()
waitUntil("Explicit bookmark navigation must win over second-book resume") { reading("manual-last")["documentID"] as? String == firstBook }
XCTAssertEqual(reading("manual-last")["anchor"] as? String, firstPosition["anchor"] as? String)
manual.buttons["manual.bookmarks"].click()
manual.radioButtons["This Book"].click()
XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertFalse(secondEntry.exists)
firstEntry.click()
relaunch()
menu("Help", "Archive Library…")
XCTAssertEqual(archiveSearch.value as? String, "MOTD strip buffer")
waitUntil("The selected PDF search page must survive the second process relaunch") { pdfPage.value as? String == "12" }
capture(archive, "Archive search and cited page after process relaunch")
menu("Help", "Manual Library…")
waitUntil("The explicit first-book visit must become the new automatic resume") { reading("manual-last")["documentID"] as? String == firstBook && manual.buttons["manual.bookmark-location"].isEnabled }
manual.buttons["manual.bookmarks"].click()
XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertFalse(secondEntry.exists)
manual.radioButtons["All Books"].click(); XCTAssertTrue(secondEntry.exists)
XCTAssertEqual(bookmarks().count, 2)
capture(manual, "First manual and saved bookmark filter after second relaunch")
}
func testManualLibraryBookmarksAndWindowResume() throws {
try requireFullManualEdition()
menu("Help", "Manual Library…")
let reader = app.windows["Manual Library"]
XCTAssertTrue(reader.waitForExistence(timeout: 8))
for title in ["Open the first book", "Start reading"] {
let link = reader.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch
XCTAssertTrue(link.waitForExistence(timeout: 8)); link.click()
}
let bookmark = reader.buttons["manual.bookmark-location"]
let ready = NSPredicate { _, _ in bookmark.exists && bookmark.isEnabled }
XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 8), .completed)
bookmark.click(); reader.buttons["manual.bookmarks"].click()
let entry = reader.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "manual.bookmark-open-")).firstMatch
XCTAssertTrue(entry.waitForExistence(timeout: 5))
reader.radioButtons["All Books"].click(); XCTAssertTrue(entry.exists)
reader.radioButtons["This Book"].click(); XCTAssertTrue(entry.exists)
let shot = XCTAttachment(screenshot: reader.screenshot()); shot.name = "Manual bookmarks — one list with filters"; shot.lifetime = .keepAlways; add(shot)
entry.click()
reader.buttons["manual.bookmark-location"].click() // recognizes the existing entry
XCTAssertTrue(entry.waitForExistence(timeout: 5))
XCTAssertEqual(reader.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "manual.bookmark-open-")).count, 1)
entry.click()
reader.buttons[XCUIIdentifierCloseWindow].firstMatch.click()
menu("Help", "Manual Library…")
XCTAssertTrue(reader.buttons["manual.bookmark-location"].waitForExistence(timeout: 5))
reader.buttons["manual.bookmarks"].click(); XCTAssertTrue(entry.waitForExistence(timeout: 5))
}
func testSoftwareLibraryPersonalImportPreservesGuest() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 8))
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let source = mac.appendingPathComponent("Tests/Fixtures/DiskEditor/DECB.dsk")
let original = try Data(contentsOf: source)
library.buttons["library-scope-personal"].click()
let addButton = library.buttons["library-personal-add"]
let addFirst = library.buttons["library-personal-add-first"]
XCTAssertTrue(addButton.waitForExistence(timeout: 5))
XCTAssertTrue(addFirst.waitForExistence(timeout: 5))
addFirst.click()
XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5))
app.buttons["Cancel"].click()
XCTAssertTrue(addButton.waitForExistence(timeout: 5))
addButton.click()
XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(source.path); app.typeKey(.return, modifierFlags: [])
app.buttons["Review Files"].click()
let field = library.textFields["personal-title"]
XCTAssertTrue(field.waitForExistence(timeout: 8)); field.click(); app.typeKey("a", modifierFlags: .command); app.typeText("Private Library UI Example")
let category = library.popUpButtons["personal-category"]
XCTAssertTrue(category.exists); XCTAssertEqual(category.value as? String, "Other")
category.click(); app.menuItems["Games"].click()
let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Add Personal Software — review before import"; shot.lifetime = .keepAlways; add(shot)
library.buttons["personal-save"].click()
let title = library.staticTexts["Private Library UI Example"].firstMatch
XCTAssertTrue(title.waitForExistence(timeout: 10))
XCTAssertTrue(library.buttons["library-scope-personal"].exists)
XCTAssertTrue(addButton.exists, "Add Software stays available after the first import")
XCTAssertFalse(addFirst.exists, "A populated library must not show the first-item invitation")
let search = library.descendants(matching: .any)["library-search"].firstMatch
search.click(); app.typeText("No such personal title 370")
let clear = library.buttons["library-empty-clear-search"]
XCTAssertTrue(clear.waitForExistence(timeout: 5))
XCTAssertFalse(addButton.exists, "The header search opens global results, outside the private-only browse scope")
XCTAssertFalse(addFirst.exists, "A filtered library is not an empty personal collection")
clear.click()
library.buttons["library-scope-getting-started"].click()
search.click(); app.typeText("Private Library UI Example")
let personalCard = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "library-title-personal:")).firstMatch
XCTAssertTrue(personalCard.waitForExistence(timeout: 5), "Global search must find a private game from Getting Started")
XCTAssertTrue(personalCard.label.contains("Personal"))
library.buttons["Clear search"].click()
library.buttons["library-type-Games"].click()
XCTAssertTrue(personalCard.waitForExistence(timeout: 5), "The standard Games category includes the private game")
let grouped = XCTAttachment(screenshot: library.screenshot()); grouped.name = "Unified Games — Personal Library before Catalog"; grouped.lifetime = .keepAlways; add(grouped)
library.radioButtons["Table"].click()
let table = library.outlines["Software titles"]
XCTAssertTrue(table.waitForExistence(timeout: 5))
table.scroll(byDeltaX: 0, deltaY: 1200)
let tableShot = XCTAttachment(screenshot: library.screenshot()); tableShot.name = "Unified Games — Table Personal badge"; tableShot.lifetime = .keepAlways; add(tableShot)
let firstRow = table.outlineRows.element(boundBy: 0)
let badge = firstRow.descendants(matching: .any)["library-personal-badge"].firstMatch
XCTAssertTrue(badge.waitForExistence(timeout: 5), "The first table row visibly identifies the personal entry")
XCTAssertFalse(addButton.exists, "Other categories keep personal import in Library Actions")
XCTAssertEqual(try Data(contentsOf: source), original)
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
func testPersonalLibraryCoverChooserCancelDropAndRemovePreserveGuest() throws {
try personalCoverJourney(includeDrop: true)
}
func testPersonalLibraryCoverChooserCancelAndRemovePreserveGuest() throws {
try personalCoverJourney(includeDrop: false)
}
private func personalCoverJourney(includeDrop: Bool) throws {
let manualDrag = includeDrop && ProcessInfo.processInfo.environment["VCC_UI_MANUAL_COVER_DRAG"] == "1"
var manualFinderWindow: XCUIElement?
defer {
if let window = manualFinderWindow, window.exists,
window.buttons[XCUIIdentifierCloseWindow].firstMatch.exists {
window.buttons[XCUIIdentifierCloseWindow].firstMatch.click()
}
}
let before = session()
let folder = try XCTUnwrap(coverFixtureFolder)
defer { try? FileManager.default.removeItem(at: folder) }
func image(_ color: NSColor, name: String) throws -> URL {
let bitmap = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 320, pixelsHigh: 200,
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0))
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap)
color.setFill(); NSBezierPath(rect: NSRect(x: 0, y: 0, width: 320, height: 200)).fill()
NSGraphicsContext.restoreGraphicsState()
let url = folder.appendingPathComponent(name)
try XCTUnwrap(bitmap.representation(using: .png, properties: [:])).write(to: url)
return url
}
let red = try image(.red, name: "Red Cover.png"), blue = try image(.blue, name: "Blue Cover.png")
let redBytes = try Data(contentsOf: red), blueBytes = try Data(contentsOf: blue)
let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let disk = mac.appendingPathComponent("Tests/Fixtures/DiskEditor/DECB.dsk"), diskBytes = try Data(contentsOf: disk)
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 8)); library.buttons["library-scope-personal"].click()
library.buttons["library-personal-add"].click()
XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(disk.path); app.typeKey(.return, modifierFlags: [])
app.buttons["Review Files"].click()
XCTAssertTrue(library.buttons["personal-save"].waitForExistence(timeout: 8)); library.buttons["personal-save"].click()
let cover = library.descendants(matching: .any)["library-personal-cover"].firstMatch
XCTAssertTrue(cover.waitForExistence(timeout: 8))
func choose(_ url: URL, prompt: String) {
XCTAssertTrue(app.buttons[prompt].waitForExistence(timeout: 5))
app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(url.path); app.typeKey(.return, modifierFlags: [])
app.buttons[prompt].click()
}
func matches(_ element: XCUIElement, red: Bool) -> Bool {
guard element.exists, let pixels = NSBitmapImageRep(data: element.screenshot().pngRepresentation),
let color = pixels.colorAt(x: pixels.pixelsWide / 2, y: pixels.pixelsHigh / 2)?.usingColorSpace(.deviceRGB) else { return false }
// Native display captures carry the monitor's color transform;
// verify the authored dominant channel rather than raw PNG bytes.
return red ? color.redComponent > 0.7 && color.redComponent - max(color.greenComponent, color.blueComponent) > 0.4
: color.blueComponent > 0.7 && color.blueComponent - max(color.greenComponent, color.redComponent) > 0.4
}
func waitForColor(_ element: XCUIElement, red: Bool, timeout: TimeInterval = 15) {
let expectation = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in matches(element, red: red) }, object: nil)
let result = XCTWaiter.wait(for: [expectation], timeout: timeout)
if result != .completed {
let screenshot = element.screenshot()
let attachment = XCTAttachment(screenshot: screenshot); attachment.name = "Cover pixel assertion"; attachment.lifetime = .keepAlways; add(attachment)
if let pixels = NSBitmapImageRep(data: screenshot.pngRepresentation) {
print("Cover screenshot \(pixels.pixelsWide)x\(pixels.pixelsHigh), center \(String(describing: pixels.colorAt(x: pixels.pixelsWide / 2, y: pixels.pixelsHigh / 2))), frame \(element.frame)")
}
}
XCTAssertEqual(result, .completed)
}
library.menuButtons["library-personal-cover-menu"].click(); app.menuItems["Choose Cover Image…"].click()
choose(red, prompt: "Use Image"); waitForColor(cover, red: true)
library.buttons["Edit Details…"].click()
let chooseDraft = library.buttons["personal-cover-choose"]
XCTAssertTrue(chooseDraft.waitForExistence(timeout: 5))
let preview = library.descendants(matching: .any)["personal-cover-preview"].firstMatch
let form = library.sheets.firstMatch.scrollViews.firstMatch
for _ in 0..<6 where !form.frame.insetBy(dx: 8, dy: 8).contains(preview.frame) {
form.scroll(byDeltaX: 0, deltaY: -180)
}
XCTAssertTrue(form.frame.insetBy(dx: 8, dy: 8).contains(preview.frame), "Inspect the complete preview inside the form viewport")
chooseDraft.click(); choose(blue, prompt: "Choose Image")
waitForColor(preview, red: false)
let editorShot = XCTAttachment(screenshot: library.screenshot()); editorShot.name = "Personal cover — draft image preview"; editorShot.lifetime = .keepAlways; add(editorShot)
library.sheets.firstMatch.buttons["Cancel"].click(); waitForColor(cover, red: true)
if includeDrop {
app.activate()
// The authored native source starts an actual NSDraggingSession with
// a file URL. It never calls the destination handler or changes model
// state; the normal decoder/store/render path must produce blue pixels.
let source = library.descendants(matching: .any)["personal-cover-drag-source"].firstMatch
XCTAssertTrue(source.waitForExistence(timeout: 5))
let pasteboardGeneration = NSPasteboard(name: .drag).changeCount
if manualDrag {
let finder = XCUIApplication(bundleIdentifier: "com.apple.finder")
finder.activate(); finder.typeKey("n", modifierFlags: .command)
finder.typeKey("g", modifierFlags: [.command, .shift]); finder.typeText(folder.path); finder.typeKey(.return, modifierFlags: [])
let window = finder.windows[folder.lastPathComponent]
XCTAssertTrue(window.waitForExistence(timeout: 8))
manualFinderWindow = window
print("VCC_COVER_MANUAL_DRAG_READY: Drag Blue Cover.png from Finder onto the red cover in Software Library")
fflush(stdout)
let delivered = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in
let log = (try? String(contentsOf: folder.appendingPathComponent("drag-trace.txt"))) ?? ""
return log.contains("perform file-count=1") && matches(cover, red: false)
}, object: nil)
XCTAssertEqual(XCTWaiter.wait(for: [delivered], timeout: 600), .completed)
} else {
source.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).press(forDuration: 0.25,
thenDragTo: cover.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)), withVelocity: .slow, thenHoldForDuration: 1)
}
XCTAssertGreaterThan(NSPasteboard(name: .drag).changeCount, pasteboardGeneration)
XCTAssertTrue(NSPasteboard(name: .drag).types?.contains(.fileURL) == true)
let trace = (try? String(contentsOf: folder.appendingPathComponent("drag-trace.txt"))) ?? "No native drag events"
print("Native cover drag: " + trace)
XCTAssertTrue(trace.contains("perform file-count=1"))
if !manualDrag { app.activate(); waitForColor(cover, red: false) }
let shot = XCTAttachment(screenshot: cover.screenshot()); shot.name = "Personal cover — native file drop replacement"; shot.lifetime = .keepAlways; add(shot)
}
if let window = manualFinderWindow, window.exists,
window.buttons[XCUIIdentifierCloseWindow].firstMatch.exists {
window.buttons[XCUIIdentifierCloseWindow].firstMatch.click()
manualFinderWindow = nil
app.activate()
}
library.menuButtons["library-personal-cover-menu"].click(); app.menuItems["Remove Cover"].click()
let removed = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in cover.label.hasSuffix(" category cover") }, object: nil)
XCTAssertEqual(XCTWaiter.wait(for: [removed], timeout: 10), .completed)
XCTAssertFalse(matches(cover, red: true)); XCTAssertFalse(matches(cover, red: false))
XCTAssertEqual(try Data(contentsOf: red), redBytes); XCTAssertEqual(try Data(contentsOf: blue), blueBytes)
XCTAssertEqual(try Data(contentsOf: disk), diskBytes)
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
func testArchiveLibraryRelatedReferenceFromSoftware() throws {
let before = session()
menu("Media", "Software Library…")
let library = app.windows["Software Library"]
XCTAssertTrue(library.waitForExistence(timeout: 8)); library.buttons["library-scope-all"].click()
let search = library.descendants(matching: .any)["library-search"].firstMatch
search.click(); app.typeText("Raaka-Tu")
let game = library.buttons["library-title-486dda54b9351ac926c382f70f328aa5"]
XCTAssertTrue(game.waitForExistence(timeout: 8)); game.click()
let referenceID = "library-reference-02587e81cceaec9ac0c11fe9"
let link = library.links[referenceID]
XCTAssertTrue(link.waitForExistence(timeout: 8))
let detail = library.scrollViews.containing(.link, identifier: referenceID).firstMatch
func guideVisible() -> Bool {
// macOS can report clipped content beneath the fixed footer as
// hittable. Require the complete link inside its actual viewport.
let frame = link.frame
return !frame.isEmpty && link.isHittable && detail.frame.insetBy(dx: 10, dy: 18).contains(frame)
}
for _ in 0..<8 where !guideVisible() { detail.scroll(byDeltaX: 0, deltaY: -250) }
XCTAssertTrue(guideVisible(), "Scroll the entire guide action clear of the fixed footer before opening it")
let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Software Library — Raaka-Tu Guides & References"; shot.lifetime = .keepAlways; add(shot)
link.click()
let archive = app.windows["Archive Library"]
let text = archive.textViews["archive-inline-text"]
XCTAssertTrue(text.waitForExistence(timeout: 10)); XCTAssertGreaterThan((text.value as? String ?? "").count, 100)
XCTAssertEqual(text.label, "Raaka-Tu Walkthrough (Tandy)", "The loaded reader must identify the exact linked document")
let readerShot = XCTAttachment(screenshot: archive.screenshot()); readerShot.name = "Archive Library — linked Raaka-Tu walkthrough"; readerShot.lifetime = .keepAlways; add(readerShot)
XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2])
XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists)
}
}