Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
196 changes: 196 additions & 0 deletions scripts/agents-pace-harness.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
#!/usr/bin/env node
// Run the agents panel's limit-row pace logic without a QML runtime.
//
// node agents-pace-harness.js <path/to/Panel.qml>
//
// The panel's own code is what runs. The window helpers are brace-extracted and
// evaluated together, since they call one another, and CompactLimit's pace
// bindings — elapsed, paceKnown, paceDelta, paceCaption — are extracted and run
// as one program, so the caption is driven by the shipped paceDelta reading the
// shipped elapsed. A harness that re-implemented them would pass while the
// shipped bindings were wrong, which is the defect it exists to catch.
//
// Three extractor traps, each of which fakes a result rather than crashing:
// * a single-line binding has no brace to match, so it is read to end of line —
// and a multi-line expression body would be silently truncated, which is why
// every binding here is either one line or a block;
// * a block body already ends in `return`; an expression body does not, so the
// wrapper has to add one or every reader sees `undefined`;
// * the component reaches its own properties as `compact.<name>`, which the
// compiled program has as locals.

const fs = require('fs')
const path = process.argv[2]
if (!path) {
console.error('usage: agents-pace-harness.js <path/to/Panel.qml>')
process.exit(2)
}
const source = fs.readFileSync(path, 'utf8')

const HELPERS = ['windowIsLong', 'windowSpanMs', 'windowTitle', 'limitWindow',
'limitWindows', 'displayWindows', 'scopedPart', 'resetMsFor', 'clamp']
const BINDINGS = ['elapsed', 'paceKnown', 'paceDelta', 'paceCaption']
const SELF = 'compact'

function extractBlock(from) {
const start = from.indexOf('{')
if (start < 0) return null
let depth = 0
let quote = null
for (let i = start; i < from.length; i++) {
const c = from[i]
if (quote) {
if (c === '\\') i++
else if (c === quote) quote = null
continue
}
if (c === '"' || c === "'") { quote = c; continue }
if (c === '/' && from[i + 1] === '/') { i = from.indexOf('\n', i); if (i < 0) return null; continue }
if (c === '{') depth++
else if (c === '}') { depth--; if (depth === 0) return from.slice(start + 1, i) }
}
return null
}

function functionSource(name) {
const at = source.indexOf('function ' + name + '(')
if (at < 0) return null
const open = source.indexOf('(', at)
const close = source.indexOf(')', open)
const body = extractBlock(source.slice(at))
if (body === null) return null
return { params: source.slice(open + 1, close), body }
}

function bindingBody(name) {
const m = source.match(new RegExp('readonly property \\w+ ' + name + ':'))
if (!m) return null
const rest = source.slice(m.index + m[0].length).replace(/^\s*/, '')
if (!rest.startsWith('{')) return { body: rest.split('\n')[0].trim(), block: false }
const body = extractBlock(rest)
return body === null ? null : { body, block: true }
}

const helperSources = HELPERS.map(functionSource)
const bindingBodies = BINDINGS.map(bindingBody)
for (let i = 0; i < HELPERS.length; i++)
if (!helperSources[i]) { console.error('could not extract ' + HELPERS[i]); process.exit(1) }
for (let i = 0; i < BINDINGS.length; i++)
if (!bindingBodies[i]) { console.error('could not extract binding ' + BINDINGS[i]); process.exit(1) }

const wrap = (body, block) => (block ? body : 'return (' + body + ')')
// The component reaches its own properties as `compact.<name>`, and the helpers
// as `root.<name>`; the compiled program has both as locals.
const strip = text => text
.replace(new RegExp('\\b' + SELF + '\\.', 'g'), '')
.replace(/\broot\./g, '')

