import Foundation import HelderCore import HelderServices import Observation /// The clean-copy popup: text the agent wrote to `.clean-copy`, editable before it is copied. @Observable @MainActor public final class CleanCopyStore { public static let fileName = CleanCopy.fileName /// The popup's text, with the user's edits. public var text = "" /// The text as it arrived, so an edit can be told apart. public private(set) var received = "" /// The newest text waiting for the popup, while another overlay is open. public private(set) var pending: String? /// The file's last contents Helder saw; nil before the first read or while the file is missing. @ObservationIgnored private var lastSeen: String? @ObservationIgnored private let files: FileServicing public init(files: FileServicing) { self.files = files } public var isEdited: Bool { text != received } public var characterCount: Int { text.count } /// Project open: the file's current text is the baseline and never shows. public func loadBaseline() async { lastSeen = await read() } /// The file changed: returns true when it holds new text, which then waits in `pending`. @discardableResult public func fileChanged() async -> Bool { guard let contents = await read() else { return false } let isNew = CleanCopy.isNew(contents, lastSeen: lastSeen) lastSeen = contents if isNew { pending = contents } return isNew } /// Moves the pending text into the popup that is about to open. public func takePending() { guard let pending else { return } text = pending received = pending self.pending = nil } /// New text while the popup is open replaces it only when the user has not edited it. public func refreshOpenPopup() { if !isEdited { takePending() } pending = nil } private func read() async -> String? { try? await files.read(Self.fileName) } }