summaryrefslogtreecommitdiff
path: root/Sources/BubombCore/Executors/PayloadExecutor.swift
blob: 2142934d961bd329c4633a45d6e843639d3f51b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
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
            }
        }
    }
}