Files
VCCPlusOSS/platforms/macos/App/MCPAssembly.swift
T

742 lines
46 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 AppKit
import Combine
import SwiftUI
struct AssemblyProjectEdit {
let path: String
let before: String
let after: String
}
@MainActor
private final class AssemblyAccessWindowDelegate: NSObject, NSWindowDelegate {
let didClose: @MainActor (NSWindow) -> Void
init(didClose: @escaping @MainActor (NSWindow) -> Void) { self.didClose = didClose; super.init() }
func windowWillClose(_ notification: Notification) {
if let window = notification.object as? NSWindow { didClose(window) }
}
}
/// A connection is bound to one native assembly document and its original source-file set.
@MainActor
final class MCPAssembly: ObservableObject {
static let shared = MCPAssembly()
static let tools = ["get_capabilities", "get_machine_status", "get_debug_snapshot", "read_debug_memory", "search_help", "read_topic", "read_project_file", "build_project", "get_build", "propose_fix", "propose_project_edits", "get_proposal", "get_run", "read_screen_text", "send_keys"]
private weak var model: AssemblyDevelopmentModel?
private weak var editors: AssemblyEditorPool?
private var transport: MCPTransport?
private var file: MCPGrantFile?
fileprivate var grantURL: URL? { file?.url }
private var scope = UUID()
private var token = ""
private var documentID: UUID?
private var files: Set<String> = []
private var last: AssemblyProjectSnapshot?
private var lastSourceRevision: UUID?
private var revision = 0
private var selection: AnyCancellable?
private var editObservation: AnyCancellable?
private var window: NSPanel?
private var windowPresentation = UUID()
private lazy var windowDelegate = AssemblyAccessWindowDelegate { [weak self] closing in
guard let self, self.window === closing else { return }
self.windowPresentation = UUID()
}
private var buildTask: Task<Void, Never>?
private var requests: [String: (tool: String, args: NSDictionary, id: String)] = [:]
private var latestBuildID: String?
private var builds: [String: [String: Any]] = [:]
private var proposals: [String: [String: Any]] = [:]
private var built: (id: String, revision: Int, artifact: AssemblyBuildArtifact)?
private var inspection: MCPDebuggerInspection?
private var runIO: MCPCompiledRunIO?
private var run: (id: String, revision: Int, build: String, machine: VCCMachineSnapshot)? {
willSet { runIO?.invalidate(); runIO = nil }
}
private var runMessage = "No run started."
@Published private(set) var connected = false
@Published private(set) var canRun = false
@Published private(set) var status = ""
@Published private(set) var proposal: Proposal?
struct Proposal: Identifiable {
enum Content {
case line(path: String, number: Int, before: String, after: String)
case files([AssemblyProjectEdit])
}
let id: String
let revision: Int
let content: Content
}
private struct AppliedFiles {
let proposal: Proposal
let revision: Int
let removedStops: Set<AssemblyDevelopmentModel.SourceLine>
}
@Published private var appliedFiles: AppliedFiles?
fileprivate var runnableBuildID: String? { canRun ? built?.id : nil }
fileprivate var undoableProposalID: String? { proposal == nil ? appliedFiles?.proposal.id : nil }
func show(_ model: AssemblyDevelopmentModel, editors: AssemblyEditorPool) {
windowPresentation = UUID()
if self.model !== model { revoke() }
self.model = model
self.editors = editors
let panel = window ?? NSPanel(contentRect: NSRect(x: 0, y: 0, width: 670, height: 460),
styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
panel.title = "Assembly Assistant Access"
panel.isReleasedWhenClosed = false
panel.delegate = windowDelegate
panel.contentView = NSHostingView(rootView: AssemblyAccessView(access: self, model: model))
if window == nil { panel.center() }
window = panel
panel.makeKeyAndOrderFront(nil)
}
func close(for model: AssemblyDevelopmentModel) {
guard self.model === model else { return }
revoke()
window?.close()
window = nil
}
fileprivate func choose(_ model: AssemblyDevelopmentModel) {
guard let owner = window, self.model === model, owner.isVisible,
!owner.isMiniaturized, owner.attachedSheet == nil else { return }
let document = model.activeID, generation = scope, presentation = windowPresentation
let panel = NSSavePanel()
panel.title = "Save Assembly Connection"
panel.nameFieldStringValue = "VCC Plus OSS Assembly Connection.json"
panel.beginSheetModal(for: owner) { [weak self, weak owner, weak model] response in
Task { @MainActor [weak self, weak owner, weak model] in
guard let self, let owner, let model else { return }
@MainActor func currentPresentation() -> Bool {
self.windowPresentation == presentation && self.window === owner && self.model === model && owner.isVisible &&
!owner.isMiniaturized && model.activeID == document
}
guard currentPresentation(), self.scope == generation else { return }
defer { if currentPresentation() { owner.makeKeyAndOrderFront(nil) } }
guard response == .OK, let url = panel.url else { return }
do { try await self.connect(model, to: url, presentationIsCurrent: currentPresentation) }
catch is CancellationError { }
catch { if currentPresentation() { self.status = error.localizedDescription } }
}
}
}
func revoke() {
inspection = nil
scope = UUID(); token = ""; connected = false; documentID = nil; selection = nil; editObservation = nil
requests.removeAll(); builds.removeAll(); latestBuildID = nil; proposals.removeAll()
buildTask?.cancel(); buildTask = nil
proposal = nil; appliedFiles = nil; built = nil; last = nil; run = nil; runMessage = "No run started."
canRun = false; status = ""; files.removeAll(); revision = 0
let old = transport, oldFile = file
transport = nil; file = nil
Task.detached { old?.stop(); oldFile?.remove() }
}
private static func sourcePaths(_ snapshot: AssemblyProjectSnapshot) throws -> Set<String> {
guard snapshot.settings.makefile == nil, snapshot.settings.linkScript == nil,
(snapshot.settings.modules ?? []).isEmpty else {
throw AssemblyBuildFailure("Share a native direct-assembly project. Linked projects and Make recipes require the local workspace.")
}
let paths = Set(snapshot.files.keys.filter { $0 != AssemblyProjectSnapshot.configurationFilename })
let extensions = ["asm", "s", "inc", "lwasm", "a09"]
guard paths.contains(snapshot.mainPath), paths.count <= 32, snapshot.files.values.reduce(0, { $0 + $1.count }) <= 512 * 1024,
paths.allSatisfy({ path in
guard extensions.contains((path as NSString).pathExtension.lowercased()), let data = snapshot.files[path] else { return false }
return data.count <= 64 * 1024 && !data.contains(0) && String(data: data, encoding: .utf8) != nil
}) else { throw AssemblyBuildFailure("Share a project containing up to 32 UTF-8 assembly or include files, 64 KiB per file.") }
return paths
}
func connect(_ model: AssemblyDevelopmentModel, to url: URL,
presentationIsCurrent: (@MainActor () -> Bool)? = nil) async throws {
revoke(); self.model = model
let ticket = scope, doc = model.document, version = model.workspaceRevision
let snapshot = try await Task.detached { try doc.snapshot() }.value
guard scope == ticket, model.activeID == doc.id, model.workspaceRevision == version,
presentationIsCurrent?() != false else { throw CancellationError() }
let paths = try Self.sourcePaths(snapshot)
let key = UUID().uuidString + UUID().uuidString
let handler: MCPTransport.Handler = { [weak self] bytes in
guard let self else { return Data(#"{"error":"access_denied"}"#.utf8) }
return await self.reply(bytes, ticket: ticket)
}
let pair = try await Task.detached {
let server = try MCPTransport(handler: handler)
let info: [String: Any] = ["kind": "assembly", "toolset": 3, "socket": server.unixPath, "port": Int(server.port), "version": 1, "token": key]
return (server, try MCPGrantFile(create: url, data: JSONSerialization.data(withJSONObject: info)))
}.value
guard scope == ticket, model.activeID == doc.id, model.workspaceRevision == version,
presentationIsCurrent?() != false else {
Task.detached { pair.0.stop(); pair.1.remove() }
throw CancellationError()
}
last = snapshot; lastSourceRevision = model.sourceRevision; files = paths; revision = 1
documentID = doc.id; token = key; transport = pair.0; file = pair.1
connected = true; status = "Sharing " + doc.title
editObservation = model.$sourceRevision.dropFirst().sink { [weak self] _ in self?.runIO?.invalidate() }
selection = model.$activeID.dropFirst().sink { [weak self] _ in self?.revoke() }
}
private func snapshot(_ model: AssemblyDevelopmentModel, ticket: UUID, retry: Bool = true) async throws -> AssemblyProjectSnapshot {
let doc = model.document, version = model.workspaceRevision
let value = try await Task.detached { try doc.snapshot() }.value
guard scope == ticket, model.activeID == documentID, doc.id == documentID else { throw AssemblyBuildFailure("access_denied") }
if model.workspaceRevision != version {
guard retry else { throw AssemblyBuildFailure("revision_conflict") }
return try await snapshot(model, ticket: ticket, retry: false)
}
guard try Self.sourcePaths(value) == files else { throw AssemblyBuildFailure("Shared files changed. Export a new connection.") }
if last != value || lastSourceRevision != model.sourceRevision {
lastSourceRevision = model.sourceRevision
revision += 1; last = value; canRun = false; run = nil; runMessage = "No run started."
appliedFiles = nil
if let p = proposal { proposals[p.id]?["status"] = "stale"; proposal = nil }
}
return value
}
private func reply(_ data: Data, ticket: UUID) async -> Data {
func pack(_ value: [String: Any]) -> Data { (try? JSONSerialization.data(withJSONObject: value)) ?? Data(#"{"error":"encoding_error"}"#.utf8) }
guard connected, ticket == scope, let model, model.activeID == documentID,
let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
let supplied = request["token"] as? String, supplied == token else { return pack(["error": "access_denied"]) }
guard request["version"] as? Int == 1, let args = request["arguments"] as? [String: Any],
let tool = request["tool"] as? String else { return pack(["error": "invalid_arguments"]) }
func currentGrant() -> Bool {
connected && scope == ticket && self.model === model && model.activeID == documentID
}
if tool == "search_help" || tool == "read_topic" {
let reply = await MCPHelpIndex.toolResult(tool, arguments: args)
guard currentGrant() else { return pack(["error": "access_denied"]) }
return pack(reply)
}
do {
let result = try await perform(tool, args, model: model, ticket: ticket)
guard currentGrant() else { return pack(["error": "access_denied"]) }
return pack(["result": result])
} catch { return pack(["error": currentGrant() ? error.localizedDescription : "access_denied"]) }
}
private func perform(_ tool: String, _ args: [String: Any], model: AssemblyDevelopmentModel, ticket: UUID) async throws -> [String: Any] {
let snapshot = try await snapshot(model, ticket: ticket)
guard connected, scope == ticket, self.model === model, model.activeID == documentID else { throw AssemblyBuildFailure("access_denied") }
let id = model.activeID.uuidString
if tool == "get_capabilities", args.isEmpty {
return ["version": 1, "input_diagnostics": true, "kind": "assembly", "language": "assembly", "session_id": scope.uuidString,
"project_id": id, "revision": revision, "entry": snapshot.mainPath, "target": snapshot.cpu.rawValue,
"files": files.sorted(), "tools": Self.tools]
}
if tool == "get_machine_status", args.isEmpty {
let observed = await model.machine.mcpReadinessSnapshot()
var build = await MCPMachineStatus.missingToolBlockers(in: model.service.tools.toolchain, requiring: ["lwasm"])
var run: [String] = []
if requests.count >= 64 { build.append("Reconnect to start another build.") }
if buildTask != nil || model.working || model.commanding { build.append("Wait for the current build or editor command.") }
if !canRun || built?.artifact.snapshot != snapshot { run.append("Assemble the current project revision.") }
if proposal != nil { run.append("Review the pending assembly edit.") }
if model.machine.busy || model.working || model.commanding { run.append("Wait for the current machine or editor operation.") }
return MCPMachineStatus.result(observed, workspace: .assembly(needs6309: snapshot.cpu == .hd6309),
buildBlockers: build, runBlockers: run, lastBuild: latestBuildID.flatMap(buildRecord),
profile: model.machine.usageProfile, input: model.machine.inputDiagnostics(machine: observed))
}
if tool == "get_build" {
guard args.count == 1, let key = args["build_id"] as? String else { throw AssemblyBuildFailure("invalid_arguments") }
guard let record = buildRecord(key) else { throw AssemblyBuildFailure("unknown_build") }
return record
}
if tool == "get_proposal" {
guard args.count == 1, let key = args["proposal_id"] as? String else { throw AssemblyBuildFailure("invalid_arguments") }
guard let record = proposals[key] else { throw AssemblyBuildFailure("unknown_proposal") }
return record
}
if tool == "read_screen_text" || tool == "send_keys" {
guard let run, let built, let runIO, run.revision == revision, run.build == built.id,
model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") }
let epoch = model.workspaceRevision
let result = try await runIO.reply(tool, arguments: args)
guard connected, scope == ticket, self.runIO === runIO, model.activeID == documentID,
model.workspaceRevision == epoch, revision == run.revision,
model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") }
return result
}
if tool == "get_debug_snapshot" || tool == "read_debug_memory" {
guard let run, let built, run.id == args["run_id"] as? String, run.revision == revision,
run.build == built.id, model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") }
if tool == "get_debug_snapshot" {
guard args.count == 1 else { throw AssemblyBuildFailure("invalid_arguments") }
return try await runResult(model, ticket: ticket, inspect: true)
}
let epoch = model.workspaceRevision
let now = await model.machine.mcpMachineSnapshot()
guard scope == ticket, self.run?.id == run.id, model.activeID == documentID, model.workspaceRevision == epoch,
revision == run.revision, model.artifact?.id == built.artifact.id,
now.debuggerAssemblyAttached, MCPDebuggerInspection.sameProgram(now, run.machine),
let inspection else { throw AssemblyBuildFailure("stale_snapshot") }
return try inspection.reply(tool: tool, arguments: args)
}
guard args["project_id"] as? String == id else { throw AssemblyBuildFailure("access_denied") }
if tool == "read_project_file" {
guard args.count == 2, let path = args["path"] as? String, files.contains(path), let data = snapshot.files[path] else {
throw AssemblyBuildFailure("path_not_shared")
}
return ["project_id": id, "revision": revision, "path": path, "text": String(decoding: data, as: UTF8.self)]
}
guard let requestedRevision = integer(args["revision"]) else { throw AssemblyBuildFailure("invalid_arguments") }
if tool == "get_run", args.count == 2 {
guard requestedRevision == revision else { throw AssemblyBuildFailure("revision_conflict") }
return try await runResult(model, ticket: ticket)
}
guard ["build_project", "propose_fix", "propose_project_edits"].contains(tool) else { throw AssemblyBuildFailure("invalid_arguments") }
guard let requestID = args["request_id"] as? String, (1...(tool == "propose_project_edits" ? 128 : 64)).contains(requestID.utf8.count)
else { throw AssemblyBuildFailure("invalid_request_id") }
if tool == "propose_fix", integer(args["line_number"]) == nil { throw AssemblyBuildFailure("invalid_arguments") }
if let previous = requests[requestID] {
guard previous.tool == tool, previous.args.isEqual(to: args) else { throw AssemblyBuildFailure("request_conflict") }
if let record = buildRecord(previous.id) ?? proposals[previous.id] { return record }
}
guard requestedRevision == revision else { throw AssemblyBuildFailure("revision_conflict") }
guard requests.count < 64 else { throw AssemblyBuildFailure("session_request_limit") }
let key = UUID().uuidString
if tool == "build_project", args.count == 3 {
guard buildTask == nil, !model.working, !model.commanding else { throw AssemblyBuildFailure("build_busy") }
let number = revision, workspaceRevision = model.workspaceRevision
let record: [String: Any] = ["build_id": key, "project_id": id, "revision": number, "status": "building", "diagnostics": []]
latestBuildID = key
builds[key] = record; requests[requestID] = (tool, NSDictionary(dictionary: args), key)
built = nil; run = nil; canRun = false; runMessage = "No run started."
buildTask = Task { [weak self] in
await self?.build(model, inputs: snapshot, revision: number, id: key, ticket: ticket, workspaceRevision: workspaceRevision)
}
return record
}
if tool == "propose_project_edits" {
guard args.count == 4, proposal == nil else { throw AssemblyBuildFailure("invalid_proposal") }
let edits = try Self.projectEdits(args["edits"], snapshot: snapshot, shared: files)
let record: [String: Any] = ["proposal_id": key, "revision": revision, "status": "pending",
"kind": "project_edits", "files": edits.map(\.path)]
proposals[key] = record; requests[requestID] = (tool, NSDictionary(dictionary: args), key)
proposal = Proposal(id: key, revision: revision, content: .files(edits))
status = "Review the proposed assembly files."
if let window {
window.makeKeyAndOrderFront(nil)
if !NSApp.isActive { NSApp.requestUserAttention(.informationalRequest) }
}
return record
}
guard tool == "propose_fix", args.count == 6, proposal == nil, let path = args["path"] as? String, files.contains(path),
let line = args["line_number"] as? Int, line > 0, let replacement = args["replacement"] as? String,
replacement.utf8.count <= 1024, !replacement.contains(where: { $0.isNewline || $0 == "\0" }),
let data = snapshot.files[path] else { throw AssemblyBuildFailure("invalid_proposal") }
let source = String(decoding: data, as: UTF8.self)
guard let range = Self.contentRange(line, source), range.length <= 4096 else { throw AssemblyBuildFailure("invalid_line") }
let before = (source as NSString).substring(with: range)
guard before != replacement else { throw AssemblyBuildFailure("unchanged_line") }
let growth = replacement.utf8.count - before.utf8.count
guard data.count + growth <= 64 * 1024,
snapshot.files.values.reduce(0, { $0 + $1.count }) + growth <= 512 * 1024 else {
throw AssemblyBuildFailure("project_too_large")
}
let record: [String: Any] = ["proposal_id": key, "revision": revision, "path": path, "line_number": line, "status": "pending"]
proposals[key] = record; requests[requestID] = (tool, NSDictionary(dictionary: args), key)
proposal = Proposal(id: key, revision: revision, content: .line(path: path, number: line, before: before, after: replacement))
status = "Review the proposed assembly change."
return record
}
static func projectEdits(_ value: Any?, snapshot: AssemblyProjectSnapshot, shared: Set<String>) throws -> [AssemblyProjectEdit] {
guard let rows = value as? [[String: Any]], (1...8).contains(rows.count) else { throw AssemblyBuildFailure("invalid_arguments") }
var paths = Set<String>(), edits: [AssemblyProjectEdit] = []
var bytes = 0, total = snapshot.files.values.reduce(0) { $0 + $1.count }
for row in rows {
guard row.count == 2, let path = row["path"] as? String, let source = row["source"] as? String,
paths.insert(path).inserted, !source.utf8.contains(0) else { throw AssemblyBuildFailure("invalid_arguments") }
guard shared.contains(path), let data = snapshot.files[path], let before = String(data: data, encoding: .utf8) else {
throw AssemblyBuildFailure("access_denied")
}
guard !source.utf8.elementsEqual(before.utf8) else { throw AssemblyBuildFailure("unchanged_file") }
let size = source.utf8.count
bytes += size; total += size - data.count
guard bytes <= 16 * 1024 else { throw AssemblyBuildFailure("patch_too_large") }
edits.append(AssemblyProjectEdit(path: path, before: before, after: source))
}
guard total <= 512 * 1024 else { throw AssemblyBuildFailure("project_too_large") }
return edits.sorted { $0.path < $1.path }
}
private func integer(_ value: Any?) -> Int? {
guard let n = value as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID(),
!["f", "d"].contains(String(cString: n.objCType)) else { return nil }
return Int(exactly: n)
}
private func buildRecord(_ id: String) -> [String: Any]? {
guard var record = builds[id] else { return nil }
if record["revision"] as? Int != revision { record["status"] = "stale" }
return record
}
private func build(_ model: AssemblyDevelopmentModel, inputs: AssemblyProjectSnapshot, revision number: Int,
id: String, ticket: UUID, workspaceRevision: UUID) async {
defer { if ticket == scope { buildTask = nil } }
do {
let artifact = try await model.service.build(inputs)
guard try await snapshot(model, ticket: ticket) == inputs, revision == number, ticket == scope,
workspaceRevision == model.workspaceRevision else { throw AssemblyBuildFailure("revision_conflict") }
builds[id]?["status"] = "succeeded"
builds[id]?["entry"] = Int(artifact.entry)
builds[id]?["target"] = inputs.cpu.rawValue
builds[id]?["instruction_count"] = artifact.instructions.count
builds[id]?["ranges"] = artifact.ranges.map { [Int($0.lowerBound), Int($0.upperBound)] }
built = (id, number, artifact); canRun = true
model.acceptSharedBuild(artifact)
status = "Assembled for " + inputs.cpu.rawValue + ". " + AssemblyDevelopmentModel.summary(artifact)
} catch {
guard scope == ticket else { return }
builds[id]?["status"] = revision == number ? "failed" : "stale"
builds[id]?["diagnostics"] = (error as? AssemblyBuildFailure)?.diagnostics.prefix(32).map {
["path": $0.path, "line": $0.line, "message": String($0.message.prefix(512))] as [String: Any]
} ?? []
builds[id]?["message"] = String(error.localizedDescription.prefix(2048))
status = String(error.localizedDescription.prefix(512))
}
}
private static func contentRange(_ line: Int, _ source: String) -> NSRange? {
let text = source as NSString
guard let span = AssemblyDevelopmentModel.lineRange(line, text: source), span.location < text.length else { return nil }
var end = 0
text.getLineStart(nil, end: nil, contentsEnd: &end, for: NSRange(location: span.location, length: 0))
return NSRange(location: span.location, length: end - span.location)
}
func decide(_ id: String, apply: Bool) async {
guard let p = proposal, p.id == id, let model else { return }
if !apply { proposals[p.id]?["status"] = "cancelled"; proposal = nil; return }
do {
let value = try await snapshot(model, ticket: scope)
guard proposal?.id == p.id, revision == p.revision, !model.working, !model.commanding else { throw AssemblyBuildFailure("revision_conflict") }
guard connected, model.activeID == documentID, model.sourceRevision == lastSourceRevision else { throw AssemblyBuildFailure("revision_conflict") }
if case let .files(edits) = p.content {
let removed = try replaceFiles(edits, model: model, value: value)
appliedFiles = AppliedFiles(proposal: p, revision: revision, removedStops: removed)
proposal = nil; proposals[p.id]?["status"] = "applied"; proposals[p.id]?["applied_revision"] = revision
status = "Applied all reviewed files to the assembly draft."
return
}
guard case let .line(path, line, before, after) = p.content else { return }
guard model.buffer.path == path, value.files[path] == Data(model.buffer.text.utf8) else {
model.selectFile(path, line: line)
status = "Review the selected source file, then apply the change."
return
}
guard let range = Self.contentRange(line, model.buffer.text), (model.buffer.text as NSString).substring(with: range) == before else {
throw AssemblyBuildFailure("revision_conflict")
}
let expected = (model.buffer.text as NSString).replacingCharacters(in: range, with: after)
let accepted = editors?.replaceReviewedLine(in: model.buffer, range: range, with: after) ?? false
guard accepted, model.buffer.text == expected else { throw AssemblyBuildFailure("Open the assembly editor before applying the proposal.") }
proposal = nil; proposals[p.id]?["status"] = "applied"
_ = try await snapshot(model, ticket: scope)
proposals[p.id]?["applied_revision"] = revision
status = "Applied the edit. Build the revised assembly source."
} catch { status = error.localizedDescription }
}
private func replaceFiles(_ edits: [AssemblyProjectEdit], model: AssemblyDevelopmentModel, value: AssemblyProjectSnapshot,
undo: Bool = false, restore: Set<AssemblyDevelopmentModel.SourceLine> = []) throws -> Set<AssemblyDevelopmentModel.SourceLine> {
let paths = Set(edits.map(\.path))
guard editors?.canReplace(model.document.buffers.filter { paths.contains($0.path) }) != false else {
throw AssemblyBuildFailure("Finish the current editor input before applying this review.")
}
let removed = try model.replaceReviewedFiles(edits, snapshot: value, undo: undo, restoreStops: restore)
var files = value.files
for edit in edits { files[edit.path] = Data((undo ? edit.before : edit.after).utf8) }
last = AssemblyProjectSnapshot(mainPath: value.mainPath, files: files, cpu: value.cpu, settings: value.settings)
lastSourceRevision = model.sourceRevision; revision += 1
built = nil; canRun = false; run = nil; runMessage = "No run started."
return removed
}
func undoFiles(_ id: String) async {
guard let applied = appliedFiles, applied.proposal.id == id, let model, case let .files(edits) = applied.proposal.content else { return }
do {
let value = try await snapshot(model, ticket: scope)
guard connected, model.activeID == documentID, appliedFiles?.proposal.id == applied.proposal.id, proposal == nil,
revision == applied.revision, model.sourceRevision == lastSourceRevision else { throw AssemblyBuildFailure("revision_conflict") }
_ = try replaceFiles(edits, model: model, value: value, undo: true, restore: applied.removedStops)
proposals[applied.proposal.id]?["status"] = "undone"; appliedFiles = nil
status = "Undid all reviewed assembly changes."
} catch { status = error.localizedDescription }
}
func startRun(_ id: String, confirm: ((String) -> Bool)? = nil) async {
guard canRun, proposal == nil, let model, let built, built.id == id, !model.working, !model.commanding else { return }
let ticket = scope
do {
guard try await snapshot(model, ticket: ticket) == built.artifact.snapshot, self.built?.id == built.id,
proposal == nil, revision == built.revision else { throw AssemblyBuildFailure("revision_conflict") }
run = nil; runMessage = "Starting"
let launched = try await model.launchShared(built.artifact, stillGranted: { [weak self] in
self?.scope == ticket && self?.built?.id == built.id && self?.revision == built.revision &&
self?.proposal == nil && self?.model?.activeID == self?.documentID
}, confirm: confirm)
guard scope == ticket else { return }
let runID = UUID().uuidString
run = (runID, built.revision, built.id, launched)
runIO = MCPCompiledRunIO(machine: model.machine, runID: runID, expected: launched, assembly: true)
runMessage = "started"; status = "Assembly program loaded."
} catch { if scope == ticket { runMessage = error.localizedDescription; status = runMessage } }
}
private func runResult(_ model: AssemblyDevelopmentModel, ticket: UUID, inspect: Bool = false) async throws -> [String: Any] {
guard let run, let built, run.revision == revision, run.build == built.id else {
return ["status": runMessage, "revision": revision]
}
let workspaceRevision = model.workspaceRevision
let capture: VCCDebuggerSnapshot? = await withCheckedContinuation { c in
model.machine.readDebugger(address: 0, followPC: true, memoryAddress: 0x0400) { c.resume(returning: $0) }
}
guard let capture, scope == ticket, revision == run.revision, self.run?.id == run.id,
model.activeID == documentID, workspaceRevision == model.workspaceRevision,
model.artifact?.id == built.artifact.id else { throw AssemblyBuildFailure("stale_run") }
let current = capture.machine
guard current.generation == run.machine.generation, current.debuggerProgramRevision == run.machine.debuggerProgramRevision,
current.debuggerMappingFingerprint == run.machine.debuggerMappingFingerprint, current.debuggerAssemblyAttached
else { throw AssemblyBuildFailure("stale_run") }
var result: [String: Any] = ["run_id": run.id, "build_id": built.id, "revision": revision, "target": built.artifact.snapshot.cpu.rawValue,
"processor": current.use6309 ? "HD6309" : "MC6809", "status": current.state == .paused ? "paused" : "running"]
if current.assistantCompiledReturned {
if inspect { throw AssemblyBuildFailure("run_finished") }
result["status"] = "finished"
if let runIO {
if let text = try await runIO.finalScreenText() { result["final_screen_text"] = text }
guard scope == ticket, self.runIO === runIO, self.run?.id == run.id,
model.activeID == documentID, workspaceRevision == model.workspaceRevision else {
throw AssemblyBuildFailure("stale_run")
}
}
return result
}
guard current.state == .paused else {
if inspect { throw AssemblyBuildFailure("pause_required") }
return result
}
let guards = AssemblyDevelopmentModel.codeGuards(built.artifact.instructions)
for (address, bytes) in guards {
let range = Int(address)..<(Int(address) + bytes.count)
guard range.upperBound <= capture.logicalMemory.count, range.upperBound <= capture.logicalMemoryAvailable.count,
capture.logicalMemoryAvailable[range].allSatisfy({ $0 != 0 }), capture.logicalMemory[range].elementsEqual(bytes)
else { throw AssemblyBuildFailure("stale_run") }
}
let pc = current.programCounter
let candidates = built.artifact.instructions.filter { $0.address == pc }
var sourceStop: [String: Any]?
if candidates.count == 1, let mapped = candidates.first, files.contains(mapped.path),
AssemblyDevelopmentModel.location(.init(path: mapped.path, line: mapped.line), in: built.artifact) != nil,
let instruction = capture.instructions.first, instruction.address == pc, Array(instruction.bytes) == mapped.bytes {
sourceStop = ["path": mapped.path, "line": mapped.line, "address": Int(pc), "instruction_bytes": mapped.bytes.map(Int.init)]
}
if inspect {
var ranges = built.artifact.instructions.filter { files.contains($0.path) && guards[$0.address] != nil }.map {
Int($0.address)..<(Int($0.address) + $0.bytes.count)
}
ranges.append(0x0400..<0x0401)
let snapshot = try MCPDebuggerInspection(runID: run.id, capture: capture,
scope: ["project_id": model.activeID.uuidString, "build_id": built.id, "revision": revision],
sourceStop: sourceStop, watches: [], watchStatus: "Assembly has no source-level variable watches.", ranges: ranges)
inspection = snapshot
return snapshot.fields
}
guard let sourceStop else { return result }
result["source_stop"] = sourceStop
var registers = ["pc": Int(pc)]
if let a = capture.registers["A"] { registers["a"] = a.intValue }
if let e = capture.registers["E"] { registers["e"] = e.intValue }
result["registers"] = registers
if capture.logicalMemoryAvailable.count > 0x0400, capture.logicalMemoryAvailable[0x0400] != 0 {
result["text_ram_0400"] = Int(capture.logicalMemory[0x0400])
}
return result
}
#if DEBUG
/// A fresh, explicitly isolated synthetic project. Only the regression variant accepts test decisions.
func startFixture(_ model: AssemblyDevelopmentModel, directory: URL, romDirectory: URL) async throws {
guard CommandLine.arguments.contains("--interface-validation"),
try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty
else { throw AssemblyBuildFailure("Use an empty isolated assembly validation directory.") }
try await MCPBASICRun.bootFixture(model.machine, romDirectory: romDirectory)
let project = directory.appendingPathComponent("Assembly")
try FileManager.default.createDirectory(at: project, withIntermediateDirectories: false)
let enhanced = CommandLine.arguments.contains("--mcp-assembly-hd6309")
let source = """
org $3f00
include "value.inc"
start \(enhanced ? "lde" : "lda") #VALUE
\(enhanced ? "adde" : "adda") #1
\(enhanced ? "ste" : "sta") $0400
done rts
end start
"""
try Data(source.utf8).write(to: project.appendingPathComponent("main.asm"), options: .withoutOverwriting)
try Data("VALUE equ 1\n".utf8).write(to: project.appendingPathComponent("value.inc"), options: .withoutOverwriting)
model.open(project, folder: true)
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
while model.document.directory?.lastPathComponent != project.lastPathComponent, ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(30))
}
let physicalProject = try CMOCProject.physicalURL(project)
guard model.document.directory?.path == physicalProject.path else { throw AssemblyBuildFailure("The synthetic assembly workspace failed to open.") }
model.setCPU(enhanced ? .hd6309 : .mc6809)
try await connect(model, to: directory.appendingPathComponent("grant.json"))
guard CommandLine.arguments.contains("--mcp-assembly-regression") else { return }
let editorPool = AssemblyEditorPool()
editors = editorPool
let editorWindow = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 620, height: 320),
styleMask: [.titled], backing: .buffered, defer: false)
editorWindow.title = "Assembly Development — Regression"
let editor = NSHostingView(rootView: AssemblyEditor(finder: SourceFind(), model: model, pool: editorPool, lookup: {}))
editor.sizingOptions = []
editorWindow.contentView = editor
editorWindow.orderBack(nil)
editor.layoutSubtreeIfNeeded()
try Data().write(to: directory.appendingPathComponent("assembly-regression-fixture"), options: .withoutOverwriting)
let ticket = scope
Task {
defer { editorWindow.orderOut(nil) }
func consume(_ name: String) -> Bool { unlink(directory.appendingPathComponent(name).path) == 0 }
while scope == ticket {
try? await Task.sleep(for: .milliseconds(100))
if consume("apply"), let id = proposal?.id { await decide(id, apply: true) }
if consume("undo-files"), let id = undoableProposalID { await undoFiles(id) }
if consume("cancel-project-edits"), let id = proposal?.id { await decide(id, apply: false) }
if consume("stale-review-click") {
// A click captured from a retired native review must never operate on its replacement.
await decide("retired-review", apply: true)
await decide("retired-review", apply: false)
await undoFiles("retired-review")
try? Data().write(to: directory.appendingPathComponent("checked-stale-click"))
}
if consume("capture-review"), proposal != nil {
show(model, editors: editorPool)
try? await Task.sleep(for: .milliseconds(250))
if let panel = window {
let capture = Process()
capture.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
capture.arguments = ["-x", "-o", "-l", String(panel.windowNumber), directory.appendingPathComponent("review.png").path]
capture.terminationHandler = { _ in Task { @MainActor in panel.orderOut(nil) } }
do { try capture.run() } catch { panel.orderOut(nil) }
}
}
if consume("stale-run-click") {
await startRun("retired-build", confirm: { _ in true })
try? Data().write(to: directory.appendingPathComponent("checked-stale-run"))
}
if consume("play"), let id = runnableBuildID { await startRun(id, confirm: { _ in true }) }
if consume("run"), let id = runnableBuildID {
if !model.document.breakpoints.contains(.init(path: "main.asm", line: 6)),
let span = AssemblyDevelopmentModel.lineRange(6, text: model.buffer.text) {
model.moveCursor(span.location); model.toggleBreakpoint()
}
await startRun(id, confirm: { _ in true })
}
if consume("quit") {
revoke()
NSApp.perform(#selector(NSApplication.terminate(_:)), with: nil, afterDelay: 0)
return
}
}
}
}
#endif
}
private struct AssemblyAccessView: View {
@ObservedObject var access: MCPAssembly
@ObservedObject var model: AssemblyDevelopmentModel
@State private var expandedFiles = Set<String>()
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 10) {
Label(model.document.title, systemImage: "cpu").font(.headline)
if access.connected {
if let proposal = access.proposal {
switch proposal.content {
case let .line(path, number, before, after):
Text("\(path), line \(number)").bold()
comparison(before: before, after: after)
reviewButtons(proposal.id, multiple: false)
case .files(let edits):
Text(edits.count == 1 ? "Review 1 assembly file" : "Review \(edits.count) assembly files").font(.headline)
reviewButtons(proposal.id, multiple: true)
ForEach(edits, id: \.path) { edit in
DisclosureGroup(edit.path, isExpanded: Binding(
get: { expandedFiles.contains(edit.path) },
set: { if $0 { expandedFiles.insert(edit.path) } else { expandedFiles.remove(edit.path) } }
)) {
HStack(alignment: .top, spacing: 12) {
sourceColumn("Current", edit.before)
Divider()
sourceColumn("Proposed", edit.after)
}.padding(.vertical, 4)
}
}
.onAppear { if let first = edits.first { expandedFiles = [first.path] } }
.id(proposal.id)
}
}
if let id = access.undoableProposalID {
Button("Undo All Changes") { Task { await access.undoFiles(id) } }
}
if let url = access.grantURL {
MCPChatGPTSetup(grantURL: url, firstPrompt: "Identify my shared VCC Plus assembly project and target processor. Read the entry source file and describe what the CoCo program does.")
}
HStack {
Button("Copy MCP Helper Path") {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/vcc-mcp").path, forType: .string)
}
Button("Revoke Connection") { access.revoke() }
}
let buildID = access.runnableBuildID
Button("Run Shared Build…") {
if let buildID { Task { await access.startRun(buildID) } }
}.disabled(buildID == nil || access.proposal != nil || model.commanding || model.working)
} else {
Text("Share this document’s assembly files with a client that can build them and propose edits. You approve edits and start runs. The client can read the guest text screen and send one letter, digit or space at a time during your run. It can check machine and media status. At a verified source stop it can inspect registers, shared program memory and the text byte at $0400. The client’s model provider may receive those results.")
Button("Save Assembly Connection…") { access.choose(model) }
}
if !access.status.isEmpty { Text(access.status).foregroundStyle(.secondary).textSelection(.enabled) }
}.padding().frame(maxWidth: .infinity, alignment: .leading)
}
}
private func sourceColumn(_ title: String, _ source: String) -> some View {
VStack(alignment: .leading, spacing: 4) {
Text(title).font(.caption).foregroundStyle(.secondary)
ScrollView(.horizontal) {
Text(verbatim: source).font(.callout.monospaced()).textSelection(.enabled)
.fixedSize(horizontal: true, vertical: true)
}
}.frame(maxWidth: .infinity, alignment: .leading)
}
@ViewBuilder private func comparison(before: String, after: String) -> some View {
Text("Current").font(.caption)
Text(before).font(.body.monospaced()).textSelection(.enabled)
Text("Proposed").font(.caption)
Text(after).font(.body.monospaced()).textSelection(.enabled)
}
private func reviewButtons(_ id: String, multiple: Bool) -> some View {
HStack {
Button(multiple ? "Apply All Changes" : "Apply Edit") { Task { await access.decide(id, apply: true) } }
Button(multiple ? "Cancel Changes" : "Cancel Edit") { Task { await access.decide(id, apply: false) } }
}
}
}