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. Each chunk arrives twice — a machine pair has two connections and the replay ring exempts these two types — soReassemblerkeeps its own ring of chunkIds; keying reassembly by sender rather than by socket is what makes the duplicate visible (§10.7 note 11). 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, idWindow: 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 sendChunks(payload: Data, isImage: Bool) // paced, see beginChunkedSend
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 beginChunkedSend(_ packets: [Packet],
forward: @escaping @Sendable ([Packet]) async -> Void)
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.- In-band chunks are paced, 128 packets every 5 ms. A 1 MB payload is
21 846 packets; handing them to
ControlChannel.forwardin one loop overruns the 512-packet outbox contracts C3 allows and closes the connection, and puts a second of clipboard traffic in front of the next mouse packet. Windows paces naturally —SendClipboardDataUsingTCPwrites each packet down a blocking socket from its own thread (Clipboard.cs:260-305) — andbeginChunkedSendis that thread. A second copy cancels the first, because two interleaved payloads would arrive as one corrupt stream. 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).
Reassemblerde-duplicates by chunkId. Found while re-reading the first pass: a peer pair has two control connections,SkSendwrites the same chunk to both, andPreProcessexemptsClipboardTextandClipboardImagefrom the replay ring — so a reassembly keyed by sending machine, as ours is, interleaves the two copies and corrupts the payload where Windows's socket-keyed loop merely does the work twice (§10.7 note 11).- The download folder is created on the first received file, not at startup, so an app that never receives one leaves the Desktop alone.
- The offer is cleared before a new copy is examined, and the 20 MB text
and 50 MB image caps live in the pasteboard reader where
FormHelper.cs:204-210, 287puts them — both found re-reading the first pass, where a branch that decided not to share left the previous payload on offer. - In-band chunks are paced. Also found re-reading the first pass: the
obvious
chunkPackets(...).map { .send($0) }puts up to 21 846 packets into a 512-packet outbox at once, which contracts C3 answers by closing the connection — so anything over about 24 KB of clipboard would have killed the control connection instead of copying.
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; the same chunk stream delivered twice, interleaved, collapsing to one payload; an untagged blob read as plain text. 170 checks, 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.
QA log
2026-09-16 — QA
Read CLAUDE.md, docs/protocol.md §2.3/§6/§10.7, docs/contracts.md
C1–C4 and this README end to end, then git diff 18c9702..HEAD. Ran
tools/gates.sh — all three gates green (swift-format lint --strict,
MWBCore layering, swift build -Xswiftc -warnings-as-errors). Built
only; nothing here touched the real pasteboard, opened a live listener
beyond what the codec/loopback harnesses in the work log already
exercised, launched the app, or wrote to ~/Desktop (invariant 5).
Per-tick verification against the Windows source, reading
Core/Clipboard.cs whole, Class/SocketStuff.cs:475-495, 1566-1931,
Helper/FormHelper.cs:180-330, Core/ReceivedDestinationFile.cs,
Core/Receiver.cs:273-380, Core/Event.cs:219-231 and
Core/Common.cs:1291-1330:
- Text/CF_HTML codec, 48-byte chunking,
Reassembler's duplicate-id ring: traced againstClipboard.cs:43-47, 190-201, 253-373, 1101-1194andReceiver.cs:40-82. The ring's reasoning holds —SkSendreally does write oneIdto both of a peer pair's control connections, andPreProcessreally does exemptClipboardText/ClipboardImagefrom the 50-entry ring (confirmed inSources/MWBCore/Sequencing.swift:87-91, unchanged by this lane) — so keying by sending machine and de-duplicating byIdis the right fix for the interleaving a socket-keyed loop never has to face. - Bulk handshake: the raw, unframed 64-byte
DATA, the bytes-1..3-zero check (BulkConnection.swift:230-241), and the trust gate before any payload (BulkConnection.swift:258-276) all matchClipboard.cs: 961-1066. Verified the less obvious half too:ShakeHandruns identically on both ends, so the connector also authorises what it reads back before it will send or receive — the port's.pulling/.pushingroles go through the sameacceptHandshake/authorisepath as.accepted, which is correct and not just incidental. - 1024-byte header, error forms, 1 MB chunks, 32-byte padding: the
trailingPaddingformula (block - (length % block)) matchesSendFileEx'sPACKAGE_SIZE - (sentCount % PACKAGE_SIZE)(SocketStuff.cs:1832-1836) bit for bit, including the case the formula name doesn't advertise — a body already block-aligned still gets a full 32-byte pad, which is what Windows does too since theif (...> 0)guard is never false for a% PACKAGE_SIZEcomputed this way. ReceivedFilestaging/commit/discard and path-traversal:fileName (fromHeaderName:)strips both separators and refuses./..(ClipboardCodec.swift:262-266), and the staged file's random name is independent of the attacker-controlled header name, so traversal cannot reach outside the download folder.- 100 MB limit and folder refusal, the 30 s window, pull-on-
MachineSwitchedvs ask/push, pasteboard polling/quiet-period/ own-write suppression,ShareClipboard/TransferFilegating: each traced to itsCheckClipboardEx(Clipboard.cs:85-251) orReceiver.cs:273-380counterpart and found correct, including the easy-to-miss ones —Clipboard (69)really is un-addressed (ClipboardBridge.swift:190-195applies noDescheck, matchingReceiver.cs:273-282), andMachineSwitched/ClipboardAskreally are gated onDes == localID(:197-207, matching:284-291, 318). - The four
Engine.dispatch/EngineActionscall sites the dev added beyond the brief: minimal and correct. Each is exactly the one line the README's Handshakes section says it is, at the point app-engine had already marked;.machineSwitchedrouting intoclipboardDispatchis right because Windows's ownMachineSwitchedcase inReceiver.csdoes nothing but the clipboard-pull check — there is no other received-side handling for that packet to preserve. - C1:
chunkPacketsreturns unstamped packets;forwardClipboardBatchstamps each once via the Engine's sharedstampAndForwardand hands identical bytes to every target session (ClipboardBridge.swift: 488-492). No clipboard path re-stamps a forwarded packet. - Invariant 2, checked end to end on the bulk connection: nothing is
read from
inboxinto.header/.bodyphase, and nothing is written to a file or the pasteboard, beforeauthorised(true)returns from the Engine (BulkConnection.swift:173-178, 258-276). - No clipboard content or the security key is logged anywhere in the
five changed files — checked every
Log.engine.*andfail(...)call site; all carry machine names, filenames, byte counts or fixed strings, never payload bytes orsecurityKey.
Findings (none block CP2; see below).
Sources/MWBNet/BulkChannel.swift:104-112vsApp/Core/Clipboard.cs:375, 925-941andApp/Class/SocketStuff.cs: 1655-1665. Windows serialises clipboard receives to exactly one at a time, process-wide, with a real mutex (ClipboardReceiveGate = new SemaphoreSlim(1, 1)): both the pull path (ReceiveAndProcessClipboardDataafter dialling out) and the accept-a-push path (SendOrReceiveClipboardData) wait on it, and a second concurrent receive is rejected — socket closed, "Rejecting clipboard transfer because the previous transfer is still active."BulkChannel.connectionLimit = 4is not that: it caps all bulk connections combined (both directions, any role) at four, so two peers pushing to this Mac (or one pushing while another is pulled from) can complete concurrently where Windows would drop the second. The doc comment aboveconnectionLimitcalls this "the equivalent bound" to the semaphore, which overstates it — it neither serialises nor caps receives specifically. Failure scenario: two of the three peers both copy a file within the same 30 s window and both end up pulled/pushed to/from this Mac at once; both transfers finish instead of one being rejected as Windows would reject it. Not a wire-format or trust problem — eachBulkConnectionis self-contained — but it is a silently un-ported behaviour and the comment's citation doesn't hold up.Sources/MWBMac/ReceivedFile.swift:58-61(stagingURL(in:)) is dead: nothing calls it.Sources/MWBNet/BulkConnection.swift: 336-339has its own privatestagingURL()instead, for the layering reason the README's "Five deviations" section gives — a good reason, but it leaves theReceivedFilecopy, which the README's "Promised" interface still lists as public API, unused by anything inSourcesorTests.Sources/MWBMac/Pasteboard.swift:123-126. The comment says the 20 MB gate is "measured on the tagged blob before compression" citingFormHelper.cs:204-210, but the code sumstext.plain?.count + text.rtf?.count + text.html?.count— the three flavour strings alone, without the"TXT"/"RTF"/"HTM"tags or the ~38-characterSEPGUID appended after each one Windows includes inst.Length. The undercount is at most a few hundred characters against a 20,000,000-character limit, so no realistic copy crosses it one way and not the other, but the comment claims more fidelity toFormHelper.csthan the code has.Sources/mwb/ClipboardBridge.swift:17.import AppKitis unused — noNS/CGsymbol appears anywhere in the file; every AppKit access already goes throughMWBMacas the file's own header comment says it should.Sources/MWBNet/BulkConnection.swift:397-409vsSources/mwb/ClipboardBridge.swift:143-160.localFiledecides "too big" vs "not found" once, at copy time.beginSendingindependently re-derives the file's size at send time and, on any failure there (deleted or grown past 100 MB since the copy), always reports"<path> not found!"— never"<path> - File too big...", which Windows's own send path preserves by re-testing the cached message string rather than the file (SocketStuff.cs: 1690-1697). Cosmetic only (still a well-formed"0*…"failure) and the window is narrow — a file would have to cross 100 MB in the 30 s between copy and a peer's pull — but it is a case Windows's message distinguishes and the port's doesn't.
No fixes applied — none of the above is a typo or a trivially wrong comment; findings 3 and 4 are the closest, but 3 is a behavioural question (what should the gate measure?) for the dev/lead to answer rather than a QA judgment call, and 4 is a one-line deletion that is still the dev's to make since it's their file.
Everything else — the four Engine call sites, the offer-clearing and size-cap fixes, the pacing, the padding formula, the CF_HTML wrap/ unwrap, the reassembler ring, the trust gate, the destination folder and its atomic commit — checked out against the Windows source with no further findings.
Verdict: PASS
Review
- 2026-09-16 (lead): inspected per
docs/loop.md§5. Gates green run by me; diff limited to the brief's files, the authorised Engine hooks (the four one-line calls beyond the brief are accepted — they are the minimal interface), TODO §8, protocol §10.7. ReadBulkConnection.acceptHandshake/authorised: raw 64-byteDATA, bytes 1..3 checked zero, name+id sent to the Engine for theresolveID == src && connectedgate before any header or payload — invariant 2 holds. The Dev's three self-found bugs (duplicate in-band delivery, outbox overflow, Windows' short padding) are real and each is cited. QA PASS with five follow-ups, moved to TODO §10. Verdict: merge. CP2 is now due alongside CP1. Carry into extras: the clipboard's open request to app-ui (transfer notifications) is extras' to do.