Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Sources/PerchModuleKit/AnyNotchModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,16 @@ public struct AnyNotchModule: Sendable {
let face = module.face(for: snapshot.value, in: slot)
let pill = PillContent(face: face, freshness: snapshot.freshness, asOf: snapshot.asOf)
let detail = module.detail(for: snapshot.value)
let actions = module.actions(for: snapshot.value, context: context)
var alert: ModuleAlert?
if snapshot.freshness.isTrustworthy { // a real (live) observation
if let previousLive {
alert = module.notification(for: snapshot.value, previous: previousLive)
}
previousLive = snapshot.value
}
continuation.yield(ModuleRender(pill: pill, detail: detail, alert: alert, contextLabel: contextLabel))
continuation.yield(ModuleRender(pill: pill, detail: detail, alert: alert,
contextLabel: contextLabel, actions: actions))
}
continuation.finish()
}
Expand Down
7 changes: 6 additions & 1 deletion Sources/PerchModuleKit/DetailRow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,16 @@ public struct ModuleRender: Equatable, Sendable {
/// scoped to, or the host it pings), shown under the panel row's title so
/// the user always knows the source.
public let contextLabel: String?
/// Suggested next actions this update implies, for the Pilot aggregator to
/// rank. Empty for modules that don't override `actions(for:context:)`.
public let actions: [PilotAction]

public init(pill: PillContent, detail: [DetailRow], alert: ModuleAlert? = nil, contextLabel: String? = nil) {
public init(pill: PillContent, detail: [DetailRow], alert: ModuleAlert? = nil,
contextLabel: String? = nil, actions: [PilotAction] = []) {
self.pill = pill
self.detail = detail
self.alert = alert
self.contextLabel = contextLabel
self.actions = actions
}
}
9 changes: 9 additions & 0 deletions Sources/PerchModuleKit/NotchModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,19 @@ public protocol NotchModule: Sendable {
/// …), shown under the panel row title. Receives the same context (settings)
/// as `stream`, so it can name the configured repo/URL. Defaults to nil.
func contextLabel(_ context: ModuleContext) -> String?

/// Suggested next actions derived purely from this state (and the module's
/// settings), for the Pilot aggregator to rank and surface. Defaults to empty —
/// a module overrides it only when its state implies something to *do* (merge a
/// ready PR, look at a failing run, check a down deploy). Takes `context` so a
/// module can read its own settings (e.g. a URL that lives there, not in State),
/// mirroring `contextLabel`.
func actions(for value: State, context: ModuleContext) -> [PilotAction]
}

public extension NotchModule {
func detail(for value: State) -> [DetailRow] { [] }
func notification(for value: State, previous: State?) -> ModuleAlert? { nil }
func contextLabel(_ context: ModuleContext) -> String? { nil }
func actions(for value: State, context: ModuleContext) -> [PilotAction] { [] }
}
88 changes: 88 additions & 0 deletions Sources/PerchModuleKit/PilotAction.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import Foundation
import PerchCore

/// How urgent one `PilotAction` is — the single ranking axis every module shares,
/// so Pilot can merge actions from different signals and sort them consistently.
///
/// The named levels are the ONLY way to make a priority: the memberwise init is
/// internal, so a module in `PerchModules` picks a documented level rather than
/// inventing a magic number. Higher `rank` = more urgent.
public struct PilotPriority: Comparable, Hashable, Sendable {
public let rank: Int
init(_ rank: Int) { self.rank = rank }

public static func < (lhs: PilotPriority, rhs: PilotPriority) -> Bool { lhs.rank < rhs.rank }

/// A deploy/health endpoint is down — a production incident, nothing outranks it.
public static let prodDown = PilotPriority(100)
/// CI failing on a *specific* branch you chose to watch (your main build is broken).
public static let mainBroken = PilotPriority(90)
/// Deploy degraded (reachable but non-2xx) — still an incident, so above your own work.
public static let degraded = PilotPriority(80)
/// Changes requested on YOUR PR with unresolved threads — the ball is in your court.
public static let yourMove = PilotPriority(70)
/// Your PR has merge conflicts — blocks landing it.
public static let conflicts = PilotPriority(68)
/// CI failing on your PR, or a watched build on any/unspecified branch.
public static let ciFailingPR = PilotPriority(65)
/// A review has been requested of you — unblocking someone else ranks above landing
/// your own already-green PR (a deliberate call; flip the two if you disagree).
public static let reviewAsked = PilotPriority(55)
/// Your PR is approved + green + mergeable — a win that's ready to land.
public static let readyToMerge = PilotPriority(50)
}

/// One suggested next action Pilot surfaces: what to do, how urgent, and where a
/// tap goes. In v1 every action is *navigation* — opening the thing in the
/// browser — so `url` is the whole interaction; write-actions (merge, re-run) are
/// a v2 concern layered on later.
public struct PilotAction: Equatable, Sendable, Identifiable {
/// Stable, per-kind-prefixed dedup key, e.g. `"pr-merge:owner/repo#120"`. The
/// same action across polls keeps the same id, so ordering never flaps and the
/// shell can dedup.
public let id: String
public let title: String
public let subtitle: String?
public let symbolName: String?
public let tint: Tint
public let priority: PilotPriority
/// Where a tap opens (the PR, the failing run, the deploy). nil = no target.
public let url: String?

public init(id: String, title: String, subtitle: String? = nil,
symbolName: String? = nil, tint: Tint = .neutral,
priority: PilotPriority, url: String? = nil) {
self.id = id
self.title = title
self.subtitle = subtitle
self.symbolName = symbolName
self.tint = tint
self.priority = priority
self.url = url
}
}

/// Pilot's typed state: the ranked actions plus enough about the *sources* to stay
/// honest on the pill. `face`/`detail` only receive `State` (never freshness), so
/// readiness and source availability are carried here — that's what lets the pill
/// say "Checking…" or "N unavailable" instead of a confident, wrong "All clear".
public struct PilotState: Equatable, Sendable {
/// Already ranked (most urgent first).
public let actions: [PilotAction]
/// Human names of sources that are configured but whose signal isn't usable —
/// either a reported render that's stale/error/no-access, or a source you turned
/// on but haven't finished setting up (e.g. CI with no repo). Lets the pill +
/// panel admit the picture is partial instead of a false "All clear".
public let sourcesUnavailable: [String]
/// True once every live source has reported at least once — until then the pill
/// reads "Checking…" rather than a premature "All clear".
public let ready: Bool

public init(actions: [PilotAction], sourcesUnavailable: [String], ready: Bool) {
self.actions = actions
self.sourcesUnavailable = sourcesUnavailable
self.ready = ready
}

public static let empty = PilotState(actions: [], sourcesUnavailable: [], ready: false)
}
20 changes: 20 additions & 0 deletions Sources/PerchModules/DeployModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,24 @@ public struct DeployModule: NotchModule {
return PillFace(text: "…", symbolName: "questionmark.circle", tint: .neutral, tooltip: "Checking")
}
}

