clipboard: de-duplicate in-band chunks by Id

A machine pair keeps two control connections and PreProcess exempts
ClipboardText/ClipboardImage from the replay ring (Receiver.cs:40-82), so
every chunk is delivered twice. Windows reassembles from the one socket the
first chunk arrived on (Clipboard.cs:308-373) and never sees it; ours is
keyed by sending machine, so the copies interleaved and corrupted the
payload. Reassembler now keeps a 50-entry ring of chunk Ids, which works
because contracts C1 stamps one Id per chunk for both deliveries.
docs/protocol.md §10.7 note 11.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-09-16 04:56:31 -07:00
1 parent 105a34cb45
commit dd26befe58
3 files changed
+59 -5

No files matched your search

+26 -1
View File
@@ -345,6 +345,11 @@ public final class Reassembler {
/// one chunk of zero padding.
public static let sizeLimit = ClipboardCodec.inBandLimit + Packet.clipboardChunkSize
/// How many chunk ids are remembered to collapse a peer pair's second
/// delivery. The same size as the session replay ring (`Receiver.cs:31`),
/// and for the same reason.
public static let idWindow = ReplayFilter.windowSize
/// True when the payload grew past `sizeLimit` and was thrown away.
public private(set) var abandoned = false
/// Whether the chunks seen so far are image bytes.
@@ -353,6 +358,7 @@ public final class Reassembler {
public private(set) var lastChunk: TimeInterval
private var payload = Data()
private var recentIDs: [Int32] = []
/// An empty reassembly, started at `now`.
public init(now: TimeInterval) {
@@ -368,7 +374,7 @@ public final class Reassembler {
switch packet.type {
case .clipboardText, .clipboardImage:
isImage = packet.type == .clipboardImage
guard !abandoned else { return nil }
guard !abandoned, !isRepeat(packet.id) else { return nil }
payload.append(packet.payload48)
if payload.count > Reassembler.sizeLimit {
abandoned = true
@@ -382,4 +388,23 @@ public final class Reassembler {
return nil
}
}
/// True when this chunk has already been appended.
///
/// A machine pair keeps **two** control connections (docs/protocol.md §10.3
/// note 4) and the session replay ring deliberately exempts
/// `ClipboardText` and `ClipboardImage` (`Receiver.cs:40-82`), so every
/// chunk is delivered twice. Windows never notices: its receive loop blocks
/// on the one socket the first chunk arrived on and reassembles from that
/// socket alone (`Clipboard.cs:308-373`), so the second copy becomes a
/// separate, parallel reassembly. Ours is keyed by sending machine, which
/// is what makes the interleaving visible — and the sender stamps one `Id`
/// per chunk for both deliveries (contracts C1), so the `Id` tells the copy
/// from the original.
private func isRepeat(_ id: Int32) -> Bool {
if recentIDs.contains(id) { return true }
recentIDs.append(id)
if recentIDs.count > Reassembler.idWindow { recentIDs.removeFirst() }
return false
}
}