Skip to content

feat(api): add tenant-facing AI-usage endpoint in compute-units - #7717

Closed
joaovictor712 wants to merge 1 commit into
JSONbored:mainfrom
joaovictor712:feat/tenant-ai-usage-endpoint-7660
Closed

feat(api): add tenant-facing AI-usage endpoint in compute-units#7717
joaovictor712 wants to merge 1 commit into
JSONbored:mainfrom
joaovictor712:feat/tenant-ai-usage-endpoint-7660

Conversation

@joaovictor712

Copy link
Copy Markdown
Contributor

Summary

  • sumAiCostForTenantSince (src/db/repositories.ts, added via Add tenant column to ai_usage_events for centralized hosted billing across ORB + AMS #7176 for centralized hosted billing) had zero real callers outside its own test file — its fleet-wide sibling listAiCostByTenantSince is consumed only by the operator-only dashboard, so no ORB or AMS hosted tenant could see their own usage/spend anywhere.
  • Adds a new tenant-facing GET /v1/app/tenant-ai-usage route that calls sumAiCostForTenantSince and returns the figure in normalized compute-units — mirroring packages/loopover-engine/src/tenant-quota.ts's TenantQuota.computeUnits shape, never the raw costUsd dollar figure (src/services/tenant-ai-usage.ts's new costUsdToComputeUnits/sumTenantAiComputeUnitsSince).
  • The route is scoped the same way /v1/app/maintainer-dashboard already scopes its data: it reuses that route's exact loadControlPanelAccessScope call and installation-filtering logic, so a session only ever sees the AI cost billed to the installation(s) their own GitHub login controls, never another tenant's spend.
  • Regenerated apps/loopover-ui/public/openapi.json and added the route to src/openapi/spec.ts alongside its /v1/app/* siblings.

Scope

  • The PR title follows type(scope): short summary Conventional Commit format, for example fix(api): restore profile access checks.
  • This PR is focused and does not mix unrelated backend, UI, MCP, docs, dependency, and deploy changes.
  • This follows CONTRIBUTING.md and does not reintroduce GitHub Pages, VitePress, site/, or CNAME.
  • I linked a currently open issue this PR resolves (e.g. Closes #123) — a linked open issue is required for every contributor PR.

Validation

  • git diff --check
  • npm run actionlint
  • npm run typecheck (whole-repo tsc OOMs in this sandbox; verified with a scoped tsc --noEmit on the exact changed files + src/env.d.ts/worker-configuration.d.ts using the root tsconfig.json's compiler flags — clean, no errors)
  • npm run test:coverage locally; codecov/patch requires ≥99% coverage of the lines AND branches you changed (aim for 100% on your diff so CI variance does not fail near the threshold). Global coverage is a non-blocking trend with a loose 90% backstop, not the gate.
  • npm run test:workers
  • npm run build:mcp
  • npm run test:mcp-pack
  • npm run ui:openapi:check
  • npm run ui:lint
  • npm run ui:typecheck
  • npm run ui:build
  • npm audit --audit-level=moderate
  • New or changed behavior has unit/integration tests for new branches, fallback paths, and sanitizer boundaries

If any required check was skipped, explain why:

  • None skipped; whole-repo npm run typecheck OOMs in this sandbox specifically (known local resource limit), so it was substituted with an equivalent scoped tsc --noEmit invocation covering every changed file with the project's exact strict compiler flags.

Safety

  • No secrets, wallet details, hotkeys, coldkeys, user PATs, private keys, raw trust scores, private rankings, or private maintainer evidence are exposed.
  • Public GitHub text stays sanitized, low-noise, and does not imply compensation guarantees or optimization tactics.
  • Auth, cookie, CORS, GitHub App, Cloudflare, or session changes include negative-path tests. (unauthenticated → 401, insufficient role → 403, and cross-tenant scoping-exclusion are all covered by new tests)
  • API/OpenAPI/MCP behavior is updated and tested where needed.
  • UI changes use live API data or real empty/error/loading states, not production mock/demo fallbacks. (N/A — this PR is backend-only; no apps/loopover-ui/** route or component changes)
  • Visible UI changes include a UI Evidence section below with JPG/JPEG or PNG screenshots arranged as organized, captioned, clickable thumbnails. SVG screenshots are not used as review evidence. Review-only screenshots or recordings are not committed to the repository. (N/A — no visible UI change; see the issue's own "Area" field, src/api/routes.ts/src/services/)
  • Public docs/changelogs are updated where needed; changelogs are only edited for release-prep PRs.

UI Evidence

N/A — this is a backend-only change (new API route). No apps/loopover-ui/** files were touched beyond the regenerated, machine-generated openapi.json.

Notes

  • Unit conversion: 1 compute-unit = $0.01 (one USD cent), floored — an integer figure that still tracks spend proportionally without echoing a fractional-dollar cost back to the tenant. No change to how cost itself is tracked or computed; this is a read-only exposure of the already-computed sumAiCostForTenantSince figure, converted to the decided unit.

Closes #7660

sumAiCostForTenantSince had zero real callers outside its own test
file, and its fleet-wide sibling listAiCostByTenantSince is
operator-only, so no hosted tenant could see their own AI usage/spend
anywhere. GET /v1/app/tenant-ai-usage exposes that figure converted to
normalized compute-units (mirroring tenant-quota.ts's shape, never raw
costUsd), scoped the same way /v1/app/maintainer-dashboard already
scopes its data.

Closes #7660
@joaovictor712
joaovictor712 requested a review from JSONbored as a code owner July 21, 2026 10:52
@superagent-security

Copy link
Copy Markdown
Contributor

Superagent didn't find any vulnerabilities or security issues in this PR.

@codecov

codecov Bot commented Jul 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.74%. Comparing base (3a9450b) to head (f6e8b3d).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7717      +/-   ##
==========================================
- Coverage   88.56%   79.74%   -8.83%     
==========================================
  Files         725       84     -641     
  Lines       76266    22952   -53314     
  Branches    22705     3648   -19057     
==========================================
- Hits        67544    18302   -49242     
+ Misses       7680     4472    -3208     
+ Partials     1042      178     -864     
Flag Coverage Δ
shard-1 0.00% <ø> (-52.85%) ⬇️
shard-2 0.00% <ø> (-51.96%) ⬇️
shard-3 0.00% <ø> (-48.48%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.
see 641 files with indirect coverage changes

@loopover-orb loopover-orb Bot added the gittensor:feature Gittensor-scored feature linked to a feature issue — scores a 0.25x multiplier. label Jul 21, 2026
@loopover-orb

loopover-orb Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Caution

🛑 LoopOver review result - fixes required

Review updated: 2026-07-21 10:58:15 UTC

6 files · 1 AI reviewer · no blockers · CI failing · blocked

🛑 Suggested Action - Fix Blockers

Review summary
Adds a tenant-facing GET /v1/app/tenant-ai-usage endpoint that reuses the existing loadControlPanelAccessScope logic from maintainer-dashboard to scope AI cost data per installation, converts raw costUsd to compute-units via a new pure helper (costUsdToComputeUnits), and wires the route into the OpenAPI spec and generated openapi.json. The scoping logic mirrors an already-trusted pattern (maintainer-dashboard route) rather than inventing new access-control logic, and the conversion/aggregation logic is covered by both unit and route-level tests including a duplicate-tenant-isolation test. The route is well-scoped to the linked issue (#7660) and doesn't bundle unrelated changes.

Nits — 4 non-blocking
  • The route handler in src/api/routes.ts duplicates the installation-scoping filter logic already present in the maintainer-dashboard route instead of extracting a shared helper, which risks the two scoping implementations drifting apart over time.
  • costUsdToComputeUnits truncates via Math.floor without ever aggregating fractional cents lost per-installation before summing (fine here since costs are summed before flooring, but worth a comment noting the summing happens pre-floor to avoid future refactors introducing per-installation flooring).
  • Consider extracting the installation-scoping block (src/api/routes.ts, scope/installations construction) shared between /v1/app/maintainer-dashboard and /v1/app/tenant-ai-usage into a helper to keep the two access-control paths from silently diverging.
  • Add a JSDoc/comment noting USD_PER_COMPUTE_UNIT should stay in sync with packages/loopover-engine/src/tenant-quota.ts's own unit definition, since the PR notes this duplication is intentional but unmonitored.

CI checks failing

  • validate
  • validate-tests-merge

Decision drivers

  • ✅ Code review — No blockers (1 reviewer)
  • ✅ Gate result — Passing (No configured blocker found.)
Context & advisory signals — never blocks the verdict
Signal Result Evidence
Linked issue ✅ Linked #7660
Related work ✅ No active overlap found No same-issue or scoped active PR overlap found.
Change scope ✅ 20/20 Low review scope from cached public metadata (1 linked issue).
Validation posture ✅ 25/25 PR body includes validation/test evidence.
Contributor workload ✅ 10/10 Author activity: 1950 registered-repo PR(s), 1280 merged, 53 issue(s).
Contributor context ✅ Confirmed Gittensor contributor galuis116; Gittensor profile; 1950 PR(s), 53 issue(s).
Improvement ✅ Minor risk: clean · value: minor · LLM: moderate
Linked issue satisfaction

Addressed
The PR adds a tenant-scoped GET /v1/app/tenant-ai-usage route that calls sumAiCostForTenantSince (via sumTenantAiComputeUnitsSince), converts the raw cost into normalized compute-units rather than raw costUsd, and reuses loadControlPanelAccessScope, the same scoping helper used by /v1/app/maintainer-dashboard, to restrict results to the requesting session's own installations. Tests verify tenant i

Review context
  • Author: galuis116
  • Role context: outside_contributor
  • Public audience mode: oss maintainer
  • Lane context: Repository is configured for direct PR review.
  • Public profile languages: JavaScript, Python, Dart, TypeScript, HTML, MDX, Rust, C++
  • Official Gittensor activity: 1950 PR(s), 53 issue(s).
  • PR-specific overlap: none found.
Contributor next steps
  • Keep the PR focused and include validation evidence before maintainer review.
Signal definitions
  • Related work = same linked issue, overlapping active PRs, or title/path similarity.
  • Change scope = cached public metadata such as size labels, draft state, and review-burden hints.
  • Validation posture = whether the PR provides enough public validation/test evidence for maintainer review.
  • Contributor workload = public contributor activity and cleanup pressure, not a repo-wide quality failure.
  • Contributor context = public GitHub/Gittensor identity context; non-Gittensor status is not a blocker.
🧪 Chat with LoopOver

Ask LoopOver a question about this PR directly in a comment — grounded only in the same cached, public-safe facts shown above, never a new claim.

  • @loopover ask &lt;question&gt; answers contribution-quality Q&A with source citations and freshness.
  • @loopover chat &lt;question&gt; answers in natural prose from cached decision-pack facts via local inference (maintainer/collaborator; read-only).
  • A plain-language @loopover mention with a real question is routed to the closest matching read-only command automatically — no exact syntax required.

Full command reference: https://loopover.ai/docs/loopover-commands

🧪 Experimental — new and may change.

Visual preview
Route Viewport Before (production) After (this PR's preview) Diff
/ desktop before /
before /
after /
after /
/ mobile before / (mobile)
before / (mobile)
after / (mobile)
after / (mobile)

Click any thumbnail to open the full-size screenshot. Before = production · After = this PR's preview deploy.

Scroll preview
Route Before (production) After (this PR's preview)
/ before / (scroll)
before / (scroll)
after / (scroll)
after / (scroll)

A short scroll-through clip (desktop) — click either thumbnail to open the full animation. Evidence for scroll-linked behavior a single screenshot can't show.

🟩 Safe / merged · 🟦 Advisory · 🟨 Held for review · 🟥 Blocked / closed


💰 Earn for open-source contributions like this. Gittensor lets GitHub contributors earn for the work they already do — register to start earning →.

Checked by LoopOver, a quiet PR intelligence layer for OSS maintainers.

  • Re-run LoopOver review

@loopover-orb

loopover-orb Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

This pull request changes UI/visual code but its screenshot evidence is incomplete. Every required viewport × theme combination needs its own before/after image pair in a labeled table row (e.g. "Desktop · Light | before | after"). Still missing: Desktop · Dark, Tablet · Dark, Mobile · Dark.

Please resubmit with the remaining rows filled in.

See https://github.com/JSONbored/loopover/blob/main/.claude/skills/contributing-to-loopover/SKILL.md for the exact format and examples. This is an automated maintenance action.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gittensor:feature Gittensor-scored feature linked to a feature issue — scores a 0.25x multiplier.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add tenant-facing AI-usage/cost endpoint (sumAiCostForTenantSince has zero real callers) — unit decided: normalized compute-units

1 participant