summaryrefslogtreecommitdiff
path: root/Sources
diff options
context:
space:
mode:
authorgigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com>2026-10-14 20:18:20 +0530
committergigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com>2026-10-14 20:18:20 +0530
commitaceca8b5dfc8edd378ee9ff891bccb0f94c69f31 (patch)
tree08401ce8d050afbbe77514f479601a8e9535f4ec /Sources
feat: launch Bubomb - native macOS menu bar utility ('Configure the boom')HEADmain
Diffstat (limited to 'Sources')
-rw-r--r--Sources/BubombApp/AppDelegate.swift76
-rw-r--r--Sources/BubombApp/main.swift8
-rw-r--r--Sources/BubombCore/Executors/ApplicationLauncher.swift78
-rw-r--r--Sources/BubombCore/Executors/ExecutionResult.swift21
-rw-r--r--Sources/BubombCore/Executors/PayloadExecutor.swift242
-rw-r--r--Sources/BubombCore/Executors/ProcessRunner.swift219
-rw-r--r--Sources/BubombCore/Executors/ScriptExecutor.swift77
-rw-r--r--Sources/BubombCore/Executors/SequenceExecutor.swift131
-rw-r--r--Sources/BubombCore/Executors/ShellCommandExecutor.swift63
-rw-r--r--Sources/BubombCore/Executors/URLLauncher.swift45
-rw-r--r--Sources/BubombCore/Models/AppSettings.swift55
-rw-r--r--Sources/BubombCore/Models/ExecutionRecord.swift83
-rw-r--r--Sources/BubombCore/Models/Payload.swift129
-rw-r--r--Sources/BubombCore/Models/PayloadType.swift105
-rw-r--r--Sources/BubombCore/Models/SafetyPolicy.swift88
-rw-r--r--Sources/BubombCore/Models/SequenceStep.swift43
-rw-r--r--Sources/BubombCore/Persistence/SettingsStore.swift134
-rw-r--r--Sources/BubombCore/Utilities/ExecutionError.swift64
-rw-r--r--Sources/BubombCore/Utilities/PathValidator.swift69
-rw-r--r--Sources/BubombUI/Icons/AnimatedBombView.swift157
-rw-r--r--Sources/BubombUI/Icons/BombIconRenderer.swift206
-rw-r--r--Sources/BubombUI/MenuBar/MenuBarController.swift283
-rw-r--r--Sources/BubombUI/Settings/ExecutionStatusView.swift308
-rw-r--r--Sources/BubombUI/Settings/GeneralSettingsView.swift217
-rw-r--r--Sources/BubombUI/Settings/PayloadEditorView.swift724
-rw-r--r--Sources/BubombUI/Settings/SequenceStepEditorView.swift184
-rw-r--r--Sources/BubombUI/Settings/SettingsView.swift95
-rw-r--r--Sources/BubombUI/Settings/Theme.swift42
-rw-r--r--Sources/BubombUI/Windows/WindowManager.swift56
29 files changed, 4002 insertions, 0 deletions
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