const program = `
var nowMs = 0
function pace(window) {
var resetMs = resetMsFor(window)
var ${BINDINGS.join(', ')}
${BINDINGS.map((name, i) =>
name + ' = (function(){' + wrap(strip(bindingBodies[i].body), bindingBodies[i].block) + '})();').join('\n ')}
return { elapsed: elapsed, paceKnown: paceKnown, paceDelta: paceDelta, paceCaption: paceCaption, resetMs: resetMs }
}
return { pace: pace, setNow: function(v) { nowMs = v },
windowSpanMs: windowSpanMs, windowTitle: windowTitle, limitWindows: limitWindows,
displayWindows: displayWindows, resetMsFor: resetMsFor }
`

const build = new Function(
helperSources.map((h, i) => 'function ' + HELPERS[i] + '(' + h.params + ') {' + strip(h.body) + '}').join('\n')
+ '\n' + program)
const panel = build()

let pass = 0
let fail = 0
function check(name, expected, actual) {
const e = JSON.stringify(expected)
const a = JSON.stringify(actual)
if (e === a) { console.log('ok - ' + name); pass++ }
else { console.log('not ok - ' + name + '\n expected: ' + e + '\n actual: ' + a); fail++ }
}

const HOUR = 3600 * 1000
const DAY = 24 * HOUR
const NOW = 1700000000000
panel.setNow(NOW)

// A window as the collector states it, run through the shipped limitWindow().
function window(label, percent, msLeft, title) {
const resetAt = new Date(NOW + msLeft).toISOString()
return panel.limitWindows({ limits: [{ label: label, percent: percent, resetsAt: resetAt, title: title }] })[0]
}
const paceOf = w => panel.pace(w)

// ---- the cycle a label names ----
for (const [label, span] of [
['Rolling (5h)', 5 * HOUR],
['5h window', 5 * HOUR],
['5 hours', 5 * HOUR],
['Weekly (7-day)', 7 * DAY],
['Monthly', 30 * DAY],
['Session', 0],
['30m window', 30 * 60 * 1000],
['Rolling (30m)', 30 * 60 * 1000],
['90m window', 90 * 60 * 1000],
['120m window', 120 * 60 * 1000],
['Opus 5 (1M context) Session', 0],
['Opus 5 (1m context) Session', 0],
['GPT 5.4 (1M context)', 0],
['Opus 5 (1M context) 30m window', 30 * 60 * 1000],
['Opus 5 (1M context) 5h window', 5 * HOUR],
['Opus 5 (1M context) Weekly', 7 * DAY]
]) {
check('windowSpanMs reads ' + label, span, panel.windowSpanMs(label))
}

// ---- the elapsed fraction and the caption ----
let c = window('Rolling (5h)', 0.16, 47 * 60 * 1000)
check('a 5h window with 47m left is ~84% elapsed', 0.84, Math.round(paceOf(c).elapsed * 100) / 100)
check('and 68 points behind the clock reads as behind', '68% behind', paceOf(c).paceCaption)

c = window('Weekly (7-day)', 0.26, (4 * 24 + 10) * HOUR)
check('a 7d window with 4d10h left is ~37% elapsed', 0.37, Math.round(paceOf(c).elapsed * 100) / 100)
check('and 11 points behind reads as behind', '11% behind', paceOf(c).paceCaption)

// 90% used with two hours of a five-hour cycle left: 60% of the clock gone, so
// the fill is well past it.
c = window('Rolling (5h)', 0.9, 2 * HOUR)
check('a window ahead of the clock says so', '30% ahead', paceOf(c).paceCaption)

c = window('Rolling (5h)', 0.5, 2.5 * HOUR)
check('a level window reads as on pace', 'on pace', paceOf(c).paceCaption)

c = window('Session', 0.5, 30 * 60 * 1000)
check('a window of unknown length has no elapsed position', -1, paceOf(c).elapsed)
check('a window of unknown length says nothing', '', paceOf(c).paceCaption)

c = window('Opus 5 (1M context) Session', 0.5, 30 * 60 * 1000)
check('a model-scoped window is left unpaced', '', paceOf(c).paceCaption)

