34.7 KiB · text History 905ae26
import QtQuick
import QtQuick.Layouts
import org.kde.plasma.plasmoid
import org.kde.plasma.core as PlasmaCore
import org.kde.kirigami as Kirigami
import org.kde.notification

import "Vigil.js" as Vigil

PlasmoidItem {
    id: root

    switchWidth: Kirigami.Units.gridUnit * 20
    switchHeight: Kirigami.Units.gridUnit * 16

    // In a panel always the circles, however much room we're given; on
    // the desktop let Plasma pick by size.
    preferredRepresentation: Plasmoid.formFactor === PlasmaCore.Types.Horizontal
                             || Plasmoid.formFactor === PlasmaCore.Types.Vertical
                             ? compactRepresentation : null

    Plasmoid.backgroundHints: PlasmaCore.Types.DefaultBackground | PlasmaCore.Types.ConfigurableBackground

    // The header's pin, as in the system tray: a pinned popup stays open
    // when focus moves elsewhere.
    hideOnWindowDeactivate: !Plasmoid.configuration.pin

    // The logo and each circle carry their own tooltips; the applet-wide
    // one would just sit on top of them.
    toolTipMainText: ""
    toolTipSubText: ""

    readonly property url logoSource: Qt.resolvedUrl("../icons/vigil.svg")

    property string serverUrl: Plasmoid.configuration.serverUrl
    property string accessToken: Plasmoid.configuration.accessToken
    readonly property string orgSetting: Plasmoid.configuration.organization
    readonly property string projectsJson: Plasmoid.configuration.projects
    readonly property bool foldOrg: Plasmoid.configuration.foldOrg
    readonly property int updateInterval: Math.max(15, Plasmoid.configuration.updateInterval)
    readonly property int recentHours: Math.max(1, Plasmoid.configuration.recentHours)
    readonly property bool notifyNewIssues: Plasmoid.configuration.notifyNewIssues
    readonly property bool notifyRegressions: Plasmoid.configuration.notifyRegressions
    readonly property bool notifyMonitors: Plasmoid.configuration.notifyMonitors
    readonly property string projectFilter: Plasmoid.configuration.projectFilter

    readonly property bool hasValidConfig: api.configured

    // ── server state ────────────────────────────────────────────────────

    property var me: null               // {id, email, name}
    property var scopes: []
    readonly property bool canTriage: scopes.indexOf("event:write") !== -1
    property string authError: ""       // the token was refused; polling stops until it changes

    property var orgs: []               // [{id, slug, name}]
    property bool orgsLoaded: false
    property double orgsAt: 0
    property var projects: []           // the org's [{id, slug, name, platform}]
    property string projectsOrg: ""     // whose projects `projects` are

    property var issues: []             // unresolved, watched projects, newest activity first
    property bool moreIssues: false     // there were more than the pages fetched
    property bool issuesLoaded: false
    property var crons: []
    property var uptimes: []
    property bool monitorsLoaded: false
    property string monitorsError: ""

    // What the last poll saw, for telling news apart from what was there.
    property var knownUnresolved: ({})  // issue key -> true
    property var resolvedSeen: ({})     // issue key -> true: resolved when last seen
    property var regressedAt: ({})      // issue key -> ms it was seen coming back
    property var monitorFailing: ({})   // "cron:<id>" | "uptime:<id>" -> bool
    property bool primed: false         // a poll has landed: notify from the next one
    property double lastPollAt: 0       // start of the last poll that landed

    property bool loading: false
    property bool refreshQueued: false
    property double loadingSince: 0
    property int generation: 0
    property bool offline: false
    property string lastError: ""
    property double now: Date.now()

    // View state, kept here so it survives the list refreshing.
    property string expandedKey: ""
    property var events: ({})           // issue key -> {lastSeen, event} | {lastSeen, error}
    property var pending: ({})          // issue key -> true while a triage is out
    property string flash: ""
    property bool flashIsError: false
    property var lastAction: null       // {issue (before), update}, for Undo

    VigilAPI {
        id: vigilApi
        baseUrl: root.serverUrl
        accessToken: root.accessToken
    }
    property alias api: vigilApi

    // ── derived ─────────────────────────────────────────────────────────

    readonly property var org: {
        if (orgs.length === 0) return null
        for (var i = 0; i < orgs.length; i++) if (orgs[i].slug === orgSetting) return orgs[i]
        return orgs[0]
    }
    readonly property string orgSlug: org ? org.slug : ""

    readonly property var watchedSlugs: Vigil.parseList(projectsJson)
    readonly property bool everyProject: watchedSlugs.length === 0
    readonly property bool folded: everyProject || foldOrg

    // The watched projects, in circle order; slugs no longer there drop out.
    readonly property var watchedProjects: {
        if (projectsOrg !== orgSlug) return []
        if (everyProject) return projects
        var bySlug = {}
        for (var i = 0; i < projects.length; i++) bySlug[projects[i].slug] = projects[i]
        return watchedSlugs.map(function(s) { return bySlug[s] }).filter(function(p) { return !!p })
    }

    function watches(projectRef) {
        if (!projectRef) return false
        if (everyProject) return true
        return watchedSlugs.indexOf(projectRef.slug) !== -1
    }

    readonly property var watchedCrons: crons.filter(function(m) { return root.watches(m.project) })
    readonly property var watchedUptimes: uptimes.filter(function(m) { return root.watches(m.project) })

    readonly property var unresolvedIssues: issues.filter(function(i) { return i.status === "unresolved" })

    // One project's (or, for null, every watched project's) health.
    function healthOf(slug) {
        var mine = function(ref) { return slug === null || (ref && ref.slug === slug) }
        var out = { health: "unknown", unresolved: 0, fresh: 0, regressed: 0, failing: [] }
        if (!issuesLoaded) return out
        var t = now
        for (var i = 0; i < unresolvedIssues.length; i++) {
            var issue = unresolvedIssues[i]
            if (!mine(issue.project)) continue
            out.unresolved++
            var k = Vigil.issueKey(issue)
            if (regressedAt[k] && t - regressedAt[k] <= recentHours * 3600000) out.regressed++
            else if (Vigil.within(issue.firstSeen, t, recentHours)) out.fresh++
        }
        for (var c = 0; c < watchedCrons.length; c++) {
            if (mine(watchedCrons[c].project) && Vigil.cronState(watchedCrons[c]).failing) out.failing.push(watchedCrons[c].name)
        }
        for (var u = 0; u < watchedUptimes.length; u++) {
            if (mine(watchedUptimes[u].project) && Vigil.uptimeState(watchedUptimes[u]).failing) out.failing.push(watchedUptimes[u].name)
        }
        out.health = out.failing.length > 0 || out.regressed > 0 ? "failing" : out.fresh > 0 ? "new" : "ok"
        return out
    }

    function summaryLines(h) {
        var lines = []
        if (h.health === "unknown") return [i18n("Not loaded yet")]
        var n = moreIssues && h === totals ? h.unresolved + "+" : String(h.unresolved)
        lines.push(h.unresolved === 0 ? i18n("Nothing unresolved") : i18np("%2 unresolved issue", "%2 unresolved issues", h.unresolved, n))
        if (h.fresh > 0) lines.push(i18np("%1 new in the last %2 h", "%1 new in the last %2 h", h.fresh, recentHours))
        if (h.regressed > 0) lines.push(i18np("%1 regressed", "%1 regressed", h.regressed))
        if (h.failing.length > 0) lines.push(i18n("Failing: %1", h.failing.join(", ")))
        return lines
    }

    readonly property var totals: healthOf(null)

    // [{key, label, slug ("" = every watched project), health, tooltip}]
    readonly property var circles: {
        if (!hasValidConfig || !org) return []
        if (folded) {
            return [{ key: "org", label: org.name || org.slug, slug: "", health: totals.health,
                      tooltip: summaryLines(totals).concat(statusLine()).filter(function(s) { return s !== "" }).join("\n") }]
        }
        return watchedProjects.map(function(p) {
            var h = root.healthOf(p.slug)
            return { key: "p:" + p.slug, label: p.name || p.slug, slug: p.slug, health: h.health,
                     tooltip: root.summaryLines(h).concat(root.statusLine()).filter(function(s) { return s !== "" }).join("\n") }
        })
    }

    // "offline · retrying" and the like: what's wrong with the data, if anything.
    function statusLine() {
        if (authError !== "") return authError
        if (offline) return i18n("offline · retrying")
        if (lastError !== "") return lastError
        return ""
    }

    readonly property string logoTooltip: {
        if (!hasValidConfig) return i18n("Click to connect to Vigil")
        if (authError !== "") return authError
        var lines = []
        if (org && orgs.length > 1) lines.push(org.name || org.slug)
        lines = lines.concat(summaryLines(totals))
        var s = statusLine()
        if (s !== "") lines.push(s)
        return lines.join("\n")
    }

    readonly property string badgeText: {
        if (!issuesLoaded) return ""
        var n = unresolvedIssues.length
        if (n === 0) return ""
        return n > 99 || moreIssues ? "99+" : String(n)
    }

    // The popup's rows: the project filter on top of the watched set.
    readonly property var shownIssues: issues.filter(function(i) {
        return root.projectFilter === "" || (i.project && i.project.slug === root.projectFilter)
    })

    // Cron and uptime monitors together, failing first.
    readonly property var monitorRows: {
        var rows = []
        var f = projectFilter
        var t = now
        watchedCrons.forEach(function(m) {
            if (f !== "" && m.project.slug !== f) return
            var st = Vigil.cronState(m)
            var bits = []
            if (m.schedule) bits.push(m.schedule)
            bits.push(m.lastCheckIn ? i18n("last check-in %1", Vigil.relativeTime(m.lastCheckIn, t)) : i18n("never checked in"))
            if (m.nextCheckIn && m.status !== "disabled") bits.push(i18n("next due %1", Vigil.relativeTime(m.nextCheckIn, t)))
            rows.push({ key: "cron:" + m.id, kind: "cron", name: m.name, project: m.project, state: st,
                        detail: bits.join(" · "), url: api.cronUrl(root.orgSlug, m.project.slug, m.slug) })
        })
        watchedUptimes.forEach(function(m) {
            if (f !== "" && m.project.slug !== f) return
            var st = Vigil.uptimeState(m)
            var bits = []
            if (m.status === "down" && m.reason) bits.push(m.reason)
            else if (m.target) bits.push(m.target)
            if (m.responseMs) bits.push(m.responseMs + " ms")
            if (m.lastChange) bits.push(i18n("%1 since %2", st.label, Vigil.relativeTime(m.lastChange, t).replace(/ ago$/, "")))
            rows.push({ key: "uptime:" + m.id, kind: "uptime", name: m.name, project: m.project, state: st,
                        detail: bits.join(" · "), url: api.uptimeUrl(root.orgSlug, m.id) })
        })
        rows.sort(function(a, b) {
            return a.state.rank - b.state.rank || a.name.toLowerCase().localeCompare(b.name.toLowerCase())
        })
        return rows
    }

    readonly property int failingMonitorCount: monitorRows.filter(function(r) { return r.state.failing }).length

    // ── the list model ──────────────────────────────────────────────────
    //
    // Synced in place rather than replaced, so a poll doesn't reset the
    // popup's scroll or rebuild every row.

    ListModel { id: issuesModel }      // {key, issueJson}
    readonly property ListModel issuesModelRef: issuesModel

    function syncModel(model, items) {
        for (var i = 0; i < items.length; i++) {
            var item = items[i]
            var found = -1
            for (var j = i; j < model.count; j++) {
                if (model.get(j).key === item.key) { found = j; break }
            }
            if (found === -1) {
                model.insert(i, item)
                continue
            }
            if (found !== i) model.move(found, i, 1)
            var row = model.get(i)
            for (var prop in item) {
                if (row[prop] !== item[prop]) model.setProperty(i, prop, item[prop])
            }
        }
        while (model.count > items.length) model.remove(model.count - 1)
    }

    onShownIssuesChanged: syncModel(issuesModel, shownIssues.map(function(i) {
        return { key: Vigil.issueKey(i), issueJson: JSON.stringify(i) }
    }))

    // ── resets ──────────────────────────────────────────────────────────

    onServerUrlChanged: resetAll()
    onAccessTokenChanged: resetAll()
    onProjectsJsonChanged: resetWatch()
    // The first org to load isn't a change; switching to another is.
    property string seenOrg: ""
    onOrgSlugChanged: {
        if (seenOrg !== "" && orgSlug !== "" && seenOrg !== orgSlug) resetWatch()
        if (orgSlug !== "") seenOrg = orgSlug
    }

    function resetAll() {
        if (!started) return
        api.abortAll()
        generation++
        loading = false
        me = null
        scopes = []
        authError = ""
        orgs = []
        orgsLoaded = false
        projects = []
        projectsOrg = ""
        seenOrg = ""
        offline = false
        lastError = ""
        resetData()
    }

    function resetWatch() {
        if (!started) return
        api.abortAll()
        generation++
        loading = false
        resetData()
    }

    // What we watch changed: start the news-tracking over, so switching
    // org doesn't announce its whole backlog.
    function resetData() {
        issues = []
        moreIssues = false
        issuesLoaded = false
        crons = []
        uptimes = []
        monitorsLoaded = false
        monitorsError = ""
        knownUnresolved = {}
        resolvedSeen = {}
        regressedAt = {}
        monitorFailing = {}
        primed = false
        expandedKey = ""
        events = {}
        Qt.callLater(refresh)
    }

    // ── polling ─────────────────────────────────────────────────────────

    // Config values landing while the item is built aren't changes.
    property bool started: false
    Component.onCompleted: {
        started = true
        refresh()
    }

    function refresh() {
        if (!hasValidConfig || authError !== "") return
        if (loading) {
            refreshQueued = true
            return
        }
        loading = true
        loadingSince = Date.now()
        var gen = ++generation
        var started = Date.now()
        function current() { return gen === root.generation }

        function finish() {
            if (!current()) return
            loading = false
            if (refreshQueued) {
                refreshQueued = false
                Qt.callLater(refresh)
            }
        }

        function failed(message, network) {
            if (!current()) return
            offline = network
            if (!network) lastError = message
            finish()
        }

        // 1. Who the token is, and what it may do.
        function identity(next) {
            if (me) return next()
            api.whoami(function(ok, data, network, status) {
                if (!current()) return
                if (!ok) {
                    if (status === 401) {
                        authError = data
                        return finish()
                    }
                    return failed(data, network)
                }
                if (!data.user) {
                    authError = i18n("The server didn't recognise that token")
                    return finish()
                }
                me = data.user
                scopes = data.auth && data.auth.scopes ? data.auth.scopes : []
                next()
            })
        }

        // 2. The organizations and the chosen one's projects, every ten
        // minutes or when the choice changes.
        function orgAndProjects(next) {
            var stale = Date.now() - orgsAt > 10 * 60 * 1000
            function projectsStep() {
                if (!org) {
                    lastError = i18n("The token can't see any organization")
                    return finish()
                }
                if (projectsOrg === orgSlug && !stale) return next()
                api.projects(orgSlug, function(ok, data, network) {
                    if (!current()) return
                    if (!ok) return failed(data, network)
                    projects = data
                    projectsOrg = orgSlug
                    next()
                })
            }
            if (orgsLoaded && !stale) return projectsStep()
            api.organizations(function(ok, data, network) {
                if (!current()) return
                if (!ok) return failed(data, network)
                orgs = data
                orgsLoaded = true
                orgsAt = Date.now()
                projectsStep()
            })
        }

        // 3. Issues (unresolved, and the recently-seen resolved ones, to
        // tell a regression) and monitors, side by side.
        function fetchData() {
            var projectIds = everyProject ? [] : watchedProjects.map(function(p) { return p.id })
            if (!everyProject && projectIds.length === 0) {
                // Every watched project is gone: nothing to ask for.
                issues = []
                issuesLoaded = true
                lastError = i18n("None of the watched projects are left in %1", org.name || orgSlug)
                return finish()
            }

            var outstanding = 4
            var unresolved = []
            var more = false
            var resolved = null
            var cronList = null
            var uptimeList = null
            var networkDown = false
            var firstError = ""

            function done() {
                if (!current()) return
                if (--outstanding > 0) return
                offline = networkDown
                if (networkDown) return finish()   // keep the last data
                lastError = firstError
                if (unresolved !== null) {
                    landIssues(unresolved, more, resolved, started)
                }
                if (cronList !== null || uptimeList !== null) {
                    landMonitors(cronList, uptimeList)
                }
                if (unresolved !== null) {
                    primed = true
                    lastPollAt = started
                }
                finish()
            }

            function note(message, network) {
                if (network) networkDown = true
                else if (firstError === "") firstError = message
            }

            // Up to three pages of a hundred.
            function page(cursor, n) {
                api.issues(orgSlug, "is:unresolved", projectIds, cursor, 100, function(ok, rows, network, status, link) {
                    if (!current()) return
                    if (!ok) {
                        note(rows, network)
                        unresolved = null
                        return done()
                    }
                    unresolved = unresolved.concat(rows)
                    var next = Vigil.nextCursor(link)
                    if (next !== "" && n < 3) return page(next, n + 1)
                    more = next !== ""
                    done()
                })
            }
            page("", 1)

            api.issues(orgSlug, "is:resolved", projectIds, "", 100, function(ok, rows, network) {
                if (!current()) return
                if (ok) resolved = rows
                else note(rows, network)
                done()
            })

            api.monitors(orgSlug, function(ok, rows, network) {
                if (!current()) return
                if (ok) cronList = rows
                else if (network) note(rows, true)
                else monitorsError = rows
                done()
            })

            api.uptime(orgSlug, function(ok, rows, network) {
                if (!current()) return
                if (ok) uptimeList = rows
                else if (network) note(rows, true)
                else monitorsError = rows
                done()
            })
        }

        identity(function() { orgAndProjects(fetchData) })
    }

    // A poll's issues landed: find what's news, then keep them.
    function landIssues(list, more, resolvedList, started) {
        var t = Date.now()
        var known = knownUnresolved
        var wasResolved = resolvedSeen
        var regs = {}
        var nowKnown = {}
        // An issue that predates the last poll but is new to the list
        // came off another page; only one first seen since then is new.
        var since = lastPollAt - 5 * 60 * 1000

        for (var i = 0; i < list.length; i++) {
            var issue = list[i]
            var k = Vigil.issueKey(issue)
            nowKnown[k] = true
            if (regressedAt[k] && t - regressedAt[k] <= recentHours * 3600000) regs[k] = regressedAt[k]
            if (known[k]) continue
            if (wasResolved[k]) {
                regs[k] = t
                if (primed && notifyRegressions) notifyIssue(issue, true)
            } else if (primed && notifyNewIssues && Vigil.parseTime(issue.firstSeen) >= since) {
                notifyIssue(issue, false)
            }
        }

        var res = {}
        if (resolvedList) {
            for (var r = 0; r < resolvedList.length; r++) res[Vigil.issueKey(resolvedList[r])] = true
        } else {
            // The resolved page failed this time: keep what we knew.
            for (var w in wasResolved) if (!nowKnown[w]) res[w] = true
        }

        issues = list
        moreIssues = more
        issuesLoaded = true
        knownUnresolved = nowKnown
        resolvedSeen = res
        regressedAt = regs
        now = t
    }

    function landMonitors(cronList, uptimeList) {
        var failing = Object.assign({}, monitorFailing)
        var hadAny = Object.keys(monitorFailing).length > 0 || monitorsLoaded
        if (cronList !== null) {
            cronList.forEach(function(m) {
                var k = "cron:" + m.id
                var f = Vigil.cronState(m).failing
                if (f && failing[k] === false && root.primed && root.notifyMonitors && root.watches(m.project)) notifyMonitor("cron", m)
                failing[k] = f
            })
            crons = cronList
        }
        if (uptimeList !== null) {
            uptimeList.forEach(function(m) {
                var k = "uptime:" + m.id
                var f = Vigil.uptimeState(m).failing
                if (f && failing[k] === false && root.primed && root.notifyMonitors && root.watches(m.project)) notifyMonitor("uptime", m)
                failing[k] = f
            })
            uptimes = uptimeList
        }
        if (cronList !== null && uptimeList !== null) monitorsError = ""
        monitorFailing = failing
        monitorsLoaded = true
    }

    Timer {
        // Offline (just woke, Wi-Fi not back yet): retry soon rather than
        // sitting on an error for a whole interval.
        interval: (root.offline ? Math.min(15, root.updateInterval) : root.updateInterval) * 1000
        running: root.hasValidConfig && root.authError === ""
        repeat: true
        onTriggered: root.refresh()
    }

    // Wall-clock watchdog. Timers don't fire during suspend, so a tick
    // that arrives far later than scheduled means the machine slept: any
    // request open across that is suspect, so drop them all and start
    // over. It also unsticks a poll that has outlived every timeout.
    Timer {
        property double lastTick: Date.now()
        interval: 5000
        running: true
        repeat: true
        onTriggered: {
            var t = Date.now()
            var gap = t - lastTick
            lastTick = t
            if (gap > interval * 6) {
                root.recover("resumed after " + Math.round(gap / 1000) + "s")
            } else if (root.loading && t - root.loadingSince > root.api.timeoutMs * 3) {
                root.recover("poll stuck for " + Math.round((t - root.loadingSince) / 1000) + "s")
            }
        }
    }

    function recover(reason) {
        console.log("Vigil: recovering —", reason)
        api.abortAll()
        generation++
        loading = false
        refreshQueued = false
        refresh()
    }

    // Relative times tick over while the popup is open.
    Timer {
        interval: 30 * 1000
        running: root.expanded
        repeat: true
        onTriggered: root.now = Date.now()
    }

    onExpandedChanged: function() {
        if (!root.expanded) return
        now = Date.now()
        // A poll already out is as fresh as one sent now.
        if (!loading && Date.now() - lastPollAt > 15 * 1000) refresh()
    }

    // ── the accordion ───────────────────────────────────────────────────

    function setKey(obj, key, value) {
        var copy = Object.assign({}, obj)
        if (value === undefined) delete copy[key]
        else copy[key] = value
        return copy
    }

    function toggleIssue(issue) {
        var k = Vigil.issueKey(issue)
        if (expandedKey === k) {
            expandedKey = ""
            return
        }
        expandedKey = k
        var cached = events[k]
        if (!cached || cached.lastSeen !== issue.lastSeen || cached.error) loadEvent(issue)
    }

    function loadEvent(issue) {
        var k = Vigil.issueKey(issue)
        events = setKey(events, k, { lastSeen: issue.lastSeen, loading: true, event: events[k] ? events[k].event : null })
        api.latestEvent(orgSlug, issue.project.slug, issue.id, function(ok, data) {
            events = setKey(events, k, ok ? { lastSeen: issue.lastSeen, event: data }
                                          : { lastSeen: issue.lastSeen, error: data })
        })
    }

    // ── triage ──────────────────────────────────────────────────────────

    Timer {
        id: flashTimer
        interval: 8000
        onTriggered: {
            root.flash = ""
            root.lastAction = null
        }
    }

    function showFlash(message, isError) {
        flash = message
        flashIsError = !!isError
        flashTimer.restart()
    }

    function replaceIssue(updated) {
        var k = Vigil.issueKey(updated)
        issues = issues.map(function(i) { return Vigil.issueKey(i) === k ? updated : i })
    }

    // A status ({status}) or assignee ({assignedTo}) change to one issue.
    // The row keeps its new status until the next poll drops it, so it
    // can still be put back from there or with Undo.
    function triage(issue, update, done, undoing) {
        var k = Vigil.issueKey(issue)
        pending = setKey(pending, k, true)
        api.updateIssues(orgSlug, issue.project.slug, [issue.id], update, function(ok, data, network, status) {
            pending = setKey(pending, k, undefined)
            if (!ok) {
                showFlash(i18n("%1: %2", issue.shortId, data), true)
                return
            }
            if (status === 204) {
                issues = issues.filter(function(i) { return Vigil.issueKey(i) !== k })
                showFlash(i18n("%1 isn't there any more", issue.shortId), true)
                return
            }
            var after = Vigil.applying(issue, update, data)
            replaceIssue(after)
            if (after.status === "resolved") resolvedSeen = setKey(resolvedSeen, k, true)
            else resolvedSeen = setKey(resolvedSeen, k, undefined)
            if (after.status === "unresolved") knownUnresolved = setKey(knownUnresolved, k, true)
            lastAction = undoing ? null : { issue: issue, update: update }
            showFlash(i18n("%1: %2", issue.shortId, done), false)
        })
    }

    function setStatus(issue, option) {
        var past = { resolved: i18n("resolved"), resolvedInNextRelease: i18n("resolved in the next release"),
                     ignored: i18n("ignored"), unresolved: i18n("reopened") }
        triage(issue, { status: option.status }, past[option.status] || option.status, false)
    }

    function assignedToMe(issue) {
        return !!(me && issue.assignedTo && String(issue.assignedTo.id) === String(me.id))
    }

    function toggleAssignMe(issue) {
        if (!me) return
        if (assignedToMe(issue)) triage(issue, { assignedTo: "" }, i18n("unassigned"), false)
        else triage(issue, { assignedTo: "user:" + me.id }, i18n("assigned to you"), false)
    }

    // Puts the last change back as it was before.
    function undo() {
        var a = lastAction
        if (!a) return
        lastAction = null
        var before = a.issue
        var update = {}
        if (a.update.status !== undefined) {
            update.status = before.status === "resolved" && before.statusDetails && before.statusDetails.inNextRelease
                            ? "resolvedInNextRelease" : before.status
        }
        if (a.update.assignedTo !== undefined) {
            update.assignedTo = before.assignedTo && before.assignedTo.id ? "user:" + before.assignedTo.id : ""
        }
        var current = issues.filter(function(i) { return Vigil.issueKey(i) === Vigil.issueKey(before) })[0] || before
        triage(current, update, i18n("undone"), true)
    }

    // ── popup helpers ───────────────────────────────────────────────────

    function selectOrg(slug) {
        Plasmoid.configuration.organization = slug
        Plasmoid.configuration.projectFilter = ""
    }

    function openCircle(slug) {
        Plasmoid.configuration.projectFilter = slug
        root.expanded = true
    }

    function openWeb() {
        if (!orgSlug) {
            Qt.openUrlExternally(api.normalizedBase())
        } else if (projectFilter !== "") {
            Qt.openUrlExternally(api.projectUrl(orgSlug, projectFilter))
        } else {
            Qt.openUrlExternally(api.orgUrl(orgSlug))
        }
    }

    Plasmoid.contextualActions: [
        PlasmaCore.Action {
            text: i18n("Open Vigil in Browser")
            icon.name: "internet-web-browser"
            enabled: root.hasValidConfig
            onTriggered: root.openWeb()
        },
        PlasmaCore.Action {
            text: i18n("Refresh")
            icon.name: "view-refresh"
            enabled: root.hasValidConfig
            onTriggered: {
                root.authError = ""
                root.refresh()
            }
        }
    ]

    // ── notifications ───────────────────────────────────────────────────
    //
    // Only for changes seen between two polls: nothing fires for what was
    // already true on the first one, nor after the org or the watched
    // projects change.

    function notifyIssue(issue, regressed) {
        var note = notificationComponent.createObject(root, {
            title: regressed ? i18n("Regressed in %1: %2", issue.project.name || issue.project.slug, issue.title)
                             : i18n("New issue in %1: %2", issue.project.name || issue.project.slug, issue.title),
            text: [issue.shortId, issue.culprit || "", Vigil.levelLabel(issue.level)].filter(function(s) { return s !== "" }).join(" · "),
            iconName: regressed ? "dialog-warning" : "dialog-error",
            urgency: regressed || issue.level === "fatal" ? Notification.HighUrgency : Notification.NormalUrgency,
            url: issue.permalink || api.projectUrl(orgSlug, issue.project.slug),
            projectSlug: issue.project.slug,
            issueKey: Vigil.issueKey(issue)
        })
        if (note) note.sendEvent()
    }

    function notifyMonitor(kind, m) {
        var note = notificationComponent.createObject(root, {
            title: kind === "cron" ? i18n("Cron monitor failing: %1", m.name) : i18n("Down: %1", m.name),
            text: [m.project.name || m.project.slug,
                   kind === "cron" ? (m.lastCheckIn ? i18n("last check-in %1", Vigil.relativeTime(m.lastCheckIn, Date.now())) : "")
                                   : (m.reason || m.target || "")].filter(function(s) { return s !== "" }).join(" · "),
            iconName: "dialog-error",
            urgency: Notification.HighUrgency,
            url: kind === "cron" ? api.cronUrl(orgSlug, m.project.slug, m.slug) : api.uptimeUrl(orgSlug, m.id),
            projectSlug: m.project.slug,
            issueKey: ""
        })
        if (note) note.sendEvent()
    }

    Component {
        id: notificationComponent
        Notification {
            id: note
            property string url
            property string projectSlug
            property string issueKey

            componentName: "plasma_workspace"
            eventId: "notification"
            autoDelete: false

            defaultAction: NotificationAction {
                label: i18n("Show")
                onActivated: {
                    Plasmoid.configuration.projectFilter = root.folded ? "" : note.projectSlug
                    if (note.issueKey !== "") {
                        var issue = root.issues.filter(function(i) { return Vigil.issueKey(i) === note.issueKey })[0]
                        if (issue && root.expandedKey !== note.issueKey) root.toggleIssue(issue)
                    }
                    root.expanded = true
                }
            }
            actions: [
                NotificationAction {
                    label: i18n("Open in Browser")
                    onActivated: Qt.openUrlExternally(note.url)
                }
            ]

            onClosed: note.destroy()
        }
    }

    // ── representations ─────────────────────────────────────────────────

    compactRepresentation: CircleStrip {
        store: root
    }

    fullRepresentation: FullView {
        Layout.minimumWidth: Kirigami.Units.gridUnit * 22
        Layout.minimumHeight: Kirigami.Units.gridUnit * 18
        Layout.preferredWidth: Kirigami.Units.gridUnit * 30
        Layout.preferredHeight: Kirigami.Units.gridUnit * 32
        store: root
    }
}