// Clips: a copy on one device is a paste on another, without iCloud// (owner, 14 Oct 2026). This file is the half every platform shares — what// a copy must be to become a clip, and the write. Watching a pasteboard is// the platform's: the Mac's `ClipboardWatch` (CottonHost) polls NSPasteboard's// change count, the phone reads on coming to the front.//// What never becomes a clip, in the order it is judged:// 1. an item the copying app marked concealed or transient// (nspasteboard.org) — judged on its TYPES, before its value is read;// 2. a value shaped like a secret or a card number — the core's// `engine::clips::refusal`, one rule for every device and for MCP, so the// create is refused and nothing is written;// 3. a text already among the clips (a clip tapped to copy it again comes// back to the clipboard; keeping it twice would push a real one out).//// The table rides a schema rise: until the database carries the Clips// definition, the keeper writes nothing.importCottonValuesimportFoundationimportCottonKit/// One copy a device saw, before it is a clip.publicstructCopiedText: Equatable, Sendable {publicvar text: String/// The pasteboard type identifiers the copied item carries.publicvar types: Set<String>/// The app it was copied in, when the platform says.publicvar sourceApp: String?/// This device's name.publicvar sourceDevice: String?publicvar copiedAt: Datepublicinit(text: String, types: Set<String>, sourceApp: String? = nil, sourceDevice: String? = nil, copiedAt: Date = Date()) {self.text = textself.types = typesself.sourceApp = sourceAppself.sourceDevice = sourceDeviceself.copiedAt = copiedAt }}publicenumClipCapture {/// The Clips table's definition id.publicstaticlet table = "clip"/// Whether the copying app asked every reader not to keep this item.publicstaticfunc refuses(types: Set<String>) -> Bool { !types.isDisjoint(with: PasteboardMark.skipped) }/// What the device detects the text to be — one of the crate's kinds/// (`engine::clips::KINDS`): the whole text a link, an email address, a/// postal address, a phone number or a date, else text.publicstaticfunc kind(of text: String) -> String {let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)guard !trimmed.isEmpty, trimmed.count <= ClipCaptureKnobs.detectedUpTo else { return"text" }let whole = NSRange(trimmed.startIndex..., in: trimmed)let types: NSTextCheckingResult.CheckingType = [.link, .address, .phoneNumber, .date]guardlet detector = try? NSDataDetector(types: types.rawValue),let match = detector.firstMatch(in: trimmed, options: [], range: whole), match.range == whole else { return"text" }switch match.resultType {case .link: return match.url?.scheme == "mailto" ? "email" : "link"case .address: return"address"case .phoneNumber: return"phone"case .date: return"date"default: return"text" } }/// The create a copy is written with.staticfunc data(_ copied: CopiedText) -> [String: RecordValue] {var data: [String: RecordValue] = ["text": .text(copied.text),"kind": .text(kind(of: copied.text)),"copied_at": .text(CottonDate.format(copied.copiedAt)), ]iflet app = copied.sourceApp, !app.isEmpty { data["source_app"] = .text(app) }iflet device = copied.sourceDevice, !device.isEmpty { data["source_device"] = .text(device) }return data }}/// Writes copies as clips into one database (the person's own).public actor ClipKeeper {privatelet store: any Recordsprivatevar hasClips = falseprivatevar lookedAt: Date?publicinit(store: any Records) {self.store = store }/// Keep the copy as a clip, unless it is one of the three that never/// become a clip (the file's header) or the database has no Clips yet./// Answers whether a clip was written; a refusal is not an error. @discardableResultpublicfunc keep(_ copied: CopiedText, now: Date = Date()) async -> Bool {guard !ClipCapture.refuses(types: copied.types), !copied.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,await carriesClips(now: now) else { returnfalse }iflet held = try? await store.list(table: ClipCapture.table, project: nil, query: nil, page: 0, where: [:]), held.records.contains(where: { $0["text"].text == copied.text }) {returnfalse }do { _ = tryawait store.create(table: ClipCapture.table, data: ClipCapture.data(copied))returntrue } catch {// The core refused it (a secret's shape, too long) or the write// failed: either way the copy is not kept, and nothing is said —// a clipboard is read in the background.returnfalse } }/// Whether this device's own row lets it keep copies: its `column`/// (`clips_on_open` on a phone, off unless turned on; `clips_watch` on a/// Mac, on unless turned off), or `otherwise` while the row carries no/// such column — a file before the rise that adds them.publicfunc deviceAllows(_ column: String, device: String?, otherwise: Bool) async -> Bool {guardlet device, let row = try? await store.get(table: "device", id: device) else { return otherwise }switch row[column] {case .bool(let on): return oncase .number(let value): return value != 0default: return otherwise } }/// The clips held, newest first — every device's, as synced here; none/// while the database has no Clips.publicfunc newest(now: Date = Date()) async -> [(text: String, device: String?)] {guardawait carriesClips(now: now),let page = try? await store.list(table: ClipCapture.table, project: nil, query: nil, page: 0, where: [:])else { return [] }return page.records .sorted { ($0["copied_at"].text ?? "") > ($1["copied_at"].text ?? "") } .compactMap { record in record["text"].text.map { ($0, record["source_device"].text) } } }/// Whether the database carries the Clips definition, asked again at most/// once a minute while it does not (the table arrives with a rise).privatefunc carriesClips(now: Date) async -> Bool {if hasClips { returntrue }iflet lookedAt, now.timeIntervalSince(lookedAt) < ClipCaptureKnobs.lookAgainAfter { returnfalse } lookedAt = now hasClips = (try? await store.tableDefinitions().contains { $0.id == ClipCapture.table }) ?? falsereturn hasClips }}/// The sizes and timings Clips works with: Swift's own, beside their reader.enumClipCaptureKnobs {/// Longer texts are text: a detector over a document is slow and never/// finds one link that IS the whole of it.staticlet detectedUpTo = 2_000/// How long a database without Clips is left before it is asked again.staticlet lookAgainAfter: TimeInterval = 60}