Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): dedup repainted TUI frames, require panel marker, don't cache no-provider result
[._.]/ Adam Eivya2a430120a61
diff --git a/server/lib/tuiUsageScrape.js b/server/lib/tuiUsageScrape.jsindex 9e77be8752..8bdeb7b31e 100644--- a/server/lib/tuiUsageScrape.js+++ b/server/lib/tuiUsageScrape.js@@ -60,6 +60,11 @@ const DEFAULT_HARD_TIMEOUT_MS = 45000; // absolute backstop for the whole scrape* @param {object} [opts.env] — extra env vars merged over `process.env` (the* matched provider's `envVars`, so a provider that authenticates via env* scrapes with the same config a normal run uses).+ * @param {RegExp} [opts.readyMarker] — when set, the render phase does not+ * treat output-idle as "done" until this pattern appears in the captured+ * screen. Guards against a TUI that renders a loading row (which would arm+ * the plain idle heuristic) before its real panel arrives — completion then+ * requires the panel itself, not merely "some output then quiet."* @param {string} [opts.sandboxDir] — cwd override (default USAGE_SANDBOX_DIR).* @param {number} [opts.readyMs] @param {number} [opts.primerCapMs]* @param {number} [opts.idleMs] @param {number} [opts.renderCapMs]@@ -71,6 +76,7 @@ export async function scrapeTuiUsage({args = [],slashCommand,env: extraEnv = {},+ readyMarker = null,sandboxDir = USAGE_SANDBOX_DIR,readyMs = DEFAULT_READY_MS,primerCapMs = DEFAULT_PRIMER_CAP_MS,@@ -125,12 +131,17 @@ export async function scrapeTuiUsage({// chunk has arrived since the wait began (else we wait out `capMs`, then the// hard-timeout backstop). The primer phase leaves it off so an already-trusted// sandbox (which emits nothing) returns promptly.- const waitForIdle = async (capMs, { requireOutput = false } = {}) => {+ // `ready` (optional) is a final predicate on the captured screen that must+ // also hold before idle counts as done — used to require the actual quota+ // panel, not just any post-submit output. Only evaluated when idle is already+ // reached, so its stripAnsi cost is paid at most once per idle poll.+ const waitForIdle = async (capMs, { requireOutput = false, ready = null } = {}) => {const start = Date.now();const deadline = start + capMs;while (!exited && !timedOut && Date.now() < deadline) {const sawOutput = lastDataAt > start;- if ((!requireOutput || sawOutput) && Date.now() - lastDataAt >= idleMs) return;+ const idle = Date.now() - lastDataAt >= idleMs;+ if ((!requireOutput || sawOutput) && idle && (!ready || ready())) return;await Promise.race([sleep(250), hardStop]);}};@@ -153,7 +164,10 @@ export async function scrapeTuiUsage({pty.write('\r');lastDataAt = Date.now();}- await waitForIdle(renderCapMs, { requireOutput: true });+ await waitForIdle(renderCapMs, {+ requireOutput: true,+ ready: readyMarker ? () => readyMarker.test(stripAnsi(raw)) : null,+ });} finally {if (hardTimer) clearTimeout(hardTimer);killPty();diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 493966e2ea..9fa92eb2d8 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -277,7 +277,11 @@ export function agyRefreshToIso(text, now = Date.now()) {*/export function parseAgyUsage(text, { now = Date.now() } = {}) {const lines = String(text || '').split('\n').map((l) => l.trim());- const limits = [];+ // The scraped buffer is an append-only terminal stream: if the TUI repaints+ // the panel, an older and newer copy of each window both survive the ANSI+ // strip. Key by the stable limit key so a repaint OVERWRITES (latest wins)+ // instead of emitting duplicate rows (which would collide on the React key).+ const byKey = new Map();const groups = new Set();let group = null;for (let i = 0; i < lines.length; i++) {@@ -300,19 +304,19 @@ export function parseAgyUsage(text, { now = Date.now() } = {}) {}if (remaining === null) continue; // not a real limit blockconst windowLabel = agyWindowLabel(w[1]);- const percentRemaining = Math.round(remaining);- limits.push({- key: `${slug(group)}-${slug(windowLabel)}`,+ const key = `${slug(group)}-${slug(windowLabel)}`;+ byKey.set(key, {+ key,label: `${group} · ${windowLabel}`,scope: slug(windowLabel),model: group,percentUsed: Math.max(0, Math.round(100 - remaining)),- percentRemaining,+ percentRemaining: Math.round(remaining),resetsAt: quotaAvailable ? null : resetsAt,timezone: null,});}- return { limits, groups: groups.size };+ return { limits: [...byKey.values()], groups: groups.size };}/**@@ -324,10 +328,14 @@ export function parseAgyUsage(text, { now = Date.now() } = {}) {*/export function parseGrokUsage(text) {const str = String(text || '');- const wl = str.match(/weekly limit:\s*([\d.]+)\s*%/i);+ // Append-only terminal stream: a repaint leaves an older copy of the line+ // ahead of the newer one, so take the LAST match (the freshest frame), not+ // the first (see parseAgyUsage for the same repaint hazard).+ const lastMatch = (re) => { const all = [...str.matchAll(re)]; return all.length ? all[all.length - 1] : null; };+ const wl = lastMatch(/weekly limit:\s*([\d.]+)\s*%/gi);if (!wl) return { limits: [] };const percentUsed = Math.round(parseFloat(wl[1]));- const nr = str.match(/next reset:\s*([A-Za-z0-9 ,:]+?)(?:\s{2,}|$)/i);+ const nr = lastMatch(/next reset:\s*([A-Za-z0-9 ,:]+?)(?:\s{2,}|$)/gi);return {limits: [{key: 'weekly',@@ -367,19 +375,28 @@ function pickScrapeProvider(providers, binary) {* becomes a `supported`-but-`error` card so the UI shows a soft warning rather* than a blank card. `name` is the human product name spliced into the copy.*/-function makeTuiUsageFetcher({ id, binary, slashCommand, label, parse, name }) {- return ({ refresh = false, providers = [] } = {}) => cachedScrape(id, { refresh }, async () => {+function makeTuiUsageFetcher({ id, binary, slashCommand, label, parse, name, readyMarker }) {+ return ({ refresh = false, providers = [] } = {}) => {const base = { family: id, label, plan: null, activity: [], approximate: true, fetchedAt: new Date().toISOString() };const provider = pickScrapeProvider(providers, binary);+ // No CLI/TUI provider (e.g. only the API provider is enabled) → unsupported.+ // Returned OUTSIDE cachedScrape so it is NOT cached: enabling the CLI later+ // must take effect on the next load, not be masked by a 5-min stale "off".if (!provider) {- return { ...base, supported: false, limits: [], note: `${name} usage is read from the local CLI/TUI — enable the ${name} to see quota (the API provider has no queryable usage surface).` };+ return Promise.resolve({ ...base, supported: false, limits: [], note: `${name} usage is read from the local CLI/TUI — enable the ${name} to see quota (the API provider has no queryable usage surface).` });}- const text = await scrapeTuiUsage({ command: provider.command || binary, slashCommand, env: provider.envVars });- const { limits } = parse(text);- return limits.length- ? { ...base, supported: true, limits, note: `Scraped from the ${name} /usage panel — local, approximate.` }- : { ...base, supported: true, limits: [], error: `No quota data found in the ${name} /usage panel.` };- });+ return cachedScrape(id, { refresh }, async () => {+ // Only `command` + `envVars` are forwarded — deliberately NOT the+ // provider's `args`. Stored args are headless-mode flags (`-p`, `exec -`,+ // `--print`, `--prompt-file`) that would break the interactive TUI we need+ // for `/usage`; the TUI launches bare.+ const text = await scrapeTuiUsage({ command: provider.command || binary, slashCommand, env: provider.envVars, readyMarker });+ const { limits } = parse(text);+ return limits.length+ ? { ...base, supported: true, limits, note: `Scraped from the ${name} /usage panel — local, approximate.` }+ : { ...base, supported: true, limits: [], error: `No quota data found in the ${name} /usage panel.` };+ });+ };}// --- Claude: wrap the existing /usage CLI parser ---------------------------@@ -424,13 +441,13 @@ const FAMILIES = [id: 'agy',label: 'Antigravity',matches: (p) => commandBasename(p.command) === 'agy' || /antigravity/i.test(p.id || ''),- fetch: makeTuiUsageFetcher({ id: 'agy', binary: 'agy', slashCommand: '/usage', label: 'Antigravity', parse: parseAgyUsage, name: 'Antigravity CLI' })+ fetch: makeTuiUsageFetcher({ id: 'agy', binary: 'agy', slashCommand: '/usage', label: 'Antigravity', parse: parseAgyUsage, name: 'Antigravity CLI', readyMarker: /Weekly Limit|Five Hour Limit|Models & Quota/i })},{id: 'grok',label: 'Grok',matches: (p) => isGrokCommand(p.command) || /grok/i.test(p.id || ''),- fetch: makeTuiUsageFetcher({ id: 'grok', binary: 'grok', slashCommand: '/usage show', label: 'Grok', parse: parseGrokUsage, name: 'Grok Build CLI' })+ fetch: makeTuiUsageFetcher({ id: 'grok', binary: 'grok', slashCommand: '/usage show', label: 'Grok', parse: parseGrokUsage, name: 'Grok Build CLI', readyMarker: /Weekly limit:/i })}];diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.jsindex 9aa0d5dc71..8523cb284d 100644--- a/server/services/providerUsage.test.js+++ b/server/services/providerUsage.test.js@@ -211,6 +211,16 @@ describe('parseAgyUsage', () => {expect(parseAgyUsage('Welcome to the Antigravity CLI').limits).toEqual([]);expect(parseAgyUsage('').limits).toEqual([]);});++ it('dedups repainted frames to one row per key (no duplicate React keys)', () => {+ // The append-only PTY buffer can contain the panel twice if the TUI+ // repaints; latest-wins so keys stay unique and the newer value survives.+ const repainted = AGY_PANEL + '\n' + AGY_PANEL.replace('98.99%', '55.00%').replace('99% remaining', '55% remaining');+ const { limits } = parseAgyUsage(repainted, { now: NOW });+ expect(limits).toHaveLength(4);+ expect(new Set(limits.map((l) => l.key)).size).toBe(4);+ expect(limits.find((l) => l.key === 'gemini-weekly').percentRemaining).toBe(55); // newest frame won+ });});describe('parseGrokUsage', () => {@@ -224,6 +234,12 @@ describe('parseGrokUsage', () => {expect(parseGrokUsage('Grok Build Beta 0.2.101').limits).toEqual([]);expect(parseGrokUsage(undefined).limits).toEqual([]);});++ it('takes the freshest (last) frame when the panel is repainted', () => {+ const repainted = 'Weekly limit: 10% Next reset: July 1, 00:00\nWeekly limit: 73% Next reset: August 1, 06:07';+ const { limits } = parseGrokUsage(repainted);+ expect(limits[0]).toMatchObject({ percentUsed: 73, percentRemaining: 27, resetsAt: 'August 1, 06:07' });+ });});describe('TUI usage fetchers (via getProviderQuotas)', () => {