clipboard: pace in-band chunks, 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), which closes the
connection, and puts a second of clipboard traffic ahead of the next mouse
packet. Windows paces naturally because SendClipboardDataUsingTCP writes
each packet down a blocking socket from its own thread (Clipboard.cs:260-305).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-09-16 04:58:07 -07:00
1 parent dd26befe58
commit 4181bb273f
2 files changed
+71 -1

No files matched your search

+54 -1
View File
@@ -24,6 +24,9 @@ import MWBNet
public enum ClipboardAction: Sendable {
/// Route this packet; the Engine stamps `Id` and `Src` (contracts C1).
case send(Packet)
/// Send a small payload in-band as 48-byte chunks, paced (see
/// `ClipboardBridge.beginChunkedSend`).
case sendChunks(payload: Data, isImage: Bool)
/// Fetch the big payload waiting on `machine`: pull if we have an outbound
/// connection to it, else ask it to push (`Clipboard.cs:425-449`).
case getRemoteClipboard(machine: String, postAction: UInt32)
@@ -50,6 +53,7 @@ public final class ClipboardBridge {
private var machineWithData: String?
private var beatTime: TimeInterval = 0
private var reassemblers: [UInt32: Reassembler] = [:]
private var sendTask: Task<Void, Never>?
private var started = false
/// Builds the bridge. `relay` is the `Sendable` object the channel and the
@@ -79,6 +83,8 @@ public final class ClipboardBridge {
/// Stops both, and forgets what was on offer.
public func stop() {
started = false
sendTask?.cancel()
sendTask = nil
watcher.stop()
bulk.serve(nil)
bulk.stop()
@@ -154,7 +160,7 @@ public final class ClipboardBridge {
private func offer(_ payload: BulkPayload, bytes: Data, isImage: Bool) -> [ClipboardAction] {
bulk.serve(payload)
guard bytes.count > ClipboardCodec.inBandLimit else {
return ClipboardCodec.chunkPackets(payload: bytes, isImage: isImage).map { .send($0) }
return [.sendChunks(payload: bytes, isImage: isImage)]
}
return [.send(beat())]
}
@@ -278,6 +284,43 @@ public final class ClipboardBridge {
return [.note("text received")]
}
// MARK: - Pacing the in-band chunks
/// Chunks handed to the channel at once.
static let chunkBatch = 128
/// How long the sender waits between batches.
static let chunkPause = Duration.milliseconds(5)
/// Feeds a chunked payload to the Engine a batch at a time.
///
/// A 1 MB payload is 21 846 packets. Handing them over in one go would
/// overrun the 512-packet outbox a connection is allowed (contracts C3) and
/// close it, and would put a second of clipboard traffic in front of the
/// next mouse packet. Windows paces naturally because
/// `SendClipboardDataUsingTCP` writes each packet down a blocking socket
/// from its own thread (`Clipboard.cs:260-305`); this is that thread.
///
/// Only one chunked send runs at a time: a second copy cancels the first,
/// because interleaved chunks from two payloads would arrive as one
/// corrupt stream.
func beginChunkedSend(
_ packets: [Packet], forward: @escaping @Sendable ([Packet]) async -> Void
) {
sendTask?.cancel()
// Captures nothing but `packets` and `forward`, both `Sendable`, so the
// task does not drag this actor-isolated object off the Engine.
sendTask = Task {
var index = 0
while index < packets.count {
if Task.isCancelled { return }
let end = min(index + ClipboardBridge.chunkBatch, packets.count)
await forward(Array(packets[index..<end]))
index = end
try? await Task.sleep(for: ClipboardBridge.chunkPause)
}
}
}
/// Puts a received file's URL on the pasteboard, as
/// `Clipboard.SetFileDropList` does (`Clipboard.cs:864-868`).
public func announce(_ file: URL) {
@@ -422,6 +465,10 @@ extension Engine {
switch action {
case .send(let packet):
stampAndForward(packet)
case .sendChunks(let payload, let isImage):
clipboard?.beginChunkedSend(
ClipboardCodec.chunkPackets(payload: payload, isImage: isImage),
forward: { [weak self] batch in await self?.forwardClipboardBatch(batch) })
case .getRemoteClipboard(let machine, let postAction):
getRemoteClipboard(from: machine, postAction: postAction)
case .pushClipboard(let machine, let postAction):
@@ -434,6 +481,12 @@ extension Engine {
}
}
/// One batch of in-band clipboard chunks, each stamped once and fanned out
/// unchanged (contracts C1).
func forwardClipboardBatch(_ packets: [Packet]) {
for packet in packets { stampAndForward(packet) }
}
/// `ConnectAndGetData` (`Clipboard.cs:419-449`): pull over an outbound
/// connection if there is one, otherwise ask the peer to push, because a
/// machine we never dialled may not be reachable from here at all.
+17
View File
@@ -224,6 +224,7 @@ public final class BulkChannel: @unchecked Sendable {
// 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)
@@ -239,6 +240,8 @@ public final class ClipboardBridge { // Engine-isolated, not S
-> [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 {
@@ -272,6 +275,15 @@ all deliberate:
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
@@ -422,6 +434,11 @@ was not needed.
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.
- 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