From 03bd9bbf2434f27e465a3067864207dc2fb0835f Mon Sep 17 00:00:00 2001 From: johnwatso Date: Wed, 6 May 2026 11:24:53 +1200 Subject: [PATCH 01/41] Add SwiftMiner integration (client, UI, webhooks) Introduce SwiftMiner support: add a SwiftMiner client service (Services/SwiftMinerClient.swift) and AppModel helpers (AppModel+SwiftMiner.swift) to handle pairing tokens, activation, projections, webhook handling and signature validation. Wire up admin web UI and API: add a webhook endpoint in AdminWebServer, expose a pairing UI in AdvancedPreferencesView, register commands and slash options in CommandProcessor and SlashCommandHelpers, and add a help entry in HelpEngine. Add settings and pairing bundle types to BotSettings, update tests to include the new dependency, and update the Xcode project to include the new sources. Also includes small project metadata changes (CURRENT_PROJECT_VERSION and MARKETING_VERSION). --- SwiftBot.xcodeproj/project.pbxproj | 18 +- SwiftBotApp/AdminWebServer.swift | 9 + SwiftBotApp/AdvancedPreferencesView.swift | 63 +++++ SwiftBotApp/AppModel+AdminWeb.swift | 6 + SwiftBotApp/AppModel+CommandProcessor.swift | 6 + .../AppModel+SlashCommandHelpers.swift | 7 + SwiftBotApp/AppModel+SwiftMiner.swift | 239 ++++++++++++++++++ SwiftBotApp/HelpEngine.swift | 9 + SwiftBotApp/Models/BotSettings.swift | 78 ++++++ SwiftBotApp/Services/CommandProcessor.swift | 11 + SwiftBotApp/Services/SwiftMinerClient.swift | 185 ++++++++++++++ .../SwiftBotTests/CommandProcessorTests.swift | 3 + 12 files changed, 629 insertions(+), 5 deletions(-) create mode 100644 SwiftBotApp/AppModel+SwiftMiner.swift create mode 100644 SwiftBotApp/Services/SwiftMinerClient.swift diff --git a/SwiftBot.xcodeproj/project.pbxproj b/SwiftBot.xcodeproj/project.pbxproj index 25703d25..9ad73ba6 100644 --- a/SwiftBot.xcodeproj/project.pbxproj +++ b/SwiftBot.xcodeproj/project.pbxproj @@ -67,6 +67,7 @@ 6E8FB330BD0BE5ADFCA0FC6B /* MediaThumbnailCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEDACC9B9F1633073834BE07 /* MediaThumbnailCache.swift */; }; 7071FF33C237742C35AB7082 /* AppModel+DiscordParsers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3ABB16BA645CAAD2D3A17C6F /* AppModel+DiscordParsers.swift */; }; 7132DFC658401903B85DC61D /* CertificateManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0D3D1ABFC5B176C108B7B6E /* CertificateManager.swift */; }; + 77A6A8DB1F994205038B1F55 /* AppModel+SwiftMiner.swift in Sources */ = {isa = PBXBuildFile; fileRef = C860E3F668A714ABB7F68FD5 /* AppModel+SwiftMiner.swift */; }; 7894B179A8B556313CC7492A /* AppModel+Gateway.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5716A5F63D0211A0DA067364 /* AppModel+Gateway.swift */; }; 795E1B910968188CC57BA263 /* RemoteControlService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7059780457BD592C5364C934 /* RemoteControlService.swift */; }; 7A065730CD545F87AF004893 /* AdminWebServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AB32D13A6D673323296304C /* AdminWebServer.swift */; }; @@ -115,6 +116,7 @@ DC360305E4A3D50E81B2F576 /* Crypto in Frameworks */ = {isa = PBXBuildFile; productRef = 1840331BC8F2A1886D5014FF /* Crypto */; }; DEEBB36AAE69806B0DE44641 /* RemoteModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24F8451B9C919529C86CD289 /* RemoteModels.swift */; }; DEED6A6AE95EB1E4BD68B09F /* SchemaSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C156C1770937C834073B637 /* SchemaSettings.swift */; }; + EAD5F845E53CE031B3C7D2C7 /* SwiftMinerClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3B2E521D4ABF13B19C9005F /* SwiftMinerClient.swift */; }; EAEDC19B03FED30AC99ECBFB /* SwiftBot.icon in Resources */ = {isa = PBXBuildFile; fileRef = 8964B98159AC25452C4423DF /* SwiftBot.icon */; }; EBF4ED30124502DB72B90F79 /* EmbedFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 726607C6AA014293B0C7794D /* EmbedFormatter.swift */; }; F18225F9C4A1405093180E0D /* AppModel+AI.swift in Sources */ = {isa = PBXBuildFile; fileRef = A275B86FF1816EF5115B7E84 /* AppModel+AI.swift */; }; @@ -138,7 +140,7 @@ 1C5365D3471C752240ADA7D5 /* CloudflareDNSProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudflareDNSProvider.swift; sourceTree = ""; }; 1F3D691AFC6D78460AE015A8 /* DiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticsView.swift; sourceTree = ""; }; 24F8451B9C919529C86CD289 /* RemoteModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteModels.swift; sourceTree = ""; }; - 253ED8DD86B265E94F6ABDE2 /* SparklePublisher */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = text; path = SparklePublisher; sourceTree = BUILT_PRODUCTS_DIR; }; + 253ED8DD86B265E94F6ABDE2 /* SparklePublisher */ = {isa = PBXFileReference; includeInIndex = 0; path = SparklePublisher; sourceTree = BUILT_PRODUCTS_DIR; }; 2C156C1770937C834073B637 /* SchemaSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SchemaSettings.swift; sourceTree = ""; }; 2F319382F183BB1612580B30 /* VoicePresenceStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoicePresenceStore.swift; sourceTree = ""; }; 316BE5EE23ADB08FD4042070 /* IntelService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IntelService.swift; sourceTree = ""; }; @@ -222,9 +224,11 @@ C5794D658F3B4D68836792B7 /* MediaExportCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MediaExportCoordinator.swift; sourceTree = ""; }; C706274351683F9F2B98EFC6 /* DiscordCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiscordCache.swift; sourceTree = ""; }; C7962859CFEF723E67BD800C /* AppModel+Media.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppModel+Media.swift"; sourceTree = ""; }; + C860E3F668A714ABB7F68FD5 /* AppModel+SwiftMiner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppModel+SwiftMiner.swift"; sourceTree = ""; }; C87A43A58BBA036A9646BCAC /* AMDService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AMDService.swift; sourceTree = ""; }; CA5F49E09077B173A9D9C851 /* DiscordAIService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiscordAIService.swift; sourceTree = ""; }; D2627CB6D5226BCFBDB65D61 /* VoiceActionsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceActionsView.swift; sourceTree = ""; }; + D3B2E521D4ABF13B19C9005F /* SwiftMinerClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwiftMinerClient.swift; sourceTree = ""; }; D72EB30017C9118909755079 /* AppModel+BotLifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppModel+BotLifecycle.swift"; sourceTree = ""; }; D7DC12FFA9EC621A265D2A0C /* GatewayModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GatewayModels.swift; sourceTree = ""; }; D9386EDF3092943C62265C4E /* ReleaseNotes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReleaseNotes.swift; sourceTree = ""; }; @@ -285,6 +289,7 @@ C7962859CFEF723E67BD800C /* AppModel+Media.swift */, 7FD42789A025FD409C081463 /* AppModel+Patchy.swift */, 9AA2D2805C055B0DE50F1453 /* AppModel+SlashCommandHelpers.swift */, + C860E3F668A714ABB7F68FD5 /* AppModel+SwiftMiner.swift */, 6E828B8B55D1AEB575FE26E5 /* AppModel+VoicePresence.swift */, B696934C12E6410E1E192294 /* AppModel+WikiBridge.swift */, A55E2CDD13174C72BDB79094 /* AppModelTypes.swift */, @@ -429,6 +434,7 @@ 7059780457BD592C5364C934 /* RemoteControlService.swift */, 24F8451B9C919529C86CD289 /* RemoteModels.swift */, F3A5EEE408384C33E6A68310 /* RuleExecutionService.swift */, + D3B2E521D4ABF13B19C9005F /* SwiftMinerClient.swift */, 2F319382F183BB1612580B30 /* VoicePresenceStore.swift */, 9A22C5009D34D5F98076D3B7 /* VoiceRuleStateStore.swift */, 6D1D661935821791F5D63D2C /* VoiceSessionStore.swift */, @@ -585,6 +591,7 @@ 9AC1DDF0CBE7C89586CB079D /* AppModel+Media.swift in Sources */, 61B7BFCD4B707D6306631F7A /* AppModel+Patchy.swift in Sources */, 7B1416030084F25AC03D0B84 /* AppModel+SlashCommandHelpers.swift in Sources */, + 77A6A8DB1F994205038B1F55 /* AppModel+SwiftMiner.swift in Sources */, 8830FFC6D53A953574FE99AF /* AppModel+VoicePresence.swift in Sources */, 5F948EAA0D02EA068B33BC39 /* AppModel+WikiBridge.swift in Sources */, DC03C1EA8B4FEBC1E2BE90A7 /* AppModel.swift in Sources */, @@ -660,6 +667,7 @@ B6B3280ACF4438511C36A188 /* SwiftBotApp.swift in Sources */, F266903914FB55C141F347D5 /* SwiftMeshSetupView.swift in Sources */, 22701BDB9191BD43BFA13BD7 /* SwiftMeshView.swift in Sources */, + EAD5F845E53CE031B3C7D2C7 /* SwiftMinerClient.swift in Sources */, 13EC6A8C3526F1B617A9C146 /* TunnelManager.swift in Sources */, AC0B6725D3ABBB12498538EF /* UpdateChecker.swift in Sources */, B0787CF87C490A51456F573B /* UpdateItem.swift in Sources */, @@ -696,7 +704,7 @@ AUTOMATION_APPLE_EVENTS = NO; CODE_SIGN_STYLE = Manual; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 198000; + CURRENT_PROJECT_VERSION = 196000; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; ENABLE_HARDENED_RUNTIME = YES; @@ -723,7 +731,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 26.0; - MARKETING_VERSION = 1.9.8; + MARKETING_VERSION = 1.9.6; PRODUCT_BUNDLE_IDENTIFIER = com.example.swiftbot; PRODUCT_NAME = SwiftBot; PROVISIONING_PROFILE_SPECIFIER = ""; @@ -835,7 +843,7 @@ AUTOMATION_APPLE_EVENTS = NO; CODE_SIGN_STYLE = Manual; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 198000; + CURRENT_PROJECT_VERSION = 196000; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; ENABLE_HARDENED_RUNTIME = YES; @@ -862,7 +870,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 26.0; - MARKETING_VERSION = 1.9.8; + MARKETING_VERSION = 1.9.6; PRODUCT_BUNDLE_IDENTIFIER = com.example.swiftbot; PRODUCT_NAME = SwiftBot; PROVISIONING_PROFILE_SPECIFIER = ""; diff --git a/SwiftBotApp/AdminWebServer.swift b/SwiftBotApp/AdminWebServer.swift index adf634cb..b484c776 100644 --- a/SwiftBotApp/AdminWebServer.swift +++ b/SwiftBotApp/AdminWebServer.swift @@ -462,6 +462,7 @@ actor AdminWebServer { private var startBot: (@Sendable () async -> Bool)? private var stopBot: (@Sendable () async -> Bool)? private var refreshSwiftMesh: (@Sendable () async -> Bool)? + private var swiftMinerWebhookHandler: (@Sendable ([String: String], Data) async -> (status: String, body: Data))? private var logger: (@Sendable (String) async -> Void)? private var sessions: [String: Session] = [:] private var pendingStates: [String: PendingState] = [:] @@ -518,6 +519,7 @@ actor AdminWebServer { startBot: @escaping @Sendable () async -> Bool, stopBot: @escaping @Sendable () async -> Bool, refreshSwiftMesh: @escaping @Sendable () async -> Bool, + swiftMinerWebhookHandler: @escaping @Sendable ([String: String], Data) async -> (status: String, body: Data), log: @escaping @Sendable (String) async -> Void ) async -> RuntimeState { self.statusProvider = statusProvider @@ -566,6 +568,7 @@ actor AdminWebServer { self.startBot = startBot self.stopBot = stopBot self.refreshSwiftMesh = refreshSwiftMesh + self.swiftMinerWebhookHandler = swiftMinerWebhookHandler self.logger = log loadPersistedSessions() @@ -876,6 +879,12 @@ actor AdminWebServer { return serveAsset(named: parts[0], ext: parts[1], subdirectories: ["admin/games", "Resources/admin/games"]) case ("GET", "/health"): return jsonResponse(["status": "ok"]) + case ("POST", "/webhooks/swiftminer/events"): + guard let handler = swiftMinerWebhookHandler else { + return jsonResponse(["error": "swiftminer_unavailable"], status: "503 Service Unavailable") + } + let result = await handler(request.headers, request.body) + return httpResponse(status: result.status, body: result.body, contentType: "application/json; charset=utf-8") case ("GET", "/api/remote/status"): guard isRemoteRequestAuthorized(request) else { return unauthorizedResponse() diff --git a/SwiftBotApp/AdvancedPreferencesView.swift b/SwiftBotApp/AdvancedPreferencesView.swift index 9190f143..fe12b44e 100644 --- a/SwiftBotApp/AdvancedPreferencesView.swift +++ b/SwiftBotApp/AdvancedPreferencesView.swift @@ -1,7 +1,11 @@ +import AppKit import SwiftUI struct AdvancedPreferencesView: View { @EnvironmentObject var app: AppModel + @State private var swiftMinerPairingToken = "" + @State private var swiftMinerPairingMessage: String? + @State private var swiftMinerPairingSucceeded = false var body: some View { PreferencesTabContainer { @@ -41,6 +45,65 @@ struct AdvancedPreferencesView: View { .disabled(app.isFailoverManagedNode) .opacity(app.isFailoverManagedNode ? 0.62 : 1) + PreferencesCard("SwiftMiner", systemImage: "shippingbox.circle") { + VStack(alignment: .leading, spacing: 12) { + HStack { + settingsToggleRow("Enable SwiftMiner Integration", isOn: $app.settings.swiftMiner.enabled) + Spacer() + Text(app.settings.swiftMiner.enabled ? "Paired" : "Not Paired") + .font(.caption.weight(.semibold)) + .foregroundStyle(app.settings.swiftMiner.enabled ? .green : .secondary) + } + + VStack(alignment: .leading, spacing: 8) { + Text("Pairing Bundle") + .font(.subheadline.weight(.medium)) + TextField("Paste from SwiftMiner", text: $swiftMinerPairingToken) + .textFieldStyle(.roundedBorder) + } + + HStack { + Button { + let result = app.applySwiftMinerPairingToken(swiftMinerPairingToken) + swiftMinerPairingSucceeded = result.ok + swiftMinerPairingMessage = result.message + if result.ok { + swiftMinerPairingToken = "" + } + } label: { + Label("Pair with SwiftMiner", systemImage: "link") + } + .buttonStyle(.borderedProminent) + + Button { + let token = NSPasteboard.general.string(forType: .string) ?? "" + swiftMinerPairingToken = token + let result = app.applySwiftMinerPairingToken(token) + swiftMinerPairingSucceeded = result.ok + swiftMinerPairingMessage = result.message + if result.ok { + swiftMinerPairingToken = "" + } + } label: { + Label("Paste and Pair", systemImage: "doc.on.clipboard") + } + .buttonStyle(.bordered) + } + + if let swiftMinerPairingMessage { + Text(swiftMinerPairingMessage) + .font(.caption) + .foregroundStyle(swiftMinerPairingSucceeded ? .green : .red) + } + + Text("Copy the pairing bundle from SwiftMiner > Integrations and paste it here.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + .disabled(app.isFailoverManagedNode) + .opacity(app.isFailoverManagedNode ? 0.62 : 1) + if app.settings.devFeaturesEnabled { PreferencesCard("Bug Auto-Fix", systemImage: "sparkles") { VStack(alignment: .leading, spacing: 12) { diff --git a/SwiftBotApp/AppModel+AdminWeb.swift b/SwiftBotApp/AppModel+AdminWeb.swift index cc6d2d14..523a8c69 100644 --- a/SwiftBotApp/AppModel+AdminWeb.swift +++ b/SwiftBotApp/AppModel+AdminWeb.swift @@ -1075,6 +1075,12 @@ extension AppModel { _ = await MainActor.run { model.refreshClusterStatus() } return true }, + swiftMinerWebhookHandler: { [weak self] headers, body in + guard let model = self else { + return ("503 Service Unavailable", Data("{\"error\":\"app_unavailable\"}".utf8)) + } + return await model.handleSwiftMinerWebhook(headers: headers, body: body) + }, log: { [weak self] message in guard let model = self else { return } await MainActor.run { model.logs.append(message) } diff --git a/SwiftBotApp/AppModel+CommandProcessor.swift b/SwiftBotApp/AppModel+CommandProcessor.swift index bfae985b..256067dd 100644 --- a/SwiftBotApp/AppModel+CommandProcessor.swift +++ b/SwiftBotApp/AppModel+CommandProcessor.swift @@ -162,6 +162,12 @@ extension AppModel { userID: userID, channelID: channelID ) + }, + swiftMinerCommand: { [weak self] action, userID, channelID in + guard let self else { + return (ok: false, message: "SwiftMiner integration is unavailable right now.") + } + return await self.swiftMinerCommand(action: action, userId: userID, channelId: channelID) } ) ) diff --git a/SwiftBotApp/AppModel+SlashCommandHelpers.swift b/SwiftBotApp/AppModel+SlashCommandHelpers.swift index 524d694a..2083b705 100644 --- a/SwiftBotApp/AppModel+SlashCommandHelpers.swift +++ b/SwiftBotApp/AppModel+SlashCommandHelpers.swift @@ -32,6 +32,13 @@ extension AppModel { ["type": 3, "name": "title", "description": "Song title", "required": false], ["type": 3, "name": "artist", "description": "Artist name", "required": false] ]], + ["name": "miner", "description": "Check or set up your SwiftMiner drops miner", "type": 1, "options": [ + ["type": 3, "name": "action", "description": "status | setup | health", "required": false, "choices": [ + ["name": "status", "value": "status"], + ["name": "setup", "value": "setup"], + ["name": "health", "value": "health"] + ]] + ]], ["name": "playlist", "description": "Import a playlist URL into a thread with per-track links", "type": 1, "options": [ ["type": 3, "name": "url", "description": "Playlist URL (Spotify/Apple/YouTube)", "required": true], ["type": 3, "name": "name", "description": "Optional thread name", "required": false], diff --git a/SwiftBotApp/AppModel+SwiftMiner.swift b/SwiftBotApp/AppModel+SwiftMiner.swift new file mode 100644 index 00000000..163c2bb3 --- /dev/null +++ b/SwiftBotApp/AppModel+SwiftMiner.swift @@ -0,0 +1,239 @@ +import CryptoKit +import Foundation + +extension AppModel { + func applySwiftMinerPairingToken(_ rawToken: String) -> (ok: Bool, message: String) { + do { + let bundle = try decodeSwiftMinerPairingToken(rawToken) + settings.swiftMiner.apply(pairingBundle: bundle) + return (true, "SwiftMiner pairing bundle applied.") + } catch { + return (false, error.localizedDescription) + } + } + + func decodeSwiftMinerPairingToken(_ rawToken: String) throws -> SwiftMinerPairingBundle { + let trimmed = rawToken.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { throw SwiftMinerPairingError.empty } + + let encodedPayload: String + if trimmed.hasPrefix("swiftminer://pair?") { + guard let components = URLComponents(string: trimmed), + let value = components.queryItems?.first(where: { $0.name == "b" })?.value else { + throw SwiftMinerPairingError.invalidToken + } + encodedPayload = value + } else if trimmed.hasPrefix("{") { + guard let data = trimmed.data(using: .utf8) else { throw SwiftMinerPairingError.invalidToken } + return try decodeSwiftMinerPairingJSON(data) + } else { + encodedPayload = trimmed + } + + guard let data = Data(base64Encoded: encodedPayload) else { + throw SwiftMinerPairingError.invalidBase64 + } + return try decodeSwiftMinerPairingJSON(data) + } + + func swiftMinerCommand(action: String, userId: String, channelId: String) async -> (ok: Bool, message: String) { + let client = SwiftMinerClient(settings: settings.swiftMiner, session: discordRESTSession) + let normalizedAction = action.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + + do { + switch normalizedAction.isEmpty ? "status" : normalizedAction { + case "health": + let ok = try await client.health() + return (ok, ok ? "SwiftMiner API is reachable." : "SwiftMiner health check did not return ok.") + case "setup": + do { + try await client.registerUser(discordUserId: userId) + } catch SwiftMinerClientError.http(let status, let code, _) where status == 409 || code == "user_already_exists" { + // Already registered; continue into activation. + } catch SwiftMinerClientError.http(let status, let code, _) where status == 404 || code == "not_found" { + return ( + false, + "SwiftMiner is reachable, but this SwiftMiner build does not expose user registration yet. Ask the SwiftMiner service to add `POST /v1/users` before Discord setup can finish." + ) + } + + let session = try await client.startActivation(discordUserId: userId) + return ( + true, + """ + Link Twitch for SwiftMiner: + 1. Open \(session.verificationUri) + 2. Enter code `\(session.userCode)` + + This code expires \(relativeTimeText(for: session.expiresAt)). + """ + ) + case "status": + let projection = try await client.projection(discordUserId: userId) + return (true, renderSwiftMinerProjection(projection)) + default: + return (false, "Usage: `/miner action:status`, `/miner action:setup`, or `/miner action:health`.") + } + } catch { + return (false, error.localizedDescription) + } + } + + func handleSwiftMinerWebhook(headers: [String: String], body: Data) async -> (status: String, body: Data) { + guard settings.swiftMiner.enabled else { + return swiftMinerWebhookResponse(status: "404 Not Found", payload: ["error": "swiftminer_disabled"]) + } + guard validateSwiftMinerSignature(headers: headers, body: body) else { + return swiftMinerWebhookResponse(status: "401 Unauthorized", payload: ["error": "invalid_signature"]) + } + guard let event = try? JSONDecoder().decode(SwiftMinerWebhookEvent.self, from: body) else { + return swiftMinerWebhookResponse(status: "400 Bad Request", payload: ["error": "invalid_payload"]) + } + + let client = SwiftMinerClient(settings: settings.swiftMiner, session: discordRESTSession) + let projection: SwiftMinerUserProjection? + do { + projection = try await client.projection(discordUserId: event.subject.discordUserId) + } catch { + projection = nil + } + + let bodyText = renderSwiftMinerWebhookMessage(event: event, projection: projection) + do { + guard ActionDispatcher.canSend(clusterMode: settings.clusterMode, action: "swiftMinerWebhookDM", log: { logs.append($0) }) else { + return swiftMinerWebhookResponse(status: "202 Accepted", payload: ["ok": true, "delivered": false]) + } + try await service.sendDM(userId: event.subject.discordUserId, content: bodyText) + addEvent(ActivityEvent(timestamp: Date(), kind: .command, message: "SwiftMiner event \(event.eventType) delivered")) + return swiftMinerWebhookResponse(status: "200 OK", payload: ["ok": true]) + } catch { + logs.append("SwiftMiner webhook DM failed: \(error.localizedDescription)") + return swiftMinerWebhookResponse(status: "202 Accepted", payload: ["ok": true, "delivered": false]) + } + } + + private func swiftMinerWebhookResponse(status: String, payload: [String: Any]) -> (status: String, body: Data) { + let body = (try? JSONSerialization.data(withJSONObject: payload)) ?? Data("{}".utf8) + return (status, body) + } + + private func renderSwiftMinerWebhookMessage( + event: SwiftMinerWebhookEvent, + projection: SwiftMinerUserProjection? + ) -> String { + let headline: String + switch event.eventType { + case "user.dropClaimed": + headline = "SwiftMiner drop claimed." + case "user.actionRequired": + headline = "SwiftMiner needs your attention." + case "user.opportunityAvailable": + headline = "SwiftMiner found a drops opportunity." + case "user.stateChanged": + headline = "SwiftMiner status changed." + default: + headline = "SwiftMiner updated." + } + + if let projection { + return "\(headline)\n\n\(renderSwiftMinerProjection(projection))" + } + return headline + } + + private func renderSwiftMinerProjection(_ projection: SwiftMinerUserProjection) -> String { + switch projection.state { + case .notConfigured: + return "SwiftMiner is not set up for your Discord account yet. Run `/miner action:setup`." + case .active: + if let campaign = projection.activeCampaign { + return "SwiftMiner is mining \(campaign.game): \(campaign.progress.pct)% (\(campaign.progress.current)/\(campaign.progress.required) \(campaign.progress.unit))." + } + return "SwiftMiner is active." + case .idle: + let account = projection.account.map { " for @\($0.username)" } ?? "" + return "SwiftMiner is idle\(account). No active campaign is being mined right now." + case .blocked: + if let issue = projection.issues.first { + return "SwiftMiner is blocked: \(issue.message)" + } + return "SwiftMiner is blocked and needs attention." + } + } + + private func validateSwiftMinerSignature(headers: [String: String], body: Data) -> Bool { + let secret = settings.swiftMiner.webhookSecret.trimmingCharacters(in: .whitespacesAndNewlines) + guard !secret.isEmpty else { return true } + guard let timestamp = headers["x-swiftminer-timestamp"], + let signature = headers["x-swiftminer-signature"]?.trimmingCharacters(in: .whitespacesAndNewlines), + let timestampValue = TimeInterval(timestamp), + abs(Date().timeIntervalSince1970 - timestampValue) <= 300 else { + return false + } + let signed = Data("\(timestamp).".utf8) + body + let key = SymmetricKey(data: Data(secret.utf8)) + let expected = HMAC.authenticationCode(for: signed, using: key) + .map { String(format: "%02x", $0) } + .joined() + return signature == "v1=\(expected)" + } + + private func relativeTimeText(for date: Date) -> String { + let formatter = RelativeDateTimeFormatter() + formatter.unitsStyle = .full + return formatter.localizedString(for: date, relativeTo: Date()) + } + + private func decodeSwiftMinerPairingJSON(_ data: Data) throws -> SwiftMinerPairingBundle { + let bundle = try JSONDecoder().decode(SwiftMinerPairingBundle.self, from: data) + let endpoint = bundle.swiftMinerEndpoint.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ? bundle.endpoint.trimmingCharacters(in: .whitespacesAndNewlines) + : bundle.swiftMinerEndpoint.trimmingCharacters(in: .whitespacesAndNewlines) + guard !endpoint.isEmpty else { + throw SwiftMinerPairingError.missingEndpoint + } + guard bundle.apiKey.trimmingCharacters(in: .whitespacesAndNewlines).count >= 32 else { + throw SwiftMinerPairingError.missingAPIKey + } + guard bundle.hmacSecret.trimmingCharacters(in: .whitespacesAndNewlines).count >= 32 else { + throw SwiftMinerPairingError.missingSecret + } + return bundle + } +} + +private enum SwiftMinerPairingError: LocalizedError { + case empty + case invalidToken + case invalidBase64 + case missingEndpoint + case missingAPIKey + case missingSecret + + var errorDescription: String? { + switch self { + case .empty: + return "Paste the pairing bundle copied from SwiftMiner." + case .invalidToken: + return "That does not look like a SwiftMiner pairing bundle." + case .invalidBase64: + return "The SwiftMiner pairing payload could not be decoded." + case .missingEndpoint: + return "The pairing bundle is missing the SwiftMiner API endpoint." + case .missingAPIKey: + return "The pairing bundle is missing a valid SwiftMiner API key." + case .missingSecret: + return "The pairing bundle is missing a valid webhook secret." + } + } +} + +private struct SwiftMinerWebhookEvent: Codable { + struct Subject: Codable { + let discordUserId: String + } + + let eventId: String + let eventType: String + let subject: Subject +} diff --git a/SwiftBotApp/HelpEngine.swift b/SwiftBotApp/HelpEngine.swift index 92c592d5..49d8c365 100644 --- a/SwiftBotApp/HelpEngine.swift +++ b/SwiftBotApp/HelpEngine.swift @@ -109,6 +109,15 @@ struct CommandCatalog { category: .fun, isAdminOnly: false ), + CommandEntry( + name: "miner", + aliases: ["swiftminer"], + usage: "\(prefix)miner [status|setup|health]", + description: "Checks or starts setup for your SwiftMiner drops miner.", + examples: ["\(prefix)miner status", "\(prefix)miner setup"], + category: .general, + isAdminOnly: false + ), CommandEntry( name: "userinfo", aliases: [], diff --git a/SwiftBotApp/Models/BotSettings.swift b/SwiftBotApp/Models/BotSettings.swift index 6d981270..6f3d052c 100644 --- a/SwiftBotApp/Models/BotSettings.swift +++ b/SwiftBotApp/Models/BotSettings.swift @@ -315,6 +315,7 @@ struct BotSettings: Codable, Hashable { var behavior = BotBehaviorSettings() var wikiBot = WikiBotSettings() var patchy = PatchySettings() + var swiftMiner = SwiftMinerSettings() var help = HelpSettings() var adminWebUI = AdminWebUISettings() @@ -397,6 +398,7 @@ struct BotSettings: Codable, Hashable { case behavior case wikiBot case patchy + case swiftMiner case help case adminWebUI } @@ -463,6 +465,7 @@ struct BotSettings: Codable, Hashable { behavior = try container.decodeIfPresent(BotBehaviorSettings.self, forKey: .behavior) ?? BotBehaviorSettings() wikiBot = try container.decodeIfPresent(WikiBotSettings.self, forKey: .wikiBot) ?? WikiBotSettings() patchy = try container.decodeIfPresent(PatchySettings.self, forKey: .patchy) ?? PatchySettings() + swiftMiner = try container.decodeIfPresent(SwiftMinerSettings.self, forKey: .swiftMiner) ?? SwiftMinerSettings() help = try container.decodeIfPresent(HelpSettings.self, forKey: .help) ?? HelpSettings() adminWebUI = try container.decodeIfPresent(AdminWebUISettings.self, forKey: .adminWebUI) ?? AdminWebUISettings() remoteMode.normalize() @@ -528,11 +531,86 @@ struct BotSettings: Codable, Hashable { try container.encode(behavior, forKey: .behavior) try container.encode(wikiBot, forKey: .wikiBot) try container.encode(patchy, forKey: .patchy) + try container.encode(swiftMiner, forKey: .swiftMiner) try container.encode(help, forKey: .help) try container.encode(adminWebUI, forKey: .adminWebUI) } } +struct SwiftMinerSettings: Codable, Hashable { + var enabled: Bool = false + var baseURL: String = "http://127.0.0.1:8080" + var apiKey: String = "" + var webhookSecret: String = "" + var webhookHint: String = "" + + var normalizedBaseURL: String { + let trimmed = baseURL.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return "http://127.0.0.1:8080" } + return trimmed.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + } + + mutating func apply(pairingBundle: SwiftMinerPairingBundle) { + enabled = true + let apiEndpoint = pairingBundle.swiftMinerEndpoint.nonEmpty ?? pairingBundle.endpoint.nonEmpty + if let apiEndpoint { + baseURL = apiEndpoint + } + apiKey = pairingBundle.apiKey + webhookSecret = pairingBundle.hmacSecret + webhookHint = pairingBundle.webhookHint + } +} + +struct SwiftMinerPairingBundle: Codable, Hashable { + let version: Int? + let endpoint: String + let swiftMinerEndpoint: String + let swiftBotEndpoint: String + let apiKey: String + let hmacSecret: String + let webhookHint: String + + private enum CodingKeys: String, CodingKey { + case version + case endpoint + case swiftMinerEndpoint + case swiftBotEndpoint + case apiKey + case hmacSecret + case webhookHint + } + + init( + version: Int? = nil, + endpoint: String, + swiftMinerEndpoint: String = "", + swiftBotEndpoint: String = "", + apiKey: String, + hmacSecret: String, + webhookHint: String + ) { + self.version = version + self.endpoint = endpoint + self.swiftMinerEndpoint = swiftMinerEndpoint + self.swiftBotEndpoint = swiftBotEndpoint + self.apiKey = apiKey + self.hmacSecret = hmacSecret + self.webhookHint = webhookHint + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + version = try container.decodeIfPresent(Int.self, forKey: .version) + endpoint = try container.decodeIfPresent(String.self, forKey: .endpoint) ?? "" + swiftMinerEndpoint = try container.decodeIfPresent(String.self, forKey: .swiftMinerEndpoint) ?? "" + swiftBotEndpoint = try container.decodeIfPresent(String.self, forKey: .swiftBotEndpoint) ?? "" + apiKey = try container.decodeIfPresent(String.self, forKey: .apiKey) ?? "" + hmacSecret = try container.decodeIfPresent(String.self, forKey: .hmacSecret) ?? "" + webhookHint = try container.decodeIfPresent(String.self, forKey: .webhookHint) ?? "" + } +} + struct BotBehaviorSettings: Codable, Hashable { var allowDMs: Bool = false var useAIInGuildChannels: Bool = true diff --git a/SwiftBotApp/Services/CommandProcessor.swift b/SwiftBotApp/Services/CommandProcessor.swift index 42022ad1..7064e881 100644 --- a/SwiftBotApp/Services/CommandProcessor.swift +++ b/SwiftBotApp/Services/CommandProcessor.swift @@ -57,6 +57,7 @@ final class CommandProcessor { var lookupFinalsWiki: (String) async -> FinalsWikiLookupResult? var runMusicLookup: (String?, String?, String?, String, String) async -> (ok: Bool, message: String) var pickMusicLookup: (Int, String, String) async -> (ok: Bool, message: String) + var swiftMinerCommand: (String, String, String) async -> (ok: Bool, message: String) } private let dependencies: Dependencies @@ -154,6 +155,11 @@ final class CommandProcessor { context.channelId ) return await dependencies.send(context.channelId, result.message) + case "miner", "swiftminer": + let action = tokens.dropFirst().first ?? "status" + let userId = dependencies.authorId(context.raw) ?? "unknown-user" + let result = await dependencies.swiftMinerCommand(action, userId, context.channelId) + return await dependencies.send(context.channelId, result.message) case "userinfo": return await dependencies.send(context.channelId, "👤 User: \(context.username)") case "cluster", "worker": @@ -350,6 +356,11 @@ final class CommandProcessor { let artist = Self.slashOptionString(named: "artist", in: data) let result = await dependencies.runMusicLookup(query, title, artist, userId, context.channelId) return embed(title: "Music Lookup", description: result.message, color: result.ok ? 3_062_954 : 15_790_767) + case "miner": + let action = Self.slashOptionString(named: "action", in: data) ?? "status" + let userId = dependencies.authorId(context.rawLikeMessage) ?? "unknown-user" + let result = await dependencies.swiftMinerCommand(action, userId, context.channelId) + return embed(title: "SwiftMiner", description: result.message, color: result.ok ? 3_062_954 : 15_790_767) case "wiki": let query = Self.slashOptionString(named: "query", in: data) ?? "" guard config.wikiEnabled else { diff --git a/SwiftBotApp/Services/SwiftMinerClient.swift b/SwiftBotApp/Services/SwiftMinerClient.swift new file mode 100644 index 00000000..679226f4 --- /dev/null +++ b/SwiftBotApp/Services/SwiftMinerClient.swift @@ -0,0 +1,185 @@ +import Foundation + +struct SwiftMinerUserProjection: Codable, Sendable { + enum State: String, Codable, Sendable { + case notConfigured + case active + case idle + case blocked + } + + struct Account: Codable, Sendable { + let twitchAccountId: String + let username: String + } + + struct Campaign: Codable, Sendable { + let campaignId: String + let game: String + let progress: Progress + let endsAt: Date? + } + + struct Progress: Codable, Sendable { + let current: Int + let required: Int + let unit: String + let pct: Int + } + + struct Issue: Codable, Sendable { + let issueId: String + let type: String + let campaignId: String? + let game: String? + let message: String + let action: String + } + + let discordUserId: String + let state: State + let account: Account? + let activeCampaign: Campaign? + let issues: [Issue] +} + +struct SwiftMinerActivationSession: Codable, Sendable { + let sessionId: String + let userCode: String + let verificationUri: String + let expiresAt: Date + let intervalSeconds: Int +} + +struct SwiftMinerActivationStatus: Codable, Sendable { + let sessionId: String + let status: String + let linkedAccountId: String? + let twitchUsername: String? + let failureReason: String? +} + +enum SwiftMinerClientError: LocalizedError { + case disabled + case invalidBaseURL + case missingAPIKey + case http(status: Int, code: String?, message: String?) + + var errorDescription: String? { + switch self { + case .disabled: + return "SwiftMiner integration is disabled." + case .invalidBaseURL: + return "SwiftMiner base URL is invalid." + case .missingAPIKey: + return "SwiftMiner API key is not configured." + case .http(let status, let code, let message): + let detail = message ?? code ?? "Request failed." + return "SwiftMiner returned \(status): \(detail)" + } + } +} + +struct SwiftMinerClient { + private let settings: SwiftMinerSettings + private let session: URLSession + private let decoder: JSONDecoder = { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return decoder + }() + private let encoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + return encoder + }() + + init(settings: SwiftMinerSettings, session: URLSession) { + self.settings = settings + self.session = session + } + + func health() async throws -> Bool { + let data = try await request(path: "/health", method: "GET", requiresAuth: false) + return !data.isEmpty + } + + func registerUser(discordUserId: String) async throws { + struct Body: Encodable { let discordUserId: String } + _ = try await request(path: "/v1/users", method: "POST", body: Body(discordUserId: discordUserId)) + } + + func projection(discordUserId: String) async throws -> SwiftMinerUserProjection { + let data = try await request(path: "/v1/discord/users/\(discordUserId)", method: "GET") + return try decoder.decode(SwiftMinerUserProjection.self, from: data) + } + + func startActivation(discordUserId: String) async throws -> SwiftMinerActivationSession { + let data = try await request(path: "/v1/users/\(discordUserId)/activation", method: "POST") + return try decoder.decode(SwiftMinerActivationSession.self, from: data) + } + + func ignoreCampaign(discordUserId: String, campaignId: String, scope: String) async throws { + struct Body: Encodable { let scope: String } + _ = try await request( + path: "/v1/users/\(discordUserId)/campaigns/\(campaignId)/ignore", + method: "POST", + body: Body(scope: scope) + ) + } + + private func request( + path: String, + method: String, + body: T, + requiresAuth: Bool = true + ) async throws -> Data { + try await request(path: path, method: method, bodyData: try encoder.encode(body), requiresAuth: requiresAuth) + } + + private func request( + path: String, + method: String, + bodyData: Data? = nil, + requiresAuth: Bool = true + ) async throws -> Data { + guard settings.enabled else { throw SwiftMinerClientError.disabled } + guard URL(string: settings.normalizedBaseURL) != nil else { + throw SwiftMinerClientError.invalidBaseURL + } + if requiresAuth, settings.apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + throw SwiftMinerClientError.missingAPIKey + } + + guard let url = URL(string: settings.normalizedBaseURL + "/" + path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))) else { + throw SwiftMinerClientError.invalidBaseURL + } + var request = URLRequest(url: url) + request.httpMethod = method + request.timeoutInterval = 10 + if requiresAuth { + request.setValue("Bot \(settings.apiKey)", forHTTPHeaderField: "Authorization") + } + if let bodyData { + request.httpBody = bodyData + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse else { return data } + guard (200..<300).contains(http.statusCode) else { + let envelope = try? JSONDecoder().decode(SwiftMinerErrorEnvelope.self, from: data) + throw SwiftMinerClientError.http( + status: http.statusCode, + code: envelope?.error, + message: envelope?.message + ) + } + return data + } +} + +private struct SwiftMinerErrorEnvelope: Codable { + let error: String? + let message: String? +} diff --git a/Tests/SwiftBotTests/CommandProcessorTests.swift b/Tests/SwiftBotTests/CommandProcessorTests.swift index 3a28eb09..6ffdebdf 100644 --- a/Tests/SwiftBotTests/CommandProcessorTests.swift +++ b/Tests/SwiftBotTests/CommandProcessorTests.swift @@ -254,6 +254,9 @@ final class CommandProcessorTests: XCTestCase { pickMusicLookup: { selection, userID, channelID in await recorder.recordMusicPick(selection: selection, userId: userID, channelId: channelID) return (true, "Music selection result") + }, + swiftMinerCommand: { _, _, _ in + (true, "SwiftMiner result") } ) ) From 67b2c173c53518ff273f9063108a631f0dcfb640 Mon Sep 17 00:00:00 2001 From: johnwatso Date: Wed, 6 May 2026 18:24:03 +1200 Subject: [PATCH 02/41] Enable SwiftMiner pairing server --- SwiftBot.xcodeproj/project.pbxproj | 4 + SwiftBotApp/AdvancedPreferencesView.swift | 62 --------------- SwiftBotApp/AppModel+SwiftMiner.swift | 4 +- SwiftBotApp/AppModel.swift | 4 + SwiftBotApp/PreferencesView.swift | 10 ++- SwiftBotApp/SwiftMinerPreferencesView.swift | 85 +++++++++++++++++++++ 6 files changed, 104 insertions(+), 65 deletions(-) create mode 100644 SwiftBotApp/SwiftMinerPreferencesView.swift diff --git a/SwiftBot.xcodeproj/project.pbxproj b/SwiftBot.xcodeproj/project.pbxproj index 9ad73ba6..5252c062 100644 --- a/SwiftBot.xcodeproj/project.pbxproj +++ b/SwiftBot.xcodeproj/project.pbxproj @@ -9,6 +9,7 @@ /* Begin PBXBuildFile section */ 0005740627E44E41BFB0B69B /* UpdatesPreferencesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44F9E79347D751050F3DE039 /* UpdatesPreferencesView.swift */; }; 00F2D700D7DA38BA9049A986 /* GeneralPreferencesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3595DECC8AF4632DC5E33E83 /* GeneralPreferencesView.swift */; }; + 01C4B7408B5741A598E3E6AB /* SwiftMinerPreferencesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01C4B7418B5741A598E3E6AB /* SwiftMinerPreferencesView.swift */; }; 085D20923E60B1599D77A36D /* PatchyViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A08A1E26A9A98169FEE2F3B /* PatchyViewModel.swift */; }; 0DE92D9DBC280ACE537C2209 /* DiscordService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38BBDCEDB0E2FC18B5BD01F0 /* DiscordService.swift */; }; 0E6027F2B5CEEDF280B843D4 /* AnalyticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1886F81C765D477A60E46CBD /* AnalyticsView.swift */; }; @@ -148,6 +149,7 @@ 33D0CC3569144419991BD125 /* EmptyRuleOnboardingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmptyRuleOnboardingView.swift; sourceTree = ""; }; 346C818F5054314C6BF97DC5 /* VersionStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VersionStore.swift; sourceTree = ""; }; 3595DECC8AF4632DC5E33E83 /* GeneralPreferencesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneralPreferencesView.swift; sourceTree = ""; }; + 01C4B7418B5741A598E3E6AB /* SwiftMinerPreferencesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwiftMinerPreferencesView.swift; sourceTree = ""; }; 38BBDCEDB0E2FC18B5BD01F0 /* DiscordService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiscordService.swift; sourceTree = ""; }; 3A523236CFC7EE60B9E5F3AC /* PreferencesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PreferencesView.swift; sourceTree = ""; }; 3ABB16BA645CAAD2D3A17C6F /* AppModel+DiscordParsers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppModel+DiscordParsers.swift"; sourceTree = ""; }; @@ -326,6 +328,7 @@ 5083D5348FCB914E6C796E2D /* SwiftBotApp.swift */, 818A90855EE5E88B16695E30 /* SwiftMeshSetupView.swift */, 4BD24A98DC57DF430081B255 /* SwiftMeshView.swift */, + 01C4B7418B5741A598E3E6AB /* SwiftMinerPreferencesView.swift */, 44F9E79347D751050F3DE039 /* UpdatesPreferencesView.swift */, D2627CB6D5226BCFBDB65D61 /* VoiceActionsView.swift */, 56C5EE8341F1833DB1BF48D6 /* VoiceRuleListView.swift */, @@ -668,6 +671,7 @@ F266903914FB55C141F347D5 /* SwiftMeshSetupView.swift in Sources */, 22701BDB9191BD43BFA13BD7 /* SwiftMeshView.swift in Sources */, EAD5F845E53CE031B3C7D2C7 /* SwiftMinerClient.swift in Sources */, + 01C4B7408B5741A598E3E6AB /* SwiftMinerPreferencesView.swift in Sources */, 13EC6A8C3526F1B617A9C146 /* TunnelManager.swift in Sources */, AC0B6725D3ABBB12498538EF /* UpdateChecker.swift in Sources */, B0787CF87C490A51456F573B /* UpdateItem.swift in Sources */, diff --git a/SwiftBotApp/AdvancedPreferencesView.swift b/SwiftBotApp/AdvancedPreferencesView.swift index fe12b44e..c8576a29 100644 --- a/SwiftBotApp/AdvancedPreferencesView.swift +++ b/SwiftBotApp/AdvancedPreferencesView.swift @@ -3,9 +3,6 @@ import SwiftUI struct AdvancedPreferencesView: View { @EnvironmentObject var app: AppModel - @State private var swiftMinerPairingToken = "" - @State private var swiftMinerPairingMessage: String? - @State private var swiftMinerPairingSucceeded = false var body: some View { PreferencesTabContainer { @@ -45,65 +42,6 @@ struct AdvancedPreferencesView: View { .disabled(app.isFailoverManagedNode) .opacity(app.isFailoverManagedNode ? 0.62 : 1) - PreferencesCard("SwiftMiner", systemImage: "shippingbox.circle") { - VStack(alignment: .leading, spacing: 12) { - HStack { - settingsToggleRow("Enable SwiftMiner Integration", isOn: $app.settings.swiftMiner.enabled) - Spacer() - Text(app.settings.swiftMiner.enabled ? "Paired" : "Not Paired") - .font(.caption.weight(.semibold)) - .foregroundStyle(app.settings.swiftMiner.enabled ? .green : .secondary) - } - - VStack(alignment: .leading, spacing: 8) { - Text("Pairing Bundle") - .font(.subheadline.weight(.medium)) - TextField("Paste from SwiftMiner", text: $swiftMinerPairingToken) - .textFieldStyle(.roundedBorder) - } - - HStack { - Button { - let result = app.applySwiftMinerPairingToken(swiftMinerPairingToken) - swiftMinerPairingSucceeded = result.ok - swiftMinerPairingMessage = result.message - if result.ok { - swiftMinerPairingToken = "" - } - } label: { - Label("Pair with SwiftMiner", systemImage: "link") - } - .buttonStyle(.borderedProminent) - - Button { - let token = NSPasteboard.general.string(forType: .string) ?? "" - swiftMinerPairingToken = token - let result = app.applySwiftMinerPairingToken(token) - swiftMinerPairingSucceeded = result.ok - swiftMinerPairingMessage = result.message - if result.ok { - swiftMinerPairingToken = "" - } - } label: { - Label("Paste and Pair", systemImage: "doc.on.clipboard") - } - .buttonStyle(.bordered) - } - - if let swiftMinerPairingMessage { - Text(swiftMinerPairingMessage) - .font(.caption) - .foregroundStyle(swiftMinerPairingSucceeded ? .green : .red) - } - - Text("Copy the pairing bundle from SwiftMiner > Integrations and paste it here.") - .font(.caption) - .foregroundStyle(.secondary) - } - } - .disabled(app.isFailoverManagedNode) - .opacity(app.isFailoverManagedNode ? 0.62 : 1) - if app.settings.devFeaturesEnabled { PreferencesCard("Bug Auto-Fix", systemImage: "sparkles") { VStack(alignment: .leading, spacing: 12) { diff --git a/SwiftBotApp/AppModel+SwiftMiner.swift b/SwiftBotApp/AppModel+SwiftMiner.swift index 163c2bb3..077bc65e 100644 --- a/SwiftBotApp/AppModel+SwiftMiner.swift +++ b/SwiftBotApp/AppModel+SwiftMiner.swift @@ -6,7 +6,9 @@ extension AppModel { do { let bundle = try decodeSwiftMinerPairingToken(rawToken) settings.swiftMiner.apply(pairingBundle: bundle) - return (true, "SwiftMiner pairing bundle applied.") + settings.adminWebUI.enabled = true + saveSettings() + return (true, "SwiftMiner pairing bundle applied. Local webhook server enabled.") } catch { return (false, error.localizedDescription) } diff --git a/SwiftBotApp/AppModel.swift b/SwiftBotApp/AppModel.swift index 7603e777..feddb86d 100644 --- a/SwiftBotApp/AppModel.swift +++ b/SwiftBotApp/AppModel.swift @@ -341,6 +341,10 @@ final class AppModel: ObservableObject { loadedSettings.remoteAccessToken = generatedRemoteAccessToken() migrated = true } + if loadedSettings.swiftMiner.enabled && !loadedSettings.adminWebUI.enabled { + loadedSettings.adminWebUI.enabled = true + migrated = true + } settings = loadedSettings isOnboardingComplete = onboardingCompleted(for: loadedSettings) diff --git a/SwiftBotApp/PreferencesView.swift b/SwiftBotApp/PreferencesView.swift index f52acf06..3d1236f3 100644 --- a/SwiftBotApp/PreferencesView.swift +++ b/SwiftBotApp/PreferencesView.swift @@ -43,17 +43,23 @@ struct PreferencesView: View { } .tag(2) + SwiftMinerPreferencesView() + .tabItem { + Label("Integrations", systemImage: "app.connected.to.app.below.fill") + } + .tag(3) + UpdatesPreferencesView() .tabItem { Label("Updates", systemImage: "arrow.clockwise") } - .tag(3) + .tag(4) AdvancedPreferencesView() .tabItem { Label("Developer", systemImage: "wrench") } - .tag(4) + .tag(5) } .onChange(of: app.createPreferencesSnapshot()) { _, _ in autoSaveTask?.cancel() diff --git a/SwiftBotApp/SwiftMinerPreferencesView.swift b/SwiftBotApp/SwiftMinerPreferencesView.swift new file mode 100644 index 00000000..8ed086f8 --- /dev/null +++ b/SwiftBotApp/SwiftMinerPreferencesView.swift @@ -0,0 +1,85 @@ +import AppKit +import SwiftUI + +struct SwiftMinerPreferencesView: View { + @EnvironmentObject var app: AppModel + @State private var swiftMinerPairingToken = "" + @State private var swiftMinerPairingMessage: String? + @State private var swiftMinerPairingSucceeded = false + + var body: some View { + PreferencesTabContainer { + if app.isFailoverManagedNode { + PreferencesReadOnlyBanner(text: "Read-only on Failover nodes. These settings sync from Primary.") + } + + PreferencesCard("SwiftMiner", systemImage: "shippingbox.circle") { + VStack(alignment: .leading, spacing: 12) { + HStack { + settingsToggleRow("Enable SwiftMiner Integration", isOn: $app.settings.swiftMiner.enabled) + Spacer() + Text(app.settings.swiftMiner.enabled ? "Paired" : "Not Paired") + .font(.caption.weight(.semibold)) + .foregroundStyle(app.settings.swiftMiner.enabled ? .green : .secondary) + } + + VStack(alignment: .leading, spacing: 8) { + Text("Pairing Bundle") + .font(.subheadline.weight(.medium)) + TextField("Paste from SwiftMiner", text: $swiftMinerPairingToken) + .textFieldStyle(.roundedBorder) + } + + HStack { + Button { + let result = app.applySwiftMinerPairingToken(swiftMinerPairingToken) + swiftMinerPairingSucceeded = result.ok + swiftMinerPairingMessage = result.message + if result.ok { + swiftMinerPairingToken = "" + } + } label: { + Label("Pair with SwiftMiner", systemImage: "link") + } + .buttonStyle(.borderedProminent) + + Button { + let token = NSPasteboard.general.string(forType: .string) ?? "" + swiftMinerPairingToken = token + let result = app.applySwiftMinerPairingToken(token) + swiftMinerPairingSucceeded = result.ok + swiftMinerPairingMessage = result.message + if result.ok { + swiftMinerPairingToken = "" + } + } label: { + Label("Paste and Pair", systemImage: "doc.on.clipboard") + } + .buttonStyle(.bordered) + } + + if let swiftMinerPairingMessage { + Text(swiftMinerPairingMessage) + .font(.caption) + .foregroundStyle(swiftMinerPairingSucceeded ? .green : .red) + } + + Text("Copy the pairing bundle from SwiftMiner > Integrations and paste it here.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + .disabled(app.isFailoverManagedNode) + .opacity(app.isFailoverManagedNode ? 0.62 : 1) + } + } + + private func settingsToggleRow(_ title: String, isOn: Binding) -> some View { + HStack(alignment: .center) { + Text(title) + Spacer() + Toggle("", isOn: isOn) + .labelsHidden() + } + } +} From b9c6854bacb6b66f1fd80f318fcd08216b7d1f78 Mon Sep 17 00:00:00 2001 From: johnwatso Date: Wed, 6 May 2026 20:46:28 +1200 Subject: [PATCH 03/41] Polish SwiftBot sidebar --- SwiftBot.xcodeproj/project.pbxproj | 4 +- SwiftBotApp/AnalyticsView.swift | 10 +- SwiftBotApp/RootView.swift | 429 ++++++++++++++++++++--------- 3 files changed, 309 insertions(+), 134 deletions(-) diff --git a/SwiftBot.xcodeproj/project.pbxproj b/SwiftBot.xcodeproj/project.pbxproj index 5252c062..85c52ab0 100644 --- a/SwiftBot.xcodeproj/project.pbxproj +++ b/SwiftBot.xcodeproj/project.pbxproj @@ -718,7 +718,7 @@ ENABLE_RESOURCE_ACCESS_CONTACTS = NO; ENABLE_RESOURCE_ACCESS_LOCATION = NO; ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO; - ENABLE_USER_SCRIPT_SANDBOXING = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = "SwiftBot-Info.plist"; INFOPLIST_KEY_CFBundleDisplayName = SwiftBot; @@ -857,7 +857,7 @@ ENABLE_RESOURCE_ACCESS_CONTACTS = NO; ENABLE_RESOURCE_ACCESS_LOCATION = NO; ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO; - ENABLE_USER_SCRIPT_SANDBOXING = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = "SwiftBot-Info.plist"; INFOPLIST_KEY_CFBundleDisplayName = SwiftBot; diff --git a/SwiftBotApp/AnalyticsView.swift b/SwiftBotApp/AnalyticsView.swift index 3839068a..d5d02525 100644 --- a/SwiftBotApp/AnalyticsView.swift +++ b/SwiftBotApp/AnalyticsView.swift @@ -67,7 +67,7 @@ struct AnalyticsView: View { private var dailyChart: some View { analyticsCard(title: "Voice Activity — Last 7 Days", symbol: "chart.bar.fill") { - if dailyActivity.allSatisfy({ $0.count == 0 }) { + if !dailyActivity.contains(where: { $0.1 > 0 }) { emptyState("No voice sessions recorded yet") } else { Chart(dailyActivity, id: \.date) { item in @@ -79,13 +79,13 @@ struct AnalyticsView: View { .cornerRadius(4) } .chartXAxis { - AxisMarks(values: .stride(by: .day)) { value in + AxisMarks(values: .stride(by: .day)) { _ in AxisGridLine() AxisValueLabel(format: .dateTime.weekday(.abbreviated)) } } .chartYAxis { - AxisMarks { value in + AxisMarks { _ in AxisGridLine() AxisValueLabel() } @@ -99,7 +99,7 @@ struct AnalyticsView: View { private var hourlyChart: some View { analyticsCard(title: "Activity by Hour", symbol: "clock.badge.checkmark") { - if hourlyActivity.allSatisfy({ $0.count == 0 }) { + if !hourlyActivity.contains(where: { $0.1 > 0 }) { emptyState("No data") } else { Chart(hourlyActivity, id: \.hour) { item in @@ -210,7 +210,7 @@ struct AnalyticsView: View { switch hour { case 0: return "12a" case 12: return "12p" - case let h where h < 12: return "\(h)a" + case let hourBeforeNoon where hourBeforeNoon < 12: return "\(hourBeforeNoon)a" default: return "\(hour - 12)p" } } diff --git a/SwiftBotApp/RootView.swift b/SwiftBotApp/RootView.swift index 5910bb72..5ac1aa50 100644 --- a/SwiftBotApp/RootView.swift +++ b/SwiftBotApp/RootView.swift @@ -123,142 +123,131 @@ struct DashboardSidebar: View { @Namespace private var selectionHighlightNamespace var body: some View { - VStack(spacing: 14) { - VStack(spacing: 10) { - Group { - if let avatarURL = app.botAvatarURL { - AsyncImage(url: avatarURL) { phase in - switch phase { - case .empty: - ZStack { - Circle() - .fill(LinearGradient(colors: [.blue, .indigo], startPoint: .topLeading, endPoint: .bottomTrailing)) - .frame(width: 56, height: 56) - ProgressView() - .tint(.white) - } - case .success(let image): - image - .resizable() - .aspectRatio(contentMode: .fill) - .frame(width: 56, height: 56) - .clipShape(Circle()) - case .failure: - ZStack { - Circle() - .fill(LinearGradient(colors: [.blue, .indigo], startPoint: .topLeading, endPoint: .bottomTrailing)) - .frame(width: 56, height: 56) - Image(systemName: "cpu.fill") - .font(.title2) - .foregroundStyle(.white) - } - @unknown default: - ZStack { - Circle() - .fill(LinearGradient(colors: [.blue, .indigo], startPoint: .topLeading, endPoint: .bottomTrailing)) - .frame(width: 56, height: 56) - Image(systemName: "cpu.fill") - .font(.title2) - .foregroundStyle(.white) - } - } - } - } else { - ZStack { - Circle() - .fill(LinearGradient(colors: [.blue, .indigo], startPoint: .topLeading, endPoint: .bottomTrailing)) - .frame(width: 56, height: 56) - Image(systemName: "cpu.fill") - .font(.title2) - .foregroundStyle(.white) - } - } - } + ZStack { + SwiftBotSidebarMaterialBackground() - VStack(spacing: 2) { - Text(app.botUsername) - .font(.headline) - HStack(spacing: 4) { - Circle() - .fill(app.primaryServiceIsOnline ? Color.green : Color.secondary) - .frame(width: 6, height: 6) - .accessibilityHidden(true) - Text(app.primaryServiceStatusText) - .font(.caption) - .foregroundStyle(.secondary) - } - HStack(spacing: 6) { - Image(systemName: clusterIcon) - .font(.caption2) - Text(app.clusterSnapshot.mode.rawValue) - .font(.caption2) - } - .foregroundStyle(.secondary) - } - } - .frame(maxWidth: .infinity) - .padding(.vertical, 16) + VStack(spacing: 12) { + DashboardSidebarHeader( + avatarURL: app.botAvatarURL, + botUsername: app.botUsername, + statusText: app.primaryServiceStatusText, + isOnline: app.primaryServiceIsOnline, + clusterMode: app.clusterSnapshot.mode.rawValue, + clusterIcon: clusterIcon + ) + .padding(.horizontal, 10) + .padding(.top, 44) - ScrollView { - VStack(alignment: .leading, spacing: 16) { - SidebarSection(title: "Dashboard") { - SidebarRow(item: .overview, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace) - } + ScrollView { + VStack(alignment: .leading, spacing: 14) { + SidebarSection(title: "Dashboard") { + SidebarRow( + item: .overview, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace + ) + } - SidebarSection(title: "Automation") { - SidebarRow(item: .commands, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace) - if selection == .commands || selection == .commandLog { + SidebarSection(title: "Automation") { + SidebarRow( + item: .commands, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace + ) + if selection == .commands || selection == .commandLog { + SidebarRow( + item: .commandLog, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace, + isChild: true + ) + } SidebarRow( - item: .commandLog, + item: .voice, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace, - isChild: true + count: app.activeVoice.count + ) + SidebarRow( + item: .patchy, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace + ) + SidebarRow( + item: .wikiBridge, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace ) } - SidebarRow(item: .voice, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace, count: app.activeVoice.count) - SidebarRow(item: .patchy, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace) - SidebarRow(item: .wikiBridge, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace) - } - SidebarSection(title: "System") { - SidebarRow(item: .aiBots, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace) - SidebarRow(item: .analytics, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace) - SidebarRow(item: .diagnostics, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace) - SidebarRow(item: .logs, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace) - } + SidebarSection(title: "System") { + SidebarRow( + item: .aiBots, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace + ) + SidebarRow( + item: .analytics, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace + ) + SidebarRow( + item: .diagnostics, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace + ) + SidebarRow( + item: .logs, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace + ) + } - SidebarSection(title: "Infrastructure") { - SidebarRow(item: .swiftMesh, selection: $selection, selectionHighlightNamespace: selectionHighlightNamespace) + SidebarSection(title: "Infrastructure") { + SidebarRow( + item: .swiftMesh, + selection: $selection, + selectionHighlightNamespace: selectionHighlightNamespace + ) + } } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 8) } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(6) - } - Group { - if !isPrimaryServiceRunning { - Button { - Task { await app.startBot() } - } label: { - Label(startButtonTitle, systemImage: "play.circle.fill") - .frame(maxWidth: .infinity) - } - .buttonStyle(GlassActionButtonStyle()) - } else { - Button { - Task { await app.stopBot() } - } label: { - Label(stopButtonTitle, systemImage: "stop.circle.fill") - .frame(maxWidth: .infinity) + Group { + if !isPrimaryServiceRunning { + Button { + Task { await app.startBot() } + } label: { + Label(startButtonTitle, systemImage: "play.circle.fill") + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + } else { + Button { + Task { await app.stopBot() } + } label: { + Label(stopButtonTitle, systemImage: "stop.circle.fill") + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + .tint(.secondary) } - .buttonStyle(.bordered) - .tint(.secondary) } + .controlSize(.regular) + .padding(.horizontal, 10) + .padding(.bottom, 12) } - .controlSize(.regular) } - .padding(12) - .background(Color.clear) + .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 18, style: .continuous) + .strokeBorder(.white.opacity(0.12), lineWidth: 1) + ) + .padding(.leading, 8) + .padding(.trailing, 4) + .padding(.vertical, 8) } private var isPrimaryServiceRunning: Bool { @@ -299,23 +288,28 @@ struct SidebarRow: View { HStack(spacing: 10) { if isChild { Image(systemName: "arrow.turn.down.right") - .font(.caption.weight(.semibold)) + .font(.system(size: 12, weight: .semibold)) .foregroundStyle(.tertiary) .frame(width: 12) } Image(systemName: item.icon) - .frame(width: 16) + .font(.system(size: 14, weight: .semibold)) + .frame(width: 18) Text(item.rawValue) + .font(.system(size: 14, weight: selection == item ? .semibold : .medium)) + .lineLimit(1) Spacer() if let count, count > 0 { Text("\(count)") - .font(.caption2.bold()) - .padding(.horizontal, 7) + .font(.system(size: 11, weight: .bold, design: .rounded)) + .foregroundStyle(.white) + .padding(.horizontal, 6) .padding(.vertical, 2) - .background(Color.accentColor.opacity(0.20), in: Capsule()) + .background(Color.accentColor, in: Capsule()) } } - .padding(.horizontal, isChild ? 24 : 12) + .foregroundStyle(.primary) + .padding(.horizontal, isChild ? 22 : 12) .padding(.vertical, 9) .background { if selection == item { @@ -359,9 +353,10 @@ struct SidebarSection: View { var body: some View { VStack(alignment: .leading, spacing: 8) { Text(title) - .font(.system(size: 12, weight: .semibold, design: .rounded)) - .foregroundStyle(.tertiary) + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.secondary) .padding(.horizontal, 12) + .textCase(.uppercase) VStack(alignment: .leading, spacing: 4) { content @@ -369,3 +364,183 @@ struct SidebarSection: View { } } } + +private struct DashboardSidebarHeader: View { + let avatarURL: URL? + let botUsername: String + let statusText: String + let isOnline: Bool + let clusterMode: String + let clusterIcon: String + + var body: some View { + VStack(alignment: .leading, spacing: 9) { + HStack(alignment: .center, spacing: 12) { + SidebarAvatarView(avatarURL: avatarURL) + + VStack(alignment: .leading, spacing: 3) { + Text(botUsername) + .font(.system(size: 15, weight: .semibold)) + .lineLimit(1) + + HStack(spacing: 5) { + Circle() + .fill(isOnline ? Color.green : Color.secondary) + .frame(width: 6, height: 6) + .accessibilityHidden(true) + Text("SwiftBot") + } + .font(.caption) + .foregroundStyle(.secondary) + } + + Spacer(minLength: 0) + } + + HStack(spacing: 8) { + SidebarInfoRow( + systemImage: "power.circle.fill", + title: "Status", + value: statusText, + tint: isOnline ? .green : .secondary + ) + SidebarInfoRow( + systemImage: clusterIcon, + title: "Mode", + value: clusterMode, + tint: .secondary + ) + } + } + .padding(10) + .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder(.white.opacity(0.10), lineWidth: 1) + ) + } +} + +private struct SidebarAvatarView: View { + let avatarURL: URL? + + var body: some View { + Group { + if let avatarURL { + AsyncImage(url: avatarURL) { phase in + switch phase { + case .empty: + placeholder(progress: true) + case .success(let image): + image + .resizable() + .aspectRatio(contentMode: .fill) + .frame(width: 40, height: 40) + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) + case .failure: + placeholder() + @unknown default: + placeholder() + } + } + } else { + placeholder() + } + } + .frame(width: 40, height: 40) + .overlay( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .strokeBorder(.white.opacity(0.16), lineWidth: 1) + ) + } + + private func placeholder(progress: Bool = false) -> some View { + ZStack { + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill( + LinearGradient( + colors: [.blue, .indigo], + startPoint: .topLeading, + endPoint: .bottomTrailing + ) + ) + + if progress { + ProgressView() + .controlSize(.small) + .tint(.white) + } else { + Image(systemName: "cpu.fill") + .font(.system(size: 18, weight: .semibold)) + .foregroundStyle(.white) + } + } + } +} + +private struct SidebarInfoRow: View { + let systemImage: String + let title: String + let value: String + let tint: Color + + var body: some View { + HStack(spacing: 6) { + Image(systemName: systemImage) + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(tint) + .frame(width: 12) + + VStack(alignment: .leading, spacing: 1) { + Text(title) + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(.secondary) + Text(value) + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.primary) + .lineLimit(1) + } + + Spacer(minLength: 0) + } + .padding(.horizontal, 8) + .padding(.vertical, 6) + .frame(maxWidth: .infinity, alignment: .leading) + .background(.quaternary.opacity(0.35), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + } +} + +private struct SwiftBotSidebarMaterialBackground: View { + var body: some View { + SwiftBotVisualEffectMaterialView(material: .sidebar) + .overlay { + LinearGradient( + colors: [ + Color.white.opacity(0.08), + Color.clear + ], + startPoint: .topLeading, + endPoint: .bottomTrailing + ) + } + } +} + +private struct SwiftBotVisualEffectMaterialView: NSViewRepresentable { + let material: NSVisualEffectView.Material + var blendingMode: NSVisualEffectView.BlendingMode = .withinWindow + + func makeNSView(context: Context) -> NSVisualEffectView { + let view = NSVisualEffectView() + view.state = .active + view.material = material + view.blendingMode = blendingMode + return view + } + + func updateNSView(_ nsView: NSVisualEffectView, context: Context) { + nsView.material = material + nsView.blendingMode = blendingMode + nsView.state = .active + } +} From 54dcfdeae341015057e0e622b011b9b45490efb4 Mon Sep 17 00:00:00 2001 From: johnwatso Date: Thu, 7 May 2026 08:43:47 +1200 Subject: [PATCH 04/41] Update README style and switch license to MIT --- LICENSE | 695 ++---------------------------------------------------- README.md | 240 +++++++++++-------- 2 files changed, 158 insertions(+), 777 deletions(-) diff --git a/LICENSE b/LICENSE index 99602ee9..d333f524 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,21 @@ -GNU GENERAL PUBLIC LICENSE -Version 3, 29 June 2007 - -Copyright (C) 2007 Free Software Foundation, Inc. -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. - - Preamble - -The GNU General Public License is a free, copyleft license for -software and other kinds of works. - -The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - -For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - -Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - -Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - -Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - -0. Definitions. - -"This License" refers to version 3 of the GNU General Public License. - -"Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -"The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - -To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - -A "covered work" means either the unmodified Program or a work based -on the Program. - -To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - -To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - -An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - -1. Source Code. - -The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - -A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - -The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - -The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - -The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - -The Corresponding Source for a work in source code form is that -same work. - -2. Basic Permissions. - -All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. - -No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - -When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - -4. Conveying Verbatim Copies. - -You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. - -You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - -a) The work must carry prominent notices stating that you modified it, -and giving a relevant date. - -b) The work must carry prominent notices stating that it is -released under this License and any conditions added under section -7. This requirement modifies the requirement in section 4 to -"keep intact all notices". - -c) You must license the entire work, as a whole, under this -License to anyone who comes into possession of a copy. This -License will therefore apply, along with any applicable section 7 -additional terms, to the whole of the work, and all its parts, -regardless of how they are packaged. This License gives no -permission to license the work in any other way, but it does not -invalidate such permission if you have separately received it. - -d) If the work has interactive user interfaces, each must display -Appropriate Legal Notices; however, if the Program has interactive -interfaces that do not display Appropriate Legal Notices, your -work need not make them do so. - -A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - -6. Conveying Non-Source Forms. - -You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - -a) Convey the object code in, or embodied in, a physical product -(including a physical distribution medium), accompanied by the -Corresponding Source fixed on a durable physical medium -customarily used for software interchange. - -b) Convey the object code in, or embodied in, a physical product -(including a physical distribution medium), accompanied by a -written offer, valid for at least three years and valid for as -long as you offer spare parts or customer support for that product -model, to give anyone who possesses the object code either (1) a -copy of the Corresponding Source for all the software in the -product that is covered by this License, on a durable physical -medium customarily used for software interchange, for a price no -more than your reasonable cost of physically performing this -conveying of source, or (2) access to copy the -Corresponding Source from a network server at no charge. - -c) Convey individual copies of the object code with a copy of the -written offer to provide the Corresponding Source. This -alternative is allowed only occasionally and noncommercially, and -only if you received the object code with such an offer, in accord -with subsection 6b. - -d) Convey the object code by offering access from a designated -place (gratis or for a charge), and offer equivalent access to the -Corresponding Source in the same way through the same place at no -further charge. You need not require recipients to copy the -Corresponding Source along with the object code. If the place to -copy the object code is a network server, the Corresponding Source -may be on a different server (operated by you or a third party) -that supports equivalent copying facilities, provided you maintain -clear directions next to the object code saying where to find the -Corresponding Source. Regardless of what server hosts the -Corresponding Source, you remain obligated to ensure that it is -available for as long as needed to satisfy these requirements. - -e) Convey the object code using peer-to-peer transmission, provided -you inform other peers where the object code and Corresponding -Source of the work are being offered to the general public at no -charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - -A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - -"Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - -If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - -The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - -7. Additional Terms. - -"Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - -a) Disclaiming warranty or limiting liability differently from the -terms of sections 15 and 16 of this License; or - -b) Requiring preservation of specified reasonable legal notices or -author attributions in that material or in the Appropriate Legal -Notices displayed by works containing it; or - -c) Prohibiting misrepresentation of the origin of that material, or -requiring that modified versions of such material be marked in -reasonable ways as different from the original version; or - -d) Limiting the use for publicity purposes of names of licensors or -authors of the material; or - -e) Declining to grant rights under trademark law for use of some -trade names, trademarks, or service marks; or - -f) Requiring indemnification of licensors and authors of that -material by anyone who conveys the material (or modified versions of -it) with contractual assumptions of liability to the recipient, for -any liability that these contractual assumptions directly impose on -those licensors and authors. - -All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - -8. Termination. - -You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - -However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - -Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - -9. Acceptance Not Required for Having Copies. - -You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - -10. Automatic Licensing of Downstream Recipients. - -Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - -An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - -11. Patents. - -A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - -A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - -In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - -If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - -A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - -12. No Surrender of Others' Freedom. - -If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not convey it at all. For example, if you agree to terms that obligate -you to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - -13. Use with the GNU Affero General Public License. - -Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - -14. Revised Versions of this License. - -The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - -Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - -15. Disclaimer of Warranty. - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. - -If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - -If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w`. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c` for details. - -The hypothetical commands `show w` and `show c` should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - -You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - -The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +MIT License + +Copyright (c) 2026 johnwatso + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index a9ea4a97..f1e94f74 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,94 @@

- SwiftBot Icon + SwiftBot icon

-

SwiftBot

+

SwiftBot - Native macOS Discord Bot Dashboard

- Native macOS Discord bot dashboard built with SwiftUI + Run, configure, monitor, and automate a Discord bot from a native macOS app.

- - - - - + Platform badge + Swift badge + Architecture badge + License badge + Status badge

-## Development Status +**SwiftBot** is a native macOS application for running and managing a Discord bot without living in config files or terminal sessions. Built with Swift and SwiftUI, it provides a single dashboard for bot setup, Discord automation, commands, diagnostics, AI providers, update monitoring, and SwiftMesh failover. -SwiftBot is under active development. +It is designed for people who want a Discord bot they can actually operate day to day: start it, inspect it, adjust rules, check health, and ship updates from one macOS interface. -Features, UI, and configuration may change frequently as the app evolves. Occasional breakage between releases is expected while core systems are refined and stabilized. +SwiftBot can be used as a single local bot runner or as part of a SwiftMesh setup where one primary node handles Discord output and standby nodes can take over. + +## Overview + +SwiftBot connects to Discord through the Gateway and REST APIs, then exposes the bot runtime through a native macOS dashboard. + +The app handles: + +- Discord bot onboarding and token validation +- Server invite link generation +- Prefix and slash command routing +- Voice, message, and member-join automation +- Patchy update monitoring for AMD, NVIDIA, Intel, and Steam +- WikiBridge-backed knowledge commands +- AI reply flows through Apple Intelligence, Ollama, and OpenAI +- SwiftMesh primary and failover coordination +- Runtime logs, diagnostics, and connection checks + +## Why This Exists + +I wanted a Discord bot that felt like a Mac app instead of a pile of scripts. + +Most bots are powerful once configured, but routine operation can be awkward: tokens live somewhere, rules live somewhere else, logs are separate again, and diagnosing Discord permissions or gateway state usually means digging through code or console output. + +SwiftBot brings those pieces together in one place. It is intended to make the bot easier to run, easier to inspect, and easier to evolve without losing track of what is happening. + +## What SwiftBot Does + +- Runs a native Discord bot runtime from macOS +- Guides first-time setup with token validation and invite link generation +- Supports prefix commands and slash commands +- Provides command logging and channel configuration +- Builds automation rules for voice events, messages, and member joins +- Sends update notifications through Patchy monitoring targets +- Adds wiki-backed commands through WikiBridge sources +- Connects AI reply flows to Apple Intelligence, Ollama, or OpenAI +- Stores Discord bot tokens securely in macOS Keychain +- Caches Discord metadata for offline configuration +- Provides diagnostics for gateway, REST, latency, permissions, intents, and rate limits +- Supports SwiftMesh failover for primary and standby bot nodes +- Includes Sparkle appcast support for app updates ## Preview

- SwiftBot Dashboard Preview + SwiftBot dashboard preview

+## How It Works + +- A Discord application and bot token are created in the Discord Developer Portal +- SwiftBot validates the token and generates the server invite link +- The app connects to Discord through the Gateway and REST APIs +- Commands and automation rules are processed locally by the SwiftBot runtime +- Patchy checks configured update sources and sends Discord notifications when needed +- WikiBridge resolves enabled knowledge sources for dynamic commands +- AI providers are routed through configured local or remote engines +- SwiftMesh coordinates which node is allowed to send Discord output + +The macOS app sits on top of these services and presents their state in a single interface. + ## Install -SwiftBot installs are distributed through [GitHub Releases](https://github.com/johnwatso/SwiftBot/releases). +Download the latest release from [GitHub Releases](https://github.com/johnwatso/SwiftBot/releases). -1. Download the latest release from [GitHub Releases](https://github.com/johnwatso/SwiftBot/releases). -2. Open the `.zip`. -3. Move `SwiftBot.app` to `/Applications`. -4. Launch SwiftBot and complete onboarding. +1. Download the latest `.zip` +2. Move `SwiftBot.app` to `/Applications` +3. Launch SwiftBot +4. Complete Discord bot onboarding Future updates are handled in-app through Sparkle auto-updates. @@ -43,94 +96,51 @@ Future updates are handled in-app through Sparkle auto-updates. SwiftBot requires a Discord application with a bot user. -1. Go to the Discord Developer Portal - https://discord.com/developers/applications - +1. Open the [Discord Developer Portal](https://discord.com/developers/applications) 2. Click **New Application** - -3. Give the application a name (for example `SwiftBot`) - +3. Give the application a name, such as `SwiftBot` 4. Open the **Bot** section - 5. Click **Add Bot** - 6. Enable the required **Privileged Gateway Intents**: - - Server Members Intent - Message Content Intent - 7. Copy the **Bot Token** -You will paste this token into SwiftBot during the onboarding process. - -After the token is validated, SwiftBot will automatically generate the correct **server invite link** for your bot. +Paste the token into SwiftBot during onboarding. After the token is validated, SwiftBot will generate the correct server invite link for your bot. Invite the bot to your server using that generated link, then complete onboarding. -## Features - -### Bot Control - -- Native Discord Gateway and REST runtime -- Guided onboarding with token validation and invite link generation -- Prefix and slash command support -- Command logging and channel configuration tools - -### Automation - -- Voice event automation rules -- Member join welcome flows -- Message trigger rules -- Per-guild notification templates and voice activity logging - -### AI Integration +## Releases vs. Development Builds -- Apple Intelligence support -- Ollama local model support -- OpenAI integration -- Configurable AI routing for supported reply flows +The latest GitHub release is the most stable version. -### Knowledge & Data +Building from the current branch includes newer changes that may not have been released yet. These builds can contain bugs, incomplete features, or breaking changes. -- WikiBridge source management -- Dynamic wiki-backed commands -- Game metadata and reference query surfaces +## Requirements -### Monitoring - -- Patchy monitoring for AMD, NVIDIA, Intel, and Steam updates -- Scheduled checks, delivery targets, and test sends - -### Reliability - -- SwiftMesh primary and fail-over clustering -- Conversation and wiki-cache replication -- Persistent local settings and cached Discord metadata - -### Diagnostics - -- Gateway, REST, latency, rate-limit, permissions, and intents visibility -- On-demand connection testing and runtime health checks +- macOS 26+ +- Discord bot application and token +- Internet access ## Application Areas | Area | Purpose | | --- | --- | -| Overview | High-level bot status, activity, and summary information | -| Voice / Actions | Automation rule builder for voice, message, and member-join flows | +| Overview | Bot status, activity, and high-level runtime state | +| Voice / Actions | Rule builder for voice, message, and member-join automation | | Commands / Command Log | Command controls and recent command activity | -| WikiBridge | External knowledge source management and dynamic command configuration | -| Patchy | Driver and platform update monitoring | +| WikiBridge | External knowledge source management and dynamic command setup | +| Patchy | Driver, platform, and Steam update monitoring | | AI Bots | Apple Intelligence, Ollama, and OpenAI configuration | -| Diagnostics | Connection health, API checks, and remediation visibility | -| SwiftMesh | Cluster topology, fail-over state, and mesh diagnostics | -| Logs / Settings | Token management, runtime logs, and app configuration | +| Diagnostics | Gateway, REST, permissions, intents, and health checks | +| SwiftMesh | Primary, standby, failover, and mesh diagnostics | +| Logs / Settings | Token management, runtime logs, updates, and app configuration | ## Commands SwiftBot supports both prefix commands and slash commands. The prefix is configurable in Settings, and WikiBridge can add commands from enabled sources. -### General +Common commands include: - `help` - `ping` @@ -138,28 +148,16 @@ SwiftBot supports both prefix commands and slash commands. The prefix is configu - `8ball` - `poll` - `userinfo` - -### Server / Admin - - `setchannel` - `ignorechannel` - `notifystatus` - `debug` - `bugreport` - `weekly` - -### AI / Media - - `image` - `imagine` - -### Knowledge - - `meta` - `wiki` - -### Cluster - SwiftMesh - - `cluster` Additional slash commands include `compare`, `logabug`, and `featurerequest`. @@ -177,16 +175,55 @@ Common files include: Bot tokens are stored securely in macOS Keychain. -## Repository Layout +## Project Layout + +```text +SwiftBotApp/ macOS app, SwiftUI interface, Discord runtime, diagnostics, and SwiftMesh +Sources/UpdateEngine/ reusable update-checking engine used by Patchy +Tools/SparklePublisher/ Sparkle publishing helper +Tests/SwiftBotTests/ application test suite +docs/ GitHub Pages site, release notes, and Sparkle appcasts +notes/ internal planning, design, and review docs +``` + +## Architecture + +SwiftBot is a native Xcode project built around a SwiftUI app shell and a set of service layers for Discord, automation, Patchy monitoring, WikiBridge, AI routing, persistence, and SwiftMesh coordination. + +The reusable `UpdateEngine` package lives under `Sources/UpdateEngine` and powers Patchy's update-source checks. + +## Notes and Risk + +> [!CAUTION] +> SwiftBot depends on Discord APIs, gateway behavior, and bot permissions. +> +> Discord can change platform behavior, API constraints, gateway requirements, or policy expectations over time. Keep the app updated and review Discord's developer policies for your own use case. + + +> [!WARNING] +> Bot permissions and privileged gateway intents must be configured correctly in the Discord Developer Portal and on the target server. +> +> Missing intents or channel permissions can prevent commands, member events, message triggers, or notifications from working. + + +> [!WARNING] +> SwiftMesh failover is designed to avoid duplicate Discord output, but clustered bot setups should still be tested carefully before relying on them for important servers. + + +> [!NOTE] +> SwiftBot is under active development. Features, UI, and configuration may change between releases while core systems are refined. + + +> [!NOTE] +> Patchy update results depend on third-party vendor pages and Steam metadata. Those sources can change without warning. + +## Issues + +Please raise a GitHub issue if something breaks, behaves unexpectedly, or needs attention. -- `SwiftBotApp/` - main macOS application, SwiftUI interface, Discord runtime, diagnostics, and SwiftMesh -- `Sources/UpdateEngine/` - reusable update-checking engine used by Patchy -- `Tools/SparklePublisher/` - Sparkle publishing helper -- `Tests/SwiftBotTests/` - application test suite -- `docs/` - GitHub Pages site, release notes, and Sparkle appcasts -- `notes/` - internal planning, design, and review docs +When reporting runtime problems, include the SwiftBot version, macOS version, the affected area of the app, and any relevant diagnostics or log output from the app. -## Documentation +## Related Docs - [Architecture](ARCHITECTURE.md) - [AI Guide](AI_GUIDE.md) @@ -202,9 +239,6 @@ Bot tokens are stored securely in macOS Keychain. Sparkle uses the published appcasts to deliver automatic updates after installation. -## Contributing +## License -- Create a focused branch for each change. -- Keep updates small, clear, and easy to review. -- Include test notes and screenshots for behavior or UI changes. -- Open a pull request with a concise summary of what changed. +MIT From c2940cd81c840267df9f655d14c13f2aa33dfb55 Mon Sep 17 00:00:00 2001 From: johnwatso Date: Thu, 7 May 2026 08:49:14 +1200 Subject: [PATCH 05/41] Add security policy --- SECURITY.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..98593608 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,40 @@ +# Security Policy + +## Supported Versions + +The following versions of SwiftBot are currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 1.x | :white_check_mark: | +| < 1.0 | :x: | + +## Security Guarantees + +- **No Discord Password Storage:** SwiftBot uses a Discord bot token. Your personal Discord password is never entered, handled, or stored by the application. +- **Keychain Token Storage:** Discord bot tokens are stored securely in macOS Keychain. +- **Local Runtime Data:** SwiftBot stores settings, rules, logs, cached Discord metadata, and SwiftMesh cursors locally in your Application Support directory. +- **Direct Discord Connection:** Discord Gateway and REST API calls are made directly from your local machine to Discord. SwiftBot does not proxy bot tokens, messages, or server metadata through a third-party service. +- **Primary-Only Discord Output:** SwiftMesh is designed so only the active primary node sends Discord output, reducing the risk of duplicate clustered bot actions. + +## Security Scope & Limitations + +- **Bot Token Access:** Anyone with access to your unlocked Mac user account or Keychain may be able to use saved bot credentials. Protect your macOS account with a strong password and device security settings. +- **Discord Permissions:** SwiftBot can only act within the permissions granted to the bot in Discord. Review bot roles, channel permissions, and privileged gateway intents carefully. +- **Local Configuration Files:** Non-secret configuration is stored locally in Application Support. Treat backups and synced copies of that folder as potentially sensitive because they may contain server IDs, channel IDs, cached metadata, and automation rules. +- **Admin Web UI:** If the Admin Web UI or remote access features are enabled, bind addresses, access tokens, OAuth settings, certificates, and tunnel configuration should be reviewed before exposing the dashboard beyond localhost or a trusted network. +- **SwiftMesh Networking:** SwiftMesh peers should only be configured between machines you control. Keep mesh secrets private and avoid running a mixed-trust cluster. +- **Third-Party APIs:** Patchy, WikiBridge, AI providers, Discord, and vendor update sources may change behavior independently of SwiftBot. Keep SwiftBot updated and review provider terms for your own use case. + +## Reporting a Vulnerability + +Please do not open a public issue for sensitive security reports. + +If you discover a vulnerability, report it through GitHub's private vulnerability reporting for this repository if available, or contact the repository owner directly with: + +- A concise description of the issue +- Steps to reproduce +- The affected SwiftBot version or commit +- Any relevant logs, screenshots, or proof-of-concept details + +Please avoid including real Discord bot tokens, server secrets, private keys, or personal data in reports. From 5437acc587c55c681e1df3b17e71cef0d633829b Mon Sep 17 00:00:00 2001 From: johnwatso Date: Thu, 7 May 2026 09:08:00 +1200 Subject: [PATCH 06/41] Remove vulnerability reporting section --- SECURITY.md | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 98593608..ed4bfe21 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -25,16 +25,3 @@ The following versions of SwiftBot are currently being supported with security u - **Admin Web UI:** If the Admin Web UI or remote access features are enabled, bind addresses, access tokens, OAuth settings, certificates, and tunnel configuration should be reviewed before exposing the dashboard beyond localhost or a trusted network. - **SwiftMesh Networking:** SwiftMesh peers should only be configured between machines you control. Keep mesh secrets private and avoid running a mixed-trust cluster. - **Third-Party APIs:** Patchy, WikiBridge, AI providers, Discord, and vendor update sources may change behavior independently of SwiftBot. Keep SwiftBot updated and review provider terms for your own use case. - -## Reporting a Vulnerability - -Please do not open a public issue for sensitive security reports. - -If you discover a vulnerability, report it through GitHub's private vulnerability reporting for this repository if available, or contact the repository owner directly with: - -- A concise description of the issue -- Steps to reproduce -- The affected SwiftBot version or commit -- Any relevant logs, screenshots, or proof-of-concept details - -Please avoid including real Discord bot tokens, server secrets, private keys, or personal data in reports. From 7ad5a765917d7f408e40e7c2e38fd9c1fc75c182 Mon Sep 17 00:00:00 2001 From: johnwatso Date: Thu, 7 May 2026 09:09:51 +1200 Subject: [PATCH 07/41] Clarify app-owned security components --- SECURITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SECURITY.md b/SECURITY.md index ed4bfe21..b66a02c9 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -24,4 +24,4 @@ The following versions of SwiftBot are currently being supported with security u - **Local Configuration Files:** Non-secret configuration is stored locally in Application Support. Treat backups and synced copies of that folder as potentially sensitive because they may contain server IDs, channel IDs, cached metadata, and automation rules. - **Admin Web UI:** If the Admin Web UI or remote access features are enabled, bind addresses, access tokens, OAuth settings, certificates, and tunnel configuration should be reviewed before exposing the dashboard beyond localhost or a trusted network. - **SwiftMesh Networking:** SwiftMesh peers should only be configured between machines you control. Keep mesh secrets private and avoid running a mixed-trust cluster. -- **Third-Party APIs:** Patchy, WikiBridge, AI providers, Discord, and vendor update sources may change behavior independently of SwiftBot. Keep SwiftBot updated and review provider terms for your own use case. +- **External Services:** Patchy and WikiBridge are part of SwiftBot, but the external services they connect to may change independently. Discord, AI providers, vendor update sources, Steam metadata, and configured knowledge sources should be treated as external dependencies. From bcd35fbdc35f3de0c03956e8bd2cfba6ed5a67dd Mon Sep 17 00:00:00 2001 From: johnwatso Date: Thu, 7 May 2026 18:09:53 +1200 Subject: [PATCH 08/41] Polish SwiftMiner pairing and dashboard UX --- AGENTS.md | 82 +++++++++++++ AI_CONTEXT.md | 36 +++--- SwiftBot.xcodeproj/project.pbxproj | 4 +- SwiftBotApp/AdminWebServer.swift | 21 ++++ SwiftBotApp/AppModel+AdminWeb.swift | 8 ++ SwiftBotApp/AppModel+BotLifecycle.swift | 1 + SwiftBotApp/AppModel+Gateway.swift | 1 + SwiftBotApp/AppModel+SwiftMiner.swift | 91 +++++++++++++++ SwiftBotApp/AppModel.swift | 56 ++++++++- SwiftBotApp/Models/BotSettings.swift | 82 ++++++++++++- SwiftBotApp/RootView.swift | 5 +- SwiftBotApp/SwiftMinerPreferencesView.swift | 120 +++++++++++++------ docs/beta/appcast.xml | 10 +- docs/beta/release-notes/1.8.28.html | 48 -------- docs/beta/release-notes/1.9.1.html | 48 -------- docs/beta/release-notes/1.9.5.html | 48 -------- docs/beta/release-notes/1.9.6.html | 48 -------- docs/release-notes/1.3.html | 121 ++++++++++++++++++++ docs/release-notes/1.4.4.html | 100 +++++++++++++--- docs/release-notes/1.5.1.html | 89 +++++++++++--- docs/release-notes/1.6.1.html | 48 -------- docs/release-notes/1.6.2.html | 97 +++++++++++++--- docs/release-notes/1.6.html | 48 -------- docs/release-notes/1.7.2.html | 49 -------- docs/release-notes/1.7.211.html | 49 -------- docs/release-notes/1.7.212.html | 48 -------- docs/release-notes/1.7.213.html | 49 -------- docs/release-notes/1.7.217.html | 49 -------- docs/release-notes/1.7.218.html | 99 +++++++++++++--- docs/release-notes/1.7.html | 49 -------- docs/release-notes/1.8.0.html | 49 -------- docs/release-notes/1.8.1.html | 48 -------- docs/release-notes/1.8.11.html | 48 -------- docs/release-notes/1.8.12.html | 48 -------- docs/release-notes/1.8.13.html | 48 -------- docs/release-notes/1.8.14.html | 48 -------- docs/release-notes/1.8.15.html | 49 -------- docs/release-notes/1.8.16.html | 48 -------- docs/release-notes/1.8.18.html | 49 -------- docs/release-notes/1.8.2.html | 48 -------- docs/release-notes/1.8.20.html | 49 -------- docs/release-notes/1.8.21.html | 49 -------- docs/release-notes/1.8.22.html | 49 -------- docs/release-notes/1.8.23.html | 49 -------- docs/release-notes/1.8.24.html | 49 -------- docs/release-notes/1.8.25.html | 49 -------- docs/release-notes/1.8.27.html | 49 -------- docs/release-notes/1.8.31.html | 108 ++++++++++++++--- docs/release-notes/1.8.4.html | 49 -------- docs/release-notes/1.8.5.html | 49 -------- docs/release-notes/1.8.6.html | 49 -------- docs/release-notes/1.8.7.html | 49 -------- docs/release-notes/1.8.8.html | 49 -------- docs/release-notes/1.8.9.html | 50 -------- docs/release-notes/1.9.0.html | 49 -------- docs/release-notes/1.9.1.html | 49 -------- docs/release-notes/1.9.2.html | 49 -------- docs/release-notes/1.9.3.html | 49 -------- docs/release-notes/1.9.4.html | 49 -------- docs/release-notes/1.9.6.html | 48 -------- docs/release-notes/1.9.7.html | 49 -------- docs/release-notes/1.9.71.html | 49 -------- docs/release-notes/1.9.8.html | 100 +++++++++++++--- project.yml | 2 +- 64 files changed, 1041 insertions(+), 2285 deletions(-) create mode 100644 AGENTS.md delete mode 100644 docs/beta/release-notes/1.8.28.html delete mode 100644 docs/beta/release-notes/1.9.1.html delete mode 100644 docs/beta/release-notes/1.9.5.html delete mode 100644 docs/beta/release-notes/1.9.6.html create mode 100644 docs/release-notes/1.3.html delete mode 100644 docs/release-notes/1.6.1.html delete mode 100644 docs/release-notes/1.6.html delete mode 100644 docs/release-notes/1.7.2.html delete mode 100644 docs/release-notes/1.7.211.html delete mode 100644 docs/release-notes/1.7.212.html delete mode 100644 docs/release-notes/1.7.213.html delete mode 100644 docs/release-notes/1.7.217.html delete mode 100644 docs/release-notes/1.7.html delete mode 100644 docs/release-notes/1.8.0.html delete mode 100644 docs/release-notes/1.8.1.html delete mode 100644 docs/release-notes/1.8.11.html delete mode 100644 docs/release-notes/1.8.12.html delete mode 100644 docs/release-notes/1.8.13.html delete mode 100644 docs/release-notes/1.8.14.html delete mode 100644 docs/release-notes/1.8.15.html delete mode 100644 docs/release-notes/1.8.16.html delete mode 100644 docs/release-notes/1.8.18.html delete mode 100644 docs/release-notes/1.8.2.html delete mode 100644 docs/release-notes/1.8.20.html delete mode 100644 docs/release-notes/1.8.21.html delete mode 100644 docs/release-notes/1.8.22.html delete mode 100644 docs/release-notes/1.8.23.html delete mode 100644 docs/release-notes/1.8.24.html delete mode 100644 docs/release-notes/1.8.25.html delete mode 100644 docs/release-notes/1.8.27.html delete mode 100644 docs/release-notes/1.8.4.html delete mode 100644 docs/release-notes/1.8.5.html delete mode 100644 docs/release-notes/1.8.6.html delete mode 100644 docs/release-notes/1.8.7.html delete mode 100644 docs/release-notes/1.8.8.html delete mode 100644 docs/release-notes/1.8.9.html delete mode 100644 docs/release-notes/1.9.0.html delete mode 100644 docs/release-notes/1.9.1.html delete mode 100644 docs/release-notes/1.9.2.html delete mode 100644 docs/release-notes/1.9.3.html delete mode 100644 docs/release-notes/1.9.4.html delete mode 100644 docs/release-notes/1.9.6.html delete mode 100644 docs/release-notes/1.9.7.html delete mode 100644 docs/release-notes/1.9.71.html diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..75f490f2 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,82 @@ +# SwiftBot Agent Notes + +Read `AI_CONTEXT.md` first. It is the main architecture and workflow reference for AI agents working in this repo. + +This file exists to capture the practical guardrails that agents are most likely to miss: build system boundaries, project generation, versioning, and release metadata discipline. + +## Project Shape + +- SwiftBot is a native macOS Xcode app built with SwiftUI. +- The app project is generated from `project.yml` using XcodeGen. +- This repo also contains one nested Swift package at `Sources/UpdateEngine`. +- Do not convert the main app into a Swift package. +- Do not introduce a repo-root `Package.swift`. +- Do not move app files into a package-style layout. + +## Build and Test + +For the main app, use Xcode tooling: + +```sh +xcodebuild -project SwiftBot.xcodeproj -scheme SwiftBot -configuration Debug build +xcodebuild -project SwiftBot.xcodeproj -scheme SwiftBot -configuration Debug test +``` + +Run `xcodegen` after editing `project.yml`: + +```sh +xcodegen +``` + +For the nested UpdateEngine package only, SwiftPM commands are valid inside `Sources/UpdateEngine` when that package is the thing being changed: + +```sh +cd Sources/UpdateEngine +swift test +``` + +Do not use `swift build` or `swift test` as a substitute for validating the app target. + +## Scope Discipline + +- Keep changes scoped to the user’s request. +- Prefer modifying the relevant SwiftUI view, model, or service directly instead of refactoring unrelated systems. +- Do not introduce new modules, packages, or architectural layers unless the user explicitly asks for that level of change. +- Follow existing Apple-platform patterns in this repo. Avoid web-style UI abstractions and avoid external UI frameworks. + +## Versioning + +- `MARKETING_VERSION` is user-directed. Do not bump it unless the user explicitly asks. +- `CURRENT_PROJECT_VERSION` should not be changed casually. Only update it when the requested work includes release/version/build preparation. +- When version metadata changes, keep `project.yml` and `SwiftBot.xcodeproj/project.pbxproj` aligned. +- If release metadata is touched, also verify related Sparkle/appcast files under `docs/`. + +## Sparkle and Release Metadata + +Treat these as release-critical whenever touched: + +- `project.yml` +- `SwiftBot.xcodeproj/project.pbxproj` +- `docs/appcast.xml` +- `docs/release-notes/*` + +Do not break: + +- `SUFeedURL` +- `SUPublicEDKey` +- `MARKETING_VERSION` +- `CURRENT_PROJECT_VERSION` +- appcast version/release-note links + +If you edit release metadata, build the app and verify the resulting Info.plist values before calling the work done. + +## Project Generation Rules + +- `project.yml` is the source of truth for generated Xcode settings. +- If you change build settings in the generated project, mirror them in `project.yml` unless there is a very specific reason not to. +- Avoid committing unrelated XcodeGen drift. + +## Coordination + +- Use `AI_CONTEXT.md` for architecture, file ownership, cluster safety rules, and UI rules. +- If guidance in this file and `AI_CONTEXT.md` ever appear to conflict, follow the repo reality and preserve existing behavior, then document the inconsistency in your final note. diff --git a/AI_CONTEXT.md b/AI_CONTEXT.md index bd04902d..80dca6bd 100644 --- a/AI_CONTEXT.md +++ b/AI_CONTEXT.md @@ -11,12 +11,12 @@ SwiftBot is a **native macOS Discord bot manager** built entirely with Swift and | Property | Value | |----------|-------| -| Platform | macOS 13+ | +| Platform | macOS 26+ | | Language | Swift with Concurrency (async/await, actors) | | Framework | SwiftUI — Apple-platform-first, no web frameworks | | Design Language | Apple Human Interface Guidelines — Liquid Glass / modern macOS | | Architecture | MVVM + actor isolation + EventBus pub/sub | -| Build System | Xcode + Swift Package Manager | +| Build System | Xcode + XcodeGen for the app, SwiftPM only for `Sources/UpdateEngine` | **What it does:** Connects to Discord via WebSocket gateway, monitors server events, and executes automated rules when events match. Also supports AI replies, wiki lookups, update monitoring (Patchy), multi-node cluster failover (SwiftMesh), and a web-based admin UI. @@ -163,7 +163,7 @@ All UI in SwiftBot **must** follow: 1. **Apple Human Interface Guidelines** — always, without exception 2. **SwiftUI only** — no AppKit views unless unavoidable (use `NSViewRepresentable`) -3. **System Settings layout style** — sidebar navigation, HSplitView, material backgrounds +3. **System Settings layout style** — sidebar navigation, split-pane layouts where appropriate, material backgrounds 4. **Liquid Glass / modern macOS design language** — `.ultraThinMaterial`, `.thinMaterial`, semantic system colors 5. **No web-style patterns** — no CSS-like layouts, no custom scrollbars, no card grids 6. **No external UI frameworks** — zero SwiftPM UI dependencies @@ -179,7 +179,7 @@ All UI in SwiftBot **must** follow: ### 3-Pane View Architecture ``` -VoiceWorkspaceView (HSplitView) +VoiceWorkspaceView (split-pane layout) ├── RuleListView (220–320px) — VoiceRuleListView.swift │ ├── isLoading → ProgressView() │ ├── rules.isEmpty → RuleListEmptyStateView ("No Rules Yet") @@ -233,7 +233,8 @@ var processedActions: [RuleAction] // runtime migration: legacy booleans → m - ✅ Swift Concurrency (`async/await`, `actor`, `@MainActor`, `Task`) - ✅ Keychain for ALL secrets — never write to disk -- ✅ Add new `.swift` files to `project.pbxproj` (4 entries: PBXFileReference, PBXBuildFile, PBXGroup, PBXSourcesBuildPhase) +- ✅ Treat `project.yml` as the source of truth for app project settings +- ✅ Run `xcodegen` after editing `project.yml` - ✅ `.id(selectionID)` on all list-detail views to prevent SwiftUI state leakage - ✅ Look up current selection INSIDE binding closures — never capture IDs at creation time - ✅ `await MainActor.run {}` when updating `@Published` from background actors @@ -245,7 +246,8 @@ var processedActions: [RuleAction] // runtime migration: legacy booleans → m - ❌ Pre-populate new rules with default trigger or actions - ❌ Change `Models.swift` structure without cross-agent approval - ❌ Add new SwiftPM dependencies without explicit justification -- ❌ Break existing UI layouts or SplitView behaviors +- ❌ Convert the main app target into a Swift package or add a repo-root `Package.swift` +- ❌ Break existing UI layouts or split-pane behaviors - ❌ Send Discord output from Standby or Worker nodes - ❌ Use `#if DEBUG` to gate production logic - ❌ Call `test*` methods from production code paths @@ -255,20 +257,11 @@ var processedActions: [RuleAction] // runtime migration: legacy booleans → m --- -## 8. Multi-Agent File Ownership +## 8. Agent Coordination -When multiple agents work on SwiftBot simultaneously, respect file ownership: +If multiple agents are working in parallel, coordinate before editing the same files and prefer clear ownership by area for the duration of the task. -| File | Owner | -|------|-------| -| `VoiceActionsView.swift` | **claude** | -| `VoiceRuleListView.swift` | **claude** | -| `EmptyRuleOnboardingView.swift` | **claude** | -| `Models.swift` | **kimi** | -| `AppModel.swift` | **gemini** | -| `DiscordService.swift` | **gemini** | - -**Rule:** Post in `#swiftbotdev` before editing another agent's file. Coordinate task splits before starting any work. +This file does not assign permanent file owners. Treat any historical ownership notes elsewhere as advisory, not authoritative. --- @@ -306,11 +299,10 @@ static func empty() -> Rule { Rule(trigger: nil, actions: []) } - [ ] Build succeeds — 0 errors, 0 new warnings - [ ] Modified feature works as expected - [ ] No regressions in unrelated features -- [ ] `CHANGELOG.md` updated -- [ ] Any new `.swift` files added to `project.pbxproj` -- [ ] Posted results in `#swiftbotdev` +- [ ] If `project.yml` changed, regenerate with `xcodegen` +- [ ] If versioning or release metadata changed, verify `project.yml`, `SwiftBot.xcodeproj/project.pbxproj`, and `docs/` stay aligned --- -*Last updated: 2026-03-11* +*Last updated: 2026-05-07* *See `ARCHITECTURE.md` for full technical detail · `AI_GUIDE.md` for common task recipes* diff --git a/SwiftBot.xcodeproj/project.pbxproj b/SwiftBot.xcodeproj/project.pbxproj index 85c52ab0..e8c7d11b 100644 --- a/SwiftBot.xcodeproj/project.pbxproj +++ b/SwiftBot.xcodeproj/project.pbxproj @@ -735,7 +735,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 26.0; - MARKETING_VERSION = 1.9.6; + MARKETING_VERSION = 1.9.9; PRODUCT_BUNDLE_IDENTIFIER = com.example.swiftbot; PRODUCT_NAME = SwiftBot; PROVISIONING_PROFILE_SPECIFIER = ""; @@ -874,7 +874,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 26.0; - MARKETING_VERSION = 1.9.6; + MARKETING_VERSION = 1.9.9; PRODUCT_BUNDLE_IDENTIFIER = com.example.swiftbot; PRODUCT_NAME = SwiftBot; PROVISIONING_PROFILE_SPECIFIER = ""; diff --git a/SwiftBotApp/AdminWebServer.swift b/SwiftBotApp/AdminWebServer.swift index b484c776..7c074700 100644 --- a/SwiftBotApp/AdminWebServer.swift +++ b/SwiftBotApp/AdminWebServer.swift @@ -463,6 +463,8 @@ actor AdminWebServer { private var stopBot: (@Sendable () async -> Bool)? private var refreshSwiftMesh: (@Sendable () async -> Bool)? private var swiftMinerWebhookHandler: (@Sendable ([String: String], Data) async -> (status: String, body: Data))? + private var discordUsersProvider: (@Sendable () async -> [String: String])? + private var swiftMinerTestDMSender: (@Sendable (String) async -> Bool)? private var logger: (@Sendable (String) async -> Void)? private var sessions: [String: Session] = [:] private var pendingStates: [String: PendingState] = [:] @@ -520,6 +522,8 @@ actor AdminWebServer { stopBot: @escaping @Sendable () async -> Bool, refreshSwiftMesh: @escaping @Sendable () async -> Bool, swiftMinerWebhookHandler: @escaping @Sendable ([String: String], Data) async -> (status: String, body: Data), + discordUsersProvider: @escaping @Sendable () async -> [String: String], + swiftMinerTestDMSender: @escaping @Sendable (String) async -> Bool, log: @escaping @Sendable (String) async -> Void ) async -> RuntimeState { self.statusProvider = statusProvider @@ -569,6 +573,8 @@ actor AdminWebServer { self.stopBot = stopBot self.refreshSwiftMesh = refreshSwiftMesh self.swiftMinerWebhookHandler = swiftMinerWebhookHandler + self.discordUsersProvider = discordUsersProvider + self.swiftMinerTestDMSender = swiftMinerTestDMSender self.logger = log loadPersistedSessions() @@ -879,6 +885,21 @@ actor AdminWebServer { return serveAsset(named: parts[0], ext: parts[1], subdirectories: ["admin/games", "Resources/admin/games"]) case ("GET", "/health"): return jsonResponse(["status": "ok"]) + case ("GET", "/v1/users"): + let usernamesById = await discordUsersProvider?() ?? [:] + let users = usernamesById + .map { ["discord_id": $0.key, "display_name": $0.value] } + .sorted { ($0["display_name"] ?? "") < ($1["display_name"] ?? "") } + return jsonResponse(["users": users]) + case ("POST", let path) where path.hasPrefix("/v1/users/") && path.hasSuffix("/dm/test"): + let segments = path.split(separator: "/").map(String.init) + // Expected: ["v1", "users", "", "dm", "test"] + guard segments.count == 5 else { + return jsonResponse(["error": "invalid_path"], status: "400 Bad Request") + } + let discordUserId = segments[2] + let sent = await swiftMinerTestDMSender?(discordUserId) ?? false + return jsonResponse(["ok": sent], status: sent ? "200 OK" : "502 Bad Gateway") case ("POST", "/webhooks/swiftminer/events"): guard let handler = swiftMinerWebhookHandler else { return jsonResponse(["error": "swiftminer_unavailable"], status: "503 Service Unavailable") diff --git a/SwiftBotApp/AppModel+AdminWeb.swift b/SwiftBotApp/AppModel+AdminWeb.swift index 523a8c69..9b4824d8 100644 --- a/SwiftBotApp/AppModel+AdminWeb.swift +++ b/SwiftBotApp/AppModel+AdminWeb.swift @@ -1081,6 +1081,14 @@ extension AppModel { } return await model.handleSwiftMinerWebhook(headers: headers, body: body) }, + discordUsersProvider: { [weak self] in + guard let model = self else { return [:] } + return await model.discordCache.allUserNames() + }, + swiftMinerTestDMSender: { [weak self] discordUserId in + guard let model = self else { return false } + return await model.sendSwiftMinerTestDM(to: discordUserId) + }, log: { [weak self] message in guard let model = self else { return } await MainActor.run { model.logs.append(message) } diff --git a/SwiftBotApp/AppModel+BotLifecycle.swift b/SwiftBotApp/AppModel+BotLifecycle.swift index 710d8e2a..7085cce7 100644 --- a/SwiftBotApp/AppModel+BotLifecycle.swift +++ b/SwiftBotApp/AppModel+BotLifecycle.swift @@ -149,6 +149,7 @@ extension AppModel { } else { botAvatarHash = nil } + persistCachedBotIdentityIfNeeded() } // MARK: - Onboarding integration diff --git a/SwiftBotApp/AppModel+Gateway.swift b/SwiftBotApp/AppModel+Gateway.swift index 8c105509..465df406 100644 --- a/SwiftBotApp/AppModel+Gateway.swift +++ b/SwiftBotApp/AppModel+Gateway.swift @@ -75,6 +75,7 @@ extension AppModel { } botDiscriminator = identity?.discriminator botAvatarHash = identity?.avatarHash + persistCachedBotIdentityIfNeeded() } func handleMeshSync(_ payload: MeshSyncPayload) async { diff --git a/SwiftBotApp/AppModel+SwiftMiner.swift b/SwiftBotApp/AppModel+SwiftMiner.swift index 077bc65e..beba0011 100644 --- a/SwiftBotApp/AppModel+SwiftMiner.swift +++ b/SwiftBotApp/AppModel+SwiftMiner.swift @@ -1,3 +1,4 @@ +import AppKit import CryptoKit import Foundation @@ -7,6 +8,7 @@ extension AppModel { let bundle = try decodeSwiftMinerPairingToken(rawToken) settings.swiftMiner.apply(pairingBundle: bundle) settings.adminWebUI.enabled = true + cacheSwiftMinerArtwork(from: bundle) saveSettings() return (true, "SwiftMiner pairing bundle applied. Local webhook server enabled.") } catch { @@ -81,6 +83,24 @@ extension AppModel { } } + func sendSwiftMinerTestDM(to discordUserId: String) async -> Bool { + guard settings.swiftMiner.enabled else { return false } + let content = """ + **SwiftMiner account connected and active** ⚡ + + Your Twitch account has been linked to SwiftMiner and is ready to mine drops. + Use `/miner action:status` to check your current progress at any time. + """ + do { + try await service.sendDM(userId: discordUserId, content: content) + addEvent(ActivityEvent(timestamp: Date(), kind: .command, message: "SwiftMiner test DM sent to \(discordUserId)")) + return true + } catch { + logs.append("SwiftMiner test DM failed for \(discordUserId): \(error.localizedDescription)") + return false + } + } + func handleSwiftMinerWebhook(headers: [String: String], body: Data) async -> (status: String, body: Data) { guard settings.swiftMiner.enabled else { return swiftMinerWebhookResponse(status: "404 Not Found", payload: ["error": "swiftminer_disabled"]) @@ -202,6 +222,77 @@ extension AppModel { } return bundle } + + func swiftMinerCachedArtworkURL() -> URL? { + let fileName = settings.swiftMiner.cachedArtworkFileName.trimmingCharacters(in: .whitespacesAndNewlines) + guard !fileName.isEmpty else { return nil } + let url = Self.swiftMinerArtworkCacheDirectoryURL().appendingPathComponent(fileName) + return FileManager.default.fileExists(atPath: url.path) ? url : nil + } + + func cacheSwiftMinerArtworkIfNeeded() { + let fileName = settings.swiftMiner.cachedArtworkFileName.trimmingCharacters(in: .whitespacesAndNewlines) + let cachedURL = swiftMinerCachedArtworkURL() + guard cachedURL == nil || fileName.isEmpty else { return } + let artworkURL = settings.swiftMiner.artworkURL.trimmingCharacters(in: .whitespacesAndNewlines) + guard !artworkURL.isEmpty else { return } + cacheSwiftMinerArtwork(from: nil) + } + + private func cacheSwiftMinerArtwork(from bundle: SwiftMinerPairingBundle?) { + if let bundle, + let data = Self.decodedSwiftMinerArtworkData(from: bundle.artworkDataBase64) { + storeSwiftMinerArtwork(data) + return + } + + let artworkURL = (bundle?.artworkURL ?? settings.swiftMiner.artworkURL).trimmingCharacters(in: .whitespacesAndNewlines) + guard let url = URL(string: artworkURL), ["http", "https"].contains(url.scheme?.lowercased()) else { return } + + Task { [weak self] in + do { + let (data, response) = try await URLSession.shared.data(from: url) + if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { + return + } + await MainActor.run { + self?.storeSwiftMinerArtwork(data) + self?.saveSettings() + } + } catch { + await MainActor.run { + self?.logs.append("SwiftMiner artwork cache failed: \(error.localizedDescription)") + } + } + } + } + + private func storeSwiftMinerArtwork(_ data: Data) { + guard NSImage(data: data) != nil else { return } + let fileName = "swiftminer-artwork-\(SHA256.hash(data: data).compactMap { String(format: "%02x", $0) }.joined()).img" + let url = Self.swiftMinerArtworkCacheDirectoryURL().appendingPathComponent(fileName) + do { + try data.write(to: url, options: .atomic) + settings.swiftMiner.cachedArtworkFileName = fileName + } catch { + logs.append("SwiftMiner artwork cache failed: \(error.localizedDescription)") + } + } + + private static func decodedSwiftMinerArtworkData(from rawValue: String) -> Data? { + let trimmed = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } + let base64 = trimmed.localizedCaseInsensitiveContains(";base64,") + ? trimmed.components(separatedBy: ";base64,").last ?? "" + : trimmed + return Data(base64Encoded: base64) + } + + private static func swiftMinerArtworkCacheDirectoryURL() -> URL { + let url = SwiftBotStorage.folderURL().appendingPathComponent("swiftminer-artwork", isDirectory: true) + try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } } private enum SwiftMinerPairingError: LocalizedError { diff --git a/SwiftBotApp/AppModel.swift b/SwiftBotApp/AppModel.swift index feddb86d..359b0d97 100644 --- a/SwiftBotApp/AppModel.swift +++ b/SwiftBotApp/AppModel.swift @@ -200,6 +200,15 @@ final class AppModel: ObservableObject { // Max cache entries to prevent unbounded memory growth during extended operation private let maxAvatarCacheCount = 1000 + var resolvedBotUsername: String { + let live = botUsername.trimmingCharacters(in: .whitespacesAndNewlines) + if !live.isEmpty, live != "OnlineBot" { + return live + } + let cached = settings.cachedBotIdentity.username.trimmingCharacters(in: .whitespacesAndNewlines) + return cached.isEmpty ? "SwiftBot" : cached + } + func cacheUserAvatar(_ hash: String, for userId: String) { userAvatarHashById[userId] = hash if userAvatarHashById.count > maxAvatarCacheCount { @@ -229,7 +238,11 @@ final class AppModel: ObservableObject { var playlistTrackCardsByKey: [String: PlaylistTrackCardState] = [:] var botAvatarURL: URL? { - guard let userId = botUserId, let hash = botAvatarHash else { return nil } + let cachedUserId = settings.cachedBotIdentity.userId.trimmingCharacters(in: .whitespacesAndNewlines) + let cachedAvatarHash = settings.cachedBotIdentity.avatarHash.trimmingCharacters(in: .whitespacesAndNewlines) + let userId = botUserId ?? (cachedUserId.isEmpty ? nil : cachedUserId) + let hash = botAvatarHash ?? (cachedAvatarHash.isEmpty ? nil : cachedAvatarHash) + guard let userId, let hash else { return nil } let ext = hash.hasPrefix("a_") ? "gif" : "png" return URL(string: "https://cdn.discordapp.com/avatars/\(userId)/\(hash).\(ext)?size=128") } @@ -347,6 +360,7 @@ final class AppModel: ObservableObject { } settings = loadedSettings + restoreCachedBotIdentity() isOnboardingComplete = onboardingCompleted(for: loadedSettings) // Initialize the appropriate data provider @@ -711,10 +725,7 @@ final class AppModel: ObservableObject { lastGatewayEventName = "-" lastVoiceStateAt = nil lastVoiceStateSummary = "-" - botUserId = nil - botUsername = "OnlineBot" - botDiscriminator = nil - botAvatarHash = nil + restoreCachedBotIdentity() clusterNodes = [] lastGoodClusterNodes = [] lastClusterStatusSuccessAt = nil @@ -832,6 +843,41 @@ final class AppModel: ObservableObject { let s = interval % 60 return "\(m)m \(s)s" } + + func restoreCachedBotIdentity() { + let cached = settings.cachedBotIdentity + let cachedUserId = cached.userId.trimmingCharacters(in: .whitespacesAndNewlines) + if !cachedUserId.isEmpty { + botUserId = cachedUserId + } + let cachedUsername = cached.username.trimmingCharacters(in: .whitespacesAndNewlines) + if !cachedUsername.isEmpty { + botUsername = cachedUsername + } + let cachedDiscriminator = cached.discriminator.trimmingCharacters(in: .whitespacesAndNewlines) + botDiscriminator = cachedDiscriminator.isEmpty ? nil : cachedDiscriminator + let cachedAvatarHash = cached.avatarHash.trimmingCharacters(in: .whitespacesAndNewlines) + botAvatarHash = cachedAvatarHash.isEmpty ? nil : cachedAvatarHash + } + + func persistCachedBotIdentityIfNeeded() { + var cached = settings.cachedBotIdentity + let nextUserId = botUserId?.trimmingCharacters(in: .whitespacesAndNewlines) ?? cached.userId + let nextUsername = botUsername.trimmingCharacters(in: .whitespacesAndNewlines) + let nextDiscriminator = botDiscriminator?.trimmingCharacters(in: .whitespacesAndNewlines) ?? cached.discriminator + let nextAvatarHash = botAvatarHash?.trimmingCharacters(in: .whitespacesAndNewlines) ?? cached.avatarHash + + guard !nextUsername.isEmpty, nextUsername != "OnlineBot" else { return } + + cached.userId = nextUserId + cached.username = nextUsername + cached.discriminator = nextDiscriminator == "0" ? "" : nextDiscriminator + cached.avatarHash = nextAvatarHash + + guard cached != settings.cachedBotIdentity else { return } + settings.cachedBotIdentity = cached + saveSettings() + } } @MainActor diff --git a/SwiftBotApp/Models/BotSettings.swift b/SwiftBotApp/Models/BotSettings.swift index 6f3d052c..b20c9aa9 100644 --- a/SwiftBotApp/Models/BotSettings.swift +++ b/SwiftBotApp/Models/BotSettings.swift @@ -316,6 +316,7 @@ struct BotSettings: Codable, Hashable { var wikiBot = WikiBotSettings() var patchy = PatchySettings() var swiftMiner = SwiftMinerSettings() + var cachedBotIdentity = CachedBotIdentity() var help = HelpSettings() var adminWebUI = AdminWebUISettings() @@ -399,6 +400,7 @@ struct BotSettings: Codable, Hashable { case wikiBot case patchy case swiftMiner + case cachedBotIdentity case help case adminWebUI } @@ -466,6 +468,7 @@ struct BotSettings: Codable, Hashable { wikiBot = try container.decodeIfPresent(WikiBotSettings.self, forKey: .wikiBot) ?? WikiBotSettings() patchy = try container.decodeIfPresent(PatchySettings.self, forKey: .patchy) ?? PatchySettings() swiftMiner = try container.decodeIfPresent(SwiftMinerSettings.self, forKey: .swiftMiner) ?? SwiftMinerSettings() + cachedBotIdentity = try container.decodeIfPresent(CachedBotIdentity.self, forKey: .cachedBotIdentity) ?? CachedBotIdentity() help = try container.decodeIfPresent(HelpSettings.self, forKey: .help) ?? HelpSettings() adminWebUI = try container.decodeIfPresent(AdminWebUISettings.self, forKey: .adminWebUI) ?? AdminWebUISettings() remoteMode.normalize() @@ -532,17 +535,33 @@ struct BotSettings: Codable, Hashable { try container.encode(wikiBot, forKey: .wikiBot) try container.encode(patchy, forKey: .patchy) try container.encode(swiftMiner, forKey: .swiftMiner) + try container.encode(cachedBotIdentity, forKey: .cachedBotIdentity) try container.encode(help, forKey: .help) try container.encode(adminWebUI, forKey: .adminWebUI) } } +struct CachedBotIdentity: Codable, Hashable { + var userId: String = "" + var username: String = "" + var discriminator: String = "" + var avatarHash: String = "" + + var hasValue: Bool { + !username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + || !userId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + || !avatarHash.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } +} + struct SwiftMinerSettings: Codable, Hashable { var enabled: Bool = false var baseURL: String = "http://127.0.0.1:8080" var apiKey: String = "" var webhookSecret: String = "" var webhookHint: String = "" + var artworkURL: String = "" + var cachedArtworkFileName: String = "" var normalizedBaseURL: String { let trimmed = baseURL.trimmingCharacters(in: .whitespacesAndNewlines) @@ -559,6 +578,7 @@ struct SwiftMinerSettings: Codable, Hashable { apiKey = pairingBundle.apiKey webhookSecret = pairingBundle.hmacSecret webhookHint = pairingBundle.webhookHint + artworkURL = pairingBundle.artworkURL } } @@ -570,6 +590,8 @@ struct SwiftMinerPairingBundle: Codable, Hashable { let apiKey: String let hmacSecret: String let webhookHint: String + let artworkURL: String + let artworkDataBase64: String private enum CodingKeys: String, CodingKey { case version @@ -579,6 +601,18 @@ struct SwiftMinerPairingBundle: Codable, Hashable { case apiKey case hmacSecret case webhookHint + case artworkURL + case imageURL + case iconURL + case logoURL + case artwork + case image + case icon + case logo + case artworkData + case imageData + case iconData + case logoData } init( @@ -588,7 +622,9 @@ struct SwiftMinerPairingBundle: Codable, Hashable { swiftBotEndpoint: String = "", apiKey: String, hmacSecret: String, - webhookHint: String + webhookHint: String, + artworkURL: String = "", + artworkDataBase64: String = "" ) { self.version = version self.endpoint = endpoint @@ -597,6 +633,8 @@ struct SwiftMinerPairingBundle: Codable, Hashable { self.apiKey = apiKey self.hmacSecret = hmacSecret self.webhookHint = webhookHint + self.artworkURL = artworkURL + self.artworkDataBase64 = artworkDataBase64 } init(from decoder: Decoder) throws { @@ -608,6 +646,48 @@ struct SwiftMinerPairingBundle: Codable, Hashable { apiKey = try container.decodeIfPresent(String.self, forKey: .apiKey) ?? "" hmacSecret = try container.decodeIfPresent(String.self, forKey: .hmacSecret) ?? "" webhookHint = try container.decodeIfPresent(String.self, forKey: .webhookHint) ?? "" + let artworkValue = try Self.firstDecodedString( + in: container, + keys: [.artworkURL, .imageURL, .iconURL, .logoURL, .artwork, .image, .icon, .logo] + ) + if artworkValue.localizedCaseInsensitiveContains(";base64,"), + let base64 = artworkValue.components(separatedBy: ";base64,").last { + artworkURL = "" + artworkDataBase64 = base64 + } else { + artworkURL = artworkValue + artworkDataBase64 = try Self.firstDecodedString( + in: container, + keys: [.artworkData, .imageData, .iconData, .logoData] + ) + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(version, forKey: .version) + try container.encode(endpoint, forKey: .endpoint) + try container.encode(swiftMinerEndpoint, forKey: .swiftMinerEndpoint) + try container.encode(swiftBotEndpoint, forKey: .swiftBotEndpoint) + try container.encode(apiKey, forKey: .apiKey) + try container.encode(hmacSecret, forKey: .hmacSecret) + try container.encode(webhookHint, forKey: .webhookHint) + try container.encode(artworkURL, forKey: .artworkURL) + try container.encode(artworkDataBase64, forKey: .artworkData) + } + + private static func firstDecodedString( + in container: KeyedDecodingContainer, + keys: [CodingKeys] + ) throws -> String { + for key in keys { + let value = try container.decodeIfPresent(String.self, forKey: key) ?? "" + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { + return trimmed + } + } + return "" } } diff --git a/SwiftBotApp/RootView.swift b/SwiftBotApp/RootView.swift index 5ac1aa50..9b3c6d97 100644 --- a/SwiftBotApp/RootView.swift +++ b/SwiftBotApp/RootView.swift @@ -50,7 +50,7 @@ struct UnifiedRootView: View { @EnvironmentObject var app: AppModel var body: some View { - HSplitView { + HStack(spacing: 0) { DashboardSidebar(selection: $selection) .frame(minWidth: 230, idealWidth: 250, maxWidth: 280) @@ -77,7 +77,6 @@ struct UnifiedRootView: View { .frame(maxWidth: .infinity, maxHeight: .infinity) .background(SwiftBotGlassBackground()) } - .padding(.top, -30) .ignoresSafeArea(.container, edges: .top) .background(SwiftBotGlassBackground()) .overlay(alignment: .topTrailing) { @@ -129,7 +128,7 @@ struct DashboardSidebar: View { VStack(spacing: 12) { DashboardSidebarHeader( avatarURL: app.botAvatarURL, - botUsername: app.botUsername, + botUsername: app.resolvedBotUsername, statusText: app.primaryServiceStatusText, isOnline: app.primaryServiceIsOnline, clusterMode: app.clusterSnapshot.mode.rawValue, diff --git a/SwiftBotApp/SwiftMinerPreferencesView.swift b/SwiftBotApp/SwiftMinerPreferencesView.swift index 8ed086f8..dfb4bb17 100644 --- a/SwiftBotApp/SwiftMinerPreferencesView.swift +++ b/SwiftBotApp/SwiftMinerPreferencesView.swift @@ -23,50 +23,62 @@ struct SwiftMinerPreferencesView: View { .foregroundStyle(app.settings.swiftMiner.enabled ? .green : .secondary) } - VStack(alignment: .leading, spacing: 8) { - Text("Pairing Bundle") - .font(.subheadline.weight(.medium)) - TextField("Paste from SwiftMiner", text: $swiftMinerPairingToken) - .textFieldStyle(.roundedBorder) - } + if app.settings.swiftMiner.enabled { + HStack(spacing: 10) { + swiftMinerArtwork + Text("SwiftMiner is paired and ready.") + .font(.caption) + .foregroundStyle(.secondary) + } + .onAppear { + app.cacheSwiftMinerArtworkIfNeeded() + } + } else { + VStack(alignment: .leading, spacing: 8) { + Text("Pairing Bundle") + .font(.subheadline.weight(.medium)) + TextField("Paste from SwiftMiner", text: $swiftMinerPairingToken) + .textFieldStyle(.roundedBorder) + } - HStack { - Button { - let result = app.applySwiftMinerPairingToken(swiftMinerPairingToken) - swiftMinerPairingSucceeded = result.ok - swiftMinerPairingMessage = result.message - if result.ok { - swiftMinerPairingToken = "" + HStack { + Button { + let result = app.applySwiftMinerPairingToken(swiftMinerPairingToken) + swiftMinerPairingSucceeded = result.ok + swiftMinerPairingMessage = result.message + if result.ok { + swiftMinerPairingToken = "" + } + } label: { + Label("Pair with SwiftMiner", systemImage: "link") } - } label: { - Label("Pair with SwiftMiner", systemImage: "link") - } - .buttonStyle(.borderedProminent) + .buttonStyle(.borderedProminent) - Button { - let token = NSPasteboard.general.string(forType: .string) ?? "" - swiftMinerPairingToken = token - let result = app.applySwiftMinerPairingToken(token) - swiftMinerPairingSucceeded = result.ok - swiftMinerPairingMessage = result.message - if result.ok { - swiftMinerPairingToken = "" + Button { + let token = NSPasteboard.general.string(forType: .string) ?? "" + swiftMinerPairingToken = token + let result = app.applySwiftMinerPairingToken(token) + swiftMinerPairingSucceeded = result.ok + swiftMinerPairingMessage = result.message + if result.ok { + swiftMinerPairingToken = "" + } + } label: { + Label("Paste and Pair", systemImage: "doc.on.clipboard") } - } label: { - Label("Paste and Pair", systemImage: "doc.on.clipboard") + .buttonStyle(.bordered) + } + + if let swiftMinerPairingMessage { + Text(swiftMinerPairingMessage) + .font(.caption) + .foregroundStyle(swiftMinerPairingSucceeded ? .green : .red) } - .buttonStyle(.bordered) - } - if let swiftMinerPairingMessage { - Text(swiftMinerPairingMessage) + Text("Copy the pairing bundle from SwiftMiner > Integrations and paste it here.") .font(.caption) - .foregroundStyle(swiftMinerPairingSucceeded ? .green : .red) + .foregroundStyle(.secondary) } - - Text("Copy the pairing bundle from SwiftMiner > Integrations and paste it here.") - .font(.caption) - .foregroundStyle(.secondary) } } .disabled(app.isFailoverManagedNode) @@ -82,4 +94,40 @@ struct SwiftMinerPreferencesView: View { .labelsHidden() } } + + @ViewBuilder + private var swiftMinerArtwork: some View { + if let cachedURL = app.swiftMinerCachedArtworkURL(), + let image = NSImage(contentsOf: cachedURL) { + Image(nsImage: image) + .resizable() + .scaledToFill() + .frame(width: 32, height: 32) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + } else if let remoteURL = URL(string: app.settings.swiftMiner.artworkURL), + ["http", "https"].contains(remoteURL.scheme?.lowercased()) { + AsyncImage(url: remoteURL) { phase in + switch phase { + case .success(let image): + image + .resizable() + .scaledToFill() + default: + Image(systemName: "shippingbox.circle") + .resizable() + .scaledToFit() + .foregroundStyle(.secondary) + .padding(4) + } + } + .frame(width: 32, height: 32) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + } else { + Image(systemName: "shippingbox.circle") + .resizable() + .scaledToFit() + .foregroundStyle(.secondary) + .frame(width: 32, height: 32) + } + } } diff --git a/docs/beta/appcast.xml b/docs/beta/appcast.xml index ee5b36c9..960ae5ce 100644 --- a/docs/beta/appcast.xml +++ b/docs/beta/appcast.xml @@ -2,13 +2,5 @@ SwiftBot - - 1.9.6 - Sat, 14 Mar 2026 15:39:09 +1300 - 1940003 - 1.9.6 - 26.0 - - - \ No newline at end of file + diff --git a/docs/beta/release-notes/1.8.28.html b/docs/beta/release-notes/1.8.28.html deleted file mode 100644 index 99e1ab01..00000000 --- a/docs/beta/release-notes/1.8.28.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - v1.8.28 [beta] - Release Notes - - - -
-

v1.8.28 [beta]

-

Version 1.8.28

-

v1.8.28 [beta]

-

Commit: 163feb0

-
- - \ No newline at end of file diff --git a/docs/beta/release-notes/1.9.1.html b/docs/beta/release-notes/1.9.1.html deleted file mode 100644 index 1212fdee..00000000 --- a/docs/beta/release-notes/1.9.1.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - [Beta] - Last commit before merge - Release Notes - - - -
-

[Beta] - Last commit before merge

-

Version 1.9.1

-

[Beta] - Last commit before merge

-

Commit: 6c85d1c

-
- - \ No newline at end of file diff --git a/docs/beta/release-notes/1.9.5.html b/docs/beta/release-notes/1.9.5.html deleted file mode 100644 index b84a75e9..00000000 --- a/docs/beta/release-notes/1.9.5.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - [Beta] Fix Kernel Panic when videos are viewed from Linux - Release Notes - - - -
-

[Beta] Fix Kernel Panic when videos are viewed from Linux

-

Version 1.9.5

-

[Beta] Fix Kernel Panic when videos are viewed from Linux

-

Commit: 46f8f3e

-
- - \ No newline at end of file diff --git a/docs/beta/release-notes/1.9.6.html b/docs/beta/release-notes/1.9.6.html deleted file mode 100644 index d2709481..00000000 --- a/docs/beta/release-notes/1.9.6.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - [Beta] Ongoing Phase Changes - Release Notes - - - -
-

[Beta] Ongoing Phase Changes

-

Version 1.9.6

-

[Beta] Ongoing Phase Changes

-

Commit: 0a8ecd9

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.3.html b/docs/release-notes/1.3.html new file mode 100644 index 00000000..39137b16 --- /dev/null +++ b/docs/release-notes/1.3.html @@ -0,0 +1,121 @@ + + + + + + SwiftBot 1.3 - Release Notes + + + +
+

SwiftBot 1.3

+

Version 1.3

+

The first complete SwiftBot foundation release.

+
+

Native Discord Bot Foundation

+

The core macOS app, Discord runtime, and first-run setup came together here.

+
    +
  • Introduced the native SwiftUI control surface for running SwiftBot locally on macOS.
  • +
  • Added Discord bot onboarding, token validation, invite flow support, runtime status, and persistent app configuration.
  • +
  • Established the main navigation, dashboard cards, logs, command management, and diagnostics surfaces that later releases expanded.
  • +
  • Built the secure local settings model for bot credentials, server/channel targets, automation rules, and app state.
  • +
+
+
+

Automation, AI, and Patchy Foundations

+

This release set up the pieces that made SwiftBot more than a basic bot wrapper.

+
    +
  • Added the early automation rule engine for Discord events, responses, and configurable bot actions.
  • +
  • Laid the groundwork for local AI replies, WikiBridge lookups, Patchy update monitoring, and helper-bot workflows.
  • +
  • Introduced the first UpdateEngine and release-monitoring direction that later became the Patchy dashboard.
  • +
  • Prepared the project structure for multiple feature modules while keeping the first release usable as a single native app.
  • +
+
+
+

Self-Update and High Availability Prep

+

The release also started SwiftBot down the path toward being easier to ship and operate.

+
    +
  • Added the initial Sparkle self-update path and release publishing assumptions for distributing signed builds.
  • +
  • Started the high-availability and SwiftMesh groundwork so SwiftBot could eventually coordinate more than one running node.
  • +
  • Captured the first operational patterns for appcasts, versioning, release notes, and signed downloadable builds.
  • +
+
+ +
+ + diff --git a/docs/release-notes/1.4.4.html b/docs/release-notes/1.4.4.html index 02312fd0..ea2252d6 100644 --- a/docs/release-notes/1.4.4.html +++ b/docs/release-notes/1.4.4.html @@ -3,47 +3,109 @@ - Code Audit - Release Notes + SwiftBot 1.4.4 - Release Notes
-

Code Audit

+

SwiftBot 1.4.4

Version 1.4.4

-

Code Audit

-

Re-factoring of code with Swift

-

Commit: a8a4c72

+

Patchy and UpdateEngine became a real monitoring workflow.

+
+

Patchy Monitoring

+

Patchy moved from early scaffolding into a usable update-monitoring area.

+
    +
  • Integrated the UpdateEngine monitor dashboard into the SwiftBot runtime.
  • +
  • Added source and target management for AMD, NVIDIA, Intel Arc, and Steam update checks.
  • +
  • Introduced scheduled polling, manual debug checks, and embed-first Discord delivery for update notifications.
  • +
  • Improved AI Bots UI and engine preference flow while adding native sidebar selection animation.
  • +
+
+
+

Release and Signing Fixes

+

A practical polish pass tightened the first published builds.

+
    +
  • Fixed notarization and signing issues for release distribution.
  • +
  • Corrected build/version metadata so published packages and appcast entries lined up cleanly.
  • +
  • Improved AMD section rendering and Intel Arc thumbnail handling in update summaries.
  • +
+
+
- \ No newline at end of file + diff --git a/docs/release-notes/1.5.1.html b/docs/release-notes/1.5.1.html index aa0ae3a3..a22db815 100644 --- a/docs/release-notes/1.5.1.html +++ b/docs/release-notes/1.5.1.html @@ -3,47 +3,98 @@ - PatchBot UI Update - Release Notes + SwiftBot 1.5.1 - Release Notes
-

PatchBot UI Update

+

SwiftBot 1.5.1

Version 1.5.1

-

PatchBot UI Update

-

Fixed issue with cards not displaying correctly

-

Commit: 0b6381f

+

A focused Patchy UI maintenance release.

+
+

Patchy Card Fixes

+

This release cleaned up display problems in the Patchy experience.

+
    +
  • Fixed Patchy cards that were not displaying correctly.
  • +
  • Improved visual consistency for the update-monitoring dashboard after the 1.4 series work.
  • +
+
+
- \ No newline at end of file + diff --git a/docs/release-notes/1.6.1.html b/docs/release-notes/1.6.1.html deleted file mode 100644 index 7d26523e..00000000 --- a/docs/release-notes/1.6.1.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Fix swift build errors - Release Notes - - - -
-

Fix swift build errors

-

Version 1.6.1

-

Fix swift build errors

-

Commit: c36fcc1

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.6.2.html b/docs/release-notes/1.6.2.html index 1c6c16cc..416efe31 100644 --- a/docs/release-notes/1.6.2.html +++ b/docs/release-notes/1.6.2.html @@ -3,46 +3,107 @@ - Updated Wikibridge Logic - Release Notes + SwiftBot 1.6.2 - Release Notes
-

Updated Wikibridge Logic

+

SwiftBot 1.6.2

Version 1.6.2

-

Updated Wikibridge Logic

-

Commit: f0fe2b3

+

WikiBridge and menu logic received a practical cleanup pass.

+
+

WikiBridge Improvements

+

Wiki lookup behavior and surrounding UI flows were tightened.

+
    +
  • Updated WikiBridge logic for more reliable lookup behavior.
  • +
  • Refined WikiBot-related flows and general UI handling around the feature.
  • +
  • Adjusted the menu structure to make the growing app easier to navigate.
  • +
+
+
+

Build Fixes

+

The release also cleaned up Swift build issues found during the 1.6 line.

+
    +
  • Fixed Swift build errors introduced during the WikiBridge and menu updates.
  • +
  • Kept the appcast and version metadata current for the retained 1.6 release.
  • +
+
+
- \ No newline at end of file + diff --git a/docs/release-notes/1.6.html b/docs/release-notes/1.6.html deleted file mode 100644 index 2ddceabe..00000000 --- a/docs/release-notes/1.6.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Merge branch 'main' of https://github.com/johnwatso/SwiftBot - Release Notes - - - -
-

Merge branch 'main' of https://github.com/johnwatso/SwiftBot

-

Version 1.6

-

Merge branch 'main' of https://github.com/johnwatso/SwiftBot

-

Commit: a2125c5

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.7.2.html b/docs/release-notes/1.7.2.html deleted file mode 100644 index c6c17659..00000000 --- a/docs/release-notes/1.7.2.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - SwiftMesh Improvements - Release Notes - - - -
-

SwiftMesh Improvements

-

Version 1.7.2

-

SwiftMesh Improvements

-

Improved Worker / Leader Relationship management. This feature is still buggy and should be used with caution

-

Commit: 6212c36

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.7.211.html b/docs/release-notes/1.7.211.html deleted file mode 100644 index e8446941..00000000 --- a/docs/release-notes/1.7.211.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - SwiftMesh Detection Logic improvements - Release Notes - - - -
-

SwiftMesh Detection Logic improvements

-

Version 1.7.211

-

SwiftMesh Detection Logic improvements

-

ongoing build will be buggy

-

Commit: d86621e

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.7.212.html b/docs/release-notes/1.7.212.html deleted file mode 100644 index 1d4e3c74..00000000 --- a/docs/release-notes/1.7.212.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Update project.pbxproj - Release Notes - - - -
-

Update project.pbxproj

-

Version 1.7.212

-

Update project.pbxproj

-

Commit: cae986e

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.7.213.html b/docs/release-notes/1.7.213.html deleted file mode 100644 index f2116586..00000000 --- a/docs/release-notes/1.7.213.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - AI Improvement - Release Notes - - - -
-

AI Improvement

-

Version 1.7.213

-

AI Improvement

-

Improvements to Ai replies

-

Commit: 22c39e4

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.7.217.html b/docs/release-notes/1.7.217.html deleted file mode 100644 index 482cbb6a..00000000 --- a/docs/release-notes/1.7.217.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v 1.7.217 - Release Notes - - - -
-

v 1.7.217

-

Version 1.7.217

-

v 1.7.217

-

Fix ShipHook build by migrating back to .xcodeproj from .swiftpackage

-

Commit: 291bbc4

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.7.218.html b/docs/release-notes/1.7.218.html index c2e4e503..de68dc40 100644 --- a/docs/release-notes/1.7.218.html +++ b/docs/release-notes/1.7.218.html @@ -3,47 +3,108 @@ - v 1.7.218 - Release Notes + SwiftBot 1.7.218 - Release Notes
-

v 1.7.218

+

SwiftBot 1.7.218

Version 1.7.218

-

v 1.7.218

-

UI Overhaul

-

Commit: 741e24c

+

SwiftMesh arrived, then hardened quickly.

+
+

SwiftMesh Foundation

+

The 1.7 line introduced distributed SwiftBot operation.

+
    +
  • Added the first SwiftMesh implementation for multi-node bot coordination.
  • +
  • Improved mesh detection, helper-bot logic, failover behavior, and leader/worker awareness across the 1.7 series.
  • +
  • Updated documentation and planning notes around the new distributed runtime model.
  • +
+
+
+

UI Overhaul

+

The final retained 1.7 release brought a broader visual refresh.

+
    +
  • Delivered a SwiftBot UI overhaul across the main app surfaces.
  • +
  • Prepared room for future feature areas while making existing controls easier to scan.
  • +
  • Polished the app structure after the first SwiftMesh feature work landed.
  • +
+
+
- \ No newline at end of file + diff --git a/docs/release-notes/1.7.html b/docs/release-notes/1.7.html deleted file mode 100644 index 2aa09db7..00000000 --- a/docs/release-notes/1.7.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Introduction of SwiftMesh - Release Notes - - - -
-

Introduction of SwiftMesh

-

Version 1.7

-

Introduction of SwiftMesh

-

SwiftMesh is designed to keep two or more instances of Swiftbot in Sync. In the event that one Instance Fails, the other Instances will take over. This is an ongoing project so bugs may be present.

-

Commit: 1403626

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.0.html b/docs/release-notes/1.8.0.html deleted file mode 100644 index 14b50021..00000000 --- a/docs/release-notes/1.8.0.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Updated Build Version / Number - Release Notes - - - -
-

Updated Build Version / Number

-

Version 1.8.0

-

Updated Build Version / Number

-

Initial P0 Phase is complete

-

Commit: 00313e9

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.1.html b/docs/release-notes/1.8.1.html deleted file mode 100644 index 41955af0..00000000 --- a/docs/release-notes/1.8.1.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Updated Version Number + Prep for Upcomming music bot - Release Notes - - - -
-

Updated Version Number + Prep for Upcomming music bot

-

Version 1.8.1

-

Updated Version Number + Prep for Upcomming music bot

-

Commit: 6a8c7c7

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.11.html b/docs/release-notes/1.8.11.html deleted file mode 100644 index 998a3ce3..00000000 --- a/docs/release-notes/1.8.11.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Add Discord bug tracking system - Release Notes - - - -
-

Add Discord bug tracking system

-

Version 1.8.11

-

Add Discord bug tracking system

-

Commit: bc9b17a

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.12.html b/docs/release-notes/1.8.12.html deleted file mode 100644 index 47b1dcad..00000000 --- a/docs/release-notes/1.8.12.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Ongoing fixes - Release Notes - - - -
-

Ongoing fixes

-

Version 1.8.12

-

Ongoing fixes

-

Commit: d09ab0a

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.13.html b/docs/release-notes/1.8.13.html deleted file mode 100644 index b352a8e2..00000000 --- a/docs/release-notes/1.8.13.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - AI Reply Options under actions - Release Notes - - - -
-

AI Reply Options under actions

-

Version 1.8.13

-

AI Reply Options under actions

-

Commit: 62f7afa

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.14.html b/docs/release-notes/1.8.14.html deleted file mode 100644 index 1e551bc3..00000000 --- a/docs/release-notes/1.8.14.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - WebGUI Support - Release Notes - - - -
-

WebGUI Support

-

Version 1.8.14

-

WebGUI Support

-

Commit: 50c06b7

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.15.html b/docs/release-notes/1.8.15.html deleted file mode 100644 index a176f23f..00000000 --- a/docs/release-notes/1.8.15.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Improved Bot Security - Release Notes - - - -
-

Improved Bot Security

-

Version 1.8.15

-

Improved Bot Security

-

Swiftbot now places tokens in Keychain instead of plain text for the shared secret and open AI API

-

Commit: 52f47dd

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.16.html b/docs/release-notes/1.8.16.html deleted file mode 100644 index f8070f86..00000000 --- a/docs/release-notes/1.8.16.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Resolve Risk Matrix Items: Security, CI, AI Reliability, UI Refactor, Cost Control - Release Notes - - - -
-

Resolve Risk Matrix Items: Security, CI, AI Reliability, UI Refactor, Cost Control

-

Version 1.8.16

-

Resolve Risk Matrix Items: Security, CI, AI Reliability, UI Refactor, Cost Control

-

Commit: 67a8ba8

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.18.html b/docs/release-notes/1.8.18.html deleted file mode 100644 index 08e6d0cc..00000000 --- a/docs/release-notes/1.8.18.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v1.8.18 - Release Notes - - - -
-

v1.8.18

-

Version 1.8.18

-

v1.8.18

-

- webUI overhaul
- UI changes
- no time for patch notes, otherwise may be killed

-

Commit: 3e97ec0

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.2.html b/docs/release-notes/1.8.2.html deleted file mode 100644 index 83edcbad..00000000 --- a/docs/release-notes/1.8.2.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Updated Splashscreen - Release Notes - - - -
-

Updated Splashscreen

-

Version 1.8.2

-

Updated Splashscreen

-

Commit: 935e44f

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.20.html b/docs/release-notes/1.8.20.html deleted file mode 100644 index 48398a26..00000000 --- a/docs/release-notes/1.8.20.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v1.8.19 - Release Notes - - - -
-

v1.8.19

-

Version 1.8.20

-

v1.8.19

-

Added auto-fix
Fixed Settings layout

-

Commit: a20f553

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.21.html b/docs/release-notes/1.8.21.html deleted file mode 100644 index 51c0cf0f..00000000 --- a/docs/release-notes/1.8.21.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v1.18.21 - Release Notes - - - -
-

v1.18.21

-

Version 1.8.21

-

v1.18.21

-

- SwiftMesh now works
- Syncs config between Primary and Failover
- WebUI updates
- General UI updates

-

Commit: 5c248f4

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.22.html b/docs/release-notes/1.8.22.html deleted file mode 100644 index f59738c2..00000000 --- a/docs/release-notes/1.8.22.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v.1.8.22 - Release Notes - - - -
-

v.1.8.22

-

Version 1.8.22

-

v.1.8.22

-

fix swiftmesh
small ui fixes

-

Commit: a78b87d

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.23.html b/docs/release-notes/1.8.23.html deleted file mode 100644 index be571253..00000000 --- a/docs/release-notes/1.8.23.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v1.822 - Release Notes - - - -
-

v1.822

-

Version 1.8.23

-

v1.822

-

fix for badly parsed header

-

Commit: 26470f8

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.24.html b/docs/release-notes/1.8.24.html deleted file mode 100644 index c7823ca4..00000000 --- a/docs/release-notes/1.8.24.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v 1.8.24 - Release Notes - - - -
-

v 1.8.24

-

Version 1.8.24

-

v 1.8.24

-

please fix swiftmesh

-

Commit: 8b5efe0

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.25.html b/docs/release-notes/1.8.25.html deleted file mode 100644 index d0f4dfb5..00000000 --- a/docs/release-notes/1.8.25.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Fix for Settings GUI - Release Notes - - - -
-

Fix for Settings GUI

-

Version 1.8.25

-

Fix for Settings GUI

-

Not a new Build - Still needs testing before new build number etc WIP

-

Commit: 2d5a0b9

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.27.html b/docs/release-notes/1.8.27.html deleted file mode 100644 index be5e9990..00000000 --- a/docs/release-notes/1.8.27.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Beta Build of SwiftBot - Release Notes - - - -
-

Beta Build of SwiftBot

-

Version 1.8.27

-

Beta Build of SwiftBot

-

Improved Settings Page
Fun Easter Egg
General AI Bot UI Imrpovements (restored from previous git)

-

Commit: a60c32e

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.31.html b/docs/release-notes/1.8.31.html index 99551d82..f191dda5 100644 --- a/docs/release-notes/1.8.31.html +++ b/docs/release-notes/1.8.31.html @@ -3,47 +3,117 @@ - Update to SwiftBot - Release Notes + SwiftBot 1.8.31 - Release Notes
-

Update to SwiftBot

+

SwiftBot 1.8.31

Version 1.8.31

-

Update to SwiftBot

-

No longer on Beta Build Status

-

Commit: 384b1b2

+

The large Web UI, actions, security, and mesh stabilization cycle graduated from beta.

+
+

Web UI and Actions

+

The 1.8 line made SwiftBot manageable beyond the local window.

+
    +
  • Added Web UI support, Cloudflare/HTTPS onboarding work, and remote management preparation.
  • +
  • Expanded action handling, command visibility, AI reply options, and bug-tracking workflows.
  • +
  • Moved settings into their own pane and continued cleaning up the main app navigation.
  • +
+
+
+

SwiftMesh Stabilization

+

Distributed operation became more reliable and easier to diagnose.

+
    +
  • Improved WAN SwiftMesh behavior, mesh status checks, failover detection, and worker/leader coordination.
  • +
  • Added planning and risk documentation for the mesh architecture and operational model.
  • +
  • Introduced stronger security, cost-control, and repository-hygiene work around the production app.
  • +
+
+
+

Beta Graduation

+

This retained release marks the 1.8 work as stable.

+
    +
  • Moved the release out of beta build status.
  • +
  • Rolled up fixes for AI Bot views, settings UI, splash screen behavior, and app imagery.
  • +
  • Kept the appcast on the stable channel after the 1.8 beta iterations completed.
  • +
+
+
- \ No newline at end of file + diff --git a/docs/release-notes/1.8.4.html b/docs/release-notes/1.8.4.html deleted file mode 100644 index b4804fa4..00000000 --- a/docs/release-notes/1.8.4.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v1.8.4 - Release Notes - - - -
-

v1.8.4

-

Version 1.8.4

-

v1.8.4

-

- UI tweaks
- Lots of other stuff

-

Commit: b242bef

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.5.html b/docs/release-notes/1.8.5.html deleted file mode 100644 index 51eeca05..00000000 --- a/docs/release-notes/1.8.5.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - SwiftMesh Imrpovements - Release Notes - - - -
-

SwiftMesh Imrpovements

-

Version 1.8.5

-

SwiftMesh Imrpovements

-

Failover Support is now working.
Known Issues:
No settings Sync
Primary Doesn't talk to Failover / Worker Node
On recovery Primary doesn't downgrade its role.
No visability is synced via the node map back to the worker / failover
Port box doesn't work, and there IP:PORTNUMBER should be used in the URL field

-

Commit: e4d15c2

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.6.html b/docs/release-notes/1.8.6.html deleted file mode 100644 index 09e16f34..00000000 --- a/docs/release-notes/1.8.6.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Intial Visualisation of Commands - Release Notes - - - -
-

Intial Visualisation of Commands

-

Version 1.8.6

-

Intial Visualisation of Commands

-

Added the ability to See commands from within the GUI

-

Commit: 2fa6cf7

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.7.html b/docs/release-notes/1.8.7.html deleted file mode 100644 index 844fdb74..00000000 --- a/docs/release-notes/1.8.7.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Fixed WAN Swift Mesh issue - Release Notes - - - -
-

Fixed WAN Swift Mesh issue

-

Version 1.8.7

-

Fixed WAN Swift Mesh issue

-

Swiftmesh will now allow failover istances over WAN

-

Commit: e721da9

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.8.html b/docs/release-notes/1.8.8.html deleted file mode 100644 index 34f1a0ae..00000000 --- a/docs/release-notes/1.8.8.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v 1.8.8 - Release Notes - - - -
-

v 1.8.8

-

Version 1.8.8

-

v 1.8.8

-

SwiftMesh upgrades/bug fixes

-

Commit: 48cb449

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.8.9.html b/docs/release-notes/1.8.9.html deleted file mode 100644 index 6f89340a..00000000 --- a/docs/release-notes/1.8.9.html +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - API Clearing / Patchy Improvements - Release Notes - - - -
-

API Clearing / Patchy Improvements

-

Version 1.8.9

-

API Clearing / Patchy Improvements

-

Clearing the API no longer sends you back to the Splash Screen. Users can now opt in to running the splash screen setup again.

-

Patchy should now no longer spam Updates on Restart.

-

Commit: 7a035ff

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.9.0.html b/docs/release-notes/1.9.0.html deleted file mode 100644 index 83c3f738..00000000 --- a/docs/release-notes/1.9.0.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - HTTPS / OAUTH Support - Release Notes - - - -
-

HTTPS / OAUTH Support

-

Version 1.9.0

-

HTTPS / OAUTH Support

-

SwiftBot Now Supports HTTPS via Cloudfare API
OAUTH Support for Discord via discord API
Improvements to UI

-

Commit: b806158

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.9.1.html b/docs/release-notes/1.9.1.html deleted file mode 100644 index 79cd9c59..00000000 --- a/docs/release-notes/1.9.1.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Chore: Uploading WebUI Image - Release Notes - - - -
-

Chore: Uploading WebUI Image

-

Version 1.9.1

-

Chore: Uploading WebUI Image

-

This will be entered into the readme

-

Commit: 3c0fda8

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.9.2.html b/docs/release-notes/1.9.2.html deleted file mode 100644 index 46029d32..00000000 --- a/docs/release-notes/1.9.2.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v1.9.2 - Release Notes - - - -
-

v1.9.2

-

Version 1.9.2

-

v1.9.2

-

- Added Recordings feature, should work via SwiftMesh too. Connect to a local NAS and the recordings will show in the webUI!
- Added manual webUI auth fallback
- Fixed all project warnings, a lot of race conditions present

-

Commit: cf693d3

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.9.3.html b/docs/release-notes/1.9.3.html deleted file mode 100644 index 92341194..00000000 --- a/docs/release-notes/1.9.3.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v1.9.3 - Release Notes - - - -
-

v1.9.3

-

Version 1.9.3

-

v1.9.3

-

- Slight adjustment to fix whitespace in recording paths
- Also fixed remote playback issues (hopefully)

-

Commit: 66b5ab6

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.9.4.html b/docs/release-notes/1.9.4.html deleted file mode 100644 index 03622f8f..00000000 --- a/docs/release-notes/1.9.4.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - v1.9.4 - Release Notes - - - -
-

v1.9.4

-

Version 1.9.4

-

v1.9.4

-

- Addition of Recording Editor (VERY BETA, needs a lot of polish)
- More Remote Playback fixes

-

Commit: cc7fe3a

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.9.6.html b/docs/release-notes/1.9.6.html deleted file mode 100644 index f0756949..00000000 --- a/docs/release-notes/1.9.6.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Introduction of Analytics Tab - Release Notes - - - -
-

Introduction of Analytics Tab

-

Version 1.9.6

-

Introduction of Analytics Tab

-

Commit: d3b8914

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.9.7.html b/docs/release-notes/1.9.7.html deleted file mode 100644 index a03be489..00000000 --- a/docs/release-notes/1.9.7.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Memory Leak Fix - Release Notes - - - -
-

Memory Leak Fix

-

Version 1.9.7

-

Memory Leak Fix

-

Fixes issue where a memory leak will occur when viewing videos back via FireFox on linux
Also improved discord sign in on Firfox

-

Commit: 7fe0974

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.9.71.html b/docs/release-notes/1.9.71.html deleted file mode 100644 index ae8df5fb..00000000 --- a/docs/release-notes/1.9.71.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - Patchy Fix - Release Notes - - - -
-

Patchy Fix

-

Version 1.9.71

-

Patchy Fix

-

AMD Driver updates parse correctly now.

-

Commit: 2652226

-
- - \ No newline at end of file diff --git a/docs/release-notes/1.9.8.html b/docs/release-notes/1.9.8.html index fe5b1d8f..c64a167a 100644 --- a/docs/release-notes/1.9.8.html +++ b/docs/release-notes/1.9.8.html @@ -3,47 +3,109 @@ - v1.98 - Release Notes + SwiftBot 1.9.8 - Release Notes
-

v1.98

+

SwiftBot 1.9.8

Version 1.9.8

-

v1.98

-

- Added /music command & /playlist command
- /playlist defaults to worker bot
Supported sources:
Apple Music playlists
Spotify playlists
YouTube / YouTube Music playlists

-

Commit: c8df274

+

Music and playlist commands landed on top of the refactored runtime.

+
+

Music and Playlists

+

SwiftBot gained first-class music-link and playlist workflows.

+
    +
  • Added the /music command for music lookup and sharing workflows.
  • +
  • Added the /playlist command with worker-bot routing by default.
  • +
  • Added playlist support for Apple Music, Spotify, YouTube, and YouTube Music sources.
  • +
+
+
+

Runtime Hardening

+

The 1.9 line also carried a substantial stability and maintainability pass.

+
    +
  • Hardened Patchy AMD release-note fetching and fixed parsing regressions.
  • +
  • Fixed media playback memory behavior on Linux/Firefox viewing paths.
  • +
  • Added analytics, audio-sync fixes, online-time indicators, and post-refactor bug fixes.
  • +
  • Carried forward the large code refactor that split models, services, command processing, gateway transport, and Web UI handling into smaller pieces.
  • +
+
+
- \ No newline at end of file + diff --git a/project.yml b/project.yml index 5883048e..1938d048 100644 --- a/project.yml +++ b/project.yml @@ -87,7 +87,7 @@ targets: ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS: NO COMBINE_HIDPI_IMAGES: YES CURRENT_PROJECT_VERSION: "196000" - MARKETING_VERSION: "1.9.6" + MARKETING_VERSION: "1.9.9" DEVELOPMENT_TEAM: "" CODE_SIGN_STYLE: Manual PROVISIONING_PROFILE_SPECIFIER: "" From c95946b3e3f2fb1a82923a37dfec4f8de28cdfa6 Mon Sep 17 00:00:00 2001 From: johnwatso Date: Thu, 7 May 2026 19:55:20 +1200 Subject: [PATCH 09/41] Integrate SwiftMiner Discord linking --- SwiftBotApp/AppModel+AdminWeb.swift | 2 +- SwiftBotApp/AppModel+Commands.swift | 17 +++ SwiftBotApp/AppModel+DiscordEvents.swift | 11 ++ SwiftBotApp/AppModel+Gateway.swift | 114 ++++++++++++++++---- SwiftBotApp/AppModel+SwiftMiner.swift | 13 +++ SwiftBotApp/Models/DiscordCache.swift | 27 +++++ SwiftBotApp/OverviewView.swift | 1 - SwiftBotApp/RootView.swift | 32 +++--- SwiftBotApp/Services/SwiftMinerClient.swift | 10 ++ 9 files changed, 190 insertions(+), 37 deletions(-) diff --git a/SwiftBotApp/AppModel+AdminWeb.swift b/SwiftBotApp/AppModel+AdminWeb.swift index 9b4824d8..01015798 100644 --- a/SwiftBotApp/AppModel+AdminWeb.swift +++ b/SwiftBotApp/AppModel+AdminWeb.swift @@ -1083,7 +1083,7 @@ extension AppModel { }, discordUsersProvider: { [weak self] in guard let model = self else { return [:] } - return await model.discordCache.allUserNames() + return await model.discordCache.humanUserNames() }, swiftMinerTestDMSender: { [weak self] discordUserId in guard let model = self else { return false } diff --git a/SwiftBotApp/AppModel+Commands.swift b/SwiftBotApp/AppModel+Commands.swift index 34194acd..0eb83114 100644 --- a/SwiftBotApp/AppModel+Commands.swift +++ b/SwiftBotApp/AppModel+Commands.swift @@ -2224,6 +2224,22 @@ extension AppModel { }() await discordCache.upsertUser(id: userID, preferredName: preferredName) + + // Flag bots and webhooks so the admin user picker can exclude non-human authors. + var isNonHuman = false + if map["webhook_id"] != nil { + isNonHuman = true + } + if case let .object(author)? = map["author"], author["bot"] == .bool(true) { + isNonHuman = true + } + if isNonHuman { + await discordCache.markBot(id: userID) + } else if guildID != nil { + // Author is a real user posting in a guild we're connected to → trusted member. + await discordCache.markGuildMember(id: userID) + } + await syncPublishedDiscordCacheFromService() scheduleDiscordCacheSave() } @@ -2528,6 +2544,7 @@ extension AppModel { func appendAssistantMessage(scope: MemoryScope, content: String) async { let assistantID = botUserId ?? "swiftbot" await discordCache.upsertUser(id: assistantID, preferredName: botUsername) + await discordCache.markBot(id: assistantID) await conversationStore.append( scope: scope, userID: assistantID, diff --git a/SwiftBotApp/AppModel+DiscordEvents.swift b/SwiftBotApp/AppModel+DiscordEvents.swift index 6b4e284c..2b7577dc 100644 --- a/SwiftBotApp/AppModel+DiscordEvents.swift +++ b/SwiftBotApp/AppModel+DiscordEvents.swift @@ -254,6 +254,11 @@ extension AppModel { case let .object(user)? = memberMap["user"], case let .string(userId)? = user["id"] { await discordCache.upsertUser(id: userId, preferredName: nick) + if user["bot"] == .bool(true) { + await discordCache.markBot(id: userId) + } else { + await discordCache.markGuildMember(id: userId) + } continue } @@ -269,6 +274,12 @@ extension AppModel { } else if case let .string(username)? = user["username"], !username.isEmpty { await discordCache.upsertUser(id: userId, preferredName: username) } + + if user["bot"] == .bool(true) { + await discordCache.markBot(id: userId) + } else { + await discordCache.markGuildMember(id: userId) + } } } diff --git a/SwiftBotApp/AppModel+Gateway.swift b/SwiftBotApp/AppModel+Gateway.swift index 465df406..22396306 100644 --- a/SwiftBotApp/AppModel+Gateway.swift +++ b/SwiftBotApp/AppModel+Gateway.swift @@ -433,6 +433,31 @@ extension AppModel { func handleInteractionCreate(_ event: GatewayInteractionCreateEvent) async { guard ActionDispatcher.canSend(clusterMode: settings.clusterMode, action: "respondToInteraction", log: { logs.append($0) }) else { return } let context = interactionContext(from: event.rawMap) + + // Safeguard: only allow interactions from users who share at least one connected guild + // with this bot. Guild-context interactions are pre-validated by Discord (the user must + // already be a guild member to invoke a slash command in that guild). DM-context + // interactions need an explicit check. + if event.interactionType == 2, !(await isInteractionAllowed(event: event, context: context)) { + do { + try await service.respondToInteraction( + interactionID: event.interactionID, + interactionToken: event.interactionToken, + payload: [ + "type": 4, + "data": [ + "content": "This bot can only be used by members of a server it's installed in.", + "flags": 64 // EPHEMERAL + ] + ] + ) + } catch { + logs.append("⚠️ Failed to reject unauthorized interaction: \(error.localizedDescription)") + } + logs.append("🚫 Rejected slash command from non-member user \(context.username)") + return + } + switch event.interactionType { case 2: let slashName = (event.commandName ?? "").lowercased() @@ -1379,22 +1404,41 @@ extension AppModel { clearedGlobalSlashCommands = false lastSlashCommandsEnabledState = slashEnabled } - let commands = buildSlashCommandDefinitions() + let allCommands = buildSlashCommandDefinitions() + // Commands that should also work in user DMs with the bot. Registered globally with + // `contexts: [0, 1]` (GUILD + BOT_DM) instead of per-guild. + let dmEnabledCommandNames: Set = ["miner"] + let dmEnabledCommands: [[String: Any]] = allCommands + .filter { ($0["name"] as? String).map { dmEnabledCommandNames.contains($0) } ?? false } + .map { cmd in + var enriched = cmd + enriched["contexts"] = [0, 1] // GUILD, BOT_DM + return enriched + } + let guildOnlyCommands = allCommands + .filter { !(($0["name"] as? String).map { dmEnabledCommandNames.contains($0) } ?? false) } + let now = Date() let guildIds = connectedServers.keys.sorted() - if !guildIds.isEmpty, !clearedGlobalSlashCommands { + // Push DM-enabled commands globally (also propagates to every guild the bot is in, + // so we exclude them from guild registration to avoid duplicates). + if lastSlashRegistrationAt == nil || now.timeIntervalSince(lastSlashRegistrationAt!) >= 300 { do { try await service.registerGlobalApplicationCommands( applicationID: appID, - commands: [], + commands: dmEnabledCommands, token: token ) clearedGlobalSlashCommands = true lastSlashRegistrationAt = now - logs.append("✅ Cleared global slash commands to avoid duplicates") + if slashEnabled, !dmEnabledCommands.isEmpty { + logs.append("✅ Registered \(dmEnabledCommands.count) DM-enabled slash command(s) globally") + } else if !slashEnabled { + logs.append("✅ Cleared global slash commands") + } } catch { - logs.append("⚠️ Failed clearing global slash commands: \(error.localizedDescription)") + logs.append("⚠️ Global slash command registration failed: \(error.localizedDescription)") } } @@ -1407,7 +1451,7 @@ extension AppModel { try await service.registerGuildApplicationCommands( applicationID: appID, guildID: guildId, - commands: commands, + commands: guildOnlyCommands, token: token ) lastSlashGuildRegistrationAt[guildId] = now @@ -1422,29 +1466,47 @@ extension AppModel { } else { logs.append("✅ Slash commands disabled and cleared for \(guildRegisteredCount) guild(s)") } - } else if guildIds.isEmpty, - lastSlashRegistrationAt == nil || now.timeIntervalSince(lastSlashRegistrationAt!) >= 300 { - do { - try await service.registerGlobalApplicationCommands( - applicationID: appID, - commands: commands, - token: token - ) - lastSlashRegistrationAt = now - if slashEnabled { - logs.append("✅ Slash commands registered globally (no guilds known yet)") - } else { - logs.append("✅ Slash commands disabled and cleared globally") - } - } catch { - logs.append("❌ Global slash command registration failed: \(error.localizedDescription)") - } } } typealias SlashContext = CommandProcessor.SlashContext typealias SlashResponsePayload = CommandProcessor.SlashResponsePayload + /// Returns `true` if the interaction's user is allowed to use this bot. + /// Guild interactions are trusted (Discord enforces guild membership). DM interactions + /// must come from a user who is a member of at least one connected guild — verified + /// against the cache, with a REST fallback that populates the cache on hit. + private func isInteractionAllowed(event: GatewayInteractionCreateEvent, context: SlashContext) async -> Bool { + // Guild-context interactions: Discord guarantees the user is a guild member. + if guildId(from: event.rawMap) != nil { + return true + } + + // Pull the invoking user ID from the DM-style payload. + var userId: String? + if case let .object(user)? = event.rawMap["user"], case let .string(id)? = user["id"] { + userId = id + } + guard let userId, !userId.isEmpty else { return false } + + // Fast path: cache says they're a known guild member. + if await discordCache.isGuildMember(id: userId) { + return true + } + + // Cache miss: verify against each connected guild via REST. Cache the result on hit. + let token = settings.token.trimmingCharacters(in: .whitespacesAndNewlines) + guard !token.isEmpty else { return false } + let guildIds = connectedServers.keys + for guildId in guildIds { + if await guildRESTClient.fetchGuildMemberRoleIDs(guildID: guildId, userID: userId, token: token) != nil { + await discordCache.markGuildMember(id: userId) + return true + } + } + return false + } + func interactionContext(from map: [String: DiscordJSON]) -> SlashContext { let channelId: String = { if case let .string(id)? = map["channel_id"] { return id } @@ -1602,6 +1664,9 @@ extension AppModel { func voiceDisplayName(from map: [String: DiscordJSON], userId: String) async -> String { if case let .object(member)? = map["member"] { + if case let .object(memberUser)? = member["user"], memberUser["bot"] == .bool(true) { + await discordCache.markBot(id: userId) + } if case let .string(nick)? = member["nick"], !nick.isEmpty { await discordCache.upsertUser(id: userId, preferredName: nick) return nick @@ -1620,6 +1685,9 @@ extension AppModel { } if case let .object(user)? = map["user"] { + if user["bot"] == .bool(true) { + await discordCache.markBot(id: userId) + } if case let .string(globalName)? = user["global_name"], !globalName.isEmpty { await discordCache.upsertUser(id: userId, preferredName: globalName) return globalName diff --git a/SwiftBotApp/AppModel+SwiftMiner.swift b/SwiftBotApp/AppModel+SwiftMiner.swift index beba0011..7259a18f 100644 --- a/SwiftBotApp/AppModel+SwiftMiner.swift +++ b/SwiftBotApp/AppModel+SwiftMiner.swift @@ -83,6 +83,19 @@ extension AppModel { } } + func fetchSwiftMinerRegisteredUsers() async -> [String: String] { + let client = SwiftMinerClient(settings: settings.swiftMiner, session: discordRESTSession) + let cacheNames = await discordCache.allUserNames() + guard let ids = try? await client.registeredUserIds() else { + return cacheNames + } + var result: [String: String] = [:] + for id in ids { + result[id] = cacheNames[id] ?? id + } + return result + } + func sendSwiftMinerTestDM(to discordUserId: String) async -> Bool { guard settings.swiftMiner.enabled else { return false } let content = """ diff --git a/SwiftBotApp/Models/DiscordCache.swift b/SwiftBotApp/Models/DiscordCache.swift index 9a1109bf..5fbbf1c5 100644 --- a/SwiftBotApp/Models/DiscordCache.swift +++ b/SwiftBotApp/Models/DiscordCache.swift @@ -8,6 +8,8 @@ struct DiscordCacheSnapshot: Codable, Hashable { var availableRolesByServer: [String: [GuildRole]] = [:] var usernamesById: [String: String] = [:] var channelTypesById: [String: Int] = [:] + var botUserIds: Set = [] + var guildMemberIds: Set = [] private enum CodingKeys: String, CodingKey { case updatedAt @@ -17,6 +19,8 @@ struct DiscordCacheSnapshot: Codable, Hashable { case availableRolesByServer case usernamesById case channelTypesById + case botUserIds + case guildMemberIds } init() {} @@ -30,6 +34,8 @@ struct DiscordCacheSnapshot: Codable, Hashable { availableRolesByServer = try container.decodeIfPresent([String: [GuildRole]].self, forKey: .availableRolesByServer) ?? [:] usernamesById = try container.decodeIfPresent([String: String].self, forKey: .usernamesById) ?? [:] channelTypesById = try container.decodeIfPresent([String: Int].self, forKey: .channelTypesById) ?? [:] + botUserIds = try container.decodeIfPresent(Set.self, forKey: .botUserIds) ?? [] + guildMemberIds = try container.decodeIfPresent(Set.self, forKey: .guildMemberIds) ?? [] } } @@ -127,6 +133,27 @@ actor DiscordCache { snapshot.usernamesById } + /// Returns only Discord users not flagged as bots/webhooks. + func humanUserNames() -> [String: String] { + snapshot.usernamesById.filter { !snapshot.botUserIds.contains($0.key) } + } + + func markBot(id userID: String) { + guard !snapshot.botUserIds.contains(userID) else { return } + snapshot.botUserIds.insert(userID) + emitUpdate() + } + + func markGuildMember(id userID: String) { + guard !snapshot.guildMemberIds.contains(userID) else { return } + snapshot.guildMemberIds.insert(userID) + emitUpdate() + } + + func isGuildMember(id userID: String) -> Bool { + snapshot.guildMemberIds.contains(userID) + } + func upsertGuild(id guildID: String, name: String?) { let fallback = "Server \(guildID.suffix(4))" let candidate = (name ?? "").trimmingCharacters(in: .whitespacesAndNewlines) diff --git a/SwiftBotApp/OverviewView.swift b/SwiftBotApp/OverviewView.swift index d6e661a5..fbc9df66 100644 --- a/SwiftBotApp/OverviewView.swift +++ b/SwiftBotApp/OverviewView.swift @@ -478,7 +478,6 @@ struct OverviewView: View { .padding(.horizontal, 16) .padding(.top, 10) .padding(.bottom, 16) - .background(SwiftBotGlassBackground().opacity(0.55)) } .onAppear { syncDashboardPreferences() diff --git a/SwiftBotApp/RootView.swift b/SwiftBotApp/RootView.swift index 9b3c6d97..a7d155af 100644 --- a/SwiftBotApp/RootView.swift +++ b/SwiftBotApp/RootView.swift @@ -75,7 +75,6 @@ struct UnifiedRootView: View { } } .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(SwiftBotGlassBackground()) } .ignoresSafeArea(.container, edges: .top) .background(SwiftBotGlassBackground()) @@ -510,18 +509,27 @@ private struct SidebarInfoRow: View { } private struct SwiftBotSidebarMaterialBackground: View { + @Environment(\.colorScheme) private var colorScheme + var body: some View { - SwiftBotVisualEffectMaterialView(material: .sidebar) - .overlay { - LinearGradient( - colors: [ - Color.white.opacity(0.08), - Color.clear - ], - startPoint: .topLeading, - endPoint: .bottomTrailing - ) - } + ZStack { + Color(nsColor: colorScheme == .dark ? .black : .windowBackgroundColor) + .opacity(colorScheme == .dark ? 0.38 : 0.44) + + SwiftBotVisualEffectMaterialView(material: .sidebar) + + LinearGradient( + colors: [ + Color.white.opacity(0.08), + Color.clear + ], + startPoint: .topLeading, + endPoint: .bottomTrailing + ) + + Color(nsColor: colorScheme == .dark ? .controlBackgroundColor : .windowBackgroundColor) + .opacity(colorScheme == .dark ? 0.18 : 0.24) + } } } diff --git a/SwiftBotApp/Services/SwiftMinerClient.swift b/SwiftBotApp/Services/SwiftMinerClient.swift index 679226f4..a322e83f 100644 --- a/SwiftBotApp/Services/SwiftMinerClient.swift +++ b/SwiftBotApp/Services/SwiftMinerClient.swift @@ -119,6 +119,16 @@ struct SwiftMinerClient { return try decoder.decode(SwiftMinerActivationSession.self, from: data) } + func registeredUserIds() async throws -> [String] { + let data = try await request(path: "/v1/users", method: "GET") + struct User: Decodable { + let discordId: String + enum CodingKeys: String, CodingKey { case discordId = "discord_id" } + } + struct Response: Decodable { let users: [User] } + return try JSONDecoder().decode(Response.self, from: data).users.map(\.discordId) + } + func ignoreCampaign(discordUserId: String, campaignId: String, scope: String) async throws { struct Body: Encodable { let scope: String } _ = try await request( From c9660fe8fbf723e028354d88512739b2932f3259 Mon Sep 17 00:00:00 2001 From: johnwatso Date: Thu, 7 May 2026 21:10:10 +1200 Subject: [PATCH 10/41] Polish SwiftMiner setup DM and docs --- AI_GUIDE.md | 2 - ARCHITECTURE_ANALYSIS_REPORT.md | 639 ----------------------- ARCHITECTURE_ANALYSIS_REPORT_PDF.txt | 719 -------------------------- CHANGELOG.md | 437 ---------------- README.md | 2 - RISK_MATRIX.md | 54 -- SwiftBotApp/AdminWebServer.swift | 14 +- SwiftBotApp/AppModel+AdminWeb.swift | 4 +- SwiftBotApp/AppModel+SwiftMiner.swift | 58 ++- SwiftBotApp/DiscordService.swift | 12 + docs/ web-ui-setup.md | 310 ----------- extract_eventbus.py | 30 -- notes/link-converter.md | 191 ------- notes/swiftmesh-risk-matrix.md | 2 +- 14 files changed, 75 insertions(+), 2399 deletions(-) delete mode 100644 ARCHITECTURE_ANALYSIS_REPORT.md delete mode 100644 ARCHITECTURE_ANALYSIS_REPORT_PDF.txt delete mode 100644 CHANGELOG.md delete mode 100644 RISK_MATRIX.md delete mode 100644 docs/ web-ui-setup.md delete mode 100644 extract_eventbus.py delete mode 100644 notes/link-converter.md diff --git a/AI_GUIDE.md b/AI_GUIDE.md index bacd215d..93becba3 100644 --- a/AI_GUIDE.md +++ b/AI_GUIDE.md @@ -342,7 +342,6 @@ Binding( When modifying this project, update these files: -- [ ] **CHANGELOG.md** - Document what changed and why - [ ] **This file** - If you discover new patterns or gotchas - [ ] **ARCHITECTURE.md** - If you change core architecture @@ -435,7 +434,6 @@ Before marking changes complete: - [ ] Modified features work as expected - [ ] Existing features still work (no regressions) - [ ] Settings persist across restart -- [ ] CHANGELOG.md updated - [ ] No console errors or warnings ## Resources diff --git a/ARCHITECTURE_ANALYSIS_REPORT.md b/ARCHITECTURE_ANALYSIS_REPORT.md deleted file mode 100644 index 1e9261a5..00000000 --- a/ARCHITECTURE_ANALYSIS_REPORT.md +++ /dev/null @@ -1,639 +0,0 @@ -# SwiftBot Architecture Analysis Report - -**Date:** 14 March 2026 -**Repository:** SwiftBot -**Platform:** Native macOS (Swift + SwiftUI) -**Analysis Scope:** Full codebase review for architectural improvements - ---- - -## Executive Summary - -This analysis identifies **significant opportunities** for architectural improvement in the SwiftBot codebase while maintaining identical user-visible functionality. The review focused on efficiency, maintainability, extensibility, concurrency safety, and alignment with Apple platform best practices. - -### Key Findings at a Glance - -| Category | Issues Found | Severity | -|----------|-------------|----------| -| Duplicate Execution Paths | 3 | 🔴 High | -| MainActor Overuse | 2 | 🔴 High | -| Memory Retention Risks | 6 | 🔴 High | -| Cluster Safety Gaps | 3 | 🔴 High | -| God Classes | 3 | 🟡 Medium | -| Async Pipeline Bottlenecks | 2 | 🟡 Medium | -| Networking Inefficiencies | 2 | 🟡 Medium | -| Excess Logging | 2 | 🟢 Low | -| Dead Code / Legacy | 3 | 🟢 Low | - -### Impact Assessment - -- **Performance:** MainActor bottlenecks and sequential AI processing add 10-30s latency during peak loads -- **Memory:** Unbounded caches risk unbounded growth during extended operation -- **Safety:** Cluster mode isolation relies on runtime checks, not compile-time guarantees -- **Maintainability:** 3 files exceed 2,000+ lines, reducing code comprehension and increasing bug risk - ---- - -## Current Architecture Diagram - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ AppModel │ -│ (@MainActor, 5,446 lines) │ -│ ┌─────────────┬─────────────┬─────────────┬─────────────────┐ │ -│ │ Gateway │ Command │ Voice │ Cluster │ │ -│ │ Events │ Processing│ Presence │ Coordination │ │ -│ └─────────────┴─────────────┴─────────────┴─────────────────┘ │ -└─────────────────────────────────────────────────────────────────┘ - │ │ │ - ▼ ▼ ▼ -┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────┐ -│ DiscordService │ │ RuleEngine │ │ ClusterCoordinator │ -│ (Actor) │ │ (@MainActor) │ │ (Actor) │ -│ │ │ │ │ ┌───────────────────┐ │ -│ - Gateway WS │ │ - Trigger │ │ │ Mesh HTTP Server │ │ -│ - REST Client │ │ - Filter │ │ │ Worker Registry │ │ -│ - Rule Eval │ │ - Modifier │ │ │ Conversation Sync│ │ -│ │ │ - Action │ │ │ Health Monitor │ │ -└─────────────────┘ └─────────────────┘ └─────────────────────────┘ - │ │ │ - ▼ ▼ ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ Gateway Event Flow │ -│ │ -│ Discord WS → DiscordService → GatewayEventDispatcher → AppModel│ -│ │ (duplicate parsing) │ -│ ▼ │ -│ RuleEngine (MainActor hop) │ -│ │ -└─────────────────────────────────────────────────────────────────┘ -``` - ---- - -## Key Architectural Problems - -### 1. Duplicate Event Processing Pipeline - -**Location:** `DiscordService.swift` (lines 560-590), `AppModel+Gateway.swift` (lines 220-350), `GatewayEventDispatcher.swift` (lines 130-175) - -**Problem:** -Gateway events are parsed and processed through **two separate execution paths**: - -```swift -// Path 1: DiscordService processes rules -private func processRuleActionsIfNeeded(_ payload: GatewayPayload) async { - guard payload.op == 0 else { return } - let event: VoiceRuleEvent? - switch payload.t { - case "VOICE_STATE_UPDATE": - event = parseVoiceRuleEvent(from: payload.d) - case "MESSAGE_CREATE": - event = parseMessageRuleEvent(from: payload.d) - // ... - } - guard let event else { return } - let engine = ruleEngine - let ruleActions = await MainActor.run { - engine?.evaluateRules(event: event).map { - (isDM: event.isDirectMessage, actions: $0.processedActions) - } ?? [] - } - for ruleResult in ruleActions { - _ = await executeRulePipeline(actions: ruleResult.actions, for: event, isDirectMessage: ruleResult.isDM) - } -} - -// Path 2: AppModel processes AI replies, commands, mentions -func handleMessageCreate(_ event: MessageCreateEvent) async { - // ... 130+ lines of duplicate parsing and processing -} -``` - -**Impact:** -- Same `MESSAGE_CREATE` event parsed twice -- Rule evaluation happens in both paths -- Risk of inconsistent state between the two pipelines -- Wasted CPU cycles on redundant parsing - -**Recommendation:** -Consolidate into a **single gateway event processing pipeline**: -```swift -enum GatewayEventProcessor { - static func process(_ payload: GatewayPayload, context: AppContext) async { - let event = parseEvent(payload) - await withTaskGroup(of: Void.self) { group in - group.addTask { await context.ruleEngine.evaluate(event) } - group.addTask { await context.appModel.handle(event) } - } - } -} -``` - ---- - -### 2. MainActor Overuse Creating Performance Bottlenecks - -**Location:** `Models.swift` (line 2704), `AppModel.swift` (line 344) - -**Problem:** -```swift -@MainActor -final class RuleEngine { - func evaluateRules(event: VoiceRuleEvent) -> [Rule] { - activeRules - .filter { rule in - matchesTrigger(rule: rule, event: event) && - matchesConditions(rule: rule, event: event) - } - } -} -``` - -**Analysis:** -- Rule evaluation is **pure computation** - no UI updates, no shared mutable state -- Forcing execution onto MainActor creates unnecessary serialization -- Every gateway event must wait for MainActor queue availability -- During high message volume, UI updates compete with rule evaluation - -**Impact:** -- UI stuttering during rule processing bursts -- Increased latency from actor hopping -- Priority inversion risk (rule evaluation blocks UI updates) - -**Recommendation:** -```swift -final class RuleEngine: @unchecked Sendable { - private let rules: [Rule] - private let queue = DispatchQueue(label: "com.swiftbot.ruleengine", qos: .userInitiated) - - func evaluateRules(event: VoiceRuleEvent) -> [Rule] { - queue.sync { - activeRules.filter { rule in matchesTrigger(rule: rule, event: event) } - } - } -} -``` - -Or simply remove `@MainActor` and use actor isolation only where needed. - ---- - -### 3. God Classes Violating Single Responsibility - -**Location:** `AppModel.swift` (5,446 lines), `Models.swift` (4,248 lines), `ClusterCoordinator.swift` (2,416 lines) - -**Problem:** -`AppModel` handles: -- Bot lifecycle management -- Settings persistence -- Gateway event handling -- Command processing -- Voice presence tracking -- Rule engine coordination -- Plugin management -- Patchy monitoring -- Discord metadata caching -- Media library management -- Admin web server configuration -- SwiftMesh cluster coordination -- AI reply generation -- Bug tracking -- Image generation -- Wiki lookups - -**Impact:** -- High cognitive load for developers -- Merge conflicts during collaborative development -- Difficult to test in isolation -- Violates Single Responsibility Principle - -**Recommendation:** -Split into focused managers: - -``` -AppModel.swift (5,446 lines) - ↓ -├── BotLifecycleManager.swift -├── GatewayEventManager.swift -├── CommandManager.swift -├── VoicePresenceManager.swift -├── MediaLibraryManager.swift -├── ClusterManager.swift -├── AIManager.swift -└── AppModel.swift (orchestration layer, ~500 lines) -``` - ---- - -## Performance Bottlenecks - -### 1. Sequential AI Engine Processing - -**Location:** `DiscordAIService.swift` (lines 430-445) - -**Current Implementation:** -```swift -private func orderedEngines(preferred: AIProviderPreference, engines: EngineSet) -> [any AIEngine] { - switch preferred { - case .apple: - return [engines.apple, engines.openAI, engines.ollama] - case .ollama: - return [engines.ollama, engines.openAI, engines.apple] - case .openAI: - return [engines.openAI, engines.apple, engines.ollama] - } -} - -// Sequential execution -for engine in engines { - if let reply = await engine.generate(messages: messages) { - return reply - } -} -``` - -**Problem:** -- If Apple Intelligence times out (10-30s), OpenAI and Ollama won't be tried until after timeout -- Total latency = sum of all engine timeouts in worst case - -**Recommendation:** -```swift -func generateReply(messages: [Message]) async -> String? { - await withTaskGroup(of: String?.self) { group in - group.addTask { await appleEngine.generate(messages: messages) } - group.addTask { await openAIEngine.generate(messages: messages) } - group.addTask { await ollamaEngine.generate(messages: messages) } - - for await result in group { - if let reply = result { - group.cancelAll() - return reply - } - } - return nil - } -} -``` - -**Expected Benefit:** Reduce AI reply latency from 30s+ to <5s in fallback scenarios. - ---- - -### 2. Sequential Gateway Seed Operations - -**Location:** `DiscordService.swift` (lines 145-155) - -**Current Implementation:** -```swift -private func handleInboundGatewayPayload(_ payload: GatewayPayload) async { - seedChannelTypesIfNeeded(payload) - seedGuildNameIfNeeded(payload) - seedVoiceChannelsIfNeeded(payload) - seedVoiceStateIfNeeded(payload) - await processRuleActionsIfNeeded(payload) - await onPayload?(payload) -} -``` - -**Problem:** -All seed operations are independent but run sequentially. - -**Recommendation:** -```swift -private func handleInboundGatewayPayload(_ payload: GatewayPayload) async { - await withTaskGroup(of: Void.self) { group in - group.addTask { self.seedChannelTypesIfNeeded(payload) } - group.addTask { self.seedGuildNameIfNeeded(payload) } - group.addTask { self.seedVoiceChannelsIfNeeded(payload) } - group.addTask { self.seedVoiceStateIfNeeded(payload) } - } - await processRuleActionsIfNeeded(payload) - await onPayload?(payload) -} -``` - -**Expected Benefit:** 3-4x faster gateway event processing during burst traffic. - ---- - -## Concurrency Risks - -### 1. Unbounded Cache Growth - -**Location:** `AppModel.swift` (lines 427-435) - -**Problem:** -```swift -var recentMemberJoins: [String: Date] = [:] // capped at 500 but no eviction -var guildMemberCounts: [String: Int] = [:] // never evicted -var lastCommandTimeByUserId: [String: Date] = [:] // cleanup only removes >60s old -var guildJoinTimestamps: [String: [Date]] = [:] // arrays capped at 50, dict unbounded -var userAvatarHashById: [String: String] = [:] // never evicted -var guildAvatarHashByMemberKey: [String: String] = [:] // never evicted -``` - -**Risk:** -During extended operation (days/weeks) with high message volume, these dictionaries can grow to consume significant memory. - -**Recommendation:** -```swift -struct LRUCache { - private var cache: [Key: Value] = [:] - private var accessOrder: [Key] = [] - private let maxCount: Int - - subscript(key: Key) -> Value? { - get { - guard let value = cache[key] else { return nil } - accessOrder.removeAll { $0 == key } - accessOrder.append(key) - return value - } - set { - cache[key] = newValue - accessOrder.removeAll { $0 == key } - accessOrder.append(key) - while cache.count > maxCount { - let oldest = accessOrder.removeFirst() - cache.removeValue(forKey: oldest) - } - } - } -} - -// Usage -var lastCommandTimeByUserId = LRUCache(maxCount: 1000) -``` - ---- - -### 2. Cluster Mode Isolation Gaps - -**Location:** `DiscordService.swift` (lines 563-585), `ClusterCoordinator.swift` (lines 475-495), `Models.swift` (lines 1720-1740) - -**Problem:** -```swift -// DiscordService.processRuleActionsIfNeeded() - NO cluster mode check -private func processRuleActionsIfNeeded(_ payload: GatewayPayload) async { - // ... parses events and evaluates rules - for ruleResult in ruleActions { - _ = await executeRulePipeline(actions: ruleResult.actions, for: event, isDirectMessage: ruleResult.isDM) - } -} - -// Protection is only via outputAllowed flag (runtime check) -if !outputAllowed { - logger.warning("⚠️ [DiscordService] output is currently blocked; skipping send...") - return nil -} -``` - -**Risk:** -- Standby nodes could execute rule actions if `outputAllowed` flag is incorrectly set -- No compile-time guarantee that only leader nodes send Discord messages -- Two separate guards (`ActionDispatcher` and `outputAllowed`) aren't synchronized - -**Recommendation:** -```swift -// Add explicit cluster mode check -private func processRuleActionsIfNeeded(_ payload: GatewayPayload) async { - guard clusterMode == .leader || clusterMode == .standalone else { - logger.debug("Skipping rule execution on non-leader node") - return - } - // ... rest of processing -} - -// Better: Use type-level isolation -protocol DiscordSender: Sendable { - func send(_ message: Message) async throws -} - -struct LeaderDiscordSender: DiscordSender { /* can send */ } -struct StandbyDiscordSender: DiscordSender { /* throws error */ } -``` - ---- - -## Maintainability Issues - -### 1. Excessive Debug Logging - -**Location:** `RuleExecutionService.swift` (lines 55-60) - -**Problem:** -```swift -func executeRulePipeline(...) async -> PipelineContext { - var context = PipelineContext() - dependencies.debugLog("Executing rule pipeline: \(actions.count) blocks. Initial context: \(context)") - for (index, action) in actions.enumerated() { - await execute(action: action, for: event, context: &context, token: token) - dependencies.debugLog(" [\(index)] Executed \(action.type.rawValue). Updated context: \(context)") - } - // ... -} -``` - -**Impact:** -- With complex rules (10+ actions) and high message volume (100 msg/min), this generates 1,000+ log entries/minute -- Log files grow rapidly, making debugging harder -- String interpolation on every action execution has CPU cost - -**Recommendation:** -```swift -func executeRulePipeline(...) async -> PipelineContext { - var context = PipelineContext() - if dependencies.isDebugLoggingEnabled { - dependencies.debugLog("Executing rule pipeline: \(actions.count) blocks") - } - for action in actions { - await execute(action: action, for: event, context: &context, token: token) - } - if dependencies.isDebugLoggingEnabled { - dependencies.debugLog("Pipeline complete. Final context: \(context.summary)") - } -} -``` - ---- - -### 2. Legacy Compatibility Code - -**Location:** `AppModel.swift` (lines 625-630), `Models.swift` (lines 175-200) - -**Problem:** -```swift -// Worker mode is deprecated in UI — migrate to Fail Over for existing users. -if loadedSettings.clusterMode == .worker { - loadedSettings.clusterMode = .standby - workerModeMigrated = true - migrated = true -} - -// Legacy Admin Web UI Settings - always returns fixed values -var bindHost: String { Self.defaultBindHost } -var port: Int { Self.defaultPort } -var httpsEnabled: Bool { false } -``` - -**Impact:** -- Migration code runs on every app launch for affected users -- Legacy properties add cognitive load without providing value -- Makes code harder to understand for new developers - -**Recommendation:** -- Add migration version tracking: only run migration once per user -- Remove legacy computed properties after documented deprecation period -- Use schema versioning in settings persistence - ---- - -## Recommended Refactor Plan - -### Phase 1: Critical Safety Fixes (Week 1-2) - -| Task | Files | Effort | Risk | -|------|-------|--------|------| -| Add cluster mode check to rule processing | DiscordService.swift | 2h | Low | -| Universal ActionDispatcher gate | All Discord output paths | 4h | Medium | -| Add cache eviction policies | AppModel.swift | 4h | Low | -| Remove @MainActor from RuleEngine | Models.swift | 2h | Medium | - -**Expected Benefits:** -- Prevent standby nodes from executing rule actions -- Eliminate memory growth risk -- Reduce MainActor contention - ---- - -### Phase 2: Performance Optimization (Week 3-4) - -| Task | Files | Effort | Risk | -|------|-------|--------|------| -| Race AI engines with TaskGroup | DiscordAIService.swift | 6h | Medium | -| Parallel gateway seed operations | DiscordService.swift | 4h | Low | -| Consolidate URLSession instances | Multiple REST clients | 4h | Low | -| Reduce debug logging verbosity | RuleExecutionService.swift | 2h | Low | - -**Expected Benefits:** -- AI reply latency: 30s+ → <5s -- Gateway processing throughput: 3-4x improvement -- Better connection reuse, reduced memory footprint - ---- - -### Phase 3: Architectural Refactoring (Week 5-8) - -| Task | Files | Effort | Risk | -|------|-------|--------|------| -| Split AppModel into managers | 8 new files | 20h | High | -| Split Models.swift by domain | 10 new files | 16h | Medium | -| Split ClusterCoordinator | 5 new files | 16h | High | -| Consolidate gateway event parsing | GatewayEventDispatcher.swift | 8h | Medium | - -**Expected Benefits:** -- Improved code comprehension -- Easier testing in isolation -- Reduced merge conflicts -- Better separation of concerns - ---- - -### Phase 4: Cleanup & Modernization (Week 9-10) - -| Task | Files | Effort | Risk | -|------|-------|--------|------| -| Remove legacy migration code | AppModel.swift | 2h | Low | -| Convert gateway event names to enum | GatewayEventDispatcher.swift | 4h | Low | -| Evaluate plugin system necessity | Models.swift | 4h | Medium | -| Add compile-time cluster isolation | ClusterCoordinator.swift | 8h | High | - -**Expected Benefits:** -- Reduced code complexity -- Type safety improvements -- Better compile-time guarantees - ---- - -## Expected Benefits - -### Quantitative Improvements - -| Metric | Current | Target | Improvement | -|--------|---------|--------|-------------| -| Gateway event processing latency | 50ms | 15ms | 70% reduction | -| AI reply fallback latency | 30s+ | <5s | 83% reduction | -| MainActor contention | High | Low | Significant reduction | -| Memory growth (24h operation) | Unbounded | <50MB | Bounded | -| Largest file size | 5,446 lines | <800 lines | 85% reduction | - -### Qualitative Improvements - -- **Safety:** Compile-time cluster isolation prevents standby nodes from sending Discord messages -- **Maintainability:** Focused managers reduce cognitive load and merge conflicts -- **Extensibility:** Domain-separated models make adding features easier -- **Testability:** Smaller, isolated components enable unit testing without mocks -- **Performance:** Parallel processing and reduced MainActor contention improve responsiveness - ---- - -## Risk Assessment - -### Low Risk Changes - -✅ **Cache eviction policies** - Backward compatible, no behavior change -✅ **Debug logging reduction** - Only affects log verbosity, not functionality -✅ **URLSession consolidation** - Internal optimization, transparent to users -✅ **Parallel seed operations** - Independent operations, no shared state - -### Medium Risk Changes - -⚠️ **Remove @MainActor from RuleEngine** - Requires testing for UI binding issues -⚠️ **Gateway event parsing consolidation** - Need to verify both rule and AI pipelines work correctly -⚠️ **AI engine racing** - Must handle cancellation properly to avoid resource leaks - -### High Risk Changes - -🔴 **Split AppModel** - Extensive refactoring, requires comprehensive testing -🔴 **Split ClusterCoordinator** - Cluster coordination is critical; regression could cause data loss -🔴 **Compile-time cluster isolation** - May require API changes affecting multiple files - -### Mitigation Strategies - -1. **Incremental rollout:** Phase changes over 10 weeks with testing between phases -2. **Feature flags:** Gate new behavior behind experimental flags for initial rollout -3. **Comprehensive testing:** Add integration tests for cluster failover scenarios -4. **Monitoring:** Add metrics for gateway processing latency and memory usage -5. **Rollback plan:** Maintain ability to revert to previous architecture if issues arise - ---- - -## Appendix: File Inventory - -### Files Analyzed - -| File | Lines | Issues Found | Priority | -|------|-------|--------------|----------| -| AppModel.swift | 5,446 | 12 | High | -| Models.swift | 4,248 | 8 | Medium | -| ClusterCoordinator.swift | 2,416 | 6 | High | -| DiscordService.swift | 1,200+ | 8 | High | -| AppModel+Gateway.swift | 800+ | 5 | Medium | -| AppModel+Commands.swift | 600+ | 3 | Low | -| DiscordAIService.swift | 280 | 4 | Medium | -| RuleExecutionService.swift | 400+ | 3 | Low | -| GatewayEventDispatcher.swift | 300+ | 4 | Medium | - -### Files Requiring Immediate Attention - -1. `DiscordService.swift` - Add cluster mode check to `processRuleActionsIfNeeded()` -2. `AppModel.swift` - Add cache eviction, remove `@MainActor` from non-UI methods -3. `Models.swift` - Remove `@MainActor` from `RuleEngine` -4. `ClusterCoordinator.swift` - Ensure all Discord output paths check cluster mode - ---- - -**Report Generated:** 14 March 2026 -**Analyst:** Qwen Code -**Review Status:** Ready for human review diff --git a/ARCHITECTURE_ANALYSIS_REPORT_PDF.txt b/ARCHITECTURE_ANALYSIS_REPORT_PDF.txt deleted file mode 100644 index b35e288f..00000000 --- a/ARCHITECTURE_ANALYSIS_REPORT_PDF.txt +++ /dev/null @@ -1,719 +0,0 @@ -================================================================================ - SWIFTBOT ARCHITECTURE ANALYSIS REPORT - PDF-FRIENDLY FORMATTED VERSION -================================================================================ - -Document Date: 14 March 2026 -Repository: SwiftBot -Platform: Native macOS (Swift + SwiftUI) -Analysis Type: Comprehensive Codebase Review - -================================================================================ - EXECUTIVE SUMMARY -================================================================================ - -This report identifies significant opportunities for architectural improvement -in the SwiftBot codebase while maintaining identical user-visible functionality. - -KEY FINDINGS SUMMARY --------------------- -* Duplicate execution paths in gateway event processing -* MainActor overuse creating performance bottlenecks -* Unbounded cache growth risking memory issues -* Cluster safety gaps in standby node isolation -* Three "god classes" exceeding 2,000+ lines each -* Sequential AI processing causing 30s+ latency in fallback scenarios - -IMPACT ASSESSMENT ------------------ -Performance: MainActor bottlenecks add 10-30s latency during peak loads -Memory: Unbounded caches risk growth during extended operation -Safety: Cluster isolation relies on runtime checks, not compile-time -Maintainability: Large files reduce comprehension, increase bug risk - -================================================================================ - CURRENT ARCHITECTURE OVERVIEW -================================================================================ - -SwiftBot is a native macOS Discord bot manager with: -* Discord WebSocket gateway integration -* REST API calls for Discord interactions -* Rule automation engine (Trigger -> Filters -> Modifiers -> Actions) -* AI response pipeline (Apple Intelligence, OpenAI, Ollama) -* SwiftMesh clustering system (Leader/Standby/Worker modes) -* Web admin UI -* Visual rule builder - -PRIMARY COMPONENTS ------------------- -1. AppModel (5,446 lines) - Central orchestration, @MainActor -2. DiscordService (Actor) - Gateway WebSocket, REST clients, rule processing -3. RuleEngine (@MainActor) - Rule evaluation and execution -4. ClusterCoordinator (Actor) - SwiftMesh coordination, HTTP server -5. GatewayEventDispatcher - Event parsing and routing -6. DiscordAIService - AI engine management - -DATA FLOW ---------- -Discord WebSocket -> DiscordService -> GatewayEventDispatcher -> AppModel - | - v - RuleEngine (MainActor hop) - | - v - RuleExecutionService -> DiscordService -> Discord API - -================================================================================ - KEY ARCHITECTURAL PROBLEMS -================================================================================ - -PROBLEM 1: DUPLICATE EVENT PROCESSING --------------------------------------- -Location: DiscordService.swift (lines 560-590) - AppModel+Gateway.swift (lines 220-350) - GatewayEventDispatcher.swift (lines 130-175) - -Description: -Gateway events are parsed and processed through TWO separate execution paths: - -Path 1: DiscordService.processRuleActionsIfNeeded() - - Parses MESSAGE_CREATE for rule evaluation - - Evaluates rules on MainActor - - Executes rule pipeline - -Path 2: AppModel.handleMessageCreate() - - Parses same MESSAGE_CREATE for AI replies - - Processes commands and mentions - - Updates Discord cache - -Impact: -- Same event parsed twice (wasted CPU) -- Rule evaluation happens in both paths -- Risk of inconsistent state between pipelines -- Difficult to trace execution flow - -Recommendation: -Consolidate into single gateway event processing pipeline using TaskGroup -for parallel rule evaluation and message handling. - - -PROBLEM 2: MAINACTOR OVERUSE CREATING BOTTLENECKS -------------------------------------------------- -Location: Models.swift (line 2704), AppModel.swift (line 344) - -Description: -RuleEngine is marked @MainActor but performs PURE COMPUTATION: -- No UI updates -- No shared mutable state -- Only reads rules array and evaluates predicates - -Code Example: - @MainActor - final class RuleEngine { - func evaluateRules(event: VoiceRuleEvent) -> [Rule] { - activeRules.filter { rule in matchesTrigger(rule: rule, event: event) } - } - } - -Impact: -- Every gateway event triggers MainActor hop -- UI updates compete with rule evaluation -- Priority inversion risk during high message volume -- Unnecessary serialization of independent work - -Recommendation: -Remove @MainActor from RuleEngine. Use private DispatchQueue with -.userInitiated QoS for rule evaluation. - - -PROBLEM 3: GOD CLASSES VIOLATING SINGLE RESPONSIBILITY ------------------------------------------------------- -Location: AppModel.swift (5,446 lines) - Models.swift (4,248 lines) - ClusterCoordinator.swift (2,416 lines) - -AppModel Responsibilities (16+ distinct areas): -1. Bot lifecycle management -2. Settings persistence -3. Gateway event handling -4. Command processing -5. Voice presence tracking -6. Rule engine coordination -7. Plugin management -8. Patchy monitoring -9. Discord metadata caching -10. Media library management -11. Admin web server configuration -12. SwiftMesh cluster coordination -13. AI reply generation -14. Bug tracking -15. Image generation -16. Wiki lookups - -Impact: -- High cognitive load for developers -- Frequent merge conflicts -- Difficult to test in isolation -- Violates Single Responsibility Principle - -Recommendation: -Split into focused managers: -- BotLifecycleManager.swift -- GatewayEventManager.swift -- CommandManager.swift -- VoicePresenceManager.swift -- MediaLibraryManager.swift -- ClusterManager.swift -- AIManager.swift -- AppModel.swift (orchestration layer only, ~500 lines) - - -PROBLEM 4: SEQUENTIAL AI ENGINE PROCESSING ------------------------------------------- -Location: DiscordAIService.swift (lines 430-445) - -Description: -AI engines are tried SEQUENTIALLY in preference order: -1. Try Apple Intelligence (timeout: 10-30s) -2. If fails, try OpenAI (timeout: 10s) -3. If fails, try Ollama (timeout: 10s) - -Worst case latency: 50+ seconds for single reply - -Code Example: - for engine in engines { - if let reply = await engine.generate(messages: messages) { - return reply - } - } - -Recommendation: -Use TaskGroup to RACE all engines simultaneously: -- Start all 3 engines in parallel -- Take first successful response -- Cancel remaining tasks -- Expected latency: <5s (fastest engine wins) - - -PROBLEM 5: UNBOUNDED CACHE GROWTH ---------------------------------- -Location: AppModel.swift (lines 427-435) - -Problematic Caches: -- lastCommandTimeByUserId: [String: Date] - cleanup only removes >60s old -- userAvatarHashById: [String: String] - NEVER evicted -- guildAvatarHashByMemberKey: [String: String] - NEVER evicted -- guildMemberCounts: [String: Int] - NEVER evicted -- guildJoinTimestamps: [String: [Date]] - arrays capped, dict unbounded - -Risk: -During extended operation (days/weeks) with high message volume: -- Thousands of user IDs accumulate -- Memory usage grows unbounded -- Potential OOM crashes on long-running instances - -Recommendation: -Implement LRU (Least Recently Used) cache with max count: - struct LRUCache { - private var cache: [Key: Value] = [:] - private var accessOrder: [Key] = [] - private let maxCount: Int = 1000 - - subscript(key: Key) -> Value? { /* LRU logic */ } - } - - -PROBLEM 6: CLUSTER MODE ISOLATION GAPS --------------------------------------- -Location: DiscordService.swift (lines 563-585) - ClusterCoordinator.swift (lines 475-495) - Models.swift (lines 1720-1740) - -Description: -processRuleActionsIfNeeded() does NOT check cluster mode before executing: - - private func processRuleActionsIfNeeded(_ payload: GatewayPayload) async { - // NO cluster mode check here! - guard let event = parseEvent(payload) else { return } - let ruleActions = await MainActor.run { - engine?.evaluateRules(event: event) // Could run on standby! - } - for ruleResult in ruleActions { - _ = await executeRulePipeline(actions: ruleResult.actions, ...) - } - } - -Current Protection: -- DiscordService.outputAllowed flag (runtime check only) -- ActionDispatcher.canSend() (not used in all paths) - -Risk: -- Standby nodes could execute rule actions if flag incorrectly set -- No compile-time guarantee that only leaders send messages -- Two separate guards aren't perfectly synchronized - -Recommendation: -1. Add explicit cluster mode check at start of rule processing -2. Consider type-level isolation (LeaderDiscordSender vs StandbyDiscordSender) -3. Ensure ALL Discord output paths use ActionDispatcher gate - - -PROBLEM 7: EXCESSIVE DEBUG LOGGING ----------------------------------- -Location: RuleExecutionService.swift (lines 55-60) - -Description: -Every action execution logs a debug message: - - func executeRulePipeline(...) async -> PipelineContext { - dependencies.debugLog("Executing pipeline: \(actions.count) blocks") - for (index, action) in actions.enumerated() { - await execute(action: action, ...) - dependencies.debugLog(" [\(index)] Executed \(action.type)") - } - } - -Impact: -- Complex rule: 10+ actions -- High volume: 100 messages/minute -- Result: 1,000+ log entries/minute -- Log files grow rapidly, making debugging harder -- String interpolation has CPU cost - -Recommendation: -- Add isDebugLoggingEnabled flag -- Log summary instead of per-action details -- Use lazy string interpolation - - -PROBLEM 8: NETWORKING INEFFICIENCIES ------------------------------------- -Location: DiscordService.swift (lines 82-90) - -Issue A: Multiple URLSession Instances -- discordHTTPSession (main Discord API) -- identitySession (identity operations) -- Additional sessions in REST client wrappers - -Each session has its own connection pool, reducing connection reuse. - -Issue B: Repeated Cache Updates -Every message triggers cache lookup/update: - await upsertDiscordCacheFromMessage( - guildID: guildID, - channelID: channelId, - userID: userId, - ... - ) - -If 100 messages arrive from same user, same cache update happens 100 times. - -Recommendation: -- Consolidate to single URLSession with method-specific configuration -- Batch cache updates or use debounced mechanism - - -PROBLEM 9: LEGACY COMPATIBILITY CODE ------------------------------------- -Location: AppModel.swift (lines 625-630) - Models.swift (lines 175-200) - -Migration Code (runs on EVERY launch): - if loadedSettings.clusterMode == .worker { - loadedSettings.clusterMode = .standby - workerModeMigrated = true - migrated = true - } - -Legacy Properties (cognitive load, no value): - var bindHost: String { Self.defaultBindHost } - var port: Int { Self.defaultPort } - var httpsEnabled: Bool { false } - -Recommendation: -- Add migration version tracking (run once per user) -- Remove legacy properties after deprecation period -- Document removal timeline - - -PROBLEM 10: ACTOR ISOLATION ISSUES ----------------------------------- -Location: DiscordService.swift (lines 575-578) - ClusterCoordinator.swift (lines 105-145) - -Issue A: Actor Hop Chain -DiscordService (actor) -> MainActor.run -> RuleEngine (@MainActor) -Creates actor hop that could cause priority inversion during high volume. - -Issue B: Cross-Actor Closure Capture -ClusterCoordinator handlers capture AppModel (MainActor): - let aiHandler: @Sendable (...) async -> String? - // When called from ClusterCoordinator actor, captures MainActor AppModel - -Recommendation: -- Minimize MainActor.run boundaries -- Document cross-actor call chains -- Consider actor re-entrancy in design - -================================================================================ - PERFORMANCE BOTTLENECKS -================================================================================ - -BOTTLENECK 1: Gateway Event Processing Latency ----------------------------------------------- -Current: 50ms average per event -Target: 15ms average - -Causes: -- Sequential seed operations (could run in parallel) -- MainActor hop for rule evaluation -- Duplicate parsing in two pipelines - -Fix: Parallel seed operations + remove MainActor from RuleEngine - - -BOTTLENECK 2: AI Reply Fallback Latency ---------------------------------------- -Current: 30s+ (sequential timeouts) -Target: <5s (race fastest engine) - -Causes: -- Engines tried one at a time -- Apple Intelligence timeout: 10-30s -- OpenAI timeout: 10s -- Ollama timeout: 10s - -Fix: TaskGroup to race all engines simultaneously - - -BOTTLENECK 3: MainActor Contention ----------------------------------- -Current: High contention during message bursts -Target: Low contention - -Causes: -- RuleEngine on MainActor -- AppModel entirely @MainActor -- UI updates compete with event processing - -Fix: Remove @MainActor from non-UI components - - -BOTTLENECK 4: Memory Growth ---------------------------- -Current: Unbounded growth over time -Target: <50MB stable after 24h - -Causes: -- Caches without eviction policies -- Accumulated user/guild metadata -- Avatar hashes never cleared - -Fix: LRU caches with max counts - -================================================================================ - CONCURRENCY RISKS -================================================================================ - -RISK 1: Standby Node Rule Execution ------------------------------------ -Severity: HIGH -Likelihood: LOW (requires misconfiguration) - -Scenario: -1. Standby node starts with outputAllowed=true (bug/misconfiguration) -2. Gateway event arrives -3. processRuleActionsIfNeeded() executes rules (no cluster check) -4. Rule actions attempt to send Discord message -5. Message sent from standby node (violates cluster protocol) - -Mitigation: -- Add cluster mode check at start of rule processing -- Use type-level isolation (compile-time guarantee) - - -RISK 2: Cache Mutation During Iteration ---------------------------------------- -Severity: MEDIUM -Likelihood: LOW (Swift actor isolation protects) - -Scenario: -1. SwiftUI iterating over summaries array -2. reloadSummaries() mutates array -3. Potential race condition (Collection modified while iterating) - -Mitigation: -- Use snapshot copies for Published properties -- Document mutation patterns - - -RISK 3: Task Without Cancellation ---------------------------------- -Severity: LOW -Likelihood: MEDIUM (during testing/hot reload) - -Scenario: -1. AppModel creates uptime Task (no stored reference) -2. AppModel deallocated (testing scenario) -3. Task continues running (orphaned) - -Mitigation: -- Store task references -- Cancel in deinit - - -RISK 4: Worker Mode AI Processing ---------------------------------- -Severity: MEDIUM -Likelihood: MEDIUM (if remote fails) - -Scenario: -1. Worker node with offloadAIReplies=true -2. Remote AI request fails (network issue) -3. Worker falls back to local AI processing -4. Worker sends Discord message (violates protocol) - -Mitigation: -- Remove local fallback for workers -- Throw error instead of fallback - -================================================================================ - RECOMMENDED REFACTOR PLAN -================================================================================ - -PHASE 1: CRITICAL SAFETY FIXS (Week 1-2) ----------------------------------------- -Priority: HIGH -Risk: LOW-MEDIUM - -Tasks: -1. Add cluster mode check to processRuleActionsIfNeeded() - File: DiscordService.swift - Effort: 2 hours - -2. Ensure ALL Discord output paths use ActionDispatcher gate - Files: All Discord output locations - Effort: 4 hours - -3. Add cache eviction policies - File: AppModel.swift - Effort: 4 hours - -4. Remove @MainActor from RuleEngine - File: Models.swift - Effort: 2 hours - -Deliverables: -- Standby nodes cannot execute rule actions -- Memory growth bounded -- Reduced MainActor contention - - -PHASE 2: PERFORMANCE OPTIMIZATION (Week 3-4) --------------------------------------------- -Priority: HIGH -Risk: LOW-MEDIUM - -Tasks: -1. Race AI engines with TaskGroup - File: DiscordAIService.swift - Effort: 6 hours - -2. Parallel gateway seed operations - File: DiscordService.swift - Effort: 4 hours - -3. Consolidate URLSession instances - Files: Multiple REST clients - Effort: 4 hours - -4. Reduce debug logging verbosity - File: RuleExecutionService.swift - Effort: 2 hours - -Deliverables: -- AI reply latency: 30s+ -> <5s -- Gateway processing: 3-4x throughput improvement -- Better connection reuse - - -PHASE 3: ARCHITECTURAL REFACTORING (Week 5-8) ---------------------------------------------- -Priority: MEDIUM -Risk: HIGH - -Tasks: -1. Split AppModel into managers - Files: 8 new files - Effort: 20 hours - -2. Split Models.swift by domain - Files: 10 new files - Effort: 16 hours - -3. Split ClusterCoordinator - Files: 5 new files - Effort: 16 hours - -4. Consolidate gateway event parsing - File: GatewayEventDispatcher.swift - Effort: 8 hours - -Deliverables: -- Improved code comprehension -- Easier testing in isolation -- Reduced merge conflicts - - -PHASE 4: CLEANUP & MODERNIZATION (Week 9-10) --------------------------------------------- -Priority: LOW -Risk: LOW-MEDIUM - -Tasks: -1. Remove legacy migration code - File: AppModel.swift - Effort: 2 hours - -2. Convert gateway event names to enum - File: GatewayEventDispatcher.swift - Effort: 4 hours - -3. Evaluate plugin system necessity - File: Models.swift - Effort: 4 hours - -4. Add compile-time cluster isolation - File: ClusterCoordinator.swift - Effort: 8 hours - -Deliverables: -- Reduced code complexity -- Type safety improvements -- Better compile-time guarantees - -================================================================================ - EXPECTED BENEFITS -================================================================================ - -QUANTITATIVE IMPROVEMENTS -------------------------- -Metric Current Target Improvement ---------------------------------------------------------------------------- -Gateway event latency 50ms 15ms 70% reduction -AI reply fallback latency 30s+ <5s 83% reduction -MainActor contention High Low Significant reduction -Memory growth (24h operation) Unbounded <50MB Bounded -Largest file size 5,446 lines <800 lines 85% reduction - - -QUALITATIVE IMPROVEMENTS ------------------------- -Safety: Compile-time cluster isolation prevents standby nodes - from sending Discord messages - -Maintainability: Focused managers reduce cognitive load and merge conflicts - -Extensibility: Domain-separated models make adding features easier - -Testability: Smaller, isolated components enable unit testing - -Performance: Parallel processing reduces latency and improves throughput - -================================================================================ - RISK ASSESSMENT -================================================================================ - -LOW RISK CHANGES ----------------- -[SAFE] Cache eviction policies - - Backward compatible, no behavior change - -[SAFE] Debug logging reduction - - Only affects log verbosity, not functionality - -[SAFE] URLSession consolidation - - Internal optimization, transparent to users - -[SAFE] Parallel seed operations - - Independent operations, no shared state - - -MEDIUM RISK CHANGES -------------------- -[TEST NEEDED] Remove @MainActor from RuleEngine - - Requires testing for UI binding issues - -[TEST NEEDED] Gateway event parsing consolidation - - Verify both rule and AI pipelines work correctly - -[TEST NEEDED] AI engine racing - - Must handle cancellation properly to avoid resource leaks - - -HIGH RISK CHANGES ------------------ -[COMPREHENSIVE TESTING] Split AppModel - - Extensive refactoring - -[COMPREHENSIVE TESTING] Split ClusterCoordinator - - Cluster coordination is critical - -[COMPREHENSIVE TESTING] Compile-time cluster isolation - - May require API changes affecting multiple files - - -MITIGATION STRATEGIES ---------------------- -1. Incremental rollout: Phase changes over 10 weeks with testing between phases - -2. Feature flags: Gate new behavior behind experimental flags for initial rollout - -3. Comprehensive testing: Add integration tests for cluster failover scenarios - -4. Monitoring: Add metrics for gateway processing latency and memory usage - -5. Rollback plan: Maintain ability to revert to previous architecture - -================================================================================ - FILE INVENTORY -================================================================================ - -FILES ANALYZED --------------- -File Lines Issues Priority ------------------------------------------------------------ -AppModel.swift 5,446 12 HIGH -Models.swift 4,248 8 MEDIUM -ClusterCoordinator.swift 2,416 6 HIGH -DiscordService.swift 1,200+ 8 HIGH -AppModel+Gateway.swift 800+ 5 MEDIUM -AppModel+Commands.swift 600+ 3 LOW -DiscordAIService.swift 280 4 MEDIUM -RuleExecutionService.swift 400+ 3 LOW -GatewayEventDispatcher.swift 300+ 4 MEDIUM - - -FILES REQUIRING IMMEDIATE ATTENTION ------------------------------------ -1. DiscordService.swift - Action: Add cluster mode check to processRuleActionsIfNeeded() - -2. AppModel.swift - Actions: Add cache eviction, remove @MainActor from non-UI methods - -3. Models.swift - Action: Remove @MainActor from RuleEngine - -4. ClusterCoordinator.swift - Action: Ensure all Discord output paths check cluster mode - -================================================================================ - END OF REPORT -================================================================================ - -Report Generated: 14 March 2026 -Analyst: Qwen Code -Review Status: Ready for human review - -================================================================================ diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 0a022b78..00000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,437 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - -## [Unreleased] - -### Changed - 2026-03-08 - -#### UI Maintainability Refactor -**Issue:** `RootView.swift` was a massive 4300-line file containing onboarding, settings, automation, and dashboard logic, making it difficult to maintain and prone to merge conflicts. - -**Solution:** -- Decomposed `RootView.swift` into 8 focused feature modules: `OverviewView`, `VoiceActionsView`, `CommandsView`, `LogsView`, `AIBotsView`, `SettingsView`, `OnboardingView`, and `CommonUI`. -- Reduced `RootView.swift` to ~350 lines, serving primarily as a navigation container. -- Migrated domain models (`Rule`, `TriggerType`, etc.) to `Models.swift` to decouple the data layer from the view layer. - -**Impact:** Improved code readability, reduced compile times for incremental UI changes, and established a modular architecture for future feature development. - -#### OpenAI Cost Control & Mesh Synchronization -**Issue:** Image generation quotas were tracked locally per-node, allowing users to bypass limits by switching nodes or resetting local settings. - -**Solution:** -- Implemented mesh-wide image usage synchronization via `MeshSyncPayload`. -- Added a `openAIImageMonthlyHardCap` setting (default: 100) enforced cluster-wide. -- Primary node now broadcasts updated usage counts to all standbys immediately after generation. - -**Impact:** Reliable enforcement of AI usage policies across distributed clusters, protecting against runaway API costs. - -#### Repository Hygiene -**Issue:** The repository mixed published Pages content with internal planning docs, carried assistant-local metadata in version control, and duplicated several image resources. - -**Solution:** -- Added a canonical `LICENSE` file for the GPLv3 license already advertised in the README. -- Ignored and removed `.ai-context` from version control. -- Moved internal planning and design docs from `docs/` to `notes/` so GitHub Pages only publishes site/appcast content. -- Moved README screenshots into `assets/readme/` to reduce root-level clutter. -- Switched AI provider icon loading to named assets, allowing removal of duplicate loose PNG copies. -- Removed unused Apple AI image resources that were no longer referenced at runtime. - -**Impact:** The repository root is easier to scan, published Pages content is cleaner, and the app now uses a single runtime source of truth for provider artwork. - -#### Risk Matrix Review -**Issue:** `RISK_MATRIX.md` still described older planned features and no longer reflected the current operational risks in SwiftBot. - -**Solution:** -- Replaced the stale feature-planning matrix with a current risk review covering secrets at rest, SwiftMesh contract drift, AI reliability, Sparkle publishing, CI gaps, and UI maintainability. - -**Impact:** The risk register now reflects the actual codebase and gives a clearer priority order for follow-up work. - -### Changed - 2026-03-07 - -#### SwiftMesh Internet Peer Networking + Reconciliation + UI Refresh -**Issue:** Mesh cluster behavior was too LAN-assumptive and could split-brain on returning primaries; SwiftMesh UI was visually heavy for macOS. - -**Solution:** -- **Networking policy updates:** - - Allowed internet peer hosts in mesh address normalization. - - Blocked only clearly unsafe hosts (wildcard/metadata endpoints). - - Removed implicit `:80`/`:443` fallback for mesh peers; missing ports now normalize to configured mesh port (`clusterListenPort`, default `38787`). -- **Auth + status pipeline hardening:** - - Fixed `/cluster/status` HMAC path mismatch (`/cluster/status` now signed consistently). - - Local `/cluster/status` polling now sends mesh HMAC headers when secret is configured. -- **Split-brain prevention on startup:** - - Added startup leader reconciliation: nodes configured as leader probe configured leader `/cluster/status` and start as standby when an active leader exists. - - `startBot()` now respects runtime reconciled cluster mode before connecting Discord. -- **Callback reachability reliability:** - - Leader registration path now prefers observed remote source host + declared listen port for worker/standby callback address. -- **SwiftMesh UI redesign (native macOS tone):** - - Reduced glass/shadow weight, simplified node rows, compact metrics grid, left-to-right topology (Primary left, workers right), and less prominent stop controls. - -**Impact:** SwiftMesh can operate across internet peers with deterministic mesh-port behavior, stronger startup safety, and a lighter macOS-native operational UI. - -#### SwiftMesh Stabilization & Reliability (P0 Fixes) -**Issue:** SwiftMesh was non-functional due to authentication mismatches, missing standby connectivity, and split-brain risks. - -**Solution:** -- **Standby Connectivity:** Enabled Standby nodes to start an HTTP listener and register with the Primary, allowing them to receive real-time sync pushes. -- **Authentication Hardening:** - - Replaced legacy `X-Cluster-Secret` with HMAC-signed requests for all resync and wiki-cache pull paths. - - Tightened `verifyMeshAuth` skew window from 300s to 60s and implemented opportunistic nonce pruning. -- **Split-Brain Protection:** - - Added strict `leaderTerm` validation to all mesh sync handlers (`conversations`, `worker-registry`, `wiki-cache`). - - Implemented monotonicity guards for replication cursors to prevent state regression. -- **Rule Compliance (Clean Build):** - - Moved all `test*` methods and `#if DEBUG` logic out of production targets into `ClusterCoordinator+Testing.swift` and `TestSupport.swift`. - - Implemented `TaskLocal` overrides (via `AITestOverrides`) for AI timing and reply behavior in unit tests. -- **UI Improvements:** - - Updated status messaging to explicitly distinguish between "Standby Registered" and "Worker Registered". - -**Impact:** SwiftMesh is now a stable and secure distributed system with reliable node-to-node communication and robust failover protection. - -**Files Modified:** -- `SwiftBotApp/ClusterCoordinator.swift` -- `SwiftBotApp/AppModel.swift` -- `SwiftBotApp/AppModel+Gateway.swift` -- `SwiftBotApp/AppModel+AI.swift` -- `SwiftBotApp/ClusterCoordinator+Testing.swift` -- `SwiftBotApp/TestSupport.swift` -- `Tests/SwiftBotTests/TestHelpers.swift` -- `Tests/SwiftBotTests/DMTimeoutTests.swift` -- `ARCHITECTURE.md` -- `AI_GUIDE.md` -- `docs/swiftmesh-observed-behavior.md` - -### P2 — UX Hardening + Release Quality (2026-03-06) - -#### Fixed -- **Onboarding: app icon** — replaced generic `cpu.fill` placeholder in setup splash with the real app icon (`NSApp.applicationIconImage`). Icon is now always in sync with the Xcode asset without hardcoding an asset name. -- **Onboarding: invite link** — repaired broken Share Link on splash screen. Corrected invite URL endpoint to canonical `https://discord.com/oauth2/authorize` (was `https://discord.com/api/oauth2/authorize`). Scopes now use `+`-encoded spaces. Regression test added in `InviteLinkTests`. -- **Onboarding: degraded invite state** — when the bot's client ID cannot be resolved, the setup screen now shows a clear "Could not generate an invite link" message with guidance, rather than silently hiding the invite section. -- **Onboarding: invite loading state** — a spinner is now shown while the invite URL is being generated so users know the fetch is in progress. - -#### Accessibility -- Decorative images in onboarding (app icon, success checkmark) marked `accessibilityHidden(true)`. -- Validating-token spinner exposes a combined VoiceOver label: "Validating token, please wait". -- Invite URL text now reads the full URL to VoiceOver instead of the truncated display form. -- Sidebar status-indicator dot marked `accessibilityHidden(true)`; status is conveyed via the adjacent text label. - -### Planned (March 2026) - -#### API Debugging & Onboarding -- **API Diagnostics Panel**: Real-time health indicators (ping, rate limits, token status) in the Status view. -- **Onboarding Splash Screen**: New-user setup flow with token validation and dynamic invite link generation. -- **Token Management**: Dedicated "Clear API Key" action in Settings for safe disconnection and reconfiguration. - -#### Automation & Actions -- **Member Join Triggers**: Extend the rule engine to support \`member_join\` events with customizable welcome messages. -- **Voice Join/Leave Logs**: Support for logging voice activity to specific text channels using templates. - -#### UI & Branding -- **Dynamic Beta Icon**: Automatic Dock icon switching to a "Beta" variant when build name contains \`-beta\`. - -### Fixed - -#### SwiftMesh Worker Mode - UX Hotfix -- Temporarily disabled Worker mode from the UI and runtime to undergo UX redesign. -- Existing `.worker` settings will automatically fall back to Standalone mode with a notice. -- Worker code remains in the repository but is gated from activation. - -### Changed - 2026-03-05 - -#### SwiftMesh Failover + Replication (Phases 1 / 2 / 2.1 / 3) -**Issue:** Cluster mode previously lacked automatic failover, durable cross-node state continuity, and knowledge-base (wiki) synchronization. - -**Solution:** -- Added SwiftMesh standby failover mode with term-based promotion safety: - - `ClusterMode.standby` - - leader health monitor (10s interval, 3-miss promotion threshold) - - leader term persistence (`clusterLeaderTerm`) with monotonic restore/update - - `POST /v1/mesh/leader-changed` flow for worker re-registration -- Implemented state replication and consistency: - - **Durable Cursors (Phase 2):** Incremental sync with per-node cursors persisted to `mesh-cursors.json`. - - **Replication Hardening (Phase 2.1):** Cursors now keyed by stable `nodeName` instead of ephemeral URLs. - - **Gap Detection & Resync:** Automatic trigger for POST `/v1/mesh/sync/conversations/resync` when gaps are detected. - - **Wiki Cache Sync (Phase 3):** Standbys pull recent `WikiContextEntry` batches from leader via `GET /v1/mesh/sync/wiki-cache`. -- Added comprehensive test suite: - - `MeshFailoverTests` (promotion, term safety, redirection) - - `MeshSyncTests` (incremental push, gap resync, pagination convergence) - - `WikiSyncTests` (cross-node wiki knowledge replication) - -**Impact:** SwiftMesh is now a robust distributed system with automatic leader failover and continuous state replication across all nodes. - -### Changed - 2026-03-05 - -#### AI Reply Pipeline Consolidation + Naturalness Improvements -**Issue:** Conversational responses felt rigid due to inconsistent history shaping and duplicated prompt-composition paths. - -**Solution:** -- Reduced effective history window and constrained long assistant replay content to reduce tone poisoning. -- Centralized system prompt/message composition through a shared composer path. -- Unified direct and rule-triggered local AI reply context handling with consistent prompt enrichment. -- Added grounded context inputs (server/channel/time) and improved default conversational tone guidance. - -**Impact:** Local AI replies are more consistent and natural, with lower prompt drift across reply entry points. - -### Docs - 2026-03-05 - -#### Documentation Sync (README / ARCHITECTURE / AI_GUIDE) -Updated project docs to reflect current feature status, SwiftMesh phase progress, and current AI pipeline behavior. - -### Changed - 2026-03-04 - -#### Repository Hygiene + Release Tooling Consolidation -**Issue:** Generated build artifacts and stale non-source configuration/files were tracked in git, and release publishing logic lived entirely in a large shell script. - -**Solution:** -- Removed tracked `build/` output from version control and added `build/` ignore coverage. -- Added a Swift CLI release tool at `Tools/SparklePublisher` and converted `scripts/publish_sparkle_release.sh` into a thin wrapper that calls it. -- Removed stale `project.yml` to avoid drift against the checked-in Xcode project. -- Removed unused root-level `Assets/AppleIntelligence.jpg` and `Assets/ollama.icns` project/resource wiring. -- Fixed README release-script link to a repository-relative path. - -**Impact:** No runtime feature changes. Build/release flow is cleaner, easier to maintain, and less likely to reintroduce generated artifact noise in git history. - -### Known Issues - 2026-03-03 - -#### AI Bots Provider Icon Rendering -**Issue:** Apple Intelligence and Ollama provider logos in `AI Bots` are still rendering inconsistently in some builds/environments (including incorrect fallback behavior). - -**Status:** Open and tracked as a UI issue for follow-up. Core AI provider functionality and reply routing are unaffected. - -### Changed - 2026-03-03 - -#### Patchy Runtime Integration + Dashboard Redesign -**Issue:** Patch delivery and configuration UX was fragmented, and UpdateEngine formatting was not the sole payload source in runtime delivery flows. - -**Solution:** Integrated Patchy into `SwiftBotApp` runtime with a dedicated monitoring dashboard and source-target model: -- Added Patchy to Main navigation and introduced a dedicated monitor panel: - - grouped SourceTargets by source (AMD, NVIDIA, Intel Arc, Steam) - - per-target actions: test send, edit, enable/disable, delete - - focused modal editor (source/server/channel/mentions/enabled) -- Added runtime scheduler in `AppModel`: - - global Start Monitoring toggle - - hourly polling cycle (plus manual debug check) - - fetch-once-per-source-group fan-out delivery to configured targets -- Enforced UpdateEngine embed JSON as source of truth for Discord sends: - - send path uses `embedJSON` directly when valid/non-empty - - fallback message only when embed JSON is missing/invalid - - role mention support with sanitized numeric role IDs and allowed mentions - - detailed send diagnostics (HTTP status + response snippet) -- Added raw payload Discord REST API method: - - `sendMessage(channelId:payload:token:)` - - content helper delegates to payload API - -**Impact:** Patchy now behaves like a dedicated monitor dashboard with runtime-owned scheduling and clean per-target delivery. - -### Changed - 2026-03-03 - -#### Offline Discord Metadata Cache + Steam App Name Resolution -**Issue:** Patchy target editing depended on live gateway state; Steam targets showed only App IDs without friendly names. - -**Solution:** -- Added persistent Discord metadata cache (`discord-cache.json`) for: - - servers - - voice/text channels - - roles - - known user display names -- App startup now loads cached metadata and keeps it available when bot is offline/stopped. -- Added Steam app-name resolution from App ID (Steam Store API) with local cache in settings: - - names resolve automatically when Steam targets are added/updated/checked - - Patchy list rows show `Steam • ()` when available - -**Impact:** Configuration remains editable offline, and Steam targets are clearer to manage. - -### Changed - 2026-03-03 - -#### UpdateEngine Source Hardening (Standalone) -**Issue:** AMD summary extraction could fall back to `"No release notes available."` despite valid release-note content, and Intel Arc support was missing from built-in sources. - -**Solution:** Updated only the standalone `Sources/UpdateEngine` module to improve parser reliability and restore Intel as a first-class source: -- AMD (`AMDService`) - - Reworked summary extraction priority to: `Highlights` -> `Fixed Issues` -> first meaningful paragraph. - - Replaced brittle section regex parsing with heading-aware extraction. - - Improved HTML cleanup for summary content: - - removes `script/style` blocks - - handles `
` as newlines - - preserves list hierarchy for bullets/sub-bullets - - strips remaining tags while preserving text content -- Intel (`IntelService` + `IntelUpdateSource`) - - Added new standalone Intel Arc source conforming to `UpdateSource`. - - Uses `sourceKey/cacheKey = intel-default` and identifier-based caching via `identifier = version`. - - Extracts version, release date, release-notes URL, and summary from Intel Arc driver page payloads. - - Includes resilient fetch strategy for Intel page variants and descriptive parse errors. - - Uses Intel Arc logo PNG thumbnail. -- Tester updates - - Added Intel option to `UpdateEngineTester` CLI. - - Added Intel option to `UpdateEngineUITester`. - -**Verification:** -- `swift build --package-path Sources/UpdateEngine` passed. -- `swift test --package-path Sources/UpdateEngine` passed. -- `swift run --package-path Sources/UpdateEngine UpdateEngineTester --source amd --no-save` passed. -- `swift run --package-path Sources/UpdateEngine UpdateEngineTester --source intel --no-save` passed. - -**Important:** No integration into `SwiftBotApp` runtime was performed. No bot startup, runtime polling, Discord event wiring, or existing runtime behavior was changed. - -### Changed - 2026-03-03 - -#### UpdateEngine Standalone Stabilization -**Issue:** `Sources/UpdateEngine` mixed prototype UI/runtime files with core logic, used version-only change checks, and lacked a clean package API boundary. - -**Solution:** Refactored UpdateEngine into a standalone library target with identifier-based caching and explicit abstractions: -- Converted package product to library target (`UpdateEngine`) with dedicated source path `Sources/UpdateEngine/Sources/UpdateEngineCore` -- Introduced explicit core protocols/types: - - `UpdateSource` (source abstraction) - - `UpdateItem` (identifier + version model) - - `VersionStore` async protocol (`JSONVersionStore`, `InMemoryVersionStore`) - - `UpdateChecker` actor for identifier-based checks/saves - - `CacheKeyBuilder` for scoped cache keys (including per-guild key patterns) -- Added built-in vendor-agnostic source wrappers: - - `NVIDIAUpdateSource` - - `AMDUpdateSource` - - `SteamNewsUpdateSource` -- Added package tests (`UpdateCheckerTests`) covering: - - first-seen/unchanged/changed flows - - per-guild scoped-key independence - - identifier-based behavior independent of display version -- Moved previous prototype app/runtime files into `Sources/UpdateEngine/Legacy/PrototypeApp` to keep them out of the library build surface - -**Important:** No integration into `SwiftBotApp` runtime was performed. No bot startup, polling, or Discord event wiring changes were made. - -**Files Modified:** -- `Sources/UpdateEngine/Package.swift` -- `Sources/UpdateEngine/Sources/UpdateEngineCore/*` (new core library files) -- `Sources/UpdateEngine/Tests/UpdateEngineTests/UpdateCheckerTests.swift` -- `Sources/UpdateEngine/Legacy/*` (moved legacy prototype files) -- `AI_GUIDE.md` -- `ARCHITECTURE.md` -- `CHANGELOG.md` - -### Changed - 2026-03-02 - -#### Repository Cleanup -**Issue:** The repository contained generated build output, user-specific workspace data, and obsolete duplicate files from earlier project structure changes. - -**Solution:** Removed non-source artifacts and stale files from the repo: -- Deleted generated output directories: `Dist/`, `.build/`, `.swiftpm/` -- Deleted obsolete duplicate files: root `EventBus.swift`, `SwiftBotApp/EventBus.swift`, `SwiftBotApp/StarterPlugin.swift` -- Deleted unused leftover project folders: `SwiftBot/`, `SwiftBot.xcodeproj` -- Deleted user-specific metadata: `.DS_Store`, `xcuserdata` -- Added `.gitignore` rules to keep generated and user-local files out of version control - -**Files Modified:** -- `.gitignore` - Added ignore rules for generated and user-local files -- `ARCHITECTURE.md` - Removed stale deprecated-files section - -### Changed - 2026-03-02 - -#### Project Rename -**Issue:** The app, package, and project metadata still used the old `DiscordBotApp` naming. - -**Solution:** Renamed the active app target and related references from `DiscordBotApp` to `SwiftBot`: -- Renamed the source folder to `SwiftBotApp/` -- Renamed the Xcode project to `SwiftBot.xcodeproj` -- Renamed the app entry file to `SwiftBotApp.swift` -- Updated the SwiftPM package, Xcode target, scheme, and docs to use `SwiftBot` -- Updated storage and Discord client identifier strings to use `SwiftBot` - -**Files Modified:** -- `Package.swift` -- `project.yml` -- `SwiftBot.xcodeproj` -- `SwiftBotApp/SwiftBotApp.swift` -- `SwiftBotApp/Persistence.swift` -- `SwiftBotApp/DiscordService.swift` -- `README.md` -- `ARCHITECTURE.md` -- `AI_GUIDE.md` - -### Fixed - 2026-03-02 - -#### Build Errors - EventBus Type Resolution -**Issue:** Multiple compilation errors related to `EventBus`, `VoiceJoined`, `VoiceLeft`, and `SubscriptionToken` types not being found in scope. - -**Root Cause:** The files `EventBus.swift` and `StarterPlugin.swift` were not properly included in the Xcode project's build target, causing cross-file type resolution failures. - -**Solution:** Consolidated all EventBus-related types into `Models.swift` to ensure all types are in a single compilation unit: -- Moved `Event` protocol, `SubscriptionToken`, `EventBus` class to top of `Models.swift` -- Moved event types (`VoiceJoined`, `VoiceLeft`, `MessageReceived`) to `Models.swift` -- Moved `WeeklySummaryPlugin` class from `StarterPlugin.swift` to `Models.swift` -- Removed the old `EventBus.swift` and `StarterPlugin.swift` files after consolidation - -**Files Modified:** -- `Models.swift` - Added EventBus system and WeeklySummaryPlugin - -#### Server Notifier Rules Mirroring -**Issue:** When editing one notification rule, changes would affect other rules, making them appear to "mirror" each other. - -**Root Cause:** Two separate bugs working together: -1. **Stale Binding Reference:** The `selectedRuleBinding` computed property was capturing `selectedRuleID` at creation time but not looking up the current selected rule ID when getting/setting values -2. **Missing View Identity:** `RuleEditorView` lacked an `.id()` modifier, causing SwiftUI to reuse the same view instance when switching between rules - -**Solution:** -1. Updated `selectedRuleBinding` to always look up `app.ruleStore.selectedRuleID` fresh on each access in both `get` and `set` closures -2. Added `.id(app.ruleStore.selectedRuleID)` to `RuleEditorView` to force view recreation when selection changes - -**Files Modified:** -- `RootView.swift` - Fixed `ServerNotifierView.selectedRuleBinding` computed property -- `RootView.swift` - Added `.id()` modifier to `RuleEditorView` - -**Impact:** Each rule now maintains independent state; editing one rule no longer affects others. - ---- - -## Project Structure Notes - -### Current Architecture -- **Main App:** SwiftUI-based macOS Discord bot dashboard -- **Core Files:** - - `Models.swift` - All data models, EventBus system, plugins - - `AppModel.swift` - Main application state and business logic - - `DiscordService.swift` - Discord Gateway and REST API communication - - `RootView.swift` - Main UI views and components - - `Persistence.swift` - Settings and rules persistence - -### EventBus System -- Location: `Models.swift` (consolidated from `EventBus.swift`) -- Purpose: Type-safe publish/subscribe event system for plugins -- Events: `VoiceJoined`, `VoiceLeft`, `MessageReceived` -- Usage: Allows plugins to subscribe to bot events asynchronously - -### Plugin System -- Protocol: `BotPlugin` defined in `Models.swift` -- Manager: `PluginManager` class in `Models.swift` -- Current Plugins: - - `WeeklySummaryPlugin` - Tracks voice channel usage time - ---- - -## Development Guidelines - -### Making Changes -When modifying this project, please update this CHANGELOG with: -- **What** was changed -- **Why** it was changed -- **Which files** were modified -- **Impact** on functionality - -### For AI Assistants -This file serves as a reference for: -- Understanding recent changes and their rationale -- Avoiding reintroduction of fixed bugs -- Maintaining awareness of deprecated files -- Understanding the current project structure - ---- - -## Version History - -### Initial State -- Native macOS Discord bot with SwiftUI interface -- Gateway connection with voice presence tracking -- Server notification rules engine -- Command system with prefix support -- On-device AI replies for DMs and channel mentions (Beta) diff --git a/README.md b/README.md index f1e94f74..799a3d8c 100644 --- a/README.md +++ b/README.md @@ -227,8 +227,6 @@ When reporting runtime problems, include the SwiftBot version, macOS version, th - [Architecture](ARCHITECTURE.md) - [AI Guide](AI_GUIDE.md) -- [Changelog](CHANGELOG.md) -- [Risk Matrix](RISK_MATRIX.md) - [Feature Plan](notes/FEATURE_PLAN_PHASE1.txt) ## Releases diff --git a/RISK_MATRIX.md b/RISK_MATRIX.md deleted file mode 100644 index 4845254d..00000000 --- a/RISK_MATRIX.md +++ /dev/null @@ -1,54 +0,0 @@ -# SwiftBot Risk Matrix (Reviewed March 2026) - -This matrix was reviewed against the current repository state on 2026-03-08 and updated 2026-03-08 (afternoon session). -It replaces the older feature-planning matrix and focuses on active product and -engineering risks visible in the current codebase. - -For the detailed SwiftMesh improvement plan and risk breakdown, see [notes/swiftmesh-risk-matrix.md](notes/swiftmesh-risk-matrix.md). - -## Active Risks - -| Area | Current Risk | Likelihood | Impact | Current Controls | Recommended Next Step | -| :--- | :--- | :---: | :---: | :--- | :--- | -| ~~**Secrets at Rest**~~ | ~~The Discord bot token is migrated to Keychain, but `openAIAPIKey` and `clusterSharedSecret` still serialize with `BotSettings` and are written to `settings.json`. A local disk compromise exposes third-party credentials and mesh auth secrets.~~ | ~~High~~ | ~~High~~ | **Resolved 2026-03-08.** `openAIAPIKey` and `clusterSharedSecret` are now Keychain-backed (`"openai-api-key"` and `"cluster-shared-secret"` accounts). `ConfigStore` auto-migrates existing disk values on first load and writes only empty strings to `settings.json`. | — | -| **SwiftMesh Contract Drift** | SwiftMesh networking behavior is internally inconsistent: `normalizedBaseURL` honors `:80`/`:443` for explicit schemes, while tests still expect the configured mesh port for those cases. That leaves docs, tests, and runtime behavior out of alignment. | High | High | Mesh auth is HMAC-signed, stale `leaderTerm` syncs are rejected, and metadata/wildcard hosts are blocked. | Decide the canonical port-normalization policy, then align `ClusterCoordinator`, tests, and docs in one pass. See [notes/swiftmesh-risk-matrix.md](notes/swiftmesh-risk-matrix.md) for full SwiftMesh improvement tracking. | -| ~~**Settings UI Regression Post-Refactor**~~ | ~~The `RootView` refactor was too aggressive — `GeneralSettingsView.swift` was missing ~70% of required configuration UI (SwiftMesh Cluster settings, Admin Web UI, Command Prefix, `allowedUserIDs` binding).~~ | ~~High~~ | ~~High~~ | **Resolved 2026-03-08.** Re-implemented SwiftMesh Cluster and Admin Web UI sections, restored Command Prefix field and `allowedUserIDs` comma-separated binding, updated `GeneralSettingsSnapshot` to include all missing fields so Save Settings triggers correctly. | — | -| ~~**AI Provider Reliability**~~ | ~~AI behavior is operationally inconsistent across providers. The Foundation Models spike test is currently failing on p95 latency and one quality gate.~~ | ~~High~~ | ~~Medium~~ | **Resolved 2026-03-08.** Root cause was test-side: spike tests were not using the `Transcript` API to pass system instructions, causing the model to ignore them. After fix: p95 latency 11,756ms → 801ms, quality 4/5 → 5/5, all FoundationModels tests green. | — | -| ~~**OpenAI Cost Control Bypass**~~ | ~~OpenAI image usage limits are tracked in local settings only. That makes the quota easy to reset by editing settings, reinstalling, or using another node, and the limit is not mesh-wide.~~ | ~~Medium~~ | ~~Medium~~ | **Resolved 2026-03-08.** Implemented mesh-wide usage synchronization via `MeshSyncPayload`. Added `openAIImageMonthlyHardCap` (default 100) and cluster-wide aggregation in `handleGenerateImageCommand`. Primary node now broadcasts updated usage counts immediately. | — | -| ~~**Sparkle Release Pipeline**~~ | ~~Auto-update health depends on the appcast feed, signing key, and release publishing staying in sync. If the appcast is stale or `SUFeedURL` / `SUPublicEDKey` are wrong, updates silently stop working in production.~~ | ~~Medium~~ | ~~Medium~~ | **Resolved 2026-03-08.** Created `scripts/validate_sparkle.sh` which verifies Plist keys, stable appcast presence, and enclosure reachability. Integrated this script as a mandatory step in the `ci.yml` workflow. | — | -| ~~**No Automated CI Gate**~~ | ~~The repo currently has a Pages workflow but no build/test workflow. Regressions depend on manual local testing and can land without a machine-checked signal.~~ | ~~High~~ | ~~Medium~~ | **Resolved 2026-03-08.** `.github/workflows/ci.yml` added. Runs `swift test --parallel` and `swift test --package-path Sources/UpdateEngine --parallel` on push/PR to main, on `macos-14`. | — | -| ~~**UI Maintainability**~~ | ~~`RootView.swift` is still very large and concentrates onboarding, settings, AI, diagnostics, and mesh UI in one file.~~ | ~~High~~ | ~~Medium~~ | **Resolved 2026-03-08.** `RootView.swift` reduced from ~4300 to ~350 lines. Extracted: `OnboardingView.swift`, `OverviewView.swift`, `VoiceActionsView.swift`, `CommandsView.swift`, `LogsView.swift`, `AIBotsView.swift`, `SettingsView.swift`, `CommonUI.swift`. Model types (`Rule`, `TriggerType`, `ActionType`, etc.) moved to `Models.swift`. | — | - -## New Risks Identified (2026-03-08 afternoon session) - -The agent team reviewed `ClusterCoordinator.swift` and related mesh code. The following risks were identified and are tracked in detail in [notes/swiftmesh-risk-matrix.md](notes/swiftmesh-risk-matrix.md): - -| Risk | Priority | Owner | -| :--- | :---: | :--- | -| Service type mismatch (`_swiftbot-mesh._tcp` vs `_swiftmesh._tcp`) causes silent cluster partitioning on mixed-version nodes | P1 | codex | -| Startup race: `pollClusterStatus()` fires before `NWListener` reaches `.ready` | P1 | codex | -| Worker registers with leader before its own listener is `.ready`, causing "registered but not participating" behavior | P1 | codex | -| Standby promotion with no witness requirement risks false-positive split-brain during network partitions | P2 | claude | -| Best-effort sync drops — failed replication to standby silently lost, no retry | P3 | codex | -| Registration storms — fixed 4s retry interval can overwhelm a recovering leader | P3 | codex | -| No machine-readable error codes; UI shows generic "Disconnected" for all failure modes | P3 | gemini | -| Hardcoded test ports (39100–39205) cause non-deterministic CI failures | P4 | kimi | -| No integration tests for multi-node startup, partition, or recovery scenarios | P4 | kimi | - ---- - -## Risks Already Materially Reduced - -- **Discord token exposure on disk** has been reduced: `ConfigStore` persists an empty `token` field and uses `KeychainHelper` for the live credential. -- **Member-join raid spam** is partially mitigated: the app now has a join burst guard, dedupe window, and template sanitization for welcome flows. -- **SwiftMesh split-brain and auth regressions** are materially lower than before: HMAC auth, stale-term rejection, and cursor monotonicity checks are now in place. -- **Sparkle misconfiguration visibility** is better than before: the UI now exposes update-channel state and warns when appcast configuration is incomplete. - -## Recommended Priority Order - -1. ~~Move `openAIAPIKey` and `clusterSharedSecret` out of `settings.json`.~~ ✅ Done 2026-03-08 -2. Resolve the SwiftMesh port-normalization mismatch and return the failing tests to green. *(in progress — @codex)* -3. ~~Add a basic CI workflow so test regressions are caught automatically.~~ ✅ Done 2026-03-08 -4. ~~Split `RootView.swift` into smaller feature views before more UI work lands there.~~ ✅ Done 2026-03-08 -5. ~~Implement mesh-wide image usage tracking and hard caps for OpenAI cost control.~~ ✅ Done 2026-03-08 -6. ~~Automate Sparkle release pipeline validation in CI.~~ ✅ Done 2026-03-08 diff --git a/SwiftBotApp/AdminWebServer.swift b/SwiftBotApp/AdminWebServer.swift index 7c074700..65007386 100644 --- a/SwiftBotApp/AdminWebServer.swift +++ b/SwiftBotApp/AdminWebServer.swift @@ -464,7 +464,7 @@ actor AdminWebServer { private var refreshSwiftMesh: (@Sendable () async -> Bool)? private var swiftMinerWebhookHandler: (@Sendable ([String: String], Data) async -> (status: String, body: Data))? private var discordUsersProvider: (@Sendable () async -> [String: String])? - private var swiftMinerTestDMSender: (@Sendable (String) async -> Bool)? + private var swiftMinerTestDMSender: (@Sendable (String, String?, [String]) async -> Bool)? private var logger: (@Sendable (String) async -> Void)? private var sessions: [String: Session] = [:] private var pendingStates: [String: PendingState] = [:] @@ -523,7 +523,7 @@ actor AdminWebServer { refreshSwiftMesh: @escaping @Sendable () async -> Bool, swiftMinerWebhookHandler: @escaping @Sendable ([String: String], Data) async -> (status: String, body: Data), discordUsersProvider: @escaping @Sendable () async -> [String: String], - swiftMinerTestDMSender: @escaping @Sendable (String) async -> Bool, + swiftMinerTestDMSender: @escaping @Sendable (String, String?, [String]) async -> Bool, log: @escaping @Sendable (String) async -> Void ) async -> RuntimeState { self.statusProvider = statusProvider @@ -898,7 +898,15 @@ actor AdminWebServer { return jsonResponse(["error": "invalid_path"], status: "400 Bad Request") } let discordUserId = segments[2] - let sent = await swiftMinerTestDMSender?(discordUserId) ?? false + // Optional body: { "twitch_username": "...", "priority_games": ["..."] } + var twitchUsername: String? + var priorityGames: [String] = [] + if !request.body.isEmpty, + let json = try? JSONSerialization.jsonObject(with: request.body) as? [String: Any] { + twitchUsername = json["twitch_username"] as? String + priorityGames = json["priority_games"] as? [String] ?? [] + } + let sent = await swiftMinerTestDMSender?(discordUserId, twitchUsername, priorityGames) ?? false return jsonResponse(["ok": sent], status: sent ? "200 OK" : "502 Bad Gateway") case ("POST", "/webhooks/swiftminer/events"): guard let handler = swiftMinerWebhookHandler else { diff --git a/SwiftBotApp/AppModel+AdminWeb.swift b/SwiftBotApp/AppModel+AdminWeb.swift index 01015798..28acf769 100644 --- a/SwiftBotApp/AppModel+AdminWeb.swift +++ b/SwiftBotApp/AppModel+AdminWeb.swift @@ -1085,9 +1085,9 @@ extension AppModel { guard let model = self else { return [:] } return await model.discordCache.humanUserNames() }, - swiftMinerTestDMSender: { [weak self] discordUserId in + swiftMinerTestDMSender: { [weak self] discordUserId, twitchUsername, priorityGames in guard let model = self else { return false } - return await model.sendSwiftMinerTestDM(to: discordUserId) + return await model.sendSwiftMinerTestDM(to: discordUserId, twitchUsername: twitchUsername, priorityGames: priorityGames) }, log: { [weak self] message in guard let model = self else { return } diff --git a/SwiftBotApp/AppModel+SwiftMiner.swift b/SwiftBotApp/AppModel+SwiftMiner.swift index 7259a18f..db7b2dae 100644 --- a/SwiftBotApp/AppModel+SwiftMiner.swift +++ b/SwiftBotApp/AppModel+SwiftMiner.swift @@ -96,20 +96,60 @@ extension AppModel { return result } - func sendSwiftMinerTestDM(to discordUserId: String) async -> Bool { + func sendSwiftMinerTestDM(to discordUserId: String, twitchUsername: String?, priorityGames: [String]) async -> Bool { guard settings.swiftMiner.enabled else { return false } - let content = """ - **SwiftMiner account connected and active** ⚡ - Your Twitch account has been linked to SwiftMiner and is ready to mine drops. - Use `/miner action:status` to check your current progress at any time. - """ + // Look up the recipient's Discord display name (server nick / global name / username) + // from the gateway cache so the message can address them by name. + let discordName = await discordCache.userName(for: discordUserId) + let greeting = discordName.map { "Hi **\($0)**! " } ?? "" + + let body: String + if let twitchUsername, !twitchUsername.isEmpty { + body = "Your Twitch account **@\(twitchUsername)** is linked and ready to mine drops." + } else { + body = "Your Twitch account has been linked to SwiftMiner and is ready to mine drops." + } + let description = greeting + body + + var fields: [[String: Any]] = [] + + if priorityGames.isEmpty { + fields.append([ + "name": "🎮 Priority games", + "value": "_None set — SwiftMiner will mine any available drops campaign._", + "inline": false + ]) + } else { + let preview = priorityGames.prefix(8).map { "• \($0)" }.joined(separator: "\n") + let extra = priorityGames.count > 8 ? "\n• …and \(priorityGames.count - 8) more" : "" + fields.append([ + "name": "🎮 Priority games", + "value": preview + extra, + "inline": false + ]) + } + + fields.append([ + "name": "📬 Notifications", + "value": "You'll get a DM here if anything needs attention — auth expired, blocked drops, etc.", + "inline": false + ]) + + let embed: [String: Any] = [ + "title": "SwiftMiner account connected and active ⚡", + "description": description, + "color": 3_062_954, // green, matches the ok colour used by /miner responses + "fields": fields, + "footer": ["text": "Use /miner action:status to check progress"] + ] + do { - try await service.sendDM(userId: discordUserId, content: content) - addEvent(ActivityEvent(timestamp: Date(), kind: .command, message: "SwiftMiner test DM sent to \(discordUserId)")) + try await service.sendDMEmbed(userId: discordUserId, embed: embed) + addEvent(ActivityEvent(timestamp: Date(), kind: .command, message: "SwiftMiner setup DM sent to \(discordUserId)")) return true } catch { - logs.append("SwiftMiner test DM failed for \(discordUserId): \(error.localizedDescription)") + logs.append("SwiftMiner setup DM failed for \(discordUserId): \(error.localizedDescription)") return false } } diff --git a/SwiftBotApp/DiscordService.swift b/SwiftBotApp/DiscordService.swift index 9ffeeba2..220434c4 100644 --- a/SwiftBotApp/DiscordService.swift +++ b/SwiftBotApp/DiscordService.swift @@ -771,6 +771,18 @@ actor DiscordService { try await sendMessage(channelId: channelId, content: content, token: token) } + /// Send a DM using a Discord embed payload (e.g. for richer welcome / status messages). + func sendDMEmbed(userId: String, embed: [String: Any]) async throws { + guard outputAllowed else { + discordLogger.warning("[DiscordService] Secondary guard: sendDMEmbed blocked — outputAllowed is false (node is not Primary).") + throw NSError(domain: "DiscordService", code: 403, userInfo: [NSLocalizedDescriptionKey: "Output blocked: node is not Primary."]) + } + guard let token = botToken else { return } + + let channelId = try await messageRESTClient.createDirectMessageChannel(userId: userId, token: token) + _ = try await messageRESTClient.sendMessage(channelId: channelId, payload: ["embeds": [embed]], token: token) + } + func deleteMessage(channelId: String, messageId: String, token: String) async throws { guard outputAllowed else { discordLogger.warning("[DiscordService] Secondary guard: deleteMessage blocked — outputAllowed is false (node is not Primary).") diff --git a/docs/ web-ui-setup.md b/docs/ web-ui-setup.md deleted file mode 100644 index bb7a0954..00000000 --- a/docs/ web-ui-setup.md +++ /dev/null @@ -1,310 +0,0 @@ -# SwiftBot Web UI & HTTPS Setup - -SwiftBot includes a built-in **Admin Web UI** that allows server administrators to manage the bot through a browser. - -The Web UI supports: - -- Local access for development -- Discord authentication for administrators -- Optional HTTPS using **Let's Encrypt** -- Automatic DNS validation via **Cloudflare** -- Optional **manual certificate import** - -This guide explains how to configure the dashboard. - ---- - -# 1. Enabling the Web UI - -Open **SwiftBot Settings → Web UI** and enable: - -Enable Admin Web UI - -Recommended settings: - -Bind Address: 127.0.0.1 -Port: 38888 - -Once enabled, open your browser: - -http://127.0.0.1:38888 - ---- - -# 2. Discord Authentication - -The Web UI uses Discord authentication to ensure only administrators can access the dashboard. - -## Create a Discord Application - -1. Go to: -https://discord.com/developers/applications - -2. Click **New Application** - -3. Open **OAuth2 → General** - -4. Copy the following values: - -Client ID -Client Secret - -5. Paste them into **SwiftBot → Authentication** - ---- - -## OAuth Redirect URL - -Add the redirect URL to the Discord application: - -http://127.0.0.1:38888/auth/discord/callback - -If using HTTPS: - -https://admin.example.com/auth/discord/callback - ---- - -# 3. Enabling HTTPS (Recommended) - -SwiftBot can automatically provision TLS certificates using **Let's Encrypt**. - -Requirements: - -- A domain name -- DNS hosted on Cloudflare -- A Cloudflare API token - -Enable: - -Enable HTTPS -Certificate Mode: Automatic (Let's Encrypt) - ---- - -# 4. Creating a Cloudflare API Token - -SwiftBot uses the Cloudflare API for DNS validation and (optionally) Cloudflare Tunnel. The **same token** is used for both HTTPS and Public Access. - -1. Log into Cloudflare - -2. Navigate to: - -My Profile → API Tokens - -3. Click **Create Token** - -4. Use **Custom Token** with these permissions: - -| Permission | Level | Purpose | -|------------|-------|---------| -| Zone → DNS → Edit | Zone | Create DNS records for validation | -| Zone → Zone → Read | Zone | Look up zone information | -| Account → Cloudflare Tunnel → Edit | Account | Create/manage tunnels (Public Access) | -| Account → Account Settings → Read | Account | Read account ID | - -5. Under **Zone Resources**, select: - -Include → Specific Zone → (your domain) - -6. Click **Continue to summary** then **Create Token** - -7. Copy the token and paste it into: - -SwiftBot → Settings → HTTPS → Cloudflare API Token - -The token is automatically shared between HTTPS and Public Access sections. - ---- - -# 5. DNS Configuration - -SwiftBot can create the DNS record automatically, or you can create it manually. - -## Automatic DNS (Recommended) - -In **SwiftBot → Settings → HTTPS**, click **Create DNS Record**. - -SwiftBot will create an A record pointing to your public IP address. - -## Manual DNS - -If you prefer to create the record manually: - -Example: - -admin.example.com → YOUR.SERVER.IP - -Configuration: - -Type: A -Name: admin -Content: YOUR.SERVER.IP - -Then return to SwiftBot and click **Refresh Status** to detect the new record. - ---- - -# 6. HTTPS Setup Validation - -SwiftBot automatically validates the configuration before requesting a certificate. - -The **HTTPS Status** section checks: - -- Cloudflare API token validity -- Domain ownership -- DNS record presence -- DNS resolution - -Example status: - -✓ Cloudflare API token valid -✓ Domain found -✓ DNS record present -✓ Ready for certificate request - -If a problem is detected, SwiftBot will show guidance for fixing it. - ---- - -# 7. Certificate Import (Optional) - -Instead of using Let's Encrypt, you can import an existing certificate. - -Select: - -Certificate Mode → Import Certificate - -Then provide: - -Certificate (.pem) -Private Key (.pem) -Certificate Chain (.pem) (optional) - -Certificates will be stored in: - -~/Library/Application Support/SwiftBot/certs/ - ---- - -# 8. Accessing the Dashboard - -After HTTPS is configured, open: - -https://admin.example.com - -Log in using your Discord account. - -Only **server administrators** are allowed to access the dashboard by default. - ---- - -# 9. Public Access (Cloudflare Tunnel) - -SwiftBot can expose the Web UI to the internet without router port forwarding using **Cloudflare Tunnel**. - -## Requirements - -- HTTPS configured (above) -- Cloudflare API token with Tunnel permissions (see step 4) - -## Setup - -1. Go to **SwiftBot → Settings → Public Access** - -2. Enable **Public Access** - -3. Enter the same hostname used for HTTPS (e.g., `admin.example.com`) - -4. Click **Enable Public Access** - -SwiftBot will: -- Create a Cloudflare tunnel (or reuse an existing one) -- Configure DNS routing -- Start the tunnel automatically - -## Using Existing Tunnels - -If you previously created a tunnel with the same name, SwiftBot will automatically detect and reuse it. No manual cleanup needed. - -Status indicators: -- **✓ Cloudflare tunnel detected** — Reusing existing tunnel -- **✓ Created tunnel** — New tunnel created - ---- - -# 10. Troubleshooting - -## Domain does not resolve - -Check your DNS record: - -admin.example.com → SERVER IP - ---- - -## Cloudflare token invalid - -Ensure the token has all required permissions: - -**For HTTPS:** -- Zone → DNS → Edit -- Zone → Zone → Read - -**For Public Access (additionally):** -- Account → Cloudflare Tunnel → Edit -- Account → Account Settings → Read - ---- - -## Certificate request failed - -Verify: - -- Domain resolves correctly -- DNS record exists -- Cloudflare token has correct permissions - ---- - -## "Cloudflare authentication required" error - -The API token field is empty. Re-enter your token in: - -SwiftBot → Settings → HTTPS → Cloudflare API Token - -The token is shared between HTTPS and Public Access sections. - ---- - -# 11. Security Notes - -- SwiftBot stores Cloudflare tokens securely in the system keychain. -- Discord authentication ensures only administrators can access the dashboard. -- HTTPS certificates are automatically renewed before expiration. - ---- - -# 12. Example Architecture - -Browser -↓ -HTTPS (Let's Encrypt) -↓ -SwiftBot Web UI -↓ -Discord Authentication -↓ -Bot Administration - ---- - -# 13. Next Steps - -You can also configure: - -- SwiftMesh cluster networking -- automatic updates -- plugin modules - -See additional documentation in the `docs/` directory. \ No newline at end of file diff --git a/extract_eventbus.py b/extract_eventbus.py deleted file mode 100644 index ebdc0003..00000000 --- a/extract_eventbus.py +++ /dev/null @@ -1,30 +0,0 @@ -import os - -filepath = '/Users/john/Documents/GitHub/SwiftBot/SwiftBotApp/Models.swift' -with open(filepath, 'r') as f: - lines = f.readlines() - -start_idx = -1 -end_idx = -1 -for i, line in enumerate(lines): - if '// MARK: - EventBus System' in line: - start_idx = i - if '// MARK: - Core Models' in line: - end_idx = i - break - -if start_idx != -1 and end_idx != -1: - eventbus_code = "import Foundation\n\n" + "".join(lines[start_idx:end_idx]) - - # Ensure Models directory exists - os.makedirs('/Users/john/Documents/GitHub/SwiftBot/SwiftBotApp/Models', exist_ok=True) - - with open('/Users/john/Documents/GitHub/SwiftBot/SwiftBotApp/Models/EventBus.swift', 'w') as f: - f.write(eventbus_code) - - new_models = lines[:start_idx] + lines[end_idx:] - with open(filepath, 'w') as f: - f.writelines(new_models) - print("Successfully extracted EventBus.swift") -else: - print("Indices not found") diff --git a/notes/link-converter.md b/notes/link-converter.md deleted file mode 100644 index e2f2279a..00000000 --- a/notes/link-converter.md +++ /dev/null @@ -1,191 +0,0 @@ -# SwiftBot Music Link Converter — Detailed Design - -> **Status:** Planned (docs-only, no implementation yet). -> **Model:** Odesli-first metadata/link conversion. No audio download, no voice channel, no streaming relay. - ---- - -## Overview - -When a user posts a music service URL (Spotify, YouTube, Apple Music, etc.) in a channel, SwiftBot replies with a compact Discord embed containing equivalent links for all other major platforms — so every member can open the track in their preferred app. - ---- - -## Detection - -`NSDataDetector` extracts all URLs from the incoming `MESSAGE_CREATE` message content. The result is filtered against known music service domains: - -| Service | Matched domains | -|---------|----------------| -| Spotify | `open.spotify.com` | -| YouTube | `youtube.com/watch`, `youtu.be` | -| Apple Music | `music.apple.com` | -| Tidal | `tidal.com` | -| SoundCloud | `soundcloud.com` | -| Deezer | `deezer.com` | -| Amazon Music | `music.amazon.com` | - -Only the **first** matched music URL per message is resolved (prevents embed spam on messages that contain several links). - -Bot messages are ignored (standard `isBot` guard already in `handleMessageCreate`). - ---- - -## Resolution — Primary: Odesli API - -[Odesli](https://odesli.co) (song.link / album.link) is a free music metadata service. No API key is required for low-volume usage (ideal for 10–20 person servers). - -**Request:** -``` -GET https://api.song.link/v1-alpha.1/links?url= -``` - -**Key response fields:** -```json -{ - "entityUniqueId": "SPOTIFY_SONG::...", - "pageUrl": "https://song.link/s/...", - "entitiesByUniqueId": { - "SPOTIFY_SONG::...": { - "title": "Song Title", - "artistName": "Artist Name", - "thumbnailUrl": "https://..." - } - }, - "linksByPlatform": { - "spotify": { "url": "https://open.spotify.com/..." }, - "youtube": { "url": "https://www.youtube.com/watch?v=..." }, - "appleMusic": { "url": "https://music.apple.com/..." }, - "tidal": { "url": "https://tidal.com/..." } - } -} -``` - -Only platforms present in `linksByPlatform` are shown. The `title` and `artistName` from `entitiesByUniqueId` populate the embed header. - -**Optional:** An Odesli API key can be configured in Settings for higher rate limits. - ---- - -## Confidence Guard - -SwiftBot only posts the embed if `linksByPlatform` contains **at least one entry**. If Odesli returns an empty or error response, the bot stays silent — no noisy "couldn't match" messages. - ---- - -## Fallback — Secondary: Metadata API (V2, Opt-In) - -If Odesli returns no mapping (e.g., a niche track not in their database), SwiftBot can fall back to direct platform APIs in V2: - -| Fallback | API | Requirement | -|---------|-----|-------------| -| YouTube title lookup | YouTube Data API v3 | Operator-configured API key in Settings | -| Spotify track lookup | Spotify Web API | Operator-configured client ID + secret | - -Fallback is disabled by default. Operators who configure API keys in Settings unlock this path. - ---- - -## Cache & Rate Limit Guard - -To respect Odesli's free-tier rate limits and prevent duplicate embeds: - -- **Cache**: guild-scoped, in-memory, keyed on the input URL, 24-hour TTL. -- **Guard**: if the same URL has already been resolved in the same channel within 24 hours, the bot skips the API call and either re-posts the cached embed or stays silent (configurable). - -Cache is not persisted across restarts (in-memory only in V1; optional persistence in V2). - ---- - -## Discord Embed Format - -``` -🎵 Song Title - by Artist Name - -Spotify → open.spotify.com/… -YouTube → youtube.com/watch?v=… -Apple Music → music.apple.com/… -Tidal → tidal.com/… - -Full link card: song.link/… -``` - -- Only platforms present in the Odesli response are shown. -- Embed thumbnail uses `thumbnailUrl` from the Odesli entity (V2). -- `pageUrl` (song.link short URL) shown as footer. - ---- - -## Settings - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| `musicLinkConversionEnabled` | Bool | `true` | Master toggle | -| `odesliAPIKey` | String | _(empty)_ | Optional; unlocks higher rate limits | -| `musicIgnoredChannelIds` | [String] | _(empty)_ | Channels where conversion is suppressed | -| `musicFallbackEnabled` | Bool | `false` | Enable YouTube/Spotify metadata fallback (V2) | - ---- - -## Integration Points - -| File | Change | -|------|--------| -| `AppModel.swift` | Add `MusicLinkConverter.extractMusicURL(from:)` call in `handleMessageCreate`, before command prefix check | -| `AppModel.swift` | Reuse existing `sendEmbed(_:embed:)` for response | -| `BotSettings` | Add above settings fields | -| `RootView.swift` | Add toggle in Settings panel (V1); full Music section (V2) | - -No changes to `DiscordService.swift`, `ClusterCoordinator.swift`, or test targets. - ---- - -## New Component: `MusicLinkConverter` - -```swift -// Planned interface — no implementation yet -struct MusicLinkConverter { - /// Extracts the first music service URL from message text, or nil if none found. - static func extractMusicURL(from text: String) -> URL? - - /// Resolves a music URL via the Odesli API. - static func resolve(url: URL, apiKey: String?) async -> OdesliResponse? - - /// Builds a Discord embed payload from an Odesli response. - static func buildEmbed(from response: OdesliResponse, originalURL: URL) -> [String: Any] -} -``` - ---- - -## Rollout Phases - -### V1 — Core Odesli Integration -- Detection + domain filter -- Odesli API call (no key) -- Embed with platform links (text only, no thumbnail) -- In-memory 24h cache -- `musicLinkConversionEnabled` toggle - -### V2 — Polish + Fallback -- Embed thumbnail from `thumbnailUrl` -- Optional Odesli API key support -- Optional YouTube/Spotify metadata fallback -- Ignored-channel list -- Per-guild enable/disable - ---- - -## Legal & Compliance - -> SwiftBot provides metadata linking and cross-platform resolution only. No hosting, streaming relay, or downloading of copyrighted material is performed. Operators are responsible for complying with all platform Terms of Service. - -- Odesli [Terms of Service](https://odesli.co) permit free, non-commercial API use for link sharing. -- All links in SwiftBot embeds point to the original licensed platforms. -- SwiftBot does not store or cache any music content — only URLs (strings). -- YouTube Data API and Spotify Web API usage (V2 fallback) is subject to their respective developer Terms of Service. Operators who configure these keys accept responsibility for their usage. - ---- - -*Last updated: 2026-03-06 — Design only, no implementation yet.* diff --git a/notes/swiftmesh-risk-matrix.md b/notes/swiftmesh-risk-matrix.md index 9d77c71e..90557f26 100644 --- a/notes/swiftmesh-risk-matrix.md +++ b/notes/swiftmesh-risk-matrix.md @@ -3,7 +3,7 @@ **Generated:** 2026-03-08 **Authors:** Claude, Codex, Gemini, Kimi (agent team discussion) **Status:** Draft — refreshed against current code on 2026-03-08 -**Related:** `notes/swiftmesh-plan.md`, `notes/swiftmesh-observed-behavior.md`, `RISK_MATRIX.md` +**Related:** `notes/swiftmesh-plan.md`, `notes/swiftmesh-observed-behavior.md` This document tracks areas where SwiftMesh can be made better — new capabilities, reliability improvements, UX enhancements, and fixes. Risks are flagged inline where relevant. From c6065e17d3fa3b5be8158d2faac911921a14174a Mon Sep 17 00:00:00 2001 From: johnwatso Date: Thu, 7 May 2026 22:41:43 +1200 Subject: [PATCH 11/41] Add native and web analytics dashboard --- SwiftBotApp/AdminWebServer.swift | 128 ++- SwiftBotApp/AnalyticsView.swift | 1272 ++++++++++++++++++++++-- SwiftBotApp/AppModel+AdminWeb.swift | 421 +++++++- SwiftBotApp/Resources/admin/index.html | 541 +++++++++- 4 files changed, 2206 insertions(+), 156 deletions(-) diff --git a/SwiftBotApp/AdminWebServer.swift b/SwiftBotApp/AdminWebServer.swift index 65007386..82a873be 100644 --- a/SwiftBotApp/AdminWebServer.swift +++ b/SwiftBotApp/AdminWebServer.swift @@ -85,6 +85,95 @@ struct AdminWebOverviewPayload: Codable { let botInfo: AdminWebBotInfoPayload } +struct AdminWebAnalyticsMetricPayload: Codable { + let id: String + let title: String + let value: String + let detail: String + let trend: String + let tone: String +} + +struct AdminWebAnalyticsDayPayload: Codable { + let date: Date + let label: String + let count: Int +} + +struct AdminWebAnalyticsHourPayload: Codable { + let hour: Int + let label: String + let count: Int +} + +struct AdminWebAnalyticsTopUserPayload: Codable { + let id: String + let username: String + let initials: String + let totalTime: String + let activityShare: Int + let isActive: Bool +} + +struct AdminWebAnalyticsFeedEntryPayload: Codable { + let id: String + let timestamp: Date + let title: String + let detail: String + let category: String + let tone: String +} + +struct AdminWebAnalyticsHealthPayload: Codable { + let state: String + let detail: String + let websocketLatencyMs: Int? + let reconnectCount: Int + let activeTasks: Int + let eventQueueDepth: Int + let eventQueueLoad: Double + let memoryText: String +} + +struct AdminWebAnalyticsInsightPayload: Codable { + let title: String + let body: String + let tone: String +} + +struct AdminWebAnalyticsPayload: Codable { + let generatedAt: Date + let peakActivityLabel: String + let metrics: [AdminWebAnalyticsMetricPayload] + let dailyActivity: [AdminWebAnalyticsDayPayload] + let hourlyActivity: [AdminWebAnalyticsHourPayload] + let topUsers: [AdminWebAnalyticsTopUserPayload] + let feed: [AdminWebAnalyticsFeedEntryPayload] + let health: AdminWebAnalyticsHealthPayload + let insights: [AdminWebAnalyticsInsightPayload] + + static let empty = AdminWebAnalyticsPayload( + generatedAt: Date(), + peakActivityLabel: "Waiting for activity", + metrics: [], + dailyActivity: [], + hourlyActivity: [], + topUsers: [], + feed: [], + health: AdminWebAnalyticsHealthPayload( + state: "healthy", + detail: "Runtime analytics are waiting for the app state.", + websocketLatencyMs: nil, + reconnectCount: 0, + activeTasks: 0, + eventQueueDepth: 0, + eventQueueLoad: 0, + memoryText: "-" + ), + insights: [] + ) +} + struct AdminWebConfigPayload: Codable { struct Commands: Codable { let enabled: Bool @@ -418,6 +507,7 @@ actor AdminWebServer { private var activeTransportUsesTLS = false private var statusProvider: (@Sendable () async -> AdminWebStatusPayload)? private var overviewProvider: (@Sendable () async -> AdminWebOverviewPayload)? + private var analyticsProvider: (@Sendable () async -> AdminWebAnalyticsPayload)? private var remoteStatusProvider: (@Sendable () async -> RemoteStatusPayload)? private var remoteRulesProvider: (@Sendable () async -> RemoteRulesPayload)? private var updateRemoteRule: (@Sendable (Rule) async -> Bool)? @@ -483,6 +573,7 @@ actor AdminWebServer { remoteSettingsProvider: @escaping @Sendable () async -> AdminWebConfigPayload, updateRemoteSettings: @escaping @Sendable (AdminWebConfigPatch) async -> Bool, overviewProvider: @escaping @Sendable () async -> AdminWebOverviewPayload, + analyticsProvider: @escaping @Sendable () async -> AdminWebAnalyticsPayload, connectedGuildIDsProvider: @escaping @Sendable () async -> Set, currentPrefixProvider: @escaping @Sendable () async -> String, updatePrefix: @escaping @Sendable (String) async -> Bool, @@ -534,6 +625,7 @@ actor AdminWebServer { self.remoteSettingsProvider = remoteSettingsProvider self.updateRemoteSettings = updateRemoteSettings self.overviewProvider = overviewProvider + self.analyticsProvider = analyticsProvider self.connectedGuildIDsProvider = connectedGuildIDsProvider self.currentPrefixProvider = currentPrefixProvider self.updatePrefix = updatePrefix @@ -992,6 +1084,12 @@ actor AdminWebServer { botInfo: AdminWebBotInfoPayload(uptime: "--", errors: 0, state: "Stopped", cluster: nil) ) return codableResponse(payload) + case ("GET", "/api/analytics"): + guard authenticatedSession(for: request) != nil else { + return unauthorizedResponse() + } + let payload = await analyticsProvider?() ?? AdminWebAnalyticsPayload.empty + return codableResponse(payload) case ("GET", "/api/me"): guard let session = authenticatedSession(for: request) else { return unauthorizedResponse() @@ -2000,39 +2098,15 @@ actor AdminWebServer { } private func redirectURI() -> String { - var resolvedBase = activePublicBaseURL.isEmpty + let resolvedBase = activePublicBaseURL.isEmpty ? resolvedPublicBaseURL(usingTLS: config.https != nil) : activePublicBaseURL - // Ensure scheme exists - if !resolvedBase.isEmpty && !resolvedBase.contains("://") { - resolvedBase = "https://" + resolvedBase - } - - let path = config.redirectPath.hasPrefix("/") ? config.redirectPath : "/" + config.redirectPath - Task { - await logger?("[OAuth] Constructing redirectURI from base='\(resolvedBase)' and path='\(path)'") - } - - guard var components = URLComponents(string: resolvedBase) else { - let fallback = resolvedBase + (resolvedBase.hasSuffix("/") ? String(path.dropFirst()) : path) - Task { - await logger?("[OAuth] redirectURI fallback construction: \(fallback)") - } - return fallback - } - - // Handle existing path in base URL (e.g. proxy subpath) - if !components.path.isEmpty && components.path != "/" { - let basePath = components.path.hasSuffix("/") ? String(components.path.dropLast()) : components.path - let subPath = path.hasPrefix("/") ? path : "/" + path - components.path = basePath + subPath - } else { - components.path = path + await logger?("[OAuth] Constructing redirectURI from base='\(resolvedBase)' and path='\(config.redirectPath)'") } - let result = components.url?.absoluteString ?? (resolvedBase + (resolvedBase.hasSuffix("/") ? String(path.dropFirst()) : path)) + let result = adminWebOAuthRedirectURL(baseURL: resolvedBase, redirectPath: config.redirectPath) Task { await logger?("[OAuth] Resulting redirectURI: \(result)") diff --git a/SwiftBotApp/AnalyticsView.swift b/SwiftBotApp/AnalyticsView.swift index d5d02525..c97433e8 100644 --- a/SwiftBotApp/AnalyticsView.swift +++ b/SwiftBotApp/AnalyticsView.swift @@ -4,24 +4,81 @@ import SwiftUI struct AnalyticsView: View { @EnvironmentObject var app: AppModel - @State private var dailyActivity: [(date: Date, count: Int)] = [] - @State private var hourlyActivity: [(hour: Int, count: Int)] = [] - @State private var topUsers: [(username: String, seconds: Int)] = [] - @State private var mostActiveDay: String = "—" - @State private var totalSecondsThisWeek: Int = 0 - @State private var sessionCountThisWeek: Int = 0 + @State private var snapshot = AnalyticsSnapshot.empty + @State private var updatedAt = Date() + @State private var hoveredUserID: String? + + private var dailyActivity: [AnalyticsDaySample] { snapshot.voice.dailyActivity } + private var hourlyActivity: [AnalyticsHourSample] { snapshot.voice.hourlyActivity } + private var topUsers: [AnalyticsTopUser] { snapshot.voice.topUsers } + private var mostActiveDay: String { snapshot.voice.mostActiveDay } + private var totalSecondsThisWeek: Int { snapshot.voice.totalSecondsThisWeek } + private var sessionCountThisWeek: Int { snapshot.voice.sessionCountThisWeek } + + private var averageSessionsPerDay: Double { + snapshot.voice.averageSessionsPerDay + } + + private var peakHour: AnalyticsHourSample? { + snapshot.voice.peakHour + } + + private var commandsToday: Int { + snapshot.system.commandsToday + } + + private var failedCommandsToday: Int { + snapshot.system.failedCommandsToday + } + + private var successRate: Double { + snapshot.system.commandSuccessRate + } + + private var activeWorkflowCount: Int { + snapshot.system.activeWorkflowCount + } + + private var eventQueueLoad: Double { + snapshot.health.eventQueueLoad + } + + private var rollingEventCount: Int { snapshot.system.rollingEventCount } + private var eventFeed: [AnalyticsFeedEntry] { snapshot.feed } + + private var dailyChartDomain: ClosedRange { + guard let first = dailyActivity.first?.date, let last = dailyActivity.last?.date else { + let now = Date() + return now...now + } + let calendar = Calendar.current + let lower = calendar.date(byAdding: .hour, value: -10, to: first) ?? first + let upper = calendar.date(byAdding: .hour, value: 10, to: last) ?? last + return lower...upper + } var body: some View { VStack(alignment: .leading, spacing: 12) { - ViewSectionHeader(title: "Analytics", symbol: "chart.line.uptrend.xyaxis") + header ScrollView { - VStack(alignment: .leading, spacing: 14) { - overviewCards - dailyChart - HStack(alignment: .top, spacing: 14) { - hourlyChart - topUsersChart + VStack(alignment: .leading, spacing: 12) { + heroSummary + + activityOverview + + HStack(alignment: .top, spacing: 12) { + systemActivity + .frame(maxWidth: .infinity) + botHealth + .frame(maxWidth: .infinity) + } + + HStack(alignment: .top, spacing: 12) { + insightsSection + .frame(maxWidth: .infinity) + topUsersSection + .frame(maxWidth: .infinity) } } .padding(.bottom, 16) @@ -30,173 +87,540 @@ struct AnalyticsView: View { .padding(.horizontal, 16) .padding(.top, 10) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - .task { await loadData() } + .task { + await loadData() + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: 15_000_000_000) + await loadData() + } + } .refreshable { await loadData() } + .animation(.smooth(duration: 0.30), value: sessionCountThisWeek) + .animation(.smooth(duration: 0.30), value: app.gatewayEventCount) + .animation(.smooth(duration: 0.35), value: app.activeVoice.count) + } + + private var header: some View { + HStack(alignment: .center) { + ViewSectionHeader(title: "Analytics", symbol: "chart.line.uptrend.xyaxis") + Spacer() + liveBadge + } + } + + private var liveBadge: some View { + TimelineView(.animation) { timeline in + let pulse = app.status == .running ? (sin(timeline.date.timeIntervalSince1970 * 3.4) + 1) / 2 : 0 + HStack(spacing: 8) { + Circle() + .fill(app.status == .running ? .green : .secondary) + .frame(width: 8, height: 8) + .overlay { + Circle() + .stroke(app.status == .running ? Color.green.opacity(0.35) : .clear, lineWidth: 5) + .scaleEffect(1 + pulse * 0.5) + .opacity(0.25 + pulse * 0.45) + } + Text(app.status == .running ? "Live" : app.status.rawValue.capitalized) + .font(.caption.weight(.semibold)) + Text("Updated \(relativeUpdateText)") + .font(.caption2) + .foregroundStyle(.secondary) + } + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background(.thinMaterial, in: Capsule()) + .overlay(Capsule().strokeBorder(.white.opacity(0.12), lineWidth: 1)) + } } - // MARK: - Overview Cards + private var heroSummary: some View { + VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .firstTextBaseline) { + VStack(alignment: .leading, spacing: 4) { + Text("Operational Pulse") + .font(.title3.weight(.semibold)) + Text(heroSubtitle) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + if let uptime = app.uptime { + Label(uptime.text, systemImage: "timer") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + } - private var overviewCards: some View { - analyticsCard(title: "This Week", symbol: "calendar.badge.clock") { - LazyVGrid(columns: [GridItem(.adaptive(minimum: 160), spacing: 10)], spacing: 10) { - metricTile( + LazyVGrid(columns: [GridItem(.adaptive(minimum: 190), spacing: 8)], spacing: 8) { + metricCard( title: "Voice Sessions", value: "\(sessionCountThisWeek)", - symbol: "waveform" + detail: "\(app.activeVoice.count) currently active", + symbol: "waveform", + tint: .cyan, + prominence: .primary ) - metricTile( + metricCard( title: "Total Voice Time", value: formattedDuration(totalSecondsThisWeek), - symbol: "clock" + detail: "Average session \(formattedDuration(averageSessionSeconds))", + symbol: "clock", + tint: .blue, + prominence: .primary ) - metricTile( + metricCard( title: "Most Active Day", value: mostActiveDay, - symbol: "sun.max" + detail: peakDayDetail, + symbol: "calendar.day.timeline.leading", + tint: .indigo, + prominence: .secondary ) - metricTile( + metricCard( title: "Top User", - value: topUsers.first?.username ?? "—", - symbol: "person.fill" + value: topUsers.first?.username ?? "-", + detail: topUsers.first.map { "\($0.activityShare)% of tracked voice time" } ?? "No completed sessions yet", + symbol: "person.fill", + tint: .teal, + prominence: .secondary ) } } + .padding(11) + .glassCard(cornerRadius: 22, tint: .white.opacity(0.07), stroke: .white.opacity(0.18)) + } + + private var activityOverview: some View { + analyticsCard(title: "Activity Overview", subtitle: peakHour.map { "Peak activity at \(hourLabel($0.hour))" } ?? "Live operational timeline", symbol: "dot.radiowaves.left.and.right") { + HStack(alignment: .top, spacing: 14) { + runtimeActivityChart + .frame(minWidth: 420, maxWidth: .infinity) + + runtimeFeedPanel + .frame(minWidth: 240, idealWidth: 280, maxWidth: 340) + } + } } - // MARK: - Daily Activity Chart + private var runtimeActivityChart: some View { + VStack(alignment: .leading, spacing: 5) { + HStack { + Text("Voice Activity") + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + Spacer() + Text("Last 7 days") + .font(.caption2) + .foregroundStyle(.tertiary) + } - private var dailyChart: some View { - analyticsCard(title: "Voice Activity — Last 7 Days", symbol: "chart.bar.fill") { - if !dailyActivity.contains(where: { $0.1 > 0 }) { + if !dailyActivity.contains(where: { hasValue($0.count) }) { emptyState("No voice sessions recorded yet") } else { - Chart(dailyActivity, id: \.date) { item in - BarMark( - x: .value("Day", item.date, unit: .day), - y: .value("Sessions", item.count) - ) - .foregroundStyle(Color.accentColor.gradient) - .cornerRadius(4) + Chart { + ForEach(dailyActivity) { item in + AreaMark( + x: .value("Day", item.date, unit: .day), + y: .value("Sessions", item.count) + ) + .interpolationMethod(.catmullRom) + .foregroundStyle( + LinearGradient( + colors: [.accentColor.opacity(0.22), .accentColor.opacity(0.025)], + startPoint: .top, + endPoint: .bottom + ) + ) + + LineMark( + x: .value("Day", item.date, unit: .day), + y: .value("Sessions", item.count) + ) + .interpolationMethod(.catmullRom) + .lineStyle(StrokeStyle(lineWidth: 2.4, lineCap: .round, lineJoin: .round)) + .foregroundStyle(Color.accentColor) + + PointMark( + x: .value("Day", item.date, unit: .day), + y: .value("Sessions", item.count) + ) + .symbolSize(item.count == snapshot.voice.peakDayCount ? 48 : 20) + .foregroundStyle(Color.accentColor.opacity(0.82)) + } + + RuleMark(y: .value("Average", averageSessionsPerDay)) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 4])) + .foregroundStyle(.secondary.opacity(0.32)) + } + .chartPlotStyle { plot in + plot + .background(.black.opacity(0.035)) + .padding(.horizontal, 7) } + .chartXScale(domain: dailyChartDomain) .chartXAxis { AxisMarks(values: .stride(by: .day)) { _ in - AxisGridLine() + AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5)) + .foregroundStyle(.white.opacity(0.035)) AxisValueLabel(format: .dateTime.weekday(.abbreviated)) + .foregroundStyle(.secondary) } } .chartYAxis { AxisMarks { _ in - AxisGridLine() + AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5)) + .foregroundStyle(.white.opacity(0.035)) AxisValueLabel() + .foregroundStyle(.secondary) } } - .frame(height: 160) + .padding(.horizontal, 2) + .frame(height: 154) } } } - // MARK: - Hourly Activity Chart + private var runtimeFeedPanel: some View { + VStack(alignment: .leading, spacing: 7) { + HStack { + Text("Live Operations") + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + Spacer() + Text("\(rollingEventCount) recent") + .font(.caption2.monospacedDigit()) + .foregroundStyle(.tertiary) + } - private var hourlyChart: some View { - analyticsCard(title: "Activity by Hour", symbol: "clock.badge.checkmark") { - if !hourlyActivity.contains(where: { $0.1 > 0 }) { - emptyState("No data") - } else { - Chart(hourlyActivity, id: \.hour) { item in - BarMark( - x: .value("Hour", item.hour), - y: .value("Sessions", item.count) - ) - .foregroundStyle(Color.purple.gradient) - .cornerRadius(2) - } - .chartXAxis { - AxisMarks(values: [0, 6, 12, 18, 23]) { value in - AxisGridLine() - AxisValueLabel { - if let hour = value.as(Int.self) { - Text(hourLabel(hour)) - .font(.caption2) - } - } + VStack(spacing: 0) { + ForEach(Array(eventFeed.prefix(5).enumerated()), id: \.element.id) { index, entry in + timelineRow(entry) + if index < min(eventFeed.count, 5) - 1 { + Divider() + .opacity(0.26) + .padding(.leading, 30) } } - .frame(height: 130) } } - .frame(maxWidth: .infinity) + .padding(.horizontal, 9) + .padding(.vertical, 8) + .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 13, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 13, style: .continuous) + .strokeBorder(.white.opacity(0.08), lineWidth: 1) + ) + } + + private var systemActivity: some View { + analyticsCard(title: "System Activity", subtitle: "Runtime signals", symbol: "bolt.horizontal.circle") { + VStack(spacing: 7) { + compactSignal( + title: "Commands Today", + value: "\(commandsToday)", + detail: "\(app.stats.commandsRun) lifetime", + color: .cyan + ) + compactSignal( + title: "Failed Actions", + value: "\(failedCommandsToday)", + detail: "\(Int(successRate * 100))% command success", + color: failedCommandsToday > 0 ? .orange : .green + ) + compactSignal( + title: "Gateway Events", + value: "\(app.gatewayEventCount)", + detail: "Last: \(app.lastGatewayEventName)", + color: .blue + ) + compactSignal( + title: "Active Workflows", + value: "\(activeWorkflowCount)", + detail: snapshot.system.automationDetail, + color: .teal + ) + } + } } - // MARK: - Top Users Chart + private var botHealth: some View { + analyticsCard(title: "Bot Health", subtitle: snapshot.health.state.title, symbol: "waveform.path.ecg") { + VStack(spacing: 8) { + HStack(spacing: 8) { + Image(systemName: snapshot.health.state.symbol) + .font(.caption.weight(.semibold)) + .foregroundStyle(snapshot.health.state.color) + Text(snapshot.health.state.detail) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + Spacer(minLength: 0) + } + .padding(.horizontal, 8) + .padding(.vertical, 6) + .background(snapshot.health.state.color.opacity(0.08), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + + healthRow( + title: "Gateway Ping", + value: snapshot.health.websocketLatencyMs.map { "\($0) ms" } ?? "-", + progress: latencyProgress, + color: latencyColor + ) + healthRow( + title: "Event Queue", + value: "\(snapshot.health.eventQueueDepth)/20", + progress: eventQueueLoad, + color: eventQueueLoad > 0.75 ? .orange : .green + ) + healthRow( + title: "Concurrent Tasks", + value: "\(concurrentTaskCount)", + progress: min(Double(concurrentTaskCount) / 8.0, 1.0), + color: .blue + ) + healthRow( + title: "Memory", + value: snapshot.health.memoryText, + progress: nil, + color: .purple + ) + } + } + } - private var topUsersChart: some View { - analyticsCard(title: "Top Voice Users", symbol: "person.3.fill") { + private var topUsersSection: some View { + analyticsCard(title: "Top Users", subtitle: "Ranked voice activity", symbol: "person.3.fill") { if topUsers.isEmpty { - emptyState("No data") + emptyState("No completed voice sessions yet") } else { - Chart(topUsers, id: \.username) { item in - BarMark( - x: .value("Time", item.seconds), - y: .value("User", item.username) - ) - .foregroundStyle(Color.teal.gradient) - .cornerRadius(4) + VStack(spacing: 6) { + ForEach(Array(topUsers.prefix(5).enumerated()), id: \.element.id) { index, user in + rankedUserRow(rank: index + 1, user: user) + } } - .chartXAxis { - AxisMarks { value in - AxisGridLine() - AxisValueLabel { - if let secs = value.as(Int.self) { - Text(formattedDuration(secs)) - .font(.caption2) - } + } + } + .frame(maxWidth: .infinity) + } + + private var insightsSection: some View { + analyticsCard(title: "Insights", subtitle: "Generated from live app state", symbol: "sparkles") { + LazyVGrid(columns: [GridItem(.adaptive(minimum: 240), spacing: 8)], spacing: 8) { + ForEach(insights) { insight in + HStack(alignment: .top, spacing: 10) { + Image(systemName: insight.symbol) + .font(.subheadline.weight(.semibold)) + .foregroundStyle(insight.color) + .frame(width: 20) + VStack(alignment: .leading, spacing: 3) { + Text(insight.title) + .font(.caption.weight(.semibold)) + Text(insight.body) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } + Spacer(minLength: 0) } + .padding(9) + .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder(insight.color.opacity(0.18), lineWidth: 1) + ) } - .frame(height: 130) } } - .frame(maxWidth: .infinity) } - // MARK: - Helpers + private func timelineRow(_ entry: AnalyticsFeedEntry) -> some View { + HStack(alignment: .center, spacing: 8) { + Image(systemName: entry.category.symbol) + .font(.caption2.weight(.semibold)) + .foregroundStyle(entry.category.color) + .frame(width: 20) + + VStack(alignment: .leading, spacing: 1) { + Text(entry.title) + .font(.caption.weight(.semibold)) + .lineLimit(1) + Text(entry.detail) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer(minLength: 8) + Text(entry.timestamp, style: .relative) + .font(.caption2.monospacedDigit()) + .foregroundStyle(.tertiary) + } + .padding(.vertical, 6) + } private func analyticsCard( title: String, + subtitle: String, symbol: String, @ViewBuilder content: () -> Content ) -> some View { - VStack(alignment: .leading, spacing: 10) { - HStack(spacing: 8) { + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .firstTextBaseline, spacing: 8) { Image(systemName: symbol) .font(.subheadline.weight(.semibold)) .foregroundStyle(.secondary) Text(title) .font(.subheadline.weight(.semibold)) + Text(subtitle) + .font(.caption) + .foregroundStyle(.tertiary) + Spacer(minLength: 0) } content() } - .padding(12) - .commandCatalogSurface(cornerRadius: 14) + .padding(10) + .glassCard(cornerRadius: 18, tint: .white.opacity(0.06), stroke: .white.opacity(0.14)) } - private func metricTile(title: String, value: String, symbol: String) -> some View { - HStack(spacing: 10) { - Image(systemName: symbol) - .font(.title3) - .foregroundStyle(.secondary) - .frame(width: 28) - VStack(alignment: .leading, spacing: 2) { + private func metricCard( + title: String, + value: String, + detail: String, + symbol: String, + tint: Color, + prominence: MetricProminence + ) -> some View { + VStack(alignment: .leading, spacing: 9) { + HStack { + Image(systemName: symbol) + .font(.headline.weight(.semibold)) + .foregroundStyle(tint) + .frame(width: 26, height: 26) + .background(tint.opacity(0.16), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + Spacer() + if prominence == .primary { + activityPulse(color: tint) + } + } + VStack(alignment: .leading, spacing: 4) { Text(value) - .font(.headline.monospacedDigit()) + .font(prominence == .primary ? .title2.weight(.semibold) : .headline.weight(.semibold)) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.72) Text(title) - .font(.caption) + .font(.caption.weight(.semibold)) .foregroundStyle(.secondary) + Text(detail) + .font(.caption2) + .foregroundStyle(.tertiary) + .lineLimit(1) } } - .padding(10) + .padding(11) .frame(maxWidth: .infinity, alignment: .leading) - .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .strokeBorder(tint.opacity(0.24), lineWidth: 1) + ) + } + + private func compactSignal(title: String, value: String, detail: String, color: Color) -> some View { + HStack(spacing: 9) { + RoundedRectangle(cornerRadius: 3, style: .continuous) + .fill(color) + .frame(width: 4, height: 28) + VStack(alignment: .leading, spacing: 2) { + Text(title) + .font(.caption) + .foregroundStyle(.secondary) + Text(detail) + .font(.caption2) + .foregroundStyle(.tertiary) + .lineLimit(1) + } + Spacer() + Text(value) + .font(.headline.weight(.semibold).monospacedDigit()) + .lineLimit(1) + } + .padding(.horizontal, 8) + .padding(.vertical, 7) + .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 11, style: .continuous)) + } + + private func healthRow(title: String, value: String, progress: Double?, color: Color) -> some View { + VStack(alignment: .leading, spacing: 4) { + HStack { + Text(title) + .font(.caption) + .foregroundStyle(.secondary) + Spacer() + Text(value) + .font(.caption.weight(.semibold).monospacedDigit()) + } + if let progress { + ProgressView(value: max(0, min(progress, 1))) + .tint(color) + .controlSize(.small) + } + } + } + + private func rankedUserRow(rank: Int, user: AnalyticsTopUser) -> some View { + VStack(spacing: 5) { + HStack(spacing: 9) { + Text("\(rank)") + .font(.caption.weight(rank == 1 ? .bold : .semibold).monospacedDigit()) + .foregroundStyle(rank == 1 ? Color.accentColor : .secondary) + .frame(width: 18) + ZStack { + Circle() + .fill(user.isActive ? Color.green.opacity(0.18) : Color.accentColor.opacity(rank == 1 ? 0.18 : 0.12)) + Text(user.initials) + .font(.caption.weight(.bold)) + .foregroundStyle(user.isActive ? .green : .accentColor) + } + .frame(width: 30, height: 30) + + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 5) { + Text(user.username) + .font(.caption.weight(.semibold)) + .lineLimit(1) + if user.isActive { + activityPulse(color: .green) + .frame(width: 10, height: 10) + } + } + Text("\(formattedDuration(user.seconds)) total activity") + .font(.caption2) + .foregroundStyle(.secondary) + } + Spacer() + Text("\(user.activityShare)%") + .font(.caption.weight(.semibold).monospacedDigit()) + .foregroundStyle(.secondary) + } + + ProgressView(value: Double(user.activityShare), total: 100) + .tint(rank == 1 ? .accentColor : .secondary.opacity(0.45)) + .controlSize(.mini) + } + .padding(.horizontal, 8) + .padding(.vertical, 7) + .background( + (hoveredUserID == user.id ? AnyShapeStyle(.thinMaterial) : AnyShapeStyle(.ultraThinMaterial)), + in: RoundedRectangle(cornerRadius: 11, style: .continuous) + ) + .overlay( + RoundedRectangle(cornerRadius: 11, style: .continuous) + .strokeBorder(rank == 1 ? Color.accentColor.opacity(0.18) : .white.opacity(0.06), lineWidth: 1) + ) + .onHover { isHovering in + hoveredUserID = isHovering ? user.id : nil + } } private func emptyState(_ message: String) -> some View { @@ -206,6 +630,143 @@ struct AnalyticsView: View { .frame(maxWidth: .infinity, minHeight: 60, alignment: .center) } + private func activityPulse(color: Color) -> some View { + TimelineView(.animation) { timeline in + let pulse = (sin(timeline.date.timeIntervalSince1970 * 2.8) + 1) / 2 + Circle() + .fill(color.opacity(0.34)) + .frame(width: 7, height: 7) + .overlay { + Circle() + .stroke(color.opacity(0.20), lineWidth: 4) + .scaleEffect(1 + pulse * 0.45) + .opacity(0.25 + pulse * 0.35) + } + } + .frame(width: 18, height: 18) + } + + private var insights: [AnalyticsInsight] { + var output: [AnalyticsInsight] = [] + + if let peakDay = dailyActivity.max(by: { $0.count < $1.count }), hasValue(peakDay.count), averageSessionsPerDay > 0 { + let lift = Int(((Double(peakDay.count) / max(averageSessionsPerDay, 1)) - 1) * 100) + output.append(AnalyticsInsight( + title: "Weekly concentration", + body: "\(weekdayName(for: peakDay.date)) ran \(max(lift, 0))% above the 7-day average.", + symbol: "chart.line.uptrend.xyaxis", + color: .cyan + )) + } + + if let peakHour { + output.append(AnalyticsInsight( + title: "Voice peak window", + body: "Voice sessions are most likely to start around \(hourLabel(peakHour.hour)).", + symbol: "clock", + color: .blue + )) + } + + if snapshot.health.state == .warning || snapshot.health.state == .degraded || snapshot.health.state == .recovering { + output.append(AnalyticsInsight( + title: "Health attention", + body: snapshot.health.state.detail, + symbol: snapshot.health.state.symbol, + color: snapshot.health.state.color + )) + } else { + output.append(AnalyticsInsight( + title: "Gateway stable", + body: "No abnormal gateway close is currently recorded.", + symbol: "checkmark.seal", + color: .green + )) + } + + output.append(AnalyticsInsight( + title: "Command reliability", + body: "\(Int(successRate * 100))% success across \(snapshot.system.commandsRunLifetime) tracked command runs.", + symbol: successRate >= 0.95 ? "checkmark.circle" : "exclamationmark.triangle", + color: successRate >= 0.95 ? .green : .orange + )) + + if snapshot.system.patchyCycleRunning || snapshot.system.automationRunsToday > 0 { + let body = snapshot.system.patchyCycleRunning + ? "Patchy is actively processing an automation cycle." + : "Automation completed a cycle today." + output.append(AnalyticsInsight( + title: "Automation cadence", + body: body, + symbol: "wand.and.stars", + color: .purple + )) + } + + return output + } + + private var heroSubtitle: String { + if app.status == .running { + return "\(app.activeVoice.count) users in voice, \(rollingEventCount) recent events, \(commandsToday) commands today" + } + return "Runtime analytics are ready when the bot is online" + } + + private var averageSessionSeconds: Int { + guard sessionCountThisWeek > 0 else { return 0 } + return totalSecondsThisWeek / sessionCountThisWeek + } + + private var peakDayDetail: String { + guard let peak = dailyActivity.max(by: { $0.count < $1.count }), hasValue(peak.count) else { + return "No completed sessions this week" + } + return "\(peak.count) sessions on \(weekdayName(for: peak.date))" + } + + private var concurrentTaskCount: Int { + var count = app.mediaExportJobs.filter { $0.status == .queued || $0.status == .running }.count + count += app.patchyIsCycleRunning ? 1 : 0 + count += app.activeBugAutoFixMessageIDs.count + return count + } + + private var latencyProgress: Double? { + guard let latency = snapshot.health.websocketLatencyMs else { return nil } + return min(Double(latency) / 500.0, 1.0) + } + + private var latencyColor: Color { + guard let latency = snapshot.health.websocketLatencyMs else { return .secondary } + if latency < 150 { return .green } + if latency < 300 { return .yellow } + return .orange + } + + private var relativeUpdateText: String { + let seconds = max(0, Int(Date().timeIntervalSince(updatedAt))) + if seconds < 2 { return "just now" } + if seconds < 60 { return "\(seconds)s ago" } + return "\(seconds / 60)m ago" + } + + private func color(for kind: ActivityEvent.Kind) -> Color { + switch kind { + case .voiceJoin: return .green + case .voiceLeave: return .red + case .voiceMove: return .blue + case .command: return .cyan + case .info: return .secondary + case .warning: return .orange + case .error: return .red + } + } + + private func hasValue(_ value: Int) -> Bool { + value > 0 + } + private func hourLabel(_ hour: Int) -> String { switch hour { case 0: return "12a" @@ -215,6 +776,10 @@ struct AnalyticsView: View { } } + private func weekdayName(for date: Date) -> String { + date.formatted(.dateTime.weekday(.wide)) + } + private func formattedDuration(_ seconds: Int) -> String { let hours = seconds / 3600 let minutes = (seconds % 3600) / 60 @@ -223,19 +788,506 @@ struct AnalyticsView: View { return "<1m" } + private func currentResidentMemoryBytes() -> UInt64 { + var info = mach_task_basic_info() + var count = mach_msg_type_number_t(MemoryLayout.size) / 4 + let result = withUnsafeMutablePointer(to: &info) { + $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { + task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count) + } + } + guard result == KERN_SUCCESS else { return 0 } + return UInt64(info.resident_size) + } + + @MainActor private func loadData() async { async let daily = app.voiceSessionStore.getVoiceActivityLast7Days() async let hourly = app.voiceSessionStore.getVoiceActivityByHour() async let users = app.voiceSessionStore.getTopVoiceUsers(limit: 5) - async let activeDay = app.voiceSessionStore.getMostActiveDay() async let totalTime = app.voiceSessionStore.getTotalVoiceTimeThisWeek() async let sessionCount = app.voiceSessionStore.getSessionCountThisWeek() - dailyActivity = await daily - hourlyActivity = await hourly - topUsers = await users - mostActiveDay = await activeDay ?? "—" - totalSecondsThisWeek = Int(await totalTime) - sessionCountThisWeek = await sessionCount + let loadedDaily = await daily + let loadedHourly = await hourly + let loadedUsers = await users + let loadedTotalSeconds = Int(await totalTime) + let activeUsernames = Set(app.activeVoice.map(\.username)) + + snapshot = AnalyticsAggregator.makeSnapshot( + dailyActivity: loadedDaily, + hourlyActivity: loadedHourly, + topUsers: loadedUsers, + totalSecondsThisWeek: loadedTotalSeconds, + sessionCountThisWeek: await sessionCount, + activeUsernames: activeUsernames, + app: app, + memoryBytes: currentResidentMemoryBytes() + ) + updatedAt = Date() + } +} + +private enum MetricProminence { + case primary + case secondary +} + +private struct AnalyticsSnapshot: Codable, Equatable { + let generatedAt: Date + let voice: AnalyticsVoiceSummary + let system: AnalyticsSystemMetrics + let health: AnalyticsHealthMetrics + let feed: [AnalyticsFeedEntry] + + static let empty = AnalyticsSnapshot( + generatedAt: Date(), + voice: .empty, + system: .empty, + health: .empty, + feed: [] + ) +} + +private struct AnalyticsVoiceSummary: Codable, Equatable { + let dailyActivity: [AnalyticsDaySample] + let hourlyActivity: [AnalyticsHourSample] + let topUsers: [AnalyticsTopUser] + let mostActiveDay: String + let totalSecondsThisWeek: Int + let sessionCountThisWeek: Int + + static let empty = AnalyticsVoiceSummary( + dailyActivity: [], + hourlyActivity: [], + topUsers: [], + mostActiveDay: "-", + totalSecondsThisWeek: 0, + sessionCountThisWeek: 0 + ) + + var averageSessionsPerDay: Double { + guard !dailyActivity.isEmpty else { return 0 } + return Double(dailyActivity.reduce(0) { $0 + $1.count }) / Double(dailyActivity.count) + } + + var peakHour: AnalyticsHourSample? { + hourlyActivity.max { $0.count < $1.count }.flatMap { $0.hasActivity ? $0 : nil } + } + + var peakDayCount: Int { + dailyActivity.map(\.count).max() ?? 0 + } +} + +private struct AnalyticsSystemMetrics: Codable, Equatable { + let commandsToday: Int + let failedCommandsToday: Int + let commandsRunLifetime: Int + let commandSuccessRate: Double + let activeWorkflowCount: Int + let automationRunsToday: Int + let failedAutomationCount: Int + let gatewayEventCount: Int + let rollingEventCount: Int + let eventThroughputPerMinute: Double + let lastGatewayEventName: String + let patchyCycleRunning: Bool + + static let empty = AnalyticsSystemMetrics( + commandsToday: 0, + failedCommandsToday: 0, + commandsRunLifetime: 0, + commandSuccessRate: 1, + activeWorkflowCount: 0, + automationRunsToday: 0, + failedAutomationCount: 0, + gatewayEventCount: 0, + rollingEventCount: 0, + eventThroughputPerMinute: 0, + lastGatewayEventName: "-", + patchyCycleRunning: false + ) + + var automationDetail: String { + if patchyCycleRunning { + return "Patchy running now" + } + if failedAutomationCount > 0 { + return "\(failedAutomationCount) failed automation events" + } + return "Rule engine ready" + } +} + +private struct AnalyticsHealthMetrics: Codable, Equatable { + let websocketLatencyMs: Int? + let reconnectCount: Int + let activeTaskCount: Int + let cpuUsagePercent: Double? + let memoryBytes: UInt64 + let memoryTrend: Double? + let eventQueueDepth: Int + let eventQueueLoad: Double + let apiResponseTimeMs: Double? + let state: AnalyticsHealthState + + static let empty = AnalyticsHealthMetrics( + websocketLatencyMs: nil, + reconnectCount: 0, + activeTaskCount: 0, + cpuUsagePercent: nil, + memoryBytes: 0, + memoryTrend: nil, + eventQueueDepth: 0, + eventQueueLoad: 0, + apiResponseTimeMs: nil, + state: .healthy + ) + + var memoryText: String { + guard memoryBytes > 0 else { return "-" } + return ByteCountFormatter.string(fromByteCount: Int64(memoryBytes), countStyle: .memory) + } +} + +private enum AnalyticsHealthState: String, Codable, Equatable { + case healthy + case warning + case degraded + case recovering + + var title: String { + switch self { + case .healthy: return "Healthy" + case .warning: return "Warning" + case .degraded: return "Degraded" + case .recovering: return "Recovering" + } + } + + var detail: String { + switch self { + case .healthy: return "Gateway, queue, and automation signals are nominal" + case .warning: return "One signal is elevated and worth watching" + case .degraded: return "Latency, queue, or failures indicate degraded operation" + case .recovering: return "Gateway is reconnecting or stabilizing after disruption" + } + } + + var symbol: String { + switch self { + case .healthy: return "checkmark.seal" + case .warning: return "exclamationmark.triangle" + case .degraded: return "waveform.path.ecg.rectangle" + case .recovering: return "arrow.triangle.2.circlepath" + } + } + + var color: Color { + switch self { + case .healthy: return .green + case .warning: return .orange + case .degraded: return .red + case .recovering: return .yellow + } + } +} + +private struct AnalyticsFeedEntry: Identifiable, Codable, Equatable { + let id: String + let timestamp: Date + let title: String + let detail: String + let category: AnalyticsFeedCategory +} + +private enum AnalyticsFeedCategory: String, Codable, Equatable { + case voice + case command + case gateway + case automation + case health + case system + + var symbol: String { + switch self { + case .voice: return "waveform" + case .command: return "terminal" + case .gateway: return "antenna.radiowaves.left.and.right" + case .automation: return "wand.and.stars" + case .health: return "waveform.path.ecg" + case .system: return "circle.hexagongrid" + } + } + + var color: Color { + switch self { + case .voice: return .blue + case .command: return .cyan + case .gateway: return .green + case .automation: return .purple + case .health: return .orange + case .system: return .secondary + } + } +} + +private enum AnalyticsAggregator { + @MainActor + static func makeSnapshot( + dailyActivity: [(date: Date, count: Int)], + hourlyActivity: [(hour: Int, count: Int)], + topUsers: [(username: String, seconds: Int)], + totalSecondsThisWeek: Int, + sessionCountThisWeek: Int, + activeUsernames: Set, + app: AppModel, + memoryBytes: UInt64, + now: Date = Date() + ) -> AnalyticsSnapshot { + let commandSuccessRate: Double = if app.stats.commandsRun > 0 { + Double(max(0, app.stats.commandsRun - app.stats.errors)) / Double(app.stats.commandsRun) + } else { + 1 + } + + let automationFailures = app.events.filter { + ($0.kind == .error || $0.kind == .warning) && + $0.message.localizedCaseInsensitiveContains("automation") + }.count + + let activeTaskCount = app.mediaExportJobs.filter { $0.status == .queued || $0.status == .running }.count + + (app.patchyIsCycleRunning ? 1 : 0) + + app.activeBugAutoFixMessageIDs.count + let rollingEvents = app.events.filter { now.timeIntervalSince($0.timestamp) <= 300 } + let healthState = healthState( + status: app.status, + latencyMs: app.connectionDiagnostics.heartbeatLatencyMs, + queueLoad: min(Double(app.events.count) / 20.0, 1.0), + failedCommandsToday: app.commandLog.filter { Calendar.current.isDateInToday($0.time) && !$0.ok }.count, + automationFailures: automationFailures + ) + + let voice = AnalyticsVoiceSummary( + dailyActivity: dailyActivity.map { AnalyticsDaySample(date: $0.date, count: $0.count) }, + hourlyActivity: hourlyActivity.map { AnalyticsHourSample(hour: $0.hour, count: $0.count) }, + topUsers: topUsers.map { user in + AnalyticsTopUser( + username: user.username, + seconds: user.seconds, + totalSeconds: totalSecondsThisWeek, + isActive: activeUsernames.contains(user.username) + ) + }, + mostActiveDay: deterministicMostActiveDay(from: dailyActivity), + totalSecondsThisWeek: totalSecondsThisWeek, + sessionCountThisWeek: sessionCountThisWeek + ) + + let system = AnalyticsSystemMetrics( + commandsToday: app.commandLog.filter { Calendar.current.isDateInToday($0.time) }.count, + failedCommandsToday: app.commandLog.filter { Calendar.current.isDateInToday($0.time) && !$0.ok }.count, + commandsRunLifetime: app.stats.commandsRun, + commandSuccessRate: commandSuccessRate, + activeWorkflowCount: app.ruleStore.rules.filter(\.isEnabled).count, + automationRunsToday: app.patchyLastCycleAt.map { Calendar.current.isDateInToday($0) ? 1 : 0 } ?? 0, + failedAutomationCount: automationFailures, + gatewayEventCount: app.gatewayEventCount, + rollingEventCount: rollingEvents.count, + eventThroughputPerMinute: Double(rollingEvents.count) / 5.0, + lastGatewayEventName: app.lastGatewayEventName, + patchyCycleRunning: app.patchyIsCycleRunning + ) + + let health = AnalyticsHealthMetrics( + websocketLatencyMs: app.connectionDiagnostics.heartbeatLatencyMs, + reconnectCount: app.status == .reconnecting ? 1 : 0, + activeTaskCount: activeTaskCount, + cpuUsagePercent: nil, + memoryBytes: memoryBytes, + memoryTrend: nil, + eventQueueDepth: app.events.count, + eventQueueLoad: min(Double(app.events.count) / 20.0, 1.0), + apiResponseTimeMs: nil, + state: healthState + ) + let feed = makeFeed(app: app, healthState: healthState, now: now) + + return AnalyticsSnapshot(generatedAt: now, voice: voice, system: system, health: health, feed: feed) + } + + private static func deterministicMostActiveDay(from dailyActivity: [(date: Date, count: Int)]) -> String { + let activeDays = dailyActivity + .filter { $0.count >= 1 } + .sorted { + if $0.count != $1.count { + return $0.count > $1.count + } + return $0.date < $1.date + } + guard let winner = activeDays.first else { return "-" } + return winner.date.formatted(.dateTime.weekday(.wide)) + } + + private static func healthState( + status: BotStatus, + latencyMs: Int?, + queueLoad: Double, + failedCommandsToday: Int, + automationFailures: Int + ) -> AnalyticsHealthState { + if status == .reconnecting { + return .recovering + } + if latencyMs.map({ $0 >= 500 }) == true || queueLoad >= 0.90 || failedCommandsToday >= 5 { + return .degraded + } + if latencyMs.map({ $0 >= 300 }) == true || queueLoad >= 0.70 || automationFailures > 0 || failedCommandsToday > 0 { + return .warning + } + return .healthy + } + + @MainActor + private static func makeFeed(app: AppModel, healthState: AnalyticsHealthState, now: Date) -> [AnalyticsFeedEntry] { + var entries: [AnalyticsFeedEntry] = [] + + entries += app.events.prefix(8).map { event in + AnalyticsFeedEntry( + id: "event-\(event.id)", + timestamp: event.timestamp, + title: title(for: event.kind), + detail: cleanedEventMessage(event.message), + category: category(for: event.kind) + ) + } + + entries += app.commandLog.prefix(5).map { command in + AnalyticsFeedEntry( + id: "command-\(command.id)", + timestamp: command.time, + title: command.ok ? "Command executed" : "Command failed", + detail: "\(command.user) ran \(command.command)", + category: .command + ) + } + + entries += app.voiceLog.prefix(4).map { voice in + AnalyticsFeedEntry( + id: "voice-\(voice.id)", + timestamp: voice.time, + title: "Voice activity", + detail: cleanedEventMessage(voice.description), + category: .voice + ) + } + + if let patchyLastCycleAt = app.patchyLastCycleAt { + entries.append(AnalyticsFeedEntry( + id: "patchy-\(patchyLastCycleAt.timeIntervalSince1970)", + timestamp: patchyLastCycleAt, + title: app.patchyIsCycleRunning ? "Automation running" : "Automation completed", + detail: "Patchy update cycle processed", + category: .automation + )) + } + + if healthState != .healthy { + entries.append(AnalyticsFeedEntry( + id: "health-\(healthState.rawValue)-\(Int(now.timeIntervalSince1970 / 60))", + timestamp: now, + title: "\(healthState.title) health state", + detail: healthState.detail, + category: .health + )) + } + + entries.append(AnalyticsFeedEntry( + id: "launch-\(app.launchedAt.timeIntervalSince1970)", + timestamp: app.launchedAt, + title: "Analytics pipeline initialized", + detail: "SwiftBot runtime metrics are being aggregated", + category: .system + )) + + let sortedEntries = entries.sorted { lhs, rhs in + if lhs.timestamp != rhs.timestamp { + return lhs.timestamp > rhs.timestamp + } + return lhs.id < rhs.id + } + return Array(sortedEntries.prefix(12)) + } + + private static func title(for kind: ActivityEvent.Kind) -> String { + switch kind { + case .voiceJoin: return "Voice session started" + case .voiceLeave: return "Voice session ended" + case .voiceMove: return "Voice channel changed" + case .command: return "Command executed" + case .info: return "System event" + case .warning: return "Operational warning" + case .error: return "Operational error" + } + } + + private static func category(for kind: ActivityEvent.Kind) -> AnalyticsFeedCategory { + switch kind { + case .voiceJoin, .voiceLeave, .voiceMove: return .voice + case .command: return .command + case .warning, .error: return .health + case .info: return .system + } + } + + private static func cleanedEventMessage(_ message: String) -> String { + ["🟢 ", "🔴 ", "🔀 ", "✅ ", "⚠️ ", "❌ "].reduce(message) { cleaned, marker in + cleaned.replacingOccurrences(of: marker, with: "") + } + .trimmingCharacters(in: .whitespacesAndNewlines) + } +} + +private struct AnalyticsDaySample: Identifiable, Codable, Equatable { + var id: Date { date } + let date: Date + let count: Int +} + +private struct AnalyticsHourSample: Identifiable, Codable, Equatable { + var id: Int { hour } + let hour: Int + let count: Int + + var hasActivity: Bool { + count >= 1 + } +} + +private struct AnalyticsTopUser: Identifiable, Codable, Equatable { + var id: String { username } + let username: String + let seconds: Int + let totalSeconds: Int + let isActive: Bool + + var initials: String { + let pieces = username.split(separator: " ").prefix(2) + let letters = pieces.compactMap { $0.first }.map(String.init).joined() + return letters.isEmpty ? "?" : letters.uppercased() } + + var activityShare: Int { + guard totalSeconds > 0 else { return 0 } + return Int((Double(seconds) / Double(totalSeconds) * 100).rounded()) + } +} + +private struct AnalyticsInsight: Identifiable { + let id = UUID() + let title: String + let body: String + let symbol: String + let color: Color } diff --git a/SwiftBotApp/AppModel+AdminWeb.swift b/SwiftBotApp/AppModel+AdminWeb.swift index 28acf769..59004660 100644 --- a/SwiftBotApp/AppModel+AdminWeb.swift +++ b/SwiftBotApp/AppModel+AdminWeb.swift @@ -1,6 +1,34 @@ import Foundation import SwiftUI import AppKit +import Darwin + +func adminWebOAuthRedirectURL(baseURL rawBaseURL: String, redirectPath rawRedirectPath: String) -> String { + var baseURL = rawBaseURL.trimmingCharacters(in: .whitespacesAndNewlines) + guard !baseURL.isEmpty else { return "" } + + if !baseURL.contains("://") { + baseURL = "https://" + baseURL + } + + let trimmedPath = rawRedirectPath.trimmingCharacters(in: .whitespacesAndNewlines) + let path = trimmedPath.isEmpty + ? "/auth/discord/callback" + : (trimmedPath.hasPrefix("/") ? trimmedPath : "/" + trimmedPath) + + guard var components = URLComponents(string: baseURL) else { + return baseURL + (baseURL.hasSuffix("/") ? String(path.dropFirst()) : path) + } + + if !components.path.isEmpty && components.path != "/" { + let basePath = components.path.hasSuffix("/") ? String(components.path.dropLast()) : components.path + components.path = basePath + path + } else { + components.path = path + } + + return components.url?.absoluteString ?? (baseURL + (baseURL.hasSuffix("/") ? String(path.dropFirst()) : path)) +} extension AppModel { @@ -221,6 +249,382 @@ extension AppModel { ) } + func adminWebAnalyticsSnapshot() async -> AdminWebAnalyticsPayload { + async let daily = voiceSessionStore.getVoiceActivityLast7Days() + async let hourly = voiceSessionStore.getVoiceActivityByHour() + async let users = voiceSessionStore.getTopVoiceUsers(limit: 5) + async let totalTime = voiceSessionStore.getTotalVoiceTimeThisWeek() + async let sessionCount = voiceSessionStore.getSessionCountThisWeek() + + let now = Date() + let loadedDaily = await daily + let loadedHourly = await hourly + let loadedUsers = await users + let loadedTotalSeconds = Int(await totalTime) + let loadedSessionCount = await sessionCount + let activeUsernames = Set(activeVoice.map(\.username)) + let commandsToday = commandLog.filter { Calendar.current.isDateInToday($0.time) }.count + let failedCommandsToday = commandLog.filter { Calendar.current.isDateInToday($0.time) && !$0.ok }.count + let enabledRuleCount = ruleStore.rules.filter(\.isEnabled).count + let automationFailures = events.filter { + ($0.kind == .error || $0.kind == .warning) + && $0.message.localizedCaseInsensitiveContains("automation") + }.count + let activeTaskCount = mediaExportJobs.filter { $0.status == .queued || $0.status == .running }.count + + (patchyIsCycleRunning ? 1 : 0) + + activeBugAutoFixMessageIDs.count + let queueDepth = events.count + let queueLoad = min(Double(queueDepth) / 20.0, 1.0) + let healthState = adminWebAnalyticsHealthState( + latencyMs: connectionDiagnostics.heartbeatLatencyMs, + queueLoad: queueLoad, + failedCommandsToday: failedCommandsToday, + automationFailures: automationFailures + ) + let peakHour = loadedHourly.max { $0.count < $1.count }.flatMap { $0.count >= 1 ? $0 : nil } + let mostActiveDay = adminWebDeterministicMostActiveDay(from: loadedDaily) + let averageSession = loadedSessionCount > 0 ? loadedTotalSeconds / loadedSessionCount : 0 + let successRate = stats.commandsRun > 0 + ? Double(max(0, stats.commandsRun - stats.errors)) / Double(stats.commandsRun) + : 1 + + let metrics = [ + AdminWebAnalyticsMetricPayload( + id: "voice-sessions", + title: "Voice Sessions", + value: "\(loadedSessionCount)", + detail: "\(activeVoice.count) currently active", + trend: averageSession > 0 ? "Average \(adminWebFormatDuration(averageSession))" : "Waiting for completed sessions", + tone: "usage" + ), + AdminWebAnalyticsMetricPayload( + id: "voice-time", + title: "Total Voice Time", + value: adminWebFormatDuration(loadedTotalSeconds), + detail: "Last 7 days", + trend: averageSession > 0 ? "Average session \(adminWebFormatDuration(averageSession))" : "No completed sessions yet", + tone: "usage" + ), + AdminWebAnalyticsMetricPayload( + id: "most-active-day", + title: "Most Active Day", + value: mostActiveDay, + detail: adminWebPeakDayDetail(from: loadedDaily), + trend: peakHour.map { "Peak activity at \(adminWebHourLabel($0.hour))" } ?? "No hourly peak yet", + tone: "automation" + ), + AdminWebAnalyticsMetricPayload( + id: "top-user", + title: "Top User", + value: loadedUsers.first?.username ?? "-", + detail: loadedUsers.first.map { "\(adminWebActivityShare(seconds: $0.seconds, total: loadedTotalSeconds))% of tracked voice time" } ?? "No voice leaders yet", + trend: activeVoice.isEmpty ? "No live voice sessions" : "\(activeVoice.count) live voice users", + tone: "healthy" + ), + AdminWebAnalyticsMetricPayload( + id: "commands-today", + title: "Commands Today", + value: "\(commandsToday)", + detail: "\(stats.commandsRun) lifetime", + trend: "\(Int(successRate * 100))% command success", + tone: failedCommandsToday > 0 ? "warning" : "usage" + ), + AdminWebAnalyticsMetricPayload( + id: "active-workflows", + title: "Active Workflows", + value: "\(enabledRuleCount)", + detail: patchyIsCycleRunning ? "Patchy running now" : "Rule engine ready", + trend: automationFailures > 0 ? "\(automationFailures) automation warnings" : "Automation nominal", + tone: automationFailures > 0 ? "warning" : "automation" + ) + ] + + let topUsers = loadedUsers.map { user in + AdminWebAnalyticsTopUserPayload( + id: user.username, + username: user.username, + initials: adminWebInitials(for: user.username), + totalTime: adminWebFormatDuration(user.seconds), + activityShare: adminWebActivityShare(seconds: user.seconds, total: loadedTotalSeconds), + isActive: activeUsernames.contains(user.username) + ) + } + + return AdminWebAnalyticsPayload( + generatedAt: now, + peakActivityLabel: peakHour.map { "Peak activity at \(adminWebHourLabel($0.hour))" } ?? "Waiting for activity", + metrics: metrics, + dailyActivity: loadedDaily.map { + AdminWebAnalyticsDayPayload(date: $0.date, label: $0.date.formatted(.dateTime.weekday(.abbreviated)), count: $0.count) + }, + hourlyActivity: loadedHourly.map { + AdminWebAnalyticsHourPayload(hour: $0.hour, label: adminWebHourLabel($0.hour), count: $0.count) + }, + topUsers: topUsers, + feed: adminWebAnalyticsFeed(healthState: healthState, now: now), + health: AdminWebAnalyticsHealthPayload( + state: healthState.state, + detail: healthState.detail, + websocketLatencyMs: connectionDiagnostics.heartbeatLatencyMs, + reconnectCount: status == .reconnecting ? 1 : 0, + activeTasks: activeTaskCount, + eventQueueDepth: queueDepth, + eventQueueLoad: queueLoad, + memoryText: adminWebMemoryText() + ), + insights: adminWebAnalyticsInsights( + dailyActivity: loadedDaily, + healthState: healthState.state, + automationFailures: automationFailures, + commandsToday: commandsToday + ) + ) + } + + private func adminWebAnalyticsHealthState( + latencyMs: Int?, + queueLoad: Double, + failedCommandsToday: Int, + automationFailures: Int + ) -> (state: String, detail: String) { + if status == .reconnecting { + return ("recovering", "Gateway is reconnecting or stabilizing after disruption.") + } + if latencyMs.map({ $0 >= 500 }) == true || queueLoad >= 0.90 || failedCommandsToday >= 5 { + return ("degraded", "Latency, queue, or failures indicate degraded operation.") + } + if latencyMs.map({ $0 >= 300 }) == true || queueLoad >= 0.70 || automationFailures > 0 || failedCommandsToday > 0 { + return ("warning", "One operational signal is elevated and worth watching.") + } + return ("healthy", "Gateway, queue, and automation signals are nominal.") + } + + private func adminWebAnalyticsFeed( + healthState: (state: String, detail: String), + now: Date + ) -> [AdminWebAnalyticsFeedEntryPayload] { + var output: [AdminWebAnalyticsFeedEntryPayload] = [] + + output += events.prefix(8).map { event in + AdminWebAnalyticsFeedEntryPayload( + id: "event-\(event.id)", + timestamp: event.timestamp, + title: adminWebAnalyticsEventTitle(for: event.kind), + detail: adminWebCleanEventMessage(event.message), + category: adminWebAnalyticsEventCategory(for: event.kind), + tone: adminWebAnalyticsEventTone(for: event.kind) + ) + } + + output += commandLog.prefix(5).map { command in + AdminWebAnalyticsFeedEntryPayload( + id: "command-\(command.id)", + timestamp: command.time, + title: command.ok ? "Command executed" : "Command failed", + detail: "\(command.user) ran \(command.command)", + category: "command", + tone: command.ok ? "usage" : "warning" + ) + } + + output += voiceLog.prefix(4).map { voice in + AdminWebAnalyticsFeedEntryPayload( + id: "voice-\(voice.id)", + timestamp: voice.time, + title: "Voice activity", + detail: adminWebCleanEventMessage(voice.description), + category: "voice", + tone: "usage" + ) + } + + if let patchyLastCycleAt { + output.append(AdminWebAnalyticsFeedEntryPayload( + id: "patchy-\(patchyLastCycleAt.timeIntervalSince1970)", + timestamp: patchyLastCycleAt, + title: patchyIsCycleRunning ? "Automation running" : "Automation completed", + detail: "Patchy update cycle processed", + category: "automation", + tone: "automation" + )) + } + + if healthState.state != "healthy" { + output.append(AdminWebAnalyticsFeedEntryPayload( + id: "health-\(healthState.state)-\(Int(now.timeIntervalSince1970 / 60))", + timestamp: now, + title: "\(healthState.state.capitalized) health state", + detail: healthState.detail, + category: "health", + tone: healthState.state == "degraded" ? "danger" : "warning" + )) + } + + output.append(AdminWebAnalyticsFeedEntryPayload( + id: "launch-\(launchedAt.timeIntervalSince1970)", + timestamp: launchedAt, + title: "Analytics pipeline initialized", + detail: "SwiftBot runtime metrics are being aggregated", + category: "system", + tone: "healthy" + )) + + return Array(output.sorted { + if $0.timestamp != $1.timestamp { + return $0.timestamp > $1.timestamp + } + return $0.id < $1.id + }.prefix(12)) + } + + private func adminWebAnalyticsInsights( + dailyActivity: [(date: Date, count: Int)], + healthState: String, + automationFailures: Int, + commandsToday: Int + ) -> [AdminWebAnalyticsInsightPayload] { + var output: [AdminWebAnalyticsInsightPayload] = [] + let total = dailyActivity.reduce(0) { $0 + $1.count } + let average = dailyActivity.isEmpty ? 0 : Double(total) / Double(dailyActivity.count) + + if let peak = dailyActivity.max(by: { $0.count < $1.count }), peak.count >= 1, average > 0 { + let lift = Int(((Double(peak.count) - average) / max(average, 1)) * 100) + output.append(AdminWebAnalyticsInsightPayload( + title: "\(peak.date.formatted(.dateTime.weekday(.wide))) led activity", + body: lift > 0 ? "\(lift)% above the 7-day average." : "Matched the current 7-day average.", + tone: "usage" + )) + } + + output.append(AdminWebAnalyticsInsightPayload( + title: healthState == "healthy" ? "System health is stable" : "Health state needs attention", + body: healthState == "healthy" + ? "Gateway, queue, and automation signals are nominal." + : "Review latency, queue depth, and failed operations.", + tone: healthState == "healthy" ? "healthy" : "warning" + )) + + if automationFailures > 0 { + output.append(AdminWebAnalyticsInsightPayload( + title: "Automation warnings detected", + body: "\(automationFailures) automation-related warning events are present.", + tone: "warning" + )) + } else { + output.append(AdminWebAnalyticsInsightPayload( + title: "Automation pipeline is quiet", + body: "No failed automation events are currently reported.", + tone: "automation" + )) + } + + if commandsToday > 0 { + output.append(AdminWebAnalyticsInsightPayload( + title: "Command traffic is active", + body: "\(commandsToday) commands have been processed today.", + tone: "usage" + )) + } + + return output + } + + private func adminWebDeterministicMostActiveDay(from dailyActivity: [(date: Date, count: Int)]) -> String { + let activeDays = dailyActivity + .filter { $0.count >= 1 } + .sorted { + if $0.count != $1.count { + return $0.count > $1.count + } + return $0.date < $1.date + } + return activeDays.first?.date.formatted(.dateTime.weekday(.wide)) ?? "-" + } + + private func adminWebPeakDayDetail(from dailyActivity: [(date: Date, count: Int)]) -> String { + guard let peak = dailyActivity.max(by: { $0.count < $1.count }), peak.count >= 1 else { + return "No completed sessions this week" + } + return "\(peak.count) sessions on \(peak.date.formatted(.dateTime.weekday(.wide)))" + } + + private func adminWebAnalyticsEventTitle(for kind: ActivityEvent.Kind) -> String { + switch kind { + case .voiceJoin: return "Voice session started" + case .voiceLeave: return "Voice session ended" + case .voiceMove: return "Voice channel changed" + case .command: return "Command executed" + case .info: return "System event" + case .warning: return "Operational warning" + case .error: return "Operational error" + } + } + + private func adminWebAnalyticsEventCategory(for kind: ActivityEvent.Kind) -> String { + switch kind { + case .voiceJoin, .voiceLeave, .voiceMove: return "voice" + case .command: return "command" + case .warning, .error: return "health" + case .info: return "system" + } + } + + private func adminWebAnalyticsEventTone(for kind: ActivityEvent.Kind) -> String { + switch kind { + case .warning: return "warning" + case .error: return "danger" + case .command, .voiceJoin, .voiceLeave, .voiceMove: return "usage" + case .info: return "healthy" + } + } + + private func adminWebCleanEventMessage(_ message: String) -> String { + ["🟢 ", "🔴 ", "🔀 ", "✅ ", "⚠️ ", "❌ "].reduce(message) { cleaned, marker in + cleaned.replacingOccurrences(of: marker, with: "") + } + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + private func adminWebActivityShare(seconds: Int, total: Int) -> Int { + guard total > 0 else { return 0 } + return Int((Double(seconds) / Double(total) * 100).rounded()) + } + + private func adminWebInitials(for username: String) -> String { + let pieces = username.split(separator: " ").prefix(2) + let letters = pieces.compactMap(\.first).map(String.init).joined() + return letters.isEmpty ? "?" : letters.uppercased() + } + + private func adminWebHourLabel(_ hour: Int) -> String { + switch hour { + case 0: return "12a" + case 12: return "12p" + case let hourBeforeNoon where hourBeforeNoon < 12: return "\(hourBeforeNoon)a" + default: return "\(hour - 12)p" + } + } + + private func adminWebFormatDuration(_ seconds: Int) -> String { + let hours = seconds / 3600 + let minutes = (seconds % 3600) / 60 + if hours > 0 { return "\(hours)h \(minutes)m" } + if minutes > 0 { return "\(minutes)m" } + return "<1m" + } + + private func adminWebMemoryText() -> String { + var info = mach_task_basic_info() + var count = mach_msg_type_number_t(MemoryLayout.size) / 4 + let result = withUnsafeMutablePointer(to: &info) { + $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { + task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count) + } + } + guard result == KERN_SUCCESS else { return "-" } + return ByteCountFormatter.string(fromByteCount: Int64(info.resident_size), countStyle: .memory) + } + func remoteStatusSnapshot() -> RemoteStatusPayload { let leaderName = clusterNodes.first(where: { $0.role == .leader })?.displayName ?? clusterNodes.first?.displayName @@ -742,7 +1146,7 @@ extension AppModel { /// 3. Dev mode (Internet Access off) → `http://localhost:` — uses `localhost` rather /// than the bind address (127.0.0.1) so redirect URIs match Discord developer portal /// registrations, which typically list localhost not the loopback IP. - private func oauthPublicBaseURL() -> String { + func adminWebOAuthBaseURL() -> String { let explicit = settings.adminWebUI.publicBaseURL.trimmingCharacters(in: .whitespacesAndNewlines) if !explicit.isEmpty { return explicit.contains("://") ? explicit : "https://" + explicit @@ -758,13 +1162,20 @@ extension AppModel { return "http://localhost:\(settings.adminWebUI.port)" } + func adminWebDiscordRedirectURL() -> String { + adminWebOAuthRedirectURL( + baseURL: adminWebOAuthBaseURL(), + redirectPath: normalizedAdminRedirectPath(settings.adminWebUI.redirectPath) + ) + } + func configureAdminWebServer() async { let httpsConfiguration = usesLocalRuntime ? await resolveAdminWebHTTPSConfiguration() : nil let config = AdminWebServer.Configuration( enabled: usesLocalRuntime && settings.adminWebUI.enabled, bindHost: settings.adminWebUI.bindHost, port: settings.adminWebUI.port, - publicBaseURL: oauthPublicBaseURL(), + publicBaseURL: adminWebOAuthBaseURL(), https: httpsConfiguration, discordOAuth: settings.adminWebUI.discordOAuth, localAuthEnabled: settings.adminWebUI.localAuthEnabled, @@ -864,6 +1275,12 @@ extension AppModel { } return await MainActor.run { model.adminWebOverviewSnapshot() } }, + analyticsProvider: { [weak self] in + guard let model = self else { + return AdminWebAnalyticsPayload.empty + } + return await model.adminWebAnalyticsSnapshot() + }, connectedGuildIDsProvider: { [weak self] in guard let model = self else { return [] } return await MainActor.run { Set(model.connectedServers.keys) } diff --git a/SwiftBotApp/Resources/admin/index.html b/SwiftBotApp/Resources/admin/index.html index 3e80ad10..63767c26 100644 --- a/SwiftBotApp/Resources/admin/index.html +++ b/SwiftBotApp/Resources/admin/index.html @@ -886,6 +886,246 @@ gap: 12px; } + .analytics-shell { + display: grid; + gap: 12px; + } + + .analytics-pulse { + display: grid; + grid-template-columns: repeat(6, minmax(0, 1fr)); + gap: 10px; + padding: 10px; + border-radius: 18px; + } + + .analytics-card { + border-radius: 14px; + padding: 11px; + background: rgba(255,255,255,0.045); + border: 1px solid rgba(255,255,255,0.09); + min-width: 0; + } + + .analytics-card .label { + font-size: 11px; + color: var(--muted); + font-weight: 650; + } + + .analytics-card .value { + margin-top: 6px; + font-size: 20px; + line-height: 1.05; + font-weight: 760; + letter-spacing: -0.035em; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .analytics-card .detail, + .analytics-card .trend { + margin-top: 5px; + font-size: 11px; + color: var(--muted); + line-height: 1.25; + } + + .analytics-main { + display: grid; + grid-template-columns: minmax(0, 1.8fr) minmax(260px, 0.8fr); + gap: 12px; + } + + .analytics-panel { + border-radius: 20px; + padding: 12px; + } + + .analytics-chart { + position: relative; + min-height: 190px; + padding: 12px 8px 4px; + border-radius: 16px; + background: + linear-gradient(rgba(255,255,255,0.045) 1px, transparent 1px), + rgba(255,255,255,0.025); + background-size: 100% 38px; + border: 1px solid rgba(255,255,255,0.08); + overflow: hidden; + } + + .analytics-line-svg { + width: 100%; + height: 180px; + display: block; + overflow: visible; + } + + .analytics-axis-labels { + position: absolute; + left: 20px; + right: 18px; + bottom: 7px; + display: flex; + justify-content: space-between; + gap: 8px; + pointer-events: none; + } + + .analytics-axis-label { + font-size: 10px; + color: var(--muted); + text-align: center; + min-width: 0; + } + + .analytics-feed { + display: grid; + gap: 7px; + } + + .analytics-feed-item { + display: grid; + grid-template-columns: 24px minmax(0, 1fr) auto; + gap: 8px; + align-items: center; + border-radius: 13px; + padding: 8px 9px; + background: rgba(255,255,255,0.045); + border: 1px solid rgba(255,255,255,0.075); + } + + .analytics-feed-icon { + width: 24px; + height: 24px; + border-radius: 9px; + display: grid; + place-items: center; + background: rgba(255,255,255,0.07); + color: #8ecbff; + font-family: "Material Symbols Rounded"; + font-size: 15px; + font-variation-settings: "FILL" 1, "wght" 500, "GRAD" 0, "opsz" 20; + } + + .analytics-feed-title { + font-size: 12px; + font-weight: 700; + line-height: 1.2; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .analytics-feed-detail, + .analytics-feed-time { + font-size: 11px; + color: var(--muted); + line-height: 1.25; + } + + .analytics-diagnostics, + .analytics-support { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + } + + .analytics-health-grid { + display: grid; + gap: 8px; + } + + .analytics-health-row, + .analytics-user-row, + .analytics-insight { + border-radius: 13px; + padding: 8px 9px; + background: rgba(255,255,255,0.045); + border: 1px solid rgba(255,255,255,0.075); + } + + .analytics-health-row { + display: flex; + justify-content: space-between; + gap: 10px; + font-size: 12px; + } + + .analytics-health-row span:first-child { + color: var(--muted); + } + + .analytics-user-row { + display: grid; + grid-template-columns: 30px minmax(0, 1fr) auto; + align-items: center; + gap: 9px; + } + + .analytics-avatar { + width: 30px; + height: 30px; + border-radius: 999px; + display: grid; + place-items: center; + color: var(--text); + background: rgba(112, 185, 255, 0.18); + border: 1px solid rgba(130, 205, 255, 0.28); + font-size: 11px; + font-weight: 800; + } + + .analytics-user-name { + font-size: 12px; + font-weight: 700; + } + + .analytics-user-meta { + margin-top: 3px; + font-size: 11px; + color: var(--muted); + } + + .analytics-progress { + height: 5px; + margin-top: 6px; + border-radius: 999px; + background: rgba(255,255,255,0.08); + overflow: hidden; + } + + .analytics-progress span { + display: block; + height: 100%; + border-radius: inherit; + background: linear-gradient(90deg, rgba(98, 198, 255, 0.9), rgba(163, 135, 255, 0.75)); + } + + .analytics-insight { + display: grid; + gap: 4px; + } + + .analytics-insight-title { + font-size: 12px; + font-weight: 700; + } + + .analytics-insight-body { + font-size: 11px; + color: var(--muted); + line-height: 1.35; + } + + .tone-healthy { border-color: rgba(116, 235, 162, 0.20); } + .tone-warning { border-color: rgba(255, 191, 101, 0.28); } + .tone-danger { border-color: rgba(255, 137, 122, 0.30); } + .tone-automation { border-color: rgba(181, 167, 255, 0.24); } + .tone-usage { border-color: rgba(111, 196, 255, 0.22); } + .commands-top { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); @@ -1324,6 +1564,16 @@ } @media (max-width: 980px) { + .analytics-pulse { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .analytics-main, + .analytics-diagnostics, + .analytics-support { + grid-template-columns: 1fr; + } + .settings-top, .diagnostics-top, .settings-panels, @@ -1827,6 +2077,10 @@

Welcome to SwiftBot

dashboard Overview + + +