Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
221 changes: 221 additions & 0 deletions scripts/agents-pace-harness.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
#!/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, fetchedAt) {
var resetMs = resetMsFor(window)
fetchedAt = fetchedAt || 0
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)

// ---- a kept reading holds its position ----
// The percentage is frozen when a check fails, so the clock it is compared with
// has to be read at the same instant; otherwise the notch drifts while the fill
// stands still, and a stale row's pace reads as though it were being measured.
c = window('Rolling (5h)', 0.5, 2.5 * HOUR)
check('a fresh reading is on pace', 'on pace', paceOf(c).paceCaption)
const staleAt = NOW
panel.setNow(NOW + 45 * 60 * 1000)
check('a kept reading still reads the same an hour later', 'on pace', panel.pace(c, staleAt).paceCaption)
check('and its position is unchanged', 0.5, Math.round(panel.pace(c, staleAt).elapsed * 100) / 100)
check('while the countdown beside it does advance', 1.75 * HOUR, panel.pace(c, staleAt).resetMs)
panel.setNow(NOW)

// ---- a window rolled forward since the reading ----
// Grok rolls an expired Weekly window past its reset when its access token lapses,
// keeping the cached timestamp, so the record holds 0% against a cycle that began
// after the reading was taken. The reading's instant does not describe that window,
// and the clock its zero should be compared with is now — not ten days ago, which
// would put the notch at the start of a week that is already three days old.
c = panel.limitWindows({ limits: [{ label: 'Weekly', percent: 0, resetsAt: new Date(NOW + 4 * DAY).toISOString() }] })[0]
const longAgo = NOW - 10 * DAY
check('a window rolled forward since the reading is paced against now', 0.43, Math.round(panel.pace(c, longAgo).elapsed * 100) / 100)
check('so its zero reads as behind rather than on pace', '43% behind', panel.pace(c, longAgo).paceCaption)

// ---- 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)
95 changes: 90 additions & 5 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 @@ -569,10 +582,15 @@ Panel {
return best
}

function resetMsFor(w) {
// How long until the window resets, measured from `atMs` when one is given:
// the pace marker compares the spend with the clock at the instant the spend was
// read, not at the instant it happens to be drawn, or a reading kept past a
// failed check would drift while its percentage stood still.
function resetMsFor(w, atMs) {
if (!w || w.resetAt === "") return -1
var ms = new Date(w.resetAt).getTime()
return isFinite(ms) ? ms - root.nowMs : -1
var at = atMs === undefined || atMs <= 0 ? root.nowMs : atMs
return isFinite(ms) ? ms - at : -1
}

function formatDuration(ms) {
Expand Down Expand Up @@ -1884,6 +1902,41 @@ 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.
//
// Read at `fetchedAt` when the collector states it, so the clock is read at the
// same instant as the percentage it is compared with. A reading kept past a
// failed check then holds its position instead of drifting as `nowMs` advances,
// which would let stale numbers read as current while the row is only dimmed.
readonly property real elapsed: {
var span = compact.window ? Number(compact.window.spanMs || 0) : 0
if (span <= 0) return -1
// Read the clock at the moment the percentage was, so a reading kept past a
// failed check holds its position instead of drifting as `nowMs` advances.
var at = compact.fetchedAt
// Unless the window began after that moment, in which case it has been rolled
// forward into a new cycle since the reading was taken — Grok rolls a lapsed
// Weekly window past its reset while keeping the cached timestamp — so the
// reading's instant does not describe this window. Its zero still stands,
// since nothing spends the allowance while the agent is not running, and the
// clock to compare it with is now.
var resets = compact.window && compact.window.resetAt ? new Date(compact.window.resetAt).getTime() : NaN
if (at > 0 && isFinite(resets) && resets - span > at) at = root.nowMs
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
var remaining = at > 0 ? root.resetMsFor(compact.window, at) : compact.resetMs
if (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 +1949,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 +1982,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 +2017,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 +2035,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 +2059,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
Loading