204 lines
14 KiB
Swift
204 lines
14 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import XCTest
|
|
import AppKit
|
|
|
|
@MainActor
|
|
final class MCPDebuggerInspectionTests: XCTestCase {
|
|
private let resources = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
|
|
.deletingLastPathComponent().appendingPathComponent("LocalResources")
|
|
|
|
private func command(_ operation: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot {
|
|
await withCheckedContinuation { c in operation { c.resume(returning: $0) } }
|
|
}
|
|
|
|
func testMemoryIsFrozenScopedBoundedAndCPUSpecific() async throws {
|
|
for enhanced in [false, true] {
|
|
let controller = VCCMachineController()
|
|
_ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) }
|
|
_ = await command { controller.loadDiagnostic(use6309: enhanced, completion: $0) }
|
|
_ = await command { controller.debuggerWriteMemory(address: 0x4000, data: Data([0xa5, 0x5a]), completion: $0) }
|
|
let capture: VCCDebuggerSnapshot = await withCheckedContinuation { c in
|
|
controller.debuggerSnapshot(address: 0, followPC: true, memoryAddress: 0x4000) { c.resume(returning: $0) }
|
|
}
|
|
let snapshot = try MCPDebuggerInspection(runID: "run", capture: capture, scope: [:], sourceStop: nil,
|
|
watches: [], watchStatus: "unavailable", ranges: [0x4000..<0x4002, 0xff00..<0xff01])
|
|
let regs = try XCTUnwrap(snapshot.fields["registers"] as? [String: Int])
|
|
XCTAssertEqual(regs["pc"], Int(capture.machine.programCounter))
|
|
XCTAssertEqual(regs["e"] != nil, enhanced)
|
|
func read(_ address: Any, _ count: Any, run: String = "run", id: String? = nil) throws -> [Int]? {
|
|
try snapshot.reply(tool: "read_debug_memory", arguments: ["address": address, "count": count,
|
|
"run_id": run, "snapshot_id": id ?? snapshot.id])["bytes"] as? [Int]
|
|
}
|
|
_ = await command { controller.debuggerWriteMemory(address: 0x4000, data: Data([0x55]), completion: $0) }
|
|
XCTAssertEqual(try read(0x4000, 2), [0xa5, 0x5a])
|
|
for address in [0, 0x3fff, 0x4001, 0xfeff, 0xff00, 0xffff] { XCTAssertThrowsError(try read(address, 2)) }
|
|
for count: Any in [0, -1, 257, true, 1.5] { XCTAssertThrowsError(try read(0x4000, count)) }
|
|
XCTAssertThrowsError(try read(0x4000, 1, run: "other"))
|
|
XCTAssertThrowsError(try read(0x4000, 1, id: "other"))
|
|
XCTAssertThrowsError(try snapshot.reply(tool: "get_debug_snapshot", arguments: ["run_id": "run", "expression": "PEEK(0)"]))
|
|
_ = await command(controller.shutdown)
|
|
}
|
|
}
|
|
|
|
#if DEBUG
|
|
private func machine(at directory: URL, enhanced: Bool) async throws -> MachineModel {
|
|
_ = NSApplication.shared
|
|
let roms = resources.appendingPathComponent("ROMs")
|
|
try XCTSkipUnless(["coco3.rom", "disk11.rom"].allSatisfy { FileManager.default.fileExists(atPath: roms.appendingPathComponent($0).path) },
|
|
"Requires the licensed local BASIC ROMs.")
|
|
let suite = "MCPDebugTests-" + UUID().uuidString
|
|
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
|
addTeardownBlock { UserDefaults.standard.removePersistentDomain(forName: suite) }
|
|
let machine = MachineModel(diskStore: .init(url: directory.appendingPathComponent("disks.json")), displayDefaults: defaults,
|
|
inputStore: .init(url: directory.appendingPathComponent("input.json")))
|
|
let end = ContinuousClock.now.advanced(by: .seconds(5))
|
|
while machine.busy && ContinuousClock.now < end { try await Task.sleep(for: .milliseconds(20)) }
|
|
try await MCPBASICRun.bootFixture(machine, romDirectory: roms, use6309: enhanced)
|
|
return machine
|
|
}
|
|
|
|
private func directory() throws -> URL {
|
|
let root = FileManager.default.temporaryDirectory.appendingPathComponent("MCPDebugger-" + UUID().uuidString)
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
addTeardownBlock { try? FileManager.default.removeItem(at: root) }
|
|
return root
|
|
}
|
|
|
|
func testBASICSourceStopWatchMemoryAndEditedDocumentRejection() async throws {
|
|
let root = try directory()
|
|
let machine = try await machine(at: root, enhanced: false)
|
|
defer { machine.shutdown() }
|
|
let model = BASICDevelopmentModel(machine: machine, directory: root, initialSource: "10 A=7\n20 PRINT A\n30 END")
|
|
model.toggleBreakpoint(20)
|
|
model.watchEntry = "A"; model.addWatch()
|
|
let host = MCPBASICRun()
|
|
await host.start(model: model, bothChoices: false, isCurrent: { true })
|
|
let id = try XCTUnwrap(host.runID, host.status)
|
|
var result: [String: Any] = [:]
|
|
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
|
repeat {
|
|
result = await host.handle(tool: "get_debug_snapshot", arguments: ["run_id": id], model: model)
|
|
if result["result"] != nil { break }
|
|
try await Task.sleep(for: .milliseconds(25))
|
|
} while ContinuousClock.now < deadline
|
|
let snapshot = try XCTUnwrap(result["result"] as? [String: Any], String(describing: result))
|
|
XCTAssertEqual((snapshot["source_stop"] as? [String: Int])?["line"], 20)
|
|
let watches = try XCTUnwrap(snapshot["watches"] as? [[String: String]])
|
|
XCTAssertEqual(watches.first?["value"], "7")
|
|
let ranges = try XCTUnwrap(snapshot["memory_ranges"] as? [[String: Int]])
|
|
let args: [String: Any] = ["run_id": id, "snapshot_id": try XCTUnwrap(snapshot["snapshot_id"] as? String),
|
|
"address": try XCTUnwrap(ranges.first?["address"]), "count": 4]
|
|
let read = await host.handle(tool: "read_debug_memory", arguments: args, model: model)
|
|
XCTAssertEqual(((read["result"] as? [String: Any])?["bytes"] as? [Int])?.suffix(2), [0, 10])
|
|
model.source = "10 END"
|
|
let stale = await host.handle(tool: "read_debug_memory", arguments: args, model: model)
|
|
XCTAssertNotNil(stale["error"])
|
|
}
|
|
|
|
func testOrdinaryCMOCStopsAtMainWithCompiledWatchAndNoDisk() async throws {
|
|
let root = try directory(), toolchain = resources.appendingPathComponent("ToolchainBundle")
|
|
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path),
|
|
"Requires the local staged toolchain.")
|
|
let machine = try await machine(at: root, enhanced: true)
|
|
defer { machine.shutdown() }
|
|
let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds"),
|
|
recoveryRoot: root.appendingPathComponent("Recovery"))
|
|
let project = try CMOCProject.create(at: root.appendingPathComponent("C"))
|
|
let file = "#include <cmoc.h>\nunsigned int total = 37;\nint main(void)\n{\n total += 5;\n printf(\"RESULT %u\\n\", total);\n return 0;\n}\n"
|
|
let artifact = try await model.service.build(project: project, overlays: ["main.c": file], action: .build, configuration: "Debug")
|
|
var saved: MCPDebuggerInspection?
|
|
let receipt = try await MCPCMOCGuest.runOrdinary(model: model, build: artifact, play: true, isCurrent: { true }) { capture, info, point in
|
|
saved = try MCPCMOCGuest.inspection(runID: "native", revision: 2, projectID: "project", build: artifact, capture: capture,
|
|
info: info, point: point, watches: ["total", "*((int*) 0xff00)"], sharedPaths: ["main.c"])
|
|
}
|
|
let snapshot = try XCTUnwrap(saved)
|
|
XCTAssertEqual(snapshot.fields["processor"] as? String, "HD6309")
|
|
XCTAssertEqual(receipt["artifact_id"] as? String, artifact.id.uuidString)
|
|
XCTAssertEqual((snapshot.fields["source_stop"] as? [String: Any])?["path"] as? String, "main.c")
|
|
let watches = try XCTUnwrap(snapshot.fields["watches"] as? [[String: String]])
|
|
XCTAssertEqual(watches.first?["value"], "37")
|
|
XCTAssertNotNil(watches.last?["unavailable"])
|
|
XCTAssertFalse(snapshot.machine.disks.contains { $0.mounted })
|
|
XCTAssertEqual(receipt["status"] as? String, "continued_from_main")
|
|
let deadline = ContinuousClock.now.advanced(by: .seconds(6))
|
|
var end = await machine.mcpMachineSnapshot()
|
|
while !end.assistantCompiledReturned && ContinuousClock.now < deadline {
|
|
try await Task.sleep(for: .milliseconds(30))
|
|
end = await machine.mcpMachineSnapshot()
|
|
}
|
|
XCTAssertTrue(end.assistantCompiledReturned)
|
|
XCTAssertTrue(MCPDebuggerInspection.sameProgram(end, snapshot.machine))
|
|
let io = MCPCompiledRunIO(machine: machine, runID: "native", expected: snapshot.machine, assembly: false)
|
|
let text = try await io.finalScreenText()
|
|
XCTAssertTrue(text?.contains("RESULT 42") == true, text ?? "Missing final screen")
|
|
do {
|
|
_ = try await io.reply("send_keys", arguments: ["run_id": "native", "request_id": "late", "keys": "1"])
|
|
XCTFail("A key after program return must not reach the BASIC prompt.")
|
|
} catch { XCTAssertEqual(error.localizedDescription, "run_finished") }
|
|
let inspected = try await MCPCMOCGuest.runOrdinary(model: model, build: artifact, isCurrent: { true }) { _, _, _ in }
|
|
let paused = await machine.mcpMachineSnapshot()
|
|
XCTAssertEqual(inspected["status"] as? String, "paused")
|
|
XCTAssertEqual(paused.state, .paused)
|
|
XCTAssertNotEqual(paused.debuggerProgramRevision, snapshot.machine.debuggerProgramRevision)
|
|
}
|
|
func testHelloDiskKeepsCapturedInspectionAfterContinueAndEject() async throws {
|
|
let root = try directory(), toolchain = resources.appendingPathComponent("ToolchainBundle")
|
|
try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: toolchain.appendingPathComponent("bin/cmoc").path),
|
|
"Requires the local staged toolchain.")
|
|
let machine = try await machine(at: root, enhanced: false)
|
|
defer { machine.shutdown() }
|
|
let model = CMOCDevelopmentModel(machine: machine, toolchain: toolchain, buildRoot: root.appendingPathComponent("Builds"),
|
|
recoveryRoot: root.appendingPathComponent("Recovery"))
|
|
let template = resources.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
|
.appendingPathComponent("examples/cmoc/HelloDisk")
|
|
let project = try CMOCProject.createHelloDisk(at: root.appendingPathComponent("Disk"), templateDirectory: template)
|
|
let artifact = try await model.service.build(project: project, overlays: [:], action: .disk, configuration: "Debug")
|
|
var saved: MCPDebuggerInspection?
|
|
let receipt = try await MCPCMOCGuest.run(model: model, build: artifact, isCurrent: { true }) { capture, info, point in
|
|
saved = try MCPCMOCGuest.inspection(runID: "disk", revision: 1, projectID: "shared", build: artifact, capture: capture,
|
|
info: info, point: point, watches: [], sharedPaths: Set(MCPCMOCProject.diskPaths))
|
|
}
|
|
let snapshot = try XCTUnwrap(saved), now = await machine.mcpMachineSnapshot()
|
|
XCTAssertTrue((receipt["screen"] as? String)?.contains("DISK RESULT: 0") == true)
|
|
XCTAssertFalse(now.disks.contains { $0.mounted })
|
|
XCTAssertTrue(MCPDebuggerInspection.sameProgram(now, snapshot.machine))
|
|
XCTAssertEqual((snapshot.fields["source_stop"] as? [String: Any])?["address"] as? Int,
|
|
(receipt["source_stop"] as? [String: Any])?["address"] as? Int)
|
|
}
|
|
#endif
|
|
}
|
|
|
|
|
|
extension MCPDebuggerInspectionTests {
|
|
func testOwnedCallContextIdentityRejectsSameClockGuestChanges() throws {
|
|
let base: [String: Any] = ["boot": 1, "field_clock": 2, "machine_frame": 3, "cycles": 4, "generation": 5,
|
|
"pc": 0x3100, "registers": ["PC": 0x3100, "S": 0x7000, "U": 0x7100],
|
|
"processor": "MC6809", "execution_mode": "not_applicable", "md_register": NSNull(),
|
|
"mapping_fingerprint": "mapping-1", "program_revision": 1, "physical_pages": ["3": 56],
|
|
"logical_memory": Data(repeating: 0, count: 65536).base64EncodedString(),
|
|
"available": Data(repeating: 1, count: 65536).base64EncodedString()]
|
|
let expected = try XCTUnwrap(MCPCMOC.ownedCaptureFingerprint(base))
|
|
for (key, value): (String, Any) in [
|
|
("boot", 2), ("field_clock", 3), ("machine_frame", 4), ("cycles", 5), ("generation", 6),
|
|
("pc", 0x3101), ("registers", ["PC": 0x3100, "S": 0x7002, "U": 0x7100]),
|
|
("processor", "HD6309"), ("execution_mode", "native"), ("md_register", 1),
|
|
("mapping_fingerprint", "mapping-2"), ("program_revision", 2), ("physical_pages", ["3": 57]),
|
|
("residency_fingerprint", "changed-owner"),
|
|
("logical_memory", Data(repeating: 1, count: 65536).base64EncodedString()),
|
|
("available", Data(repeating: 0, count: 65536).base64EncodedString())] {
|
|
var changed = base; changed[key] = value
|
|
XCTAssertNotEqual(MCPCMOC.ownedCaptureFingerprint(changed), expected, key)
|
|
}
|
|
var budgetOnly = base; budgetOnly["remaining_field_budget"] = 7; budgetOnly["remaining_requests"] = 9
|
|
XCTAssertEqual(MCPCMOC.ownedCaptureFingerprint(budgetOnly), expected,
|
|
"Read-request bookkeeping is independent of immutable guest identity")
|
|
for key in base.keys where key != "md_register" {
|
|
var missing = base; missing.removeValue(forKey: key)
|
|
XCTAssertNil(MCPCMOC.ownedCaptureFingerprint(missing), key)
|
|
}
|
|
var reordered = [String: Any]()
|
|
for key in base.keys.sorted().reversed() { reordered[key] = base[key] }
|
|
XCTAssertEqual(MCPCMOC.ownedCaptureFingerprint(reordered), expected)
|
|
}
|
|
}
|