// A window whose reset has passed keeps no position: it is not 100% through, it
// is over, and the row shows a fresh window instead.
c = window('Rolling (5h)', 0.5, -60 * 1000)
check('an already-reset window has no elapsed position', -1, paceOf(c).elapsed)

// The elapsed fraction is clamped, so a reset further out than the cycle states
// cannot put the notch off the track.
c = window('Rolling (5h)', 0.5, 6 * HOUR)
check('a window before its cycle clamps to zero elapsed', 0, paceOf(c).elapsed)

// ---- the span survives the row-building ----
// displayWindows() attaches scoped allowances to their base row; it must not drop
// the cycle on the way through, or the meter loses its marker.
const built = panel.displayWindows({ limits: [
{ label: 'Rolling (5h)', percent: 0.4, resetsAt: new Date(NOW + 2 * HOUR).toISOString() },
{ label: 'Rolling (5h)', percent: 0.2, resetsAt: new Date(NOW + 2 * HOUR).toISOString(), title: 'Fable Session' }
] })
check('displayWindows keeps the cycle on the base row', 5 * HOUR, built[0].spanMs)
check('and attaches the scoped allowance to it', 1, built[0].scoped.length)
check('the scoped allowance keeps its own percent', 0.2, built[0].scoped[0].percent)

console.log('\n' + pass + ' passed, ' + fail + ' failed')
process.exit(fail === 0 ? 0 : 1)
69 changes: 66 additions & 3 deletions shell/plugins/agents/Panel.qml
Original file line number Diff line number Diff line change
Expand Up @@ -483,9 +483,17 @@ Panel {
var text = String(label || "").toLowerCase()
if (text.indexOf("month") >= 0 || text.indexOf("30-day") >= 0) return 30 * 24 * 3600 * 1000
if (windowIsLong(text)) return 7 * 24 * 3600 * 1000
var hours = text.match(/(\d+)\s*-?\s*h(?:our)?\b/)
var hours = text.match(/(\d+)\s*-?\s*h(?:our)?s?\b/)
if (hours) return Number(hours[1]) * 3600 * 1000
var minutes = text.match(/(\d+)\s*-?\s*m(?:in(?:ute)?s?)?\b/)
// A context size is not a cycle, and it sits exactly where a duration would:
// "Opus 5 (1M context) Session" is a five-hour session whose "1M" would
// otherwise parse as one minute — and "1m" is indistinguishable from it once
// the label is lowercased, so the word "context" is the only tell. A number
// is dropped only where that word says it is a context size, so a collector
// stating a real cycle beside one keeps it, and "30m", "90m" and
// "120m window" stay cycles at any length.
var minutes = text.replace(/\b\d+\s*m(?=\s*(?:context|million))/g, " ")
.match(/(\d+)\s*-?\s*(?:min(?:ute)?s?\b|m\b)/)
if (minutes) return Number(minutes[1]) * 60 * 1000
return 0
}
Expand All @@ -509,7 +517,12 @@ Panel {
return {
title: String(title || "") !== "" ? String(title) : windowTitle(label),
percent: expired ? 0 : Number(percent),
resetAt: expired ? "" : String(resetAt || "")
resetAt: expired ? "" : String(resetAt || ""),
// The cycle the label names, kept because the display title — "Session" is
// what a five-hour window is called on screen — drops the duration the pace
// marker needs, and it has to be read from the raw label before the title
// is derived from it.
spanMs: windowSpanMs(label)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}
}

