style: swiftformat sweep

This commit is contained in:
Peter Steinberger
2026-01-08 02:36:29 +00:00
parent 7f0f82e869
commit 1e1293cc0a
44 changed files with 85 additions and 89 deletions

View File

@@ -13,7 +13,7 @@ public struct WakeWordSegment: Sendable, Equatable {
self.range = range
}
public var end: TimeInterval { self.start + self.duration }
public var end: TimeInterval { start + duration }
}
public struct WakeWordGateConfig: Sendable, Equatable {
@@ -62,10 +62,10 @@ public enum WakeWordGate {
segments: [WakeWordSegment],
config: WakeWordGateConfig)
-> WakeWordGateMatch? {
let triggerTokens = self.normalizeTriggers(config.triggers)
let triggerTokens = normalizeTriggers(config.triggers)
guard !triggerTokens.isEmpty else { return nil }
let tokens = self.normalizeSegments(segments)
let tokens = normalizeSegments(segments)
guard !tokens.isEmpty else { return nil }
var best: (index: Int, triggerEnd: TimeInterval, gap: TimeInterval)?
@@ -89,7 +89,7 @@ public enum WakeWordGate {
}
guard let best else { return nil }
let command = self.commandText(transcript: transcript, segments: segments, triggerEndTime: best.triggerEnd)
let command = commandText(transcript: transcript, segments: segments, triggerEndTime: best.triggerEnd)
.trimmingCharacters(in: Self.whitespaceAndPunctuation)
guard command.count >= config.minCommandLength else { return nil }
return WakeWordGateMatch(triggerEndTime: best.triggerEnd, postGap: best.gap, command: command)
@@ -111,7 +111,7 @@ public enum WakeWordGate {
}
let text = segments
.filter { $0.start >= threshold && !self.normalizeToken($0.text).isEmpty }
.filter { $0.start >= threshold && !normalizeToken($0.text).isEmpty }
.map(\.text)
.joined(separator: " ")
return text.trimmingCharacters(in: Self.whitespaceAndPunctuation)
@@ -121,7 +121,7 @@ public enum WakeWordGate {
guard !text.isEmpty else { return false }
let normalized = text.lowercased()
for trigger in triggers {
let token = trigger.trimmingCharacters(in: self.whitespaceAndPunctuation).lowercased()
let token = trigger.trimmingCharacters(in: whitespaceAndPunctuation).lowercased()
if token.isEmpty { continue }
if normalized.contains(token) { return true }
}
@@ -131,11 +131,11 @@ public enum WakeWordGate {
public static func stripWake(text: String, triggers: [String]) -> String {
var out = text
for trigger in triggers {
let token = trigger.trimmingCharacters(in: self.whitespaceAndPunctuation)
let token = trigger.trimmingCharacters(in: whitespaceAndPunctuation)
guard !token.isEmpty else { continue }
out = out.replacingOccurrences(of: token, with: "", options: [.caseInsensitive])
}
return out.trimmingCharacters(in: self.whitespaceAndPunctuation)
return out.trimmingCharacters(in: whitespaceAndPunctuation)
}
private static func normalizeTriggers(_ triggers: [String]) -> [TriggerTokens] {
@@ -143,7 +143,7 @@ public enum WakeWordGate {
for trigger in triggers {
let tokens = trigger
.split(whereSeparator: { $0.isWhitespace })
.map { self.normalizeToken(String($0)) }
.map { normalizeToken(String($0)) }
.filter { !$0.isEmpty }
if tokens.isEmpty { continue }
output.append(TriggerTokens(tokens: tokens))
@@ -153,7 +153,7 @@ public enum WakeWordGate {
private static func normalizeSegments(_ segments: [WakeWordSegment]) -> [Token] {
segments.compactMap { segment in
let normalized = self.normalizeToken(segment.text)
let normalized = normalizeToken(segment.text)
guard !normalized.isEmpty else { return nil }
return Token(
normalized: normalized,
@@ -166,7 +166,7 @@ public enum WakeWordGate {
private static func normalizeToken(_ token: String) -> String {
token
.trimmingCharacters(in: self.whitespaceAndPunctuation)
.trimmingCharacters(in: whitespaceAndPunctuation)
.lowercased()
}

View File

@@ -1,6 +1,6 @@
import Foundation
import Testing
import SwabbleKit
import Testing
@Suite struct WakeWordGateTests {
@Test func matchRequiresGapAfterTrigger() {

View File

@@ -5,7 +5,8 @@ import Testing
@Test func errorDescriptionsAreStable() {
#expect(CameraController.CameraError.cameraUnavailable.errorDescription == "Camera unavailable")
#expect(CameraController.CameraError.microphoneUnavailable.errorDescription == "Microphone unavailable")
#expect(CameraController.CameraError.permissionDenied(kind: "Camera").errorDescription == "Camera permission denied")
#expect(CameraController.CameraError.permissionDenied(kind: "Camera")
.errorDescription == "Camera permission denied")
#expect(CameraController.CameraError.invalidParams("bad").errorDescription == "bad")
#expect(CameraController.CameraError.captureFailed("nope").errorDescription == "nope")
#expect(CameraController.CameraError.exportFailed("export").errorDescription == "export")

View File

@@ -20,4 +20,3 @@ import Testing
#expect(triggers == nil)
}
}

View File

@@ -1,6 +1,6 @@
import Foundation
import Testing
import SwabbleKit
import Testing
@testable import Clawdbot
@Suite struct VoiceWakeManagerExtractCommandTests {

View File

@@ -1,6 +1,6 @@
import Foundation
import Testing
import SwabbleKit
import Testing
@testable import Clawdbot
@Suite(.serialized) struct VoiceWakeManagerStateTests {

View File

@@ -55,8 +55,8 @@ final class RemotePortTunnel {
let sshHost = parsed.host.trimmingCharacters(in: .whitespacesAndNewlines)
let remotePortOverride =
allowRemoteUrlOverride && remotePort == GatewayEnvironment.gatewayPort()
? Self.resolveRemotePortOverride(for: sshHost)
: nil
? Self.resolveRemotePortOverride(for: sshHost)
: nil
let resolvedRemotePort = remotePortOverride ?? remotePort
if let override = remotePortOverride {
Self.logger.info(

View File

@@ -1,6 +1,6 @@
import ClawdbotProtocol
import Foundation
import Testing
import ClawdbotProtocol
@testable import Clawdbot
@Suite

View File

@@ -29,4 +29,3 @@ struct AnthropicOAuthCodeStateTests {
#expect(parsed == .init(code: "abcDEF1234", state: "stateXYZ9876"))
}
}

View File

@@ -19,4 +19,3 @@ import Testing
#expect(high.quality == 1.0)
}
}

View File

@@ -59,4 +59,3 @@ import Testing
}
}
}

View File

@@ -8,7 +8,8 @@ import Testing
@MainActor
struct CanvasWindowSmokeTests {
@Test func panelControllerShowsAndHides() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("clawdbot-canvas-test-\(UUID().uuidString)")
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("clawdbot-canvas-test-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
@@ -30,7 +31,8 @@ struct CanvasWindowSmokeTests {
}
@Test func windowControllerShowsAndCloses() async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("clawdbot-canvas-test-\(UUID().uuidString)")
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("clawdbot-canvas-test-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }

View File

@@ -10,8 +10,7 @@ struct ConfigStoreTests {
await ConfigStore._testSetOverrides(.init(
isRemoteMode: { true },
loadLocal: { localHit = true; return ["local": true] },
loadRemote: { remoteHit = true; return ["remote": true] }
))
loadRemote: { remoteHit = true; return ["remote": true] }))
let result = await ConfigStore.load()
@@ -27,8 +26,7 @@ struct ConfigStoreTests {
await ConfigStore._testSetOverrides(.init(
isRemoteMode: { false },
loadLocal: { localHit = true; return ["local": true] },
loadRemote: { remoteHit = true; return ["remote": true] }
))
loadRemote: { remoteHit = true; return ["remote": true] }))
let result = await ConfigStore.load()
@@ -44,8 +42,7 @@ struct ConfigStoreTests {
await ConfigStore._testSetOverrides(.init(
isRemoteMode: { true },
saveLocal: { _ in localHit = true },
saveRemote: { _ in remoteHit = true }
))
saveRemote: { _ in remoteHit = true }))
try await ConfigStore.save(["remote": true])
@@ -60,8 +57,7 @@ struct ConfigStoreTests {
await ConfigStore._testSetOverrides(.init(
isRemoteMode: { false },
saveLocal: { _ in localHit = true },
saveRemote: { _ in remoteHit = true }
))
saveRemote: { _ in remoteHit = true }))
try await ConfigStore.save(["local": true])

View File

@@ -12,7 +12,7 @@ struct CronModelsTests {
}
@Test func scheduleEveryEncodesAndDecodesWithAnchor() throws {
let schedule = CronSchedule.every(everyMs: 5_000, anchorMs: 10_000)
let schedule = CronSchedule.every(everyMs: 5000, anchorMs: 10000)
let data = try JSONEncoder().encode(schedule)
let decoded = try JSONDecoder().decode(CronSchedule.self, from: data)
#expect(decoded == schedule)

View File

@@ -5,8 +5,10 @@ import Testing
struct DeviceModelCatalogTests {
@Test
func symbolPrefersModelIdentifierPrefixes() {
#expect(DeviceModelCatalog.symbol(deviceFamily: "iPad", modelIdentifier: "iPad16,6", friendlyName: nil) == "ipad")
#expect(DeviceModelCatalog.symbol(deviceFamily: "iPhone", modelIdentifier: "iPhone17,3", friendlyName: nil) == "iphone")
#expect(DeviceModelCatalog
.symbol(deviceFamily: "iPad", modelIdentifier: "iPad16,6", friendlyName: nil) == "ipad")
#expect(DeviceModelCatalog
.symbol(deviceFamily: "iPhone", modelIdentifier: "iPhone17,3", friendlyName: nil) == "iphone")
}
@Test

View File

@@ -21,4 +21,3 @@ import Testing
#expect(GatewayAgentChannel(raw: "unknown") == .last)
}
}

View File

@@ -29,4 +29,3 @@ struct GatewayAutostartPolicyTests {
attachExistingOnly: false))
}
}

View File

@@ -70,7 +70,7 @@ struct GatewayDiscoveryModelTests {
"tailnetDns": " peters-mac-studio-1.ts.net ",
"sshPort": " 2222 ",
"gatewayPort": " 18799 ",
"cliPath": " /opt/clawdbot "
"cliPath": " /opt/clawdbot ",
])
#expect(parsed.lanHost == "studio.local")
#expect(parsed.tailnetDns == "peters-mac-studio-1.ts.net")
@@ -84,7 +84,7 @@ struct GatewayDiscoveryModelTests {
"lanHost": " ",
"tailnetDns": "\n",
"gatewayPort": "nope",
"sshPort": "nope"
"sshPort": "nope",
])
#expect(parsed.lanHost == nil)
#expect(parsed.tailnetDns == nil)

View File

@@ -1,7 +1,7 @@
import AppKit
import ClawdbotProtocol
import Foundation
import Testing
import ClawdbotProtocol
@testable import Clawdbot
@@ -98,17 +98,17 @@ struct LowCoverageHelperTests {
[
"CLAWDBOT_GATEWAY_BIND": "Lan",
"CLAWDBOT_GATEWAY_TOKEN": " secret ",
])
{
#expect(GatewayLaunchAgentManager._testPreferredGatewayBind() == "lan")
#expect(GatewayLaunchAgentManager._testPreferredGatewayToken() == "secret")
#expect(
GatewayLaunchAgentManager._testEscapePlistValue("a&b<c>\"'") ==
"a&amp;b&lt;c&gt;&quot;&apos;")
]) {
#expect(GatewayLaunchAgentManager._testPreferredGatewayBind() == "lan")
#expect(GatewayLaunchAgentManager._testPreferredGatewayToken() == "secret")
#expect(
GatewayLaunchAgentManager._testEscapePlistValue("a&b<c>\"'") ==
"a&amp;b&lt;c&gt;&quot;&apos;")
#expect(GatewayLaunchAgentManager._testGatewayExecutablePath(bundlePath: "/App") == "/App/Contents/Resources/Relay/clawdbot")
#expect(GatewayLaunchAgentManager._testRelayDir(bundlePath: "/App") == "/App/Contents/Resources/Relay")
}
#expect(GatewayLaunchAgentManager
._testGatewayExecutablePath(bundlePath: "/App") == "/App/Contents/Resources/Relay/clawdbot")
#expect(GatewayLaunchAgentManager._testRelayDir(bundlePath: "/App") == "/App/Contents/Resources/Relay")
}
}
@Test func portGuardianParsesListenersAndBuildsReports() {

View File

@@ -1,7 +1,7 @@
import AppKit
import ClawdbotProtocol
import SwiftUI
import Testing
import ClawdbotProtocol
@testable import Clawdbot

View File

@@ -138,7 +138,7 @@ private func waitForListenerReady(_ listener: NWListener, timeoutSeconds: Double
switch state {
case .ready:
finish(.success(()))
case .failed(let err):
case let .failed(err):
finish(.failure(err))
case .cancelled:
finish(.failure(ListenerTimeoutError()))

View File

@@ -15,7 +15,7 @@ struct MacNodeRuntimeTests {
@Test func handleInvokeRejectsEmptySystemRun() async throws {
let runtime = MacNodeRuntime()
let params = ClawdbotSystemRunParams(command: [])
let json = String(data: try JSONEncoder().encode(params), encoding: .utf8)
let json = try String(data: JSONEncoder().encode(params), encoding: .utf8)
let response = await runtime.handleInvoke(
BridgeInvokeRequest(id: "req-2", command: ClawdbotSystemCommand.run.rawValue, paramsJSON: json))
#expect(response.ok == false)
@@ -24,7 +24,7 @@ struct MacNodeRuntimeTests {
@Test func handleInvokeRejectsEmptyNotification() async throws {
let runtime = MacNodeRuntime()
let params = ClawdbotSystemNotifyParams(title: "", body: "")
let json = String(data: try JSONEncoder().encode(params), encoding: .utf8)
let json = try String(data: JSONEncoder().encode(params), encoding: .utf8)
let response = await runtime.handleInvoke(
BridgeInvokeRequest(id: "req-3", command: ClawdbotSystemCommand.notify.rawValue, paramsJSON: json))
#expect(response.ok == false)
@@ -71,7 +71,7 @@ struct MacNodeRuntimeTests {
let runtime = MacNodeRuntime(makeMainActorServices: { services })
let params = MacNodeScreenRecordParams(durationMs: 250)
let json = String(data: try JSONEncoder().encode(params), encoding: .utf8)
let json = try String(data: JSONEncoder().encode(params), encoding: .utf8)
let response = await runtime.handleInvoke(
BridgeInvokeRequest(id: "req-5", command: MacNodeScreenCommand.record.rawValue, paramsJSON: json))
#expect(response.ok == true)

View File

@@ -51,4 +51,3 @@ struct ModelCatalogLoaderTests {
#expect(choices.isEmpty)
}
}

View File

@@ -43,4 +43,3 @@ import Testing
#expect(!bins.contains(missingNodeBin.path))
}
}

View File

@@ -9,6 +9,6 @@ import Testing
}
@Test func policyUsesSlowSafetyInterval() {
#expect(NodePairingReconcilePolicy.activeIntervalMs >= 10_000)
#expect(NodePairingReconcilePolicy.activeIntervalMs >= 10000)
}
}

View File

@@ -1,6 +1,6 @@
import ClawdbotProtocol
import SwiftUI
import Testing
import ClawdbotProtocol
@testable import Clawdbot
@Suite(.serialized)

View File

@@ -1,6 +1,6 @@
import Testing
import ClawdbotIPC
import CoreLocation
import Testing
@testable import Clawdbot
@Suite(.serialized)

View File

@@ -19,4 +19,3 @@ struct ScreenshotSizeTests {
#expect(ScreenshotSize.readPNGSize(data: Data("nope".utf8)) == nil)
}
}

View File

@@ -14,7 +14,7 @@ struct SessionDataTests {
@Test func sessionTokenStatsFormatKTokensRoundsAsExpected() {
#expect(SessionTokenStats.formatKTokens(999) == "999")
#expect(SessionTokenStats.formatKTokens(1000) == "1.0k")
#expect(SessionTokenStats.formatKTokens(12_340) == "12k")
#expect(SessionTokenStats.formatKTokens(12340) == "12k")
}
@Test func sessionTokenStatsPercentUsedClampsTo100() {

View File

@@ -1,5 +1,5 @@
import Testing
import ClawdbotProtocol
import Testing
@testable import Clawdbot
@Suite(.serialized)

View File

@@ -84,13 +84,13 @@ private func makeWav16Mono(sampleRate: UInt32, samples: Int) -> Data {
return data
}
private extension Data {
mutating func appendLEUInt16(_ value: UInt16) {
extension Data {
fileprivate mutating func appendLEUInt16(_ value: UInt16) {
var v = value.littleEndian
Swift.withUnsafeBytes(of: &v) { append(contentsOf: $0) }
}
mutating func appendLEUInt32(_ value: UInt32) {
fileprivate mutating func appendLEUInt32(_ value: UInt32) {
var v = value.littleEndian
Swift.withUnsafeBytes(of: &v) { append(contentsOf: $0) }
}

View File

@@ -98,14 +98,14 @@ enum TestIsolation {
_ values: [String: String?],
_ body: () async throws -> T) async rethrows -> T
{
try await Self.withIsolatedState(env: values, defaults: [:], body)
try await self.withIsolatedState(env: values, defaults: [:], body)
}
static func withUserDefaultsValues<T>(
_ values: [String: Any?],
_ body: () async throws -> T) async rethrows -> T
{
try await Self.withIsolatedState(env: [:], defaults: values, body)
try await self.withIsolatedState(env: [:], defaults: values, body)
}
nonisolated static func tempConfigPath() -> String {

View File

@@ -26,4 +26,3 @@ struct VoiceWakeOverlayViewSmokeTests {
_ = view.body
}
}

View File

@@ -1,6 +1,6 @@
import Foundation
import Testing
import SwabbleKit
import Testing
@testable import Clawdbot
@Suite struct VoiceWakeRuntimeTests {

View File

@@ -1,6 +1,6 @@
import Foundation
import Testing
import SwabbleKit
import Testing
struct VoiceWakeTesterTests {
@Test func matchRespectsGapRequirement() {

View File

@@ -1,6 +1,6 @@
import ClawdbotProtocol
import Foundation
import Testing
import ClawdbotProtocol
@testable import Clawdbot
@Suite

View File

@@ -1,5 +1,5 @@
@testable import ClawdbotChatUI
import Testing
@testable import ClawdbotChatUI
@Suite struct AssistantTextParserTests {
@Test func splitsThinkAndFinalSegments() {

View File

@@ -24,4 +24,3 @@ import Testing
#expect(BonjourEscapes.decode("Hello\\065World") == "HelloAWorld")
}
}

View File

@@ -40,4 +40,3 @@ import Testing
}
}
}

View File

@@ -13,4 +13,3 @@ import Testing
#expect(decoded.format == .jpeg)
}
}

View File

@@ -1,6 +1,6 @@
@testable import ClawdbotChatUI
import Foundation
import Testing
@testable import ClawdbotChatUI
#if os(macOS)
import AppKit

View File

@@ -1,7 +1,7 @@
@testable import ClawdbotChatUI
import ClawdbotKit
import Foundation
import Testing
@testable import ClawdbotChatUI
private struct TimeoutError: Error, CustomStringConvertible {
let label: String
@@ -118,20 +118,20 @@ private final class TestChatTransport: @unchecked Sendable, ClawdbotChatTranspor
}
}
private extension TestChatTransportState {
func setHistoryCallCount(_ v: Int) {
extension TestChatTransportState {
fileprivate func setHistoryCallCount(_ v: Int) {
self.historyCallCount = v
}
func setSessionsCallCount(_ v: Int) {
fileprivate func setSessionsCallCount(_ v: Int) {
self.sessionsCallCount = v
}
func sentRunIdsAppend(_ v: String) {
fileprivate func sentRunIdsAppend(_ v: String) {
self.sentRunIds.append(v)
}
func abortedRunIdsAppend(_ v: String) {
fileprivate func abortedRunIdsAppend(_ v: String) {
self.abortedRunIds.append(v)
}
}
@@ -177,7 +177,9 @@ private extension TestChatTransportState {
ts: Int(Date().timeIntervalSince1970 * 1000),
data: ["text": AnyCodable("streaming…")])))
try await waitUntil("assistant stream visible") { await MainActor.run { vm.streamingAssistantText == "streaming…" } }
try await waitUntil("assistant stream visible") {
await MainActor.run { vm.streamingAssistantText == "streaming…" }
}
transport.emit(
.agent(
@@ -206,7 +208,9 @@ private extension TestChatTransportState {
errorMessage: nil)))
try await waitUntil("pending run clears") { await MainActor.run { vm.pendingRunCount == 0 } }
try await waitUntil("history refresh") { await MainActor.run { vm.messages.contains(where: { $0.role == "assistant" }) } }
try await waitUntil("history refresh") {
await MainActor.run { vm.messages.contains(where: { $0.role == "assistant" }) }
}
#expect(await MainActor.run { vm.streamingAssistantText } == nil)
#expect(await MainActor.run { vm.pendingToolCalls.isEmpty })
}
@@ -247,7 +251,9 @@ private extension TestChatTransportState {
"args": AnyCodable(["x": 1]),
])))
try await waitUntil("streaming active") { await MainActor.run { vm.streamingAssistantText == "external stream" } }
try await waitUntil("streaming active") {
await MainActor.run { vm.streamingAssistantText == "external stream" }
}
try await waitUntil("tool call pending") { await MainActor.run { vm.pendingToolCalls.count == 1 } }
transport.emit(
@@ -436,7 +442,9 @@ private extension TestChatTransportState {
ts: Int(Date().timeIntervalSince1970 * 1000),
data: ["text": AnyCodable("external stream")])))
try await waitUntil("streaming active") { await MainActor.run { vm.streamingAssistantText == "external stream" } }
try await waitUntil("streaming active") {
await MainActor.run { vm.streamingAssistantText == "external stream" }
}
transport.emit(
.chat(

View File

@@ -80,7 +80,8 @@ import UniformTypeIdentifiers
}
let encoded = NSMutableData()
guard let dest = CGImageDestinationCreateWithData(encoded, UTType.jpeg.identifier as CFString, 1, nil) else {
guard let dest = CGImageDestinationCreateWithData(encoded, UTType.jpeg.identifier as CFString, 1, nil)
else {
throw NSError(domain: "JPEGTranscoderTests", code: 9)
}
CGImageDestinationAddImage(dest, img, nil)

View File

@@ -13,4 +13,3 @@ final class TalkPromptBuilderTests: XCTestCase {
XCTAssertTrue(prompt.contains("Assistant speech interrupted at 1.2s."))
}
}