From 34f76bed389b866e1eef27595ca29a5781bfb462 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 10:06:39 -0800 Subject: [PATCH 01/21] Run CI for the master branch --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 14799e2..15a7052 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,9 +2,9 @@ name: CI on: push: - branches: [main] + branches: [main, master] pull_request: - branches: [main] + branches: [main, master] jobs: test: From 6b5f54b1d3e47d8508f058e15d244448d778d313 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 10:12:31 -0800 Subject: [PATCH 02/21] Install a pinned periphery release in CI The periphery Homebrew tap cask no longer installs on current Homebrew. Also cancel superseded CI runs. --- .github/workflows/ci.yml | 15 ++++++++++++++- CLAUDE.md | 3 ++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 15a7052..56bf774 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,10 @@ on: pull_request: branches: [main, master] +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: test: runs-on: macos-latest @@ -30,8 +34,17 @@ jobs: ruby-version: '3.3' bundler-cache: true + # The periphery Homebrew tap's cask fails on current Homebrew, so install a + # pinned release binary instead. - name: Install periphery - run: brew install peripheryapp/periphery/periphery + env: + PERIPHERY_VERSION: '3.8.0' + run: | + curl -fsSL -o "$RUNNER_TEMP/periphery.zip" \ + "https://github.com/peripheryapp/periphery/releases/download/${PERIPHERY_VERSION}/periphery-${PERIPHERY_VERSION}.zip" + unzip -q "$RUNNER_TEMP/periphery.zip" -d "$RUNNER_TEMP/periphery" + echo "$RUNNER_TEMP/periphery" >> "$GITHUB_PATH" + "$RUNNER_TEMP/periphery/periphery" version - name: Scan for dead code run: bundle exec fastlane periphery diff --git a/CLAUDE.md b/CLAUDE.md index d923945..de7896f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,7 +58,8 @@ The project uses [periphery](https://github.com/peripheryapp/periphery) to detec In CI this runs as the `periphery` fastlane lane (`bundle exec fastlane periphery`), which adds `--strict` so the scan exits non-zero on findings. The -`.github/workflows/ci.yml` workflow runs it on every push and pull request. +`.github/workflows/ci.yml` workflow runs it, with a pinned periphery release, on +pushes to and pull requests against `master` (and `main`). Configuration lives in the committed `.periphery.yml`; `periphery scan` reads it automatically. A clean run reports `No unused code detected.`. Notes: From 0a74e72c4d3ec6890efa9e9a1e4b500210785824 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 10:17:29 -0800 Subject: [PATCH 03/21] Classify server lines and frame long lines safely Lines with defaultDevice are full states, lines with icon are icon replies, and anything else is ignored instead of ending the connection. The full state decodes the v8 features list and per-session iconId. Framing now searches only new bytes, drops a trailing CR, skips blank lines and discards lines over 4 MiB. --- PcVolumeControl/datasources/LineFramer.swift | 53 +++++++ .../VolumeTransportDataSource.swift | 13 +- PcVolumeControl/models/ServerLine.swift | 56 +++++++ .../repos/VolumeControlRepository.swift | 18 ++- .../viewmodels/MainViewModel.swift | 13 +- .../viewmodels/SliderViewModel.swift | 12 +- PcVolumeControlTests/LineFramerTests.swift | 74 +++++++++ PcVolumeControlTests/ServerLineTests.swift | 144 ++++++++++++++++++ .../VolumeControlRepositoryTests.swift | 57 +++++++ 9 files changed, 420 insertions(+), 20 deletions(-) create mode 100644 PcVolumeControl/datasources/LineFramer.swift create mode 100644 PcVolumeControl/models/ServerLine.swift create mode 100644 PcVolumeControlTests/LineFramerTests.swift create mode 100644 PcVolumeControlTests/ServerLineTests.swift create mode 100644 PcVolumeControlTests/VolumeControlRepositoryTests.swift diff --git a/PcVolumeControl/datasources/LineFramer.swift b/PcVolumeControl/datasources/LineFramer.swift new file mode 100644 index 0000000..3416ec8 --- /dev/null +++ b/PcVolumeControl/datasources/LineFramer.swift @@ -0,0 +1,53 @@ +import Foundation + +/// Splits a byte stream into newline-terminated lines, independent of how the bytes +/// were chunked by the socket. A trailing `\r` is dropped and blank lines are skipped. +/// A line longer than `maxLineLength` is discarded up to its terminator so one bad +/// line cannot grow the buffer without bound or end the stream. +struct LineFramer { + /// Icon replies can be several hundred KiB; the protocol requires accepting at least 1 MiB. + static let defaultMaxLineLength = 4 * 1024 * 1024 + + private let maxLineLength: Int + private var buffer: [UInt8] = [] + // Bytes at the front of `buffer` already searched for a newline. + private var searchedCount = 0 + private var discardingOverlongLine = false + + init(maxLineLength: Int = LineFramer.defaultMaxLineLength) { + self.maxLineLength = maxLineLength + } + + /// Appends `chunk` and returns every line it completes, in order. + mutating func append(_ chunk: Data) -> [Data] { + buffer.append(contentsOf: chunk) + + var lines: [Data] = [] + var lineStart = 0 + var searchFrom = searchedCount + while let newline = buffer[searchFrom...].firstIndex(of: 0x0A) { + if discardingOverlongLine { + discardingOverlongLine = false + } else { + var lineEnd = newline + if lineEnd > lineStart, buffer[lineEnd - 1] == 0x0D { + lineEnd -= 1 + } + if lineEnd > lineStart { + lines.append(Data(buffer[lineStart.. maxLineLength { + buffer.removeAll() + searchedCount = 0 + discardingOverlongLine = true + } + return lines + } +} diff --git a/PcVolumeControl/datasources/VolumeTransportDataSource.swift b/PcVolumeControl/datasources/VolumeTransportDataSource.swift index e36bd0a..ab73ef0 100644 --- a/PcVolumeControl/datasources/VolumeTransportDataSource.swift +++ b/PcVolumeControl/datasources/VolumeTransportDataSource.swift @@ -15,7 +15,7 @@ struct VolumeTransportDataSource: VolumeTransportDataSourceProtocol { } func incoming() -> AsyncThrowingStream { - .streamNewlineDelimitedBytes(from: connection.bytes()) + .streamLines(from: connection.bytes()) } func close() { @@ -24,19 +24,16 @@ struct VolumeTransportDataSource: VolumeTransportDataSourceProtocol { } private extension AsyncThrowingStream where Element == Data, Failure == Error { - static func streamNewlineDelimitedBytes(from upstream: AsyncThrowingStream) + static func streamLines(from upstream: AsyncThrowingStream) -> AsyncThrowingStream { AsyncThrowingStream { continuation in - var buffer = Data() let task = Task { + var framer = LineFramer() do { for try await chunk in upstream { - buffer.append(chunk) - while let nl = buffer.firstIndex(of: 0x0A) { - let frame = buffer.prefix(upTo: nl) - buffer.removeSubrange(...nl) - continuation.yield(Data(frame)) + for line in framer.append(chunk) { + continuation.yield(line) } } continuation.finish() diff --git a/PcVolumeControl/models/ServerLine.swift b/PcVolumeControl/models/ServerLine.swift new file mode 100644 index 0000000..297f92f --- /dev/null +++ b/PcVolumeControl/models/ServerLine.swift @@ -0,0 +1,56 @@ +import Foundation + +/// One line received from the server. Every line carries `protocolVersion` and exactly +/// one of `defaultDevice` (a full state) or `icon` (an icon reply); anything else, +/// including lines that are not valid JSON, is ignored for forward compatibility. +enum ServerLine { + case state(FullState) + case icon(IconReply) + case ignored + + static func classify(_ line: Data) -> ServerLine { + (try? JSONDecoder().decode(Envelope.self, from: line))?.line ?? .ignored + } + + // Decodes the document once and picks the line type by which key is present. + private struct Envelope: Decodable { + let line: ServerLine + + private enum CodingKeys: String, CodingKey { + case defaultDevice, icon + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + switch (container.contains(.defaultDevice), container.contains(.icon)) { + case (true, false): + line = .state(try FullState(from: decoder)) + case (false, true): + line = .icon(try container.decode(IconReply.self, forKey: .icon)) + default: + line = .ignored + } + } + } +} + +/// The server's answer for one requested icon id. +struct IconReply: Decodable { + let id: String + /// The PNG bytes, or nil when the server has no image for the id or sent an unusable payload. + let png: Data? + + private enum CodingKeys: String, CodingKey { + case id, data, error + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decode(String.self, forKey: .id) + // Any `error` value means "no image". A bad payload must still produce a reply + // for the id, so it is mapped to "no image" instead of failing the whole line. + let error = try? container.decodeIfPresent(String.self, forKey: .error) + let base64 = try? container.decodeIfPresent(String.self, forKey: .data) + png = error == nil ? base64.flatMap { Data(base64Encoded: $0) } : nil + } +} diff --git a/PcVolumeControl/repos/VolumeControlRepository.swift b/PcVolumeControl/repos/VolumeControlRepository.swift index a1dc78d..34af076 100644 --- a/PcVolumeControl/repos/VolumeControlRepository.swift +++ b/PcVolumeControl/repos/VolumeControlRepository.swift @@ -6,14 +6,22 @@ struct VolumeControlRepository { let transport: VolumeTransportDataSourceProtocol let deviceIdLookup = DeviceIdLookup() - func fullStateStream() -> AsyncThrowingStream { + /// Full states and icon replies from the server; lines of any other kind are dropped. + func serverLines() -> AsyncThrowingStream { AsyncThrowingStream { continuation in let task = Task { do { - for try await msgBytes in transport.incoming() { - let state = try JSONDecoder().decode(FullState.self, from: msgBytes) - deviceIdLookup.ingest(state.deviceIds) - continuation.yield(state) + for try await bytes in transport.incoming() { + let line = ServerLine.classify(bytes) + switch line { + case .state(let state): + deviceIdLookup.ingest(state.deviceIds) + continuation.yield(line) + case .icon: + continuation.yield(line) + case .ignored: + appLog("Ignoring unrecognized server line (\(bytes.count) bytes)") + } } continuation.finish() } catch { diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index 9d0c192..645cfa7 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -341,9 +341,10 @@ final class MainViewModel: ObservableObject { private func subscribe(to repo: VolumeControlRepository) { streamTask = Task { do { - for try await state in repo.fullStateStream() { + for try await line in repo.serverLines() { // Stop applying updates after cancellation so an in-flight value can't resurrect state. if Task.isCancelled { break } + guard case .state(let state) = line else { continue } fullState = state // view state only here connectionStatus = .connected updateSharedState(with: state) // Update widget state @@ -614,7 +615,8 @@ class FullState: Codable, Equatable { lhs.defaultDevice.masterMuted == rhs.defaultDevice.masterMuted && lhs.defaultDevice.masterVolume == rhs.defaultDevice.masterVolume && lhs.defaultDevice.name == rhs.defaultDevice.name && - lhs.defaultDevice.sessions == rhs.defaultDevice.sessions + lhs.defaultDevice.sessions == rhs.defaultDevice.sessions && + lhs.features == rhs.features } struct theDefaultDevice: Codable, Equatable { let deviceId: String @@ -628,14 +630,19 @@ class FullState: Codable, Equatable { var muted: Bool var name: String var volume: Double + // v8: content-derived icon id; absent on older servers and until the server resolves the icon. + var iconId: String? = nil } var defaultDevice: theDefaultDevice let deviceIds: [String: String] let protocolVersion: Int + // v8: protocol extensions the server supports; absent on older servers. + let features: [String]? - init(protocolVersion: Int, deviceIds: [String:String], defaultDevice: theDefaultDevice) { + init(protocolVersion: Int, deviceIds: [String:String], defaultDevice: theDefaultDevice, features: [String]? = nil) { self.protocolVersion = protocolVersion self.deviceIds = deviceIds self.defaultDevice = defaultDevice + self.features = features } } diff --git a/PcVolumeControl/viewmodels/SliderViewModel.swift b/PcVolumeControl/viewmodels/SliderViewModel.swift index eae5f81..46a15e3 100644 --- a/PcVolumeControl/viewmodels/SliderViewModel.swift +++ b/PcVolumeControl/viewmodels/SliderViewModel.swift @@ -180,7 +180,8 @@ final class SliderViewModel: ObservableObject { id: session.id, muted: session.muted, name: displayName, - volume: session.volume + volume: session.volume, + iconId: session.iconId ) } @@ -208,7 +209,8 @@ final class SliderViewModel: ObservableObject { id: existing.id, muted: existing.muted, name: incoming.name, - volume: existing.volume + volume: existing.volume, + iconId: incoming.iconId ) } else { return incoming @@ -259,7 +261,8 @@ final class SliderViewModel: ObservableObject { id: sessionId, muted: existing.muted, name: session.name, - volume: existing.volume + volume: existing.volume, + iconId: session.iconId )) } else { orderedSessions.append(session) @@ -301,7 +304,8 @@ final class SliderViewModel: ObservableObject { id: session.id, muted: session.muted, name: incoming.name, - volume: session.volume + volume: session.volume, + iconId: incoming.iconId )) } else { updatedSessions.append(incoming) diff --git a/PcVolumeControlTests/LineFramerTests.swift b/PcVolumeControlTests/LineFramerTests.swift new file mode 100644 index 0000000..cce328d --- /dev/null +++ b/PcVolumeControlTests/LineFramerTests.swift @@ -0,0 +1,74 @@ +// +// LineFramerTests.swift +// PcVolumeControlTests +// +// Newline framing of the server byte stream, independent of socket read sizes. +// + +import XCTest +@testable import PcVolumeControl + +final class LineFramerTests: XCTestCase { + + private func strings(_ lines: [Data]) -> [String] { + lines.map { String(decoding: $0, as: UTF8.self) } + } + + func testCompleteLinesInOneRead() { + var framer = LineFramer() + XCTAssertEqual(strings(framer.append(Data("a\nbb\nccc\n".utf8))), ["a", "bb", "ccc"]) + } + + func testLineSplitAcrossReads() { + var framer = LineFramer() + XCTAssertEqual(framer.append(Data(#"{"protocol"#.utf8)), []) + XCTAssertEqual(framer.append(Data(#"Version":7,"#.utf8)), []) + XCTAssertEqual(strings(framer.append(Data((#""x":1}"# + "\n{").utf8))), [#"{"protocolVersion":7,"x":1}"#]) + XCTAssertEqual(strings(framer.append(Data("}\n".utf8))), ["{}"]) + } + + func testTerminatorSplitFromCarriageReturn() { + var framer = LineFramer() + XCTAssertEqual(framer.append(Data("abc\r".utf8)), []) + XCTAssertEqual(strings(framer.append(Data("\n".utf8))), ["abc"]) + } + + func testBlankLinesAreSkipped() { + var framer = LineFramer() + XCTAssertEqual(strings(framer.append(Data("\n\r\na\n\n".utf8))), ["a"]) + } + + func testVeryLongLineInSocketSizedReads() { + // Larger than any icon reply the protocol allows, delivered in 64 KiB reads. + let longLine = Data(repeating: UInt8(ascii: "A"), count: 1_500_000) + let stream = longLine + Data("\nnext\n".utf8) + var framer = LineFramer() + var lines: [Data] = [] + var offset = 0 + while offset < stream.count { + let end = min(offset + 65_536, stream.count) + lines += framer.append(stream.subdata(in: offset.. ServerLine { + ServerLine.classify(Data(text.utf8)) + } + + // MARK: - Full state decoding + + func testV7StateDecodesWithoutV8Fields() throws { + guard case .state(let state) = classify(Self.v7State) else { + return XCTFail("Expected a full state") + } + XCTAssertNil(state.features) + XCTAssertEqual(state.defaultDevice.sessions.count, 1) + XCTAssertNil(state.defaultDevice.sessions[0].iconId) + XCTAssertEqual(state.defaultDevice.sessions[0].volume, 35.0) + } + + func testV8StateDecodesFeaturesAndIconIds() throws { + guard case .state(let state) = classify(Self.v8State) else { + return XCTFail("Expected a full state") + } + XCTAssertEqual(state.features, ["icons"]) + XCTAssertEqual(state.defaultDevice.sessions.map(\.iconId), [ + nil, + "4b13f0d55a3779a6ff892414f951be3f", + "4b13f0d55a3779a6ff892414f951be3f", + "6b58026ae167f8f2e802f2531657443c", + ]) + } + + func testUnknownFeatureNamesAreKept() throws { + let text = Self.v7State.replacingOccurrences( + of: #""applicationVersion":"v10","#, + with: #""applicationVersion":"v10","features":["somethingNew"],"# + ) + guard case .state(let state) = classify(text) else { + return XCTFail("Expected a full state") + } + XCTAssertEqual(state.features, ["somethingNew"]) + } + + // MARK: - Icon replies + + func testIconImageReplyDecodesToPNG() throws { + guard case .icon(let reply) = classify(Self.iconImageReply) else { + return XCTFail("Expected an icon reply") + } + XCTAssertEqual(reply.id, "6b58026ae167f8f2e802f2531657443c") + let png = try XCTUnwrap(reply.png) + XCTAssertEqual(Array(png.prefix(4)), [0x89, 0x50, 0x4E, 0x47]) + let image = try XCTUnwrap(UIImage(data: png)) + XCTAssertEqual(image.size.width * image.scale, 16) + XCTAssertEqual(image.size.height * image.scale, 16) + } + + func testIconNotFoundReplyHasNoImage() { + guard case .icon(let reply) = classify(Self.iconNotFoundReply) else { + return XCTFail("Expected an icon reply") + } + XCTAssertEqual(reply.id, "0000notarealid") + XCTAssertNil(reply.png) + } + + func testIconReplyWithUnknownErrorHasNoImage() { + let text = #"{"protocolVersion":7,"icon":{"id":"abc","error":"somethingElse","data":"iVBORw0KGgo="}}"# + guard case .icon(let reply) = classify(text) else { + return XCTFail("Expected an icon reply") + } + XCTAssertNil(reply.png) + } + + func testIconReplyWithInvalidBase64StillAnswersTheId() { + let text = #"{"protocolVersion":7,"icon":{"id":"abc","size":16,"mime":"image/png","data":"not base64!"}}"# + guard case .icon(let reply) = classify(text) else { + return XCTFail("Expected an icon reply") + } + XCTAssertEqual(reply.id, "abc") + XCTAssertNil(reply.png) + } + + // MARK: - Classification + + func testUnknownLineIsIgnored() { + guard case .ignored = classify(#"{"protocolVersion":7,"somethingNew":{"a":1}}"#) else { + return XCTFail("Expected the line to be ignored") + } + } + + func testMalformedLinesAreIgnored() { + for text in [ + #"{"protocolVersion":7,"defaultDevice":{"deviceId":"#, + #"{"protocolVersion":7,"defaultDevice":{"deviceId":"x"}}"#, + #"{"protocolVersion":7,"icon":{"error":"notFound"}}"#, + "[1,2,3]", + "not json", + ] { + guard case .ignored = classify(text) else { + return XCTFail("Expected \(text) to be ignored") + } + } + } + + func testLineWithBothStateAndIconIsIgnored() { + let text = Self.v7State.replacingOccurrences( + of: #""protocolVersion":7,"#, + with: #""protocolVersion":7,"icon":{"id":"abc","error":"notFound"},"# + ) + guard case .ignored = classify(text) else { + return XCTFail("Expected the line to be ignored") + } + } +} diff --git a/PcVolumeControlTests/VolumeControlRepositoryTests.swift b/PcVolumeControlTests/VolumeControlRepositoryTests.swift new file mode 100644 index 0000000..460798f --- /dev/null +++ b/PcVolumeControlTests/VolumeControlRepositoryTests.swift @@ -0,0 +1,57 @@ +// +// VolumeControlRepositoryTests.swift +// PcVolumeControlTests +// +// The repository's line stream: states and icon replies are delivered, anything +// else is dropped without ending the stream. +// + +import XCTest +@testable import PcVolumeControl + +final class VolumeControlRepositoryTests: XCTestCase { + + func testUnknownAndMalformedLinesDoNotEndTheStream() async throws { + let transport = ScriptedTransport(lines: [ + ServerLineTests.v7State, + "not json", + #"{"protocolVersion":7,"somethingNew":true}"#, + ServerLineTests.iconNotFoundReply, + ServerLineTests.v8State, + ]) + let repo = VolumeControlRepository(transport: transport) + + var kinds: [String] = [] + for try await line in repo.serverLines() { + switch line { + case .state: kinds.append("state") + case .icon: kinds.append("icon") + case .ignored: kinds.append("ignored") + } + } + XCTAssertEqual(kinds, ["state", "icon", "state"]) + } +} + +/// A transport that delivers a fixed list of lines, then ends. +final class ScriptedTransport: VolumeTransportDataSourceProtocol { + private let lines: [String] + + init(lines: [String]) { + self.lines = lines + } + + func outgoing(_ data: Data) async throws {} + + func incoming() -> AsyncThrowingStream { + let lines = lines + return AsyncThrowingStream { continuation in + for line in lines { + continuation.yield(Data(line.utf8)) + } + continuation.finish() + } + } + + func close() {} +} From b4bfc777c90cc1c0b9c941bb662a98fa94e26656 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 10:20:18 -0800 Subject: [PATCH 04/21] Address review of server line handling An undecodable full state ends the connection as before; other unrecognized lines are still ignored. Treat any non-null icon error and empty icon data as no image, discard overlong lines completed within one read, reuse one JSON decoder, and merge edited sessions without rebuilding every field. --- PcVolumeControl/datasources/LineFramer.swift | 2 +- PcVolumeControl/models/ServerLine.swift | 46 ++++++++++---- .../repos/VolumeControlRepository.swift | 15 +++-- .../viewmodels/SliderViewModel.swift | 49 +++++---------- PcVolumeControlTests/LineFramerTests.swift | 5 ++ PcVolumeControlTests/ServerLineTests.swift | 63 ++++++++++++------- .../VolumeControlRepositoryTests.swift | 21 ++++++- 7 files changed, 122 insertions(+), 79 deletions(-) diff --git a/PcVolumeControl/datasources/LineFramer.swift b/PcVolumeControl/datasources/LineFramer.swift index 3416ec8..cf31cce 100644 --- a/PcVolumeControl/datasources/LineFramer.swift +++ b/PcVolumeControl/datasources/LineFramer.swift @@ -33,7 +33,7 @@ struct LineFramer { if lineEnd > lineStart, buffer[lineEnd - 1] == 0x0D { lineEnd -= 1 } - if lineEnd > lineStart { + if lineEnd > lineStart, lineEnd - lineStart <= maxLineLength { lines.append(Data(buffer[lineStart.. ServerLine { - (try? JSONDecoder().decode(Envelope.self, from: line))?.line ?? .ignored + /// Returns nil for a line to ignore: one that is not a JSON object, has neither or both + /// of the keys, or is an icon reply without an id. Throws only for a full state that + /// cannot be decoded, which ends the connection as it always has. + static func classify(_ line: Data) throws -> ServerLine? { + do { + return try decoder.decode(Envelope.self, from: line).line + } catch let error as MalformedStateError { + throw error + } catch { + return nil + } } + private static let decoder = JSONDecoder() + // Decodes the document once and picks the line type by which key is present. private struct Envelope: Decodable { - let line: ServerLine + let line: ServerLine? private enum CodingKeys: String, CodingKey { case defaultDevice, icon @@ -24,16 +33,28 @@ enum ServerLine { let container = try decoder.container(keyedBy: CodingKeys.self) switch (container.contains(.defaultDevice), container.contains(.icon)) { case (true, false): - line = .state(try FullState(from: decoder)) + do { + line = .state(try FullState(from: decoder)) + } catch { + throw MalformedStateError(underlying: error) + } case (false, true): line = .icon(try container.decode(IconReply.self, forKey: .icon)) default: - line = .ignored + line = nil } } } } +struct MalformedStateError: LocalizedError { + let underlying: Error + + var errorDescription: String? { + "The server sent a full state that could not be read: \(underlying.localizedDescription)" + } +} + /// The server's answer for one requested icon id. struct IconReply: Decodable { let id: String @@ -47,10 +68,11 @@ struct IconReply: Decodable { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) - // Any `error` value means "no image". A bad payload must still produce a reply - // for the id, so it is mapped to "no image" instead of failing the whole line. - let error = try? container.decodeIfPresent(String.self, forKey: .error) + // Any non-null `error` means "no image". A bad payload must still answer the id, + // so it maps to "no image" instead of failing the whole line. + let hasError = container.contains(.error) && (try? container.decodeNil(forKey: .error)) != true let base64 = try? container.decodeIfPresent(String.self, forKey: .data) - png = error == nil ? base64.flatMap { Data(base64Encoded: $0) } : nil + let decoded = hasError ? nil : base64.flatMap { Data(base64Encoded: $0) } + png = decoded?.isEmpty == false ? decoded : nil } } diff --git a/PcVolumeControl/repos/VolumeControlRepository.swift b/PcVolumeControl/repos/VolumeControlRepository.swift index 34af076..d9f7514 100644 --- a/PcVolumeControl/repos/VolumeControlRepository.swift +++ b/PcVolumeControl/repos/VolumeControlRepository.swift @@ -7,21 +7,20 @@ struct VolumeControlRepository { let deviceIdLookup = DeviceIdLookup() /// Full states and icon replies from the server; lines of any other kind are dropped. + /// Ends with an error for a full state that cannot be decoded. func serverLines() -> AsyncThrowingStream { AsyncThrowingStream { continuation in let task = Task { do { for try await bytes in transport.incoming() { - let line = ServerLine.classify(bytes) - switch line { - case .state(let state): - deviceIdLookup.ingest(state.deviceIds) - continuation.yield(line) - case .icon: - continuation.yield(line) - case .ignored: + guard let line = try ServerLine.classify(bytes) else { appLog("Ignoring unrecognized server line (\(bytes.count) bytes)") + continue + } + if case .state(let state) = line { + deviceIdLookup.ingest(state.deviceIds) } + continuation.yield(line) } continuation.finish() } catch { diff --git a/PcVolumeControl/viewmodels/SliderViewModel.swift b/PcVolumeControl/viewmodels/SliderViewModel.swift index 46a15e3..6ece5c6 100644 --- a/PcVolumeControl/viewmodels/SliderViewModel.swift +++ b/PcVolumeControl/viewmodels/SliderViewModel.swift @@ -175,14 +175,9 @@ final class SliderViewModel: ObservableObject { private func updateSessionsRespectingDebounce(with incoming: [FullState.Session]) { // Apply new naming protocol to sessions let processedSessions = incoming.map { session in - let displayName = parseSessionDisplayName(sessionId: session.id, fallbackName: session.name) - return FullState.Session( - id: session.id, - muted: session.muted, - name: displayName, - volume: session.volume, - iconId: session.iconId - ) + var processed = session + processed.name = parseSessionDisplayName(sessionId: session.id, fallbackName: session.name) + return processed } // If preserving order and we have a saved order, use it @@ -204,14 +199,7 @@ final class SliderViewModel: ObservableObject { sessions = sortedSessions.map { incoming in if editingIds.contains(incoming.id), let existing = sessions.first(where: { $0.id == incoming.id }) { - // Keep current values for editing session - return FullState.Session( - id: existing.id, - muted: existing.muted, - name: incoming.name, - volume: existing.volume, - iconId: incoming.iconId - ) + return incoming.keepingUserValues(of: existing) } else { return incoming } @@ -255,15 +243,7 @@ final class SliderViewModel: ObservableObject { if let session = incomingDict[sessionId] { if editingIds.contains(sessionId), let existingIdx = sessions.firstIndex(where: { $0.id == sessionId }) { - // Keep current values for editing session - let existing = sessions[existingIdx] - orderedSessions.append(FullState.Session( - id: sessionId, - muted: existing.muted, - name: session.name, - volume: existing.volume, - iconId: session.iconId - )) + orderedSessions.append(session.keepingUserValues(of: sessions[existingIdx])) } else { orderedSessions.append(session) } @@ -299,14 +279,7 @@ final class SliderViewModel: ObservableObject { guard let incoming = incomingDict[session.id] else { continue } if editingIds.contains(session.id) { - // Keep current values for editing session - updatedSessions.append(FullState.Session( - id: session.id, - muted: session.muted, - name: incoming.name, - volume: session.volume, - iconId: incoming.iconId - )) + updatedSessions.append(incoming.keepingUserValues(of: session)) } else { updatedSessions.append(incoming) } @@ -326,3 +299,13 @@ final class SliderViewModel: ObservableObject { } } } + +private extension FullState.Session { + /// This incoming session with the volume and mute of `existing`, for a session the user is editing. + func keepingUserValues(of existing: FullState.Session) -> FullState.Session { + var merged = self + merged.muted = existing.muted + merged.volume = existing.volume + return merged + } +} diff --git a/PcVolumeControlTests/LineFramerTests.swift b/PcVolumeControlTests/LineFramerTests.swift index cce328d..7188629 100644 --- a/PcVolumeControlTests/LineFramerTests.swift +++ b/PcVolumeControlTests/LineFramerTests.swift @@ -71,4 +71,9 @@ final class LineFramerTests: XCTestCase { XCTAssertEqual(strings(framer.append(Data("tail\nok\n".utf8))), ["ok"]) XCTAssertEqual(strings(framer.append(Data("fine\n".utf8))), ["fine"]) } + + func testOverlongLineCompletedInOneReadIsDiscarded() { + var framer = LineFramer(maxLineLength: 8) + XCTAssertEqual(strings(framer.append(Data("0123456789\n12345678\n".utf8))), ["12345678"]) + } } diff --git a/PcVolumeControlTests/ServerLineTests.swift b/PcVolumeControlTests/ServerLineTests.swift index 88466ce..35061ad 100644 --- a/PcVolumeControlTests/ServerLineTests.swift +++ b/PcVolumeControlTests/ServerLineTests.swift @@ -31,14 +31,14 @@ final class ServerLineTests: XCTestCase { {"protocolVersion":7,"icon":{"id":"0000notarealid","error":"notFound"}} """# - private func classify(_ text: String) -> ServerLine { - ServerLine.classify(Data(text.utf8)) + private func classify(_ text: String) throws -> ServerLine? { + try ServerLine.classify(Data(text.utf8)) } // MARK: - Full state decoding func testV7StateDecodesWithoutV8Fields() throws { - guard case .state(let state) = classify(Self.v7State) else { + guard case .state(let state) = try classify(Self.v7State) else { return XCTFail("Expected a full state") } XCTAssertNil(state.features) @@ -48,7 +48,7 @@ final class ServerLineTests: XCTestCase { } func testV8StateDecodesFeaturesAndIconIds() throws { - guard case .state(let state) = classify(Self.v8State) else { + guard case .state(let state) = try classify(Self.v8State) else { return XCTFail("Expected a full state") } XCTAssertEqual(state.features, ["icons"]) @@ -65,7 +65,7 @@ final class ServerLineTests: XCTestCase { of: #""applicationVersion":"v10","#, with: #""applicationVersion":"v10","features":["somethingNew"],"# ) - guard case .state(let state) = classify(text) else { + guard case .state(let state) = try classify(text) else { return XCTFail("Expected a full state") } XCTAssertEqual(state.features, ["somethingNew"]) @@ -74,7 +74,7 @@ final class ServerLineTests: XCTestCase { // MARK: - Icon replies func testIconImageReplyDecodesToPNG() throws { - guard case .icon(let reply) = classify(Self.iconImageReply) else { + guard case .icon(let reply) = try classify(Self.iconImageReply) else { return XCTFail("Expected an icon reply") } XCTAssertEqual(reply.id, "6b58026ae167f8f2e802f2531657443c") @@ -85,60 +85,75 @@ final class ServerLineTests: XCTestCase { XCTAssertEqual(image.size.height * image.scale, 16) } - func testIconNotFoundReplyHasNoImage() { - guard case .icon(let reply) = classify(Self.iconNotFoundReply) else { + func testIconNotFoundReplyHasNoImage() throws { + guard case .icon(let reply) = try classify(Self.iconNotFoundReply) else { return XCTFail("Expected an icon reply") } XCTAssertEqual(reply.id, "0000notarealid") XCTAssertNil(reply.png) } - func testIconReplyWithUnknownErrorHasNoImage() { + func testIconReplyWithUnknownErrorHasNoImage() throws { let text = #"{"protocolVersion":7,"icon":{"id":"abc","error":"somethingElse","data":"iVBORw0KGgo="}}"# - guard case .icon(let reply) = classify(text) else { + guard case .icon(let reply) = try classify(text) else { return XCTFail("Expected an icon reply") } XCTAssertNil(reply.png) } - func testIconReplyWithInvalidBase64StillAnswersTheId() { + func testIconReplyWithInvalidBase64StillAnswersTheId() throws { let text = #"{"protocolVersion":7,"icon":{"id":"abc","size":16,"mime":"image/png","data":"not base64!"}}"# - guard case .icon(let reply) = classify(text) else { + guard case .icon(let reply) = try classify(text) else { return XCTFail("Expected an icon reply") } XCTAssertEqual(reply.id, "abc") XCTAssertNil(reply.png) } - // MARK: - Classification + func testIconReplyWithNonStringErrorHasNoImage() throws { + let text = #"{"protocolVersion":7,"icon":{"id":"abc","error":{"code":3},"data":"iVBORw0KGgo="}}"# + guard case .icon(let reply) = try classify(text) else { + return XCTFail("Expected an icon reply") + } + XCTAssertNil(reply.png) + } - func testUnknownLineIsIgnored() { - guard case .ignored = classify(#"{"protocolVersion":7,"somethingNew":{"a":1}}"#) else { - return XCTFail("Expected the line to be ignored") + func testIconReplyWithEmptyDataHasNoImage() throws { + let text = #"{"protocolVersion":7,"icon":{"id":"abc","size":16,"mime":"image/png","data":""}}"# + guard case .icon(let reply) = try classify(text) else { + return XCTFail("Expected an icon reply") } + XCTAssertNil(reply.png) } - func testMalformedLinesAreIgnored() { + // MARK: - Classification + + func testUnknownLineIsIgnored() throws { + XCTAssertNil(try classify(#"{"protocolVersion":7,"somethingNew":{"a":1}}"#)) + } + + func testMalformedLinesAreIgnored() throws { for text in [ #"{"protocolVersion":7,"defaultDevice":{"deviceId":"#, - #"{"protocolVersion":7,"defaultDevice":{"deviceId":"x"}}"#, #"{"protocolVersion":7,"icon":{"error":"notFound"}}"#, "[1,2,3]", "not json", ] { - guard case .ignored = classify(text) else { - return XCTFail("Expected \(text) to be ignored") - } + XCTAssertNil(try classify(text), text) } } - func testLineWithBothStateAndIconIsIgnored() { + func testLineWithBothStateAndIconIsIgnored() throws { let text = Self.v7State.replacingOccurrences( of: #""protocolVersion":7,"#, with: #""protocolVersion":7,"icon":{"id":"abc","error":"notFound"},"# ) - guard case .ignored = classify(text) else { - return XCTFail("Expected the line to be ignored") + XCTAssertNil(try classify(text)) + } + + func testUndecodableFullStateThrows() { + XCTAssertThrowsError(try classify(#"{"protocolVersion":7,"defaultDevice":{"deviceId":"x"}}"#)) { error in + XCTAssertTrue(error is MalformedStateError) } } } diff --git a/PcVolumeControlTests/VolumeControlRepositoryTests.swift b/PcVolumeControlTests/VolumeControlRepositoryTests.swift index 460798f..549a0fc 100644 --- a/PcVolumeControlTests/VolumeControlRepositoryTests.swift +++ b/PcVolumeControlTests/VolumeControlRepositoryTests.swift @@ -26,11 +26,30 @@ final class VolumeControlRepositoryTests: XCTestCase { switch line { case .state: kinds.append("state") case .icon: kinds.append("icon") - case .ignored: kinds.append("ignored") } } XCTAssertEqual(kinds, ["state", "icon", "state"]) } + + func testUndecodableFullStateEndsTheStream() async { + let transport = ScriptedTransport(lines: [ + ServerLineTests.v7State, + #"{"protocolVersion":7,"defaultDevice":{"deviceId":"x"}}"#, + ServerLineTests.v7State, + ]) + let repo = VolumeControlRepository(transport: transport) + + var states = 0 + do { + for try await _ in repo.serverLines() { + states += 1 + } + XCTFail("Expected the stream to end with an error") + } catch { + XCTAssertTrue(error is MalformedStateError) + } + XCTAssertEqual(states, 1) + } } /// A transport that delivers a fixed list of lines, then ends. From dbe45185b4c3d43a9d9182799f283f47c7541d73 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 10:34:33 -0800 Subject: [PATCH 05/21] Request, cache and show application icons When the server lists the icons feature, ids that are not cached are requested in batches of at most 32 with at most 64 outstanding. Ids the server has no image for are not asked for again until the user connects anew. Icons are decoded off the main thread and cached in memory and in Caches, and each session row shows its icon or a placeholder of the same size. --- .../datasources/IconDiskCacheDataSource.swift | 64 ++++++++++ PcVolumeControl/models/IconId.swift | 10 ++ PcVolumeControl/models/VolumeUpdateDTOs.swift | 10 ++ PcVolumeControl/repos/IconRepository.swift | 37 ++++++ .../repos/VolumeControlRepository.swift | 8 ++ .../usecases/IconRequestPlanner.swift | 59 +++++++++ .../viewmodels/MainViewModel.swift | 115 +++++++++++++++++- PcVolumeControl/views/SessionCell.swift | 3 + PcVolumeControl/views/SessionIconView.swift | 45 +++++++ PcVolumeControl/views/SliderView.swift | 12 ++ PcVolumeControlTests/IconCacheTests.swift | 110 +++++++++++++++++ .../IconRequestPlannerTests.swift | 107 ++++++++++++++++ PcVolumeControlTests/ServerLineTests.swift | 12 ++ .../VolumeControlRepositoryTests.swift | 14 +++ 14 files changed, 601 insertions(+), 5 deletions(-) create mode 100644 PcVolumeControl/datasources/IconDiskCacheDataSource.swift create mode 100644 PcVolumeControl/models/IconId.swift create mode 100644 PcVolumeControl/repos/IconRepository.swift create mode 100644 PcVolumeControl/usecases/IconRequestPlanner.swift create mode 100644 PcVolumeControl/views/SessionIconView.swift create mode 100644 PcVolumeControlTests/IconCacheTests.swift create mode 100644 PcVolumeControlTests/IconRequestPlannerTests.swift diff --git a/PcVolumeControl/datasources/IconDiskCacheDataSource.swift b/PcVolumeControl/datasources/IconDiskCacheDataSource.swift new file mode 100644 index 0000000..8e0a264 --- /dev/null +++ b/PcVolumeControl/datasources/IconDiskCacheDataSource.swift @@ -0,0 +1,64 @@ +import Foundation + +protocol IconDiskCacheDataSourceProtocol { + func load(id: String) -> Data? + func store(_ png: Data, id: String) +} + +/// Icon PNGs on disk, one file per icon id, bounded by file count. The least recently +/// used files are evicted first. Invalid ids are never turned into paths. +struct IconDiskCacheDataSource: IconDiskCacheDataSourceProtocol { + private let directory: URL + private let maxEntries: Int + + init( + directory: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + .appendingPathComponent("AppIcons", isDirectory: true), + maxEntries: Int = 256 + ) { + self.directory = directory + self.maxEntries = maxEntries + } + + func load(id: String) -> Data? { + guard let url = fileURL(for: id), let data = try? Data(contentsOf: url) else { return nil } + // The modification date doubles as the last-used date for eviction. + try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: url.path) + return data + } + + func store(_ png: Data, id: String) { + guard let url = fileURL(for: id) else { return } + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try png.write(to: url, options: .atomic) + } catch { + appLog("Failed to cache icon \(id): \(error)") + return + } + evictIfNeeded() + } + + private func fileURL(for id: String) -> URL? { + guard IconId.isValid(id) else { return nil } + return directory.appendingPathComponent("\(id).png", isDirectory: false) + } + + private func evictIfNeeded() { + let fileManager = FileManager.default + guard let files = try? fileManager.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: [.contentModificationDateKey], + options: .skipsHiddenFiles + ), files.count > maxEntries else { return } + + let byLastUse = files + .map { url in + (url, (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? .distantPast) + } + .sorted { $0.1 < $1.1 } + for (url, _) in byLastUse.prefix(files.count - maxEntries) { + try? fileManager.removeItem(at: url) + } + } +} diff --git a/PcVolumeControl/models/IconId.swift b/PcVolumeControl/models/IconId.swift new file mode 100644 index 0000000..6d18656 --- /dev/null +++ b/PcVolumeControl/models/IconId.swift @@ -0,0 +1,10 @@ +import Foundation + +enum IconId { + /// Icon ids are 1 to 64 characters of `[a-z0-9]`, which also makes them safe file names. + static func isValid(_ id: String) -> Bool { + let bytes = id.utf8 + return (1...64).contains(bytes.count) + && bytes.allSatisfy { (0x30...0x39).contains($0) || (0x61...0x7A).contains($0) } + } +} diff --git a/PcVolumeControl/models/VolumeUpdateDTOs.swift b/PcVolumeControl/models/VolumeUpdateDTOs.swift index 1081254..159185f 100644 --- a/PcVolumeControl/models/VolumeUpdateDTOs.swift +++ b/PcVolumeControl/models/VolumeUpdateDTOs.swift @@ -38,3 +38,13 @@ struct OneSession : Codable { let volume: Double let muted: Bool } + +// v8: ask for application icons; only sent to a server whose full state lists "icons" in features +struct AIconRequest : Codable { + struct Payload : Codable { + let ids: [String] + let size: Int + } + let protocolVersion: Int + let iconRequest: Payload +} diff --git a/PcVolumeControl/repos/IconRepository.swift b/PcVolumeControl/repos/IconRepository.swift new file mode 100644 index 0000000..caf36d3 --- /dev/null +++ b/PcVolumeControl/repos/IconRepository.swift @@ -0,0 +1,37 @@ +import UIKit + +/// Decoded application icons by icon id, cached in memory (bounded) and on disk. Ids are +/// content-derived, so entries never need invalidating. Decoding runs on this actor, +/// off the main thread. +actor IconRepository { + private let disk: IconDiskCacheDataSourceProtocol + private let memory = NSCache() + + init(disk: IconDiskCacheDataSourceProtocol = IconDiskCacheDataSource()) { + self.disk = disk + memory.countLimit = 128 + } + + /// The cached icon for `id` from memory or disk, or nil if it is not cached. + func cachedIcon(for id: String) -> UIImage? { + if let image = memory.object(forKey: id as NSString) { + return image + } + guard let png = disk.load(id: id), let image = Self.decode(png) else { return nil } + memory.setObject(image, forKey: id as NSString) + return image + } + + /// Decodes `png` and caches it under `id`. Returns nil, caching nothing, when the data + /// is not a usable image. + func store(png: Data, for id: String) -> UIImage? { + guard let image = Self.decode(png) else { return nil } + memory.setObject(image, forKey: id as NSString) + disk.store(png, id: id) + return image + } + + private static func decode(_ png: Data) -> UIImage? { + UIImage(data: png)?.preparingForDisplay() + } +} diff --git a/PcVolumeControl/repos/VolumeControlRepository.swift b/PcVolumeControl/repos/VolumeControlRepository.swift index d9f7514..19cc0ad 100644 --- a/PcVolumeControl/repos/VolumeControlRepository.swift +++ b/PcVolumeControl/repos/VolumeControlRepository.swift @@ -64,6 +64,14 @@ struct VolumeControlRepository { try await send(dto) } + func requestIcons(ids: [String], size: Int) async throws { + let dto = AIconRequest( + protocolVersion: VolumeControlRepository.protocolVersion, + iconRequest: AIconRequest.Payload(ids: ids, size: size) + ) + try await send(dto) + } + private func send(_ dto: T) async throws { try await transport.outgoing(JSONEncoder().encode(dto)) } diff --git a/PcVolumeControl/usecases/IconRequestPlanner.swift b/PcVolumeControl/usecases/IconRequestPlanner.swift new file mode 100644 index 0000000..816364b --- /dev/null +++ b/PcVolumeControl/usecases/IconRequestPlanner.swift @@ -0,0 +1,59 @@ +import CoreGraphics + +/// Decides which icon ids to request, within the protocol's limits: at most +/// `maxIdsPerRequest` ids per request and `maxOutstanding` unanswered ids per connection. +struct IconRequestPlanner { + static let maxIdsPerRequest = 32 + static let maxOutstanding = 64 + + /// Ids requested on the current connection that have not been answered yet. + private(set) var outstanding = Set() + // Ids the server had no usable image for. Kept across reconnects so they are not + // asked for again in a loop; a new planner starts clean. + private var unavailable = Set() + + /// The requests to send now for `ids`, in order. Leaves out ids that are invalid, + /// repeated, in `skipping` (cached or being resolved locally), already outstanding, or + /// unavailable, and stops at the outstanding limit; the rest are planned once replies + /// free up room. Returns nothing unless the server supports icons. + mutating func requests(for ids: [String], supportsIcons: Bool, skipping: Set) -> [[String]] { + guard supportsIcons else { return [] } + + let capacity = Self.maxOutstanding - outstanding.count + var planned: [String] = [] + var seen = Set() + for id in ids where planned.count < capacity { + guard IconId.isValid(id), + seen.insert(id).inserted, + !skipping.contains(id), + !outstanding.contains(id), + !unavailable.contains(id) + else { continue } + planned.append(id) + } + outstanding.formUnion(planned) + + return stride(from: 0, to: planned.count, by: Self.maxIdsPerRequest).map { + Array(planned[$0.. Int { + Int(min(max((points * scale).rounded(), 16), 256)) + } +} diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index 645cfa7..bdfd11c 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -28,6 +28,9 @@ final class MainViewModel: ObservableObject { /// True only when the connection is live; controls are interactive only then. var isConnectionLive: Bool { connectionStatus == .connected } + /// Decoded icons for the current sessions, by icon id. + @Published private(set) var icons: [String: UIImage] = [:] + private let connect: ConnectToServerUseCase private var defUpdate: SendDefaultDeviceUpdateUseCase private var masterUpdate: SendMasterChannelUpdateUseCase @@ -53,17 +56,28 @@ final class MainViewModel: ObservableObject { private var connectedOverWiFi = false private var connectedOverCellular = false + // Icons (protocol v8 `icons` feature). + private let iconRepo: IconRepository + private var iconPlanner = IconRequestPlanner() + // Set by the session list; no icons are requested until then. + private var iconPixelSize: Int? + private var iconCacheLookups = Set() + // Ids looked up in the local cache and not found there: only these are requested. + private var iconsMissingFromCache = Set() + init(connect: ConnectToServerUseCase, defUpdate: SendDefaultDeviceUpdateUseCase, masterUpdate: SendMasterChannelUpdateUseCase, sessionUpdate: SendSessionUpdateUseCase, - serversRepo: ServersRepository) + serversRepo: ServersRepository, + iconRepo: IconRepository = IconRepository()) { self.connect = connect self.defUpdate = defUpdate self.masterUpdate = masterUpdate self.sessionUpdate = sessionUpdate self.serversRepo = serversRepo + self.iconRepo = iconRepo NotificationCenter.default.addObserver( forName: UIApplication.didEnterBackgroundNotification, @@ -156,6 +170,8 @@ final class MainViewModel: ObservableObject { closeConnection(repo) currentRepo = nil } + // The next connection may be to another server, so forget its unavailable icons too. + iconPlanner = IconRequestPlanner() // Clear the full state to trigger UI reset fullState = nil @@ -198,6 +214,7 @@ final class MainViewModel: ObservableObject { repo.transport.close() currentRepo = nil } + iconPlanner.connectionDropped() startReconnectLoop(to: server) } @@ -223,6 +240,7 @@ final class MainViewModel: ObservableObject { repo.transport.close() currentRepo = nil } + iconPlanner.connectionDropped() updateSharedStateDisconnected() guard let server = lastConnectedServer else { @@ -344,10 +362,15 @@ final class MainViewModel: ObservableObject { for try await line in repo.serverLines() { // Stop applying updates after cancellation so an in-flight value can't resurrect state. if Task.isCancelled { break } - guard case .state(let state) = line else { continue } - fullState = state // view state only here - connectionStatus = .connected - updateSharedState(with: state) // Update widget state + switch line { + case .state(let state): + fullState = state // view state only here + connectionStatus = .connected + updateSharedState(with: state) // Update widget state + resolveIcons(for: state) + case .icon(let reply): + handleIconReply(reply) + } } // Stream ended without throwing (server closed the connection). if !Task.isCancelled { handleConnectionLost() } @@ -379,6 +402,78 @@ final class MainViewModel: ObservableObject { } } + // MARK: - Icons + + /// Called by the session list with the pixel size it draws icons at. + func setIconPixelSize(_ size: Int) { + guard size != iconPixelSize else { return } + iconPixelSize = size + requestMissingIcons() + } + + private func resolveIcons(for state: FullState) { + guard state.supportsIcons else { return } + let ids = state.iconIds + let current = Set(ids) + if icons.keys.contains(where: { !current.contains($0) }) { + icons = icons.filter { current.contains($0.key) } + } + iconsMissingFromCache.formIntersection(current) + + let unchecked = ids.filter { + icons[$0] == nil && !iconCacheLookups.contains($0) && !iconsMissingFromCache.contains($0) + } + if !unchecked.isEmpty { + loadCachedIcons(unchecked) + } + requestMissingIcons() + } + + private func loadCachedIcons(_ ids: [String]) { + iconCacheLookups.formUnion(ids) + Task { + for id in ids { + let image = await iconRepo.cachedIcon(for: id) + iconCacheLookups.remove(id) + if let image { + icons[id] = image + } else { + iconsMissingFromCache.insert(id) + } + } + requestMissingIcons() + } + } + + private func requestMissingIcons() { + guard let state = fullState, let size = iconPixelSize, let repo = currentRepo else { return } + let skipping = Set(state.iconIds).subtracting(iconsMissingFromCache) + let batches = iconPlanner.requests(for: state.iconIds, supportsIcons: state.supportsIcons, skipping: skipping) + for ids in batches { + Task { try? await repo.requestIcons(ids: ids, size: size) } + } + } + + private func handleIconReply(_ reply: IconReply) { + defer { + // Ids left out at the outstanding limit are requested once earlier replies are in. + if iconPlanner.outstanding.isEmpty { requestMissingIcons() } + } + guard let png = reply.png else { + iconPlanner.recordReply(for: reply.id, available: false) + return + } + iconPlanner.recordReply(for: reply.id, available: true) + iconsMissingFromCache.remove(reply.id) + Task { + if let image = await iconRepo.store(png: png, for: reply.id) { + icons[reply.id] = image + } else { + iconPlanner.recordReply(for: reply.id, available: false) + } + } + } + // MARK: - Shared State Management (for Widget) private func updateSharedState(with state: FullState) { @@ -645,4 +740,14 @@ class FullState: Codable, Equatable { self.defaultDevice = defaultDevice self.features = features } + + var supportsIcons: Bool { + features?.contains("icons") ?? false + } + + /// Distinct icon ids of the default device's sessions, in session order. + var iconIds: [String] { + var seen = Set() + return defaultDevice.sessions.compactMap(\.iconId).filter { seen.insert($0).inserted } + } } diff --git a/PcVolumeControl/views/SessionCell.swift b/PcVolumeControl/views/SessionCell.swift index 234ffc5..30492c5 100644 --- a/PcVolumeControl/views/SessionCell.swift +++ b/PcVolumeControl/views/SessionCell.swift @@ -140,6 +140,7 @@ struct RecessedCapsuleToggleStyle: ToggleStyle { struct SessionCell: View { @Binding var session: FullState.Session + var icon: UIImage? = nil var isChat: Bool = false var chatMode: Bool = false var isMasterMuted: Bool = false @@ -201,6 +202,8 @@ struct SessionCell: View { } HStack { + SessionIconView(image: icon) + // Chat balance indicator if isChat { Image(systemName: "arrow.up.arrow.down.circle.fill") diff --git a/PcVolumeControl/views/SessionIconView.swift b/PcVolumeControl/views/SessionIconView.swift new file mode 100644 index 0000000..703c22c --- /dev/null +++ b/PcVolumeControl/views/SessionIconView.swift @@ -0,0 +1,45 @@ +import SwiftUI + +/// An application's icon in a session row, or a neutral placeholder of the same size +/// while the icon is unknown, loading or unavailable. Decorative for VoiceOver: the +/// row's name already identifies the application. +struct SessionIconView: View { + /// Edge length at the default Dynamic Type size; scales with `.subheadline` like the name. + static let basePointSize: CGFloat = 22 + + let image: UIImage? + + @ScaledMetric(relativeTo: .subheadline) private var size = SessionIconView.basePointSize + + var body: some View { + ZStack { + if let image { + Image(uiImage: image) + .resizable() + .interpolation(.high) + .scaledToFit() + } else { + RoundedRectangle(cornerRadius: size * 0.22, style: .continuous) + .fill(Color.white.opacity(0.12)) + Image(systemName: "waveform") + .resizable() + .scaledToFit() + .padding(size * 0.25) + .foregroundColor(.white.opacity(0.45)) + } + } + .frame(width: size, height: size) + .accessibilityHidden(true) + } +} + +#Preview { + HStack { + SessionIconView(image: nil) + Text("Spotify") + .font(.subheadline) + .foregroundColor(.white) + } + .padding() + .background(Color.almostBlack) +} diff --git a/PcVolumeControl/views/SliderView.swift b/PcVolumeControl/views/SliderView.swift index 8f84fdb..fff81a9 100644 --- a/PcVolumeControl/views/SliderView.swift +++ b/PcVolumeControl/views/SliderView.swift @@ -8,6 +8,13 @@ struct SliderView: View { @State private var showSettings = false @State private var showOverlay = false + @Environment(\.displayScale) private var displayScale + // Matches SessionIconView's size so icons are requested at the pixel size they are drawn at. + @ScaledMetric(relativeTo: .subheadline) private var iconPointSize = SessionIconView.basePointSize + private var iconPixelSize: Int { + IconRequestPlanner.pixelSize(points: iconPointSize, scale: displayScale) + } + // Connection-status banner; lives outside the disabled content so its buttons stay tappable. @ViewBuilder private var connectionBanner: some View { @@ -85,6 +92,7 @@ struct SliderView: View { ForEach($vm.sessions) { $session in SessionCell( session: $session, + icon: session.iconId.flatMap { mainVM.icons[$0] }, isChat: vm.chatBalanceSessionId == session.id, chatMode: vm.chatBalanceMode, isMasterMuted: vm.isMasterMuted, @@ -134,6 +142,10 @@ struct SliderView: View { .onReceive(mainVM.$fullState) { newState in vm.fullState = newState } + .onAppear { mainVM.setIconPixelSize(iconPixelSize) } + .onChange(of: iconPixelSize) { _, newSize in + mainVM.setIconPixelSize(newSize) + } } } diff --git a/PcVolumeControlTests/IconCacheTests.swift b/PcVolumeControlTests/IconCacheTests.swift new file mode 100644 index 0000000..daf9a2b --- /dev/null +++ b/PcVolumeControlTests/IconCacheTests.swift @@ -0,0 +1,110 @@ +// +// IconCacheTests.swift +// PcVolumeControlTests +// +// The on-disk icon cache and the repository that decodes and caches icons. +// + +import XCTest +import UIKit +@testable import PcVolumeControl + +final class IconCacheTests: XCTestCase { + + private var directory: URL! + + override func setUpWithError() throws { + try super.setUpWithError() + directory = FileManager.default.temporaryDirectory + .appendingPathComponent("IconCacheTests-\(UUID().uuidString)", isDirectory: true) + } + + override func tearDownWithError() throws { + try? FileManager.default.removeItem(at: directory) + try super.tearDownWithError() + } + + private func samplePNG() throws -> Data { + guard case .icon(let reply) = try ServerLine.classify(Data(ServerLineTests.iconImageReply.utf8)) else { + throw XCTSkip("Sample icon reply did not decode") + } + return try XCTUnwrap(reply.png) + } + + private func cachedFileNames() -> [String] { + ((try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []).sorted() + } + + // MARK: - Disk cache + + func testStoreThenLoad() { + let disk = IconDiskCacheDataSource(directory: directory) + let data = Data([1, 2, 3]) + disk.store(data, id: "abc123") + XCTAssertEqual(disk.load(id: "abc123"), data) + XCTAssertEqual(cachedFileNames(), ["abc123.png"]) + } + + func testLoadOfUnknownIdIsNil() { + let disk = IconDiskCacheDataSource(directory: directory) + XCTAssertNil(disk.load(id: "abc123")) + } + + func testInvalidIdsAreNeverUsedAsPaths() { + let disk = IconDiskCacheDataSource(directory: directory) + for id in ["../escape", "a/b", "ABC", "", ".hidden", String(repeating: "a", count: 65)] { + disk.store(Data([1]), id: id) + XCTAssertNil(disk.load(id: id), id) + } + XCTAssertEqual(cachedFileNames(), []) + XCTAssertFalse(FileManager.default.fileExists( + atPath: directory.deletingLastPathComponent().appendingPathComponent("escape.png").path + )) + } + + func testCacheIsBoundedByEntryCount() throws { + let disk = IconDiskCacheDataSource(directory: directory, maxEntries: 3) + for index in 0..<3 { + disk.store(Data([UInt8(index)]), id: "old\(index)") + } + // Make the existing files clearly older than anything stored next. + for name in cachedFileNames() { + try FileManager.default.setAttributes( + [.modificationDate: Date(timeIntervalSinceNow: -3600)], + ofItemAtPath: directory.appendingPathComponent(name).path + ) + } + // Loading refreshes "old2", so "old0" and "old1" are the least recently used. + XCTAssertNotNil(disk.load(id: "old2")) + + disk.store(Data([9]), id: "new0") + disk.store(Data([9]), id: "new1") + + XCTAssertEqual(cachedFileNames(), ["new0.png", "new1.png", "old2.png"]) + } + + // MARK: - Repository + + func testRepositoryStoresDecodedIconsAndReadsThemBack() async throws { + let png = try samplePNG() + let repo = IconRepository(disk: IconDiskCacheDataSource(directory: directory)) + + let isCachedBefore = await repo.cachedIcon(for: "6b58026ae167f8f2e802f2531657443c") != nil + XCTAssertFalse(isCachedBefore) + let stored = await repo.store(png: png, for: "6b58026ae167f8f2e802f2531657443c") + XCTAssertNotNil(stored) + XCTAssertEqual(cachedFileNames(), ["6b58026ae167f8f2e802f2531657443c.png"]) + + // A fresh repository (empty memory cache) finds it on disk. + let reloaded = IconRepository(disk: IconDiskCacheDataSource(directory: directory)) + let image = await reloaded.cachedIcon(for: "6b58026ae167f8f2e802f2531657443c") + XCTAssertEqual(image.map { $0.size.width * $0.scale }, 16) + } + + func testRepositoryRejectsDataThatIsNotAnImage() async { + let repo = IconRepository(disk: IconDiskCacheDataSource(directory: directory)) + let stored = await repo.store(png: Data("not a png".utf8), for: "abc") + XCTAssertNil(stored) + XCTAssertEqual(cachedFileNames(), []) + } +} diff --git a/PcVolumeControlTests/IconRequestPlannerTests.swift b/PcVolumeControlTests/IconRequestPlannerTests.swift new file mode 100644 index 0000000..b76ef59 --- /dev/null +++ b/PcVolumeControlTests/IconRequestPlannerTests.swift @@ -0,0 +1,107 @@ +// +// IconRequestPlannerTests.swift +// PcVolumeControlTests +// +// Which icon ids are requested, and when, within the protocol's limits. +// + +import XCTest +@testable import PcVolumeControl + +final class IconRequestPlannerTests: XCTestCase { + + private func ids(_ count: Int, prefix: String = "id") -> [String] { + (0.. Date: Sun, 15 Nov 2026 10:49:57 -0800 Subject: [PATCH 06/21] Address review of icon requests and caching Cache icons by id and requested pixel size so a larger Dynamic Type size fetches sharper icons, and share one sizing function between the row and the request. Request more ids whenever a full batch fits, drop replies that were not asked for, keep ids being decoded from being requested again, ignore lookups and decodes that finished after a size change or disconnect, load cached icons in one batch, and evict the disk cache only when its maintained count exceeds the bound. --- .../datasources/IconDiskCacheDataSource.swift | 52 +++++++---- PcVolumeControl/repos/IconRepository.swift | 39 +++++--- .../usecases/IconRequestPlanner.swift | 41 +++++--- .../viewmodels/MainViewModel.swift | 87 +++++++++++------ PcVolumeControl/views/SessionIconView.swift | 13 ++- PcVolumeControl/views/SliderView.swift | 5 +- PcVolumeControlTests/IconCacheTests.swift | 70 ++++++++------ .../IconRequestPlannerTests.swift | 93 +++++++++++++------ 8 files changed, 264 insertions(+), 136 deletions(-) diff --git a/PcVolumeControl/datasources/IconDiskCacheDataSource.swift b/PcVolumeControl/datasources/IconDiskCacheDataSource.swift index 8e0a264..e1d69ee 100644 --- a/PcVolumeControl/datasources/IconDiskCacheDataSource.swift +++ b/PcVolumeControl/datasources/IconDiskCacheDataSource.swift @@ -1,15 +1,19 @@ import Foundation protocol IconDiskCacheDataSourceProtocol { - func load(id: String) -> Data? - func store(_ png: Data, id: String) + func load(id: String, size: Int) -> Data? + func store(_ png: Data, id: String, size: Int) } -/// Icon PNGs on disk, one file per icon id, bounded by file count. The least recently -/// used files are evicted first. Invalid ids are never turned into paths. -struct IconDiskCacheDataSource: IconDiskCacheDataSourceProtocol { +/// Icon PNGs on disk, one file per icon id and requested pixel size, bounded by file +/// count. When the bound is exceeded the least recently used files are evicted down to +/// three quarters of it. Invalid ids are never turned into paths. Not thread-safe: use +/// from one isolation domain. +final class IconDiskCacheDataSource: IconDiskCacheDataSourceProtocol { private let directory: URL private let maxEntries: Int + // Counted from the directory on first store, then maintained; eviction recounts. + private var entryCount: Int? init( directory: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] @@ -20,15 +24,16 @@ struct IconDiskCacheDataSource: IconDiskCacheDataSourceProtocol { self.maxEntries = maxEntries } - func load(id: String) -> Data? { - guard let url = fileURL(for: id), let data = try? Data(contentsOf: url) else { return nil } + func load(id: String, size: Int) -> Data? { + guard let url = fileURL(for: id, size: size), let data = try? Data(contentsOf: url) else { return nil } // The modification date doubles as the last-used date for eviction. try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: url.path) return data } - func store(_ png: Data, id: String) { - guard let url = fileURL(for: id) else { return } + func store(_ png: Data, id: String, size: Int) { + guard let url = fileURL(for: id, size: size) else { return } + let isNewFile = !FileManager.default.fileExists(atPath: url.path) do { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) try png.write(to: url, options: .atomic) @@ -36,29 +41,40 @@ struct IconDiskCacheDataSource: IconDiskCacheDataSourceProtocol { appLog("Failed to cache icon \(id): \(error)") return } - evictIfNeeded() + let count = entryCount.map { $0 + (isNewFile ? 1 : 0) } ?? cachedFiles().count + entryCount = count + if count > maxEntries { + evict() + } } - private func fileURL(for id: String) -> URL? { + private func fileURL(for id: String, size: Int) -> URL? { guard IconId.isValid(id) else { return nil } - return directory.appendingPathComponent("\(id).png", isDirectory: false) + return directory.appendingPathComponent("\(id)_\(size).png", isDirectory: false) } - private func evictIfNeeded() { - let fileManager = FileManager.default - guard let files = try? fileManager.contentsOfDirectory( + private func cachedFiles() -> [URL] { + (try? FileManager.default.contentsOfDirectory( at: directory, includingPropertiesForKeys: [.contentModificationDateKey], options: .skipsHiddenFiles - ), files.count > maxEntries else { return } + )) ?? [] + } + private func evict() { + let files = cachedFiles() + let keep = maxEntries * 3 / 4 let byLastUse = files .map { url in (url, (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? .distantPast) } .sorted { $0.1 < $1.1 } - for (url, _) in byLastUse.prefix(files.count - maxEntries) { - try? fileManager.removeItem(at: url) + var removed = 0 + for (url, _) in byLastUse.prefix(max(files.count - keep, 0)) { + if (try? FileManager.default.removeItem(at: url)) != nil { + removed += 1 + } } + entryCount = files.count - removed } } diff --git a/PcVolumeControl/repos/IconRepository.swift b/PcVolumeControl/repos/IconRepository.swift index caf36d3..c7f3c8d 100644 --- a/PcVolumeControl/repos/IconRepository.swift +++ b/PcVolumeControl/repos/IconRepository.swift @@ -1,8 +1,8 @@ import UIKit -/// Decoded application icons by icon id, cached in memory (bounded) and on disk. Ids are -/// content-derived, so entries never need invalidating. Decoding runs on this actor, -/// off the main thread. +/// Decoded application icons by icon id and requested pixel size, cached in memory +/// (bounded) and on disk. Ids are content-derived, so entries never need invalidating. +/// Decoding runs on this actor, off the main thread. actor IconRepository { private let disk: IconDiskCacheDataSourceProtocol private let memory = NSCache() @@ -12,25 +12,34 @@ actor IconRepository { memory.countLimit = 128 } - /// The cached icon for `id` from memory or disk, or nil if it is not cached. - func cachedIcon(for id: String) -> UIImage? { - if let image = memory.object(forKey: id as NSString) { - return image + /// The icons among `ids` that are cached at `size`, from memory or disk. + func cachedIcons(for ids: [String], size: Int) -> [String: UIImage] { + var found: [String: UIImage] = [:] + for id in ids { + let key = Self.key(id, size) + if let image = memory.object(forKey: key) { + found[id] = image + } else if let png = disk.load(id: id, size: size), let image = Self.decode(png) { + memory.setObject(image, forKey: key) + found[id] = image + } } - guard let png = disk.load(id: id), let image = Self.decode(png) else { return nil } - memory.setObject(image, forKey: id as NSString) - return image + return found } - /// Decodes `png` and caches it under `id`. Returns nil, caching nothing, when the data - /// is not a usable image. - func store(png: Data, for id: String) -> UIImage? { + /// Decodes `png`, requested at `size`, and caches it under `id`. Returns nil, caching + /// nothing, when the data is not a usable image. + func store(png: Data, for id: String, size: Int) -> UIImage? { guard let image = Self.decode(png) else { return nil } - memory.setObject(image, forKey: id as NSString) - disk.store(png, id: id) + memory.setObject(image, forKey: Self.key(id, size)) + disk.store(png, id: id, size: size) return image } + private static func key(_ id: String, _ size: Int) -> NSString { + NSString(string: "\(id)_\(size)") + } + private static func decode(_ png: Data) -> UIImage? { UIImage(data: png)?.preparingForDisplay() } diff --git a/PcVolumeControl/usecases/IconRequestPlanner.swift b/PcVolumeControl/usecases/IconRequestPlanner.swift index 816364b..23ebbd1 100644 --- a/PcVolumeControl/usecases/IconRequestPlanner.swift +++ b/PcVolumeControl/usecases/IconRequestPlanner.swift @@ -6,17 +6,23 @@ struct IconRequestPlanner { static let maxIdsPerRequest = 32 static let maxOutstanding = 64 - /// Ids requested on the current connection that have not been answered yet. - private(set) var outstanding = Set() + /// Ids requested on the current connection and not answered yet, with the pixel size + /// each was requested at. + private(set) var outstanding: [String: Int] = [:] // Ids the server had no usable image for. Kept across reconnects so they are not // asked for again in a loop; a new planner starts clean. private var unavailable = Set() - /// The requests to send now for `ids`, in order. Leaves out ids that are invalid, - /// repeated, in `skipping` (cached or being resolved locally), already outstanding, or - /// unavailable, and stops at the outstanding limit; the rest are planned once replies - /// free up room. Returns nothing unless the server supports icons. - mutating func requests(for ids: [String], supportsIcons: Bool, skipping: Set) -> [[String]] { + /// True when a full request fits under the outstanding limit. + var hasRoomForFullBatch: Bool { + outstanding.count + Self.maxIdsPerRequest <= Self.maxOutstanding + } + + /// The requests to send now for `ids`, in order, at `size` pixels. Leaves out ids that + /// are invalid, repeated, in `skipping` (cached or being resolved locally), already + /// outstanding, or unavailable, and stops at the outstanding limit; the rest are + /// planned once replies free up room. Returns nothing unless the server supports icons. + mutating func requests(for ids: [String], size: Int, supportsIcons: Bool, skipping: Set) -> [[String]] { guard supportsIcons else { return [] } let capacity = Self.maxOutstanding - outstanding.count @@ -26,25 +32,34 @@ struct IconRequestPlanner { guard IconId.isValid(id), seen.insert(id).inserted, !skipping.contains(id), - !outstanding.contains(id), + outstanding[id] == nil, !unavailable.contains(id) else { continue } planned.append(id) } - outstanding.formUnion(planned) + for id in planned { + outstanding[id] = size + } return stride(from: 0, to: planned.count, by: Self.maxIdsPerRequest).map { Array(planned[$0.. Int? { + guard let size = outstanding.removeValue(forKey: id) else { return nil } if !available { unavailable.insert(id) } + return size + } + + /// For an image that arrived but could not be decoded. + mutating func markUnavailable(_ id: String) { + unavailable.insert(id) } /// Replies to ids requested on a dropped connection never arrive. diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index bdfd11c..5d4bd95 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -56,14 +56,19 @@ final class MainViewModel: ObservableObject { private var connectedOverWiFi = false private var connectedOverCellular = false - // Icons (protocol v8 `icons` feature). + // Icons (protocol v8 `icons` feature). The sets describe ids at the current pixel size; + // `icons` keeps showing images of an earlier size until replacements arrive. private let iconRepo: IconRepository private var iconPlanner = IconRequestPlanner() // Set by the session list; no icons are requested until then. private var iconPixelSize: Int? - private var iconCacheLookups = Set() - // Ids looked up in the local cache and not found there: only these are requested. + private var iconsAtCurrentSize = Set() + // A cache lookup or decode is in flight. + private var iconsResolving = Set() + // Looked up in the local cache and not found there: only these are requested. private var iconsMissingFromCache = Set() + // Bumped when in-flight lookups and decodes no longer apply (new pixel size, user disconnect). + private var iconGeneration = 0 init(connect: ConnectToServerUseCase, defUpdate: SendDefaultDeviceUpdateUseCase, @@ -172,6 +177,8 @@ final class MainViewModel: ObservableObject { } // The next connection may be to another server, so forget its unavailable icons too. iconPlanner = IconRequestPlanner() + icons = [:] + resetIconResolution() // Clear the full state to trigger UI reset fullState = nil @@ -408,47 +415,59 @@ final class MainViewModel: ObservableObject { func setIconPixelSize(_ size: Int) { guard size != iconPixelSize else { return } iconPixelSize = size - requestMissingIcons() + resetIconResolution() + if let state = fullState { resolveIcons(for: state) } + } + + private func resetIconResolution() { + iconGeneration += 1 + iconsAtCurrentSize.removeAll() + iconsResolving.removeAll() + iconsMissingFromCache.removeAll() } private func resolveIcons(for state: FullState) { - guard state.supportsIcons else { return } + guard state.supportsIcons, let size = iconPixelSize else { return } let ids = state.iconIds let current = Set(ids) if icons.keys.contains(where: { !current.contains($0) }) { icons = icons.filter { current.contains($0.key) } } + iconsAtCurrentSize.formIntersection(current) iconsMissingFromCache.formIntersection(current) let unchecked = ids.filter { - icons[$0] == nil && !iconCacheLookups.contains($0) && !iconsMissingFromCache.contains($0) + !iconsAtCurrentSize.contains($0) && !iconsResolving.contains($0) && !iconsMissingFromCache.contains($0) } if !unchecked.isEmpty { - loadCachedIcons(unchecked) + loadCachedIcons(unchecked, size: size) } requestMissingIcons() } - private func loadCachedIcons(_ ids: [String]) { - iconCacheLookups.formUnion(ids) + private func loadCachedIcons(_ ids: [String], size: Int) { + let generation = iconGeneration + iconsResolving.formUnion(ids) Task { - for id in ids { - let image = await iconRepo.cachedIcon(for: id) - iconCacheLookups.remove(id) - if let image { - icons[id] = image - } else { - iconsMissingFromCache.insert(id) - } + let found = await iconRepo.cachedIcons(for: ids, size: size) + guard generation == iconGeneration else { return } + iconsResolving.subtract(ids) + if !found.isEmpty { + icons.merge(found) { _, cached in cached } } + iconsAtCurrentSize.formUnion(found.keys) + iconsMissingFromCache.formUnion(ids.filter { found[$0] == nil }) requestMissingIcons() } } private func requestMissingIcons() { guard let state = fullState, let size = iconPixelSize, let repo = currentRepo else { return } - let skipping = Set(state.iconIds).subtracting(iconsMissingFromCache) - let batches = iconPlanner.requests(for: state.iconIds, supportsIcons: state.supportsIcons, skipping: skipping) + let skipping = Set(state.iconIds).subtracting(iconsMissingFromCache).union(iconsResolving) + let batches = iconPlanner.requests( + for: state.iconIds, size: size, supportsIcons: state.supportsIcons, skipping: skipping + ) + // A failed send means the connection is failing; its loss resets the outstanding ids. for ids in batches { Task { try? await repo.requestIcons(ids: ids, size: size) } } @@ -456,20 +475,30 @@ final class MainViewModel: ObservableObject { private func handleIconReply(_ reply: IconReply) { defer { - // Ids left out at the outstanding limit are requested once earlier replies are in. - if iconPlanner.outstanding.isEmpty { requestMissingIcons() } + // Ids left out at the outstanding limit are requested as replies free up room. + if iconPlanner.hasRoomForFullBatch { requestMissingIcons() } } - guard let png = reply.png else { - iconPlanner.recordReply(for: reply.id, available: false) - return + // A reply this connection did not ask for is dropped. + guard let size = iconPlanner.recordReply(for: reply.id, available: reply.png != nil), + let png = reply.png + else { return } + + let id = reply.id + let generation = iconGeneration + let isCurrentSize = size == iconPixelSize + if isCurrentSize { + iconsResolving.insert(id) } - iconPlanner.recordReply(for: reply.id, available: true) - iconsMissingFromCache.remove(reply.id) Task { - if let image = await iconRepo.store(png: png, for: reply.id) { - icons[reply.id] = image + let image = await iconRepo.store(png: png, for: id, size: size) + guard generation == iconGeneration, isCurrentSize else { return } + iconsResolving.remove(id) + if let image { + icons[id] = image + iconsAtCurrentSize.insert(id) + iconsMissingFromCache.remove(id) } else { - iconPlanner.recordReply(for: reply.id, available: false) + iconPlanner.markUnavailable(id) } } } diff --git a/PcVolumeControl/views/SessionIconView.swift b/PcVolumeControl/views/SessionIconView.swift index 703c22c..982e4a6 100644 --- a/PcVolumeControl/views/SessionIconView.swift +++ b/PcVolumeControl/views/SessionIconView.swift @@ -4,14 +4,19 @@ import SwiftUI /// while the icon is unknown, loading or unavailable. Decorative for VoiceOver: the /// row's name already identifies the application. struct SessionIconView: View { - /// Edge length at the default Dynamic Type size; scales with `.subheadline` like the name. - static let basePointSize: CGFloat = 22 - let image: UIImage? - @ScaledMetric(relativeTo: .subheadline) private var size = SessionIconView.basePointSize + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + + /// Edge length in points: 22 at the default Dynamic Type size, scaled like `.subheadline` + /// (the row's name). + nonisolated static func pointSize(for dynamicTypeSize: DynamicTypeSize) -> CGFloat { + let traits = UITraitCollection(preferredContentSizeCategory: UIContentSizeCategory(dynamicTypeSize)) + return UIFontMetrics(forTextStyle: .subheadline).scaledValue(for: 22, compatibleWith: traits) + } var body: some View { + let size = Self.pointSize(for: dynamicTypeSize) ZStack { if let image { Image(uiImage: image) diff --git a/PcVolumeControl/views/SliderView.swift b/PcVolumeControl/views/SliderView.swift index fff81a9..08a999a 100644 --- a/PcVolumeControl/views/SliderView.swift +++ b/PcVolumeControl/views/SliderView.swift @@ -9,10 +9,9 @@ struct SliderView: View { @State private var showOverlay = false @Environment(\.displayScale) private var displayScale - // Matches SessionIconView's size so icons are requested at the pixel size they are drawn at. - @ScaledMetric(relativeTo: .subheadline) private var iconPointSize = SessionIconView.basePointSize + @Environment(\.dynamicTypeSize) private var dynamicTypeSize private var iconPixelSize: Int { - IconRequestPlanner.pixelSize(points: iconPointSize, scale: displayScale) + IconRequestPlanner.pixelSize(points: SessionIconView.pointSize(for: dynamicTypeSize), scale: displayScale) } // Connection-status banner; lives outside the disabled content so its buttons stay tappable. diff --git a/PcVolumeControlTests/IconCacheTests.swift b/PcVolumeControlTests/IconCacheTests.swift index daf9a2b..3d9b36c 100644 --- a/PcVolumeControlTests/IconCacheTests.swift +++ b/PcVolumeControlTests/IconCacheTests.swift @@ -40,70 +40,86 @@ final class IconCacheTests: XCTestCase { func testStoreThenLoad() { let disk = IconDiskCacheDataSource(directory: directory) let data = Data([1, 2, 3]) - disk.store(data, id: "abc123") - XCTAssertEqual(disk.load(id: "abc123"), data) - XCTAssertEqual(cachedFileNames(), ["abc123.png"]) + disk.store(data, id: "abc123", size: 66) + XCTAssertEqual(disk.load(id: "abc123", size: 66), data) + XCTAssertEqual(cachedFileNames(), ["abc123_66.png"]) } - func testLoadOfUnknownIdIsNil() { + func testLoadOfUnknownIdOrSizeIsNil() { let disk = IconDiskCacheDataSource(directory: directory) - XCTAssertNil(disk.load(id: "abc123")) + XCTAssertNil(disk.load(id: "abc123", size: 66)) + disk.store(Data([1]), id: "abc123", size: 66) + XCTAssertNil(disk.load(id: "abc123", size: 132)) } func testInvalidIdsAreNeverUsedAsPaths() { let disk = IconDiskCacheDataSource(directory: directory) for id in ["../escape", "a/b", "ABC", "", ".hidden", String(repeating: "a", count: 65)] { - disk.store(Data([1]), id: id) - XCTAssertNil(disk.load(id: id), id) + disk.store(Data([1]), id: id, size: 66) + XCTAssertNil(disk.load(id: id, size: 66), id) } XCTAssertEqual(cachedFileNames(), []) XCTAssertFalse(FileManager.default.fileExists( - atPath: directory.deletingLastPathComponent().appendingPathComponent("escape.png").path + atPath: directory.deletingLastPathComponent().appendingPathComponent("escape_66.png").path )) } func testCacheIsBoundedByEntryCount() throws { - let disk = IconDiskCacheDataSource(directory: directory, maxEntries: 3) - for index in 0..<3 { - disk.store(Data([UInt8(index)]), id: "old\(index)") + let disk = IconDiskCacheDataSource(directory: directory, maxEntries: 4) + for index in 0..<4 { + disk.store(Data([UInt8(index)]), id: "old\(index)", size: 66) } - // Make the existing files clearly older than anything stored next. - for name in cachedFileNames() { + // Make the existing files clearly older than anything stored next, oldest first. + for (offset, name) in cachedFileNames().enumerated() { try FileManager.default.setAttributes( - [.modificationDate: Date(timeIntervalSinceNow: -3600)], + [.modificationDate: Date(timeIntervalSinceNow: Double(offset - 10) * 60)], ofItemAtPath: directory.appendingPathComponent(name).path ) } - // Loading refreshes "old2", so "old0" and "old1" are the least recently used. - XCTAssertNotNil(disk.load(id: "old2")) + // Loading refreshes "old0", so "old1" and "old2" are now the least recently used. + XCTAssertNotNil(disk.load(id: "old0", size: 66)) - disk.store(Data([9]), id: "new0") - disk.store(Data([9]), id: "new1") + // Exceeding 4 entries evicts down to 3 (three quarters). + disk.store(Data([9]), id: "new0", size: 66) + XCTAssertEqual(cachedFileNames(), ["new0_66.png", "old0_66.png", "old3_66.png"]) - XCTAssertEqual(cachedFileNames(), ["new0.png", "new1.png", "old2.png"]) + disk.store(Data([9]), id: "new1", size: 66) + XCTAssertEqual(cachedFileNames(), ["new0_66.png", "new1_66.png", "old0_66.png", "old3_66.png"]) + } + + func testRewritingAnEntryDoesNotCountTwice() { + let disk = IconDiskCacheDataSource(directory: directory, maxEntries: 2) + disk.store(Data([1]), id: "a", size: 66) + disk.store(Data([2]), id: "b", size: 66) + disk.store(Data([3]), id: "b", size: 66) + XCTAssertEqual(cachedFileNames(), ["a_66.png", "b_66.png"]) } // MARK: - Repository func testRepositoryStoresDecodedIconsAndReadsThemBack() async throws { let png = try samplePNG() + let id = "6b58026ae167f8f2e802f2531657443c" let repo = IconRepository(disk: IconDiskCacheDataSource(directory: directory)) - let isCachedBefore = await repo.cachedIcon(for: "6b58026ae167f8f2e802f2531657443c") != nil - XCTAssertFalse(isCachedBefore) - let stored = await repo.store(png: png, for: "6b58026ae167f8f2e802f2531657443c") + let before = await repo.cachedIcons(for: [id], size: 16) + XCTAssertTrue(before.isEmpty) + let stored = await repo.store(png: png, for: id, size: 16) XCTAssertNotNil(stored) - XCTAssertEqual(cachedFileNames(), ["6b58026ae167f8f2e802f2531657443c.png"]) + XCTAssertEqual(cachedFileNames(), ["\(id)_16.png"]) - // A fresh repository (empty memory cache) finds it on disk. + // A fresh repository (empty memory cache) finds it on disk, at that size only. let reloaded = IconRepository(disk: IconDiskCacheDataSource(directory: directory)) - let image = await reloaded.cachedIcon(for: "6b58026ae167f8f2e802f2531657443c") - XCTAssertEqual(image.map { $0.size.width * $0.scale }, 16) + let found = await reloaded.cachedIcons(for: [id, "other"], size: 16) + XCTAssertEqual(Array(found.keys), [id]) + XCTAssertEqual(found[id].map { $0.size.width * $0.scale }, 16) + let otherSize = await reloaded.cachedIcons(for: [id], size: 32) + XCTAssertTrue(otherSize.isEmpty) } func testRepositoryRejectsDataThatIsNotAnImage() async { let repo = IconRepository(disk: IconDiskCacheDataSource(directory: directory)) - let stored = await repo.store(png: Data("not a png".utf8), for: "abc") + let stored = await repo.store(png: Data("not a png".utf8), for: "abc", size: 16) XCTAssertNil(stored) XCTAssertEqual(cachedFileNames(), []) } diff --git a/PcVolumeControlTests/IconRequestPlannerTests.swift b/PcVolumeControlTests/IconRequestPlannerTests.swift index b76ef59..98590f3 100644 --- a/PcVolumeControlTests/IconRequestPlannerTests.swift +++ b/PcVolumeControlTests/IconRequestPlannerTests.swift @@ -6,30 +6,35 @@ // import XCTest +import SwiftUI @testable import PcVolumeControl final class IconRequestPlannerTests: XCTestCase { - private func ids(_ count: Int, prefix: String = "id") -> [String] { - (0.. [String] { + (0.. = []) -> [[String]] { + planner.requests(for: ids, size: 66, supportsIcons: true, skipping: skipping) } func testNoRequestsWithoutTheIconsFeature() { var planner = IconRequestPlanner() - XCTAssertEqual(planner.requests(for: ["a", "b"], supportsIcons: false, skipping: []), []) + XCTAssertEqual(planner.requests(for: ["a", "b"], size: 66, supportsIcons: false, skipping: []), []) XCTAssertTrue(planner.outstanding.isEmpty) } func testDuplicatesAreRequestedOnce() { var planner = IconRequestPlanner() - XCTAssertEqual(planner.requests(for: ["a", "b", "a", "b", "c"], supportsIcons: true, skipping: []), [["a", "b", "c"]]) + XCTAssertEqual(plan(&planner, ["a", "b", "a", "b", "c"]), [["a", "b", "c"]]) } func testSkippedAndInvalidIdsAreNotRequested() { var planner = IconRequestPlanner() - let batches = planner.requests( - for: ["cached", "UPPER", "", "has-dash", String(repeating: "a", count: 65), "wanted"], - supportsIcons: true, + let batches = plan( + &planner, + ["cached", "UPPER", "", "has-dash", String(repeating: "a", count: 65), "wanted"], skipping: ["cached"] ) XCTAssertEqual(batches, [["wanted"]]) @@ -37,14 +42,14 @@ final class IconRequestPlannerTests: XCTestCase { func testOutstandingIdsAreNotRequestedAgain() { var planner = IconRequestPlanner() - XCTAssertEqual(planner.requests(for: ["a", "b"], supportsIcons: true, skipping: []), [["a", "b"]]) - XCTAssertEqual(planner.requests(for: ["a", "b", "c"], supportsIcons: true, skipping: []), [["c"]]) - XCTAssertEqual(planner.outstanding, ["a", "b", "c"]) + XCTAssertEqual(plan(&planner, ["a", "b"]), [["a", "b"]]) + XCTAssertEqual(plan(&planner, ["a", "b", "c"]), [["c"]]) + XCTAssertEqual(planner.outstanding, ["a": 66, "b": 66, "c": 66]) } func testBatchesHoldAtMost32Ids() { var planner = IconRequestPlanner() - let batches = planner.requests(for: ids(40), supportsIcons: true, skipping: []) + let batches = plan(&planner, ids(40)) XCTAssertEqual(batches.map(\.count), [32, 8]) XCTAssertEqual(batches.flatMap { $0 }, ids(40)) } @@ -52,50 +57,78 @@ final class IconRequestPlannerTests: XCTestCase { func testAtMost64IdsAreOutstanding() { var planner = IconRequestPlanner() let all = ids(100) - let first = planner.requests(for: all, supportsIcons: true, skipping: []) - XCTAssertEqual(first.map(\.count), [32, 32]) + XCTAssertEqual(plan(&planner, all).map(\.count), [32, 32]) XCTAssertEqual(planner.outstanding.count, 64) + XCTAssertFalse(planner.hasRoomForFullBatch) // Full: nothing more until replies arrive. - XCTAssertEqual(planner.requests(for: all, supportsIcons: true, skipping: []), []) + XCTAssertEqual(plan(&planner, all), []) for id in all.prefix(10) { - planner.recordReply(for: id, available: true) + XCTAssertEqual(planner.recordReply(for: id, available: true), 66) } // Answered ids are now cached by the caller and skipped. - let next = planner.requests(for: all, supportsIcons: true, skipping: Set(all.prefix(10))) - XCTAssertEqual(next, [Array(all[64..<74])]) + XCTAssertEqual(plan(&planner, all, skipping: Set(all.prefix(10))), [Array(all[64..<74])]) XCTAssertEqual(planner.outstanding.count, 64) } + func testRoomForFullBatchOnceEnoughRepliesArrive() { + var planner = IconRequestPlanner() + let all = ids(64) + _ = plan(&planner, all) + for id in all.prefix(31) { + _ = planner.recordReply(for: id, available: true) + } + XCTAssertFalse(planner.hasRoomForFullBatch) + _ = planner.recordReply(for: all[31], available: true) + XCTAssertTrue(planner.hasRoomForFullBatch) + } + func testUnavailableIdsAreNotRequestedAgain() { var planner = IconRequestPlanner() - _ = planner.requests(for: ["a", "b"], supportsIcons: true, skipping: []) - planner.recordReply(for: "a", available: false) - planner.recordReply(for: "b", available: true) + _ = plan(&planner, ["a", "b", "c"]) + _ = planner.recordReply(for: "a", available: false) + _ = planner.recordReply(for: "b", available: true) + _ = planner.recordReply(for: "c", available: true) + planner.markUnavailable("c") XCTAssertTrue(planner.outstanding.isEmpty) - XCTAssertEqual(planner.requests(for: ["a", "b"], supportsIcons: true, skipping: ["b"]), []) + XCTAssertEqual(plan(&planner, ["a", "b", "c"], skipping: ["b"]), []) + } + + func testReplyThatWasNotRequestedIsReported() { + var planner = IconRequestPlanner() + XCTAssertNil(planner.recordReply(for: "a", available: false)) + // ... and does not mark the id unavailable. + XCTAssertEqual(plan(&planner, ["a"]), [["a"]]) + } + + func testReplyReportsTheRequestedSize() { + var planner = IconRequestPlanner() + _ = planner.requests(for: ["a"], size: 48, supportsIcons: true, skipping: []) + _ = planner.requests(for: ["b"], size: 96, supportsIcons: true, skipping: []) + XCTAssertEqual(planner.recordReply(for: "a", available: true), 48) + XCTAssertEqual(planner.recordReply(for: "b", available: true), 96) } func testDroppedConnectionClearsOutstandingButRemembersUnavailable() { var planner = IconRequestPlanner() - _ = planner.requests(for: ["a", "b", "c"], supportsIcons: true, skipping: []) - planner.recordReply(for: "a", available: false) + _ = plan(&planner, ["a", "b", "c"]) + _ = planner.recordReply(for: "a", available: false) planner.connectionDropped() XCTAssertTrue(planner.outstanding.isEmpty) // After reconnecting only the still-unknown ids are requested again. - XCTAssertEqual(planner.requests(for: ["a", "b", "c"], supportsIcons: true, skipping: []), [["b", "c"]]) + XCTAssertEqual(plan(&planner, ["a", "b", "c"]), [["b", "c"]]) } func testNewPlannerRetriesUnavailableIds() { var planner = IconRequestPlanner() - _ = planner.requests(for: ["a"], supportsIcons: true, skipping: []) - planner.recordReply(for: "a", available: false) + _ = plan(&planner, ["a"]) + _ = planner.recordReply(for: "a", available: false) planner = IconRequestPlanner() - XCTAssertEqual(planner.requests(for: ["a"], supportsIcons: true, skipping: []), [["a"]]) + XCTAssertEqual(plan(&planner, ["a"]), [["a"]]) } func testPixelSizeIsRoundedAndClamped() { @@ -104,4 +137,10 @@ final class IconRequestPlannerTests: XCTestCase { XCTAssertEqual(IconRequestPlanner.pixelSize(points: 4, scale: 2), 16) XCTAssertEqual(IconRequestPlanner.pixelSize(points: 120, scale: 3), 256) } + + func testIconPointSizeFollowsDynamicType() { + XCTAssertEqual(SessionIconView.pointSize(for: .large), 22, accuracy: 0.5) + XCTAssertGreaterThan(SessionIconView.pointSize(for: .accessibility3), SessionIconView.pointSize(for: .large)) + XCTAssertLessThan(SessionIconView.pointSize(for: .xSmall), SessionIconView.pointSize(for: .large)) + } } From adeb447a81bb4fcd3db3765b33165cf11e34b3a6 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 11:26:13 -0800 Subject: [PATCH 07/21] Upload test diagnostics when CI tests fail --- .github/workflows/ci.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 56bf774..467b1d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,20 @@ jobs: - name: Run tests run: bundle exec fastlane test + # The console output is condensed by xcbeautify; keep the raw log, the result + # bundle and any crash reports so failures can be diagnosed. + - name: Upload test diagnostics + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-diagnostics + path: | + ~/Library/Logs/scan + ~/Library/Developer/Xcode/DerivedData/*/Logs/Test/*.xcresult + ~/Library/Logs/DiagnosticReports + if-no-files-found: ignore + retention-days: 7 + periphery: runs-on: macos-latest steps: From ba0a3f8c62ced4098a654018eb9d5be4701d4d82 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 11:26:13 -0800 Subject: [PATCH 08/21] Document the v8 icon support --- CLAUDE.md | 21 +++++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index de7896f..b5ba9d5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -93,6 +93,27 @@ The app communicates with the PC server using a JSON protocol: - Master volume/mute changes - Individual application volume/mute changes +The canonical spec is `docs/PROTOCOL.md` in the PcVolumeControlServer repo. + +### v8 icon extension + +`protocolVersion` stays 7 on the wire; support is detected per feature. + +- A server with icon support adds `"features": ["icons"]` to the full state and an + optional `iconId` (`[a-z0-9]{1,64}`, content-derived) to sessions. Older servers send + neither, and the app then never sends an icon request. +- Lines are classified in `models/ServerLine.swift`: `defaultDevice` means a full + state, `icon` means an icon reply, anything else is ignored. A full state that + cannot be decoded still ends the connection. +- `datasources/LineFramer.swift` frames the byte stream; icon lines can be several + hundred KiB. +- `usecases/IconRequestPlanner.swift` decides what to request: at most 32 ids per + `iconRequest`, at most 64 outstanding, `notFound` ids not asked for again until the + user connects anew, outstanding ids reset when the connection drops. +- `repos/IconRepository.swift` (memory) and `datasources/IconDiskCacheDataSource.swift` + (Caches/AppIcons) cache icons by id and requested pixel size. +- Rows show `views/SessionIconView.swift`: the icon, or a placeholder of the same size. + ## Related Resources - Demo Video: https://youtu.be/OgueVzguP3w diff --git a/README.md b/README.md index f0e0428..3bcc338 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ The app connects to a free companion Windows server over your local network, dis - Per-app mute/unmute - Master volume and mute for the default output device - Auto-discovery of the server on your local network (or manual IP/port entry) +- Application icons next to each app, when the server supports them ## Demo From 1952e66de32dcc57f4264abe9d84026e6d01b758 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 11:29:28 -0800 Subject: [PATCH 09/21] Clarify the v8 icon notes in the contributor docs --- CLAUDE.md | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b5ba9d5..ffe97e6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -87,31 +87,40 @@ automatically. A clean run reports `No unused code detected.`. Notes: The app communicates with the PC server using a JSON protocol: -- **Server → Client**: Sends `FullState` with all devices and sessions information +- **Server → Client**: Sends `FullState` with all devices and sessions information, + and (v8) icon replies to the client's own icon requests - **Client → Server**: Sends updates for: - Default device changes - Master volume/mute changes - Individual application volume/mute changes + - (v8) `iconRequest` for application icons -The canonical spec is `docs/PROTOCOL.md` in the PcVolumeControlServer repo. +The canonical spec is `docs/PROTOCOL.md` in the PcVolumeControlServer repo. Paths +below are relative to `PcVolumeControl/`. ### v8 icon extension `protocolVersion` stays 7 on the wire; support is detected per feature. -- A server with icon support adds `"features": ["icons"]` to the full state and an - optional `iconId` (`[a-z0-9]{1,64}`, content-derived) to sessions. Older servers send - neither, and the app then never sends an icon request. +- A server with icon support includes `icons` in a `features` array on the full state + (other entries may be present and are ignored) and adds an optional `iconId` + (`[a-z0-9]{1,64}`, content-derived) to sessions. Older servers send neither, and the + app then never sends an icon request. - Lines are classified in `models/ServerLine.swift`: `defaultDevice` means a full - state, `icon` means an icon reply, anything else is ignored. A full state that - cannot be decoded still ends the connection. + state, `icon` means an icon reply, anything else is ignored. Not every line is a + full state. A full state that cannot be decoded ends the stream, which goes through + the normal connection-lost and reconnect path, as before v8. - `datasources/LineFramer.swift` frames the byte stream; icon lines can be several hundred KiB. - `usecases/IconRequestPlanner.swift` decides what to request: at most 32 ids per - `iconRequest`, at most 64 outstanding, `notFound` ids not asked for again until the - user connects anew, outstanding ids reset when the connection drops. -- `repos/IconRepository.swift` (memory) and `datasources/IconDiskCacheDataSource.swift` - (Caches/AppIcons) cache icons by id and requested pixel size. + `iconRequest`, at most 64 outstanding, outstanding ids reset when the connection + drops. Ids without a usable image (`notFound` or any other `error`, missing or bad + data, a PNG that does not decode) are not asked for again until the user connects + anew. +- `repos/IconRepository.swift` is the entry point for icons: an actor that decodes + PNGs off the main thread and keeps a bounded memory cache over + `datasources/IconDiskCacheDataSource.swift` (Caches/AppIcons, not thread-safe, used + only through the actor). Both are keyed by icon id and requested pixel size. - Rows show `views/SessionIconView.swift`: the icon, or a placeholder of the same size. ## Related Resources From 98e66284e3ad465c37ad51341aa4939f63e36e4f Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 11:32:36 -0800 Subject: [PATCH 10/21] Record status changes in the reconnect state test Polling every 10 ms missed the 0.1 s reconnecting phase whenever the main thread was busy for longer, which failed the test on CI. --- PcVolumeControlTests/MainViewModelSimpleTests.swift | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/PcVolumeControlTests/MainViewModelSimpleTests.swift b/PcVolumeControlTests/MainViewModelSimpleTests.swift index 27a5d48..a5fbcff 100644 --- a/PcVolumeControlTests/MainViewModelSimpleTests.swift +++ b/PcVolumeControlTests/MainViewModelSimpleTests.swift @@ -6,6 +6,7 @@ // Copyright © 2025 PcVolumeControl. All rights reserved. // +import Combine import XCTest import UIKit @testable import PcVolumeControl @@ -199,16 +200,19 @@ final class MainViewModelSimpleTests: XCTestCase { sut.reconnectInitialDelaySeconds = 0.02 sut.reconnectMaxDelaySeconds = 0.02 sut.reconnectWindowSeconds = 0.1 + // Record every published status: polling can miss the short .reconnecting phase + // when the main thread is busy for longer than the reconnect window. + var statuses: [MainViewModel.ConnectionStatus] = [] + let subscription = sut.$connectionStatus.sink { statuses.append($0) } sut.startReconnectLoop(to: DiscoveredServer(address: "192.0.2.1", port: 3000)) // It should enter .reconnecting before settling on .lost - var sawReconnecting = false for _ in 0..<300 { - if sut.connectionStatus == .reconnecting { sawReconnecting = true } if sut.connectionStatus == .lost { break } try? await Task.sleep(nanoseconds: 10_000_000) } - XCTAssertTrue(sawReconnecting) + subscription.cancel() + XCTAssertTrue(statuses.contains(.reconnecting)) XCTAssertEqual(sut.connectionStatus, .lost) } From d661c239aca6efa84860fe5835ddbace656dd619 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 11:35:37 -0800 Subject: [PATCH 11/21] Address review of the docs and the reconnect test Mark an undecodable icon unavailable even when the drawn size changed meanwhile, reset outstanding icon ids when going to the background (the stream ends there), wait for the reconnect test's final state with an expectation and assert the exact status sequence, and describe the reconnect-on-bad-state and features behaviour accurately. --- CLAUDE.md | 9 ++++---- .../viewmodels/MainViewModel.swift | 21 ++++++++++++------- .../MainViewModelSimpleTests.swift | 14 ++++++------- 3 files changed, 26 insertions(+), 18 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index ffe97e6..63bdf18 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -102,19 +102,20 @@ below are relative to `PcVolumeControl/`. `protocolVersion` stays 7 on the wire; support is detected per feature. -- A server with icon support includes `icons` in a `features` array on the full state - (other entries may be present and are ignored) and adds an optional `iconId` +- A server with icon support includes `icons` in a `features` array of strings on the + full state (other feature names may be present and are ignored) and adds an optional `iconId` (`[a-z0-9]{1,64}`, content-derived) to sessions. Older servers send neither, and the app then never sends an icon request. - Lines are classified in `models/ServerLine.swift`: `defaultDevice` means a full state, `icon` means an icon reply, anything else is ignored. Not every line is a full state. A full state that cannot be decoded ends the stream, which goes through - the normal connection-lost and reconnect path, as before v8. + the normal connection-lost and reconnect path, as before v8 (so a server that keeps + sending one makes the app reconnect repeatedly). - `datasources/LineFramer.swift` frames the byte stream; icon lines can be several hundred KiB. - `usecases/IconRequestPlanner.swift` decides what to request: at most 32 ids per `iconRequest`, at most 64 outstanding, outstanding ids reset when the connection - drops. Ids without a usable image (`notFound` or any other `error`, missing or bad + drops or the app goes to the background (both end the stream). Ids without a usable image (`notFound` or any other `error`, missing or bad data, a PNG that does not decode) are not asked for again until the user connects anew. - `repos/IconRepository.swift` is the entry point for icons: an actor that decodes diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index 5d4bd95..bdc984d 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -69,6 +69,8 @@ final class MainViewModel: ObservableObject { private var iconsMissingFromCache = Set() // Bumped when in-flight lookups and decodes no longer apply (new pixel size, user disconnect). private var iconGeneration = 0 + // Bumped when `iconPlanner` is replaced. + private var iconPlannerEpoch = 0 init(connect: ConnectToServerUseCase, defUpdate: SendDefaultDeviceUpdateUseCase, @@ -177,6 +179,7 @@ final class MainViewModel: ObservableObject { } // The next connection may be to another server, so forget its unavailable icons too. iconPlanner = IconRequestPlanner() + iconPlannerEpoch += 1 icons = [:] resetIconResolution() @@ -200,6 +203,8 @@ final class MainViewModel: ObservableObject { reconnectTask?.cancel() reconnectTask = nil stopPathMonitor() + // Replies still in flight are no longer read once the stream is cancelled. + iconPlanner.connectionDropped() } private func appWillEnterForeground() { @@ -485,21 +490,23 @@ final class MainViewModel: ObservableObject { let id = reply.id let generation = iconGeneration + let plannerEpoch = iconPlannerEpoch let isCurrentSize = size == iconPixelSize if isCurrentSize { iconsResolving.insert(id) } Task { let image = await iconRepo.store(png: png, for: id, size: size) - guard generation == iconGeneration, isCurrentSize else { return } - iconsResolving.remove(id) - if let image { - icons[id] = image - iconsAtCurrentSize.insert(id) - iconsMissingFromCache.remove(id) - } else { + // An undecodable image stays unavailable whatever size is drawn now. + if image == nil, plannerEpoch == iconPlannerEpoch { iconPlanner.markUnavailable(id) } + guard generation == iconGeneration, isCurrentSize else { return } + iconsResolving.remove(id) + guard let image else { return } + icons[id] = image + iconsAtCurrentSize.insert(id) + iconsMissingFromCache.remove(id) } } diff --git a/PcVolumeControlTests/MainViewModelSimpleTests.swift b/PcVolumeControlTests/MainViewModelSimpleTests.swift index a5fbcff..37ce98c 100644 --- a/PcVolumeControlTests/MainViewModelSimpleTests.swift +++ b/PcVolumeControlTests/MainViewModelSimpleTests.swift @@ -203,16 +203,16 @@ final class MainViewModelSimpleTests: XCTestCase { // Record every published status: polling can miss the short .reconnecting phase // when the main thread is busy for longer than the reconnect window. var statuses: [MainViewModel.ConnectionStatus] = [] - let subscription = sut.$connectionStatus.sink { statuses.append($0) } + let lost = expectation(description: "Reconnect loop gives up") + let subscription = sut.$connectionStatus.sink { status in + statuses.append(status) + if status == .lost { lost.fulfill() } + } sut.startReconnectLoop(to: DiscoveredServer(address: "192.0.2.1", port: 3000)) - // It should enter .reconnecting before settling on .lost - for _ in 0..<300 { - if sut.connectionStatus == .lost { break } - try? await Task.sleep(nanoseconds: 10_000_000) - } + await fulfillment(of: [lost], timeout: 10) subscription.cancel() - XCTAssertTrue(statuses.contains(.reconnecting)) + XCTAssertEqual(statuses, [.connected, .reconnecting, .lost]) XCTAssertEqual(sut.connectionStatus, .lost) } From 40128b542adf8cae6fb988ebc73409c062c9d6f7 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 12:34:51 -0800 Subject: [PATCH 12/21] Show session details under the application name Decode the optional v8 session detail and show it beneath the name or alias on one line, in a smaller and dimmer style. Every row reserves the detail line so heights stay fixed as details come and go, changes are not animated, and VoiceOver reads the detail after the name. Details are display only: aliases, saved order and outgoing updates are unchanged. --- CLAUDE.md | 13 ++++ .../viewmodels/MainViewModel.swift | 3 + PcVolumeControl/views/SessionCell.swift | 63 ++++++++++++++--- PcVolumeControlTests/ServerLineTests.swift | 31 ++++++++ PcVolumeControlTests/SessionDetailTests.swift | 70 +++++++++++++++++++ .../VolumeControlRepositoryTests.swift | 19 +++++ README.md | 2 +- 7 files changed, 191 insertions(+), 10 deletions(-) create mode 100644 PcVolumeControlTests/SessionDetailTests.swift diff --git a/CLAUDE.md b/CLAUDE.md index 63bdf18..ac97ca4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -124,6 +124,19 @@ below are relative to `PcVolumeControl/`. only through the actor). Both are keyed by icon id and requested pixel size. - Rows show `views/SessionIconView.swift`: the icon, or a placeholder of the same size. +### v8 session details + +- A session may carry an optional `detail` (one line, at most 120 characters), such as a + browser tab title, that tells apart sessions with the same `name`. It is not a feature: + nothing is detected or requested, it is shown whenever present, and servers may be + configured never to send it. +- It is display text only. Aliases, saved order and anything else remembered about a + session keep keying on the session `id`; outgoing updates never include it. +- `SessionCell` shows it under the name (or alias) in a smaller, dimmer style on one + line, truncated at the tail. Every row reserves that line, so heights do not change + when a detail appears, changes (up to once a second) or disappears; it is not + animated, and VoiceOver reads it after the name. + ## Related Resources - Demo Video: https://youtu.be/OgueVzguP3w diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index bdc984d..2b465b4 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -763,6 +763,9 @@ class FullState: Codable, Equatable { var volume: Double // v8: content-derived icon id; absent on older servers and until the server resolves the icon. var iconId: String? = nil + // v8: display-only label telling same-named sessions apart (a browser tab title). + // Never an identity: aliases and saved state key on `id`. + var detail: String? = nil } var defaultDevice: theDefaultDevice let deviceIds: [String: String] diff --git a/PcVolumeControl/views/SessionCell.swift b/PcVolumeControl/views/SessionCell.swift index 30492c5..326e619 100644 --- a/PcVolumeControl/views/SessionCell.swift +++ b/PcVolumeControl/views/SessionCell.swift @@ -179,6 +179,56 @@ struct SessionCell: View { (muted || masterMuted) ? 0 : volume } + // Alias if the user set one, otherwise the session's name. + private var displayName: String { + aliasManager.displayNameForSession(sessionId: session.id, originalName: session.name) + } + + private var detail: String? { + guard let detail = session.detail, !detail.isEmpty else { return nil } + return detail + } + + /// The row's spoken name: the display name, then the detail when there is one. + nonisolated static func spokenName(_ displayName: String, detail: String?) -> String { + guard let detail else { return displayName } + return "\(displayName), \(detail)" + } + + // The hidden stack reserves the detail's line in every row, so a row keeps its height + // when a detail appears, changes or disappears; without one the name is centred in it. + private var nameAndDetail: some View { + ZStack(alignment: .leading) { + VStack(alignment: .leading, spacing: 1) { + Text(verbatim: "X") + .font(.subheadline) + .fontWeight(.medium) + Text(verbatim: "X") + .font(.caption) + } + .hidden() + + VStack(alignment: .leading, spacing: 1) { + Text(displayName) + .font(.subheadline) + .fontWeight(.medium) + .foregroundColor(.white) + .lineLimit(1) + .truncationMode(.middle) + if let detail { + Text(detail) + .font(.caption) + .foregroundColor(.white.opacity(0.6)) + .lineLimit(1) + .truncationMode(.tail) + } + } + } + .animation(nil, value: detail) + .accessibilityElement(children: .ignore) + .accessibilityLabel(SessionCell.spokenName(displayName, detail: detail)) + } + private var displayVolume: Double { SessionCell.displayVolume( volume: session.volume, @@ -211,13 +261,7 @@ struct SessionCell: View { .font(.system(size: 16)) } - // Use alias if available, otherwise use original name - Text(aliasManager.displayNameForSession(sessionId: session.id, originalName: session.name)) - .font(.subheadline) - .fontWeight(.medium) - .foregroundColor(.white) - .lineLimit(1) - .truncationMode(.middle) + nameAndDetail Spacer() @@ -270,7 +314,7 @@ struct SessionCell: View { value: $localVolume, range: 0...100, steps: 10, - accessibilityLabel: "Volume for \(aliasManager.displayNameForSession(sessionId: session.id, originalName: session.name))", + accessibilityLabel: "Volume for \(SessionCell.spokenName(displayName, detail: detail))", onEditingChanged: { editing in if editing { ignoreServerUpdates = true @@ -399,7 +443,8 @@ struct SessionCell: View { id: "radio.exe", muted: false, name: "Radio", - volume: 75.0 + volume: 75.0, + detail: "Morning Show - Live" ) SessionCell( diff --git a/PcVolumeControlTests/ServerLineTests.swift b/PcVolumeControlTests/ServerLineTests.swift index 749c43b..1c3338e 100644 --- a/PcVolumeControlTests/ServerLineTests.swift +++ b/PcVolumeControlTests/ServerLineTests.swift @@ -23,6 +23,12 @@ final class ServerLineTests: XCTestCase { {"protocolVersion":7,"applicationVersion":"v10","features":["icons"],"deviceIds":{"dev-a":"Headset","dev-b":"Speakers"},"defaultDevice":{"deviceId":"dev-a","name":"Headset","masterVolume":100.0,"masterMuted":false,"sessions":[{"name":"speech-dispatcher-dummy","id":"dev-a|413","volume":100.0,"muted":false},{"name":"Firefox","id":"dev-a|961","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f"},{"name":"Firefox","id":"dev-a|6492","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f"},{"name":"Spotify","id":"dev-a|6565","volume":100.0,"muted":false,"iconId":"6b58026ae167f8f2e802f2531657443c"}]}} """# + // Captured from a v8 server on Linux with Firefox playing in three tabs. Device names + // are shortened and the tab titles replaced; field order and shape are as sent. + static let v8StateWithDetails = #""" + {"protocolVersion":7,"applicationVersion":"v10","features":["icons"],"deviceIds":{"dev-a":"Speakers","dev-b":"Headset"},"defaultDevice":{"deviceId":"dev-a","name":"Speakers","masterVolume":36.439514,"masterMuted":false,"sessions":[{"name":"speech-dispatcher-dummy","id":"dev-a|413","volume":100.0,"muted":false},{"name":"Firefox","id":"dev-a|961","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Big Buck Bunny - YouTube"},{"name":"Firefox","id":"dev-a|6622","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Radio Paradise - Main Mix"},{"name":"Firefox","id":"dev-a|6974","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Café Concert: You've Got a Friend…"}]}} + """# + // Captured verbatim from a v8 server: a 16 px PNG reply and a notFound reply. static let iconImageReply = #""" {"protocolVersion":7,"icon":{"id":"6b58026ae167f8f2e802f2531657443c","size":16,"mime":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACWUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1U/8+yCej1se/14vZ8Vby34UgKQn5qifuf0lvvPPeU6IB7j2b97jmllfvh14C56/n1sP7f3vfanvu48rEM/0sKe8xzXjWH4feAQvjP2Urs9Xe+rDv+8+APFMtzz+fX4O/Oa8KMwv3vbY734zAAE8+G/e45WyL388/fodDN/3FPLeJawb9EGcWRCP2KG8whnqa16PtjoAYuBVbn2p7/5jAdzy9+/9xRQ+qf31efJvzqMbNtGi4FXD9yxpj9+l/fl9eDLdWz2I2Ue+OJgvue2x3/3JAnjQP7zXTzn01qwaw088nbz9AI4mWFTihg3iJU5SH3Oc6bfvpv35OWaf/jIY//Ttj/2etxHALf/wnj9NxFv50sDwXU8ibthAmxUvG3n7Ae0vz5O7a/p3eCj9ez6Cy1r+zG0v/r1vLYCb/+Y9v0x9fDzA9Mf30f7mPD4Y0aISD9mmvuIZfG7F9Ot30X/IYyAEw/Rlt73U93+iAG75/Xd5dU7Nfg9g+p270ayg7Q4fTuRT95h+/250cs78014a5pXLdo9e/bZX+dE/EFfolr95j1+lL6/PC5BP2nU8dEfUwKv2a7e/zPe9EWDxTDf+xJvcVB5++vfpy4N4YaZ8RnvS2Ve/8+1+6Q4A8QAnv/MNb954iTPfFVvd6/F85MH4G/l3Z9/nrvf91du5AvG84rqfeuvXrNcs3pqiRxLA6CdN9y1/+p63+enfBZJnQ/z78I+X+d0RjTFkMwAAAABJRU5ErkJggg=="}} @@ -71,6 +77,31 @@ final class ServerLineTests: XCTestCase { XCTAssertEqual(v7.iconIds, []) } + func testSessionDetailsDecode() throws { + guard case .state(let state) = try classify(Self.v8StateWithDetails) else { + return XCTFail("Expected a full state") + } + XCTAssertEqual(state.defaultDevice.sessions.map(\.detail), [ + nil, + "Big Buck Bunny - YouTube", + "Radio Paradise - Main Mix", + "Caf\u{E9} Concert: You've Got a Friend\u{2026}", + ]) + // Same application, told apart only by the detail. + XCTAssertEqual(Set(state.defaultDevice.sessions.dropFirst().map(\.name)), ["Firefox"]) + // Details are not a feature: the features list is unaffected. + XCTAssertEqual(state.features, ["icons"]) + } + + func testStatesWithoutDetailsDecodeWithNone() throws { + for text in [Self.v7State, Self.v8State] { + guard case .state(let state) = try classify(text) else { + return XCTFail("Expected a full state") + } + XCTAssertTrue(state.defaultDevice.sessions.allSatisfy { $0.detail == nil }) + } + } + func testUnknownFeatureNamesAreKept() throws { let text = Self.v7State.replacingOccurrences( of: #""applicationVersion":"v10","#, diff --git a/PcVolumeControlTests/SessionDetailTests.swift b/PcVolumeControlTests/SessionDetailTests.swift new file mode 100644 index 0000000..ff8f6bd --- /dev/null +++ b/PcVolumeControlTests/SessionDetailTests.swift @@ -0,0 +1,70 @@ +// +// SessionDetailTests.swift +// PcVolumeControlTests +// +// Session details are display text: a state that only changes details must not +// disturb what the user is editing, the row order or row identity. +// + +import XCTest +@testable import PcVolumeControl + +@MainActor +final class SessionDetailTests: XCTestCase { + + private func state(details: [String?], volumes: [Double] = [50, 50, 50]) -> FullState { + let sessions = zip(details, volumes).enumerated().map { index, pair in + FullState.Session( + id: "dev-a|\(index)", muted: false, name: "Firefox", volume: pair.1, + iconId: "4b13f0d55a3779a6ff892414f951be3f", detail: pair.0 + ) + } + return FullState( + protocolVersion: 7, + deviceIds: ["dev-a": "Speakers"], + defaultDevice: FullState.theDefaultDevice( + deviceId: "dev-a", masterMuted: false, masterVolume: 80, name: "Speakers", sessions: sessions + ), + features: ["icons"] + ) + } + + func testDetailOnlyUpdateKeepsOrderAndIdentity() { + let vm = SliderViewModel() + vm.fullState = state(details: ["Tab A", "Tab B", nil]) + let ids = vm.sessions.map(\.id) + + vm.fullState = state(details: ["Tab A2", nil, "Tab C"]) + + XCTAssertEqual(vm.sessions.map(\.id), ids) + let details = Dictionary(uniqueKeysWithValues: vm.sessions.map { ($0.id, $0.detail) }) + XCTAssertEqual(details["dev-a|0"], "Tab A2") + XCTAssertEqual(details["dev-a|1"], .some(nil)) + XCTAssertEqual(details["dev-a|2"], "Tab C") + } + + func testDetailOnlyUpdateKeepsValuesOfASessionBeingEdited() throws { + let vm = SliderViewModel() + vm.fullState = state(details: ["Tab A", "Tab B", nil]) + let index = try XCTUnwrap(vm.sessions.firstIndex { $0.id == "dev-a|1" }) + + // The user is dragging this session's slider. + vm.beginEditing("dev-a|1") + vm.sessions[index].volume = 85 + vm.sessions[index].muted = true + + vm.fullState = state(details: ["Tab A", "Tab B changed", nil]) + + let edited = try XCTUnwrap(vm.sessions.first { $0.id == "dev-a|1" }) + XCTAssertEqual(edited.volume, 85) + XCTAssertTrue(edited.muted) + XCTAssertEqual(edited.detail, "Tab B changed") + XCTAssertEqual(edited.iconId, "4b13f0d55a3779a6ff892414f951be3f") + vm.endEditing("dev-a|1") + } + + func testSpokenNameAddsTheDetailOnlyWhenPresent() { + XCTAssertEqual(SessionCell.spokenName("Firefox", detail: nil), "Firefox") + XCTAssertEqual(SessionCell.spokenName("Firefox", detail: "Big Buck Bunny - YouTube"), "Firefox, Big Buck Bunny - YouTube") + } +} diff --git a/PcVolumeControlTests/VolumeControlRepositoryTests.swift b/PcVolumeControlTests/VolumeControlRepositoryTests.swift index d476281..585ff1e 100644 --- a/PcVolumeControlTests/VolumeControlRepositoryTests.swift +++ b/PcVolumeControlTests/VolumeControlRepositoryTests.swift @@ -51,6 +51,25 @@ final class VolumeControlRepositoryTests: XCTestCase { XCTAssertEqual(states, 1) } + func testSessionUpdateDoesNotSendDetail() async throws { + let transport = MockVolumeTransport() + let repo = VolumeControlRepository(transport: transport) + let session = FullState.Session( + id: "dev-a|961", muted: false, name: "Firefox", volume: 40, + iconId: "4b13f0d55a3779a6ff892414f951be3f", detail: "Big Buck Bunny - YouTube" + ) + try await repo.pushSessionValues(name: session.name, id: session.id, volume: session.volume, muted: session.muted) + + let sent = try XCTUnwrap(transport.sentData.first) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: sent) as? [String: Any]) + XCTAssertEqual(Set(json.keys), ["protocolVersion", "defaultDevice"]) + let device = try XCTUnwrap(json["defaultDevice"] as? [String: Any]) + XCTAssertEqual(Set(device.keys), ["sessions", "deviceId"]) + let sessions = try XCTUnwrap(device["sessions"] as? [[String: Any]]) + XCTAssertEqual(sessions.count, 1) + XCTAssertEqual(Set(sessions[0].keys), ["name", "id", "volume", "muted"]) + } + func testIconRequestEncoding() async throws { let transport = MockVolumeTransport() let repo = VolumeControlRepository(transport: transport) diff --git a/README.md b/README.md index 3bcc338..a5512f0 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ The app connects to a free companion Windows server over your local network, dis - Per-app mute/unmute - Master volume and mute for the default output device - Auto-discovery of the server on your local network (or manual IP/port entry) -- Application icons next to each app, when the server supports them +- Application icons next to each app, and details such as a browser tab's title under the app name, when the server sends them ## Demo From dab79d2caa9b16c48de1b269aa23435a0da14f7a Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 12:38:02 -0800 Subject: [PATCH 13/21] Address review of session details Order same-named sessions by id, trim details before showing them, name the detail in the rename prompt, share line styling with the hidden height reservation, and skip widget and saved-order writes for states that change neither. The outgoing-update test now goes through the view model. --- .../viewmodels/MainViewModel.swift | 10 +++++- .../viewmodels/SliderViewModel.swift | 32 ++++++++++++----- PcVolumeControl/views/SessionCell.swift | 36 +++++++++++-------- .../MainViewModelSimpleTests.swift | 18 ++++++++++ PcVolumeControlTests/SessionDetailTests.swift | 2 ++ .../VolumeControlRepositoryTests.swift | 19 ---------- 6 files changed, 73 insertions(+), 44 deletions(-) diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index 2b465b4..a36058a 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -72,6 +72,9 @@ final class MainViewModel: ObservableObject { // Bumped when `iconPlanner` is replaced. private var iconPlannerEpoch = 0 + // Master volume last written to the widget's shared state; nil once it says disconnected. + private var sharedMasterVolume: Double? + init(connect: ConnectToServerUseCase, defUpdate: SendDefaultDeviceUpdateUseCase, masterUpdate: SendMasterChannelUpdateUseCase, @@ -378,7 +381,10 @@ final class MainViewModel: ObservableObject { case .state(let state): fullState = state // view state only here connectionStatus = .connected - updateSharedState(with: state) // Update widget state + // The widget shows only the master volume; the heartbeat keeps it fresh otherwise. + if state.defaultDevice.masterVolume != sharedMasterVolume { + updateSharedState(with: state) + } resolveIcons(for: state) case .icon(let reply): handleIconReply(reply) @@ -525,11 +531,13 @@ final class MainViewModel: ObservableObject { ) SharedStateManager.writeState(sharedState) + sharedMasterVolume = state.defaultDevice.masterVolume WidgetCenter.shared.reloadTimelines(ofKind: "PcVolumeControlWidget") } private func updateSharedStateDisconnected() { + sharedMasterVolume = nil if var existingState = SharedStateManager.readState() { existingState.isConnected = false SharedStateManager.writeState(existingState) diff --git a/PcVolumeControl/viewmodels/SliderViewModel.swift b/PcVolumeControl/viewmodels/SliderViewModel.swift index 6ece5c6..a14652e 100644 --- a/PcVolumeControl/viewmodels/SliderViewModel.swift +++ b/PcVolumeControl/viewmodels/SliderViewModel.swift @@ -190,9 +190,7 @@ final class SliderViewModel: ObservableObject { } // Otherwise sort alphabetically, but respect editingIds else { - let sortedSessions = processedSessions.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } + let sortedSessions = processedSessions.sorted(by: Self.inDisplayOrder) // If any sessions are being edited, preserve their values if !editingIds.isEmpty { @@ -257,11 +255,11 @@ final class SliderViewModel: ObservableObject { } } - remainingSessions.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } + remainingSessions.sort(by: Self.inDisplayOrder) sessions = orderedSessions + remainingSessions // Update saved order - savedOrder = sessions.map { $0.id } + saveOrderIfChanged() } private func updatePreservingCurrentOrder(incomingSessions: [FullState.Session]) { @@ -288,14 +286,30 @@ final class SliderViewModel: ObservableObject { // Add new sessions at the end let existingIds = Set(sessions.map { $0.id }) let newSessions = incomingSessions.filter { !existingIds.contains($0.id) } - let sortedNewSessions = newSessions.sorted { - $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending - } + let sortedNewSessions = newSessions.sorted(by: Self.inDisplayOrder) sessions = updatedSessions + sortedNewSessions if preserveSessionOrder { - savedOrder = sessions.map { $0.id } + saveOrderIfChanged() + } + } + + // States can arrive every second (session details), so skip writes that change nothing. + private func saveOrderIfChanged() { + let order = sessions.map { $0.id } + if order != savedOrder { + savedOrder = order + } + } + + // By name; same-named sessions (told apart only by their detail) by id, so their order + // is stable and never depends on the detail. + private static func inDisplayOrder(_ lhs: FullState.Session, _ rhs: FullState.Session) -> Bool { + switch lhs.name.localizedCaseInsensitiveCompare(rhs.name) { + case .orderedAscending: return true + case .orderedDescending: return false + case .orderedSame: return lhs.id < rhs.id } } } diff --git a/PcVolumeControl/views/SessionCell.swift b/PcVolumeControl/views/SessionCell.swift index 326e619..5e87588 100644 --- a/PcVolumeControl/views/SessionCell.swift +++ b/PcVolumeControl/views/SessionCell.swift @@ -185,12 +185,13 @@ struct SessionCell: View { } private var detail: String? { - guard let detail = session.detail, !detail.isEmpty else { return nil } + guard let detail = session.detail?.trimmingCharacters(in: .whitespacesAndNewlines), + !detail.isEmpty else { return nil } return detail } /// The row's spoken name: the display name, then the detail when there is one. - nonisolated static func spokenName(_ displayName: String, detail: String?) -> String { + static func spokenName(_ displayName: String, detail: String?) -> String { guard let detail else { return displayName } return "\(displayName), \(detail)" } @@ -200,26 +201,18 @@ struct SessionCell: View { private var nameAndDetail: some View { ZStack(alignment: .leading) { VStack(alignment: .leading, spacing: 1) { - Text(verbatim: "X") - .font(.subheadline) - .fontWeight(.medium) - Text(verbatim: "X") - .font(.caption) + nameLine("X") + detailLine("X") } .hidden() VStack(alignment: .leading, spacing: 1) { - Text(displayName) - .font(.subheadline) - .fontWeight(.medium) + nameLine(displayName) .foregroundColor(.white) - .lineLimit(1) .truncationMode(.middle) if let detail { - Text(detail) - .font(.caption) + detailLine(detail) .foregroundColor(.white.opacity(0.6)) - .lineLimit(1) .truncationMode(.tail) } } @@ -229,6 +222,15 @@ struct SessionCell: View { .accessibilityLabel(SessionCell.spokenName(displayName, detail: detail)) } + // Shared by the visible lines and the hidden ones that reserve their height. + private func nameLine(_ text: String) -> some View { + Text(text).font(.subheadline).fontWeight(.medium).lineLimit(1) + } + + private func detailLine(_ text: String) -> some View { + Text(text).font(.caption).lineLimit(1) + } + private var displayVolume: Double { SessionCell.displayVolume( volume: session.volume, @@ -427,7 +429,11 @@ struct SessionCell: View { Button("Cancel", role: .cancel) {} } message: { - Text("Enter a custom name for \"\(session.name)\"") + if let detail { + Text("Enter a custom name for \"\(session.name)\" (\(detail))") + } else { + Text("Enter a custom name for \"\(session.name)\"") + } } } diff --git a/PcVolumeControlTests/MainViewModelSimpleTests.swift b/PcVolumeControlTests/MainViewModelSimpleTests.swift index 37ce98c..4fe832f 100644 --- a/PcVolumeControlTests/MainViewModelSimpleTests.swift +++ b/PcVolumeControlTests/MainViewModelSimpleTests.swift @@ -120,6 +120,24 @@ final class MainViewModelSimpleTests: XCTestCase { XCTAssertFalse(mockRepository.sentData.isEmpty) } + func testSessionUpdateDoesNotSendDetail() async throws { + let session = FullState.Session( + id: "dev-a|961", muted: false, name: "Firefox", volume: 40, + iconId: "4b13f0d55a3779a6ff892414f951be3f", detail: "Big Buck Bunny - YouTube" + ) + + try await sut.updateSession(session) + + let sent = try XCTUnwrap(mockRepository.sentData.first) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: sent) as? [String: Any]) + XCTAssertEqual(Set(json.keys), ["protocolVersion", "defaultDevice"]) + let device = try XCTUnwrap(json["defaultDevice"] as? [String: Any]) + XCTAssertEqual(Set(device.keys), ["sessions", "deviceId"]) + let sessions = try XCTUnwrap(device["sessions"] as? [[String: Any]]) + XCTAssertEqual(sessions.count, 1) + XCTAssertEqual(Set(sessions[0].keys), ["name", "id", "volume", "muted"]) + } + // MARK: - Error Handling Tests func testConnectToServerWithInvalidAddress() async { diff --git a/PcVolumeControlTests/SessionDetailTests.swift b/PcVolumeControlTests/SessionDetailTests.swift index ff8f6bd..00c70a4 100644 --- a/PcVolumeControlTests/SessionDetailTests.swift +++ b/PcVolumeControlTests/SessionDetailTests.swift @@ -33,6 +33,8 @@ final class SessionDetailTests: XCTestCase { let vm = SliderViewModel() vm.fullState = state(details: ["Tab A", "Tab B", nil]) let ids = vm.sessions.map(\.id) + // Same-named sessions are ordered by id, never by detail. + XCTAssertEqual(ids, ["dev-a|0", "dev-a|1", "dev-a|2"]) vm.fullState = state(details: ["Tab A2", nil, "Tab C"]) diff --git a/PcVolumeControlTests/VolumeControlRepositoryTests.swift b/PcVolumeControlTests/VolumeControlRepositoryTests.swift index 585ff1e..d476281 100644 --- a/PcVolumeControlTests/VolumeControlRepositoryTests.swift +++ b/PcVolumeControlTests/VolumeControlRepositoryTests.swift @@ -51,25 +51,6 @@ final class VolumeControlRepositoryTests: XCTestCase { XCTAssertEqual(states, 1) } - func testSessionUpdateDoesNotSendDetail() async throws { - let transport = MockVolumeTransport() - let repo = VolumeControlRepository(transport: transport) - let session = FullState.Session( - id: "dev-a|961", muted: false, name: "Firefox", volume: 40, - iconId: "4b13f0d55a3779a6ff892414f951be3f", detail: "Big Buck Bunny - YouTube" - ) - try await repo.pushSessionValues(name: session.name, id: session.id, volume: session.volume, muted: session.muted) - - let sent = try XCTUnwrap(transport.sentData.first) - let json = try XCTUnwrap(JSONSerialization.jsonObject(with: sent) as? [String: Any]) - XCTAssertEqual(Set(json.keys), ["protocolVersion", "defaultDevice"]) - let device = try XCTUnwrap(json["defaultDevice"] as? [String: Any]) - XCTAssertEqual(Set(device.keys), ["sessions", "deviceId"]) - let sessions = try XCTUnwrap(device["sessions"] as? [[String: Any]]) - XCTAssertEqual(sessions.count, 1) - XCTAssertEqual(Set(sessions[0].keys), ["name", "id", "volume", "muted"]) - } - func testIconRequestEncoding() async throws { let transport = MockVolumeTransport() let repo = VolumeControlRepository(transport: transport) From aad99ace50a3865b1ceff8f19c2930ab1a2ca284 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 12:50:27 -0800 Subject: [PATCH 14/21] Address second review of session details Drop the widget write skip, which needed per-path resets and could leave the widget stale after returning to the foreground. Read the saved order once per state, sort same-named sessions by id with numbers compared numerically, capture the detail when the rename prompt opens, keep a single order write path, and add the new prompt string to the catalog. --- Localizable.xcstrings | 3 +++ .../viewmodels/MainViewModel.swift | 11 +---------- .../viewmodels/SliderViewModel.swift | 19 +++++++++++++------ PcVolumeControl/views/SessionCell.swift | 5 ++++- 4 files changed, 21 insertions(+), 17 deletions(-) diff --git a/Localizable.xcstrings b/Localizable.xcstrings index dc5be65..84a81ad 100644 --- a/Localizable.xcstrings +++ b/Localizable.xcstrings @@ -110,6 +110,9 @@ }, "Enter a custom name for \"%@\"" : { + }, + "Enter a custom name for \"%@\" (%@)" : { + }, "Enter new name" : { diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index a36058a..24577f3 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -71,10 +71,6 @@ final class MainViewModel: ObservableObject { private var iconGeneration = 0 // Bumped when `iconPlanner` is replaced. private var iconPlannerEpoch = 0 - - // Master volume last written to the widget's shared state; nil once it says disconnected. - private var sharedMasterVolume: Double? - init(connect: ConnectToServerUseCase, defUpdate: SendDefaultDeviceUpdateUseCase, masterUpdate: SendMasterChannelUpdateUseCase, @@ -381,10 +377,7 @@ final class MainViewModel: ObservableObject { case .state(let state): fullState = state // view state only here connectionStatus = .connected - // The widget shows only the master volume; the heartbeat keeps it fresh otherwise. - if state.defaultDevice.masterVolume != sharedMasterVolume { - updateSharedState(with: state) - } + updateSharedState(with: state) // Update widget state resolveIcons(for: state) case .icon(let reply): handleIconReply(reply) @@ -531,13 +524,11 @@ final class MainViewModel: ObservableObject { ) SharedStateManager.writeState(sharedState) - sharedMasterVolume = state.defaultDevice.masterVolume WidgetCenter.shared.reloadTimelines(ofKind: "PcVolumeControlWidget") } private func updateSharedStateDisconnected() { - sharedMasterVolume = nil if var existingState = SharedStateManager.readState() { existingState.isConnected = false SharedStateManager.writeState(existingState) diff --git a/PcVolumeControl/viewmodels/SliderViewModel.swift b/PcVolumeControl/viewmodels/SliderViewModel.swift index a14652e..eb93579 100644 --- a/PcVolumeControl/viewmodels/SliderViewModel.swift +++ b/PcVolumeControl/viewmodels/SliderViewModel.swift @@ -55,7 +55,7 @@ final class SliderViewModel: ObservableObject { func reorder(from source: IndexSet, to destination: Int) { sessions.move(fromOffsets: source, toOffset: destination) if preserveSessionOrder { - savedOrder = sessions.map { $0.id } + saveOrderIfChanged() } } @@ -237,7 +237,9 @@ final class SliderViewModel: ObservableObject { var remainingSessions = [FullState.Session]() // Add sessions in saved order - for sessionId in savedOrder { + let saved = savedOrder + let savedIds = Set(saved) + for sessionId in saved { if let session = incomingDict[sessionId] { if editingIds.contains(sessionId), let existingIdx = sessions.firstIndex(where: { $0.id == sessionId }) { @@ -250,7 +252,7 @@ final class SliderViewModel: ObservableObject { // Add new sessions not in saved order for session in incomingSessions { - if !savedOrder.contains(session.id) { + if !savedIds.contains(session.id) { remainingSessions.append(session) } } @@ -303,13 +305,18 @@ final class SliderViewModel: ObservableObject { } } - // By name; same-named sessions (told apart only by their detail) by id, so their order - // is stable and never depends on the detail. + // By name; same-named sessions (told apart only by their detail) by id, numbers in ids + // compared numerically, so their order is stable and never depends on the detail. private static func inDisplayOrder(_ lhs: FullState.Session, _ rhs: FullState.Session) -> Bool { switch lhs.name.localizedCaseInsensitiveCompare(rhs.name) { case .orderedAscending: return true case .orderedDescending: return false - case .orderedSame: return lhs.id < rhs.id + case .orderedSame: + switch lhs.id.localizedStandardCompare(rhs.id) { + case .orderedAscending: return true + case .orderedDescending: return false + case .orderedSame: return lhs.id < rhs.id + } } } } diff --git a/PcVolumeControl/views/SessionCell.swift b/PcVolumeControl/views/SessionCell.swift index 5e87588..1973181 100644 --- a/PcVolumeControl/views/SessionCell.swift +++ b/PcVolumeControl/views/SessionCell.swift @@ -166,6 +166,8 @@ struct SessionCell: View { // Show a dialog to edit the alias for this session @State private var isEditingAlias = false @State private var newAlias = "" + // Captured when the prompt opens: the live detail can change while the user types. + @State private var aliasPromptDetail: String? = nil private var isInEditMode: Bool { editMode?.wrappedValue == .active @@ -429,7 +431,7 @@ struct SessionCell: View { Button("Cancel", role: .cancel) {} } message: { - if let detail { + if let detail = aliasPromptDetail { Text("Enter a custom name for \"\(session.name)\" (\(detail))") } else { Text("Enter a custom name for \"\(session.name)\"") @@ -440,6 +442,7 @@ struct SessionCell: View { private func showAliasEditingPrompt() { // Initialize with current alias if exists newAlias = aliasManager.sessionAliases[session.id] ?? "" + aliasPromptDetail = detail isEditingAlias = true } } From 1e87ba271f13df160ae319ee2da1b5aba3b4c92d Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 12:51:11 -0800 Subject: [PATCH 15/21] Restore a blank line in MainViewModel --- PcVolumeControl/viewmodels/MainViewModel.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index 24577f3..2b465b4 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -71,6 +71,7 @@ final class MainViewModel: ObservableObject { private var iconGeneration = 0 // Bumped when `iconPlanner` is replaced. private var iconPlannerEpoch = 0 + init(connect: ConnectToServerUseCase, defUpdate: SendDefaultDeviceUpdateUseCase, masterUpdate: SendMasterChannelUpdateUseCase, From a6146097f7d80d1a9f4026bb603f40d931cf8edc Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 13:14:17 -0800 Subject: [PATCH 16/21] Speak protocol version 8 only Send protocolVersion 8 in every message and reject a full state of another version before decoding the rest: the app disconnects without reconnecting and says whether the server or the app needs updating. Drop the features list and request icons for any unknown icon id. Session updates go to the current default device instead of a device id searched for in the opaque session id. Point the setup guide and README to PcVolumeControlServer. --- CLAUDE.md | 57 +++++---- Localizable.xcstrings | 16 ++- PcVolumeControl/models/ServerLine.swift | 42 ++++++- PcVolumeControl/models/VolumeUpdateDTOs.swift | 2 +- .../repos/VolumeControlRepository.swift | 33 ++--- .../usecases/IconRequestPlanner.swift | 6 +- .../usecases/VolumeControlUseCases.swift | 4 +- .../viewmodels/MainViewModel.swift | 37 +++--- PcVolumeControl/views/MainView.swift | 2 +- .../views/ServerSetupGuideView.swift | 10 +- .../IconRequestPlannerTests.swift | 12 +- PcVolumeControlTests/LineFramerTests.swift | 2 +- .../MainViewModelSimpleTests.swift | 29 ++++- PcVolumeControlTests/ServerLineTests.swift | 114 ++++++++++++------ PcVolumeControlTests/SessionDetailTests.swift | 5 +- .../VolumeControlRepositoryTests.swift | 43 ++++++- README.md | 12 +- 17 files changed, 272 insertions(+), 154 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index ac97ca4..e82d012 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ PCVolumeControl is an iOS application that allows users to remotely control appl - **Platform**: iOS 17+ Swift app using SwiftUI - **Architecture Pattern**: MVVM (Model-View-ViewModel) - **Networking**: TCP socket communication using Apple's Network framework -- **Protocol**: JSON-based protocol (version 7) for client-server communication +- **Protocol**: JSON-based protocol (version 8) for client-server communication ## Key Components @@ -85,51 +85,56 @@ automatically. A clean run reports `No unused code detected.`. Notes: ## Protocol -The app communicates with the PC server using a JSON protocol: +The app speaks protocol version 8 only, a JSON protocol with one message per line: -- **Server → Client**: Sends `FullState` with all devices and sessions information, - and (v8) icon replies to the client's own icon requests -- **Client → Server**: Sends updates for: - - Default device changes - - Master volume/mute changes - - Individual application volume/mute changes - - (v8) `iconRequest` for application icons +- **Server → Client**: full states (all devices and the default device's sessions) and + icon replies to the client's own icon requests +- **Client → Server**: updates for the default device, master volume/mute and session + volume/mute, and `iconRequest` for application icons -The canonical spec is `docs/PROTOCOL.md` in the PcVolumeControlServer repo. Paths -below are relative to `PcVolumeControl/`. +The canonical spec is the protocol version 8 document of the PcVolumeControlServer repo. +This app does not work with the original C# PcVolumeControlWindows server (version 7). +Paths below are relative to `PcVolumeControl/`. -### v8 icon extension +### Version and ids -`protocolVersion` stays 7 on the wire; support is detected per feature. +- Every outgoing message carries `protocolVersion` 8 (`WireProtocol.version` in + `models/ServerLine.swift`). A full state with another version throws + `ProtocolVersionMismatch`, checked before the rest of the state is decoded; the view + model then disconnects (no reconnect) and shows a localised message saying whether the + server (lower number) or the app (higher number) needs updating. +- Session ids are opaque. A session update is sent with the current state's + `defaultDevice.deviceId`, the device whose sessions the app shows. +- mDNS discovery does not read TXT records; a server of another version shows up in the + list and is rejected with the message above when connecting. + +### Lines and icons -- A server with icon support includes `icons` in a `features` array of strings on the - full state (other feature names may be present and are ignored) and adds an optional `iconId` - (`[a-z0-9]{1,64}`, content-derived) to sessions. Older servers send neither, and the - app then never sends an icon request. - Lines are classified in `models/ServerLine.swift`: `defaultDevice` means a full state, `icon` means an icon reply, anything else is ignored. Not every line is a full state. A full state that cannot be decoded ends the stream, which goes through - the normal connection-lost and reconnect path, as before v8 (so a server that keeps - sending one makes the app reconnect repeatedly). + the normal connection-lost and reconnect path (so a server that keeps sending one + makes the app reconnect repeatedly). - `datasources/LineFramer.swift` frames the byte stream; icon lines can be several hundred KiB. +- Sessions may carry an `iconId` (`[a-z0-9]{1,64}`, content-derived). Every server + answers `iconRequest`; one that serves no icons never sends an `iconId`. - `usecases/IconRequestPlanner.swift` decides what to request: at most 32 ids per `iconRequest`, at most 64 outstanding, outstanding ids reset when the connection - drops or the app goes to the background (both end the stream). Ids without a usable image (`notFound` or any other `error`, missing or bad - data, a PNG that does not decode) are not asked for again until the user connects - anew. + drops or the app goes to the background (both end the stream). Ids without a usable + image (`notFound` or any other `error`, missing or bad data, a PNG that does not + decode) are not asked for again until the user connects anew. - `repos/IconRepository.swift` is the entry point for icons: an actor that decodes PNGs off the main thread and keeps a bounded memory cache over `datasources/IconDiskCacheDataSource.swift` (Caches/AppIcons, not thread-safe, used only through the actor). Both are keyed by icon id and requested pixel size. - Rows show `views/SessionIconView.swift`: the icon, or a placeholder of the same size. -### v8 session details +### Session details - A session may carry an optional `detail` (one line, at most 120 characters), such as a - browser tab title, that tells apart sessions with the same `name`. It is not a feature: - nothing is detected or requested, it is shown whenever present, and servers may be - configured never to send it. + browser tab title, that tells apart sessions with the same `name`. It is shown + whenever present; servers may be configured never to send it. - It is display text only. Aliases, saved order and anything else remembered about a session keep keying on the session `id`; outgoing updates never include it. - `SessionCell` shows it under the name (or alias) in a smaller, dimmer style on one diff --git a/Localizable.xcstrings b/Localizable.xcstrings index 84a81ad..a51f085 100644 --- a/Localizable.xcstrings +++ b/Localizable.xcstrings @@ -98,8 +98,8 @@ "Done" : { }, - "Download PcVolumeControlWindows releases on GitHub" : { - "comment" : "A link that, when tapped, directs the user to the GitHub releases page for the PcVolumeControlWindows app.", + "Download PcVolumeControlServer releases on GitHub" : { + "comment" : "A link that, when tapped, directs the user to the GitHub releases page for the PcVolumeControlServer app.", "isCommentAutoGenerated" : true }, "Edit Custom Name" : { @@ -210,8 +210,8 @@ "comment" : "A description of the purpose of the Windows server.", "isCommentAutoGenerated" : true }, - "PcVolumeControlWindows releases" : { - "comment" : "A link label that, when tapped, takes the user to the GitHub releases page for the PcVolumeControlWindows repository.", + "PcVolumeControlServer releases" : { + "comment" : "A link label that, when tapped, takes the user to the GitHub releases page for the PcVolumeControlServer repository.", "isCommentAutoGenerated" : true }, "Please enter a valid TCP port (1-65535)" : { @@ -291,7 +291,7 @@ "isCommentAutoGenerated" : true }, "Share the download link to open on your PC" : { - "comment" : "A button that allows the user to share the download link to open the PcVolumeControlWindows installer on their PC.", + "comment" : "A button that allows the user to share the download link to open the PcVolumeControlServer installer on their PC.", "isCommentAutoGenerated" : true }, "Show me how to set it up" : { @@ -306,6 +306,12 @@ "comment" : "A description of how to find the IP address and port of the server.", "isCommentAutoGenerated" : true }, + "This PC server is newer than this app (protocol version %lld). Update PcVolumeControl on this device to connect to it." : { + "comment" : "Error shown when the server speaks a newer protocol version than the app." + }, + "This PC server is too old (protocol version %lld). Install the latest PcVolumeControlServer on your PC to use this version of the app." : { + "comment" : "Error shown when the server speaks an older protocol version than the app." + }, "This app talks to the PcVolumeControl server, a small program that runs on your Windows PC." : { "comment" : "A description of how the app interacts with the server.", "isCommentAutoGenerated" : true diff --git a/PcVolumeControl/models/ServerLine.swift b/PcVolumeControl/models/ServerLine.swift index 783a998..a124a4c 100644 --- a/PcVolumeControl/models/ServerLine.swift +++ b/PcVolumeControl/models/ServerLine.swift @@ -1,5 +1,11 @@ import Foundation +enum WireProtocol { + /// The only protocol version this app speaks, sent in every message and required in + /// every full state. + static let version = 8 +} + /// One line received from the server. Every line carries `protocolVersion` and exactly /// one of `defaultDevice` (a full state) or `icon` (an icon reply). enum ServerLine { @@ -7,11 +13,15 @@ enum ServerLine { case icon(IconReply) /// Returns nil for a line to ignore: one that is not a JSON object, has neither or both - /// of the keys, or is an icon reply without an id. Throws only for a full state that - /// cannot be decoded, which ends the connection as it always has. + /// of the keys, or is an icon reply without an id. Throws `ProtocolVersionMismatch` for + /// a full state of another protocol version (checked before the rest is decoded, so the + /// shape of other versions does not matter) and `MalformedStateError` for a full state + /// that cannot be decoded. static func classify(_ line: Data) throws -> ServerLine? { do { return try decoder.decode(Envelope.self, from: line).line + } catch let error as ProtocolVersionMismatch { + throw error } catch let error as MalformedStateError { throw error } catch { @@ -26,13 +36,22 @@ enum ServerLine { let line: ServerLine? private enum CodingKeys: String, CodingKey { - case defaultDevice, icon + case protocolVersion, defaultDevice, icon } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) switch (container.contains(.defaultDevice), container.contains(.icon)) { case (true, false): + let version: Int + do { + version = try container.decode(Int.self, forKey: .protocolVersion) + } catch { + throw MalformedStateError(underlying: error) + } + guard version == WireProtocol.version else { + throw ProtocolVersionMismatch(serverVersion: version) + } do { line = .state(try FullState(from: decoder)) } catch { @@ -55,6 +74,23 @@ struct MalformedStateError: LocalizedError { } } +/// The server speaks another protocol version; the connection cannot be used. +struct ProtocolVersionMismatch: LocalizedError { + let serverVersion: Int + + /// True when the server needs updating, false when this app does. + var serverIsOlder: Bool { + serverVersion < WireProtocol.version + } + + var errorDescription: String? { + if serverIsOlder { + return String(localized: "This PC server is too old (protocol version \(serverVersion)). Install the latest PcVolumeControlServer on your PC to use this version of the app.") + } + return String(localized: "This PC server is newer than this app (protocol version \(serverVersion)). Update PcVolumeControl on this device to connect to it.") + } +} + /// The server's answer for one requested icon id. struct IconReply: Decodable { let id: String diff --git a/PcVolumeControl/models/VolumeUpdateDTOs.swift b/PcVolumeControl/models/VolumeUpdateDTOs.swift index 159185f..5195a02 100644 --- a/PcVolumeControl/models/VolumeUpdateDTOs.swift +++ b/PcVolumeControl/models/VolumeUpdateDTOs.swift @@ -39,7 +39,7 @@ struct OneSession : Codable { let muted: Bool } -// v8: ask for application icons; only sent to a server whose full state lists "icons" in features +// ask for application icons by icon id struct AIconRequest : Codable { struct Payload : Codable { let ids: [String] diff --git a/PcVolumeControl/repos/VolumeControlRepository.swift b/PcVolumeControl/repos/VolumeControlRepository.swift index 19cc0ad..ca8415f 100644 --- a/PcVolumeControl/repos/VolumeControlRepository.swift +++ b/PcVolumeControl/repos/VolumeControlRepository.swift @@ -1,13 +1,11 @@ import Foundation struct VolumeControlRepository { - static let protocolVersion = 7 - let transport: VolumeTransportDataSourceProtocol - let deviceIdLookup = DeviceIdLookup() /// Full states and icon replies from the server; lines of any other kind are dropped. - /// Ends with an error for a full state that cannot be decoded. + /// Ends with `ProtocolVersionMismatch` for a full state of another protocol version and + /// with `MalformedStateError` for one that cannot be decoded. func serverLines() -> AsyncThrowingStream { AsyncThrowingStream { continuation in let task = Task { @@ -17,9 +15,6 @@ struct VolumeControlRepository { appLog("Ignoring unrecognized server line (\(bytes.count) bytes)") continue } - if case .state(let state) = line { - deviceIdLookup.ingest(state.deviceIds) - } continuation.yield(line) } continuation.finish() @@ -34,7 +29,7 @@ struct VolumeControlRepository { func pushDefaultDevice(id: String) async throws { let dto = ADefaultDeviceUpdate( - protocolVersion: VolumeControlRepository.protocolVersion, + protocolVersion: WireProtocol.version, defaultDevice: ADefaultDeviceUpdate.adflDevice(deviceId: id) ) try await send(dto) @@ -42,7 +37,7 @@ struct VolumeControlRepository { func pushMasterValues(id: String, muted: Bool, volume: Double) async throws { let dto = AMasterChannelUpdate( - protocolVersion: VolumeControlRepository.protocolVersion, + protocolVersion: WireProtocol.version, defaultDevice: AMasterChannelUpdate.adflDevice( deviceId: id, masterMuted: muted, @@ -52,13 +47,13 @@ struct VolumeControlRepository { try await send(dto) } - func pushSessionValues(name: String, id: String, volume: Double, muted: Bool) async throws { - let shortId = deviceIdLookup.shortId(for: id) ?? id + /// `deviceId` is the id of the device the session plays on; session ids are opaque. + func pushSessionValues(name: String, id: String, volume: Double, muted: Bool, deviceId: String) async throws { let dto = ASessionUpdate( - protocolVersion: VolumeControlRepository.protocolVersion, + protocolVersion: WireProtocol.version, defaultDevice: ASessionUpdate.adflDevice( sessions: [OneSession(name: name, id: id, volume: volume, muted: muted)], - deviceId: shortId + deviceId: deviceId ) ) try await send(dto) @@ -66,7 +61,7 @@ struct VolumeControlRepository { func requestIcons(ids: [String], size: Int) async throws { let dto = AIconRequest( - protocolVersion: VolumeControlRepository.protocolVersion, + protocolVersion: WireProtocol.version, iconRequest: AIconRequest.Payload(ids: ids, size: size) ) try await send(dto) @@ -76,13 +71,3 @@ struct VolumeControlRepository { try await transport.outgoing(JSONEncoder().encode(dto)) } } - -final class DeviceIdLookup { - private var table = [String: String]() - func ingest(_ mapping: [String: String]) { - table.merge(mapping) { _, new in new } - } - func shortId(for longName: String) -> String? { - table.first { longName.contains($0.key) }?.key - } -} diff --git a/PcVolumeControl/usecases/IconRequestPlanner.swift b/PcVolumeControl/usecases/IconRequestPlanner.swift index 23ebbd1..37ea9f1 100644 --- a/PcVolumeControl/usecases/IconRequestPlanner.swift +++ b/PcVolumeControl/usecases/IconRequestPlanner.swift @@ -21,10 +21,8 @@ struct IconRequestPlanner { /// The requests to send now for `ids`, in order, at `size` pixels. Leaves out ids that /// are invalid, repeated, in `skipping` (cached or being resolved locally), already /// outstanding, or unavailable, and stops at the outstanding limit; the rest are - /// planned once replies free up room. Returns nothing unless the server supports icons. - mutating func requests(for ids: [String], size: Int, supportsIcons: Bool, skipping: Set) -> [[String]] { - guard supportsIcons else { return [] } - + /// planned once replies free up room. + mutating func requests(for ids: [String], size: Int, skipping: Set) -> [[String]] { let capacity = Self.maxOutstanding - outstanding.count var planned: [String] = [] var seen = Set() diff --git a/PcVolumeControl/usecases/VolumeControlUseCases.swift b/PcVolumeControl/usecases/VolumeControlUseCases.swift index 6b6dcff..662a981 100644 --- a/PcVolumeControl/usecases/VolumeControlUseCases.swift +++ b/PcVolumeControl/usecases/VolumeControlUseCases.swift @@ -12,7 +12,7 @@ struct SendMasterChannelUpdateUseCase { struct SendSessionUpdateUseCase { let repo: VolumeControlRepository - func execute(name: String, id: String, vol: Double, muted: Bool) async throws { - try await repo.pushSessionValues(name: name, id: id, volume: vol, muted: muted) + func execute(name: String, id: String, vol: Double, muted: Bool, deviceId: String) async throws { + try await repo.pushSessionValues(name: name, id: id, volume: vol, muted: muted, deviceId: deviceId) } } diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index 2b465b4..e9a6610 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -386,6 +386,12 @@ final class MainViewModel: ObservableObject { } // Stream ended without throwing (server closed the connection). if !Task.isCancelled { handleConnectionLost() } + } catch let mismatch as ProtocolVersionMismatch { + // Reconnecting cannot help: leave the server and tell the user which side to update. + if !Task.isCancelled { + disconnect() + self.error = mismatch.localizedDescription + } } catch { // RST / keepalive timeout / read error. if !Task.isCancelled { handleConnectionLost() } @@ -432,7 +438,7 @@ final class MainViewModel: ObservableObject { } private func resolveIcons(for state: FullState) { - guard state.supportsIcons, let size = iconPixelSize else { return } + guard let size = iconPixelSize else { return } let ids = state.iconIds let current = Set(ids) if icons.keys.contains(where: { !current.contains($0) }) { @@ -469,9 +475,7 @@ final class MainViewModel: ObservableObject { private func requestMissingIcons() { guard let state = fullState, let size = iconPixelSize, let repo = currentRepo else { return } let skipping = Set(state.iconIds).subtracting(iconsMissingFromCache).union(iconsResolving) - let batches = iconPlanner.requests( - for: state.iconIds, size: size, supportsIcons: state.supportsIcons, skipping: skipping - ) + let batches = iconPlanner.requests(for: state.iconIds, size: size, skipping: skipping) // A failed send means the connection is failing; its loss resets the outstanding ids. for ids in batches { Task { try? await repo.requestIcons(ids: ids, size: size) } @@ -555,12 +559,17 @@ final class MainViewModel: ObservableObject { func updateMaster(id: String, muted: Bool, vol: Double) { Task { try? await masterUpdate.execute(id: id, muted: muted, volume: vol) } } + // Sessions shown are those of the current default device, so updates go to it. func updateSession(name: String, id: String, vol: Double, muted: Bool) { - Task { try? await sessionUpdate.execute(name: name, id: id, vol: vol, muted: muted) } + guard let deviceId = fullState?.defaultDevice.deviceId else { return } + Task { try? await sessionUpdate.execute(name: name, id: id, vol: vol, muted: muted, deviceId: deviceId) } } func updateSession(_ session: FullState.Session) async throws { - try await sessionUpdate.execute(name: session.name, id: session.id, vol: session.volume, muted: session.muted) + guard let deviceId = fullState?.defaultDevice.deviceId else { return } + try await sessionUpdate.execute( + name: session.name, id: session.id, vol: session.volume, muted: session.muted, deviceId: deviceId + ) } // MARK: - Server Management @@ -746,8 +755,7 @@ class FullState: Codable, Equatable { lhs.defaultDevice.masterMuted == rhs.defaultDevice.masterMuted && lhs.defaultDevice.masterVolume == rhs.defaultDevice.masterVolume && lhs.defaultDevice.name == rhs.defaultDevice.name && - lhs.defaultDevice.sessions == rhs.defaultDevice.sessions && - lhs.features == rhs.features + lhs.defaultDevice.sessions == rhs.defaultDevice.sessions } struct theDefaultDevice: Codable, Equatable { let deviceId: String @@ -761,27 +769,20 @@ class FullState: Codable, Equatable { var muted: Bool var name: String var volume: Double - // v8: content-derived icon id; absent on older servers and until the server resolves the icon. + // Content-derived icon id; absent until the server resolves the icon, or if it has none. var iconId: String? = nil - // v8: display-only label telling same-named sessions apart (a browser tab title). + // Display-only label telling same-named sessions apart (a browser tab title). // Never an identity: aliases and saved state key on `id`. var detail: String? = nil } var defaultDevice: theDefaultDevice let deviceIds: [String: String] let protocolVersion: Int - // v8: protocol extensions the server supports; absent on older servers. - let features: [String]? - init(protocolVersion: Int, deviceIds: [String:String], defaultDevice: theDefaultDevice, features: [String]? = nil) { + init(protocolVersion: Int, deviceIds: [String:String], defaultDevice: theDefaultDevice) { self.protocolVersion = protocolVersion self.deviceIds = deviceIds self.defaultDevice = defaultDevice - self.features = features - } - - var supportsIcons: Bool { - features?.contains("icons") ?? false } /// Distinct icon ids of the default device's sessions, in session order. diff --git a/PcVolumeControl/views/MainView.swift b/PcVolumeControl/views/MainView.swift index bf585ae..064805c 100644 --- a/PcVolumeControl/views/MainView.swift +++ b/PcVolumeControl/views/MainView.swift @@ -269,7 +269,7 @@ struct MainView: View { // Multiple output devices so the master-device selector has a // meaningful list; "mock-device" is the selected default. viewModel.fullState = FullState( - protocolVersion: 7, + protocolVersion: WireProtocol.version, deviceIds: [ "mock-device": "Speakers (HDMI)", "headphones": "Headphones (Bluetooth)", diff --git a/PcVolumeControl/views/ServerSetupGuideView.swift b/PcVolumeControl/views/ServerSetupGuideView.swift index fabb9e4..9729a59 100644 --- a/PcVolumeControl/views/ServerSetupGuideView.swift +++ b/PcVolumeControl/views/ServerSetupGuideView.swift @@ -9,11 +9,11 @@ import SwiftUI -// Single source of truth for the Windows server download location. +// Single source of truth for the server download location. enum ServerDownload { - static let releasesURL = URL(string: "https://github.com/PcVolumeControl/PcVolumeControlWindows/releases/latest")! + static let releasesURL = URL(string: "https://github.com/PcVolumeControl/PcVolumeControlServer/releases/latest")! static let organizationURL = URL(string: "https://github.com/PcVolumeControl")! - static var supportedProtocolVersion: Int { VolumeControlRepository.protocolVersion } + static var supportedProtocolVersion: Int { WireProtocol.version } } struct ServerSetupGuideView: View { @@ -29,12 +29,12 @@ struct ServerSetupGuideView: View { Link(destination: ServerDownload.releasesURL) { HStack(spacing: 4) { Image(systemName: "link") - Text("PcVolumeControlWindows releases") + Text("PcVolumeControlServer releases") } .font(.footnote) .foregroundColor(.sliderPink) } - .accessibilityLabel("Download PcVolumeControlWindows releases on GitHub") + .accessibilityLabel("Download PcVolumeControlServer releases on GitHub") ShareLink(item: ServerDownload.releasesURL) { HStack(spacing: 4) { Image(systemName: "square.and.arrow.up") diff --git a/PcVolumeControlTests/IconRequestPlannerTests.swift b/PcVolumeControlTests/IconRequestPlannerTests.swift index 98590f3..3c2d6fc 100644 --- a/PcVolumeControlTests/IconRequestPlannerTests.swift +++ b/PcVolumeControlTests/IconRequestPlannerTests.swift @@ -16,13 +16,7 @@ final class IconRequestPlannerTests: XCTestCase { } private func plan(_ planner: inout IconRequestPlanner, _ ids: [String], skipping: Set = []) -> [[String]] { - planner.requests(for: ids, size: 66, supportsIcons: true, skipping: skipping) - } - - func testNoRequestsWithoutTheIconsFeature() { - var planner = IconRequestPlanner() - XCTAssertEqual(planner.requests(for: ["a", "b"], size: 66, supportsIcons: false, skipping: []), []) - XCTAssertTrue(planner.outstanding.isEmpty) + planner.requests(for: ids, size: 66, skipping: skipping) } func testDuplicatesAreRequestedOnce() { @@ -104,8 +98,8 @@ final class IconRequestPlannerTests: XCTestCase { func testReplyReportsTheRequestedSize() { var planner = IconRequestPlanner() - _ = planner.requests(for: ["a"], size: 48, supportsIcons: true, skipping: []) - _ = planner.requests(for: ["b"], size: 96, supportsIcons: true, skipping: []) + _ = planner.requests(for: ["a"], size: 48, skipping: []) + _ = planner.requests(for: ["b"], size: 96, skipping: []) XCTAssertEqual(planner.recordReply(for: "a", available: true), 48) XCTAssertEqual(planner.recordReply(for: "b", available: true), 96) } diff --git a/PcVolumeControlTests/LineFramerTests.swift b/PcVolumeControlTests/LineFramerTests.swift index 7188629..bd04d22 100644 --- a/PcVolumeControlTests/LineFramerTests.swift +++ b/PcVolumeControlTests/LineFramerTests.swift @@ -23,7 +23,7 @@ final class LineFramerTests: XCTestCase { var framer = LineFramer() XCTAssertEqual(framer.append(Data(#"{"protocol"#.utf8)), []) XCTAssertEqual(framer.append(Data(#"Version":7,"#.utf8)), []) - XCTAssertEqual(strings(framer.append(Data((#""x":1}"# + "\n{").utf8))), [#"{"protocolVersion":7,"x":1}"#]) + XCTAssertEqual(strings(framer.append(Data((#""x":1}"# + "\n{").utf8))), [#"{"protocolVersion":8,"x":1}"#]) XCTAssertEqual(strings(framer.append(Data("}\n".utf8))), ["{}"]) } diff --git a/PcVolumeControlTests/MainViewModelSimpleTests.swift b/PcVolumeControlTests/MainViewModelSimpleTests.swift index 4fe832f..1f3d90b 100644 --- a/PcVolumeControlTests/MainViewModelSimpleTests.swift +++ b/PcVolumeControlTests/MainViewModelSimpleTests.swift @@ -112,6 +112,8 @@ final class MainViewModelSimpleTests: XCTestCase { volume: 80.0 ) + sut.fullState = createMockFullState() + // When - this will call the actual use case but with mock transport try await sut.updateSession(testSession) @@ -119,12 +121,35 @@ final class MainViewModelSimpleTests: XCTestCase { XCTAssertTrue(mockRepository.outgoingDataCalled) XCTAssertFalse(mockRepository.sentData.isEmpty) } + + func testSessionUpdateGoesToTheDefaultDeviceWhateverTheSessionId() async throws { + // Session ids are opaque: this one does not contain any device id. + sut.fullState = createMockFullState() + let session = FullState.Session(id: "stream-42", muted: false, name: "Firefox", volume: 30) + + try await sut.updateSession(session) + + let sent = try XCTUnwrap(mockRepository.sentData.first) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: sent) as? [String: Any]) + XCTAssertEqual(json["protocolVersion"] as? Int, 8) + let device = try XCTUnwrap(json["defaultDevice"] as? [String: Any]) + XCTAssertEqual(device["deviceId"] as? String, "device1") + let sessions = try XCTUnwrap(device["sessions"] as? [[String: Any]]) + XCTAssertEqual(sessions.first?["id"] as? String, "stream-42") + } + + func testSessionUpdateWithoutAStateSendsNothing() async throws { + let session = FullState.Session(id: "stream-42", muted: false, name: "Firefox", volume: 30) + try await sut.updateSession(session) + XCTAssertTrue(mockRepository.sentData.isEmpty) + } func testSessionUpdateDoesNotSendDetail() async throws { let session = FullState.Session( id: "dev-a|961", muted: false, name: "Firefox", volume: 40, iconId: "4b13f0d55a3779a6ff892414f951be3f", detail: "Big Buck Bunny - YouTube" ) + sut.fullState = createMockFullState() try await sut.updateSession(session) @@ -165,7 +190,7 @@ final class MainViewModelSimpleTests: XCTestCase { // Then XCTAssertNotNil(sut.fullState) - XCTAssertEqual(sut.fullState?.protocolVersion, 7) + XCTAssertEqual(sut.fullState?.protocolVersion, 8) XCTAssertEqual(sut.fullState?.defaultDevice.deviceId, "device1") } @@ -345,7 +370,7 @@ final class MainViewModelSimpleTests: XCTestCase { let deviceIds = ["device1": "Default Device", "device2": "Secondary Device"] return FullState( - protocolVersion: 7, + protocolVersion: 8, deviceIds: deviceIds, defaultDevice: defaultDevice ) diff --git a/PcVolumeControlTests/ServerLineTests.swift b/PcVolumeControlTests/ServerLineTests.swift index 1c3338e..d21e13d 100644 --- a/PcVolumeControlTests/ServerLineTests.swift +++ b/PcVolumeControlTests/ServerLineTests.swift @@ -2,8 +2,8 @@ // ServerLineTests.swift // PcVolumeControlTests // -// Decoding and classification of server lines, including protocol v8 fields and -// icon replies captured from a v8 server. +// Decoding and classification of protocol version 8 server lines, including icon +// replies captured from a server, and the version check. // import XCTest @@ -12,29 +12,34 @@ import UIKit final class ServerLineTests: XCTestCase { - // A v7 server: no `features`, no `iconId`. - static let v7State = #""" + // A server that serves no icons or details: no `iconId`, no `detail`. + static let plainState = #""" + {"protocolVersion":8,"applicationVersion":"v10","deviceIds":{"dev-a":"Speakers"},"defaultDevice":{"deviceId":"dev-a","name":"Speakers","masterVolume":80.0,"masterMuted":false,"sessions":[{"name":"Chrome","id":"{0.0.0.00000000}.{dev-a}|chrome.exe","volume":35.0,"muted":false}]}} + """# + + // The original C# Windows server: the same shape, but protocol version 7. + static let olderServerState = #""" {"protocolVersion":7,"applicationVersion":"v10","deviceIds":{"dev-a":"Speakers"},"defaultDevice":{"deviceId":"dev-a","name":"Speakers","masterVolume":80.0,"masterMuted":false,"sessions":[{"name":"Chrome","id":"{0.0.0.00000000}.{dev-a}|chrome.exe","volume":35.0,"muted":false}]}} """# // Shape captured from a v8 server (device names shortened): one session without an // icon id yet, and two sessions sharing an id. static let v8State = #""" - {"protocolVersion":7,"applicationVersion":"v10","features":["icons"],"deviceIds":{"dev-a":"Headset","dev-b":"Speakers"},"defaultDevice":{"deviceId":"dev-a","name":"Headset","masterVolume":100.0,"masterMuted":false,"sessions":[{"name":"speech-dispatcher-dummy","id":"dev-a|413","volume":100.0,"muted":false},{"name":"Firefox","id":"dev-a|961","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f"},{"name":"Firefox","id":"dev-a|6492","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f"},{"name":"Spotify","id":"dev-a|6565","volume":100.0,"muted":false,"iconId":"6b58026ae167f8f2e802f2531657443c"}]}} + {"protocolVersion":8,"applicationVersion":"v10","deviceIds":{"dev-a":"Headset","dev-b":"Speakers"},"defaultDevice":{"deviceId":"dev-a","name":"Headset","masterVolume":100.0,"masterMuted":false,"sessions":[{"name":"speech-dispatcher-dummy","id":"dev-a|413","volume":100.0,"muted":false},{"name":"Firefox","id":"dev-a|961","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f"},{"name":"Firefox","id":"dev-a|6492","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f"},{"name":"Spotify","id":"dev-a|6565","volume":100.0,"muted":false,"iconId":"6b58026ae167f8f2e802f2531657443c"}]}} """# // Captured from a v8 server on Linux with Firefox playing in three tabs. Device names // are shortened and the tab titles replaced; field order and shape are as sent. static let v8StateWithDetails = #""" - {"protocolVersion":7,"applicationVersion":"v10","features":["icons"],"deviceIds":{"dev-a":"Speakers","dev-b":"Headset"},"defaultDevice":{"deviceId":"dev-a","name":"Speakers","masterVolume":36.439514,"masterMuted":false,"sessions":[{"name":"speech-dispatcher-dummy","id":"dev-a|413","volume":100.0,"muted":false},{"name":"Firefox","id":"dev-a|961","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Big Buck Bunny - YouTube"},{"name":"Firefox","id":"dev-a|6622","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Radio Paradise - Main Mix"},{"name":"Firefox","id":"dev-a|6974","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Café Concert: You've Got a Friend…"}]}} + {"protocolVersion":8,"applicationVersion":"v10","deviceIds":{"dev-a":"Speakers","dev-b":"Headset"},"defaultDevice":{"deviceId":"dev-a","name":"Speakers","masterVolume":36.439514,"masterMuted":false,"sessions":[{"name":"speech-dispatcher-dummy","id":"dev-a|413","volume":100.0,"muted":false},{"name":"Firefox","id":"dev-a|961","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Big Buck Bunny - YouTube"},{"name":"Firefox","id":"dev-a|6622","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Radio Paradise - Main Mix"},{"name":"Firefox","id":"dev-a|6974","volume":100.0,"muted":false,"iconId":"4b13f0d55a3779a6ff892414f951be3f","detail":"Café Concert: You've Got a Friend…"}]}} """# // Captured verbatim from a v8 server: a 16 px PNG reply and a notFound reply. static let iconImageReply = #""" - {"protocolVersion":7,"icon":{"id":"6b58026ae167f8f2e802f2531657443c","size":16,"mime":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACWUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1U/8+yCej1se/14vZ8Vby34UgKQn5qifuf0lvvPPeU6IB7j2b97jmllfvh14C56/n1sP7f3vfanvu48rEM/0sKe8xzXjWH4feAQvjP2Urs9Xe+rDv+8+APFMtzz+fX4O/Oa8KMwv3vbY734zAAE8+G/e45WyL388/fodDN/3FPLeJawb9EGcWRCP2KG8whnqa16PtjoAYuBVbn2p7/5jAdzy9+/9xRQ+qf31efJvzqMbNtGi4FXD9yxpj9+l/fl9eDLdWz2I2Ue+OJgvue2x3/3JAnjQP7zXTzn01qwaw088nbz9AI4mWFTihg3iJU5SH3Oc6bfvpv35OWaf/jIY//Ttj/2etxHALf/wnj9NxFv50sDwXU8ibthAmxUvG3n7Ae0vz5O7a/p3eCj9ez6Cy1r+zG0v/r1vLYCb/+Y9v0x9fDzA9Mf30f7mPD4Y0aISD9mmvuIZfG7F9Ot30X/IYyAEw/Rlt73U93+iAG75/Xd5dU7Nfg9g+p270ayg7Q4fTuRT95h+/250cs78014a5pXLdo9e/bZX+dE/EFfolr95j1+lL6/PC5BP2nU8dEfUwKv2a7e/zPe9EWDxTDf+xJvcVB5++vfpy4N4YaZ8RnvS2Ve/8+1+6Q4A8QAnv/MNb954iTPfFVvd6/F85MH4G/l3Z9/nrvf91du5AvG84rqfeuvXrNcs3pqiRxLA6CdN9y1/+p63+enfBZJnQ/z78I+X+d0RjTFkMwAAAABJRU5ErkJggg=="}} + {"protocolVersion":8,"icon":{"id":"6b58026ae167f8f2e802f2531657443c","size":16,"mime":"image/png","data":"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACWUlEQVR4Ae3AA6AkWZbG8f937o3IzKdyS2Oubdu2bdu2bdu2bWmMnpZKr54yMyLu+Xa3anqmhztr1U/8+yCej1se/14vZ8Vby34UgKQn5qifuf0lvvPPeU6IB7j2b97jmllfvh14C56/n1sP7f3vfanvu48rEM/0sKe8xzXjWH4feAQvjP2Urs9Xe+rDv+8+APFMtzz+fX4O/Oa8KMwv3vbY734zAAE8+G/e45WyL388/fodDN/3FPLeJawb9EGcWRCP2KG8whnqa16PtjoAYuBVbn2p7/5jAdzy9+/9xRQ+qf31efJvzqMbNtGi4FXD9yxpj9+l/fl9eDLdWz2I2Ue+OJgvue2x3/3JAnjQP7zXTzn01qwaw088nbz9AI4mWFTihg3iJU5SH3Oc6bfvpv35OWaf/jIY//Ttj/2etxHALf/wnj9NxFv50sDwXU8ibthAmxUvG3n7Ae0vz5O7a/p3eCj9ez6Cy1r+zG0v/r1vLYCb/+Y9v0x9fDzA9Mf30f7mPD4Y0aISD9mmvuIZfG7F9Ot30X/IYyAEw/Rlt73U93+iAG75/Xd5dU7Nfg9g+p270ayg7Q4fTuRT95h+/250cs78014a5pXLdo9e/bZX+dE/EFfolr95j1+lL6/PC5BP2nU8dEfUwKv2a7e/zPe9EWDxTDf+xJvcVB5++vfpy4N4YaZ8RnvS2Ve/8+1+6Q4A8QAnv/MNb954iTPfFVvd6/F85MH4G/l3Z9/nrvf91du5AvG84rqfeuvXrNcs3pqiRxLA6CdN9y1/+p63+enfBZJnQ/z78I+X+d0RjTFkMwAAAABJRU5ErkJggg=="}} """# static let iconNotFoundReply = #""" - {"protocolVersion":7,"icon":{"id":"0000notarealid","error":"notFound"}} + {"protocolVersion":8,"icon":{"id":"0000notarealid","error":"notFound"}} """# private func classify(_ text: String) throws -> ServerLine? { @@ -43,21 +48,20 @@ final class ServerLineTests: XCTestCase { // MARK: - Full state decoding - func testV7StateDecodesWithoutV8Fields() throws { - guard case .state(let state) = try classify(Self.v7State) else { + func testStateWithoutIconsOrDetailsDecodes() throws { + guard case .state(let state) = try classify(Self.plainState) else { return XCTFail("Expected a full state") } - XCTAssertNil(state.features) + XCTAssertEqual(state.protocolVersion, 8) XCTAssertEqual(state.defaultDevice.sessions.count, 1) XCTAssertNil(state.defaultDevice.sessions[0].iconId) XCTAssertEqual(state.defaultDevice.sessions[0].volume, 35.0) } - func testV8StateDecodesFeaturesAndIconIds() throws { + func testStateDecodesIconIds() throws { guard case .state(let state) = try classify(Self.v8State) else { return XCTFail("Expected a full state") } - XCTAssertEqual(state.features, ["icons"]) XCTAssertEqual(state.defaultDevice.sessions.map(\.iconId), [ nil, "4b13f0d55a3779a6ff892414f951be3f", @@ -66,15 +70,13 @@ final class ServerLineTests: XCTestCase { ]) } - func testIconHelpersOnFullState() throws { - guard case .state(let v8) = try classify(Self.v8State), - case .state(let v7) = try classify(Self.v7State) else { + func testIconIdsAreDistinctAndInSessionOrder() throws { + guard case .state(let withIcons) = try classify(Self.v8State), + case .state(let plain) = try classify(Self.plainState) else { return XCTFail("Expected full states") } - XCTAssertTrue(v8.supportsIcons) - XCTAssertEqual(v8.iconIds, ["4b13f0d55a3779a6ff892414f951be3f", "6b58026ae167f8f2e802f2531657443c"]) - XCTAssertFalse(v7.supportsIcons) - XCTAssertEqual(v7.iconIds, []) + XCTAssertEqual(withIcons.iconIds, ["4b13f0d55a3779a6ff892414f951be3f", "6b58026ae167f8f2e802f2531657443c"]) + XCTAssertEqual(plain.iconIds, []) } func testSessionDetailsDecode() throws { @@ -89,12 +91,10 @@ final class ServerLineTests: XCTestCase { ]) // Same application, told apart only by the detail. XCTAssertEqual(Set(state.defaultDevice.sessions.dropFirst().map(\.name)), ["Firefox"]) - // Details are not a feature: the features list is unaffected. - XCTAssertEqual(state.features, ["icons"]) } func testStatesWithoutDetailsDecodeWithNone() throws { - for text in [Self.v7State, Self.v8State] { + for text in [Self.plainState, Self.v8State] { guard case .state(let state) = try classify(text) else { return XCTFail("Expected a full state") } @@ -102,16 +102,52 @@ final class ServerLineTests: XCTestCase { } } - func testUnknownFeatureNamesAreKept() throws { - let text = Self.v7State.replacingOccurrences( + func testUnknownFieldsAreIgnored() throws { + let text = Self.plainState.replacingOccurrences( of: #""applicationVersion":"v10","#, - with: #""applicationVersion":"v10","features":["somethingNew"],"# + with: #""applicationVersion":"v10","features":["icons"],"somethingNew":{"a":1},"# ) guard case .state(let state) = try classify(text) else { return XCTFail("Expected a full state") } - XCTAssertEqual(state.features, ["somethingNew"]) - XCTAssertFalse(state.supportsIcons) + XCTAssertEqual(state.defaultDevice.sessions.count, 1) + } + + // MARK: - Protocol version + + func testOlderServerIsRejected() { + XCTAssertThrowsError(try classify(Self.olderServerState)) { error in + guard let mismatch = error as? ProtocolVersionMismatch else { + return XCTFail("Expected a version mismatch, got \(error)") + } + XCTAssertEqual(mismatch.serverVersion, 7) + XCTAssertTrue(mismatch.serverIsOlder) + } + } + + func testNewerServerIsRejectedEvenIfItsStateCannotBeDecoded() { + XCTAssertThrowsError(try classify(#"{"protocolVersion":9,"defaultDevice":{"somethingElse":true}}"#)) { error in + guard let mismatch = error as? ProtocolVersionMismatch else { + return XCTFail("Expected a version mismatch, got \(error)") + } + XCTAssertEqual(mismatch.serverVersion, 9) + XCTAssertFalse(mismatch.serverIsOlder) + } + } + + func testMismatchMessagesSayWhichSideToUpdate() { + let older = ProtocolVersionMismatch(serverVersion: 7).localizedDescription + let newer = ProtocolVersionMismatch(serverVersion: 9).localizedDescription + XCTAssertTrue(older.contains("PcVolumeControlServer"), older) + XCTAssertTrue(older.contains("7"), older) + XCTAssertTrue(newer.contains("Update PcVolumeControl on this device"), newer) + XCTAssertTrue(newer.contains("9"), newer) + } + + func testStateWithoutVersionIsMalformed() { + XCTAssertThrowsError(try classify(#"{"defaultDevice":{"deviceId":"x"}}"#)) { error in + XCTAssertTrue(error is MalformedStateError) + } } // MARK: - Icon replies @@ -137,7 +173,7 @@ final class ServerLineTests: XCTestCase { } func testIconReplyWithUnknownErrorHasNoImage() throws { - let text = #"{"protocolVersion":7,"icon":{"id":"abc","error":"somethingElse","data":"iVBORw0KGgo="}}"# + let text = #"{"protocolVersion":8,"icon":{"id":"abc","error":"somethingElse","data":"iVBORw0KGgo="}}"# guard case .icon(let reply) = try classify(text) else { return XCTFail("Expected an icon reply") } @@ -145,7 +181,7 @@ final class ServerLineTests: XCTestCase { } func testIconReplyWithInvalidBase64StillAnswersTheId() throws { - let text = #"{"protocolVersion":7,"icon":{"id":"abc","size":16,"mime":"image/png","data":"not base64!"}}"# + let text = #"{"protocolVersion":8,"icon":{"id":"abc","size":16,"mime":"image/png","data":"not base64!"}}"# guard case .icon(let reply) = try classify(text) else { return XCTFail("Expected an icon reply") } @@ -154,7 +190,7 @@ final class ServerLineTests: XCTestCase { } func testIconReplyWithNonStringErrorHasNoImage() throws { - let text = #"{"protocolVersion":7,"icon":{"id":"abc","error":{"code":3},"data":"iVBORw0KGgo="}}"# + let text = #"{"protocolVersion":8,"icon":{"id":"abc","error":{"code":3},"data":"iVBORw0KGgo="}}"# guard case .icon(let reply) = try classify(text) else { return XCTFail("Expected an icon reply") } @@ -162,7 +198,7 @@ final class ServerLineTests: XCTestCase { } func testIconReplyWithEmptyDataHasNoImage() throws { - let text = #"{"protocolVersion":7,"icon":{"id":"abc","size":16,"mime":"image/png","data":""}}"# + let text = #"{"protocolVersion":8,"icon":{"id":"abc","size":16,"mime":"image/png","data":""}}"# guard case .icon(let reply) = try classify(text) else { return XCTFail("Expected an icon reply") } @@ -172,13 +208,13 @@ final class ServerLineTests: XCTestCase { // MARK: - Classification func testUnknownLineIsIgnored() throws { - XCTAssertNil(try classify(#"{"protocolVersion":7,"somethingNew":{"a":1}}"#)) + XCTAssertNil(try classify(#"{"protocolVersion":8,"somethingNew":{"a":1}}"#)) } func testMalformedLinesAreIgnored() throws { for text in [ - #"{"protocolVersion":7,"defaultDevice":{"deviceId":"#, - #"{"protocolVersion":7,"icon":{"error":"notFound"}}"#, + #"{"protocolVersion":8,"defaultDevice":{"deviceId":"#, + #"{"protocolVersion":8,"icon":{"error":"notFound"}}"#, "[1,2,3]", "not json", ] { @@ -187,15 +223,15 @@ final class ServerLineTests: XCTestCase { } func testLineWithBothStateAndIconIsIgnored() throws { - let text = Self.v7State.replacingOccurrences( - of: #""protocolVersion":7,"#, - with: #""protocolVersion":7,"icon":{"id":"abc","error":"notFound"},"# + let text = Self.plainState.replacingOccurrences( + of: #""protocolVersion":8,"#, + with: #""protocolVersion":8,"icon":{"id":"abc","error":"notFound"},"# ) XCTAssertNil(try classify(text)) } func testUndecodableFullStateThrows() { - XCTAssertThrowsError(try classify(#"{"protocolVersion":7,"defaultDevice":{"deviceId":"x"}}"#)) { error in + XCTAssertThrowsError(try classify(#"{"protocolVersion":8,"defaultDevice":{"deviceId":"x"}}"#)) { error in XCTAssertTrue(error is MalformedStateError) } } diff --git a/PcVolumeControlTests/SessionDetailTests.swift b/PcVolumeControlTests/SessionDetailTests.swift index 00c70a4..c1f8646 100644 --- a/PcVolumeControlTests/SessionDetailTests.swift +++ b/PcVolumeControlTests/SessionDetailTests.swift @@ -20,12 +20,11 @@ final class SessionDetailTests: XCTestCase { ) } return FullState( - protocolVersion: 7, + protocolVersion: 8, deviceIds: ["dev-a": "Speakers"], defaultDevice: FullState.theDefaultDevice( deviceId: "dev-a", masterMuted: false, masterVolume: 80, name: "Speakers", sessions: sessions - ), - features: ["icons"] + ) ) } diff --git a/PcVolumeControlTests/VolumeControlRepositoryTests.swift b/PcVolumeControlTests/VolumeControlRepositoryTests.swift index d476281..fe47217 100644 --- a/PcVolumeControlTests/VolumeControlRepositoryTests.swift +++ b/PcVolumeControlTests/VolumeControlRepositoryTests.swift @@ -13,9 +13,9 @@ final class VolumeControlRepositoryTests: XCTestCase { func testUnknownAndMalformedLinesDoNotEndTheStream() async throws { let transport = ScriptedTransport(lines: [ - ServerLineTests.v7State, + ServerLineTests.plainState, "not json", - #"{"protocolVersion":7,"somethingNew":true}"#, + #"{"protocolVersion":8,"somethingNew":true}"#, ServerLineTests.iconNotFoundReply, ServerLineTests.v8State, ]) @@ -33,9 +33,9 @@ final class VolumeControlRepositoryTests: XCTestCase { func testUndecodableFullStateEndsTheStream() async { let transport = ScriptedTransport(lines: [ - ServerLineTests.v7State, - #"{"protocolVersion":7,"defaultDevice":{"deviceId":"x"}}"#, - ServerLineTests.v7State, + ServerLineTests.plainState, + #"{"protocolVersion":8,"defaultDevice":{"deviceId":"x"}}"#, + ServerLineTests.plainState, ]) let repo = VolumeControlRepository(transport: transport) @@ -51,6 +51,37 @@ final class VolumeControlRepositoryTests: XCTestCase { XCTAssertEqual(states, 1) } + func testOlderServerEndsTheStreamWithAVersionMismatch() async { + let transport = ScriptedTransport(lines: [ServerLineTests.olderServerState, ServerLineTests.plainState]) + let repo = VolumeControlRepository(transport: transport) + + var states = 0 + do { + for try await _ in repo.serverLines() { + states += 1 + } + XCTFail("Expected the stream to end with an error") + } catch { + XCTAssertEqual((error as? ProtocolVersionMismatch)?.serverVersion, 7) + } + XCTAssertEqual(states, 0) + } + + func testEveryOutgoingMessageSaysVersion8() async throws { + let transport = MockVolumeTransport() + let repo = VolumeControlRepository(transport: transport) + try await repo.pushDefaultDevice(id: "dev-a") + try await repo.pushMasterValues(id: "dev-a", muted: false, volume: 50) + try await repo.pushSessionValues(name: "Firefox", id: "s1", volume: 40, muted: false, deviceId: "dev-a") + try await repo.requestIcons(ids: ["abc"], size: 66) + + XCTAssertEqual(transport.sentData.count, 4) + for data in transport.sentData { + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + XCTAssertEqual(json["protocolVersion"] as? Int, 8) + } + } + func testIconRequestEncoding() async throws { let transport = MockVolumeTransport() let repo = VolumeControlRepository(transport: transport) @@ -58,7 +89,7 @@ final class VolumeControlRepositoryTests: XCTestCase { let sent = try XCTUnwrap(transport.sentData.first) let json = try XCTUnwrap(JSONSerialization.jsonObject(with: sent) as? [String: Any]) - XCTAssertEqual(json["protocolVersion"] as? Int, 7) + XCTAssertEqual(json["protocolVersion"] as? Int, 8) XCTAssertNil(json["defaultDevice"]) let request = try XCTUnwrap(json["iconRequest"] as? [String: Any]) XCTAssertEqual(request["ids"] as? [String], ["abc", "def"]) diff --git a/README.md b/README.md index a5512f0..3c4a6fb 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,8 @@ The app connects to a free companion Windows server over your local network, dis - Auto-discovery of the server on your local network (or manual IP/port entry) - Application icons next to each app, and details such as a browser tab's title under the app name, when the server sends them +This version of the app needs [PcVolumeControlServer](https://github.com/PcVolumeControl/PcVolumeControlServer) (protocol version 8) on the PC. It does not work with the original PcVolumeControlWindows server; if you connect to one, the app says the server needs updating. + ## Demo [Watch a quick demo](https://www.youtube.com/shorts/yMf1cxd65t4) @@ -41,13 +43,13 @@ The app connects to a free companion Windows server over your local network, dis [Get it on the App Store](https://itunes.apple.com/us/app/pcvolumecontrol/id1336171942?ls=1&mt=8) -### 2. Install the Windows Server +### 2. Install the Server -PC Volume Control requires the free companion server on your Windows PC. +PC Volume Control requires the free companion server, [PcVolumeControlServer](https://github.com/PcVolumeControl/PcVolumeControlServer), on your PC (Windows or Linux). The older PcVolumeControlWindows server does not work with this version of the app; uninstall it first, as both use port 3000. -1. **Download** the latest [PC Volume Control Server release](https://github.com/PcVolumeControl/PcVolumeControlWindows/releases/latest) for Windows. -2. **Install and run** the server on your PC. Allow it through Windows Firewall when prompted (private networks). -3. **Note the server address** — the server window displays your PC's IP address and port (default 3000). +1. **Download** the latest [PcVolumeControlServer release](https://github.com/PcVolumeControl/PcVolumeControlServer/releases/latest) for your system; its README has the install steps. +2. **Install and run** the server on your PC. On Windows, allow it through Windows Firewall when prompted (private networks). +3. **Note the server address**: your PC's IP address and the port (default 3000). ### 3. Connect Your Device From f0b6f68fd430f33b53bfcad22efd99d0576d4aa4 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 13:19:02 -0800 Subject: [PATCH 17/21] Address review of the version 8 change Stop parsing session ids for purpose suffixes (ids are opaque and no server sends them), make the in-app server copy platform neutral, drop the unused synchronous session update and the protocol version alias, and fix a stale comment. --- Localizable.xcstrings | 16 ++++---- .../viewmodels/MainViewModel.swift | 7 +--- .../viewmodels/SliderViewModel.swift | 40 ++----------------- PcVolumeControl/views/IntroTourView.swift | 4 +- PcVolumeControl/views/MainView.swift | 2 +- .../views/ServerSetupGuideView.swift | 9 ++--- .../MainViewModelSimpleTests.swift | 1 - 7 files changed, 19 insertions(+), 60 deletions(-) diff --git a/Localizable.xcstrings b/Localizable.xcstrings index a51f085..323423d 100644 --- a/Localizable.xcstrings +++ b/Localizable.xcstrings @@ -20,7 +20,7 @@ "About" : { }, - "Adjust the volume of every application on your Windows PC remotely. Turn the game down without leaving voice chat behind." : { + "Adjust the volume of every application on your PC remotely. Turn the game down without leaving voice chat behind." : { "comment" : "A description of the main feature of the app.", "isCommentAutoGenerated" : true }, @@ -184,14 +184,14 @@ "comment" : "A description of how to connect to the PcVolumeControl server.", "isCommentAutoGenerated" : true }, - "On your Windows PC, download the latest installer from GitHub." : { + "On your PC (Windows or Linux), download the latest release from GitHub." : { "comment" : "A step in the guide that instructs the user to download the latest installer from GitHub.", "isCommentAutoGenerated" : true }, "Opens a picker to choose the active output device" : { }, - "Opens the Windows server setup guide" : { + "Opens the server setup guide" : { "comment" : "A hint that appears when hovering over the button to", "isCommentAutoGenerated" : true }, @@ -206,8 +206,8 @@ "comment" : "The accessibility label for the app logo.", "isCommentAutoGenerated" : true }, - "PcVolumeControl needs a small, free server running on your Windows PC. Set it up once and this app can find it automatically." : { - "comment" : "A description of the purpose of the Windows server.", + "PcVolumeControl needs a small, free server running on your PC. Set it up once and this app can find it automatically." : { + "comment" : "A description of the purpose of the server.", "isCommentAutoGenerated" : true }, "PcVolumeControlServer releases" : { @@ -242,8 +242,8 @@ "comment" : "A button that, when pressed, replays the introductory tour.", "isCommentAutoGenerated" : true }, - "Run the installer, then start the server. If Windows Firewall asks, click Allow so the server can accept connections on private networks." : { - "comment" : "A step in the guide that instructs the user to run the installer and start the server, with a note about Windows Firewall.", + "Install the server as its README describes, then start it. On Windows, if Windows Firewall asks, click Allow so the server can accept connections on private networks." : { + "comment" : "A step in the guide that instructs the user to install and start the server, with a note about Windows Firewall.", "isCommentAutoGenerated" : true }, "Save" : { @@ -312,7 +312,7 @@ "This PC server is too old (protocol version %lld). Install the latest PcVolumeControlServer on your PC to use this version of the app." : { "comment" : "Error shown when the server speaks an older protocol version than the app." }, - "This app talks to the PcVolumeControl server, a small program that runs on your Windows PC." : { + "This app talks to the PcVolumeControl server, a small program that runs on your PC." : { "comment" : "A description of how the app interacts with the server.", "isCommentAutoGenerated" : true }, diff --git a/PcVolumeControl/viewmodels/MainViewModel.swift b/PcVolumeControl/viewmodels/MainViewModel.swift index e9a6610..ffe941b 100644 --- a/PcVolumeControl/viewmodels/MainViewModel.swift +++ b/PcVolumeControl/viewmodels/MainViewModel.swift @@ -56,7 +56,7 @@ final class MainViewModel: ObservableObject { private var connectedOverWiFi = false private var connectedOverCellular = false - // Icons (protocol v8 `icons` feature). The sets describe ids at the current pixel size; + // Icons. The sets describe ids at the current pixel size; // `icons` keeps showing images of an earlier size until replacements arrive. private let iconRepo: IconRepository private var iconPlanner = IconRequestPlanner() @@ -560,11 +560,6 @@ final class MainViewModel: ObservableObject { Task { try? await masterUpdate.execute(id: id, muted: muted, volume: vol) } } // Sessions shown are those of the current default device, so updates go to it. - func updateSession(name: String, id: String, vol: Double, muted: Bool) { - guard let deviceId = fullState?.defaultDevice.deviceId else { return } - Task { try? await sessionUpdate.execute(name: name, id: id, vol: vol, muted: muted, deviceId: deviceId) } - } - func updateSession(_ session: FullState.Session) async throws { guard let deviceId = fullState?.defaultDevice.deviceId else { return } try await sessionUpdate.execute( diff --git a/PcVolumeControl/viewmodels/SliderViewModel.swift b/PcVolumeControl/viewmodels/SliderViewModel.swift index eb93579..154ad76 100644 --- a/PcVolumeControl/viewmodels/SliderViewModel.swift +++ b/PcVolumeControl/viewmodels/SliderViewModel.swift @@ -145,52 +145,18 @@ final class SliderViewModel: ObservableObject { devices = state.deviceIds } - // Parse session name from ID and fallback name using new protocol - private func parseSessionDisplayName(sessionId: String, fallbackName: String) -> String { - // Check for new protocol format: |PCVC# - if let pcvcRange = sessionId.range(of: "|PCVC#") { - let purposeStart = sessionId.index(pcvcRange.upperBound, offsetBy: 0) - let purpose = String(sessionId[purposeStart...]) - - // Convert purpose to user-friendly display name - switch purpose.lowercased() { - case "discord-voice": - return "Discord (Voice)" - case "discord-notifications": - return "Discord (Notifications)" - default: - // For other purposes, capitalize and format nicely - let formattedPurpose = purpose.replacingOccurrences(of: "-", with: " ") - .split(separator: " ") - .map { $0.prefix(1).uppercased() + $0.dropFirst().lowercased() } - .joined(separator: " ") - return "\(fallbackName) (\(formattedPurpose))" - } - } - - // Use existing backward compatible logic - return fallbackName - } - private func updateSessionsRespectingDebounce(with incoming: [FullState.Session]) { - // Apply new naming protocol to sessions - let processedSessions = incoming.map { session in - var processed = session - processed.name = parseSessionDisplayName(sessionId: session.id, fallbackName: session.name) - return processed - } - // If preserving order and we have a saved order, use it if preserveSessionOrder && !savedOrder.isEmpty { - updateWithSavedOrder(incomingSessions: processedSessions) + updateWithSavedOrder(incomingSessions: incoming) } // If we have sessions and user has reordered, preserve current order else if !sessions.isEmpty { - updatePreservingCurrentOrder(incomingSessions: processedSessions) + updatePreservingCurrentOrder(incomingSessions: incoming) } // Otherwise sort alphabetically, but respect editingIds else { - let sortedSessions = processedSessions.sorted(by: Self.inDisplayOrder) + let sortedSessions = incoming.sorted(by: Self.inDisplayOrder) // If any sessions are being edited, preserve their values if !editingIds.isEmpty { diff --git a/PcVolumeControl/views/IntroTourView.swift b/PcVolumeControl/views/IntroTourView.swift index 10a5366..b3e3dd9 100644 --- a/PcVolumeControl/views/IntroTourView.swift +++ b/PcVolumeControl/views/IntroTourView.swift @@ -54,7 +54,7 @@ struct IntroTourView: View { .fontWeight(.bold) .foregroundColor(.white) .multilineTextAlignment(.center) - Text("Adjust the volume of every application on your Windows PC remotely. Turn the game down without leaving voice chat behind.") + Text("Adjust the volume of every application on your PC remotely. Turn the game down without leaving voice chat behind.") .font(.subheadline) .foregroundColor(.gray) .multilineTextAlignment(.center) @@ -76,7 +76,7 @@ struct IntroTourView: View { .fontWeight(.bold) .foregroundColor(.white) .multilineTextAlignment(.center) - Text("This app talks to the PcVolumeControl server, a small program that runs on your Windows PC.") + Text("This app talks to the PcVolumeControl server, a small program that runs on your PC.") .font(.subheadline) .foregroundColor(.gray) .multilineTextAlignment(.center) diff --git a/PcVolumeControl/views/MainView.swift b/PcVolumeControl/views/MainView.swift index 064805c..7068b97 100644 --- a/PcVolumeControl/views/MainView.swift +++ b/PcVolumeControl/views/MainView.swift @@ -109,7 +109,7 @@ struct MainView: View { .padding(.vertical, 12) .accessibilityElement(children: .combine) } - .accessibilityHint("Opens the Windows server setup guide") + .accessibilityHint("Opens the server setup guide") } .readableContentWidth() } diff --git a/PcVolumeControl/views/ServerSetupGuideView.swift b/PcVolumeControl/views/ServerSetupGuideView.swift index 9729a59..08f982c 100644 --- a/PcVolumeControl/views/ServerSetupGuideView.swift +++ b/PcVolumeControl/views/ServerSetupGuideView.swift @@ -13,19 +13,18 @@ import SwiftUI enum ServerDownload { static let releasesURL = URL(string: "https://github.com/PcVolumeControl/PcVolumeControlServer/releases/latest")! static let organizationURL = URL(string: "https://github.com/PcVolumeControl")! - static var supportedProtocolVersion: Int { WireProtocol.version } } struct ServerSetupGuideView: View { var body: some View { ScrollView { VStack(alignment: .leading, spacing: 16) { - Text("PcVolumeControl needs a small, free server running on your Windows PC. Set it up once and this app can find it automatically.") + Text("PcVolumeControl needs a small, free server running on your PC. Set it up once and this app can find it automatically.") .font(.subheadline) .foregroundColor(.gray) SetupStepRow(number: 1, title: "Download the server") { - Text("On your Windows PC, download the latest installer from GitHub.") + Text("On your PC (Windows or Linux), download the latest release from GitHub.") Link(destination: ServerDownload.releasesURL) { HStack(spacing: 4) { Image(systemName: "link") @@ -47,7 +46,7 @@ struct ServerSetupGuideView: View { } SetupStepRow(number: 2, title: "Install and run it") { - Text("Run the installer, then start the server. If Windows Firewall asks, click Allow so the server can accept connections on private networks.") + Text("Install the server as its README describes, then start it. On Windows, if Windows Firewall asks, click Allow so the server can accept connections on private networks.") } SetupStepRow(number: 3, title: "Find the address") { @@ -85,7 +84,7 @@ struct ServerSetupGuideView: View { } .padding(.top, 4) - Text("App \(Bundle.main.appVersion) · Server protocol v\(ServerDownload.supportedProtocolVersion)") + Text("App \(Bundle.main.appVersion) · Server protocol v\(WireProtocol.version)") .font(.caption2) .foregroundColor(.gray.opacity(0.5)) .frame(maxWidth: .infinity, alignment: .center) diff --git a/PcVolumeControlTests/MainViewModelSimpleTests.swift b/PcVolumeControlTests/MainViewModelSimpleTests.swift index 1f3d90b..293b4ad 100644 --- a/PcVolumeControlTests/MainViewModelSimpleTests.swift +++ b/PcVolumeControlTests/MainViewModelSimpleTests.swift @@ -326,7 +326,6 @@ final class MainViewModelSimpleTests: XCTestCase { sut.updateDefaultDevice(id: "test-device") sut.updateMaster(id: "master-device", muted: true, vol: 50.0) - sut.updateSession(name: "Test", id: "test.exe", vol: 75.0, muted: false) // If we get here without crashing, the test passes XCTAssertNotNil(sut) From ce3099586de2b7453bdea9b0ddd284af2f5a8641 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 13:29:02 -0800 Subject: [PATCH 18/21] Fix the split-read framing test input The version bump changed only the expected line, not the split chunk feeding it. --- PcVolumeControlTests/LineFramerTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/PcVolumeControlTests/LineFramerTests.swift b/PcVolumeControlTests/LineFramerTests.swift index bd04d22..88be359 100644 --- a/PcVolumeControlTests/LineFramerTests.swift +++ b/PcVolumeControlTests/LineFramerTests.swift @@ -22,7 +22,7 @@ final class LineFramerTests: XCTestCase { func testLineSplitAcrossReads() { var framer = LineFramer() XCTAssertEqual(framer.append(Data(#"{"protocol"#.utf8)), []) - XCTAssertEqual(framer.append(Data(#"Version":7,"#.utf8)), []) + XCTAssertEqual(framer.append(Data(#"Version":8,"#.utf8)), []) XCTAssertEqual(strings(framer.append(Data((#""x":1}"# + "\n{").utf8))), [#"{"protocolVersion":8,"x":1}"#]) XCTAssertEqual(strings(framer.append(Data("}\n".utf8))), ["{}"]) } From a9d26d60c8ee0186e76e47aa976ad589c6868035 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 13:32:26 -0800 Subject: [PATCH 19/21] Make the remaining server copy platform neutral Firewall advice names the port and mDNS instead of Windows Firewall only, step 3 points to the server's Status page, and the README intro no longer says Windows only. --- Localizable.xcstrings | 4 ++-- PcVolumeControl/views/ServerSetupGuideView.swift | 6 +++--- README.md | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Localizable.xcstrings b/Localizable.xcstrings index 323423d..bd8e614 100644 --- a/Localizable.xcstrings +++ b/Localizable.xcstrings @@ -136,7 +136,7 @@ "Leave" : { }, - "Make sure this device and PC are on the same network, the server is allowed through Windows Firewall, and no VPN is active on either device. VPNs often block local discovery." : { + "Make sure this device and PC are on the same network, the PC's firewall allows TCP port 3000 and mDNS (UDP 5353), and no VPN is active on either device. VPNs often block local discovery." : { "comment" : "A description of troubleshooting steps for connecting to the server.", "isCommentAutoGenerated" : true }, @@ -302,7 +302,7 @@ "comment" : "A button that lets a user skip the first-launch welcome tour.", "isCommentAutoGenerated" : true }, - "The server window shows your PC's IP address and port. The default port is 3000." : { + "The server's Status page shows your PC's IP address and port. The default port is 3000." : { "comment" : "A description of how to find the IP address and port of the server.", "isCommentAutoGenerated" : true }, diff --git a/PcVolumeControl/views/ServerSetupGuideView.swift b/PcVolumeControl/views/ServerSetupGuideView.swift index 08f982c..4a48664 100644 --- a/PcVolumeControl/views/ServerSetupGuideView.swift +++ b/PcVolumeControl/views/ServerSetupGuideView.swift @@ -2,7 +2,7 @@ // ServerSetupGuideView.swift // PcVolumeControl // -// Step-by-step guide for installing the Windows companion server. +// Step-by-step guide for installing the companion server. // Designed to work both pushed onto a NavigationStack (intro tour, // Settings) and wrapped in a sheet (connect screen footer). // @@ -50,7 +50,7 @@ struct ServerSetupGuideView: View { } SetupStepRow(number: 3, title: "Find the address") { - Text("The server window shows your PC's IP address and port. The default port is 3000.") + Text("The server's Status page shows your PC's IP address and port. The default port is 3000.") } SetupStepRow(number: 4, title: "Connect from this app") { @@ -62,7 +62,7 @@ struct ServerSetupGuideView: View { .font(.subheadline) .fontWeight(.semibold) .foregroundColor(.white) - Text("Make sure this device and PC are on the same network, the server is allowed through Windows Firewall, and no VPN is active on either device. VPNs often block local discovery.") + Text("Make sure this device and PC are on the same network, the PC's firewall allows TCP port 3000 and mDNS (UDP 5353), and no VPN is active on either device. VPNs often block local discovery.") .font(.footnote) .foregroundColor(.gray) } diff --git a/README.md b/README.md index 3c4a6fb..c502e1a 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ # PC Volume Control — iOS -Control your Windows PC's application audio volumes remotely from your iPhone or iPad. +Control your PC's application audio volumes remotely from your iPhone or iPad. ## What it does -PC Volume Control lets you adjust the volume of individual applications running on your Windows PC from your iOS device. This was designed primarily for remote volume control while gaming or streaming. +PC Volume Control lets you adjust the volume of individual applications running on your PC from your iOS device. This was designed primarily for remote volume control while gaming or streaming. -The app connects to a free companion Windows server over your local network, displaying all running applications and their volume levels in a clean, responsive interface. Adjust volumes, mute/unmute, and switch between output devices (speakers, headphones, etc.) all from your phone or tablet. +The app connects to a free companion server on your PC (Windows or Linux) over your local network, displaying all running applications and their volume levels in a clean, responsive interface. Adjust volumes, mute/unmute, and switch between output devices (speakers, headphones, etc.) all from your phone or tablet. **Features:** - Remote application volume control @@ -59,7 +59,7 @@ PC Volume Control requires the free companion server, [PcVolumeControlServer](ht ### Troubleshooting -- **Can't connect?** Check Windows Firewall isn't blocking the server. +- **Can't connect?** Check that the PC's firewall allows TCP port 3000 and mDNS (UDP 5353); on Windows, that Windows Firewall isn't blocking the server. - **No audio output?** Use the master device selector (top of the volume screen) to switch between multiple audio outputs. ## Contributing From 55b4b278f36eb24b7f503285804f1ee95abedddb Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 16:49:30 -0800 Subject: [PATCH 20/21] Test the reference full state and point docs to the version 8 spec --- CLAUDE.md | 10 ++++++---- PcVolumeControlTests/ServerLineTests.swift | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e82d012..2dcb3c6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -92,8 +92,9 @@ The app speaks protocol version 8 only, a JSON protocol with one message per lin - **Client → Server**: updates for the default device, master volume/mute and session volume/mute, and `iconRequest` for application icons -The canonical spec is the protocol version 8 document of the PcVolumeControlServer repo. -This app does not work with the original C# PcVolumeControlWindows server (version 7). +The canonical spec is `docs/PROTOCOL.md` in the PcVolumeControlServer repo; sample +messages are in `examples/` of the PcVolumeControlProtocol repo. This app does not work +with the original C# PcVolumeControlWindows server (version 7). Paths below are relative to `PcVolumeControl/`. ### Version and ids @@ -105,8 +106,9 @@ Paths below are relative to `PcVolumeControl/`. server (lower number) or the app (higher number) needs updating. - Session ids are opaque. A session update is sent with the current state's `defaultDevice.deviceId`, the device whose sessions the app shows. -- mDNS discovery does not read TXT records; a server of another version shows up in the - list and is rejected with the message above when connecting. +- mDNS discovery does not read TXT records (servers advertise `protocol=8`); a server of + another version shows up in the list and is rejected with the message above when + connecting, which tells the user what to update instead of hiding the server. ### Lines and icons diff --git a/PcVolumeControlTests/ServerLineTests.swift b/PcVolumeControlTests/ServerLineTests.swift index d21e13d..e318d1c 100644 --- a/PcVolumeControlTests/ServerLineTests.swift +++ b/PcVolumeControlTests/ServerLineTests.swift @@ -22,6 +22,11 @@ final class ServerLineTests: XCTestCase { {"protocolVersion":7,"applicationVersion":"v10","deviceIds":{"dev-a":"Speakers"},"defaultDevice":{"deviceId":"dev-a","name":"Speakers","masterVolume":80.0,"masterMuted":false,"sessions":[{"name":"Chrome","id":"{0.0.0.00000000}.{dev-a}|chrome.exe","volume":35.0,"muted":false}]}} """# + // examples/full-state.json from the protocol repo (the reference mock server), on one line. + static let referenceState = #""" + {"protocolVersion":8,"applicationVersion":"v10","deviceIds":{"0f4090a9-dee2-4563-ba29-0ad6b93d9e22":"Speakers (Mock Audio)","c5a32106-264d-40b2-a2e0-74eda397454c":"Headphones (Mock Audio)","c98e4030-926b-4e62-8c83-1c529574cc51":"Headset (Mock USB Audio)"},"defaultDevice":{"deviceId":"0f4090a9-dee2-4563-ba29-0ad6b93d9e22","name":"Speakers (Mock Audio)","masterVolume":80.0,"masterMuted":false,"sessions":[{"name":"Firefox","id":"mock-9ff8bf89-firefox","volume":100.0,"muted":false,"iconId":"demo1d94c5a"},{"name":"Spotify","id":"mock-9ff8bf89-spotify","volume":65.0,"muted":false,"iconId":"demo1b64cd9"},{"name":"Discord","id":"mock-9ff8bf89-discord","volume":40.0,"muted":false,"iconId":"demo174d94c"},{"name":"Musique été","id":"mock-9ff8bf89-musique","volume":55.0,"muted":false,"iconId":"demo14cd968"},{"name":"Firefox","id":"mock-9ff8bf89-firefox-radio","volume":70.0,"muted":false,"iconId":"demo1d94c5a","detail":"Radio Paradise - Main Mix"},{"name":"Firefox","id":"mock-9ff8bf89-firefox-video","volume":90.0,"muted":false,"iconId":"demo1d94c5a","detail":"Tears of Steel - YouTube"}]}} + """# + // Shape captured from a v8 server (device names shortened): one session without an // icon id yet, and two sessions sharing an id. static let v8State = #""" @@ -58,6 +63,19 @@ final class ServerLineTests: XCTestCase { XCTAssertEqual(state.defaultDevice.sessions[0].volume, 35.0) } + func testReferenceExampleDecodes() throws { + guard case .state(let state) = try classify(Self.referenceState) else { + return XCTFail("Expected a full state") + } + let sessions = state.defaultDevice.sessions + XCTAssertEqual(sessions.count, 6) + // Session ids are opaque: none contains the device id. + XCTAssertFalse(sessions.contains { $0.id.contains(state.defaultDevice.deviceId) }) + XCTAssertEqual(state.iconIds, ["demo1d94c5a", "demo1b64cd9", "demo174d94c", "demo14cd968"]) + XCTAssertEqual(sessions.compactMap(\.detail), ["Radio Paradise - Main Mix", "Tears of Steel - YouTube"]) + XCTAssertEqual(sessions[3].name, "Musique \u{E9}t\u{E9}") + } + func testStateDecodesIconIds() throws { guard case .state(let state) = try classify(Self.v8State) else { return XCTFail("Expected a full state") From 2dbcbd813f86eb502058043de89e51fbfb8042a1 Mon Sep 17 00:00:00 2001 From: adam Date: Sun, 15 Nov 2026 16:50:17 -0800 Subject: [PATCH 21/21] Test the version mismatch flow in the view model ServersRepository takes a transport factory so tests can drive MainViewModel with a scripted transport: an older or newer server is left with the right message and no reconnect. --- PcVolumeControl/repos/ServersRepository.swift | 5 +- .../ProtocolVersionMismatchFlowTests.swift | 87 +++++++++++++++++++ 2 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 PcVolumeControlTests/ProtocolVersionMismatchFlowTests.swift diff --git a/PcVolumeControl/repos/ServersRepository.swift b/PcVolumeControl/repos/ServersRepository.swift index 30e7215..0e30aec 100644 --- a/PcVolumeControl/repos/ServersRepository.swift +++ b/PcVolumeControl/repos/ServersRepository.swift @@ -3,11 +3,12 @@ import Network struct ServersRepository { let local: ServersLocalDataSourceProtocol let remote: TCPConnectionDataSourceProtocol + // Tests substitute a scripted transport to drive the view model without a socket. + var makeTransport: (Connection) -> VolumeTransportDataSourceProtocol = { VolumeTransportDataSource(connection: $0) } func connect(to server: DiscoveredServer) async throws -> VolumeControlRepository { let connection = try await remote.openConnection(to: server) - let transport = VolumeTransportDataSource(connection: connection) - return VolumeControlRepository(transport: transport) + return VolumeControlRepository(transport: makeTransport(connection)) } func recent() -> [DiscoveredServer] { local.loadRecent() } diff --git a/PcVolumeControlTests/ProtocolVersionMismatchFlowTests.swift b/PcVolumeControlTests/ProtocolVersionMismatchFlowTests.swift new file mode 100644 index 0000000..b1ee4f9 --- /dev/null +++ b/PcVolumeControlTests/ProtocolVersionMismatchFlowTests.swift @@ -0,0 +1,87 @@ +// +// ProtocolVersionMismatchFlowTests.swift +// PcVolumeControlTests +// +// Connecting to a server of another protocol version: the view model leaves it, +// shows a message and does not try to reconnect. +// + +import Combine +import Network +import XCTest +@testable import PcVolumeControl + +@MainActor +final class ProtocolVersionMismatchFlowTests: XCTestCase { + + private func makeViewModel(serverLines: [String]) -> MainViewModel { + let serversRepo = ServersRepository( + local: MockLocalDataSource(), + remote: UnstartedConnectionDataSource(), + makeTransport: { _ in ScriptedTransport(lines: serverLines) } + ) + let placeholder = VolumeControlRepository(transport: MockVolumeTransport()) + let viewModel = MainViewModel( + connect: ConnectToServerUseCase(repo: serversRepo), + defUpdate: SendDefaultDeviceUpdateUseCase(repo: placeholder), + masterUpdate: SendMasterChannelUpdateUseCase(repo: placeholder), + sessionUpdate: SendSessionUpdateUseCase(repo: placeholder), + serversRepo: serversRepo + ) + // Short enough that a reconnect, if one were started, would show within the test. + viewModel.reconnectInitialDelaySeconds = 0.01 + viewModel.reconnectMaxDelaySeconds = 0.01 + viewModel.reconnectWindowSeconds = 0.2 + return viewModel + } + + private func connectAndWaitForError(_ sut: MainViewModel) async throws -> [MainViewModel.ConnectionStatus] { + var statuses: [MainViewModel.ConnectionStatus] = [] + let statusSubscription = sut.$connectionStatus.sink { statuses.append($0) } + let errorShown = expectation(description: "Error shown") + errorShown.assertForOverFulfill = false + let errorSubscription = sut.$error.sink { if $0 != nil { errorShown.fulfill() } } + + sut.connectToServer(address: "192.0.2.1", port: 3000) + await fulfillment(of: [errorShown], timeout: 5) + // Leave time for a reconnect attempt to begin if the view model started one. + try await Task.sleep(nanoseconds: 300_000_000) + + statusSubscription.cancel() + errorSubscription.cancel() + return statuses + } + + func testOlderServerIsLeftWithAMessageAndNoReconnect() async throws { + let sut = makeViewModel(serverLines: [ServerLineTests.olderServerState]) + + let statuses = try await connectAndWaitForError(sut) + + XCTAssertEqual(sut.error, ProtocolVersionMismatch(serverVersion: 7).localizedDescription) + XCTAssertTrue(sut.error?.contains("PcVolumeControlServer") ?? false) + XCTAssertNil(sut.fullState) + XCTAssertFalse(sut.hasActiveConnection) + XCTAssertFalse(statuses.contains(.reconnecting)) + XCTAssertEqual(sut.connectionStatus, .connected) + } + + func testNewerServerAsksToUpdateTheApp() async throws { + let newer = ServerLineTests.plainState.replacingOccurrences( + of: #""protocolVersion":8"#, with: #""protocolVersion":9"# + ) + let sut = makeViewModel(serverLines: [newer]) + + let statuses = try await connectAndWaitForError(sut) + + XCTAssertEqual(sut.error, ProtocolVersionMismatch(serverVersion: 9).localizedDescription) + XCTAssertNil(sut.fullState) + XCTAssertFalse(statuses.contains(.reconnecting)) + } +} + +/// Hands out a connection that is never started; the scripted transport replaces it. +final class UnstartedConnectionDataSource: TCPConnectionDataSourceProtocol { + func openConnection(to server: DiscoveredServer) async throws -> Connection { + Connection(nw: NWConnection(host: "192.0.2.1", port: 3000, using: .tcp)) + } +}