clipboard
Goal
Clipboard sharing as PowerToys does it (docs/protocol.md §6): text in
its three flavours, PNG images and single files, sent in-band over the
control channel when small and over the separate bulk connection on
port 15100 when large, pulled by the machine the user switches to or
pushed on request; received files land in ~/Desktop/MouseWithoutBorders/
exactly as on Windows. ShareClipboard and TransferFile gate it.
This lane ends at CP2.
Assumptions
Confirmed or corrected while porting; every correction is written up in
docs/protocol.md §10.7 with its citation.
- Formats (
Helper/FormHelper.cs:180-218, 269-330,Clipboard.cs: 1148-1194): text is"TXT"+plain+SEP+"RTF"+rtf+SEP+"HTM"+html+SEPin UTF-16LE, raw-DEFLATE compressed (Clipboard.cs:190-201). The HTML flavour on Windows is CF_HTML (§10.7 note 5); the wire form is whatClipboardText.htmlalways holds, andPasteboard.swiftwraps on send and unwraps on receive. Images are PNG bytes (FormHelper.cs:281);NSPasteboard.pngif present, else.tiffre-encoded viaNSBitmapImageRep. Files: exactly onefileURL; a directory is refused with the Windows message (SocketStuff.cs:1693). - Foundation's
.zlibis raw DEFLATE — verified in the scratchpad against Pythonzlib.decompress(d, -15)in both directions (§10.7 note 2).compression_streamwas not needed. - Small payloads (≤ 1 MB after compression,
Clipboard.cs:43) go in-band: 64-byteClipboardText (124)/ClipboardImage (125)packets with 48 payload bytes at offset 16,Des = ALL, terminated byClipboardDataEnd (76), last chunk zero-padded with no length field (Clipboard.cs:253-306). They are app-stamped and forwarded (C1). The receiver keeps oneReassemblerper sender; trailing zeros are part of the DEFLATE stream and the decoder tolerates them. The "abort after 100 interleaved foreign packets" rule is not ported — it is a property of the Windows blocking read loop, which we do not have; a size cap and a 30 s idle timeout take its place (§10.7 note 9). - Big payloads and files (
Clipboard.cs:498-923, 961-1060,SocketStuff.cs:1673-1811): on a local copy that is too big, or any file, the machine broadcastsClipboard (69)("I have big data") and remembersclipboardCopiedTime(30 s window,Clipboard.cs:42). When a peer is switched to (MachineSwitched (77),Receiver.cs: 284-291,Event.cs:219-231) and the source has fresh big data, the peer pulls: it connects to the source's port 15100, both sides exchange the cipher preamble (§2.3) and one 64-byteDATA, then the source writes the 1024-byte UTF-16LE header"<len>*<name>"and the bytes in 1 MB chunks, padded to 32 bytes; the puller reads exactlylen. If the puller has no outbound client to the source it asks withClipboardAsk (78)and the source pushes (ClipboardPush (79)as the firstDATA). That 64-byteDATAis raw, not framed — the lane's question (a), answered in §10.7 note 1 — so bytes 1..3 are zero and are checked to be. - Padding is load-bearing. Both bulk senders pad after the body
because a CBC stream holds back a final partial block. Windows's
SendDatapads by the wrong amount and truncates its own big text and image transfers (§10.7 note 4); we pad theSendFileExway for every payload, which a Windows receiver reads correctly because it takes exactly<len>bytes. - Destination:
~/Desktop/MouseWithoutBorders/<original name>, written to a hidden staging file in that same directory and renamed into place; incomplete transfers deleted, an existing destination kept until success (ReceivedDestinationFile.cs). The folder is created when the first file arrives, never at startup. Files100 MB refused with the Windows message (
Clipboard.cs:44). After a file lands its URL goes on the pasteboard (Clipboard.cs:864-868) and the folder is revealed in Finder (:840-848); Windows picks one or the other by post action and puts the non-drag-drop case in aScreenCapturessubfolder (§10.7 note 6).PostActionvalues (ClipboardPostAction.cs) travel unchanged but nothing branches on them:Mspaintand the drag-and-dropDesktoppath are out of scope (README D6). - Pasteboard watching: poll
changeCountevery 500 ms on a background queue; ignore changes within 1 s of the previous one (Clipboard.cs:100-107); ignore our own writes; only whenShareClipboardis on; files only whenTransferFileis on. Files are tested before text, unlike Windows, because a file copied in Finder also carries its path as a string. Windows's extra content-equality dedup (lastClipboardObject,:130-137, 206-213) is not ported:changeCountalready rises once per copy, and dropping a repeat copy of the same text would surprise a user who copied it again on purpose. - Receiving is not gated by
ShareClipboard, faithfully: Windows gates only the sending side (CheckClipboardEx), and neitherReceiveClipboardDataUsingTCPnorGetRemoteClipboardtests the setting. Turning sharing off stops this Mac's clipboard from leaving; it does not refuse a peer that pushes. - Ownership: the bulk listener and connections live in
MWBNet/BulkChannel.swift+BulkConnection.swifton their own queues and report throughBulkSink; the policy lives inmwb/ClipboardBridge.swift, which the Engine owns and calls. - Never act before trust: a bulk connection is authorised only when
the Engine says the handshake's machine name resolves to its
Srcin the pool and that id is connected (Clipboard.cs:1009). Nothing is read from or written to the connection in between (invariant 2).
Handshakes
Consumed
wire-core:Packet(payload48,postAction,machineName,setMachineName),PackageType,MachineID,CipherWriter,CipherReader,packageSizeEx.Framingis deliberately not used on the bulk connection (§10.7 note 1).session-matrix:MachinePool.resolveID(name:)/name(for:),Switcher.isConnected(to:),SwitchAction.remoteClipboardWanted,SocketStatus.control-channel:PeerStatus(name, status,isOutbound,address) — the "do we have a client socket to it" test and the address to dial port 15100 on.app-engine:Engine.dispatch,Engine.stampAndForward,Settings.shareClipboard/transferFile/tcpPort/securityKey,Log,EventTap.now().
Nothing consumed was changed.
Promised (to extras, polish)
As shipped 2026-09-16. Later lanes code against this, not against the sketch this section used to hold.
// MWBCore/ClipboardCodec.swift
public struct ClipboardText: Sendable, Equatable {
public var plain, rtf, html: String? // html is CF_HTML, the wire form
public init(plain: String? = nil, rtf: String? = nil, html: String? = nil)
public var isEmpty: Bool
}
public enum ClipboardContent: Sendable, Equatable {
case text(ClipboardText); case image(png: Data); case file(URL)
}
public enum ClipboardCodecError: Error, Sendable, Equatable {
case compressionFailed, decompressionFailed, notUTF16, malformedHeader
}
public enum ClipboardCodec {
public static let textSeparator: String // Clipboard.cs:47
public static let inBandLimit: Int // 1 MB
public static let maxFileSize: Int64 // 100 MB
public static let maxTextLength, maxImageSize: Int
public static let bigDataWindow, quietPeriod: TimeInterval // 30 s, 1 s
public static let bulkHeaderSize, bulkChunkSize: Int // 1024, 1 MB
public static let textStreamName, imageStreamName: String // "text", "image"
public static func encodeText(_:) throws -> Data
public static func decodeText(_:) throws -> ClipboardText
public static func htmlFragment(from cfHTML: String) -> String
public static func cfHTML(wrapping fragment: String) -> String
public static func chunkPackets(payload: Data, isImage: Bool) -> [Packet]
public static func bulkHeader(byteCount: Int64, name: String) -> Data
public static func parseBulkHeader(_:) throws -> (byteCount: Int64, name: String)
public static func fileName(fromHeaderName: String) -> String
public static func trailingPadding(forBodyLength: Int64) -> Int
public static func deflate(_:) throws -> Data
public static func inflate(_:) throws -> Data
public static func utf16LE(_:) -> Data
public static func string(fromUTF16LE:) throws -> String
}
public final class Reassembler { // one per sending machine
public static let sizeLimit: Int
public init(now: TimeInterval)
public func feed(_ packet: Packet, now: TimeInterval) -> Data? // payload on DataEnd
public private(set) var abandoned, isImage: Bool
public private(set) var lastChunk: TimeInterval
}
// MWBMac/Pasteboard.swift
public final class PasteboardWatcher: @unchecked Sendable {
public static let pollInterval: TimeInterval // 0.5
public init(onChange: @escaping @Sendable (ClipboardContent) -> Void)
public func start(); public func stop()
public func write(_ content: ClipboardContent)
}
// MWBMac/ReceivedFile.swift
public enum ReceivedFileError: Error, Sendable, Equatable {
case destinationUnavailable(String), commitFailed(String)
}
public enum ReceivedFile {
public static let folderName: String // "MouseWithoutBorders"
public static func destinationURL() -> URL // creates nothing
public static func destinationDirectory() throws -> URL
public static func stagingURL(in directory: URL) -> URL
@discardableResult public static func commit(
staged: URL, toFileNamed: String, in directory: URL) throws -> URL
public static func discard(_ staged: URL)
@MainActor public static func reveal(_ file: URL)
public static func size(of file: URL) -> Int64?
public static func isDirectory(_ url: URL) -> Bool
}
// MWBNet/BulkChannel.swift
public struct BulkConfig: Sendable, Equatable {
public var localName: String; public var localID: UInt32; public var port: UInt16
public var securityKey: String; public var stagingDirectory: URL
public var maxFileSize: Int64
public init(localName:localID:port:securityKey:stagingDirectory:maxFileSize:)
}
public enum BulkPayload: Sendable, Equatable {
case text(Data); case image(Data); case file(URL); case failure(String)
}
public enum BulkReceived: Sendable, Equatable {
case text(Data); case image(Data); case file(staged: URL, name: String)
}
public protocol BulkSink: AnyObject, Sendable {
func bulk(_ channel: BulkChannel, authorise peerName: String, peerID: UInt32,
reply: @escaping @Sendable (Bool) -> Void)
func bulk(_ channel: BulkChannel, received: BulkReceived, from peerName: String,
postAction: UInt32)
func bulk(_ channel: BulkChannel, failed reason: String)
}
public final class BulkChannel: @unchecked Sendable {
public static let idleTimeout: TimeInterval // 30
public static let chunkSize, connectionLimit: Int // 1 MB, 4
public init(config: BulkConfig, sink: BulkSink)
public func start(); public func stop(); public func reconfigure(_ new: BulkConfig)
public func serve(_ new: BulkPayload?)
public func pull(from address: String, peerName: String, postAction: UInt32)
public func push(to address: String, peerName: String, postAction: UInt32)
}
// mwb/ClipboardBridge.swift
public enum ClipboardAction: Sendable {
case send(Packet) // the Engine stamps it (C1)
case getRemoteClipboard(machine: String, postAction: UInt32)
case pushClipboard(machine: String, postAction: UInt32)
case commitFile(staged: URL, name: String)
case note(String)
}
public final class ClipboardBridge { // Engine-isolated, not Sendable
public init(config: BulkConfig, shareClipboard: Bool, transferFile: Bool,
relay: ClipboardRelay)
public func start(); public func stop()
public func apply(config: BulkConfig, shareClipboard: Bool, transferFile: Bool)
public func localCopy(_ content: ClipboardContent, now: TimeInterval) -> [ClipboardAction]
public func handle(_ packet: Packet, from peerName: String?, now: TimeInterval)
-> [ClipboardAction]
public func wantsRemoteClipboard(now: TimeInterval) -> [ClipboardAction]
public func received(_ content: BulkReceived, from peerName: String) -> [ClipboardAction]
public func announce(_ file: URL)
}
public final class ClipboardRelay: BulkSink, @unchecked Sendable {
public init(engine: Engine)
}
Five deviations from the shape this section sketched at planning time, all deliberate:
BulkChannelhas noserve(_:until:)and noisTrustedon the sink. Windows puts no expiry on the served payload — the 30 s window is the puller's rule (Receiver.cs:285) — soserve(_:)takes no deadline. Trust is asynchronous (authorise…reply:) because the answer lives on the Engine actor and a synchronous predicate would have forced the channel to keep a shadow copy of the pool and the connection set.BulkChannelnever touchesMWBMac. It streams a received file into a staging file insidestagingDirectoryand hands the URL back; the download folder, the atomic commit and the Finder reveal areMWBMac/ReceivedFile.swift, called by the Engine.MWBNetmay not importMWBMac(README D2), and the staging file must be on the same volume as the destination for the rename to be atomic.ClipboardBridgereturns[ClipboardAction]instead of calling the Engine. It is a non-Sendableproperty of theEngineactor, so it runs on the actor and cannot call back into it synchronously; theSwitcher→[SwitchAction]shape already in the codebase solves the same problem the same way, and it keeps packet stamping in the one place contracts C1 allows.PasteboardWatcherowns both directions. EveryNSPasteboard.generalaccess in the app is on its one serial queue, so a poll can never interleave with a write and mistake a received clipboard for a local copy. AppKit documents the general pasteboard as usable off the main thread; it is a window-server object, not a view.ReceivedFilehasdestinationURL()(pure) besidedestinationDirectory()(creates).BulkConfigneeds the path at startup, and nothing should appear on the user's Desktop until a file is actually on its way.
Requested of app-engine (taken provisionally — the lead rules at review)
The brief authorised the clipboard cases of Engine.dispatch and the
property holding the bridge. Four further one-line edits were needed for
the feature to be reachable at all, all in places the app-engine lane had
already marked for this lane. They are listed here rather than made
silently; revert them and the lane is inert.
Sources/mwb/Engine.swift,start():startClipboard(). Without it nothing ever builds the bridge, so the bulk listener never opens and the pasteboard is never watched.Sources/mwb/Engine.swift,stop():stopClipboard(), beforesayGoodbye(), so the listener and the watcher stop with everything else.Sources/mwb/EngineActions.swift,perform(_ action:):case .remoteClipboardWanted: pullRemoteClipboard(), replacing abreakwhose comment already read "the clipboard lane asks the machine we just left for its data".Sources/mwb/EngineActions.swift,applyConfiguration():applyClipboardConfiguration(), so aShareClipboard,TransferFile, port, key or identity change reaches the bridge on the same path every other config change takes.
If the lead prefers them elsewhere, the four calls are the whole interface; nothing else in those files was touched.
Requested of app-ui (open)
- Nothing shows a clipboard transfer. Windows has a tray-icon
animation and, under
ShowClipboardAndNetworkStatusMessages, a tooltip per transfer (Clipboard.cs:610-618, 878-881). The setting exists inSettingsand is read by nobody.Notifier.post(title: body:)is already published by app-ui, andClipboardAction.notecarries exactly the text; a.notethat reached the Notifier when the setting is on would close it. Left alone here:UIBridge.swiftandNotifications.swiftare app-ui's files.
Status / TODO
Sources/MWBCore/ClipboardCodec.swift: tag/SEP text codec, UTF-16LE, DEFLATE (verified raw), CF_HTML wrap/unwrap, 48-byte chunking,Reassembler(Clipboard.cs:43-47, 190-201, 253-373, 1148-1194,FormHelper.cs:180-330).Sources/MWBMac/Pasteboard.swift: watcher and writer per Assumptions (Clipboard.cs:100-107,FormHelper.cs).Sources/MWBMac/ReceivedFile.swift: staging + atomic commit + reveal (ReceivedDestinationFile.cs,Common.cs:1291-1330,Clipboard.cs:669-711, 840-848, 943-959).Sources/MWBNet/BulkChannel.swift+BulkConnection.swift: listener on port, pull/push connections, preamble, the 64-byteDATAexchange, 1024-byte header, chunked body, trust gate (Clipboard.cs:425-449, 498-923, 961-1060,SocketStuff.cs: 1673-1811, 1832-1836).Sources/mwb/ClipboardBridge.swift: policy (small → in-band, big/file →Clipboard (69)+ serve; onMachineSwitchedpull orClipboardAsk; 30 s window;ShareClipboard/TransferFile);Engine.swiftdispatch hooks (authorised) and four further hooks flagged above.docs/protocol.md: appended §10.7 (DEFLATE check, bulkDATAframing answer, CF_HTML, and six other findings), cited.- Checkpoint CP2 is the lead's after merge.
Not done, deliberately:
- Drag and drop, screen capture to Paint and the
ClipboardCapture/CaptureScreenCommand/ClipboardDragDrop*/ExplorerDragDroppacket types. Out of scope for v1 (README D6, protocol §6.4); they need the Windows shell helper process. The types are accepted and ignored inEngine.dispatch. OneWayClipboardMode(Clipboard.cs:95-98,SocketStuff.cs:1675-1679). Not in the settings schema README §Settings transcribes, and it only ever applies whenRunWithNoAdminRight— a Windows elevation concept with no macOS equivalent.- A progress indicator per transfer. Requested of app-ui above.
Work log
2026-09-16 — dev
Read CLAUDE.md, README.md, docs/protocol.md §2.3/§6/§10,
docs/contracts.md, docs/topo.md and the Handshakes of wire-core,
session-matrix, control-channel, app-engine and app-ui; then
Core/Clipboard.cs whole, Class/SocketStuff.cs:475-495, 1566-1931,
Helper/FormHelper.cs:170-340, Core/ReceivedDestinationFile.cs,
Core/ClipboardPostAction.cs, Core/Common.cs (112, 499-507, 617-620,
407-415, 1291-1330), Core/Receiver.cs:145-430 and Core/Event.cs:205-240.
The two questions the brief left open. Both are answered with
citations in docs/protocol.md §10.7 notes 1 and 2.
(a) Is the 64-byte DATA on the bulk connection framed? No — it is
raw. ShakeHand writes package.Bytes straight to the encrypting
stream (Clipboard.cs:987) rather than through TcpSendData, and reads
it back with package.Bytes = buf (:996-997), which marshals all four
type bytes. So there is no magic number and no checksum on this
connection; bytes 1..3 must be zero, and BulkConnection.acceptHandshake
checks them, because Packet.type only reads byte 0. What stands in for
framing is the key-derived cipher stream plus the
ResolveID(name) == Src && IsConnectedTo(Src) gate (:1009) — and
nothing is read or written until both pass (invariant 2).
(b) Is Foundation's .zlib the same stream as .NET DeflateStream?
Yes. In the scratchpad: a UTF-16LE tag/SEP fixture compressed with
(data as NSData).compressed(using: .zlib) starts ad 8e 3b 0a (no
78 xx zlib header, no 1f 8b gzip header); Python
zlib.decompress(bytes, -15) inflates it exactly, zlib.decompress(bytes)
fails with "incorrect header check", and bytes from Python's
compressobj(9, DEFLATED, -15) inflate correctly through
NSData.decompressed(using: .zlib). Trailing zeros are tolerated in both
directions, which matters twice over (§10.7 note 3). compression_stream
was not needed.
Decisions.
ClipboardBridgefollows theSwitchershape — decide, return[ClipboardAction], let the Engine act — because it is an actor-isolated property and cannot call back into the actor synchronously, and because only the Engine may stamp a packet (C1).BulkChannel's trust gate is asynchronous. The alternative was a shadow copy of the pool and the connected set insideMWBNet, kept in step by extra Engine hooks; onereply:closure is less machinery and cannot go stale.- Every bulk body is padded the
SendFileExway. Windows'sSendDatapads bysentCount % 32instead of32 - (sentCount % 32), which leaves 2–14 bytes inside the sender'sCryptoStreamfor 7 of every 8 payload lengths and truncates its own big text and image transfers (§10.7 note 4). Over-padding is invisible to a Windows receiver, which reads exactly<len>. - Received files all land in
~/Desktop/MouseWithoutBorders/, not in theScreenCapturessubfolder Windows uses for the non-drag-drop post action (§10.7 note 6), and are both put on the pasteboard and revealed. - The pasteboard is read files-first, unlike Windows, because Finder puts the path on as a string too.
- The "100 interleaved foreign packets" abort became a size cap plus an idle timeout: we have no blocking read loop for foreign packets to interleave with (§10.7 note 9).
- The download folder is created on the first received file, not at startup, so an app that never receives one leaves the Desktop alone.
Deviations from the brief. Four one-line calls outside the strictly
authorised set, all in Sources/mwb/Engine.swift and
Sources/mwb/EngineActions.swift and all at points the app-engine lane
had already marked for this lane. They are listed under Requested of
app-engine above and flagged in the lane report; without them nothing
starts the bridge and .remoteClipboardWanted stays a break.
Verification (scratchpad only — no pasteboard, no event tap, no real clipboard, no listener outside a few seconds on 127.0.0.1:51599):
- the DEFLATE interop check above;
- a codec harness: text round trip through all three flavours; CF_HTML
offsets checked byte-for-byte against the fragment they claim to
delimit; decoding with 137 bytes of zero padding appended; chunking and
reassembly at lengths 0, 1, 47, 48, 96 and 5000, each packet 64 bytes,
each result a zero-padded multiple of 48 with the payload as its
prefix; the 1024-byte header round trip including a Windows path, the
0*<message>error form and..\..traversal reduced to its last component; padding block-aligned for 0, 1, 15, 16, 31, 32, 119 and 1 048 577; theReassemblersize cap; an untagged blob read as plain text. All pass. - a two-channel loopback harness on 127.0.0.1:51599, up for six seconds: a text payload pulled and decoded correctly; a 5 000-byte file pushed and staged with the right size and name; a 3 MB image pulled across four chunks plus padding, byte count exact; and a peer the sink refuses rejected with "not a connected machine" before any payload moved.
tools/gates.sh green.