summaryrefslogtreecommitdiff
path: root/_usage_footer.lua
blob: 421afd5470a6f4996b8047e79028a4eba0b9b546 (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
-- Identical private copies share one footer hook, without a companion rock.
-- Each published section renders on its own row.
local M = {}
-- v3 sections include the whole row, unlike v2 which added a prefix in the hook.
local slot = "panto.subscription_usage.v3"

local function text(value)
    return tostring(value):gsub("[%c]", " "):sub(1, 100)
end

local function reset_time(value)
    if type(value) == "number" then
        if value == value and value >= 0 and value <= 253402300799 then return value end
        return nil
    end
    if type(value) ~= "string" then return nil end
    local y, m, d, h, n, tail = value:match("^(%d%d%d%d)%-(%d%d)%-(%d%d)[Tt ](%d%d):(%d%d)(.*)$")
    if not y then return nil end
    local s, zone = tail:match("^:(%d%d)(.*)$")
    if s then zone = zone:gsub("^%.%d+", "") else s, zone = "0", tail end
    y, m, d, h, n, s = tonumber(y), tonumber(m), tonumber(d), tonumber(h), tonumber(n), tonumber(s)
    local leap = y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0)
    local days = { 31, leap and 29 or 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
    if y < 1 or m < 1 or m > 12 or d < 1 or d > days[m] or h > 23 or n > 59 or s > 59 then return nil end
    local offset = 0
    if zone ~= "Z" and zone ~= "z" then
        local sign, oh, om = zone:match("^([+-])(%d%d):(%d%d)$")
        if not sign or tonumber(oh) > 23 or tonumber(om) > 59 then return nil end
        offset = (tonumber(oh) * 60 + tonumber(om)) * 60 * (sign == "+" and 1 or -1)
    end
    -- Gregorian civil date to Unix days; independent of local timezone/DST.
    y = y - (m <= 2 and 1 or 0)
    local era = math.floor(y / 400)
    local year = y - era * 400
    local day = math.floor((153 * (m + (m > 2 and -3 or 9)) + 2) / 5) + d - 1
    local unix_days = era * 146097 + year * 365 + math.floor(year / 4) - math.floor(year / 100) + day - 719468
    return unix_days * 86400 + h * 3600 + n * 60 + s - offset
end

local function countdown(reset, now)
    if not reset then return "reset unknown" end
    local seconds = reset - now
    if seconds <= 0 then return "reset due" end
    if seconds < 60 then return "reset in <1m" end
    local minutes = math.floor(seconds / 60)
    local parts = {}
    for _, unit in ipairs({ {1440, "d"}, {60, "h"}, {1, "m"} }) do
        local amount = math.floor(minutes / unit[1])
        if amount > 0 then parts[#parts + 1] = amount .. unit[2] end
        minutes = minutes % unit[1]
    end
    return "reset in " .. table.concat(parts, " ")
end

M.text, M.reset_time, M.countdown = text, reset_time, countdown

-- Build one subscription's complete section text as a renderer. The renderer
-- is re-evaluated each frame so countdowns and theme colors stay live without
-- refetching. opts.status appends a status word. Invalid windows are dropped here.
function M.section(ext, label, windows, opts)
    opts = type(opts) == "table" and opts or { status = opts }
    label = text(label):gsub("^%S+", string.lower)
    local provider = (label:match("^(.-) %(") or label):lower()
    local status = opts.status and text(opts.status) or nil
    local snapshot = {}
    for _, window in ipairs(windows or {}) do
        local percent = window.used_percent
        local valid = type(percent) == "number" and percent == percent and percent >= 0 and percent < math.huge
        local at = reset_time(window.resets_at)
        if valid or (percent == nil and at ~= nil) then
            snapshot[#snapshot + 1] = {
                label = text(window.label or "quota"), used_percent = valid and percent or nil, resets_at = at,
            }
        end
    end
    return function(now)
        local style = type(ext.style) == "function" and ext.style() or {}
        local base, reset = style.dim or style.footer or "\27[2m", style.reset or "\27[0m"
        local blue = style.syntax_function or "\27[36m"
        local accent = "\27[1m" .. blue
        -- Use the same severity colors as the native footer context meter.
        local green = style.tool_success or "\27[32m"
        local yellow = style.compaction_header or "\27[33m"
        local red = style.tool_error or "\27[31m"
        local label_color = ({
            claude = yellow, codex = style.canvas_fg or "\27[97m",
            ["opencode go"] = style.thinking_header or "\27[35m",
        })[provider] or blue
        local function paint(color, value) return reset .. color .. value .. reset .. base end
        local parts = {}
        for _, window in ipairs(snapshot) do
            local percent = window.used_percent
            local color = percent and (percent <= 33 and green or percent <= 66 and yellow or red) or base
            local value = percent and string.format("%.1f%%", percent):gsub("%.0%%", "%%") or "?%"
            local meter = ""
            if percent then
                -- Match the native context meter's glyphs, rounding and minimum nonzero fill.
                local filled = math.floor(math.min(percent, 100) / 20 + 0.5)
                if percent > 0 then filled = math.max(1, filled) end
                local fill = filled > 0 and paint(color, string.rep("━", filled)) or ""
                meter = fill .. string.rep("─", 5 - filled) .. " "
            end
            parts[#parts + 1] = paint(accent, window.label) .. " " .. paint(color, value) .. " "
                .. meter .. countdown(window.resets_at, now)
        end
        local detail = table.concat(parts, ", ")
        if status then
            detail = detail == "" and status or (detail .. " · " .. status)
        end
        return detail ~= "" and (paint("\27[1m" .. label_color, label) .. " usage: " .. detail .. reset) or nil
    end
end

local function start_clock(state)
    if state.timer then return end
    local ok, uv = pcall(require, "luv")
    if not ok or type(uv.new_timer) ~= "function" then return end
    state.timer = uv.new_timer()
    state.timer:start(60000, 60000, function()
        if not state.closed and state.handle then state.handle:invalidate() end
    end)
    state.timer:unref()
end

-- Install during activate(), before render_footer; sections may arrive later.
function M.install(ext)
    if type(ext.on) ~= "function" then return nil end
    local state = package.loaded[slot]
    if not state then
        state = { sections = {} }
        package.loaded[slot] = state
        ext.on("render_footer", function(event)
            if event.has_tui == false then return end
            local inner = event:get_component()
            state.handle = event:set_component({
                render = function(_, width)
                    local lines = inner:render(width)
                    local now, keys = os.time(), {}
                    for key in pairs(state.sections) do keys[#keys + 1] = key end
                    table.sort(keys)
                    for _, key in ipairs(keys) do
                        local section = state.sections[key]
                        local line = type(section) == "function" and section(now) or section
                        if type(line) == "string" and line ~= "" then
                            lines[#lines + 1] = line
                        end
                    end
                    return lines
                end,
            })
            if state.handle and next(state.sections) then start_clock(state) end
        end)
        ext.on("session_end", function()
            state.closed = true
            if state.timer then state.timer:stop(); state.timer:close(); state.timer = nil end
        end)
    end
    return state
end

-- Publish a section renderer (or plain string).
-- Each account has a stable key and its own row.
-- Also accepts (ext, key, label, windows, status, opts) for direct callers.
function M.publish(ext, key, section, windows, status, opts)
    local state = M.install(ext)
    if not state or state.closed then return false end
    if windows ~= nil or status ~= nil or opts ~= nil then
        local section_opts = type(opts) == "table" and opts or {}
        if status ~= nil then section_opts.status = status end
        section = M.section(ext, section, windows, section_opts)
    end
    if type(section) ~= "function" and type(section) ~= "string" then return false end
    state.sections[key] = section
    if state.handle then
        start_clock(state)
        state.handle:invalidate()
    end
    return true
end

return M