native macOS codings agent orchestrator prowl.onev.cat
Something went wrong. Try again.
Swift
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490import Foundationimport ProwlCLIShared
@MainActorstruct WorkflowStatusCenterPresentation: Equatable { let runs: [WorkflowRunPresentation]
init( state: WorkflowRunsFeature.State, selectedWorktreeID: Worktree.ID?, now: Date ) { guard let selectedWorktreeID else { runs = [] return } func ordered(_ sessions: [WorkflowRunSession]) -> [WorkflowRunPresentation] { sessions .map(\.run) .filter { $0.context.worktree.id == selectedWorktreeID } .sorted { if $0.startedAt != $1.startedAt { return $0.startedAt > $1.startedAt } if $0.updatedAt != $1.updatedAt { return $0.updatedAt > $1.updatedAt } return $0.id.uuidString > $1.id.uuidString } .map { WorkflowRunPresentation(run: $0, now: now) } } // Active runs first; a run that just ended stays listed for `finishedNoticeDuration` so // the toolbar can show its outcome instead of vanishing the moment it completes. runs = ordered(state.activeSessions) + ordered(state.recentlyFinishedSessions) }
/// The run the compact status item names: the most recent active run, else the run that just ended. var primary: WorkflowRunPresentation? { runs.first } var attentionRun: WorkflowRunPresentation? { runs.first { $0.status.isAttention } } var activeRunCount: Int { runs.count(where: { !$0.status.isFinished }) } var hasAttention: Bool { attentionRun != nil }}
/// How a run ended, for the status item's closing line.nonisolated enum WorkflowFinishedOutcome: Equatable, Sendable { case completed case cancelled case skipped case iterationLimitReached case interrupted}
nonisolated struct WorkflowRunPresentation: Equatable, Sendable, Identifiable { enum Status: Equatable, Sendable { case running case needsAttention(String) case finished(WorkflowFinishedOutcome) }
let id: UUID let workflowName: String let workflowIcon: String let worktreeID: Worktree.ID let worktreeName: String let startedAt: Date let elapsedText: String let status: Status let currentStepTitle: String let currentPrompt: String? let roles: [WorkflowRolePresentation] let stepItems: [WorkflowStepListItem] let attentionControls: [WorkflowAttentionControl] let runDirectory: URL let logURL: URL
init(run: WorkflowRun, now: Date) { id = run.id workflowName = run.definition.name workflowIcon = run.definition.icon ?? "point.3.connected.trianglepath.dotted" worktreeID = run.context.worktree.id worktreeName = run.context.worktree.name startedAt = run.startedAt elapsedText = Self.elapsedText(from: run.startedAt, to: now) status = switch run.status { case .running: .running case .needsAttention(let attention): .needsAttention(attention.message) case .completed: .finished(.completed) case .cancelled: .finished(.cancelled) case .skipped: .finished(.skipped) case .iterationLimitReached: .finished(.iterationLimitReached) case .interrupted: .finished(.interrupted) } let context = Self.templateContext(for: run, iteration: run.currentIteration) currentStepTitle = Self.title(for: run.currentStep, context: context) ?? String(localized: "Finishing workflow") currentPrompt = Self.prompt(for: run.currentStep, context: context) roles = run.definition.roles.map { role in WorkflowRolePresentation(role: role, binding: run.bindings[role.name]) } stepItems = Self.stepItems(for: run) if let attention = run.status.attention { let machine = WorkflowRunMachine( run: run, limits: WorkflowDeliveryLimits(), now: { now }, makeToken: { "presentation-does-not-mint-tokens" } ) let skipConsequence = machine.skipConsequence(forStep: attention.stepID) attentionControls = attention.actions.map { WorkflowAttentionControl( action: $0, run: run, attention: attention, skipConsequence: skipConsequence ) } } else { attentionControls = [] } runDirectory = run.runDirectory logURL = run.runDirectory.appending(path: "log.md", directoryHint: .notDirectory) }
func elapsedText(at now: Date) -> String { Self.elapsedText(from: startedAt, to: now) }
/// The compact status item's text: the current step while the run lives, its outcome once it ended. var summaryText: String { switch status { case .running, .needsAttention: return currentStepTitle case .finished(let outcome): switch outcome { case .completed: return String(localized: "\(workflowName) completed") case .cancelled: return String(localized: "\(workflowName) cancelled") case .skipped: return String(localized: "\(workflowName) ended after a skipped step") case .iterationLimitReached: return String(localized: "\(workflowName) reached its iteration limit") case .interrupted: return String(localized: "\(workflowName) was interrupted") } } }
private static func elapsedText(from start: Date, to end: Date) -> String { let seconds = max(0, Int(end.timeIntervalSince(start))) if seconds < 60 { return "\(seconds)s" } let minutes = seconds / 60 if minutes < 60 { return "\(minutes)m" } let hours = minutes / 60 let remainingMinutes = minutes % 60 if hours < 24 { return remainingMinutes == 0 ? "\(hours)h" : "\(hours)h \(remainingMinutes)m" } let days = hours / 24 let remainingHours = hours % 24 return remainingHours == 0 ? "\(days)d" : "\(days)d \(remainingHours)h" }
private static func templateContext(for run: WorkflowRun, iteration: Int?) -> [String: WorkflowJSONValue] { var values = run.stepValues.isEmpty ? run.expressionValues(capturedAt: run.updatedAt) : run.stepValues if case .object(var context) = values["context"], case .object(var step) = context["step"] { step["iteration"] = iteration.map(WorkflowJSONValue.integer) ?? .null context["step"] = .object(step) values["context"] = .object(context) } return values }
private static func title( for step: WorkflowStepDefinition?, context: [String: WorkflowJSONValue] ) -> String? { guard let step else { return nil } guard let title = step.title else { return Self.fallbackTitle(for: step) } return (try? WorkflowExpression.renderText(title, values: context)) ?? title }
private static func fallbackTitle(for step: WorkflowStepDefinition) -> String { step.historyTitle }
private static func prompt( for step: WorkflowStepDefinition?, context: [String: WorkflowJSONValue] ) -> String? { guard let step else { return nil } let source: String? switch step.action { case .message(_, let prompt, _): source = prompt case .launch(_, let prompt, _, _): source = prompt case .action(let id, _): source = String(localized: "Run action \(id).") case .notify(let text): source = text case .close(let role): source = String(localized: "Close the pane bound to \(role).") case .control: source = nil } guard let source else { return nil } return (try? WorkflowExpression.renderText(source, values: context)) ?? source }
private static func stepItems(for run: WorkflowRun) -> [WorkflowStepListItem] { var items: [WorkflowStepListItem] = [] for step in run.definition.steps { switch step.action { case .control(.loop(_, let maximum, let children)): let body = children.flatMap { [$0] + $0.action.descendants } let recordedIterations = run.stepRecords.compactMap { record in body.contains { $0.id == record.stepID } ? record.iteration : nil } var iterations = Set(recordedIterations) if body.contains(where: { $0.id == run.currentStep?.id }), let current = run.currentIteration { iterations.insert(current) } if iterations.isEmpty { items.append( .step( WorkflowStepPresentation( id: "\(step.id)-pending", stepID: step.id, title: title(for: step, context: templateContext(for: run, iteration: nil)) ?? step.id, state: .pending ))) } else { for iteration in iterations.sorted() { let steps = body.map { inner in let record = run.stepRecords.last { $0.stepID == inner.id && $0.iteration == iteration } let context = templateContext(for: run, iteration: iteration) return WorkflowStepPresentation( id: "\(step.id)-\(iteration)-\(inner.id)", stepID: inner.id, title: title(for: inner, context: context) ?? inner.id, state: record.map { WorkflowStepPresentation.State($0.state) } ?? .pending ) } items.append( .round( WorkflowRoundPresentation( id: "\(step.id)-\(iteration)", index: iteration, maximum: maximum, steps: steps ))) } } case .control(.conditional(_, let yes, let otherwise)): for child in [step] + (yes + otherwise).flatMap({ [$0] + $0.action.descendants }) { let record = run.stepRecords.last { $0.stepID == child.id } let context = templateContext(for: run, iteration: record?.iteration) items.append( .step( .init( id: child.id, stepID: child.id, title: title(for: child, context: context) ?? child.id, state: record.map { .init($0.state) } ?? .pending))) } default: let record = run.stepRecords.last { $0.stepID == step.id && $0.iteration == nil } let context = templateContext(for: run, iteration: nil) items.append( .step( WorkflowStepPresentation( id: "\(step.id)-top", stepID: step.id, title: title(for: step, context: context) ?? step.id, state: record.map { WorkflowStepPresentation.State($0.state) } ?? .pending ))) } } return items }}
nonisolated extension WorkflowRunPresentation.Status { var isAttention: Bool { if case .needsAttention = self { return true } return false }
var isFinished: Bool { if case .finished = self { return true } return false }}
nonisolated struct WorkflowRolePresentation: Equatable, Sendable, Identifiable { let id: String let displayName: String let agent: String? let paneHandle: String? let surfaceID: UUID?
init(role: WorkflowRoleDefinition, binding: WorkflowRoleBinding?) { id = role.name displayName = binding?.displayName ?? role.name agent = binding?.agent.nilIfEmpty paneHandle = binding?.pane?.handle surfaceID = binding?.pane?.surfaceID }}
nonisolated enum WorkflowStepListItem: Equatable, Sendable, Identifiable { case step(WorkflowStepPresentation) case round(WorkflowRoundPresentation)
var id: String { switch self { case .step(let step): step.id case .round(let round): round.id } }}
nonisolated struct WorkflowRoundPresentation: Equatable, Sendable, Identifiable { let id: String let index: Int let maximum: Int? let steps: [WorkflowStepPresentation]}
nonisolated struct WorkflowStepPresentation: Equatable, Sendable, Identifiable { enum State: Equatable, Sendable { case pending case active case completed case skipped case failed
init(_ state: WorkflowStepState) { switch state { case .active: self = .active case .completed: self = .completed case .skipped: self = .skipped case .failed: self = .failed } } }
let id: String let stepID: String let title: String let state: State}
nonisolated enum WorkflowRunPanelIntent: Equatable, Sendable { case focusPane(worktreeID: Worktree.ID, surfaceID: UUID) case userAction(runID: UUID, action: WorkflowUserAction) case revealRunFolder(URL) case openLog(URL)}
nonisolated struct WorkflowAttentionControl: Equatable, Sendable, Identifiable { var id: WorkflowAttentionAction { action } let action: WorkflowAttentionAction let label: String let systemImage: String let isDestructive: Bool let focusSurfaceID: UUID? let verdicts: [String] let confirmationMessage: String?
init( action: WorkflowAttentionAction, run: WorkflowRun, attention: WorkflowAttention, skipConsequence: WorkflowSkipConsequence ) { self.action = action let rolePane = attention.role.flatMap { run.bindings[$0]?.pane } focusSurfaceID = action == .focusPane ? rolePane?.surfaceID : nil verdicts = action == .acceptWithVerdict ? (run.activeActivation?.expect.verdicts ?? []) : [] isDestructive = action == .cancel switch action { case .focusPane: label = String(localized: "Focus Pane") systemImage = "scope" confirmationMessage = nil case .nudge: label = String(localized: "Nudge Again") systemImage = "bell.badge" confirmationMessage = nil case .keepWaiting: label = String(localized: "Keep Waiting") systemImage = "clock" confirmationMessage = nil case .retry: label = String(localized: "Retry") systemImage = "arrow.clockwise" confirmationMessage = nil case .relaunch: label = String(localized: "Relaunch Role") systemImage = "arrow.trianglehead.2.clockwise.rotate.90" confirmationMessage = nil case .acceptDelivery: label = String(localized: "Accept as Delivered") systemImage = "checkmark" confirmationMessage = nil case .acceptWithVerdict: label = String(localized: "Accept with Verdict") systemImage = "checkmark.circle" confirmationMessage = nil case .askAgain: label = String(localized: "Ask Again") systemImage = "arrowshape.turn.up.left" confirmationMessage = nil case .skip: label = String(localized: "Skip Step") systemImage = "forward.end" confirmationMessage = Self.skipConfirmation( stepID: attention.stepID, consequence: skipConsequence ) case .cancel: label = String(localized: "Cancel Run") systemImage = "xmark" confirmationMessage = String( localized: "Cancel this workflow run? Its panes and deliveries will be kept." ) } }
func intent( runID: UUID, worktreeID: Worktree.ID, verdict: String? = nil ) -> WorkflowRunPanelIntent? { switch action { case .focusPane: guard let focusSurfaceID else { return nil } return .focusPane(worktreeID: worktreeID, surfaceID: focusSurfaceID) case .nudge: return .userAction(runID: runID, action: .nudge) case .keepWaiting: return .userAction(runID: runID, action: .keepWaiting) case .retry: return .userAction(runID: runID, action: .retry) case .relaunch: return .userAction(runID: runID, action: .relaunch) case .acceptDelivery: return .userAction(runID: runID, action: .acceptDelivery(verdict: nil)) case .acceptWithVerdict: guard let verdict, verdicts.contains(verdict) else { return nil } return .userAction(runID: runID, action: .acceptDelivery(verdict: verdict)) case .askAgain: return .userAction(runID: runID, action: .askAgain) case .skip: return .userAction(runID: runID, action: .skip) case .cancel: return .userAction(runID: runID, action: .cancel) } }
private static func skipConfirmation( stepID: String, consequence: WorkflowSkipConsequence ) -> String { switch consequence { case .noDelivery: String(localized: "Skip step '\(stepID)'? The workflow continues without an output from this step.") case .continues(let optionalInputs): if optionalInputs.isEmpty { String(localized: "Skip step '\(stepID)'? The workflow continues without this delivery.") } else { String( localized: """ Skip step '\(stepID)'? The workflow continues without the optional input used by \ \(optionalInputs.joined(separator: ", ")). """ ) } case .endsRun(let dependent): String( localized: "Skip step '\(stepID)'? This ends the run because step '\(dependent)' depends on its output." ) } }}nonisolated extension String { fileprivate var nilIfEmpty: String? { isEmpty ? nil : self }}nonisolated extension Collection { fileprivate subscript(safe index: Index) -> Element? { indices.contains(index) ? self[index] : nil }}