Expand Down Expand Up @@ -1884,6 +1897,24 @@ Panel {
readonly property var scoped: window && window.scoped ? window.scoped : []
readonly property bool alarming: window && window.percent >= 0.9
readonly property real resetMs: root.resetMsFor(window)
// How far through its cycle the window is: the elapsed fraction of the label's
// cycle, or -1 when the label names no cycle (a model-scoped limit, a window
// stated without a duration) or the window has already reset.
readonly property real elapsed: {
var span = compact.window ? Number(compact.window.spanMs || 0) : 0
var remaining = compact.resetMs
if (span <= 0 || remaining < 0) return -1
return root.clamp(1 - remaining / span, 0, 1)
}
readonly property bool paceKnown: compact.elapsed >= 0 && !!compact.window && compact.window.percent >= 0
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
readonly property real paceDelta: compact.paceKnown ? compact.window.percent - compact.elapsed : 0
// Under a point either way reads as level rather than as noise.
readonly property string paceCaption: {
if (!compact.paceKnown) return ""
var points = Math.round(Math.abs(compact.paceDelta) * 100)
if (points < 1) return "on pace"
return points + "% " + (compact.paceDelta > 0 ? "ahead" : "behind")
}
implicitHeight: Math.max(compactTitle.implicitHeight, compactValue.implicitHeight)

HoverHandler { id: compactHover }
Expand All @@ -1896,6 +1927,10 @@ Panel {
lines.push(compact.window.title + ": " + Math.round(compact.window.percent * 100) + "% used"
+ (compact.resetMs > 0 ? " · resets in " + root.formatDuration(compact.resetMs) : ""))
}
// The row shows the pace as a band and a notch on the meter; the words
// live here, with the exact percentage, so the row stays one line.
if (compact.paceCaption !== "")
lines.push(Math.round(compact.elapsed * 100) + "% of the cycle elapsed · " + compact.paceCaption)
if (compact.stale)
lines.push(compact.fetchedAt > 0 && root.nowMs - compact.fetchedAt > 60000
? "Last updated " + root.formatDuration(root.nowMs - compact.fetchedAt) + " ago"
Expand Down Expand Up @@ -1925,6 +1960,7 @@ Panel {
anchors.rightMargin: Style.space(20)
anchors.verticalCenter: parent.verticalCenter
value: compact.window ? compact.window.percent : -1
elapsed: compact.elapsed
alarming: compact.alarming
markers: compact.scoped
}
Expand Down Expand Up @@ -1959,6 +1995,10 @@ Panel {
id: meter
property real value: -1
property bool alarming: false
// How far through its cycle the window is, or -1 when its label names no
// cycle. Drawn dimly behind the fill, so the fill can be read against the
// clock: past the notch is ahead of it, short of it is behind.
property real elapsed: -1
property real thickness: Math.max(Style.space(4), Math.round(Style.spacing.controlHeight * 0.14))

// Other allowances on the same clock, drawn as ticks across the track.
Expand All @@ -1973,6 +2013,17 @@ Panel {
color: root.track
}

// The elapsed part of the cycle, dim under the fill.
Rectangle {
visible: meter.elapsed >= 0
anchors.left: meterTrack.left
anchors.verticalCenter: meterTrack.verticalCenter
height: meterTrack.height
radius: meterTrack.radius
width: meterTrack.width * root.clamp(meter.elapsed, 0, 1)
color: root.alpha(root.foreground, 0.22)
}

Rectangle {
anchors.left: meterTrack.left
anchors.verticalCenter: meterTrack.verticalCenter
Expand All @@ -1986,6 +2037,18 @@ Panel {
}
}

// Where the clock stands in the cycle, marked so the fill can be compared
// with it. Dim, so it reads as the clock rather than as another allowance.
Rectangle {
visible: meter.elapsed >= 0
width: Math.max(2, Math.round(meter.thickness * 0.5))
height: meter.thickness * 2.5
radius: width / 2
anchors.verticalCenter: meterTrack.verticalCenter
x: root.clamp(meterTrack.width * root.clamp(meter.elapsed, 0, 1) - width / 2, 0, meterTrack.width - width)
color: root.dim
}

Repeater {
model: meter.markers

Expand Down
8 changes: 7 additions & 1 deletion shell/plugins/agents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ Every subscription on one page, limits first.
corner has + to add a subscription and >_ to start the default agent.
- **One section per agent** — its mark, name, and plan, then a compact line
per limit window: its meter and the time until it resets (the exact percentage
on hover). A model-scoped allowance on the same clock (Claude's Fable weekly
on hover). When the window's label states its cycle — "5h window",
"Weekly (7-day)" — the meter also carries the cycle's elapsed time dimly behind
the fill, its edge marked by a notch: fill past the notch is ahead of the clock,
short of it is behind, and the tooltip says by how much ("42% of the cycle
elapsed · 12% behind"). A window whose label states no cycle — a model-scoped
limit, one named without a duration — keeps the plain meter. A model-scoped
allowance on the same clock (Claude's Fable weekly
limit) is a tick on that window's meter rather than a line of its own; the
row's tooltip names it. A lapsed or missing sign-in shows a _Sign-in required_ link that signs
that account in again from the panel; other endpoint trouble shows under the
Expand Down
14 changes: 7 additions & 7 deletions test/shell.d/agent-usage-claude-limits-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -343,23 +343,23 @@ assertDeepEqual(
{ label: 'Opus 5 (1M context) Weekly', title: 'Opus 5 (1M context) Weekly', percent: 0.42, resetsAt: '' }
] }),
[
{ title: 'Session', percent: 0.78, resetAt: '' },
{ title: 'Opus 5 (1M context) Weekly', percent: 0.42, resetAt: '' }
{ title: 'Session', percent: 0.78, resetAt: '', spanMs: 5 * 3600 * 1000 },
{ title: 'Opus 5 (1M context) Weekly', percent: 0.42, resetAt: '', spanMs: 7 * 24 * 3600 * 1000 }
],
'agents panel titles a limit off the collector when it states one'
)

assertDeepEqual(
limitWindows({ limits: [{ label: 'Weekly (7-day)', percent: 0.12, resetsAt: '' }] }),
[{ title: 'Weekly', percent: 0.12, resetAt: '' }],
[{ title: 'Weekly', percent: 0.12, resetAt: '', spanMs: 7 * 24 * 3600 * 1000 }],
'agents panel still reads a window out of a label that carries no title'
)

const resetAt = new Date(panelRoot.nowMs + 1000).toISOString()
const measured = { limits: [{ label: 'Session (5-hour)', percent: 0.78, resetsAt: resetAt }] }
assertEqual(limitWindows(measured)[0].percent, 0.78, 'usage remains until the reset time')
panelRoot.nowMs += 1000
assertDeepEqual(limitWindows(measured), [{ title: 'Session', percent: 0, resetAt: '' }], 'usage resets at the deadline while the panel stays open')
assertDeepEqual(limitWindows(measured), [{ title: 'Session', percent: 0, resetAt: '', spanMs: 5 * 3600 * 1000 }], 'usage resets at the deadline while the panel stays open')
assertEqual(measured.limits[0].percent, 0.78, 'display reset leaves the measured record intact')

// A model's weekly allowance rides under the Weekly row; one whose window has
Expand All @@ -372,9 +372,9 @@ assertDeepEqual(
{ label: 'Opus Monthly', title: 'Opus Monthly', percent: 0.5, resetsAt: '' }
] }),
[
{ title: 'Session', percent: 0.94, resetAt: '', scoped: [] },
{ title: 'Weekly', percent: 0.25, resetAt: 'w', scoped: [{ title: 'Fable', percent: 0.09, resetAt: 'w' }] },
{ title: 'Opus Monthly', percent: 0.5, resetAt: '', scoped: [] }
{ title: 'Session', percent: 0.94, resetAt: '', spanMs: 5 * 3600 * 1000, scoped: [] },
{ title: 'Weekly', percent: 0.25, resetAt: 'w', spanMs: 7 * 24 * 3600 * 1000, scoped: [{ title: 'Fable', percent: 0.09, resetAt: 'w' }] },
{ title: 'Opus Monthly', percent: 0.5, resetAt: '', spanMs: 30 * 24 * 3600 * 1000, scoped: [] }
],
'agents panel shows a model-scoped window under the window it runs on'
)
Expand Down
Loading