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): gate TUI scrape on a real CLI/TUI provider, thread its command+env, wait for output before idle
[._.]/ Adam Eivy9dfa35576326
diff --git a/server/lib/tuiUsageScrape.js b/server/lib/tuiUsageScrape.jsindex eba18b4e57..9e77be8752 100644--- a/server/lib/tuiUsageScrape.js+++ b/server/lib/tuiUsageScrape.js@@ -57,6 +57,9 @@ const DEFAULT_HARD_TIMEOUT_MS = 45000; // absolute backstop for the whole scrape* @param {string} opts.command — TUI binary (`agy`, `grok`).* @param {string[]} [opts.args] — extra argv (default none).* @param {string} opts.slashCommand — e.g. `/usage` or `/usage show`.+ * @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 {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]@@ -67,6 +70,7 @@ export async function scrapeTuiUsage({command,args = [],slashCommand,+ env: extraEnv = {},sandboxDir = USAGE_SANDBOX_DIR,readyMs = DEFAULT_READY_MS,primerCapMs = DEFAULT_PRIMER_CAP_MS,@@ -79,9 +83,10 @@ export async function scrapeTuiUsage({mkdirSync(sandboxDir, { recursive: true });+ // Provider envVars (auth/config) merged over process.env, then the PTY hints.// CLAUDECODE leaks when PortOS itself runs under Claude Code; strip it so a// spawned TUI doesn't think it's nested (mirrors tuiPromptRunner.js).- const env = { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor' };+ const env = { ...process.env, ...extraEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' };delete env.CLAUDECODE;let pty;@@ -112,10 +117,20 @@ export async function scrapeTuiUsage({// idle still returns when hardStop resolves. Callers reset `lastDataAt` right// after a keystroke so this measures idle relative to that input, not to stale// banner output from an earlier phase.- const waitForIdle = async (capMs) => {- const deadline = Date.now() + capMs;+ //+ // `requireOutput` guards the render phase: after submitting the command, a+ // slow sign-in / quota lookup can stay silent for >idleMs, and without this+ // the initial silence would read as "done" and kill the TUI before its panel+ // ever renders. When set, idle can only mean completion once at least one+ // 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 } = {}) => {+ const start = Date.now();+ const deadline = start + capMs;while (!exited && !timedOut && Date.now() < deadline) {- if (Date.now() - lastDataAt >= idleMs) return;+ const sawOutput = lastDataAt > start;+ if ((!requireOutput || sawOutput) && Date.now() - lastDataAt >= idleMs) return;await Promise.race([sleep(250), hardStop]);}};@@ -138,7 +153,7 @@ export async function scrapeTuiUsage({pty.write('\r');lastDataAt = Date.now();}- await waitForIdle(renderCapMs);+ await waitForIdle(renderCapMs, { requireOutput: true });} finally {if (hardTimer) clearTimeout(hardTimer);killPty();diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 04551197a2..493966e2ea 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -344,20 +344,41 @@ export function parseGrokUsage(text) {};}+/**+ * Pick the enabled provider to actually drive for a TUI scrape: a `cli`/`tui`+ * process provider (preferring one whose command basename is the expected+ * `binary`), never an `api` provider. The `/usage` panel is a property of the+ * local CLI/TUI, not the OpenAI-compatible API endpoint — an install that+ * enables only the API provider (e.g. the built-in `grok` API, matched by id)+ * has no scrapeable surface and no `command` to spawn, so return null and let+ * the fetcher report it unsupported rather than launching an unrelated binary.+ */+function pickScrapeProvider(providers, binary) {+ const cliTui = (providers || []).filter((p) => p?.type === 'cli' || p?.type === 'tui');+ return cliTui.find((p) => commandBasename(p.command) === binary) || cliTui[0] || null;+}+/*** Build a family `fetch` fn that scrapes a TUI `/usage` panel and maps it to the- * common quota shape (cached; `refresh` bypasses). `parse` returns `{ limits }`;- * an empty result 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 note/error copy (e.g. `Antigravity CLI`).+ * common quota shape (cached; `refresh` bypasses). It drives the matched+ * provider's configured `command` (falling back to `binary`) and `envVars`, so+ * an absolute-path or env-authenticated provider scrapes with the same+ * invocation a normal run uses. `parse` returns `{ limits }`; an empty result+ * 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, command, slashCommand, label, parse, name }) {- return ({ refresh = false } = {}) => cachedScrape(id, { refresh }, async () => {- const { limits } = parse(await scrapeTuiUsage({ command, slashCommand }));- const base = { family: id, label, supported: true, plan: null, activity: [], approximate: true, fetchedAt: new Date().toISOString() };+function makeTuiUsageFetcher({ id, binary, slashCommand, label, parse, name }) {+ return ({ refresh = false, providers = [] } = {}) => cachedScrape(id, { refresh }, async () => {+ const base = { family: id, label, plan: null, activity: [], approximate: true, fetchedAt: new Date().toISOString() };+ const provider = pickScrapeProvider(providers, binary);+ 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).` };+ }+ const text = await scrapeTuiUsage({ command: provider.command || binary, slashCommand, env: provider.envVars });+ const { limits } = parse(text);return limits.length- ? { ...base, limits, note: `Scraped from the ${name} /usage panel — local, approximate.` }- : { ...base, limits: [], error: `No quota data found in the ${name} /usage panel.` };+ ? { ...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.` };});}@@ -403,13 +424,13 @@ const FAMILIES = [id: 'agy',label: 'Antigravity',matches: (p) => commandBasename(p.command) === 'agy' || /antigravity/i.test(p.id || ''),- fetch: makeTuiUsageFetcher({ id: 'agy', command: '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' })},{id: 'grok',label: 'Grok',matches: (p) => isGrokCommand(p.command) || /grok/i.test(p.id || ''),- fetch: makeTuiUsageFetcher({ id: 'grok', command: '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' })}];@@ -425,8 +446,8 @@ export function resolveEnabledFamilies(providers) {return FAMILIES.filter((family) => enabled.some((p) => family.matches(p)));}-const fetchFamilyQuota = (family, { refresh }) =>- Promise.resolve(family.fetch({ refresh })).catch((err) => ({+const fetchFamilyQuota = (family, { refresh, providers }) =>+ Promise.resolve(family.fetch({ refresh, providers })).catch((err) => ({family: family.id,label: family.label,supported: true,@@ -440,11 +461,15 @@ const fetchFamilyQuota = (family, { refresh }) =>/*** Quota status for every enabled provider family. `refresh: true` bypasses* the claude adapter's 60s cache. Never rejects — per-family failures surface- * as `error` entries.+ * as `error` entries. Each family fetch receives the enabled providers that+ * matched it, so TUI-scrape adapters drive the actual configured provider+ * (command + envVars), not a hardcoded binary.*/export async function getProviderQuotas({ refresh = false } = {}) {const result = await getAllProviders();const providers = Array.isArray(result) ? result : (result?.providers || []);+ const enabled = providers.filter((p) => p?.enabled && p.ollamaBacked !== true);const families = resolveEnabledFamilies(providers);- return Promise.all(families.map((family) => fetchFamilyQuota(family, { refresh })));+ return Promise.all(families.map((family) =>+ fetchFamilyQuota(family, { refresh, providers: enabled.filter((p) => family.matches(p)) })));}diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.jsindex 8fb5f5ac58..9aa0d5dc71 100644--- a/server/services/providerUsage.test.js+++ b/server/services/providerUsage.test.js@@ -236,14 +236,23 @@ describe('TUI usage fetchers (via getProviderQuotas)', () => {getAllProviders.mockResolvedValueOnce({ activeProvider: 'agy', providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });scrapeTuiUsage.mockResolvedValueOnce(AGY_PANEL);const [card] = await getProviderQuotas();- expect(scrapeTuiUsage).toHaveBeenCalledWith({ command: 'agy', slashCommand: '/usage' });+ expect(scrapeTuiUsage).toHaveBeenCalledWith(expect.objectContaining({ command: 'agy', slashCommand: '/usage' }));expect(card).toMatchObject({ family: 'agy', supported: true });expect(card.error).toBeUndefined();expect(card.limits).toHaveLength(4);});- it('surfaces a supported-but-error card when the scrape yields no parseable data', async () => {- getAllProviders.mockResolvedValueOnce({ activeProvider: 'grok', providers: [{ id: 'grok', enabled: true, type: 'api', endpoint: 'https://api.x.ai/v1' }] });+ it("drives the matched provider's configured command and envVars, not the bare binary", async () => {+ getAllProviders.mockResolvedValueOnce({ activeProvider: 'agy', providers: [+ { id: 'antigravity-cli', enabled: true, type: 'cli', command: '/opt/tools/agy', envVars: { AGY_TOKEN: 'x' } },+ ] });+ scrapeTuiUsage.mockResolvedValueOnce(AGY_PANEL);+ await getProviderQuotas();+ expect(scrapeTuiUsage).toHaveBeenCalledWith(expect.objectContaining({ command: '/opt/tools/agy', env: { AGY_TOKEN: 'x' } }));+ });++ it('surfaces a supported-but-error card when a CLI provider scrape yields no parseable data', async () => {+ getAllProviders.mockResolvedValueOnce({ activeProvider: 'grok', providers: [{ id: 'grok-tui', enabled: true, type: 'tui', command: 'grok' }] });scrapeTuiUsage.mockResolvedValueOnce('unrecognized banner, no usage line');const [card] = await getProviderQuotas();expect(card).toMatchObject({ family: 'grok', supported: true });@@ -251,6 +260,17 @@ describe('TUI usage fetchers (via getProviderQuotas)', () => {expect(card.error).toMatch(/No quota data/);});+ it('does NOT scrape when only the API provider is enabled — reports it unsupported', async () => {+ // The built-in `grok` API provider matches the family by id, but the /usage+ // panel is a CLI/TUI surface; scraping would launch an unrelated (possibly+ // absent) binary against a different account. Regression for that.+ getAllProviders.mockResolvedValueOnce({ activeProvider: 'grok', providers: [{ id: 'grok', enabled: true, type: 'api', endpoint: 'https://api.x.ai/v1' }] });+ const [card] = await getProviderQuotas();+ expect(scrapeTuiUsage).not.toHaveBeenCalled();+ expect(card).toMatchObject({ family: 'grok', supported: false });+ expect(card.limits).toEqual([]);+ });+it('caches a scrape and folds a bypassing refresh into a fresh call', async () => {getAllProviders.mockResolvedValue({ activeProvider: 'agy', providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });scrapeTuiUsage.mockResolvedValue(AGY_PANEL);