/// Pilot actions: a down or degraded endpoint is something to go look at. The
/// URL lives in settings (not in `HealthState`), so this reads it from context.
public func actions(for value: HealthState, context: ModuleContext) -> [PilotAction] {
let urlString = context.settings["url"] ?? ""
guard !urlString.isEmpty else { return [] }
let host = URL(string: urlString)?.host ?? urlString
switch value {
case .down:
return [PilotAction(id: "deploy-down:\(urlString)", title: "Deploy down",
subtitle: "\(host) — unreachable", symbolName: "xmark.octagon.fill",
tint: .critical, priority: .prodDown, url: urlString)]
case .degraded:
return [PilotAction(id: "deploy-degraded:\(urlString)", title: "Deploy degraded",
subtitle: "\(host) — non-2xx", symbolName: "exclamationmark.triangle.fill",
tint: .warning, priority: .degraded, url: urlString)]
case .healthy, .unknown:
return []
}
}
}
18 changes: 18 additions & 0 deletions Sources/PerchModules/GitHubBuildsModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,24 @@ public struct GitHubBuildsModule: NotchModule {
url: value.url.isEmpty ? nil : value.url)
}

/// Pilot action: a failing build is something to look at. Priority is higher
/// when a *specific* branch is watched (your main build is broken) than when
/// watching "any branch" (`*`/blank). `BuildInfo.branch` is the run's branch, so
/// the watched-branch decision uses the module's own configured `branch`. The id
/// uses owner/repo (BuildInfo has no repo field) so it's stable + distinct.
public func actions(for value: BuildInfo, context: ModuleContext) -> [PilotAction] {
guard value.state == .failing else { return [] }
let watchesSpecificBranch = !branch.isEmpty && branch != "*"
let priority: PilotPriority = watchesSpecificBranch ? .mainBroken : .ciFailingPR
let where_ = value.branch.isEmpty ? "" : " on \(value.branch)"
return [PilotAction(
id: "build-failing:\(owner)/\(repo):\(value.shortSHA.isEmpty ? value.url : value.shortSHA)",
title: "CI failing\(where_)",
subtitle: "\(owner)/\(repo) · \(value.workflowName.isEmpty ? "CI" : value.workflowName)",
symbolName: "xmark.octagon.fill", tint: .critical, priority: priority,
url: value.url.isEmpty ? nil : value.url)]
}

