650 lines
36 KiB
Swift
650 lines
36 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import SwiftUI
|
|
import AppKit
|
|
import Combine
|
|
import Darwin
|
|
|
|
fileprivate struct BASICEditProposal: Identifiable {
|
|
let id = UUID().uuidString
|
|
let requestID: String, revision: Int, line: Int?, before: String, after: String
|
|
var status = "pending"
|
|
var appliedRevision: Int?
|
|
var subject: String { line.map { "BASIC line " + String($0) } ?? "Complete BASIC listing" }
|
|
|
|
func range(in source: String) -> NSRange? {
|
|
if let line { return BASICLanguage.lineRange(for: line, in: source) }
|
|
return NSRange(location: 0, length: (source as NSString).length)
|
|
}
|
|
|
|
var result: [String: Any] {
|
|
var result: [String: Any] = ["proposal_id": id, "revision": revision, "status": status]
|
|
if let line { result["line_number"] = line } else { result["kind"] = "listing" }
|
|
if let appliedRevision { result["applied_revision"] = appliedRevision }
|
|
return result
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
final class MCPAccess: ObservableObject {
|
|
static let shared = MCPAccess()
|
|
fileprivate weak var selected: BASICDevelopmentModel?
|
|
@Published fileprivate(set) var activeTitle: String?
|
|
@Published fileprivate(set) var message: String?
|
|
private var listener: MCPTransport?
|
|
private var pendingGrant = UUID()
|
|
private weak var pendingModel: BASICDevelopmentModel?
|
|
private weak var panelModel: BASICDevelopmentModel?
|
|
private var token = ""
|
|
private var sessionID = ""
|
|
private var documentID: UUID?
|
|
fileprivate var grantFile: MCPGrantFile?
|
|
private var documentChange: AnyCancellable?
|
|
private var panel: NSPanel?
|
|
private let guest = MCPBASICRun()
|
|
@Published fileprivate var canPropose = false
|
|
@Published fileprivate var current: BASICEditProposal?
|
|
private var history: [String: BASICEditProposal] = [:]
|
|
private var reviewWindow: NSPanel?
|
|
private var fixtureLabel: String?
|
|
private var regressionFixture = false
|
|
#if DEBUG
|
|
private var fixtureEditor: NSWindow?
|
|
#endif
|
|
#if DEBUG
|
|
private var fixturePoll: Task<Void, Never>?
|
|
#endif
|
|
|
|
func show(for model: BASICDevelopmentModel) {
|
|
panel?.close()
|
|
let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 550, height: 510),
|
|
styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
|
|
window.title = "Connect to ChatGPT or Another Assistant"
|
|
window.isReleasedWhenClosed = false
|
|
window.contentMinSize = NSSize(width: 360, height: 230)
|
|
let content = NSHostingView(rootView: ScrollView { MCPAccessView(access: self, model: model) })
|
|
content.sizingOptions = []
|
|
window.contentView = content
|
|
window.center()
|
|
panel = window
|
|
panelModel = model
|
|
window.makeKeyAndOrderFront(nil)
|
|
}
|
|
|
|
fileprivate func chooseGrant(for model: BASICDevelopmentModel, proposals: Bool) {
|
|
guard let owner = panel, panelModel === model, owner.isVisible,
|
|
!owner.isMiniaturized, owner.attachedSheet == nil else { return }
|
|
let draft = model.documentID, connection = sessionID, generation = pendingGrant
|
|
let picker = NSSavePanel()
|
|
picker.nameFieldStringValue = "VCC Plus OSS Connection.json"
|
|
picker.title = proposals ? "Save Review and Run Connection" : "Save Read-Only Connection"
|
|
picker.message = "Choose a new local file. Give it only to assistants you trust to read this program."
|
|
picker.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.panel === owner && self.panelModel === model && owner.isVisible &&
|
|
!owner.isMiniaturized && model.documentID == draft
|
|
}
|
|
guard currentPresentation(), self.sessionID == connection, self.pendingGrant == generation else { return }
|
|
defer { if currentPresentation() { owner.makeKeyAndOrderFront(nil) } }
|
|
guard response == .OK, let url = picker.url else { return }
|
|
do { try await self.grant(model, at: url, proposals: proposals, presentationIsCurrent: currentPresentation) }
|
|
catch is CancellationError { }
|
|
catch {
|
|
if currentPresentation() { self.message = "Could not create a new connection file. " + error.localizedDescription }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func grant(_ model: BASICDevelopmentModel, at url: URL, proposals: Bool = false,
|
|
presentationIsCurrent: (@MainActor () -> Bool)? = nil) async throws {
|
|
let ticket = UUID()
|
|
pendingGrant = ticket
|
|
pendingModel = model
|
|
defer { if pendingGrant == ticket { pendingModel = nil } }
|
|
let draft = model.documentID
|
|
let id = UUID().uuidString
|
|
let secret = UUID().uuidString + UUID().uuidString
|
|
let callback: MCPTransport.Handler = { [weak self] request in
|
|
guard let self else { return Data(#"{"error":"access_denied"}"#.utf8) }
|
|
return await self.reply(to: request, session: id)
|
|
}
|
|
let (server, file) = try await Task.detached(priority: .userInitiated) {
|
|
let server = try MCPTransport(handler: callback)
|
|
let data = try JSONSerialization.data(withJSONObject: ["socket": server.unixPath, "port": Int(server.port),
|
|
"version": 1, "toolset": 3, "token": secret, "canPropose": proposals])
|
|
return (server, try MCPGrantFile(create: url, data: data))
|
|
}.value
|
|
guard ticket == pendingGrant, model.documentID == draft, presentationIsCurrent?() != false else {
|
|
Task.detached { server.stop(); file.remove() }
|
|
throw CancellationError()
|
|
}
|
|
revoke()
|
|
selected = model
|
|
sessionID = id
|
|
token = secret
|
|
documentID = model.documentID
|
|
grantFile = file
|
|
listener = server
|
|
canPropose = proposals
|
|
activeTitle = model.title
|
|
message = nil
|
|
documentChange = model.$documentID.dropFirst().sink { [weak self] _ in _ = self?.revoke() }
|
|
}
|
|
|
|
@discardableResult
|
|
func revoke() -> Task<Void, Never> {
|
|
pendingGrant = UUID()
|
|
pendingModel = nil
|
|
token = ""
|
|
canPropose = false
|
|
current = nil
|
|
history.removeAll()
|
|
guest.reset()
|
|
reviewWindow?.orderOut(nil)
|
|
reviewWindow = nil
|
|
selected = nil
|
|
documentID = nil
|
|
sessionID = ""
|
|
documentChange = nil
|
|
activeTitle = nil
|
|
let old = listener, file = grantFile
|
|
listener = nil
|
|
grantFile = nil
|
|
return Task.detached {
|
|
old?.stop()
|
|
file?.remove()
|
|
}
|
|
}
|
|
|
|
func closing(_ model: BASICDevelopmentModel) {
|
|
if selected === model || pendingModel === model { revoke() }
|
|
if panelModel === model {
|
|
panel?.close()
|
|
panel = nil
|
|
panelModel = nil
|
|
}
|
|
}
|
|
|
|
private func reply(to data: Data, session: String) async -> Data {
|
|
func pack(_ value: [String: Any]) -> Data {
|
|
(try? JSONSerialization.data(withJSONObject: value)) ?? Data(#"{"error":"encoding_error"}"#.utf8)
|
|
}
|
|
guard let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
|
let supplied = request["token"] as? String, sessionID == session,
|
|
!token.isEmpty, supplied == token, let model = selected, model.documentID == documentID
|
|
else { return pack(["error": "access_denied"]) }
|
|
guard request["version"] as? Int == 1 else { return pack(["error": "version_mismatch"]) }
|
|
guard let args = request["arguments"] as? [String: Any] else { return pack(["error": "invalid_arguments"]) }
|
|
let id = model.documentID.uuidString
|
|
let result: [String: Any]
|
|
switch request["tool"] as? String {
|
|
case "get_capabilities" where args.isEmpty:
|
|
result = ["tools": ["get_capabilities", "get_machine_status", "read_source", "search_help", "read_topic"] + (canPropose ? ["propose_edit", "propose_listing", "get_proposal", "get_run", "read_screen_text", "send_keys", "get_debug_snapshot", "read_debug_memory"] : []),
|
|
"version": 1, "input_diagnostics": true, "session_id": session, "title": model.title, "document_id": id,
|
|
"app": "VCC Plus OSS", "build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown"]
|
|
case "get_machine_status" where args.isEmpty:
|
|
let observed = await model.machine.mcpReadinessSnapshot()
|
|
guard sessionID == session, selected === model, model.documentID == documentID else { return pack(["error": "access_denied"]) }
|
|
refreshProposal(model)
|
|
var blockers: [String] = []
|
|
if !canPropose { blockers.append("Save a review and run connection to start a shared program.") }
|
|
if current?.status != "applied" || current?.appliedRevision != model.sourceRevision {
|
|
blockers.append("Apply a proposal for the current BASIC draft.")
|
|
}
|
|
if model.editorLocked || model.machine.busy || guest.busy { blockers.append("Wait for the current operation to finish.") }
|
|
result = MCPMachineStatus.result(observed, workspace: .basic, buildBlockers: nil, runBlockers: blockers,
|
|
profile: model.machine.usageProfile, input: model.machine.inputDiagnostics(machine: observed))
|
|
case "read_source" where args.count == 1:
|
|
guard args["document_id"] as? String == id else { return pack(["error": "access_denied"]) }
|
|
guard model.source.utf8.count <= 65536 else { return pack(["error": "source_too_large"]) }
|
|
result = ["document_id": id, "text": model.source, "revision": model.sourceRevision, "title": model.title]
|
|
case let name? where name == "propose_edit" || name == "propose_listing":
|
|
guard canPropose else { return pack(["error": "access_denied"]) }
|
|
return pack(propose(args, model: model, wholeListing: name == "propose_listing"))
|
|
case "get_proposal":
|
|
guard canPropose else { return pack(["error": "access_denied"]) }
|
|
guard args.count == 1, let id = args["proposal_id"] as? String, let proposal = history[id] else {
|
|
return pack(["error": "unknown_proposal"])
|
|
}
|
|
refreshProposal(model)
|
|
return pack(["result": (history[id] ?? proposal).result])
|
|
case let name? where ["get_run", "get_debug_snapshot", "read_debug_memory", "read_screen_text", "send_keys"].contains(name):
|
|
guard canPropose else { return pack(["error": "access_denied"]) }
|
|
let reply = await guest.handle(tool: name, arguments: args, model: model)
|
|
guard sessionID == session, selected === model, model.documentID == documentID else { return pack(["error": "access_denied"]) }
|
|
return pack(reply)
|
|
case let tool? where tool == "search_help" || tool == "read_topic":
|
|
let response = await MCPHelpIndex.toolResult(tool, arguments: args)
|
|
guard sessionID == session, selected === model, documentID == model.documentID else {
|
|
return pack(["error": "access_denied"])
|
|
}
|
|
return pack(response)
|
|
default:
|
|
return pack(["error": "invalid_arguments"])
|
|
}
|
|
guard sessionID == session, selected === model, documentID == model.documentID else {
|
|
return pack(["error": "access_denied"])
|
|
}
|
|
return pack(["result": result])
|
|
}
|
|
|
|
private func update(_ proposal: BASICEditProposal) {
|
|
current = proposal
|
|
history[proposal.id] = proposal
|
|
}
|
|
|
|
fileprivate func refreshProposal(_ model: BASICDevelopmentModel) {
|
|
guard var proposal = current else { return }
|
|
if proposal.status == "pending", proposal.revision != model.sourceRevision {
|
|
proposal.status = "stale"
|
|
update(proposal)
|
|
}
|
|
}
|
|
|
|
private func propose(_ args: [String: Any], model: BASICDevelopmentModel, wholeListing: Bool) -> [String: Any] {
|
|
guard args["document_id"] as? String == model.documentID.uuidString else { return ["error": "access_denied"] }
|
|
func integer(_ key: String) -> Int? {
|
|
guard let number = args[key] as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
|
|
!["d", "f"].contains(String(cString: number.objCType)) else { return nil }
|
|
return Int(exactly: number)
|
|
}
|
|
guard let revision = integer("revision"), revision >= 0,
|
|
let requestID = args["request_id"] as? String, (1...128).contains(requestID.utf8.count)
|
|
else { return ["error": "invalid_arguments"] }
|
|
let line: Int?
|
|
let replacement: String
|
|
if wholeListing {
|
|
guard args.count == 4, let listing = args["source"] as? String,
|
|
(1...12 * 1024).contains(listing.utf8.count) else { return ["error": "invalid_arguments"] }
|
|
let lines = listing.replacingOccurrences(of: "\r\n", with: "\n").components(separatedBy: "\n")
|
|
guard lines.allSatisfy({ $0.utf8.count <= 249 && $0.utf8.allSatisfy { $0 == 9 || (32...126).contains($0) } })
|
|
else { return ["error": "invalid_listing"] }
|
|
let analysis = BASICLanguage.analyze(listing)
|
|
guard !analysis.hasErrors, !analysis.lines.isEmpty else { return ["error": "invalid_listing"] }
|
|
line = nil
|
|
replacement = listing
|
|
} else {
|
|
guard args.count == 5, let number = integer("line_number"), let text = args["replacement"] as? String,
|
|
(1...249).contains(text.utf8.count), text.utf8.allSatisfy({ $0 == 9 || (32...126).contains($0) }),
|
|
BASICLanguage.lineRange(for: number, in: text) != nil else { return ["error": "invalid_arguments"] }
|
|
line = number
|
|
replacement = text
|
|
}
|
|
refreshProposal(model)
|
|
if let retry = history.values.first(where: { $0.requestID == requestID }) {
|
|
guard retry.revision == revision, retry.line == line, retry.after == replacement else { return ["error": "request_id_conflict"] }
|
|
return ["result": retry.result]
|
|
}
|
|
guard revision == model.sourceRevision else { return ["error": "stale_revision"] }
|
|
guard current?.status != "pending" else { return ["error": "review_pending"] }
|
|
guard history.count < 128 else { return ["error": "session_proposal_limit"] }
|
|
guard model.source.utf8.count <= 65536 else { return ["error": "source_too_large"] }
|
|
let before: String
|
|
if let line {
|
|
guard let range = BASICLanguage.lineRange(for: line, in: model.source) else { return ["error": "line_not_found"] }
|
|
before = (model.source as NSString).substring(with: range)
|
|
} else {
|
|
before = model.source
|
|
}
|
|
guard before != replacement else { return ["error": wholeListing ? "unchanged_listing" : "unchanged_line"] }
|
|
let proposal = BASICEditProposal(requestID: requestID, revision: revision, line: line, before: before, after: replacement)
|
|
update(proposal)
|
|
showReview(model)
|
|
return ["result": proposal.result]
|
|
}
|
|
|
|
fileprivate func showReview(_ model: BASICDevelopmentModel) {
|
|
guard selected === model, current != nil else { return }
|
|
if let reviewWindow {
|
|
if !regressionFixture { reviewWindow.makeKeyAndOrderFront(nil) }
|
|
return
|
|
}
|
|
let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 595, height: 340),
|
|
styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
|
|
window.title = fixtureLabel.map { "Review BASIC Edit — " + $0 } ?? "Review BASIC Edit"
|
|
window.isReleasedWhenClosed = false
|
|
window.contentMinSize = NSSize(width: 440, height: 280)
|
|
let content = NSHostingView(rootView: ScrollView { MCPReviewView(access: self, model: model, guest: guest) })
|
|
content.sizingOptions = []
|
|
window.contentView = content
|
|
window.center()
|
|
reviewWindow = window
|
|
if !regressionFixture {
|
|
#if DEBUG
|
|
if let label = fixtureLabel, let bounds = window.screen?.visibleFrame {
|
|
let side: CGFloat = label.lowercased().contains("ollama") ? 1 : -1
|
|
let offset = max(0, min(bounds.width / 4, (bounds.width - window.frame.width) / 2))
|
|
window.setFrameOrigin(NSPoint(x: bounds.midX - window.frame.width / 2 + side * offset, y: window.frame.minY))
|
|
}
|
|
#endif
|
|
window.makeKeyAndOrderFront(nil)
|
|
NSApp.requestUserAttention(.informationalRequest)
|
|
}
|
|
#if DEBUG
|
|
if let index = CommandLine.arguments.firstIndex(of: "--mcp-validation-dir"), CommandLine.arguments.indices.contains(index + 1) {
|
|
let directory = URL(fileURLWithPath: CommandLine.arguments[index + 1])
|
|
try? Data(String(window.windowNumber).utf8).write(to: directory.appendingPathComponent("review-window-id"))
|
|
}
|
|
#endif
|
|
}
|
|
|
|
fileprivate func decide(_ id: String, model: BASICDevelopmentModel, apply: Bool) {
|
|
guard var proposal = current, proposal.id == id, proposal.status == "pending" else { return }
|
|
guard selected === model, model.documentID == documentID, model.sourceRevision == proposal.revision else {
|
|
proposal.status = "stale"; update(proposal); return
|
|
}
|
|
guard apply else { proposal.status = "cancelled"; update(proposal); return }
|
|
guard !model.editorLocked, let range = proposal.range(in: model.source),
|
|
let editor = model.assistantEditor, editor.window != nil, let manager = editor.undoManager else {
|
|
message = "Open the BASIC source editor and finish any active edit before applying."; return
|
|
}
|
|
let source = model.source as NSString
|
|
guard source.substring(with: range) == proposal.before else { proposal.status = "stale"; update(proposal); return }
|
|
let revised = source.replacingCharacters(in: range, with: proposal.after)
|
|
// Remote decisions can arrive in the same AppKit event group. Give each
|
|
// approved replacement a top-level Undo without absorbing earlier typing.
|
|
let automaticGroups = manager.groupsByEvent
|
|
guard !manager.isUndoing, !manager.isRedoing, manager.groupingLevel <= (automaticGroups ? 1 : 0)
|
|
else { message = "Finish the current editor operation before applying."; return }
|
|
editor.breakUndoCoalescing()
|
|
if manager.groupingLevel == 1 { manager.endUndoGrouping() }
|
|
manager.groupsByEvent = false
|
|
manager.beginUndoGrouping()
|
|
defer {
|
|
manager.endUndoGrouping()
|
|
manager.groupsByEvent = automaticGroups
|
|
}
|
|
let action = BASICEditorAction(expectedSource: model.source, operation: .replace(source: revised, undoName: "Assistant BASIC Edit"))
|
|
guard editor.applyEditorAction(action, revealReplacementAt: range.location),
|
|
model.source == revised else { message = "The source editor could not apply this edit."; return }
|
|
proposal.status = "applied"
|
|
proposal.appliedRevision = model.sourceRevision
|
|
message = nil
|
|
update(proposal)
|
|
}
|
|
|
|
fileprivate func undo(_ id: String, model: BASICDevelopmentModel) {
|
|
guard var proposal = current, proposal.id == id, proposal.status == "applied", selected === model,
|
|
documentID == model.documentID, proposal.appliedRevision == model.sourceRevision,
|
|
!model.editorLocked, let editor = model.assistantEditor, let manager = editor.undoManager,
|
|
manager.canUndo, manager.undoActionName == "Assistant BASIC Edit" else { return }
|
|
manager.undo()
|
|
guard let range = proposal.range(in: model.source),
|
|
(model.source as NSString).substring(with: range) == proposal.before else { return }
|
|
proposal.status = "undone"; update(proposal)
|
|
}
|
|
|
|
fileprivate func run(_ id: String, model: BASICDevelopmentModel, both: Bool) {
|
|
guard let proposal = current, proposal.id == id, proposal.status == "applied", !guest.busy,
|
|
selected === model, documentID == model.documentID, proposal.appliedRevision == model.sourceRevision else { return }
|
|
guard !both || Self.isRevisedPlanetExample(model.source) else { return }
|
|
let owner = sessionID
|
|
Task { [self, model] in
|
|
await guest.start(model: model, bothChoices: both, isCurrent: { [weak self, weak model] in
|
|
guard let self, let model else { return false }
|
|
return self.sessionID == owner && self.selected === model && self.documentID == model.documentID
|
|
&& self.current?.id == id && self.current?.status == "applied" && proposal.appliedRevision == model.sourceRevision
|
|
})
|
|
}
|
|
}
|
|
|
|
fileprivate static func isRevisedPlanetExample(_ source: String) -> Bool {
|
|
let before = "90 PALETTE 6,37:M$=\"Hello Cold Red Dot World!\""
|
|
let after = "90 PALETTE 6,37:M$=\"Bring a warm coat!\""
|
|
let starter = BASICLanguage.sample
|
|
guard starter.contains(before) else { return false }
|
|
let revised = starter.replacingOccurrences(of: before, with: after)
|
|
return revised.split(whereSeparator: \.isNewline) == source.split(whereSeparator: \.isNewline)
|
|
}
|
|
|
|
#if DEBUG
|
|
private func captureFixtureContent(_ window: NSWindow, to file: URL) {
|
|
guard let content = window.contentView else { return }
|
|
content.layoutSubtreeIfNeeded()
|
|
content.displayIfNeeded()
|
|
guard let bitmap = content.bitmapImageRepForCachingDisplay(in: content.bounds) else { return }
|
|
content.cacheDisplay(in: content.bounds, to: bitmap)
|
|
try? bitmap.representation(using: .png, properties: [:])?.write(to: file)
|
|
}
|
|
|
|
/// Available only after the app delegate has created an isolated interface-validation machine.
|
|
func validate(model: BASICDevelopmentModel, other: BASICDevelopmentModel, in directory: URL) async throws {
|
|
var info = stat()
|
|
guard lstat(directory.path, &info) == 0, (info.st_mode & S_IFMT) == S_IFDIR, info.st_uid == geteuid(),
|
|
info.st_mode & 0o077 == 0 else { throw POSIXError(.EACCES) }
|
|
let args = CommandLine.arguments
|
|
let review = args.firstIndex(of: "--mcp-edit-review").flatMap { args.indices.contains($0 + 1) ? args[$0 + 1] : nil }
|
|
let regression = review != nil && args.contains("--mcp-review-regression")
|
|
regressionFixture = regression
|
|
if regression {
|
|
try Data().write(to: directory.appendingPathComponent("regression-fixture"), options: .withoutOverwriting)
|
|
}
|
|
if let review {
|
|
fixtureLabel = review
|
|
if let i = args.firstIndex(of: "--mcp-rom-dir"), args.indices.contains(i + 1) {
|
|
try await MCPBASICRun.bootFixture(model.machine, romDirectory: URL(fileURLWithPath: args[i + 1]))
|
|
}
|
|
model.source = regression && args.contains("--mcp-blank-draft") ? "" : BASICLanguage.sample
|
|
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1050, height: 720),
|
|
styleMask: [.titled, .resizable, .miniaturizable], backing: .buffered, defer: false)
|
|
window.title = "BASIC Development — " + review
|
|
let content = NSHostingView(rootView: BASICDevelopmentView(model: model))
|
|
content.sizingOptions = []
|
|
window.contentView = content
|
|
window.center()
|
|
fixtureEditor = window
|
|
if regression { window.orderBack(nil) } else { window.orderFront(nil) }
|
|
content.layoutSubtreeIfNeeded()
|
|
} else {
|
|
model.source = "10 REM MCP LOCAL PROOF\n20 PRINT 6*7\n"
|
|
}
|
|
other.source = "10 REM PRIVATE UNSHARED EXAMPLE\n"
|
|
let path = directory.appendingPathComponent("grant.json")
|
|
try Data(other.documentID.uuidString.utf8).write(to: directory.appendingPathComponent("other-id"), options: .withoutOverwriting)
|
|
try await grant(model, at: path, proposals: review != nil)
|
|
if review == nil { show(for: model) }
|
|
if let id = panel?.windowNumber, id > 0 {
|
|
try Data(String(id).utf8).write(to: directory.appendingPathComponent("panel-window-id"), options: .withoutOverwriting)
|
|
if CommandLine.arguments.contains("--mcp-capture-panel") {
|
|
if let panel { captureFixtureContent(panel, to: directory.appendingPathComponent("access.png")) }
|
|
}
|
|
}
|
|
fixturePoll = Task { @MainActor [weak self] in
|
|
func consume(_ name: String) -> Bool { unlink(directory.appendingPathComponent(name).path) == 0 }
|
|
func mark(_ name: String) { try? Data().write(to: directory.appendingPathComponent(name)) }
|
|
while !Task.isCancelled {
|
|
try? await Task.sleep(nanoseconds: 200_000_000)
|
|
guard let self, !Task.isCancelled else { return }
|
|
if consume("revoke") { await self.revoke().value; mark("revoked") }
|
|
if (review == nil || regression), consume("edit") { model.source += review == nil ? "30 REM UPDATED DRAFT\n" : "9000 REM UPDATED DRAFT\n"; mark("edited") }
|
|
if consume("reconnect") {
|
|
do { try await self.grant(model, at: path, proposals: review != nil); mark("reconnected") }
|
|
catch { NSLog("MCP fixture reconnection failed: %@", error.localizedDescription) }
|
|
}
|
|
if regression, let proposal = self.current {
|
|
if consume("apply") { self.decide(proposal.id, model: model, apply: true); mark("applied") }
|
|
if consume("cancel") { self.decide(proposal.id, model: model, apply: false); mark("cancelled") }
|
|
if consume("undo") { self.undo(proposal.id, model: model); mark("undone") }
|
|
if consume("save-reopen"), proposal.status == "applied" {
|
|
let target = directory.appendingPathComponent("Reviewed.bas")
|
|
let reopened = BASICDevelopmentModel(machine: model.machine, directory: directory.appendingPathComponent("Reopened Workspace"))
|
|
if !FileManager.default.fileExists(atPath: target.path), model.saveSource(to: target),
|
|
reopened.openSource(at: target), reopened.source == model.source, !reopened.dirty {
|
|
mark("saved-and-reopened")
|
|
}
|
|
}
|
|
if consume("run-both") { self.run(proposal.id, model: model, both: true); mark("run-started") }
|
|
if consume("run") { self.run(proposal.id, model: model, both: false); mark("run-started") }
|
|
if consume("capture-review"), let window = self.reviewWindow {
|
|
window.orderFront(nil)
|
|
try? await Task.sleep(for: .milliseconds(350))
|
|
self.captureFixtureContent(window, to: directory.appendingPathComponent("review.png"))
|
|
window.orderOut(nil)
|
|
}
|
|
if consume("capture-result"), self.guest.receipt != nil, let window = self.reviewWindow {
|
|
window.setContentSize(NSSize(width: 640, height: 480))
|
|
window.orderFront(nil)
|
|
try? await Task.sleep(for: .milliseconds(400))
|
|
let capture = Process()
|
|
capture.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
|
|
capture.arguments = ["-x", "-o", "-l", String(window.windowNumber), directory.appendingPathComponent("verified.png").path]
|
|
capture.terminationHandler = { _ in Task { @MainActor in window.orderOut(nil) } }
|
|
do { try capture.run() } catch { window.orderOut(nil) }
|
|
}
|
|
}
|
|
if consume("quit") {
|
|
await self.revoke().value
|
|
if review == nil || regression { model.source = model.savedSource }
|
|
other.source = other.savedSource
|
|
// AppKit's termination loop must be entered from a run-loop event,
|
|
// so the main actor remains available to finish asynchronous shutdown.
|
|
NSApp.perform(#selector(NSApplication.terminate(_:)), with: nil, afterDelay: 0)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
#endif
|
|
}
|
|
|
|
struct MCPGrantFile {
|
|
let url: URL
|
|
let device: dev_t
|
|
let inode: ino_t
|
|
|
|
init(create url: URL, data: Data) throws {
|
|
let fd = open(url.path, O_CREAT | O_WRONLY | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)
|
|
guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) }
|
|
let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
|
var info = stat()
|
|
do {
|
|
guard fstat(fd, &info) == 0 else { throw POSIXError(.EIO) }
|
|
try file.write(contentsOf: data)
|
|
try file.close()
|
|
} catch {
|
|
unlink(url.path)
|
|
throw error
|
|
}
|
|
self.url = url
|
|
device = info.st_dev
|
|
inode = info.st_ino
|
|
}
|
|
|
|
func remove() {
|
|
var info = stat()
|
|
if lstat(url.path, &info) == 0 && info.st_dev == device && info.st_ino == inode { unlink(url.path) }
|
|
}
|
|
}
|
|
|
|
private struct MCPAccessView: View {
|
|
@ObservedObject var access: MCPAccess
|
|
@ObservedObject var model: BASICDevelopmentModel
|
|
@State private var proposals = false
|
|
var body: some View {
|
|
VStack(alignment: .leading, spacing: 12) {
|
|
Label(model.title, systemImage: "doc.text").font(.headline)
|
|
Text("A local assistant with the connection file can read this BASIC draft, including unsaved edits, search the installed manuals, and check the guest processor and mounted drive status. Its model provider may receive that text.")
|
|
|
|
if let name = access.activeTitle, access.selected !== model {
|
|
Label("Another BASIC editor is sharing \(name).", systemImage: "link")
|
|
Button("Revoke That Connection") { access.revoke() }
|
|
} else if let name = access.activeTitle {
|
|
Label("Sharing: \(name)", systemImage: "link").accessibilityIdentifier("mcp.access.active")
|
|
if let file = access.grantFile {
|
|
MCPChatGPTSetup(grantURL: file.url, firstPrompt: "Use VCC Plus to identify my shared BASIC draft and read its source. Tell me its title and what the program does.")
|
|
}
|
|
if access.canPropose {
|
|
Text("Edits require native review. Starting a reviewed run permits bounded guest input and inspection of its screen, debugger registers, watches and program memory.")
|
|
if access.current != nil { Button("Show Edit Review…") { access.showReview(model) } }
|
|
}
|
|
Button("Revoke Access") { access.revoke() }.accessibilityIdentifier("mcp.access.revoke")
|
|
} else {
|
|
Toggle("Allow proposed edits and controls for runs I start", isOn: $proposals)
|
|
Button(proposals ? "Save Review and Run Connection…" : "Save Read-Only Connection…") {
|
|
access.chooseGrant(for: model, proposals: proposals)
|
|
}.accessibilityIdentifier("mcp.access.grant")
|
|
}
|
|
if let message = access.message { Text(message).foregroundStyle(.secondary) }
|
|
}.padding(18).frame(maxWidth: .infinity, alignment: .leading)
|
|
}
|
|
}
|
|
|
|
private struct MCPReviewView: View {
|
|
@ObservedObject var access: MCPAccess
|
|
@ObservedObject var model: BASICDevelopmentModel
|
|
@ObservedObject var guest: MCPBASICRun
|
|
|
|
var body: some View {
|
|
if let p = access.current {
|
|
VStack(alignment: .leading, spacing: 13) {
|
|
Label(model.title, systemImage: "doc.text").font(.headline)
|
|
if let revision = p.appliedRevision {
|
|
Text("\(p.subject) · Reviewed revision \(p.revision) → applied revision \(revision)").foregroundStyle(.secondary)
|
|
} else {
|
|
Text("\(p.subject) · Draft revision \(p.revision)").foregroundStyle(.secondary)
|
|
}
|
|
line(p.appliedRevision == nil ? "Current" : "Before", p.before, color: .red, listing: p.line == nil)
|
|
line(p.appliedRevision == nil ? "Proposed" : "Applied", p.after, color: .green, listing: p.line == nil)
|
|
switch p.status {
|
|
case "pending":
|
|
HStack {
|
|
Button("Cancel Edit") { access.decide(p.id, model: model, apply: false) }
|
|
Button("Apply Edit") { access.decide(p.id, model: model, apply: true) }.buttonStyle(.borderedProminent)
|
|
}
|
|
case "applied":
|
|
Text("Applied to the BASIC draft.").font(.headline)
|
|
HStack {
|
|
Button("Undo Edit") { access.undo(p.id, model: model) }
|
|
Button("Run") { access.run(p.id, model: model, both: false) }
|
|
if MCPAccess.isRevisedPlanetExample(model.source) {
|
|
Button("Run Both Choices") { access.run(p.id, model: model, both: true) }
|
|
.help("Verify the Earth and revised Mars greetings, their backgrounds, and a fresh PRINT 7 command.")
|
|
}
|
|
}.disabled(guest.busy || p.appliedRevision != model.sourceRevision)
|
|
if !guest.status.isEmpty { Text(guest.status).textSelection(.enabled) }
|
|
if let branches = guest.receipt?["branches"] as? [[String: Any]] {
|
|
ForEach(branches.indices, id: \.self) { index in
|
|
let branch = branches[index]
|
|
if let rgb = branch["background_rgb"] as? String, let value = UInt32(rgb.dropFirst(), radix: 16),
|
|
let text = branch["greeting"] as? String {
|
|
HStack(spacing: 8) {
|
|
RoundedRectangle(cornerRadius: 3)
|
|
.fill(Color(red: Double(value >> 16 & 255) / 255, green: Double(value >> 8 & 255) / 255, blue: Double(value & 255) / 255))
|
|
.frame(width: 18, height: 18).accessibilityHidden(true)
|
|
Text(branch["key"] as? String == "2" ? "Mars" : "Earth").fontWeight(.semibold)
|
|
Text(text.trimmingCharacters(in: .whitespaces))
|
|
Text(rgb).font(.system(.caption, design: .monospaced))
|
|
}.textSelection(.enabled)
|
|
}
|
|
}
|
|
}
|
|
if let message = model.message { Text(message).foregroundStyle(.secondary) }
|
|
case "stale": Text("The draft changed. Ask the assistant to read it again and propose a fresh edit.")
|
|
case "undone": Text("Edit undone.")
|
|
default: Text("Edit cancelled.")
|
|
}
|
|
if let message = access.message { Text(message).foregroundStyle(.secondary) }
|
|
}.padding(18).frame(maxWidth: .infinity, alignment: .leading)
|
|
.onChange(of: model.sourceRevision) { _, _ in access.refreshProposal(model) }
|
|
}
|
|
}
|
|
|
|
private func line(_ label: String, _ text: String, color: Color, listing: Bool) -> some View {
|
|
VStack(alignment: .leading, spacing: 4) {
|
|
Text(label).font(.caption.weight(.semibold))
|
|
if listing && text.isEmpty {
|
|
Text("Empty draft").foregroundStyle(.secondary)
|
|
} else if listing && text.components(separatedBy: .newlines).count > 5 {
|
|
ScrollView {
|
|
Text(verbatim: text).frame(maxWidth: .infinity, alignment: .leading)
|
|
.font(.system(.body, design: .monospaced)).textSelection(.enabled)
|
|
}.frame(height: 110)
|
|
} else {
|
|
Text(verbatim: text).font(.system(.body, design: .monospaced)).textSelection(.enabled)
|
|
}
|
|
}.padding(9).frame(maxWidth: .infinity, alignment: .leading).background(color.opacity(0.10), in: RoundedRectangle(cornerRadius: 5))
|
|
}
|
|
}
|