Repository navigation
feat(site): show AI spend per organization - #32204
Conversation
Docs previewLinks open this pull request's preview at https://pr-32204.docs.cdr-preview.dev, which updates with each push. Check off each page once it's been reviewed. If a page changes in a later push, its checkbox clears automatically so it gets a fresh look. Pages not yet wired into the docs navigation aren't listed here. Preview sites for each built commit (1)Every built commit keeps its own preview, newest first. Previews aren't indexed by search engines and are deleted when this pull request is merged or closed. |
f496666 to
da3823b
Compare
mollymaefraser
left a comment
There was a problem hiding this comment.
A few Nits/Qs. Main change I think is needed is in UserDropdownAISpend.tsx lines 45-52.
| {exceeded && ( | ||
| <div className="mt-1 text-xs text-content-primary"> | ||
| AI requests are paused until{" "} | ||
| <span className="whitespace-nowrap"> | ||
| {formatSpendPeriodEnd(periodEnd)}. | ||
| </span> | ||
| </div> | ||
| )} |
There was a problem hiding this comment.
"AI requests are paused until…" should name the organization when the selector is shown. The limit is enforced per organization of the request (checkUserAIBudget), so other organizations still work. The fix needs the org name passed in from UserDropdown.tsx (the <UserDropdownAISpend render at line 101).
There was a problem hiding this comment.
How do you feel about "AI requests ion this organization are paused until" for the multi org case instead of naming the organization? Because organizations can have arbitrary names, I'm a little hesitant to just interpolate it there and assume the user will know exactly what that means. Even with the org picker right above it.
If that works, I have a patch ready to send up. Otherwise, I can shift to naming the org specifically but it will take more time.
There was a problem hiding this comment.
Works for me, the picker right above makes "this organization" clear, and I agree about arbitrary names. Happy for you to send the patch. Could you keep the current wording for single-org users, and add an assertion for the new text in the multi-org exceeded test/story?
| const error = menuSpend?.orgSelection | ||
| ? byOrganizationQuery.error | ||
| : siteWideQuery.error; | ||
| const indicator = severityIndicators[getSpendSeverity(spend)]; |
There was a problem hiding this comment.
The avatar badge follows only the selected org. Is it intended that a user over the limit in another org gets no signal until they open the selector?
There was a problem hiding this comment.
Is it intended that a user over the limit in another org gets no signal until they open the selector?
Fair point. I'll experiment with this a bit.
| if (spend.spendLimit === 0) { | ||
| return "exceeded"; | ||
| } |
There was a problem hiding this comment.
This rule is a menu-only fork of getSeverity. Should the shared helper change instead, so UsageIndicator agrees? getSeverity itself isn't in the diff, so it can't take an inline comment.
| @@ -36,17 +83,11 @@ export const UserDropdownAISpend: React.FC<UserDropdownAISpendProps> = ({ | |||
| <UsageBar | |||
| ariaLabel="AI spend usage" | |||
| percent={usageProgressPercentage(currentSpend, spendLimit)} | |||
There was a problem hiding this comment.
Nit: A $0 limit gives a 0% bar under "Limit exceeded". It should probably render at 100%.
| }, | ||
| play: async ({ canvasElement, step }) => { | ||
| await step("shows a zero limit without exceeding", async () => { | ||
| await step("shows a zero limit as exceeded", async () => { |
There was a problem hiding this comment.
Nit: The step name claims "exceeded", but nothing checks "Limit exceeded" or "paused until". The new assertions would go after line 314.
| ], | ||
| }, | ||
| play: async ({ canvasElement }) => { | ||
| await openDropdown(canvasElement); |
There was a problem hiding this comment.
Nit: Add a check for "AI spend unavailable" and that the selector is still there. MultiOrgAISpend (331) and MultiOrgAISpendExceeded (366) have no assertions either.
| MockUserAISpendStatus, | ||
| MockUserOrganizationsAISpendStatus, | ||
| } from "#/testHelpers/entities"; | ||
| import { getUserMenuSpend } from "./viewedSpend"; |
There was a problem hiding this comment.
Nit: getSpendSeverity isn't tested. Suggested cases: 0/0 → exceeded, a null limit → normal, null spend → normal.
| parameters: { | ||
| ...aiCostControl, | ||
| queries: [{ key: meAISpendKey, data: mockAISpend }], | ||
| queries: [{ key: meAISpendKey, data: MockUserAISpendStatus }], |
There was a problem hiding this comment.
Nit: The single-org stories don't seed meOrganizationsAISpendKey, so each one fires a real request. Seeding it once at the meta level would cover them all. The meta block (82–98) isn't in the diff, so the comment has to go here.
| ref={triggerRef} | ||
| // The avatar fallback initials would otherwise prefix typeahead. | ||
| textValue={orgName(selected)} | ||
| aria-expanded={open} |
There was a problem hiding this comment.
Nit: There's no aria-controls. Also worth asking whether DropdownMenuSub was considered, since it keeps the parent menu open too.
Adds `GET /api/v2/users/{user}/ai/spend/organizations`, which returns a
user's AI budget and current-period spend in each of their
organizations. The avatar menu uses it to show spend to users who belong
to more than one organization (#32204).
The response lists each organization the user is a current member of and
the caller can read, sorted by name. Each entry has the effective group,
budget, and spend that AI Gateway resolves for a request in that
organization. When no group budget applies, the effective group is the
organization's `Everyone` group. `organization_id` names the
organization of the user's site-wide effective group, so the menu opens
on the numbers the user sees today. It's null when that organization
isn't in the list.
`GET /users/{user}/ai/spend` is unchanged. Its API docs now say that it
resolves the site-wide effective group, and point to the new endpoint
for the per-organization breakdown.
dbauthz filters the user's organizations to those the caller can read,
so an organization-scoped admin only sees the organizations they
administer. The handler queries spend only for those organizations. A
new query, `GetUserAISpendByEffectiveGroupsSince`, reads the spend for
all of them in one call. It reads existing tables, so there's no
migration, and dbauthz checks it the same way as `GetUserAISpendSince`:
the caller must be able to read the user.
Refs [AIGOV-766](https://linear.app/codercom/issue/AIGOV-766)
<details>
<summary>Decisions</summary>
- **Separate endpoint.** An earlier version of this PR added
`organizations` and `organization_id` to `GET /users/{user}/ai/spend`.
Following review, the breakdown moved to its own route ([AIGOV-766
comment](https://linear.app/codercom/issue/AIGOV-766/show-spend-per-org-to-users-in-several-orgs#comment-6855c55c)).
Because the breakdown depends on who is asking, a dedicated route keeps
the existing endpoint's response the same for every caller.
- **`organization_id` on the new response.** The comment's schema left
it out, but its frontend notes and its test rely on it, so the response
includes it.
- **Existing endpoint left as on `main`.** An organization-scoped admin
can still see a user's site-wide effective group, budget, and spend
through `GET /users/{user}/ai/spend`, even when that group is in another
organization. The earlier version of this PR hid those fields; this
version keeps the existing behavior, as the review asked.
- **Authorization check.** dbauthz post-filters
`GetOrganizationsByUserID` with `read` on each organization. The
endpoint itself requires read on the user, as the existing spend
endpoint does.
- **Empty result.** A caller who can read the user but none of their
organizations gets `200` with an empty `organizations` list and a null
`organization_id`, so the response doesn't reveal that memberships
exist.
- **Per-organization spend.** Each entry reports spend on the user's
current effective group in that organization, which is what budget
enforcement compares.
</details>
---
*Generated by Coder Agents on behalf of @SasSwart.*
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Users in more than one organization can pick an organization in the avatar menu to see their AI spend and budget there. The avatar badge follows the selected organization, and users over their limit see a "Limit exceeded" header with the date AI requests resume. Refs AIGOV-766 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…indings - Show a $0 budget as exceeded in the user menu, since AI Gateway blocks requests once spend reaches the limit. - Give the organization items a typeahead value, so the avatar initials no longer prefix the text Radix matches against. - Cover picking an organization with the keyboard, including focus returning to the organization button. - Make the organization_id fallback fixture match what the server returns. Refs AIGOV-766 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The per-organization breakdown moved from GET /users/me/ai/spend to GET /users/me/ai/spend/organizations. The user menu now polls both: the selector and the selected organization's spend come from the new endpoint when it lists more than one organization, and the menu falls back to the site-wide spend otherwise, including while the new request has no data.
da3823b to
7f3d163
Compare
… message to the selected organization
AI Gateway enforces the spend limit per organization, so a user over the
limit in one organization can still make requests in another. When the
organization selector is shown, the exceeded message now reads "AI
requests in this organization are paused until {date}." Users in one
organization keep "AI requests are paused until {date}."
*Generated by Coder Agents on behalf of @SasSwart.*
mollymaefraser
left a comment
There was a problem hiding this comment.
As you have fixed the main one that was blocking, going to approve 🚀 as don't want my approval holding you up for the nits!
Users in more than one organization can now pick an organization in the avatar menu and see their AI spend and budget there. Before, the menu showed one figure from a site-wide effective group, so these users couldn't see their spend in their other organizations.
The menu now polls two endpoints every 60 seconds:
GET /users/me/ai/spendfor the site-wide spend, as before, andGET /users/me/ai/spend/organizations(#32202) for the per-organization breakdown. The menu can't know that a user is in more than one organization until the second request returns, so it always makes both requests.DropdownMenuRadioGroupinside the existing menu, so the menu stays open while the user switches. Each organization shows a warning or exceeded badge with a screen reader label, in API order, and typeahead matches the organization name. The selection lives in local component state. It starts on the entry that matchesorganization_id, or on the first entry if none matches. If a refetch drops the selected organization, it falls back the same way.getSeverityhelper is unchanged, so other views still show $0 of $0 as normal. The normal and warning states look the same as before.UsageIndicatorstill hides spend on error.A pure helper,
getUserMenuSpendinviewedSpend.ts, decides which spend to show. The severity map moved intoseverityIndicators.tsx, next to a sharedSeverityBadge. The cost controls page now describes the selector and the exceeded state.Stacked on #32203. Review only the last three commits here.
Open questions
A $0 budget blocks every AI Gateway request, but the shared
getSeverityhelper insite/src/utils/budget.tsstill shows $0 of $0 as normal. This PR only changes the user menu. Two other screens use the shared helper:UsageIndicator) shows users their own spend. Should a $0 budget show as exceeded there too, to match the menu?AIBudgetAmount) show admins each group's budget. Should a group with a $0 budget, where AI is deliberately off, show as exceeded or stay neutral?Out of scope, tracked in AIGOV-738: organization search, the count badge on the collapsed row, sorting organizations by severity, the workspace quota row, and a shared app-wide current organization.
UserDropdown.test.tsxchecks the exceeded text because the ticket asks for it. A Pixel story also covers that state. The failed-poll state has a Vitest test but no story yet.Refs AIGOV-766
Screenshots
Multiple organizations
Organization picker with severity badges
Selected organization over its limit
AI spend unavailable for the selected organization
Generated by Coder Agents on behalf of @SasSwart.