/// A 401 (revoked/expired token) won't fix itself by retrying — back off hard.
static func isAuthError(_ error: Error) -> Bool {
if case GitHubAuthError.http(let status) = error, status == 401 { return true }
Expand Down
117 changes: 95 additions & 22 deletions Sources/PerchModules/GitHubPRsModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -341,31 +341,104 @@ public struct GitHubPRsModule: NotchModule {
return pluralComment(pr.commentCount)
}

/// Map a PR's review + merge status to a label, tint, and icon.
static func status(for pr: PRSummary) -> (label: String, tint: Tint, symbol: String) {
if pr.isDraft { return ("draft", .neutral, "pencil.circle") }
if pr.mergeable == "CONFLICTING" { return ("conflicts", .critical, "exclamationmark.triangle.fill") }
// The good end-state: approved, green, no conflicts — good to land.
if pr.isReadyToMerge { return ("ready to merge", .good, "checkmark.seal.fill") }
/// The ordered classification of a PR's review + merge status — the ONE
/// precedence both the panel label (`status(for:)`) and the Pilot action
/// (`authorAction(for:)`) read, so the two can never drift.
enum PRSignal: Equatable {
case draft, conflicts, readyToMerge, approved
case changesToResolve, awaitingReReview, reviewRequired
case commented, comments, open
}

/// Classify a PR in the same order `status(for:)` always used: draft →
/// conflicts → ready → decision (approved / changes-requested{threads,none} /
/// review-required) → engagement (commented / N-comments / open).
static func classify(_ pr: PRSummary) -> PRSignal {
if pr.isDraft { return .draft }
if pr.mergeable == "CONFLICTING" { return .conflicts }
if pr.isReadyToMerge { return .readyToMerge } // approved, green, no conflicts — good to land
switch pr.reviewDecision {
case "APPROVED": return ("approved", .good, "checkmark.circle.fill")
case "APPROVED": return .approved
case "CHANGES_REQUESTED":
// GitHub holds this decision until a reviewer re-reviews, so make it
// actionable: unresolved threads ⇒ your move (resolve them); none
// left ⇒ you've addressed them and it's waiting on the reviewer.
if pr.unresolvedThreads > 0 {
return ("\(pr.unresolvedLabel) to resolve", .critical, "text.bubble.fill")
}
return ("awaiting re-review", .warning, "clock.arrow.circlepath")
case "REVIEW_REQUIRED": return ("review required", .warning, "clock.fill")
// Held by GitHub until re-review: unresolved threads ⇒ your move; none ⇒ awaiting reviewer.
return pr.unresolvedThreads > 0 ? .changesToResolve : .awaitingReReview
case "REVIEW_REQUIRED": return .reviewRequired
default:
// No formal decision, but say whether people have engaged instead of a
// bare "open": a Comment review → "commented"; conversation → "N
// comments". (A plain "Comment" review never sets reviewDecision, so
// "open" alone hides that the PR has been looked at.)
if pr.reviewCount > 0 { return ("commented", .info, "text.bubble.fill") }
if pr.commentCount > 0 { return (pluralComment(pr.commentCount), .info, "bubble.left.fill") }
return ("open", .info, "arrow.triangle.pull")
if pr.reviewCount > 0 { return .commented }
if pr.commentCount > 0 { return .comments }
return .open
}
}

/// Map a PR's review + merge status to a label, tint, and icon — derived from
/// `classify` so it stays the single source of PR precedence.
static func status(for pr: PRSummary) -> (label: String, tint: Tint, symbol: String) {
switch classify(pr) {
case .draft: return ("draft", .neutral, "pencil.circle")
case .conflicts: return ("conflicts", .critical, "exclamationmark.triangle.fill")
case .readyToMerge: return ("ready to merge", .good, "checkmark.seal.fill")
case .approved: return ("approved", .good, "checkmark.circle.fill")
case .changesToResolve: return ("\(pr.unresolvedLabel) to resolve", .critical, "text.bubble.fill")
case .awaitingReReview: return ("awaiting re-review", .warning, "clock.arrow.circlepath")
case .reviewRequired: return ("review required", .warning, "clock.fill")
// A plain Comment review never sets reviewDecision, so "open" alone would
// hide that the PR has been looked at — distinguish engagement.
case .commented: return ("commented", .info, "text.bubble.fill")
case .comments: return (pluralComment(pr.commentCount), .info, "bubble.left.fill")
case .open: return ("open", .info, "arrow.triangle.pull")
}
}

/// Pilot actions for the PR queue. Author queues yield one *author* action per
/// PR (merge/resolve/your-move/CI); the review-requested queue yields "review"
/// actions. Other queues and no-access yield nothing (so we never suggest
/// "Merge" on a PR you don't own).
public func actions(for value: PRState, context: ModuleContext) -> [PilotAction] {
guard !value.noAccess else { return [] }
switch value.queue {
case .authored:
return value.items.compactMap { Self.authorAction(for: $0) }
case .reviewRequested:
return value.items.map { pr in
PilotAction(id: "pr-review:\(pr.repo)#\(pr.number)",
title: "Review #\(pr.number)",
subtitle: "\(pr.repo) · \(pr.title)",
symbolName: "eye", tint: .warning, priority: .reviewAsked, url: pr.url)
}
case .reviewing, .reviewedBy:
return []
}
}

/// At most ONE author action per PR, in the same precedence as `classify`, with
/// CI-failing layered on top (it is not a `status` branch, so `status` stays
/// untouched): conflicts → your-move → merge → CI-failing → nothing.
static func authorAction(for pr: PRSummary) -> PilotAction? {
switch classify(pr) {
case .draft:
return nil // don't nag about a draft
case .conflicts:
return PilotAction(id: "pr-conflicts:\(pr.repo)#\(pr.number)", title: "Resolve conflicts #\(pr.number)",
subtitle: "\(pr.repo) · \(pr.title)", symbolName: "exclamationmark.triangle.fill",
tint: .critical, priority: .conflicts, url: pr.url)
case .changesToResolve:
return PilotAction(id: "pr-threads:\(pr.repo)#\(pr.number)", title: "\(pr.unresolvedLabel) to resolve #\(pr.number)",
subtitle: "\(pr.repo) · \(pr.title)", symbolName: "text.bubble.fill",
tint: .critical, priority: .yourMove, url: pr.url)
case .readyToMerge:
return PilotAction(id: "pr-merge:\(pr.repo)#\(pr.number)", title: "Merge #\(pr.number)",
subtitle: "\(pr.repo) · approved · CI green", symbolName: "checkmark.seal.fill",
tint: .good, priority: .readyToMerge, url: pr.url)
case .approved, .awaitingReReview, .reviewRequired, .commented, .comments, .open:
// Nothing structural to do as the author — but a red pipeline is: offer
// "CI failing" here (it's not a `status` precedence branch, so layering it
// on doesn't change the panel label). Everything else is nil.
if pr.checksState == "FAILURE" || pr.checksState == "ERROR" {
return PilotAction(id: "pr-ci:\(pr.repo)#\(pr.number)", title: "CI failing #\(pr.number)",
subtitle: "\(pr.repo) · \(pr.title)", symbolName: "xmark.octagon.fill",
tint: .critical, priority: .ciFailingPR, url: pr.url)
}
return nil
}
}

Expand Down
Loading
Loading