643 lines
35 KiB
Markdown
643 lines
35 KiB
Markdown
# 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+SEP`
|
||
in 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 what `ClipboardText.html` always holds, and `Pasteboard.swift`
|
||
wraps on send and unwraps on receive. Images are PNG bytes
|
||
(`FormHelper.cs:281`); `NSPasteboard` `.png` if present, else `.tiff`
|
||
re-encoded via `NSBitmapImageRep`. Files: exactly one `fileURL`; a
|
||
directory is refused with the Windows message (`SocketStuff.cs:1693`).
|
||
- **Foundation's `.zlib` is raw DEFLATE** — verified in the scratchpad
|
||
against Python `zlib.decompress(d, -15)` in both directions (§10.7
|
||
note 2). `compression_stream` was not needed.
|
||
- **Small payloads** (≤ 1 MB after compression, `Clipboard.cs:43`) go
|
||
in-band: 64-byte `ClipboardText (124)` / `ClipboardImage (125)`
|
||
packets with 48 payload bytes at offset 16, `Des = ALL`, terminated by
|
||
`ClipboardDataEnd (76)`, last chunk zero-padded with no length field
|
||
(`Clipboard.cs:253-306`). They are app-stamped and forwarded (C1).
|
||
The receiver keeps one `Reassembler` per 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 — so `Reassembler` keeps its own ring of
|
||
chunk `Id`s; 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 broadcasts `Clipboard (69)` ("I have big data") and
|
||
remembers `clipboardCopiedTime` (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-byte `DATA`, 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 exactly
|
||
`len`. If the puller has no outbound client to the source it asks with
|
||
`ClipboardAsk (78)` and the source **pushes** (`ClipboardPush (79)` as
|
||
the first `DATA`). That 64-byte `DATA` is **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
|
||
`SendData` pads by the wrong amount and truncates its own big text and
|
||
image transfers (§10.7 note 4); we pad the `SendFileEx` way 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. Files
|
||
> 100 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 a
|
||
`ScreenCaptures` subfolder (§10.7 note 6). `PostAction` values
|
||
(`ClipboardPostAction.cs`) travel unchanged but nothing branches on
|
||
them: `Mspaint` and the drag-and-drop `Desktop` path are out of scope
|
||
(README D6).
|
||
- **Pasteboard watching**: poll `changeCount` every 500 ms on a
|
||
background queue; ignore changes within 1 s of the previous one
|
||
(`Clipboard.cs:100-107`); ignore our own writes; only when
|
||
`ShareClipboard` is on; files only when `TransferFile` is 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:
|
||
`changeCount` already 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 neither
|
||
`ReceiveClipboardDataUsingTCP` nor `GetRemoteClipboard` tests 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.swift` on their own
|
||
queues and report through `BulkSink`; the policy lives in
|
||
`mwb/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 `Src` in
|
||
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`. `Framing` is 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.
|
||
|
||
```swift
|
||
// 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:
|
||
|
||
- **`BulkChannel` has no `serve(_:until:)` and no `isTrusted` on the
|
||
sink.** Windows puts no expiry on the served payload — the 30 s window
|
||
is the *puller's* rule (`Receiver.cs:285`) — so `serve(_:)` 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.
|
||
- **`BulkChannel` never touches `MWBMac`.** It streams a received file
|
||
into a staging file inside `stagingDirectory` and hands the URL back;
|
||
the download folder, the atomic commit and the Finder reveal are
|
||
`MWBMac/ReceivedFile.swift`, called by the Engine. `MWBNet` may not
|
||
import `MWBMac` (README D2), and the staging file must be on the same
|
||
volume as the destination for the rename to be atomic.
|
||
- **`ClipboardBridge` returns `[ClipboardAction]` instead of calling the
|
||
Engine.** It is a non-`Sendable` property of the `Engine` actor, so it
|
||
runs on the actor and cannot call back into it synchronously; the
|
||
`Switcher` → `[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.
|
||
- **`PasteboardWatcher` owns both directions.** Every
|
||
`NSPasteboard.general` access 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.forward` in 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 — `SendClipboardDataUsingTCP`
|
||
writes each packet down a blocking socket from its own thread
|
||
(`Clipboard.cs:260-305`) — and `beginChunkedSend` is that thread. A
|
||
second copy cancels the first, because two interleaved payloads would
|
||
arrive as one corrupt stream.
|
||
- **`ReceivedFile` has `destinationURL()` (pure) beside
|
||
`destinationDirectory()` (creates).** `BulkConfig` needs 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.
|
||
|
||
1. `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.
|
||
2. `Sources/mwb/Engine.swift`, `stop()`: `stopClipboard()`, before
|
||
`sayGoodbye()`, so the listener and the watcher stop with everything
|
||
else.
|
||
3. `Sources/mwb/EngineActions.swift`, `perform(_ action:)`:
|
||
`case .remoteClipboardWanted: pullRemoteClipboard()`, replacing a
|
||
`break` whose comment already read "the clipboard lane asks the
|
||
machine we just left for its data".
|
||
4. `Sources/mwb/EngineActions.swift`, `applyConfiguration()`:
|
||
`applyClipboardConfiguration()`, so a `ShareClipboard`,
|
||
`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)
|
||
|
||
1. **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 in `Settings` and is read by nobody. `Notifier.post(title:
|
||
body:)` is already published by app-ui, and `ClipboardAction.note`
|
||
carries exactly the text; a `.note` that reached the Notifier when the
|
||
setting is on would close it. Left alone here: `UIBridge.swift` and
|
||
`Notifications.swift` are app-ui's files.
|
||
|
||
## Status / TODO
|
||
|
||
- [x] `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`).
|
||
- [x] `Sources/MWBMac/Pasteboard.swift`: watcher and writer per
|
||
Assumptions (`Clipboard.cs:100-107`, `FormHelper.cs`).
|
||
- [x] `Sources/MWBMac/ReceivedFile.swift`: staging + atomic commit +
|
||
reveal (`ReceivedDestinationFile.cs`, `Common.cs:1291-1330`,
|
||
`Clipboard.cs:669-711, 840-848, 943-959`).
|
||
- [x] `Sources/MWBNet/BulkChannel.swift` + `BulkConnection.swift`:
|
||
listener on port, pull/push connections, preamble, the
|
||
64-byte `DATA` exchange, 1024-byte header, chunked body, trust
|
||
gate (`Clipboard.cs:425-449, 498-923, 961-1060`, `SocketStuff.cs:
|
||
1673-1811, 1832-1836`).
|
||
- [x] `Sources/mwb/ClipboardBridge.swift`: policy (small → in-band,
|
||
big/file → `Clipboard (69)` + serve; on `MachineSwitched` pull or
|
||
`ClipboardAsk`; 30 s window; `ShareClipboard`/`TransferFile`);
|
||
`Engine.swift` dispatch hooks (authorised) and four further hooks
|
||
flagged above.
|
||
- [x] `docs/protocol.md`: appended §10.7 (DEFLATE check, bulk `DATA`
|
||
framing 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*` / `ExplorerDragDrop`
|
||
packet types.** Out of scope for v1 (README D6, protocol §6.4); they
|
||
need the Windows shell helper process. The types are accepted and
|
||
ignored in `Engine.dispatch`.
|
||
- **`OneWayClipboardMode`** (`Clipboard.cs:95-98`,
|
||
`SocketStuff.cs:1675-1679`). Not in the settings schema README §Settings
|
||
transcribes, and it only ever applies when `RunWithNoAdminRight` — 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.**
|
||
|
||
- `ClipboardBridge` follows the `Switcher` shape — 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 inside `MWBNet`, kept in
|
||
step by extra Engine hooks; one `reply:` closure is less machinery and
|
||
cannot go stale.
|
||
- Every bulk body is padded the `SendFileEx` way. Windows's `SendData`
|
||
pads by `sentCount % 32` instead of `32 - (sentCount % 32)`, which
|
||
leaves 2–14 bytes inside the sender's `CryptoStream` for 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 the
|
||
`ScreenCaptures` subfolder 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).
|
||
- `Reassembler` de-duplicates by chunk `Id`. Found while re-reading the
|
||
first pass: a peer pair has two control connections, `SkSend` writes
|
||
the same chunk to both, and `PreProcess` exempts `ClipboardText` and
|
||
`ClipboardImage` from 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, 287` puts 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; the `Reassembler` size 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 against `Clipboard.cs:43-47, 190-201, 253-373,
|
||
1101-1194` and `Receiver.cs:40-82`. The ring's reasoning holds —
|
||
`SkSend` really does write one `Id` to both of a peer pair's control
|
||
connections, and `PreProcess` really does exempt `ClipboardText`/
|
||
`ClipboardImage` from the 50-entry ring (confirmed in
|
||
`Sources/MWBCore/Sequencing.swift:87-91`, unchanged by this lane) —
|
||
so keying by sending machine and de-duplicating by `Id` is 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 match `Clipboard.cs:
|
||
961-1066`. Verified the less obvious half too: `ShakeHand` runs
|
||
identically on both ends, so the *connector* also authorises what it
|
||
reads back before it will send or receive — the port's `.pulling`/
|
||
`.pushing` roles go through the same `acceptHandshake`/`authorise`
|
||
path as `.accepted`, which is correct and not just incidental.
|
||
- 1024-byte header, error forms, 1 MB chunks, 32-byte padding: the
|
||
`trailingPadding` formula (`block - (length % block)`) matches
|
||
`SendFileEx`'s `PACKAGE_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 the
|
||
`if (...> 0)` guard is never false for a `% PACKAGE_SIZE` computed
|
||
this way.
|
||
- `ReceivedFile` staging/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-
|
||
`MachineSwitched` vs ask/push, pasteboard polling/quiet-period/
|
||
own-write suppression, `ShareClipboard`/`TransferFile` gating: each
|
||
traced to its `CheckClipboardEx` (`Clipboard.cs:85-251`) or
|
||
`Receiver.cs:273-380` counterpart and found correct, including the
|
||
easy-to-miss ones — `Clipboard (69)` really is un-addressed
|
||
(`ClipboardBridge.swift:190-195` applies no `Des` check, matching
|
||
`Receiver.cs:273-282`), and `MachineSwitched`/`ClipboardAsk` really
|
||
are gated on `Des == localID` (`:197-207`, matching `:284-291, 318`).
|
||
- The four `Engine.dispatch`/`EngineActions` call 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; `.machineSwitched` routing into
|
||
`clipboardDispatch` is right because Windows's own `MachineSwitched`
|
||
case in `Receiver.cs` does nothing *but* the clipboard-pull check —
|
||
there is no other received-side handling for that packet to
|
||
preserve.
|
||
- C1: `chunkPackets` returns unstamped packets; `forwardClipboardBatch`
|
||
stamps each once via the Engine's shared `stampAndForward` and 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 `inbox` into `.header`/`.body` phase, and nothing is
|
||
written to a file or the pasteboard, before `authorised(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.*` and `fail(...)`
|
||
call site; all carry machine names, filenames, byte counts or fixed
|
||
strings, never payload bytes or `securityKey`.
|
||
|
||
**Findings** (none block CP2; see below).
|
||
|
||
1. `Sources/MWBNet/BulkChannel.swift:104-112` vs
|
||
`App/Core/Clipboard.cs:375, 925-941` and `App/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 (`ReceiveAndProcessClipboardData` after 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 = 4` is 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 above `connectionLimit` calls 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 — each `BulkConnection`
|
||
is self-contained — but it is a silently un-ported behaviour and the
|
||
comment's citation doesn't hold up.
|
||
2. `Sources/MWBMac/ReceivedFile.swift:58-61` (`stagingURL(in:)`) is
|
||
dead: nothing calls it. `Sources/MWBNet/BulkConnection.swift:
|
||
336-339` has its own private `stagingURL()` instead, for the
|
||
layering reason the README's "Five deviations" section gives — a
|
||
good reason, but it leaves the `ReceivedFile` copy, which the
|
||
README's "Promised" interface still lists as public API, unused by
|
||
anything in `Sources` or `Tests`.
|
||
3. `Sources/MWBMac/Pasteboard.swift:123-126`. The comment says the
|
||
20 MB gate is "measured on the tagged blob before compression"
|
||
citing `FormHelper.cs:204-210`, but the code sums
|
||
`text.plain?.count + text.rtf?.count + text.html?.count` — the
|
||
three flavour strings alone, without the `"TXT"`/`"RTF"`/`"HTM"`
|
||
tags or the ~38-character `SEP` GUID appended after each one
|
||
Windows includes in `st.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 to `FormHelper.cs` than the code has.
|
||
4. `Sources/mwb/ClipboardBridge.swift:17`. `import AppKit` is unused —
|
||
no `NS`/`CG` symbol appears anywhere in the file; every AppKit
|
||
access already goes through `MWBMac` as the file's own header
|
||
comment says it should.
|
||
5. `Sources/MWBNet/BulkConnection.swift:397-409` vs
|
||
`Sources/mwb/ClipboardBridge.swift:143-160`. `localFile` decides
|
||
"too big" vs "not found" once, at copy time. `beginSending`
|
||
independently 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. Read
|
||
`BulkConnection.acceptHandshake`/`authorised`: raw 64-byte `DATA`,
|
||
bytes 1..3 checked zero, name+id sent to the Engine for the
|
||
`resolveID == src && connected` gate 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.
|