Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions App/Sources/Features/RemoteMirror/MirrorClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ final class MirrorClient: Identifiable {
@ObservationIgnored private var configuration: MirrorSavedConnection
@ObservationIgnored private let makeConnection: (MirrorSavedConnection) -> MirrorRemoteConnection
@ObservationIgnored private var peer: MirrorRemoteConnection?
/// This connection already asked the Host to compress (docs-ai 097).
@ObservationIgnored private var requestedCompression = false
@ObservationIgnored private var historyID: UUID?
@ObservationIgnored private var historyPageGate = MirrorHistoryPageGate()
@ObservationIgnored private var subscriptionID: UUID?
Expand Down Expand Up @@ -93,6 +95,7 @@ final class MirrorClient: Identifiable {
isConnecting = true
let peer = makeConnection(configuration)
self.peer = peer
requestedCompression = false
peer.onEnrolled = { [weak self, weak peer] enrolled in
guard let self, let peer, self.peer === peer else { return }
self.configuration = enrolled
Expand Down Expand Up @@ -382,6 +385,11 @@ final class MirrorClient: Identifiable {
}

private func receivePanes(_ message: MirrorMessage) {
// Before anything else this connection sends, so the replies to it come compressed.
if message.capabilities?.contains(MirrorWireCompression.capability) == true, !requestedCompression {
requestedCompression = true
peer?.send(.compress)
}
panes = message.panes ?? []
supportsProfileLaunch = message.capabilities?.contains("launch-profile") == true
supportsShellLaunch = message.capabilities?.contains("launch-shell") == true
Expand Down
19 changes: 17 additions & 2 deletions App/Sources/Features/RemoteMirror/MirrorConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ final class MirrorConnection {
private var closed = false
private var finishing = false
private var queuedBytes = 0
/// Set once the peer asked for compressed messages (docs-ai 097); compresses every later send.
private var deflater: MirrorWireCompression.Deflater?
/// Created on the first compressed message received.
private var inflater: MirrorWireCompression.Inflater?
/// How many compressed messages arrived, so a test can tell that the peer compresses.
private(set) var compressedMessagesReceived = 0
private var heartbeat: Task<Void, Never>?
private var deadline: Task<Void, Never>?
private let clock: any Clock<Duration>
Expand Down Expand Up @@ -112,7 +118,7 @@ final class MirrorConnection {
func send(_ message: MirrorMessage, closeAfterSending: Bool = false) {
guard !closed, !finishing else { return }
do {
let bytes = try MirrorWire.encode(message)
let bytes = try MirrorWire.encode(message, compressor: deflater)
guard queuedBytes + bytes.count <= 2 * MirrorWire.maximumPayload else {
close(String(localized: "Remote receiver is too slow."))
return
Expand All @@ -138,6 +144,12 @@ final class MirrorConnection {
} catch { close(error.localizedDescription) }
}

/// Compresses every message sent from now on. Once per connection; later calls do nothing.
func startCompressing() throws {
guard deflater == nil else { return }
deflater = try MirrorWireCompression.Deflater()
}

func close(_ reason: String? = nil) {
guard !closed else { return }
#if DEBUG
Expand Down Expand Up @@ -178,7 +190,10 @@ final class MirrorConnection {
self.read(count: length) { [weak self] payload in
guard let self else { return }
do {
let message = try MirrorWire.decode(payload)
if payload.first == MirrorWireCompression.payloadType { self.compressedMessagesReceived += 1 }
let plain = try MirrorWireCompression.expand(
payload, with: &self.inflater, limit: MirrorWire.maximumPayload)
let message = try MirrorWire.decode(plain)
self.receive(message)
if !self.closed { self.readHeader() }
} catch { self.close(error.localizedDescription) }
Expand Down
33 changes: 22 additions & 11 deletions App/Sources/Features/RemoteMirror/MirrorHost.swift
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,7 @@ final class MirrorHost {
panes: panes,
capabilities: [
"vt-v1", "text-v1", "conversation-v1", "takeover", "refresh", MirrorPushContract.capability,
MirrorWireCompression.capability,
]
+ (commandService != nil
? [
Expand All @@ -731,29 +732,39 @@ final class MirrorHost {
case .acknowledge:
try acknowledge(message, peer: peer)
case .refresh:
guard var subscription = subscription(for: message, peer: peer) else {
throw MirrorProtocolError.invalidMessage
}
subscription.gate.requestRefresh()
subscription.textGate.requestRefresh()
subscriptions[peer.id] = subscription
try refresh(message, peer: peer)
case .input:
guard let subscription = subscription(for: message, peer: peer),
subscription.representation == .terminal, let bytes = message.bytes,
!bytes.isEmpty, bytes.count <= MirrorWire.maximumInput
else { throw MirrorProtocolError.invalidMessage }
try source.write(bytes, to: subscription.paneID)
try writeInput(message, peer: peer)
case .scroll:
try scroll(message, peer: peer)
case .history:
try sendHistory(message, to: peer)
case .pushRegister, .pushUnregister:
try updatePushRegistration(message, peer: peer)
case .compress:
try peer.startCompressing()
default: throw MirrorProtocolError.invalidMessage
}
} catch { peer.close(error.localizedDescription) }
}

private func refresh(_ message: MirrorMessage, peer: MirrorConnection) throws {
guard var subscription = subscription(for: message, peer: peer) else {
throw MirrorProtocolError.invalidMessage
}
subscription.gate.requestRefresh()
subscription.textGate.requestRefresh()
subscriptions[peer.id] = subscription
}

private func writeInput(_ message: MirrorMessage, peer: MirrorConnection) throws {
guard let subscription = subscription(for: message, peer: peer),
subscription.representation == .terminal, let bytes = message.bytes,
!bytes.isEmpty, bytes.count <= MirrorWire.maximumInput
else { throw MirrorProtocolError.invalidMessage }
try source.write(bytes, to: subscription.paneID)
}

private func scroll(_ message: MirrorMessage, peer: MirrorConnection) throws {
guard var subscription = subscription(for: message, peer: peer), case .scroll(let request) = message else {
throw MirrorProtocolError.invalidMessage
Expand Down
19 changes: 17 additions & 2 deletions App/Sources/Features/RemoteMirror/MirrorProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ nonisolated enum MirrorMessage: Codable, Sendable {
case challenge, authenticate, pair, paired, authenticated, list, panes, subscribe, subscribed,
frame, textFrame, viewport, acknowledge, input, history, historyPage, failure, ping, pong, ended,
refresh, scroll, scrollResult, scrollState, command, commandResult, commandReceipt,
conversationSnapshot, conversationEvents, screenPrompt, pushRegister, pushUnregister, pushStatus
conversationSnapshot, conversationEvents, screenPrompt, pushRegister, pushUnregister, pushStatus, compress
}
case list
case panes(PanesPayload)
Expand Down Expand Up @@ -188,6 +188,9 @@ nonisolated enum MirrorMessage: Codable, Sendable {
typealias PushRegisterPayload = MirrorPushRegisterPayload
/// `push-v1`: the phone turned notifications off for this Host.
case pushUnregister
/// `deflate-v1`: the client asks the Host to compress what it sends on this connection
/// (docs-ai 097). Sent once, only to a Host that lists the capability.
case compress
/// The Host's reply to `pushRegister` and `pushUnregister`.
case pushStatus(PushStatusPayload)
typealias PushStatusPayload = MirrorPushStatusPayload
Expand Down Expand Up @@ -300,6 +303,7 @@ nonisolated enum MirrorMessage: Codable, Sendable {
case .screenPrompt: .screenPrompt
case .pushRegister: .pushRegister
case .pushUnregister: .pushUnregister
case .compress: .compress
case .pushStatus: .pushStatus
}
}
Expand Down Expand Up @@ -554,6 +558,17 @@ nonisolated enum MirrorWire {
static let maximumInput = 64 * 1024

static func encode(_ message: MirrorMessage) throws -> Data {
try frame(payload(message))
}

/// The framed bytes for `message`, compressed when the connection compresses (docs-ai 097).
static func encode(_ message: MirrorMessage, compressor: MirrorWireCompression.Deflater?) throws -> Data {
let plain = try payload(message)
return try frame(compressor.map { try $0.compress(plain) } ?? plain)
}

/// The payload of `message`: its type byte and body, without the length prefix.
static func payload(_ message: MirrorMessage) throws -> Data {
let payload: Data
switch message {
case .frame(let value):
Expand Down Expand Up @@ -582,7 +597,7 @@ nonisolated enum MirrorWire {
default:
payload = Data([0]) + (try JSONEncoder().encode(message))
}
return try frame(payload)
return payload
}

private static func uuidBytes(_ id: UUID) -> Data {
Expand Down
38 changes: 38 additions & 0 deletions App/Tests/RemoteMirror/MirrorHostTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1135,6 +1135,44 @@ struct MirrorHostTests {
#expect(saved.devices[0].push?.token == dead)
}

@Test(.timeLimit(.minutes(1))) func aClientThatAsksGetsCompressedMessagesAndOthersDoNot() async throws {
var saved = Self.identity
let host = MirrorHost(
source: Source(), defaults: .mirrorTests, enabled: true, loadIdentity: { saved },
saveIdentity: { saved = $0 })
host.address = "127.0.0.1"
host.port = String(try MirrorTestPort.unusedPort())
defer { host.stop() }
try await MirrorTestPort.startHost(host)
let compressing = try await Peer(port: UInt16(host.port)!, key: host.pairingKey)
defer { compressing.connection.close() }
let plain = try await Peer(port: UInt16(host.port)!, key: host.pairingKey)
defer { plain.connection.close() }
var compressed = compressing.messages.makeAsyncIterator()
var uncompressed = plain.messages.makeAsyncIterator()

compressing.connection.send(.list)
guard case .panes(let first) = await compressed.next() else {
Issue.record("Expected panes")
return
}
#expect(first.capabilities.contains(MirrorWireCompression.capability))
#expect(compressing.connection.compressedMessagesReceived == 0)

compressing.connection.send(.compress)
compressing.connection.send(.compress)
for _ in 0..<3 {
compressing.connection.send(.list)
#expect(await compressed.next()?.kind == .panes)
}
// Asking twice is harmless; every reply after the request came compressed.
#expect(compressing.connection.compressedMessagesReceived == 3)

plain.connection.send(.list)
#expect(await uncompressed.next()?.kind == .panes)
#expect(plain.connection.compressedMessagesReceived == 0)
}

@Test(.timeLimit(.minutes(1))) func pushControlsArePerConnectionLimited() async throws {
var saved = Self.identity
let host = MirrorHost(
Expand Down
86 changes: 86 additions & 0 deletions App/Tests/RemoteMirror/MirrorWireCompressionTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import Foundation
import Testing

@testable import Prowl

struct MirrorWireCompressionTests {
/// Three type-3 payload bodies of one stream, made by another zlib (Python, raw DEFLATE,
/// level 6, sync flush): `{"list":{}}` twice, then `{"pong":{}}`. Every client must read
/// them, whatever bytes its own deflater writes.
static let vector: [[UInt8]] = [
[98, 168, 86, 202, 201, 44, 46, 81, 178, 170, 174, 173, 5, 0, 0, 0, 255, 255],
[98, 64, 98, 3, 0, 0, 0, 255, 255],
[2, 178, 11, 242, 243, 210, 193, 108, 0, 0, 0, 0, 255, 255],
]

@Test func readsTheVectorOfAnotherZlib() throws {
var inflater: MirrorWireCompression.Inflater?
let kinds = try Self.vector.map { body in
let plain = try MirrorWireCompression.expand(Data([3] + body), with: &inflater, limit: MirrorWire.maximumPayload)
return try MirrorWire.decode(plain).kind
}
#expect(kinds == [.list, .list, .pong])
}

@Test func aStreamRoundTripsEveryPayloadTypeAndShrinksRepeats() throws {
let deflater = try MirrorWireCompression.Deflater()
var inflater: MirrorWireCompression.Inflater?
let panes = MirrorMessage.panes(
.init(
panes: (0..<4).map { index in
MirrorPaneDescriptor(
id: UUID(), title: "Claude Code · feature-\(index)", directory: "/Users/me/Projects/Prowl", busy: false,
projectName: "Prowl", agent: "claude")
},
capabilities: ["text-v1", "conversation-v1", MirrorWireCompression.capability], hostRunID: UUID()))
let text = MirrorMessage.textFrame(
.init(
columns: 80, rows: 24, truncated: false, sequence: 7, text: String(repeating: "ls -la\n", count: 200),
subscriptionID: UUID()))
var sizes: [Int] = []
for message in [panes, panes, panes, text, .pong] {
let plain = try MirrorWire.payload(message)
let compressed = try deflater.compress(plain)
#expect(compressed.first == MirrorWireCompression.payloadType)
sizes.append(compressed.count)
let expanded = try MirrorWireCompression.expand(compressed, with: &inflater, limit: MirrorWire.maximumPayload)
#expect(expanded == plain)
}
// A list the stream has seen costs a few dozen bytes instead of the whole list.
let plainList = try MirrorWire.payload(panes).count
#expect(sizes[0] < plainList)
#expect(sizes[1] < 64 && sizes[2] < 64, "repeated list sizes: \(sizes)")
}

@Test func plainPayloadsPassThroughWithoutAStream() throws {
var inflater: MirrorWireCompression.Inflater?
let plain = try MirrorWire.payload(.pong)
#expect(try MirrorWireCompression.expand(plain, with: &inflater, limit: MirrorWire.maximumPayload) == plain)
#expect(inflater == nil)
}

@Test func rejectsCorruptNestedAndOversizedPayloads() throws {
var inflater: MirrorWireCompression.Inflater?
#expect(throws: MirrorProtocolError.self) {
try MirrorWireCompression.expand(Data([3, 0xFF, 0x00, 0x13]), with: &inflater, limit: MirrorWire.maximumPayload)
}
#expect(throws: MirrorProtocolError.self) {
try MirrorWireCompression.expand(Data([3]), with: &inflater, limit: MirrorWire.maximumPayload)
}

let deflater = try MirrorWireCompression.Deflater()
var fresh: MirrorWireCompression.Inflater?
let nested = try deflater.compress(Data([3, 1, 2, 3]))
#expect(throws: MirrorProtocolError.self) {
try MirrorWireCompression.expand(nested, with: &fresh, limit: MirrorWire.maximumPayload)
}

// One megabyte of zeros compresses to about a kilobyte; the limit stops it, not the size.
let bomb = try MirrorWireCompression.Deflater().compress(Data([0]) + Data(count: 1_024 * 1_024))
var bounded: MirrorWireCompression.Inflater?
#expect(bomb.count < 4_096)
#expect(throws: MirrorProtocolError.self) {
try MirrorWireCompression.expand(bomb, with: &bounded, limit: 64 * 1_024)
}
}
}
Loading
Loading